[PATCH] D152195: [Clang] Fix access of friend function in local class

Elizabeth Andrews via Phabricator via cfe-commits cfe-commits at lists.llvm.org
Mon Jun 5 13:31:42 PDT 2023


eandrews created this revision.
eandrews added reviewers: erichkeane, aaron.ballman.
Herald added a project: All.
eandrews requested review of this revision.

Clang currently emits an error when a friend of a local class tries to access it's private data members. This patch fixes the bug.


https://reviews.llvm.org/D152195

Files:
  clang/lib/Sema/SemaDecl.cpp
  clang/test/Sema/local-class-friend.cpp


Index: clang/test/Sema/local-class-friend.cpp
===================================================================
--- /dev/null
+++ clang/test/Sema/local-class-friend.cpp
@@ -0,0 +1,17 @@
+// RUN: %clang_cc1 -verify -fsyntax-only %s
+// expected-no-diagnostics
+
+void foo()
+{ class c1 {
+    private:
+      int testVar;
+    public:
+      friend class c2;
+  };
+
+  class c2 {
+    void f(c1 obj) {
+      int a = obj.testVar; // Ok
+    }
+  };
+}
Index: clang/lib/Sema/SemaDecl.cpp
===================================================================
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -17065,11 +17065,14 @@
       S = getTagInjectionScope(S, getLangOpts());
     } else {
       assert(TUK == TUK_Friend);
+      CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(SearchDC);
+
       // C++ [namespace.memdef]p3:
       //   If a friend declaration in a non-local class first declares a
       //   class or function, the friend class or function is a member of
       //   the innermost enclosing namespace.
-      SearchDC = SearchDC->getEnclosingNamespaceContext();
+      SearchDC = RD->isLocalClass() ? RD->isLocalClass()
+                                    : SearchDC->getEnclosingNamespaceContext();
     }
 
     // In C++, we need to do a redeclaration lookup to properly


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D152195.528556.patch
Type: text/x-patch
Size: 1315 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/cfe-commits/attachments/20230605/ee8cff27/attachment.bin>


More information about the cfe-commits mailing list