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