[cfe-dev] How to rewrite a header file?

Marcel Schaible via cfe-dev cfe-dev at lists.llvm.org
Thu Sep 7 06:03:12 PDT 2017


Hi Miklos,

thanks for your hint. What do you mean by "Rewriting in header files
happens out of the box..."?

When I rewrite with my tools some definition in a header file I'll get
an error message from the rewriter:

<<<INVALID SOURCE LOCATION >>>


My code snippet looks something like this:


    bool TransformFunctionReturnTypeDef(FunctionDecl *funcdecl)
    {
        if (funcdecl->getPreviousDecl())
        {
            TypeSourceInfo *TI = funcdecl->getTypeSourceInfo();
            TypeLoc TL = TI->getTypeLoc();
            FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();

            clang::SourceLocation l1 = FTL.getLParenLoc();
            clang::SourceLocation l2 = FTL.getRParenLoc();

            int offset = Lexer::MeasureTokenLength(l1,
                TheRewriter.getSourceMgr(),
                TheRewriter.getLangOpts());

            int offset2 = Lexer::MeasureTokenLength(l2,
                TheRewriter.getSourceMgr(),
                TheRewriter.getLangOpts());

            SourceLocation END1 = l1.getLocWithOffset(offset);
            SourceLocation END2 = l2.getLocWithOffset(offset2 - 1);
            SourceRange range(END1, END2);
            std::stringstream SSBefore;

            if (auto typ =
dyn_cast_or_null<PointerType>(funcdecl->getReturnType().getTypePtr())) {
                SSBefore << ", " <<
funcdecl->getReturnType().getAsString() << " new_param";
            }
            else {
                SSBefore << ", " <<
funcdecl->getReturnType().getAsString() << " *new_param";
            }

            TheRewriter.ReplaceText(range, SSBefore.str());
        }

        return true;
    }

Marcel




Am 07.09.2017 um 14:28 schrieb Miklos Vajna:
> Hi,
>
> On Wed, Sep 06, 2017 at 08:01:30PM +0200, Marcel Schaible via cfe-dev <cfe-dev at lists.llvm.org> wrote:
>> my tool changes the signatures of some annotated C functions in .c files.
>>
>> Now I am facing the problem that I have to propaged this changes into
>> the corresponding
>>
>> header file.
>>
>> How can I do this? Can I use something like ASTConsumer/RecursiveAstVisitor?
>>
>> Any hint and/or idea is welcome. Is there some example code available?
> Look at clang-tools-extra for examples. Rewriting in header files
> happens out of the box, but if you want to check if your location is in
> the "main" file or in a header file, you can use the source manager's
> isInMainFile() for that purpose. See e.g.
> tools/clang/tools/extra/clang-tidy/google/GlobalNamesInHeadersCheck.cpp:55
> for a place where that happens.
>
> Regards,
>
> Miklos

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/cfe-dev/attachments/20170907/0b2f47ba/attachment.html>


More information about the cfe-dev mailing list