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?