Meaningful errors during parsing with FSyacc

佐手、 提交于 2019-12-18 17:36:29

问题


I'm using fsyacc/fslex from F# Power Pack to parse some source code.

To detect errors I use the following code:

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   

But when this code throws the error message on parsing multi-line source file, I'm getting wrong line and column position:

Parse failed at line 0, column 10899:

How can I get line number correctly on which error has been occurred?


回答1:


During lexing, you need to manually increment the line number with a rule like

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

rule tokenize = parse
| newline    { lexbuf.EndPos <- lexbuf.EndPos.NextLine; tokenize lexbuf }
...


来源:https://stackoverflow.com/questions/7928438/meaningful-errors-during-parsing-with-fsyacc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!