|
| 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 | + |
| 9 | +#include "AvoidPragmaOnceCheck.h" |
| 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 | + |
| 16 | +namespace clang::tidy::portability { |
| 17 | + |
| 18 | +class PragmaOnceCallbacks : public PPCallbacks { |
| 19 | +public: |
| 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 | + |
| 36 | +private: |
| 37 | + AvoidPragmaOnceCheck *Check; |
| 38 | + const SourceManager &SM; |
| 39 | +}; |
| 40 | + |
| 41 | +void 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 |
0 commit comments