我正在使用F#Power Pack中的fsyacc / fslex解析一些源代码。
要检测错误,请使用以下代码:
use inputChannel = new StreamReader(File.OpenRead tempFileName)
let lexbuf = Lexing.LexBuffer<_>.FromTextReader inputChannel
let ast = try
Parser.start Lexer.tokenize lexbuf
with e ->
let pos = lexbuf.EndPos
let line = pos.Line
let column = pos.Column
let message = e.Message
let lastToken = new System.String(lexbuf.Lexeme)
printf "Parse failed at line %d, column %d:\n" line column
printf "Last loken: %s" lastToken
printf "\n"
exit 1
但是当这段代码在解析多行源文件时抛出错误消息时,我的行和列位置错误:
Parse failed at line 0, column 10899:
如何正确地获取已发生错误的行号?
答案 0 :(得分:3)
在lexing期间,您需要使用
之类的规则手动增加行号...
let newline = ('\n' | '\r' '\n')
rule tokenize = parse
| newline { lexbuf.EndPos <- lexbuf.EndPos.NextLine; tokenize lexbuf }
...