How to get source location of #includes using clang libtooling?

元气小坏坏 提交于 2019-12-24 06:29:47

问题


Is there any way to get clang::SourceLocation for every #include in file by its clang::FileID or clang::FileEntry or something?


回答1:


What about using source manager's GetIncludedLoc function which takes fileid as parameter.

SourceManager.GetIncludedLoc(fileid)




回答2:


Thank's @Hemant for your answer, you're right

I Already found that by myself (in clang 3.8 it is called getIncludeLoc) but forgot to write here. I used this to find the location after all #includes where i can put my own. Here's the function (For sure not the best way) I wrote for this, hope it helps someone

SourceLocation getIncludeLocation(FileID fileID, SourceManager &sm, unsigned carriages) {
       return SourceLocation();
     set<unsigned> lines;
    if (fileID.isInvalid())
    for (auto it = sm.fileinfo_begin(); it != sm.fileinfo_end(); it++) {
        SourceLocation includeLoc = sm.getIncludeLoc(sm.translateFile(it->first));
        if (includeLoc.isValid() && sm.isInFileID(includeLoc, fileID)) {
            lines.insert(sm.getSpellingLineNumber(includeLoc));
        }
    }
    unsigned pos(0);
    if (!lines.empty()) {
        bool first = true;
        for (unsigned line :lines) {
            if (first)
                first = false;
            else if ((line - pos) > carriages)
                break;
            pos = line;
            //cout << "Include line:" << pos << endl;
        }
        //cout << console_hline('-') << endl;
    }
    cout << sm.getFileEntryForID(fileID)->getName() << endl;
    return sm.translateFileLineCol(sm.getFileEntryForID(fileID), ++pos, 1);
}

Also some information about includes can be get by

Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc, StringRef &Buffer)

and

Lexer::ComputePreamble(StringRef Buffer, const LangOptions &LangOpts, unsigned MaxLines = 0)    


来源:https://stackoverflow.com/questions/43448448/how-to-get-source-location-of-includes-using-clang-libtooling

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!