clang-tools 22.0.0git
AvoidPragmaOnceCheck.cpp
Go to the documentation of this file.
1//===--- AvoidPragmaOnceCheck.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
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
18class PragmaOnceCallbacks : public PPCallbacks {
19public:
20 PragmaOnceCallbacks(AvoidPragmaOnceCheck *Check, const SourceManager &SM)
21 : Check(Check), SM(SM) {}
22 void PragmaDirective(SourceLocation Loc,
23 PragmaIntroducerKind Introducer) override {
24 auto Str = llvm::StringRef(SM.getCharacterData(Loc));
25 if (!Str.consume_front("#"))
26 return;
27 Str = Str.trim();
28 if (!Str.consume_front("pragma"))
29 return;
30 Str = Str.trim();
31 if (Str.starts_with("once"))
32 Check->diag(Loc,
33 "avoid 'pragma once' directive; use include guards instead");
34 }
35
36private:
38 const SourceManager &SM;
39};
40
41void AvoidPragmaOnceCheck::registerPPCallbacks(const SourceManager &SM,
42 Preprocessor *PP,
43 Preprocessor *ModuleExpanderPP) {
44 PP->addPPCallbacks(std::make_unique<PragmaOnceCallbacks>(this, SM));
45}
46
47} // 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
void PragmaDirective(SourceLocation Loc, PragmaIntroducerKind Introducer) override
PragmaOnceCallbacks(AvoidPragmaOnceCheck *Check, const SourceManager &SM)