| 1 |
//===--- IncorrectEnableIfCheck.cpp - clang-tidy --------------------------===// |
| 2 |
// |
| 3 |
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 4 |
// See https://llvm.org/LICENSE.txt for license information. |
| 5 |
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 6 |
// |
| 7 |
//===----------------------------------------------------------------------===// |
| 8 |
|
| 9 |
#include "IncorrectEnableIfCheck.h" |
| 10 |
#include "clang/AST/ASTContext.h" |
| 11 |
#include "clang/ASTMatchers/ASTMatchFinder.h" |
| 12 |
|
| 13 |
using namespace clang::ast_matchers; |
| 14 |
|
| 15 |
namespace clang::tidy::bugprone { |
| 16 |
|
| 17 |
namespace { |
| 18 |
|
| 19 |
AST_MATCHER_P(TemplateTypeParmDecl, hasUnnamedDefaultArgument, |
| 20 |
ast_matchers::internal::Matcher<TypeLoc>, InnerMatcher) { |
| 21 |
if (Node.getIdentifier() != nullptr || !Node.hasDefaultArgument() || |
| 22 |
Node.getDefaultArgument().getArgument().isNull()) |
| 23 |
return false; |
| 24 |
|
| 25 |
TypeLoc DefaultArgTypeLoc = |
| 26 |
Node.getDefaultArgument().getTypeSourceInfo()->getTypeLoc(); |
| 27 |
return InnerMatcher.matches(DefaultArgTypeLoc, Finder, Builder); |
| 28 |
} |
| 29 |
|
| 30 |
} // namespace |
| 31 |
|
| 32 |
void IncorrectEnableIfCheck::registerMatchers(MatchFinder *Finder) { |
| 33 |
Finder->addMatcher( |
| 34 |
templateTypeParmDecl( |
| 35 |
hasUnnamedDefaultArgument( |
| 36 |
elaboratedTypeLoc( |
| 37 |
hasNamedTypeLoc(templateSpecializationTypeLoc( |
| 38 |
loc(qualType(hasDeclaration(namedDecl( |
| 39 |
hasName("::std::enable_if")))))) |
| 40 |
.bind("enable_if_specialization"))) |
| 41 |
.bind("elaborated"))) |
| 42 |
.bind("enable_if"), |
| 43 |
this); |
| 44 |
} |
| 45 |
|
| 46 |
void IncorrectEnableIfCheck::check(const MatchFinder::MatchResult &Result) { |
| 47 |
const auto *EnableIf = |
| 48 |
Result.Nodes.getNodeAs<TemplateTypeParmDecl>("enable_if"); |
| 49 |
const auto *ElaboratedLoc = |
| 50 |
Result.Nodes.getNodeAs<ElaboratedTypeLoc>("elaborated"); |
| 51 |
const auto *EnableIfSpecializationLoc = |
| 52 |
Result.Nodes.getNodeAs<TemplateSpecializationTypeLoc>( |
| 53 |
"enable_if_specialization"); |
| 54 |
|
| 55 |
if (!EnableIf || !ElaboratedLoc || !EnableIfSpecializationLoc) |
| 56 |
return; |
| 57 |
|
| 58 |
const SourceManager &SM = *Result.SourceManager; |
| 59 |
SourceLocation RAngleLoc = |
| 60 |
SM.getExpansionLoc(EnableIfSpecializationLoc->getRAngleLoc()); |
| 61 |
|
| 62 |
auto Diag = diag(EnableIf->getBeginLoc(), |
| 63 |
"incorrect std::enable_if usage detected; use " |
| 64 |
"'typename std::enable_if<...>::type'"); |
| 65 |
if (!getLangOpts().CPlusPlus20) { |
| 66 |
Diag << FixItHint::CreateInsertion(ElaboratedLoc->getBeginLoc(), |
| 67 |
"typename "); |
| 68 |
} |
| 69 |
Diag << FixItHint::CreateInsertion(RAngleLoc.getLocWithOffset(1), "::type"); |
| 70 |
} |
| 71 |
|
| 72 |
} // namespace clang::tidy::bugprone |