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