1 # Copyright 2006 Google, Inc. All Rights Reserved.
2 # Licensed to PSF under a Contributor Agreement.
6 The grammer is taken from PatternGrammar.txt.
8 The compiler compiles a pattern to a pytree.*Pattern instance.
11 __author__ = "Guido van Rossum <guido@python.org>"
16 # Fairly local imports
17 from .pgen2 import driver, literals, token, tokenize, parse, grammar
19 # Really local imports
23 # The pattern grammar file
24 _PATTERN_GRAMMAR_FILE = os.path.join(os.path.dirname(__file__),
28 class PatternSyntaxError(Exception):
32 def tokenize_wrapper(input):
33 """Tokenizes a string suppressing significant whitespace."""
34 skip = set((token.NEWLINE, token.INDENT, token.DEDENT))
35 tokens = tokenize.generate_tokens(driver.generate_lines(input).next)
36 for quintuple in tokens:
37 type, value, start, end, line_text = quintuple
42 class PatternCompiler(object):
44 def __init__(self, grammar_file=_PATTERN_GRAMMAR_FILE):
47 Takes an optional alternative filename for the pattern grammar.
49 self.grammar = driver.load_grammar(grammar_file)
50 self.syms = pygram.Symbols(self.grammar)
51 self.pygrammar = pygram.python_grammar
52 self.pysyms = pygram.python_symbols
53 self.driver = driver.Driver(self.grammar, convert=pattern_convert)
55 def compile_pattern(self, input, debug=False, with_tree=False):
56 """Compiles a pattern string to a nested pytree.*Pattern object."""
57 tokens = tokenize_wrapper(input)
59 root = self.driver.parse_tokens(tokens, debug=debug)
60 except parse.ParseError as e:
61 raise PatternSyntaxError(str(e))
63 return self.compile_node(root), root
65 return self.compile_node(root)
67 def compile_node(self, node):
68 """Compiles a node, recursively.
70 This is one big switch on the node type.
72 # XXX Optimize certain Wildcard-containing-Wildcard patterns
74 if node.type == self.syms.Matcher:
75 node = node.children[0] # Avoid unneeded recursion
77 if node.type == self.syms.Alternatives:
78 # Skip the odd children since they are just '|' tokens
79 alts = [self.compile_node(ch) for ch in node.children[::2]]
82 p = pytree.WildcardPattern([[a] for a in alts], min=1, max=1)
85 if node.type == self.syms.Alternative:
86 units = [self.compile_node(ch) for ch in node.children]
89 p = pytree.WildcardPattern([units], min=1, max=1)
92 if node.type == self.syms.NegatedUnit:
93 pattern = self.compile_basic(node.children[1:])
94 p = pytree.NegatedPattern(pattern)
97 assert node.type == self.syms.Unit
100 nodes = node.children
101 if len(nodes) >= 3 and nodes[1].type == token.EQUAL:
102 name = nodes[0].value
105 if len(nodes) >= 2 and nodes[-1].type == self.syms.Repeater:
109 # Now we've reduced it to: STRING | NAME [Details] | (...) | [...]
110 pattern = self.compile_basic(nodes, repeat)
112 if repeat is not None:
113 assert repeat.type == self.syms.Repeater
114 children = repeat.children
116 if child.type == token.STAR:
119 elif child.type == token.PLUS:
122 elif child.type == token.LBRACE:
123 assert children[-1].type == token.RBRACE
124 assert len(children) in (3, 5)
125 min = max = self.get_int(children[1])
126 if len(children) == 5:
127 max = self.get_int(children[3])
130 if min != 1 or max != 1:
131 pattern = pattern.optimize()
132 pattern = pytree.WildcardPattern([[pattern]], min=min, max=max)
136 return pattern.optimize()
138 def compile_basic(self, nodes, repeat=None):
139 # Compile STRING | NAME [Details] | (...) | [...]
140 assert len(nodes) >= 1
142 if node.type == token.STRING:
143 value = unicode(literals.evalString(node.value))
144 return pytree.LeafPattern(_type_of_literal(value), value)
145 elif node.type == token.NAME:
148 if value not in TOKEN_MAP:
149 raise PatternSyntaxError("Invalid token: %r" % value)
151 raise PatternSyntaxError("Can't have details for token")
152 return pytree.LeafPattern(TOKEN_MAP[value])
156 elif not value.startswith("_"):
157 type = getattr(self.pysyms, value, None)
159 raise PatternSyntaxError("Invalid symbol: %r" % value)
160 if nodes[1:]: # Details present
161 content = [self.compile_node(nodes[1].children[1])]
164 return pytree.NodePattern(type, content)
165 elif node.value == "(":
166 return self.compile_node(nodes[1])
167 elif node.value == "[":
168 assert repeat is None
169 subpattern = self.compile_node(nodes[1])
170 return pytree.WildcardPattern([[subpattern]], min=0, max=1)
173 def get_int(self, node):
174 assert node.type == token.NUMBER
175 return int(node.value)
178 # Map named tokens to the type value for a LeafPattern
179 TOKEN_MAP = {"NAME": token.NAME,
180 "STRING": token.STRING,
181 "NUMBER": token.NUMBER,
185 def _type_of_literal(value):
186 if value[0].isalpha():
188 elif value in grammar.opmap:
189 return grammar.opmap[value]
194 def pattern_convert(grammar, raw_node_info):
195 """Converts raw node information to a Node or Leaf instance."""
196 type, value, context, children = raw_node_info
197 if children or type in grammar.number2symbol:
198 return pytree.Node(type, children, context=context)
200 return pytree.Leaf(type, value, context=context)
203 def compile_pattern(pattern):
204 return PatternCompiler().compile_pattern(pattern)