-
Notifications
You must be signed in to change notification settings - Fork 0
/
nodeutils.py
67 lines (50 loc) · 1.37 KB
/
nodeutils.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
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
64
65
66
67
"""
Utilities for nodes (cursors) in the Clang AST
"""
from clang.cindex import CursorKind
from mylog import log
import clang
def pp(node):
"""
Return str of node for pretty print
"""
try:
return f'{node.spelling} ({node.kind}) [{node.location}]'
except:
return f'{node.spelling} ({node.kind})'
def find(node, selector, verbose=False):
"""
Return all node's descendants of a certain kind
"""
if verbose:
log.debug(f'find: walked node {pp(node)}')
found = []
if isinstance(selector, CursorKind):
if node.kind == selector:
found.append(node)
elif callable(selector):
if selector(node):
found.append(node)
# Recurse for children of this node
for child in node.get_children():
found += find(child, selector, verbose)
return found
class GlobalIndex:
"""
Singleton Clang Index
"""
def __init__(self):
self.index = clang.cindex.Index.create()
_instance = None
@classmethod
def get(cls):
if cls._instance is None:
cls._instance = GlobalIndex()
return cls._instance.index
def parse(filepath, args=[]):
"""
Parse filepath and return a cursor to the translation unit
"""
index = GlobalIndex.get()
translation_unit = index.parse(filepath, args=args)
return translation_unit.cursor