aboutsummaryrefslogtreecommitdiff
path: root/clang-tools-extra/clang-tidy/misc/HeaderIncludeCycleCheck.cpp
blob: 1f6ceda9f5b9e5058366c4f84789adf6e66c5081 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
//===--- HeaderIncludeCycleCheck.cpp - clang-tidy -------------------------===//
//
// 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 "HeaderIncludeCycleCheck.h"
#include "../utils/OptionsUtils.h"
#include "clang/AST/ASTContext.h"
#include "clang/Lex/PPCallbacks.h"
#include "clang/Lex/Preprocessor.h"
#include "llvm/Support/Regex.h"
#include <algorithm>
#include <optional>
#include <vector>

using namespace clang::ast_matchers;

namespace clang::tidy::misc {

namespace {

struct Include {
  const FileEntry *File;
  StringRef Name;
  SourceLocation Loc;
};

class CyclicDependencyCallbacks : public PPCallbacks {
public:
  CyclicDependencyCallbacks(HeaderIncludeCycleCheck &Check,
                            const SourceManager &SM,
                            const std::vector<StringRef> &IgnoredFilesList)
      : Check(Check), SM(SM) {
    IgnoredFilesRegexes.reserve(IgnoredFilesList.size());
    for (const StringRef &It : IgnoredFilesList) {
      if (!It.empty())
        IgnoredFilesRegexes.emplace_back(It);
    }
  }

  void FileChanged(SourceLocation Loc, FileChangeReason Reason,
                   SrcMgr::CharacteristicKind FileType,
                   FileID PrevFID) override {
    if (FileType != clang::SrcMgr::C_User)
      return;

    if (Reason != EnterFile && Reason != ExitFile)
      return;

    const FileID Id = SM.getFileID(Loc);
    if (Id.isInvalid())
      return;

    const FileEntry *NewFile = SM.getFileEntryForID(Id);
    const FileEntry *PrevFile = SM.getFileEntryForID(PrevFID);

    if (Reason == ExitFile) {
      if ((Files.size() > 1U) && (Files.back().File == PrevFile) &&
          (Files[Files.size() - 2U].File == NewFile))
        Files.pop_back();
      return;
    }

    if (!Files.empty() && Files.back().File == NewFile)
      return;

    const std::optional<StringRef> FilePath = SM.getNonBuiltinFilenameForID(Id);
    const StringRef FileName =
        FilePath ? llvm::sys::path::filename(*FilePath) : StringRef();
    Files.push_back({NewFile, FileName, std::exchange(NextToEnter, {})});
  }

  void InclusionDirective(SourceLocation, const Token &, StringRef FilePath,
                          bool, CharSourceRange Range,
                          OptionalFileEntryRef File, StringRef, StringRef,
                          const Module *, bool,
                          SrcMgr::CharacteristicKind FileType) override {
    if (FileType != clang::SrcMgr::C_User)
      return;

    NextToEnter = Range.getBegin();

    if (!File)
      return;

    checkForDoubleInclude(&File->getFileEntry(),
                          llvm::sys::path::filename(FilePath),
                          Range.getBegin());
  }

  void checkForDoubleInclude(const FileEntry *File, StringRef FileName,
                             SourceLocation Loc) {
    const auto It =
        llvm::find_if(llvm::reverse(Files),
                      [&](const Include &Entry) { return Entry.File == File; });
    if (It == Files.rend())
      return;

    const StringRef FilePath = File->tryGetRealPathName();
    if (FilePath.empty() || isFileIgnored(FilePath))
      return;

    if (It == Files.rbegin()) {
      Check.diag(Loc, "direct self-inclusion of header file '%0'") << FileName;
      return;
    }

    Check.diag(Loc, "circular header file dependency detected while including "
                    "'%0', please check the include path")
        << FileName;

    const bool IsIncludePathValid =
        std::all_of(Files.rbegin(), It + 1, [](const Include &Elem) {
          return !Elem.Name.empty() && Elem.Loc.isValid();
        });
    if (!IsIncludePathValid)
      return;

    for (const Include &I : llvm::make_range(Files.rbegin(), It + 1))
      Check.diag(I.Loc, "'%0' included from here", DiagnosticIDs::Note)
          << I.Name;
  }

  bool isFileIgnored(StringRef FileName) const {
    return llvm::any_of(IgnoredFilesRegexes, [&](const llvm::Regex &It) {
      return It.match(FileName);
    });
  }

#ifndef NDEBUG
  void EndOfMainFile() override {
    if (!Files.empty() &&
        Files.back().File == SM.getFileEntryForID(SM.getMainFileID()))
      Files.pop_back();

    assert(Files.empty());
  }
#endif

private:
  std::vector<Include> Files;
  SourceLocation NextToEnter;
  HeaderIncludeCycleCheck &Check;
  const SourceManager &SM;
  std::vector<llvm::Regex> IgnoredFilesRegexes;
};

} // namespace

HeaderIncludeCycleCheck::HeaderIncludeCycleCheck(StringRef Name,
                                                 ClangTidyContext *Context)
    : ClangTidyCheck(Name, Context),
      IgnoredFilesList(utils::options::parseStringList(
          Options.get("IgnoredFilesList", ""))) {}

void HeaderIncludeCycleCheck::registerPPCallbacks(
    const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) {
  PP->addPPCallbacks(
      std::make_unique<CyclicDependencyCallbacks>(*this, SM, IgnoredFilesList));
}

void HeaderIncludeCycleCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
  Options.store(Opts, "IgnoredFilesList",
                utils::options::serializeStringList(IgnoredFilesList));
}

} // namespace clang::tidy::misc