FParsec:保留行号和列号

时间:2019-04-09 10:40:07

标签: f# fparsec

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

谢谢!

1 个答案:

答案 0 :(得分:2)

您可以使用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);}