Skip to content Skip to sidebar Skip to footer

Function Boundary Identification Using Libclang

I am learning to parse C++ files using Python + libclang with the help of this very informative (but slightly outdated) tutorial by Eli Bendersky. My objective is to parse C++ file

Solution 1:

You're looking for the extent property on the Cursor class. For example:

s = '''
void f();
void g() 
{}
void f() 
{}
'''

idx = clang.cindex.Index.create()
tu = idx.parse('tmp.cpp', unsaved_files=[('tmp.cpp', s)])
for f in tu.cursor.walk_preorder():
    if f.kind == CursorKind.FUNCTION_DECL:
        print f.extent

Will return a Python equivalent of a source range:

<SourceRange start<SourceLocation file 'tmp.cpp', line 2, column1>, end<SourceLocation file 'tmp.cpp', line 2, column9>><SourceRange start<SourceLocation file 'tmp.cpp', line 3, column1>, end<SourceLocation file 'tmp.cpp', line 4, column3>><SourceRange start<SourceLocation file 'tmp.cpp', line 5, column1>, end<SourceLocation file 'tmp.cpp', line 6, column3>>

You may want to consider restricting attention to definitions using Cursor.is_definition if you want function bodies rather than just their declarations.

Solution 2:

#include"clang/Basic/SourceManager.h"

FunctionDecl *f;

SourceLocation ST = f->getSourceRange().getBegin();
SourceLocation ED = f->getSourceRange().getEnd();

https://github.com/eliben/llvm-clang-samples/blob/master/src_clang/rewritersample.cpp

https://clang.llvm.org/doxygen/classclang_1_1FunctionDecl.htmlhttps://clang.llvm.org/doxygen/classclang_1_1SourceRange.html

Post a Comment for "Function Boundary Identification Using Libclang"