clang 20.0.0git
RangeSelector.cpp
Go to the documentation of this file.
1//===--- RangeSelector.cpp - RangeSelector implementations ------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
10#include "clang/AST/Expr.h"
11#include "clang/AST/TypeLoc.h"
14#include "clang/Lex/Lexer.h"
16#include "llvm/ADT/StringRef.h"
17#include "llvm/Support/Errc.h"
18#include "llvm/Support/Error.h"
19#include <string>
20#include <utility>
21#include <vector>
22
23using namespace clang;
24using namespace transformer;
25
27using llvm::Error;
28using llvm::StringError;
29
31
32static Error invalidArgumentError(Twine Message) {
33 return llvm::make_error<StringError>(llvm::errc::invalid_argument, Message);
34}
35
36static Error typeError(StringRef ID, const ASTNodeKind &Kind) {
37 return invalidArgumentError("mismatched type (node id=" + ID +
38 " kind=" + Kind.asStringRef() + ")");
39}
40
41static Error typeError(StringRef ID, const ASTNodeKind &Kind,
42 Twine ExpectedType) {
43 return invalidArgumentError("mismatched type: expected one of " +
44 ExpectedType + " (node id=" + ID +
45 " kind=" + Kind.asStringRef() + ")");
46}
47
48static Error missingPropertyError(StringRef ID, Twine Description,
49 StringRef Property) {
50 return invalidArgumentError(Description + " requires property '" + Property +
51 "' (node id=" + ID + ")");
52}
53
55 StringRef ID) {
56 auto &NodesMap = Nodes.getMap();
57 auto It = NodesMap.find(ID);
58 if (It == NodesMap.end())
59 return invalidArgumentError("ID not bound: " + ID);
60 return It->second;
61}
62
63// FIXME: handling of macros should be configurable.
65 const SourceManager &SM,
66 const LangOptions &LangOpts) {
67 if (Start.isInvalid() || Start.isMacroID())
68 return SourceLocation();
69
70 SourceLocation BeforeStart = Start.getLocWithOffset(-1);
71 if (BeforeStart.isInvalid() || BeforeStart.isMacroID())
72 return SourceLocation();
73
74 return Lexer::GetBeginningOfToken(BeforeStart, SM, LangOpts);
75}
76
77// Finds the start location of the previous token of kind \p TK.
78// FIXME: handling of macros should be configurable.
80 const SourceManager &SM,
81 const LangOptions &LangOpts,
82 tok::TokenKind TK) {
83 while (true) {
84 SourceLocation L = findPreviousTokenStart(Start, SM, LangOpts);
85 if (L.isInvalid() || L.isMacroID())
86 return SourceLocation();
87
88 Token T;
89 if (Lexer::getRawToken(L, T, SM, LangOpts, /*IgnoreWhiteSpace=*/true))
90 return SourceLocation();
91
92 if (T.is(TK))
93 return T.getLocation();
94
95 Start = L;
96 }
97}
98
100 return [Selector](const MatchResult &Result) -> Expected<CharSourceRange> {
101 Expected<CharSourceRange> SelectedRange = Selector(Result);
102 if (!SelectedRange)
103 return SelectedRange.takeError();
104 return CharSourceRange::getCharRange(SelectedRange->getBegin());
105 };
106}
107
109 return [Selector](const MatchResult &Result) -> Expected<CharSourceRange> {
110 Expected<CharSourceRange> SelectedRange = Selector(Result);
111 if (!SelectedRange)
112 return SelectedRange.takeError();
113 SourceLocation End = SelectedRange->getEnd();
114 if (SelectedRange->isTokenRange()) {
115 // We need to find the actual (exclusive) end location from which to
116 // create a new source range. However, that's not guaranteed to be valid,
117 // even if the token location itself is valid. So, we create a token range
118 // consisting only of the last token, then map that range back to the
119 // source file. If that succeeds, we have a valid location for the end of
120 // the generated range.
122 CharSourceRange::getTokenRange(SelectedRange->getEnd()),
123 *Result.SourceManager, Result.Context->getLangOpts());
124 if (Range.isInvalid())
126 "after: can't resolve sub-range to valid source range");
127 End = Range.getEnd();
128 }
129
131 };
132}
133
135 return [ID](const MatchResult &Result) -> Expected<CharSourceRange> {
136 Expected<DynTypedNode> Node = getNode(Result.Nodes, ID);
137 if (!Node)
138 return Node.takeError();
139 return (Node->get<Decl>() != nullptr ||
140 (Node->get<Stmt>() != nullptr && Node->get<Expr>() == nullptr))
141 ? tooling::getExtendedRange(*Node, tok::TokenKind::semi,
142 *Result.Context)
144 };
145}
146
148 return [ID](const MatchResult &Result) -> Expected<CharSourceRange> {
149 Expected<DynTypedNode> Node = getNode(Result.Nodes, ID);
150 if (!Node)
151 return Node.takeError();
152 return tooling::getExtendedRange(*Node, tok::TokenKind::semi,
153 *Result.Context);
154 };
155}
156
158 return [Begin, End](const MatchResult &Result) -> Expected<CharSourceRange> {
159 Expected<CharSourceRange> BeginRange = Begin(Result);
160 if (!BeginRange)
161 return BeginRange.takeError();
162 Expected<CharSourceRange> EndRange = End(Result);
163 if (!EndRange)
164 return EndRange.takeError();
165 SourceLocation B = BeginRange->getBegin();
166 SourceLocation E = EndRange->getEnd();
167 // Note: we are precluding the possibility of sub-token ranges in the case
168 // that EndRange is a token range.
169 if (Result.SourceManager->isBeforeInTranslationUnit(E, B)) {
170 return invalidArgumentError("Bad range: out of order");
171 }
172 return CharSourceRange(SourceRange(B, E), EndRange->isTokenRange());
173 };
174}
175
177 std::string EndID) {
178 return transformer::enclose(node(std::move(BeginID)), node(std::move(EndID)));
179}
180
182 return [ID](const MatchResult &Result) -> Expected<CharSourceRange> {
183 Expected<DynTypedNode> Node = getNode(Result.Nodes, ID);
184 if (!Node)
185 return Node.takeError();
186 if (auto *M = Node->get<clang::MemberExpr>())
188 M->getMemberNameInfo().getSourceRange());
189 return typeError(ID, Node->getNodeKind(), "MemberExpr");
190 };
191}
192
194 return [ID](const MatchResult &Result) -> Expected<CharSourceRange> {
195 Expected<DynTypedNode> N = getNode(Result.Nodes, ID);
196 if (!N)
197 return N.takeError();
198 auto &Node = *N;
199 if (const auto *D = Node.get<NamedDecl>()) {
200 if (!D->getDeclName().isIdentifier())
201 return missingPropertyError(ID, "name", "identifier");
203 auto R = CharSourceRange::getTokenRange(L, L);
204 // Verify that the range covers exactly the name.
205 // FIXME: extend this code to support cases like `operator +` or
206 // `foo<int>` for which this range will be too short. Doing so will
207 // require subcasing `NamedDecl`, because it doesn't provide virtual
208 // access to the \c DeclarationNameInfo.
209 if (tooling::getText(R, *Result.Context) != D->getName())
210 return CharSourceRange();
211 return R;
212 }
213 if (const auto *E = Node.get<DeclRefExpr>()) {
214 if (!E->getNameInfo().getName().isIdentifier())
215 return missingPropertyError(ID, "name", "identifier");
216 SourceLocation L = E->getLocation();
218 }
219 if (const auto *I = Node.get<CXXCtorInitializer>()) {
220 if (!I->isMemberInitializer() && I->isWritten())
221 return missingPropertyError(ID, "name", "explicit member initializer");
222 SourceLocation L = I->getMemberLocation();
224 }
225 if (const auto *T = Node.get<TypeLoc>()) {
226 TypeLoc Loc = *T;
227 auto ET = Loc.getAs<ElaboratedTypeLoc>();
228 if (!ET.isNull())
229 Loc = ET.getNamedTypeLoc();
230 if (auto SpecLoc = Loc.getAs<TemplateSpecializationTypeLoc>();
231 !SpecLoc.isNull())
232 return CharSourceRange::getTokenRange(SpecLoc.getTemplateNameLoc());
233 return CharSourceRange::getTokenRange(Loc.getSourceRange());
234 }
235 return typeError(ID, Node.getNodeKind(),
236 "DeclRefExpr, NamedDecl, CXXCtorInitializer, TypeLoc");
237 };
238}
239
240namespace {
241// FIXME: make this available in the public API for users to easily create their
242// own selectors.
243
244// Creates a selector from a range-selection function \p Func, which selects a
245// range that is relative to a bound node id. \c T is the node type expected by
246// \p Func.
247template <typename T, CharSourceRange (*Func)(const MatchResult &, const T &)>
248class RelativeSelector {
249 std::string ID;
250
251public:
252 RelativeSelector(std::string ID) : ID(std::move(ID)) {}
253
254 Expected<CharSourceRange> operator()(const MatchResult &Result) {
255 Expected<DynTypedNode> N = getNode(Result.Nodes, ID);
256 if (!N)
257 return N.takeError();
258 if (const auto *Arg = N->get<T>())
259 return Func(Result, *Arg);
260 return typeError(ID, N->getNodeKind());
261 }
262};
263} // namespace
264
265// FIXME: Change the following functions from being in an anonymous namespace
266// to static functions, after the minimum Visual C++ has _MSC_VER >= 1915
267// (equivalent to Visual Studio 2017 v15.8 or higher). Using the anonymous
268// namespace works around a bug in earlier versions.
269namespace {
270// Returns the range of the statements (all source between the braces).
271CharSourceRange getStatementsRange(const MatchResult &,
272 const CompoundStmt &CS) {
274 CS.getRBracLoc());
275}
276} // namespace
277
279 return RelativeSelector<CompoundStmt, getStatementsRange>(std::move(ID));
280}
281
282namespace {
283
284SourceLocation getRLoc(const CallExpr &E) { return E.getRParenLoc(); }
285
286SourceLocation getRLoc(const CXXConstructExpr &E) {
287 return E.getParenOrBraceRange().getEnd();
288}
289
290tok::TokenKind getStartToken(const CallExpr &E) {
291 return tok::TokenKind::l_paren;
292}
293
294tok::TokenKind getStartToken(const CXXConstructExpr &E) {
295 return isa<CXXTemporaryObjectExpr>(E) ? tok::TokenKind::l_paren
296 : tok::TokenKind::l_brace;
297}
298
299template <typename ExprWithArgs>
300SourceLocation findArgStartDelimiter(const ExprWithArgs &E, SourceLocation RLoc,
301 const SourceManager &SM,
302 const LangOptions &LangOpts) {
303 SourceLocation Loc = E.getNumArgs() == 0 ? RLoc : E.getArg(0)->getBeginLoc();
304 return findPreviousTokenKind(Loc, SM, LangOpts, getStartToken(E));
305}
306// Returns the range of the source between the call's or construct expr's
307// parentheses/braces.
308template <typename ExprWithArgs>
309CharSourceRange getArgumentsRange(const MatchResult &Result,
310 const ExprWithArgs &CE) {
311 const SourceLocation RLoc = getRLoc(CE);
313 findArgStartDelimiter(CE, RLoc, *Result.SourceManager,
314 Result.Context->getLangOpts())
315 .getLocWithOffset(1),
316 RLoc);
317}
318} // namespace
319
321 return RelativeSelector<CallExpr, getArgumentsRange<CallExpr>>(std::move(ID));
322}
323
325 return RelativeSelector<CXXConstructExpr,
326 getArgumentsRange<CXXConstructExpr>>(std::move(ID));
327}
328
329namespace {
330// Returns the range of the elements of the initializer list. Includes all
331// source between the braces.
332CharSourceRange getElementsRange(const MatchResult &,
333 const InitListExpr &E) {
334 return CharSourceRange::getCharRange(E.getLBraceLoc().getLocWithOffset(1),
335 E.getRBraceLoc());
336}
337} // namespace
338
340 return RelativeSelector<InitListExpr, getElementsRange>(std::move(ID));
341}
342
343namespace {
344// Returns the range of the else branch, including the `else` keyword.
345CharSourceRange getElseRange(const MatchResult &Result, const IfStmt &S) {
347 CharSourceRange::getTokenRange(S.getElseLoc(), S.getEndLoc()),
348 tok::TokenKind::semi, *Result.Context);
349}
350} // namespace
351
353 return RelativeSelector<IfStmt, getElseRange>(std::move(ID));
354}
355
357 return [S](const MatchResult &Result) -> Expected<CharSourceRange> {
358 Expected<CharSourceRange> SRange = S(Result);
359 if (!SRange)
360 return SRange.takeError();
361 return Result.SourceManager->getExpansionRange(*SRange);
362 };
363}
BoundNodesTreeBuilder Nodes
DynTypedNode Node
#define SM(sm)
Definition: Cuda.cpp:83
const Decl * D
Expr * E
static Error invalidArgumentError(Twine Message)
static SourceLocation findPreviousTokenKind(SourceLocation Start, const SourceManager &SM, const LangOptions &LangOpts, tok::TokenKind TK)
static SourceLocation findPreviousTokenStart(SourceLocation Start, const SourceManager &SM, const LangOptions &LangOpts)
static Error missingPropertyError(StringRef ID, Twine Description, StringRef Property)
static Error typeError(StringRef ID, const ASTNodeKind &Kind)
static Expected< DynTypedNode > getNode(const ast_matchers::BoundNodes &Nodes, StringRef ID)
Defines a combinator library supporting the definition of selectors, which select source ranges based...
SourceRange Range
Definition: SemaObjC.cpp:757
SourceLocation Loc
Definition: SemaObjC.cpp:758
Defines the clang::SourceLocation class and associated facilities.
Defines the clang::TypeLoc interface and its subclasses.
SourceLocation Begin
Kind identifier.
Definition: ASTTypeTraits.h:51
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1546
Represents a C++ base or member initializer.
Definition: DeclCXX.h:2300
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2830
Represents a character-granular source range.
static CharSourceRange getCharRange(SourceRange R)
static CharSourceRange getTokenRange(SourceRange R)
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:1606
SourceLocation getLBracLoc() const
Definition: Stmt.h:1743
SourceLocation getRBracLoc() const
Definition: Stmt.h:1744
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1265
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
SourceLocation getLocation() const
Definition: DeclBase.h:445
const LangOptions & getLangOpts() const LLVM_READONLY
Helper to get the language options from the ASTContext.
Definition: DeclBase.cpp:529
ASTNodeKind getNodeKind() const
SourceRange getSourceRange() const
For nodes which represent textual entities in the source code, return their SourceRange.
const T * get() const
Retrieve the stored node as type T.
This represents one expression.
Definition: Expr.h:110
IfStmt - This represents an if/then/else.
Definition: Stmt.h:2143
Describes an C or C++ initializer list.
Definition: Expr.h:5029
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:461
static CharSourceRange makeFileCharRange(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts)
Accepts a range and returns a character range with file locations.
Definition: Lexer.cpp:955
static SourceLocation GetBeginningOfToken(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Given a location any where in a source buffer, find the location that corresponds to the beginning of...
Definition: Lexer.cpp:609
static bool getRawToken(SourceLocation Loc, Token &Result, const SourceManager &SM, const LangOptions &LangOpts, bool IgnoreWhiteSpace=false)
Relex the token at the specified location.
Definition: Lexer.cpp:510
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:3187
This represents a decl that may have a name.
Definition: Decl.h:249
Smart pointer class that efficiently represents Objective-C method names.
Encodes a location in the source.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
This class handles loading and caching of source files into memory.
A trivial tuple used to represent a source range.
bool isInvalid() const
SourceLocation getEnd() const
Stmt - This represents one statement.
Definition: Stmt.h:84
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:338
Token - This structure provides full information about a lexed token.
Definition: Token.h:36
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:59
bool isNull() const
Definition: TypeLoc.h:121
Maps string IDs to AST nodes matched by parts of a matcher.
Definition: ASTMatchers.h:109
A class to allow finding matches over the Clang AST.
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition: TokenKinds.h:25
CharSourceRange getExtendedRange(const T &Node, tok::TokenKind Next, ASTContext &Context)
Returns the source range spanning the node, extended to include Next, if it immediately follows Node.
Definition: SourceCode.h:34
CharSourceRange maybeExtendRange(CharSourceRange Range, tok::TokenKind Terminator, ASTContext &Context)
Extends Range to include the token Terminator, if it immediately follows the end of the range.
Definition: SourceCode.cpp:37
StringRef getText(CharSourceRange Range, const ASTContext &Context)
Returns the source-code text in the specified range.
Definition: SourceCode.cpp:31
RangeSelector initListElements(std::string ID)
RangeSelector enclose(RangeSelector Begin, RangeSelector End)
Selects from the start of Begin and to the end of End.
RangeSelector member(std::string ID)
Given a MemberExpr, selects the member token.
RangeSelector elseBranch(std::string ID)
Given an \IfStmt (bound to ID), selects the range of the else branch, starting from the else keyword.
RangeSelector node(std::string ID)
Selects a node, including trailing semicolon, if any (for declarations and non-expression statements)...
MatchConsumer< CharSourceRange > RangeSelector
Definition: RangeSelector.h:27
RangeSelector encloseNodes(std::string BeginID, std::string EndID)
Convenience version of range where end-points are bound nodes.
RangeSelector after(RangeSelector Selector)
Selects the point immediately following Selector.
RangeSelector constructExprArgs(std::string ID)
RangeSelector callArgs(std::string ID)
RangeSelector before(RangeSelector Selector)
Selects the (empty) range [B,B) when Selector selects the range [B,E).
RangeSelector statement(std::string ID)
Selects a node, including trailing semicolon (always).
RangeSelector expansion(RangeSelector S)
Selects the range from which S was expanded (possibly along with other source), if S is an expansion,...
RangeSelector statements(std::string ID)
RangeSelector name(std::string ID)
Given a node with a "name", (like NamedDecl, DeclRefExpr, CxxCtorInitializer, and TypeLoc) selects th...
The JSON file list parser is used to communicate input to InstallAPI.
@ Property
The type of a property.
const FunctionProtoType * T
Contains all information for a given match.