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