-
Notifications
You must be signed in to change notification settings - Fork 161
/
ast.py
38 lines (31 loc) · 1.21 KB
/
ast.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import ast
from ast import *
from rope.base import fscommands
def parse(source, filename="<string>"):
# NOTE: the raw string should be given to `compile` function
if isinstance(source, str):
source = fscommands.unicode_to_file_data(source)
if b"\r" in source:
source = source.replace(b"\r\n", b"\n").replace(b"\r", b"\n")
if not source.endswith(b"\n"):
source += b"\n"
try:
return ast.parse(source, filename="<unknown>")
except (TypeError, ValueError) as e:
error = SyntaxError()
error.lineno = 1
error.filename = filename
error.msg = str(e)
raise error
def call_for_nodes(node, callback, recursive=False):
"""If callback returns `True` the child nodes are skipped"""
result = callback(node)
if recursive and not result:
for child in ast.iter_child_nodes(node):
call_for_nodes(child, callback, recursive)
class RopeNodeVisitor(ast.NodeVisitor):
def visit(self, node):
"""Modified from ast.NodeVisitor to match rope's existing Visitor implementation"""
method = "_" + node.__class__.__name__
visitor = getattr(self, method, self.generic_visit)
return visitor(node)