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