Parsing libclang generates incorrect output

I am trying to create a small syntax program using libclang.

Source file for parsing (Node.h):

#pragma once struct Node { int value; struct Node *next; }; 

The basic program simple calls the parser and executes all the elements in the AST:

 int main(int argc, char *argv[]) { CXIndex index = clang_createIndex(0, 0); const char *filename = "Node.h"; CXTranslationUnit TU = clang_parseTranslationUnit(index, filename, NULL, 0, NULL, 0, CXTranslationUnit_None); CXCursor rootCursor = clang_getTranslationUnitCursor(TU); clang_visitChildren(rootCursor, printVisitor, NULL); clang_disposeTranslationUnit(TU); clang_disposeIndex(index); return 0; } 

Visitor:

 CXChildVisitResult printVisitor(CXCursor cursor, CXCursor parent, CXClientData client_data) { CXSourceRange range = clang_getCursorExtent(cursor); CXSourceLocation startLocation = clang_getRangeStart(range); CXSourceLocation endLocation = clang_getRangeEnd(range); CXFile file; unsigned int line, column, offset; clang_getInstantiationLocation(startLocation, &file, &line, &column, &offset); printf("Start: Line: %u Column: %u Offset: %u\n", line, column, offset); clang_getInstantiationLocation(endLocation, &file, &line, &column, &offset); printf("End: Line: %u Column: %u Offset: %u\n", line, column, offset); return CXChildVisit_Recurse; } 

However, the output shows some strange parts:

 Start: Line: 99 Column: 9 Offset: 3160 End: Line: 99 Column: 122 Offset: 3273 Kind: A field (in C) or non-static data member (in C++) in a struct. Filename: (null) 

Where did it come from?

When you delete a pragma, nothing changes. The same thing happens with a completely empty header file for parsing.

Do I need to go around all the nodes found in the AST until I get the "first statement" - or the "first expression" - node?

+4
source share
1 answer

I got TU as follows:

CXTranslationUnit TU = clang_parseTranslationUnit (index, 0, argv, argc, 0, 0, CXTranslationUnit_None);

And then I ran the test file (Node.h), got the result:

Start: Row: 3 Column: 1 Offset: 14

End: Line: 6 Column: 2 Offset: 67

Start: Row: 4 Column: 5 Offset: 32

End: Line: 4 Column: 14 Offset: 41

Start: Line: 5 Column: 5 Offset: 47

End: Row: 5 Column: 22 Offset: 64

Start: Line: 5 Column: 12 Offset: 54

End: Row: 5 Column: 16 Offset: 58

I think the result is correct. You can try it like this.

0
source

Source: https://habr.com/ru/post/1345684/


All Articles