Fparsec location information

My AST model should contain location information (file name, line, index). Is there a built-in way to access this information? From the reference documents, the stream seems to carry this position, but I would prefer that I don't have to execute the partix parser just to maintain the position, and add this everywhere.

Thanks in advance

+5
source share
1 answer

Parsers are actually type abbreviations for functions from response threads:

Parser<_,_> is just CharStream<_> -> Reply<_>

With this in mind, you can easily write your own parser for positions:

let position : CharStream<_> -> Reply<Position> = fun stream -> Reply(stream.Position)
(* OR *)
let position : Parser<_,_> = fun stream -> Reply stream.Position

and bind location information to every bit that you parse using

position .>>. yourParser (*or tuple2 position yourParser*)

, .

, , :

type AST = Slash of int64
         | Hash  of int64

let slash : Parser<AST,_> = char '/' >>. pint64 |>> Slash
let hash  : Parser<AST,_> = char '#' >>. pint64 |>> Hash
let ast   : Parser<AST,_> = slash <|> hash

(*if this is the final parser used for parsing lists of your ASTs*)
let manyAst  : Parser<            AST  list,_> = many                (ast  .>> spaces)

let manyAstP : Parser<(Position * AST) list,_> = many ((position .>>. ast) .>> spaces)
(*you can opt in to parse position information for every bit
  you parse just by modifiying only the combined parser     *)

: FParsec : http://www.quanttec.com/fparsec/reference/charparsers.html#members.getPosition

+7

All Articles