clang-tools  10.0.0git
HeaderGuardCheck.cpp
Go to the documentation of this file.
1 //===--- HeaderGuardCheck.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 "HeaderGuardCheck.h"
10 
11 namespace clang {
12 namespace tidy {
13 namespace llvm_check {
14 
16  ClangTidyContext *Context)
17  : HeaderGuardCheck(Name, Context) {}
18 
20  StringRef OldGuard) {
21  std::string Guard = tooling::getAbsolutePath(Filename);
22 
23  // Sanitize the path. There are some rules for compatibility with the historic
24  // style in include/llvm and include/clang which we want to preserve.
25 
26  // We don't want _INCLUDE_ in our guards.
27  size_t PosInclude = Guard.rfind("include/");
28  if (PosInclude != StringRef::npos)
29  Guard = Guard.substr(PosInclude + std::strlen("include/"));
30 
31  // For clang we drop the _TOOLS_.
32  size_t PosToolsClang = Guard.rfind("tools/clang/");
33  if (PosToolsClang != StringRef::npos)
34  Guard = Guard.substr(PosToolsClang + std::strlen("tools/"));
35 
36  // Unlike LLVM svn, LLVM git monorepo is named llvm-project, so we replace
37  // "/llvm-project/" with the cannonical "/llvm/".
38  const static StringRef LLVMProject = "/llvm-project/";
39  size_t PosLLVMProject = Guard.rfind(LLVMProject);
40  if (PosLLVMProject != StringRef::npos)
41  Guard = Guard.replace(PosLLVMProject, LLVMProject.size(), "/llvm/");
42 
43  // The remainder is LLVM_FULL_PATH_TO_HEADER_H
44  size_t PosLLVM = Guard.rfind("llvm/");
45  if (PosLLVM != StringRef::npos)
46  Guard = Guard.substr(PosLLVM);
47 
48  std::replace(Guard.begin(), Guard.end(), '/', '_');
49  std::replace(Guard.begin(), Guard.end(), '.', '_');
50  std::replace(Guard.begin(), Guard.end(), '-', '_');
51 
52  // The prevalent style in clang is LLVM_CLANG_FOO_BAR_H
53  if (StringRef(Guard).startswith("clang"))
54  Guard = "LLVM_" + Guard;
55 
56  return StringRef(Guard).upper();
57 }
58 
59 } // namespace llvm_check
60 } // namespace tidy
61 } // namespace clang
std::string getHeaderGuard(StringRef Filename, StringRef OldGuard) override
Gets the canonical header guard for a file.
static std::string replace(llvm::StringRef Haystack, llvm::StringRef Needle, llvm::StringRef Repl)
Definition: TestIndex.cpp:30
std::string Filename
Filename as a string.
LLVMHeaderGuardCheck(StringRef Name, ClangTidyContext *Context)
static constexpr llvm::StringLiteral Name
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.