gpt4 book ai didi

f# - fparsec 中的位置信息

转载 作者:行者123 更新时间:2023-12-04 17:57:05 24 4
gpt4 key购买 nike

我的 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*)

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

您可以将所需的代码更改限制在一行,并避免无法控制的代码传播:
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

关于f# - fparsec 中的位置信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6350752/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com