Search code examples
ocamlocamlyacc

Integer in rules for parser definition - Ocaml


I am running into a problem when compiling the following rule for my parser:

%%

expr:

  | expr ASN expr { Asn ($1, $2) }

This is an assignment rule that takes an integer, then the assignment (equal sign) and an expression, as defined in my AST:

type expr = Asn of int * expr

Of course, the compiler is complaining because I am defining "expr ASN expr", and the first argument should be an integer, not an expression. However, I have not been able to figure out the syntax to specify this.

If somebody could lead me in the right direction, I would really appreciate it.

Thanks!


Solution

  • Probably what you want is the assignment as:

    type expr = Asn of var * int
    

    and then define expr in the parser as:

    expr:
      | VAR ASN INT { Asn ($1, $2) }
    

    in the lexer you should have defined VAR as string and INT as integer literal too, just as examples:

    | [a-zA-z]+ { VAR($1) }
    | [0-9]+ as i { INT(int_of_string i) }