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