Version 1.0
Copyright © 2022 Lowell D. Thomas
Python APG
 … an ABNF Parser Generator
limits.py
Go to the documentation of this file.
1 ''' @file examples/exp/limits.py
2 @brief Demonstrates placing limits on the node hits and parse tree depth.
3 '''
4 import sys
5 import os
6 # add the current working directory to the path
7 # DO NOT MOVE THE FOLLOWING STATEMENT
8 # if using autopep8 formatter, for example, set argument '--ignore=E402'
9 sys.path.append(os.getcwd())
10 from apg_py.exp.exp import ApgExp
11 
12 title = '''This example will demonstrate how to place limits
13 on the number of node hits and parse tree depth.
14 Exists to avoid the problem of "catestrophic backtracking".
15 Although this is not nearly as big a problem for ApgExp
16 as it is for regex, nonetheless, facilities exist for
17 limiting a runaway parser.
18 '''
19 print()
20 print(title)
21 
22 pattern = '''float = sign decimal exponent
23 sign = ["+" / "-"]
24 decimal = integer [dot fraction]
25  / dot fraction
26 integer = 1*%d48-57
27 dot = "."
28 fraction = *%d48-57
29 exponent = ["e" esign exp]
30 esign = ["+" / "-"]
31 exp = 1*%d48-57
32 '''
33 print()
34 print('PATTERN')
35 print(pattern)
36 input = '---+1234.56789E-10==='
37 header = 'RESULT'
38 testno = 0
39 
40 # the full result
41 exp = ApgExp(pattern)
42 result = exp.exec(input)
43 testno += 1
44 print('\n' + str(testno) + ') The full match.')
45 print('input string: ' + input)
46 print(header)
47 print(result)
48 
49 # limit node hits
50 exp = ApgExp(pattern)
51 exp.set_node_hits(40)
52 testno += 1
53 try:
54  result = exp.exec(input)
55 except Exception as msg:
56  print('\n' + str(testno) + ') Limited node hits - parser raises an exception.')
57  print('input string: ' + input)
58  print('Exception: ', end='')
59  print(msg)
60 
61 # limit tree depth
62 exp = ApgExp(pattern)
63 exp.set_tree_depth(5)
64 testno += 1
65 print('\n' + str(testno) + ') Limited tree depth - parser raises an exception.')
66 print('input string: ' + input)
67 try:
68  result = exp.exec(input)
69 except Exception as msg:
70  print(
71  '\n' +
72  str(testno) +
73  ') Limited tree depth - parser raises an exception.')
74  print('input string: ' + input)
75  print('Exception: ', end='')
76  print(msg)
The ApgExp class provides a pattern-matching engine similar to JavaScript's RegExp
Definition: exp.py:79
Python APG, Version 1.0, is licensed under the 2-Clause BSD License,
an Open Source Initiative Approved License.