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