forked from GumTreeDiff/pythonparser
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpythonparser
More file actions
executable file
·56 lines (48 loc) · 1.59 KB
/
pythonparser
File metadata and controls
executable file
·56 lines (48 loc) · 1.59 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
#!/usr/bin/env python3
from xml.dom import minidom
import parso
import sys
doc = minidom.Document()
positions = [0]
def main(file):
parsoAst = parso.parse(readFile(file))
gumtreeAst = toGumtreeNode(parsoAst)
doc.appendChild(gumtreeAst)
processNode(parsoAst, gumtreeAst)
xml = doc.toprettyxml()
print(xml)
def processNode(parsoNode, gumtreeNode):
if parsoNode.type == 'error_node':
sys.exit(parsoNode)
for parsoChild in parsoNode.children:
gumtreeChild = toGumtreeNode(parsoChild)
if gumtreeChild != None:
gumtreeNode.appendChild(gumtreeChild)
if hasattr(parsoChild, 'children'):
processNode(parsoChild, gumtreeChild)
def toGumtreeNode(parsoNode):
if parsoNode.type in ['keyword', 'newline', 'endmarker']:
return
if parsoNode.type == 'operator' and parsoNode.value in ['.', '(', ')', '[', ']', ':', ';']:
return
gumtreeNode = doc.createElement('tree')
gumtreeNode.setAttribute("type", parsoNode.type)
startPos = positions[parsoNode.start_pos[0] - 1] + parsoNode.start_pos[1]
endPos = positions[parsoNode.end_pos[0] - 1] + parsoNode.end_pos[1]
length = endPos - startPos
gumtreeNode.setAttribute("pos", str(startPos))
gumtreeNode.setAttribute("length", str(length))
if (not hasattr(parsoNode, 'children')) or len(parsoNode.children) == 0:
gumtreeNode.setAttribute("label", parsoNode.value)
return gumtreeNode
def readFile(file):
with open(file, 'r') as file:
data = file.read()
index = 0
for chr in data:
index += 1
if chr == '\n':
positions.append(index)
return data
if __name__ == '__main__':
main(sys.argv[1])