xref: /freebsd/contrib/llvm-project/clang/lib/Tooling/Inclusions/HeaderIncludes.cpp (revision e8d8bef961a50d4dc22501cde4fb9fb0be1b2532)
10b57cec5SDimitry Andric //===--- HeaderIncludes.cpp - Insert/Delete #includes --*- C++ -*----------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric 
90b57cec5SDimitry Andric #include "clang/Tooling/Inclusions/HeaderIncludes.h"
105ffd83dbSDimitry Andric #include "clang/Basic/FileManager.h"
110b57cec5SDimitry Andric #include "clang/Basic/SourceManager.h"
120b57cec5SDimitry Andric #include "clang/Lex/Lexer.h"
130b57cec5SDimitry Andric #include "llvm/ADT/Optional.h"
140b57cec5SDimitry Andric #include "llvm/Support/FormatVariadic.h"
15*e8d8bef9SDimitry Andric #include "llvm/Support/Path.h"
160b57cec5SDimitry Andric 
170b57cec5SDimitry Andric namespace clang {
180b57cec5SDimitry Andric namespace tooling {
190b57cec5SDimitry Andric namespace {
200b57cec5SDimitry Andric 
210b57cec5SDimitry Andric LangOptions createLangOpts() {
220b57cec5SDimitry Andric   LangOptions LangOpts;
230b57cec5SDimitry Andric   LangOpts.CPlusPlus = 1;
240b57cec5SDimitry Andric   LangOpts.CPlusPlus11 = 1;
250b57cec5SDimitry Andric   LangOpts.CPlusPlus14 = 1;
260b57cec5SDimitry Andric   LangOpts.LineComment = 1;
270b57cec5SDimitry Andric   LangOpts.CXXOperatorNames = 1;
280b57cec5SDimitry Andric   LangOpts.Bool = 1;
290b57cec5SDimitry Andric   LangOpts.ObjC = 1;
300b57cec5SDimitry Andric   LangOpts.MicrosoftExt = 1;    // To get kw___try, kw___finally.
310b57cec5SDimitry Andric   LangOpts.DeclSpecKeyword = 1; // To get __declspec.
320b57cec5SDimitry Andric   LangOpts.WChar = 1;           // To get wchar_t
330b57cec5SDimitry Andric   return LangOpts;
340b57cec5SDimitry Andric }
350b57cec5SDimitry Andric 
360b57cec5SDimitry Andric // Returns the offset after skipping a sequence of tokens, matched by \p
370b57cec5SDimitry Andric // GetOffsetAfterSequence, from the start of the code.
380b57cec5SDimitry Andric // \p GetOffsetAfterSequence should be a function that matches a sequence of
390b57cec5SDimitry Andric // tokens and returns an offset after the sequence.
400b57cec5SDimitry Andric unsigned getOffsetAfterTokenSequence(
410b57cec5SDimitry Andric     StringRef FileName, StringRef Code, const IncludeStyle &Style,
420b57cec5SDimitry Andric     llvm::function_ref<unsigned(const SourceManager &, Lexer &, Token &)>
430b57cec5SDimitry Andric         GetOffsetAfterSequence) {
440b57cec5SDimitry Andric   SourceManagerForFile VirtualSM(FileName, Code);
450b57cec5SDimitry Andric   SourceManager &SM = VirtualSM.get();
46*e8d8bef9SDimitry Andric   Lexer Lex(SM.getMainFileID(), SM.getBufferOrFake(SM.getMainFileID()), SM,
470b57cec5SDimitry Andric             createLangOpts());
480b57cec5SDimitry Andric   Token Tok;
490b57cec5SDimitry Andric   // Get the first token.
500b57cec5SDimitry Andric   Lex.LexFromRawLexer(Tok);
510b57cec5SDimitry Andric   return GetOffsetAfterSequence(SM, Lex, Tok);
520b57cec5SDimitry Andric }
530b57cec5SDimitry Andric 
540b57cec5SDimitry Andric // Check if a sequence of tokens is like "#<Name> <raw_identifier>". If it is,
550b57cec5SDimitry Andric // \p Tok will be the token after this directive; otherwise, it can be any token
560b57cec5SDimitry Andric // after the given \p Tok (including \p Tok). If \p RawIDName is provided, the
570b57cec5SDimitry Andric // (second) raw_identifier name is checked.
580b57cec5SDimitry Andric bool checkAndConsumeDirectiveWithName(
590b57cec5SDimitry Andric     Lexer &Lex, StringRef Name, Token &Tok,
600b57cec5SDimitry Andric     llvm::Optional<StringRef> RawIDName = llvm::None) {
610b57cec5SDimitry Andric   bool Matched = Tok.is(tok::hash) && !Lex.LexFromRawLexer(Tok) &&
620b57cec5SDimitry Andric                  Tok.is(tok::raw_identifier) &&
630b57cec5SDimitry Andric                  Tok.getRawIdentifier() == Name && !Lex.LexFromRawLexer(Tok) &&
640b57cec5SDimitry Andric                  Tok.is(tok::raw_identifier) &&
650b57cec5SDimitry Andric                  (!RawIDName || Tok.getRawIdentifier() == *RawIDName);
660b57cec5SDimitry Andric   if (Matched)
670b57cec5SDimitry Andric     Lex.LexFromRawLexer(Tok);
680b57cec5SDimitry Andric   return Matched;
690b57cec5SDimitry Andric }
700b57cec5SDimitry Andric 
710b57cec5SDimitry Andric void skipComments(Lexer &Lex, Token &Tok) {
720b57cec5SDimitry Andric   while (Tok.is(tok::comment))
730b57cec5SDimitry Andric     if (Lex.LexFromRawLexer(Tok))
740b57cec5SDimitry Andric       return;
750b57cec5SDimitry Andric }
760b57cec5SDimitry Andric 
770b57cec5SDimitry Andric // Returns the offset after header guard directives and any comments
780b57cec5SDimitry Andric // before/after header guards (e.g. #ifndef/#define pair, #pragma once). If no
790b57cec5SDimitry Andric // header guard is present in the code, this will return the offset after
800b57cec5SDimitry Andric // skipping all comments from the start of the code.
810b57cec5SDimitry Andric unsigned getOffsetAfterHeaderGuardsAndComments(StringRef FileName,
820b57cec5SDimitry Andric                                                StringRef Code,
830b57cec5SDimitry Andric                                                const IncludeStyle &Style) {
840b57cec5SDimitry Andric   // \p Consume returns location after header guard or 0 if no header guard is
850b57cec5SDimitry Andric   // found.
860b57cec5SDimitry Andric   auto ConsumeHeaderGuardAndComment =
870b57cec5SDimitry Andric       [&](std::function<unsigned(const SourceManager &SM, Lexer &Lex,
880b57cec5SDimitry Andric                                  Token Tok)>
890b57cec5SDimitry Andric               Consume) {
900b57cec5SDimitry Andric         return getOffsetAfterTokenSequence(
910b57cec5SDimitry Andric             FileName, Code, Style,
920b57cec5SDimitry Andric             [&Consume](const SourceManager &SM, Lexer &Lex, Token Tok) {
930b57cec5SDimitry Andric               skipComments(Lex, Tok);
940b57cec5SDimitry Andric               unsigned InitialOffset = SM.getFileOffset(Tok.getLocation());
950b57cec5SDimitry Andric               return std::max(InitialOffset, Consume(SM, Lex, Tok));
960b57cec5SDimitry Andric             });
970b57cec5SDimitry Andric       };
980b57cec5SDimitry Andric   return std::max(
990b57cec5SDimitry Andric       // #ifndef/#define
1000b57cec5SDimitry Andric       ConsumeHeaderGuardAndComment(
1010b57cec5SDimitry Andric           [](const SourceManager &SM, Lexer &Lex, Token Tok) -> unsigned {
1020b57cec5SDimitry Andric             if (checkAndConsumeDirectiveWithName(Lex, "ifndef", Tok)) {
1030b57cec5SDimitry Andric               skipComments(Lex, Tok);
104*e8d8bef9SDimitry Andric               if (checkAndConsumeDirectiveWithName(Lex, "define", Tok) &&
105*e8d8bef9SDimitry Andric                   Tok.isAtStartOfLine())
1060b57cec5SDimitry Andric                 return SM.getFileOffset(Tok.getLocation());
1070b57cec5SDimitry Andric             }
1080b57cec5SDimitry Andric             return 0;
1090b57cec5SDimitry Andric           }),
1100b57cec5SDimitry Andric       // #pragma once
1110b57cec5SDimitry Andric       ConsumeHeaderGuardAndComment(
1120b57cec5SDimitry Andric           [](const SourceManager &SM, Lexer &Lex, Token Tok) -> unsigned {
1130b57cec5SDimitry Andric             if (checkAndConsumeDirectiveWithName(Lex, "pragma", Tok,
1140b57cec5SDimitry Andric                                                  StringRef("once")))
1150b57cec5SDimitry Andric               return SM.getFileOffset(Tok.getLocation());
1160b57cec5SDimitry Andric             return 0;
1170b57cec5SDimitry Andric           }));
1180b57cec5SDimitry Andric }
1190b57cec5SDimitry Andric 
1200b57cec5SDimitry Andric // Check if a sequence of tokens is like
1210b57cec5SDimitry Andric //    "#include ("header.h" | <header.h>)".
1220b57cec5SDimitry Andric // If it is, \p Tok will be the token after this directive; otherwise, it can be
1230b57cec5SDimitry Andric // any token after the given \p Tok (including \p Tok).
1240b57cec5SDimitry Andric bool checkAndConsumeInclusiveDirective(Lexer &Lex, Token &Tok) {
1250b57cec5SDimitry Andric   auto Matched = [&]() {
1260b57cec5SDimitry Andric     Lex.LexFromRawLexer(Tok);
1270b57cec5SDimitry Andric     return true;
1280b57cec5SDimitry Andric   };
1290b57cec5SDimitry Andric   if (Tok.is(tok::hash) && !Lex.LexFromRawLexer(Tok) &&
1300b57cec5SDimitry Andric       Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "include") {
1310b57cec5SDimitry Andric     if (Lex.LexFromRawLexer(Tok))
1320b57cec5SDimitry Andric       return false;
1330b57cec5SDimitry Andric     if (Tok.is(tok::string_literal))
1340b57cec5SDimitry Andric       return Matched();
1350b57cec5SDimitry Andric     if (Tok.is(tok::less)) {
1360b57cec5SDimitry Andric       while (!Lex.LexFromRawLexer(Tok) && Tok.isNot(tok::greater)) {
1370b57cec5SDimitry Andric       }
1380b57cec5SDimitry Andric       if (Tok.is(tok::greater))
1390b57cec5SDimitry Andric         return Matched();
1400b57cec5SDimitry Andric     }
1410b57cec5SDimitry Andric   }
1420b57cec5SDimitry Andric   return false;
1430b57cec5SDimitry Andric }
1440b57cec5SDimitry Andric 
1450b57cec5SDimitry Andric // Returns the offset of the last #include directive after which a new
1460b57cec5SDimitry Andric // #include can be inserted. This ignores #include's after the #include block(s)
1470b57cec5SDimitry Andric // in the beginning of a file to avoid inserting headers into code sections
1480b57cec5SDimitry Andric // where new #include's should not be added by default.
1490b57cec5SDimitry Andric // These code sections include:
1500b57cec5SDimitry Andric //      - raw string literals (containing #include).
1510b57cec5SDimitry Andric //      - #if blocks.
1520b57cec5SDimitry Andric //      - Special #include's among declarations (e.g. functions).
1530b57cec5SDimitry Andric //
1540b57cec5SDimitry Andric // If no #include after which a new #include can be inserted, this returns the
1550b57cec5SDimitry Andric // offset after skipping all comments from the start of the code.
1560b57cec5SDimitry Andric // Inserting after an #include is not allowed if it comes after code that is not
1570b57cec5SDimitry Andric // #include (e.g. pre-processing directive that is not #include, declarations).
1580b57cec5SDimitry Andric unsigned getMaxHeaderInsertionOffset(StringRef FileName, StringRef Code,
1590b57cec5SDimitry Andric                                      const IncludeStyle &Style) {
1600b57cec5SDimitry Andric   return getOffsetAfterTokenSequence(
1610b57cec5SDimitry Andric       FileName, Code, Style,
1620b57cec5SDimitry Andric       [](const SourceManager &SM, Lexer &Lex, Token Tok) {
1630b57cec5SDimitry Andric         skipComments(Lex, Tok);
1640b57cec5SDimitry Andric         unsigned MaxOffset = SM.getFileOffset(Tok.getLocation());
1650b57cec5SDimitry Andric         while (checkAndConsumeInclusiveDirective(Lex, Tok))
1660b57cec5SDimitry Andric           MaxOffset = SM.getFileOffset(Tok.getLocation());
1670b57cec5SDimitry Andric         return MaxOffset;
1680b57cec5SDimitry Andric       });
1690b57cec5SDimitry Andric }
1700b57cec5SDimitry Andric 
1710b57cec5SDimitry Andric inline StringRef trimInclude(StringRef IncludeName) {
1720b57cec5SDimitry Andric   return IncludeName.trim("\"<>");
1730b57cec5SDimitry Andric }
1740b57cec5SDimitry Andric 
1750b57cec5SDimitry Andric const char IncludeRegexPattern[] =
1760b57cec5SDimitry Andric     R"(^[\t\ ]*#[\t\ ]*(import|include)[^"<]*(["<][^">]*[">]))";
1770b57cec5SDimitry Andric 
178*e8d8bef9SDimitry Andric // The filename of Path excluding extension.
179*e8d8bef9SDimitry Andric // Used to match implementation with headers, this differs from sys::path::stem:
180*e8d8bef9SDimitry Andric //  - in names with multiple dots (foo.cu.cc) it terminates at the *first*
181*e8d8bef9SDimitry Andric //  - an empty stem is never returned: /foo/.bar.x => .bar
182*e8d8bef9SDimitry Andric //  - we don't bother to handle . and .. specially
183*e8d8bef9SDimitry Andric StringRef matchingStem(llvm::StringRef Path) {
184*e8d8bef9SDimitry Andric   StringRef Name = llvm::sys::path::filename(Path);
185*e8d8bef9SDimitry Andric   return Name.substr(0, Name.find('.', 1));
186*e8d8bef9SDimitry Andric }
187*e8d8bef9SDimitry Andric 
1880b57cec5SDimitry Andric } // anonymous namespace
1890b57cec5SDimitry Andric 
1900b57cec5SDimitry Andric IncludeCategoryManager::IncludeCategoryManager(const IncludeStyle &Style,
1910b57cec5SDimitry Andric                                                StringRef FileName)
1920b57cec5SDimitry Andric     : Style(Style), FileName(FileName) {
193*e8d8bef9SDimitry Andric   for (const auto &Category : Style.IncludeCategories) {
194*e8d8bef9SDimitry Andric     CategoryRegexs.emplace_back(Category.Regex, Category.RegexIsCaseSensitive
195*e8d8bef9SDimitry Andric                                                     ? llvm::Regex::NoFlags
196*e8d8bef9SDimitry Andric                                                     : llvm::Regex::IgnoreCase);
197*e8d8bef9SDimitry Andric   }
1980b57cec5SDimitry Andric   IsMainFile = FileName.endswith(".c") || FileName.endswith(".cc") ||
1990b57cec5SDimitry Andric                FileName.endswith(".cpp") || FileName.endswith(".c++") ||
2000b57cec5SDimitry Andric                FileName.endswith(".cxx") || FileName.endswith(".m") ||
2010b57cec5SDimitry Andric                FileName.endswith(".mm");
202480093f4SDimitry Andric   if (!Style.IncludeIsMainSourceRegex.empty()) {
203480093f4SDimitry Andric     llvm::Regex MainFileRegex(Style.IncludeIsMainSourceRegex);
204480093f4SDimitry Andric     IsMainFile |= MainFileRegex.match(FileName);
205480093f4SDimitry Andric   }
2060b57cec5SDimitry Andric }
2070b57cec5SDimitry Andric 
2080b57cec5SDimitry Andric int IncludeCategoryManager::getIncludePriority(StringRef IncludeName,
2090b57cec5SDimitry Andric                                                bool CheckMainHeader) const {
2100b57cec5SDimitry Andric   int Ret = INT_MAX;
2110b57cec5SDimitry Andric   for (unsigned i = 0, e = CategoryRegexs.size(); i != e; ++i)
2120b57cec5SDimitry Andric     if (CategoryRegexs[i].match(IncludeName)) {
2130b57cec5SDimitry Andric       Ret = Style.IncludeCategories[i].Priority;
2140b57cec5SDimitry Andric       break;
2150b57cec5SDimitry Andric     }
2160b57cec5SDimitry Andric   if (CheckMainHeader && IsMainFile && Ret > 0 && isMainHeader(IncludeName))
2170b57cec5SDimitry Andric     Ret = 0;
2180b57cec5SDimitry Andric   return Ret;
2190b57cec5SDimitry Andric }
2200b57cec5SDimitry Andric 
221a7dea167SDimitry Andric int IncludeCategoryManager::getSortIncludePriority(StringRef IncludeName,
222a7dea167SDimitry Andric                                                    bool CheckMainHeader) const {
223a7dea167SDimitry Andric   int Ret = INT_MAX;
224a7dea167SDimitry Andric   for (unsigned i = 0, e = CategoryRegexs.size(); i != e; ++i)
225a7dea167SDimitry Andric     if (CategoryRegexs[i].match(IncludeName)) {
226a7dea167SDimitry Andric       Ret = Style.IncludeCategories[i].SortPriority;
227a7dea167SDimitry Andric       if (Ret == 0)
228a7dea167SDimitry Andric         Ret = Style.IncludeCategories[i].Priority;
229a7dea167SDimitry Andric       break;
230a7dea167SDimitry Andric     }
231a7dea167SDimitry Andric   if (CheckMainHeader && IsMainFile && Ret > 0 && isMainHeader(IncludeName))
232a7dea167SDimitry Andric     Ret = 0;
233a7dea167SDimitry Andric   return Ret;
234a7dea167SDimitry Andric }
2350b57cec5SDimitry Andric bool IncludeCategoryManager::isMainHeader(StringRef IncludeName) const {
2360b57cec5SDimitry Andric   if (!IncludeName.startswith("\""))
2370b57cec5SDimitry Andric     return false;
238*e8d8bef9SDimitry Andric 
239*e8d8bef9SDimitry Andric   IncludeName =
240*e8d8bef9SDimitry Andric       IncludeName.drop_front(1).drop_back(1); // remove the surrounding "" or <>
241*e8d8bef9SDimitry Andric   // Not matchingStem: implementation files may have compound extensions but
242*e8d8bef9SDimitry Andric   // headers may not.
243*e8d8bef9SDimitry Andric   StringRef HeaderStem = llvm::sys::path::stem(IncludeName);
244*e8d8bef9SDimitry Andric   StringRef FileStem = llvm::sys::path::stem(FileName); // foo.cu for foo.cu.cc
245*e8d8bef9SDimitry Andric   StringRef MatchingFileStem = matchingStem(FileName);  // foo for foo.cu.cc
246*e8d8bef9SDimitry Andric   // main-header examples:
247*e8d8bef9SDimitry Andric   //  1) foo.h => foo.cc
248*e8d8bef9SDimitry Andric   //  2) foo.h => foo.cu.cc
249*e8d8bef9SDimitry Andric   //  3) foo.proto.h => foo.proto.cc
250*e8d8bef9SDimitry Andric   //
251*e8d8bef9SDimitry Andric   // non-main-header examples:
252*e8d8bef9SDimitry Andric   //  1) foo.h => bar.cc
253*e8d8bef9SDimitry Andric   //  2) foo.proto.h => foo.cc
254*e8d8bef9SDimitry Andric   StringRef Matching;
255*e8d8bef9SDimitry Andric   if (MatchingFileStem.startswith_lower(HeaderStem))
256*e8d8bef9SDimitry Andric     Matching = MatchingFileStem; // example 1), 2)
257*e8d8bef9SDimitry Andric   else if (FileStem.equals_lower(HeaderStem))
258*e8d8bef9SDimitry Andric     Matching = FileStem; // example 3)
259*e8d8bef9SDimitry Andric   if (!Matching.empty()) {
2600b57cec5SDimitry Andric     llvm::Regex MainIncludeRegex(HeaderStem.str() + Style.IncludeIsMainRegex,
2610b57cec5SDimitry Andric                                  llvm::Regex::IgnoreCase);
262*e8d8bef9SDimitry Andric     if (MainIncludeRegex.match(Matching))
2630b57cec5SDimitry Andric       return true;
2640b57cec5SDimitry Andric   }
2650b57cec5SDimitry Andric   return false;
2660b57cec5SDimitry Andric }
2670b57cec5SDimitry Andric 
2680b57cec5SDimitry Andric HeaderIncludes::HeaderIncludes(StringRef FileName, StringRef Code,
2690b57cec5SDimitry Andric                                const IncludeStyle &Style)
2700b57cec5SDimitry Andric     : FileName(FileName), Code(Code), FirstIncludeOffset(-1),
2710b57cec5SDimitry Andric       MinInsertOffset(
2720b57cec5SDimitry Andric           getOffsetAfterHeaderGuardsAndComments(FileName, Code, Style)),
2730b57cec5SDimitry Andric       MaxInsertOffset(MinInsertOffset +
2740b57cec5SDimitry Andric                       getMaxHeaderInsertionOffset(
2750b57cec5SDimitry Andric                           FileName, Code.drop_front(MinInsertOffset), Style)),
2760b57cec5SDimitry Andric       Categories(Style, FileName),
2770b57cec5SDimitry Andric       IncludeRegex(llvm::Regex(IncludeRegexPattern)) {
2780b57cec5SDimitry Andric   // Add 0 for main header and INT_MAX for headers that are not in any
2790b57cec5SDimitry Andric   // category.
2800b57cec5SDimitry Andric   Priorities = {0, INT_MAX};
2810b57cec5SDimitry Andric   for (const auto &Category : Style.IncludeCategories)
2820b57cec5SDimitry Andric     Priorities.insert(Category.Priority);
2830b57cec5SDimitry Andric   SmallVector<StringRef, 32> Lines;
2840b57cec5SDimitry Andric   Code.drop_front(MinInsertOffset).split(Lines, "\n");
2850b57cec5SDimitry Andric 
2860b57cec5SDimitry Andric   unsigned Offset = MinInsertOffset;
2870b57cec5SDimitry Andric   unsigned NextLineOffset;
2880b57cec5SDimitry Andric   SmallVector<StringRef, 4> Matches;
2890b57cec5SDimitry Andric   for (auto Line : Lines) {
2900b57cec5SDimitry Andric     NextLineOffset = std::min(Code.size(), Offset + Line.size() + 1);
2910b57cec5SDimitry Andric     if (IncludeRegex.match(Line, &Matches)) {
2920b57cec5SDimitry Andric       // If this is the last line without trailing newline, we need to make
2930b57cec5SDimitry Andric       // sure we don't delete across the file boundary.
2940b57cec5SDimitry Andric       addExistingInclude(
2950b57cec5SDimitry Andric           Include(Matches[2],
2960b57cec5SDimitry Andric                   tooling::Range(
2970b57cec5SDimitry Andric                       Offset, std::min(Line.size() + 1, Code.size() - Offset))),
2980b57cec5SDimitry Andric           NextLineOffset);
2990b57cec5SDimitry Andric     }
3000b57cec5SDimitry Andric     Offset = NextLineOffset;
3010b57cec5SDimitry Andric   }
3020b57cec5SDimitry Andric 
3030b57cec5SDimitry Andric   // Populate CategoryEndOfssets:
3040b57cec5SDimitry Andric   // - Ensure that CategoryEndOffset[Highest] is always populated.
3050b57cec5SDimitry Andric   // - If CategoryEndOffset[Priority] isn't set, use the next higher value
3060b57cec5SDimitry Andric   // that is set, up to CategoryEndOffset[Highest].
3070b57cec5SDimitry Andric   auto Highest = Priorities.begin();
3080b57cec5SDimitry Andric   if (CategoryEndOffsets.find(*Highest) == CategoryEndOffsets.end()) {
3090b57cec5SDimitry Andric     if (FirstIncludeOffset >= 0)
3100b57cec5SDimitry Andric       CategoryEndOffsets[*Highest] = FirstIncludeOffset;
3110b57cec5SDimitry Andric     else
3120b57cec5SDimitry Andric       CategoryEndOffsets[*Highest] = MinInsertOffset;
3130b57cec5SDimitry Andric   }
3140b57cec5SDimitry Andric   // By this point, CategoryEndOffset[Highest] is always set appropriately:
3150b57cec5SDimitry Andric   //  - to an appropriate location before/after existing #includes, or
3160b57cec5SDimitry Andric   //  - to right after the header guard, or
3170b57cec5SDimitry Andric   //  - to the beginning of the file.
3180b57cec5SDimitry Andric   for (auto I = ++Priorities.begin(), E = Priorities.end(); I != E; ++I)
3190b57cec5SDimitry Andric     if (CategoryEndOffsets.find(*I) == CategoryEndOffsets.end())
3200b57cec5SDimitry Andric       CategoryEndOffsets[*I] = CategoryEndOffsets[*std::prev(I)];
3210b57cec5SDimitry Andric }
3220b57cec5SDimitry Andric 
3230b57cec5SDimitry Andric // \p Offset: the start of the line following this include directive.
3240b57cec5SDimitry Andric void HeaderIncludes::addExistingInclude(Include IncludeToAdd,
3250b57cec5SDimitry Andric                                         unsigned NextLineOffset) {
3260b57cec5SDimitry Andric   auto Iter =
3270b57cec5SDimitry Andric       ExistingIncludes.try_emplace(trimInclude(IncludeToAdd.Name)).first;
3280b57cec5SDimitry Andric   Iter->second.push_back(std::move(IncludeToAdd));
3290b57cec5SDimitry Andric   auto &CurInclude = Iter->second.back();
3300b57cec5SDimitry Andric   // The header name with quotes or angle brackets.
3310b57cec5SDimitry Andric   // Only record the offset of current #include if we can insert after it.
3320b57cec5SDimitry Andric   if (CurInclude.R.getOffset() <= MaxInsertOffset) {
3330b57cec5SDimitry Andric     int Priority = Categories.getIncludePriority(
3340b57cec5SDimitry Andric         CurInclude.Name, /*CheckMainHeader=*/FirstIncludeOffset < 0);
3350b57cec5SDimitry Andric     CategoryEndOffsets[Priority] = NextLineOffset;
3360b57cec5SDimitry Andric     IncludesByPriority[Priority].push_back(&CurInclude);
3370b57cec5SDimitry Andric     if (FirstIncludeOffset < 0)
3380b57cec5SDimitry Andric       FirstIncludeOffset = CurInclude.R.getOffset();
3390b57cec5SDimitry Andric   }
3400b57cec5SDimitry Andric }
3410b57cec5SDimitry Andric 
3420b57cec5SDimitry Andric llvm::Optional<tooling::Replacement>
3430b57cec5SDimitry Andric HeaderIncludes::insert(llvm::StringRef IncludeName, bool IsAngled) const {
3440b57cec5SDimitry Andric   assert(IncludeName == trimInclude(IncludeName));
3450b57cec5SDimitry Andric   // If a <header> ("header") already exists in code, "header" (<header>) with
3460b57cec5SDimitry Andric   // different quotation will still be inserted.
3470b57cec5SDimitry Andric   // FIXME: figure out if this is the best behavior.
3480b57cec5SDimitry Andric   auto It = ExistingIncludes.find(IncludeName);
3490b57cec5SDimitry Andric   if (It != ExistingIncludes.end())
3500b57cec5SDimitry Andric     for (const auto &Inc : It->second)
3510b57cec5SDimitry Andric       if ((IsAngled && StringRef(Inc.Name).startswith("<")) ||
3520b57cec5SDimitry Andric           (!IsAngled && StringRef(Inc.Name).startswith("\"")))
3530b57cec5SDimitry Andric         return llvm::None;
3540b57cec5SDimitry Andric   std::string Quoted =
3555ffd83dbSDimitry Andric       std::string(llvm::formatv(IsAngled ? "<{0}>" : "\"{0}\"", IncludeName));
3560b57cec5SDimitry Andric   StringRef QuotedName = Quoted;
3570b57cec5SDimitry Andric   int Priority = Categories.getIncludePriority(
3580b57cec5SDimitry Andric       QuotedName, /*CheckMainHeader=*/FirstIncludeOffset < 0);
3590b57cec5SDimitry Andric   auto CatOffset = CategoryEndOffsets.find(Priority);
3600b57cec5SDimitry Andric   assert(CatOffset != CategoryEndOffsets.end());
3610b57cec5SDimitry Andric   unsigned InsertOffset = CatOffset->second; // Fall back offset
3620b57cec5SDimitry Andric   auto Iter = IncludesByPriority.find(Priority);
3630b57cec5SDimitry Andric   if (Iter != IncludesByPriority.end()) {
3640b57cec5SDimitry Andric     for (const auto *Inc : Iter->second) {
3650b57cec5SDimitry Andric       if (QuotedName < Inc->Name) {
3660b57cec5SDimitry Andric         InsertOffset = Inc->R.getOffset();
3670b57cec5SDimitry Andric         break;
3680b57cec5SDimitry Andric       }
3690b57cec5SDimitry Andric     }
3700b57cec5SDimitry Andric   }
3710b57cec5SDimitry Andric   assert(InsertOffset <= Code.size());
3725ffd83dbSDimitry Andric   std::string NewInclude =
3735ffd83dbSDimitry Andric       std::string(llvm::formatv("#include {0}\n", QuotedName));
3740b57cec5SDimitry Andric   // When inserting headers at end of the code, also append '\n' to the code
3750b57cec5SDimitry Andric   // if it does not end with '\n'.
3760b57cec5SDimitry Andric   // FIXME: when inserting multiple #includes at the end of code, only one
3770b57cec5SDimitry Andric   // newline should be added.
3780b57cec5SDimitry Andric   if (InsertOffset == Code.size() && (!Code.empty() && Code.back() != '\n'))
3790b57cec5SDimitry Andric     NewInclude = "\n" + NewInclude;
3800b57cec5SDimitry Andric   return tooling::Replacement(FileName, InsertOffset, 0, NewInclude);
3810b57cec5SDimitry Andric }
3820b57cec5SDimitry Andric 
3830b57cec5SDimitry Andric tooling::Replacements HeaderIncludes::remove(llvm::StringRef IncludeName,
3840b57cec5SDimitry Andric                                              bool IsAngled) const {
3850b57cec5SDimitry Andric   assert(IncludeName == trimInclude(IncludeName));
3860b57cec5SDimitry Andric   tooling::Replacements Result;
3870b57cec5SDimitry Andric   auto Iter = ExistingIncludes.find(IncludeName);
3880b57cec5SDimitry Andric   if (Iter == ExistingIncludes.end())
3890b57cec5SDimitry Andric     return Result;
3900b57cec5SDimitry Andric   for (const auto &Inc : Iter->second) {
3910b57cec5SDimitry Andric     if ((IsAngled && StringRef(Inc.Name).startswith("\"")) ||
3920b57cec5SDimitry Andric         (!IsAngled && StringRef(Inc.Name).startswith("<")))
3930b57cec5SDimitry Andric       continue;
3940b57cec5SDimitry Andric     llvm::Error Err = Result.add(tooling::Replacement(
3950b57cec5SDimitry Andric         FileName, Inc.R.getOffset(), Inc.R.getLength(), ""));
3960b57cec5SDimitry Andric     if (Err) {
3970b57cec5SDimitry Andric       auto ErrMsg = "Unexpected conflicts in #include deletions: " +
3980b57cec5SDimitry Andric                     llvm::toString(std::move(Err));
3990b57cec5SDimitry Andric       llvm_unreachable(ErrMsg.c_str());
4000b57cec5SDimitry Andric     }
4010b57cec5SDimitry Andric   }
4020b57cec5SDimitry Andric   return Result;
4030b57cec5SDimitry Andric }
4040b57cec5SDimitry Andric 
4050b57cec5SDimitry Andric } // namespace tooling
4060b57cec5SDimitry Andric } // namespace clang
407