#include "clang/Tooling/Transformer/SourceCode.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Attr.h"
#include "clang/AST/Comment.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DeclTemplate.h"
#include "clang/AST/Expr.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Lex/Lexer.h"
#include "llvm/Support/Errc.h"
#include "llvm/Support/Error.h"
#include <set>
using namespace clang;
using llvm::errc;
using llvm::StringError;
StringRef clang::tooling::getText(CharSourceRange Range,
const ASTContext &Context) {
return Lexer::getSourceText(Range, Context.getSourceManager(),
Context.getLangOpts());
}
CharSourceRange clang::tooling::maybeExtendRange(CharSourceRange Range,
tok::TokenKind Next,
ASTContext &Context) {
CharSourceRange R = Lexer::getAsCharRange(Range, Context.getSourceManager(),
Context.getLangOpts());
if (R.isInvalid())
return Range;
Token Tok;
bool Err =
Lexer::getRawToken(R.getEnd(), Tok, Context.getSourceManager(),
Context.getLangOpts(), true);
if (Err || !Tok.is(Next))
return Range;
return CharSourceRange::getTokenRange(Range.getBegin(), Tok.getLocation());
}
llvm::Error clang::tooling::validateRange(const CharSourceRange &Range,
const SourceManager &SM,
bool AllowSystemHeaders) {
if (Range.isInvalid())
return llvm::make_error<StringError>(errc::invalid_argument,
"Invalid range");
if (Range.getBegin().isMacroID() || Range.getEnd().isMacroID())
return llvm::make_error<StringError>(
errc::invalid_argument, "Range starts or ends in a macro expansion");
if (!AllowSystemHeaders) {
if (SM.isInSystemHeader(Range.getBegin()) ||
SM.isInSystemHeader(Range.getEnd()))
return llvm::make_error<StringError>(errc::invalid_argument,
"Range is in system header");
}
std::pair<FileID, unsigned> BeginInfo = SM.getDecomposedLoc(Range.getBegin());
std::pair<FileID, unsigned> EndInfo = SM.getDecomposedLoc(Range.getEnd());
if (BeginInfo.first != EndInfo.first)
return llvm::make_error<StringError>(
errc::invalid_argument, "Range begins and ends in different files");
if (BeginInfo.second > EndInfo.second)
return llvm::make_error<StringError>(errc::invalid_argument,
"Range's begin is past its end");
return llvm::Error::success();
}
llvm::Error clang::tooling::validateEditRange(const CharSourceRange &Range,
const SourceManager &SM) {
return validateRange(Range, SM, false);
}
static bool spelledInMacroDefinition(SourceLocation Loc,
const SourceManager &SM) {
while (Loc.isMacroID()) {
const auto &Expansion = SM.getSLocEntry(SM.getFileID(Loc)).getExpansion();
if (Expansion.isMacroArgExpansion()) {
Loc = Expansion.getSpellingLoc();
} else {
return true;
}
}
return false;
}
static std::optional<CharSourceRange>
getExpansionForSplitToken(SourceLocation Loc, const SourceManager &SM,
const LangOptions &LangOpts) {
if (Loc.isMacroID()) {
bool Invalid = false;
auto &SLoc = SM.getSLocEntry(SM.getFileID(Loc), &Invalid);
if (Invalid)
return std::nullopt;
if (auto &Expansion = SLoc.getExpansion();
!Expansion.isExpansionTokenRange()) {
return Expansion.getExpansionLocRange();
}
}
return std::nullopt;
}
static CharSourceRange getRangeForSplitTokens(CharSourceRange Range,
const SourceManager &SM,
const LangOptions &LangOpts) {
if (Range.isTokenRange()) {
auto BeginToken = getExpansionForSplitToken(Range.getBegin(), SM, LangOpts);
auto EndToken = getExpansionForSplitToken(Range.getEnd(), SM, LangOpts);
if (EndToken) {
SourceLocation BeginLoc =
BeginToken ? BeginToken->getBegin() : Range.getBegin();
return CharSourceRange::getCharRange(BeginLoc, EndToken->getEnd());
} else if (BeginToken) {
return CharSourceRange::getTokenRange(BeginToken->getBegin(),
Range.getEnd());
}
}
return Range;
}
static CharSourceRange getRange(const CharSourceRange &EditRange,
const SourceManager &SM,
const LangOptions &LangOpts,
bool IncludeMacroExpansion) {
CharSourceRange Range;
if (IncludeMacroExpansion) {
Range = Lexer::makeFileCharRange(EditRange, SM, LangOpts);
} else {
auto AdjustedRange = getRangeForSplitTokens(EditRange, SM, LangOpts);
if (spelledInMacroDefinition(AdjustedRange.getBegin(), SM) ||
spelledInMacroDefinition(AdjustedRange.getEnd(), SM))
return {};
auto B = SM.getSpellingLoc(AdjustedRange.getBegin());
auto E = SM.getSpellingLoc(AdjustedRange.getEnd());
if (AdjustedRange.isTokenRange())
E = Lexer::getLocForEndOfToken(E, 0, SM, LangOpts);
Range = CharSourceRange::getCharRange(B, E);
}
return Range;
}
std::optional<CharSourceRange> clang::tooling::getFileRangeForEdit(
const CharSourceRange &EditRange, const SourceManager &SM,
const LangOptions &LangOpts, bool IncludeMacroExpansion) {
CharSourceRange Range =
getRange(EditRange, SM, LangOpts, IncludeMacroExpansion);
bool IsInvalid = llvm::errorToBool(validateEditRange(Range, SM));
if (IsInvalid)
return std::nullopt;
return Range;
}
std::optional<CharSourceRange> clang::tooling::getFileRange(
const CharSourceRange &EditRange, const SourceManager &SM,
const LangOptions &LangOpts, bool IncludeMacroExpansion) {
CharSourceRange Range =
getRange(EditRange, SM, LangOpts, IncludeMacroExpansion);
bool IsInvalid =
llvm::errorToBool(validateRange(Range, SM, true));
if (IsInvalid)
return std::nullopt;
return Range;
}
static bool startsWithNewline(const SourceManager &SM, const Token &Tok) {
return isVerticalWhitespace(SM.getCharacterData(Tok.getLocation())[0]);
}
static bool contains(const std::set<tok::TokenKind> &Terminators,
const Token &Tok) {
return Terminators.count(Tok.getKind()) > 0;
}
static SourceLocation
getEntityEndLoc(const SourceManager &SM, SourceLocation EntityLast,
const std::set<tok::TokenKind> &Terminators,
const LangOptions &LangOpts) {
assert(EntityLast.isValid() && "Invalid end location found.");
CharSourceRange ExpansionRange = SM.getExpansionRange(EntityLast);
std::unique_ptr<Lexer> Lexer = [&]() {
bool Invalid = false;
auto FileOffset = SM.getDecomposedLoc(ExpansionRange.getEnd());
llvm::StringRef File = SM.getBufferData(FileOffset.first, &Invalid);
assert(!Invalid && "Cannot get file/offset");
return std::make_unique<clang::Lexer>(
SM.getLocForStartOfFile(FileOffset.first), LangOpts, File.begin(),
File.data() + FileOffset.second, File.end());
}();
Lexer->SetKeepWhitespaceMode(true);
Token Tok;
bool Terminated = false;
bool TerminatedByMacro = false;
Lexer->LexFromRawLexer(Tok);
if (Terminators.empty() || contains(Terminators, Tok))
Terminated = true;
else if (EntityLast.isMacroID()) {
Terminated = true;
TerminatedByMacro = true;
}
SourceLocation End = Tok.getEndLoc();
while (!Terminated) {
Lexer->LexFromRawLexer(Tok);
switch (Tok.getKind()) {
case tok::eof:
case tok::l_brace:
case tok::r_brace:
case tok::comma:
return End;
case tok::unknown:
if (startsWithNewline(SM, Tok))
End = Tok.getEndLoc();
break;
default:
if (contains(Terminators, Tok))
Terminated = true;
End = Tok.getEndLoc();
break;
}
}
do {
Lexer->LexFromRawLexer(Tok);
switch (Tok.getKind()) {
case tok::unknown:
if (startsWithNewline(SM, Tok))
return Tok.getEndLoc();
break;
case tok::comment:
End = Tok.getEndLoc();
break;
case tok::semi:
case tok::comma:
if (TerminatedByMacro && contains(Terminators, Tok)) {
End = Tok.getEndLoc();
TerminatedByMacro = false;
break;
}
return End;
default:
return End;
}
} while (true);
}
static std::set<tok::TokenKind> getTerminators(const Decl &D) {
if (llvm::isa<RecordDecl>(D) || llvm::isa<UsingDecl>(D))
return {tok::semi};
if (llvm::isa<FunctionDecl>(D) || llvm::isa<LinkageSpecDecl>(D))
return {tok::r_brace, tok::semi};
if (llvm::isa<VarDecl>(D) || llvm::isa<FieldDecl>(D))
return {tok::comma, tok::semi};
return {};
}
static SourceLocation skipWhitespaceAndNewline(const SourceManager &SM,
SourceLocation Loc,
const LangOptions &LangOpts) {
const char *LocChars = SM.getCharacterData(Loc);
int i = 0;
while (isHorizontalWhitespace(LocChars[i]))
++i;
if (isVerticalWhitespace(LocChars[i]))
++i;
return Loc.getLocWithOffset(i);
}
static bool atOrBeforeSeparation(const SourceManager &SM, SourceLocation Loc,
const LangOptions &LangOpts) {
bool Invalid = false;
const char *LocChars =
SM.getCharacterData(Loc.getLocWithOffset(-1), &Invalid);
assert(!Invalid &&
"Loc must be a valid character and not the first of the source file.");
if (isVerticalWhitespace(LocChars[0])) {
for (int i = 1; isWhitespace(LocChars[i]); ++i)
if (isVerticalWhitespace(LocChars[i]))
return true;
}
Token Tok;
bool Failed = Lexer::getRawToken(Loc, Tok, SM, LangOpts,
true);
if (Failed)
return true;
switch (Tok.getKind()) {
case tok::comment:
case tok::l_brace:
case tok::r_brace:
case tok::eof:
return true;
default:
return false;
}
}
CharSourceRange tooling::getAssociatedRange(const Decl &Decl,
ASTContext &Context) {
const SourceManager &SM = Context.getSourceManager();
const LangOptions &LangOpts = Context.getLangOpts();
CharSourceRange Range = CharSourceRange::getTokenRange(Decl.getSourceRange());
if (const auto *Record = llvm::dyn_cast<CXXRecordDecl>(&Decl)) {
if (const auto *T = Record->getDescribedClassTemplate())
if (SM.isBeforeInTranslationUnit(T->getBeginLoc(), Range.getBegin()))
Range.setBegin(T->getBeginLoc());
} else if (const auto *F = llvm::dyn_cast<FunctionDecl>(&Decl)) {
if (const auto *T = F->getDescribedFunctionTemplate())
if (SM.isBeforeInTranslationUnit(T->getBeginLoc(), Range.getBegin()))
Range.setBegin(T->getBeginLoc());
}
Range.setEnd(
getEntityEndLoc(SM, Decl.getEndLoc(), getTerminators(Decl), LangOpts));
Range.setTokenRange(false);
if (const RawComment *Comment =
Decl.getASTContext().getRawCommentForDeclNoCache(&Decl))
if (SM.isBeforeInTranslationUnit(Comment->getBeginLoc(),
Range.getBegin()) &&
!atOrBeforeSeparation(
SM, skipWhitespaceAndNewline(SM, Comment->getEndLoc(), LangOpts),
LangOpts) &&
atOrBeforeSeparation(SM, Range.getEnd(), LangOpts)) {
const StringRef CommentText = Comment->getRawText(SM);
if (!CommentText.contains("LINT.IfChange") &&
!CommentText.contains("LINT.ThenChange"))
Range.setBegin(Comment->getBeginLoc());
}
for (auto *Attr : Decl.attrs()) {
if (Attr->getLocation().isInvalid() ||
!SM.isBeforeInTranslationUnit(Attr->getLocation(), Range.getBegin()))
continue;
Range.setBegin(Attr->getLocation());
bool Invalid;
StringRef Source =
SM.getBufferData(SM.getFileID(Range.getBegin()), &Invalid);
if (Invalid)
continue;
llvm::StringRef BeforeAttr =
Source.substr(0, SM.getFileOffset(Range.getBegin()));
llvm::StringRef BeforeAttrStripped = BeforeAttr.rtrim();
for (llvm::StringRef Prefix : {"[[", "__attribute__(("}) {
if (BeforeAttrStripped.ends_with(Prefix)) {
Range.setBegin(Range.getBegin().getLocWithOffset(static_cast<int>(
-BeforeAttr.size() + BeforeAttrStripped.size() - Prefix.size())));
break;
}
}
}
return Lexer::makeFileCharRange(Range, SM, LangOpts);
}