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”
结尾的字符串?