I have implemented this example, and it works well.
Now, I want to read from a string instead of reading from stdin, so I change the calc.ml:
let _ =
try
let lexbuf = Lexing.from_string "1+3" in
let result = Parser.main Lexer.token lexbuf in
print_int result
with Lexer.Eof ->
print_string "Lexer.Eof";
exit 0
And oddly, it returns Lexer.Eof as result. If I remove | eof { raise Eof } from lexer.mll and , it tells Fatal error: exception Failure("lexing: empty token"). I guess something is wrong around end-of-input condition… Does anyone know how to change the lexer so that it could lex a string?
You forgot the EOL:
EDIT
Or if you do not want to add the EOL:
In
parser.mly, add the tokenEOFand:In
lexer.mll, not raise eof but return the tokenEOF:And finally,
calc.ml: