1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
|
//===--- SourceLocationUtilities.cpp - Source location helper functions ---===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "SourceLocationUtilities.h"
#include "clang/AST/Stmt.h"
#include "clang/Lex/Lexer.h"
#include <limits>
namespace clang {
namespace tooling {
SourceLocation findLastLocationOfSourceConstruct(SourceLocation HeaderEnd,
const Stmt *Body,
const SourceManager &SM) {
SourceLocation BodyStart = SM.getSpellingLoc(Body->getBeginLoc());
unsigned BodyLine = SM.getSpellingLineNumber(BodyStart);
unsigned HeaderLine = SM.getSpellingLineNumber(HeaderEnd);
if (BodyLine > HeaderLine) {
// The Last location on the previous line if the body is not on the same
// line as the last known location.
SourceLocation LineLocThatPrecedesBody =
SM.translateLineCol(SM.getFileID(BodyStart), BodyLine - 1,
std::numeric_limits<unsigned>::max());
if (LineLocThatPrecedesBody.isValid())
return LineLocThatPrecedesBody;
}
// We want to include the location of the '{'.
return isa<CompoundStmt>(Body) ? BodyStart : BodyStart.getLocWithOffset(-1);
}
SourceLocation findFirstLocationOfSourceConstruct(SourceLocation HeaderStart,
const Stmt *PreviousBody,
const SourceManager &SM) {
if (!isa<CompoundStmt>(PreviousBody))
return HeaderStart;
SourceLocation BodyEnd = SM.getSpellingLoc(PreviousBody->getEndLoc());
unsigned BodyLine = SM.getSpellingLineNumber(BodyEnd);
unsigned HeaderLine = SM.getSpellingLineNumber(HeaderStart);
if (BodyLine >= HeaderLine)
return BodyEnd;
return HeaderStart;
}
bool isLocationInAnyRange(SourceLocation Location, ArrayRef<SourceRange> Ranges,
const SourceManager &SM) {
for (const SourceRange &Range : Ranges) {
if (!isPointWithin(Location, Range.getBegin(), Range.getEnd(), SM))
continue;
return true;
}
return false;
}
SourceLocation getPreciseTokenLocEnd(SourceLocation Loc,
const SourceManager &SM,
const LangOptions &LangOpts) {
return Lexer::getLocForEndOfToken(Loc, 0, SM, LangOpts);
}
SourceLocation findClosingParenLocEnd(SourceLocation LastKnownLoc,
const SourceManager &SM,
const LangOptions &LangOpts) {
return Lexer::findLocationAfterToken(
LastKnownLoc, tok::r_paren, SM, LangOpts,
/*SkipTrailingWhitespaceAndNewLine=*/false);
}
SourceRange getRangeOfNextToken(SourceLocation Loc, tok::TokenKind Kind,
const SourceManager &SM,
const LangOptions &LangOpts) {
SourceLocation NextLoc =
Lexer::findLocationAfterToken(Loc, Kind, SM, LangOpts,
/*SkipTrailingWhitespaceAndNewLine=*/false);
if (NextLoc.isInvalid())
return SourceRange();
return SourceRange(
Lexer::GetBeginningOfToken(NextLoc.getLocWithOffset(-1), SM, LangOpts),
NextLoc);
}
SourceLocation findLastNonCompoundLocation(const Stmt *S) {
const auto *CS = dyn_cast<CompoundStmt>(S);
if (!CS)
return S->getEndLoc();
return CS->body_back() ? CS->body_back()->getEndLoc() : SourceLocation();
}
bool areOnSameLine(SourceLocation Loc1, SourceLocation Loc2,
const SourceManager &SM) {
return !Loc1.isMacroID() && !Loc2.isMacroID() &&
SM.getSpellingLineNumber(Loc1) == SM.getSpellingLineNumber(Loc2);
}
SourceLocation
getLastLineLocationUnlessItHasOtherTokens(SourceLocation SpellingLoc,
const SourceManager &SM,
const LangOptions &LangOpts) {
assert(!SpellingLoc.isMacroID() && "Expecting a spelling location");
SourceLocation NextTokenLoc =
Lexer::findNextTokenLocationAfterTokenAt(SpellingLoc, SM, LangOpts);
if (NextTokenLoc.isValid()) {
bool IsSameLine = areOnSameLine(SpellingLoc, NextTokenLoc, SM);
if (IsSameLine) {
// Could be a ';' on the same line, so try looking after the ';'
if (isSemicolonAtLocation(NextTokenLoc, SM, LangOpts))
return getLastLineLocationUnlessItHasOtherTokens(NextTokenLoc, SM,
LangOpts);
} else {
SourceLocation LastLoc = SM.translateLineCol(
SM.getFileID(SpellingLoc), SM.getSpellingLineNumber(SpellingLoc),
std::numeric_limits<unsigned>::max());
if (LastLoc.isValid())
return LastLoc;
}
}
return getPreciseTokenLocEnd(SpellingLoc, SM, LangOpts);
}
bool isSemicolonAtLocation(SourceLocation TokenLoc, const SourceManager &SM,
const LangOptions &LangOpts) {
return Lexer::getSourceText(
CharSourceRange::getTokenRange(TokenLoc, TokenLoc), SM,
LangOpts) == ";";
}
SourceRange trimSelectionRange(SourceRange Range, const SourceManager &SM,
const LangOptions &LangOpts) {
bool IsInvalid = false;
StringRef Text = Lexer::getSourceText(CharSourceRange::getCharRange(Range),
SM, LangOpts, &IsInvalid);
if (IsInvalid || Text.empty())
return Range;
assert(Range.getBegin().isFileID() && "Not a file range!");
std::string Source = Text.str();
Lexer Lex(Range.getBegin(), LangOpts, Source.c_str(), Source.c_str(),
Source.c_str() + Source.size());
// Get comment tokens as well.
Lex.SetCommentRetentionState(true);
SourceLocation StartLoc, EndLoc;
while (true) {
Token Tok;
Lex.LexFromRawLexer(Tok);
if (Tok.getKind() == tok::eof)
break;
if (StartLoc.isInvalid())
StartLoc = Tok.getLocation();
if (Tok.getKind() != tok::semi)
EndLoc = Tok.getEndLoc();
}
return StartLoc.isValid() && EndLoc.isValid() ? SourceRange(StartLoc, EndLoc)
: SourceRange();
}
/// Tokenize the given file and check if it contains a comment that ends at the
/// given location.
static SourceLocation findCommentThatEndsAt(FileID FID,
SourceLocation StartOfFile,
const SourceManager &SM,
const LangOptions &LangOpts,
SourceLocation ExpectedEndLoc) {
// Try to load the file buffer.
bool InvalidTemp = false;
StringRef File = SM.getBufferData(FID, &InvalidTemp);
if (InvalidTemp)
return SourceLocation();
// Search for the comment that ends at the given location.
Lexer Lex(StartOfFile, LangOpts, File.begin(), File.begin(), File.end());
Lex.SetCommentRetentionState(true);
Token Tok;
while (!Lex.LexFromRawLexer(Tok)) {
if (Tok.is(tok::comment) && Tok.getEndLoc() == ExpectedEndLoc)
return Tok.getLocation();
}
// Find the token.
return SourceLocation();
}
SourceLocation getLocationOfPrecedingComment(SourceLocation Location,
const SourceManager &SM,
const LangOptions &LangOpts) {
SourceLocation PrevResult = Location;
SourceLocation Result = Location;
if (Result.isMacroID())
Result = SM.getExpansionLoc(Result);
FileID FID = SM.getFileID(Result);
SourceLocation StartOfFile = SM.getLocForStartOfFile(FID);
Token Tok;
Tok.setKind(tok::unknown);
SourceLocation TokenLoc = Result;
auto GetPreviousToken = [&]() -> bool {
TokenLoc =
Lexer::GetBeginningOfToken(TokenLoc.getLocWithOffset(-1), SM, LangOpts);
return !Lexer::getRawToken(TokenLoc, Tok, SM, LangOpts);
};
// Look for a comment token.
while (TokenLoc != StartOfFile) {
bool LocHasToken = GetPreviousToken();
if (LocHasToken && Tok.is(tok::slash)) {
// Check if this the end of a multiline '/*' comment before returning.
SourceLocation CommentLoc = findCommentThatEndsAt(
FID, StartOfFile, SM, LangOpts, Tok.getEndLoc());
return CommentLoc.isInvalid() ? Result : CommentLoc;
}
if (LocHasToken && Tok.isNot(tok::comment))
break;
if (!LocHasToken)
continue;
// We found a preceding comment. Check if there are other preceding
// comments.
PrevResult = Result;
Result = Tok.getLocation();
while (TokenLoc != StartOfFile) {
bool LocHasToken = GetPreviousToken();
if (LocHasToken && Tok.isNot(tok::comment)) {
// Reset the result to the previous location if this comment trails
// another token on the same line.
if (SM.getSpellingLineNumber(Tok.getEndLoc()) ==
SM.getSpellingLineNumber(Result))
Result = PrevResult;
break;
}
if (!LocHasToken)
continue;
// The location of this comment is accepted only when the next comment
// is located immediately after this comment.
if (SM.getSpellingLineNumber(Tok.getEndLoc()) !=
SM.getSpellingLineNumber(Result) - 1)
break;
PrevResult = Result;
Result = Tok.getLocation();
}
break;
}
return Result;
}
SourceLocation getLocationOfPrecedingToken(SourceLocation Loc,
const SourceManager &SM,
const LangOptions &LangOpts) {
SourceLocation Result = Loc;
if (Result.isMacroID())
Result = SM.getExpansionLoc(Result);
FileID FID = SM.getFileID(Result);
SourceLocation StartOfFile = SM.getLocForStartOfFile(FID);
if (Loc == StartOfFile)
return SourceLocation();
return Lexer::GetBeginningOfToken(Result.getLocWithOffset(-1), SM, LangOpts);
}
} // end namespace tooling
} // end namespace clang
|