[cfe-users] How to create TranslationUnit for source code?
Kirill Bugaev via cfe-users
cfe-users at lists.llvm.org
Mon Apr 8 06:21:27 PDT 2019
I write program which determines type of instance under cursor in source
code. I pass on ast-file and cursor location as cmd arguments and output
instance location(line number and column) and its type.
#include <stdio.h>
> #include <stdlib.h>
> #include <clang-c/Index.h>
> int main(int argc, char *argv[])
> {
> CXIndex index;
> CXTranslationUnit tu;
> CXFile file;
> CXSourceLocation loc;
> CXCursor cursor, def;
> CXType type;
> CXString typesp;
> const char *types;
> index = clang_createIndex(0, 0);
> // tu = clang_createTranslationUnitFromSourceFile(index, argv[1],
> // 0, NULL, 0, NULL);
> tu = clang_createTranslationUnit(index, argv[1]);
> file = clang_getFile(tu, argv[1]);
> loc = clang_getLocation(tu, file, atoi(argv[2]), atoi(argv[3]));
> cursor = clang_getCursor(tu, loc);
> /* Cursor location check */
> CXSourceLocation testloc;
> testloc = clang_getCursorLocation(cursor);
> unsigned lnum, colnum;
> clang_getFileLocation(testloc, NULL, &lnum, &colnum, NULL);
> printf("%d %d\n", lnum, colnum);
> if (clang_isPreprocessing(cursor.kind))
> printf("Preprocessor\n");
> else {
> def = clang_getCursorDefinition(cursor);
> if (clang_Cursor_isNull(def))
> type = clang_getCursorType(cursor);
> else
> type = clang_getCursorType(def);
> typesp = clang_getTypeSpelling(type);
> types = clang_getCString(typesp);
> printf("%s\n", types);
> clang_disposeString(typesp);
> }
> clang_disposeTranslationUnit(tu);
> clang_disposeIndex(index);
> }
I don't want to generate ast file for source file before program starts. I
can use clang_createTranslationUnitFromSourceFile() and
clang_reparseTranslationUnit instead of clang_createTranslationUnit(). But
problem is TranslationUnits which I will get with this functions is some
kind of wrong. So I can't get appropriate Cursor for 7, 10 (line, column)
position when force program process its own source code.
When I apply program to itself source code with 16 (line) and 3 (column)
parameters which correspond
> index = clang_createIndex(0, 0);
> // ^
it displays 6 (line) and 1 (column) which corresponds
> int main(int argc, char *argv[])
> {
> ^
It's wrong. But when apply 29 3 which correspond
> printf("%d %d\n", lnum, colnum);
> //^
It displays 28 1 and it's right. Why Cursor is made wrong in first case and
how to make it right? Does some way exists to create right TranslationUnit
for source code without using clang -emit-ast?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/cfe-users/attachments/20190408/54078e85/attachment.html>
More information about the cfe-users
mailing list