[cfe-dev] Modification of a StringLiteral (SemaConsumer - RecursiveASTVisitor - TreeTransform)

Richard Smith richard at metafoo.co.uk
Thu May 29 20:00:59 PDT 2014


On Tue, May 27, 2014 at 8:44 AM, Timothée Vandeput <
timothee.vandeput at gmail.com> wrote:

> Hello,
>
> We are currently working on a clang plugin to check some StringLiteral
> (In-class initializer of field).
> So far we are able to find the fields, analyze the strings and make the
> replacement in the source file when needed with :
>
> PluginASTAction::CreateASTConsumer => SemaConsumer::HandleTopLevelDecl =>
> RecursiveASTVisitor::TraverseFieldDecl => Rewriter::ReplaceText
>
> What we would like now, is to make the change 'online'. So when we compile
> our sources, apply the modification in the source file but also in the AST
> (to avoid a second compilation step).
>
> We tried the StringLiteral::setString method to change the string, but it
> partially worked. The string gets changed but the size of the const char []
> doesn't, which result in the string being truncated.
>
> Here is the ouput of the dump before and after the setString :
>
> CXXConstructExpr 0xb8eec90 'class Toto' 'void (const char *, double)'
> |-ImplicitCastExpr 0xb8eec80 'const char *' <ArrayToPointerDecay>
>
> *| `-StringLiteral 0xb8eec14 'const char [2]' lvalue "-"*`-FloatingLiteral
> 0xb8eec38 'double' 4.250000e+01
>
> CXXConstructExpr 0xb8eec90 'class Toto' 'void (const char *, double)'
> |-ImplicitCastExpr 0xb8eec80 'const char *' <ArrayToPointerDecay>
>
> *| `-StringLiteral 0xb8eec14 'const char [2]' lvalue "modified"*`-FloatingLiteral
> 0xb8eec38 'double' 4.250000e+01
>
> We also tried to use the TreeTransform class by implementing the
> TransformStringLiteral method and invoking the
> TreeTransform::TransformInitializer method.
> The result was the same, it seems the node doesn't get rebuild.
>
> Are we missing something obvious? Any suggestion of how we could replace
> that string in the AST?
>

The AST is neither designed nor intended to support in-place modification
-- it's supposed to be essentially immutable once created. TreeTransform is
a better approach (since it creates new AST rather than updating existing
AST nodes in-place).

In your overridden TransformStringLiteral, how are you creating the new
StringLiteral? We don't seem to have any relevant functions on Sema for
this, so I think you'd need to compute the relevant type yourself and call
StringLiteral::Create.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/cfe-dev/attachments/20140529/b387d185/attachment.html>


More information about the cfe-dev mailing list