lark-parser / lark

Lark is a parsing toolkit for Python, built with a focus on ergonomics, performance and modularity.
MIT License
4.88k stars 414 forks source link

List and range terms #429

Closed johnny-alvarado closed 5 years ago

johnny-alvarado commented 5 years ago

How can I specify terms for lists or ranges?

For example to check if a variable is in a list or a range: var IN (1,2,3) var IN (1-10)

erezsh commented 5 years ago

You can use lexer callbacks: https://lark-parser.readthedocs.io/en/latest/recipes/

johnny-alvarado commented 5 years ago

Ok, if we take your example:

from lark import Lark, Token

def tok_to_int(tok):
    "Convert the value of `tok` from string to int, while maintaining line number & column."
    # tok.type == 'INT'
    return Token.new_borrow_pos(tok.type, int(tok), tok)

parser = Lark("""
start: INT*
%import common.INT
%ignore " "
""", parser="lalr", lexer_callbacks = {'INT': tok_to_int})

print(parser.parse('3 14 159'))

How do I change the grammar to accept the list of numbers separated by a comma, like in bring(parser.parse('3, 14, 159'))

erezsh commented 5 years ago

Oh, I misunderstood your question.

Follow the JSON tutorial, it explains that and more: https://github.com/lark-parser/lark/blob/master/docs/json_tutorial.md

P.S. I reformatted your comment. Take a look and learn for next time.

johnny-alvarado commented 5 years ago

Thank you, it worked quite well!

erezsh commented 5 years ago

Happy to help