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