2011-06-14 61 views
5

我的AST模型需要携带位置信息(文件名,行,索引)。是否有内置的方式来访问这些信息?从参考文档看,这个流看起来像是支持这个位置,但我更喜欢我不必为了保存位置而实现一个虚拟分析器,并且无处不在。fparsec中的位置信息

在此先感谢

回答

7

解析器实际上是从流回复键入功能缩写:

Parser<_,_> is just CharStream<_> -> Reply<_> 

牢记这一点,你可以随便写了位置的自定义分析器:

let position : CharStream<_> -> Reply<Position> = fun stream -> Reply(stream.Position) 
(* OR *) 
let position : Parser<_,_> = fun stream -> Reply stream.Position 

并将您附属的位置信息附加到您解析的每一位

position .>>. yourParser (*or tuple2 position yourParser*) 

位置解析器不会消耗任何输入,因此以这种方式组合是安全的。

可以保持必要限制为单行代码更改,避免不可控的代码传播:

type AST = Slash of int64 
     | Hash of int64 

let slash : Parser<AST,_> = char '/' >>. pint64 |>> Slash 
let hash : Parser<AST,_> = char '#' >>. pint64 |>> Hash 
let ast : Parser<AST,_> = slash <|> hash 

(*if this is the final parser used for parsing lists of your ASTs*) 
let manyAst : Parser<   AST list,_> = many    (ast .>> spaces) 

let manyAstP : Parser<(Position * AST) list,_> = many ((position .>>. ast) .>> spaces) 
(*you can opt in to parse position information for every bit 
    you parse just by modifiying only the combined parser  *) 

更新:FParsec有位置的预定义的解析器: http://www.quanttec.com/fparsec/reference/charparsers.html#members.getPosition

+1

你不实际上你不需要自己定义位置解析器:http://www.quanttec.com/fparsec/reference/charparsers.html#members.getPosition – 2011-06-15 16:37:32

+0

对不起,我没有阅读fparsec的完整参考^ __ ^“ – 2011-06-15 16:53:32

+1

没问题,谢谢你回答这个问题:-)顺便说一句,还有一个解析器概述:http://www.quanttec.com/fparsec/reference/parser-overview.html#user-state-handling-and-getting-该输入流位置 – 2011-06-15 17:14:24