[cfe-dev] How to lookup a name from a specific expression's location?

Nicolás Alvarez via cfe-dev cfe-dev at lists.llvm.org
Sun Oct 4 00:31:21 PDT 2020

> El 3 oct. 2020, a la(s) 22:06, Oleksandr Koval via cfe-dev <cfe-dev at lists.llvm.org> escribió:
> Hi, I'm writing a check that detects and removes redundant `this->` usage. Finding explicit `this->` was simple, now I want to check whether it's safe to remove it. My main concern is such case:
> struct X{
>     void f(int x){
>         // without `this->` will use parameter
>         this->x++;
>         // can remove `this->` because
>         // local `y` is not visible yet
>         this->y++;
>         y++;
>         int y;
>         y++;
>     }
>     int x;
>     int y;
> };
> I need to know whether a specific name(function or variable) will resolve to the same declaration without `this->` part. My matcher is memberExpr(has(cxxThisExpr())), I bind  MemberExpr and CXXThisExpr, I can rewrite matcher to also bind enclosing CXXMethodDecl. As I understand, simple enumeration of parameter/local variable names won't work(as in case with `y`) because of lookup/visibility rules. Is there some `lookup()` function whose result I can compare against the declaration of original function/variable? I found Sema::LookupName() but can't figure out how to get Scope of the found expression. Can you give me an example please?

Removing this-> from this->y is safe in the sense that the code will still work, because the local y isn't visible yet, but it would be very confusing and error prone for the human reading it. It would subtly break if someone moves the local y declaration higher for example.

So maybe you should consider *not* suggesting the removal of this-> in a situation like this (when there is a local var with the same name but it's not yet visible) due to code readability, even if it's technically safe to remove it.

And as a bonus, it becomes easier to implement :)

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/cfe-dev/attachments/20201004/6caa2929/attachment-0001.html>

More information about the cfe-dev mailing list