[clang] Fix range for forward-declared enums

This used to span just the `[[enum foo]] : bar;` in the absence of a
body. This patch expands the range to cover the base specifier, so that the
various consumers can detect the full range of the decl.

Differential Revision: https://reviews.llvm.org/D111259
This commit is contained in:
Kadir Cetinkaya 2021-10-06 20:25:26 +02:00
parent 025f6ca7c4
commit ffa96f022c
No known key found for this signature in database
GPG Key ID: E39E36B8D2057ED6
3 changed files with 34 additions and 0 deletions

View File

@ -3701,6 +3701,10 @@ public:
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

View File

@ -4524,6 +4524,17 @@ unsigned EnumDecl::getODRHash() {
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
//===----------------------------------------------------------------------===//

View File

@ -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 @@ TEST(Decl, MangleDependentSizedArray) {
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<TagDecl>("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);
}