clang 22.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
22using namespace clang;
23using namespace transformer;
24
26using llvm::Error;
27using llvm::StringError;
28
30
31static Error invalidArgumentError(Twine Message) {
32 return llvm::make_error<StringError>(llvm::errc::invalid_argument, Message);
33}
34
35static Error typeError(StringRef ID, const ASTNodeKind &Kind) {
36 return invalidArgumentError("mismatched type (node id=" + ID +
37 " kind=" + Kind.asStringRef() + ")");
38}
39
40static Error typeError(StringRef ID, const ASTNodeKind &Kind,
41 Twine ExpectedType) {
42 return invalidArgumentError("mismatched type: expected one of " +
43 ExpectedType + " (node id=" + ID +
44 " kind=" + Kind.asStringRef() + ")");
45}
46
47static Error missingPropertyError(StringRef ID, Twine Description,
48 StringRef Property) {
49 return invalidArgumentError(Description + " requires property '" + Property +
50 "' (node id=" + ID + ")");
51}
52
54 StringRef ID) {
55 auto &NodesMap = Nodes.getMap();
56 auto It = NodesMap.find(ID);
57 if (It == NodesMap.end())
58 return invalidArgumentError("ID not bound: " + ID);
59 return It->second;
60}
61
62// FIXME: handling of macros should be configurable.
64 const SourceManager &SM,
65 const LangOptions &LangOpts) {
66 if (Start.isInvalid() || Start.isMacroID())
67 return SourceLocation();
68
69 SourceLocation BeforeStart = Start.getLocWithOffset(-1);
70 if (BeforeStart.isInvalid() || BeforeStart.isMacroID())
71 return SourceLocation();
72
73 return Lexer::GetBeginningOfToken(BeforeStart, SM, LangOpts);
74}
75
76// Finds the start location of the previous token of kind \p TK.
77// FIXME: handling of macros should be configurable.
79 const SourceManager &SM,
80 const LangOptions &LangOpts,
81 tok::TokenKind TK) {
82 while (true) {
83 SourceLocation L = findPreviousTokenStart(Start, SM, LangOpts);
84 if (L.isInvalid() || L.isMacroID())
85 return SourceLocation();
86
87 Token T;
88 if (Lexer::getRawToken(L, T, SM, LangOpts, /*IgnoreWhiteSpace=*/true))
89 return SourceLocation();
90
91 if (T.is(TK))
92 return T.getLocation();
93
94 Start = L;
95 }
96}
97
99 return [Selector](const MatchResult &Result) -> Expected<CharSourceRange> {
100 Expected<CharSourceRange> SelectedRange = Selector(Result);
101 if (!SelectedRange)
102 return SelectedRange.takeError();
103 return CharSourceRange::getCharRange(SelectedRange->getBegin());
104 };
105}
106
108 return [Selector](const MatchResult &Result) -> Expected<CharSourceRange> {
109 Expected<CharSourceRange> SelectedRange = Selector(Result);
110 if (!SelectedRange)
111 return SelectedRange.takeError();
112 SourceLocation End = SelectedRange->getEnd();
113 if (SelectedRange->isTokenRange()) {
114 // We need to find the actual (exclusive) end location from which to
115 // create a new source range. However, that's not guaranteed to be valid,
116 // even if the token location itself is valid. So, we create a token range
117 // consisting only of the last token, then map that range back to the
118 // source file. If that succeeds, we have a valid location for the end of
119 // the generated range.
121 CharSourceRange::getTokenRange(SelectedRange->getEnd()),
122 *Result.SourceManager, Result.Context->getLangOpts());
123 if (Range.isInvalid())
125 "after: can't resolve sub-range to valid source range");
126 End = Range.getEnd();
127 }
128
130 };
131}
132
134 return [ID](const MatchResult &Result) -> Expected<CharSourceRange> {
135 Expected<DynTypedNode> Node = getNode(Result.Nodes, ID);
136 if (!Node)
137 return Node.takeError();
138 return (Node->get<Decl>() != nullptr ||
139 (Node->get<Stmt>() != nullptr && Node->get<Expr>() == nullptr))
140 ? tooling::getExtendedRange(*Node, tok::TokenKind::semi,
141 *Result.Context)
143 };
144}
145
147 return [ID](const MatchResult &Result) -> Expected<CharSourceRange> {
148 Expected<DynTypedNode> Node = getNode(Result.Nodes, ID);
149 if (!Node)
150 return Node.takeError();
151 return tooling::getExtendedRange(*Node, tok::TokenKind::semi,
152 *Result.Context);
153 };
154}
155
157 return [Begin, End](const MatchResult &Result) -> Expected<CharSourceRange> {
158 Expected<CharSourceRange> BeginRange = Begin(Result);
159 if (!BeginRange)
160 return BeginRange.takeError();
161 Expected<CharSourceRange> EndRange = End(Result);
162 if (!EndRange)
163 return EndRange.takeError();
164 SourceLocation B = BeginRange->getBegin();
165 SourceLocation E = EndRange->getEnd();
166 // Note: we are precluding the possibility of sub-token ranges in the case
167 // that EndRange is a token range.
168 if (Result.SourceManager->isBeforeInTranslationUnit(E, B)) {
169 return invalidArgumentError("Bad range: out of order");
170 }
171 return CharSourceRange(SourceRange(B, E), EndRange->isTokenRange());
172 };
173}
174
176 std::string EndID) {
177 return transformer::enclose(node(std::move(BeginID)), node(std::move(EndID)));
178}
179
181 return [ID](const MatchResult &Result) -> Expected<CharSourceRange> {
182 Expected<DynTypedNode> Node = getNode(Result.Nodes, ID);
183 if (!Node)
184 return Node.takeError();
185 if (auto *M = Node->get<clang::MemberExpr>())
187 M->getMemberNameInfo().getSourceRange());
188 return typeError(ID, Node->getNodeKind(), "MemberExpr");
189 };
190}
191
193 return [ID](const MatchResult &Result) -> Expected<CharSourceRange> {
194 Expected<DynTypedNode> N = getNode(Result.Nodes, ID);
195 if (!N)
196 return N.takeError();
197 auto &Node = *N;
198 if (const auto *D = Node.get<NamedDecl>()) {
199 if (!D->getDeclName().isIdentifier())
200 return missingPropertyError(ID, "name", "identifier");
202 auto R = CharSourceRange::getTokenRange(L, L);
203 // Verify that the range covers exactly the name.
204 // FIXME: extend this code to support cases like `operator +` or
205 // `foo<int>` for which this range will be too short. Doing so will
206 // require subcasing `NamedDecl`, because it doesn't provide virtual
207 // access to the \c DeclarationNameInfo.
208 if (tooling::getText(R, *Result.Context) != D->getName())
209 return CharSourceRange();
210 return R;
211 }
212 if (const auto *E = Node.get<DeclRefExpr>()) {
213 if (!E->getNameInfo().getName().isIdentifier())
214 return missingPropertyError(ID, "name", "identifier");
215 SourceLocation L = E->getLocation();
217 }
218 if (const auto *I = Node.get<CXXCtorInitializer>()) {
219 if (!I->isMemberInitializer() && I->isWritten())
220 return missingPropertyError(ID, "name", "explicit member initializer");
221 SourceLocation L = I->getMemberLocation();
223 }
224 if (const auto *T = Node.get<TypeLoc>()) {
225 if (auto SpecLoc = T->getAs<TemplateSpecializationTypeLoc>();
226 !SpecLoc.isNull())
227 return CharSourceRange::getTokenRange(SpecLoc.getTemplateNameLoc());
228 return CharSourceRange::getTokenRange(T->getSourceRange());
229 }
230 return typeError(ID, Node.getNodeKind(),
231 "DeclRefExpr, NamedDecl, CXXCtorInitializer, TypeLoc");
232 };
233}
234
235namespace {
236// FIXME: make this available in the public API for users to easily create their
237// own selectors.
238
239// Creates a selector from a range-selection function \p Func, which selects a
240// range that is relative to a bound node id. \c T is the node type expected by
241// \p Func.
242template <typename T, CharSourceRange (*Func)(const MatchResult &, const T &)>
243class RelativeSelector {
244 std::string ID;
245
246public:
247 RelativeSelector(std::string ID) : ID(std::move(ID)) {}
248
249 Expected<CharSourceRange> operator()(const MatchResult &Result) {
250 Expected<DynTypedNode> N = getNode(Result.Nodes, ID);
251 if (!N)
252 return N.takeError();
253 if (const auto *Arg = N->get<T>())
254 return Func(Result, *Arg);
255 return typeError(ID, N->getNodeKind());
256 }
257};
258} // namespace
259
260// FIXME: Change the following functions from being in an anonymous namespace
261// to static functions, after the minimum Visual C++ has _MSC_VER >= 1915
262// (equivalent to Visual Studio 2017 v15.8 or higher). Using the anonymous
263// namespace works around a bug in earlier versions.
264namespace {
265// Returns the range of the statements (all source between the braces).
266CharSourceRange getStatementsRange(const MatchResult &,
267 const CompoundStmt &CS) {
269 CS.getRBracLoc());
270}
271} // namespace
272
274 return RelativeSelector<CompoundStmt, getStatementsRange>(std::move(ID));
275}
276
277namespace {
278
279SourceLocation findArgStartDelimiter(const CallExpr &E, SourceLocation RLoc,
280 const SourceManager &SM,
281 const LangOptions &LangOpts) {
282 SourceLocation Loc = E.getNumArgs() == 0 ? RLoc : E.getArg(0)->getBeginLoc();
283 return findPreviousTokenKind(Loc, SM, LangOpts, tok::TokenKind::l_paren);
284}
285
286// Returns the location after the last argument of the construct expr. Returns
287// an invalid location if there are no arguments.
288SourceLocation findLastArgEnd(const CXXConstructExpr &CE,
289 const SourceManager &SM,
290 const LangOptions &LangOpts) {
291 for (int i = CE.getNumArgs() - 1; i >= 0; --i) {
292 const Expr *Arg = CE.getArg(i);
293 if (isa<CXXDefaultArgExpr>(Arg))
294 continue;
295 return Lexer::getLocForEndOfToken(Arg->getEndLoc(), 0, SM, LangOpts);
296 }
297 return {};
298}
299
300// Returns the range of the source between the call's parentheses/braces.
301CharSourceRange getCallArgumentsRange(const MatchResult &Result,
302 const CallExpr &CE) {
303 const SourceLocation RLoc = CE.getRParenLoc();
305 findArgStartDelimiter(CE, RLoc, *Result.SourceManager,
306 Result.Context->getLangOpts())
307 .getLocWithOffset(1),
308 RLoc);
309}
310
311// Returns the range of the source between the construct expr's
312// parentheses/braces.
313CharSourceRange getConstructArgumentsRange(const MatchResult &Result,
314 const CXXConstructExpr &CE) {
315 if (SourceRange R = CE.getParenOrBraceRange(); R.isValid()) {
317 Lexer::getLocForEndOfToken(R.getBegin(), 0, *Result.SourceManager,
318 Result.Context->getLangOpts()),
319 R.getEnd());
320 }
321
322 if (CE.getNumArgs() > 0) {
324 CE.getArg(0)->getBeginLoc(),
325 findLastArgEnd(CE, *Result.SourceManager,
326 Result.Context->getLangOpts()));
327 }
328
329 return {};
330}
331
332} // namespace
333
335 return RelativeSelector<CallExpr, getCallArgumentsRange>(std::move(ID));
336}
337
339 return RelativeSelector<CXXConstructExpr, getConstructArgumentsRange>(
340 std::move(ID));
341}
342
343namespace {
344// Returns the range of the elements of the initializer list. Includes all
345// source between the braces.
346CharSourceRange getElementsRange(const MatchResult &,
347 const InitListExpr &E) {
348 return CharSourceRange::getCharRange(E.getLBraceLoc().getLocWithOffset(1),
349 E.getRBraceLoc());
350}
351} // namespace
352
354 return RelativeSelector<InitListExpr, getElementsRange>(std::move(ID));
355}
356
357namespace {
358// Returns the range of the else branch, including the `else` keyword.
359CharSourceRange getElseRange(const MatchResult &Result, const IfStmt &S) {
361 CharSourceRange::getTokenRange(S.getElseLoc(), S.getEndLoc()),
362 tok::TokenKind::semi, *Result.Context);
363}
364} // namespace
365
367 return RelativeSelector<IfStmt, getElseRange>(std::move(ID));
368}
369
371 return [S](const MatchResult &Result) -> Expected<CharSourceRange> {
372 Expected<CharSourceRange> SRange = S(Result);
373 if (!SRange)
374 return SRange.takeError();
375 return Result.SourceManager->getExpansionRange(*SRange);
376 };
377}
BoundNodesTreeBuilder Nodes
DynTypedNode Node
const Decl * D
Expr * E
#define SM(sm)
Definition: OffloadArch.cpp:16
static Error invalidArgumentError(Twine Message)
static SourceLocation findPreviousTokenKind(SourceLocation Start, const SourceManager &SM, const LangOptions &LangOpts, tok::TokenKind TK)
MatchFinder::MatchResult MatchResult
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:753
SourceLocation Loc
Definition: SemaObjC.cpp:754
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:1549
SourceRange getParenOrBraceRange() const
Definition: ExprCXX.h:1730
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition: ExprCXX.h:1692
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Definition: ExprCXX.h:1689
Represents a C++ base or member initializer.
Definition: DeclCXX.h:2369
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2879
SourceLocation getRParenLoc() const
Definition: Expr.h:3210
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:1720
SourceLocation getLBracLoc() const
Definition: Stmt.h:1857
SourceLocation getRBracLoc() const
Definition: Stmt.h:1858
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1272
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
SourceLocation getLocation() const
Definition: DeclBase.h:439
const LangOptions & getLangOpts() const LLVM_READONLY
Helper to get the language options from the ASTContext.
Definition: DeclBase.cpp:530
ASTNodeKind getNodeKind() const
const T * get() const
Retrieve the stored node as type T.
SourceRange getSourceRange(bool IncludeQualifier=false) const
For nodes which represent textual entities in the source code, return their SourceRange.
This represents one expression.
Definition: Expr.h:112
IfStmt - This represents an if/then/else.
Definition: Stmt.h:2259
Describes an C or C++ initializer list.
Definition: Expr.h:5235
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:434
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:951
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:608
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:509
static SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset, const SourceManager &SM, const LangOptions &LangOpts)
Computes the source location just past the end of the token at this source location.
Definition: Lexer.cpp:848
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:3300
This represents a decl that may have a name.
Definition: Decl.h:273
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
bool isValid() const
Stmt - This represents one statement.
Definition: Stmt.h:85
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:358
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:346
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
const T * getAs() const
Member-template getAs<specific type>'.
Definition: TypeBase.h:9159
Maps string IDs to AST nodes matched by parts of a matcher.
Definition: ASTMatchers.h:111
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.