xref: /llvm-project/clang/lib/Tooling/Transformer/SourceCode.cpp (revision 345c4822e4db2aa734b9f8a0b106308288ddc702)
1fbdf8352SYitzhak Mandelbaum //===--- SourceCode.cpp - Source code manipulation routines -----*- C++ -*-===//
2fbdf8352SYitzhak Mandelbaum //
3fbdf8352SYitzhak Mandelbaum // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4fbdf8352SYitzhak Mandelbaum // See https://llvm.org/LICENSE.txt for license information.
5fbdf8352SYitzhak Mandelbaum // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6fbdf8352SYitzhak Mandelbaum //
7fbdf8352SYitzhak Mandelbaum //===----------------------------------------------------------------------===//
8fbdf8352SYitzhak Mandelbaum //
9fbdf8352SYitzhak Mandelbaum //  This file provides functions that simplify extraction of source code.
10fbdf8352SYitzhak Mandelbaum //
11fbdf8352SYitzhak Mandelbaum //===----------------------------------------------------------------------===//
12fbdf8352SYitzhak Mandelbaum #include "clang/Tooling/Transformer/SourceCode.h"
1338b4516dSYitzhak Mandelbaum #include "clang/AST/ASTContext.h"
1438b4516dSYitzhak Mandelbaum #include "clang/AST/Attr.h"
1538b4516dSYitzhak Mandelbaum #include "clang/AST/Comment.h"
1638b4516dSYitzhak Mandelbaum #include "clang/AST/Decl.h"
1738b4516dSYitzhak Mandelbaum #include "clang/AST/DeclCXX.h"
1838b4516dSYitzhak Mandelbaum #include "clang/AST/DeclTemplate.h"
1938b4516dSYitzhak Mandelbaum #include "clang/AST/Expr.h"
2086565c13SReid Kleckner #include "clang/Basic/SourceManager.h"
21fbdf8352SYitzhak Mandelbaum #include "clang/Lex/Lexer.h"
22b9d2bf38SYitzhak Mandelbaum #include "llvm/Support/Errc.h"
2376221c73SReid Kleckner #include "llvm/Support/Error.h"
24ba1ffd25SReid Kleckner #include <set>
25fbdf8352SYitzhak Mandelbaum 
26fbdf8352SYitzhak Mandelbaum using namespace clang;
27fbdf8352SYitzhak Mandelbaum 
28b9d2bf38SYitzhak Mandelbaum using llvm::errc;
29b9d2bf38SYitzhak Mandelbaum using llvm::StringError;
30b9d2bf38SYitzhak Mandelbaum 
getText(CharSourceRange Range,const ASTContext & Context)31fbdf8352SYitzhak Mandelbaum StringRef clang::tooling::getText(CharSourceRange Range,
32fbdf8352SYitzhak Mandelbaum                                   const ASTContext &Context) {
33fbdf8352SYitzhak Mandelbaum   return Lexer::getSourceText(Range, Context.getSourceManager(),
34fbdf8352SYitzhak Mandelbaum                               Context.getLangOpts());
35fbdf8352SYitzhak Mandelbaum }
36fbdf8352SYitzhak Mandelbaum 
maybeExtendRange(CharSourceRange Range,tok::TokenKind Next,ASTContext & Context)37fbdf8352SYitzhak Mandelbaum CharSourceRange clang::tooling::maybeExtendRange(CharSourceRange Range,
38fbdf8352SYitzhak Mandelbaum                                                  tok::TokenKind Next,
39fbdf8352SYitzhak Mandelbaum                                                  ASTContext &Context) {
40ecfa0b24SGabriel Matute   CharSourceRange R = Lexer::getAsCharRange(Range, Context.getSourceManager(),
41ecfa0b24SGabriel Matute                                             Context.getLangOpts());
42ecfa0b24SGabriel Matute   if (R.isInvalid())
43fbdf8352SYitzhak Mandelbaum     return Range;
44ecfa0b24SGabriel Matute   Token Tok;
45ecfa0b24SGabriel Matute   bool Err =
46ecfa0b24SGabriel Matute       Lexer::getRawToken(R.getEnd(), Tok, Context.getSourceManager(),
47ecfa0b24SGabriel Matute                          Context.getLangOpts(), /*IgnoreWhiteSpace=*/true);
48ecfa0b24SGabriel Matute   if (Err || !Tok.is(Next))
49ecfa0b24SGabriel Matute     return Range;
50ecfa0b24SGabriel Matute   return CharSourceRange::getTokenRange(Range.getBegin(), Tok.getLocation());
51fbdf8352SYitzhak Mandelbaum }
52fbdf8352SYitzhak Mandelbaum 
validateRange(const CharSourceRange & Range,const SourceManager & SM,bool AllowSystemHeaders)5375b76c4bSClement Courbet llvm::Error clang::tooling::validateRange(const CharSourceRange &Range,
547d0cdbf6SEric Li                                           const SourceManager &SM,
557d0cdbf6SEric Li                                           bool AllowSystemHeaders) {
56b9d2bf38SYitzhak Mandelbaum   if (Range.isInvalid())
57b9d2bf38SYitzhak Mandelbaum     return llvm::make_error<StringError>(errc::invalid_argument,
58b9d2bf38SYitzhak Mandelbaum                                          "Invalid range");
59b9d2bf38SYitzhak Mandelbaum 
60b9d2bf38SYitzhak Mandelbaum   if (Range.getBegin().isMacroID() || Range.getEnd().isMacroID())
61b9d2bf38SYitzhak Mandelbaum     return llvm::make_error<StringError>(
62b9d2bf38SYitzhak Mandelbaum         errc::invalid_argument, "Range starts or ends in a macro expansion");
63b9d2bf38SYitzhak Mandelbaum 
647d0cdbf6SEric Li   if (!AllowSystemHeaders) {
65b9d2bf38SYitzhak Mandelbaum     if (SM.isInSystemHeader(Range.getBegin()) ||
66b9d2bf38SYitzhak Mandelbaum         SM.isInSystemHeader(Range.getEnd()))
67b9d2bf38SYitzhak Mandelbaum       return llvm::make_error<StringError>(errc::invalid_argument,
68b9d2bf38SYitzhak Mandelbaum                                            "Range is in system header");
697d0cdbf6SEric Li   }
70b9d2bf38SYitzhak Mandelbaum 
71b9d2bf38SYitzhak Mandelbaum   std::pair<FileID, unsigned> BeginInfo = SM.getDecomposedLoc(Range.getBegin());
72b9d2bf38SYitzhak Mandelbaum   std::pair<FileID, unsigned> EndInfo = SM.getDecomposedLoc(Range.getEnd());
73b9d2bf38SYitzhak Mandelbaum   if (BeginInfo.first != EndInfo.first)
74b9d2bf38SYitzhak Mandelbaum     return llvm::make_error<StringError>(
75b9d2bf38SYitzhak Mandelbaum         errc::invalid_argument, "Range begins and ends in different files");
76b9d2bf38SYitzhak Mandelbaum 
77b9d2bf38SYitzhak Mandelbaum   if (BeginInfo.second > EndInfo.second)
787d0cdbf6SEric Li     return llvm::make_error<StringError>(errc::invalid_argument,
797d0cdbf6SEric Li                                          "Range's begin is past its end");
80b9d2bf38SYitzhak Mandelbaum 
81b9d2bf38SYitzhak Mandelbaum   return llvm::Error::success();
82b9d2bf38SYitzhak Mandelbaum }
83b9d2bf38SYitzhak Mandelbaum 
validateEditRange(const CharSourceRange & Range,const SourceManager & SM)847d0cdbf6SEric Li llvm::Error clang::tooling::validateEditRange(const CharSourceRange &Range,
857d0cdbf6SEric Li                                               const SourceManager &SM) {
867d0cdbf6SEric Li   return validateRange(Range, SM, /*AllowSystemHeaders=*/false);
877d0cdbf6SEric Li }
887d0cdbf6SEric Li 
spelledInMacroDefinition(SourceLocation Loc,const SourceManager & SM)897d0cdbf6SEric Li static bool spelledInMacroDefinition(SourceLocation Loc,
90a78d4b5bSEric Li                                      const SourceManager &SM) {
91a78d4b5bSEric Li   while (Loc.isMacroID()) {
92a78d4b5bSEric Li     const auto &Expansion = SM.getSLocEntry(SM.getFileID(Loc)).getExpansion();
93a78d4b5bSEric Li     if (Expansion.isMacroArgExpansion()) {
94a78d4b5bSEric Li       // Check the spelling location of the macro arg, in case the arg itself is
95a78d4b5bSEric Li       // in a macro expansion.
96a78d4b5bSEric Li       Loc = Expansion.getSpellingLoc();
97a78d4b5bSEric Li     } else {
98a78d4b5bSEric Li       return true;
99a78d4b5bSEric Li     }
100a78d4b5bSEric Li   }
101a78d4b5bSEric Li   return false;
102a78d4b5bSEric Li }
103a78d4b5bSEric Li 
104*345c4822SEric Li // Returns the expansion char-range of `Loc` if `Loc` is a split token. For
105*345c4822SEric Li // example, `>>` in nested templates needs the first `>` to be split, otherwise
106*345c4822SEric Li // the `SourceLocation` of the token would lex as `>>` instead of `>`.
107*345c4822SEric Li static std::optional<CharSourceRange>
getExpansionForSplitToken(SourceLocation Loc,const SourceManager & SM,const LangOptions & LangOpts)108*345c4822SEric Li getExpansionForSplitToken(SourceLocation Loc, const SourceManager &SM,
109*345c4822SEric Li                           const LangOptions &LangOpts) {
110*345c4822SEric Li   if (Loc.isMacroID()) {
111*345c4822SEric Li     bool Invalid = false;
112*345c4822SEric Li     auto &SLoc = SM.getSLocEntry(SM.getFileID(Loc), &Invalid);
113*345c4822SEric Li     if (Invalid)
114*345c4822SEric Li       return std::nullopt;
115*345c4822SEric Li     if (auto &Expansion = SLoc.getExpansion();
116*345c4822SEric Li         !Expansion.isExpansionTokenRange()) {
117*345c4822SEric Li       // A char-range expansion is only used where a token-range would be
118*345c4822SEric Li       // incorrect, and so identifies this as a split token (and importantly,
119*345c4822SEric Li       // not as a macro).
120*345c4822SEric Li       return Expansion.getExpansionLocRange();
121*345c4822SEric Li     }
122*345c4822SEric Li   }
123*345c4822SEric Li   return std::nullopt;
124*345c4822SEric Li }
125*345c4822SEric Li 
126*345c4822SEric Li // If `Range` covers a split token, returns the expansion range, otherwise
127*345c4822SEric Li // returns `Range`.
getRangeForSplitTokens(CharSourceRange Range,const SourceManager & SM,const LangOptions & LangOpts)128*345c4822SEric Li static CharSourceRange getRangeForSplitTokens(CharSourceRange Range,
129*345c4822SEric Li                                               const SourceManager &SM,
130*345c4822SEric Li                                               const LangOptions &LangOpts) {
131*345c4822SEric Li   if (Range.isTokenRange()) {
132*345c4822SEric Li     auto BeginToken = getExpansionForSplitToken(Range.getBegin(), SM, LangOpts);
133*345c4822SEric Li     auto EndToken = getExpansionForSplitToken(Range.getEnd(), SM, LangOpts);
134*345c4822SEric Li     if (EndToken) {
135*345c4822SEric Li       SourceLocation BeginLoc =
136*345c4822SEric Li           BeginToken ? BeginToken->getBegin() : Range.getBegin();
137*345c4822SEric Li       // We can't use the expansion location with a token-range, because that
138*345c4822SEric Li       // will incorrectly lex the end token, so use a char-range that ends at
139*345c4822SEric Li       // the split.
140*345c4822SEric Li       return CharSourceRange::getCharRange(BeginLoc, EndToken->getEnd());
141*345c4822SEric Li     } else if (BeginToken) {
142*345c4822SEric Li       // Since the end token is not split, the whole range covers the split, so
143*345c4822SEric Li       // the only adjustment we make is to use the expansion location of the
144*345c4822SEric Li       // begin token.
145*345c4822SEric Li       return CharSourceRange::getTokenRange(BeginToken->getBegin(),
146*345c4822SEric Li                                             Range.getEnd());
147*345c4822SEric Li     }
148*345c4822SEric Li   }
149*345c4822SEric Li   return Range;
150*345c4822SEric Li }
151*345c4822SEric Li 
getRange(const CharSourceRange & EditRange,const SourceManager & SM,const LangOptions & LangOpts,bool IncludeMacroExpansion)1527d0cdbf6SEric Li static CharSourceRange getRange(const CharSourceRange &EditRange,
1537d0cdbf6SEric Li                                 const SourceManager &SM,
1547d0cdbf6SEric Li                                 const LangOptions &LangOpts,
1557d0cdbf6SEric Li                                 bool IncludeMacroExpansion) {
156a78d4b5bSEric Li   CharSourceRange Range;
157a78d4b5bSEric Li   if (IncludeMacroExpansion) {
158a78d4b5bSEric Li     Range = Lexer::makeFileCharRange(EditRange, SM, LangOpts);
159a78d4b5bSEric Li   } else {
160*345c4822SEric Li     auto AdjustedRange = getRangeForSplitTokens(EditRange, SM, LangOpts);
161*345c4822SEric Li     if (spelledInMacroDefinition(AdjustedRange.getBegin(), SM) ||
162*345c4822SEric Li         spelledInMacroDefinition(AdjustedRange.getEnd(), SM))
1637d0cdbf6SEric Li       return {};
164a78d4b5bSEric Li 
165*345c4822SEric Li     auto B = SM.getSpellingLoc(AdjustedRange.getBegin());
166*345c4822SEric Li     auto E = SM.getSpellingLoc(AdjustedRange.getEnd());
167*345c4822SEric Li     if (AdjustedRange.isTokenRange())
168a78d4b5bSEric Li       E = Lexer::getLocForEndOfToken(E, 0, SM, LangOpts);
169a78d4b5bSEric Li     Range = CharSourceRange::getCharRange(B, E);
170a78d4b5bSEric Li   }
1717d0cdbf6SEric Li   return Range;
1727d0cdbf6SEric Li }
173a78d4b5bSEric Li 
getFileRangeForEdit(const CharSourceRange & EditRange,const SourceManager & SM,const LangOptions & LangOpts,bool IncludeMacroExpansion)1742307029bSEric Li std::optional<CharSourceRange> clang::tooling::getFileRangeForEdit(
1757d0cdbf6SEric Li     const CharSourceRange &EditRange, const SourceManager &SM,
1767d0cdbf6SEric Li     const LangOptions &LangOpts, bool IncludeMacroExpansion) {
1777d0cdbf6SEric Li   CharSourceRange Range =
1787d0cdbf6SEric Li       getRange(EditRange, SM, LangOpts, IncludeMacroExpansion);
179b9d2bf38SYitzhak Mandelbaum   bool IsInvalid = llvm::errorToBool(validateEditRange(Range, SM));
180b9d2bf38SYitzhak Mandelbaum   if (IsInvalid)
1815891420eSKazu Hirata     return std::nullopt;
182fbdf8352SYitzhak Mandelbaum   return Range;
183fbdf8352SYitzhak Mandelbaum }
18438b4516dSYitzhak Mandelbaum 
getFileRange(const CharSourceRange & EditRange,const SourceManager & SM,const LangOptions & LangOpts,bool IncludeMacroExpansion)1857d0cdbf6SEric Li std::optional<CharSourceRange> clang::tooling::getFileRange(
1867d0cdbf6SEric Li     const CharSourceRange &EditRange, const SourceManager &SM,
1877d0cdbf6SEric Li     const LangOptions &LangOpts, bool IncludeMacroExpansion) {
1887d0cdbf6SEric Li   CharSourceRange Range =
1897d0cdbf6SEric Li       getRange(EditRange, SM, LangOpts, IncludeMacroExpansion);
1907d0cdbf6SEric Li   bool IsInvalid =
1917d0cdbf6SEric Li       llvm::errorToBool(validateRange(Range, SM, /*AllowSystemHeaders=*/true));
1927d0cdbf6SEric Li   if (IsInvalid)
1937d0cdbf6SEric Li     return std::nullopt;
1947d0cdbf6SEric Li   return Range;
1957d0cdbf6SEric Li }
1967d0cdbf6SEric Li 
startsWithNewline(const SourceManager & SM,const Token & Tok)19738b4516dSYitzhak Mandelbaum static bool startsWithNewline(const SourceManager &SM, const Token &Tok) {
19838b4516dSYitzhak Mandelbaum   return isVerticalWhitespace(SM.getCharacterData(Tok.getLocation())[0]);
19938b4516dSYitzhak Mandelbaum }
20038b4516dSYitzhak Mandelbaum 
contains(const std::set<tok::TokenKind> & Terminators,const Token & Tok)20138b4516dSYitzhak Mandelbaum static bool contains(const std::set<tok::TokenKind> &Terminators,
20238b4516dSYitzhak Mandelbaum                      const Token &Tok) {
20338b4516dSYitzhak Mandelbaum   return Terminators.count(Tok.getKind()) > 0;
20438b4516dSYitzhak Mandelbaum }
20538b4516dSYitzhak Mandelbaum 
20638b4516dSYitzhak Mandelbaum // Returns the exclusive, *file* end location of the entity whose last token is
20738b4516dSYitzhak Mandelbaum // at location 'EntityLast'. That is, it returns the location one past the last
20838b4516dSYitzhak Mandelbaum // relevant character.
20938b4516dSYitzhak Mandelbaum //
21038b4516dSYitzhak Mandelbaum // Associated tokens include comments, horizontal whitespace and 'Terminators'
21138b4516dSYitzhak Mandelbaum // -- optional tokens, which, if any are found, will be included; if
21238b4516dSYitzhak Mandelbaum // 'Terminators' is empty, we will not include any extra tokens beyond comments
21338b4516dSYitzhak Mandelbaum // and horizontal whitespace.
21438b4516dSYitzhak Mandelbaum static SourceLocation
getEntityEndLoc(const SourceManager & SM,SourceLocation EntityLast,const std::set<tok::TokenKind> & Terminators,const LangOptions & LangOpts)21538b4516dSYitzhak Mandelbaum getEntityEndLoc(const SourceManager &SM, SourceLocation EntityLast,
21638b4516dSYitzhak Mandelbaum                 const std::set<tok::TokenKind> &Terminators,
21738b4516dSYitzhak Mandelbaum                 const LangOptions &LangOpts) {
21838b4516dSYitzhak Mandelbaum   assert(EntityLast.isValid() && "Invalid end location found.");
21938b4516dSYitzhak Mandelbaum 
22038b4516dSYitzhak Mandelbaum   // We remember the last location of a non-horizontal-whitespace token we have
22138b4516dSYitzhak Mandelbaum   // lexed; this is the location up to which we will want to delete.
22238b4516dSYitzhak Mandelbaum   // FIXME: Support using the spelling loc here for cases where we want to
22338b4516dSYitzhak Mandelbaum   // analyze the macro text.
22438b4516dSYitzhak Mandelbaum 
22538b4516dSYitzhak Mandelbaum   CharSourceRange ExpansionRange = SM.getExpansionRange(EntityLast);
22638b4516dSYitzhak Mandelbaum   // FIXME: Should check isTokenRange(), for the (rare) case that
22738b4516dSYitzhak Mandelbaum   // `ExpansionRange` is a character range.
22838b4516dSYitzhak Mandelbaum   std::unique_ptr<Lexer> Lexer = [&]() {
22938b4516dSYitzhak Mandelbaum     bool Invalid = false;
23038b4516dSYitzhak Mandelbaum     auto FileOffset = SM.getDecomposedLoc(ExpansionRange.getEnd());
23138b4516dSYitzhak Mandelbaum     llvm::StringRef File = SM.getBufferData(FileOffset.first, &Invalid);
23238b4516dSYitzhak Mandelbaum     assert(!Invalid && "Cannot get file/offset");
23338b4516dSYitzhak Mandelbaum     return std::make_unique<clang::Lexer>(
23438b4516dSYitzhak Mandelbaum         SM.getLocForStartOfFile(FileOffset.first), LangOpts, File.begin(),
23538b4516dSYitzhak Mandelbaum         File.data() + FileOffset.second, File.end());
23638b4516dSYitzhak Mandelbaum   }();
23738b4516dSYitzhak Mandelbaum 
23838b4516dSYitzhak Mandelbaum   // Tell Lexer to return whitespace as pseudo-tokens (kind is tok::unknown).
23938b4516dSYitzhak Mandelbaum   Lexer->SetKeepWhitespaceMode(true);
24038b4516dSYitzhak Mandelbaum 
24138b4516dSYitzhak Mandelbaum   // Generally, the code we want to include looks like this ([] are optional),
24238b4516dSYitzhak Mandelbaum   // If Terminators is empty:
24338b4516dSYitzhak Mandelbaum   //   [ <comment> ] [ <newline> ]
24438b4516dSYitzhak Mandelbaum   // Otherwise:
24538b4516dSYitzhak Mandelbaum   //   ... <terminator> [ <comment> ] [ <newline> ]
24638b4516dSYitzhak Mandelbaum 
24738b4516dSYitzhak Mandelbaum   Token Tok;
24838b4516dSYitzhak Mandelbaum   bool Terminated = false;
24938b4516dSYitzhak Mandelbaum 
25038b4516dSYitzhak Mandelbaum   // First, lex to the current token (which is the last token of the range that
25138b4516dSYitzhak Mandelbaum   // is definitely associated with the decl). Then, we process the first token
25238b4516dSYitzhak Mandelbaum   // separately from the rest based on conditions that hold specifically for
25338b4516dSYitzhak Mandelbaum   // that first token.
25438b4516dSYitzhak Mandelbaum   //
25538b4516dSYitzhak Mandelbaum   // We do not search for a terminator if none is required or we've already
25638b4516dSYitzhak Mandelbaum   // encountered it. Otherwise, if the original `EntityLast` location was in a
25738b4516dSYitzhak Mandelbaum   // macro expansion, we don't have visibility into the text, so we assume we've
25838b4516dSYitzhak Mandelbaum   // already terminated. However, we note this assumption with
25938b4516dSYitzhak Mandelbaum   // `TerminatedByMacro`, because we'll want to handle it somewhat differently
26038b4516dSYitzhak Mandelbaum   // for the terminators semicolon and comma. These terminators can be safely
26138b4516dSYitzhak Mandelbaum   // associated with the entity when they appear after the macro -- extra
26238b4516dSYitzhak Mandelbaum   // semicolons have no effect on the program and a well-formed program won't
26338b4516dSYitzhak Mandelbaum   // have multiple commas in a row, so we're guaranteed that there is only one.
26438b4516dSYitzhak Mandelbaum   //
26538b4516dSYitzhak Mandelbaum   // FIXME: This handling of macros is more conservative than necessary. When
26638b4516dSYitzhak Mandelbaum   // the end of the expansion coincides with the end of the node, we can still
26738b4516dSYitzhak Mandelbaum   // safely analyze the code. But, it is more complicated, because we need to
26838b4516dSYitzhak Mandelbaum   // start by lexing the spelling loc for the first token and then switch to the
26938b4516dSYitzhak Mandelbaum   // expansion loc.
27038b4516dSYitzhak Mandelbaum   bool TerminatedByMacro = false;
27138b4516dSYitzhak Mandelbaum   Lexer->LexFromRawLexer(Tok);
27238b4516dSYitzhak Mandelbaum   if (Terminators.empty() || contains(Terminators, Tok))
27338b4516dSYitzhak Mandelbaum     Terminated = true;
27438b4516dSYitzhak Mandelbaum   else if (EntityLast.isMacroID()) {
27538b4516dSYitzhak Mandelbaum     Terminated = true;
27638b4516dSYitzhak Mandelbaum     TerminatedByMacro = true;
27738b4516dSYitzhak Mandelbaum   }
27838b4516dSYitzhak Mandelbaum 
27938b4516dSYitzhak Mandelbaum   // We save the most recent candidate for the exclusive end location.
28038b4516dSYitzhak Mandelbaum   SourceLocation End = Tok.getEndLoc();
28138b4516dSYitzhak Mandelbaum 
28238b4516dSYitzhak Mandelbaum   while (!Terminated) {
28338b4516dSYitzhak Mandelbaum     // Lex the next token we want to possibly expand the range with.
28438b4516dSYitzhak Mandelbaum     Lexer->LexFromRawLexer(Tok);
28538b4516dSYitzhak Mandelbaum 
28638b4516dSYitzhak Mandelbaum     switch (Tok.getKind()) {
28738b4516dSYitzhak Mandelbaum     case tok::eof:
28838b4516dSYitzhak Mandelbaum     // Unexpected separators.
28938b4516dSYitzhak Mandelbaum     case tok::l_brace:
29038b4516dSYitzhak Mandelbaum     case tok::r_brace:
29138b4516dSYitzhak Mandelbaum     case tok::comma:
29238b4516dSYitzhak Mandelbaum       return End;
29338b4516dSYitzhak Mandelbaum     // Whitespace pseudo-tokens.
29438b4516dSYitzhak Mandelbaum     case tok::unknown:
29538b4516dSYitzhak Mandelbaum       if (startsWithNewline(SM, Tok))
29638b4516dSYitzhak Mandelbaum         // Include at least until the end of the line.
29738b4516dSYitzhak Mandelbaum         End = Tok.getEndLoc();
29838b4516dSYitzhak Mandelbaum       break;
29938b4516dSYitzhak Mandelbaum     default:
30038b4516dSYitzhak Mandelbaum       if (contains(Terminators, Tok))
30138b4516dSYitzhak Mandelbaum         Terminated = true;
30238b4516dSYitzhak Mandelbaum       End = Tok.getEndLoc();
30338b4516dSYitzhak Mandelbaum       break;
30438b4516dSYitzhak Mandelbaum     }
30538b4516dSYitzhak Mandelbaum   }
30638b4516dSYitzhak Mandelbaum 
30738b4516dSYitzhak Mandelbaum   do {
30838b4516dSYitzhak Mandelbaum     // Lex the next token we want to possibly expand the range with.
30938b4516dSYitzhak Mandelbaum     Lexer->LexFromRawLexer(Tok);
31038b4516dSYitzhak Mandelbaum 
31138b4516dSYitzhak Mandelbaum     switch (Tok.getKind()) {
31238b4516dSYitzhak Mandelbaum     case tok::unknown:
31338b4516dSYitzhak Mandelbaum       if (startsWithNewline(SM, Tok))
31438b4516dSYitzhak Mandelbaum         // We're done, but include this newline.
31538b4516dSYitzhak Mandelbaum         return Tok.getEndLoc();
31638b4516dSYitzhak Mandelbaum       break;
31738b4516dSYitzhak Mandelbaum     case tok::comment:
31838b4516dSYitzhak Mandelbaum       // Include any comments we find on the way.
31938b4516dSYitzhak Mandelbaum       End = Tok.getEndLoc();
32038b4516dSYitzhak Mandelbaum       break;
32138b4516dSYitzhak Mandelbaum     case tok::semi:
32238b4516dSYitzhak Mandelbaum     case tok::comma:
32338b4516dSYitzhak Mandelbaum       if (TerminatedByMacro && contains(Terminators, Tok)) {
32438b4516dSYitzhak Mandelbaum         End = Tok.getEndLoc();
32538b4516dSYitzhak Mandelbaum         // We've found a real terminator.
32638b4516dSYitzhak Mandelbaum         TerminatedByMacro = false;
32738b4516dSYitzhak Mandelbaum         break;
32838b4516dSYitzhak Mandelbaum       }
32938b4516dSYitzhak Mandelbaum       // Found an unrelated token; stop and don't include it.
33038b4516dSYitzhak Mandelbaum       return End;
33138b4516dSYitzhak Mandelbaum     default:
33238b4516dSYitzhak Mandelbaum       // Found an unrelated token; stop and don't include it.
33338b4516dSYitzhak Mandelbaum       return End;
33438b4516dSYitzhak Mandelbaum     }
33538b4516dSYitzhak Mandelbaum   } while (true);
33638b4516dSYitzhak Mandelbaum }
33738b4516dSYitzhak Mandelbaum 
33838b4516dSYitzhak Mandelbaum // Returns the expected terminator tokens for the given declaration.
33938b4516dSYitzhak Mandelbaum //
34038b4516dSYitzhak Mandelbaum // If we do not know the correct terminator token, returns an empty set.
34138b4516dSYitzhak Mandelbaum //
34238b4516dSYitzhak Mandelbaum // There are cases where we have more than one possible terminator (for example,
34338b4516dSYitzhak Mandelbaum // we find either a comma or a semicolon after a VarDecl).
getTerminators(const Decl & D)34438b4516dSYitzhak Mandelbaum static std::set<tok::TokenKind> getTerminators(const Decl &D) {
34538b4516dSYitzhak Mandelbaum   if (llvm::isa<RecordDecl>(D) || llvm::isa<UsingDecl>(D))
34638b4516dSYitzhak Mandelbaum     return {tok::semi};
34738b4516dSYitzhak Mandelbaum 
34838b4516dSYitzhak Mandelbaum   if (llvm::isa<FunctionDecl>(D) || llvm::isa<LinkageSpecDecl>(D))
34938b4516dSYitzhak Mandelbaum     return {tok::r_brace, tok::semi};
35038b4516dSYitzhak Mandelbaum 
35138b4516dSYitzhak Mandelbaum   if (llvm::isa<VarDecl>(D) || llvm::isa<FieldDecl>(D))
35238b4516dSYitzhak Mandelbaum     return {tok::comma, tok::semi};
35338b4516dSYitzhak Mandelbaum 
35438b4516dSYitzhak Mandelbaum   return {};
35538b4516dSYitzhak Mandelbaum }
35638b4516dSYitzhak Mandelbaum 
35738b4516dSYitzhak Mandelbaum // Starting from `Loc`, skips whitespace up to, and including, a single
35838b4516dSYitzhak Mandelbaum // newline. Returns the (exclusive) end of any skipped whitespace (that is, the
35938b4516dSYitzhak Mandelbaum // location immediately after the whitespace).
skipWhitespaceAndNewline(const SourceManager & SM,SourceLocation Loc,const LangOptions & LangOpts)36038b4516dSYitzhak Mandelbaum static SourceLocation skipWhitespaceAndNewline(const SourceManager &SM,
36138b4516dSYitzhak Mandelbaum                                                SourceLocation Loc,
36238b4516dSYitzhak Mandelbaum                                                const LangOptions &LangOpts) {
36338b4516dSYitzhak Mandelbaum   const char *LocChars = SM.getCharacterData(Loc);
36438b4516dSYitzhak Mandelbaum   int i = 0;
36538b4516dSYitzhak Mandelbaum   while (isHorizontalWhitespace(LocChars[i]))
36638b4516dSYitzhak Mandelbaum     ++i;
36738b4516dSYitzhak Mandelbaum   if (isVerticalWhitespace(LocChars[i]))
36838b4516dSYitzhak Mandelbaum     ++i;
36938b4516dSYitzhak Mandelbaum   return Loc.getLocWithOffset(i);
37038b4516dSYitzhak Mandelbaum }
37138b4516dSYitzhak Mandelbaum 
37238b4516dSYitzhak Mandelbaum // Is `Loc` separated from any following decl by something meaningful (e.g. an
37338b4516dSYitzhak Mandelbaum // empty line, a comment), ignoring horizontal whitespace?  Since this is a
37438b4516dSYitzhak Mandelbaum // heuristic, we return false when in doubt.  `Loc` cannot be the first location
37538b4516dSYitzhak Mandelbaum // in the file.
atOrBeforeSeparation(const SourceManager & SM,SourceLocation Loc,const LangOptions & LangOpts)37638b4516dSYitzhak Mandelbaum static bool atOrBeforeSeparation(const SourceManager &SM, SourceLocation Loc,
37738b4516dSYitzhak Mandelbaum                                  const LangOptions &LangOpts) {
37838b4516dSYitzhak Mandelbaum   // If the preceding character is a newline, we'll check for an empty line as a
37938b4516dSYitzhak Mandelbaum   // separator. However, we can't identify an empty line using tokens, so we
38038b4516dSYitzhak Mandelbaum   // analyse the characters. If we try to use tokens, we'll just end up with a
38138b4516dSYitzhak Mandelbaum   // whitespace token, whose characters we'd have to analyse anyhow.
38238b4516dSYitzhak Mandelbaum   bool Invalid = false;
38338b4516dSYitzhak Mandelbaum   const char *LocChars =
38438b4516dSYitzhak Mandelbaum       SM.getCharacterData(Loc.getLocWithOffset(-1), &Invalid);
38538b4516dSYitzhak Mandelbaum   assert(!Invalid &&
38638b4516dSYitzhak Mandelbaum          "Loc must be a valid character and not the first of the source file.");
38738b4516dSYitzhak Mandelbaum   if (isVerticalWhitespace(LocChars[0])) {
38838b4516dSYitzhak Mandelbaum     for (int i = 1; isWhitespace(LocChars[i]); ++i)
38938b4516dSYitzhak Mandelbaum       if (isVerticalWhitespace(LocChars[i]))
39038b4516dSYitzhak Mandelbaum         return true;
39138b4516dSYitzhak Mandelbaum   }
39238b4516dSYitzhak Mandelbaum   // We didn't find an empty line, so lex the next token, skipping past any
39338b4516dSYitzhak Mandelbaum   // whitespace we just scanned.
39438b4516dSYitzhak Mandelbaum   Token Tok;
39538b4516dSYitzhak Mandelbaum   bool Failed = Lexer::getRawToken(Loc, Tok, SM, LangOpts,
39638b4516dSYitzhak Mandelbaum                                    /*IgnoreWhiteSpace=*/true);
39738b4516dSYitzhak Mandelbaum   if (Failed)
39838b4516dSYitzhak Mandelbaum     // Any text that confuses the lexer seems fair to consider a separation.
39938b4516dSYitzhak Mandelbaum     return true;
40038b4516dSYitzhak Mandelbaum 
40138b4516dSYitzhak Mandelbaum   switch (Tok.getKind()) {
40238b4516dSYitzhak Mandelbaum   case tok::comment:
40338b4516dSYitzhak Mandelbaum   case tok::l_brace:
40438b4516dSYitzhak Mandelbaum   case tok::r_brace:
40538b4516dSYitzhak Mandelbaum   case tok::eof:
40638b4516dSYitzhak Mandelbaum     return true;
40738b4516dSYitzhak Mandelbaum   default:
40838b4516dSYitzhak Mandelbaum     return false;
40938b4516dSYitzhak Mandelbaum   }
41038b4516dSYitzhak Mandelbaum }
41138b4516dSYitzhak Mandelbaum 
getAssociatedRange(const Decl & Decl,ASTContext & Context)41238b4516dSYitzhak Mandelbaum CharSourceRange tooling::getAssociatedRange(const Decl &Decl,
41338b4516dSYitzhak Mandelbaum                                             ASTContext &Context) {
41438b4516dSYitzhak Mandelbaum   const SourceManager &SM = Context.getSourceManager();
41538b4516dSYitzhak Mandelbaum   const LangOptions &LangOpts = Context.getLangOpts();
41638b4516dSYitzhak Mandelbaum   CharSourceRange Range = CharSourceRange::getTokenRange(Decl.getSourceRange());
41738b4516dSYitzhak Mandelbaum 
41838b4516dSYitzhak Mandelbaum   // First, expand to the start of the template<> declaration if necessary.
41938b4516dSYitzhak Mandelbaum   if (const auto *Record = llvm::dyn_cast<CXXRecordDecl>(&Decl)) {
42038b4516dSYitzhak Mandelbaum     if (const auto *T = Record->getDescribedClassTemplate())
42138b4516dSYitzhak Mandelbaum       if (SM.isBeforeInTranslationUnit(T->getBeginLoc(), Range.getBegin()))
42238b4516dSYitzhak Mandelbaum         Range.setBegin(T->getBeginLoc());
42338b4516dSYitzhak Mandelbaum   } else if (const auto *F = llvm::dyn_cast<FunctionDecl>(&Decl)) {
42438b4516dSYitzhak Mandelbaum     if (const auto *T = F->getDescribedFunctionTemplate())
42538b4516dSYitzhak Mandelbaum       if (SM.isBeforeInTranslationUnit(T->getBeginLoc(), Range.getBegin()))
42638b4516dSYitzhak Mandelbaum         Range.setBegin(T->getBeginLoc());
42738b4516dSYitzhak Mandelbaum   }
42838b4516dSYitzhak Mandelbaum 
42938b4516dSYitzhak Mandelbaum   // Next, expand the end location past trailing comments to include a potential
43038b4516dSYitzhak Mandelbaum   // newline at the end of the decl's line.
43138b4516dSYitzhak Mandelbaum   Range.setEnd(
43238b4516dSYitzhak Mandelbaum       getEntityEndLoc(SM, Decl.getEndLoc(), getTerminators(Decl), LangOpts));
43338b4516dSYitzhak Mandelbaum   Range.setTokenRange(false);
43438b4516dSYitzhak Mandelbaum 
43538b4516dSYitzhak Mandelbaum   // Expand to include preceeding associated comments. We ignore any comments
43638b4516dSYitzhak Mandelbaum   // that are not preceeding the decl, since we've already skipped trailing
43738b4516dSYitzhak Mandelbaum   // comments with getEntityEndLoc.
43838b4516dSYitzhak Mandelbaum   if (const RawComment *Comment =
43938b4516dSYitzhak Mandelbaum           Decl.getASTContext().getRawCommentForDeclNoCache(&Decl))
44038b4516dSYitzhak Mandelbaum     // Only include a preceding comment if:
44138b4516dSYitzhak Mandelbaum     // * it is *not* separate from the declaration (not including any newline
44238b4516dSYitzhak Mandelbaum     //   that immediately follows the comment),
44338b4516dSYitzhak Mandelbaum     // * the decl *is* separate from any following entity (so, there are no
44438b4516dSYitzhak Mandelbaum     //   other entities the comment could refer to), and
44538b4516dSYitzhak Mandelbaum     // * it is not a IfThisThenThat lint check.
44638b4516dSYitzhak Mandelbaum     if (SM.isBeforeInTranslationUnit(Comment->getBeginLoc(),
44738b4516dSYitzhak Mandelbaum                                      Range.getBegin()) &&
44838b4516dSYitzhak Mandelbaum         !atOrBeforeSeparation(
44938b4516dSYitzhak Mandelbaum             SM, skipWhitespaceAndNewline(SM, Comment->getEndLoc(), LangOpts),
45038b4516dSYitzhak Mandelbaum             LangOpts) &&
45138b4516dSYitzhak Mandelbaum         atOrBeforeSeparation(SM, Range.getEnd(), LangOpts)) {
45238b4516dSYitzhak Mandelbaum       const StringRef CommentText = Comment->getRawText(SM);
45338b4516dSYitzhak Mandelbaum       if (!CommentText.contains("LINT.IfChange") &&
45438b4516dSYitzhak Mandelbaum           !CommentText.contains("LINT.ThenChange"))
45538b4516dSYitzhak Mandelbaum         Range.setBegin(Comment->getBeginLoc());
45638b4516dSYitzhak Mandelbaum     }
45738b4516dSYitzhak Mandelbaum   // Add leading attributes.
45838b4516dSYitzhak Mandelbaum   for (auto *Attr : Decl.attrs()) {
45938b4516dSYitzhak Mandelbaum     if (Attr->getLocation().isInvalid() ||
46038b4516dSYitzhak Mandelbaum         !SM.isBeforeInTranslationUnit(Attr->getLocation(), Range.getBegin()))
46138b4516dSYitzhak Mandelbaum       continue;
46238b4516dSYitzhak Mandelbaum     Range.setBegin(Attr->getLocation());
46338b4516dSYitzhak Mandelbaum 
46438b4516dSYitzhak Mandelbaum     // Extend to the left '[[' or '__attribute((' if we saw the attribute,
46538b4516dSYitzhak Mandelbaum     // unless it is not a valid location.
46638b4516dSYitzhak Mandelbaum     bool Invalid;
46738b4516dSYitzhak Mandelbaum     StringRef Source =
46838b4516dSYitzhak Mandelbaum         SM.getBufferData(SM.getFileID(Range.getBegin()), &Invalid);
46938b4516dSYitzhak Mandelbaum     if (Invalid)
47038b4516dSYitzhak Mandelbaum       continue;
47138b4516dSYitzhak Mandelbaum     llvm::StringRef BeforeAttr =
47238b4516dSYitzhak Mandelbaum         Source.substr(0, SM.getFileOffset(Range.getBegin()));
47338b4516dSYitzhak Mandelbaum     llvm::StringRef BeforeAttrStripped = BeforeAttr.rtrim();
47438b4516dSYitzhak Mandelbaum 
47538b4516dSYitzhak Mandelbaum     for (llvm::StringRef Prefix : {"[[", "__attribute__(("}) {
47638b4516dSYitzhak Mandelbaum       // Handle whitespace between attribute prefix and attribute value.
477f3dcc235SKazu Hirata       if (BeforeAttrStripped.ends_with(Prefix)) {
47838b4516dSYitzhak Mandelbaum         // Move start to start position of prefix, which is
47938b4516dSYitzhak Mandelbaum         // length(BeforeAttr) - length(BeforeAttrStripped) + length(Prefix)
48038b4516dSYitzhak Mandelbaum         // positions to the left.
48138b4516dSYitzhak Mandelbaum         Range.setBegin(Range.getBegin().getLocWithOffset(static_cast<int>(
48238b4516dSYitzhak Mandelbaum             -BeforeAttr.size() + BeforeAttrStripped.size() - Prefix.size())));
48338b4516dSYitzhak Mandelbaum         break;
48438b4516dSYitzhak Mandelbaum         // If we didn't see '[[' or '__attribute' it's probably coming from a
48538b4516dSYitzhak Mandelbaum         // macro expansion which is already handled by makeFileCharRange(),
48638b4516dSYitzhak Mandelbaum         // below.
48738b4516dSYitzhak Mandelbaum       }
48838b4516dSYitzhak Mandelbaum     }
48938b4516dSYitzhak Mandelbaum   }
49038b4516dSYitzhak Mandelbaum 
49138b4516dSYitzhak Mandelbaum   // Range.getEnd() is already fully un-expanded by getEntityEndLoc. But,
49238b4516dSYitzhak Mandelbaum   // Range.getBegin() may be inside an expansion.
49338b4516dSYitzhak Mandelbaum   return Lexer::makeFileCharRange(Range, SM, LangOpts);
49438b4516dSYitzhak Mandelbaum }
495