Skip to content

Conversation

@Samhitha1212
Copy link

@Samhitha1212 Samhitha1212 commented Nov 7, 2025

Summary

Fixes incorrect source range for default/delete function definations outside struct/class.

Description

Previously, function and constructor definitions written outside the class body using '= delete' or '= default' had incorrect SourceRange end locations in the AST. This patch updates Parser.cpp to record the end location of the keyword token and apply it after Sema finalization.

fixes issue: #64805

Includes new tests under clang/test/Parser/deleted_defaulted_func_range.cpp

@github-actions
Copy link

github-actions bot commented Nov 7, 2025

Thank you for submitting a Pull Request (PR) to the LLVM Project!

This PR will be automatically labeled and the relevant teams will be notified.

If you wish to, you can add reviewers by using the "Reviewers" section on this page.

If this is not working for you, it is probably because you do not have write permissions for the repository. In which case you can instead tag reviewers by name in a comment by using @ followed by their GitHub username.

If you have received no comments on your PR for a week, you can request a review by "ping"ing the PR by adding a comment “Ping”. The common courtesy "ping" rate is once a week. Please remember that you are asking for valuable time from other developers.

If you have further questions, they may be answered by the LLVM GitHub User Guide.

You can also ask questions in a comment on this PR, on the LLVM Discord or on the forums.

@llvmbot llvmbot added clang Clang issues not falling into any other category clang:frontend Language frontend issues, e.g. anything involving "Sema" labels Nov 7, 2025
@llvmbot
Copy link
Member

llvmbot commented Nov 7, 2025

@llvm/pr-subscribers-clang

Author: None (Samhitha1212)

Changes

Summary

Fixes incorrect source range for default/delete function definations outside struct/class.

Description

Previously, function and constructor definitions written outside the class body using '= delete' or '= default' had incorrect SourceRange end locations in the AST. This patch updates Parser.cpp to record the end location of the keyword token and apply it after Sema finalization.

Includes new tests under clang/test/Parser/deleted_defaulted_func_range.cpp


Full diff: https://github.com/llvm/llvm-project/pull/167007.diff

2 Files Affected:

  • (modified) clang/lib/Parse/Parser.cpp (+26-1)
  • (added) clang/test/Parser/deleted_defaulted_func_range.cpp (+28)
diff --git a/clang/lib/Parse/Parser.cpp b/clang/lib/Parse/Parser.cpp
index a6fc676f23a51..7d68821b71b8d 100644
--- a/clang/lib/Parse/Parser.cpp
+++ b/clang/lib/Parse/Parser.cpp
@@ -26,6 +26,7 @@
 #include "llvm/ADT/STLForwardCompat.h"
 #include "llvm/Support/Path.h"
 #include "llvm/Support/TimeProfiler.h"
+#include "clang/Lex/Lexer.h"
 using namespace clang;
 
 
@@ -1331,6 +1332,7 @@ Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D,
   StringLiteral *DeletedMessage = nullptr;
   Sema::FnBodyKind BodyKind = Sema::FnBodyKind::Other;
   SourceLocation KWLoc;
+  SourceLocation FuncRangeEnd;
   if (TryConsumeToken(tok::equal)) {
     assert(getLangOpts().CPlusPlus && "Only C++ function definitions have '='");
 
@@ -1341,12 +1343,15 @@ Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D,
           << 1 /* deleted */;
       BodyKind = Sema::FnBodyKind::Delete;
       DeletedMessage = ParseCXXDeletedFunctionMessage();
+      FuncRangeEnd = clang::Lexer::getLocForEndOfToken(KWLoc, 0, PP.getSourceManager(), getLangOpts()).getLocWithOffset(-1);
+
     } else if (TryConsumeToken(tok::kw_default, KWLoc)) {
       Diag(KWLoc, getLangOpts().CPlusPlus11
                       ? diag::warn_cxx98_compat_defaulted_deleted_function
                       : diag::ext_defaulted_deleted_function)
           << 0 /* defaulted */;
       BodyKind = Sema::FnBodyKind::Default;
+      FuncRangeEnd = clang::Lexer::getLocForEndOfToken(KWLoc, 0, PP.getSourceManager(), getLangOpts()).getLocWithOffset(-1);
     } else {
       llvm_unreachable("function definition after = not 'delete' or 'default'");
     }
@@ -1374,6 +1379,18 @@ Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D,
                                                   : MultiTemplateParamsArg(),
                                               &SkipBody, BodyKind);
 
+  auto updateFuncRangeEnd = [&](Decl *D) {
+    if (!FuncRangeEnd.isValid() || !D)
+      return;
+    if (auto *FD = dyn_cast<FunctionDecl>(D)) {
+      FD->setRangeEnd(FuncRangeEnd);
+    } else if (auto *FT = dyn_cast<FunctionTemplateDecl>(D)) {
+      if (auto *InnerFD = FT->getTemplatedDecl())
+        InnerFD->setRangeEnd(FuncRangeEnd);
+    }
+  };
+
+
   if (SkipBody.ShouldSkip) {
     // Do NOT enter SkipFunctionBody if we already consumed the tokens.
     if (BodyKind == Sema::FnBodyKind::Other)
@@ -1390,6 +1407,8 @@ Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D,
     // and PopExpressionEvaluationContext().
     if (!isLambdaCallOperator(dyn_cast_if_present<FunctionDecl>(Res)))
       Actions.PopExpressionEvaluationContext();
+
+      updateFuncRangeEnd(Res);
     return Res;
   }
 
@@ -1404,6 +1423,7 @@ Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D,
     Actions.SetFunctionBodyKind(Res, KWLoc, BodyKind, DeletedMessage);
     Stmt *GeneratedBody = Res ? Res->getBody() : nullptr;
     Actions.ActOnFinishFunctionBody(Res, GeneratedBody, false);
+    updateFuncRangeEnd(Res);
     return Res;
   }
 
@@ -1424,12 +1444,15 @@ Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D,
   if (SkipFunctionBodies && (!Res || Actions.canSkipFunctionBody(Res)) &&
       trySkippingFunctionBody()) {
     BodyScope.Exit();
+    updateFuncRangeEnd(Res);
     Actions.ActOnSkippedFunctionBody(Res);
     return Actions.ActOnFinishFunctionBody(Res, nullptr, false);
   }
 
-  if (Tok.is(tok::kw_try))
+  if (Tok.is(tok::kw_try)){
+    updateFuncRangeEnd(Res);
     return ParseFunctionTryBlock(Res, BodyScope);
+  }
 
   // If we have a colon, then we're probably parsing a C++
   // ctor-initializer.
@@ -1439,12 +1462,14 @@ Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D,
     // Recover from error.
     if (!Tok.is(tok::l_brace)) {
       BodyScope.Exit();
+      updateFuncRangeEnd(Res);
       Actions.ActOnFinishFunctionBody(Res, nullptr);
       return Res;
     }
   } else
     Actions.ActOnDefaultCtorInitializers(Res);
 
+  updateFuncRangeEnd(Res);
   return ParseFunctionStatementBody(Res, BodyScope);
 }
 
diff --git a/clang/test/Parser/deleted_defaulted_func_range.cpp b/clang/test/Parser/deleted_defaulted_func_range.cpp
new file mode 100644
index 0000000000000..bb85a9cf7c243
--- /dev/null
+++ b/clang/test/Parser/deleted_defaulted_func_range.cpp
@@ -0,0 +1,28 @@
+// RUN: %clang_cc1 -fsyntax-only -ast-dump %s | FileCheck %s
+
+// CHECK: FunctionDecl {{.*}} <{{.*}}:4:1, col:17> {{.*}}
+void f() = delete;
+
+
+struct S {
+  inline S();
+  ~S();
+};
+
+//CHECK: CXXConstructorDecl {{.*}} <{{.*}}:13:1, col:23> {{.*}}
+inline S::S() = default;
+//CHECK: CXXDestructorDecl {{.*}} <{{.*}}:15:1, col:17> {{.*}}
+S::~S() = default;
+
+template <typename T>
+class U {
+  U();
+  ~U();
+};
+
+//CHECK: CXXConstructorDecl {{.*}} <{{.*}}:24:1, line:25:19> {{.*}}
+template <typename T>
+U<T>::U() = default;
+//CHECK: CXXDestructorDecl {{.*}} <{{.*}}:27:1, line:28:20> {{.*}}
+template <typename T>
+U<T>::~U() = default;
\ No newline at end of file

Copy link
Contributor

@zwuis zwuis left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for your patch! Please add a release note entry to "clang/docs/ReleaseNotes.rst".

return;
if (auto *FD = dyn_cast<FunctionDecl>(D)) {
FD->setRangeEnd(FuncRangeEnd);
} else if (auto *FT = dyn_cast<FunctionTemplateDecl>(D)) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ActOnStartOfFunctionDef always returns FunctionDecl * or FunctionTemplateDecl *. You don't need to call dyn_cast.

if (auto *FD = dyn_cast<FunctionDecl>(D)) {
FD->setRangeEnd(FuncRangeEnd);
} else if (auto *FT = dyn_cast<FunctionTemplateDecl>(D)) {
if (auto *InnerFD = FT->getTemplatedDecl())
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

getTemplatedDecl should never return nullptr. Use assert instead if you still want to check the return value.

if (SkipFunctionBodies && (!Res || Actions.canSkipFunctionBody(Res)) &&
trySkippingFunctionBody()) {
BodyScope.Exit();
updateFuncRangeEnd(Res);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do we need to call updateFuncRangeEnd here? Could you give an example?


if (Tok.is(tok::kw_try))
if (Tok.is(tok::kw_try)){
updateFuncRangeEnd(Res);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ditto.

// Recover from error.
if (!Tok.is(tok::l_brace)) {
BodyScope.Exit();
updateFuncRangeEnd(Res);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ditto.

} else
Actions.ActOnDefaultCtorInitializers(Res);

updateFuncRangeEnd(Res);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ditto.

: MultiTemplateParamsArg(),
&SkipBody, BodyKind);

auto updateFuncRangeEnd = [&](Decl *D) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

<< 1 /* deleted */;
BodyKind = Sema::FnBodyKind::Delete;
DeletedMessage = ParseCXXDeletedFunctionMessage();
FuncRangeEnd = clang::Lexer::getLocForEndOfToken(KWLoc, 0, PP.getSourceManager(), getLangOpts()).getLocWithOffset(-1);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

= delete("reason") (C++26 feature) is not handled correctly.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The test should be in "clang/test/AST/" folder.

Comment on lines +23 to +25
//CHECK: CXXConstructorDecl {{.*}} <{{.*}}:24:1, line:25:19> {{.*}}
template <typename T>
U<T>::U() = default;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verifying line numbers is brittle. Other people may add something before this line. Ditto elsewhere.

You might consider writing code in one line.

template ... = default;

@github-actions
Copy link

github-actions bot commented Nov 9, 2025

⚠️ We detected that you are using a GitHub private e-mail address to contribute to the repo.
Please turn off Keep my email addresses private setting in your account.
See LLVM Developer Policy and LLVM Discourse for more information.

@github-actions
Copy link

github-actions bot commented Nov 9, 2025

⚠️ C/C++ code formatter, clang-format found issues in your code. ⚠️

You can test this locally with the following command:
git-clang-format --diff origin/main HEAD --extensions cpp -- clang/test/Parser/deleted_defaulted_func_range.cpp clang/lib/Parse/Parser.cpp --diff_from_common_commit

⚠️
The reproduction instructions above might return results for more than one PR
in a stack if you are using a stacked PR workflow. You can limit the results by
changing origin/main to the base branch/commit you want to compare against.
⚠️

View the diff from clang-format here.
diff --git a/clang/lib/Parse/Parser.cpp b/clang/lib/Parse/Parser.cpp
index 7d68821b7..f3355f4bf 100644
--- a/clang/lib/Parse/Parser.cpp
+++ b/clang/lib/Parse/Parser.cpp
@@ -17,6 +17,7 @@
 #include "clang/AST/DeclTemplate.h"
 #include "clang/Basic/DiagnosticParse.h"
 #include "clang/Basic/StackExhaustionHandler.h"
+#include "clang/Lex/Lexer.h"
 #include "clang/Parse/RAIIObjectsForParser.h"
 #include "clang/Sema/DeclSpec.h"
 #include "clang/Sema/EnterExpressionEvaluationContext.h"
@@ -26,7 +27,6 @@
 #include "llvm/ADT/STLForwardCompat.h"
 #include "llvm/Support/Path.h"
 #include "llvm/Support/TimeProfiler.h"
-#include "clang/Lex/Lexer.h"
 using namespace clang;
 
 
@@ -1343,7 +1343,9 @@ Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D,
           << 1 /* deleted */;
       BodyKind = Sema::FnBodyKind::Delete;
       DeletedMessage = ParseCXXDeletedFunctionMessage();
-      FuncRangeEnd = clang::Lexer::getLocForEndOfToken(KWLoc, 0, PP.getSourceManager(), getLangOpts()).getLocWithOffset(-1);
+      FuncRangeEnd = clang::Lexer::getLocForEndOfToken(
+                         KWLoc, 0, PP.getSourceManager(), getLangOpts())
+                         .getLocWithOffset(-1);
 
     } else if (TryConsumeToken(tok::kw_default, KWLoc)) {
       Diag(KWLoc, getLangOpts().CPlusPlus11
@@ -1351,7 +1353,9 @@ Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D,
                       : diag::ext_defaulted_deleted_function)
           << 0 /* defaulted */;
       BodyKind = Sema::FnBodyKind::Default;
-      FuncRangeEnd = clang::Lexer::getLocForEndOfToken(KWLoc, 0, PP.getSourceManager(), getLangOpts()).getLocWithOffset(-1);
+      FuncRangeEnd = clang::Lexer::getLocForEndOfToken(
+                         KWLoc, 0, PP.getSourceManager(), getLangOpts())
+                         .getLocWithOffset(-1);
     } else {
       llvm_unreachable("function definition after = not 'delete' or 'default'");
     }
@@ -1390,7 +1394,6 @@ Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D,
     }
   };
 
-
   if (SkipBody.ShouldSkip) {
     // Do NOT enter SkipFunctionBody if we already consumed the tokens.
     if (BodyKind == Sema::FnBodyKind::Other)
@@ -1408,7 +1411,7 @@ Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D,
     if (!isLambdaCallOperator(dyn_cast_if_present<FunctionDecl>(Res)))
       Actions.PopExpressionEvaluationContext();
 
-      updateFuncRangeEnd(Res);
+    updateFuncRangeEnd(Res);
     return Res;
   }
 
@@ -1449,7 +1452,7 @@ Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D,
     return Actions.ActOnFinishFunctionBody(Res, nullptr, false);
   }
 
-  if (Tok.is(tok::kw_try)){
+  if (Tok.is(tok::kw_try)) {
     updateFuncRangeEnd(Res);
     return ParseFunctionTryBlock(Res, BodyScope);
   }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

clang:frontend Language frontend issues, e.g. anything involving "Sema" clang Clang issues not falling into any other category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants