llvm-project icon indicating copy to clipboard operation
llvm-project copied to clipboard

[Clang] Accepts invalid lambda init-capture shadowing a template parameter

Open MagentaTreehouse opened this issue 1 year ago • 4 comments

In the following code, the init-capture of the lambda has the same name as the NTTP i, which should not be allowed.

template <int i>
int f() {
    return [i = 0] { return i; }();
}

int i = f<0>();

This is diagnosed by GCC and EDG.

See https://compiler-explorer.com/z/oh7MhabG9.

MagentaTreehouse avatar Feb 09 '25 00:02 MagentaTreehouse

@llvm/issue-subscribers-clang-frontend

Author: None (MagentaTreehouse)

In the following code, the init-capture of the lambda has the same name as the NTTP `i`, which should not be allowed. ```c++ template <int i> int f() { return [i = 0] { return i; }(); }

int i = f<0>();


This is diagnosed by GCC and EDG.

See https://compiler-explorer.com/z/oh7MhabG9.
</details>

llvmbot avatar Feb 09 '25 01:02 llvmbot

I don't quite understand the difference as to why https://compiler-explorer.com/z/xfhcvdErj is not diagnosed by GCC.

zyn0217 avatar Feb 16 '25 13:02 zyn0217

I don't quite understand the difference as to why https://compiler-explorer.com/z/xfhcvdErj is not diagnosed by GCC.

There is a specific rule that disallows hiding a template parameter.

zygoloid avatar Feb 16 '25 18:02 zygoloid

I remembered doing something similar for https://github.com/llvm/llvm-project/commit/0fb84bc7fdec1c20c2461e54d5c994939fe5b47f . I went to ActOnStartOfLambdaDefinition where other related diagnostics happen and put there

@@ -1475,6 +1475,21 @@ void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
     ValueDecl *Var = C.getVariable();
     if (Var && Var->isInitCapture()) {
       PushOnScopeChains(Var, CurScope, false);
+      LookupResult R(*this, Var->getIdentifier(), Var->getLocation(),
+                     LookupOrdinaryName,
+                     RedeclarationKind::ForVisibleRedeclaration);
+      LookupName(R, CurScope);
+      // auto *PrevDecl = LookupSingleName(
+      //     CurScope, Var->getIdentifier(), Var->getLocation(),
+      //     Sema::LookupOrdinaryName, RedeclarationKind::ForVisibleRedeclaration);
+      NamedDecl *PrevDecl = nullptr;
+      if (!R.empty()) {
+        PrevDecl = *R.begin();
+        if (PrevDecl)
+          PrevDecl->dump();
+      }
+      if (PrevDecl && PrevDecl->isTemplateParameter())
+        DiagnoseTemplateParameterShadow(Var->getLocation(), PrevDecl);
     }
   }

I know this is not entirely correct in terms of checking lookup result. But it never finds template parameter. I wonder what I'm doing wrong.

Fznamznon avatar Feb 17 '25 15:02 Fznamznon