gpt4 book ai didi

f# - FParsec:保留行号和列号

转载 作者:行者123 更新时间:2023-12-04 01:45:07 24 4
gpt4 key购买 nike

例如,从给定解析器中提取行号和列号以便将它们添加到 AST 中的最佳方法是什么?

谢谢!

最佳答案

您可以使用 getPosition,这是一个不消耗任何输入并返回当前位置的解析器。例如:

type WithPos<'T> = { value: 'T; start: Position; finish: Position }

module Position =
/// Get the previous position on the same line.
let leftOf (p: Position) =
if p.Column > 1L then
Position(p.StreamName, p.Index - 1L, p.Line, p.Column - 1L)
else
p

/// Wrap a parser to include the position
let withPos (p: Parser<'T, 'U>) : Parser<WithPos<'T>, 'U> =
// Get the position before and after parsing
pipe3 getPosition p getPosition <| fun start value finish ->
{
value = value
start = start
finish = Position.leftOf finish
}

// Example use:

let s = pstring "test" |> withPos

printfn "%A" <| runParserOnString s () "" "test"
// Prints:
// Success: {value = "test";
// start = (Ln: 1, Col: 1);
// finish = (Ln: 1, Col: 4);}

关于f# - FParsec:保留行号和列号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55590902/

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