from lark import Lark grammar = """ start: "hello" NAME "!" NAME: /[a-zA-Z]+/ """ parser = Lark(grammar) tree = parser.parse("hello John!") print(tree)
from lark import Lark, Transformer, v_args grammar = """ start: ID "(" expr ")" expr: "(" expr ")" | ID ID: /[a-zA-Z]+/ %import common.WS %ignore WS """ class ExprTransformer(Transformer): @v_args(inline=True) def expr(self, expr): if isinstance(expr, list): return tuple(expr[1:-1]) else: return str(expr) start = expr parser = Lark(grammar, parser='lalr', transformer=ExprTransformer()) tree = parser.parse("foo(bar(baz))") print(tree)This code defines a more complex grammar that matches function calls with nested parentheses. The grammar is defined using the EBNF notation supported by Lark. The ExprTransformer class defines methods that are called when the parser matches the different rules. The v_args decorator is used to optimize the transformer code. The parser is then created with the Lark constructor, specifying the grammar, the parser algorithm to use, and the transformer class. Finally, the parser is used to parse a test string, and the resulting tree is printed. Overall, Lark is a powerful and flexible library for parsing languages, with many options and plugins to customize its behavior.