318
|
1
|
|
2 class Tree:
|
319
|
3 """ Tree node with a name and possibly some child nodes """
|
318
|
4 def __init__(self, name, *args):
|
|
5 self.name = name
|
|
6 self.children = args
|
|
7
|
|
8 def __repr__(self):
|
319
|
9 if self.children:
|
|
10 ch = ', '.join(str(c) for c in self.children)
|
|
11 return '{}({})'.format(self.name, ch)
|
|
12 else:
|
|
13 return '{}'.format(self.name)
|
|
14
|
|
15
|
|
16 class State:
|
320
|
17 """ State used to label tree nodes """
|
319
|
18 def __init__(self):
|
|
19 self.labels = {}
|
320
|
20
|
319
|
21 def has_goal(self, goal):
|
|
22 return goal in self.labels
|
320
|
23
|
319
|
24 def get_cost(self, goal):
|
|
25 return self.labels[goal][0]
|
320
|
26
|
319
|
27 def get_rule(self, goal):
|
|
28 return self.labels[goal][1]
|
320
|
29
|
319
|
30 def set_cost(self, goal, cost, rule):
|
|
31 if self.has_goal(goal):
|
|
32 if self.get_cost(goal) > cost:
|
|
33 self.labels[goal] = (cost, rule)
|
|
34 else:
|
|
35 self.labels[goal] = (cost, rule)
|
|
36
|
320
|
37
|
319
|
38 class BaseMatcher:
|
320
|
39 """ Base class for matcher objects. """
|
319
|
40 def kids(self, tree, rule):
|
|
41 return self.kid_functions[rule](tree)
|
|
42
|
|
43 def nts(self, rule):
|
|
44 return self.nts_map[rule]
|
|
45
|
|
46 def burm_label(self, tree):
|
320
|
47 """ Label all nodes in the tree bottom up """
|
319
|
48 for c in tree.children:
|
|
49 self.burm_label(c)
|
|
50 self.burm_state(tree)
|
|
51
|
|
52 def apply_rules(self, tree, goal):
|
|
53 rule = tree.state.get_rule(goal)
|
320
|
54 results = [self.apply_rules(kid_tree, kid_goal)
|
|
55 for kid_tree, kid_goal in zip(self.kids(tree, rule), self.nts(rule))]
|
|
56 self.pat_f[rule](*results)
|