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
13using namespace clang::ast_matchers;
14
15namespace clang::tidy::bugprone {
16
17namespace {
18
19AST_MATCHER_P(TemplateTypeParmDecl, hasUnnamedDefaultArgument,
20 ast_matchers::internal::Matcher<TypeLoc>, InnerMatcher) {
21 if (Node.getIdentifier() != nullptr || !Node.hasDefaultArgument() ||
22 Node.getDefaultArgumentInfo() == nullptr)
23 return false;
24
25 TypeLoc DefaultArgTypeLoc = Node.getDefaultArgumentInfo()->getTypeLoc();
26 return InnerMatcher.matches(Node: DefaultArgTypeLoc, Finder, Builder);
27}
28
29} // namespace
30
31void IncorrectEnableIfCheck::registerMatchers(MatchFinder *Finder) {
32 Finder->addMatcher(
33 templateTypeParmDecl(
34 hasUnnamedDefaultArgument(
35 elaboratedTypeLoc(
36 hasNamedTypeLoc(templateSpecializationTypeLoc(
37 loc(InnerMatcher: qualType(hasDeclaration(InnerMatcher: namedDecl(
38 hasName(Name: "::std::enable_if"))))))
39 .bind("enable_if_specialization")))
40 .bind("elaborated")))
41 .bind("enable_if"),
42 this);
43}
44
45void IncorrectEnableIfCheck::check(const MatchFinder::MatchResult &Result) {
46 const auto *EnableIf =
47 Result.Nodes.getNodeAs<TemplateTypeParmDecl>(ID: "enable_if");
48 const auto *ElaboratedLoc =
49 Result.Nodes.getNodeAs<ElaboratedTypeLoc>(ID: "elaborated");
50 const auto *EnableIfSpecializationLoc =
51 Result.Nodes.getNodeAs<TemplateSpecializationTypeLoc>(
52 ID: "enable_if_specialization");
53
54 if (!EnableIf || !ElaboratedLoc || !EnableIfSpecializationLoc)
55 return;
56
57 const SourceManager &SM = *Result.SourceManager;
58 SourceLocation RAngleLoc =
59 SM.getExpansionLoc(Loc: EnableIfSpecializationLoc->getRAngleLoc());
60
61 auto Diag = diag(EnableIf->getBeginLoc(),
62 "incorrect std::enable_if usage detected; use "
63 "'typename std::enable_if<...>::type'");
64 if (!getLangOpts().CPlusPlus20) {
65 Diag << FixItHint::CreateInsertion(InsertionLoc: ElaboratedLoc->getBeginLoc(),
66 Code: "typename ");
67 }
68 Diag << FixItHint::CreateInsertion(InsertionLoc: RAngleLoc.getLocWithOffset(Offset: 1), Code: "::type");
69}
70
71} // namespace clang::tidy::bugprone
72

source code of clang-tools-extra/clang-tidy/bugprone/IncorrectEnableIfCheck.cpp