Bug Summary

File:clang/lib/Parse/ParseExprCXX.cpp
Warning:line 2023, column 5
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name ParseExprCXX.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -fhalf-no-semantic-interposition -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/build-llvm/tools/clang/lib/Parse -resource-dir /usr/lib/llvm-13/lib/clang/13.0.0 -D CLANG_ROUND_TRIP_CC1_ARGS=ON -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/build-llvm/tools/clang/lib/Parse -I /build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Parse -I /build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include -I /build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/build-llvm/include -I /build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../x86_64-linux-gnu/include -internal-isystem /usr/lib/llvm-13/lib/clang/13.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/build-llvm/tools/clang/lib/Parse -fdebug-prefix-map=/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2021-04-05-202135-9119-1 -x c++ /build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Parse/ParseExprCXX.cpp

/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Parse/ParseExprCXX.cpp

1//===--- ParseExprCXX.cpp - C++ Expression Parsing ------------------------===//
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//
9// This file implements the Expression parsing implementation for C++.
10//
11//===----------------------------------------------------------------------===//
12#include "clang/Parse/Parser.h"
13#include "clang/AST/ASTContext.h"
14#include "clang/AST/Decl.h"
15#include "clang/AST/DeclTemplate.h"
16#include "clang/AST/ExprCXX.h"
17#include "clang/Basic/PrettyStackTrace.h"
18#include "clang/Lex/LiteralSupport.h"
19#include "clang/Parse/ParseDiagnostic.h"
20#include "clang/Parse/RAIIObjectsForParser.h"
21#include "clang/Sema/DeclSpec.h"
22#include "clang/Sema/ParsedTemplate.h"
23#include "clang/Sema/Scope.h"
24#include "llvm/Support/ErrorHandling.h"
25#include <numeric>
26
27using namespace clang;
28
29static int SelectDigraphErrorMessage(tok::TokenKind Kind) {
30 switch (Kind) {
31 // template name
32 case tok::unknown: return 0;
33 // casts
34 case tok::kw_addrspace_cast: return 1;
35 case tok::kw_const_cast: return 2;
36 case tok::kw_dynamic_cast: return 3;
37 case tok::kw_reinterpret_cast: return 4;
38 case tok::kw_static_cast: return 5;
39 default:
40 llvm_unreachable("Unknown type for digraph error message.")::llvm::llvm_unreachable_internal("Unknown type for digraph error message."
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Parse/ParseExprCXX.cpp"
, 40)
;
41 }
42}
43
44// Are the two tokens adjacent in the same source file?
45bool Parser::areTokensAdjacent(const Token &First, const Token &Second) {
46 SourceManager &SM = PP.getSourceManager();
47 SourceLocation FirstLoc = SM.getSpellingLoc(First.getLocation());
48 SourceLocation FirstEnd = FirstLoc.getLocWithOffset(First.getLength());
49 return FirstEnd == SM.getSpellingLoc(Second.getLocation());
50}
51
52// Suggest fixit for "<::" after a cast.
53static void FixDigraph(Parser &P, Preprocessor &PP, Token &DigraphToken,
54 Token &ColonToken, tok::TokenKind Kind, bool AtDigraph) {
55 // Pull '<:' and ':' off token stream.
56 if (!AtDigraph)
57 PP.Lex(DigraphToken);
58 PP.Lex(ColonToken);
59
60 SourceRange Range;
61 Range.setBegin(DigraphToken.getLocation());
62 Range.setEnd(ColonToken.getLocation());
63 P.Diag(DigraphToken.getLocation(), diag::err_missing_whitespace_digraph)
64 << SelectDigraphErrorMessage(Kind)
65 << FixItHint::CreateReplacement(Range, "< ::");
66
67 // Update token information to reflect their change in token type.
68 ColonToken.setKind(tok::coloncolon);
69 ColonToken.setLocation(ColonToken.getLocation().getLocWithOffset(-1));
70 ColonToken.setLength(2);
71 DigraphToken.setKind(tok::less);
72 DigraphToken.setLength(1);
73
74 // Push new tokens back to token stream.
75 PP.EnterToken(ColonToken, /*IsReinject*/ true);
76 if (!AtDigraph)
77 PP.EnterToken(DigraphToken, /*IsReinject*/ true);
78}
79
80// Check for '<::' which should be '< ::' instead of '[:' when following
81// a template name.
82void Parser::CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectType,
83 bool EnteringContext,
84 IdentifierInfo &II, CXXScopeSpec &SS) {
85 if (!Next.is(tok::l_square) || Next.getLength() != 2)
86 return;
87
88 Token SecondToken = GetLookAheadToken(2);
89 if (!SecondToken.is(tok::colon) || !areTokensAdjacent(Next, SecondToken))
90 return;
91
92 TemplateTy Template;
93 UnqualifiedId TemplateName;
94 TemplateName.setIdentifier(&II, Tok.getLocation());
95 bool MemberOfUnknownSpecialization;
96 if (!Actions.isTemplateName(getCurScope(), SS, /*hasTemplateKeyword=*/false,
97 TemplateName, ObjectType, EnteringContext,
98 Template, MemberOfUnknownSpecialization))
99 return;
100
101 FixDigraph(*this, PP, Next, SecondToken, tok::unknown,
102 /*AtDigraph*/false);
103}
104
105/// Parse global scope or nested-name-specifier if present.
106///
107/// Parses a C++ global scope specifier ('::') or nested-name-specifier (which
108/// may be preceded by '::'). Note that this routine will not parse ::new or
109/// ::delete; it will just leave them in the token stream.
110///
111/// '::'[opt] nested-name-specifier
112/// '::'
113///
114/// nested-name-specifier:
115/// type-name '::'
116/// namespace-name '::'
117/// nested-name-specifier identifier '::'
118/// nested-name-specifier 'template'[opt] simple-template-id '::'
119///
120///
121/// \param SS the scope specifier that will be set to the parsed
122/// nested-name-specifier (or empty)
123///
124/// \param ObjectType if this nested-name-specifier is being parsed following
125/// the "." or "->" of a member access expression, this parameter provides the
126/// type of the object whose members are being accessed.
127///
128/// \param ObjectHadErrors if this unqualified-id occurs within a member access
129/// expression, indicates whether the original subexpressions had any errors.
130/// When true, diagnostics for missing 'template' keyword will be supressed.
131///
132/// \param EnteringContext whether we will be entering into the context of
133/// the nested-name-specifier after parsing it.
134///
135/// \param MayBePseudoDestructor When non-NULL, points to a flag that
136/// indicates whether this nested-name-specifier may be part of a
137/// pseudo-destructor name. In this case, the flag will be set false
138/// if we don't actually end up parsing a destructor name. Moreover,
139/// if we do end up determining that we are parsing a destructor name,
140/// the last component of the nested-name-specifier is not parsed as
141/// part of the scope specifier.
142///
143/// \param IsTypename If \c true, this nested-name-specifier is known to be
144/// part of a type name. This is used to improve error recovery.
145///
146/// \param LastII When non-NULL, points to an IdentifierInfo* that will be
147/// filled in with the leading identifier in the last component of the
148/// nested-name-specifier, if any.
149///
150/// \param OnlyNamespace If true, only considers namespaces in lookup.
151///
152///
153/// \returns true if there was an error parsing a scope specifier
154bool Parser::ParseOptionalCXXScopeSpecifier(
155 CXXScopeSpec &SS, ParsedType ObjectType, bool ObjectHadErrors,
156 bool EnteringContext, bool *MayBePseudoDestructor, bool IsTypename,
157 IdentifierInfo **LastII, bool OnlyNamespace, bool InUsingDeclaration) {
158 assert(getLangOpts().CPlusPlus &&((getLangOpts().CPlusPlus && "Call sites of this function should be guarded by checking for C++"
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"Call sites of this function should be guarded by checking for C++\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Parse/ParseExprCXX.cpp"
, 159, __PRETTY_FUNCTION__))
159 "Call sites of this function should be guarded by checking for C++")((getLangOpts().CPlusPlus && "Call sites of this function should be guarded by checking for C++"
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"Call sites of this function should be guarded by checking for C++\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Parse/ParseExprCXX.cpp"
, 159, __PRETTY_FUNCTION__))
;
160
161 if (Tok.is(tok::annot_cxxscope)) {
162 assert(!LastII && "want last identifier but have already annotated scope")((!LastII && "want last identifier but have already annotated scope"
) ? static_cast<void> (0) : __assert_fail ("!LastII && \"want last identifier but have already annotated scope\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Parse/ParseExprCXX.cpp"
, 162, __PRETTY_FUNCTION__))
;
163 assert(!MayBePseudoDestructor && "unexpected annot_cxxscope")((!MayBePseudoDestructor && "unexpected annot_cxxscope"
) ? static_cast<void> (0) : __assert_fail ("!MayBePseudoDestructor && \"unexpected annot_cxxscope\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Parse/ParseExprCXX.cpp"
, 163, __PRETTY_FUNCTION__))
;
164 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
165 Tok.getAnnotationRange(),
166 SS);
167 ConsumeAnnotationToken();
168 return false;
169 }
170
171 // Has to happen before any "return false"s in this function.
172 bool CheckForDestructor = false;
173 if (MayBePseudoDestructor && *MayBePseudoDestructor) {
174 CheckForDestructor = true;
175 *MayBePseudoDestructor = false;
176 }
177
178 if (LastII)
179 *LastII = nullptr;
180
181 bool HasScopeSpecifier = false;
182
183 if (Tok.is(tok::coloncolon)) {
184 // ::new and ::delete aren't nested-name-specifiers.
185 tok::TokenKind NextKind = NextToken().getKind();
186 if (NextKind == tok::kw_new || NextKind == tok::kw_delete)
187 return false;
188
189 if (NextKind == tok::l_brace) {
190 // It is invalid to have :: {, consume the scope qualifier and pretend
191 // like we never saw it.
192 Diag(ConsumeToken(), diag::err_expected) << tok::identifier;
193 } else {
194 // '::' - Global scope qualifier.
195 if (Actions.ActOnCXXGlobalScopeSpecifier(ConsumeToken(), SS))
196 return true;
197
198 HasScopeSpecifier = true;
199 }
200 }
201
202 if (Tok.is(tok::kw___super)) {
203 SourceLocation SuperLoc = ConsumeToken();
204 if (!Tok.is(tok::coloncolon)) {
205 Diag(Tok.getLocation(), diag::err_expected_coloncolon_after_super);
206 return true;
207 }
208
209 return Actions.ActOnSuperScopeSpecifier(SuperLoc, ConsumeToken(), SS);
210 }
211
212 if (!HasScopeSpecifier &&
213 Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)) {
214 DeclSpec DS(AttrFactory);
215 SourceLocation DeclLoc = Tok.getLocation();
216 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
217
218 SourceLocation CCLoc;
219 // Work around a standard defect: 'decltype(auto)::' is not a
220 // nested-name-specifier.
221 if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto ||
222 !TryConsumeToken(tok::coloncolon, CCLoc)) {
223 AnnotateExistingDecltypeSpecifier(DS, DeclLoc, EndLoc);
224 return false;
225 }
226
227 if (Actions.ActOnCXXNestedNameSpecifierDecltype(SS, DS, CCLoc))
228 SS.SetInvalid(SourceRange(DeclLoc, CCLoc));
229
230 HasScopeSpecifier = true;
231 }
232
233 // Preferred type might change when parsing qualifiers, we need the original.
234 auto SavedType = PreferredType;
235 while (true) {
236 if (HasScopeSpecifier) {
237 if (Tok.is(tok::code_completion)) {
238 cutOffParsing();
239 // Code completion for a nested-name-specifier, where the code
240 // completion token follows the '::'.
241 Actions.CodeCompleteQualifiedId(getCurScope(), SS, EnteringContext,
242 InUsingDeclaration, ObjectType.get(),
243 SavedType.get(SS.getBeginLoc()));
244 // Include code completion token into the range of the scope otherwise
245 // when we try to annotate the scope tokens the dangling code completion
246 // token will cause assertion in
247 // Preprocessor::AnnotatePreviousCachedTokens.
248 SS.setEndLoc(Tok.getLocation());
249 return true;
250 }
251
252 // C++ [basic.lookup.classref]p5:
253 // If the qualified-id has the form
254 //
255 // ::class-name-or-namespace-name::...
256 //
257 // the class-name-or-namespace-name is looked up in global scope as a
258 // class-name or namespace-name.
259 //
260 // To implement this, we clear out the object type as soon as we've
261 // seen a leading '::' or part of a nested-name-specifier.
262 ObjectType = nullptr;
263 }
264
265 // nested-name-specifier:
266 // nested-name-specifier 'template'[opt] simple-template-id '::'
267
268 // Parse the optional 'template' keyword, then make sure we have
269 // 'identifier <' after it.
270 if (Tok.is(tok::kw_template)) {
271 // If we don't have a scope specifier or an object type, this isn't a
272 // nested-name-specifier, since they aren't allowed to start with
273 // 'template'.
274 if (!HasScopeSpecifier && !ObjectType)
275 break;
276
277 TentativeParsingAction TPA(*this);
278 SourceLocation TemplateKWLoc = ConsumeToken();
279
280 UnqualifiedId TemplateName;
281 if (Tok.is(tok::identifier)) {
282 // Consume the identifier.
283 TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
284 ConsumeToken();
285 } else if (Tok.is(tok::kw_operator)) {
286 // We don't need to actually parse the unqualified-id in this case,
287 // because a simple-template-id cannot start with 'operator', but
288 // go ahead and parse it anyway for consistency with the case where
289 // we already annotated the template-id.
290 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType,
291 TemplateName)) {
292 TPA.Commit();
293 break;
294 }
295
296 if (TemplateName.getKind() != UnqualifiedIdKind::IK_OperatorFunctionId &&
297 TemplateName.getKind() != UnqualifiedIdKind::IK_LiteralOperatorId) {
298 Diag(TemplateName.getSourceRange().getBegin(),
299 diag::err_id_after_template_in_nested_name_spec)
300 << TemplateName.getSourceRange();
301 TPA.Commit();
302 break;
303 }
304 } else {
305 TPA.Revert();
306 break;
307 }
308
309 // If the next token is not '<', we have a qualified-id that refers
310 // to a template name, such as T::template apply, but is not a
311 // template-id.
312 if (Tok.isNot(tok::less)) {
313 TPA.Revert();
314 break;
315 }
316
317 // Commit to parsing the template-id.
318 TPA.Commit();
319 TemplateTy Template;
320 TemplateNameKind TNK = Actions.ActOnTemplateName(
321 getCurScope(), SS, TemplateKWLoc, TemplateName, ObjectType,
322 EnteringContext, Template, /*AllowInjectedClassName*/ true);
323 if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateKWLoc,
324 TemplateName, false))
325 return true;
326
327 continue;
328 }
329
330 if (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) {
331 // We have
332 //
333 // template-id '::'
334 //
335 // So we need to check whether the template-id is a simple-template-id of
336 // the right kind (it should name a type or be dependent), and then
337 // convert it into a type within the nested-name-specifier.
338 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
339 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde)) {
340 *MayBePseudoDestructor = true;
341 return false;
342 }
343
344 if (LastII)
345 *LastII = TemplateId->Name;
346
347 // Consume the template-id token.
348 ConsumeAnnotationToken();
349
350 assert(Tok.is(tok::coloncolon) && "NextToken() not working properly!")((Tok.is(tok::coloncolon) && "NextToken() not working properly!"
) ? static_cast<void> (0) : __assert_fail ("Tok.is(tok::coloncolon) && \"NextToken() not working properly!\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Parse/ParseExprCXX.cpp"
, 350, __PRETTY_FUNCTION__))
;
351 SourceLocation CCLoc = ConsumeToken();
352
353 HasScopeSpecifier = true;
354
355 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
356 TemplateId->NumArgs);
357
358 if (TemplateId->isInvalid() ||
359 Actions.ActOnCXXNestedNameSpecifier(getCurScope(),
360 SS,
361 TemplateId->TemplateKWLoc,
362 TemplateId->Template,
363 TemplateId->TemplateNameLoc,
364 TemplateId->LAngleLoc,
365 TemplateArgsPtr,
366 TemplateId->RAngleLoc,
367 CCLoc,
368 EnteringContext)) {
369 SourceLocation StartLoc
370 = SS.getBeginLoc().isValid()? SS.getBeginLoc()
371 : TemplateId->TemplateNameLoc;
372 SS.SetInvalid(SourceRange(StartLoc, CCLoc));
373 }
374
375 continue;
376 }
377
378 // The rest of the nested-name-specifier possibilities start with
379 // tok::identifier.
380 if (Tok.isNot(tok::identifier))
381 break;
382
383 IdentifierInfo &II = *Tok.getIdentifierInfo();
384
385 // nested-name-specifier:
386 // type-name '::'
387 // namespace-name '::'
388 // nested-name-specifier identifier '::'
389 Token Next = NextToken();
390 Sema::NestedNameSpecInfo IdInfo(&II, Tok.getLocation(), Next.getLocation(),
391 ObjectType);
392
393 // If we get foo:bar, this is almost certainly a typo for foo::bar. Recover
394 // and emit a fixit hint for it.
395 if (Next.is(tok::colon) && !ColonIsSacred) {
396 if (Actions.IsInvalidUnlessNestedName(getCurScope(), SS, IdInfo,
397 EnteringContext) &&
398 // If the token after the colon isn't an identifier, it's still an
399 // error, but they probably meant something else strange so don't
400 // recover like this.
401 PP.LookAhead(1).is(tok::identifier)) {
402 Diag(Next, diag::err_unexpected_colon_in_nested_name_spec)
403 << FixItHint::CreateReplacement(Next.getLocation(), "::");
404 // Recover as if the user wrote '::'.
405 Next.setKind(tok::coloncolon);
406 }
407 }
408
409 if (Next.is(tok::coloncolon) && GetLookAheadToken(2).is(tok::l_brace)) {
410 // It is invalid to have :: {, consume the scope qualifier and pretend
411 // like we never saw it.
412 Token Identifier = Tok; // Stash away the identifier.
413 ConsumeToken(); // Eat the identifier, current token is now '::'.
414 Diag(PP.getLocForEndOfToken(ConsumeToken()), diag::err_expected)
415 << tok::identifier;
416 UnconsumeToken(Identifier); // Stick the identifier back.
417 Next = NextToken(); // Point Next at the '{' token.
418 }
419
420 if (Next.is(tok::coloncolon)) {
421 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde)) {
422 *MayBePseudoDestructor = true;
423 return false;
424 }
425
426 if (ColonIsSacred) {
427 const Token &Next2 = GetLookAheadToken(2);
428 if (Next2.is(tok::kw_private) || Next2.is(tok::kw_protected) ||
429 Next2.is(tok::kw_public) || Next2.is(tok::kw_virtual)) {
430 Diag(Next2, diag::err_unexpected_token_in_nested_name_spec)
431 << Next2.getName()
432 << FixItHint::CreateReplacement(Next.getLocation(), ":");
433 Token ColonColon;
434 PP.Lex(ColonColon);
435 ColonColon.setKind(tok::colon);
436 PP.EnterToken(ColonColon, /*IsReinject*/ true);
437 break;
438 }
439 }
440
441 if (LastII)
442 *LastII = &II;
443
444 // We have an identifier followed by a '::'. Lookup this name
445 // as the name in a nested-name-specifier.
446 Token Identifier = Tok;
447 SourceLocation IdLoc = ConsumeToken();
448 assert(Tok.isOneOf(tok::coloncolon, tok::colon) &&((Tok.isOneOf(tok::coloncolon, tok::colon) && "NextToken() not working properly!"
) ? static_cast<void> (0) : __assert_fail ("Tok.isOneOf(tok::coloncolon, tok::colon) && \"NextToken() not working properly!\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Parse/ParseExprCXX.cpp"
, 449, __PRETTY_FUNCTION__))
449 "NextToken() not working properly!")((Tok.isOneOf(tok::coloncolon, tok::colon) && "NextToken() not working properly!"
) ? static_cast<void> (0) : __assert_fail ("Tok.isOneOf(tok::coloncolon, tok::colon) && \"NextToken() not working properly!\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Parse/ParseExprCXX.cpp"
, 449, __PRETTY_FUNCTION__))
;
450 Token ColonColon = Tok;
451 SourceLocation CCLoc = ConsumeToken();
452
453 bool IsCorrectedToColon = false;
454 bool *CorrectionFlagPtr = ColonIsSacred ? &IsCorrectedToColon : nullptr;
455 if (Actions.ActOnCXXNestedNameSpecifier(
456 getCurScope(), IdInfo, EnteringContext, SS, false,
457 CorrectionFlagPtr, OnlyNamespace)) {
458 // Identifier is not recognized as a nested name, but we can have
459 // mistyped '::' instead of ':'.
460 if (CorrectionFlagPtr && IsCorrectedToColon) {
461 ColonColon.setKind(tok::colon);
462 PP.EnterToken(Tok, /*IsReinject*/ true);
463 PP.EnterToken(ColonColon, /*IsReinject*/ true);
464 Tok = Identifier;
465 break;
466 }
467 SS.SetInvalid(SourceRange(IdLoc, CCLoc));
468 }
469 HasScopeSpecifier = true;
470 continue;
471 }
472
473 CheckForTemplateAndDigraph(Next, ObjectType, EnteringContext, II, SS);
474
475 // nested-name-specifier:
476 // type-name '<'
477 if (Next.is(tok::less)) {
478
479 TemplateTy Template;
480 UnqualifiedId TemplateName;
481 TemplateName.setIdentifier(&II, Tok.getLocation());
482 bool MemberOfUnknownSpecialization;
483 if (TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
484 /*hasTemplateKeyword=*/false,
485 TemplateName,
486 ObjectType,
487 EnteringContext,
488 Template,
489 MemberOfUnknownSpecialization)) {
490 // If lookup didn't find anything, we treat the name as a template-name
491 // anyway. C++20 requires this, and in prior language modes it improves
492 // error recovery. But before we commit to this, check that we actually
493 // have something that looks like a template-argument-list next.
494 if (!IsTypename && TNK == TNK_Undeclared_template &&
495 isTemplateArgumentList(1) == TPResult::False)
496 break;
497
498 // We have found a template name, so annotate this token
499 // with a template-id annotation. We do not permit the
500 // template-id to be translated into a type annotation,
501 // because some clients (e.g., the parsing of class template
502 // specializations) still want to see the original template-id
503 // token, and it might not be a type at all (e.g. a concept name in a
504 // type-constraint).
505 ConsumeToken();
506 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
507 TemplateName, false))
508 return true;
509 continue;
510 }
511
512 if (MemberOfUnknownSpecialization && (ObjectType || SS.isSet()) &&
513 (IsTypename || isTemplateArgumentList(1) == TPResult::True)) {
514 // If we had errors before, ObjectType can be dependent even without any
515 // templates. Do not report missing template keyword in that case.
516 if (!ObjectHadErrors) {
517 // We have something like t::getAs<T>, where getAs is a
518 // member of an unknown specialization. However, this will only
519 // parse correctly as a template, so suggest the keyword 'template'
520 // before 'getAs' and treat this as a dependent template name.
521 unsigned DiagID = diag::err_missing_dependent_template_keyword;
522 if (getLangOpts().MicrosoftExt)
523 DiagID = diag::warn_missing_dependent_template_keyword;
524
525 Diag(Tok.getLocation(), DiagID)
526 << II.getName()
527 << FixItHint::CreateInsertion(Tok.getLocation(), "template ");
528 }
529
530 SourceLocation TemplateNameLoc = ConsumeToken();
531
532 TemplateNameKind TNK = Actions.ActOnTemplateName(
533 getCurScope(), SS, TemplateNameLoc, TemplateName, ObjectType,
534 EnteringContext, Template, /*AllowInjectedClassName*/ true);
535 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
536 TemplateName, false))
537 return true;
538
539 continue;
540 }
541 }
542
543 // We don't have any tokens that form the beginning of a
544 // nested-name-specifier, so we're done.
545 break;
546 }
547
548 // Even if we didn't see any pieces of a nested-name-specifier, we
549 // still check whether there is a tilde in this position, which
550 // indicates a potential pseudo-destructor.
551 if (CheckForDestructor && !HasScopeSpecifier && Tok.is(tok::tilde))
552 *MayBePseudoDestructor = true;
553
554 return false;
555}
556
557ExprResult Parser::tryParseCXXIdExpression(CXXScopeSpec &SS,
558 bool isAddressOfOperand,
559 Token &Replacement) {
560 ExprResult E;
561
562 // We may have already annotated this id-expression.
563 switch (Tok.getKind()) {
564 case tok::annot_non_type: {
565 NamedDecl *ND = getNonTypeAnnotation(Tok);
566 SourceLocation Loc = ConsumeAnnotationToken();
567 E = Actions.ActOnNameClassifiedAsNonType(getCurScope(), SS, ND, Loc, Tok);
568 break;
569 }
570
571 case tok::annot_non_type_dependent: {
572 IdentifierInfo *II = getIdentifierAnnotation(Tok);
573 SourceLocation Loc = ConsumeAnnotationToken();
574
575 // This is only the direct operand of an & operator if it is not
576 // followed by a postfix-expression suffix.
577 if (isAddressOfOperand && isPostfixExpressionSuffixStart())
578 isAddressOfOperand = false;
579
580 E = Actions.ActOnNameClassifiedAsDependentNonType(SS, II, Loc,
581 isAddressOfOperand);
582 break;
583 }
584
585 case tok::annot_non_type_undeclared: {
586 assert(SS.isEmpty() &&((SS.isEmpty() && "undeclared non-type annotation should be unqualified"
) ? static_cast<void> (0) : __assert_fail ("SS.isEmpty() && \"undeclared non-type annotation should be unqualified\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Parse/ParseExprCXX.cpp"
, 587, __PRETTY_FUNCTION__))
587 "undeclared non-type annotation should be unqualified")((SS.isEmpty() && "undeclared non-type annotation should be unqualified"
) ? static_cast<void> (0) : __assert_fail ("SS.isEmpty() && \"undeclared non-type annotation should be unqualified\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Parse/ParseExprCXX.cpp"
, 587, __PRETTY_FUNCTION__))
;
588 IdentifierInfo *II = getIdentifierAnnotation(Tok);
589 SourceLocation Loc = ConsumeAnnotationToken();
590 E = Actions.ActOnNameClassifiedAsUndeclaredNonType(II, Loc);
591 break;
592 }
593
594 default:
595 SourceLocation TemplateKWLoc;
596 UnqualifiedId Name;
597 if (ParseUnqualifiedId(SS, /*ObjectType=*/nullptr,
598 /*ObjectHadErrors=*/false,
599 /*EnteringContext=*/false,
600 /*AllowDestructorName=*/false,
601 /*AllowConstructorName=*/false,
602 /*AllowDeductionGuide=*/false, &TemplateKWLoc, Name))
603 return ExprError();
604
605 // This is only the direct operand of an & operator if it is not
606 // followed by a postfix-expression suffix.
607 if (isAddressOfOperand && isPostfixExpressionSuffixStart())
608 isAddressOfOperand = false;
609
610 E = Actions.ActOnIdExpression(
611 getCurScope(), SS, TemplateKWLoc, Name, Tok.is(tok::l_paren),
612 isAddressOfOperand, /*CCC=*/nullptr, /*IsInlineAsmIdentifier=*/false,
613 &Replacement);
614 break;
615 }
616
617 if (!E.isInvalid() && !E.isUnset() && Tok.is(tok::less))
618 checkPotentialAngleBracket(E);
619 return E;
620}
621
622/// ParseCXXIdExpression - Handle id-expression.
623///
624/// id-expression:
625/// unqualified-id
626/// qualified-id
627///
628/// qualified-id:
629/// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
630/// '::' identifier
631/// '::' operator-function-id
632/// '::' template-id
633///
634/// NOTE: The standard specifies that, for qualified-id, the parser does not
635/// expect:
636///
637/// '::' conversion-function-id
638/// '::' '~' class-name
639///
640/// This may cause a slight inconsistency on diagnostics:
641///
642/// class C {};
643/// namespace A {}
644/// void f() {
645/// :: A :: ~ C(); // Some Sema error about using destructor with a
646/// // namespace.
647/// :: ~ C(); // Some Parser error like 'unexpected ~'.
648/// }
649///
650/// We simplify the parser a bit and make it work like:
651///
652/// qualified-id:
653/// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
654/// '::' unqualified-id
655///
656/// That way Sema can handle and report similar errors for namespaces and the
657/// global scope.
658///
659/// The isAddressOfOperand parameter indicates that this id-expression is a
660/// direct operand of the address-of operator. This is, besides member contexts,
661/// the only place where a qualified-id naming a non-static class member may
662/// appear.
663///
664ExprResult Parser::ParseCXXIdExpression(bool isAddressOfOperand) {
665 // qualified-id:
666 // '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
667 // '::' unqualified-id
668 //
669 CXXScopeSpec SS;
670 ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
671 /*ObjectHadErrors=*/false,
672 /*EnteringContext=*/false);
673
674 Token Replacement;
675 ExprResult Result =
676 tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
677 if (Result.isUnset()) {
678 // If the ExprResult is valid but null, then typo correction suggested a
679 // keyword replacement that needs to be reparsed.
680 UnconsumeToken(Replacement);
681 Result = tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
682 }
683 assert(!Result.isUnset() && "Typo correction suggested a keyword replacement "((!Result.isUnset() && "Typo correction suggested a keyword replacement "
"for a previous keyword suggestion") ? static_cast<void>
(0) : __assert_fail ("!Result.isUnset() && \"Typo correction suggested a keyword replacement \" \"for a previous keyword suggestion\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Parse/ParseExprCXX.cpp"
, 684, __PRETTY_FUNCTION__))
684 "for a previous keyword suggestion")((!Result.isUnset() && "Typo correction suggested a keyword replacement "
"for a previous keyword suggestion") ? static_cast<void>
(0) : __assert_fail ("!Result.isUnset() && \"Typo correction suggested a keyword replacement \" \"for a previous keyword suggestion\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Parse/ParseExprCXX.cpp"
, 684, __PRETTY_FUNCTION__))
;
685 return Result;
686}
687
688/// ParseLambdaExpression - Parse a C++11 lambda expression.
689///
690/// lambda-expression:
691/// lambda-introducer lambda-declarator compound-statement
692/// lambda-introducer '<' template-parameter-list '>'
693/// requires-clause[opt] lambda-declarator compound-statement
694///
695/// lambda-introducer:
696/// '[' lambda-capture[opt] ']'
697///
698/// lambda-capture:
699/// capture-default
700/// capture-list
701/// capture-default ',' capture-list
702///
703/// capture-default:
704/// '&'
705/// '='
706///
707/// capture-list:
708/// capture
709/// capture-list ',' capture
710///
711/// capture:
712/// simple-capture
713/// init-capture [C++1y]
714///
715/// simple-capture:
716/// identifier
717/// '&' identifier
718/// 'this'
719///
720/// init-capture: [C++1y]
721/// identifier initializer
722/// '&' identifier initializer
723///
724/// lambda-declarator:
725/// lambda-specifiers [C++2b]
726/// '(' parameter-declaration-clause ')' lambda-specifiers
727/// requires-clause[opt]
728///
729/// lambda-specifiers:
730/// decl-specifier-seq[opt] noexcept-specifier[opt]
731/// attribute-specifier-seq[opt] trailing-return-type[opt]
732///
733ExprResult Parser::ParseLambdaExpression() {
734 // Parse lambda-introducer.
735 LambdaIntroducer Intro;
736 if (ParseLambdaIntroducer(Intro)) {
737 SkipUntil(tok::r_square, StopAtSemi);
738 SkipUntil(tok::l_brace, StopAtSemi);
739 SkipUntil(tok::r_brace, StopAtSemi);
740 return ExprError();
741 }
742
743 return ParseLambdaExpressionAfterIntroducer(Intro);
744}
745
746/// Use lookahead and potentially tentative parsing to determine if we are
747/// looking at a C++11 lambda expression, and parse it if we are.
748///
749/// If we are not looking at a lambda expression, returns ExprError().
750ExprResult Parser::TryParseLambdaExpression() {
751 assert(getLangOpts().CPlusPlus11((getLangOpts().CPlusPlus11 && Tok.is(tok::l_square) &&
"Not at the start of a possible lambda expression.") ? static_cast
<void> (0) : __assert_fail ("getLangOpts().CPlusPlus11 && Tok.is(tok::l_square) && \"Not at the start of a possible lambda expression.\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Parse/ParseExprCXX.cpp"
, 753, __PRETTY_FUNCTION__))
752 && Tok.is(tok::l_square)((getLangOpts().CPlusPlus11 && Tok.is(tok::l_square) &&
"Not at the start of a possible lambda expression.") ? static_cast
<void> (0) : __assert_fail ("getLangOpts().CPlusPlus11 && Tok.is(tok::l_square) && \"Not at the start of a possible lambda expression.\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Parse/ParseExprCXX.cpp"
, 753, __PRETTY_FUNCTION__))
753 && "Not at the start of a possible lambda expression.")((getLangOpts().CPlusPlus11 && Tok.is(tok::l_square) &&
"Not at the start of a possible lambda expression.") ? static_cast
<void> (0) : __assert_fail ("getLangOpts().CPlusPlus11 && Tok.is(tok::l_square) && \"Not at the start of a possible lambda expression.\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Parse/ParseExprCXX.cpp"
, 753, __PRETTY_FUNCTION__))
;
754
755 const Token Next = NextToken();
756 if (Next.is(tok::eof)) // Nothing else to lookup here...
757 return ExprEmpty();
758
759 const Token After = GetLookAheadToken(2);
760 // If lookahead indicates this is a lambda...
761 if (Next.is(tok::r_square) || // []
762 Next.is(tok::equal) || // [=
763 (Next.is(tok::amp) && // [&] or [&,
764 After.isOneOf(tok::r_square, tok::comma)) ||
765 (Next.is(tok::identifier) && // [identifier]
766 After.is(tok::r_square)) ||
767 Next.is(tok::ellipsis)) { // [...
768 return ParseLambdaExpression();
769 }
770
771 // If lookahead indicates an ObjC message send...
772 // [identifier identifier
773 if (Next.is(tok::identifier) && After.is(tok::identifier))
774 return ExprEmpty();
775
776 // Here, we're stuck: lambda introducers and Objective-C message sends are
777 // unambiguous, but it requires arbitrary lookhead. [a,b,c,d,e,f,g] is a
778 // lambda, and [a,b,c,d,e,f,g h] is a Objective-C message send. Instead of
779 // writing two routines to parse a lambda introducer, just try to parse
780 // a lambda introducer first, and fall back if that fails.
781 LambdaIntroducer Intro;
782 {
783 TentativeParsingAction TPA(*this);
784 LambdaIntroducerTentativeParse Tentative;
785 if (ParseLambdaIntroducer(Intro, &Tentative)) {
786 TPA.Commit();
787 return ExprError();
788 }
789
790 switch (Tentative) {
791 case LambdaIntroducerTentativeParse::Success:
792 TPA.Commit();
793 break;
794
795 case LambdaIntroducerTentativeParse::Incomplete:
796 // Didn't fully parse the lambda-introducer, try again with a
797 // non-tentative parse.
798 TPA.Revert();
799 Intro = LambdaIntroducer();
800 if (ParseLambdaIntroducer(Intro))
801 return ExprError();
802 break;
803
804 case LambdaIntroducerTentativeParse::MessageSend:
805 case LambdaIntroducerTentativeParse::Invalid:
806 // Not a lambda-introducer, might be a message send.
807 TPA.Revert();
808 return ExprEmpty();
809 }
810 }
811
812 return ParseLambdaExpressionAfterIntroducer(Intro);
813}
814
815/// Parse a lambda introducer.
816/// \param Intro A LambdaIntroducer filled in with information about the
817/// contents of the lambda-introducer.
818/// \param Tentative If non-null, we are disambiguating between a
819/// lambda-introducer and some other construct. In this mode, we do not
820/// produce any diagnostics or take any other irreversible action unless
821/// we're sure that this is a lambda-expression.
822/// \return \c true if parsing (or disambiguation) failed with a diagnostic and
823/// the caller should bail out / recover.
824bool Parser::ParseLambdaIntroducer(LambdaIntroducer &Intro,
825 LambdaIntroducerTentativeParse *Tentative) {
826 if (Tentative)
827 *Tentative = LambdaIntroducerTentativeParse::Success;
828
829 assert(Tok.is(tok::l_square) && "Lambda expressions begin with '['.")((Tok.is(tok::l_square) && "Lambda expressions begin with '['."
) ? static_cast<void> (0) : __assert_fail ("Tok.is(tok::l_square) && \"Lambda expressions begin with '['.\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Parse/ParseExprCXX.cpp"
, 829, __PRETTY_FUNCTION__))
;
830 BalancedDelimiterTracker T(*this, tok::l_square);
831 T.consumeOpen();
832
833 Intro.Range.setBegin(T.getOpenLocation());
834
835 bool First = true;
836
837 // Produce a diagnostic if we're not tentatively parsing; otherwise track
838 // that our parse has failed.
839 auto Invalid = [&](llvm::function_ref<void()> Action) {
840 if (Tentative) {
841 *Tentative = LambdaIntroducerTentativeParse::Invalid;
842 return false;
843 }
844 Action();
845 return true;
846 };
847
848 // Perform some irreversible action if this is a non-tentative parse;
849 // otherwise note that our actions were incomplete.
850 auto NonTentativeAction = [&](llvm::function_ref<void()> Action) {
851 if (Tentative)
852 *Tentative = LambdaIntroducerTentativeParse::Incomplete;
853 else
854 Action();
855 };
856
857 // Parse capture-default.
858 if (Tok.is(tok::amp) &&
859 (NextToken().is(tok::comma) || NextToken().is(tok::r_square))) {
860 Intro.Default = LCD_ByRef;
861 Intro.DefaultLoc = ConsumeToken();
862 First = false;
863 if (!Tok.getIdentifierInfo()) {
864 // This can only be a lambda; no need for tentative parsing any more.
865 // '[[and]]' can still be an attribute, though.
866 Tentative = nullptr;
867 }
868 } else if (Tok.is(tok::equal)) {
869 Intro.Default = LCD_ByCopy;
870 Intro.DefaultLoc = ConsumeToken();
871 First = false;
872 Tentative = nullptr;
873 }
874
875 while (Tok.isNot(tok::r_square)) {
876 if (!First) {
877 if (Tok.isNot(tok::comma)) {
878 // Provide a completion for a lambda introducer here. Except
879 // in Objective-C, where this is Almost Surely meant to be a message
880 // send. In that case, fail here and let the ObjC message
881 // expression parser perform the completion.
882 if (Tok.is(tok::code_completion) &&
883 !(getLangOpts().ObjC && Tentative)) {
884 cutOffParsing();
885 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
886 /*AfterAmpersand=*/false);
887 break;
888 }
889
890 return Invalid([&] {
891 Diag(Tok.getLocation(), diag::err_expected_comma_or_rsquare);
892 });
893 }
894 ConsumeToken();
895 }
896
897 if (Tok.is(tok::code_completion)) {
898 cutOffParsing();
899 // If we're in Objective-C++ and we have a bare '[', then this is more
900 // likely to be a message receiver.
901 if (getLangOpts().ObjC && Tentative && First)
902 Actions.CodeCompleteObjCMessageReceiver(getCurScope());
903 else
904 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
905 /*AfterAmpersand=*/false);
906 break;
907 }
908
909 First = false;
910
911 // Parse capture.
912 LambdaCaptureKind Kind = LCK_ByCopy;
913 LambdaCaptureInitKind InitKind = LambdaCaptureInitKind::NoInit;
914 SourceLocation Loc;
915 IdentifierInfo *Id = nullptr;
916 SourceLocation EllipsisLocs[4];
917 ExprResult Init;
918 SourceLocation LocStart = Tok.getLocation();
919
920 if (Tok.is(tok::star)) {
921 Loc = ConsumeToken();
922 if (Tok.is(tok::kw_this)) {
923 ConsumeToken();
924 Kind = LCK_StarThis;
925 } else {
926 return Invalid([&] {
927 Diag(Tok.getLocation(), diag::err_expected_star_this_capture);
928 });
929 }
930 } else if (Tok.is(tok::kw_this)) {
931 Kind = LCK_This;
932 Loc = ConsumeToken();
933 } else if (Tok.isOneOf(tok::amp, tok::equal) &&
934 NextToken().isOneOf(tok::comma, tok::r_square) &&
935 Intro.Default == LCD_None) {
936 // We have a lone "&" or "=" which is either a misplaced capture-default
937 // or the start of a capture (in the "&" case) with the rest of the
938 // capture missing. Both are an error but a misplaced capture-default
939 // is more likely if we don't already have a capture default.
940 return Invalid(
941 [&] { Diag(Tok.getLocation(), diag::err_capture_default_first); });
942 } else {
943 TryConsumeToken(tok::ellipsis, EllipsisLocs[0]);
944
945 if (Tok.is(tok::amp)) {
946 Kind = LCK_ByRef;
947 ConsumeToken();
948
949 if (Tok.is(tok::code_completion)) {
950 cutOffParsing();
951 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
952 /*AfterAmpersand=*/true);
953 break;
954 }
955 }
956
957 TryConsumeToken(tok::ellipsis, EllipsisLocs[1]);
958
959 if (Tok.is(tok::identifier)) {
960 Id = Tok.getIdentifierInfo();
961 Loc = ConsumeToken();
962 } else if (Tok.is(tok::kw_this)) {
963 return Invalid([&] {
964 // FIXME: Suggest a fixit here.
965 Diag(Tok.getLocation(), diag::err_this_captured_by_reference);
966 });
967 } else {
968 return Invalid([&] {
969 Diag(Tok.getLocation(), diag::err_expected_capture);
970 });
971 }
972
973 TryConsumeToken(tok::ellipsis, EllipsisLocs[2]);
974
975 if (Tok.is(tok::l_paren)) {
976 BalancedDelimiterTracker Parens(*this, tok::l_paren);
977 Parens.consumeOpen();
978
979 InitKind = LambdaCaptureInitKind::DirectInit;
980
981 ExprVector Exprs;
982 CommaLocsTy Commas;
983 if (Tentative) {
984 Parens.skipToEnd();
985 *Tentative = LambdaIntroducerTentativeParse::Incomplete;
986 } else if (ParseExpressionList(Exprs, Commas)) {
987 Parens.skipToEnd();
988 Init = ExprError();
989 } else {
990 Parens.consumeClose();
991 Init = Actions.ActOnParenListExpr(Parens.getOpenLocation(),
992 Parens.getCloseLocation(),
993 Exprs);
994 }
995 } else if (Tok.isOneOf(tok::l_brace, tok::equal)) {
996 // Each lambda init-capture forms its own full expression, which clears
997 // Actions.MaybeODRUseExprs. So create an expression evaluation context
998 // to save the necessary state, and restore it later.
999 EnterExpressionEvaluationContext EC(
1000 Actions, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
1001
1002 if (TryConsumeToken(tok::equal))
1003 InitKind = LambdaCaptureInitKind::CopyInit;
1004 else
1005 InitKind = LambdaCaptureInitKind::ListInit;
1006
1007 if (!Tentative) {
1008 Init = ParseInitializer();
1009 } else if (Tok.is(tok::l_brace)) {
1010 BalancedDelimiterTracker Braces(*this, tok::l_brace);
1011 Braces.consumeOpen();
1012 Braces.skipToEnd();
1013 *Tentative = LambdaIntroducerTentativeParse::Incomplete;
1014 } else {
1015 // We're disambiguating this:
1016 //
1017 // [..., x = expr
1018 //
1019 // We need to find the end of the following expression in order to
1020 // determine whether this is an Obj-C message send's receiver, a
1021 // C99 designator, or a lambda init-capture.
1022 //
1023 // Parse the expression to find where it ends, and annotate it back
1024 // onto the tokens. We would have parsed this expression the same way
1025 // in either case: both the RHS of an init-capture and the RHS of an
1026 // assignment expression are parsed as an initializer-clause, and in
1027 // neither case can anything be added to the scope between the '[' and
1028 // here.
1029 //
1030 // FIXME: This is horrible. Adding a mechanism to skip an expression
1031 // would be much cleaner.
1032 // FIXME: If there is a ',' before the next ']' or ':', we can skip to
1033 // that instead. (And if we see a ':' with no matching '?', we can
1034 // classify this as an Obj-C message send.)
1035 SourceLocation StartLoc = Tok.getLocation();
1036 InMessageExpressionRAIIObject MaybeInMessageExpression(*this, true);
1037 Init = ParseInitializer();
1038 if (!Init.isInvalid())
1039 Init = Actions.CorrectDelayedTyposInExpr(Init.get());
1040
1041 if (Tok.getLocation() != StartLoc) {
1042 // Back out the lexing of the token after the initializer.
1043 PP.RevertCachedTokens(1);
1044
1045 // Replace the consumed tokens with an appropriate annotation.
1046 Tok.setLocation(StartLoc);
1047 Tok.setKind(tok::annot_primary_expr);
1048 setExprAnnotation(Tok, Init);
1049 Tok.setAnnotationEndLoc(PP.getLastCachedTokenLocation());
1050 PP.AnnotateCachedTokens(Tok);
1051
1052 // Consume the annotated initializer.
1053 ConsumeAnnotationToken();
1054 }
1055 }
1056 }
1057
1058 TryConsumeToken(tok::ellipsis, EllipsisLocs[3]);
1059 }
1060
1061 // Check if this is a message send before we act on a possible init-capture.
1062 if (Tentative && Tok.is(tok::identifier) &&
1063 NextToken().isOneOf(tok::colon, tok::r_square)) {
1064 // This can only be a message send. We're done with disambiguation.
1065 *Tentative = LambdaIntroducerTentativeParse::MessageSend;
1066 return false;
1067 }
1068
1069 // Ensure that any ellipsis was in the right place.
1070 SourceLocation EllipsisLoc;
1071 if (std::any_of(std::begin(EllipsisLocs), std::end(EllipsisLocs),
1072 [](SourceLocation Loc) { return Loc.isValid(); })) {
1073 // The '...' should appear before the identifier in an init-capture, and
1074 // after the identifier otherwise.
1075 bool InitCapture = InitKind != LambdaCaptureInitKind::NoInit;
1076 SourceLocation *ExpectedEllipsisLoc =
1077 !InitCapture ? &EllipsisLocs[2] :
1078 Kind == LCK_ByRef ? &EllipsisLocs[1] :
1079 &EllipsisLocs[0];
1080 EllipsisLoc = *ExpectedEllipsisLoc;
1081
1082 unsigned DiagID = 0;
1083 if (EllipsisLoc.isInvalid()) {
1084 DiagID = diag::err_lambda_capture_misplaced_ellipsis;
1085 for (SourceLocation Loc : EllipsisLocs) {
1086 if (Loc.isValid())
1087 EllipsisLoc = Loc;
1088 }
1089 } else {
1090 unsigned NumEllipses = std::accumulate(
1091 std::begin(EllipsisLocs), std::end(EllipsisLocs), 0,
1092 [](int N, SourceLocation Loc) { return N + Loc.isValid(); });
1093 if (NumEllipses > 1)
1094 DiagID = diag::err_lambda_capture_multiple_ellipses;
1095 }
1096 if (DiagID) {
1097 NonTentativeAction([&] {
1098 // Point the diagnostic at the first misplaced ellipsis.
1099 SourceLocation DiagLoc;
1100 for (SourceLocation &Loc : EllipsisLocs) {
1101 if (&Loc != ExpectedEllipsisLoc && Loc.isValid()) {
1102 DiagLoc = Loc;
1103 break;
1104 }
1105 }
1106 assert(DiagLoc.isValid() && "no location for diagnostic")((DiagLoc.isValid() && "no location for diagnostic") ?
static_cast<void> (0) : __assert_fail ("DiagLoc.isValid() && \"no location for diagnostic\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Parse/ParseExprCXX.cpp"
, 1106, __PRETTY_FUNCTION__))
;
1107
1108 // Issue the diagnostic and produce fixits showing where the ellipsis
1109 // should have been written.
1110 auto &&D = Diag(DiagLoc, DiagID);
1111 if (DiagID == diag::err_lambda_capture_misplaced_ellipsis) {
1112 SourceLocation ExpectedLoc =
1113 InitCapture ? Loc
1114 : Lexer::getLocForEndOfToken(
1115 Loc, 0, PP.getSourceManager(), getLangOpts());
1116 D << InitCapture << FixItHint::CreateInsertion(ExpectedLoc, "...");
1117 }
1118 for (SourceLocation &Loc : EllipsisLocs) {
1119 if (&Loc != ExpectedEllipsisLoc && Loc.isValid())
1120 D << FixItHint::CreateRemoval(Loc);
1121 }
1122 });
1123 }
1124 }
1125
1126 // Process the init-capture initializers now rather than delaying until we
1127 // form the lambda-expression so that they can be handled in the context
1128 // enclosing the lambda-expression, rather than in the context of the
1129 // lambda-expression itself.
1130 ParsedType InitCaptureType;
1131 if (Init.isUsable())
1132 Init = Actions.CorrectDelayedTyposInExpr(Init.get());
1133 if (Init.isUsable()) {
1134 NonTentativeAction([&] {
1135 // Get the pointer and store it in an lvalue, so we can use it as an
1136 // out argument.
1137 Expr *InitExpr = Init.get();
1138 // This performs any lvalue-to-rvalue conversions if necessary, which
1139 // can affect what gets captured in the containing decl-context.
1140 InitCaptureType = Actions.actOnLambdaInitCaptureInitialization(
1141 Loc, Kind == LCK_ByRef, EllipsisLoc, Id, InitKind, InitExpr);
1142 Init = InitExpr;
1143 });
1144 }
1145
1146 SourceLocation LocEnd = PrevTokLocation;
1147
1148 Intro.addCapture(Kind, Loc, Id, EllipsisLoc, InitKind, Init,
1149 InitCaptureType, SourceRange(LocStart, LocEnd));
1150 }
1151
1152 T.consumeClose();
1153 Intro.Range.setEnd(T.getCloseLocation());
1154 return false;
1155}
1156
1157static void tryConsumeLambdaSpecifierToken(Parser &P,
1158 SourceLocation &MutableLoc,
1159 SourceLocation &ConstexprLoc,
1160 SourceLocation &ConstevalLoc,
1161 SourceLocation &DeclEndLoc) {
1162 assert(MutableLoc.isInvalid())((MutableLoc.isInvalid()) ? static_cast<void> (0) : __assert_fail
("MutableLoc.isInvalid()", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Parse/ParseExprCXX.cpp"
, 1162, __PRETTY_FUNCTION__))
;
1163 assert(ConstexprLoc.isInvalid())((ConstexprLoc.isInvalid()) ? static_cast<void> (0) : __assert_fail
("ConstexprLoc.isInvalid()", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Parse/ParseExprCXX.cpp"
, 1163, __PRETTY_FUNCTION__))
;
1164 // Consume constexpr-opt mutable-opt in any sequence, and set the DeclEndLoc
1165 // to the final of those locations. Emit an error if we have multiple
1166 // copies of those keywords and recover.
1167
1168 while (true) {
1169 switch (P.getCurToken().getKind()) {
1170 case tok::kw_mutable: {
1171 if (MutableLoc.isValid()) {
1172 P.Diag(P.getCurToken().getLocation(),
1173 diag::err_lambda_decl_specifier_repeated)
1174 << 0 << FixItHint::CreateRemoval(P.getCurToken().getLocation());
1175 }
1176 MutableLoc = P.ConsumeToken();
1177 DeclEndLoc = MutableLoc;
1178 break /*switch*/;
1179 }
1180 case tok::kw_constexpr:
1181 if (ConstexprLoc.isValid()) {
1182 P.Diag(P.getCurToken().getLocation(),
1183 diag::err_lambda_decl_specifier_repeated)
1184 << 1 << FixItHint::CreateRemoval(P.getCurToken().getLocation());
1185 }
1186 ConstexprLoc = P.ConsumeToken();
1187 DeclEndLoc = ConstexprLoc;
1188 break /*switch*/;
1189 case tok::kw_consteval:
1190 if (ConstevalLoc.isValid()) {
1191 P.Diag(P.getCurToken().getLocation(),
1192 diag::err_lambda_decl_specifier_repeated)
1193 << 2 << FixItHint::CreateRemoval(P.getCurToken().getLocation());
1194 }
1195 ConstevalLoc = P.ConsumeToken();
1196 DeclEndLoc = ConstevalLoc;
1197 break /*switch*/;
1198 default:
1199 return;
1200 }
1201 }
1202}
1203
1204static void
1205addConstexprToLambdaDeclSpecifier(Parser &P, SourceLocation ConstexprLoc,
1206 DeclSpec &DS) {
1207 if (ConstexprLoc.isValid()) {
1208 P.Diag(ConstexprLoc, !P.getLangOpts().CPlusPlus17
1209 ? diag::ext_constexpr_on_lambda_cxx17
1210 : diag::warn_cxx14_compat_constexpr_on_lambda);
1211 const char *PrevSpec = nullptr;
1212 unsigned DiagID = 0;
1213 DS.SetConstexprSpec(ConstexprSpecKind::Constexpr, ConstexprLoc, PrevSpec,
1214 DiagID);
1215 assert(PrevSpec == nullptr && DiagID == 0 &&((PrevSpec == nullptr && DiagID == 0 && "Constexpr cannot have been set previously!"
) ? static_cast<void> (0) : __assert_fail ("PrevSpec == nullptr && DiagID == 0 && \"Constexpr cannot have been set previously!\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Parse/ParseExprCXX.cpp"
, 1216, __PRETTY_FUNCTION__))
1216 "Constexpr cannot have been set previously!")((PrevSpec == nullptr && DiagID == 0 && "Constexpr cannot have been set previously!"
) ? static_cast<void> (0) : __assert_fail ("PrevSpec == nullptr && DiagID == 0 && \"Constexpr cannot have been set previously!\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Parse/ParseExprCXX.cpp"
, 1216, __PRETTY_FUNCTION__))
;
1217 }
1218}
1219
1220static void addConstevalToLambdaDeclSpecifier(Parser &P,
1221 SourceLocation ConstevalLoc,
1222 DeclSpec &DS) {
1223 if (ConstevalLoc.isValid()) {
1224 P.Diag(ConstevalLoc, diag::warn_cxx20_compat_consteval);
1225 const char *PrevSpec = nullptr;
1226 unsigned DiagID = 0;
1227 DS.SetConstexprSpec(ConstexprSpecKind::Consteval, ConstevalLoc, PrevSpec,
1228 DiagID);
1229 if (DiagID != 0)
1230 P.Diag(ConstevalLoc, DiagID) << PrevSpec;
1231 }
1232}
1233
1234/// ParseLambdaExpressionAfterIntroducer - Parse the rest of a lambda
1235/// expression.
1236ExprResult Parser::ParseLambdaExpressionAfterIntroducer(
1237 LambdaIntroducer &Intro) {
1238 SourceLocation LambdaBeginLoc = Intro.Range.getBegin();
1239 Diag(LambdaBeginLoc, diag::warn_cxx98_compat_lambda);
1240
1241 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), LambdaBeginLoc,
1242 "lambda expression parsing");
1243
1244
1245
1246 // FIXME: Call into Actions to add any init-capture declarations to the
1247 // scope while parsing the lambda-declarator and compound-statement.
1248
1249 // Parse lambda-declarator[opt].
1250 DeclSpec DS(AttrFactory);
1251 Declarator D(DS, DeclaratorContext::LambdaExpr);
1252 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1253 Actions.PushLambdaScope();
1254
1255 ParsedAttributes Attr(AttrFactory);
1256 if (getLangOpts().CUDA) {
1257 // In CUDA code, GNU attributes are allowed to appear immediately after the
1258 // "[...]", even if there is no "(...)" before the lambda body.
1259 MaybeParseGNUAttributes(D);
1260 }
1261
1262 // Helper to emit a warning if we see a CUDA host/device/global attribute
1263 // after '(...)'. nvcc doesn't accept this.
1264 auto WarnIfHasCUDATargetAttr = [&] {
1265 if (getLangOpts().CUDA)
1266 for (const ParsedAttr &A : Attr)
1267 if (A.getKind() == ParsedAttr::AT_CUDADevice ||
1268 A.getKind() == ParsedAttr::AT_CUDAHost ||
1269 A.getKind() == ParsedAttr::AT_CUDAGlobal)
1270 Diag(A.getLoc(), diag::warn_cuda_attr_lambda_position)
1271 << A.getAttrName()->getName();
1272 };
1273
1274 MultiParseScope TemplateParamScope(*this);
1275 if (Tok.is(tok::less)) {
1276 Diag(Tok, getLangOpts().CPlusPlus20
1277 ? diag::warn_cxx17_compat_lambda_template_parameter_list
1278 : diag::ext_lambda_template_parameter_list);
1279
1280 SmallVector<NamedDecl*, 4> TemplateParams;
1281 SourceLocation LAngleLoc, RAngleLoc;
1282 if (ParseTemplateParameters(TemplateParamScope,
1283 CurTemplateDepthTracker.getDepth(),
1284 TemplateParams, LAngleLoc, RAngleLoc)) {
1285 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1286 return ExprError();
1287 }
1288
1289 if (TemplateParams.empty()) {
1290 Diag(RAngleLoc,
1291 diag::err_lambda_template_parameter_list_empty);
1292 } else {
1293 ExprResult RequiresClause;
1294 if (TryConsumeToken(tok::kw_requires)) {
1295 RequiresClause =
1296 Actions.ActOnRequiresClause(ParseConstraintLogicalOrExpression(
1297 /*IsTrailingRequiresClause=*/false));
1298 if (RequiresClause.isInvalid())
1299 SkipUntil({tok::l_brace, tok::l_paren}, StopAtSemi | StopBeforeMatch);
1300 }
1301
1302 Actions.ActOnLambdaExplicitTemplateParameterList(
1303 LAngleLoc, TemplateParams, RAngleLoc, RequiresClause);
1304 ++CurTemplateDepthTracker;
1305 }
1306 }
1307
1308 // Implement WG21 P2173, which allows attributes immediately before the
1309 // lambda declarator and applies them to the corresponding function operator
1310 // or operator template declaration. We accept this as a conforming extension
1311 // in all language modes that support lambdas.
1312 if (isCXX11AttributeSpecifier()) {
1313 Diag(Tok, getLangOpts().CPlusPlus2b
1314 ? diag::warn_cxx20_compat_decl_attrs_on_lambda
1315 : diag::ext_decl_attrs_on_lambda);
1316 MaybeParseCXX11Attributes(D);
1317 }
1318
1319 TypeResult TrailingReturnType;
1320 SourceLocation TrailingReturnTypeLoc;
1321
1322 auto ParseLambdaSpecifiers =
1323 [&](SourceLocation LParenLoc, SourceLocation RParenLoc,
1324 MutableArrayRef<DeclaratorChunk::ParamInfo> ParamInfo,
1325 SourceLocation EllipsisLoc) {
1326 SourceLocation DeclEndLoc = RParenLoc;
1327
1328 // GNU-style attributes must be parsed before the mutable specifier to
1329 // be compatible with GCC. MSVC-style attributes must be parsed before
1330 // the mutable specifier to be compatible with MSVC.
1331 MaybeParseAttributes(PAKM_GNU | PAKM_Declspec, Attr);
1332
1333 // Parse mutable-opt and/or constexpr-opt or consteval-opt, and update
1334 // the DeclEndLoc.
1335 SourceLocation MutableLoc;
1336 SourceLocation ConstexprLoc;
1337 SourceLocation ConstevalLoc;
1338 tryConsumeLambdaSpecifierToken(*this, MutableLoc, ConstexprLoc,
1339 ConstevalLoc, DeclEndLoc);
1340
1341 addConstexprToLambdaDeclSpecifier(*this, ConstexprLoc, DS);
1342 addConstevalToLambdaDeclSpecifier(*this, ConstevalLoc, DS);
1343 // Parse exception-specification[opt].
1344 ExceptionSpecificationType ESpecType = EST_None;
1345 SourceRange ESpecRange;
1346 SmallVector<ParsedType, 2> DynamicExceptions;
1347 SmallVector<SourceRange, 2> DynamicExceptionRanges;
1348 ExprResult NoexceptExpr;
1349 CachedTokens *ExceptionSpecTokens;
1350 ESpecType = tryParseExceptionSpecification(
1351 /*Delayed=*/false, ESpecRange, DynamicExceptions,
1352 DynamicExceptionRanges, NoexceptExpr, ExceptionSpecTokens);
1353
1354 if (ESpecType != EST_None)
1355 DeclEndLoc = ESpecRange.getEnd();
1356
1357 // Parse attribute-specifier[opt].
1358 MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
1359
1360 // Parse OpenCL addr space attribute.
1361 if (Tok.isOneOf(tok::kw___private, tok::kw___global, tok::kw___local,
1362 tok::kw___constant, tok::kw___generic)) {
1363 ParseOpenCLQualifiers(DS.getAttributes());
1364 ConsumeToken();
1365 }
1366
1367 SourceLocation FunLocalRangeEnd = DeclEndLoc;
1368
1369 // Parse trailing-return-type[opt].
1370 if (Tok.is(tok::arrow)) {
1371 FunLocalRangeEnd = Tok.getLocation();
1372 SourceRange Range;
1373 TrailingReturnType = ParseTrailingReturnType(
1374 Range, /*MayBeFollowedByDirectInit*/ false);
1375 TrailingReturnTypeLoc = Range.getBegin();
1376 if (Range.getEnd().isValid())
1377 DeclEndLoc = Range.getEnd();
1378 }
1379
1380 SourceLocation NoLoc;
1381 D.AddTypeInfo(
1382 DeclaratorChunk::getFunction(
1383 /*HasProto=*/true,
1384 /*IsAmbiguous=*/false, LParenLoc, ParamInfo.data(),
1385 ParamInfo.size(), EllipsisLoc, RParenLoc,
1386 /*RefQualifierIsLvalueRef=*/true,
1387 /*RefQualifierLoc=*/NoLoc, MutableLoc, ESpecType, ESpecRange,
1388 DynamicExceptions.data(), DynamicExceptionRanges.data(),
1389 DynamicExceptions.size(),
1390 NoexceptExpr.isUsable() ? NoexceptExpr.get() : nullptr,
1391 /*ExceptionSpecTokens*/ nullptr,
1392 /*DeclsInPrototype=*/None, LParenLoc, FunLocalRangeEnd, D,
1393 TrailingReturnType, TrailingReturnTypeLoc, &DS),
1394 std::move(Attr), DeclEndLoc);
1395 };
1396
1397 if (Tok.is(tok::l_paren)) {
1398 ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
1399 Scope::FunctionDeclarationScope |
1400 Scope::DeclScope);
1401
1402 BalancedDelimiterTracker T(*this, tok::l_paren);
1403 T.consumeOpen();
1404 SourceLocation LParenLoc = T.getOpenLocation();
1405
1406 // Parse parameter-declaration-clause.
1407 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
1408 SourceLocation EllipsisLoc;
1409
1410 if (Tok.isNot(tok::r_paren)) {
1411 Actions.RecordParsingTemplateParameterDepth(
1412 CurTemplateDepthTracker.getOriginalDepth());
1413
1414 ParseParameterDeclarationClause(D.getContext(), Attr, ParamInfo,
1415 EllipsisLoc);
1416 // For a generic lambda, each 'auto' within the parameter declaration
1417 // clause creates a template type parameter, so increment the depth.
1418 // If we've parsed any explicit template parameters, then the depth will
1419 // have already been incremented. So we make sure that at most a single
1420 // depth level is added.
1421 if (Actions.getCurGenericLambda())
1422 CurTemplateDepthTracker.setAddedDepth(1);
1423 }
1424
1425 T.consumeClose();
1426
1427 // Parse lambda-specifiers.
1428 ParseLambdaSpecifiers(LParenLoc, /*DeclEndLoc=*/T.getCloseLocation(),
1429 ParamInfo, EllipsisLoc);
1430
1431 // Parse requires-clause[opt].
1432 if (Tok.is(tok::kw_requires))
1433 ParseTrailingRequiresClause(D);
1434 } else if (Tok.isOneOf(tok::kw_mutable, tok::arrow, tok::kw___attribute,
1435 tok::kw_constexpr, tok::kw_consteval,
1436 tok::kw___private, tok::kw___global, tok::kw___local,
1437 tok::kw___constant, tok::kw___generic,
1438 tok::kw_requires, tok::kw_noexcept) ||
1439 (Tok.is(tok::l_square) && NextToken().is(tok::l_square))) {
1440 if (!getLangOpts().CPlusPlus2b)
1441 // It's common to forget that one needs '()' before 'mutable', an
1442 // attribute specifier, the result type, or the requires clause. Deal with
1443 // this.
1444 Diag(Tok, diag::ext_lambda_missing_parens)
1445 << FixItHint::CreateInsertion(Tok.getLocation(), "() ");
1446
1447 SourceLocation NoLoc;
1448 // Parse lambda-specifiers.
1449 std::vector<DeclaratorChunk::ParamInfo> EmptyParamInfo;
1450 ParseLambdaSpecifiers(/*LParenLoc=*/NoLoc, /*RParenLoc=*/NoLoc,
1451 EmptyParamInfo, /*EllipsisLoc=*/NoLoc);
1452 }
1453
1454 WarnIfHasCUDATargetAttr();
1455
1456 // FIXME: Rename BlockScope -> ClosureScope if we decide to continue using
1457 // it.
1458 unsigned ScopeFlags = Scope::BlockScope | Scope::FnScope | Scope::DeclScope |
1459 Scope::CompoundStmtScope;
1460 ParseScope BodyScope(this, ScopeFlags);
1461
1462 Actions.ActOnStartOfLambdaDefinition(Intro, D, getCurScope());
1463
1464 // Parse compound-statement.
1465 if (!Tok.is(tok::l_brace)) {
1466 Diag(Tok, diag::err_expected_lambda_body);
1467 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1468 return ExprError();
1469 }
1470
1471 StmtResult Stmt(ParseCompoundStatementBody());
1472 BodyScope.Exit();
1473 TemplateParamScope.Exit();
1474
1475 if (!Stmt.isInvalid() && !TrailingReturnType.isInvalid())
1476 return Actions.ActOnLambdaExpr(LambdaBeginLoc, Stmt.get(), getCurScope());
1477
1478 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1479 return ExprError();
1480}
1481
1482/// ParseCXXCasts - This handles the various ways to cast expressions to another
1483/// type.
1484///
1485/// postfix-expression: [C++ 5.2p1]
1486/// 'dynamic_cast' '<' type-name '>' '(' expression ')'
1487/// 'static_cast' '<' type-name '>' '(' expression ')'
1488/// 'reinterpret_cast' '<' type-name '>' '(' expression ')'
1489/// 'const_cast' '<' type-name '>' '(' expression ')'
1490///
1491/// C++ for OpenCL s2.3.1 adds:
1492/// 'addrspace_cast' '<' type-name '>' '(' expression ')'
1493ExprResult Parser::ParseCXXCasts() {
1494 tok::TokenKind Kind = Tok.getKind();
1495 const char *CastName = nullptr; // For error messages
1496
1497 switch (Kind) {
1498 default: llvm_unreachable("Unknown C++ cast!")::llvm::llvm_unreachable_internal("Unknown C++ cast!", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Parse/ParseExprCXX.cpp"
, 1498)
;
1499 case tok::kw_addrspace_cast: CastName = "addrspace_cast"; break;
1500 case tok::kw_const_cast: CastName = "const_cast"; break;
1501 case tok::kw_dynamic_cast: CastName = "dynamic_cast"; break;
1502 case tok::kw_reinterpret_cast: CastName = "reinterpret_cast"; break;
1503 case tok::kw_static_cast: CastName = "static_cast"; break;
1504 }
1505
1506 SourceLocation OpLoc = ConsumeToken();
1507 SourceLocation LAngleBracketLoc = Tok.getLocation();
1508
1509 // Check for "<::" which is parsed as "[:". If found, fix token stream,
1510 // diagnose error, suggest fix, and recover parsing.
1511 if (Tok.is(tok::l_square) && Tok.getLength() == 2) {
1512 Token Next = NextToken();
1513 if (Next.is(tok::colon) && areTokensAdjacent(Tok, Next))
1514 FixDigraph(*this, PP, Tok, Next, Kind, /*AtDigraph*/true);
1515 }
1516
1517 if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName))
1518 return ExprError();
1519
1520 // Parse the common declaration-specifiers piece.
1521 DeclSpec DS(AttrFactory);
1522 ParseSpecifierQualifierList(DS);
1523
1524 // Parse the abstract-declarator, if present.
1525 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeName);
1526 ParseDeclarator(DeclaratorInfo);
1527
1528 SourceLocation RAngleBracketLoc = Tok.getLocation();
1529
1530 if (ExpectAndConsume(tok::greater))
1531 return ExprError(Diag(LAngleBracketLoc, diag::note_matching) << tok::less);
1532
1533 BalancedDelimiterTracker T(*this, tok::l_paren);
1534
1535 if (T.expectAndConsume(diag::err_expected_lparen_after, CastName))
1536 return ExprError();
1537
1538 ExprResult Result = ParseExpression();
1539
1540 // Match the ')'.
1541 T.consumeClose();
1542
1543 if (!Result.isInvalid() && !DeclaratorInfo.isInvalidType())
1544 Result = Actions.ActOnCXXNamedCast(OpLoc, Kind,
1545 LAngleBracketLoc, DeclaratorInfo,
1546 RAngleBracketLoc,
1547 T.getOpenLocation(), Result.get(),
1548 T.getCloseLocation());
1549
1550 return Result;
1551}
1552
1553/// ParseCXXTypeid - This handles the C++ typeid expression.
1554///
1555/// postfix-expression: [C++ 5.2p1]
1556/// 'typeid' '(' expression ')'
1557/// 'typeid' '(' type-id ')'
1558///
1559ExprResult Parser::ParseCXXTypeid() {
1560 assert(Tok.is(tok::kw_typeid) && "Not 'typeid'!")((Tok.is(tok::kw_typeid) && "Not 'typeid'!") ? static_cast
<void> (0) : __assert_fail ("Tok.is(tok::kw_typeid) && \"Not 'typeid'!\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Parse/ParseExprCXX.cpp"
, 1560, __PRETTY_FUNCTION__))
;
1561
1562 SourceLocation OpLoc = ConsumeToken();
1563 SourceLocation LParenLoc, RParenLoc;
1564 BalancedDelimiterTracker T(*this, tok::l_paren);
1565
1566 // typeid expressions are always parenthesized.
1567 if (T.expectAndConsume(diag::err_expected_lparen_after, "typeid"))
1568 return ExprError();
1569 LParenLoc = T.getOpenLocation();
1570
1571 ExprResult Result;
1572
1573 // C++0x [expr.typeid]p3:
1574 // When typeid is applied to an expression other than an lvalue of a
1575 // polymorphic class type [...] The expression is an unevaluated
1576 // operand (Clause 5).
1577 //
1578 // Note that we can't tell whether the expression is an lvalue of a
1579 // polymorphic class type until after we've parsed the expression; we
1580 // speculatively assume the subexpression is unevaluated, and fix it up
1581 // later.
1582 //
1583 // We enter the unevaluated context before trying to determine whether we
1584 // have a type-id, because the tentative parse logic will try to resolve
1585 // names, and must treat them as unevaluated.
1586 EnterExpressionEvaluationContext Unevaluated(
1587 Actions, Sema::ExpressionEvaluationContext::Unevaluated,
1588 Sema::ReuseLambdaContextDecl);
1589
1590 if (isTypeIdInParens()) {
1591 TypeResult Ty = ParseTypeName();
1592
1593 // Match the ')'.
1594 T.consumeClose();
1595 RParenLoc = T.getCloseLocation();
1596 if (Ty.isInvalid() || RParenLoc.isInvalid())
1597 return ExprError();
1598
1599 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/true,
1600 Ty.get().getAsOpaquePtr(), RParenLoc);
1601 } else {
1602 Result = ParseExpression();
1603
1604 // Match the ')'.
1605 if (Result.isInvalid())
1606 SkipUntil(tok::r_paren, StopAtSemi);
1607 else {
1608 T.consumeClose();
1609 RParenLoc = T.getCloseLocation();
1610 if (RParenLoc.isInvalid())
1611 return ExprError();
1612
1613 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/false,
1614 Result.get(), RParenLoc);
1615 }
1616 }
1617
1618 return Result;
1619}
1620
1621/// ParseCXXUuidof - This handles the Microsoft C++ __uuidof expression.
1622///
1623/// '__uuidof' '(' expression ')'
1624/// '__uuidof' '(' type-id ')'
1625///
1626ExprResult Parser::ParseCXXUuidof() {
1627 assert(Tok.is(tok::kw___uuidof) && "Not '__uuidof'!")((Tok.is(tok::kw___uuidof) && "Not '__uuidof'!") ? static_cast
<void> (0) : __assert_fail ("Tok.is(tok::kw___uuidof) && \"Not '__uuidof'!\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Parse/ParseExprCXX.cpp"
, 1627, __PRETTY_FUNCTION__))
;
1628
1629 SourceLocation OpLoc = ConsumeToken();
1630 BalancedDelimiterTracker T(*this, tok::l_paren);
1631
1632 // __uuidof expressions are always parenthesized.
1633 if (T.expectAndConsume(diag::err_expected_lparen_after, "__uuidof"))
1634 return ExprError();
1635
1636 ExprResult Result;
1637
1638 if (isTypeIdInParens()) {
1639 TypeResult Ty = ParseTypeName();
1640
1641 // Match the ')'.
1642 T.consumeClose();
1643
1644 if (Ty.isInvalid())
1645 return ExprError();
1646
1647 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(), /*isType=*/true,
1648 Ty.get().getAsOpaquePtr(),
1649 T.getCloseLocation());
1650 } else {
1651 EnterExpressionEvaluationContext Unevaluated(
1652 Actions, Sema::ExpressionEvaluationContext::Unevaluated);
1653 Result = ParseExpression();
1654
1655 // Match the ')'.
1656 if (Result.isInvalid())
1657 SkipUntil(tok::r_paren, StopAtSemi);
1658 else {
1659 T.consumeClose();
1660
1661 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(),
1662 /*isType=*/false,
1663 Result.get(), T.getCloseLocation());
1664 }
1665 }
1666
1667 return Result;
1668}
1669
1670/// Parse a C++ pseudo-destructor expression after the base,
1671/// . or -> operator, and nested-name-specifier have already been
1672/// parsed. We're handling this fragment of the grammar:
1673///
1674/// postfix-expression: [C++2a expr.post]
1675/// postfix-expression . template[opt] id-expression
1676/// postfix-expression -> template[opt] id-expression
1677///
1678/// id-expression:
1679/// qualified-id
1680/// unqualified-id
1681///
1682/// qualified-id:
1683/// nested-name-specifier template[opt] unqualified-id
1684///
1685/// nested-name-specifier:
1686/// type-name ::
1687/// decltype-specifier :: FIXME: not implemented, but probably only
1688/// allowed in C++ grammar by accident
1689/// nested-name-specifier identifier ::
1690/// nested-name-specifier template[opt] simple-template-id ::
1691/// [...]
1692///
1693/// unqualified-id:
1694/// ~ type-name
1695/// ~ decltype-specifier
1696/// [...]
1697///
1698/// ... where the all but the last component of the nested-name-specifier
1699/// has already been parsed, and the base expression is not of a non-dependent
1700/// class type.
1701ExprResult
1702Parser::ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc,
1703 tok::TokenKind OpKind,
1704 CXXScopeSpec &SS,
1705 ParsedType ObjectType) {
1706 // If the last component of the (optional) nested-name-specifier is
1707 // template[opt] simple-template-id, it has already been annotated.
1708 UnqualifiedId FirstTypeName;
1709 SourceLocation CCLoc;
1710 if (Tok.is(tok::identifier)) {
1711 FirstTypeName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1712 ConsumeToken();
1713 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail")((Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail"
) ? static_cast<void> (0) : __assert_fail ("Tok.is(tok::coloncolon) &&\"ParseOptionalCXXScopeSpecifier fail\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Parse/ParseExprCXX.cpp"
, 1713, __PRETTY_FUNCTION__))
;
1714 CCLoc = ConsumeToken();
1715 } else if (Tok.is(tok::annot_template_id)) {
1716 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1717 // FIXME: Carry on and build an AST representation for tooling.
1718 if (TemplateId->isInvalid())
1719 return ExprError();
1720 FirstTypeName.setTemplateId(TemplateId);
1721 ConsumeAnnotationToken();
1722 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail")((Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail"
) ? static_cast<void> (0) : __assert_fail ("Tok.is(tok::coloncolon) &&\"ParseOptionalCXXScopeSpecifier fail\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Parse/ParseExprCXX.cpp"
, 1722, __PRETTY_FUNCTION__))
;
1723 CCLoc = ConsumeToken();
1724 } else {
1725 assert(SS.isEmpty() && "missing last component of nested name specifier")((SS.isEmpty() && "missing last component of nested name specifier"
) ? static_cast<void> (0) : __assert_fail ("SS.isEmpty() && \"missing last component of nested name specifier\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Parse/ParseExprCXX.cpp"
, 1725, __PRETTY_FUNCTION__))
;
1726 FirstTypeName.setIdentifier(nullptr, SourceLocation());
1727 }
1728
1729 // Parse the tilde.
1730 assert(Tok.is(tok::tilde) && "ParseOptionalCXXScopeSpecifier fail")((Tok.is(tok::tilde) && "ParseOptionalCXXScopeSpecifier fail"
) ? static_cast<void> (0) : __assert_fail ("Tok.is(tok::tilde) && \"ParseOptionalCXXScopeSpecifier fail\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Parse/ParseExprCXX.cpp"
, 1730, __PRETTY_FUNCTION__))
;
1731 SourceLocation TildeLoc = ConsumeToken();
1732
1733 if (Tok.is(tok::kw_decltype) && !FirstTypeName.isValid()) {
1734 DeclSpec DS(AttrFactory);
1735 ParseDecltypeSpecifier(DS);
1736 if (DS.getTypeSpecType() == TST_error)
1737 return ExprError();
1738 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
1739 TildeLoc, DS);
1740 }
1741
1742 if (!Tok.is(tok::identifier)) {
1743 Diag(Tok, diag::err_destructor_tilde_identifier);
1744 return ExprError();
1745 }
1746
1747 // Parse the second type.
1748 UnqualifiedId SecondTypeName;
1749 IdentifierInfo *Name = Tok.getIdentifierInfo();
1750 SourceLocation NameLoc = ConsumeToken();
1751 SecondTypeName.setIdentifier(Name, NameLoc);
1752
1753 // If there is a '<', the second type name is a template-id. Parse
1754 // it as such.
1755 //
1756 // FIXME: This is not a context in which a '<' is assumed to start a template
1757 // argument list. This affects examples such as
1758 // void f(auto *p) { p->~X<int>(); }
1759 // ... but there's no ambiguity, and nowhere to write 'template' in such an
1760 // example, so we accept it anyway.
1761 if (Tok.is(tok::less) &&
1762 ParseUnqualifiedIdTemplateId(
1763 SS, ObjectType, Base && Base->containsErrors(), SourceLocation(),
1764 Name, NameLoc, false, SecondTypeName,
1765 /*AssumeTemplateId=*/true))
1766 return ExprError();
1767
1768 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
1769 SS, FirstTypeName, CCLoc, TildeLoc,
1770 SecondTypeName);
1771}
1772
1773/// ParseCXXBoolLiteral - This handles the C++ Boolean literals.
1774///
1775/// boolean-literal: [C++ 2.13.5]
1776/// 'true'
1777/// 'false'
1778ExprResult Parser::ParseCXXBoolLiteral() {
1779 tok::TokenKind Kind = Tok.getKind();
1780 return Actions.ActOnCXXBoolLiteral(ConsumeToken(), Kind);
1781}
1782
1783/// ParseThrowExpression - This handles the C++ throw expression.
1784///
1785/// throw-expression: [C++ 15]
1786/// 'throw' assignment-expression[opt]
1787ExprResult Parser::ParseThrowExpression() {
1788 assert(Tok.is(tok::kw_throw) && "Not throw!")((Tok.is(tok::kw_throw) && "Not throw!") ? static_cast
<void> (0) : __assert_fail ("Tok.is(tok::kw_throw) && \"Not throw!\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Parse/ParseExprCXX.cpp"
, 1788, __PRETTY_FUNCTION__))
;
1789 SourceLocation ThrowLoc = ConsumeToken(); // Eat the throw token.
1790
1791 // If the current token isn't the start of an assignment-expression,
1792 // then the expression is not present. This handles things like:
1793 // "C ? throw : (void)42", which is crazy but legal.
1794 switch (Tok.getKind()) { // FIXME: move this predicate somewhere common.
1795 case tok::semi:
1796 case tok::r_paren:
1797 case tok::r_square:
1798 case tok::r_brace:
1799 case tok::colon:
1800 case tok::comma:
1801 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, nullptr);
1802
1803 default:
1804 ExprResult Expr(ParseAssignmentExpression());
1805 if (Expr.isInvalid()) return Expr;
1806 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, Expr.get());
1807 }
1808}
1809
1810/// Parse the C++ Coroutines co_yield expression.
1811///
1812/// co_yield-expression:
1813/// 'co_yield' assignment-expression[opt]
1814ExprResult Parser::ParseCoyieldExpression() {
1815 assert(Tok.is(tok::kw_co_yield) && "Not co_yield!")((Tok.is(tok::kw_co_yield) && "Not co_yield!") ? static_cast
<void> (0) : __assert_fail ("Tok.is(tok::kw_co_yield) && \"Not co_yield!\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Parse/ParseExprCXX.cpp"
, 1815, __PRETTY_FUNCTION__))
;
1816
1817 SourceLocation Loc = ConsumeToken();
1818 ExprResult Expr = Tok.is(tok::l_brace) ? ParseBraceInitializer()
1819 : ParseAssignmentExpression();
1820 if (!Expr.isInvalid())
1821 Expr = Actions.ActOnCoyieldExpr(getCurScope(), Loc, Expr.get());
1822 return Expr;
1823}
1824
1825/// ParseCXXThis - This handles the C++ 'this' pointer.
1826///
1827/// C++ 9.3.2: In the body of a non-static member function, the keyword this is
1828/// a non-lvalue expression whose value is the address of the object for which
1829/// the function is called.
1830ExprResult Parser::ParseCXXThis() {
1831 assert(Tok.is(tok::kw_this) && "Not 'this'!")((Tok.is(tok::kw_this) && "Not 'this'!") ? static_cast
<void> (0) : __assert_fail ("Tok.is(tok::kw_this) && \"Not 'this'!\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Parse/ParseExprCXX.cpp"
, 1831, __PRETTY_FUNCTION__))
;
1832 SourceLocation ThisLoc = ConsumeToken();
1833 return Actions.ActOnCXXThis(ThisLoc);
1834}
1835
1836/// ParseCXXTypeConstructExpression - Parse construction of a specified type.
1837/// Can be interpreted either as function-style casting ("int(x)")
1838/// or class type construction ("ClassType(x,y,z)")
1839/// or creation of a value-initialized type ("int()").
1840/// See [C++ 5.2.3].
1841///
1842/// postfix-expression: [C++ 5.2p1]
1843/// simple-type-specifier '(' expression-list[opt] ')'
1844/// [C++0x] simple-type-specifier braced-init-list
1845/// typename-specifier '(' expression-list[opt] ')'
1846/// [C++0x] typename-specifier braced-init-list
1847///
1848/// In C++1z onwards, the type specifier can also be a template-name.
1849ExprResult
1850Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) {
1851 Declarator DeclaratorInfo(DS, DeclaratorContext::FunctionalCast);
1852 ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
1853
1854 assert((Tok.is(tok::l_paren) ||(((Tok.is(tok::l_paren) || (getLangOpts().CPlusPlus11 &&
Tok.is(tok::l_brace))) && "Expected '(' or '{'!") ? static_cast
<void> (0) : __assert_fail ("(Tok.is(tok::l_paren) || (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace))) && \"Expected '(' or '{'!\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Parse/ParseExprCXX.cpp"
, 1856, __PRETTY_FUNCTION__))
1855 (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)))(((Tok.is(tok::l_paren) || (getLangOpts().CPlusPlus11 &&
Tok.is(tok::l_brace))) && "Expected '(' or '{'!") ? static_cast
<void> (0) : __assert_fail ("(Tok.is(tok::l_paren) || (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace))) && \"Expected '(' or '{'!\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Parse/ParseExprCXX.cpp"
, 1856, __PRETTY_FUNCTION__))
1856 && "Expected '(' or '{'!")(((Tok.is(tok::l_paren) || (getLangOpts().CPlusPlus11 &&
Tok.is(tok::l_brace))) && "Expected '(' or '{'!") ? static_cast
<void> (0) : __assert_fail ("(Tok.is(tok::l_paren) || (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace))) && \"Expected '(' or '{'!\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Parse/ParseExprCXX.cpp"
, 1856, __PRETTY_FUNCTION__))
;
1857
1858 if (Tok.is(tok::l_brace)) {
1859 PreferredType.enterTypeCast(Tok.getLocation(), TypeRep.get());
1860 ExprResult Init = ParseBraceInitializer();
1861 if (Init.isInvalid())
1862 return Init;
1863 Expr *InitList = Init.get();
1864 return Actions.ActOnCXXTypeConstructExpr(
1865 TypeRep, InitList->getBeginLoc(), MultiExprArg(&InitList, 1),
1866 InitList->getEndLoc(), /*ListInitialization=*/true);
1867 } else {
1868 BalancedDelimiterTracker T(*this, tok::l_paren);
1869 T.consumeOpen();
1870
1871 PreferredType.enterTypeCast(Tok.getLocation(), TypeRep.get());
1872
1873 ExprVector Exprs;
1874 CommaLocsTy CommaLocs;
1875
1876 auto RunSignatureHelp = [&]() {
1877 QualType PreferredType;
1878 if (TypeRep)
1879 PreferredType = Actions.ProduceConstructorSignatureHelp(
1880 getCurScope(), TypeRep.get()->getCanonicalTypeInternal(),
1881 DS.getEndLoc(), Exprs, T.getOpenLocation());
1882 CalledSignatureHelp = true;
1883 return PreferredType;
1884 };
1885
1886 if (Tok.isNot(tok::r_paren)) {
1887 if (ParseExpressionList(Exprs, CommaLocs, [&] {
1888 PreferredType.enterFunctionArgument(Tok.getLocation(),
1889 RunSignatureHelp);
1890 })) {
1891 if (PP.isCodeCompletionReached() && !CalledSignatureHelp)
1892 RunSignatureHelp();
1893 SkipUntil(tok::r_paren, StopAtSemi);
1894 return ExprError();
1895 }
1896 }
1897
1898 // Match the ')'.
1899 T.consumeClose();
1900
1901 // TypeRep could be null, if it references an invalid typedef.
1902 if (!TypeRep)
1903 return ExprError();
1904
1905 assert((Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&&(((Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&&
"Unexpected number of commas!") ? static_cast<void> (0
) : __assert_fail ("(Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&& \"Unexpected number of commas!\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Parse/ParseExprCXX.cpp"
, 1906, __PRETTY_FUNCTION__))
1906 "Unexpected number of commas!")(((Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&&
"Unexpected number of commas!") ? static_cast<void> (0
) : __assert_fail ("(Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&& \"Unexpected number of commas!\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Parse/ParseExprCXX.cpp"
, 1906, __PRETTY_FUNCTION__))
;
1907 return Actions.ActOnCXXTypeConstructExpr(TypeRep, T.getOpenLocation(),
1908 Exprs, T.getCloseLocation(),
1909 /*ListInitialization=*/false);
1910 }
1911}
1912
1913/// ParseCXXCondition - if/switch/while condition expression.
1914///
1915/// condition:
1916/// expression
1917/// type-specifier-seq declarator '=' assignment-expression
1918/// [C++11] type-specifier-seq declarator '=' initializer-clause
1919/// [C++11] type-specifier-seq declarator braced-init-list
1920/// [Clang] type-specifier-seq ref-qualifier[opt] '[' identifier-list ']'
1921/// brace-or-equal-initializer
1922/// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
1923/// '=' assignment-expression
1924///
1925/// In C++1z, a condition may in some contexts be preceded by an
1926/// optional init-statement. This function will parse that too.
1927///
1928/// \param InitStmt If non-null, an init-statement is permitted, and if present
1929/// will be parsed and stored here.
1930///
1931/// \param Loc The location of the start of the statement that requires this
1932/// condition, e.g., the "for" in a for loop.
1933///
1934/// \param FRI If non-null, a for range declaration is permitted, and if
1935/// present will be parsed and stored here, and a null result will be returned.
1936///
1937/// \param EnterForConditionScope If true, enter a continue/break scope at the
1938/// appropriate moment for a 'for' loop.
1939///
1940/// \returns The parsed condition.
1941Sema::ConditionResult Parser::ParseCXXCondition(StmtResult *InitStmt,
1942 SourceLocation Loc,
1943 Sema::ConditionKind CK,
1944 ForRangeInfo *FRI,
1945 bool EnterForConditionScope) {
1946 // Helper to ensure we always enter a continue/break scope if requested.
1947 struct ForConditionScopeRAII {
1948 Scope *S;
1949 void enter(bool IsConditionVariable) {
1950 if (S) {
1951 S->AddFlags(Scope::BreakScope | Scope::ContinueScope);
1952 S->setIsConditionVarScope(IsConditionVariable);
1953 }
1954 }
1955 ~ForConditionScopeRAII() {
1956 if (S)
1957 S->setIsConditionVarScope(false);
1958 }
1959 } ForConditionScope{EnterForConditionScope
6.1
'EnterForConditionScope' is false
6.1
'EnterForConditionScope' is false
? getCurScope() : nullptr};
1
Assuming 'EnterForConditionScope' is false
2
'?' condition is false
7
'?' condition is false
1960
1961 ParenBraceBracketBalancer BalancerRAIIObj(*this);
1962 PreferredType.enterCondition(Actions, Tok.getLocation());
1963
1964 if (Tok.is(tok::code_completion)) {
3
Taking false branch
8
Calling 'Token::is'
11
Returning from 'Token::is'
12
Taking false branch
1965 cutOffParsing();
1966 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Condition);
1967 return Sema::ConditionError();
1968 }
1969
1970 ParsedAttributesWithRange attrs(AttrFactory);
1971 MaybeParseCXX11Attributes(attrs);
1972
1973 const auto WarnOnInit = [this, &CK] {
1974 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
1975 ? diag::warn_cxx14_compat_init_statement
1976 : diag::ext_init_statement)
1977 << (CK == Sema::ConditionKind::Switch);
1978 };
1979
1980 // Determine what kind of thing we have.
1981 switch (isCXXConditionDeclarationOrInitStatement(InitStmt, FRI)) {
4
Control jumps to 'case InitStmtDecl:' at line 2018
13
Control jumps to 'case InitStmtDecl:' at line 2018
1982 case ConditionOrInitStatement::Expression: {
1983 // If this is a for loop, we're entering its condition.
1984 ForConditionScope.enter(/*IsConditionVariable=*/false);
1985
1986 ProhibitAttributes(attrs);
1987
1988 // We can have an empty expression here.
1989 // if (; true);
1990 if (InitStmt && Tok.is(tok::semi)) {
1991 WarnOnInit();
1992 SourceLocation SemiLoc = Tok.getLocation();
1993 if (!Tok.hasLeadingEmptyMacro() && !SemiLoc.isMacroID()) {
1994 Diag(SemiLoc, diag::warn_empty_init_statement)
1995 << (CK == Sema::ConditionKind::Switch)
1996 << FixItHint::CreateRemoval(SemiLoc);
1997 }
1998 ConsumeToken();
1999 *InitStmt = Actions.ActOnNullStmt(SemiLoc);
2000 return ParseCXXCondition(nullptr, Loc, CK);
2001 }
2002
2003 // Parse the expression.
2004 ExprResult Expr = ParseExpression(); // expression
2005 if (Expr.isInvalid())
2006 return Sema::ConditionError();
2007
2008 if (InitStmt && Tok.is(tok::semi)) {
2009 WarnOnInit();
2010 *InitStmt = Actions.ActOnExprStmt(Expr.get());
2011 ConsumeToken();
2012 return ParseCXXCondition(nullptr, Loc, CK);
2013 }
2014
2015 return Actions.ActOnCondition(getCurScope(), Loc, Expr.get(), CK);
2016 }
2017
2018 case ConditionOrInitStatement::InitStmtDecl: {
2019 WarnOnInit();
2020 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
2021 DeclGroupPtrTy DG = ParseSimpleDeclaration(
2022 DeclaratorContext::SelectionInit, DeclEnd, attrs, /*RequireSemi=*/true);
2023 *InitStmt = Actions.ActOnDeclStmt(DG, DeclStart, DeclEnd);
14
Called C++ object pointer is null
2024 return ParseCXXCondition(nullptr, Loc, CK);
5
Passing null pointer value via 1st parameter 'InitStmt'
6
Calling 'Parser::ParseCXXCondition'
2025 }
2026
2027 case ConditionOrInitStatement::ForRangeDecl: {
2028 // This is 'for (init-stmt; for-range-decl : range-expr)'.
2029 // We're not actually in a for loop yet, so 'break' and 'continue' aren't
2030 // permitted here.
2031 assert(FRI && "should not parse a for range declaration here")((FRI && "should not parse a for range declaration here"
) ? static_cast<void> (0) : __assert_fail ("FRI && \"should not parse a for range declaration here\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Parse/ParseExprCXX.cpp"
, 2031, __PRETTY_FUNCTION__))
;
2032 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
2033 DeclGroupPtrTy DG = ParseSimpleDeclaration(DeclaratorContext::ForInit,
2034 DeclEnd, attrs, false, FRI);
2035 FRI->LoopVar = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
2036 return Sema::ConditionResult();
2037 }
2038
2039 case ConditionOrInitStatement::ConditionDecl:
2040 case ConditionOrInitStatement::Error:
2041 break;
2042 }
2043
2044 // If this is a for loop, we're entering its condition.
2045 ForConditionScope.enter(/*IsConditionVariable=*/true);
2046
2047 // type-specifier-seq
2048 DeclSpec DS(AttrFactory);
2049 DS.takeAttributesFrom(attrs);
2050 ParseSpecifierQualifierList(DS, AS_none, DeclSpecContext::DSC_condition);
2051
2052 // declarator
2053 Declarator DeclaratorInfo(DS, DeclaratorContext::Condition);
2054 ParseDeclarator(DeclaratorInfo);
2055
2056 // simple-asm-expr[opt]
2057 if (Tok.is(tok::kw_asm)) {
2058 SourceLocation Loc;
2059 ExprResult AsmLabel(ParseSimpleAsm(/*ForAsmLabel*/ true, &Loc));
2060 if (AsmLabel.isInvalid()) {
2061 SkipUntil(tok::semi, StopAtSemi);
2062 return Sema::ConditionError();
2063 }
2064 DeclaratorInfo.setAsmLabel(AsmLabel.get());
2065 DeclaratorInfo.SetRangeEnd(Loc);
2066 }
2067
2068 // If attributes are present, parse them.
2069 MaybeParseGNUAttributes(DeclaratorInfo);
2070
2071 // Type-check the declaration itself.
2072 DeclResult Dcl = Actions.ActOnCXXConditionDeclaration(getCurScope(),
2073 DeclaratorInfo);
2074 if (Dcl.isInvalid())
2075 return Sema::ConditionError();
2076 Decl *DeclOut = Dcl.get();
2077
2078 // '=' assignment-expression
2079 // If a '==' or '+=' is found, suggest a fixit to '='.
2080 bool CopyInitialization = isTokenEqualOrEqualTypo();
2081 if (CopyInitialization)
2082 ConsumeToken();
2083
2084 ExprResult InitExpr = ExprError();
2085 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
2086 Diag(Tok.getLocation(),
2087 diag::warn_cxx98_compat_generalized_initializer_lists);
2088 InitExpr = ParseBraceInitializer();
2089 } else if (CopyInitialization) {
2090 PreferredType.enterVariableInit(Tok.getLocation(), DeclOut);
2091 InitExpr = ParseAssignmentExpression();
2092 } else if (Tok.is(tok::l_paren)) {
2093 // This was probably an attempt to initialize the variable.
2094 SourceLocation LParen = ConsumeParen(), RParen = LParen;
2095 if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch))
2096 RParen = ConsumeParen();
2097 Diag(DeclOut->getLocation(),
2098 diag::err_expected_init_in_condition_lparen)
2099 << SourceRange(LParen, RParen);
2100 } else {
2101 Diag(DeclOut->getLocation(), diag::err_expected_init_in_condition);
2102 }
2103
2104 if (!InitExpr.isInvalid())
2105 Actions.AddInitializerToDecl(DeclOut, InitExpr.get(), !CopyInitialization);
2106 else
2107 Actions.ActOnInitializerError(DeclOut);
2108
2109 Actions.FinalizeDeclaration(DeclOut);
2110 return Actions.ActOnConditionVariable(DeclOut, Loc, CK);
2111}
2112
2113/// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
2114/// This should only be called when the current token is known to be part of
2115/// simple-type-specifier.
2116///
2117/// simple-type-specifier:
2118/// '::'[opt] nested-name-specifier[opt] type-name
2119/// '::'[opt] nested-name-specifier 'template' simple-template-id [TODO]
2120/// char
2121/// wchar_t
2122/// bool
2123/// short
2124/// int
2125/// long
2126/// signed
2127/// unsigned
2128/// float
2129/// double
2130/// void
2131/// [GNU] typeof-specifier
2132/// [C++0x] auto [TODO]
2133///
2134/// type-name:
2135/// class-name
2136/// enum-name
2137/// typedef-name
2138///
2139void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) {
2140 DS.SetRangeStart(Tok.getLocation());
2141 const char *PrevSpec;
2142 unsigned DiagID;
2143 SourceLocation Loc = Tok.getLocation();
2144 const clang::PrintingPolicy &Policy =
2145 Actions.getASTContext().getPrintingPolicy();
2146
2147 switch (Tok.getKind()) {
2148 case tok::identifier: // foo::bar
2149 case tok::coloncolon: // ::foo::bar
2150 llvm_unreachable("Annotation token should already be formed!")::llvm::llvm_unreachable_internal("Annotation token should already be formed!"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Parse/ParseExprCXX.cpp"
, 2150)
;
2151 default:
2152 llvm_unreachable("Not a simple-type-specifier token!")::llvm::llvm_unreachable_internal("Not a simple-type-specifier token!"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Parse/ParseExprCXX.cpp"
, 2152)
;
2153
2154 // type-name
2155 case tok::annot_typename: {
2156 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID,
2157 getTypeAnnotation(Tok), Policy);
2158 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
2159 ConsumeAnnotationToken();
2160
2161 DS.Finish(Actions, Policy);
2162 return;
2163 }
2164
2165 case tok::kw__ExtInt: {
2166 ExprResult ER = ParseExtIntegerArgument();
2167 if (ER.isInvalid())
2168 DS.SetTypeSpecError();
2169 else
2170 DS.SetExtIntType(Loc, ER.get(), PrevSpec, DiagID, Policy);
2171
2172 // Do this here because we have already consumed the close paren.
2173 DS.SetRangeEnd(PrevTokLocation);
2174 DS.Finish(Actions, Policy);
2175 return;
2176 }
2177
2178 // builtin types
2179 case tok::kw_short:
2180 DS.SetTypeSpecWidth(TypeSpecifierWidth::Short, Loc, PrevSpec, DiagID,
2181 Policy);
2182 break;
2183 case tok::kw_long:
2184 DS.SetTypeSpecWidth(TypeSpecifierWidth::Long, Loc, PrevSpec, DiagID,
2185 Policy);
2186 break;
2187 case tok::kw___int64:
2188 DS.SetTypeSpecWidth(TypeSpecifierWidth::LongLong, Loc, PrevSpec, DiagID,
2189 Policy);
2190 break;
2191 case tok::kw_signed:
2192 DS.SetTypeSpecSign(TypeSpecifierSign::Signed, Loc, PrevSpec, DiagID);
2193 break;
2194 case tok::kw_unsigned:
2195 DS.SetTypeSpecSign(TypeSpecifierSign::Unsigned, Loc, PrevSpec, DiagID);
2196 break;
2197 case tok::kw_void:
2198 DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID, Policy);
2199 break;
2200 case tok::kw_char:
2201 DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID, Policy);
2202 break;
2203 case tok::kw_int:
2204 DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID, Policy);
2205 break;
2206 case tok::kw___int128:
2207 DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec, DiagID, Policy);
2208 break;
2209 case tok::kw___bf16:
2210 DS.SetTypeSpecType(DeclSpec::TST_BFloat16, Loc, PrevSpec, DiagID, Policy);
2211 break;
2212 case tok::kw_half:
2213 DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, DiagID, Policy);
2214 break;
2215 case tok::kw_float:
2216 DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID, Policy);
2217 break;
2218 case tok::kw_double:
2219 DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID, Policy);
2220 break;
2221 case tok::kw__Float16:
2222 DS.SetTypeSpecType(DeclSpec::TST_float16, Loc, PrevSpec, DiagID, Policy);
2223 break;
2224 case tok::kw___float128:
2225 DS.SetTypeSpecType(DeclSpec::TST_float128, Loc, PrevSpec, DiagID, Policy);
2226 break;
2227 case tok::kw_wchar_t:
2228 DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID, Policy);
2229 break;
2230 case tok::kw_char8_t:
2231 DS.SetTypeSpecType(DeclSpec::TST_char8, Loc, PrevSpec, DiagID, Policy);
2232 break;
2233 case tok::kw_char16_t:
2234 DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID, Policy);
2235 break;
2236 case tok::kw_char32_t:
2237 DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID, Policy);
2238 break;
2239 case tok::kw_bool:
2240 DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID, Policy);
2241 break;
2242#define GENERIC_IMAGE_TYPE(ImgType, Id) \
2243 case tok::kw_##ImgType##_t: \
2244 DS.SetTypeSpecType(DeclSpec::TST_##ImgType##_t, Loc, PrevSpec, DiagID, \
2245 Policy); \
2246 break;
2247#include "clang/Basic/OpenCLImageTypes.def"
2248
2249 case tok::annot_decltype:
2250 case tok::kw_decltype:
2251 DS.SetRangeEnd(ParseDecltypeSpecifier(DS));
2252 return DS.Finish(Actions, Policy);
2253
2254 // GNU typeof support.
2255 case tok::kw_typeof:
2256 ParseTypeofSpecifier(DS);
2257 DS.Finish(Actions, Policy);
2258 return;
2259 }
2260 ConsumeAnyToken();
2261 DS.SetRangeEnd(PrevTokLocation);
2262 DS.Finish(Actions, Policy);
2263}
2264
2265/// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++
2266/// [dcl.name]), which is a non-empty sequence of type-specifiers,
2267/// e.g., "const short int". Note that the DeclSpec is *not* finished
2268/// by parsing the type-specifier-seq, because these sequences are
2269/// typically followed by some form of declarator. Returns true and
2270/// emits diagnostics if this is not a type-specifier-seq, false
2271/// otherwise.
2272///
2273/// type-specifier-seq: [C++ 8.1]
2274/// type-specifier type-specifier-seq[opt]
2275///
2276bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) {
2277 ParseSpecifierQualifierList(DS, AS_none, DeclSpecContext::DSC_type_specifier);
2278 DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy());
2279 return false;
2280}
2281
2282/// Finish parsing a C++ unqualified-id that is a template-id of
2283/// some form.
2284///
2285/// This routine is invoked when a '<' is encountered after an identifier or
2286/// operator-function-id is parsed by \c ParseUnqualifiedId() to determine
2287/// whether the unqualified-id is actually a template-id. This routine will
2288/// then parse the template arguments and form the appropriate template-id to
2289/// return to the caller.
2290///
2291/// \param SS the nested-name-specifier that precedes this template-id, if
2292/// we're actually parsing a qualified-id.
2293///
2294/// \param ObjectType if this unqualified-id occurs within a member access
2295/// expression, the type of the base object whose member is being accessed.
2296///
2297/// \param ObjectHadErrors this unqualified-id occurs within a member access
2298/// expression, indicates whether the original subexpressions had any errors.
2299///
2300/// \param Name for constructor and destructor names, this is the actual
2301/// identifier that may be a template-name.
2302///
2303/// \param NameLoc the location of the class-name in a constructor or
2304/// destructor.
2305///
2306/// \param EnteringContext whether we're entering the scope of the
2307/// nested-name-specifier.
2308///
2309/// \param Id as input, describes the template-name or operator-function-id
2310/// that precedes the '<'. If template arguments were parsed successfully,
2311/// will be updated with the template-id.
2312///
2313/// \param AssumeTemplateId When true, this routine will assume that the name
2314/// refers to a template without performing name lookup to verify.
2315///
2316/// \returns true if a parse error occurred, false otherwise.
2317bool Parser::ParseUnqualifiedIdTemplateId(
2318 CXXScopeSpec &SS, ParsedType ObjectType, bool ObjectHadErrors,
2319 SourceLocation TemplateKWLoc, IdentifierInfo *Name, SourceLocation NameLoc,
2320 bool EnteringContext, UnqualifiedId &Id, bool AssumeTemplateId) {
2321 assert(Tok.is(tok::less) && "Expected '<' to finish parsing a template-id")((Tok.is(tok::less) && "Expected '<' to finish parsing a template-id"
) ? static_cast<void> (0) : __assert_fail ("Tok.is(tok::less) && \"Expected '<' to finish parsing a template-id\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Parse/ParseExprCXX.cpp"
, 2321, __PRETTY_FUNCTION__))
;
2322
2323 TemplateTy Template;
2324 TemplateNameKind TNK = TNK_Non_template;
2325 switch (Id.getKind()) {
2326 case UnqualifiedIdKind::IK_Identifier:
2327 case UnqualifiedIdKind::IK_OperatorFunctionId:
2328 case UnqualifiedIdKind::IK_LiteralOperatorId:
2329 if (AssumeTemplateId) {
2330 // We defer the injected-class-name checks until we've found whether
2331 // this template-id is used to form a nested-name-specifier or not.
2332 TNK = Actions.ActOnTemplateName(getCurScope(), SS, TemplateKWLoc, Id,
2333 ObjectType, EnteringContext, Template,
2334 /*AllowInjectedClassName*/ true);
2335 } else {
2336 bool MemberOfUnknownSpecialization;
2337 TNK = Actions.isTemplateName(getCurScope(), SS,
2338 TemplateKWLoc.isValid(), Id,
2339 ObjectType, EnteringContext, Template,
2340 MemberOfUnknownSpecialization);
2341 // If lookup found nothing but we're assuming that this is a template
2342 // name, double-check that makes sense syntactically before committing
2343 // to it.
2344 if (TNK == TNK_Undeclared_template &&
2345 isTemplateArgumentList(0) == TPResult::False)
2346 return false;
2347
2348 if (TNK == TNK_Non_template && MemberOfUnknownSpecialization &&
2349 ObjectType && isTemplateArgumentList(0) == TPResult::True) {
2350 // If we had errors before, ObjectType can be dependent even without any
2351 // templates, do not report missing template keyword in that case.
2352 if (!ObjectHadErrors) {
2353 // We have something like t->getAs<T>(), where getAs is a
2354 // member of an unknown specialization. However, this will only
2355 // parse correctly as a template, so suggest the keyword 'template'
2356 // before 'getAs' and treat this as a dependent template name.
2357 std::string Name;
2358 if (Id.getKind() == UnqualifiedIdKind::IK_Identifier)
2359 Name = std::string(Id.Identifier->getName());
2360 else {
2361 Name = "operator ";
2362 if (Id.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId)
2363 Name += getOperatorSpelling(Id.OperatorFunctionId.Operator);
2364 else
2365 Name += Id.Identifier->getName();
2366 }
2367 Diag(Id.StartLocation, diag::err_missing_dependent_template_keyword)
2368 << Name
2369 << FixItHint::CreateInsertion(Id.StartLocation, "template ");
2370 }
2371 TNK = Actions.ActOnTemplateName(
2372 getCurScope(), SS, TemplateKWLoc, Id, ObjectType, EnteringContext,
2373 Template, /*AllowInjectedClassName*/ true);
2374 } else if (TNK == TNK_Non_template) {
2375 return false;
2376 }
2377 }
2378 break;
2379
2380 case UnqualifiedIdKind::IK_ConstructorName: {
2381 UnqualifiedId TemplateName;
2382 bool MemberOfUnknownSpecialization;
2383 TemplateName.setIdentifier(Name, NameLoc);
2384 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
2385 TemplateName, ObjectType,
2386 EnteringContext, Template,
2387 MemberOfUnknownSpecialization);
2388 if (TNK == TNK_Non_template)
2389 return false;
2390 break;
2391 }
2392
2393 case UnqualifiedIdKind::IK_DestructorName: {
2394 UnqualifiedId TemplateName;
2395 bool MemberOfUnknownSpecialization;
2396 TemplateName.setIdentifier(Name, NameLoc);
2397 if (ObjectType) {
2398 TNK = Actions.ActOnTemplateName(
2399 getCurScope(), SS, TemplateKWLoc, TemplateName, ObjectType,
2400 EnteringContext, Template, /*AllowInjectedClassName*/ true);
2401 } else {
2402 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
2403 TemplateName, ObjectType,
2404 EnteringContext, Template,
2405 MemberOfUnknownSpecialization);
2406
2407 if (TNK == TNK_Non_template && !Id.DestructorName.get()) {
2408 Diag(NameLoc, diag::err_destructor_template_id)
2409 << Name << SS.getRange();
2410 // Carry on to parse the template arguments before bailing out.
2411 }
2412 }
2413 break;
2414 }
2415
2416 default:
2417 return false;
2418 }
2419
2420 // Parse the enclosed template argument list.
2421 SourceLocation LAngleLoc, RAngleLoc;
2422 TemplateArgList TemplateArgs;
2423 if (ParseTemplateIdAfterTemplateName(true, LAngleLoc, TemplateArgs,
2424 RAngleLoc))
2425 return true;
2426
2427 // If this is a non-template, we already issued a diagnostic.
2428 if (TNK == TNK_Non_template)
2429 return true;
2430
2431 if (Id.getKind() == UnqualifiedIdKind::IK_Identifier ||
2432 Id.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId ||
2433 Id.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId) {
2434 // Form a parsed representation of the template-id to be stored in the
2435 // UnqualifiedId.
2436
2437 // FIXME: Store name for literal operator too.
2438 IdentifierInfo *TemplateII =
2439 Id.getKind() == UnqualifiedIdKind::IK_Identifier ? Id.Identifier
2440 : nullptr;
2441 OverloadedOperatorKind OpKind =
2442 Id.getKind() == UnqualifiedIdKind::IK_Identifier
2443 ? OO_None
2444 : Id.OperatorFunctionId.Operator;
2445
2446 TemplateIdAnnotation *TemplateId = TemplateIdAnnotation::Create(
2447 TemplateKWLoc, Id.StartLocation, TemplateII, OpKind, Template, TNK,
2448 LAngleLoc, RAngleLoc, TemplateArgs, /*ArgsInvalid*/false, TemplateIds);
2449
2450 Id.setTemplateId(TemplateId);
2451 return false;
2452 }
2453
2454 // Bundle the template arguments together.
2455 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
2456
2457 // Constructor and destructor names.
2458 TypeResult Type = Actions.ActOnTemplateIdType(
2459 getCurScope(), SS, TemplateKWLoc, Template, Name, NameLoc, LAngleLoc,
2460 TemplateArgsPtr, RAngleLoc, /*IsCtorOrDtorName=*/true);
2461 if (Type.isInvalid())
2462 return true;
2463
2464 if (Id.getKind() == UnqualifiedIdKind::IK_ConstructorName)
2465 Id.setConstructorName(Type.get(), NameLoc, RAngleLoc);
2466 else
2467 Id.setDestructorName(Id.StartLocation, Type.get(), RAngleLoc);
2468
2469 return false;
2470}
2471
2472/// Parse an operator-function-id or conversion-function-id as part
2473/// of a C++ unqualified-id.
2474///
2475/// This routine is responsible only for parsing the operator-function-id or
2476/// conversion-function-id; it does not handle template arguments in any way.
2477///
2478/// \code
2479/// operator-function-id: [C++ 13.5]
2480/// 'operator' operator
2481///
2482/// operator: one of
2483/// new delete new[] delete[]
2484/// + - * / % ^ & | ~
2485/// ! = < > += -= *= /= %=
2486/// ^= &= |= << >> >>= <<= == !=
2487/// <= >= && || ++ -- , ->* ->
2488/// () [] <=>
2489///
2490/// conversion-function-id: [C++ 12.3.2]
2491/// operator conversion-type-id
2492///
2493/// conversion-type-id:
2494/// type-specifier-seq conversion-declarator[opt]
2495///
2496/// conversion-declarator:
2497/// ptr-operator conversion-declarator[opt]
2498/// \endcode
2499///
2500/// \param SS The nested-name-specifier that preceded this unqualified-id. If
2501/// non-empty, then we are parsing the unqualified-id of a qualified-id.
2502///
2503/// \param EnteringContext whether we are entering the scope of the
2504/// nested-name-specifier.
2505///
2506/// \param ObjectType if this unqualified-id occurs within a member access
2507/// expression, the type of the base object whose member is being accessed.
2508///
2509/// \param Result on a successful parse, contains the parsed unqualified-id.
2510///
2511/// \returns true if parsing fails, false otherwise.
2512bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
2513 ParsedType ObjectType,
2514 UnqualifiedId &Result) {
2515 assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword")((Tok.is(tok::kw_operator) && "Expected 'operator' keyword"
) ? static_cast<void> (0) : __assert_fail ("Tok.is(tok::kw_operator) && \"Expected 'operator' keyword\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Parse/ParseExprCXX.cpp"
, 2515, __PRETTY_FUNCTION__))
;
2516
2517 // Consume the 'operator' keyword.
2518 SourceLocation KeywordLoc = ConsumeToken();
2519
2520 // Determine what kind of operator name we have.
2521 unsigned SymbolIdx = 0;
2522 SourceLocation SymbolLocations[3];
2523 OverloadedOperatorKind Op = OO_None;
2524 switch (Tok.getKind()) {
2525 case tok::kw_new:
2526 case tok::kw_delete: {
2527 bool isNew = Tok.getKind() == tok::kw_new;
2528 // Consume the 'new' or 'delete'.
2529 SymbolLocations[SymbolIdx++] = ConsumeToken();
2530 // Check for array new/delete.
2531 if (Tok.is(tok::l_square) &&
2532 (!getLangOpts().CPlusPlus11 || NextToken().isNot(tok::l_square))) {
2533 // Consume the '[' and ']'.
2534 BalancedDelimiterTracker T(*this, tok::l_square);
2535 T.consumeOpen();
2536 T.consumeClose();
2537 if (T.getCloseLocation().isInvalid())
2538 return true;
2539
2540 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2541 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2542 Op = isNew? OO_Array_New : OO_Array_Delete;
2543 } else {
2544 Op = isNew? OO_New : OO_Delete;
2545 }
2546 break;
2547 }
2548
2549#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2550 case tok::Token: \
2551 SymbolLocations[SymbolIdx++] = ConsumeToken(); \
2552 Op = OO_##Name; \
2553 break;
2554#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2555#include "clang/Basic/OperatorKinds.def"
2556
2557 case tok::l_paren: {
2558 // Consume the '(' and ')'.
2559 BalancedDelimiterTracker T(*this, tok::l_paren);
2560 T.consumeOpen();
2561 T.consumeClose();
2562 if (T.getCloseLocation().isInvalid())
2563 return true;
2564
2565 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2566 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2567 Op = OO_Call;
2568 break;
2569 }
2570
2571 case tok::l_square: {
2572 // Consume the '[' and ']'.
2573 BalancedDelimiterTracker T(*this, tok::l_square);
2574 T.consumeOpen();
2575 T.consumeClose();
2576 if (T.getCloseLocation().isInvalid())
2577 return true;
2578
2579 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2580 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2581 Op = OO_Subscript;
2582 break;
2583 }
2584
2585 case tok::code_completion: {
2586 // Don't try to parse any further.
2587 cutOffParsing();
2588 // Code completion for the operator name.
2589 Actions.CodeCompleteOperatorName(getCurScope());
2590 return true;
2591 }
2592
2593 default:
2594 break;
2595 }
2596
2597 if (Op != OO_None) {
2598 // We have parsed an operator-function-id.
2599 Result.setOperatorFunctionId(KeywordLoc, Op, SymbolLocations);
2600 return false;
2601 }
2602
2603 // Parse a literal-operator-id.
2604 //
2605 // literal-operator-id: C++11 [over.literal]
2606 // operator string-literal identifier
2607 // operator user-defined-string-literal
2608
2609 if (getLangOpts().CPlusPlus11 && isTokenStringLiteral()) {
2610 Diag(Tok.getLocation(), diag::warn_cxx98_compat_literal_operator);
2611
2612 SourceLocation DiagLoc;
2613 unsigned DiagId = 0;
2614
2615 // We're past translation phase 6, so perform string literal concatenation
2616 // before checking for "".
2617 SmallVector<Token, 4> Toks;
2618 SmallVector<SourceLocation, 4> TokLocs;
2619 while (isTokenStringLiteral()) {
2620 if (!Tok.is(tok::string_literal) && !DiagId) {
2621 // C++11 [over.literal]p1:
2622 // The string-literal or user-defined-string-literal in a
2623 // literal-operator-id shall have no encoding-prefix [...].
2624 DiagLoc = Tok.getLocation();
2625 DiagId = diag::err_literal_operator_string_prefix;
2626 }
2627 Toks.push_back(Tok);
2628 TokLocs.push_back(ConsumeStringToken());
2629 }
2630
2631 StringLiteralParser Literal(Toks, PP);
2632 if (Literal.hadError)
2633 return true;
2634
2635 // Grab the literal operator's suffix, which will be either the next token
2636 // or a ud-suffix from the string literal.
2637 IdentifierInfo *II = nullptr;
2638 SourceLocation SuffixLoc;
2639 if (!Literal.getUDSuffix().empty()) {
2640 II = &PP.getIdentifierTable().get(Literal.getUDSuffix());
2641 SuffixLoc =
2642 Lexer::AdvanceToTokenCharacter(TokLocs[Literal.getUDSuffixToken()],
2643 Literal.getUDSuffixOffset(),
2644 PP.getSourceManager(), getLangOpts());
2645 } else if (Tok.is(tok::identifier)) {
2646 II = Tok.getIdentifierInfo();
2647 SuffixLoc = ConsumeToken();
2648 TokLocs.push_back(SuffixLoc);
2649 } else {
2650 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
2651 return true;
2652 }
2653
2654 // The string literal must be empty.
2655 if (!Literal.GetString().empty() || Literal.Pascal) {
2656 // C++11 [over.literal]p1:
2657 // The string-literal or user-defined-string-literal in a
2658 // literal-operator-id shall [...] contain no characters
2659 // other than the implicit terminating '\0'.
2660 DiagLoc = TokLocs.front();
2661 DiagId = diag::err_literal_operator_string_not_empty;
2662 }
2663
2664 if (DiagId) {
2665 // This isn't a valid literal-operator-id, but we think we know
2666 // what the user meant. Tell them what they should have written.
2667 SmallString<32> Str;
2668 Str += "\"\"";
2669 Str += II->getName();
2670 Diag(DiagLoc, DiagId) << FixItHint::CreateReplacement(
2671 SourceRange(TokLocs.front(), TokLocs.back()), Str);
2672 }
2673
2674 Result.setLiteralOperatorId(II, KeywordLoc, SuffixLoc);
2675
2676 return Actions.checkLiteralOperatorId(SS, Result);
2677 }
2678
2679 // Parse a conversion-function-id.
2680 //
2681 // conversion-function-id: [C++ 12.3.2]
2682 // operator conversion-type-id
2683 //
2684 // conversion-type-id:
2685 // type-specifier-seq conversion-declarator[opt]
2686 //
2687 // conversion-declarator:
2688 // ptr-operator conversion-declarator[opt]
2689
2690 // Parse the type-specifier-seq.
2691 DeclSpec DS(AttrFactory);
2692 if (ParseCXXTypeSpecifierSeq(DS)) // FIXME: ObjectType?
2693 return true;
2694
2695 // Parse the conversion-declarator, which is merely a sequence of
2696 // ptr-operators.
2697 Declarator D(DS, DeclaratorContext::ConversionId);
2698 ParseDeclaratorInternal(D, /*DirectDeclParser=*/nullptr);
2699
2700 // Finish up the type.
2701 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), D);
2702 if (Ty.isInvalid())
2703 return true;
2704
2705 // Note that this is a conversion-function-id.
2706 Result.setConversionFunctionId(KeywordLoc, Ty.get(),
2707 D.getSourceRange().getEnd());
2708 return false;
2709}
2710
2711/// Parse a C++ unqualified-id (or a C identifier), which describes the
2712/// name of an entity.
2713///
2714/// \code
2715/// unqualified-id: [C++ expr.prim.general]
2716/// identifier
2717/// operator-function-id
2718/// conversion-function-id
2719/// [C++0x] literal-operator-id [TODO]
2720/// ~ class-name
2721/// template-id
2722///
2723/// \endcode
2724///
2725/// \param SS The nested-name-specifier that preceded this unqualified-id. If
2726/// non-empty, then we are parsing the unqualified-id of a qualified-id.
2727///
2728/// \param ObjectType if this unqualified-id occurs within a member access
2729/// expression, the type of the base object whose member is being accessed.
2730///
2731/// \param ObjectHadErrors if this unqualified-id occurs within a member access
2732/// expression, indicates whether the original subexpressions had any errors.
2733/// When true, diagnostics for missing 'template' keyword will be supressed.
2734///
2735/// \param EnteringContext whether we are entering the scope of the
2736/// nested-name-specifier.
2737///
2738/// \param AllowDestructorName whether we allow parsing of a destructor name.
2739///
2740/// \param AllowConstructorName whether we allow parsing a constructor name.
2741///
2742/// \param AllowDeductionGuide whether we allow parsing a deduction guide name.
2743///
2744/// \param Result on a successful parse, contains the parsed unqualified-id.
2745///
2746/// \returns true if parsing fails, false otherwise.
2747bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, ParsedType ObjectType,
2748 bool ObjectHadErrors, bool EnteringContext,
2749 bool AllowDestructorName,
2750 bool AllowConstructorName,
2751 bool AllowDeductionGuide,
2752 SourceLocation *TemplateKWLoc,
2753 UnqualifiedId &Result) {
2754 if (TemplateKWLoc)
2755 *TemplateKWLoc = SourceLocation();
2756
2757 // Handle 'A::template B'. This is for template-ids which have not
2758 // already been annotated by ParseOptionalCXXScopeSpecifier().
2759 bool TemplateSpecified = false;
2760 if (Tok.is(tok::kw_template)) {
2761 if (TemplateKWLoc && (ObjectType || SS.isSet())) {
2762 TemplateSpecified = true;
2763 *TemplateKWLoc = ConsumeToken();
2764 } else {
2765 SourceLocation TemplateLoc = ConsumeToken();
2766 Diag(TemplateLoc, diag::err_unexpected_template_in_unqualified_id)
2767 << FixItHint::CreateRemoval(TemplateLoc);
2768 }
2769 }
2770
2771 // unqualified-id:
2772 // identifier
2773 // template-id (when it hasn't already been annotated)
2774 if (Tok.is(tok::identifier)) {
2775 // Consume the identifier.
2776 IdentifierInfo *Id = Tok.getIdentifierInfo();
2777 SourceLocation IdLoc = ConsumeToken();
2778
2779 if (!getLangOpts().CPlusPlus) {
2780 // If we're not in C++, only identifiers matter. Record the
2781 // identifier and return.
2782 Result.setIdentifier(Id, IdLoc);
2783 return false;
2784 }
2785
2786 ParsedTemplateTy TemplateName;
2787 if (AllowConstructorName &&
2788 Actions.isCurrentClassName(*Id, getCurScope(), &SS)) {
2789 // We have parsed a constructor name.
2790 ParsedType Ty = Actions.getConstructorName(*Id, IdLoc, getCurScope(), SS,
2791 EnteringContext);
2792 if (!Ty)
2793 return true;
2794 Result.setConstructorName(Ty, IdLoc, IdLoc);
2795 } else if (getLangOpts().CPlusPlus17 &&
2796 AllowDeductionGuide && SS.isEmpty() &&
2797 Actions.isDeductionGuideName(getCurScope(), *Id, IdLoc,
2798 &TemplateName)) {
2799 // We have parsed a template-name naming a deduction guide.
2800 Result.setDeductionGuideName(TemplateName, IdLoc);
2801 } else {
2802 // We have parsed an identifier.
2803 Result.setIdentifier(Id, IdLoc);
2804 }
2805
2806 // If the next token is a '<', we may have a template.
2807 TemplateTy Template;
2808 if (Tok.is(tok::less))
2809 return ParseUnqualifiedIdTemplateId(
2810 SS, ObjectType, ObjectHadErrors,
2811 TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), Id, IdLoc,
2812 EnteringContext, Result, TemplateSpecified);
2813 else if (TemplateSpecified &&
2814 Actions.ActOnTemplateName(
2815 getCurScope(), SS, *TemplateKWLoc, Result, ObjectType,
2816 EnteringContext, Template,
2817 /*AllowInjectedClassName*/ true) == TNK_Non_template)
2818 return true;
2819
2820 return false;
2821 }
2822
2823 // unqualified-id:
2824 // template-id (already parsed and annotated)
2825 if (Tok.is(tok::annot_template_id)) {
2826 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
2827
2828 // FIXME: Consider passing invalid template-ids on to callers; they may
2829 // be able to recover better than we can.
2830 if (TemplateId->isInvalid()) {
2831 ConsumeAnnotationToken();
2832 return true;
2833 }
2834
2835 // If the template-name names the current class, then this is a constructor
2836 if (AllowConstructorName && TemplateId->Name &&
2837 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
2838 if (SS.isSet()) {
2839 // C++ [class.qual]p2 specifies that a qualified template-name
2840 // is taken as the constructor name where a constructor can be
2841 // declared. Thus, the template arguments are extraneous, so
2842 // complain about them and remove them entirely.
2843 Diag(TemplateId->TemplateNameLoc,
2844 diag::err_out_of_line_constructor_template_id)
2845 << TemplateId->Name
2846 << FixItHint::CreateRemoval(
2847 SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc));
2848 ParsedType Ty = Actions.getConstructorName(
2849 *TemplateId->Name, TemplateId->TemplateNameLoc, getCurScope(), SS,
2850 EnteringContext);
2851 if (!Ty)
2852 return true;
2853 Result.setConstructorName(Ty, TemplateId->TemplateNameLoc,
2854 TemplateId->RAngleLoc);
2855 ConsumeAnnotationToken();
2856 return false;
2857 }
2858
2859 Result.setConstructorTemplateId(TemplateId);
2860 ConsumeAnnotationToken();
2861 return false;
2862 }
2863
2864 // We have already parsed a template-id; consume the annotation token as
2865 // our unqualified-id.
2866 Result.setTemplateId(TemplateId);
2867 SourceLocation TemplateLoc = TemplateId->TemplateKWLoc;
2868 if (TemplateLoc.isValid()) {
2869 if (TemplateKWLoc && (ObjectType || SS.isSet()))
2870 *TemplateKWLoc = TemplateLoc;
2871 else
2872 Diag(TemplateLoc, diag::err_unexpected_template_in_unqualified_id)
2873 << FixItHint::CreateRemoval(TemplateLoc);
2874 }
2875 ConsumeAnnotationToken();
2876 return false;
2877 }
2878
2879 // unqualified-id:
2880 // operator-function-id
2881 // conversion-function-id
2882 if (Tok.is(tok::kw_operator)) {
2883 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, Result))
2884 return true;
2885
2886 // If we have an operator-function-id or a literal-operator-id and the next
2887 // token is a '<', we may have a
2888 //
2889 // template-id:
2890 // operator-function-id < template-argument-list[opt] >
2891 TemplateTy Template;
2892 if ((Result.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId ||
2893 Result.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId) &&
2894 Tok.is(tok::less))
2895 return ParseUnqualifiedIdTemplateId(
2896 SS, ObjectType, ObjectHadErrors,
2897 TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), nullptr,
2898 SourceLocation(), EnteringContext, Result, TemplateSpecified);
2899 else if (TemplateSpecified &&
2900 Actions.ActOnTemplateName(
2901 getCurScope(), SS, *TemplateKWLoc, Result, ObjectType,
2902 EnteringContext, Template,
2903 /*AllowInjectedClassName*/ true) == TNK_Non_template)
2904 return true;
2905
2906 return false;
2907 }
2908
2909 if (getLangOpts().CPlusPlus &&
2910 (AllowDestructorName || SS.isSet()) && Tok.is(tok::tilde)) {
2911 // C++ [expr.unary.op]p10:
2912 // There is an ambiguity in the unary-expression ~X(), where X is a
2913 // class-name. The ambiguity is resolved in favor of treating ~ as a
2914 // unary complement rather than treating ~X as referring to a destructor.
2915
2916 // Parse the '~'.
2917 SourceLocation TildeLoc = ConsumeToken();
2918
2919 if (TemplateSpecified) {
2920 // C++ [temp.names]p3:
2921 // A name prefixed by the keyword template shall be a template-id [...]
2922 //
2923 // A template-id cannot begin with a '~' token. This would never work
2924 // anyway: x.~A<int>() would specify that the destructor is a template,
2925 // not that 'A' is a template.
2926 //
2927 // FIXME: Suggest replacing the attempted destructor name with a correct
2928 // destructor name and recover. (This is not trivial if this would become
2929 // a pseudo-destructor name).
2930 Diag(*TemplateKWLoc, diag::err_unexpected_template_in_destructor_name)
2931 << Tok.getLocation();
2932 return true;
2933 }
2934
2935 if (SS.isEmpty() && Tok.is(tok::kw_decltype)) {
2936 DeclSpec DS(AttrFactory);
2937 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
2938 if (ParsedType Type =
2939 Actions.getDestructorTypeForDecltype(DS, ObjectType)) {
2940 Result.setDestructorName(TildeLoc, Type, EndLoc);
2941 return false;
2942 }
2943 return true;
2944 }
2945
2946 // Parse the class-name.
2947 if (Tok.isNot(tok::identifier)) {
2948 Diag(Tok, diag::err_destructor_tilde_identifier);
2949 return true;
2950 }
2951
2952 // If the user wrote ~T::T, correct it to T::~T.
2953 DeclaratorScopeObj DeclScopeObj(*this, SS);
2954 if (NextToken().is(tok::coloncolon)) {
2955 // Don't let ParseOptionalCXXScopeSpecifier() "correct"
2956 // `int A; struct { ~A::A(); };` to `int A; struct { ~A:A(); };`,
2957 // it will confuse this recovery logic.
2958 ColonProtectionRAIIObject ColonRAII(*this, false);
2959
2960 if (SS.isSet()) {
2961 AnnotateScopeToken(SS, /*NewAnnotation*/true);
2962 SS.clear();
2963 }
2964 if (ParseOptionalCXXScopeSpecifier(SS, ObjectType, ObjectHadErrors,
2965 EnteringContext))
2966 return true;
2967 if (SS.isNotEmpty())
2968 ObjectType = nullptr;
2969 if (Tok.isNot(tok::identifier) || NextToken().is(tok::coloncolon) ||
2970 !SS.isSet()) {
2971 Diag(TildeLoc, diag::err_destructor_tilde_scope);
2972 return true;
2973 }
2974
2975 // Recover as if the tilde had been written before the identifier.
2976 Diag(TildeLoc, diag::err_destructor_tilde_scope)
2977 << FixItHint::CreateRemoval(TildeLoc)
2978 << FixItHint::CreateInsertion(Tok.getLocation(), "~");
2979
2980 // Temporarily enter the scope for the rest of this function.
2981 if (Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
2982 DeclScopeObj.EnterDeclaratorScope();
2983 }
2984
2985 // Parse the class-name (or template-name in a simple-template-id).
2986 IdentifierInfo *ClassName = Tok.getIdentifierInfo();
2987 SourceLocation ClassNameLoc = ConsumeToken();
2988
2989 if (Tok.is(tok::less)) {
2990 Result.setDestructorName(TildeLoc, nullptr, ClassNameLoc);
2991 return ParseUnqualifiedIdTemplateId(
2992 SS, ObjectType, ObjectHadErrors,
2993 TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), ClassName,
2994 ClassNameLoc, EnteringContext, Result, TemplateSpecified);
2995 }
2996
2997 // Note that this is a destructor name.
2998 ParsedType Ty = Actions.getDestructorName(TildeLoc, *ClassName,
2999 ClassNameLoc, getCurScope(),
3000 SS, ObjectType,
3001 EnteringContext);
3002 if (!Ty)
3003 return true;
3004
3005 Result.setDestructorName(TildeLoc, Ty, ClassNameLoc);
3006 return false;
3007 }
3008
3009 Diag(Tok, diag::err_expected_unqualified_id)
3010 << getLangOpts().CPlusPlus;
3011 return true;
3012}
3013
3014/// ParseCXXNewExpression - Parse a C++ new-expression. New is used to allocate
3015/// memory in a typesafe manner and call constructors.
3016///
3017/// This method is called to parse the new expression after the optional :: has
3018/// been already parsed. If the :: was present, "UseGlobal" is true and "Start"
3019/// is its location. Otherwise, "Start" is the location of the 'new' token.
3020///
3021/// new-expression:
3022/// '::'[opt] 'new' new-placement[opt] new-type-id
3023/// new-initializer[opt]
3024/// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
3025/// new-initializer[opt]
3026///
3027/// new-placement:
3028/// '(' expression-list ')'
3029///
3030/// new-type-id:
3031/// type-specifier-seq new-declarator[opt]
3032/// [GNU] attributes type-specifier-seq new-declarator[opt]
3033///
3034/// new-declarator:
3035/// ptr-operator new-declarator[opt]
3036/// direct-new-declarator
3037///
3038/// new-initializer:
3039/// '(' expression-list[opt] ')'
3040/// [C++0x] braced-init-list
3041///
3042ExprResult
3043Parser::ParseCXXNewExpression(bool UseGlobal, SourceLocation Start) {
3044 assert(Tok.is(tok::kw_new) && "expected 'new' token")((Tok.is(tok::kw_new) && "expected 'new' token") ? static_cast
<void> (0) : __assert_fail ("Tok.is(tok::kw_new) && \"expected 'new' token\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Parse/ParseExprCXX.cpp"
, 3044, __PRETTY_FUNCTION__))
;
3045 ConsumeToken(); // Consume 'new'
3046
3047 // A '(' now can be a new-placement or the '(' wrapping the type-id in the
3048 // second form of new-expression. It can't be a new-type-id.
3049
3050 ExprVector PlacementArgs;
3051 SourceLocation PlacementLParen, PlacementRParen;
3052
3053 SourceRange TypeIdParens;
3054 DeclSpec DS(AttrFactory);
3055 Declarator DeclaratorInfo(DS, DeclaratorContext::CXXNew);
3056 if (Tok.is(tok::l_paren)) {
3057 // If it turns out to be a placement, we change the type location.
3058 BalancedDelimiterTracker T(*this, tok::l_paren);
3059 T.consumeOpen();
3060 PlacementLParen = T.getOpenLocation();
3061 if (ParseExpressionListOrTypeId(PlacementArgs, DeclaratorInfo)) {
3062 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
3063 return ExprError();
3064 }
3065
3066 T.consumeClose();
3067 PlacementRParen = T.getCloseLocation();
3068 if (PlacementRParen.isInvalid()) {
3069 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
3070 return ExprError();
3071 }
3072
3073 if (PlacementArgs.empty()) {
3074 // Reset the placement locations. There was no placement.
3075 TypeIdParens = T.getRange();
3076 PlacementLParen = PlacementRParen = SourceLocation();
3077 } else {
3078 // We still need the type.
3079 if (Tok.is(tok::l_paren)) {
3080 BalancedDelimiterTracker T(*this, tok::l_paren);
3081 T.consumeOpen();
3082 MaybeParseGNUAttributes(DeclaratorInfo);
3083 ParseSpecifierQualifierList(DS);
3084 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
3085 ParseDeclarator(DeclaratorInfo);
3086 T.consumeClose();
3087 TypeIdParens = T.getRange();
3088 } else {
3089 MaybeParseGNUAttributes(DeclaratorInfo);
3090 if (ParseCXXTypeSpecifierSeq(DS))
3091 DeclaratorInfo.setInvalidType(true);
3092 else {
3093 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
3094 ParseDeclaratorInternal(DeclaratorInfo,
3095 &Parser::ParseDirectNewDeclarator);
3096 }
3097 }
3098 }
3099 } else {
3100 // A new-type-id is a simplified type-id, where essentially the
3101 // direct-declarator is replaced by a direct-new-declarator.
3102 MaybeParseGNUAttributes(DeclaratorInfo);
3103 if (ParseCXXTypeSpecifierSeq(DS))
3104 DeclaratorInfo.setInvalidType(true);
3105 else {
3106 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
3107 ParseDeclaratorInternal(DeclaratorInfo,
3108 &Parser::ParseDirectNewDeclarator);
3109 }
3110 }
3111 if (DeclaratorInfo.isInvalidType()) {
3112 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
3113 return ExprError();
3114 }
3115
3116 ExprResult Initializer;
3117
3118 if (Tok.is(tok::l_paren)) {
3119 SourceLocation ConstructorLParen, ConstructorRParen;
3120 ExprVector ConstructorArgs;
3121 BalancedDelimiterTracker T(*this, tok::l_paren);
3122 T.consumeOpen();
3123 ConstructorLParen = T.getOpenLocation();
3124 if (Tok.isNot(tok::r_paren)) {
3125 CommaLocsTy CommaLocs;
3126 auto RunSignatureHelp = [&]() {
3127 ParsedType TypeRep =
3128 Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
3129 QualType PreferredType;
3130 // ActOnTypeName might adjust DeclaratorInfo and return a null type even
3131 // the passing DeclaratorInfo is valid, e.g. running SignatureHelp on
3132 // `new decltype(invalid) (^)`.
3133 if (TypeRep)
3134 PreferredType = Actions.ProduceConstructorSignatureHelp(
3135 getCurScope(), TypeRep.get()->getCanonicalTypeInternal(),
3136 DeclaratorInfo.getEndLoc(), ConstructorArgs, ConstructorLParen);
3137 CalledSignatureHelp = true;
3138 return PreferredType;
3139 };
3140 if (ParseExpressionList(ConstructorArgs, CommaLocs, [&] {
3141 PreferredType.enterFunctionArgument(Tok.getLocation(),
3142 RunSignatureHelp);
3143 })) {
3144 if (PP.isCodeCompletionReached() && !CalledSignatureHelp)
3145 RunSignatureHelp();
3146 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
3147 return ExprError();
3148 }
3149 }
3150 T.consumeClose();
3151 ConstructorRParen = T.getCloseLocation();
3152 if (ConstructorRParen.isInvalid()) {
3153 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
3154 return ExprError();
3155 }
3156 Initializer = Actions.ActOnParenListExpr(ConstructorLParen,
3157 ConstructorRParen,
3158 ConstructorArgs);
3159 } else if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus11) {
3160 Diag(Tok.getLocation(),
3161 diag::warn_cxx98_compat_generalized_initializer_lists);
3162 Initializer = ParseBraceInitializer();
3163 }
3164 if (Initializer.isInvalid())
3165 return Initializer;
3166
3167 return Actions.ActOnCXXNew(Start, UseGlobal, PlacementLParen,
3168 PlacementArgs, PlacementRParen,
3169 TypeIdParens, DeclaratorInfo, Initializer.get());
3170}
3171
3172/// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be
3173/// passed to ParseDeclaratorInternal.
3174///
3175/// direct-new-declarator:
3176/// '[' expression[opt] ']'
3177/// direct-new-declarator '[' constant-expression ']'
3178///
3179void Parser::ParseDirectNewDeclarator(Declarator &D) {
3180 // Parse the array dimensions.
3181 bool First = true;
3182 while (Tok.is(tok::l_square)) {
3183 // An array-size expression can't start with a lambda.
3184 if (CheckProhibitedCXX11Attribute())
3185 continue;
3186
3187 BalancedDelimiterTracker T(*this, tok::l_square);
3188 T.consumeOpen();
3189
3190 ExprResult Size =
3191 First ? (Tok.is(tok::r_square) ? ExprResult() : ParseExpression())
3192 : ParseConstantExpression();
3193 if (Size.isInvalid()) {
3194 // Recover
3195 SkipUntil(tok::r_square, StopAtSemi);
3196 return;
3197 }
3198 First = false;
3199
3200 T.consumeClose();
3201
3202 // Attributes here appertain to the array type. C++11 [expr.new]p5.
3203 ParsedAttributes Attrs(AttrFactory);
3204 MaybeParseCXX11Attributes(Attrs);
3205
3206 D.AddTypeInfo(DeclaratorChunk::getArray(0,
3207 /*isStatic=*/false, /*isStar=*/false,
3208 Size.get(), T.getOpenLocation(),
3209 T.getCloseLocation()),
3210 std::move(Attrs), T.getCloseLocation());
3211
3212 if (T.getCloseLocation().isInvalid())
3213 return;
3214 }
3215}
3216
3217/// ParseExpressionListOrTypeId - Parse either an expression-list or a type-id.
3218/// This ambiguity appears in the syntax of the C++ new operator.
3219///
3220/// new-expression:
3221/// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
3222/// new-initializer[opt]
3223///
3224/// new-placement:
3225/// '(' expression-list ')'
3226///
3227bool Parser::ParseExpressionListOrTypeId(
3228 SmallVectorImpl<Expr*> &PlacementArgs,
3229 Declarator &D) {
3230 // The '(' was already consumed.
3231 if (isTypeIdInParens()) {
3232 ParseSpecifierQualifierList(D.getMutableDeclSpec());
3233 D.SetSourceRange(D.getDeclSpec().getSourceRange());
3234 ParseDeclarator(D);
3235 return D.isInvalidType();
3236 }
3237
3238 // It's not a type, it has to be an expression list.
3239 // Discard the comma locations - ActOnCXXNew has enough parameters.
3240 CommaLocsTy CommaLocs;
3241 return ParseExpressionList(PlacementArgs, CommaLocs);
3242}
3243
3244/// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used
3245/// to free memory allocated by new.
3246///
3247/// This method is called to parse the 'delete' expression after the optional
3248/// '::' has been already parsed. If the '::' was present, "UseGlobal" is true
3249/// and "Start" is its location. Otherwise, "Start" is the location of the
3250/// 'delete' token.
3251///
3252/// delete-expression:
3253/// '::'[opt] 'delete' cast-expression
3254/// '::'[opt] 'delete' '[' ']' cast-expression
3255ExprResult
3256Parser::ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start) {
3257 assert(Tok.is(tok::kw_delete) && "Expected 'delete' keyword")((Tok.is(tok::kw_delete) && "Expected 'delete' keyword"
) ? static_cast<void> (0) : __assert_fail ("Tok.is(tok::kw_delete) && \"Expected 'delete' keyword\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Parse/ParseExprCXX.cpp"
, 3257, __PRETTY_FUNCTION__))
;
3258 ConsumeToken(); // Consume 'delete'
3259
3260 // Array delete?
3261 bool ArrayDelete = false;
3262 if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) {
3263 // C++11 [expr.delete]p1:
3264 // Whenever the delete keyword is followed by empty square brackets, it
3265 // shall be interpreted as [array delete].
3266 // [Footnote: A lambda expression with a lambda-introducer that consists
3267 // of empty square brackets can follow the delete keyword if
3268 // the lambda expression is enclosed in parentheses.]
3269
3270 const Token Next = GetLookAheadToken(2);
3271
3272 // Basic lookahead to check if we have a lambda expression.
3273 if (Next.isOneOf(tok::l_brace, tok::less) ||
3274 (Next.is(tok::l_paren) &&
3275 (GetLookAheadToken(3).is(tok::r_paren) ||
3276 (GetLookAheadToken(3).is(tok::identifier) &&
3277 GetLookAheadToken(4).is(tok::identifier))))) {
3278 TentativeParsingAction TPA(*this);
3279 SourceLocation LSquareLoc = Tok.getLocation();
3280 SourceLocation RSquareLoc = NextToken().getLocation();
3281
3282 // SkipUntil can't skip pairs of </*...*/>; don't emit a FixIt in this
3283 // case.
3284 SkipUntil({tok::l_brace, tok::less}, StopBeforeMatch);
3285 SourceLocation RBraceLoc;
3286 bool EmitFixIt = false;
3287 if (Tok.is(tok::l_brace)) {
3288 ConsumeBrace();
3289 SkipUntil(tok::r_brace, StopBeforeMatch);
3290 RBraceLoc = Tok.getLocation();
3291 EmitFixIt = true;
3292 }
3293
3294 TPA.Revert();
3295
3296 if (EmitFixIt)
3297 Diag(Start, diag::err_lambda_after_delete)
3298 << SourceRange(Start, RSquareLoc)
3299 << FixItHint::CreateInsertion(LSquareLoc, "(")
3300 << FixItHint::CreateInsertion(
3301 Lexer::getLocForEndOfToken(
3302 RBraceLoc, 0, Actions.getSourceManager(), getLangOpts()),
3303 ")");
3304 else
3305 Diag(Start, diag::err_lambda_after_delete)
3306 << SourceRange(Start, RSquareLoc);
3307
3308 // Warn that the non-capturing lambda isn't surrounded by parentheses
3309 // to disambiguate it from 'delete[]'.
3310 ExprResult Lambda = ParseLambdaExpression();
3311 if (Lambda.isInvalid())
3312 return ExprError();
3313
3314 // Evaluate any postfix expressions used on the lambda.
3315 Lambda = ParsePostfixExpressionSuffix(Lambda);
3316 if (Lambda.isInvalid())
3317 return ExprError();
3318 return Actions.ActOnCXXDelete(Start, UseGlobal, /*ArrayForm=*/false,
3319 Lambda.get());
3320 }
3321
3322 ArrayDelete = true;
3323 BalancedDelimiterTracker T(*this, tok::l_square);
3324
3325 T.consumeOpen();
3326 T.consumeClose();
3327 if (T.getCloseLocation().isInvalid())
3328 return ExprError();
3329 }
3330
3331 ExprResult Operand(ParseCastExpression(AnyCastExpr));
3332 if (Operand.isInvalid())
3333 return Operand;
3334
3335 return Actions.ActOnCXXDelete(Start, UseGlobal, ArrayDelete, Operand.get());
3336}
3337
3338/// ParseRequiresExpression - Parse a C++2a requires-expression.
3339/// C++2a [expr.prim.req]p1
3340/// A requires-expression provides a concise way to express requirements on
3341/// template arguments. A requirement is one that can be checked by name
3342/// lookup (6.4) or by checking properties of types and expressions.
3343///
3344/// requires-expression:
3345/// 'requires' requirement-parameter-list[opt] requirement-body
3346///
3347/// requirement-parameter-list:
3348/// '(' parameter-declaration-clause[opt] ')'
3349///
3350/// requirement-body:
3351/// '{' requirement-seq '}'
3352///
3353/// requirement-seq:
3354/// requirement
3355/// requirement-seq requirement
3356///
3357/// requirement:
3358/// simple-requirement
3359/// type-requirement
3360/// compound-requirement
3361/// nested-requirement
3362ExprResult Parser::ParseRequiresExpression() {
3363 assert(Tok.is(tok::kw_requires) && "Expected 'requires' keyword")((Tok.is(tok::kw_requires) && "Expected 'requires' keyword"
) ? static_cast<void> (0) : __assert_fail ("Tok.is(tok::kw_requires) && \"Expected 'requires' keyword\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Parse/ParseExprCXX.cpp"
, 3363, __PRETTY_FUNCTION__))
;
3364 SourceLocation RequiresKWLoc = ConsumeToken(); // Consume 'requires'
3365
3366 llvm::SmallVector<ParmVarDecl *, 2> LocalParameterDecls;
3367 if (Tok.is(tok::l_paren)) {
3368 // requirement parameter list is present.
3369 ParseScope LocalParametersScope(this, Scope::FunctionPrototypeScope |
3370 Scope::DeclScope);
3371 BalancedDelimiterTracker Parens(*this, tok::l_paren);
3372 Parens.consumeOpen();
3373 if (!Tok.is(tok::r_paren)) {
3374 ParsedAttributes FirstArgAttrs(getAttrFactory());
3375 SourceLocation EllipsisLoc;
3376 llvm::SmallVector<DeclaratorChunk::ParamInfo, 2> LocalParameters;
3377 ParseParameterDeclarationClause(DeclaratorContext::RequiresExpr,
3378 FirstArgAttrs, LocalParameters,
3379 EllipsisLoc);
3380 if (EllipsisLoc.isValid())
3381 Diag(EllipsisLoc, diag::err_requires_expr_parameter_list_ellipsis);
3382 for (auto &ParamInfo : LocalParameters)
3383 LocalParameterDecls.push_back(cast<ParmVarDecl>(ParamInfo.Param));
3384 }
3385 Parens.consumeClose();
3386 }
3387
3388 BalancedDelimiterTracker Braces(*this, tok::l_brace);
3389 if (Braces.expectAndConsume())
3390 return ExprError();
3391
3392 // Start of requirement list
3393 llvm::SmallVector<concepts::Requirement *, 2> Requirements;
3394
3395 // C++2a [expr.prim.req]p2
3396 // Expressions appearing within a requirement-body are unevaluated operands.
3397 EnterExpressionEvaluationContext Ctx(
3398 Actions, Sema::ExpressionEvaluationContext::Unevaluated);
3399
3400 ParseScope BodyScope(this, Scope::DeclScope);
3401 RequiresExprBodyDecl *Body = Actions.ActOnStartRequiresExpr(
3402 RequiresKWLoc, LocalParameterDecls, getCurScope());
3403
3404 if (Tok.is(tok::r_brace)) {
3405 // Grammar does not allow an empty body.
3406 // requirement-body:
3407 // { requirement-seq }
3408 // requirement-seq:
3409 // requirement
3410 // requirement-seq requirement
3411 Diag(Tok, diag::err_empty_requires_expr);
3412 // Continue anyway and produce a requires expr with no requirements.
3413 } else {
3414 while (!Tok.is(tok::r_brace)) {
3415 switch (Tok.getKind()) {
3416 case tok::l_brace: {
3417 // Compound requirement
3418 // C++ [expr.prim.req.compound]
3419 // compound-requirement:
3420 // '{' expression '}' 'noexcept'[opt]
3421 // return-type-requirement[opt] ';'
3422 // return-type-requirement:
3423 // trailing-return-type
3424 // '->' cv-qualifier-seq[opt] constrained-parameter
3425 // cv-qualifier-seq[opt] abstract-declarator[opt]
3426 BalancedDelimiterTracker ExprBraces(*this, tok::l_brace);
3427 ExprBraces.consumeOpen();
3428 ExprResult Expression =
3429 Actions.CorrectDelayedTyposInExpr(ParseExpression());
3430 if (!Expression.isUsable()) {
3431 ExprBraces.skipToEnd();
3432 SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3433 break;
3434 }
3435 if (ExprBraces.consumeClose())
3436 ExprBraces.skipToEnd();
3437
3438 concepts::Requirement *Req = nullptr;
3439 SourceLocation NoexceptLoc;
3440 TryConsumeToken(tok::kw_noexcept, NoexceptLoc);
3441 if (Tok.is(tok::semi)) {
3442 Req = Actions.ActOnCompoundRequirement(Expression.get(), NoexceptLoc);
3443 if (Req)
3444 Requirements.push_back(Req);
3445 break;
3446 }
3447 if (!TryConsumeToken(tok::arrow))
3448 // User probably forgot the arrow, remind them and try to continue.
3449 Diag(Tok, diag::err_requires_expr_missing_arrow)
3450 << FixItHint::CreateInsertion(Tok.getLocation(), "->");
3451 // Try to parse a 'type-constraint'
3452 if (TryAnnotateTypeConstraint()) {
3453 SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3454 break;
3455 }
3456 if (!isTypeConstraintAnnotation()) {
3457 Diag(Tok, diag::err_requires_expr_expected_type_constraint);
3458 SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3459 break;
3460 }
3461 CXXScopeSpec SS;
3462 if (Tok.is(tok::annot_cxxscope)) {
3463 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
3464 Tok.getAnnotationRange(),
3465 SS);
3466 ConsumeAnnotationToken();
3467 }
3468
3469 Req = Actions.ActOnCompoundRequirement(
3470 Expression.get(), NoexceptLoc, SS, takeTemplateIdAnnotation(Tok),
3471 TemplateParameterDepth);
3472 ConsumeAnnotationToken();
3473 if (Req)
3474 Requirements.push_back(Req);
3475 break;
3476 }
3477 default: {
3478 bool PossibleRequiresExprInSimpleRequirement = false;
3479 if (Tok.is(tok::kw_requires)) {
3480 auto IsNestedRequirement = [&] {
3481 RevertingTentativeParsingAction TPA(*this);
3482 ConsumeToken(); // 'requires'
3483 if (Tok.is(tok::l_brace))
3484 // This is a requires expression
3485 // requires (T t) {
3486 // requires { t++; };
3487 // ... ^
3488 // }
3489 return false;
3490 if (Tok.is(tok::l_paren)) {
3491 // This might be the parameter list of a requires expression
3492 ConsumeParen();
3493 auto Res = TryParseParameterDeclarationClause();
3494 if (Res != TPResult::False) {
3495 // Skip to the closing parenthesis
3496 // FIXME: Don't traverse these tokens twice (here and in
3497 // TryParseParameterDeclarationClause).
3498 unsigned Depth = 1;
3499 while (Depth != 0) {
3500 if (Tok.is(tok::l_paren))
3501 Depth++;
3502 else if (Tok.is(tok::r_paren))
3503 Depth--;
3504 ConsumeAnyToken();
3505 }
3506 // requires (T t) {
3507 // requires () ?
3508 // ... ^
3509 // - OR -
3510 // requires (int x) ?
3511 // ... ^
3512 // }
3513 if (Tok.is(tok::l_brace))
3514 // requires (...) {
3515 // ^ - a requires expression as a
3516 // simple-requirement.
3517 return false;
3518 }
3519 }
3520 return true;
3521 };
3522 if (IsNestedRequirement()) {
3523 ConsumeToken();
3524 // Nested requirement
3525 // C++ [expr.prim.req.nested]
3526 // nested-requirement:
3527 // 'requires' constraint-expression ';'
3528 ExprResult ConstraintExpr =
3529 Actions.CorrectDelayedTyposInExpr(ParseConstraintExpression());
3530 if (ConstraintExpr.isInvalid() || !ConstraintExpr.isUsable()) {
3531 SkipUntil(tok::semi, tok::r_brace,
3532 SkipUntilFlags::StopBeforeMatch);
3533 break;
3534 }
3535 if (auto *Req =
3536 Actions.ActOnNestedRequirement(ConstraintExpr.get()))
3537 Requirements.push_back(Req);
3538 else {
3539 SkipUntil(tok::semi, tok::r_brace,
3540 SkipUntilFlags::StopBeforeMatch);
3541 break;
3542 }
3543 break;
3544 } else
3545 PossibleRequiresExprInSimpleRequirement = true;
3546 } else if (Tok.is(tok::kw_typename)) {
3547 // This might be 'typename T::value_type;' (a type requirement) or
3548 // 'typename T::value_type{};' (a simple requirement).
3549 TentativeParsingAction TPA(*this);
3550
3551 // We need to consume the typename to allow 'requires { typename a; }'
3552 SourceLocation TypenameKWLoc = ConsumeToken();
3553 if (TryAnnotateCXXScopeToken()) {
3554 TPA.Commit();
3555 SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3556 break;
3557 }
3558 CXXScopeSpec SS;
3559 if (Tok.is(tok::annot_cxxscope)) {
3560 Actions.RestoreNestedNameSpecifierAnnotation(
3561 Tok.getAnnotationValue(), Tok.getAnnotationRange(), SS);
3562 ConsumeAnnotationToken();
3563 }
3564
3565 if (Tok.isOneOf(tok::identifier, tok::annot_template_id) &&
3566 !NextToken().isOneOf(tok::l_brace, tok::l_paren)) {
3567 TPA.Commit();
3568 SourceLocation NameLoc = Tok.getLocation();
3569 IdentifierInfo *II = nullptr;
3570 TemplateIdAnnotation *TemplateId = nullptr;
3571 if (Tok.is(tok::identifier)) {
3572 II = Tok.getIdentifierInfo();
3573 ConsumeToken();
3574 } else {
3575 TemplateId = takeTemplateIdAnnotation(Tok);
3576 ConsumeAnnotationToken();
3577 if (TemplateId->isInvalid())
3578 break;
3579 }
3580
3581 if (auto *Req = Actions.ActOnTypeRequirement(TypenameKWLoc, SS,
3582 NameLoc, II,
3583 TemplateId)) {
3584 Requirements.push_back(Req);
3585 }
3586 break;
3587 }
3588 TPA.Revert();
3589 }
3590 // Simple requirement
3591 // C++ [expr.prim.req.simple]
3592 // simple-requirement:
3593 // expression ';'
3594 SourceLocation StartLoc = Tok.getLocation();
3595 ExprResult Expression =
3596 Actions.CorrectDelayedTyposInExpr(ParseExpression());
3597 if (!Expression.isUsable()) {
3598 SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3599 break;
3600 }
3601 if (!Expression.isInvalid() && PossibleRequiresExprInSimpleRequirement)
3602 Diag(StartLoc, diag::warn_requires_expr_in_simple_requirement)
3603 << FixItHint::CreateInsertion(StartLoc, "requires");
3604 if (auto *Req = Actions.ActOnSimpleRequirement(Expression.get()))
3605 Requirements.push_back(Req);
3606 else {
3607 SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3608 break;
3609 }
3610 // User may have tried to put some compound requirement stuff here
3611 if (Tok.is(tok::kw_noexcept)) {
3612 Diag(Tok, diag::err_requires_expr_simple_requirement_noexcept)
3613 << FixItHint::CreateInsertion(StartLoc, "{")
3614 << FixItHint::CreateInsertion(Tok.getLocation(), "}");
3615 SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3616 break;
3617 }
3618 break;
3619 }
3620 }
3621 if (ExpectAndConsumeSemi(diag::err_expected_semi_requirement)) {
3622 SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3623 TryConsumeToken(tok::semi);
3624 break;
3625 }
3626 }
3627 if (Requirements.empty()) {
3628 // Don't emit an empty requires expr here to avoid confusing the user with
3629 // other diagnostics quoting an empty requires expression they never
3630 // wrote.
3631 Braces.consumeClose();
3632 Actions.ActOnFinishRequiresExpr();
3633 return ExprError();
3634 }
3635 }
3636 Braces.consumeClose();
3637 Actions.ActOnFinishRequiresExpr();
3638 return Actions.ActOnRequiresExpr(RequiresKWLoc, Body, LocalParameterDecls,
3639 Requirements, Braces.getCloseLocation());
3640}
3641
3642static TypeTrait TypeTraitFromTokKind(tok::TokenKind kind) {
3643 switch (kind) {
3644 default: llvm_unreachable("Not a known type trait")::llvm::llvm_unreachable_internal("Not a known type trait", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Parse/ParseExprCXX.cpp"
, 3644)
;
3645#define TYPE_TRAIT_1(Spelling, Name, Key) \
3646case tok::kw_ ## Spelling: return UTT_ ## Name;
3647#define TYPE_TRAIT_2(Spelling, Name, Key) \
3648case tok::kw_ ## Spelling: return BTT_ ## Name;
3649#include "clang/Basic/TokenKinds.def"
3650#define TYPE_TRAIT_N(Spelling, Name, Key) \
3651 case tok::kw_ ## Spelling: return TT_ ## Name;
3652#include "clang/Basic/TokenKinds.def"
3653 }
3654}
3655
3656static ArrayTypeTrait ArrayTypeTraitFromTokKind(tok::TokenKind kind) {
3657 switch (kind) {
3658 default:
3659 llvm_unreachable("Not a known array type trait")::llvm::llvm_unreachable_internal("Not a known array type trait"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Parse/ParseExprCXX.cpp"
, 3659)
;
3660#define ARRAY_TYPE_TRAIT(Spelling, Name, Key) \
3661 case tok::kw_##Spelling: \
3662 return ATT_##Name;
3663#include "clang/Basic/TokenKinds.def"
3664 }
3665}
3666
3667static ExpressionTrait ExpressionTraitFromTokKind(tok::TokenKind kind) {
3668 switch (kind) {
3669 default:
3670 llvm_unreachable("Not a known unary expression trait.")::llvm::llvm_unreachable_internal("Not a known unary expression trait."
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Parse/ParseExprCXX.cpp"
, 3670)
;
3671#define EXPRESSION_TRAIT(Spelling, Name, Key) \
3672 case tok::kw_##Spelling: \
3673 return ET_##Name;
3674#include "clang/Basic/TokenKinds.def"
3675 }
3676}
3677
3678static unsigned TypeTraitArity(tok::TokenKind kind) {
3679 switch (kind) {
3680 default: llvm_unreachable("Not a known type trait")::llvm::llvm_unreachable_internal("Not a known type trait", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Parse/ParseExprCXX.cpp"
, 3680)
;
3681#define TYPE_TRAIT(N,Spelling,K) case tok::kw_##Spelling: return N;
3682#include "clang/Basic/TokenKinds.def"
3683 }
3684}
3685
3686/// Parse the built-in type-trait pseudo-functions that allow
3687/// implementation of the TR1/C++11 type traits templates.
3688///
3689/// primary-expression:
3690/// unary-type-trait '(' type-id ')'
3691/// binary-type-trait '(' type-id ',' type-id ')'
3692/// type-trait '(' type-id-seq ')'
3693///
3694/// type-id-seq:
3695/// type-id ...[opt] type-id-seq[opt]
3696///
3697ExprResult Parser::ParseTypeTrait() {
3698 tok::TokenKind Kind = Tok.getKind();
3699 unsigned Arity = TypeTraitArity(Kind);
3700
3701 SourceLocation Loc = ConsumeToken();
3702
3703 BalancedDelimiterTracker Parens(*this, tok::l_paren);
3704 if (Parens.expectAndConsume())
3705 return ExprError();
3706
3707 SmallVector<ParsedType, 2> Args;
3708 do {
3709 // Parse the next type.
3710 TypeResult Ty = ParseTypeName();
3711 if (Ty.isInvalid()) {
3712 Parens.skipToEnd();
3713 return ExprError();
3714 }
3715
3716 // Parse the ellipsis, if present.
3717 if (Tok.is(tok::ellipsis)) {
3718 Ty = Actions.ActOnPackExpansion(Ty.get(), ConsumeToken());
3719 if (Ty.isInvalid()) {
3720 Parens.skipToEnd();
3721 return ExprError();
3722 }
3723 }
3724
3725 // Add this type to the list of arguments.
3726 Args.push_back(Ty.get());
3727 } while (TryConsumeToken(tok::comma));
3728
3729 if (Parens.consumeClose())
3730 return ExprError();
3731
3732 SourceLocation EndLoc = Parens.getCloseLocation();
3733
3734 if (Arity && Args.size() != Arity) {
3735 Diag(EndLoc, diag::err_type_trait_arity)
3736 << Arity << 0 << (Arity > 1) << (int)Args.size() << SourceRange(Loc);
3737 return ExprError();
3738 }
3739
3740 if (!Arity && Args.empty()) {
3741 Diag(EndLoc, diag::err_type_trait_arity)
3742 << 1 << 1 << 1 << (int)Args.size() << SourceRange(Loc);
3743 return ExprError();
3744 }
3745
3746 return Actions.ActOnTypeTrait(TypeTraitFromTokKind(Kind), Loc, Args, EndLoc);
3747}
3748
3749/// ParseArrayTypeTrait - Parse the built-in array type-trait
3750/// pseudo-functions.
3751///
3752/// primary-expression:
3753/// [Embarcadero] '__array_rank' '(' type-id ')'
3754/// [Embarcadero] '__array_extent' '(' type-id ',' expression ')'
3755///
3756ExprResult Parser::ParseArrayTypeTrait() {
3757 ArrayTypeTrait ATT = ArrayTypeTraitFromTokKind(Tok.getKind());
3758 SourceLocation Loc = ConsumeToken();
3759
3760 BalancedDelimiterTracker T(*this, tok::l_paren);
3761 if (T.expectAndConsume())
3762 return ExprError();
3763
3764 TypeResult Ty = ParseTypeName();
3765 if (Ty.isInvalid()) {
3766 SkipUntil(tok::comma, StopAtSemi);
3767 SkipUntil(tok::r_paren, StopAtSemi);
3768 return ExprError();
3769 }
3770
3771 switch (ATT) {
3772 case ATT_ArrayRank: {
3773 T.consumeClose();
3774 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), nullptr,
3775 T.getCloseLocation());
3776 }
3777 case ATT_ArrayExtent: {
3778 if (ExpectAndConsume(tok::comma)) {
3779 SkipUntil(tok::r_paren, StopAtSemi);
3780 return ExprError();
3781 }
3782
3783 ExprResult DimExpr = ParseExpression();
3784 T.consumeClose();
3785
3786 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), DimExpr.get(),
3787 T.getCloseLocation());
3788 }
3789 }
3790 llvm_unreachable("Invalid ArrayTypeTrait!")::llvm::llvm_unreachable_internal("Invalid ArrayTypeTrait!", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Parse/ParseExprCXX.cpp"
, 3790)
;
3791}
3792
3793/// ParseExpressionTrait - Parse built-in expression-trait
3794/// pseudo-functions like __is_lvalue_expr( xxx ).
3795///
3796/// primary-expression:
3797/// [Embarcadero] expression-trait '(' expression ')'
3798///
3799ExprResult Parser::ParseExpressionTrait() {
3800 ExpressionTrait ET = ExpressionTraitFromTokKind(Tok.getKind());
3801 SourceLocation Loc = ConsumeToken();
3802
3803 BalancedDelimiterTracker T(*this, tok::l_paren);
3804 if (T.expectAndConsume())
3805 return ExprError();
3806
3807 ExprResult Expr = ParseExpression();
3808
3809 T.consumeClose();
3810
3811 return Actions.ActOnExpressionTrait(ET, Loc, Expr.get(),
3812 T.getCloseLocation());
3813}
3814
3815
3816/// ParseCXXAmbiguousParenExpression - We have parsed the left paren of a
3817/// parenthesized ambiguous type-id. This uses tentative parsing to disambiguate
3818/// based on the context past the parens.
3819ExprResult
3820Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType,
3821 ParsedType &CastTy,
3822 BalancedDelimiterTracker &Tracker,
3823 ColonProtectionRAIIObject &ColonProt) {
3824 assert(getLangOpts().CPlusPlus && "Should only be called for C++!")((getLangOpts().CPlusPlus && "Should only be called for C++!"
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"Should only be called for C++!\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Parse/ParseExprCXX.cpp"
, 3824, __PRETTY_FUNCTION__))
;
3825 assert(ExprType == CastExpr && "Compound literals are not ambiguous!")((ExprType == CastExpr && "Compound literals are not ambiguous!"
) ? static_cast<void> (0) : __assert_fail ("ExprType == CastExpr && \"Compound literals are not ambiguous!\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Parse/ParseExprCXX.cpp"
, 3825, __PRETTY_FUNCTION__))
;
3826 assert(isTypeIdInParens() && "Not a type-id!")((isTypeIdInParens() && "Not a type-id!") ? static_cast
<void> (0) : __assert_fail ("isTypeIdInParens() && \"Not a type-id!\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Parse/ParseExprCXX.cpp"
, 3826, __PRETTY_FUNCTION__))
;
3827
3828 ExprResult Result(true);
3829 CastTy = nullptr;
3830
3831 // We need to disambiguate a very ugly part of the C++ syntax:
3832 //
3833 // (T())x; - type-id
3834 // (T())*x; - type-id
3835 // (T())/x; - expression
3836 // (T()); - expression
3837 //
3838 // The bad news is that we cannot use the specialized tentative parser, since
3839 // it can only verify that the thing inside the parens can be parsed as
3840 // type-id, it is not useful for determining the context past the parens.
3841 //
3842 // The good news is that the parser can disambiguate this part without
3843 // making any unnecessary Action calls.
3844 //
3845 // It uses a scheme similar to parsing inline methods. The parenthesized
3846 // tokens are cached, the context that follows is determined (possibly by
3847 // parsing a cast-expression), and then we re-introduce the cached tokens
3848 // into the token stream and parse them appropriately.
3849
3850 ParenParseOption ParseAs;
3851 CachedTokens Toks;
3852
3853 // Store the tokens of the parentheses. We will parse them after we determine
3854 // the context that follows them.
3855 if (!ConsumeAndStoreUntil(tok::r_paren, Toks)) {
3856 // We didn't find the ')' we expected.
3857 Tracker.consumeClose();
3858 return ExprError();
3859 }
3860
3861 if (Tok.is(tok::l_brace)) {
3862 ParseAs = CompoundLiteral;
3863 } else {
3864 bool NotCastExpr;
3865 if (Tok.is(tok::l_paren) && NextToken().is(tok::r_paren)) {
3866 NotCastExpr = true;
3867 } else {
3868 // Try parsing the cast-expression that may follow.
3869 // If it is not a cast-expression, NotCastExpr will be true and no token
3870 // will be consumed.
3871 ColonProt.restore();
3872 Result = ParseCastExpression(AnyCastExpr,
3873 false/*isAddressofOperand*/,
3874 NotCastExpr,
3875 // type-id has priority.
3876 IsTypeCast);
3877 }
3878
3879 // If we parsed a cast-expression, it's really a type-id, otherwise it's
3880 // an expression.
3881 ParseAs = NotCastExpr ? SimpleExpr : CastExpr;
3882 }
3883
3884 // Create a fake EOF to mark end of Toks buffer.
3885 Token AttrEnd;
3886 AttrEnd.startToken();
3887 AttrEnd.setKind(tok::eof);
3888 AttrEnd.setLocation(Tok.getLocation());
3889 AttrEnd.setEofData(Toks.data());
3890 Toks.push_back(AttrEnd);
3891
3892 // The current token should go after the cached tokens.
3893 Toks.push_back(Tok);
3894 // Re-enter the stored parenthesized tokens into the token stream, so we may
3895 // parse them now.
3896 PP.EnterTokenStream(Toks, /*DisableMacroExpansion*/ true,
3897 /*IsReinject*/ true);
3898 // Drop the current token and bring the first cached one. It's the same token
3899 // as when we entered this function.
3900 ConsumeAnyToken();
3901
3902 if (ParseAs >= CompoundLiteral) {
3903 // Parse the type declarator.
3904 DeclSpec DS(AttrFactory);
3905 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeName);
3906 {
3907 ColonProtectionRAIIObject InnerColonProtection(*this);
3908 ParseSpecifierQualifierList(DS);
3909 ParseDeclarator(DeclaratorInfo);
3910 }
3911
3912 // Match the ')'.
3913 Tracker.consumeClose();
3914 ColonProt.restore();
3915
3916 // Consume EOF marker for Toks buffer.
3917 assert(Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData())((Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData
()) ? static_cast<void> (0) : __assert_fail ("Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData()"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Parse/ParseExprCXX.cpp"
, 3917, __PRETTY_FUNCTION__))
;
3918 ConsumeAnyToken();
3919
3920 if (ParseAs == CompoundLiteral) {
3921 ExprType = CompoundLiteral;
3922 if (DeclaratorInfo.isInvalidType())
3923 return ExprError();
3924
3925 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
3926 return ParseCompoundLiteralExpression(Ty.get(),
3927 Tracker.getOpenLocation(),
3928 Tracker.getCloseLocation());
3929 }
3930
3931 // We parsed '(' type-id ')' and the thing after it wasn't a '{'.
3932 assert(ParseAs == CastExpr)((ParseAs == CastExpr) ? static_cast<void> (0) : __assert_fail
("ParseAs == CastExpr", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Parse/ParseExprCXX.cpp"
, 3932, __PRETTY_FUNCTION__))
;
3933
3934 if (DeclaratorInfo.isInvalidType())
3935 return ExprError();
3936
3937 // Result is what ParseCastExpression returned earlier.
3938 if (!Result.isInvalid())
3939 Result = Actions.ActOnCastExpr(getCurScope(), Tracker.getOpenLocation(),
3940 DeclaratorInfo, CastTy,
3941 Tracker.getCloseLocation(), Result.get());
3942 return Result;
3943 }
3944
3945 // Not a compound literal, and not followed by a cast-expression.
3946 assert(ParseAs == SimpleExpr)((ParseAs == SimpleExpr) ? static_cast<void> (0) : __assert_fail
("ParseAs == SimpleExpr", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Parse/ParseExprCXX.cpp"
, 3946, __PRETTY_FUNCTION__))
;
3947
3948 ExprType = SimpleExpr;
3949 Result = ParseExpression();
3950 if (!Result.isInvalid() && Tok.is(tok::r_paren))
3951 Result = Actions.ActOnParenExpr(Tracker.getOpenLocation(),
3952 Tok.getLocation(), Result.get());
3953
3954 // Match the ')'.
3955 if (Result.isInvalid()) {
3956 while (Tok.isNot(tok::eof))
3957 ConsumeAnyToken();
3958 assert(Tok.getEofData() == AttrEnd.getEofData())((Tok.getEofData() == AttrEnd.getEofData()) ? static_cast<
void> (0) : __assert_fail ("Tok.getEofData() == AttrEnd.getEofData()"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Parse/ParseExprCXX.cpp"
, 3958, __PRETTY_FUNCTION__))
;
3959 ConsumeAnyToken();
3960 return ExprError();
3961 }
3962
3963 Tracker.consumeClose();
3964 // Consume EOF marker for Toks buffer.
3965 assert(Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData())((Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData
()) ? static_cast<void> (0) : __assert_fail ("Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData()"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Parse/ParseExprCXX.cpp"
, 3965, __PRETTY_FUNCTION__))
;
3966 ConsumeAnyToken();
3967 return Result;
3968}
3969
3970/// Parse a __builtin_bit_cast(T, E).
3971ExprResult Parser::ParseBuiltinBitCast() {
3972 SourceLocation KWLoc = ConsumeToken();
3973
3974 BalancedDelimiterTracker T(*this, tok::l_paren);
3975 if (T.expectAndConsume(diag::err_expected_lparen_after, "__builtin_bit_cast"))
3976 return ExprError();
3977
3978 // Parse the common declaration-specifiers piece.
3979 DeclSpec DS(AttrFactory);
3980 ParseSpecifierQualifierList(DS);
3981
3982 // Parse the abstract-declarator, if present.
3983 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeName);
3984 ParseDeclarator(DeclaratorInfo);
3985
3986 if (ExpectAndConsume(tok::comma)) {
3987 Diag(Tok.getLocation(), diag::err_expected) << tok::comma;
3988 SkipUntil(tok::r_paren, StopAtSemi);
3989 return ExprError();
3990 }
3991
3992 ExprResult Operand = ParseExpression();
3993
3994 if (T.consumeClose())
3995 return ExprError();
3996
3997 if (Operand.isInvalid() || DeclaratorInfo.isInvalidType())
3998 return ExprError();
3999
4000 return Actions.ActOnBuiltinBitCastExpr(KWLoc, DeclaratorInfo, Operand,
4001 T.getCloseLocation());
4002}

/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/Lex/Token.h

1//===--- Token.h - Token interface ------------------------------*- 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//
9// This file defines the Token interface.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_LEX_TOKEN_H
14#define LLVM_CLANG_LEX_TOKEN_H
15
16#include "clang/Basic/SourceLocation.h"
17#include "clang/Basic/TokenKinds.h"
18#include "llvm/ADT/StringRef.h"
19#include <cassert>
20
21namespace clang {
22
23class IdentifierInfo;
24
25/// Token - This structure provides full information about a lexed token.
26/// It is not intended to be space efficient, it is intended to return as much
27/// information as possible about each returned token. This is expected to be
28/// compressed into a smaller form if memory footprint is important.
29///
30/// The parser can create a special "annotation token" representing a stream of
31/// tokens that were parsed and semantically resolved, e.g.: "foo::MyClass<int>"
32/// can be represented by a single typename annotation token that carries
33/// information about the SourceRange of the tokens and the type object.
34class Token {
35 /// The location of the token. This is actually a SourceLocation.
36 unsigned Loc;
37
38 // Conceptually these next two fields could be in a union. However, this
39 // causes gcc 4.2 to pessimize LexTokenInternal, a very performance critical
40 // routine. Keeping as separate members with casts until a more beautiful fix
41 // presents itself.
42
43 /// UintData - This holds either the length of the token text, when
44 /// a normal token, or the end of the SourceRange when an annotation
45 /// token.
46 unsigned UintData;
47
48 /// PtrData - This is a union of four different pointer types, which depends
49 /// on what type of token this is:
50 /// Identifiers, keywords, etc:
51 /// This is an IdentifierInfo*, which contains the uniqued identifier
52 /// spelling.
53 /// Literals: isLiteral() returns true.
54 /// This is a pointer to the start of the token in a text buffer, which
55 /// may be dirty (have trigraphs / escaped newlines).
56 /// Annotations (resolved type names, C++ scopes, etc): isAnnotation().
57 /// This is a pointer to sema-specific data for the annotation token.
58 /// Eof:
59 // This is a pointer to a Decl.
60 /// Other:
61 /// This is null.
62 void *PtrData;
63
64 /// Kind - The actual flavor of token this is.
65 tok::TokenKind Kind;
66
67 /// Flags - Bits we track about this token, members of the TokenFlags enum.
68 unsigned short Flags;
69
70public:
71 // Various flags set per token:
72 enum TokenFlags {
73 StartOfLine = 0x01, // At start of line or only after whitespace
74 // (considering the line after macro expansion).
75 LeadingSpace = 0x02, // Whitespace exists before this token (considering
76 // whitespace after macro expansion).
77 DisableExpand = 0x04, // This identifier may never be macro expanded.
78 NeedsCleaning = 0x08, // Contained an escaped newline or trigraph.
79 LeadingEmptyMacro = 0x10, // Empty macro exists before this token.
80 HasUDSuffix = 0x20, // This string or character literal has a ud-suffix.
81 HasUCN = 0x40, // This identifier contains a UCN.
82 IgnoredComma = 0x80, // This comma is not a macro argument separator (MS).
83 StringifiedInMacro = 0x100, // This string or character literal is formed by
84 // macro stringizing or charizing operator.
85 CommaAfterElided = 0x200, // The comma following this token was elided (MS).
86 IsEditorPlaceholder = 0x400, // This identifier is a placeholder.
87 IsReinjected = 0x800, // A phase 4 token that was produced before and
88 // re-added, e.g. via EnterTokenStream. Annotation
89 // tokens are *not* reinjected.
90 };
91
92 tok::TokenKind getKind() const { return Kind; }
93 void setKind(tok::TokenKind K) { Kind = K; }
94
95 /// is/isNot - Predicates to check if this token is a specific kind, as in
96 /// "if (Tok.is(tok::l_brace)) {...}".
97 bool is(tok::TokenKind K) const { return Kind == K; }
9
Assuming 'K' is not equal to field 'Kind'
10
Returning zero, which participates in a condition later
98 bool isNot(tok::TokenKind K) const { return Kind != K; }
99 bool isOneOf(tok::TokenKind K1, tok::TokenKind K2) const {
100 return is(K1) || is(K2);
101 }
102 template <typename... Ts>
103 bool isOneOf(tok::TokenKind K1, tok::TokenKind K2, Ts... Ks) const {
104 return is(K1) || isOneOf(K2, Ks...);
105 }
106
107 /// Return true if this is a raw identifier (when lexing
108 /// in raw mode) or a non-keyword identifier (when lexing in non-raw mode).
109 bool isAnyIdentifier() const {
110 return tok::isAnyIdentifier(getKind());
111 }
112
113 /// Return true if this is a "literal", like a numeric
114 /// constant, string, etc.
115 bool isLiteral() const {
116 return tok::isLiteral(getKind());
117 }
118
119 /// Return true if this is any of tok::annot_* kind tokens.
120 bool isAnnotation() const {
121 return tok::isAnnotation(getKind());
122 }
123
124 /// Return a source location identifier for the specified
125 /// offset in the current file.
126 SourceLocation getLocation() const {
127 return SourceLocation::getFromRawEncoding(Loc);
128 }
129 unsigned getLength() const {
130 assert(!isAnnotation() && "Annotation tokens have no length field")((!isAnnotation() && "Annotation tokens have no length field"
) ? static_cast<void> (0) : __assert_fail ("!isAnnotation() && \"Annotation tokens have no length field\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/Lex/Token.h"
, 130, __PRETTY_FUNCTION__))
;
131 return UintData;
132 }
133
134 void setLocation(SourceLocation L) { Loc = L.getRawEncoding(); }
135 void setLength(unsigned Len) {
136 assert(!isAnnotation() && "Annotation tokens have no length field")((!isAnnotation() && "Annotation tokens have no length field"
) ? static_cast<void> (0) : __assert_fail ("!isAnnotation() && \"Annotation tokens have no length field\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/Lex/Token.h"
, 136, __PRETTY_FUNCTION__))
;
137 UintData = Len;
138 }
139
140 SourceLocation getAnnotationEndLoc() const {
141 assert(isAnnotation() && "Used AnnotEndLocID on non-annotation token")((isAnnotation() && "Used AnnotEndLocID on non-annotation token"
) ? static_cast<void> (0) : __assert_fail ("isAnnotation() && \"Used AnnotEndLocID on non-annotation token\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/Lex/Token.h"
, 141, __PRETTY_FUNCTION__))
;
142 return SourceLocation::getFromRawEncoding(UintData ? UintData : Loc);
143 }
144 void setAnnotationEndLoc(SourceLocation L) {
145 assert(isAnnotation() && "Used AnnotEndLocID on non-annotation token")((isAnnotation() && "Used AnnotEndLocID on non-annotation token"
) ? static_cast<void> (0) : __assert_fail ("isAnnotation() && \"Used AnnotEndLocID on non-annotation token\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/Lex/Token.h"
, 145, __PRETTY_FUNCTION__))
;
146 UintData = L.getRawEncoding();
147 }
148
149 SourceLocation getLastLoc() const {
150 return isAnnotation() ? getAnnotationEndLoc() : getLocation();
151 }
152
153 SourceLocation getEndLoc() const {
154 return isAnnotation() ? getAnnotationEndLoc()
155 : getLocation().getLocWithOffset(getLength());
156 }
157
158 /// SourceRange of the group of tokens that this annotation token
159 /// represents.
160 SourceRange getAnnotationRange() const {
161 return SourceRange(getLocation(), getAnnotationEndLoc());
162 }
163 void setAnnotationRange(SourceRange R) {
164 setLocation(R.getBegin());
165 setAnnotationEndLoc(R.getEnd());
166 }
167
168 const char *getName() const { return tok::getTokenName(Kind); }
169
170 /// Reset all flags to cleared.
171 void startToken() {
172 Kind = tok::unknown;
173 Flags = 0;
174 PtrData = nullptr;
175 UintData = 0;
176 Loc = SourceLocation().getRawEncoding();
177 }
178
179 IdentifierInfo *getIdentifierInfo() const {
180 assert(isNot(tok::raw_identifier) &&((isNot(tok::raw_identifier) && "getIdentifierInfo() on a tok::raw_identifier token!"
) ? static_cast<void> (0) : __assert_fail ("isNot(tok::raw_identifier) && \"getIdentifierInfo() on a tok::raw_identifier token!\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/Lex/Token.h"
, 181, __PRETTY_FUNCTION__))
181 "getIdentifierInfo() on a tok::raw_identifier token!")((isNot(tok::raw_identifier) && "getIdentifierInfo() on a tok::raw_identifier token!"
) ? static_cast<void> (0) : __assert_fail ("isNot(tok::raw_identifier) && \"getIdentifierInfo() on a tok::raw_identifier token!\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/Lex/Token.h"
, 181, __PRETTY_FUNCTION__))
;
182 assert(!isAnnotation() &&((!isAnnotation() && "getIdentifierInfo() on an annotation token!"
) ? static_cast<void> (0) : __assert_fail ("!isAnnotation() && \"getIdentifierInfo() on an annotation token!\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/Lex/Token.h"
, 183, __PRETTY_FUNCTION__))
183 "getIdentifierInfo() on an annotation token!")((!isAnnotation() && "getIdentifierInfo() on an annotation token!"
) ? static_cast<void> (0) : __assert_fail ("!isAnnotation() && \"getIdentifierInfo() on an annotation token!\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/Lex/Token.h"
, 183, __PRETTY_FUNCTION__))
;
184 if (isLiteral()) return nullptr;
185 if (is(tok::eof)) return nullptr;
186 return (IdentifierInfo*) PtrData;
187 }
188 void setIdentifierInfo(IdentifierInfo *II) {
189 PtrData = (void*) II;
190 }
191
192 const void *getEofData() const {
193 assert(is(tok::eof))((is(tok::eof)) ? static_cast<void> (0) : __assert_fail
("is(tok::eof)", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/Lex/Token.h"
, 193, __PRETTY_FUNCTION__))
;
194 return reinterpret_cast<const void *>(PtrData);
195 }
196 void setEofData(const void *D) {
197 assert(is(tok::eof))((is(tok::eof)) ? static_cast<void> (0) : __assert_fail
("is(tok::eof)", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/Lex/Token.h"
, 197, __PRETTY_FUNCTION__))
;
198 assert(!PtrData)((!PtrData) ? static_cast<void> (0) : __assert_fail ("!PtrData"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/Lex/Token.h"
, 198, __PRETTY_FUNCTION__))
;
199 PtrData = const_cast<void *>(D);
200 }
201
202 /// getRawIdentifier - For a raw identifier token (i.e., an identifier
203 /// lexed in raw mode), returns a reference to the text substring in the
204 /// buffer if known.
205 StringRef getRawIdentifier() const {
206 assert(is(tok::raw_identifier))((is(tok::raw_identifier)) ? static_cast<void> (0) : __assert_fail
("is(tok::raw_identifier)", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/Lex/Token.h"
, 206, __PRETTY_FUNCTION__))
;
207 return StringRef(reinterpret_cast<const char *>(PtrData), getLength());
208 }
209 void setRawIdentifierData(const char *Ptr) {
210 assert(is(tok::raw_identifier))((is(tok::raw_identifier)) ? static_cast<void> (0) : __assert_fail
("is(tok::raw_identifier)", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/Lex/Token.h"
, 210, __PRETTY_FUNCTION__))
;
211 PtrData = const_cast<char*>(Ptr);
212 }
213
214 /// getLiteralData - For a literal token (numeric constant, string, etc), this
215 /// returns a pointer to the start of it in the text buffer if known, null
216 /// otherwise.
217 const char *getLiteralData() const {
218 assert(isLiteral() && "Cannot get literal data of non-literal")((isLiteral() && "Cannot get literal data of non-literal"
) ? static_cast<void> (0) : __assert_fail ("isLiteral() && \"Cannot get literal data of non-literal\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/Lex/Token.h"
, 218, __PRETTY_FUNCTION__))
;
219 return reinterpret_cast<const char*>(PtrData);
220 }
221 void setLiteralData(const char *Ptr) {
222 assert(isLiteral() && "Cannot set literal data of non-literal")((isLiteral() && "Cannot set literal data of non-literal"
) ? static_cast<void> (0) : __assert_fail ("isLiteral() && \"Cannot set literal data of non-literal\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/Lex/Token.h"
, 222, __PRETTY_FUNCTION__))
;
223 PtrData = const_cast<char*>(Ptr);
224 }
225
226 void *getAnnotationValue() const {
227 assert(isAnnotation() && "Used AnnotVal on non-annotation token")((isAnnotation() && "Used AnnotVal on non-annotation token"
) ? static_cast<void> (0) : __assert_fail ("isAnnotation() && \"Used AnnotVal on non-annotation token\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/Lex/Token.h"
, 227, __PRETTY_FUNCTION__))
;
228 return PtrData;
229 }
230 void setAnnotationValue(void *val) {
231 assert(isAnnotation() && "Used AnnotVal on non-annotation token")((isAnnotation() && "Used AnnotVal on non-annotation token"
) ? static_cast<void> (0) : __assert_fail ("isAnnotation() && \"Used AnnotVal on non-annotation token\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/Lex/Token.h"
, 231, __PRETTY_FUNCTION__))
;
232 PtrData = val;
233 }
234
235 /// Set the specified flag.
236 void setFlag(TokenFlags Flag) {
237 Flags |= Flag;
238 }
239
240 /// Get the specified flag.
241 bool getFlag(TokenFlags Flag) const {
242 return (Flags & Flag) != 0;
243 }
244
245 /// Unset the specified flag.
246 void clearFlag(TokenFlags Flag) {
247 Flags &= ~Flag;
248 }
249
250 /// Return the internal represtation of the flags.
251 ///
252 /// This is only intended for low-level operations such as writing tokens to
253 /// disk.
254 unsigned getFlags() const {
255 return Flags;
256 }
257
258 /// Set a flag to either true or false.
259 void setFlagValue(TokenFlags Flag, bool Val) {
260 if (Val)
261 setFlag(Flag);
262 else
263 clearFlag(Flag);
264 }
265
266 /// isAtStartOfLine - Return true if this token is at the start of a line.
267 ///
268 bool isAtStartOfLine() const { return getFlag(StartOfLine); }
269
270 /// Return true if this token has whitespace before it.
271 ///
272 bool hasLeadingSpace() const { return getFlag(LeadingSpace); }
273
274 /// Return true if this identifier token should never
275 /// be expanded in the future, due to C99 6.10.3.4p2.
276 bool isExpandDisabled() const { return getFlag(DisableExpand); }
277
278 /// Return true if we have an ObjC keyword identifier.
279 bool isObjCAtKeyword(tok::ObjCKeywordKind objcKey) const;
280
281 /// Return the ObjC keyword kind.
282 tok::ObjCKeywordKind getObjCKeywordID() const;
283
284 /// Return true if this token has trigraphs or escaped newlines in it.
285 bool needsCleaning() const { return getFlag(NeedsCleaning); }
286
287 /// Return true if this token has an empty macro before it.
288 ///
289 bool hasLeadingEmptyMacro() const { return getFlag(LeadingEmptyMacro); }
290
291 /// Return true if this token is a string or character literal which
292 /// has a ud-suffix.
293 bool hasUDSuffix() const { return getFlag(HasUDSuffix); }
294
295 /// Returns true if this token contains a universal character name.
296 bool hasUCN() const { return getFlag(HasUCN); }
297
298 /// Returns true if this token is formed by macro by stringizing or charizing
299 /// operator.
300 bool stringifiedInMacro() const { return getFlag(StringifiedInMacro); }
301
302 /// Returns true if the comma after this token was elided.
303 bool commaAfterElided() const { return getFlag(CommaAfterElided); }
304
305 /// Returns true if this token is an editor placeholder.
306 ///
307 /// Editor placeholders are produced by the code-completion engine and are
308 /// represented as characters between '<#' and '#>' in the source code. The
309 /// lexer uses identifier tokens to represent placeholders.
310 bool isEditorPlaceholder() const { return getFlag(IsEditorPlaceholder); }
311};
312
313/// Information about the conditional stack (\#if directives)
314/// currently active.
315struct PPConditionalInfo {
316 /// Location where the conditional started.
317 SourceLocation IfLoc;
318
319 /// True if this was contained in a skipping directive, e.g.,
320 /// in a "\#if 0" block.
321 bool WasSkipping;
322
323 /// True if we have emitted tokens already, and now we're in
324 /// an \#else block or something. Only useful in Skipping blocks.
325 bool FoundNonSkip;
326
327 /// True if we've seen a \#else in this block. If so,
328 /// \#elif/\#else directives are not allowed.
329 bool FoundElse;
330};
331
332} // end namespace clang
333
334#endif // LLVM_CLANG_LEX_TOKEN_H