1e5dd7070Spatrick //===--- SourceCode.cpp - Source code manipulation routines -----*- C++ -*-===//
2e5dd7070Spatrick //
3e5dd7070Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e5dd7070Spatrick // See https://llvm.org/LICENSE.txt for license information.
5e5dd7070Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6e5dd7070Spatrick //
7e5dd7070Spatrick //===----------------------------------------------------------------------===//
8e5dd7070Spatrick //
9e5dd7070Spatrick // This file provides functions that simplify extraction of source code.
10e5dd7070Spatrick //
11e5dd7070Spatrick //===----------------------------------------------------------------------===//
12e5dd7070Spatrick #include "clang/Tooling/Transformer/SourceCode.h"
13ec727ea7Spatrick #include "clang/AST/ASTContext.h"
14ec727ea7Spatrick #include "clang/AST/Attr.h"
15ec727ea7Spatrick #include "clang/AST/Comment.h"
16ec727ea7Spatrick #include "clang/AST/Decl.h"
17ec727ea7Spatrick #include "clang/AST/DeclCXX.h"
18ec727ea7Spatrick #include "clang/AST/DeclTemplate.h"
19ec727ea7Spatrick #include "clang/AST/Expr.h"
20ec727ea7Spatrick #include "clang/Basic/SourceManager.h"
21e5dd7070Spatrick #include "clang/Lex/Lexer.h"
22ec727ea7Spatrick #include "llvm/Support/Errc.h"
23ec727ea7Spatrick #include "llvm/Support/Error.h"
24ec727ea7Spatrick #include <set>
25e5dd7070Spatrick
26e5dd7070Spatrick using namespace clang;
27e5dd7070Spatrick
28ec727ea7Spatrick using llvm::errc;
29ec727ea7Spatrick using llvm::StringError;
30ec727ea7Spatrick
getText(CharSourceRange Range,const ASTContext & Context)31e5dd7070Spatrick StringRef clang::tooling::getText(CharSourceRange Range,
32e5dd7070Spatrick const ASTContext &Context) {
33e5dd7070Spatrick return Lexer::getSourceText(Range, Context.getSourceManager(),
34e5dd7070Spatrick Context.getLangOpts());
35e5dd7070Spatrick }
36e5dd7070Spatrick
maybeExtendRange(CharSourceRange Range,tok::TokenKind Next,ASTContext & Context)37e5dd7070Spatrick CharSourceRange clang::tooling::maybeExtendRange(CharSourceRange Range,
38e5dd7070Spatrick tok::TokenKind Next,
39e5dd7070Spatrick ASTContext &Context) {
40ec727ea7Spatrick CharSourceRange R = Lexer::getAsCharRange(Range, Context.getSourceManager(),
41ec727ea7Spatrick Context.getLangOpts());
42ec727ea7Spatrick if (R.isInvalid())
43e5dd7070Spatrick return Range;
44ec727ea7Spatrick Token Tok;
45ec727ea7Spatrick bool Err =
46ec727ea7Spatrick Lexer::getRawToken(R.getEnd(), Tok, Context.getSourceManager(),
47ec727ea7Spatrick Context.getLangOpts(), /*IgnoreWhiteSpace=*/true);
48ec727ea7Spatrick if (Err || !Tok.is(Next))
49ec727ea7Spatrick return Range;
50ec727ea7Spatrick return CharSourceRange::getTokenRange(Range.getBegin(), Tok.getLocation());
51ec727ea7Spatrick }
52ec727ea7Spatrick
validateRange(const CharSourceRange & Range,const SourceManager & SM,bool AllowSystemHeaders)53*12c85518Srobert static llvm::Error validateRange(const CharSourceRange &Range,
54*12c85518Srobert const SourceManager &SM,
55*12c85518Srobert bool AllowSystemHeaders) {
56ec727ea7Spatrick if (Range.isInvalid())
57ec727ea7Spatrick return llvm::make_error<StringError>(errc::invalid_argument,
58ec727ea7Spatrick "Invalid range");
59ec727ea7Spatrick
60ec727ea7Spatrick if (Range.getBegin().isMacroID() || Range.getEnd().isMacroID())
61ec727ea7Spatrick return llvm::make_error<StringError>(
62ec727ea7Spatrick errc::invalid_argument, "Range starts or ends in a macro expansion");
63ec727ea7Spatrick
64*12c85518Srobert if (!AllowSystemHeaders) {
65ec727ea7Spatrick if (SM.isInSystemHeader(Range.getBegin()) ||
66ec727ea7Spatrick SM.isInSystemHeader(Range.getEnd()))
67ec727ea7Spatrick return llvm::make_error<StringError>(errc::invalid_argument,
68ec727ea7Spatrick "Range is in system header");
69*12c85518Srobert }
70ec727ea7Spatrick
71ec727ea7Spatrick std::pair<FileID, unsigned> BeginInfo = SM.getDecomposedLoc(Range.getBegin());
72ec727ea7Spatrick std::pair<FileID, unsigned> EndInfo = SM.getDecomposedLoc(Range.getEnd());
73ec727ea7Spatrick if (BeginInfo.first != EndInfo.first)
74ec727ea7Spatrick return llvm::make_error<StringError>(
75ec727ea7Spatrick errc::invalid_argument, "Range begins and ends in different files");
76ec727ea7Spatrick
77ec727ea7Spatrick if (BeginInfo.second > EndInfo.second)
78*12c85518Srobert return llvm::make_error<StringError>(errc::invalid_argument,
79*12c85518Srobert "Range's begin is past its end");
80ec727ea7Spatrick
81ec727ea7Spatrick return llvm::Error::success();
82e5dd7070Spatrick }
83e5dd7070Spatrick
validateEditRange(const CharSourceRange & Range,const SourceManager & SM)84*12c85518Srobert llvm::Error clang::tooling::validateEditRange(const CharSourceRange &Range,
85*12c85518Srobert const SourceManager &SM) {
86*12c85518Srobert return validateRange(Range, SM, /*AllowSystemHeaders=*/false);
87*12c85518Srobert }
88*12c85518Srobert
spelledInMacroDefinition(SourceLocation Loc,const SourceManager & SM)89*12c85518Srobert static bool spelledInMacroDefinition(SourceLocation Loc,
90*12c85518Srobert const SourceManager &SM) {
91*12c85518Srobert while (Loc.isMacroID()) {
92*12c85518Srobert const auto &Expansion = SM.getSLocEntry(SM.getFileID(Loc)).getExpansion();
93*12c85518Srobert if (Expansion.isMacroArgExpansion()) {
94*12c85518Srobert // Check the spelling location of the macro arg, in case the arg itself is
95*12c85518Srobert // in a macro expansion.
96*12c85518Srobert Loc = Expansion.getSpellingLoc();
97*12c85518Srobert } else {
98*12c85518Srobert return true;
99*12c85518Srobert }
100*12c85518Srobert }
101*12c85518Srobert return false;
102*12c85518Srobert }
103*12c85518Srobert
getRange(const CharSourceRange & EditRange,const SourceManager & SM,const LangOptions & LangOpts,bool IncludeMacroExpansion)104*12c85518Srobert static CharSourceRange getRange(const CharSourceRange &EditRange,
105e5dd7070Spatrick const SourceManager &SM,
106*12c85518Srobert const LangOptions &LangOpts,
107*12c85518Srobert bool IncludeMacroExpansion) {
108*12c85518Srobert CharSourceRange Range;
109*12c85518Srobert if (IncludeMacroExpansion) {
110*12c85518Srobert Range = Lexer::makeFileCharRange(EditRange, SM, LangOpts);
111*12c85518Srobert } else {
112*12c85518Srobert if (spelledInMacroDefinition(EditRange.getBegin(), SM) ||
113*12c85518Srobert spelledInMacroDefinition(EditRange.getEnd(), SM))
114*12c85518Srobert return {};
115*12c85518Srobert
116*12c85518Srobert auto B = SM.getSpellingLoc(EditRange.getBegin());
117*12c85518Srobert auto E = SM.getSpellingLoc(EditRange.getEnd());
118*12c85518Srobert if (EditRange.isTokenRange())
119*12c85518Srobert E = Lexer::getLocForEndOfToken(E, 0, SM, LangOpts);
120*12c85518Srobert Range = CharSourceRange::getCharRange(B, E);
121*12c85518Srobert }
122*12c85518Srobert return Range;
123*12c85518Srobert }
124*12c85518Srobert
getFileRangeForEdit(const CharSourceRange & EditRange,const SourceManager & SM,const LangOptions & LangOpts,bool IncludeMacroExpansion)125*12c85518Srobert std::optional<CharSourceRange> clang::tooling::getFileRangeForEdit(
126*12c85518Srobert const CharSourceRange &EditRange, const SourceManager &SM,
127*12c85518Srobert const LangOptions &LangOpts, bool IncludeMacroExpansion) {
128*12c85518Srobert CharSourceRange Range =
129*12c85518Srobert getRange(EditRange, SM, LangOpts, IncludeMacroExpansion);
130ec727ea7Spatrick bool IsInvalid = llvm::errorToBool(validateEditRange(Range, SM));
131ec727ea7Spatrick if (IsInvalid)
132*12c85518Srobert return std::nullopt;
133e5dd7070Spatrick return Range;
134*12c85518Srobert }
135ec727ea7Spatrick
getFileRange(const CharSourceRange & EditRange,const SourceManager & SM,const LangOptions & LangOpts,bool IncludeMacroExpansion)136*12c85518Srobert std::optional<CharSourceRange> clang::tooling::getFileRange(
137*12c85518Srobert const CharSourceRange &EditRange, const SourceManager &SM,
138*12c85518Srobert const LangOptions &LangOpts, bool IncludeMacroExpansion) {
139*12c85518Srobert CharSourceRange Range =
140*12c85518Srobert getRange(EditRange, SM, LangOpts, IncludeMacroExpansion);
141*12c85518Srobert bool IsInvalid =
142*12c85518Srobert llvm::errorToBool(validateRange(Range, SM, /*AllowSystemHeaders=*/true));
143*12c85518Srobert if (IsInvalid)
144*12c85518Srobert return std::nullopt;
145*12c85518Srobert return Range;
146ec727ea7Spatrick }
147ec727ea7Spatrick
startsWithNewline(const SourceManager & SM,const Token & Tok)148ec727ea7Spatrick static bool startsWithNewline(const SourceManager &SM, const Token &Tok) {
149ec727ea7Spatrick return isVerticalWhitespace(SM.getCharacterData(Tok.getLocation())[0]);
150ec727ea7Spatrick }
151ec727ea7Spatrick
contains(const std::set<tok::TokenKind> & Terminators,const Token & Tok)152ec727ea7Spatrick static bool contains(const std::set<tok::TokenKind> &Terminators,
153ec727ea7Spatrick const Token &Tok) {
154ec727ea7Spatrick return Terminators.count(Tok.getKind()) > 0;
155ec727ea7Spatrick }
156ec727ea7Spatrick
157ec727ea7Spatrick // Returns the exclusive, *file* end location of the entity whose last token is
158ec727ea7Spatrick // at location 'EntityLast'. That is, it returns the location one past the last
159ec727ea7Spatrick // relevant character.
160ec727ea7Spatrick //
161ec727ea7Spatrick // Associated tokens include comments, horizontal whitespace and 'Terminators'
162ec727ea7Spatrick // -- optional tokens, which, if any are found, will be included; if
163ec727ea7Spatrick // 'Terminators' is empty, we will not include any extra tokens beyond comments
164ec727ea7Spatrick // and horizontal whitespace.
165ec727ea7Spatrick static SourceLocation
getEntityEndLoc(const SourceManager & SM,SourceLocation EntityLast,const std::set<tok::TokenKind> & Terminators,const LangOptions & LangOpts)166ec727ea7Spatrick getEntityEndLoc(const SourceManager &SM, SourceLocation EntityLast,
167ec727ea7Spatrick const std::set<tok::TokenKind> &Terminators,
168ec727ea7Spatrick const LangOptions &LangOpts) {
169ec727ea7Spatrick assert(EntityLast.isValid() && "Invalid end location found.");
170ec727ea7Spatrick
171ec727ea7Spatrick // We remember the last location of a non-horizontal-whitespace token we have
172ec727ea7Spatrick // lexed; this is the location up to which we will want to delete.
173ec727ea7Spatrick // FIXME: Support using the spelling loc here for cases where we want to
174ec727ea7Spatrick // analyze the macro text.
175ec727ea7Spatrick
176ec727ea7Spatrick CharSourceRange ExpansionRange = SM.getExpansionRange(EntityLast);
177ec727ea7Spatrick // FIXME: Should check isTokenRange(), for the (rare) case that
178ec727ea7Spatrick // `ExpansionRange` is a character range.
179ec727ea7Spatrick std::unique_ptr<Lexer> Lexer = [&]() {
180ec727ea7Spatrick bool Invalid = false;
181ec727ea7Spatrick auto FileOffset = SM.getDecomposedLoc(ExpansionRange.getEnd());
182ec727ea7Spatrick llvm::StringRef File = SM.getBufferData(FileOffset.first, &Invalid);
183ec727ea7Spatrick assert(!Invalid && "Cannot get file/offset");
184ec727ea7Spatrick return std::make_unique<clang::Lexer>(
185ec727ea7Spatrick SM.getLocForStartOfFile(FileOffset.first), LangOpts, File.begin(),
186ec727ea7Spatrick File.data() + FileOffset.second, File.end());
187ec727ea7Spatrick }();
188ec727ea7Spatrick
189ec727ea7Spatrick // Tell Lexer to return whitespace as pseudo-tokens (kind is tok::unknown).
190ec727ea7Spatrick Lexer->SetKeepWhitespaceMode(true);
191ec727ea7Spatrick
192ec727ea7Spatrick // Generally, the code we want to include looks like this ([] are optional),
193ec727ea7Spatrick // If Terminators is empty:
194ec727ea7Spatrick // [ <comment> ] [ <newline> ]
195ec727ea7Spatrick // Otherwise:
196ec727ea7Spatrick // ... <terminator> [ <comment> ] [ <newline> ]
197ec727ea7Spatrick
198ec727ea7Spatrick Token Tok;
199ec727ea7Spatrick bool Terminated = false;
200ec727ea7Spatrick
201ec727ea7Spatrick // First, lex to the current token (which is the last token of the range that
202ec727ea7Spatrick // is definitely associated with the decl). Then, we process the first token
203ec727ea7Spatrick // separately from the rest based on conditions that hold specifically for
204ec727ea7Spatrick // that first token.
205ec727ea7Spatrick //
206ec727ea7Spatrick // We do not search for a terminator if none is required or we've already
207ec727ea7Spatrick // encountered it. Otherwise, if the original `EntityLast` location was in a
208ec727ea7Spatrick // macro expansion, we don't have visibility into the text, so we assume we've
209ec727ea7Spatrick // already terminated. However, we note this assumption with
210ec727ea7Spatrick // `TerminatedByMacro`, because we'll want to handle it somewhat differently
211ec727ea7Spatrick // for the terminators semicolon and comma. These terminators can be safely
212ec727ea7Spatrick // associated with the entity when they appear after the macro -- extra
213ec727ea7Spatrick // semicolons have no effect on the program and a well-formed program won't
214ec727ea7Spatrick // have multiple commas in a row, so we're guaranteed that there is only one.
215ec727ea7Spatrick //
216ec727ea7Spatrick // FIXME: This handling of macros is more conservative than necessary. When
217ec727ea7Spatrick // the end of the expansion coincides with the end of the node, we can still
218ec727ea7Spatrick // safely analyze the code. But, it is more complicated, because we need to
219ec727ea7Spatrick // start by lexing the spelling loc for the first token and then switch to the
220ec727ea7Spatrick // expansion loc.
221ec727ea7Spatrick bool TerminatedByMacro = false;
222ec727ea7Spatrick Lexer->LexFromRawLexer(Tok);
223ec727ea7Spatrick if (Terminators.empty() || contains(Terminators, Tok))
224ec727ea7Spatrick Terminated = true;
225ec727ea7Spatrick else if (EntityLast.isMacroID()) {
226ec727ea7Spatrick Terminated = true;
227ec727ea7Spatrick TerminatedByMacro = true;
228ec727ea7Spatrick }
229ec727ea7Spatrick
230ec727ea7Spatrick // We save the most recent candidate for the exclusive end location.
231ec727ea7Spatrick SourceLocation End = Tok.getEndLoc();
232ec727ea7Spatrick
233ec727ea7Spatrick while (!Terminated) {
234ec727ea7Spatrick // Lex the next token we want to possibly expand the range with.
235ec727ea7Spatrick Lexer->LexFromRawLexer(Tok);
236ec727ea7Spatrick
237ec727ea7Spatrick switch (Tok.getKind()) {
238ec727ea7Spatrick case tok::eof:
239ec727ea7Spatrick // Unexpected separators.
240ec727ea7Spatrick case tok::l_brace:
241ec727ea7Spatrick case tok::r_brace:
242ec727ea7Spatrick case tok::comma:
243ec727ea7Spatrick return End;
244ec727ea7Spatrick // Whitespace pseudo-tokens.
245ec727ea7Spatrick case tok::unknown:
246ec727ea7Spatrick if (startsWithNewline(SM, Tok))
247ec727ea7Spatrick // Include at least until the end of the line.
248ec727ea7Spatrick End = Tok.getEndLoc();
249ec727ea7Spatrick break;
250ec727ea7Spatrick default:
251ec727ea7Spatrick if (contains(Terminators, Tok))
252ec727ea7Spatrick Terminated = true;
253ec727ea7Spatrick End = Tok.getEndLoc();
254ec727ea7Spatrick break;
255ec727ea7Spatrick }
256ec727ea7Spatrick }
257ec727ea7Spatrick
258ec727ea7Spatrick do {
259ec727ea7Spatrick // Lex the next token we want to possibly expand the range with.
260ec727ea7Spatrick Lexer->LexFromRawLexer(Tok);
261ec727ea7Spatrick
262ec727ea7Spatrick switch (Tok.getKind()) {
263ec727ea7Spatrick case tok::unknown:
264ec727ea7Spatrick if (startsWithNewline(SM, Tok))
265ec727ea7Spatrick // We're done, but include this newline.
266ec727ea7Spatrick return Tok.getEndLoc();
267ec727ea7Spatrick break;
268ec727ea7Spatrick case tok::comment:
269ec727ea7Spatrick // Include any comments we find on the way.
270ec727ea7Spatrick End = Tok.getEndLoc();
271ec727ea7Spatrick break;
272ec727ea7Spatrick case tok::semi:
273ec727ea7Spatrick case tok::comma:
274ec727ea7Spatrick if (TerminatedByMacro && contains(Terminators, Tok)) {
275ec727ea7Spatrick End = Tok.getEndLoc();
276ec727ea7Spatrick // We've found a real terminator.
277ec727ea7Spatrick TerminatedByMacro = false;
278ec727ea7Spatrick break;
279ec727ea7Spatrick }
280ec727ea7Spatrick // Found an unrelated token; stop and don't include it.
281ec727ea7Spatrick return End;
282ec727ea7Spatrick default:
283ec727ea7Spatrick // Found an unrelated token; stop and don't include it.
284ec727ea7Spatrick return End;
285ec727ea7Spatrick }
286ec727ea7Spatrick } while (true);
287ec727ea7Spatrick }
288ec727ea7Spatrick
289ec727ea7Spatrick // Returns the expected terminator tokens for the given declaration.
290ec727ea7Spatrick //
291ec727ea7Spatrick // If we do not know the correct terminator token, returns an empty set.
292ec727ea7Spatrick //
293ec727ea7Spatrick // There are cases where we have more than one possible terminator (for example,
294ec727ea7Spatrick // we find either a comma or a semicolon after a VarDecl).
getTerminators(const Decl & D)295ec727ea7Spatrick static std::set<tok::TokenKind> getTerminators(const Decl &D) {
296ec727ea7Spatrick if (llvm::isa<RecordDecl>(D) || llvm::isa<UsingDecl>(D))
297ec727ea7Spatrick return {tok::semi};
298ec727ea7Spatrick
299ec727ea7Spatrick if (llvm::isa<FunctionDecl>(D) || llvm::isa<LinkageSpecDecl>(D))
300ec727ea7Spatrick return {tok::r_brace, tok::semi};
301ec727ea7Spatrick
302ec727ea7Spatrick if (llvm::isa<VarDecl>(D) || llvm::isa<FieldDecl>(D))
303ec727ea7Spatrick return {tok::comma, tok::semi};
304ec727ea7Spatrick
305ec727ea7Spatrick return {};
306ec727ea7Spatrick }
307ec727ea7Spatrick
308ec727ea7Spatrick // Starting from `Loc`, skips whitespace up to, and including, a single
309ec727ea7Spatrick // newline. Returns the (exclusive) end of any skipped whitespace (that is, the
310ec727ea7Spatrick // location immediately after the whitespace).
skipWhitespaceAndNewline(const SourceManager & SM,SourceLocation Loc,const LangOptions & LangOpts)311ec727ea7Spatrick static SourceLocation skipWhitespaceAndNewline(const SourceManager &SM,
312ec727ea7Spatrick SourceLocation Loc,
313ec727ea7Spatrick const LangOptions &LangOpts) {
314ec727ea7Spatrick const char *LocChars = SM.getCharacterData(Loc);
315ec727ea7Spatrick int i = 0;
316ec727ea7Spatrick while (isHorizontalWhitespace(LocChars[i]))
317ec727ea7Spatrick ++i;
318ec727ea7Spatrick if (isVerticalWhitespace(LocChars[i]))
319ec727ea7Spatrick ++i;
320ec727ea7Spatrick return Loc.getLocWithOffset(i);
321ec727ea7Spatrick }
322ec727ea7Spatrick
323ec727ea7Spatrick // Is `Loc` separated from any following decl by something meaningful (e.g. an
324ec727ea7Spatrick // empty line, a comment), ignoring horizontal whitespace? Since this is a
325ec727ea7Spatrick // heuristic, we return false when in doubt. `Loc` cannot be the first location
326ec727ea7Spatrick // in the file.
atOrBeforeSeparation(const SourceManager & SM,SourceLocation Loc,const LangOptions & LangOpts)327ec727ea7Spatrick static bool atOrBeforeSeparation(const SourceManager &SM, SourceLocation Loc,
328ec727ea7Spatrick const LangOptions &LangOpts) {
329ec727ea7Spatrick // If the preceding character is a newline, we'll check for an empty line as a
330ec727ea7Spatrick // separator. However, we can't identify an empty line using tokens, so we
331ec727ea7Spatrick // analyse the characters. If we try to use tokens, we'll just end up with a
332ec727ea7Spatrick // whitespace token, whose characters we'd have to analyse anyhow.
333ec727ea7Spatrick bool Invalid = false;
334ec727ea7Spatrick const char *LocChars =
335ec727ea7Spatrick SM.getCharacterData(Loc.getLocWithOffset(-1), &Invalid);
336ec727ea7Spatrick assert(!Invalid &&
337ec727ea7Spatrick "Loc must be a valid character and not the first of the source file.");
338ec727ea7Spatrick if (isVerticalWhitespace(LocChars[0])) {
339ec727ea7Spatrick for (int i = 1; isWhitespace(LocChars[i]); ++i)
340ec727ea7Spatrick if (isVerticalWhitespace(LocChars[i]))
341ec727ea7Spatrick return true;
342ec727ea7Spatrick }
343ec727ea7Spatrick // We didn't find an empty line, so lex the next token, skipping past any
344ec727ea7Spatrick // whitespace we just scanned.
345ec727ea7Spatrick Token Tok;
346ec727ea7Spatrick bool Failed = Lexer::getRawToken(Loc, Tok, SM, LangOpts,
347ec727ea7Spatrick /*IgnoreWhiteSpace=*/true);
348ec727ea7Spatrick if (Failed)
349ec727ea7Spatrick // Any text that confuses the lexer seems fair to consider a separation.
350ec727ea7Spatrick return true;
351ec727ea7Spatrick
352ec727ea7Spatrick switch (Tok.getKind()) {
353ec727ea7Spatrick case tok::comment:
354ec727ea7Spatrick case tok::l_brace:
355ec727ea7Spatrick case tok::r_brace:
356ec727ea7Spatrick case tok::eof:
357ec727ea7Spatrick return true;
358ec727ea7Spatrick default:
359ec727ea7Spatrick return false;
360ec727ea7Spatrick }
361ec727ea7Spatrick }
362ec727ea7Spatrick
getAssociatedRange(const Decl & Decl,ASTContext & Context)363ec727ea7Spatrick CharSourceRange tooling::getAssociatedRange(const Decl &Decl,
364ec727ea7Spatrick ASTContext &Context) {
365ec727ea7Spatrick const SourceManager &SM = Context.getSourceManager();
366ec727ea7Spatrick const LangOptions &LangOpts = Context.getLangOpts();
367ec727ea7Spatrick CharSourceRange Range = CharSourceRange::getTokenRange(Decl.getSourceRange());
368ec727ea7Spatrick
369ec727ea7Spatrick // First, expand to the start of the template<> declaration if necessary.
370ec727ea7Spatrick if (const auto *Record = llvm::dyn_cast<CXXRecordDecl>(&Decl)) {
371ec727ea7Spatrick if (const auto *T = Record->getDescribedClassTemplate())
372ec727ea7Spatrick if (SM.isBeforeInTranslationUnit(T->getBeginLoc(), Range.getBegin()))
373ec727ea7Spatrick Range.setBegin(T->getBeginLoc());
374ec727ea7Spatrick } else if (const auto *F = llvm::dyn_cast<FunctionDecl>(&Decl)) {
375ec727ea7Spatrick if (const auto *T = F->getDescribedFunctionTemplate())
376ec727ea7Spatrick if (SM.isBeforeInTranslationUnit(T->getBeginLoc(), Range.getBegin()))
377ec727ea7Spatrick Range.setBegin(T->getBeginLoc());
378ec727ea7Spatrick }
379ec727ea7Spatrick
380ec727ea7Spatrick // Next, expand the end location past trailing comments to include a potential
381ec727ea7Spatrick // newline at the end of the decl's line.
382ec727ea7Spatrick Range.setEnd(
383ec727ea7Spatrick getEntityEndLoc(SM, Decl.getEndLoc(), getTerminators(Decl), LangOpts));
384ec727ea7Spatrick Range.setTokenRange(false);
385ec727ea7Spatrick
386ec727ea7Spatrick // Expand to include preceeding associated comments. We ignore any comments
387ec727ea7Spatrick // that are not preceeding the decl, since we've already skipped trailing
388ec727ea7Spatrick // comments with getEntityEndLoc.
389ec727ea7Spatrick if (const RawComment *Comment =
390ec727ea7Spatrick Decl.getASTContext().getRawCommentForDeclNoCache(&Decl))
391ec727ea7Spatrick // Only include a preceding comment if:
392ec727ea7Spatrick // * it is *not* separate from the declaration (not including any newline
393ec727ea7Spatrick // that immediately follows the comment),
394ec727ea7Spatrick // * the decl *is* separate from any following entity (so, there are no
395ec727ea7Spatrick // other entities the comment could refer to), and
396ec727ea7Spatrick // * it is not a IfThisThenThat lint check.
397ec727ea7Spatrick if (SM.isBeforeInTranslationUnit(Comment->getBeginLoc(),
398ec727ea7Spatrick Range.getBegin()) &&
399ec727ea7Spatrick !atOrBeforeSeparation(
400ec727ea7Spatrick SM, skipWhitespaceAndNewline(SM, Comment->getEndLoc(), LangOpts),
401ec727ea7Spatrick LangOpts) &&
402ec727ea7Spatrick atOrBeforeSeparation(SM, Range.getEnd(), LangOpts)) {
403ec727ea7Spatrick const StringRef CommentText = Comment->getRawText(SM);
404ec727ea7Spatrick if (!CommentText.contains("LINT.IfChange") &&
405ec727ea7Spatrick !CommentText.contains("LINT.ThenChange"))
406ec727ea7Spatrick Range.setBegin(Comment->getBeginLoc());
407ec727ea7Spatrick }
408ec727ea7Spatrick // Add leading attributes.
409ec727ea7Spatrick for (auto *Attr : Decl.attrs()) {
410ec727ea7Spatrick if (Attr->getLocation().isInvalid() ||
411ec727ea7Spatrick !SM.isBeforeInTranslationUnit(Attr->getLocation(), Range.getBegin()))
412ec727ea7Spatrick continue;
413ec727ea7Spatrick Range.setBegin(Attr->getLocation());
414ec727ea7Spatrick
415ec727ea7Spatrick // Extend to the left '[[' or '__attribute((' if we saw the attribute,
416ec727ea7Spatrick // unless it is not a valid location.
417ec727ea7Spatrick bool Invalid;
418ec727ea7Spatrick StringRef Source =
419ec727ea7Spatrick SM.getBufferData(SM.getFileID(Range.getBegin()), &Invalid);
420ec727ea7Spatrick if (Invalid)
421ec727ea7Spatrick continue;
422ec727ea7Spatrick llvm::StringRef BeforeAttr =
423ec727ea7Spatrick Source.substr(0, SM.getFileOffset(Range.getBegin()));
424ec727ea7Spatrick llvm::StringRef BeforeAttrStripped = BeforeAttr.rtrim();
425ec727ea7Spatrick
426ec727ea7Spatrick for (llvm::StringRef Prefix : {"[[", "__attribute__(("}) {
427ec727ea7Spatrick // Handle whitespace between attribute prefix and attribute value.
428ec727ea7Spatrick if (BeforeAttrStripped.endswith(Prefix)) {
429ec727ea7Spatrick // Move start to start position of prefix, which is
430ec727ea7Spatrick // length(BeforeAttr) - length(BeforeAttrStripped) + length(Prefix)
431ec727ea7Spatrick // positions to the left.
432ec727ea7Spatrick Range.setBegin(Range.getBegin().getLocWithOffset(static_cast<int>(
433ec727ea7Spatrick -BeforeAttr.size() + BeforeAttrStripped.size() - Prefix.size())));
434ec727ea7Spatrick break;
435ec727ea7Spatrick // If we didn't see '[[' or '__attribute' it's probably coming from a
436ec727ea7Spatrick // macro expansion which is already handled by makeFileCharRange(),
437ec727ea7Spatrick // below.
438ec727ea7Spatrick }
439ec727ea7Spatrick }
440ec727ea7Spatrick }
441ec727ea7Spatrick
442ec727ea7Spatrick // Range.getEnd() is already fully un-expanded by getEntityEndLoc. But,
443ec727ea7Spatrick // Range.getBegin() may be inside an expansion.
444ec727ea7Spatrick return Lexer::makeFileCharRange(Range, SM, LangOpts);
445e5dd7070Spatrick }
446