parsinglexical-analysisocamllexocamlyaccmenhir

Debug parser by printing useful information


I would like to parse a set of expressions, for instance:X[3], X[-3], XY[-2], X[4]Y[2], etc.

In my parser.mly, index (which is inside []) is defined as follows:

index:
| INTEGER { $1 }
| MINUS INTEGER { 0 - $2 }

The token INTEGER, MINUS etc. are defined in lexer as normal.

I try to parse an example, it fails. However, if I comment | MINUS INTEGER { 0 - $2 }, it works well. So the problem is certainly related to that. To debug, I want to get more information, in other words I want to know what is considered to be MINUS INTEGER. I tried to add print:

index:
| INTEGER { $1 }
| MINUS INTEGER { Printf.printf "%n" $2; 0 - $2 }

But nothing is printed while parsing.

Could anyone tell me how to print information or debug that?


Solution

  • I tried coming up with an example of what you describe and was able to get output of 8 with what I show below. [This example is completely stripped down so that it only works for [1] and [- 1 ], but I believe it's equivalent logically to what you said you did.]

    However, I also notice that your example's debug string in your example does not have an explicit flush with %! at the end, so that the debugging output might not be flushed to the terminal until later than you expect.

    Here's what I used:

    Test.mll:

    {
       open Ytest
       open Lexing
    }
    rule test =
    parse
    "-" { MINUS }
    | "1" { ONE 1 }
    | "[" { LB }
    | "]" { RB }
    | [ ' ' '\t' '\r' '\n'  ] { test lexbuf } 
    | eof { EOFTOKEN } 
    

    Ytest.mly:

    %{
    %}
    %token <int> ONE 
    %token MINUS LB RB EOFTOKEN
    %start item
    %type <int> index item
    %%
    index:
        ONE { 2 }
        | MINUS ONE { Printf.printf "%n" 8; $2 }
    item : LB index RB EOFTOKEN { $2 } 
    

    Parse.ml

    open Test;;
    open Ytest;;
    open Lexing;;
    let lexbuf = Lexing.from_channel stdin in
    ignore (Ytest.item Test.test lexbuf)