Version 1.0
Copyright © 2022 Lowell D. Thomas
Python APG
 … an ABNF Parser Generator
backreferences.py
Go to the documentation of this file.
1 ''' @file apg_py/lib/backreferences.py
2 @brief Back reference stack class
3 
4 Used for both universal and recursive back referencing.'''
5 
6 
8 
9  def __init__(self, names):
10  '''BackreferenceStack constructor.
11  Creates an (empty) LIFO stack of captured phrases,
12  one for each named rule or UDT.
13  @param names A tuple of lower case names of all rules
14  and UDTs capturing phrases for back referencing.
15  '''
16  self.stackstack = {}
17  self.namesnames = names
18  for name in names:
19  self.stackstack[name] = []
20 
21  def save_phrase(self, name, offset, length):
22  '''Pushes a phrase on the named stack.
23  @param name The (lower case) rule or UDT name that captured the phrase.
24  @param offset The offset into the input string for the first character
25  of the phrase.
26  @param length The number of characters in the phrase.
27  '''
28  assert(name in self.namesnames)
29  self.stackstack[name].append([offset, length])
30 
31  def get_phrase(self, name):
32  '''Retrieves the last phrase on the named stack.
33  @param name The (lower case) rule or UDT name that captured the phrase.
34  @returns Returns the last saved named phrase or None if none.
35  '''
36  assert(self.stackstack[name])
37  length = len(self.stackstack[name])
38  if(length):
39  return self.stackstack[name][length - 1]
40  return None
41 
42  def save_state(self):
43  '''Save the stack state.
44  @returns Returns a list of the named stack lengths.
45  '''
46  state = []
47  for name in self.namesnames:
48  state.append(len(self.stackstack[name]))
49  return state
50 
51  def restore_state(self, state):
52  '''Restores all named stack lengths to a previously saved state.
53  @param state The return value from a previous call
54  to @ref save_state().
55  '''
56  i = 0
57  for name in self.namesnames:
58  del self.stackstack[name][state[i]:]
59  i += 1
def save_state(self)
Save the stack state.
def restore_state(self, state)
Restores all named stack lengths to a previously saved state.
def save_phrase(self, name, offset, length)
Pushes a phrase on the named stack.
def __init__(self, names)
BackreferenceStack constructor.
def get_phrase(self, name)
Retrieves the last phrase on the named stack.
Python APG, Version 1.0, is licensed under the 2-Clause BSD License,
an Open Source Initiative Approved License.