Informazioni sulla posizione in fparsec
Domanda
Il mio modello AST deve trasportare informazioni sulla posizione (nome file, linea, indice). C'è qualche modo integrato per accedere a queste informazioni? Dai documenti di riferimento, il flusso sembra portare la posizione, ma preferirei che non devo implementare un parser fittizio solo per salvare la posizione e aggiungerlo ovunque.
Grazie in anticipo
Soluzione
I parser sono effettivamente le abbreviazioni di tipo per le funzioni dai flussi alle risposte:
Parser<_,_> is just CharStream<_> -> Reply<_>
Tenendo presente questo, puoi facilmente scrivere un parser personalizzato per le posizioni:
let position : CharStream<_> -> Reply<Position> = fun stream -> Reply(stream.Position)
(* OR *)
let position : Parser<_,_> = fun stream -> Reply stream.Position
e le informazioni sulla posizione di Atttach su ogni bit che analizzi utilizzando
position .>>. yourParser (*or tuple2 position yourParser*)
Il parser di posizione non consuma alcun input e quindi è sicuro combinarsi in questo modo.
Voi Potere Mantieni la modifica del codice richiesta limitata a una singola riga ed evita lo spread del codice incontrollabile:
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 *)
Aggiornare: FParsec ha un parser predefinito per le posizioni:http://www.quanttec.com/fparsec/reference/charparsers.html#members.getPosition