diff --git a/clang/include/clang/AST/Decl.h b/clang/include/clang/AST/Decl.h --- a/clang/include/clang/AST/Decl.h +++ b/clang/include/clang/AST/Decl.h @@ -3701,6 +3701,10 @@ bool IsFixed); static EnumDecl *CreateDeserialized(ASTContext &C, unsigned ID); + /// Overrides to provide correct range when there's an enum-base specifier + /// with forward declarations. + SourceRange getSourceRange() const override LLVM_READONLY; + /// When created, the EnumDecl corresponds to a /// forward-declared enum. This method is used to mark the /// declaration as being defined; its enumerators have already been diff --git a/clang/lib/AST/Decl.cpp b/clang/lib/AST/Decl.cpp --- a/clang/lib/AST/Decl.cpp +++ b/clang/lib/AST/Decl.cpp @@ -4524,6 +4524,17 @@ return ODRHash; } +SourceRange EnumDecl::getSourceRange() const { + auto Res = TagDecl::getSourceRange(); + // Set end-point to enum-base, e.g. enum foo : ^bar + if (auto *TSI = getIntegerTypeSourceInfo()) { + // TagDecl doesn't know about the enum base. + if (!getBraceRange().getEnd().isValid()) + Res.setEnd(TSI->getTypeLoc().getEndLoc()); + } + return Res; +} + //===----------------------------------------------------------------------===// // RecordDecl Implementation //===----------------------------------------------------------------------===// diff --git a/clang/unittests/AST/DeclTest.cpp b/clang/unittests/AST/DeclTest.cpp --- a/clang/unittests/AST/DeclTest.cpp +++ b/clang/unittests/AST/DeclTest.cpp @@ -10,14 +10,17 @@ // //===----------------------------------------------------------------------===// +#include "clang/AST/Decl.h" #include "clang/AST/ASTContext.h" #include "clang/AST/Mangle.h" #include "clang/ASTMatchers/ASTMatchFinder.h" #include "clang/ASTMatchers/ASTMatchers.h" #include "clang/Basic/LLVM.h" #include "clang/Basic/TargetInfo.h" +#include "clang/Lex/Lexer.h" #include "clang/Tooling/Tooling.h" #include "llvm/IR/DataLayout.h" +#include "llvm/Testing/Support/Annotations.h" #include "gtest/gtest.h" using namespace clang::ast_matchers; @@ -138,3 +141,19 @@ ASSERT_TRUE(0 == MangleA.compare("_ZTSA_i")); ASSERT_TRUE(0 == MangleB.compare("_ZTSAT0__T_")); } + +TEST(Decl, EnumDeclRange) { + llvm::Annotations Code(R"( + typedef int Foo; + [[enum Bar : Foo]];)"); + auto AST = tooling::buildASTFromCodeWithArgs(Code.code(), /*Args=*/{}); + ASTContext &Ctx = AST->getASTContext(); + const auto &SM = Ctx.getSourceManager(); + + const auto *Bar = + selectFirst("Bar", match(enumDecl().bind("Bar"), Ctx)); + auto BarRange = + Lexer::getAsCharRange(Bar->getSourceRange(), SM, Ctx.getLangOpts()); + EXPECT_EQ(SM.getFileOffset(BarRange.getBegin()), Code.range().Begin); + EXPECT_EQ(SM.getFileOffset(BarRange.getEnd()), Code.range().End); +}