diff --git a/examples/lark_grammar.py b/examples/lark_grammar.py index 30ccc8b..c7ace47 100644 --- a/examples/lark_grammar.py +++ b/examples/lark_grammar.py @@ -6,6 +6,9 @@ grammar_files = [ 'examples/python2.lark', 'examples/python3.lark', 'examples/lark.lark', + 'examples/relative-imports/multiples.lark', + 'examples/relative-imports/multiple2.lark', + 'examples/relative-imports/multiple3.lark', 'lark/grammars/common.lark', ] diff --git a/examples/relative-imports/multiple2.lark b/examples/relative-imports/multiple2.lark new file mode 100644 index 0000000..a65077c --- /dev/null +++ b/examples/relative-imports/multiple2.lark @@ -0,0 +1 @@ +start: ("0" | "1")* "0" diff --git a/examples/relative-imports/multiple3.lark b/examples/relative-imports/multiple3.lark new file mode 100644 index 0000000..6a67bce --- /dev/null +++ b/examples/relative-imports/multiple3.lark @@ -0,0 +1,5 @@ +start: mod0mod0+ + +mod0mod0: "0" | "1" mod1mod0 +mod1mod0: "1" | "0" mod2mod1 mod1mod0 +mod2mod1: "0" | "1" mod2mod1 diff --git a/examples/relative-imports/multiples.lark b/examples/relative-imports/multiples.lark new file mode 100644 index 0000000..35b5d17 --- /dev/null +++ b/examples/relative-imports/multiples.lark @@ -0,0 +1,5 @@ +start: "2:" multiple2 + | "3:" multiple3 + +%import .multiple2.start -> multiple2 +%import .multiple3.start -> multiple3 diff --git a/examples/relative-imports/multiples.py b/examples/relative-imports/multiples.py new file mode 100644 index 0000000..b57d446 --- /dev/null +++ b/examples/relative-imports/multiples.py @@ -0,0 +1,28 @@ +# +# This example demonstrates relative imports with rule rewrite +# see multiples.lark +# + +# +# if b is a number written in binary, and m is either 2 or 3, +# the grammar aims to recognise m:b iif b is a multiple of m +# +# for example, 3:1001 is recognised +# because 9 (0b1001) is a multiple of 3 +# + +from lark import Lark, UnexpectedInput + +parser = Lark.open('multiples.lark', parser='lalr') + +def is_in_grammar(data): + try: + parser.parse(data) + except UnexpectedInput: + return False + return True + +for n_dec in range(100): + n_bin = bin(n_dec)[2:] + assert is_in_grammar('2:{}'.format(n_bin)) == (n_dec % 2 == 0) + assert is_in_grammar('3:{}'.format(n_bin)) == (n_dec % 3 == 0)