17#include "llvm/ADT/STLFunctionalExtras.h"
18#include "llvm/ADT/StringRef.h"
19#include "llvm/Support/Error.h"
20#include "llvm/Support/ErrorHandling.h"
21#include "llvm/Support/FormatVariadic.h"
22#include "llvm/Support/Path.h"
23#include "llvm/Support/Regex.h"
37LangOptions createLangOpts() {
39 LangOpts.CPlusPlus = 1;
40 LangOpts.CPlusPlus11 = 1;
41 LangOpts.CPlusPlus14 = 1;
42 LangOpts.LineComment = 1;
43 LangOpts.CXXOperatorNames = 1;
46 LangOpts.MicrosoftExt = 1;
47 LangOpts.DeclSpecKeyword = 1;
59 -> std::invoke_result_t<F, const SourceManager &, Lexer &> {
60 SourceManagerForFile VirtualSM(
FileName, Code);
61 SourceManager &
SM = VirtualSM.get();
62 LangOptions LangOpts = createLangOpts();
63 Lexer Lex(
SM.getMainFileID(),
SM.getBufferOrFake(
SM.getMainFileID()),
SM,
65 return std::invoke(std::forward<F>(Callback), std::as_const(
SM), Lex);
72unsigned getOffsetAfterTokenSequence(
74 llvm::function_ref<
unsigned(
const SourceManager &, Lexer &, Token &)>
75 GetOffsetAfterSequence) {
76 return withLexer(
FileName, Code, Style,
77 [&](
const SourceManager &
SM, Lexer &Lex) {
80 Lex.LexFromRawLexer(
Tok);
81 return GetOffsetAfterSequence(
SM, Lex,
Tok);
89bool checkAndConsumeDirectiveWithName(
90 Lexer &Lex, StringRef Name, Token &
Tok,
91 std::optional<StringRef> RawIDName = std::nullopt) {
92 bool Matched =
Tok.is(tok::hash) && !Lex.LexFromRawLexer(
Tok) &&
93 Tok.is(tok::raw_identifier) &&
94 Tok.getRawIdentifier() == Name && !Lex.LexFromRawLexer(
Tok) &&
95 Tok.is(tok::raw_identifier) &&
96 (!RawIDName ||
Tok.getRawIdentifier() == *RawIDName);
98 Lex.LexFromRawLexer(
Tok);
102void skipComments(Lexer &Lex, Token &
Tok) {
103 while (
Tok.is(tok::comment))
104 if (Lex.LexFromRawLexer(
Tok))
108bool checkAndConsumeModuleDecl(
const SourceManager &
SM, Lexer &Lex,
110 bool Matched =
Tok.is(tok::raw_identifier) &&
111 Tok.getRawIdentifier() ==
"module" &&
112 !Lex.LexFromRawLexer(
Tok) &&
Tok.is(tok::semi) &&
113 !Lex.LexFromRawLexer(
Tok);
124unsigned getMinHeaderInsertionOffset(StringRef
FileName, StringRef Code,
128 auto ConsumeHeaderGuardAndComment =
132 return getOffsetAfterTokenSequence(
134 [&Consume](
const SourceManager &
SM, Lexer &Lex, Token
Tok) {
135 skipComments(Lex,
Tok);
136 unsigned InitialOffset =
SM.getFileOffset(
Tok.getLocation());
137 return std::max(InitialOffset, Consume(
SM, Lex,
Tok));
141 auto ModuleDecl = ConsumeHeaderGuardAndComment(
142 [](
const SourceManager &
SM, Lexer &Lex, Token
Tok) ->
unsigned {
143 if (checkAndConsumeModuleDecl(
SM, Lex,
Tok)) {
144 skipComments(Lex,
Tok);
145 return SM.getFileOffset(
Tok.getLocation());
150 auto HeaderAndPPOffset = std::max(
152 ConsumeHeaderGuardAndComment(
153 [](
const SourceManager &
SM, Lexer &Lex, Token
Tok) ->
unsigned {
154 if (checkAndConsumeDirectiveWithName(Lex,
"ifndef",
Tok)) {
155 skipComments(Lex,
Tok);
156 if (checkAndConsumeDirectiveWithName(Lex,
"define",
Tok) &&
157 Tok.isAtStartOfLine())
158 return SM.getFileOffset(
Tok.getLocation());
163 ConsumeHeaderGuardAndComment(
164 [](
const SourceManager &
SM, Lexer &Lex, Token
Tok) ->
unsigned {
165 if (checkAndConsumeDirectiveWithName(Lex,
"pragma",
Tok,
167 return SM.getFileOffset(
Tok.getLocation());
170 return std::max(HeaderAndPPOffset, ModuleDecl);
177bool checkAndConsumeInclusiveDirective(Lexer &Lex, Token &
Tok) {
178 auto Matched = [&]() {
179 Lex.LexFromRawLexer(
Tok);
182 if (
Tok.is(tok::hash) && !Lex.LexFromRawLexer(
Tok) &&
183 Tok.is(tok::raw_identifier) &&
184 (
Tok.getRawIdentifier() ==
"include" ||
185 Tok.getRawIdentifier() ==
"import")) {
186 if (Lex.LexFromRawLexer(
Tok))
188 if (
Tok.is(tok::string_literal))
190 if (
Tok.is(tok::less)) {
191 while (!Lex.LexFromRawLexer(
Tok) &&
Tok.isNot(tok::greater)) {
193 if (
Tok.is(tok::greater))
213unsigned getMaxHeaderInsertionOffset(StringRef
FileName, StringRef Code,
215 return getOffsetAfterTokenSequence(
217 [](
const SourceManager &
SM, Lexer &Lex, Token
Tok) {
218 skipComments(Lex,
Tok);
220 while (checkAndConsumeInclusiveDirective(Lex,
Tok))
228bool isFirstDeclModuleDecl(StringRef
FileName, StringRef Code,
231 FileName, Code, Style, [](
const SourceManager &
SM, Lexer &Lex) {
233 Lex.SetKeepWhitespaceMode(
false);
234 Lex.SetCommentRetentionState(
false);
237 if (Lex.LexFromRawLexer(tok))
248 if (tok.is(tok::raw_identifier) && tok.getRawIdentifier() ==
"export") {
249 if (Lex.LexFromRawLexer(tok))
254 if (!tok.is(tok::raw_identifier) ||
255 tok.getRawIdentifier() !=
"module" || Lex.LexFromRawLexer(tok))
259 return tok.is(tok::raw_identifier);
263inline StringRef trimInclude(StringRef IncludeName) {
264 return IncludeName.trim(
"\"<>");
267const char IncludeRegexPattern[] =
268 "^[\t ]*#[\t ]*(import|include)[^\"<]*([\"<][^\">]*[\">])";
275StringRef matchingStem(llvm::StringRef Path) {
276 StringRef Name = llvm::sys::path::filename(Path);
277 return Name.substr(0, Name.find(
'.', 1));
284 : Style(Style), FileName(FileName) {
285 for (
const auto &Category : Style.IncludeCategories) {
286 CategoryRegexs.emplace_back(Category.Regex, Category.RegexIsCaseSensitive
287 ? llvm::Regex::NoFlags
288 : llvm::Regex::IgnoreCase);
290 IsMainFile = FileName.ends_with(
".c") || FileName.ends_with(
".cc") ||
291 FileName.ends_with(
".cpp") || FileName.ends_with(
".c++") ||
292 FileName.ends_with(
".cxx") || FileName.ends_with(
".m") ||
293 FileName.ends_with(
".mm");
294 if (!Style.IncludeIsMainSourceRegex.empty()) {
295 llvm::Regex MainFileRegex(Style.IncludeIsMainSourceRegex);
296 IsMainFile |= MainFileRegex.match(FileName);
301 bool CheckMainHeader)
const {
303 for (
unsigned i = 0, e = CategoryRegexs.size(); i != e; ++i)
304 if (CategoryRegexs[i].
match(IncludeName)) {
305 Ret = Style.IncludeCategories[i].Priority;
308 if (CheckMainHeader && IsMainFile && Ret > 0 && isMainHeader(IncludeName))
314 bool CheckMainHeader)
const {
316 for (
unsigned i = 0, e = CategoryRegexs.size(); i != e; ++i)
317 if (CategoryRegexs[i].
match(IncludeName)) {
318 Ret = Style.IncludeCategories[i].SortPriority;
320 Ret = Style.IncludeCategories[i].Priority;
323 if (CheckMainHeader && IsMainFile && Ret > 0 && isMainHeader(IncludeName))
327bool IncludeCategoryManager::isMainHeader(StringRef IncludeName)
const {
328 switch (Style.MainIncludeChar) {
329 case IncludeStyle::MICD_Quote:
330 if (!IncludeName.starts_with(
"\""))
334 if (!IncludeName.starts_with(
"<"))
337 case IncludeStyle::MICD_Any:
342 IncludeName.drop_front(1).drop_back(1);
345 StringRef HeaderStem = llvm::sys::path::stem(IncludeName);
346 StringRef FileStem = llvm::sys::path::stem(
FileName);
347 StringRef MatchingFileStem = matchingStem(
FileName);
357 if (MatchingFileStem.starts_with_insensitive(HeaderStem))
358 Matching = MatchingFileStem;
359 else if (FileStem.equals_insensitive(HeaderStem))
361 if (!Matching.empty()) {
362 llvm::Regex MainIncludeRegex(llvm::Regex::escape(HeaderStem) +
363 Style.IncludeIsMainRegex,
364 llvm::Regex::IgnoreCase);
365 if (MainIncludeRegex.match(Matching))
375 : FileName(FileName), Code(Code), FirstIncludeOffset(-1),
376 MinInsertOffset(getMinHeaderInsertionOffset(FileName, Code, Style)),
377 MaxInsertOffset(MinInsertOffset +
378 getMaxHeaderInsertionOffset(
379 FileName, Code.drop_front(MinInsertOffset), Style)),
380 MainIncludeFound(
false),
381 ShouldInsertGlobalModuleFragmentDecl(
382 isFirstDeclModuleDecl(FileName, Code, Style)),
383 Categories(Style, FileName) {
387 for (
const auto &Category : Style.IncludeCategories)
388 Priorities.insert(Category.Priority);
390 Code.drop_front(MinInsertOffset).split(Lines,
"\n");
392 unsigned Offset = MinInsertOffset;
393 unsigned NextLineOffset;
396 NextLineOffset = std::min(Code.size(), Offset +
Line.size() + 1);
403 Offset, std::min(
Line.size() + 1, Code.size() - Offset)),
408 Offset = NextLineOffset;
415 auto Highest = Priorities.begin();
416 auto [It, Inserted] = CategoryEndOffsets.try_emplace(*Highest);
418 It->second = FirstIncludeOffset >= 0 ? FirstIncludeOffset : MinInsertOffset;
423 for (
auto I = ++Priorities.begin(), E = Priorities.end(); I != E; ++I)
424 if (CategoryEndOffsets.find(*I) == CategoryEndOffsets.end())
425 CategoryEndOffsets[*I] = CategoryEndOffsets[*std::prev(I)];
429void HeaderIncludes::addExistingInclude(
Include IncludeToAdd,
430 unsigned NextLineOffset) {
431 auto &Incs = ExistingIncludes[trimInclude(IncludeToAdd.Name)];
432 Incs.push_back(std::move(IncludeToAdd));
433 auto &CurInclude = Incs.back();
436 if (CurInclude.R.getOffset() <= MaxInsertOffset) {
438 CurInclude.Name, !MainIncludeFound);
440 MainIncludeFound =
true;
441 CategoryEndOffsets[Priority] = NextLineOffset;
442 IncludesByPriority[Priority].push_back(&CurInclude);
443 if (FirstIncludeOffset < 0)
444 FirstIncludeOffset = CurInclude.R.getOffset();
448std::optional<tooling::Replacement>
451 assert(Header == trimInclude(Header));
455 auto It = ExistingIncludes.find(Header);
456 if (It != ExistingIncludes.end()) {
457 for (
const auto &Inc : It->second)
459 ((IsAngled && StringRef(Inc.Name).starts_with(
"<")) ||
460 (!IsAngled && StringRef(Inc.Name).starts_with(
"\""))))
464 std::string(llvm::formatv(IsAngled ?
"<{0}>" :
"\"{0}\"", Header));
465 StringRef QuotedName = Quoted;
466 int Priority = Categories.getIncludePriority(
467 QuotedName, !MainIncludeFound);
468 auto CatOffset = CategoryEndOffsets.find(Priority);
469 assert(CatOffset != CategoryEndOffsets.end());
470 unsigned InsertOffset = CatOffset->second;
471 auto Iter = IncludesByPriority.find(Priority);
472 if (Iter != IncludesByPriority.end()) {
473 for (
const auto *Inc : Iter->second) {
474 if (QuotedName < Inc->Name) {
475 InsertOffset = Inc->R.getOffset();
480 assert(InsertOffset <= Code.size());
481 llvm::StringRef DirectiveSpelling =
483 std::string NewInclude =
484 llvm::formatv(
"#{0} {1}\n", DirectiveSpelling, QuotedName);
489 if (InsertOffset == Code.size() && (!Code.empty() && Code.back() !=
'\n'))
490 NewInclude =
"\n" + NewInclude;
491 if (ShouldInsertGlobalModuleFragmentDecl)
492 NewInclude =
"module;\n" + NewInclude;
497 bool IsAngled)
const {
498 assert(IncludeName == trimInclude(IncludeName));
500 auto Iter = ExistingIncludes.find(IncludeName);
501 if (Iter == ExistingIncludes.end())
503 for (
const auto &Inc : Iter->second) {
504 if ((IsAngled && StringRef(Inc.Name).starts_with(
"\"")) ||
505 (!IsAngled && StringRef(Inc.Name).starts_with(
"<")))
508 FileName, Inc.R.getOffset(), Inc.R.getLength(),
""));
510 auto ErrMsg =
"Unexpected conflicts in #include deletions: " +
511 llvm::toString(std::move(Err));
512 llvm_unreachable(ErrMsg.c_str());
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the SourceManager interface.
Defines the clang::TokenKind enum and support functions.
VerifyDiagnosticConsumer::Directive Directive
SmallVector< BoundNodes, 1 > match(MatcherT Matcher, const NodeT &Node, ASTContext &Context)
Returns the results of matching Matcher on Node.
The JSON file list parser is used to communicate input to InstallAPI.
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
@ Result
The result type of a method or function.
for(const auto &A :T->param_types())
int const char * function