Debian Codegraph @

src/yapps3_compiled_rt.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 # Modified for PyCIFRW by JRH to allow external scanner
12 #
13 # To maximize python3/python2 compatibility
14 from __future__ import print_function
15 from __future__ import unicode_literals
16 from __future__ import division
17 from __future__ import absolute_import
18
19 """ Detail of JRH modifications.
20
21 The compiled module handles all token administration by itself, but
22 does not deal with restrictions. It also effectively removes the
23 context-sensitivity of Yapps, as it ignores restrictions, but
24 these restrictions turn out to be unnecessary for CIF.
25
26 Interestingly, the module scan function is never called directly
27 from python.
28
29 """
30
31 """Run time libraries needed to run parsers generated by Yapps.
32
33 This module defines parse-time exception classes, a scanner class, a
34 base class for parsers produced by Yapps, and a context class that
35 keeps track of the parse stack.
36
37 """
38
39 # TODO: it should be possible to embed yappsrt into the generated
40 # grammar to make a standalone module.
41
42 import sys, re
43
44
45 # For normal installation this module is "CifFile.yapps3_compiled_rt"
46 # and StarScan is an extension module within the parent CifFile module.
47 if __name__.startswith('CifFile.'):
48 try:
49 from . import StarScan
50 have_star_scan = True
51 except ImportError:
52 have_star_scan = False
53 # Otherwise assume this is imported from the yapps3/yapps2.py script
54 # that is executed from Makefile to generate YappsStarParser sources.
55 else:
56 assert __name__.endswith('yapps3_compiled_rt'), "Unexpected module name %s" % __name__
57 if not sys.argv[0].endswith('yapps2.py'):
58 print("WARNING: This line should be reached only when running yapps2.py in Makefile.")
59 have_star_scan = False
60
61 class YappsSyntaxError(Exception):
62 """When we run into an unexpected token, this is the exception to use"""
63 def __init__(self, charpos=-1, msg="Bad Token", context=None):
64 Exception.__init__(self)
65 self.charpos = charpos
66 self.msg = msg
67 self.context = context
68
69 def __str__(self):
70 if self.charpos < 0: return 'SyntaxError'
71 else: return 'SyntaxError@char%s(%s)' % (repr(self.charpos), self.msg)
72
73 class NoMoreTokens(Exception):
74 """Another exception object, for when we run out of tokens"""
75 pass
76
77 class Scanner:
78 """Yapps scanner.
79
80 The Yapps scanner can work in context sensitive or context
81 insensitive modes. The token(i) method is used to retrieve the
82 i-th token. It takes a restrict set that limits the set of tokens
83 it is allowed to return. In context sensitive mode, this restrict
84 set guides the scanner. In context insensitive mode, there is no
85 restriction (the set is always the full set of tokens).
86
87 """
88
89 def __init__(self, patterns, ignore, input, scantype="standard"):
90 """Initialize the scanner.
91
92 Parameters:
93 patterns : [(terminal, uncompiled regex), ...] or None
94 ignore : [terminal,...]
95 input : string
96
97 If patterns is None, we assume that the subclass has
98 defined self.patterns : [(terminal, compiled regex), ...].
99 Note that the patterns parameter expects uncompiled regexes,
100 whereas the self.patterns field expects compiled regexes.
101 """
102 self.tokens = [] # [(begin char pos, end char pos, token name, matched text), ...]
103 self.restrictions = []
104 self.input = input
105 self.pos = 0
106 self.ignore = ignore
107 self.scantype = scantype
108 self.first_line_number = 1
109 if self.scantype == "flex" and have_star_scan:
110 StarScan.prepare(input)
111 self.scan = self.compiled_scan
112 self.token = self.compiled_token
113 self.__del__ = StarScan.cleanup
114 elif self.scantype == "flex":
115 print("WARNING: using Python scanner although C scanner requested")
116 self.scantype = "standard"
117 if self.scantype != "flex":
118 self.scan = self.interp_scan
119 self.token = self.interp_token
120
121 if patterns is not None:
122 # Compile the regex strings into regex objects
123 self.patterns = []
124 for terminal, regex in patterns:
125 self.patterns.append( (terminal, re.compile(regex)) )
126
127 def get_token_pos(self):
128 """Get the current token position in the input text."""
129 return len(self.tokens)
130
131 def get_char_pos(self):
132 """Get the current char position in the input text."""
133 return self.pos
134
135 def get_prev_char_pos(self, i=None):
136 """Get the previous position (one token back) in the input text."""
137 if self.pos == 0: return 0
138 if i is None: i = -1
139 return self.tokens[i][0]
140
141 def get_line_number(self):
142 """Get the line number of the current position in the input text."""
143 # TODO: make this work at any token/char position
144 return self.first_line_number + self.get_input_scanned().count('\n')
145
146 def get_line_number_with_pos(self, pos):
147 pos_input = self.input[:pos]
148 return self.first_line_number + pos_input.count('\n')
149
150 def get_column_number(self):
151 """Get the column number of the current position in the input text."""
152 s = self.get_input_scanned()
153 i = s.rfind('\n') # may be -1, but that's okay in this case
154 return len(s) - (i+1)
155
156 def get_input_scanned(self):
157 """Get the portion of the input that has been tokenized."""
158 return self.input[:self.pos]
159
160 def get_input_unscanned(self):
161 """Get the portion of the input that has not yet been tokenized."""
162 return self.input[self.pos:]
163
164 def interp_token(self, i, restrict=None):
165 """Get the i'th token in the input.
166
167 If i is one past the end, then scan for another token.
168
169 Args:
170
171 restrict : [token, ...] or None; if restrict is None, then any
172 token is allowed. You may call token(i) more than once.
173 However, the restrict set may never be larger than what was
174 passed in on the first call to token(i).
175
176 """
177 if i == len(self.tokens):
178 self.scan(restrict)
179 if i < len(self.tokens):
180 # Make sure the restriction is more restricted. This
181 # invariant is needed to avoid ruining tokenization at
182 # position i+1 and higher.
183 if restrict and self.restrictions[i]:
184 for r in restrict:
185 if r not in self.restrictions[i]:
186 raise NotImplementedError("Unimplemented: restriction set changed")
187 return self.tokens[i]
188 raise NoMoreTokens()
189
190 def compiled_token(self,i,restrict=0):
191 try:
192 return StarScan.token(i)
193 except IndexError:
194 raise NoMoreTokens()
195
196 def __repr__(self):
197 """Print the last 10 tokens that have been scanned in"""
198 output = ''
199 if self.scantype != "flex":
200 for t in self.tokens[-10:]:
201 output = '%s\n (@%s) %s = %s' % (output,t[0],t[2],repr(t[3]))
202 else:
203 out_tokens = StarScan.last_ten()
204 for t in out_tokens:
205 output = '%s\n (~line %s) %s = %s' % (output,t[0],t[2],repr(t[3]))
206 return output
207
208 def interp_scan(self, restrict):
209 """Should scan another token and add it to the list, self.tokens,
210 and add the restriction to self.restrictions"""
211 # Prepare accepted pattern list
212 if restrict:
213 # only patterns in the 'restrict' parameter or in self.ignore
214 # are accepted
215 accepted_patterns=[]
216 for p_name, p_regexp in self.patterns:
217 if p_name not in restrict and p_name not in self.ignore:
218 pass
219 else:
220 accepted_patterns.append((p_name,p_regexp))
221 else:
222 # every pattern is good
223 accepted_patterns=self.patterns
224 # Keep looking for a token, ignoring any in self.ignore
225 while 1:
226 # Search the patterns for the longest match, with earlier
227 # tokens in the list having preference
228 best_match = -1
229 best_pat = '(error)'
230 for p,regexp in accepted_patterns:
231 m = regexp.match(self.input, self.pos)
232 if m and len(m.group(0)) > best_match:
233 # We got a match that's better than the previous one
234 best_pat = p
235 best_match = len(m.group(0))
236
237 # If we didn't find anything, raise an error
238 if best_pat == '(error)' and best_match < 0:
239 msg = 'Bad Token'
240 if restrict:
241 msg = 'Trying to find one of '+', '.join(restrict)
242 raise YappsSyntaxError(self.pos, msg)
243
244 # If we found something that isn't to be ignored, return it
245 if best_pat not in self.ignore:
246 # Create a token with this data
247 token = (self.pos, self.pos+best_match, best_pat,
248 self.input[self.pos:self.pos+best_match])
249 self.pos = self.pos + best_match
250 # Only add this token if it's not in the list
251 # (to prevent looping)
252 if not self.tokens or token != self.tokens[-1]:
253 self.tokens.append(token)
254 self.restrictions.append(restrict)
255 return
256 else:
257 # This token should be ignored ..
258 self.pos = self.pos + best_match
259
260 def compiled_scan(self,restrict):
261 token = StarScan.scan()
262 print("Calling compiled scan, got %s" % repr(token))
263 if token[2] not in restrict:
264 msg = "Bad Token"
265 if restrict:
266 msg = "Trying to find one of " + ", ".join(restrict)
267 raise YappsSyntaxError(self.pos,msg)
268 self.tokens.append(token)
269 self.restrictions.append(restrict)
270 return
271
272 class Parser:
273 """Base class for Yapps-generated parsers.
274
275 """
276
277 def __init__(self, scanner):
278 self._scanner = scanner
279 self._pos = 0
280
281 def _peek(self, *types):
282 """Returns the token type for lookahead; if there are any args
283 then the list of args is the set of token types to allow"""
284 tok = self._scanner.token(self._pos, types)
285 return tok[2]
286
287 def _scan(self, type):
288 """Returns the matched text, and moves to the next token"""
289 tok = self._scanner.token(self._pos, [type])
290 if tok[2] != type:
291 raise YappsSyntaxError(tok[0], 'Trying to find '+type+' :'+ ' ,')
292 self._pos = 1 + self._pos
293 return tok[3]
294
295 class Context:
296 """Class to represent the parser's call stack.
297
298 Every rule creates a Context that links to its parent rule. The
299 contexts can be used for debugging.
300
301 """
302
303 def __init__(self, parent, scanner, tokenpos, rule, args=()):
304 """Create a new context.
305
306 Args:
307 parent: Context object or None
308 scanner: Scanner object
309 pos: integer (scanner token position)
310 rule: string (name of the rule)
311 args: tuple listing parameters to the rule
312
313 """
314 self.parent = parent
315 self.scanner = scanner
316 self.tokenpos = tokenpos
317 self.rule = rule
318 self.args = args
319
320 def __str__(self):
321 output = ''
322 if self.parent: output = str(self.parent) + ' > '
323 output += self.rule
324 return output
325
326 #
327 # Note that this sort of error printout is useless with the
328 # compiled scanner
329 #
330
331 def print_line_with_pointer(text, p):
332 """Print the line of 'text' that includes position 'p',
333 along with a second line with a single caret (^) at position p"""
334
335 # TODO: separate out the logic for determining the line/character
336 # location from the logic for determining how to display an
337 # 80-column line to stderr.
338
339 # Now try printing part of the line
340 text = text[max(p-130, 0):p+130]
341 p = p - max(p-130, 0)
342
343 # Strip to the left
344 i = text[:p].rfind('\n')
345 j = text[:p].rfind('\r')
346 if i < 0 or (0 <= j < i): j = i
347 if 0 <= i < p:
348 p = p - i - 1
349 text = text[i+1:]
350
351 if not text.startswith("loop_"):
352 # Strip to the right
353 i = text.find('\n', p)
354 j = text.find('\r', p)
355 if i < 0 or (0 <= j < i): i = j
356 if i >= 0:
357 text = text[:i]
358
359 # Now print the string, along with an indicator
360 out_str = "\n> " + text + "\n"
361 out_str += "...\n"
362
363 return out_str
364
365 def print_error(input, err, scanner):
366 """Print error messages, the parser stack, and the input text -- for human-readable error messages."""
367 # NOTE: this function assumes 80 columns :-(
368 # Figure out the line number
369 line_number = scanner.get_line_number()
370 column_number = scanner.get_column_number()
371 print('%d:%d: %s' % (line_number, column_number, err.msg),file=sys.stderr)
372
373 context = err.context
374 if not context:
375 print_line_with_pointer(input, err.charpos)
376
377 while context:
378 # TODO: add line number
379 print('while parsing %s%s:' % (context.rule, tuple(context.args)),file=sys.stderr)
380 print_line_with_pointer(input, context.scanner.get_prev_char_pos(context.tokenpos))
381 context = context.parent
382
383 def wrap_error_reporter(parser, rule):
384 try:
385 return getattr(parser, rule)()
386 except YappsSyntaxError as e:
387 input = parser._scanner.input
388 print_error(input, e, parser._scanner)
389 except NoMoreTokens:
390 print('Could not complete parsing; stopped around here:',file=sys.stderr)
391 print(parser._scanner,file=sys.stderr)