ocamlyacc分析错误:什么令牌? [英] ocamlyacc parse error: what token?
问题描述
我正在使用ocamlyacc和ocamllex.我的语法中有错误产生,表示发生自定义异常.到目前为止,我可以报告错误位置了:
I'm using ocamlyacc and ocamllex. I have an error production in my grammar that signals a custom exception. So far, I can get it to report the error position:
| error { raise (Parse_failure (string_of_position (symbol_start_pos ()))) }
但是,我也想知道读取了哪个令牌.必须有一种方法-有人知道吗?
But, I also want to know which token was read. There must be a way---anyone know?
谢谢.
推荐答案
令牌是由lexer生成的,因此,当发生错误时,您可以使用当前的lexer令牌:
Tokens are generated by lexer, hence you can use the current lexer token when error occurs :
let parse_buf_exn lexbuf =
try
T.input T.rule lexbuf
with exn ->
begin
let curr = lexbuf.Lexing.lex_curr_p in
let line = curr.Lexing.pos_lnum in
let cnum = curr.Lexing.pos_cnum - curr.Lexing.pos_bol in
let tok = Lexing.lexeme lexbuf in
let tail = Sql_lexer.ruleTail "" lexbuf in
raise (Error (exn,(line,cnum,tok,tail)))
end
Lexing.lexeme lexbuf
是您所需要的.其他部分不是必需的,而是有用的.
ruleTail
将所有剩余标记合并为字符串,以便用户轻松定位错误位置. lexbuf.Lexing.lex_curr_p
应该在词法分析器中更新以包含正确的位置. (源)
Lexing.lexeme lexbuf
is what you need. Other parts are not necessary but useful.
ruleTail
will concat all remaining tokens into string for the user to easily locate error position. lexbuf.Lexing.lex_curr_p
should be updated in the lexer to contain correct positions. (source)
这篇关于ocamlyacc分析错误:什么令牌?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!