1 //===--- DontModifyStdNamespaceCheck.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 "DontModifyStdNamespaceCheck.h"
10 #include "clang/AST/ASTContext.h"
11 #include "clang/ASTMatchers/ASTMatchFinder.h"
12 
13 using namespace clang::ast_matchers;
14 
15 namespace clang {
16 namespace tidy {
17 namespace cert {
18 
registerMatchers(MatchFinder * Finder)19 void DontModifyStdNamespaceCheck::registerMatchers(MatchFinder *Finder) {
20   Finder->addMatcher(
21       namespaceDecl(unless(isExpansionInSystemHeader()),
22                     hasAnyName("std", "posix"),
23                     has(decl(unless(anyOf(
24                         functionDecl(isExplicitTemplateSpecialization()),
25                         cxxRecordDecl(isExplicitTemplateSpecialization()))))))
26           .bind("nmspc"),
27       this);
28 }
29 
check(const MatchFinder::MatchResult & Result)30 void DontModifyStdNamespaceCheck::check(
31     const MatchFinder::MatchResult &Result) {
32   const auto *N = Result.Nodes.getNodeAs<NamespaceDecl>("nmspc");
33 
34   // Only consider top level namespaces.
35   if (N->getParent() != Result.Context->getTranslationUnitDecl())
36     return;
37 
38   diag(N->getLocation(),
39        "modification of %0 namespace can result in undefined behavior")
40       << N;
41 }
42 
43 } // namespace cert
44 } // namespace tidy
45 } // namespace clang
46