Debian Codegraph @

tests/yappsrt.py

raw symbols SCIP
1 # Yapps 2.0 Runtime
2 #
3 # This module is needed to run generated parsers.
4 #
5 # Modified for PyCIFRW by JRH to allow external scanner
6 #
7
8 from __future__ import print_function
9 from string import *
10 import re
11 try:
12 import StarScan
13 have_star_scan = True
14 except ImportError:
15 have_star_scan = False
16
17 class SyntaxError(Exception):
18 """When we run into an unexpected token, this is the exception to use"""
19 def __init__(self, pos=-1, msg="Bad Token"):
20 self.pos = pos
21 self.msg = msg
22 def __repr__(self):
23 emsg = ("#<syntax-error>" if self.pos < 0 else
24 "SyntaxError[@ char {!r}: {}]".format(self.pos, self.msg))
25 return emsg
26
27 class NoMoreTokens(Exception):
28 """Another exception object, for when we run out of tokens"""
29 pass
30
31 class Scanner:
32 def __init__(self, patterns, ignore, input,scantype="standard"):
33 """Patterns is [(terminal,regex)...]
34 Ignore is [terminal,...];
35 Input is a string"""
36 self.tokens = []
37 self.restrictions = []
38 self.input = input
39 self.ignore = ignore
40 self.pos = 0
41 self.scantype = scantype
42 if self.scantype == "flex" and have_star_scan:
43 StarScan.prepare(input)
44 self.scan = self.compiled_scan
45 self.token = self.compiled_token
46 self.__del__ = StarScan.cleanup
47 elif self.scantype == "flex":
48 print("Warning: using Python scanner")
49 self.scantype = "standard"
50 if self.scantype != "flex":
51 self.scan = self.interp_scan
52 self.token = self.interp_token
53 # The stored patterns are a pair (compiled regex,source
54 # regex). If the patterns variable passed in to the
55 # constructor is None, we assume that the class already has a
56 # proper .patterns list constructed
57 if patterns is not None:
58 self.patterns = []
59 for k,r in patterns:
60 self.patterns.append( (k, re.compile(r)) )
61
62 def interp_token(self, i, restrict=0):
63 """Get the i'th token, and if i is one past the end, then scan
64 for another token; restrict is a list of tokens that
65 are allowed, or 0 for any token."""
66 if i == len(self.tokens): self.scan(restrict)
67 if i < len(self.tokens):
68 # Make sure the restriction is more restricted
69 if restrict and self.restrictions[i]:
70 for r in restrict:
71 if r not in self.restrictions[i]:
72 raise "Unimplemented: restriction set changed"
73 return self.tokens[i]
74 raise NoMoreTokens()
75
76 def compiled_token(self,i,restrict=0):
77 """Get the i'th token, and if i is one past the end, then scan
78 for another token; restrict is a list of tokens that
79 are allowed, or 0 for any token."""
80 try:
81 return StarScan.token(i)
82 except IndexError:
83 raise NoMoreTokens()
84
85 def __repr__(self):
86 """Print the last 10 tokens that have been scanned in"""
87 output = ''
88 # for t in self.tokens[-10:]:
89 # output = '%s\n (@%s) %s = %r' % (output, t[0], t[2], t[3])
90 return output
91
92 def compiled_scan(self,restrict):
93 """Should scan another token and add it to the list, self.tokens,
94 and add the restriction to self.restrictions"""
95 token = StarScan.scan()
96 if token[2] not in restrict:
97 msg = "Bad Token"
98 if restrict:
99 msg = "Trying to find one of "+join(restrict,", ")
100 raise SyntaxError(self.pos, msg)
101 self.tokens.append(token)
102 self.restrictions.append(restrict)
103 return
104
105 def interp_scan(self,restrict):
106 """Should scan another token and add it to the list, self.tokens,
107 and add the restriction to self.restrictions"""
108 # Keep looking for a token, ignoring any in self.ignore
109 while 1:
110 # Search the patterns for the longest match, with earlier
111 # tokens in the list having preference
112 best_match = -1
113 best_pat = '(error)'
114 for p, regexp in self.patterns:
115 # First check to see if we're ignoring this token
116 if restrict and p not in restrict and p not in self.ignore:
117 continue
118 m = regexp.match(self.input, self.pos)
119 if m and len(m.group(0)) > best_match:
120 # We got a match that's better than the previous one
121 best_pat = p
122 best_match = len(m.group(0))
123
124 # If we didn't find anything, raise an error
125 if best_pat == '(error)' and best_match < 0:
126 msg = "Bad Token"
127 if restrict:
128 msg = "Trying to find one of "+join(restrict,", ")
129 raise SyntaxError(self.pos, msg)
130
131 # If we found something that isn't to be ignored, return it
132 if best_pat not in self.ignore:
133 # Create a token with this data
134 token = (self.pos, self.pos+best_match, best_pat,
135 self.input[self.pos:self.pos+best_match])
136 self.pos = self.pos + best_match
137 # Only add this token if it's not in the list
138 # (to prevent looping)
139 if not self.tokens or token != self.tokens[-1]:
140 self.tokens.append(token)
141 self.restrictions.append(restrict)
142 return
143 else:
144 # This token should be ignored ..
145 self.pos = self.pos + best_match
146
147 class Parser:
148 def __init__(self, scanner):
149 self._scanner = scanner
150 self._pos = 0
151
152 def _peek(self, *types):
153 """Returns the token type for lookahead; if there are any args
154 then the list of args is the set of token types to allow"""
155 tok = self._scanner.token(self._pos, types)
156 return tok[2]
157
158 def _scan(self, type):
159 """Returns the matched text, and moves to the next token"""
160 tok = self._scanner.token(self._pos, [type])
161 if tok[2] != type:
162 raise SyntaxError(tok[0], 'Trying to find '+type)
163 self._pos = 1+self._pos
164 return tok[3]
165
166
167
168 def print_error(input, err, scanner):
169 """This is a really dumb long function to print error messages nicely."""
170 p = err.pos
171 # Figure out the line number
172 line = count(input[:p], '\n')
173 print(err.msg, " on line ", line + 1, ":", sep='')
174 # Now try printing part of the line
175 text = input[max(p-80,0):p+80]
176 p = p - max(p-80,0)
177
178 # Strip to the left
179 i = rfind(text[:p],'\n')
180 j = rfind(text[:p],'\r')
181 if i < 0 or (j < i and j >= 0): i = j
182 if i >= 0 and i < p:
183 p = p - i - 1
184 text = text[i+1:]
185
186 # Strip to the right
187 i = find(text,'\n',p)
188 j = find(text,'\r',p)
189 if i < 0 or (j < i and j >= 0): i = j
190 if i >= 0:
191 text = text[:i]
192
193 # Now shorten the text
194 while len(text) > 70 and p > 60:
195 # Cut off 10 chars
196 text = "..." + text[10:]
197 p = p - 7
198
199 # Now print the string, along with an indicator
200 print('> ',text)
201 print('> ',' '*p + '^')
202 print('List of nearby tokens:', scanner)
203
204 def wrap_error_reporter(parser, rule):
205 try: return getattr(parser, rule)()
206 except SyntaxError as s:
207 input = parser._scanner.input
208 try:
209 print_error(input, s, parser._scanner)
210 except ImportError:
211 print('Syntax Error',s.msg,'on line',1+count(input[:s.pos], '\n'))
212 except NoMoreTokens:
213 print('Could not complete parsing; stopped around here:')
214 print(parser._scanner)