[cfe-dev] clang-tidy: Tool for removing "this->" from source code?

Wilhelm wilhelm.meier at fh-kl.de
Mon Jun 8 21:27:02 PDT 2015


Hi Kevin,

be aware that there are cases in derived from template classes (eg.
CRTP) where you can't remove "this" because it points to a depended name ...

Wilhelm

Am 08.06.2015 um 13:54 schrieb Kevin Funk:
> Heya,
> 
>  
> 
> for familiarizing myself with writing custom tools for LibTooling I
> attempted to write a tool for removing (unnecessary) "this->" usage from
> source code.
> 
>  
> 
> Examples:
> 
>  
> 
> void inc() {
> 
> this->counter++; // becomes: counter++;
> 
> }
> 
>  
> 
> Now there are a few cases where this would leave to different behaviour
> when just simply replacing "this->" by "" in source code, which is what
> I'd like to avoid:
> 
>  
> 
> Example:
> 
>  
> 
> void foo(bool b) {
> 
> this->b = b; // would become: b = b; => self-assignment, BUG
> 
> }
> 
>  
> 
> void bar() {
> 
> int num = this->num(); // would become: int num = num(); => compile-error
> 
> }
> 
>  
> 
> So, in other words, for a given expression like `this->$myid` to be
> replacable by just `$myid`, the name $myid must not be ambiguous from
> the context of the expression. (There might be other exceptions, but I'm
> just assuming this as my rule for now). In all other cases, I'd like to
> replace "this->" by "" in source code.
> 
>  
> 
> Now to the actual question: How to implement this via a clang-tidy tool?
> 
>  
> 
> Writing a AST matcher for getting to the expressions referencing `this`
> is trivial -- something like this:
> 
>  
> 
> memberExpr(hasDescendant(thisExpr().bind("this"))).bind("member")
> 
>  
> 
> Now the part I'm struggling with is how to make sure the "member name"
> is a non-ambiguous identifier from the current context so I can just
> strip "this->". How can I find out the accessible declarations (or just
> the ids) from the context of the expression referencing `this`? I'm
> missing API to get the clang::DeclContext, plus looking up declarations
> accessible from within this context.
> 
>  
> 
> Any ideas?
> 
>  
> 
> Any help appreciated,
> 
> Thanks!
> 
>  
> 
> -- 
> 
> Kevin Funk | kevin.funk at kdab.com | Software Engineer
> 
> KDAB (Deutschland) GmbH&Co KG, a KDAB Group company
> 
> Tel. Germany +49-30-521325470, Sweden (HQ) +46-563-540090
> 
> KDAB - Qt Experts - Platform-independent software solutions
> 
> 
> 
> _______________________________________________
> cfe-dev mailing list
> cfe-dev at cs.uiuc.edu
> http://lists.cs.uiuc.edu/mailman/listinfo/cfe-dev
> 


-- 
Wilhelm



More information about the cfe-dev mailing list