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) {
40*ecfa0b24SGabriel Matute CharSourceRange R = Lexer::getAsCharRange(Range, Context.getSourceManager(),
41*ecfa0b24SGabriel Matute Context.getLangOpts());
42*ecfa0b24SGabriel Matute if (R.isInvalid())
43fbdf8352SYitzhak Mandelbaum return Range;
44*ecfa0b24SGabriel Matute Token Tok;
45*ecfa0b24SGabriel Matute bool Err =
46*ecfa0b24SGabriel Matute Lexer::getRawToken(R.getEnd(), Tok, Context.getSourceManager(),
47*ecfa0b24SGabriel Matute Context.getLangOpts(), /*IgnoreWhiteSpace=*/true);
48*ecfa0b24SGabriel Matute if (Err || !Tok.is(Next))
49*ecfa0b24SGabriel Matute return Range;
50*ecfa0b24SGabriel Matute return CharSourceRange::getTokenRange(Range.getBegin(), Tok.getLocation());
51fbdf8352SYitzhak Mandelbaum }
52fbdf8352SYitzhak Mandelbaum
validateEditRange(const CharSourceRange & Range,const SourceManager & SM)53b9d2bf38SYitzhak Mandelbaum llvm::Error clang::tooling::validateEditRange(const CharSourceRange &Range,
54b9d2bf38SYitzhak Mandelbaum const SourceManager &SM) {
55b9d2bf38SYitzhak Mandelbaum if (Range.isInvalid())
56b9d2bf38SYitzhak Mandelbaum return llvm::make_error<StringError>(errc::invalid_argument,
57b9d2bf38SYitzhak Mandelbaum "Invalid range");
58b9d2bf38SYitzhak Mandelbaum
59b9d2bf38SYitzhak Mandelbaum if (Range.getBegin().isMacroID() || Range.getEnd().isMacroID())
60b9d2bf38SYitzhak Mandelbaum return llvm::make_error<StringError>(
61b9d2bf38SYitzhak Mandelbaum errc::invalid_argument, "Range starts or ends in a macro expansion");
62b9d2bf38SYitzhak Mandelbaum
63b9d2bf38SYitzhak Mandelbaum if (SM.isInSystemHeader(Range.getBegin()) ||
64b9d2bf38SYitzhak Mandelbaum SM.isInSystemHeader(Range.getEnd()))
65b9d2bf38SYitzhak Mandelbaum return llvm::make_error<StringError>(errc::invalid_argument,
66b9d2bf38SYitzhak Mandelbaum "Range is in system header");
67b9d2bf38SYitzhak Mandelbaum
68b9d2bf38SYitzhak Mandelbaum std::pair<FileID, unsigned> BeginInfo = SM.getDecomposedLoc(Range.getBegin());
69b9d2bf38SYitzhak Mandelbaum std::pair<FileID, unsigned> EndInfo = SM.getDecomposedLoc(Range.getEnd());
70b9d2bf38SYitzhak Mandelbaum if (BeginInfo.first != EndInfo.first)
71b9d2bf38SYitzhak Mandelbaum return llvm::make_error<StringError>(
72b9d2bf38SYitzhak Mandelbaum errc::invalid_argument, "Range begins and ends in different files");
73b9d2bf38SYitzhak Mandelbaum
74b9d2bf38SYitzhak Mandelbaum if (BeginInfo.second > EndInfo.second)
75b9d2bf38SYitzhak Mandelbaum return llvm::make_error<StringError>(
76b9d2bf38SYitzhak Mandelbaum errc::invalid_argument, "Range's begin is past its end");
77b9d2bf38SYitzhak Mandelbaum
78b9d2bf38SYitzhak Mandelbaum return llvm::Error::success();
79b9d2bf38SYitzhak Mandelbaum }
80b9d2bf38SYitzhak Mandelbaum
81fbdf8352SYitzhak Mandelbaum llvm::Optional<CharSourceRange>
getRangeForEdit(const CharSourceRange & EditRange,const SourceManager & SM,const LangOptions & LangOpts)82fbdf8352SYitzhak Mandelbaum clang::tooling::getRangeForEdit(const CharSourceRange &EditRange,
83fbdf8352SYitzhak Mandelbaum const SourceManager &SM,
84fbdf8352SYitzhak Mandelbaum const LangOptions &LangOpts) {
85fbdf8352SYitzhak Mandelbaum // FIXME: makeFileCharRange() has the disadvantage of stripping off "identity"
86fbdf8352SYitzhak Mandelbaum // macros. For example, if we're looking to rewrite the int literal 3 to 6,
87fbdf8352SYitzhak Mandelbaum // and we have the following definition:
88fbdf8352SYitzhak Mandelbaum // #define DO_NOTHING(x) x
89fbdf8352SYitzhak Mandelbaum // then
90fbdf8352SYitzhak Mandelbaum // foo(DO_NOTHING(3))
91fbdf8352SYitzhak Mandelbaum // will be rewritten to
92fbdf8352SYitzhak Mandelbaum // foo(6)
93fbdf8352SYitzhak Mandelbaum // rather than the arguably better
94fbdf8352SYitzhak Mandelbaum // foo(DO_NOTHING(6))
95fbdf8352SYitzhak Mandelbaum // Decide whether the current behavior is desirable and modify if not.
96fbdf8352SYitzhak Mandelbaum CharSourceRange Range = Lexer::makeFileCharRange(EditRange, SM, LangOpts);
97b9d2bf38SYitzhak Mandelbaum bool IsInvalid = llvm::errorToBool(validateEditRange(Range, SM));
98b9d2bf38SYitzhak Mandelbaum if (IsInvalid)
99b9d2bf38SYitzhak Mandelbaum return llvm::None;
100fbdf8352SYitzhak Mandelbaum return Range;
101b9d2bf38SYitzhak Mandelbaum
102fbdf8352SYitzhak Mandelbaum }
10338b4516dSYitzhak Mandelbaum
startsWithNewline(const SourceManager & SM,const Token & Tok)10438b4516dSYitzhak Mandelbaum static bool startsWithNewline(const SourceManager &SM, const Token &Tok) {
10538b4516dSYitzhak Mandelbaum return isVerticalWhitespace(SM.getCharacterData(Tok.getLocation())[0]);
10638b4516dSYitzhak Mandelbaum }
10738b4516dSYitzhak Mandelbaum
contains(const std::set<tok::TokenKind> & Terminators,const Token & Tok)10838b4516dSYitzhak Mandelbaum static bool contains(const std::set<tok::TokenKind> &Terminators,
10938b4516dSYitzhak Mandelbaum const Token &Tok) {
11038b4516dSYitzhak Mandelbaum return Terminators.count(Tok.getKind()) > 0;
11138b4516dSYitzhak Mandelbaum }
11238b4516dSYitzhak Mandelbaum
11338b4516dSYitzhak Mandelbaum // Returns the exclusive, *file* end location of the entity whose last token is
11438b4516dSYitzhak Mandelbaum // at location 'EntityLast'. That is, it returns the location one past the last
11538b4516dSYitzhak Mandelbaum // relevant character.
11638b4516dSYitzhak Mandelbaum //
11738b4516dSYitzhak Mandelbaum // Associated tokens include comments, horizontal whitespace and 'Terminators'
11838b4516dSYitzhak Mandelbaum // -- optional tokens, which, if any are found, will be included; if
11938b4516dSYitzhak Mandelbaum // 'Terminators' is empty, we will not include any extra tokens beyond comments
12038b4516dSYitzhak Mandelbaum // and horizontal whitespace.
12138b4516dSYitzhak Mandelbaum static SourceLocation
getEntityEndLoc(const SourceManager & SM,SourceLocation EntityLast,const std::set<tok::TokenKind> & Terminators,const LangOptions & LangOpts)12238b4516dSYitzhak Mandelbaum getEntityEndLoc(const SourceManager &SM, SourceLocation EntityLast,
12338b4516dSYitzhak Mandelbaum const std::set<tok::TokenKind> &Terminators,
12438b4516dSYitzhak Mandelbaum const LangOptions &LangOpts) {
12538b4516dSYitzhak Mandelbaum assert(EntityLast.isValid() && "Invalid end location found.");
12638b4516dSYitzhak Mandelbaum
12738b4516dSYitzhak Mandelbaum // We remember the last location of a non-horizontal-whitespace token we have
12838b4516dSYitzhak Mandelbaum // lexed; this is the location up to which we will want to delete.
12938b4516dSYitzhak Mandelbaum // FIXME: Support using the spelling loc here for cases where we want to
13038b4516dSYitzhak Mandelbaum // analyze the macro text.
13138b4516dSYitzhak Mandelbaum
13238b4516dSYitzhak Mandelbaum CharSourceRange ExpansionRange = SM.getExpansionRange(EntityLast);
13338b4516dSYitzhak Mandelbaum // FIXME: Should check isTokenRange(), for the (rare) case that
13438b4516dSYitzhak Mandelbaum // `ExpansionRange` is a character range.
13538b4516dSYitzhak Mandelbaum std::unique_ptr<Lexer> Lexer = [&]() {
13638b4516dSYitzhak Mandelbaum bool Invalid = false;
13738b4516dSYitzhak Mandelbaum auto FileOffset = SM.getDecomposedLoc(ExpansionRange.getEnd());
13838b4516dSYitzhak Mandelbaum llvm::StringRef File = SM.getBufferData(FileOffset.first, &Invalid);
13938b4516dSYitzhak Mandelbaum assert(!Invalid && "Cannot get file/offset");
14038b4516dSYitzhak Mandelbaum return std::make_unique<clang::Lexer>(
14138b4516dSYitzhak Mandelbaum SM.getLocForStartOfFile(FileOffset.first), LangOpts, File.begin(),
14238b4516dSYitzhak Mandelbaum File.data() + FileOffset.second, File.end());
14338b4516dSYitzhak Mandelbaum }();
14438b4516dSYitzhak Mandelbaum
14538b4516dSYitzhak Mandelbaum // Tell Lexer to return whitespace as pseudo-tokens (kind is tok::unknown).
14638b4516dSYitzhak Mandelbaum Lexer->SetKeepWhitespaceMode(true);
14738b4516dSYitzhak Mandelbaum
14838b4516dSYitzhak Mandelbaum // Generally, the code we want to include looks like this ([] are optional),
14938b4516dSYitzhak Mandelbaum // If Terminators is empty:
15038b4516dSYitzhak Mandelbaum // [ <comment> ] [ <newline> ]
15138b4516dSYitzhak Mandelbaum // Otherwise:
15238b4516dSYitzhak Mandelbaum // ... <terminator> [ <comment> ] [ <newline> ]
15338b4516dSYitzhak Mandelbaum
15438b4516dSYitzhak Mandelbaum Token Tok;
15538b4516dSYitzhak Mandelbaum bool Terminated = false;
15638b4516dSYitzhak Mandelbaum
15738b4516dSYitzhak Mandelbaum // First, lex to the current token (which is the last token of the range that
15838b4516dSYitzhak Mandelbaum // is definitely associated with the decl). Then, we process the first token
15938b4516dSYitzhak Mandelbaum // separately from the rest based on conditions that hold specifically for
16038b4516dSYitzhak Mandelbaum // that first token.
16138b4516dSYitzhak Mandelbaum //
16238b4516dSYitzhak Mandelbaum // We do not search for a terminator if none is required or we've already
16338b4516dSYitzhak Mandelbaum // encountered it. Otherwise, if the original `EntityLast` location was in a
16438b4516dSYitzhak Mandelbaum // macro expansion, we don't have visibility into the text, so we assume we've
16538b4516dSYitzhak Mandelbaum // already terminated. However, we note this assumption with
16638b4516dSYitzhak Mandelbaum // `TerminatedByMacro`, because we'll want to handle it somewhat differently
16738b4516dSYitzhak Mandelbaum // for the terminators semicolon and comma. These terminators can be safely
16838b4516dSYitzhak Mandelbaum // associated with the entity when they appear after the macro -- extra
16938b4516dSYitzhak Mandelbaum // semicolons have no effect on the program and a well-formed program won't
17038b4516dSYitzhak Mandelbaum // have multiple commas in a row, so we're guaranteed that there is only one.
17138b4516dSYitzhak Mandelbaum //
17238b4516dSYitzhak Mandelbaum // FIXME: This handling of macros is more conservative than necessary. When
17338b4516dSYitzhak Mandelbaum // the end of the expansion coincides with the end of the node, we can still
17438b4516dSYitzhak Mandelbaum // safely analyze the code. But, it is more complicated, because we need to
17538b4516dSYitzhak Mandelbaum // start by lexing the spelling loc for the first token and then switch to the
17638b4516dSYitzhak Mandelbaum // expansion loc.
17738b4516dSYitzhak Mandelbaum bool TerminatedByMacro = false;
17838b4516dSYitzhak Mandelbaum Lexer->LexFromRawLexer(Tok);
17938b4516dSYitzhak Mandelbaum if (Terminators.empty() || contains(Terminators, Tok))
18038b4516dSYitzhak Mandelbaum Terminated = true;
18138b4516dSYitzhak Mandelbaum else if (EntityLast.isMacroID()) {
18238b4516dSYitzhak Mandelbaum Terminated = true;
18338b4516dSYitzhak Mandelbaum TerminatedByMacro = true;
18438b4516dSYitzhak Mandelbaum }
18538b4516dSYitzhak Mandelbaum
18638b4516dSYitzhak Mandelbaum // We save the most recent candidate for the exclusive end location.
18738b4516dSYitzhak Mandelbaum SourceLocation End = Tok.getEndLoc();
18838b4516dSYitzhak Mandelbaum
18938b4516dSYitzhak Mandelbaum while (!Terminated) {
19038b4516dSYitzhak Mandelbaum // Lex the next token we want to possibly expand the range with.
19138b4516dSYitzhak Mandelbaum Lexer->LexFromRawLexer(Tok);
19238b4516dSYitzhak Mandelbaum
19338b4516dSYitzhak Mandelbaum switch (Tok.getKind()) {
19438b4516dSYitzhak Mandelbaum case tok::eof:
19538b4516dSYitzhak Mandelbaum // Unexpected separators.
19638b4516dSYitzhak Mandelbaum case tok::l_brace:
19738b4516dSYitzhak Mandelbaum case tok::r_brace:
19838b4516dSYitzhak Mandelbaum case tok::comma:
19938b4516dSYitzhak Mandelbaum return End;
20038b4516dSYitzhak Mandelbaum // Whitespace pseudo-tokens.
20138b4516dSYitzhak Mandelbaum case tok::unknown:
20238b4516dSYitzhak Mandelbaum if (startsWithNewline(SM, Tok))
20338b4516dSYitzhak Mandelbaum // Include at least until the end of the line.
20438b4516dSYitzhak Mandelbaum End = Tok.getEndLoc();
20538b4516dSYitzhak Mandelbaum break;
20638b4516dSYitzhak Mandelbaum default:
20738b4516dSYitzhak Mandelbaum if (contains(Terminators, Tok))
20838b4516dSYitzhak Mandelbaum Terminated = true;
20938b4516dSYitzhak Mandelbaum End = Tok.getEndLoc();
21038b4516dSYitzhak Mandelbaum break;
21138b4516dSYitzhak Mandelbaum }
21238b4516dSYitzhak Mandelbaum }
21338b4516dSYitzhak Mandelbaum
21438b4516dSYitzhak Mandelbaum do {
21538b4516dSYitzhak Mandelbaum // Lex the next token we want to possibly expand the range with.
21638b4516dSYitzhak Mandelbaum Lexer->LexFromRawLexer(Tok);
21738b4516dSYitzhak Mandelbaum
21838b4516dSYitzhak Mandelbaum switch (Tok.getKind()) {
21938b4516dSYitzhak Mandelbaum case tok::unknown:
22038b4516dSYitzhak Mandelbaum if (startsWithNewline(SM, Tok))
22138b4516dSYitzhak Mandelbaum // We're done, but include this newline.
22238b4516dSYitzhak Mandelbaum return Tok.getEndLoc();
22338b4516dSYitzhak Mandelbaum break;
22438b4516dSYitzhak Mandelbaum case tok::comment:
22538b4516dSYitzhak Mandelbaum // Include any comments we find on the way.
22638b4516dSYitzhak Mandelbaum End = Tok.getEndLoc();
22738b4516dSYitzhak Mandelbaum break;
22838b4516dSYitzhak Mandelbaum case tok::semi:
22938b4516dSYitzhak Mandelbaum case tok::comma:
23038b4516dSYitzhak Mandelbaum if (TerminatedByMacro && contains(Terminators, Tok)) {
23138b4516dSYitzhak Mandelbaum End = Tok.getEndLoc();
23238b4516dSYitzhak Mandelbaum // We've found a real terminator.
23338b4516dSYitzhak Mandelbaum TerminatedByMacro = false;
23438b4516dSYitzhak Mandelbaum break;
23538b4516dSYitzhak Mandelbaum }
23638b4516dSYitzhak Mandelbaum // Found an unrelated token; stop and don't include it.
23738b4516dSYitzhak Mandelbaum return End;
23838b4516dSYitzhak Mandelbaum default:
23938b4516dSYitzhak Mandelbaum // Found an unrelated token; stop and don't include it.
24038b4516dSYitzhak Mandelbaum return End;
24138b4516dSYitzhak Mandelbaum }
24238b4516dSYitzhak Mandelbaum } while (true);
24338b4516dSYitzhak Mandelbaum }
24438b4516dSYitzhak Mandelbaum
24538b4516dSYitzhak Mandelbaum // Returns the expected terminator tokens for the given declaration.
24638b4516dSYitzhak Mandelbaum //
24738b4516dSYitzhak Mandelbaum // If we do not know the correct terminator token, returns an empty set.
24838b4516dSYitzhak Mandelbaum //
24938b4516dSYitzhak Mandelbaum // There are cases where we have more than one possible terminator (for example,
25038b4516dSYitzhak Mandelbaum // we find either a comma or a semicolon after a VarDecl).
getTerminators(const Decl & D)25138b4516dSYitzhak Mandelbaum static std::set<tok::TokenKind> getTerminators(const Decl &D) {
25238b4516dSYitzhak Mandelbaum if (llvm::isa<RecordDecl>(D) || llvm::isa<UsingDecl>(D))
25338b4516dSYitzhak Mandelbaum return {tok::semi};
25438b4516dSYitzhak Mandelbaum
25538b4516dSYitzhak Mandelbaum if (llvm::isa<FunctionDecl>(D) || llvm::isa<LinkageSpecDecl>(D))
25638b4516dSYitzhak Mandelbaum return {tok::r_brace, tok::semi};
25738b4516dSYitzhak Mandelbaum
25838b4516dSYitzhak Mandelbaum if (llvm::isa<VarDecl>(D) || llvm::isa<FieldDecl>(D))
25938b4516dSYitzhak Mandelbaum return {tok::comma, tok::semi};
26038b4516dSYitzhak Mandelbaum
26138b4516dSYitzhak Mandelbaum return {};
26238b4516dSYitzhak Mandelbaum }
26338b4516dSYitzhak Mandelbaum
26438b4516dSYitzhak Mandelbaum // Starting from `Loc`, skips whitespace up to, and including, a single
26538b4516dSYitzhak Mandelbaum // newline. Returns the (exclusive) end of any skipped whitespace (that is, the
26638b4516dSYitzhak Mandelbaum // location immediately after the whitespace).
skipWhitespaceAndNewline(const SourceManager & SM,SourceLocation Loc,const LangOptions & LangOpts)26738b4516dSYitzhak Mandelbaum static SourceLocation skipWhitespaceAndNewline(const SourceManager &SM,
26838b4516dSYitzhak Mandelbaum SourceLocation Loc,
26938b4516dSYitzhak Mandelbaum const LangOptions &LangOpts) {
27038b4516dSYitzhak Mandelbaum const char *LocChars = SM.getCharacterData(Loc);
27138b4516dSYitzhak Mandelbaum int i = 0;
27238b4516dSYitzhak Mandelbaum while (isHorizontalWhitespace(LocChars[i]))
27338b4516dSYitzhak Mandelbaum ++i;
27438b4516dSYitzhak Mandelbaum if (isVerticalWhitespace(LocChars[i]))
27538b4516dSYitzhak Mandelbaum ++i;
27638b4516dSYitzhak Mandelbaum return Loc.getLocWithOffset(i);
27738b4516dSYitzhak Mandelbaum }
27838b4516dSYitzhak Mandelbaum
27938b4516dSYitzhak Mandelbaum // Is `Loc` separated from any following decl by something meaningful (e.g. an
28038b4516dSYitzhak Mandelbaum // empty line, a comment), ignoring horizontal whitespace? Since this is a
28138b4516dSYitzhak Mandelbaum // heuristic, we return false when in doubt. `Loc` cannot be the first location
28238b4516dSYitzhak Mandelbaum // in the file.
atOrBeforeSeparation(const SourceManager & SM,SourceLocation Loc,const LangOptions & LangOpts)28338b4516dSYitzhak Mandelbaum static bool atOrBeforeSeparation(const SourceManager &SM, SourceLocation Loc,
28438b4516dSYitzhak Mandelbaum const LangOptions &LangOpts) {
28538b4516dSYitzhak Mandelbaum // If the preceding character is a newline, we'll check for an empty line as a
28638b4516dSYitzhak Mandelbaum // separator. However, we can't identify an empty line using tokens, so we
28738b4516dSYitzhak Mandelbaum // analyse the characters. If we try to use tokens, we'll just end up with a
28838b4516dSYitzhak Mandelbaum // whitespace token, whose characters we'd have to analyse anyhow.
28938b4516dSYitzhak Mandelbaum bool Invalid = false;
29038b4516dSYitzhak Mandelbaum const char *LocChars =
29138b4516dSYitzhak Mandelbaum SM.getCharacterData(Loc.getLocWithOffset(-1), &Invalid);
29238b4516dSYitzhak Mandelbaum assert(!Invalid &&
29338b4516dSYitzhak Mandelbaum "Loc must be a valid character and not the first of the source file.");
29438b4516dSYitzhak Mandelbaum if (isVerticalWhitespace(LocChars[0])) {
29538b4516dSYitzhak Mandelbaum for (int i = 1; isWhitespace(LocChars[i]); ++i)
29638b4516dSYitzhak Mandelbaum if (isVerticalWhitespace(LocChars[i]))
29738b4516dSYitzhak Mandelbaum return true;
29838b4516dSYitzhak Mandelbaum }
29938b4516dSYitzhak Mandelbaum // We didn't find an empty line, so lex the next token, skipping past any
30038b4516dSYitzhak Mandelbaum // whitespace we just scanned.
30138b4516dSYitzhak Mandelbaum Token Tok;
30238b4516dSYitzhak Mandelbaum bool Failed = Lexer::getRawToken(Loc, Tok, SM, LangOpts,
30338b4516dSYitzhak Mandelbaum /*IgnoreWhiteSpace=*/true);
30438b4516dSYitzhak Mandelbaum if (Failed)
30538b4516dSYitzhak Mandelbaum // Any text that confuses the lexer seems fair to consider a separation.
30638b4516dSYitzhak Mandelbaum return true;
30738b4516dSYitzhak Mandelbaum
30838b4516dSYitzhak Mandelbaum switch (Tok.getKind()) {
30938b4516dSYitzhak Mandelbaum case tok::comment:
31038b4516dSYitzhak Mandelbaum case tok::l_brace:
31138b4516dSYitzhak Mandelbaum case tok::r_brace:
31238b4516dSYitzhak Mandelbaum case tok::eof:
31338b4516dSYitzhak Mandelbaum return true;
31438b4516dSYitzhak Mandelbaum default:
31538b4516dSYitzhak Mandelbaum return false;
31638b4516dSYitzhak Mandelbaum }
31738b4516dSYitzhak Mandelbaum }
31838b4516dSYitzhak Mandelbaum
getAssociatedRange(const Decl & Decl,ASTContext & Context)31938b4516dSYitzhak Mandelbaum CharSourceRange tooling::getAssociatedRange(const Decl &Decl,
32038b4516dSYitzhak Mandelbaum ASTContext &Context) {
32138b4516dSYitzhak Mandelbaum const SourceManager &SM = Context.getSourceManager();
32238b4516dSYitzhak Mandelbaum const LangOptions &LangOpts = Context.getLangOpts();
32338b4516dSYitzhak Mandelbaum CharSourceRange Range = CharSourceRange::getTokenRange(Decl.getSourceRange());
32438b4516dSYitzhak Mandelbaum
32538b4516dSYitzhak Mandelbaum // First, expand to the start of the template<> declaration if necessary.
32638b4516dSYitzhak Mandelbaum if (const auto *Record = llvm::dyn_cast<CXXRecordDecl>(&Decl)) {
32738b4516dSYitzhak Mandelbaum if (const auto *T = Record->getDescribedClassTemplate())
32838b4516dSYitzhak Mandelbaum if (SM.isBeforeInTranslationUnit(T->getBeginLoc(), Range.getBegin()))
32938b4516dSYitzhak Mandelbaum Range.setBegin(T->getBeginLoc());
33038b4516dSYitzhak Mandelbaum } else if (const auto *F = llvm::dyn_cast<FunctionDecl>(&Decl)) {
33138b4516dSYitzhak Mandelbaum if (const auto *T = F->getDescribedFunctionTemplate())
33238b4516dSYitzhak Mandelbaum if (SM.isBeforeInTranslationUnit(T->getBeginLoc(), Range.getBegin()))
33338b4516dSYitzhak Mandelbaum Range.setBegin(T->getBeginLoc());
33438b4516dSYitzhak Mandelbaum }
33538b4516dSYitzhak Mandelbaum
33638b4516dSYitzhak Mandelbaum // Next, expand the end location past trailing comments to include a potential
33738b4516dSYitzhak Mandelbaum // newline at the end of the decl's line.
33838b4516dSYitzhak Mandelbaum Range.setEnd(
33938b4516dSYitzhak Mandelbaum getEntityEndLoc(SM, Decl.getEndLoc(), getTerminators(Decl), LangOpts));
34038b4516dSYitzhak Mandelbaum Range.setTokenRange(false);
34138b4516dSYitzhak Mandelbaum
34238b4516dSYitzhak Mandelbaum // Expand to include preceeding associated comments. We ignore any comments
34338b4516dSYitzhak Mandelbaum // that are not preceeding the decl, since we've already skipped trailing
34438b4516dSYitzhak Mandelbaum // comments with getEntityEndLoc.
34538b4516dSYitzhak Mandelbaum if (const RawComment *Comment =
34638b4516dSYitzhak Mandelbaum Decl.getASTContext().getRawCommentForDeclNoCache(&Decl))
34738b4516dSYitzhak Mandelbaum // Only include a preceding comment if:
34838b4516dSYitzhak Mandelbaum // * it is *not* separate from the declaration (not including any newline
34938b4516dSYitzhak Mandelbaum // that immediately follows the comment),
35038b4516dSYitzhak Mandelbaum // * the decl *is* separate from any following entity (so, there are no
35138b4516dSYitzhak Mandelbaum // other entities the comment could refer to), and
35238b4516dSYitzhak Mandelbaum // * it is not a IfThisThenThat lint check.
35338b4516dSYitzhak Mandelbaum if (SM.isBeforeInTranslationUnit(Comment->getBeginLoc(),
35438b4516dSYitzhak Mandelbaum Range.getBegin()) &&
35538b4516dSYitzhak Mandelbaum !atOrBeforeSeparation(
35638b4516dSYitzhak Mandelbaum SM, skipWhitespaceAndNewline(SM, Comment->getEndLoc(), LangOpts),
35738b4516dSYitzhak Mandelbaum LangOpts) &&
35838b4516dSYitzhak Mandelbaum atOrBeforeSeparation(SM, Range.getEnd(), LangOpts)) {
35938b4516dSYitzhak Mandelbaum const StringRef CommentText = Comment->getRawText(SM);
36038b4516dSYitzhak Mandelbaum if (!CommentText.contains("LINT.IfChange") &&
36138b4516dSYitzhak Mandelbaum !CommentText.contains("LINT.ThenChange"))
36238b4516dSYitzhak Mandelbaum Range.setBegin(Comment->getBeginLoc());
36338b4516dSYitzhak Mandelbaum }
36438b4516dSYitzhak Mandelbaum // Add leading attributes.
36538b4516dSYitzhak Mandelbaum for (auto *Attr : Decl.attrs()) {
36638b4516dSYitzhak Mandelbaum if (Attr->getLocation().isInvalid() ||
36738b4516dSYitzhak Mandelbaum !SM.isBeforeInTranslationUnit(Attr->getLocation(), Range.getBegin()))
36838b4516dSYitzhak Mandelbaum continue;
36938b4516dSYitzhak Mandelbaum Range.setBegin(Attr->getLocation());
37038b4516dSYitzhak Mandelbaum
37138b4516dSYitzhak Mandelbaum // Extend to the left '[[' or '__attribute((' if we saw the attribute,
37238b4516dSYitzhak Mandelbaum // unless it is not a valid location.
37338b4516dSYitzhak Mandelbaum bool Invalid;
37438b4516dSYitzhak Mandelbaum StringRef Source =
37538b4516dSYitzhak Mandelbaum SM.getBufferData(SM.getFileID(Range.getBegin()), &Invalid);
37638b4516dSYitzhak Mandelbaum if (Invalid)
37738b4516dSYitzhak Mandelbaum continue;
37838b4516dSYitzhak Mandelbaum llvm::StringRef BeforeAttr =
37938b4516dSYitzhak Mandelbaum Source.substr(0, SM.getFileOffset(Range.getBegin()));
38038b4516dSYitzhak Mandelbaum llvm::StringRef BeforeAttrStripped = BeforeAttr.rtrim();
38138b4516dSYitzhak Mandelbaum
38238b4516dSYitzhak Mandelbaum for (llvm::StringRef Prefix : {"[[", "__attribute__(("}) {
38338b4516dSYitzhak Mandelbaum // Handle whitespace between attribute prefix and attribute value.
38438b4516dSYitzhak Mandelbaum if (BeforeAttrStripped.endswith(Prefix)) {
38538b4516dSYitzhak Mandelbaum // Move start to start position of prefix, which is
38638b4516dSYitzhak Mandelbaum // length(BeforeAttr) - length(BeforeAttrStripped) + length(Prefix)
38738b4516dSYitzhak Mandelbaum // positions to the left.
38838b4516dSYitzhak Mandelbaum Range.setBegin(Range.getBegin().getLocWithOffset(static_cast<int>(
38938b4516dSYitzhak Mandelbaum -BeforeAttr.size() + BeforeAttrStripped.size() - Prefix.size())));
39038b4516dSYitzhak Mandelbaum break;
39138b4516dSYitzhak Mandelbaum // If we didn't see '[[' or '__attribute' it's probably coming from a
39238b4516dSYitzhak Mandelbaum // macro expansion which is already handled by makeFileCharRange(),
39338b4516dSYitzhak Mandelbaum // below.
39438b4516dSYitzhak Mandelbaum }
39538b4516dSYitzhak Mandelbaum }
39638b4516dSYitzhak Mandelbaum }
39738b4516dSYitzhak Mandelbaum
39838b4516dSYitzhak Mandelbaum // Range.getEnd() is already fully un-expanded by getEntityEndLoc. But,
39938b4516dSYitzhak Mandelbaum // Range.getBegin() may be inside an expansion.
40038b4516dSYitzhak Mandelbaum return Lexer::makeFileCharRange(Range, SM, LangOpts);
40138b4516dSYitzhak Mandelbaum }
402