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 #include "clang/Tooling/Tooling.h" 11 #include "llvm/Support/Path.h" 12 13 namespace clang { 14 namespace tidy { 15 namespace llvm_check { 16 17 LLVMHeaderGuardCheck::LLVMHeaderGuardCheck(StringRef Name, 18 ClangTidyContext *Context) 19 : HeaderGuardCheck(Name, Context) {} 20 21 std::string LLVMHeaderGuardCheck::getHeaderGuard(StringRef Filename, 22 StringRef OldGuard) { 23 std::string Guard = tooling::getAbsolutePath(Filename); 24 25 // When running under Windows, need to convert the path separators from 26 // `\` to `/`. 27 Guard = llvm::sys::path::convert_to_slash(Guard); 28 29 // Sanitize the path. There are some rules for compatibility with the historic 30 // style in include/llvm and include/clang which we want to preserve. 31 32 // We don't want _INCLUDE_ in our guards. 33 size_t PosInclude = Guard.rfind("include/"); 34 if (PosInclude != StringRef::npos) 35 Guard = Guard.substr(PosInclude + std::strlen("include/")); 36 37 // For clang we drop the _TOOLS_. 38 size_t PosToolsClang = Guard.rfind("tools/clang/"); 39 if (PosToolsClang != StringRef::npos) 40 Guard = Guard.substr(PosToolsClang + std::strlen("tools/")); 41 42 // Unlike LLVM svn, LLVM git monorepo is named llvm-project, so we replace 43 // "/llvm-project/" with the canonical "/llvm/". 44 const static StringRef LLVMProject = "/llvm-project/"; 45 size_t PosLLVMProject = Guard.rfind(std::string(LLVMProject)); 46 if (PosLLVMProject != StringRef::npos) 47 Guard = Guard.replace(PosLLVMProject, LLVMProject.size(), "/llvm/"); 48 49 // The remainder is LLVM_FULL_PATH_TO_HEADER_H 50 size_t PosLLVM = Guard.rfind("llvm/"); 51 if (PosLLVM != StringRef::npos) 52 Guard = Guard.substr(PosLLVM); 53 54 std::replace(Guard.begin(), Guard.end(), '/', '_'); 55 std::replace(Guard.begin(), Guard.end(), '.', '_'); 56 std::replace(Guard.begin(), Guard.end(), '-', '_'); 57 58 // The prevalent style in clang is LLVM_CLANG_FOO_BAR_H 59 if (StringRef(Guard).startswith("clang")) 60 Guard = "LLVM_" + Guard; 61 62 // The prevalent style in flang is FORTRAN_FOO_BAR_H 63 if (StringRef(Guard).startswith("flang")) 64 Guard = "FORTRAN" + Guard.substr(sizeof("flang") - 1); 65 66 return StringRef(Guard).upper(); 67 } 68 69 } // namespace llvm_check 70 } // namespace tidy 71 } // namespace clang 72