[clang-tools-extra] [clangd] Drop attributes from definitions generated by DefineOutline (PR #242635)
via cfe-commits
cfe-commits at lists.llvm.org
Sat Nov 14 04:44:50 PST 2026
llvmorg-github-actions[bot] wrote:
<!--LLVM PR SUMMARY COMMENT-->
@llvm/pr-subscribers-clang-tools-extra
Author: Max Winkler (max-winkler)
<details>
<summary>Changes</summary>
When DefineOutline moves a function body out of line, it no longer copies the attributes to the generated definition. They stay on the declaration, where the definition inherits them from.
Example: Applied to
```
struct A { [[nodiscard]] int foo() { return 0; } };
```
Before:
```
struct A { [[nodiscard]] int foo(); };
[[nodiscard]] int A::foo() { return 0; }
```
Now:
```
struct A { [[nodiscard]] int foo(); };
int A::foo() { return 0; }
```
This applies to known attributes in C++11/C23 syntax (`[[...]]`), GNU syntax (`__attribute__`) and declspec syntax (`__declspec(...)`). Attributes unknown to clang and attributes coming from macros are not removed.
Various tests (mixed attribute syntaxes, attribute lists, attributes with arguments) are added. Existing ctor with attribute test is updated accordingly.
Assisted-by: Claude (explanations, code review, test ideas)
Fixes: clangd/clangd#<!-- -->1607
---
Full diff: https://github.com/llvm/llvm-project/pull/242635.diff
3 Files Affected:
- (modified) clang-tools-extra/clangd/refactor/tweaks/DefineOutline.cpp (+120-23)
- (modified) clang-tools-extra/clangd/unittests/tweaks/DefineOutlineTests.cpp (+151-1)
- (modified) clang-tools-extra/docs/ReleaseNotes.md (+4)
``````````diff
diff --git a/clang-tools-extra/clangd/refactor/tweaks/DefineOutline.cpp b/clang-tools-extra/clangd/refactor/tweaks/DefineOutline.cpp
index dcc417b5f7d8c2..94150a08c239eb 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/DefineOutline.cpp
+++ b/clang-tools-extra/clangd/refactor/tweaks/DefineOutline.cpp
@@ -23,19 +23,22 @@
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DeclTemplate.h"
#include "clang/AST/Stmt.h"
+#include "clang/Basic/AttributeCommonInfo.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/TokenKinds.h"
#include "clang/Tooling/Core/Replacement.h"
#include "clang/Tooling/Syntax/Tokens.h"
#include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/Error.h"
+#include "llvm/Support/raw_ostream.h"
#include <cstddef>
+#include <iterator>
#include <optional>
#include <string>
-#include <tuple>
namespace clang {
namespace clangd {
@@ -216,12 +219,32 @@ deleteTokensWithKind(const syntax::TokenBuffer &TokBuf, tok::TokenKind Kind,
return DelKeywordCleanups;
}
+// Helper function to skip over a matching pair of tokens (e.g., parentheses
+// or braces). Returns an iterator to the matching closing token, or the end
+// iterator if no matching pair is found.
+template <typename Iterator>
+Iterator skipTokenPair(Iterator Begin, Iterator End, tok::TokenKind StartKind,
+ tok::TokenKind EndKind) {
+ int Count = 0;
+ for (auto It = Begin; It != End; ++It) {
+ if (It->kind() == StartKind) {
+ ++Count;
+ } else if (It->kind() == EndKind) {
+ if (--Count == 0)
+ return It;
+ if (Count < 0)
+ // We encountered a closing token without a matching opening token.
+ return End;
+ }
+ }
+ return End;
+}
+
// Creates a modified version of function definition that can be inserted at a
// different location, qualifies return value and function name to achieve that.
// Contains function signature, except defaulted parameter arguments, body and
// template parameters if applicable. No need to qualify parameters, as they are
// looked up in the context containing the function/method.
-// FIXME: Drop attributes in function signature.
llvm::Expected<std::string>
getFunctionSourceCode(const FunctionDecl *FD, const DeclContext *TargetContext,
const syntax::TokenBuffer &TokBuf,
@@ -366,6 +389,101 @@ getFunctionSourceCode(const FunctionDecl *FD, const DeclContext *TargetContext,
DelKeyword(tok::kw_explicit, {FD->getBeginLoc(), FD->getLocation()});
}
+ // Drop attributes that the out-of-line definition inherits from the
+ // declaration. Ones we can't safely locate are left alone.
+ // FIXME: Attributes coing from macros and attributes unknown to clang (which
+ // are not part of the AST) are not dropped.
+ for (Attr *A : FD->attrs()) {
+ if (A->isImplicit() || A->isInherited())
+ continue;
+
+ // Get the delimiter for the attribute type
+ llvm::SmallVector<tok::TokenKind> LeftDelimiter, RightDelimiter;
+ switch (A->getSyntax()) {
+ case AttributeCommonInfo::AS_GNU:
+ // Delimited by __attribute__(( and ))
+ LeftDelimiter.assign({tok::kw___attribute, tok::l_paren, tok::l_paren});
+ RightDelimiter.assign({tok::r_paren, tok::r_paren});
+ break;
+ case AttributeCommonInfo::AS_CXX11:
+ case AttributeCommonInfo::AS_C23:
+ // Delimited by [[ and ]]
+ LeftDelimiter.assign({tok::l_square, tok::l_square});
+ RightDelimiter.assign({tok::r_square, tok::r_square});
+ break;
+ case AttributeCommonInfo::AS_Declspec:
+ // Delimited by __declspec( and )
+ LeftDelimiter.assign({tok::kw___declspec, tok::l_paren});
+ RightDelimiter.assign({tok::r_paren});
+ break;
+ default:
+ // All other syntaxes are not relevant here
+ break;
+ }
+
+ if (LeftDelimiter.empty() || RightDelimiter.empty())
+ continue;
+
+ auto FDTokens = TokBuf.spelledForExpanded(TokBuf.expandedTokens(
+ {FD->getBeginLoc(), FD->getBody()->getBeginLoc()}));
+ auto AttrTokens =
+ TokBuf.spelledForExpanded(TokBuf.expandedTokens(A->getRange()));
+
+ if (!FDTokens.has_value() || !AttrTokens.has_value() ||
+ !SM.isPointWithin(A->getLocation(), FDTokens->front().location(),
+ FDTokens->back().location()))
+ continue;
+
+ CharSourceRange DelRange;
+
+ // Find position of the right delimiter
+ for (auto It = AttrTokens->end(), E = FDTokens->end(); It != E; ++It) {
+
+ // There might be a further attribute with argument delimited by parens
+ // in the attribute list. The closing paren might be recognized as part
+ // of the attribute delimiter. So skip tokens until the closing paren.
+ if (It->kind() == tok::l_paren) {
+ It = skipTokenPair(It, E, tok::l_paren, tok::r_paren);
+ if (It != E)
+ continue;
+ }
+
+ if (std::distance(It, E) < static_cast<long>(RightDelimiter.size()))
+ // No chance to find the right delimiter. Give up.
+ break;
+
+ llvm::ArrayRef<syntax::Token> Candidate(It, RightDelimiter.size());
+
+ if (llvm::equal(Candidate, RightDelimiter, [](auto Tok, auto TokKindDel) {
+ return Tok.kind() == TokKindDel;
+ })) {
+ DelRange.setEnd(Candidate.end()->location());
+ break;
+ }
+ }
+
+ // Find position of the left delimitter
+ for (auto It = AttrTokens->begin(), E = FDTokens->begin(); It != E; --It) {
+ if (std::distance(E, It) < static_cast<long>(LeftDelimiter.size()))
+ break;
+
+ llvm::ArrayRef<syntax::Token> Candidate(
+ std::prev(It, LeftDelimiter.size()), LeftDelimiter.size());
+
+ if (llvm::equal(Candidate, LeftDelimiter, [](auto Tok, auto TokKindDel) {
+ return Tok.kind() == TokKindDel;
+ })) {
+ DelRange.setBegin(Candidate.front().location());
+ break;
+ }
+ }
+
+ if (DelRange.isValid())
+ if (auto Err =
+ DeclarationCleanups.add(tooling::Replacement(SM, DelRange, "")))
+ Errors = llvm::joinErrors(std::move(Errors), std::move(Err));
+ }
+
if (Errors)
return std::move(Errors);
return getFunctionSourceAfterReplacements(FD, DeclarationCleanups,
@@ -737,27 +855,6 @@ class DefineOutline : public Tweak {
return {};
}
- // Helper function to skip over a matching pair of tokens (e.g., parentheses
- // or braces). Returns an iterator to the matching closing token, or the end
- // iterator if no matching pair is found.
- template <typename Iterator>
- Iterator skipTokenPair(Iterator Begin, Iterator End, tok::TokenKind StartKind,
- tok::TokenKind EndKind) {
- int Count = 0;
- for (auto It = Begin; It != End; ++It) {
- if (It->kind() == StartKind) {
- ++Count;
- } else if (It->kind() == EndKind) {
- if (--Count == 0)
- return It;
- if (Count < 0)
- // We encountered a closing token without a matching opening token.
- return End;
- }
- }
- return End;
- }
-
// We don't know the actual start or end of the definition, only the position
// of the name. Therefore, we heuristically try to locate the last token
// before or in this function, respectively. Adapt as required by user code.
diff --git a/clang-tools-extra/clangd/unittests/tweaks/DefineOutlineTests.cpp b/clang-tools-extra/clangd/unittests/tweaks/DefineOutlineTests.cpp
index 284e0cebe788cd..1bff12e285873e 100644
--- a/clang-tools-extra/clangd/unittests/tweaks/DefineOutlineTests.cpp
+++ b/clang-tools-extra/clangd/unittests/tweaks/DefineOutlineTests.cpp
@@ -247,7 +247,7 @@ TEST_F(DefineOutlineTest, ApplyTest) {
Foo(T z) __attribute__((weak)) ;
int bar;
};template <typename T>
-inline Foo<T>::Foo(T z) __attribute__((weak)) : bar(2){}
+inline Foo<T>::Foo(T z) : bar(2){}
)cpp",
""},
// Default ctor
@@ -452,6 +452,124 @@ template <typename U, bool>
inline T Foo<T>::bar(const T& t, const U& u) { return {}; }
)cpp",
""},
+ // C++11 attribute list
+ {
+ R"cpp(
+ struct A {
+ [ [nodiscard, deprecated("no")] ] int ^foo() { return 0; }
+ };
+)cpp",
+ R"cpp(
+ struct A {
+ [ [nodiscard, deprecated("no")] ] int foo() ;
+ };
+)cpp",
+ "int A::foo() { return 0; }\n"},
+ // GNU attribute list
+ {
+ R"cpp(
+ struct A {
+ __attribute__((noinline, annotate("bar"))) int ^foo() { return 0; }
+ };
+)cpp",
+ R"cpp(
+ struct A {
+ __attribute__((noinline, annotate("bar"))) int foo() ;
+ };
+)cpp",
+ "int A::foo() { return 0; }\n"},
+ // Attribute at the end of the function declarator
+ {
+ R"cpp(
+ struct A {
+ int ^foo() __attribute__((noinline)) { return 0; }
+ };
+)cpp",
+ R"cpp(
+ struct A {
+ int foo() __attribute__((noinline)) ;
+ };
+)cpp",
+ "int A::foo() { return 0; }\n"},
+ // Mixed attributes
+ {
+ R"cpp(
+ struct A {
+ __attribute__((noinline)) [ [nodiscard] ] int ^foo() { return 0; }
+ };
+)cpp",
+ R"cpp(
+ struct A {
+ __attribute__((noinline)) [ [nodiscard] ] int foo() ;
+ };
+)cpp",
+ "int A::foo() { return 0; }\n"},
+ // Attributes with namespaces
+ {
+ R"cpp(
+ struct A {
+ [ [clang::noinline] ] int ^foo() { return 0; }
+ };
+)cpp",
+ R"cpp(
+ struct A {
+ [ [clang::noinline] ] int foo() ;
+ };
+)cpp",
+ "int A::foo() { return 0; }\n"},
+ {
+ R"cpp(
+ struct A {
+ [ [using clang: noinline, annotate("x")] ] int ^foo() { return 0; }
+ };
+)cpp",
+ R"cpp(
+ struct A {
+ [ [using clang: noinline, annotate("x")] ] int foo() ;
+ };
+)cpp",
+ "int A::foo() { return 0; }\n"},
+ // Unknown attributes (not part of the AST, so they are not removed)
+ {
+ R"cpp(
+ struct A {
+ [ [unknown] ] int ^foo() { return 0; }
+ };
+)cpp",
+ R"cpp(
+ struct A {
+ [ [unknown] ] int foo() ;
+ };
+)cpp",
+ "[ [unknown] ] int A::foo() { return 0; }\n"},
+ // Unknown and known attribute in one list
+ {
+ R"cpp(
+ struct A {
+ [ [unknown, nodiscard] ] int ^foo() { return 0; }
+ };
+)cpp",
+ R"cpp(
+ struct A {
+ [ [unknown, nodiscard] ] int foo() ;
+ };
+)cpp",
+ "int A::foo() { return 0; }\n"},
+ // Attribute defined as macro
+ {
+ R"cpp(
+ #define NOINLINE __attribute__((noinline))
+ struct A {
+ NOINLINE int ^foo() { return 0; }
+ };
+)cpp",
+ R"cpp(
+ #define NOINLINE __attribute__((noinline))
+ struct A {
+ NOINLINE int foo() ;
+ };
+)cpp",
+ "NOINLINE int A::foo() { return 0; }\n"},
};
for (const auto &Case : Cases) {
SCOPED_TRACE(Case.Test);
@@ -466,6 +584,38 @@ inline T Foo<T>::bar(const T& t, const U& u) { return {}; }
}
}
+TEST_F(DefineOutlineTest, DeclspecAttributes) {
+ FileName = "Test.hpp";
+ ExtraFiles["Test.cpp"] = "";
+ ExtraArgs.push_back("-fdeclspec");
+
+ struct {
+ llvm::StringRef Test;
+ llvm::StringRef ExpectedHeader;
+ llvm::StringRef ExpectedSource;
+ } Cases[] = {
+ {
+ R"cpp(
+ struct A {
+ __declspec(noinline) int ^foo() { return 0; }
+ };
+)cpp",
+ R"cpp(
+ struct A {
+ __declspec(noinline) int foo() ;
+ };
+)cpp",
+ "int A::foo() { return 0; }\n"},
+ };
+ llvm::StringMap<std::string> EditedFiles;
+ for (auto &Case : Cases) {
+ apply(Case.Test, &EditedFiles);
+ EXPECT_EQ(apply(Case.Test, &EditedFiles), Case.ExpectedHeader);
+ EXPECT_THAT(EditedFiles, testing::ElementsAre(FileWithContents(
+ testPath("Test.cpp"), Case.ExpectedSource)));
+ }
+}
+
TEST_F(DefineOutlineTest, InCppFile) {
FileName = "Test.cpp";
struct {
diff --git a/clang-tools-extra/docs/ReleaseNotes.md b/clang-tools-extra/docs/ReleaseNotes.md
index b6774370511feb..0d070338a48683 100644
--- a/clang-tools-extra/docs/ReleaseNotes.md
+++ b/clang-tools-extra/docs/ReleaseNotes.md
@@ -102,6 +102,10 @@ infrastructure are described first, followed by tool-specific sections.
value when possible, and otherwise via a pointer parameter, since C has
no references.
+- The `Define outline` tweak now longer copies attributes (`[[...]]`,
+ `__attribute__((...))` and `__declspec(...)`) from the declaration to the
+ generated out-of-line definition.
+
#### Signature help
- Parameters declared with a `decltype` are now displayed as the type the
``````````
</details>
https://github.com/llvm/llvm-project/pull/242635
More information about the cfe-commits
mailing list