我已经实施了this example,效果很好。
现在,我想从字符串中读取而不是从stdin
读取,因此我更改了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
奇怪的是,它返回Lexer.Eof
作为结果。如果我从| eof { raise Eof }
移除lexer.mll
,则会告知Fatal error: exception Failure("lexing: empty token")
。我想在end-of-input
条件下出现问题...有没有人知道如何更改词法分析器以便它可以使字符串变为字符串?
答案 0 :(得分:3)
你忘记了EOL:
let _ =
try
let lexbuf = Lexing.from_string "1+3\n" in
let result = Parser.main Lexer.token lexbuf in
print_int result
with Lexer.Eof ->
print_string "Lexer.Eof";
exit 0
修改强>
或者,如果您不想添加EOL:
在parser.mly
中,添加令牌EOF
和:
| expr EOF { $1 }
在lexer.mll
中,不提高eof但返回令牌EOF
:
| eof { EOF }
最后,calc.ml
:
let _ =
let lexbuf = Lexing.from_string "3+1" in
let result = Parser.main Lexer.token lexbuf in
print_int result