1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493
|
//===--- UseConstraintsCheck.cpp - clang-tidy -----------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "UseConstraintsCheck.h"
#include "clang/AST/ASTContext.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/Lex/Lexer.h"
#include "../utils/LexerUtils.h"
#include <optional>
#include <utility>
using namespace clang::ast_matchers;
namespace clang::tidy::modernize {
struct EnableIfData {
TemplateSpecializationTypeLoc Loc;
TypeLoc Outer;
};
namespace {
AST_MATCHER(FunctionDecl, hasOtherDeclarations) {
auto It = Node.redecls_begin();
auto EndIt = Node.redecls_end();
if (It == EndIt)
return false;
++It;
return It != EndIt;
}
} // namespace
void UseConstraintsCheck::registerMatchers(MatchFinder *Finder) {
Finder->addMatcher(
functionTemplateDecl(
// Skip external libraries included as system headers
unless(isExpansionInSystemHeader()),
has(functionDecl(unless(hasOtherDeclarations()), isDefinition(),
hasReturnTypeLoc(typeLoc().bind("return")))
.bind("function")))
.bind("functionTemplate"),
this);
}
static std::optional<TemplateSpecializationTypeLoc>
matchEnableIfSpecializationImplTypename(TypeLoc TheType) {
if (const auto Dep = TheType.getAs<DependentNameTypeLoc>()) {
const IdentifierInfo *Identifier = Dep.getTypePtr()->getIdentifier();
if (!Identifier || Identifier->getName() != "type" ||
Dep.getTypePtr()->getKeyword() != ElaboratedTypeKeyword::Typename) {
return std::nullopt;
}
TheType = Dep.getQualifierLoc().getTypeLoc();
if (TheType.isNull())
return std::nullopt;
}
if (const auto SpecializationLoc =
TheType.getAs<TemplateSpecializationTypeLoc>()) {
const auto *Specialization =
dyn_cast<TemplateSpecializationType>(SpecializationLoc.getTypePtr());
if (!Specialization)
return std::nullopt;
const TemplateDecl *TD =
Specialization->getTemplateName().getAsTemplateDecl();
if (!TD || TD->getName() != "enable_if")
return std::nullopt;
int NumArgs = SpecializationLoc.getNumArgs();
if (NumArgs != 1 && NumArgs != 2)
return std::nullopt;
return SpecializationLoc;
}
return std::nullopt;
}
static std::optional<TemplateSpecializationTypeLoc>
matchEnableIfSpecializationImplTrait(TypeLoc TheType) {
if (const auto Elaborated = TheType.getAs<ElaboratedTypeLoc>())
TheType = Elaborated.getNamedTypeLoc();
if (const auto SpecializationLoc =
TheType.getAs<TemplateSpecializationTypeLoc>()) {
const auto *Specialization =
dyn_cast<TemplateSpecializationType>(SpecializationLoc.getTypePtr());
if (!Specialization)
return std::nullopt;
const TemplateDecl *TD =
Specialization->getTemplateName().getAsTemplateDecl();
if (!TD || TD->getName() != "enable_if_t")
return std::nullopt;
if (!Specialization->isTypeAlias())
return std::nullopt;
if (const auto *AliasedType =
dyn_cast<DependentNameType>(Specialization->getAliasedType())) {
if (AliasedType->getIdentifier()->getName() != "type" ||
AliasedType->getKeyword() != ElaboratedTypeKeyword::Typename) {
return std::nullopt;
}
} else {
return std::nullopt;
}
int NumArgs = SpecializationLoc.getNumArgs();
if (NumArgs != 1 && NumArgs != 2)
return std::nullopt;
return SpecializationLoc;
}
return std::nullopt;
}
static std::optional<TemplateSpecializationTypeLoc>
matchEnableIfSpecializationImpl(TypeLoc TheType) {
if (auto EnableIf = matchEnableIfSpecializationImplTypename(TheType))
return EnableIf;
return matchEnableIfSpecializationImplTrait(TheType);
}
static std::optional<EnableIfData>
matchEnableIfSpecialization(TypeLoc TheType) {
if (const auto Pointer = TheType.getAs<PointerTypeLoc>())
TheType = Pointer.getPointeeLoc();
else if (const auto Reference = TheType.getAs<ReferenceTypeLoc>())
TheType = Reference.getPointeeLoc();
if (const auto Qualified = TheType.getAs<QualifiedTypeLoc>())
TheType = Qualified.getUnqualifiedLoc();
if (auto EnableIf = matchEnableIfSpecializationImpl(TheType))
return EnableIfData{std::move(*EnableIf), TheType};
return std::nullopt;
}
static std::pair<std::optional<EnableIfData>, const Decl *>
matchTrailingTemplateParam(const FunctionTemplateDecl *FunctionTemplate) {
// For non-type trailing param, match very specifically
// 'template <..., enable_if_type<Condition, Type> = Default>' where
// enable_if_type is 'enable_if' or 'enable_if_t'. E.g., 'template <typename
// T, enable_if_t<is_same_v<T, bool>, int*> = nullptr>
//
// Otherwise, match a trailing default type arg.
// E.g., 'template <typename T, typename = enable_if_t<is_same_v<T, bool>>>'
const TemplateParameterList *TemplateParams =
FunctionTemplate->getTemplateParameters();
if (TemplateParams->size() == 0)
return {};
const NamedDecl *LastParam =
TemplateParams->getParam(TemplateParams->size() - 1);
if (const auto *LastTemplateParam =
dyn_cast<NonTypeTemplateParmDecl>(LastParam)) {
if (!LastTemplateParam->hasDefaultArgument() ||
!LastTemplateParam->getName().empty())
return {};
return {matchEnableIfSpecialization(
LastTemplateParam->getTypeSourceInfo()->getTypeLoc()),
LastTemplateParam};
}
if (const auto *LastTemplateParam =
dyn_cast<TemplateTypeParmDecl>(LastParam)) {
if (LastTemplateParam->hasDefaultArgument() &&
LastTemplateParam->getIdentifier() == nullptr) {
return {
matchEnableIfSpecialization(LastTemplateParam->getDefaultArgument()
.getTypeSourceInfo()
->getTypeLoc()),
LastTemplateParam};
}
}
return {};
}
template <typename T>
static SourceLocation getRAngleFileLoc(const SourceManager &SM,
const T &Element) {
// getFileLoc handles the case where the RAngle loc is part of a synthesized
// '>>', which ends up allocating a 'scratch space' buffer in the source
// manager.
return SM.getFileLoc(Element.getRAngleLoc());
}
static SourceRange
getConditionRange(ASTContext &Context,
const TemplateSpecializationTypeLoc &EnableIf) {
// TemplateArgumentLoc's SourceRange End is the location of the last token
// (per UnqualifiedId docs). E.g., in `enable_if<AAA && BBB>`, the End
// location will be the first 'B' in 'BBB'.
const LangOptions &LangOpts = Context.getLangOpts();
const SourceManager &SM = Context.getSourceManager();
if (EnableIf.getNumArgs() > 1) {
TemplateArgumentLoc NextArg = EnableIf.getArgLoc(1);
return {EnableIf.getLAngleLoc().getLocWithOffset(1),
utils::lexer::findPreviousTokenKind(
NextArg.getSourceRange().getBegin(), SM, LangOpts, tok::comma)};
}
return {EnableIf.getLAngleLoc().getLocWithOffset(1),
getRAngleFileLoc(SM, EnableIf)};
}
static SourceRange getTypeRange(ASTContext &Context,
const TemplateSpecializationTypeLoc &EnableIf) {
TemplateArgumentLoc Arg = EnableIf.getArgLoc(1);
const LangOptions &LangOpts = Context.getLangOpts();
const SourceManager &SM = Context.getSourceManager();
return {utils::lexer::findPreviousTokenKind(Arg.getSourceRange().getBegin(),
SM, LangOpts, tok::comma)
.getLocWithOffset(1),
getRAngleFileLoc(SM, EnableIf)};
}
// Returns the original source text of the second argument of a call to
// enable_if_t. E.g., in enable_if_t<Condition, TheType>, this function
// returns 'TheType'.
static std::optional<StringRef>
getTypeText(ASTContext &Context,
const TemplateSpecializationTypeLoc &EnableIf) {
if (EnableIf.getNumArgs() > 1) {
const LangOptions &LangOpts = Context.getLangOpts();
const SourceManager &SM = Context.getSourceManager();
bool Invalid = false;
StringRef Text = Lexer::getSourceText(CharSourceRange::getCharRange(
getTypeRange(Context, EnableIf)),
SM, LangOpts, &Invalid)
.trim();
if (Invalid)
return std::nullopt;
return Text;
}
return "void";
}
static std::optional<SourceLocation>
findInsertionForConstraint(const FunctionDecl *Function, ASTContext &Context) {
SourceManager &SM = Context.getSourceManager();
const LangOptions &LangOpts = Context.getLangOpts();
if (const auto *Constructor = dyn_cast<CXXConstructorDecl>(Function)) {
for (const CXXCtorInitializer *Init : Constructor->inits()) {
if (Init->getSourceOrder() == 0)
return utils::lexer::findPreviousTokenKind(Init->getSourceLocation(),
SM, LangOpts, tok::colon);
}
if (!Constructor->inits().empty())
return std::nullopt;
}
if (Function->isDeleted()) {
SourceLocation FunctionEnd = Function->getSourceRange().getEnd();
return utils::lexer::findNextAnyTokenKind(FunctionEnd, SM, LangOpts,
tok::equal, tok::equal);
}
const Stmt *Body = Function->getBody();
if (!Body)
return std::nullopt;
return Body->getBeginLoc();
}
bool isPrimaryExpression(const Expr *Expression) {
// This function is an incomplete approximation of checking whether
// an Expr is a primary expression. In particular, if this function
// returns true, the expression is a primary expression. The converse
// is not necessarily true.
if (const auto *Cast = dyn_cast<ImplicitCastExpr>(Expression))
Expression = Cast->getSubExprAsWritten();
if (isa<ParenExpr, DependentScopeDeclRefExpr>(Expression))
return true;
return false;
}
// Return the original source text of an enable_if_t condition, i.e., the
// first template argument). For example, in
// 'enable_if_t<FirstCondition || SecondCondition, AType>', the text
// the text 'FirstCondition || SecondCondition' is returned.
static std::optional<std::string> getConditionText(const Expr *ConditionExpr,
SourceRange ConditionRange,
ASTContext &Context) {
SourceManager &SM = Context.getSourceManager();
const LangOptions &LangOpts = Context.getLangOpts();
SourceLocation PrevTokenLoc = ConditionRange.getEnd();
if (PrevTokenLoc.isInvalid())
return std::nullopt;
const bool SkipComments = false;
Token PrevToken;
std::tie(PrevToken, PrevTokenLoc) = utils::lexer::getPreviousTokenAndStart(
PrevTokenLoc, SM, LangOpts, SkipComments);
bool EndsWithDoubleSlash =
PrevToken.is(tok::comment) &&
Lexer::getSourceText(CharSourceRange::getCharRange(
PrevTokenLoc, PrevTokenLoc.getLocWithOffset(2)),
SM, LangOpts) == "//";
bool Invalid = false;
llvm::StringRef ConditionText = Lexer::getSourceText(
CharSourceRange::getCharRange(ConditionRange), SM, LangOpts, &Invalid);
if (Invalid)
return std::nullopt;
auto AddParens = [&](llvm::StringRef Text) -> std::string {
if (isPrimaryExpression(ConditionExpr))
return Text.str();
return "(" + Text.str() + ")";
};
if (EndsWithDoubleSlash)
return AddParens(ConditionText);
return AddParens(ConditionText.trim());
}
// Handle functions that return enable_if_t, e.g.,
// template <...>
// enable_if_t<Condition, ReturnType> function();
//
// Return a vector of FixItHints if the code can be replaced with
// a C++20 requires clause. In the example above, returns FixItHints
// to result in
// template <...>
// ReturnType function() requires Condition {}
static std::vector<FixItHint> handleReturnType(const FunctionDecl *Function,
const TypeLoc &ReturnType,
const EnableIfData &EnableIf,
ASTContext &Context) {
TemplateArgumentLoc EnableCondition = EnableIf.Loc.getArgLoc(0);
SourceRange ConditionRange = getConditionRange(Context, EnableIf.Loc);
std::optional<std::string> ConditionText = getConditionText(
EnableCondition.getSourceExpression(), ConditionRange, Context);
if (!ConditionText)
return {};
std::optional<StringRef> TypeText = getTypeText(Context, EnableIf.Loc);
if (!TypeText)
return {};
SmallVector<const Expr *, 3> ExistingConstraints;
Function->getAssociatedConstraints(ExistingConstraints);
if (!ExistingConstraints.empty()) {
// FIXME - Support adding new constraints to existing ones. Do we need to
// consider subsumption?
return {};
}
std::optional<SourceLocation> ConstraintInsertionLoc =
findInsertionForConstraint(Function, Context);
if (!ConstraintInsertionLoc)
return {};
std::vector<FixItHint> FixIts;
FixIts.push_back(FixItHint::CreateReplacement(
CharSourceRange::getTokenRange(EnableIf.Outer.getSourceRange()),
*TypeText));
FixIts.push_back(FixItHint::CreateInsertion(
*ConstraintInsertionLoc, "requires " + *ConditionText + " "));
return FixIts;
}
// Handle enable_if_t in a trailing template parameter, e.g.,
// template <..., enable_if_t<Condition, Type> = Type{}>
// ReturnType function();
//
// Return a vector of FixItHints if the code can be replaced with
// a C++20 requires clause. In the example above, returns FixItHints
// to result in
// template <...>
// ReturnType function() requires Condition {}
static std::vector<FixItHint>
handleTrailingTemplateType(const FunctionTemplateDecl *FunctionTemplate,
const FunctionDecl *Function,
const Decl *LastTemplateParam,
const EnableIfData &EnableIf, ASTContext &Context) {
SourceManager &SM = Context.getSourceManager();
const LangOptions &LangOpts = Context.getLangOpts();
TemplateArgumentLoc EnableCondition = EnableIf.Loc.getArgLoc(0);
SourceRange ConditionRange = getConditionRange(Context, EnableIf.Loc);
std::optional<std::string> ConditionText = getConditionText(
EnableCondition.getSourceExpression(), ConditionRange, Context);
if (!ConditionText)
return {};
SmallVector<const Expr *, 3> ExistingConstraints;
Function->getAssociatedConstraints(ExistingConstraints);
if (!ExistingConstraints.empty()) {
// FIXME - Support adding new constraints to existing ones. Do we need to
// consider subsumption?
return {};
}
SourceRange RemovalRange;
const TemplateParameterList *TemplateParams =
FunctionTemplate->getTemplateParameters();
if (!TemplateParams || TemplateParams->size() == 0)
return {};
if (TemplateParams->size() == 1) {
RemovalRange =
SourceRange(TemplateParams->getTemplateLoc(),
getRAngleFileLoc(SM, *TemplateParams).getLocWithOffset(1));
} else {
RemovalRange =
SourceRange(utils::lexer::findPreviousTokenKind(
LastTemplateParam->getSourceRange().getBegin(), SM,
LangOpts, tok::comma),
getRAngleFileLoc(SM, *TemplateParams));
}
std::optional<SourceLocation> ConstraintInsertionLoc =
findInsertionForConstraint(Function, Context);
if (!ConstraintInsertionLoc)
return {};
std::vector<FixItHint> FixIts;
FixIts.push_back(
FixItHint::CreateRemoval(CharSourceRange::getCharRange(RemovalRange)));
FixIts.push_back(FixItHint::CreateInsertion(
*ConstraintInsertionLoc, "requires " + *ConditionText + " "));
return FixIts;
}
void UseConstraintsCheck::check(const MatchFinder::MatchResult &Result) {
const auto *FunctionTemplate =
Result.Nodes.getNodeAs<FunctionTemplateDecl>("functionTemplate");
const auto *Function = Result.Nodes.getNodeAs<FunctionDecl>("function");
const auto *ReturnType = Result.Nodes.getNodeAs<TypeLoc>("return");
if (!FunctionTemplate || !Function || !ReturnType)
return;
// Check for
//
// Case 1. Return type of function
//
// template <...>
// enable_if_t<Condition, ReturnType>::type function() {}
//
// Case 2. Trailing template parameter
//
// template <..., enable_if_t<Condition, Type> = Type{}>
// ReturnType function() {}
//
// or
//
// template <..., typename = enable_if_t<Condition, void>>
// ReturnType function() {}
//
// Case 1. Return type of function
if (auto EnableIf = matchEnableIfSpecialization(*ReturnType)) {
diag(ReturnType->getBeginLoc(),
"use C++20 requires constraints instead of enable_if")
<< handleReturnType(Function, *ReturnType, *EnableIf, *Result.Context);
return;
}
// Case 2. Trailing template parameter
if (auto [EnableIf, LastTemplateParam] =
matchTrailingTemplateParam(FunctionTemplate);
EnableIf && LastTemplateParam) {
diag(LastTemplateParam->getSourceRange().getBegin(),
"use C++20 requires constraints instead of enable_if")
<< handleTrailingTemplateType(FunctionTemplate, Function,
LastTemplateParam, *EnableIf,
*Result.Context);
return;
}
}
} // namespace clang::tidy::modernize
|