Path: blob/master/elisp/emacs-for-python/rope-dist/rope/base/ast.py
1415 views
import _ast1from _ast import *23from rope.base import fscommands456def parse(source, filename='<string>'):7# NOTE: the raw string should be given to `compile` function8if isinstance(source, unicode):9source = fscommands.unicode_to_file_data(source)10if '\r' in source:11source = source.replace('\r\n', '\n').replace('\r', '\n')12if not source.endswith('\n'):13source += '\n'14try:15return compile(source, filename, 'exec', _ast.PyCF_ONLY_AST)16except (TypeError, ValueError), e:17error = SyntaxError()18error.lineno = 119error.filename = filename20error.msg = str(e)21raise error222324def walk(node, walker):25"""Walk the syntax tree"""26method_name = '_' + node.__class__.__name__27method = getattr(walker, method_name, None)28if method is not None:29return method(node)30for child in get_child_nodes(node):31walk(child, walker)323334def get_child_nodes(node):35if isinstance(node, _ast.Module):36return node.body37result = []38if node._fields is not None:39for name in node._fields:40child = getattr(node, name)41if isinstance(child, list):42for entry in child:43if isinstance(entry, _ast.AST):44result.append(entry)45if isinstance(child, _ast.AST):46result.append(child)47return result484950def call_for_nodes(node, callback, recursive=False):51"""If callback returns `True` the child nodes are skipped"""52result = callback(node)53if recursive and not result:54for child in get_child_nodes(node):55call_for_nodes(child, callback, recursive)565758def get_children(node):59result = []60if node._fields is not None:61for name in node._fields:62if name in ['lineno', 'col_offset']:63continue64child = getattr(node, name)65result.append(child)66return result676869