1 //===--- HeaderIncludes.cpp - Insert/Delete #includes --*- C++ -*----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "clang/Tooling/Inclusions/HeaderIncludes.h"
11 #include "clang/Basic/SourceManager.h"
12 #include "clang/Lex/Lexer.h"
13 #include "llvm/Support/FormatVariadic.h"
14 
15 namespace clang {
16 namespace tooling {
17 namespace {
18 
19 LangOptions createLangOpts() {
20   LangOptions LangOpts;
21   LangOpts.CPlusPlus = 1;
22   LangOpts.CPlusPlus11 = 1;
23   LangOpts.CPlusPlus14 = 1;
24   LangOpts.LineComment = 1;
25   LangOpts.CXXOperatorNames = 1;
26   LangOpts.Bool = 1;
27   LangOpts.ObjC1 = 1;
28   LangOpts.ObjC2 = 1;
29   LangOpts.MicrosoftExt = 1;    // To get kw___try, kw___finally.
30   LangOpts.DeclSpecKeyword = 1; // To get __declspec.
31   LangOpts.WChar = 1;           // To get wchar_t
32   return LangOpts;
33 }
34 
35 // Returns the offset after skipping a sequence of tokens, matched by \p
36 // GetOffsetAfterSequence, from the start of the code.
37 // \p GetOffsetAfterSequence should be a function that matches a sequence of
38 // tokens and returns an offset after the sequence.
39 unsigned getOffsetAfterTokenSequence(
40     StringRef FileName, StringRef Code, const IncludeStyle &Style,
41     llvm::function_ref<unsigned(const SourceManager &, Lexer &, Token &)>
42         GetOffsetAfterSequence) {
43   SourceManagerForFile VirtualSM(FileName, Code);
44   SourceManager &SM = VirtualSM.get();
45   Lexer Lex(SM.getMainFileID(), SM.getBuffer(SM.getMainFileID()), SM,
46             createLangOpts());
47   Token Tok;
48   // Get the first token.
49   Lex.LexFromRawLexer(Tok);
50   return GetOffsetAfterSequence(SM, Lex, Tok);
51 }
52 
53 // Check if a sequence of tokens is like "#<Name> <raw_identifier>". If it is,
54 // \p Tok will be the token after this directive; otherwise, it can be any token
55 // after the given \p Tok (including \p Tok).
56 bool checkAndConsumeDirectiveWithName(Lexer &Lex, StringRef Name, Token &Tok) {
57   bool Matched = Tok.is(tok::hash) && !Lex.LexFromRawLexer(Tok) &&
58                  Tok.is(tok::raw_identifier) &&
59                  Tok.getRawIdentifier() == Name && !Lex.LexFromRawLexer(Tok) &&
60                  Tok.is(tok::raw_identifier);
61   if (Matched)
62     Lex.LexFromRawLexer(Tok);
63   return Matched;
64 }
65 
66 void skipComments(Lexer &Lex, Token &Tok) {
67   while (Tok.is(tok::comment))
68     if (Lex.LexFromRawLexer(Tok))
69       return;
70 }
71 
72 // Returns the offset after header guard directives and any comments
73 // before/after header guards. If no header guard presents in the code, this
74 // will returns the offset after skipping all comments from the start of the
75 // code.
76 unsigned getOffsetAfterHeaderGuardsAndComments(StringRef FileName,
77                                                StringRef Code,
78                                                const IncludeStyle &Style) {
79   return getOffsetAfterTokenSequence(
80       FileName, Code, Style,
81       [](const SourceManager &SM, Lexer &Lex, Token Tok) {
82         skipComments(Lex, Tok);
83         unsigned InitialOffset = SM.getFileOffset(Tok.getLocation());
84         if (checkAndConsumeDirectiveWithName(Lex, "ifndef", Tok)) {
85           skipComments(Lex, Tok);
86           if (checkAndConsumeDirectiveWithName(Lex, "define", Tok))
87             return SM.getFileOffset(Tok.getLocation());
88         }
89         return InitialOffset;
90       });
91 }
92 
93 // Check if a sequence of tokens is like
94 //    "#include ("header.h" | <header.h>)".
95 // If it is, \p Tok will be the token after this directive; otherwise, it can be
96 // any token after the given \p Tok (including \p Tok).
97 bool checkAndConsumeInclusiveDirective(Lexer &Lex, Token &Tok) {
98   auto Matched = [&]() {
99     Lex.LexFromRawLexer(Tok);
100     return true;
101   };
102   if (Tok.is(tok::hash) && !Lex.LexFromRawLexer(Tok) &&
103       Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "include") {
104     if (Lex.LexFromRawLexer(Tok))
105       return false;
106     if (Tok.is(tok::string_literal))
107       return Matched();
108     if (Tok.is(tok::less)) {
109       while (!Lex.LexFromRawLexer(Tok) && Tok.isNot(tok::greater)) {
110       }
111       if (Tok.is(tok::greater))
112         return Matched();
113     }
114   }
115   return false;
116 }
117 
118 // Returns the offset of the last #include directive after which a new
119 // #include can be inserted. This ignores #include's after the #include block(s)
120 // in the beginning of a file to avoid inserting headers into code sections
121 // where new #include's should not be added by default.
122 // These code sections include:
123 //      - raw string literals (containing #include).
124 //      - #if blocks.
125 //      - Special #include's among declarations (e.g. functions).
126 //
127 // If no #include after which a new #include can be inserted, this returns the
128 // offset after skipping all comments from the start of the code.
129 // Inserting after an #include is not allowed if it comes after code that is not
130 // #include (e.g. pre-processing directive that is not #include, declarations).
131 unsigned getMaxHeaderInsertionOffset(StringRef FileName, StringRef Code,
132                                      const IncludeStyle &Style) {
133   return getOffsetAfterTokenSequence(
134       FileName, Code, Style,
135       [](const SourceManager &SM, Lexer &Lex, Token Tok) {
136         skipComments(Lex, Tok);
137         unsigned MaxOffset = SM.getFileOffset(Tok.getLocation());
138         while (checkAndConsumeInclusiveDirective(Lex, Tok))
139           MaxOffset = SM.getFileOffset(Tok.getLocation());
140         return MaxOffset;
141       });
142 }
143 
144 inline StringRef trimInclude(StringRef IncludeName) {
145   return IncludeName.trim("\"<>");
146 }
147 
148 const char IncludeRegexPattern[] =
149     R"(^[\t\ ]*#[\t\ ]*(import|include)[^"<]*(["<][^">]*[">]))";
150 
151 } // anonymous namespace
152 
153 IncludeCategoryManager::IncludeCategoryManager(const IncludeStyle &Style,
154                                                StringRef FileName)
155     : Style(Style), FileName(FileName) {
156   FileStem = llvm::sys::path::stem(FileName);
157   for (const auto &Category : Style.IncludeCategories)
158     CategoryRegexs.emplace_back(Category.Regex, llvm::Regex::IgnoreCase);
159   IsMainFile = FileName.endswith(".c") || FileName.endswith(".cc") ||
160                FileName.endswith(".cpp") || FileName.endswith(".c++") ||
161                FileName.endswith(".cxx") || FileName.endswith(".m") ||
162                FileName.endswith(".mm");
163 }
164 
165 int IncludeCategoryManager::getIncludePriority(StringRef IncludeName,
166                                                bool CheckMainHeader) const {
167   int Ret = INT_MAX;
168   for (unsigned i = 0, e = CategoryRegexs.size(); i != e; ++i)
169     if (CategoryRegexs[i].match(IncludeName)) {
170       Ret = Style.IncludeCategories[i].Priority;
171       break;
172     }
173   if (CheckMainHeader && IsMainFile && Ret > 0 && isMainHeader(IncludeName))
174     Ret = 0;
175   return Ret;
176 }
177 
178 bool IncludeCategoryManager::isMainHeader(StringRef IncludeName) const {
179   if (!IncludeName.startswith("\""))
180     return false;
181   StringRef HeaderStem =
182       llvm::sys::path::stem(IncludeName.drop_front(1).drop_back(1));
183   if (FileStem.startswith(HeaderStem) ||
184       FileStem.startswith_lower(HeaderStem)) {
185     llvm::Regex MainIncludeRegex(HeaderStem.str() + Style.IncludeIsMainRegex,
186                                  llvm::Regex::IgnoreCase);
187     if (MainIncludeRegex.match(FileStem))
188       return true;
189   }
190   return false;
191 }
192 
193 HeaderIncludes::HeaderIncludes(StringRef FileName, StringRef Code,
194                                const IncludeStyle &Style)
195     : FileName(FileName), Code(Code), FirstIncludeOffset(-1),
196       MinInsertOffset(
197           getOffsetAfterHeaderGuardsAndComments(FileName, Code, Style)),
198       MaxInsertOffset(MinInsertOffset +
199                       getMaxHeaderInsertionOffset(
200                           FileName, Code.drop_front(MinInsertOffset), Style)),
201       Categories(Style, FileName),
202       IncludeRegex(llvm::Regex(IncludeRegexPattern)) {
203   // Add 0 for main header and INT_MAX for headers that are not in any
204   // category.
205   Priorities = {0, INT_MAX};
206   for (const auto &Category : Style.IncludeCategories)
207     Priorities.insert(Category.Priority);
208   SmallVector<StringRef, 32> Lines;
209   Code.drop_front(MinInsertOffset).split(Lines, "\n");
210 
211   unsigned Offset = MinInsertOffset;
212   unsigned NextLineOffset;
213   SmallVector<StringRef, 4> Matches;
214   for (auto Line : Lines) {
215     NextLineOffset = std::min(Code.size(), Offset + Line.size() + 1);
216     if (IncludeRegex.match(Line, &Matches)) {
217       // If this is the last line without trailing newline, we need to make
218       // sure we don't delete across the file boundary.
219       addExistingInclude(
220           Include(Matches[2],
221                   tooling::Range(
222                       Offset, std::min(Line.size() + 1, Code.size() - Offset))),
223           NextLineOffset);
224     }
225     Offset = NextLineOffset;
226   }
227 
228   // Populate CategoryEndOfssets:
229   // - Ensure that CategoryEndOffset[Highest] is always populated.
230   // - If CategoryEndOffset[Priority] isn't set, use the next higher value
231   // that is set, up to CategoryEndOffset[Highest].
232   auto Highest = Priorities.begin();
233   if (CategoryEndOffsets.find(*Highest) == CategoryEndOffsets.end()) {
234     if (FirstIncludeOffset >= 0)
235       CategoryEndOffsets[*Highest] = FirstIncludeOffset;
236     else
237       CategoryEndOffsets[*Highest] = MinInsertOffset;
238   }
239   // By this point, CategoryEndOffset[Highest] is always set appropriately:
240   //  - to an appropriate location before/after existing #includes, or
241   //  - to right after the header guard, or
242   //  - to the beginning of the file.
243   for (auto I = ++Priorities.begin(), E = Priorities.end(); I != E; ++I)
244     if (CategoryEndOffsets.find(*I) == CategoryEndOffsets.end())
245       CategoryEndOffsets[*I] = CategoryEndOffsets[*std::prev(I)];
246 }
247 
248 // \p Offset: the start of the line following this include directive.
249 void HeaderIncludes::addExistingInclude(Include IncludeToAdd,
250                                         unsigned NextLineOffset) {
251   auto Iter =
252       ExistingIncludes.try_emplace(trimInclude(IncludeToAdd.Name)).first;
253   Iter->second.push_back(std::move(IncludeToAdd));
254   auto &CurInclude = Iter->second.back();
255   // The header name with quotes or angle brackets.
256   // Only record the offset of current #include if we can insert after it.
257   if (CurInclude.R.getOffset() <= MaxInsertOffset) {
258     int Priority = Categories.getIncludePriority(
259         CurInclude.Name, /*CheckMainHeader=*/FirstIncludeOffset < 0);
260     CategoryEndOffsets[Priority] = NextLineOffset;
261     IncludesByPriority[Priority].push_back(&CurInclude);
262     if (FirstIncludeOffset < 0)
263       FirstIncludeOffset = CurInclude.R.getOffset();
264   }
265 }
266 
267 llvm::Optional<tooling::Replacement>
268 HeaderIncludes::insert(llvm::StringRef IncludeName, bool IsAngled) const {
269   assert(IncludeName == trimInclude(IncludeName));
270   // If a <header> ("header") already exists in code, "header" (<header>) with
271   // different quotation will still be inserted.
272   // FIXME: figure out if this is the best behavior.
273   auto It = ExistingIncludes.find(IncludeName);
274   if (It != ExistingIncludes.end())
275     for (const auto &Inc : It->second)
276       if ((IsAngled && StringRef(Inc.Name).startswith("<")) ||
277           (!IsAngled && StringRef(Inc.Name).startswith("\"")))
278         return llvm::None;
279   std::string Quoted =
280       llvm::formatv(IsAngled ? "<{0}>" : "\"{0}\"", IncludeName);
281   StringRef QuotedName = Quoted;
282   int Priority = Categories.getIncludePriority(
283       QuotedName, /*CheckMainHeader=*/FirstIncludeOffset < 0);
284   auto CatOffset = CategoryEndOffsets.find(Priority);
285   assert(CatOffset != CategoryEndOffsets.end());
286   unsigned InsertOffset = CatOffset->second; // Fall back offset
287   auto Iter = IncludesByPriority.find(Priority);
288   if (Iter != IncludesByPriority.end()) {
289     for (const auto *Inc : Iter->second) {
290       if (QuotedName < Inc->Name) {
291         InsertOffset = Inc->R.getOffset();
292         break;
293       }
294     }
295   }
296   assert(InsertOffset <= Code.size());
297   std::string NewInclude = llvm::formatv("#include {0}\n", QuotedName);
298   // When inserting headers at end of the code, also append '\n' to the code
299   // if it does not end with '\n'.
300   // FIXME: when inserting multiple #includes at the end of code, only one
301   // newline should be added.
302   if (InsertOffset == Code.size() && (!Code.empty() && Code.back() != '\n'))
303     NewInclude = "\n" + NewInclude;
304   return tooling::Replacement(FileName, InsertOffset, 0, NewInclude);
305 }
306 
307 tooling::Replacements HeaderIncludes::remove(llvm::StringRef IncludeName,
308                                              bool IsAngled) const {
309   assert(IncludeName == trimInclude(IncludeName));
310   tooling::Replacements Result;
311   auto Iter = ExistingIncludes.find(IncludeName);
312   if (Iter == ExistingIncludes.end())
313     return Result;
314   for (const auto &Inc : Iter->second) {
315     if ((IsAngled && StringRef(Inc.Name).startswith("\"")) ||
316         (!IsAngled && StringRef(Inc.Name).startswith("<")))
317       continue;
318     llvm::Error Err = Result.add(tooling::Replacement(
319         FileName, Inc.R.getOffset(), Inc.R.getLength(), ""));
320     if (Err) {
321       auto ErrMsg = "Unexpected conflicts in #include deletions: " +
322                     llvm::toString(std::move(Err));
323       llvm_unreachable(ErrMsg.c_str());
324     }
325   }
326   return Result;
327 }
328 
329 
330 } // namespace tooling
331 } // namespace clang
332