【问题标题】:FParsec: Keeping line and column numbersFParsec:保留行号和列号
【发布时间】:2019-04-09 10:40:06
【问题描述】:

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

谢谢!

【问题讨论】:

    标签: f# fparsec


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-28
      • 1970-01-01
      • 2021-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-24
      • 1970-01-01
      相关资源
      最近更新 更多