322 | 322 |
### term matching
|
323 | 323 |
|
324 | 324 |
def match_all(self, patterns, values):
|
|
325 |
"""Returns a dict of bindings if all values match all patterns,
|
|
326 |
or False if there was a mismatch.
|
|
327 |
|
|
328 |
"""
|
325 | 329 |
i = 0
|
326 | 330 |
bindings = {}
|
327 | 331 |
while i < len(patterns):
|
328 | |
sub_bindings = self.match_terms(patterns[i], values[i])
|
329 | |
bindings.update(sub_bindings)
|
|
332 |
sub = self.match_terms(patterns[i], values[i])
|
|
333 |
if sub == False:
|
|
334 |
return False
|
|
335 |
bindings.update(sub)
|
330 | 336 |
i += 1
|
331 | 337 |
return bindings
|
332 | 338 |
|
333 | 339 |
def match_terms(self, pattern, value):
|
|
340 |
"""Returns a dict of bindings if the values matches the pattern,
|
|
341 |
or False if there was a mismatch.
|
|
342 |
|
|
343 |
"""
|
334 | 344 |
if isinstance(pattern, Variable):
|
|
345 |
# TODO: check existing binding! oh well, assume unique for now.
|
335 | 346 |
return {pattern.name: value}
|
336 | 347 |
elif isinstance(pattern, Term):
|
337 | 348 |
i = 0
|
|
349 |
if pattern.name != value.name:
|
|
350 |
return False
|
338 | 351 |
bindings = {}
|
339 | 352 |
while i < len(pattern.contents):
|
340 | 353 |
b = self.match_terms(pattern.contents[i], value.contents[i])
|
|
359 | 372 |
return x
|
360 | 373 |
elif ast[0] == 'CALL':
|
361 | 374 |
prods = self.find_productions(ast[1])
|
|
375 |
debug("candidate productions: %r" % prods)
|
362 | 376 |
args = [x.expand(self) for x in ast[2]]
|
363 | 377 |
for prod in prods:
|
364 | 378 |
formals = prod[2]
|
|
379 |
debug("formals: %r, args: %r" % (formals, args))
|
365 | 380 |
if not formals:
|
366 | 381 |
return self.interpret(prod)
|
367 | 382 |
bindings = self.match_all(formals, args)
|
368 | |
if bindings:
|
|
383 |
debug("bindings: %r" % bindings)
|
|
384 |
if bindings != False:
|
369 | 385 |
return self.interpret(prod, bindings=bindings)
|
370 | 386 |
elif ast[0] == 'SEND':
|
371 | 387 |
result = self.interpret(ast[1])
|