| 1 |
from __future__ import print_function |
| 2 |
|
| 3 |
import py |
| 4 |
from rpython.rlib.parsing.lexer import SourcePos |
| 5 |
from rpython.rlib.parsing.tree import Node, Symbol, Nonterminal |
| 6 |
from rpython.rlib.objectmodel import not_rpython |
| 7 |
|
| 8 |
class Rule(object): |
| 9 |
def __init__(self, nonterminal, expansions): |
| 10 |
self.nonterminal = nonterminal |
| 11 |
self.expansions = expansions |
| 12 |
|
| 13 |
def getkey(self): |
| 14 |
return (self.nonterminal, tuple(self.expansions)) |
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
def __eq__(self, other): |
| 20 |
return self.getkey() == other.getkey() |
| 21 |
|
| 22 |
def __ne__(self, other): |
| 23 |
return not self == other |
| 24 |
|
| 25 |
def __str__(self): |
| 26 |
return "%s: %s" % ( |
| 27 |
self.nonterminal, " | ".join([repr(e) for e in self.expansions])) |
| 28 |
|
| 29 |
def __repr__(self): |
| 30 |
return "Rule(%r, %r)" % (self.nonterminal, self.expansions) |
| 31 |
|
| 32 |
class LazyInputStream(object): |
| 33 |
def __init__(self, iterator): |
| 34 |
self.iterator = iter(iterator) |
| 35 |
self.data = [] |
| 36 |
|
| 37 |
def __getitem__(self, index): |
| 38 |
assert index >= 0 |
| 39 |
while len(self.data) <= index: |
| 40 |
try: |
| 41 |
self.data.append(self.iterator.next()) |
| 42 |
except StopIteration: |
| 43 |
raise IndexError("index out of range") |
| 44 |
return self.data[index] |
| 45 |
|
| 46 |
class ParseError(Exception): |
| 47 |
def __init__(self, source_pos, errorinformation): |
| 48 |
self.source_pos = source_pos |
| 49 |
self.errorinformation = errorinformation |
| 50 |
self.args = (source_pos, errorinformation) |
| 51 |
|
| 52 |
def nice_error_message(self, filename="<unknown>", source=""): |
| 53 |
|
| 54 |
result = [" File %s, line %s" % (filename, self.source_pos.lineno + 1)] |
| 55 |
if source: |
| 56 |
result.append(source.split("\n")[self.source_pos.lineno]) |
| 57 |
result.append(" " * self.source_pos.columnno + "^") |
| 58 |
else: |
| 59 |
result.append("<couldn't get source>") |
| 60 |
if self.errorinformation: |
| 61 |
failure_reasons = self.errorinformation.failure_reasons |
| 62 |
if len(failure_reasons) > 1: |
| 63 |
all_but_one = failure_reasons[:-1] |
| 64 |
last = failure_reasons[-1] |
| 65 |
expected = "%s or '%s'" % ( |
| 66 |
", ".join(["'%s'" % e for e in all_but_one]), last) |
| 67 |
else: |
| 68 |
expected = failure_reasons[0] |
| 69 |
result.append("ParseError: expected %s" % (expected, )) |
| 70 |
else: |
| 71 |
result.append("ParseError") |
| 72 |
return "\n".join(result) |
| 73 |
|
| 74 |
|
| 75 |
class ErrorInformation(object): |
| 76 |
def __init__(self, pos, failure_reasons=None): |
| 77 |
if failure_reasons is None: |
| 78 |
failure_reasons = [] |
| 79 |
self.failure_reasons = failure_reasons |
| 80 |
self.pos = pos |
| 81 |
|
| 82 |
def combine_errors(self, other): |
| 83 |
if self is None: |
| 84 |
return other |
| 85 |
if (other is None or self.pos > other.pos or |
| 86 |
len(other.failure_reasons) == 0): |
| 87 |
return self |
| 88 |
elif other.pos > self.pos or len(self.failure_reasons) == 0: |
| 89 |
return other |
| 90 |
failure_reasons = [] |
| 91 |
already_there = {} |
| 92 |
for fr in [self.failure_reasons, other.failure_reasons]: |
| 93 |
for reason in fr: |
| 94 |
if reason not in already_there: |
| 95 |
already_there[reason] = True |
| 96 |
failure_reasons.append(reason) |
| 97 |
return ErrorInformation(self.pos, failure_reasons) |
| 98 |
|
| 99 |
class LazyParseTable(object): |
| 100 |
def __init__(self, input, parser): |
| 101 |
self.parser = parser |
| 102 |
self.input = input |
| 103 |
self.matched = {} |
| 104 |
self.errorinformation = {} |
| 105 |
|
| 106 |
def match_symbol(self, i, symbol): |
| 107 |
|
| 108 |
|
| 109 |
if (i, symbol) in self.matched: |
| 110 |
return self.matched[i, symbol] |
| 111 |
error = None |
| 112 |
if self.parser.is_nonterminal(symbol): |
| 113 |
rule = self.parser.get_rule(symbol) |
| 114 |
subsymbol = None |
| 115 |
error = None |
| 116 |
for expansion in rule.expansions: |
| 117 |
curr = i |
| 118 |
children = [] |
| 119 |
for subsymbol in expansion: |
| 120 |
node, next, error2 = self.match_symbol(curr, subsymbol) |
| 121 |
if node is None: |
| 122 |
error = combine_errors(error, error2) |
| 123 |
break |
| 124 |
children.append(node) |
| 125 |
curr = next |
| 126 |
else: |
| 127 |
assert len(expansion) == len(children) |
| 128 |
result = (Nonterminal(symbol, children), curr, error) |
| 129 |
self.matched[i, symbol] = result |
| 130 |
return result |
| 131 |
self.matched[i, symbol] = None, 0, error |
| 132 |
return None, 0, error |
| 133 |
else: |
| 134 |
try: |
| 135 |
input = self.input[i] |
| 136 |
if self.terminal_equality(symbol, input): |
| 137 |
result = (Symbol(symbol, input.source, input), i + 1, error) |
| 138 |
self.matched[i, symbol] = result |
| 139 |
return result |
| 140 |
else: |
| 141 |
|
| 142 |
|
| 143 |
if (symbol.startswith("__") and |
| 144 |
symbol.split("_")[2][0] in "0123456789"): |
| 145 |
expected = symbol.split("_")[-1] |
| 146 |
else: |
| 147 |
expected = symbol |
| 148 |
error = ErrorInformation(i, [expected]) |
| 149 |
except IndexError: |
| 150 |
error = ErrorInformation(i) |
| 151 |
return None, 0, error |
| 152 |
|
| 153 |
def terminal_equality(self, symbol, input): |
| 154 |
return symbol == input.name |
| 155 |
|
| 156 |
|
| 157 |
class PackratParser(object): |
| 158 |
def __init__(self, rules, startsymbol, parsetablefactory=LazyParseTable, |
| 159 |
check_for_left_recursion=True): |
| 160 |
self.rules = rules |
| 161 |
self.nonterminal_to_rule = {} |
| 162 |
for rule in rules: |
| 163 |
self.nonterminal_to_rule[rule.nonterminal] = rule |
| 164 |
self.startsymbol = startsymbol |
| 165 |
if check_for_left_recursion: |
| 166 |
assert not self.has_left_recursion() |
| 167 |
self.parsetablefactory = parsetablefactory |
| 168 |
|
| 169 |
def is_nonterminal(self, symbol): |
| 170 |
return symbol in self.nonterminal_to_rule |
| 171 |
|
| 172 |
def get_rule(self, symbol): |
| 173 |
return self.nonterminal_to_rule[symbol] |
| 174 |
|
| 175 |
def parse(self, tokeniterator, lazy=False): |
| 176 |
if lazy: |
| 177 |
input = LazyInputStream(tokeniterator) |
| 178 |
else: |
| 179 |
input = list(tokeniterator) |
| 180 |
table = self.parsetablefactory(input, self) |
| 181 |
result = table.match_symbol(0, self.startsymbol) |
| 182 |
if result[0] is None: |
| 183 |
error = result[2] |
| 184 |
raise ParseError(input[error.pos].source_pos, error) |
| 185 |
return result[0] |
| 186 |
|
| 187 |
@not_rpython |
| 188 |
def has_left_recursion(self): |
| 189 |
follows = {} |
| 190 |
for rule in self.rules: |
| 191 |
follow = py.builtin.set() |
| 192 |
follows[rule.nonterminal] = follow |
| 193 |
for expansion in rule.expansions: |
| 194 |
if expansion and self.is_nonterminal(expansion[0]): |
| 195 |
follow.add(expansion[0]) |
| 196 |
changed = True |
| 197 |
while changed: |
| 198 |
changed = False |
| 199 |
for nonterminal, follow in follows.iteritems(): |
| 200 |
for nt in follow: |
| 201 |
subfollow = follows[nt] |
| 202 |
update = subfollow - follow |
| 203 |
if update: |
| 204 |
changed = True |
| 205 |
follow.update(update) |
| 206 |
break |
| 207 |
for nonterminal, follow in follows.iteritems(): |
| 208 |
if nonterminal in follow: |
| 209 |
print("nonterminal %s is in its own follow %s" % (nonterminal, follow)) |
| 210 |
return True |
| 211 |
return False |
| 212 |
|
| 213 |
def __repr__(self): |
| 214 |
from pprint import pformat |
| 215 |
return "%s%s" % (self.__class__.__name__, |
| 216 |
pformat((self.rules, self.startsymbol)), ) |
| 217 |
|
| 218 |
class ParserCompiler(object): |
| 219 |
def __init__(self, parser): |
| 220 |
self.parser = parser |
| 221 |
self.allcode = [] |
| 222 |
self.symbol_to_number = {} |
| 223 |
self.made = {} |
| 224 |
|
| 225 |
def compile(self): |
| 226 |
from rpython.tool.sourcetools import func_with_new_name |
| 227 |
self.allcode.append("class CompileableParser(baseclass):") |
| 228 |
self.make_matcher(self.parser.startsymbol) |
| 229 |
self.make_fixed() |
| 230 |
miniglobals = globals().copy() |
| 231 |
miniglobals["baseclass"] = self.parser.__class__ |
| 232 |
|
| 233 |
exec(py.code.Source("\n".join(self.allcode)).compile(), miniglobals) |
| 234 |
kls = miniglobals["CompileableParser"] |
| 235 |
|
| 236 |
parsetable = self.parser.parsetablefactory([], self.parser) |
| 237 |
kls.terminal_equality = func_with_new_name( |
| 238 |
parsetable.terminal_equality.im_func, |
| 239 |
"terminal_equality_compileable") |
| 240 |
return kls |
| 241 |
|
| 242 |
def get_number(self, symbol): |
| 243 |
if symbol in self.symbol_to_number: |
| 244 |
return self.symbol_to_number[symbol] |
| 245 |
result = len(self.symbol_to_number) |
| 246 |
self.symbol_to_number[symbol] = result |
| 247 |
return result |
| 248 |
|
| 249 |
def make_matcher(self, symbol): |
| 250 |
if symbol not in self.made: |
| 251 |
self.made[symbol] = True |
| 252 |
if self.parser.is_nonterminal(symbol): |
| 253 |
self.make_nonterminal_matcher(symbol) |
| 254 |
else: |
| 255 |
self.make_terminal_matcher(symbol) |
| 256 |
|
| 257 |
def make_terminal_matcher(self, symbol): |
| 258 |
number = self.get_number(symbol) |
| 259 |
self.allcode.append(""" |
| 260 |
def match_terminal%(number)s(self, i): |
| 261 |
# matcher for terminal %(number)s %(symbol)r |
| 262 |
if i in self.matched_terminals%(number)s: |
| 263 |
return self.matched_terminals%(number)s[i] |
| 264 |
try: |
| 265 |
input = self.input[i] |
| 266 |
if self.terminal_equality(%(symbol)r, input): |
| 267 |
symbol = Symbol(%(symbol)r, input.name, input) |
| 268 |
result = (symbol, i + 1) |
| 269 |
self.matched_terminals%(number)s[i] = result |
| 270 |
return result |
| 271 |
except IndexError: |
| 272 |
pass |
| 273 |
return None, i""" % vars()) |
| 274 |
|
| 275 |
def make_nonterminal_matcher(self, symbol): |
| 276 |
number = self.get_number(symbol) |
| 277 |
rule = self.parser.nonterminal_to_rule[symbol] |
| 278 |
code = [] |
| 279 |
code.append(""" |
| 280 |
def match_nonterminal%(number)s(self, i): |
| 281 |
# matcher for nonterminal %(number)s %(symbol)s |
| 282 |
if i in self.matched_nonterminals%(number)s: |
| 283 |
return self.matched_nonterminals%(number)s[i] |
| 284 |
last_failed_position = 0 |
| 285 |
subsymbol = None |
| 286 |
expansionindex = 0 |
| 287 |
while 1:""" % vars()) |
| 288 |
for expansionindex, expansion in enumerate(rule.expansions): |
| 289 |
nextindex = expansionindex + 1 |
| 290 |
code.append("""\ |
| 291 |
if expansionindex == %s:""" % (expansionindex, )) |
| 292 |
if not expansion: |
| 293 |
code.append("""\ |
| 294 |
result = (Nonterminal(symbol, []), i) |
| 295 |
self.matched_nonterminals%(number)s[i] = result |
| 296 |
return result""" % vars()) |
| 297 |
continue |
| 298 |
code.append("""\ |
| 299 |
curr = i |
| 300 |
children = []""") |
| 301 |
for subsymbol in expansion: |
| 302 |
self.make_matcher(subsymbol) |
| 303 |
if self.parser.is_nonterminal(subsymbol): |
| 304 |
match = "match_nonterminal%s" % self.get_number(subsymbol) |
| 305 |
else: |
| 306 |
match = "match_terminal%s" % self.get_number(subsymbol) |
| 307 |
code.append("""\ |
| 308 |
node, next = self.%(match)s(curr) |
| 309 |
if node is None: |
| 310 |
last_failed_position = next |
| 311 |
expansionindex = %(nextindex)s |
| 312 |
continue |
| 313 |
curr = next""" % vars()) |
| 314 |
code.append("""\ |
| 315 |
result = (Nonterminal(%(symbol)r, children), curr) |
| 316 |
self.matched_nonterminals%(number)s[i] = result |
| 317 |
return result""" % vars()) |
| 318 |
code.append("""\ |
| 319 |
if expansionindex == %(nextindex)s: |
| 320 |
result = None, last_failed_position |
| 321 |
self.matched_nonterminals%(number)s[i] = result |
| 322 |
return result""" % vars()) |
| 323 |
self.allcode.extend(code) |
| 324 |
|
| 325 |
def make_fixed(self): |
| 326 |
|
| 327 |
code = [""" |
| 328 |
def __init__(self): |
| 329 |
self.rules = [] # dummy |
| 330 |
self.nonterminal_to_rule = {} # dummy |
| 331 |
self.startsymbol = "" # dummy |
| 332 |
self.parsetablefactory = None # dummy"""] |
| 333 |
for symbol, number in self.symbol_to_number.iteritems(): |
| 334 |
if self.parser.is_nonterminal(symbol): |
| 335 |
name = "matched_nonterminals%s" % number |
| 336 |
else: |
| 337 |
name = "matched_terminals%s" % number |
| 338 |
code.append("""\ |
| 339 |
self.%(name)s = {}""" % vars()) |
| 340 |
|
| 341 |
startsymbol = self.get_number(self.parser.startsymbol) |
| 342 |
code.append(""" |
| 343 |
def parse(self, tokenlist, lazy=True): |
| 344 |
self.input = tokenlist |
| 345 |
result = self.match_nonterminal%(startsymbol)s(0) |
| 346 |
if result[0] is None: |
| 347 |
raise ParseError(None, self.input[result[1]]) |
| 348 |
return result[0]""" % (vars())) |
| 349 |
self.allcode.extend(code) |