MCPcopy Create free account
hub / github.com/DeepRec-AI/DeepRec / PatternMatcher

Class PatternMatcher

tensorflow/python/autograph/pyct/ast_util.py:129–190  ·  view source on GitHub ↗

Matches a node against a pattern represented by a node.

Source from the content-addressed store, hash-verified

127
128
129class PatternMatcher(gast.NodeVisitor):
130 """Matches a node against a pattern represented by a node."""
131
132 def __init__(self, pattern):
133 self.pattern = pattern
134 self.pattern_stack = []
135 self.matches = True
136
137 def compare_and_visit(self, node, pattern):
138 self.pattern_stack.append(self.pattern)
139 self.pattern = pattern
140 self.generic_visit(node)
141 self.pattern = self.pattern_stack.pop()
142
143 def no_match(self):
144 self.matches = False
145 return False
146
147 def is_wildcard(self, p):
148 if isinstance(p, (list, tuple)) and len(p) == 1:
149 p, = p
150 if isinstance(p, gast.Name) and p.id == '_':
151 return True
152 if p == '_':
153 return True
154 return False
155
156 def generic_visit(self, node):
157 if not self.matches:
158 return
159
160 pattern = self.pattern
161 for f in node._fields:
162 if f.startswith('__'):
163 continue
164
165 if not hasattr(node, f):
166 if hasattr(pattern, f) and getattr(pattern, f):
167 return self.no_match()
168 else:
169 continue
170 if not hasattr(pattern, f):
171 return self.no_match()
172
173 v = getattr(node, f)
174 p = getattr(pattern, f)
175
176 if self.is_wildcard(p):
177 continue
178 if isinstance(v, (list, tuple)):
179 if not isinstance(p, (list, tuple)) or len(v) != len(p):
180 return self.no_match()
181 for v_item, p_item in zip(v, p):
182 self.compare_and_visit(v_item, p_item)
183 elif isinstance(v, (gast.AST, ast.AST)):
184 if not isinstance(v, type(p)) and not isinstance(p, type(v)):
185 return self.no_match()
186 self.compare_and_visit(v, p)

Callers 1

matchesFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected