lexer and parser problem
| Newsgroups | gmane.comp.lang.ocaml.beginners |
|---|---|
| Message-ID | <[email protected]> |
I have a question about my program which is divided in two files: lexer.mll and parser.mly.
The first file is lexer.mll:
rule lex = parse
| [' ' '\n' '\t'] { lex lexbuf }
| ['0'-'9']+ as s { INT(int_of_string s) }
| ['a'-'z' 'A'-'Z'] ['a'-'z' 'A'-'Z' '0'-'9']* as word { IDENT word }
| '+' { ADD }
| "plus" { PLUS }
| eof { EOF }
The second file is parser.mly:
%{ type expr =
Int of int
|String of string
| Add of expr * expr
%}
%token <int> INT
%token <string> IDENT
%token ADD
%token PLUS
%token EOF
%start expr
%type <expr> expr
%left PLUS ADD
%%
expr:
IDENT { String $1 }
|INT { Int $1 }
|expr PLUS expr { Add($1, $3) }
|expr ADD expr { Add($1, $3) }
;
So as you can see, for example I want to get the same results for both "1+2" and "1plus2" like :
Add (Int 1, Int 2)
But I don't know why it works for "1+2" and it doesn't work for "1plus2".
I use these commands to run the program:
(*commands in Windows PowerShell*):
ocamllex lexer.mll
ocamlyacc parser.mly
(*commands and results in OCamlWinPlus*):
#use "parser.ml";;
#use "lexer.ml";;
# expr lex (Lexing.from_string "1+2");;
- : expr = Add (Int 1, Int 2)
# expr lex (Lexing.from_string "1plus2");;
Exception: Parsing.Parse_error.
Why it works correctly for 1+2 but not for 1plus2? and also how can I use a main class for this program which can get the inputs as a .txt file and return the result in another .txt file so I don't need to use this command (expr lex (Lexing.from_string "1plus2");;) for each code line?
Regards
--
Arash Alavi
Department of Computer Engineering & Information Technology
Amirkabir University of Technology
Email(s): [email protected] , [email protected] page: http://ceit.aut.ac.ir/~arash.alavi