[cfe-dev] How to lookup a name from a specific expression's location?
Vassil Vassilev via cfe-dev
cfe-dev at lists.llvm.org
Sun Oct 4 00:15:25 PDT 2020
On 10/3/20 3:40 PM, Oleksandr Koval via cfe-dev wrote:
> 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?
The Scope is a parser thing which contains an opaque ptr to the
DeclContext. In principle, you can create a fake Scope and attach the
relevant DeclContext via setEntity. I think just passing Sema::TUScope
may work. If you want some pseudocode:
Scope *fakeS = new Scope(...);
fakeS->setEntity(DC);
// you may need to do some work for the variable shadowing
LookupResult R(Sema, Var->getName(), SourceLocation(),
Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Sema->LookupName(R, fakeS);
delete fakeS;
Note that is an approximation as we do not attach the scope to the
chain of scopes like the parser does. It some extra work that is also
possible.
>
> --
> Regards,
> Oleksandr Koval.
>
> _______________________________________________
> cfe-dev mailing list
> cfe-dev at lists.llvm.org
> https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-dev
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/cfe-dev/attachments/20201004/e9d63e5c/attachment.html>
More information about the cfe-dev
mailing list