4

What is the best way to extract the line and column numbers from a given parser so they can be added to an AST, for example?

Thanks!

falkmar
  • 53
  • 3

1 Answers1

5

You can use getPosition, which is a parser that consumes no input and returns the current position. For example:

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);}
Tarmil
  • 11,177
  • 30
  • 35