Using Positional and positioned() in scala parser

2019-08-28 08:36发布

问题:

With separate Lexer and Parser ...

class YamlLexical extends StdLexical with YamlTokens with RegexParsers {...
object YamlParser extends StdTokenParsers with YamlTokens with PackratParsers {...

... how to get the position of the parsed string into AST classes?

(... positioned(elem(...)) * ... )^^ { ... => List( Ast(startpos, parsedtext, ... subnodes ... ), ... )}

回答1:

The type of positioned is

def positioned[T <: Positional](p: ⇒ Parser[T]): Parser[T]

which means that the parsed elements must extend Positional. So, for example, YamlLexical should be:

class YamlLexical extends Positional 

in that way, any parsed element will automatically have a pos which records the position in which it was parsed.