FParsec:保留行号和列号
FParsec: Keeping line and column numbers
例如,从给定解析器中提取行号和列号以便将它们添加到 AST 中的最佳方法是什么?
谢谢!
您可以使用 getPosition
,这是一个不消耗输入和 returns 当前位置的解析器。例如:
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);}
例如,从给定解析器中提取行号和列号以便将它们添加到 AST 中的最佳方法是什么?
谢谢!
您可以使用 getPosition
,这是一个不消耗输入和 returns 当前位置的解析器。例如:
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);}