File: multiples.py

package info (click to toggle)
python-lark 1.2.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,788 kB
  • sloc: python: 13,305; javascript: 88; makefile: 34; sh: 8
file content (28 lines) | stat: -rw-r--r-- 718 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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', rel_to=__file__, 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)