F# FParsec:保留行和列编号

F# FParsec:保留行和列编号,f#,fparsec,F#,Fparsec,例如,从给定解析器中提取行号和列号以便将它们添加到AST的最佳方法是什么 谢谢 您可以使用getPosition,这是一个不使用输入并返回当前位置的解析器。例如: type WithPos<'T> = { value: 'T; start: Position; finish: Position } module Position = /// Get the previous position on the same line. let leftOf (p: Posi

例如,从给定解析器中提取行号和列号以便将它们添加到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);}
然后用位置1L键入
位置(p.StreamName、p.Index-1L、p.Line、p.Column-1L)
其他的
P
///包装解析器以包含位置
let-withPos(p:Parser):解析器=
//获取解析前后的位置
管道3 getPosition p getPosition
{
价值=价值
开始
完成=位置。完成的左边
}
//示例用法:
让s=pstring“test”|>with pos
printfn“%A”