12 #include "llvm/ADT/Optional.h" 13 #include "llvm/Support/FormatVariadic.h" 19 LangOptions createLangOpts() {
21 LangOpts.CPlusPlus = 1;
22 LangOpts.CPlusPlus11 = 1;
23 LangOpts.CPlusPlus14 = 1;
24 LangOpts.LineComment = 1;
25 LangOpts.CXXOperatorNames = 1;
28 LangOpts.MicrosoftExt = 1;
29 LangOpts.DeclSpecKeyword = 1;
38 unsigned getOffsetAfterTokenSequence(
39 StringRef FileName, StringRef Code,
const IncludeStyle &
Style,
40 llvm::function_ref<
unsigned(
const SourceManager &, Lexer &, Token &)>
41 GetOffsetAfterSequence) {
42 SourceManagerForFile VirtualSM(FileName, Code);
43 SourceManager &
SM = VirtualSM.get();
44 Lexer Lex(SM.getMainFileID(), SM.getBuffer(SM.getMainFileID()), SM,
48 Lex.LexFromRawLexer(Tok);
49 return GetOffsetAfterSequence(SM, Lex, Tok);
56 bool checkAndConsumeDirectiveWithName(
57 Lexer &Lex, StringRef Name, Token &Tok,
59 bool Matched = Tok.is(tok::hash) && !Lex.LexFromRawLexer(Tok) &&
60 Tok.is(tok::raw_identifier) &&
61 Tok.getRawIdentifier() == Name && !Lex.LexFromRawLexer(Tok) &&
62 Tok.is(tok::raw_identifier) &&
63 (!RawIDName || Tok.getRawIdentifier() == *RawIDName);
65 Lex.LexFromRawLexer(Tok);
69 void skipComments(Lexer &Lex, Token &Tok) {
70 while (Tok.is(tok::comment))
71 if (Lex.LexFromRawLexer(Tok))
79 unsigned getOffsetAfterHeaderGuardsAndComments(StringRef FileName,
81 const IncludeStyle &Style) {
84 auto ConsumeHeaderGuardAndComment =
85 [&](std::function<unsigned(
const SourceManager &SM, Lexer &Lex,
88 return getOffsetAfterTokenSequence(
89 FileName, Code, Style,
90 [&Consume](
const SourceManager &SM, Lexer &Lex, Token Tok) {
91 skipComments(Lex, Tok);
92 unsigned InitialOffset = SM.getFileOffset(Tok.getLocation());
93 return std::max(InitialOffset, Consume(SM, Lex, Tok));
98 ConsumeHeaderGuardAndComment(
99 [](
const SourceManager &SM, Lexer &Lex, Token Tok) ->
unsigned {
100 if (checkAndConsumeDirectiveWithName(Lex,
"ifndef", Tok)) {
101 skipComments(Lex, Tok);
102 if (checkAndConsumeDirectiveWithName(Lex,
"define", Tok))
103 return SM.getFileOffset(Tok.getLocation());
108 ConsumeHeaderGuardAndComment(
109 [](
const SourceManager &SM, Lexer &Lex, Token Tok) ->
unsigned {
110 if (checkAndConsumeDirectiveWithName(Lex,
"pragma", Tok,
112 return SM.getFileOffset(Tok.getLocation());
121 bool checkAndConsumeInclusiveDirective(Lexer &Lex, Token &Tok) {
122 auto Matched = [&]() {
123 Lex.LexFromRawLexer(Tok);
126 if (Tok.is(tok::hash) && !Lex.LexFromRawLexer(Tok) &&
127 Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() ==
"include") {
128 if (Lex.LexFromRawLexer(Tok))
130 if (Tok.is(tok::string_literal))
132 if (Tok.is(tok::less)) {
133 while (!Lex.LexFromRawLexer(Tok) && Tok.isNot(tok::greater)) {
135 if (Tok.is(tok::greater))
155 unsigned getMaxHeaderInsertionOffset(StringRef FileName, StringRef Code,
156 const IncludeStyle &Style) {
157 return getOffsetAfterTokenSequence(
158 FileName, Code, Style,
159 [](
const SourceManager &SM, Lexer &Lex, Token Tok) {
160 skipComments(Lex, Tok);
161 unsigned MaxOffset = SM.getFileOffset(Tok.getLocation());
162 while (checkAndConsumeInclusiveDirective(Lex, Tok))
163 MaxOffset = SM.getFileOffset(Tok.getLocation());
168 inline StringRef trimInclude(StringRef IncludeName) {
169 return IncludeName.trim(
"\"<>");
172 const char IncludeRegexPattern[] =
173 R
"(^[\t\ ]*#[\t\ ]*(import|include)[^"<]*(["<][^">]*[">]))"; 179 : Style(Style), FileName(FileName) {
180 FileStem = llvm::sys::path::stem(FileName);
182 CategoryRegexs.emplace_back(
Category.Regex, llvm::Regex::IgnoreCase);
183 IsMainFile = FileName.endswith(
".c") || FileName.endswith(
".cc") ||
184 FileName.endswith(
".cpp") || FileName.endswith(
".c++") ||
185 FileName.endswith(
".cxx") || FileName.endswith(
".m") ||
186 FileName.endswith(
".mm");
189 IsMainFile |= MainFileRegex.match(FileName);
194 bool CheckMainHeader)
const {
196 for (
unsigned i = 0, e = CategoryRegexs.size(); i != e; ++i)
197 if (CategoryRegexs[i].
match(IncludeName)) {
198 Ret = Style.IncludeCategories[i].Priority;
201 if (CheckMainHeader && IsMainFile && Ret > 0 && isMainHeader(IncludeName))
207 bool CheckMainHeader)
const {
209 for (
unsigned i = 0, e = CategoryRegexs.size(); i != e; ++i)
210 if (CategoryRegexs[i].
match(IncludeName)) {
211 Ret = Style.IncludeCategories[i].SortPriority;
213 Ret = Style.IncludeCategories[i].Priority;
216 if (CheckMainHeader && IsMainFile && Ret > 0 && isMainHeader(IncludeName))
220 bool IncludeCategoryManager::isMainHeader(StringRef IncludeName)
const {
221 if (!IncludeName.startswith(
"\""))
223 StringRef HeaderStem =
224 llvm::sys::path::stem(IncludeName.drop_front(1).drop_back(1));
225 if (FileStem.startswith(HeaderStem) ||
226 FileStem.startswith_lower(HeaderStem)) {
227 llvm::Regex MainIncludeRegex(HeaderStem.str() + Style.IncludeIsMainRegex,
228 llvm::Regex::IgnoreCase);
229 if (MainIncludeRegex.match(FileStem))
237 : FileName(FileName), Code(Code), FirstIncludeOffset(-1),
239 getOffsetAfterHeaderGuardsAndComments(FileName, Code, Style)),
240 MaxInsertOffset(MinInsertOffset +
241 getMaxHeaderInsertionOffset(
242 FileName, Code.drop_front(MinInsertOffset), Style)),
243 Categories(Style, FileName),
244 IncludeRegex(
llvm::Regex(IncludeRegexPattern)) {
249 Priorities.insert(
Category.Priority);
251 Code.drop_front(MinInsertOffset).split(Lines,
"\n");
253 unsigned Offset = MinInsertOffset;
254 unsigned NextLineOffset;
256 for (
auto Line : Lines) {
257 NextLineOffset =
std::min(Code.size(), Offset +
Line.size() + 1);
258 if (IncludeRegex.match(
Line, &Matches)) {
267 Offset = NextLineOffset;
274 auto Highest = Priorities.begin();
275 if (CategoryEndOffsets.find(*Highest) == CategoryEndOffsets.end()) {
276 if (FirstIncludeOffset >= 0)
277 CategoryEndOffsets[*Highest] = FirstIncludeOffset;
279 CategoryEndOffsets[*Highest] = MinInsertOffset;
285 for (
auto I = ++Priorities.begin(), E = Priorities.end(); I != E; ++I)
286 if (CategoryEndOffsets.find(*I) == CategoryEndOffsets.end())
287 CategoryEndOffsets[*I] = CategoryEndOffsets[*std::prev(I)];
291 void HeaderIncludes::addExistingInclude(Include IncludeToAdd,
292 unsigned NextLineOffset) {
294 ExistingIncludes.try_emplace(trimInclude(IncludeToAdd.Name)).first;
295 Iter->second.push_back(std::move(IncludeToAdd));
296 auto &CurInclude = Iter->second.back();
299 if (CurInclude.R.getOffset() <= MaxInsertOffset) {
301 CurInclude.Name, FirstIncludeOffset < 0);
302 CategoryEndOffsets[
Priority] = NextLineOffset;
303 IncludesByPriority[
Priority].push_back(&CurInclude);
304 if (FirstIncludeOffset < 0)
305 FirstIncludeOffset = CurInclude.R.getOffset();
311 assert(IncludeName == trimInclude(IncludeName));
315 auto It = ExistingIncludes.find(IncludeName);
316 if (It != ExistingIncludes.end())
317 for (
const auto &Inc : It->second)
318 if ((IsAngled && StringRef(Inc.Name).startswith(
"<")) ||
319 (!IsAngled && StringRef(Inc.Name).startswith(
"\"")))
322 llvm::formatv(IsAngled ?
"<{0}>" :
"\"{0}\"", IncludeName);
323 StringRef QuotedName = Quoted;
325 QuotedName, FirstIncludeOffset < 0);
326 auto CatOffset = CategoryEndOffsets.find(Priority);
327 assert(CatOffset != CategoryEndOffsets.end());
328 unsigned InsertOffset = CatOffset->second;
329 auto Iter = IncludesByPriority.find(Priority);
330 if (Iter != IncludesByPriority.end()) {
331 for (
const auto *Inc : Iter->second) {
332 if (QuotedName < Inc->Name) {
333 InsertOffset = Inc->R.getOffset();
338 assert(InsertOffset <= Code.size());
339 std::string NewInclude = llvm::formatv(
"#include {0}\n", QuotedName);
344 if (InsertOffset == Code.size() && (!Code.empty() && Code.back() !=
'\n'))
345 NewInclude =
"\n" + NewInclude;
350 bool IsAngled)
const {
351 assert(IncludeName == trimInclude(IncludeName));
353 auto Iter = ExistingIncludes.find(IncludeName);
354 if (Iter == ExistingIncludes.end())
356 for (
const auto &Inc : Iter->second) {
357 if ((IsAngled && StringRef(Inc.Name).startswith(
"\"")) ||
358 (!IsAngled && StringRef(Inc.Name).startswith(
"<")))
361 FileName, Inc.R.getOffset(), Inc.R.getLength(),
""));
363 auto ErrMsg =
"Unexpected conflicts in #include deletions: " +
365 llvm_unreachable(ErrMsg.c_str());
Specialize PointerLikeTypeTraits to allow LazyGenerationalUpdatePtr to be placed into a PointerUnion...
Defines the SourceManager interface.
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
__DEVICE__ int max(int __a, int __b)
SmallVector< BoundNodes, 1 > match(MatcherT Matcher, const NodeT &Node, ASTContext &Context)
Returns the results of matching Matcher on Node.
const AnnotatedLine * Line
static bool Ret(InterpState &S, CodePtr &PC, APValue &Result)
Dataflow Directional Tag Classes.
__DEVICE__ int min(int __a, int __b)