Skip to content

Commit 2beb879

Browse files
authored
Merge branch 'python3' into master
2 parents 4e84507 + 7dee871 commit 2beb879

File tree

3 files changed

+24
-6
lines changed

3 files changed

+24
-6
lines changed

README.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
# pythonparser
2+
3+
Pythonparser is a python tool that produces a GumTree compatible Python AST. It uses under the hood asttokens and jsontree.
4+
5+
## Installation
6+
7+
Just clone the repository and `pip install -r requirements.txt`

pythonparser

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -21,10 +21,9 @@ def parse_file(filename):
2121
json_tree = []
2222

2323
def localize(node, json_node):
24-
json_node['line_no'] = str(node.first_token.start[0])
25-
json_node['col'] = str(node.first_token.start[1])
26-
json_node['end_line_no'] = str(node.last_token.end[0])
27-
json_node['end_col'] = str(node.last_token.end[1])
24+
json_pos_and_length = extract_pos_and_length(node, node)
25+
json_node['pos'] = str(json_pos_and_length[0])
26+
json_node['length'] = str(json_pos_and_length[1])
2827

2928
def gen_identifier(identifier, node_type = 'identifier', node=None):
3029
pos = len(json_tree)
@@ -46,6 +45,7 @@ def parse_file(filename):
4645
children.append(traverse(item))
4746
if (len(children) != 0):
4847
json_node['children'] = children
48+
4949
return pos
5050

5151
def traverse(node):
@@ -54,7 +54,6 @@ def parse_file(filename):
5454
json_tree.append(json_node)
5555
json_node['type'] = type(node).__name__
5656
localize(node, json_node)
57-
5857
children = []
5958
if isinstance(node, ast.Name):
6059
json_node['value'] = node.id
@@ -140,12 +139,22 @@ def parse_file(filename):
140139

141140
if (len(children) != 0):
142141
json_node['children'] = children
142+
143143
return pos
144144

145+
def extract_pos_and_length(node, other_node):
146+
try:
147+
return [node.startpos, other_node.endpos - node.startpos]
148+
except:
149+
try:
150+
return [node.first_token.startpos, other_node.last_token.endpos - node.first_token.startpos]
151+
except:
152+
pass
153+
return [-1, -1]
154+
145155
traverse(tree)
146156
return json_tree
147157

148-
149158
def json2xml(tree):
150159
lines = []
151160
def convert_node(i, indent_level=0):

requirements.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
jsontree
2+
asttokens

0 commit comments

Comments
 (0)