1 //===--- HeaderIncludes.cpp - Insert/Delete #includes --*- C++ -*----------===//
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 "clang/Tooling/Inclusions/HeaderIncludes.h"
10 #include "clang/Basic/FileManager.h"
11 #include "clang/Basic/SourceManager.h"
12 #include "clang/Lex/Lexer.h"
13 #include "llvm/ADT/Optional.h"
14 #include "llvm/Support/FormatVariadic.h"
15 #include "llvm/Support/Path.h"
16 
17 namespace clang {
18 namespace tooling {
19 namespace {
20 
21 LangOptions createLangOpts() {
22   LangOptions LangOpts;
23   LangOpts.CPlusPlus = 1;
24   LangOpts.CPlusPlus11 = 1;
25   LangOpts.CPlusPlus14 = 1;
26   LangOpts.LineComment = 1;
27   LangOpts.CXXOperatorNames = 1;
28   LangOpts.Bool = 1;
29   LangOpts.ObjC = 1;
30   LangOpts.MicrosoftExt = 1;    // To get kw___try, kw___finally.
31   LangOpts.DeclSpecKeyword = 1; // To get __declspec.
32   LangOpts.WChar = 1;           // To get wchar_t
33   return LangOpts;
34 }
35 
36 // Returns the offset after skipping a sequence of tokens, matched by \p
37 // GetOffsetAfterSequence, from the start of the code.
38 // \p GetOffsetAfterSequence should be a function that matches a sequence of
39 // tokens and returns an offset after the sequence.
40 unsigned getOffsetAfterTokenSequence(
41     StringRef FileName, StringRef Code, const IncludeStyle &Style,
42     llvm::function_ref<unsigned(const SourceManager &, Lexer &, Token &)>
43         GetOffsetAfterSequence) {
44   SourceManagerForFile VirtualSM(FileName, Code);
45   SourceManager &SM = VirtualSM.get();
46   LangOptions LangOpts = createLangOpts();
47   Lexer Lex(SM.getMainFileID(), SM.getBufferOrFake(SM.getMainFileID()), SM,
48             LangOpts);
49   Token Tok;
50   // Get the first token.
51   Lex.LexFromRawLexer(Tok);
52   return GetOffsetAfterSequence(SM, Lex, Tok);
53 }
54 
55 // Check if a sequence of tokens is like "#<Name> <raw_identifier>". If it is,
56 // \p Tok will be the token after this directive; otherwise, it can be any token
57 // after the given \p Tok (including \p Tok). If \p RawIDName is provided, the
58 // (second) raw_identifier name is checked.
59 bool checkAndConsumeDirectiveWithName(
60     Lexer &Lex, StringRef Name, Token &Tok,
61     llvm::Optional<StringRef> RawIDName = llvm::None) {
62   bool Matched = Tok.is(tok::hash) && !Lex.LexFromRawLexer(Tok) &&
63                  Tok.is(tok::raw_identifier) &&
64                  Tok.getRawIdentifier() == Name && !Lex.LexFromRawLexer(Tok) &&
65                  Tok.is(tok::raw_identifier) &&
66                  (!RawIDName || Tok.getRawIdentifier() == *RawIDName);
67   if (Matched)
68     Lex.LexFromRawLexer(Tok);
69   return Matched;
70 }
71 
72 void skipComments(Lexer &Lex, Token &Tok) {
73   while (Tok.is(tok::comment))
74     if (Lex.LexFromRawLexer(Tok))
75       return;
76 }
77 
78 // Returns the offset after header guard directives and any comments
79 // before/after header guards (e.g. #ifndef/#define pair, #pragma once). If no
80 // header guard is present in the code, this will return the offset after
81 // skipping all comments from the start of the code.
82 unsigned getOffsetAfterHeaderGuardsAndComments(StringRef FileName,
83                                                StringRef Code,
84                                                const IncludeStyle &Style) {
85   // \p Consume returns location after header guard or 0 if no header guard is
86   // found.
87   auto ConsumeHeaderGuardAndComment =
88       [&](std::function<unsigned(const SourceManager &SM, Lexer &Lex,
89                                  Token Tok)>
90               Consume) {
91         return getOffsetAfterTokenSequence(
92             FileName, Code, Style,
93             [&Consume](const SourceManager &SM, Lexer &Lex, Token Tok) {
94               skipComments(Lex, Tok);
95               unsigned InitialOffset = SM.getFileOffset(Tok.getLocation());
96               return std::max(InitialOffset, Consume(SM, Lex, Tok));
97             });
98       };
99   return std::max(
100       // #ifndef/#define
101       ConsumeHeaderGuardAndComment(
102           [](const SourceManager &SM, Lexer &Lex, Token Tok) -> unsigned {
103             if (checkAndConsumeDirectiveWithName(Lex, "ifndef", Tok)) {
104               skipComments(Lex, Tok);
105               if (checkAndConsumeDirectiveWithName(Lex, "define", Tok) &&
106                   Tok.isAtStartOfLine())
107                 return SM.getFileOffset(Tok.getLocation());
108             }
109             return 0;
110           }),
111       // #pragma once
112       ConsumeHeaderGuardAndComment(
113           [](const SourceManager &SM, Lexer &Lex, Token Tok) -> unsigned {
114             if (checkAndConsumeDirectiveWithName(Lex, "pragma", Tok,
115                                                  StringRef("once")))
116               return SM.getFileOffset(Tok.getLocation());
117             return 0;
118           }));
119 }
120 
121 // Check if a sequence of tokens is like
122 //    "#include ("header.h" | <header.h>)".
123 // If it is, \p Tok will be the token after this directive; otherwise, it can be
124 // any token after the given \p Tok (including \p Tok).
125 bool checkAndConsumeInclusiveDirective(Lexer &Lex, Token &Tok) {
126   auto Matched = [&]() {
127     Lex.LexFromRawLexer(Tok);
128     return true;
129   };
130   if (Tok.is(tok::hash) && !Lex.LexFromRawLexer(Tok) &&
131       Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "include") {
132     if (Lex.LexFromRawLexer(Tok))
133       return false;
134     if (Tok.is(tok::string_literal))
135       return Matched();
136     if (Tok.is(tok::less)) {
137       while (!Lex.LexFromRawLexer(Tok) && Tok.isNot(tok::greater)) {
138       }
139       if (Tok.is(tok::greater))
140         return Matched();
141     }
142   }
143   return false;
144 }
145 
146 // Returns the offset of the last #include directive after which a new
147 // #include can be inserted. This ignores #include's after the #include block(s)
148 // in the beginning of a file to avoid inserting headers into code sections
149 // where new #include's should not be added by default.
150 // These code sections include:
151 //      - raw string literals (containing #include).
152 //      - #if blocks.
153 //      - Special #include's among declarations (e.g. functions).
154 //
155 // If no #include after which a new #include can be inserted, this returns the
156 // offset after skipping all comments from the start of the code.
157 // Inserting after an #include is not allowed if it comes after code that is not
158 // #include (e.g. pre-processing directive that is not #include, declarations).
159 unsigned getMaxHeaderInsertionOffset(StringRef FileName, StringRef Code,
160                                      const IncludeStyle &Style) {
161   return getOffsetAfterTokenSequence(
162       FileName, Code, Style,
163       [](const SourceManager &SM, Lexer &Lex, Token Tok) {
164         skipComments(Lex, Tok);
165         unsigned MaxOffset = SM.getFileOffset(Tok.getLocation());
166         while (checkAndConsumeInclusiveDirective(Lex, Tok))
167           MaxOffset = SM.getFileOffset(Tok.getLocation());
168         return MaxOffset;
169       });
170 }
171 
172 // The filename of Path excluding extension.
173 // Used to match implementation with headers, this differs from sys::path::stem:
174 //  - in names with multiple dots (foo.cu.cc) it terminates at the *first*
175 //  - an empty stem is never returned: /foo/.bar.x => .bar
176 //  - we don't bother to handle . and .. specially
177 StringRef matchingStem(llvm::StringRef Path) {
178   StringRef Name = llvm::sys::path::filename(Path);
179   return Name.substr(0, Name.find('.', 1));
180 }
181 
182 } // anonymous namespace
183 
184 IncludeCategoryManager::IncludeCategoryManager(const IncludeStyle &Style,
185                                                StringRef FileName)
186     : Style(Style), FileName(FileName) {
187   for (const auto &Category : Style.IncludeCategories) {
188     CategoryRegexs.emplace_back(Category.Regex, Category.RegexIsCaseSensitive
189                                                     ? llvm::Regex::NoFlags
190                                                     : llvm::Regex::IgnoreCase);
191   }
192   IsMainFile = FileName.endswith(".c") || FileName.endswith(".cc") ||
193                FileName.endswith(".cpp") || FileName.endswith(".c++") ||
194                FileName.endswith(".cxx") || FileName.endswith(".m") ||
195                FileName.endswith(".mm");
196   if (!Style.IncludeIsMainSourceRegex.empty()) {
197     llvm::Regex MainFileRegex(Style.IncludeIsMainSourceRegex);
198     IsMainFile |= MainFileRegex.match(FileName);
199   }
200 }
201 
202 int IncludeCategoryManager::getIncludePriority(StringRef IncludeName,
203                                                bool CheckMainHeader) const {
204   int Ret = INT_MAX;
205   for (unsigned i = 0, e = CategoryRegexs.size(); i != e; ++i)
206     if (CategoryRegexs[i].match(IncludeName)) {
207       Ret = Style.IncludeCategories[i].Priority;
208       break;
209     }
210   if (CheckMainHeader && IsMainFile && Ret > 0 && isMainHeader(IncludeName))
211     Ret = 0;
212   return Ret;
213 }
214 
215 int IncludeCategoryManager::getSortIncludePriority(StringRef IncludeName,
216                                                    bool CheckMainHeader) const {
217   int Ret = INT_MAX;
218   for (unsigned i = 0, e = CategoryRegexs.size(); i != e; ++i)
219     if (CategoryRegexs[i].match(IncludeName)) {
220       Ret = Style.IncludeCategories[i].SortPriority;
221       if (Ret == 0)
222         Ret = Style.IncludeCategories[i].Priority;
223       break;
224     }
225   if (CheckMainHeader && IsMainFile && Ret > 0 && isMainHeader(IncludeName))
226     Ret = 0;
227   return Ret;
228 }
229 bool IncludeCategoryManager::isMainHeader(StringRef IncludeName) const {
230   if (!IncludeName.startswith("\""))
231     return false;
232 
233   IncludeName =
234       IncludeName.drop_front(1).drop_back(1); // remove the surrounding "" or <>
235   // Not matchingStem: implementation files may have compound extensions but
236   // headers may not.
237   StringRef HeaderStem = llvm::sys::path::stem(IncludeName);
238   StringRef FileStem = llvm::sys::path::stem(FileName); // foo.cu for foo.cu.cc
239   StringRef MatchingFileStem = matchingStem(FileName);  // foo for foo.cu.cc
240   // main-header examples:
241   //  1) foo.h => foo.cc
242   //  2) foo.h => foo.cu.cc
243   //  3) foo.proto.h => foo.proto.cc
244   //
245   // non-main-header examples:
246   //  1) foo.h => bar.cc
247   //  2) foo.proto.h => foo.cc
248   StringRef Matching;
249   if (MatchingFileStem.startswith_insensitive(HeaderStem))
250     Matching = MatchingFileStem; // example 1), 2)
251   else if (FileStem.equals_insensitive(HeaderStem))
252     Matching = FileStem; // example 3)
253   if (!Matching.empty()) {
254     llvm::Regex MainIncludeRegex(HeaderStem.str() + Style.IncludeIsMainRegex,
255                                  llvm::Regex::IgnoreCase);
256     if (MainIncludeRegex.match(Matching))
257       return true;
258   }
259   return false;
260 }
261 
262 HeaderIncludes::HeaderIncludes(StringRef FileName, StringRef Code,
263                                const IncludeStyle &Style)
264     : FileName(FileName), Code(Code), FirstIncludeOffset(-1),
265       MinInsertOffset(
266           getOffsetAfterHeaderGuardsAndComments(FileName, Code, Style)),
267       MaxInsertOffset(MinInsertOffset +
268                       getMaxHeaderInsertionOffset(
269                           FileName, Code.drop_front(MinInsertOffset), Style)),
270       Categories(Style, FileName), IncludeRegex(getCppIncludeRegex()) {
271   // Add 0 for main header and INT_MAX for headers that are not in any
272   // category.
273   Priorities = {0, INT_MAX};
274   for (const auto &Category : Style.IncludeCategories)
275     Priorities.insert(Category.Priority);
276   SmallVector<StringRef, 32> Lines;
277   Code.drop_front(MinInsertOffset).split(Lines, "\n");
278 
279   unsigned Offset = MinInsertOffset;
280   unsigned NextLineOffset;
281   SmallVector<StringRef, 4> Matches;
282   for (auto Line : Lines) {
283     NextLineOffset = std::min(Code.size(), Offset + Line.size() + 1);
284     if (IncludeRegex.match(Line, &Matches)) {
285       StringRef IncludeName = tooling::getIncludeNameFromMatches(Matches);
286       // If this is the last line without trailing newline, we need to make
287       // sure we don't delete across the file boundary.
288       addExistingInclude(
289           Include(IncludeName,
290                   tooling::Range(
291                       Offset, std::min(Line.size() + 1, Code.size() - Offset))),
292           NextLineOffset);
293     }
294     Offset = NextLineOffset;
295   }
296 
297   // Populate CategoryEndOfssets:
298   // - Ensure that CategoryEndOffset[Highest] is always populated.
299   // - If CategoryEndOffset[Priority] isn't set, use the next higher value
300   // that is set, up to CategoryEndOffset[Highest].
301   auto Highest = Priorities.begin();
302   if (CategoryEndOffsets.find(*Highest) == CategoryEndOffsets.end()) {
303     if (FirstIncludeOffset >= 0)
304       CategoryEndOffsets[*Highest] = FirstIncludeOffset;
305     else
306       CategoryEndOffsets[*Highest] = MinInsertOffset;
307   }
308   // By this point, CategoryEndOffset[Highest] is always set appropriately:
309   //  - to an appropriate location before/after existing #includes, or
310   //  - to right after the header guard, or
311   //  - to the beginning of the file.
312   for (auto I = ++Priorities.begin(), E = Priorities.end(); I != E; ++I)
313     if (CategoryEndOffsets.find(*I) == CategoryEndOffsets.end())
314       CategoryEndOffsets[*I] = CategoryEndOffsets[*std::prev(I)];
315 }
316 
317 // \p Offset: the start of the line following this include directive.
318 void HeaderIncludes::addExistingInclude(Include IncludeToAdd,
319                                         unsigned NextLineOffset) {
320   auto Iter =
321       ExistingIncludes.try_emplace(trimInclude(IncludeToAdd.Name)).first;
322   Iter->second.push_back(std::move(IncludeToAdd));
323   auto &CurInclude = Iter->second.back();
324   // The header name with quotes or angle brackets.
325   // Only record the offset of current #include if we can insert after it.
326   if (CurInclude.R.getOffset() <= MaxInsertOffset) {
327     int Priority = Categories.getIncludePriority(
328         CurInclude.Name, /*CheckMainHeader=*/FirstIncludeOffset < 0);
329     CategoryEndOffsets[Priority] = NextLineOffset;
330     IncludesByPriority[Priority].push_back(&CurInclude);
331     if (FirstIncludeOffset < 0)
332       FirstIncludeOffset = CurInclude.R.getOffset();
333   }
334 }
335 
336 llvm::Optional<tooling::Replacement>
337 HeaderIncludes::insert(llvm::StringRef IncludeName, bool IsAngled) const {
338   assert(IncludeName == trimInclude(IncludeName));
339   // If a <header> ("header") already exists in code, "header" (<header>) with
340   // different quotation will still be inserted.
341   // FIXME: figure out if this is the best behavior.
342   auto It = ExistingIncludes.find(IncludeName);
343   if (It != ExistingIncludes.end())
344     for (const auto &Inc : It->second)
345       if ((IsAngled && StringRef(Inc.Name).startswith("<")) ||
346           (!IsAngled && StringRef(Inc.Name).startswith("\"")))
347         return llvm::None;
348   std::string Quoted =
349       std::string(llvm::formatv(IsAngled ? "<{0}>" : "\"{0}\"", IncludeName));
350   StringRef QuotedName = Quoted;
351   int Priority = Categories.getIncludePriority(
352       QuotedName, /*CheckMainHeader=*/FirstIncludeOffset < 0);
353   auto CatOffset = CategoryEndOffsets.find(Priority);
354   assert(CatOffset != CategoryEndOffsets.end());
355   unsigned InsertOffset = CatOffset->second; // Fall back offset
356   auto Iter = IncludesByPriority.find(Priority);
357   if (Iter != IncludesByPriority.end()) {
358     for (const auto *Inc : Iter->second) {
359       if (QuotedName < Inc->Name) {
360         InsertOffset = Inc->R.getOffset();
361         break;
362       }
363     }
364   }
365   assert(InsertOffset <= Code.size());
366   std::string NewInclude =
367       std::string(llvm::formatv("#include {0}\n", QuotedName));
368   // When inserting headers at end of the code, also append '\n' to the code
369   // if it does not end with '\n'.
370   // FIXME: when inserting multiple #includes at the end of code, only one
371   // newline should be added.
372   if (InsertOffset == Code.size() && (!Code.empty() && Code.back() != '\n'))
373     NewInclude = "\n" + NewInclude;
374   return tooling::Replacement(FileName, InsertOffset, 0, NewInclude);
375 }
376 
377 tooling::Replacements HeaderIncludes::remove(llvm::StringRef IncludeName,
378                                              bool IsAngled) const {
379   assert(IncludeName == trimInclude(IncludeName));
380   tooling::Replacements Result;
381   auto Iter = ExistingIncludes.find(IncludeName);
382   if (Iter == ExistingIncludes.end())
383     return Result;
384   for (const auto &Inc : Iter->second) {
385     if ((IsAngled && StringRef(Inc.Name).startswith("\"")) ||
386         (!IsAngled && StringRef(Inc.Name).startswith("<")))
387       continue;
388     llvm::Error Err = Result.add(tooling::Replacement(
389         FileName, Inc.R.getOffset(), Inc.R.getLength(), ""));
390     if (Err) {
391       auto ErrMsg = "Unexpected conflicts in #include deletions: " +
392                     llvm::toString(std::move(Err));
393       llvm_unreachable(ErrMsg.c_str());
394     }
395   }
396   return Result;
397 }
398 
399 llvm::Regex getCppIncludeRegex() {
400   static const char CppIncludeRegexPattern[] =
401       R"(^[\t\ ]*[@#][\t\ ]*(import|include)([^"]*("[^"]+")|[^<]*(<[^>]+>)|[\t\ ]*([^;]+;)))";
402   return llvm::Regex(CppIncludeRegexPattern);
403 }
404 
405 llvm::StringRef getIncludeNameFromMatches(
406     const llvm::SmallVectorImpl<llvm::StringRef> &Matches) {
407   for (auto Match : llvm::reverse(Matches)) {
408     if (!Match.empty())
409       return Match;
410   }
411   llvm_unreachable("No non-empty match group found in list of matches");
412   return llvm::StringRef();
413 }
414 
415 llvm::StringRef trimInclude(llvm::StringRef IncludeName) {
416   return IncludeName.trim("\"<>;");
417 }
418 
419 } // namespace tooling
420 } // namespace clang
421