def _get_node_text(self, node, force=False): if not force and node in self.matched_asts: return self._get_matched_text(self.matched_asts[node]) start, end = patchedast.node_region(node) main_text = self.source[start:end] collector = codeanalyze.ChangeCollector(main_text) for node in self._get_nearest_roots(node): sub_start, sub_end = patchedast.node_region(node) collector.add_change(sub_start - start, sub_end - start, self._get_node_text(node)) result = collector.get_changed() if result is None: return main_text return result
def _evaluate_node(self, pymodule, node): scope = pymodule.get_scope().get_inner_scope_for_line(node.lineno) expression = node if isinstance(expression, ast.Name) and isinstance(expression.ctx, ast.Store): start, end = patchedast.node_region(expression) text = pymodule.source_code[start:end] return evaluate.eval_str(scope, text) else: return evaluate.eval_node(scope, expression)
def _evaluate_node(self, pymodule, node): scope = pymodule.get_scope().get_inner_scope_for_line(node.lineno) expression = node if isinstance(expression, ast.Name) and \ isinstance(expression.ctx, ast.Store): start, end = patchedast.node_region(expression) text = pymodule.source_code[start:end] return evaluate.get_string_result(scope, text) else: return evaluate.get_statement_result(scope, expression)
def _find_self_assignments(self, node, source): result = [] finder = similarfinder.RawSimilarFinder(source, node) lines = codeanalyze.SourceLinesAdapter(source) for self_assignment in finder.get_matches('${?a} = ${?a}'): region = patchedast.node_region(self_assignment.get_ast('?a')) message = 'Assigning <%s> to itself' % source[region[0]:region[1]] lineno = lines.get_line_number(self_assignment.get_region()[0]) result.append((lineno, message)) return result
def _replace_occurrences(self, content, extract_info): for match in extract_info.matches: replacement = similarfinder.CodeTemplate( extract_info.replacement_pattern) mapping = {} for name in replacement.get_names(): node = match.get_ast(name) if node: start, end = patchedast.node_region(match.get_ast(name)) mapping[name] = self.info.source[start:end] else: mapping[name] = name region = match.get_region() content.add_change(region[0], region[1], replacement.substitute(mapping))
def get_region(self): self._calculate_scope_regions_for_module() node = self.pyobject.get_ast() region = patchedast.node_region(node) return region