xref: /freebsd/contrib/llvm-project/clang/lib/Tooling/Inclusions/HeaderIncludes.cpp (revision 480093f4440d54b30b3025afeac24b48f2ba7a2e)
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"
100b57cec5SDimitry Andric #include "clang/Basic/SourceManager.h"
110b57cec5SDimitry Andric #include "clang/Lex/Lexer.h"
120b57cec5SDimitry Andric #include "llvm/ADT/Optional.h"
130b57cec5SDimitry Andric #include "llvm/Support/FormatVariadic.h"
140b57cec5SDimitry Andric 
150b57cec5SDimitry Andric namespace clang {
160b57cec5SDimitry Andric namespace tooling {
170b57cec5SDimitry Andric namespace {
180b57cec5SDimitry Andric 
190b57cec5SDimitry Andric LangOptions createLangOpts() {
200b57cec5SDimitry Andric   LangOptions LangOpts;
210b57cec5SDimitry Andric   LangOpts.CPlusPlus = 1;
220b57cec5SDimitry Andric   LangOpts.CPlusPlus11 = 1;
230b57cec5SDimitry Andric   LangOpts.CPlusPlus14 = 1;
240b57cec5SDimitry Andric   LangOpts.LineComment = 1;
250b57cec5SDimitry Andric   LangOpts.CXXOperatorNames = 1;
260b57cec5SDimitry Andric   LangOpts.Bool = 1;
270b57cec5SDimitry Andric   LangOpts.ObjC = 1;
280b57cec5SDimitry Andric   LangOpts.MicrosoftExt = 1;    // To get kw___try, kw___finally.
290b57cec5SDimitry Andric   LangOpts.DeclSpecKeyword = 1; // To get __declspec.
300b57cec5SDimitry Andric   LangOpts.WChar = 1;           // To get wchar_t
310b57cec5SDimitry Andric   return LangOpts;
320b57cec5SDimitry Andric }
330b57cec5SDimitry Andric 
340b57cec5SDimitry Andric // Returns the offset after skipping a sequence of tokens, matched by \p
350b57cec5SDimitry Andric // GetOffsetAfterSequence, from the start of the code.
360b57cec5SDimitry Andric // \p GetOffsetAfterSequence should be a function that matches a sequence of
370b57cec5SDimitry Andric // tokens and returns an offset after the sequence.
380b57cec5SDimitry Andric unsigned getOffsetAfterTokenSequence(
390b57cec5SDimitry Andric     StringRef FileName, StringRef Code, const IncludeStyle &Style,
400b57cec5SDimitry Andric     llvm::function_ref<unsigned(const SourceManager &, Lexer &, Token &)>
410b57cec5SDimitry Andric         GetOffsetAfterSequence) {
420b57cec5SDimitry Andric   SourceManagerForFile VirtualSM(FileName, Code);
430b57cec5SDimitry Andric   SourceManager &SM = VirtualSM.get();
440b57cec5SDimitry Andric   Lexer Lex(SM.getMainFileID(), SM.getBuffer(SM.getMainFileID()), SM,
450b57cec5SDimitry Andric             createLangOpts());
460b57cec5SDimitry Andric   Token Tok;
470b57cec5SDimitry Andric   // Get the first token.
480b57cec5SDimitry Andric   Lex.LexFromRawLexer(Tok);
490b57cec5SDimitry Andric   return GetOffsetAfterSequence(SM, Lex, Tok);
500b57cec5SDimitry Andric }
510b57cec5SDimitry Andric 
520b57cec5SDimitry Andric // Check if a sequence of tokens is like "#<Name> <raw_identifier>". If it is,
530b57cec5SDimitry Andric // \p Tok will be the token after this directive; otherwise, it can be any token
540b57cec5SDimitry Andric // after the given \p Tok (including \p Tok). If \p RawIDName is provided, the
550b57cec5SDimitry Andric // (second) raw_identifier name is checked.
560b57cec5SDimitry Andric bool checkAndConsumeDirectiveWithName(
570b57cec5SDimitry Andric     Lexer &Lex, StringRef Name, Token &Tok,
580b57cec5SDimitry Andric     llvm::Optional<StringRef> RawIDName = llvm::None) {
590b57cec5SDimitry Andric   bool Matched = Tok.is(tok::hash) && !Lex.LexFromRawLexer(Tok) &&
600b57cec5SDimitry Andric                  Tok.is(tok::raw_identifier) &&
610b57cec5SDimitry Andric                  Tok.getRawIdentifier() == Name && !Lex.LexFromRawLexer(Tok) &&
620b57cec5SDimitry Andric                  Tok.is(tok::raw_identifier) &&
630b57cec5SDimitry Andric                  (!RawIDName || Tok.getRawIdentifier() == *RawIDName);
640b57cec5SDimitry Andric   if (Matched)
650b57cec5SDimitry Andric     Lex.LexFromRawLexer(Tok);
660b57cec5SDimitry Andric   return Matched;
670b57cec5SDimitry Andric }
680b57cec5SDimitry Andric 
690b57cec5SDimitry Andric void skipComments(Lexer &Lex, Token &Tok) {
700b57cec5SDimitry Andric   while (Tok.is(tok::comment))
710b57cec5SDimitry Andric     if (Lex.LexFromRawLexer(Tok))
720b57cec5SDimitry Andric       return;
730b57cec5SDimitry Andric }
740b57cec5SDimitry Andric 
750b57cec5SDimitry Andric // Returns the offset after header guard directives and any comments
760b57cec5SDimitry Andric // before/after header guards (e.g. #ifndef/#define pair, #pragma once). If no
770b57cec5SDimitry Andric // header guard is present in the code, this will return the offset after
780b57cec5SDimitry Andric // skipping all comments from the start of the code.
790b57cec5SDimitry Andric unsigned getOffsetAfterHeaderGuardsAndComments(StringRef FileName,
800b57cec5SDimitry Andric                                                StringRef Code,
810b57cec5SDimitry Andric                                                const IncludeStyle &Style) {
820b57cec5SDimitry Andric   // \p Consume returns location after header guard or 0 if no header guard is
830b57cec5SDimitry Andric   // found.
840b57cec5SDimitry Andric   auto ConsumeHeaderGuardAndComment =
850b57cec5SDimitry Andric       [&](std::function<unsigned(const SourceManager &SM, Lexer &Lex,
860b57cec5SDimitry Andric                                  Token Tok)>
870b57cec5SDimitry Andric               Consume) {
880b57cec5SDimitry Andric         return getOffsetAfterTokenSequence(
890b57cec5SDimitry Andric             FileName, Code, Style,
900b57cec5SDimitry Andric             [&Consume](const SourceManager &SM, Lexer &Lex, Token Tok) {
910b57cec5SDimitry Andric               skipComments(Lex, Tok);
920b57cec5SDimitry Andric               unsigned InitialOffset = SM.getFileOffset(Tok.getLocation());
930b57cec5SDimitry Andric               return std::max(InitialOffset, Consume(SM, Lex, Tok));
940b57cec5SDimitry Andric             });
950b57cec5SDimitry Andric       };
960b57cec5SDimitry Andric   return std::max(
970b57cec5SDimitry Andric       // #ifndef/#define
980b57cec5SDimitry Andric       ConsumeHeaderGuardAndComment(
990b57cec5SDimitry Andric           [](const SourceManager &SM, Lexer &Lex, Token Tok) -> unsigned {
1000b57cec5SDimitry Andric             if (checkAndConsumeDirectiveWithName(Lex, "ifndef", Tok)) {
1010b57cec5SDimitry Andric               skipComments(Lex, Tok);
1020b57cec5SDimitry Andric               if (checkAndConsumeDirectiveWithName(Lex, "define", Tok))
1030b57cec5SDimitry Andric                 return SM.getFileOffset(Tok.getLocation());
1040b57cec5SDimitry Andric             }
1050b57cec5SDimitry Andric             return 0;
1060b57cec5SDimitry Andric           }),
1070b57cec5SDimitry Andric       // #pragma once
1080b57cec5SDimitry Andric       ConsumeHeaderGuardAndComment(
1090b57cec5SDimitry Andric           [](const SourceManager &SM, Lexer &Lex, Token Tok) -> unsigned {
1100b57cec5SDimitry Andric             if (checkAndConsumeDirectiveWithName(Lex, "pragma", Tok,
1110b57cec5SDimitry Andric                                                  StringRef("once")))
1120b57cec5SDimitry Andric               return SM.getFileOffset(Tok.getLocation());
1130b57cec5SDimitry Andric             return 0;
1140b57cec5SDimitry Andric           }));
1150b57cec5SDimitry Andric }
1160b57cec5SDimitry Andric 
1170b57cec5SDimitry Andric // Check if a sequence of tokens is like
1180b57cec5SDimitry Andric //    "#include ("header.h" | <header.h>)".
1190b57cec5SDimitry Andric // If it is, \p Tok will be the token after this directive; otherwise, it can be
1200b57cec5SDimitry Andric // any token after the given \p Tok (including \p Tok).
1210b57cec5SDimitry Andric bool checkAndConsumeInclusiveDirective(Lexer &Lex, Token &Tok) {
1220b57cec5SDimitry Andric   auto Matched = [&]() {
1230b57cec5SDimitry Andric     Lex.LexFromRawLexer(Tok);
1240b57cec5SDimitry Andric     return true;
1250b57cec5SDimitry Andric   };
1260b57cec5SDimitry Andric   if (Tok.is(tok::hash) && !Lex.LexFromRawLexer(Tok) &&
1270b57cec5SDimitry Andric       Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "include") {
1280b57cec5SDimitry Andric     if (Lex.LexFromRawLexer(Tok))
1290b57cec5SDimitry Andric       return false;
1300b57cec5SDimitry Andric     if (Tok.is(tok::string_literal))
1310b57cec5SDimitry Andric       return Matched();
1320b57cec5SDimitry Andric     if (Tok.is(tok::less)) {
1330b57cec5SDimitry Andric       while (!Lex.LexFromRawLexer(Tok) && Tok.isNot(tok::greater)) {
1340b57cec5SDimitry Andric       }
1350b57cec5SDimitry Andric       if (Tok.is(tok::greater))
1360b57cec5SDimitry Andric         return Matched();
1370b57cec5SDimitry Andric     }
1380b57cec5SDimitry Andric   }
1390b57cec5SDimitry Andric   return false;
1400b57cec5SDimitry Andric }
1410b57cec5SDimitry Andric 
1420b57cec5SDimitry Andric // Returns the offset of the last #include directive after which a new
1430b57cec5SDimitry Andric // #include can be inserted. This ignores #include's after the #include block(s)
1440b57cec5SDimitry Andric // in the beginning of a file to avoid inserting headers into code sections
1450b57cec5SDimitry Andric // where new #include's should not be added by default.
1460b57cec5SDimitry Andric // These code sections include:
1470b57cec5SDimitry Andric //      - raw string literals (containing #include).
1480b57cec5SDimitry Andric //      - #if blocks.
1490b57cec5SDimitry Andric //      - Special #include's among declarations (e.g. functions).
1500b57cec5SDimitry Andric //
1510b57cec5SDimitry Andric // If no #include after which a new #include can be inserted, this returns the
1520b57cec5SDimitry Andric // offset after skipping all comments from the start of the code.
1530b57cec5SDimitry Andric // Inserting after an #include is not allowed if it comes after code that is not
1540b57cec5SDimitry Andric // #include (e.g. pre-processing directive that is not #include, declarations).
1550b57cec5SDimitry Andric unsigned getMaxHeaderInsertionOffset(StringRef FileName, StringRef Code,
1560b57cec5SDimitry Andric                                      const IncludeStyle &Style) {
1570b57cec5SDimitry Andric   return getOffsetAfterTokenSequence(
1580b57cec5SDimitry Andric       FileName, Code, Style,
1590b57cec5SDimitry Andric       [](const SourceManager &SM, Lexer &Lex, Token Tok) {
1600b57cec5SDimitry Andric         skipComments(Lex, Tok);
1610b57cec5SDimitry Andric         unsigned MaxOffset = SM.getFileOffset(Tok.getLocation());
1620b57cec5SDimitry Andric         while (checkAndConsumeInclusiveDirective(Lex, Tok))
1630b57cec5SDimitry Andric           MaxOffset = SM.getFileOffset(Tok.getLocation());
1640b57cec5SDimitry Andric         return MaxOffset;
1650b57cec5SDimitry Andric       });
1660b57cec5SDimitry Andric }
1670b57cec5SDimitry Andric 
1680b57cec5SDimitry Andric inline StringRef trimInclude(StringRef IncludeName) {
1690b57cec5SDimitry Andric   return IncludeName.trim("\"<>");
1700b57cec5SDimitry Andric }
1710b57cec5SDimitry Andric 
1720b57cec5SDimitry Andric const char IncludeRegexPattern[] =
1730b57cec5SDimitry Andric     R"(^[\t\ ]*#[\t\ ]*(import|include)[^"<]*(["<][^">]*[">]))";
1740b57cec5SDimitry Andric 
1750b57cec5SDimitry Andric } // anonymous namespace
1760b57cec5SDimitry Andric 
1770b57cec5SDimitry Andric IncludeCategoryManager::IncludeCategoryManager(const IncludeStyle &Style,
1780b57cec5SDimitry Andric                                                StringRef FileName)
1790b57cec5SDimitry Andric     : Style(Style), FileName(FileName) {
1800b57cec5SDimitry Andric   FileStem = llvm::sys::path::stem(FileName);
1810b57cec5SDimitry Andric   for (const auto &Category : Style.IncludeCategories)
1820b57cec5SDimitry Andric     CategoryRegexs.emplace_back(Category.Regex, llvm::Regex::IgnoreCase);
1830b57cec5SDimitry Andric   IsMainFile = FileName.endswith(".c") || FileName.endswith(".cc") ||
1840b57cec5SDimitry Andric                FileName.endswith(".cpp") || FileName.endswith(".c++") ||
1850b57cec5SDimitry Andric                FileName.endswith(".cxx") || FileName.endswith(".m") ||
1860b57cec5SDimitry Andric                FileName.endswith(".mm");
187*480093f4SDimitry Andric   if (!Style.IncludeIsMainSourceRegex.empty()) {
188*480093f4SDimitry Andric     llvm::Regex MainFileRegex(Style.IncludeIsMainSourceRegex);
189*480093f4SDimitry Andric     IsMainFile |= MainFileRegex.match(FileName);
190*480093f4SDimitry Andric   }
1910b57cec5SDimitry Andric }
1920b57cec5SDimitry Andric 
1930b57cec5SDimitry Andric int IncludeCategoryManager::getIncludePriority(StringRef IncludeName,
1940b57cec5SDimitry Andric                                                bool CheckMainHeader) const {
1950b57cec5SDimitry Andric   int Ret = INT_MAX;
1960b57cec5SDimitry Andric   for (unsigned i = 0, e = CategoryRegexs.size(); i != e; ++i)
1970b57cec5SDimitry Andric     if (CategoryRegexs[i].match(IncludeName)) {
1980b57cec5SDimitry Andric       Ret = Style.IncludeCategories[i].Priority;
1990b57cec5SDimitry Andric       break;
2000b57cec5SDimitry Andric     }
2010b57cec5SDimitry Andric   if (CheckMainHeader && IsMainFile && Ret > 0 && isMainHeader(IncludeName))
2020b57cec5SDimitry Andric     Ret = 0;
2030b57cec5SDimitry Andric   return Ret;
2040b57cec5SDimitry Andric }
2050b57cec5SDimitry Andric 
206a7dea167SDimitry Andric int IncludeCategoryManager::getSortIncludePriority(StringRef IncludeName,
207a7dea167SDimitry Andric                                                    bool CheckMainHeader) const {
208a7dea167SDimitry Andric   int Ret = INT_MAX;
209a7dea167SDimitry Andric   for (unsigned i = 0, e = CategoryRegexs.size(); i != e; ++i)
210a7dea167SDimitry Andric     if (CategoryRegexs[i].match(IncludeName)) {
211a7dea167SDimitry Andric       Ret = Style.IncludeCategories[i].SortPriority;
212a7dea167SDimitry Andric       if (Ret == 0)
213a7dea167SDimitry Andric         Ret = Style.IncludeCategories[i].Priority;
214a7dea167SDimitry Andric       break;
215a7dea167SDimitry Andric     }
216a7dea167SDimitry Andric   if (CheckMainHeader && IsMainFile && Ret > 0 && isMainHeader(IncludeName))
217a7dea167SDimitry Andric     Ret = 0;
218a7dea167SDimitry Andric   return Ret;
219a7dea167SDimitry Andric }
2200b57cec5SDimitry Andric bool IncludeCategoryManager::isMainHeader(StringRef IncludeName) const {
2210b57cec5SDimitry Andric   if (!IncludeName.startswith("\""))
2220b57cec5SDimitry Andric     return false;
2230b57cec5SDimitry Andric   StringRef HeaderStem =
2240b57cec5SDimitry Andric       llvm::sys::path::stem(IncludeName.drop_front(1).drop_back(1));
2250b57cec5SDimitry Andric   if (FileStem.startswith(HeaderStem) ||
2260b57cec5SDimitry Andric       FileStem.startswith_lower(HeaderStem)) {
2270b57cec5SDimitry Andric     llvm::Regex MainIncludeRegex(HeaderStem.str() + Style.IncludeIsMainRegex,
2280b57cec5SDimitry Andric                                  llvm::Regex::IgnoreCase);
2290b57cec5SDimitry Andric     if (MainIncludeRegex.match(FileStem))
2300b57cec5SDimitry Andric       return true;
2310b57cec5SDimitry Andric   }
2320b57cec5SDimitry Andric   return false;
2330b57cec5SDimitry Andric }
2340b57cec5SDimitry Andric 
2350b57cec5SDimitry Andric HeaderIncludes::HeaderIncludes(StringRef FileName, StringRef Code,
2360b57cec5SDimitry Andric                                const IncludeStyle &Style)
2370b57cec5SDimitry Andric     : FileName(FileName), Code(Code), FirstIncludeOffset(-1),
2380b57cec5SDimitry Andric       MinInsertOffset(
2390b57cec5SDimitry Andric           getOffsetAfterHeaderGuardsAndComments(FileName, Code, Style)),
2400b57cec5SDimitry Andric       MaxInsertOffset(MinInsertOffset +
2410b57cec5SDimitry Andric                       getMaxHeaderInsertionOffset(
2420b57cec5SDimitry Andric                           FileName, Code.drop_front(MinInsertOffset), Style)),
2430b57cec5SDimitry Andric       Categories(Style, FileName),
2440b57cec5SDimitry Andric       IncludeRegex(llvm::Regex(IncludeRegexPattern)) {
2450b57cec5SDimitry Andric   // Add 0 for main header and INT_MAX for headers that are not in any
2460b57cec5SDimitry Andric   // category.
2470b57cec5SDimitry Andric   Priorities = {0, INT_MAX};
2480b57cec5SDimitry Andric   for (const auto &Category : Style.IncludeCategories)
2490b57cec5SDimitry Andric     Priorities.insert(Category.Priority);
2500b57cec5SDimitry Andric   SmallVector<StringRef, 32> Lines;
2510b57cec5SDimitry Andric   Code.drop_front(MinInsertOffset).split(Lines, "\n");
2520b57cec5SDimitry Andric 
2530b57cec5SDimitry Andric   unsigned Offset = MinInsertOffset;
2540b57cec5SDimitry Andric   unsigned NextLineOffset;
2550b57cec5SDimitry Andric   SmallVector<StringRef, 4> Matches;
2560b57cec5SDimitry Andric   for (auto Line : Lines) {
2570b57cec5SDimitry Andric     NextLineOffset = std::min(Code.size(), Offset + Line.size() + 1);
2580b57cec5SDimitry Andric     if (IncludeRegex.match(Line, &Matches)) {
2590b57cec5SDimitry Andric       // If this is the last line without trailing newline, we need to make
2600b57cec5SDimitry Andric       // sure we don't delete across the file boundary.
2610b57cec5SDimitry Andric       addExistingInclude(
2620b57cec5SDimitry Andric           Include(Matches[2],
2630b57cec5SDimitry Andric                   tooling::Range(
2640b57cec5SDimitry Andric                       Offset, std::min(Line.size() + 1, Code.size() - Offset))),
2650b57cec5SDimitry Andric           NextLineOffset);
2660b57cec5SDimitry Andric     }
2670b57cec5SDimitry Andric     Offset = NextLineOffset;
2680b57cec5SDimitry Andric   }
2690b57cec5SDimitry Andric 
2700b57cec5SDimitry Andric   // Populate CategoryEndOfssets:
2710b57cec5SDimitry Andric   // - Ensure that CategoryEndOffset[Highest] is always populated.
2720b57cec5SDimitry Andric   // - If CategoryEndOffset[Priority] isn't set, use the next higher value
2730b57cec5SDimitry Andric   // that is set, up to CategoryEndOffset[Highest].
2740b57cec5SDimitry Andric   auto Highest = Priorities.begin();
2750b57cec5SDimitry Andric   if (CategoryEndOffsets.find(*Highest) == CategoryEndOffsets.end()) {
2760b57cec5SDimitry Andric     if (FirstIncludeOffset >= 0)
2770b57cec5SDimitry Andric       CategoryEndOffsets[*Highest] = FirstIncludeOffset;
2780b57cec5SDimitry Andric     else
2790b57cec5SDimitry Andric       CategoryEndOffsets[*Highest] = MinInsertOffset;
2800b57cec5SDimitry Andric   }
2810b57cec5SDimitry Andric   // By this point, CategoryEndOffset[Highest] is always set appropriately:
2820b57cec5SDimitry Andric   //  - to an appropriate location before/after existing #includes, or
2830b57cec5SDimitry Andric   //  - to right after the header guard, or
2840b57cec5SDimitry Andric   //  - to the beginning of the file.
2850b57cec5SDimitry Andric   for (auto I = ++Priorities.begin(), E = Priorities.end(); I != E; ++I)
2860b57cec5SDimitry Andric     if (CategoryEndOffsets.find(*I) == CategoryEndOffsets.end())
2870b57cec5SDimitry Andric       CategoryEndOffsets[*I] = CategoryEndOffsets[*std::prev(I)];
2880b57cec5SDimitry Andric }
2890b57cec5SDimitry Andric 
2900b57cec5SDimitry Andric // \p Offset: the start of the line following this include directive.
2910b57cec5SDimitry Andric void HeaderIncludes::addExistingInclude(Include IncludeToAdd,
2920b57cec5SDimitry Andric                                         unsigned NextLineOffset) {
2930b57cec5SDimitry Andric   auto Iter =
2940b57cec5SDimitry Andric       ExistingIncludes.try_emplace(trimInclude(IncludeToAdd.Name)).first;
2950b57cec5SDimitry Andric   Iter->second.push_back(std::move(IncludeToAdd));
2960b57cec5SDimitry Andric   auto &CurInclude = Iter->second.back();
2970b57cec5SDimitry Andric   // The header name with quotes or angle brackets.
2980b57cec5SDimitry Andric   // Only record the offset of current #include if we can insert after it.
2990b57cec5SDimitry Andric   if (CurInclude.R.getOffset() <= MaxInsertOffset) {
3000b57cec5SDimitry Andric     int Priority = Categories.getIncludePriority(
3010b57cec5SDimitry Andric         CurInclude.Name, /*CheckMainHeader=*/FirstIncludeOffset < 0);
3020b57cec5SDimitry Andric     CategoryEndOffsets[Priority] = NextLineOffset;
3030b57cec5SDimitry Andric     IncludesByPriority[Priority].push_back(&CurInclude);
3040b57cec5SDimitry Andric     if (FirstIncludeOffset < 0)
3050b57cec5SDimitry Andric       FirstIncludeOffset = CurInclude.R.getOffset();
3060b57cec5SDimitry Andric   }
3070b57cec5SDimitry Andric }
3080b57cec5SDimitry Andric 
3090b57cec5SDimitry Andric llvm::Optional<tooling::Replacement>
3100b57cec5SDimitry Andric HeaderIncludes::insert(llvm::StringRef IncludeName, bool IsAngled) const {
3110b57cec5SDimitry Andric   assert(IncludeName == trimInclude(IncludeName));
3120b57cec5SDimitry Andric   // If a <header> ("header") already exists in code, "header" (<header>) with
3130b57cec5SDimitry Andric   // different quotation will still be inserted.
3140b57cec5SDimitry Andric   // FIXME: figure out if this is the best behavior.
3150b57cec5SDimitry Andric   auto It = ExistingIncludes.find(IncludeName);
3160b57cec5SDimitry Andric   if (It != ExistingIncludes.end())
3170b57cec5SDimitry Andric     for (const auto &Inc : It->second)
3180b57cec5SDimitry Andric       if ((IsAngled && StringRef(Inc.Name).startswith("<")) ||
3190b57cec5SDimitry Andric           (!IsAngled && StringRef(Inc.Name).startswith("\"")))
3200b57cec5SDimitry Andric         return llvm::None;
3210b57cec5SDimitry Andric   std::string Quoted =
3220b57cec5SDimitry Andric       llvm::formatv(IsAngled ? "<{0}>" : "\"{0}\"", IncludeName);
3230b57cec5SDimitry Andric   StringRef QuotedName = Quoted;
3240b57cec5SDimitry Andric   int Priority = Categories.getIncludePriority(
3250b57cec5SDimitry Andric       QuotedName, /*CheckMainHeader=*/FirstIncludeOffset < 0);
3260b57cec5SDimitry Andric   auto CatOffset = CategoryEndOffsets.find(Priority);
3270b57cec5SDimitry Andric   assert(CatOffset != CategoryEndOffsets.end());
3280b57cec5SDimitry Andric   unsigned InsertOffset = CatOffset->second; // Fall back offset
3290b57cec5SDimitry Andric   auto Iter = IncludesByPriority.find(Priority);
3300b57cec5SDimitry Andric   if (Iter != IncludesByPriority.end()) {
3310b57cec5SDimitry Andric     for (const auto *Inc : Iter->second) {
3320b57cec5SDimitry Andric       if (QuotedName < Inc->Name) {
3330b57cec5SDimitry Andric         InsertOffset = Inc->R.getOffset();
3340b57cec5SDimitry Andric         break;
3350b57cec5SDimitry Andric       }
3360b57cec5SDimitry Andric     }
3370b57cec5SDimitry Andric   }
3380b57cec5SDimitry Andric   assert(InsertOffset <= Code.size());
3390b57cec5SDimitry Andric   std::string NewInclude = llvm::formatv("#include {0}\n", QuotedName);
3400b57cec5SDimitry Andric   // When inserting headers at end of the code, also append '\n' to the code
3410b57cec5SDimitry Andric   // if it does not end with '\n'.
3420b57cec5SDimitry Andric   // FIXME: when inserting multiple #includes at the end of code, only one
3430b57cec5SDimitry Andric   // newline should be added.
3440b57cec5SDimitry Andric   if (InsertOffset == Code.size() && (!Code.empty() && Code.back() != '\n'))
3450b57cec5SDimitry Andric     NewInclude = "\n" + NewInclude;
3460b57cec5SDimitry Andric   return tooling::Replacement(FileName, InsertOffset, 0, NewInclude);
3470b57cec5SDimitry Andric }
3480b57cec5SDimitry Andric 
3490b57cec5SDimitry Andric tooling::Replacements HeaderIncludes::remove(llvm::StringRef IncludeName,
3500b57cec5SDimitry Andric                                              bool IsAngled) const {
3510b57cec5SDimitry Andric   assert(IncludeName == trimInclude(IncludeName));
3520b57cec5SDimitry Andric   tooling::Replacements Result;
3530b57cec5SDimitry Andric   auto Iter = ExistingIncludes.find(IncludeName);
3540b57cec5SDimitry Andric   if (Iter == ExistingIncludes.end())
3550b57cec5SDimitry Andric     return Result;
3560b57cec5SDimitry Andric   for (const auto &Inc : Iter->second) {
3570b57cec5SDimitry Andric     if ((IsAngled && StringRef(Inc.Name).startswith("\"")) ||
3580b57cec5SDimitry Andric         (!IsAngled && StringRef(Inc.Name).startswith("<")))
3590b57cec5SDimitry Andric       continue;
3600b57cec5SDimitry Andric     llvm::Error Err = Result.add(tooling::Replacement(
3610b57cec5SDimitry Andric         FileName, Inc.R.getOffset(), Inc.R.getLength(), ""));
3620b57cec5SDimitry Andric     if (Err) {
3630b57cec5SDimitry Andric       auto ErrMsg = "Unexpected conflicts in #include deletions: " +
3640b57cec5SDimitry Andric                     llvm::toString(std::move(Err));
3650b57cec5SDimitry Andric       llvm_unreachable(ErrMsg.c_str());
3660b57cec5SDimitry Andric     }
3670b57cec5SDimitry Andric   }
3680b57cec5SDimitry Andric   return Result;
3690b57cec5SDimitry Andric }
3700b57cec5SDimitry Andric 
3710b57cec5SDimitry Andric } // namespace tooling
3720b57cec5SDimitry Andric } // namespace clang
373