Debian Codegraph @

src/yapps3/yappsrt.py

raw symbols SCIP
1 #
2 # Yapps 2 Runtime, part of Yapps 2 - yet another python parser system
3 # Copyright 1999-2003 by Amit J. Patel <[email protected]>
4 #
5 # This version of the Yapps 2 Runtime can be distributed under the
6 # terms of the MIT open source license, either found in the LICENSE file
7 # included with the Yapps distribution
8 # <http://theory.stanford.edu/~amitp/yapps/> or at
9 # <http://www.opensource.org/licenses/mit-license.php>
10 #
11 from __future__ import print_function
12
13 """Run time libraries needed to run parsers generated by Yapps.
14
15 This module defines parse-time exception classes, a scanner class, a
16 base class for parsers produced by Yapps, and a context class that
17 keeps track of the parse stack.
18
19 """
20
21 # TODO: it should be possible to embed yappsrt into the generated
22 # grammar to make a standalone module.
23
24 import sys, re
25
26 class YappsSyntaxError(Exception):
27 """When we run into an unexpected token, this is the exception to use"""
28 def __init__(self, charpos=-1, msg="Bad Token", context=None):
29 Exception.__init__(self)
30 self.charpos = charpos
31 self.msg = msg
32 self.context = context
33
34 def __str__(self):
35 if self.charpos < 0: return 'SyntaxError'
36 else: return 'SyntaxError@char%s(%s)' % (repr(self.charpos), self.msg)
37
38 class NoMoreTokens(Exception):
39 """Another exception object, for when we run out of tokens"""
40 pass
41
42 class Scanner:
43 """Yapps scanner.
44
45 The Yapps scanner can work in context sensitive or context
46 insensitive modes. The token(i) method is used to retrieve the
47 i-th token. It takes a restrict set that limits the set of tokens
48 it is allowed to return. In context sensitive mode, this restrict
49 set guides the scanner. In context insensitive mode, there is no
50 restriction (the set is always the full set of tokens).
51
52 """
53
54 def __init__(self, patterns, ignore, input):
55 """Initialize the scanner.
56
57 Parameters:
58 patterns : [(terminal, uncompiled regex), ...] or None
59 ignore : [terminal,...]
60 input : string
61
62 If patterns is None, we assume that the subclass has
63 defined self.patterns : [(terminal, compiled regex), ...].
64 Note that the patterns parameter expects uncompiled regexes,
65 whereas the self.patterns field expects compiled regexes.
66 """
67 self.tokens = [] # [(begin char pos, end char pos, token name, matched text), ...]
68 self.restrictions = []
69 self.input = input
70 self.pos = 0
71 self.ignore = ignore
72 self.first_line_number = 1
73
74 if patterns is not None:
75 # Compile the regex strings into regex objects
76 self.patterns = []
77 for terminal, regex in patterns:
78 self.patterns.append( (terminal, re.compile(regex)) )
79
80 def get_token_pos(self):
81 """Get the current token position in the input text."""
82 return len(self.tokens)
83
84 def get_char_pos(self):
85 """Get the current char position in the input text."""
86 return self.pos
87
88 def get_prev_char_pos(self, i=None):
89 """Get the previous position (one token back) in the input text."""
90 if self.pos == 0: return 0
91 if i is None: i = -1
92 return self.tokens[i][0]
93
94 def get_line_number(self):
95 """Get the line number of the current position in the input text."""
96 # TODO: make this work at any token/char position
97 return self.first_line_number + self.get_input_scanned().count('\n')
98
99 def get_column_number(self):
100 """Get the column number of the current position in the input text."""
101 s = self.get_input_scanned()
102 i = s.rfind('\n') # may be -1, but that's okay in this case
103 return len(s) - (i+1)
104
105 def get_input_scanned(self):
106 """Get the portion of the input that has been tokenized."""
107 return self.input[:self.pos]
108
109 def get_input_unscanned(self):
110 """Get the portion of the input that has not yet been tokenized."""
111 return self.input[self.pos:]
112
113 def token(self, i, restrict=None):
114 """Get the i'th token in the input.
115
116 If i is one past the end, then scan for another token.
117
118 Args:
119
120 restrict : [token, ...] or None; if restrict is None, then any
121 token is allowed. You may call token(i) more than once.
122 However, the restrict set may never be larger than what was
123 passed in on the first call to token(i).
124
125 """
126 if i == len(self.tokens):
127 self.scan(restrict)
128 if i < len(self.tokens):
129 # Make sure the restriction is more restricted. This
130 # invariant is needed to avoid ruining tokenization at
131 # position i+1 and higher.
132 if restrict and self.restrictions[i]:
133 for r in restrict:
134 if r not in self.restrictions[i]:
135 raise NotImplementedError("Unimplemented: restriction set changed")
136 return self.tokens[i]
137 raise NoMoreTokens()
138
139 def __repr__(self):
140 """Print the last 10 tokens that have been scanned in"""
141 output = ''
142 for t in self.tokens[-10:]:
143 output = '%s\n (@%s) %s = %s' % (output,t[0],t[2],repr(t[3]))
144 return output
145
146 def scan(self, restrict):
147 """Should scan another token and add it to the list, self.tokens,
148 and add the restriction to self.restrictions"""
149 # Keep looking for a token, ignoring any in self.ignore
150 while 1:
151 # Search the patterns for the longest match, with earlier
152 # tokens in the list having preference
153 best_match = -1
154 best_pat = '(error)'
155 for p, regexp in self.patterns:
156 # First check to see if we're ignoring this token
157 if restrict and p not in restrict and p not in self.ignore:
158 continue
159 m = regexp.match(self.input, self.pos)
160 if m and len(m.group(0)) > best_match:
161 # We got a match that's better than the previous one
162 best_pat = p
163 best_match = len(m.group(0))
164
165 # If we didn't find anything, raise an error
166 if best_pat == '(error)' and best_match < 0:
167 msg = 'Bad Token'
168 if restrict:
169 msg = 'Trying to find one of '+', '.join(restrict)
170 raise YappsSyntaxError(self.pos, msg)
171
172 # If we found something that isn't to be ignored, return it
173 if best_pat not in self.ignore:
174 # Create a token with this data
175 token = (self.pos, self.pos+best_match, best_pat,
176 self.input[self.pos:self.pos+best_match])
177 self.pos = self.pos + best_match
178 # Only add this token if it's not in the list
179 # (to prevent looping)
180 if not self.tokens or token != self.tokens[-1]:
181 self.tokens.append(token)
182 self.restrictions.append(restrict)
183 return
184 else:
185 # This token should be ignored ..
186 self.pos = self.pos + best_match
187
188 class Parser:
189 """Base class for Yapps-generated parsers.
190
191 """
192
193 def __init__(self, scanner):
194 self._scanner = scanner
195 self._pos = 0
196
197 def _peek(self, *types):
198 """Returns the token type for lookahead; if there are any args
199 then the list of args is the set of token types to allow"""
200 tok = self._scanner.token(self._pos, types)
201 return tok[2]
202
203 def _scan(self, type):
204 """Returns the matched text, and moves to the next token"""
205 tok = self._scanner.token(self._pos, [type])
206 if tok[2] != type:
207 raise YappsSyntaxError(tok[0], 'Trying to find '+type+' :'+ ' ,'.join(self._scanner.restrictions[self._pos]))
208 self._pos = 1 + self._pos
209 return tok[3]
210
211 class Context:
212 """Class to represent the parser's call stack.
213
214 Every rule creates a Context that links to its parent rule. The
215 contexts can be used for debugging.
216
217 """
218
219 def __init__(self, parent, scanner, tokenpos, rule, args=()):
220 """Create a new context.
221
222 Args:
223 parent: Context object or None
224 scanner: Scanner object
225 pos: integer (scanner token position)
226 rule: string (name of the rule)
227 args: tuple listing parameters to the rule
228
229 """
230 self.parent = parent
231 self.scanner = scanner
232 self.tokenpos = tokenpos
233 self.rule = rule
234 self.args = args
235
236 def __str__(self):
237 output = ''
238 if self.parent: output = str(self.parent) + ' > '
239 output += self.rule
240 return output
241
242 def print_line_with_pointer(text, p):
243 """Print the line of 'text' that includes position 'p',
244 along with a second line with a single caret (^) at position p"""
245
246 # TODO: separate out the logic for determining the line/character
247 # location from the logic for determining how to display an
248 # 80-column line to stderr.
249
250 # Now try printing part of the line
251 text = text[max(p-80, 0):p+80]
252 p = p - max(p-80, 0)
253
254 # Strip to the left
255 i = text[:p].rfind('\n')
256 j = text[:p].rfind('\r')
257 if i < 0 or (0 <= j < i): i = j
258 if 0 <= i < p:
259 p = p - i - 1
260 text = text[i+1:]
261
262 # Strip to the right
263 i = text.find('\n', p)
264 j = text.find('\r', p)
265 if i < 0 or (0 <= j < i): i = j
266 if i >= 0:
267 text = text[:i]
268
269 # Now shorten the text
270 while len(text) > 70 and p > 60:
271 # Cut off 10 chars
272 text = "..." + text[10:]
273 p = p - 7
274
275 # Now print the string, along with an indicator
276 print('> ', text, file=sys.stderr)
277 print('> ', ' ' * p + '^', file=sys.stderr)
278
279 def print_error(input, err, scanner):
280 """Print error messages, the parser stack, and the input text -- for human-readable error messages."""
281 # NOTE: this function assumes 80 columns :-(
282 # Figure out the line number
283 line_number = scanner.get_line_number()
284 column_number = scanner.get_column_number()
285 print('%d:%d: %s' % (line_number, column_number, err.msg), file=sys.stderr)
286
287 context = err.context
288 if not context:
289 print_line_with_pointer(input, err.charpos)
290
291 while context:
292 # TODO: add line number
293 print('while parsing %s%s:' % (context.rule, tuple(context.args)), file=sys.stderr)
294 print_line_with_pointer(input, context.scanner.get_prev_char_pos(context.tokenpos))
295 context = context.parent
296
297 def wrap_error_reporter(parser, rule):
298 try:
299 return getattr(parser, rule)()
300 except YappsSyntaxError as e:
301 input = parser._scanner.input
302 print_error(input, e, parser._scanner)
303 except NoMoreTokens:
304 print('Could not complete parsing; stopped around here:', file=sys.stderr)
305 print(parser._scanner, file=sys.stderr)