Version 1.0
Copyright © 2022 Lowell D. Thomas
Python APG
 … an ABNF Parser Generator
look_ahead.py
Go to the documentation of this file.
1 ''' @file examples/basics/look_ahead.py
2 @brief Example of using the look behind operators & and !.
3 
4 A well-known non-context free language is
5 [L ={a<sup>n</sup>b<sup>n</sup>c<sup>n</sup> | n>0}]
6 (https://en.wikipedia.org/wiki/Syntactic_predicate).
7 It is shown there how to parse this using look ahead operators.
8 See also the brute-force method with UDTs, namely
9 hand written a code snippets to match a language phrase,
10 @ref examples/basics/udts.py.
11 '''
12 import sys
13 import os
14 # add the current working directory to the path
15 # DO NOT MOVE THE FOLLOWING STATEMENT
16 # if using autopep8 formatter, for example, set argument '--ignore=E402'
17 sys.path.append(os.getcwd())
18 from apg_py.lib import utilities as utils
19 from apg_py.lib.parser import Parser
20 from apg_py.api.api import Api
21 
22 title = '''Demonstrate the use of the look ahead operators.
23 & - the positive look ahead operator
24  - succeeds on a specified phrase match
25 ! - the negative look ahead operator
26  - fails on a specified phrase match
27 '''
28 print()
29 print(title)
30 
31 # SABNF syntax using the look ahead operators & and !
32 abnf_syntax = 'S = &(A !bb) 1*aa B !cc\n'
33 abnf_syntax += 'A = aa [A] bb\n'
34 abnf_syntax += 'B = bb [B] cc\n'
35 abnf_syntax += 'aa = "a"\n'
36 abnf_syntax += 'bb = "b"\n'
37 abnf_syntax += 'cc = "c"\n'
38 
39 # construct the grammar object
40 api = Api()
41 grammar = api.generate(abnf_syntax)
42 if(api.errors):
43  # report any errors
44  print('\n1) Grammar Errors')
45  print(api.display_errors())
46 else:
47  # use the grammar object to parse an input string
48  # input string must be a tuple of positive integers
49  parser = Parser(grammar)
50  input_string = 'aaabbbccc'
51  result = parser.parse(utils.string_to_tuple(input_string))
52  print('\n1) Parser Result - input = "' + input_string + '"')
53  print(result)
54  input_string = 'aaabbbcc'
55  result = parser.parse(utils.string_to_tuple(input_string))
56  print('\n2) Parser Result - input = "' + input_string + '"')
57  print(result)
The API class.
Definition: api.py:61
The Parser class for parsing an APG grammar.
Definition: parser.py:60
Python APG, Version 1.0, is licensed under the 2-Clause BSD License,
an Open Source Initiative Approved License.