#include "clang/Tooling/Inclusions/HeaderIncludes.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Lex/Lexer.h"
#include "llvm/ADT/Optional.h"
#include "llvm/Support/FormatVariadic.h"
#include "llvm/Support/Path.h"
namespace clang {
namespace tooling {
namespace {
LangOptions createLangOpts() {
LangOptions LangOpts;
LangOpts.CPlusPlus = 1;
LangOpts.CPlusPlus11 = 1;
LangOpts.CPlusPlus14 = 1;
LangOpts.LineComment = 1;
LangOpts.CXXOperatorNames = 1;
LangOpts.Bool = 1;
LangOpts.ObjC = 1;
LangOpts.MicrosoftExt = 1; LangOpts.DeclSpecKeyword = 1; LangOpts.WChar = 1; return LangOpts;
}
unsigned getOffsetAfterTokenSequence(
StringRef FileName, StringRef Code, const IncludeStyle &Style,
llvm::function_ref<unsigned(const SourceManager &, Lexer &, Token &)>
GetOffsetAfterSequence) {
SourceManagerForFile VirtualSM(FileName, Code);
SourceManager &SM = VirtualSM.get();
LangOptions LangOpts = createLangOpts();
Lexer Lex(SM.getMainFileID(), SM.getBufferOrFake(SM.getMainFileID()), SM,
LangOpts);
Token Tok;
Lex.LexFromRawLexer(Tok);
return GetOffsetAfterSequence(SM, Lex, Tok);
}
bool checkAndConsumeDirectiveWithName(
Lexer &Lex, StringRef Name, Token &Tok,
llvm::Optional<StringRef> RawIDName = llvm::None) {
bool Matched = Tok.is(tok::hash) && !Lex.LexFromRawLexer(Tok) &&
Tok.is(tok::raw_identifier) &&
Tok.getRawIdentifier() == Name && !Lex.LexFromRawLexer(Tok) &&
Tok.is(tok::raw_identifier) &&
(!RawIDName || Tok.getRawIdentifier() == *RawIDName);
if (Matched)
Lex.LexFromRawLexer(Tok);
return Matched;
}
void skipComments(Lexer &Lex, Token &Tok) {
while (Tok.is(tok::comment))
if (Lex.LexFromRawLexer(Tok))
return;
}
unsigned getOffsetAfterHeaderGuardsAndComments(StringRef FileName,
StringRef Code,
const IncludeStyle &Style) {
auto ConsumeHeaderGuardAndComment =
[&](std::function<unsigned(const SourceManager &SM, Lexer &Lex,
Token Tok)>
Consume) {
return getOffsetAfterTokenSequence(
FileName, Code, Style,
[&Consume](const SourceManager &SM, Lexer &Lex, Token Tok) {
skipComments(Lex, Tok);
unsigned InitialOffset = SM.getFileOffset(Tok.getLocation());
return std::max(InitialOffset, Consume(SM, Lex, Tok));
});
};
return std::max(
ConsumeHeaderGuardAndComment(
[](const SourceManager &SM, Lexer &Lex, Token Tok) -> unsigned {
if (checkAndConsumeDirectiveWithName(Lex, "ifndef", Tok)) {
skipComments(Lex, Tok);
if (checkAndConsumeDirectiveWithName(Lex, "define", Tok) &&
Tok.isAtStartOfLine())
return SM.getFileOffset(Tok.getLocation());
}
return 0;
}),
ConsumeHeaderGuardAndComment(
[](const SourceManager &SM, Lexer &Lex, Token Tok) -> unsigned {
if (checkAndConsumeDirectiveWithName(Lex, "pragma", Tok,
StringRef("once")))
return SM.getFileOffset(Tok.getLocation());
return 0;
}));
}
bool checkAndConsumeInclusiveDirective(Lexer &Lex, Token &Tok) {
auto Matched = [&]() {
Lex.LexFromRawLexer(Tok);
return true;
};
if (Tok.is(tok::hash) && !Lex.LexFromRawLexer(Tok) &&
Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "include") {
if (Lex.LexFromRawLexer(Tok))
return false;
if (Tok.is(tok::string_literal))
return Matched();
if (Tok.is(tok::less)) {
while (!Lex.LexFromRawLexer(Tok) && Tok.isNot(tok::greater)) {
}
if (Tok.is(tok::greater))
return Matched();
}
}
return false;
}
unsigned getMaxHeaderInsertionOffset(StringRef FileName, StringRef Code,
const IncludeStyle &Style) {
return getOffsetAfterTokenSequence(
FileName, Code, Style,
[](const SourceManager &SM, Lexer &Lex, Token Tok) {
skipComments(Lex, Tok);
unsigned MaxOffset = SM.getFileOffset(Tok.getLocation());
while (checkAndConsumeInclusiveDirective(Lex, Tok))
MaxOffset = SM.getFileOffset(Tok.getLocation());
return MaxOffset;
});
}
inline StringRef trimInclude(StringRef IncludeName) {
return IncludeName.trim("\"<>");
}
const char IncludeRegexPattern[] =
R"(^[\t\ ]*#[\t\ ]*(import|include)[^"<]*(["<][^">]*[">]))";
StringRef matchingStem(llvm::StringRef Path) {
StringRef Name = llvm::sys::path::filename(Path);
return Name.substr(0, Name.find('.', 1));
}
}
IncludeCategoryManager::IncludeCategoryManager(const IncludeStyle &Style,
StringRef FileName)
: Style(Style), FileName(FileName) {
for (const auto &Category : Style.IncludeCategories) {
CategoryRegexs.emplace_back(Category.Regex, Category.RegexIsCaseSensitive
? llvm::Regex::NoFlags
: llvm::Regex::IgnoreCase);
}
IsMainFile = FileName.endswith(".c") || FileName.endswith(".cc") ||
FileName.endswith(".cpp") || FileName.endswith(".c++") ||
FileName.endswith(".cxx") || FileName.endswith(".m") ||
FileName.endswith(".mm");
if (!Style.IncludeIsMainSourceRegex.empty()) {
llvm::Regex MainFileRegex(Style.IncludeIsMainSourceRegex);
IsMainFile |= MainFileRegex.match(FileName);
}
}
int IncludeCategoryManager::getIncludePriority(StringRef IncludeName,
bool CheckMainHeader) const {
int Ret = INT_MAX;
for (unsigned i = 0, e = CategoryRegexs.size(); i != e; ++i)
if (CategoryRegexs[i].match(IncludeName)) {
Ret = Style.IncludeCategories[i].Priority;
break;
}
if (CheckMainHeader && IsMainFile && Ret > 0 && isMainHeader(IncludeName))
Ret = 0;
return Ret;
}
int IncludeCategoryManager::getSortIncludePriority(StringRef IncludeName,
bool CheckMainHeader) const {
int Ret = INT_MAX;
for (unsigned i = 0, e = CategoryRegexs.size(); i != e; ++i)
if (CategoryRegexs[i].match(IncludeName)) {
Ret = Style.IncludeCategories[i].SortPriority;
if (Ret == 0)
Ret = Style.IncludeCategories[i].Priority;
break;
}
if (CheckMainHeader && IsMainFile && Ret > 0 && isMainHeader(IncludeName))
Ret = 0;
return Ret;
}
bool IncludeCategoryManager::isMainHeader(StringRef IncludeName) const {
if (!IncludeName.startswith("\""))
return false;
IncludeName =
IncludeName.drop_front(1).drop_back(1); StringRef HeaderStem = llvm::sys::path::stem(IncludeName);
StringRef FileStem = llvm::sys::path::stem(FileName); StringRef MatchingFileStem = matchingStem(FileName); StringRef Matching;
if (MatchingFileStem.startswith_insensitive(HeaderStem))
Matching = MatchingFileStem; else if (FileStem.equals_insensitive(HeaderStem))
Matching = FileStem; if (!Matching.empty()) {
llvm::Regex MainIncludeRegex(HeaderStem.str() + Style.IncludeIsMainRegex,
llvm::Regex::IgnoreCase);
if (MainIncludeRegex.match(Matching))
return true;
}
return false;
}
HeaderIncludes::HeaderIncludes(StringRef FileName, StringRef Code,
const IncludeStyle &Style)
: FileName(FileName), Code(Code), FirstIncludeOffset(-1),
MinInsertOffset(
getOffsetAfterHeaderGuardsAndComments(FileName, Code, Style)),
MaxInsertOffset(MinInsertOffset +
getMaxHeaderInsertionOffset(
FileName, Code.drop_front(MinInsertOffset), Style)),
Categories(Style, FileName),
IncludeRegex(llvm::Regex(IncludeRegexPattern)) {
Priorities = {0, INT_MAX};
for (const auto &Category : Style.IncludeCategories)
Priorities.insert(Category.Priority);
SmallVector<StringRef, 32> Lines;
Code.drop_front(MinInsertOffset).split(Lines, "\n");
unsigned Offset = MinInsertOffset;
unsigned NextLineOffset;
SmallVector<StringRef, 4> Matches;
for (auto Line : Lines) {
NextLineOffset = std::min(Code.size(), Offset + Line.size() + 1);
if (IncludeRegex.match(Line, &Matches)) {
addExistingInclude(
Include(Matches[2],
tooling::Range(
Offset, std::min(Line.size() + 1, Code.size() - Offset))),
NextLineOffset);
}
Offset = NextLineOffset;
}
auto Highest = Priorities.begin();
if (CategoryEndOffsets.find(*Highest) == CategoryEndOffsets.end()) {
if (FirstIncludeOffset >= 0)
CategoryEndOffsets[*Highest] = FirstIncludeOffset;
else
CategoryEndOffsets[*Highest] = MinInsertOffset;
}
for (auto I = ++Priorities.begin(), E = Priorities.end(); I != E; ++I)
if (CategoryEndOffsets.find(*I) == CategoryEndOffsets.end())
CategoryEndOffsets[*I] = CategoryEndOffsets[*std::prev(I)];
}
void HeaderIncludes::addExistingInclude(Include IncludeToAdd,
unsigned NextLineOffset) {
auto Iter =
ExistingIncludes.try_emplace(trimInclude(IncludeToAdd.Name)).first;
Iter->second.push_back(std::move(IncludeToAdd));
auto &CurInclude = Iter->second.back();
if (CurInclude.R.getOffset() <= MaxInsertOffset) {
int Priority = Categories.getIncludePriority(
CurInclude.Name, FirstIncludeOffset < 0);
CategoryEndOffsets[Priority] = NextLineOffset;
IncludesByPriority[Priority].push_back(&CurInclude);
if (FirstIncludeOffset < 0)
FirstIncludeOffset = CurInclude.R.getOffset();
}
}
llvm::Optional<tooling::Replacement>
HeaderIncludes::insert(llvm::StringRef IncludeName, bool IsAngled) const {
assert(IncludeName == trimInclude(IncludeName));
auto It = ExistingIncludes.find(IncludeName);
if (It != ExistingIncludes.end())
for (const auto &Inc : It->second)
if ((IsAngled && StringRef(Inc.Name).startswith("<")) ||
(!IsAngled && StringRef(Inc.Name).startswith("\"")))
return llvm::None;
std::string Quoted =
std::string(llvm::formatv(IsAngled ? "<{0}>" : "\"{0}\"", IncludeName));
StringRef QuotedName = Quoted;
int Priority = Categories.getIncludePriority(
QuotedName, FirstIncludeOffset < 0);
auto CatOffset = CategoryEndOffsets.find(Priority);
assert(CatOffset != CategoryEndOffsets.end());
unsigned InsertOffset = CatOffset->second; auto Iter = IncludesByPriority.find(Priority);
if (Iter != IncludesByPriority.end()) {
for (const auto *Inc : Iter->second) {
if (QuotedName < Inc->Name) {
InsertOffset = Inc->R.getOffset();
break;
}
}
}
assert(InsertOffset <= Code.size());
std::string NewInclude =
std::string(llvm::formatv("#include {0}\n", QuotedName));
if (InsertOffset == Code.size() && (!Code.empty() && Code.back() != '\n'))
NewInclude = "\n" + NewInclude;
return tooling::Replacement(FileName, InsertOffset, 0, NewInclude);
}
tooling::Replacements HeaderIncludes::remove(llvm::StringRef IncludeName,
bool IsAngled) const {
assert(IncludeName == trimInclude(IncludeName));
tooling::Replacements Result;
auto Iter = ExistingIncludes.find(IncludeName);
if (Iter == ExistingIncludes.end())
return Result;
for (const auto &Inc : Iter->second) {
if ((IsAngled && StringRef(Inc.Name).startswith("\"")) ||
(!IsAngled && StringRef(Inc.Name).startswith("<")))
continue;
llvm::Error Err = Result.add(tooling::Replacement(
FileName, Inc.R.getOffset(), Inc.R.getLength(), ""));
if (Err) {
auto ErrMsg = "Unexpected conflicts in #include deletions: " +
llvm::toString(std::move(Err));
llvm_unreachable(ErrMsg.c_str());
}
}
return Result;
}
} }