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"
135ffd83dbSDimitry Andric #include "clang/AST/ASTContext.h"
145ffd83dbSDimitry Andric #include "clang/AST/Attr.h"
155ffd83dbSDimitry Andric #include "clang/AST/Comment.h"
165ffd83dbSDimitry Andric #include "clang/AST/Decl.h"
175ffd83dbSDimitry Andric #include "clang/AST/DeclCXX.h"
185ffd83dbSDimitry Andric #include "clang/AST/DeclTemplate.h"
195ffd83dbSDimitry Andric #include "clang/AST/Expr.h"
205ffd83dbSDimitry Andric #include "clang/Basic/SourceManager.h"
21a7dea167SDimitry Andric #include "clang/Lex/Lexer.h"
225ffd83dbSDimitry Andric #include "llvm/Support/Errc.h"
235ffd83dbSDimitry Andric #include "llvm/Support/Error.h"
245ffd83dbSDimitry Andric #include <set>
25a7dea167SDimitry Andric 
26a7dea167SDimitry Andric using namespace clang;
27a7dea167SDimitry Andric 
285ffd83dbSDimitry Andric using llvm::errc;
295ffd83dbSDimitry Andric using llvm::StringError;
305ffd83dbSDimitry 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) {
405ffd83dbSDimitry Andric   CharSourceRange R = Lexer::getAsCharRange(Range, Context.getSourceManager(),
415ffd83dbSDimitry Andric                                             Context.getLangOpts());
425ffd83dbSDimitry Andric   if (R.isInvalid())
43a7dea167SDimitry Andric     return Range;
445ffd83dbSDimitry Andric   Token Tok;
455ffd83dbSDimitry Andric   bool Err =
465ffd83dbSDimitry Andric       Lexer::getRawToken(R.getEnd(), Tok, Context.getSourceManager(),
475ffd83dbSDimitry Andric                          Context.getLangOpts(), /*IgnoreWhiteSpace=*/true);
485ffd83dbSDimitry Andric   if (Err || !Tok.is(Next))
495ffd83dbSDimitry Andric     return Range;
505ffd83dbSDimitry Andric   return CharSourceRange::getTokenRange(Range.getBegin(), Tok.getLocation());
515ffd83dbSDimitry Andric }
525ffd83dbSDimitry Andric 
535ffd83dbSDimitry Andric llvm::Error clang::tooling::validateEditRange(const CharSourceRange &Range,
545ffd83dbSDimitry Andric                                               const SourceManager &SM) {
555ffd83dbSDimitry Andric   if (Range.isInvalid())
565ffd83dbSDimitry Andric     return llvm::make_error<StringError>(errc::invalid_argument,
575ffd83dbSDimitry Andric                                          "Invalid range");
585ffd83dbSDimitry Andric 
595ffd83dbSDimitry Andric   if (Range.getBegin().isMacroID() || Range.getEnd().isMacroID())
605ffd83dbSDimitry Andric     return llvm::make_error<StringError>(
615ffd83dbSDimitry Andric         errc::invalid_argument, "Range starts or ends in a macro expansion");
625ffd83dbSDimitry Andric 
635ffd83dbSDimitry Andric   if (SM.isInSystemHeader(Range.getBegin()) ||
645ffd83dbSDimitry Andric       SM.isInSystemHeader(Range.getEnd()))
655ffd83dbSDimitry Andric     return llvm::make_error<StringError>(errc::invalid_argument,
665ffd83dbSDimitry Andric                                          "Range is in system header");
675ffd83dbSDimitry Andric 
685ffd83dbSDimitry Andric   std::pair<FileID, unsigned> BeginInfo = SM.getDecomposedLoc(Range.getBegin());
695ffd83dbSDimitry Andric   std::pair<FileID, unsigned> EndInfo = SM.getDecomposedLoc(Range.getEnd());
705ffd83dbSDimitry Andric   if (BeginInfo.first != EndInfo.first)
715ffd83dbSDimitry Andric     return llvm::make_error<StringError>(
725ffd83dbSDimitry Andric         errc::invalid_argument, "Range begins and ends in different files");
735ffd83dbSDimitry Andric 
745ffd83dbSDimitry Andric   if (BeginInfo.second > EndInfo.second)
755ffd83dbSDimitry Andric     return llvm::make_error<StringError>(
765ffd83dbSDimitry Andric         errc::invalid_argument, "Range's begin is past its end");
775ffd83dbSDimitry Andric 
785ffd83dbSDimitry 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);
975ffd83dbSDimitry Andric   bool IsInvalid = llvm::errorToBool(validateEditRange(Range, SM));
985ffd83dbSDimitry Andric   if (IsInvalid)
995ffd83dbSDimitry Andric     return llvm::None;
100a7dea167SDimitry Andric   return Range;
1015ffd83dbSDimitry Andric 
1025ffd83dbSDimitry Andric }
1035ffd83dbSDimitry Andric 
1045ffd83dbSDimitry Andric static bool startsWithNewline(const SourceManager &SM, const Token &Tok) {
1055ffd83dbSDimitry Andric   return isVerticalWhitespace(SM.getCharacterData(Tok.getLocation())[0]);
1065ffd83dbSDimitry Andric }
1075ffd83dbSDimitry Andric 
1085ffd83dbSDimitry Andric static bool contains(const std::set<tok::TokenKind> &Terminators,
1095ffd83dbSDimitry Andric                      const Token &Tok) {
1105ffd83dbSDimitry Andric   return Terminators.count(Tok.getKind()) > 0;
1115ffd83dbSDimitry Andric }
1125ffd83dbSDimitry Andric 
1135ffd83dbSDimitry Andric // Returns the exclusive, *file* end location of the entity whose last token is
1145ffd83dbSDimitry Andric // at location 'EntityLast'. That is, it returns the location one past the last
1155ffd83dbSDimitry Andric // relevant character.
1165ffd83dbSDimitry Andric //
1175ffd83dbSDimitry Andric // Associated tokens include comments, horizontal whitespace and 'Terminators'
1185ffd83dbSDimitry Andric // -- optional tokens, which, if any are found, will be included; if
1195ffd83dbSDimitry Andric // 'Terminators' is empty, we will not include any extra tokens beyond comments
1205ffd83dbSDimitry Andric // and horizontal whitespace.
1215ffd83dbSDimitry Andric static SourceLocation
1225ffd83dbSDimitry Andric getEntityEndLoc(const SourceManager &SM, SourceLocation EntityLast,
1235ffd83dbSDimitry Andric                 const std::set<tok::TokenKind> &Terminators,
1245ffd83dbSDimitry Andric                 const LangOptions &LangOpts) {
1255ffd83dbSDimitry Andric   assert(EntityLast.isValid() && "Invalid end location found.");
1265ffd83dbSDimitry Andric 
1275ffd83dbSDimitry Andric   // We remember the last location of a non-horizontal-whitespace token we have
1285ffd83dbSDimitry Andric   // lexed; this is the location up to which we will want to delete.
1295ffd83dbSDimitry Andric   // FIXME: Support using the spelling loc here for cases where we want to
1305ffd83dbSDimitry Andric   // analyze the macro text.
1315ffd83dbSDimitry Andric 
1325ffd83dbSDimitry Andric   CharSourceRange ExpansionRange = SM.getExpansionRange(EntityLast);
1335ffd83dbSDimitry Andric   // FIXME: Should check isTokenRange(), for the (rare) case that
1345ffd83dbSDimitry Andric   // `ExpansionRange` is a character range.
1355ffd83dbSDimitry Andric   std::unique_ptr<Lexer> Lexer = [&]() {
1365ffd83dbSDimitry Andric     bool Invalid = false;
1375ffd83dbSDimitry Andric     auto FileOffset = SM.getDecomposedLoc(ExpansionRange.getEnd());
1385ffd83dbSDimitry Andric     llvm::StringRef File = SM.getBufferData(FileOffset.first, &Invalid);
1395ffd83dbSDimitry Andric     assert(!Invalid && "Cannot get file/offset");
1405ffd83dbSDimitry Andric     return std::make_unique<clang::Lexer>(
1415ffd83dbSDimitry Andric         SM.getLocForStartOfFile(FileOffset.first), LangOpts, File.begin(),
1425ffd83dbSDimitry Andric         File.data() + FileOffset.second, File.end());
1435ffd83dbSDimitry Andric   }();
1445ffd83dbSDimitry Andric 
1455ffd83dbSDimitry Andric   // Tell Lexer to return whitespace as pseudo-tokens (kind is tok::unknown).
1465ffd83dbSDimitry Andric   Lexer->SetKeepWhitespaceMode(true);
1475ffd83dbSDimitry Andric 
1485ffd83dbSDimitry Andric   // Generally, the code we want to include looks like this ([] are optional),
1495ffd83dbSDimitry Andric   // If Terminators is empty:
1505ffd83dbSDimitry Andric   //   [ <comment> ] [ <newline> ]
1515ffd83dbSDimitry Andric   // Otherwise:
1525ffd83dbSDimitry Andric   //   ... <terminator> [ <comment> ] [ <newline> ]
1535ffd83dbSDimitry Andric 
1545ffd83dbSDimitry Andric   Token Tok;
1555ffd83dbSDimitry Andric   bool Terminated = false;
1565ffd83dbSDimitry Andric 
1575ffd83dbSDimitry Andric   // First, lex to the current token (which is the last token of the range that
1585ffd83dbSDimitry Andric   // is definitely associated with the decl). Then, we process the first token
1595ffd83dbSDimitry Andric   // separately from the rest based on conditions that hold specifically for
1605ffd83dbSDimitry Andric   // that first token.
1615ffd83dbSDimitry Andric   //
1625ffd83dbSDimitry Andric   // We do not search for a terminator if none is required or we've already
1635ffd83dbSDimitry Andric   // encountered it. Otherwise, if the original `EntityLast` location was in a
1645ffd83dbSDimitry Andric   // macro expansion, we don't have visibility into the text, so we assume we've
1655ffd83dbSDimitry Andric   // already terminated. However, we note this assumption with
1665ffd83dbSDimitry Andric   // `TerminatedByMacro`, because we'll want to handle it somewhat differently
1675ffd83dbSDimitry Andric   // for the terminators semicolon and comma. These terminators can be safely
1685ffd83dbSDimitry Andric   // associated with the entity when they appear after the macro -- extra
1695ffd83dbSDimitry Andric   // semicolons have no effect on the program and a well-formed program won't
1705ffd83dbSDimitry Andric   // have multiple commas in a row, so we're guaranteed that there is only one.
1715ffd83dbSDimitry Andric   //
1725ffd83dbSDimitry Andric   // FIXME: This handling of macros is more conservative than necessary. When
1735ffd83dbSDimitry Andric   // the end of the expansion coincides with the end of the node, we can still
1745ffd83dbSDimitry Andric   // safely analyze the code. But, it is more complicated, because we need to
1755ffd83dbSDimitry Andric   // start by lexing the spelling loc for the first token and then switch to the
1765ffd83dbSDimitry Andric   // expansion loc.
1775ffd83dbSDimitry Andric   bool TerminatedByMacro = false;
1785ffd83dbSDimitry Andric   Lexer->LexFromRawLexer(Tok);
1795ffd83dbSDimitry Andric   if (Terminators.empty() || contains(Terminators, Tok))
1805ffd83dbSDimitry Andric     Terminated = true;
1815ffd83dbSDimitry Andric   else if (EntityLast.isMacroID()) {
1825ffd83dbSDimitry Andric     Terminated = true;
1835ffd83dbSDimitry Andric     TerminatedByMacro = true;
1845ffd83dbSDimitry Andric   }
1855ffd83dbSDimitry Andric 
1865ffd83dbSDimitry Andric   // We save the most recent candidate for the exclusive end location.
1875ffd83dbSDimitry Andric   SourceLocation End = Tok.getEndLoc();
1885ffd83dbSDimitry Andric 
1895ffd83dbSDimitry Andric   while (!Terminated) {
1905ffd83dbSDimitry Andric     // Lex the next token we want to possibly expand the range with.
1915ffd83dbSDimitry Andric     Lexer->LexFromRawLexer(Tok);
1925ffd83dbSDimitry Andric 
1935ffd83dbSDimitry Andric     switch (Tok.getKind()) {
1945ffd83dbSDimitry Andric     case tok::eof:
1955ffd83dbSDimitry Andric     // Unexpected separators.
1965ffd83dbSDimitry Andric     case tok::l_brace:
1975ffd83dbSDimitry Andric     case tok::r_brace:
1985ffd83dbSDimitry Andric     case tok::comma:
1995ffd83dbSDimitry Andric       return End;
2005ffd83dbSDimitry Andric     // Whitespace pseudo-tokens.
2015ffd83dbSDimitry Andric     case tok::unknown:
2025ffd83dbSDimitry Andric       if (startsWithNewline(SM, Tok))
2035ffd83dbSDimitry Andric         // Include at least until the end of the line.
2045ffd83dbSDimitry Andric         End = Tok.getEndLoc();
2055ffd83dbSDimitry Andric       break;
2065ffd83dbSDimitry Andric     default:
2075ffd83dbSDimitry Andric       if (contains(Terminators, Tok))
2085ffd83dbSDimitry Andric         Terminated = true;
2095ffd83dbSDimitry Andric       End = Tok.getEndLoc();
2105ffd83dbSDimitry Andric       break;
2115ffd83dbSDimitry Andric     }
2125ffd83dbSDimitry Andric   }
2135ffd83dbSDimitry Andric 
2145ffd83dbSDimitry Andric   do {
2155ffd83dbSDimitry Andric     // Lex the next token we want to possibly expand the range with.
2165ffd83dbSDimitry Andric     Lexer->LexFromRawLexer(Tok);
2175ffd83dbSDimitry Andric 
2185ffd83dbSDimitry Andric     switch (Tok.getKind()) {
2195ffd83dbSDimitry Andric     case tok::unknown:
2205ffd83dbSDimitry Andric       if (startsWithNewline(SM, Tok))
2215ffd83dbSDimitry Andric         // We're done, but include this newline.
2225ffd83dbSDimitry Andric         return Tok.getEndLoc();
2235ffd83dbSDimitry Andric       break;
2245ffd83dbSDimitry Andric     case tok::comment:
2255ffd83dbSDimitry Andric       // Include any comments we find on the way.
2265ffd83dbSDimitry Andric       End = Tok.getEndLoc();
2275ffd83dbSDimitry Andric       break;
2285ffd83dbSDimitry Andric     case tok::semi:
2295ffd83dbSDimitry Andric     case tok::comma:
2305ffd83dbSDimitry Andric       if (TerminatedByMacro && contains(Terminators, Tok)) {
2315ffd83dbSDimitry Andric         End = Tok.getEndLoc();
2325ffd83dbSDimitry Andric         // We've found a real terminator.
2335ffd83dbSDimitry Andric         TerminatedByMacro = false;
2345ffd83dbSDimitry Andric         break;
2355ffd83dbSDimitry Andric       }
2365ffd83dbSDimitry Andric       // Found an unrelated token; stop and don't include it.
2375ffd83dbSDimitry Andric       return End;
2385ffd83dbSDimitry Andric     default:
2395ffd83dbSDimitry Andric       // Found an unrelated token; stop and don't include it.
2405ffd83dbSDimitry Andric       return End;
2415ffd83dbSDimitry Andric     }
2425ffd83dbSDimitry Andric   } while (true);
2435ffd83dbSDimitry Andric }
2445ffd83dbSDimitry Andric 
2455ffd83dbSDimitry Andric // Returns the expected terminator tokens for the given declaration.
2465ffd83dbSDimitry Andric //
2475ffd83dbSDimitry Andric // If we do not know the correct terminator token, returns an empty set.
2485ffd83dbSDimitry Andric //
2495ffd83dbSDimitry Andric // There are cases where we have more than one possible terminator (for example,
2505ffd83dbSDimitry Andric // we find either a comma or a semicolon after a VarDecl).
2515ffd83dbSDimitry Andric static std::set<tok::TokenKind> getTerminators(const Decl &D) {
2525ffd83dbSDimitry Andric   if (llvm::isa<RecordDecl>(D) || llvm::isa<UsingDecl>(D))
2535ffd83dbSDimitry Andric     return {tok::semi};
2545ffd83dbSDimitry Andric 
2555ffd83dbSDimitry Andric   if (llvm::isa<FunctionDecl>(D) || llvm::isa<LinkageSpecDecl>(D))
2565ffd83dbSDimitry Andric     return {tok::r_brace, tok::semi};
2575ffd83dbSDimitry Andric 
2585ffd83dbSDimitry Andric   if (llvm::isa<VarDecl>(D) || llvm::isa<FieldDecl>(D))
2595ffd83dbSDimitry Andric     return {tok::comma, tok::semi};
2605ffd83dbSDimitry Andric 
2615ffd83dbSDimitry Andric   return {};
2625ffd83dbSDimitry Andric }
2635ffd83dbSDimitry Andric 
2645ffd83dbSDimitry Andric // Starting from `Loc`, skips whitespace up to, and including, a single
2655ffd83dbSDimitry Andric // newline. Returns the (exclusive) end of any skipped whitespace (that is, the
2665ffd83dbSDimitry Andric // location immediately after the whitespace).
2675ffd83dbSDimitry Andric static SourceLocation skipWhitespaceAndNewline(const SourceManager &SM,
2685ffd83dbSDimitry Andric                                                SourceLocation Loc,
2695ffd83dbSDimitry Andric                                                const LangOptions &LangOpts) {
2705ffd83dbSDimitry Andric   const char *LocChars = SM.getCharacterData(Loc);
2715ffd83dbSDimitry Andric   int i = 0;
2725ffd83dbSDimitry Andric   while (isHorizontalWhitespace(LocChars[i]))
2735ffd83dbSDimitry Andric     ++i;
2745ffd83dbSDimitry Andric   if (isVerticalWhitespace(LocChars[i]))
2755ffd83dbSDimitry Andric     ++i;
2765ffd83dbSDimitry Andric   return Loc.getLocWithOffset(i);
2775ffd83dbSDimitry Andric }
2785ffd83dbSDimitry Andric 
2795ffd83dbSDimitry Andric // Is `Loc` separated from any following decl by something meaningful (e.g. an
2805ffd83dbSDimitry Andric // empty line, a comment), ignoring horizontal whitespace?  Since this is a
2815ffd83dbSDimitry Andric // heuristic, we return false when in doubt.  `Loc` cannot be the first location
2825ffd83dbSDimitry Andric // in the file.
2835ffd83dbSDimitry Andric static bool atOrBeforeSeparation(const SourceManager &SM, SourceLocation Loc,
2845ffd83dbSDimitry Andric                                  const LangOptions &LangOpts) {
2855ffd83dbSDimitry Andric   // If the preceding character is a newline, we'll check for an empty line as a
2865ffd83dbSDimitry Andric   // separator. However, we can't identify an empty line using tokens, so we
2875ffd83dbSDimitry Andric   // analyse the characters. If we try to use tokens, we'll just end up with a
2885ffd83dbSDimitry Andric   // whitespace token, whose characters we'd have to analyse anyhow.
2895ffd83dbSDimitry Andric   bool Invalid = false;
2905ffd83dbSDimitry Andric   const char *LocChars =
2915ffd83dbSDimitry Andric       SM.getCharacterData(Loc.getLocWithOffset(-1), &Invalid);
2925ffd83dbSDimitry Andric   assert(!Invalid &&
2935ffd83dbSDimitry Andric          "Loc must be a valid character and not the first of the source file.");
2945ffd83dbSDimitry Andric   if (isVerticalWhitespace(LocChars[0])) {
2955ffd83dbSDimitry Andric     for (int i = 1; isWhitespace(LocChars[i]); ++i)
2965ffd83dbSDimitry Andric       if (isVerticalWhitespace(LocChars[i]))
2975ffd83dbSDimitry Andric         return true;
2985ffd83dbSDimitry Andric   }
2995ffd83dbSDimitry Andric   // We didn't find an empty line, so lex the next token, skipping past any
3005ffd83dbSDimitry Andric   // whitespace we just scanned.
3015ffd83dbSDimitry Andric   Token Tok;
3025ffd83dbSDimitry Andric   bool Failed = Lexer::getRawToken(Loc, Tok, SM, LangOpts,
3035ffd83dbSDimitry Andric                                    /*IgnoreWhiteSpace=*/true);
3045ffd83dbSDimitry Andric   if (Failed)
3055ffd83dbSDimitry Andric     // Any text that confuses the lexer seems fair to consider a separation.
3065ffd83dbSDimitry Andric     return true;
3075ffd83dbSDimitry Andric 
3085ffd83dbSDimitry Andric   switch (Tok.getKind()) {
3095ffd83dbSDimitry Andric   case tok::comment:
3105ffd83dbSDimitry Andric   case tok::l_brace:
3115ffd83dbSDimitry Andric   case tok::r_brace:
3125ffd83dbSDimitry Andric   case tok::eof:
3135ffd83dbSDimitry Andric     return true;
3145ffd83dbSDimitry Andric   default:
3155ffd83dbSDimitry Andric     return false;
3165ffd83dbSDimitry Andric   }
3175ffd83dbSDimitry Andric }
3185ffd83dbSDimitry Andric 
3195ffd83dbSDimitry Andric CharSourceRange tooling::getAssociatedRange(const Decl &Decl,
3205ffd83dbSDimitry Andric                                             ASTContext &Context) {
3215ffd83dbSDimitry Andric   const SourceManager &SM = Context.getSourceManager();
3225ffd83dbSDimitry Andric   const LangOptions &LangOpts = Context.getLangOpts();
3235ffd83dbSDimitry Andric   CharSourceRange Range = CharSourceRange::getTokenRange(Decl.getSourceRange());
3245ffd83dbSDimitry Andric 
3255ffd83dbSDimitry Andric   // First, expand to the start of the template<> declaration if necessary.
3265ffd83dbSDimitry Andric   if (const auto *Record = llvm::dyn_cast<CXXRecordDecl>(&Decl)) {
3275ffd83dbSDimitry Andric     if (const auto *T = Record->getDescribedClassTemplate())
3285ffd83dbSDimitry Andric       if (SM.isBeforeInTranslationUnit(T->getBeginLoc(), Range.getBegin()))
3295ffd83dbSDimitry Andric         Range.setBegin(T->getBeginLoc());
3305ffd83dbSDimitry Andric   } else if (const auto *F = llvm::dyn_cast<FunctionDecl>(&Decl)) {
3315ffd83dbSDimitry Andric     if (const auto *T = F->getDescribedFunctionTemplate())
3325ffd83dbSDimitry Andric       if (SM.isBeforeInTranslationUnit(T->getBeginLoc(), Range.getBegin()))
3335ffd83dbSDimitry Andric         Range.setBegin(T->getBeginLoc());
3345ffd83dbSDimitry Andric   }
3355ffd83dbSDimitry Andric 
3365ffd83dbSDimitry Andric   // Next, expand the end location past trailing comments to include a potential
3375ffd83dbSDimitry Andric   // newline at the end of the decl's line.
3385ffd83dbSDimitry Andric   Range.setEnd(
3395ffd83dbSDimitry Andric       getEntityEndLoc(SM, Decl.getEndLoc(), getTerminators(Decl), LangOpts));
3405ffd83dbSDimitry Andric   Range.setTokenRange(false);
3415ffd83dbSDimitry Andric 
3425ffd83dbSDimitry Andric   // Expand to include preceeding associated comments. We ignore any comments
3435ffd83dbSDimitry Andric   // that are not preceeding the decl, since we've already skipped trailing
3445ffd83dbSDimitry Andric   // comments with getEntityEndLoc.
3455ffd83dbSDimitry Andric   if (const RawComment *Comment =
3465ffd83dbSDimitry Andric           Decl.getASTContext().getRawCommentForDeclNoCache(&Decl))
3475ffd83dbSDimitry Andric     // Only include a preceding comment if:
3485ffd83dbSDimitry Andric     // * it is *not* separate from the declaration (not including any newline
3495ffd83dbSDimitry Andric     //   that immediately follows the comment),
3505ffd83dbSDimitry Andric     // * the decl *is* separate from any following entity (so, there are no
3515ffd83dbSDimitry Andric     //   other entities the comment could refer to), and
3525ffd83dbSDimitry Andric     // * it is not a IfThisThenThat lint check.
3535ffd83dbSDimitry Andric     if (SM.isBeforeInTranslationUnit(Comment->getBeginLoc(),
3545ffd83dbSDimitry Andric                                      Range.getBegin()) &&
3555ffd83dbSDimitry Andric         !atOrBeforeSeparation(
3565ffd83dbSDimitry Andric             SM, skipWhitespaceAndNewline(SM, Comment->getEndLoc(), LangOpts),
3575ffd83dbSDimitry Andric             LangOpts) &&
3585ffd83dbSDimitry Andric         atOrBeforeSeparation(SM, Range.getEnd(), LangOpts)) {
3595ffd83dbSDimitry Andric       const StringRef CommentText = Comment->getRawText(SM);
3605ffd83dbSDimitry Andric       if (!CommentText.contains("LINT.IfChange") &&
3615ffd83dbSDimitry Andric           !CommentText.contains("LINT.ThenChange"))
3625ffd83dbSDimitry Andric         Range.setBegin(Comment->getBeginLoc());
3635ffd83dbSDimitry Andric     }
3645ffd83dbSDimitry Andric   // Add leading attributes.
3655ffd83dbSDimitry Andric   for (auto *Attr : Decl.attrs()) {
3665ffd83dbSDimitry Andric     if (Attr->getLocation().isInvalid() ||
3675ffd83dbSDimitry Andric         !SM.isBeforeInTranslationUnit(Attr->getLocation(), Range.getBegin()))
3685ffd83dbSDimitry Andric       continue;
3695ffd83dbSDimitry Andric     Range.setBegin(Attr->getLocation());
3705ffd83dbSDimitry Andric 
3715ffd83dbSDimitry Andric     // Extend to the left '[[' or '__attribute((' if we saw the attribute,
3725ffd83dbSDimitry Andric     // unless it is not a valid location.
3735ffd83dbSDimitry Andric     bool Invalid;
3745ffd83dbSDimitry Andric     StringRef Source =
3755ffd83dbSDimitry Andric         SM.getBufferData(SM.getFileID(Range.getBegin()), &Invalid);
3765ffd83dbSDimitry Andric     if (Invalid)
3775ffd83dbSDimitry Andric       continue;
3785ffd83dbSDimitry Andric     llvm::StringRef BeforeAttr =
3795ffd83dbSDimitry Andric         Source.substr(0, SM.getFileOffset(Range.getBegin()));
3805ffd83dbSDimitry Andric     llvm::StringRef BeforeAttrStripped = BeforeAttr.rtrim();
3815ffd83dbSDimitry Andric 
3825ffd83dbSDimitry Andric     for (llvm::StringRef Prefix : {"[[", "__attribute__(("}) {
3835ffd83dbSDimitry Andric       // Handle whitespace between attribute prefix and attribute value.
3845ffd83dbSDimitry Andric       if (BeforeAttrStripped.endswith(Prefix)) {
3855ffd83dbSDimitry Andric         // Move start to start position of prefix, which is
3865ffd83dbSDimitry Andric         // length(BeforeAttr) - length(BeforeAttrStripped) + length(Prefix)
3875ffd83dbSDimitry Andric         // positions to the left.
3885ffd83dbSDimitry Andric         Range.setBegin(Range.getBegin().getLocWithOffset(static_cast<int>(
3895ffd83dbSDimitry Andric             -BeforeAttr.size() + BeforeAttrStripped.size() - Prefix.size())));
3905ffd83dbSDimitry Andric         break;
3915ffd83dbSDimitry Andric         // If we didn't see '[[' or '__attribute' it's probably coming from a
3925ffd83dbSDimitry Andric         // macro expansion which is already handled by makeFileCharRange(),
3935ffd83dbSDimitry Andric         // below.
3945ffd83dbSDimitry Andric       }
3955ffd83dbSDimitry Andric     }
3965ffd83dbSDimitry Andric   }
3975ffd83dbSDimitry Andric 
3985ffd83dbSDimitry Andric   // Range.getEnd() is already fully un-expanded by getEntityEndLoc. But,
3995ffd83dbSDimitry Andric   // Range.getBegin() may be inside an expansion.
4005ffd83dbSDimitry Andric   return Lexer::makeFileCharRange(Range, SM, LangOpts);
401a7dea167SDimitry Andric }
402