-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathparse_code.py
More file actions
65 lines (50 loc) · 1.77 KB
/
Copy pathparse_code.py
File metadata and controls
65 lines (50 loc) · 1.77 KB
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
from org.python.core import ParserFacade
from org.python.core import CompileMode
from org.python.core import CompilerFlags
import sys
code = """
from ij import IJ, ImageJ
imp = IJ.getImage()
def setRoi(an_imp):
ip = an_imp.getStack().getProcessor(3)
pixels = ip.
"""
# Last line would fail compilation, so must not be included
code_without_last = "\n".join(code.split("\n")[:-2])
# The goal: discover the type of "ip" so that we can find out
# which methods we could autocomplete with:
try:
# "exec" means consider the whole code provided.
# See https://greentreesnakes.readthedocs.io/en/latest/tofrom.html#modes
mod = ParserFacade.parse(code_without_last,
CompileMode.exec,
"<none>",
CompilerFlags())
except:
print sys.exc_info()
# mod.body is a list of parsed code blocks
# equivalent to PythonTree.getChildren
# ImportFrom
importStatement = mod.body[0]
print importStatement.module # ij
print importStatement.names[0].name # IJ
print importStatement.names[1].name # ImageJ
# Assign
assign = mod.body[1]
print assign.targets[0].id # imp
print assign.value.func.value.id # IJ
print assign.value.func.attr # getImage
print assign.value.args # []
# FunctionDef
fn = mod.body[2]
print fn.name # setRoi
print fn.args.args[0].id # an_imp
fn_assign = fn.body[0]
print fn_assign.targets[0].id # ip
print fn_assign.value.func.value.func.value.id # an_imp
print fn_assign.value.func.value.func.attr # getStack
print fn_assign.value.func.attr # getProcessor
print fn_assign.value.args # [3]
# We don't know the class of ip, as it depends on
# a typeless argument of setRoi: that's why python developed annotation libraries like mypy
# But at least we have all the "Assign" entries for autocompletion