4

我正在使用 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:

如何正确获取发生错误的行号?

4

1 回答 1

3

在词法分析期间,您需要使用如下规则手动增加行号

...
let newline = ('\n' | '\r' '\n')

rule tokenize = parse
| newline    { lexbuf.EndPos <- lexbuf.EndPos.NextLine; tokenize lexbuf }
...
于 2011-10-28T13:21:53.043 回答