[cfe-dev] how to get AST content from CXCursor?

Jacob Carlborg via cfe-dev cfe-dev at lists.llvm.org
Sat Oct 27 05:45:40 PDT 2018


On 2018-10-25 14:27, Lou Wynn via cfe-dev wrote:
> I've found some functions in the tools/libclang/CXCursor.h file, and 
> they are:
> 
> std::pair<OverloadedDeclRefStorage, SourceLocation>
>    getCursorOverloadedDeclRef(CXCursor C);
> 
> const Decl *getCursorDecl(CXCursor Cursor);
> const Expr *getCursorExpr(CXCursor Cursor);
> const Stmt *getCursorStmt(CXCursor Cursor);
> const Attr *getCursorAttr(CXCursor Cursor);
> const Decl *getCursorParentDecl(CXCursor Cursor);
> 
> ASTContext &getCursorContext(CXCursor Cursor);
> ASTUnit *getCursorASTUnit(CXCursor Cursor);
> CXTranslationUnit getCursorTU(CXCursor Cursor);
> 
> void getOverriddenCursors(CXCursor cursor,
>                            SmallVectorImpl<CXCursor> &overridden);
> 
> 
> Some of them are implemented as follows:
> 
> const Decl *cxcursor::getCursorDecl(CXCursor Cursor) {
>    return static_cast<const Decl *>(Cursor.data[0]);
> }
> 
> const Stmt *cxcursor::getCursorStmt(CXCursor Cursor) {
>    if (Cursor.kind == CXCursor_ObjCSuperClassRef ||
>        Cursor.kind == CXCursor_ObjCProtocolRef ||
>        Cursor.kind == CXCursor_ObjCClassRef)
>      return nullptr;
> 
>    return static_cast<const Stmt *>(Cursor.data[1]);
> }
> 
> const Attr *cxcursor::getCursorAttr(CXCursor Cursor) {
>    return static_cast<const Attr *>(Cursor.data[1]);
> }
> 
> const Decl *cxcursor::getCursorParentDecl(CXCursor Cursor) {
>    return static_cast<const Decl *>(Cursor.data[0]);
> }
> 
> 
> But they are not exported in the libClang. I'm wondering if I can use 
> them in my code, and how? Can anyone give me any hints on when to use 
> data[i], where i = 0, 1, 2? This would be the best way for me to get the 
> contents of a node and do source-to-source translation, if it works.

You're looking at the implementation of libclang, which is in C++. These 
functions will not be exposed. You should look at CXCursor mostly as an 
opaque data structure. It's fine to read the "kind" field but you should 
probably avoid the other two fields ("xdata" and "data").

-- 
/Jacob Carlborg




More information about the cfe-dev mailing list