2011-06-14 66 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