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
|
//===-- StdAllocatorConstCheck.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 "StdAllocatorConstCheck.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
using namespace clang::ast_matchers;
namespace clang::tidy::portability {
void StdAllocatorConstCheck::registerMatchers(MatchFinder *Finder) {
// Match std::allocator<const T>.
auto allocatorConst =
recordType(hasDeclaration(classTemplateSpecializationDecl(
hasName("::std::allocator"),
hasTemplateArgument(0, refersToType(qualType(isConstQualified()))))));
auto hasContainerName =
hasAnyName("::std::vector", "::std::deque", "::std::list",
"::std::multiset", "::std::set", "::std::unordered_multiset",
"::std::unordered_set", "::absl::flat_hash_set");
// Match `std::vector<const T> var;` and other common containers like deque,
// list, and absl::flat_hash_set. Containers like queue and stack use deque
// but do not directly use std::allocator as a template argument, so they
// aren't caught.
Finder->addMatcher(
typeLoc(
templateSpecializationTypeLoc(),
loc(hasUnqualifiedDesugaredType(anyOf(
recordType(hasDeclaration(classTemplateSpecializationDecl(
hasContainerName,
anyOf(
hasTemplateArgument(1, refersToType(allocatorConst)),
hasTemplateArgument(2, refersToType(allocatorConst)),
hasTemplateArgument(3, refersToType(allocatorConst)))))),
// Match std::vector<const dependent>
templateSpecializationType(
templateArgumentCountIs(1),
hasTemplateArgument(
0, refersToType(qualType(isConstQualified()))),
hasDeclaration(namedDecl(hasContainerName)))))))
.bind("type_loc"),
this);
}
void StdAllocatorConstCheck::check(const MatchFinder::MatchResult &Result) {
const auto *T = Result.Nodes.getNodeAs<TypeLoc>("type_loc");
if (!T)
return;
// Exclude TypeLoc matches in STL headers.
if (isSystem(Result.Context->getSourceManager().getFileCharacteristic(
T->getBeginLoc())))
return;
diag(T->getBeginLoc(),
"container using std::allocator<const T> is a deprecated libc++ "
"extension; remove const for compatibility with other standard "
"libraries");
}
} // namespace clang::tidy::portability
|