clang-tools  3.8.0
HeaderGuardCheck.cpp
Go to the documentation of this file.
1 //===--- HeaderGuardCheck.cpp - clang-tidy --------------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "HeaderGuardCheck.h"
11 
12 namespace clang {
13 namespace tidy {
14 namespace llvm {
15 
17  return Filename.endswith(".h");
18 }
19 
21  StringRef OldGuard) {
22  std::string Guard = tooling::getAbsolutePath(Filename);
23 
24  // Sanitize the path. There are some rules for compatibility with the historic
25  // style in include/llvm and include/clang which we want to preserve.
26 
27  // We don't want _INCLUDE_ in our guards.
28  size_t PosInclude = Guard.rfind("include/");
29  if (PosInclude != StringRef::npos)
30  Guard = Guard.substr(PosInclude + std::strlen("include/"));
31 
32  // For clang we drop the _TOOLS_.
33  size_t PosToolsClang = Guard.rfind("tools/clang/");
34  if (PosToolsClang != StringRef::npos)
35  Guard = Guard.substr(PosToolsClang + std::strlen("tools/"));
36 
37  // The remainder is LLVM_FULL_PATH_TO_HEADER_H
38  size_t PosLLVM = Guard.rfind("llvm/");
39  if (PosLLVM != StringRef::npos)
40  Guard = Guard.substr(PosLLVM);
41 
42  std::replace(Guard.begin(), Guard.end(), '/', '_');
43  std::replace(Guard.begin(), Guard.end(), '.', '_');
44  std::replace(Guard.begin(), Guard.end(), '-', '_');
45 
46  // The prevalent style in clang is LLVM_CLANG_FOO_BAR_H
47  if (StringRef(Guard).startswith("clang"))
48  Guard = "LLVM_" + Guard;
49 
50  return StringRef(Guard).upper();
51 }
52 
53 } // namespace llvm
54 } // namespace tidy
55 } // namespace clang
std::string getHeaderGuard(StringRef Filename, StringRef OldGuard) override
Get the canonical header guard for a file.
std::string Filename
Filename as a string.
bool shouldFixHeaderGuard(StringRef Filename) override
Returns true if the checker should suggest changing an existing header guard to the string returned b...