BogDan Vatra
BogDan Vatra

Reputation: 11

pyparsing: is it possible to add lineno/col (or startloc/endloc) to all tokens?

Are needed for a better error reporting after parsing the schema i.e.

enum MyEnum {
  Key1,
  Key2,
  Key3
}

table Test {
  field1: MyEnum = MyEnum.Key1;
  field2: MyEnum = MyEnum.WrongKey;
}

I want to report that MyEnum.WrongKey is not found but I also want to pint the location (line & col) Here https://github.com/bog-dan-ro/flatbuffers/blob/pyfbsc/bin/fbsc.py is the full parser srcs

Upvotes: 1

Views: 372

Answers (2)

PaulMcG
PaulMcG

Reputation: 63719

You can wrap any expression using pyparsing's locatedExpr helper. From the online docs (https://pythonhosted.org/pyparsing/pyparsing-module.html#locatedExpr):

Example:

wd = Word(alphas)
for match in locatedExpr(wd).searchString("ljsdf123lksdjjf123lkkjj1222"):
    print(match)

prints:

[[0, 'ljsdf', 5]]
[[8, 'lksdjjf', 15]]
[[18, 'lkkjj', 23]]

Upvotes: 0

halloleo
halloleo

Reputation: 10384

You could try to define your parser, so that MyEnum.WrongKey does not parse. Then you print out where the parsing fails with:

try:
    your_parser.parseString(your_schema)
except ParseException as pe:
   print(pe)
   print("at column: {}".format(pe.col))

See the documentation for ParseException.

Upvotes: 1

Related Questions