clang-tools 22.0.0git
AvoidPragmaOnceCheck.cpp
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
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
10
11#include "clang/Basic/SourceManager.h"
12#include "clang/Lex/PPCallbacks.h"
13#include "clang/Lex/Preprocessor.h"
14#include "llvm/ADT/StringRef.h"
15
17
18namespace {
19
20class PragmaOnceCallbacks : public PPCallbacks {
21public:
22 PragmaOnceCallbacks(AvoidPragmaOnceCheck *Check, const SourceManager &SM)
23 : Check(Check), SM(SM) {}
24 void PragmaDirective(SourceLocation Loc,
25 PragmaIntroducerKind Introducer) override {
26 auto Str = llvm::StringRef(SM.getCharacterData(Loc));
27 if (!Str.consume_front("#"))
28 return;
29 Str = Str.trim();
30 if (!Str.consume_front("pragma"))
31 return;
32 Str = Str.trim();
33 if (Str.starts_with("once"))
34 Check->diag(Loc,
35 "avoid 'pragma once' directive; use include guards instead");
36 }
37
38private:
40 const SourceManager &SM;
41};
42
43} // namespace
44
45void AvoidPragmaOnceCheck::registerPPCallbacks(const SourceManager &SM,
46 Preprocessor *PP,
47 Preprocessor *ModuleExpanderPP) {
48 PP->addPPCallbacks(std::make_unique<PragmaOnceCallbacks>(this, SM));
49}
50
51} // namespace clang::tidy::portability
Finds uses of #pragma once and suggests replacing them with standard / include guards (#ifndef/#defin...
void registerPPCallbacks(const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) override