私のASTモデルは、位置情報(ファイル名、行、インデックス)を保持する必要があります。この情報にアクセスするための組み込みの方法はありますか?リファレンスドキュメントから、ストリームは位置を保持しているように見えますが、位置を保存するためだけにダミーパーサーを実装する必要はなく、どこにでも追加することをお勧めします。
前もって感謝します
パーサーは、実際には、ストリームから応答までの関数の型の省略形です。
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*)
位置パーサーは入力を消費しないため、そのように組み合わせるのが安全です。
必要なコード変更を1行に制限し、制御できないコードの拡散を回避できます。
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