[clang-tools-extra] [llvm] New check `misc-header-guard` (PR #177315)
Baranov Victor via cfe-commits
cfe-commits at lists.llvm.org
Sat Jan 31 08:38:27 PST 2026
================
@@ -0,0 +1,105 @@
+//===----------------------------------------------------------------------===//
+//
+// 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 "HeaderGuardCheck.h"
+#include "../utils/OptionsUtils.h"
+#include "clang/Basic/SourceManager.h"
+#include "clang/Lex/PPCallbacks.h"
+#include "clang/Lex/Preprocessor.h"
+#include "clang/Tooling/Tooling.h"
+#include "llvm/Support/Path.h"
+
+namespace clang::tidy::misc {
+
+HeaderGuardCheck::HeaderGuardCheck(StringRef Name, ClangTidyContext *Context)
+ : clang::tidy::utils::HeaderGuardCheck(Name, Context),
+ AllowPragmaOnce(Options.get("AllowPragmaOnce", false)),
+ HeaderDirs(utils::options::parseStringList(
+ Options.get("HeaderDirs", "include"))),
+ EndifComment(Options.get("EndifComment", false)),
+ Prefix(Options.get("Prefix", "")) {}
+
+std::string HeaderGuardCheck::getHeaderGuard(StringRef Filename,
+ StringRef OldGuard) {
+ std::string Guard = tooling::getAbsolutePath(Filename);
+
+ // When running under Windows, need to convert the path separators from
+ // `\` to `/`.
+ Guard = llvm::sys::path::convert_to_slash(Guard);
+
+ // consider all directories from HeaderDirs option. Stop at first found.
+ for (const StringRef HeaderDir : HeaderDirs) {
+ const size_t PosHeaderDir = Guard.rfind("/" + HeaderDir.str() + "/");
+ if (PosHeaderDir != StringRef::npos) {
+ // We don't want the header dir in our guards, i.e. _INCLUDE_
+ Guard = Guard.substr(PosHeaderDir + HeaderDir.size() + 2);
+ break; // stop at first found
----------------
vbvictor wrote:
What happens if we don't find any of Header dir in file? Can we add tests for it?
https://github.com/llvm/llvm-project/pull/177315
More information about the cfe-commits
mailing list