Parsing 通过Lexing.from_string解析字符串
我已经实现了,而且效果很好 现在,我想从字符串中读取,而不是从Parsing 通过Lexing.from_string解析字符串,parsing,ocaml,lex,lexical-analysis,Parsing,Ocaml,Lex,Lexical Analysis,我已经实现了,而且效果很好 现在,我想从字符串中读取,而不是从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
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
let _ =
let lexbuf = Lexing.from_string "3+1" in
let result = Parser.main Lexer.token lexbuf in
print_int result
奇怪的是,它返回Lexer.Eof
作为结果。如果我从lexer.mll
中删除|eof{raise eof}
,它会告诉致命错误:异常失败(“lexing:empty token”)
。我想输入结束时的条件有点不对劲。。。有人知道如何更改lexer,使其可以对字符串进行lex吗?您忘记了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
编辑
或者,如果您不想添加下线:
在parser.mly
中,添加标记EOF
,并:
| expr EOF { $1 }
在lexer.mll
中,不要提高eof,而是返回令牌eof
:
| eof { EOF }
最后,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
let _ =
let lexbuf = Lexing.from_string "3+1" in
let result = Parser.main Lexer.token lexbuf in
print_int result
谢谢,那确实管用。但是我想解析一个没有EOL的正常sting。我已更改为main:expr{$1}在parser.mly
中,奇怪的是“1+3”
仍然返回Lexer.Eof
,进行词法分析。from\u string
只接受以“\n”
结尾的字符串?