Skip to content

Instantly share code, notes, and snippets.

@skmp
Created September 28, 2023 06:28
Show Gist options
  • Save skmp/7a39d98eec227865c6c1458dcd4ef8f9 to your computer and use it in GitHub Desktop.
Save skmp/7a39d98eec227865c6c1458dcd4ef8f9 to your computer and use it in GitHub Desktop.
libclang template arguments via python
template<int x, int y>
void DoSomething() {
// consume x, y as constants
}
void foo() {
DoSomething<0,1>();
DoSomething<640,480>();
}
CursorKind.TRANSLATION_UNIT test.cpp
CursorKind.FUNCTION_TEMPLATE DoSomething void ()
CursorKind.TEMPLATE_NON_TYPE_PARAMETER x int
CursorKind.TEMPLATE_NON_TYPE_PARAMETER y int
CursorKind.COMPOUND_STMT
CursorKind.FUNCTION_DECL foo void () _Z3foov
CursorKind.COMPOUND_STMT
CursorKind.CALL_EXPR DoSomething void
CursorKind.UNEXPOSED_EXPR DoSomething void (*)()
CursorKind.DECL_REF_EXPR DoSomething void ()
CursorKind.INTEGER_LITERAL int
0
CursorKind.INTEGER_LITERAL int
1
CursorKind.CALL_EXPR DoSomething void
CursorKind.UNEXPOSED_EXPR DoSomething void (*)()
CursorKind.DECL_REF_EXPR DoSomething void ()
CursorKind.INTEGER_LITERAL int
640
CursorKind.INTEGER_LITERAL int
480
import clang.cindex
from clang.cindex import *
from clang.cindex import conf, register_function, c_int, c_object_p
def traverse(node, level):
print('%s %-35s %-20s %-10s %s ' % (' ' * level,
node.kind, node.spelling, node.type.spelling, node.mangled_name))
if node.kind == clang.cindex.CursorKind.CALL_EXPR:
for arg in node.get_arguments():
print("ARG=%s %s" % (arg.kind, arg.spelling))
elif node.kind == clang.cindex.CursorKind.INTEGER_LITERAL:
eval = conf.lib.clang_Cursor_Evaluate(node)
if (eval):
eval = EvalResult(eval)
print(eval.getAsInt())
for child in node.get_children():
traverse(child, level+1)
class EvalResult:
def __init__(self, ptr):
self.ptr = ptr
def __del__(self):
conf.lib.clang_EvalResult_dispose(self)
def from_param(self):
return self.ptr
def getKind(self):
return conf.lib.clang_EvalResult_getKind(self)
def getAsInt(self):
return conf.lib.clang_EvalResult_getAsInt(self)
register_function(conf.lib, ("clang_Cursor_Evaluate", [Cursor], c_object_p), False) # not quite sure why EvalResult won't work here, seems like some issue with ctypes?
register_function(conf.lib, ("clang_EvalResult_getAsInt", [EvalResult],c_int), False)
register_function(conf.lib, ("clang_EvalResult_getKind", [EvalResult],c_int), False)
register_function(conf.lib, ("clang_EvalResult_dispose", [EvalResult]), False)
index = clang.cindex.Index.create()
translation_unit = index.parse('test.cpp', args=['-std=c++17'])
#ParseFromCursor(translation_unit.cursor)
traverse(translation_unit.cursor, 0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment