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 IdentifierInfo **LastII, bool OnlyNamespace, bool InUsingDeclaration) {
161 assert(getLangOpts().CPlusPlus &&
162 "Call sites of this function should be guarded by checking for C++");
163
164 if (Tok.is(tok::annot_cxxscope)) {
165 assert(!LastII && "want last identifier but have already annotated scope");
166 assert(!MayBePseudoDestructor && "unexpected annot_cxxscope");
168 Tok.getAnnotationRange(),
169 SS);
170 ConsumeAnnotationToken();
171 return false;
172 }
173
174 // Has to happen before any "return false"s in this function.
175 bool CheckForDestructor = false;
176 if (MayBePseudoDestructor && *MayBePseudoDestructor) {
177 CheckForDestructor = true;
178 *MayBePseudoDestructor = false;
179 }
180
181 if (LastII)
182 *LastII = nullptr;
183
184 bool HasScopeSpecifier = false;
185
186 if (Tok.is(tok::coloncolon)) {
187 // ::new and ::delete aren't nested-name-specifiers.
188 tok::TokenKind NextKind = NextToken().getKind();
189 if (NextKind == tok::kw_new || NextKind == tok::kw_delete)
190 return false;
191
192 if (NextKind == tok::l_brace) {
193 // It is invalid to have :: {, consume the scope qualifier and pretend
194 // like we never saw it.
195 Diag(ConsumeToken(), diag::err_expected) << tok::identifier;
196 } else {
197 // '::' - Global scope qualifier.
199 return true;
200
201 HasScopeSpecifier = true;
202 }
203 }
204
205 if (Tok.is(tok::kw___super)) {
206 SourceLocation SuperLoc = ConsumeToken();
207 if (!Tok.is(tok::coloncolon)) {
208 Diag(Tok.getLocation(), diag::err_expected_coloncolon_after_super);
209 return true;
210 }
211
212 return Actions.ActOnSuperScopeSpecifier(SuperLoc, ConsumeToken(), SS);
213 }
214
215 if (!HasScopeSpecifier &&
216 Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)) {
217 DeclSpec DS(AttrFactory);
218 SourceLocation DeclLoc = Tok.getLocation();
219 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
220
221 SourceLocation CCLoc;
222 // Work around a standard defect: 'decltype(auto)::' is not a
223 // nested-name-specifier.
224 if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto ||
225 !TryConsumeToken(tok::coloncolon, CCLoc)) {
226 AnnotateExistingDecltypeSpecifier(DS, DeclLoc, EndLoc);
227 return false;
228 }
229
230 if (Actions.ActOnCXXNestedNameSpecifierDecltype(SS, DS, CCLoc))
231 SS.SetInvalid(SourceRange(DeclLoc, CCLoc));
232
233 HasScopeSpecifier = true;
234 }
235
236 else if (!HasScopeSpecifier && Tok.is(tok::identifier) &&
237 GetLookAheadToken(1).is(tok::ellipsis) &&
238 GetLookAheadToken(2).is(tok::l_square)) {
239 SourceLocation Start = Tok.getLocation();
240 DeclSpec DS(AttrFactory);
241 SourceLocation CCLoc;
242 SourceLocation EndLoc = ParsePackIndexingType(DS);
243 if (DS.getTypeSpecType() == DeclSpec::TST_error)
244 return false;
245
247 DS.getRepAsType().get(), DS.getPackIndexingExpr(), DS.getBeginLoc(),
248 DS.getEllipsisLoc());
249
250 if (Type.isNull())
251 return false;
252
253 if (!TryConsumeToken(tok::coloncolon, CCLoc)) {
254 AnnotateExistingIndexedTypeNamePack(ParsedType::make(Type), Start,
255 EndLoc);
256 return false;
257 }
258 if (Actions.ActOnCXXNestedNameSpecifierIndexedPack(SS, DS, CCLoc,
259 std::move(Type)))
260 SS.SetInvalid(SourceRange(Start, CCLoc));
261 HasScopeSpecifier = true;
262 }
263
264 // Preferred type might change when parsing qualifiers, we need the original.
265 auto SavedType = PreferredType;
266 while (true) {
267 if (HasScopeSpecifier) {
268 if (Tok.is(tok::code_completion)) {
269 cutOffParsing();
270 // Code completion for a nested-name-specifier, where the code
271 // completion token follows the '::'.
272 Actions.CodeCompleteQualifiedId(getCurScope(), SS, EnteringContext,
273 InUsingDeclaration, ObjectType.get(),
274 SavedType.get(SS.getBeginLoc()));
275 // Include code completion token into the range of the scope otherwise
276 // when we try to annotate the scope tokens the dangling code completion
277 // token will cause assertion in
278 // Preprocessor::AnnotatePreviousCachedTokens.
279 SS.setEndLoc(Tok.getLocation());
280 return true;
281 }
282
283 // C++ [basic.lookup.classref]p5:
284 // If the qualified-id has the form
285 //
286 // ::class-name-or-namespace-name::...
287 //
288 // the class-name-or-namespace-name is looked up in global scope as a
289 // class-name or namespace-name.
290 //
291 // To implement this, we clear out the object type as soon as we've
292 // seen a leading '::' or part of a nested-name-specifier.
293 ObjectType = nullptr;
294 }
295
296 // nested-name-specifier:
297 // nested-name-specifier 'template'[opt] simple-template-id '::'
298
299 // Parse the optional 'template' keyword, then make sure we have
300 // 'identifier <' after it.
301 if (Tok.is(tok::kw_template)) {
302 // If we don't have a scope specifier or an object type, this isn't a
303 // nested-name-specifier, since they aren't allowed to start with
304 // 'template'.
305 if (!HasScopeSpecifier && !ObjectType)
306 break;
307
308 TentativeParsingAction TPA(*this);
309 SourceLocation TemplateKWLoc = ConsumeToken();
310
312 if (Tok.is(tok::identifier)) {
313 // Consume the identifier.
314 TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
315 ConsumeToken();
316 } else if (Tok.is(tok::kw_operator)) {
317 // We don't need to actually parse the unqualified-id in this case,
318 // because a simple-template-id cannot start with 'operator', but
319 // go ahead and parse it anyway for consistency with the case where
320 // we already annotated the template-id.
321 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType,
322 TemplateName)) {
323 TPA.Commit();
324 break;
325 }
326
329 Diag(TemplateName.getSourceRange().getBegin(),
330 diag::err_id_after_template_in_nested_name_spec)
331 << TemplateName.getSourceRange();
332 TPA.Commit();
333 break;
334 }
335 } else {
336 TPA.Revert();
337 break;
338 }
339
340 // If the next token is not '<', we have a qualified-id that refers
341 // to a template name, such as T::template apply, but is not a
342 // template-id.
343 if (Tok.isNot(tok::less)) {
344 TPA.Revert();
345 break;
346 }
347
348 // Commit to parsing the template-id.
349 TPA.Commit();
350 TemplateTy Template;
352 getCurScope(), SS, TemplateKWLoc, TemplateName, ObjectType,
353 EnteringContext, Template, /*AllowInjectedClassName*/ true);
354 if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateKWLoc,
355 TemplateName, false))
356 return true;
357
358 continue;
359 }
360
361 if (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) {
362 // We have
363 //
364 // template-id '::'
365 //
366 // So we need to check whether the template-id is a simple-template-id of
367 // the right kind (it should name a type or be dependent), and then
368 // convert it into a type within the nested-name-specifier.
369 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
370 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde)) {
371 *MayBePseudoDestructor = true;
372 return false;
373 }
374
375 if (LastII)
376 *LastII = TemplateId->Name;
377
378 // Consume the template-id token.
379 ConsumeAnnotationToken();
380
381 assert(Tok.is(tok::coloncolon) && "NextToken() not working properly!");
383
384 HasScopeSpecifier = true;
385
386 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
387 TemplateId->NumArgs);
388
389 if (TemplateId->isInvalid() ||
391 SS,
392 TemplateId->TemplateKWLoc,
393 TemplateId->Template,
394 TemplateId->TemplateNameLoc,
395 TemplateId->LAngleLoc,
396 TemplateArgsPtr,
397 TemplateId->RAngleLoc,
398 CCLoc,
399 EnteringContext)) {
400 SourceLocation StartLoc
401 = SS.getBeginLoc().isValid()? SS.getBeginLoc()
402 : TemplateId->TemplateNameLoc;
403 SS.SetInvalid(SourceRange(StartLoc, CCLoc));
404 }
405
406 continue;
407 }
408
409 // The rest of the nested-name-specifier possibilities start with
410 // tok::identifier.
411 if (Tok.isNot(tok::identifier))
412 break;
413
415
416 // nested-name-specifier:
417 // type-name '::'
418 // namespace-name '::'
419 // nested-name-specifier identifier '::'
420 Token Next = NextToken();
421 Sema::NestedNameSpecInfo IdInfo(&II, Tok.getLocation(), Next.getLocation(),
422 ObjectType);
423
424 // If we get foo:bar, this is almost certainly a typo for foo::bar. Recover
425 // and emit a fixit hint for it.
426 if (Next.is(tok::colon) && !ColonIsSacred) {
427 if (Actions.IsInvalidUnlessNestedName(getCurScope(), SS, IdInfo,
428 EnteringContext) &&
429 // If the token after the colon isn't an identifier, it's still an
430 // error, but they probably meant something else strange so don't
431 // recover like this.
432 PP.LookAhead(1).is(tok::identifier)) {
433 Diag(Next, diag::err_unexpected_colon_in_nested_name_spec)
434 << FixItHint::CreateReplacement(Next.getLocation(), "::");
435 // Recover as if the user wrote '::'.
436 Next.setKind(tok::coloncolon);
437 }
438 }
439
440 if (Next.is(tok::coloncolon) && GetLookAheadToken(2).is(tok::l_brace)) {
441 // It is invalid to have :: {, consume the scope qualifier and pretend
442 // like we never saw it.
443 Token Identifier = Tok; // Stash away the identifier.
444 ConsumeToken(); // Eat the identifier, current token is now '::'.
445 Diag(PP.getLocForEndOfToken(ConsumeToken()), diag::err_expected)
446 << tok::identifier;
447 UnconsumeToken(Identifier); // Stick the identifier back.
448 Next = NextToken(); // Point Next at the '{' token.
449 }
450
451 if (Next.is(tok::coloncolon)) {
452 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde)) {
453 *MayBePseudoDestructor = true;
454 return false;
455 }
456
457 if (ColonIsSacred) {
458 const Token &Next2 = GetLookAheadToken(2);
459 if (Next2.is(tok::kw_private) || Next2.is(tok::kw_protected) ||
460 Next2.is(tok::kw_public) || Next2.is(tok::kw_virtual)) {
461 Diag(Next2, diag::err_unexpected_token_in_nested_name_spec)
462 << Next2.getName()
463 << FixItHint::CreateReplacement(Next.getLocation(), ":");
464 Token ColonColon;
465 PP.Lex(ColonColon);
466 ColonColon.setKind(tok::colon);
467 PP.EnterToken(ColonColon, /*IsReinject*/ true);
468 break;
469 }
470 }
471
472 if (LastII)
473 *LastII = &II;
474
475 // We have an identifier followed by a '::'. Lookup this name
476 // as the name in a nested-name-specifier.
477 Token Identifier = Tok;
479 assert(Tok.isOneOf(tok::coloncolon, tok::colon) &&
480 "NextToken() not working properly!");
481 Token ColonColon = Tok;
483
484 bool IsCorrectedToColon = false;
485 bool *CorrectionFlagPtr = ColonIsSacred ? &IsCorrectedToColon : nullptr;
486 if (Actions.ActOnCXXNestedNameSpecifier(
487 getCurScope(), IdInfo, EnteringContext, SS, CorrectionFlagPtr,
488 OnlyNamespace)) {
489 // Identifier is not recognized as a nested name, but we can have
490 // mistyped '::' instead of ':'.
491 if (CorrectionFlagPtr && IsCorrectedToColon) {
492 ColonColon.setKind(tok::colon);
493 PP.EnterToken(Tok, /*IsReinject*/ true);
494 PP.EnterToken(ColonColon, /*IsReinject*/ true);
495 Tok = Identifier;
496 break;
497 }
498 SS.SetInvalid(SourceRange(IdLoc, CCLoc));
499 }
500 HasScopeSpecifier = true;
501 continue;
502 }
503
504 CheckForTemplateAndDigraph(Next, ObjectType, EnteringContext, II, SS);
505
506 // nested-name-specifier:
507 // type-name '<'
508 if (Next.is(tok::less)) {
509
510 TemplateTy Template;
512 TemplateName.setIdentifier(&II, Tok.getLocation());
513 bool MemberOfUnknownSpecialization;
514 if (TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
515 /*hasTemplateKeyword=*/false,
517 ObjectType,
518 EnteringContext,
519 Template,
520 MemberOfUnknownSpecialization)) {
521 // If lookup didn't find anything, we treat the name as a template-name
522 // anyway. C++20 requires this, and in prior language modes it improves
523 // error recovery. But before we commit to this, check that we actually
524 // have something that looks like a template-argument-list next.
525 if (!IsTypename && TNK == TNK_Undeclared_template &&
526 isTemplateArgumentList(1) == TPResult::False)
527 break;
528
529 // We have found a template name, so annotate this token
530 // with a template-id annotation. We do not permit the
531 // template-id to be translated into a type annotation,
532 // because some clients (e.g., the parsing of class template
533 // specializations) still want to see the original template-id
534 // token, and it might not be a type at all (e.g. a concept name in a
535 // type-constraint).
536 ConsumeToken();
537 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
538 TemplateName, false))
539 return true;
540 continue;
541 }
542
543 if (MemberOfUnknownSpecialization && (ObjectType || SS.isSet()) &&
544 (IsTypename || isTemplateArgumentList(1) == TPResult::True)) {
545 // If we had errors before, ObjectType can be dependent even without any
546 // templates. Do not report missing template keyword in that case.
547 if (!ObjectHadErrors) {
548 // We have something like t::getAs<T>, where getAs is a
549 // member of an unknown specialization. However, this will only
550 // parse correctly as a template, so suggest the keyword 'template'
551 // before 'getAs' and treat this as a dependent template name.
552 unsigned DiagID = diag::err_missing_dependent_template_keyword;
553 if (getLangOpts().MicrosoftExt)
554 DiagID = diag::warn_missing_dependent_template_keyword;
555
556 Diag(Tok.getLocation(), DiagID)
557 << II.getName()
558 << FixItHint::CreateInsertion(Tok.getLocation(), "template ");
559 }
560
561 SourceLocation TemplateNameLoc = ConsumeToken();
562
564 getCurScope(), SS, TemplateNameLoc, TemplateName, ObjectType,
565 EnteringContext, Template, /*AllowInjectedClassName*/ true);
566 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
567 TemplateName, false))
568 return true;
569
570 continue;
571 }
572 }
573
574 // We don't have any tokens that form the beginning of a
575 // nested-name-specifier, so we're done.
576 break;
577 }
578
579 // Even if we didn't see any pieces of a nested-name-specifier, we
580 // still check whether there is a tilde in this position, which
581 // indicates a potential pseudo-destructor.
582 if (CheckForDestructor && !HasScopeSpecifier && Tok.is(tok::tilde))
583 *MayBePseudoDestructor = true;
584
585 return false;
586}
587
588ExprResult Parser::tryParseCXXIdExpression(CXXScopeSpec &SS,
589 bool isAddressOfOperand,
590 Token &Replacement) {
591 ExprResult E;
592
593 // We may have already annotated this id-expression.
594 switch (Tok.getKind()) {
595 case tok::annot_non_type: {
596 NamedDecl *ND = getNonTypeAnnotation(Tok);
597 SourceLocation Loc = ConsumeAnnotationToken();
598 E = Actions.ActOnNameClassifiedAsNonType(getCurScope(), SS, ND, Loc, Tok);
599 break;
600 }
601
602 case tok::annot_non_type_dependent: {
603 IdentifierInfo *II = getIdentifierAnnotation(Tok);
604 SourceLocation Loc = ConsumeAnnotationToken();
605
606 // This is only the direct operand of an & operator if it is not
607 // followed by a postfix-expression suffix.
608 if (isAddressOfOperand && isPostfixExpressionSuffixStart())
609 isAddressOfOperand = false;
610
611 E = Actions.ActOnNameClassifiedAsDependentNonType(SS, II, Loc,
612 isAddressOfOperand);
613 break;
614 }
615
616 case tok::annot_non_type_undeclared: {
617 assert(SS.isEmpty() &&
618 "undeclared non-type annotation should be unqualified");
619 IdentifierInfo *II = getIdentifierAnnotation(Tok);
620 SourceLocation Loc = ConsumeAnnotationToken();
621 E = Actions.ActOnNameClassifiedAsUndeclaredNonType(II, Loc);
622 break;
623 }
624
625 default:
626 SourceLocation TemplateKWLoc;
627 UnqualifiedId Name;
628 if (ParseUnqualifiedId(SS, /*ObjectType=*/nullptr,
629 /*ObjectHadErrors=*/false,
630 /*EnteringContext=*/false,
631 /*AllowDestructorName=*/false,
632 /*AllowConstructorName=*/false,
633 /*AllowDeductionGuide=*/false, &TemplateKWLoc, Name))
634 return ExprError();
635
636 // This is only the direct operand of an & operator if it is not
637 // followed by a postfix-expression suffix.
638 if (isAddressOfOperand && isPostfixExpressionSuffixStart())
639 isAddressOfOperand = false;
640
641 E = Actions.ActOnIdExpression(
642 getCurScope(), SS, TemplateKWLoc, Name, Tok.is(tok::l_paren),
643 isAddressOfOperand, /*CCC=*/nullptr, /*IsInlineAsmIdentifier=*/false,
644 &Replacement);
645 break;
646 }
647
648 // Might be a pack index expression!
649 E = tryParseCXXPackIndexingExpression(E);
650
651 if (!E.isInvalid() && !E.isUnset() && Tok.is(tok::less))
652 checkPotentialAngleBracket(E);
653 return E;
654}
655
656ExprResult Parser::ParseCXXPackIndexingExpression(ExprResult PackIdExpression) {
657 assert(Tok.is(tok::ellipsis) && NextToken().is(tok::l_square) &&
658 "expected ...[");
659 SourceLocation EllipsisLoc = ConsumeToken();
660 BalancedDelimiterTracker T(*this, tok::l_square);
661 T.consumeOpen();
663 if (T.consumeClose() || IndexExpr.isInvalid())
664 return ExprError();
665 return Actions.ActOnPackIndexingExpr(getCurScope(), PackIdExpression.get(),
666 EllipsisLoc, T.getOpenLocation(),
667 IndexExpr.get(), T.getCloseLocation());
668}
669
671Parser::tryParseCXXPackIndexingExpression(ExprResult PackIdExpression) {
672 ExprResult E = PackIdExpression;
673 if (!PackIdExpression.isInvalid() && !PackIdExpression.isUnset() &&
674 Tok.is(tok::ellipsis) && NextToken().is(tok::l_square)) {
675 E = ParseCXXPackIndexingExpression(E);
676 }
677 return E;
678}
679
680/// ParseCXXIdExpression - Handle id-expression.
681///
682/// id-expression:
683/// unqualified-id
684/// qualified-id
685///
686/// qualified-id:
687/// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
688/// '::' identifier
689/// '::' operator-function-id
690/// '::' template-id
691///
692/// NOTE: The standard specifies that, for qualified-id, the parser does not
693/// expect:
694///
695/// '::' conversion-function-id
696/// '::' '~' class-name
697///
698/// This may cause a slight inconsistency on diagnostics:
699///
700/// class C {};
701/// namespace A {}
702/// void f() {
703/// :: A :: ~ C(); // Some Sema error about using destructor with a
704/// // namespace.
705/// :: ~ C(); // Some Parser error like 'unexpected ~'.
706/// }
707///
708/// We simplify the parser a bit and make it work like:
709///
710/// qualified-id:
711/// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
712/// '::' unqualified-id
713///
714/// That way Sema can handle and report similar errors for namespaces and the
715/// global scope.
716///
717/// The isAddressOfOperand parameter indicates that this id-expression is a
718/// direct operand of the address-of operator. This is, besides member contexts,
719/// the only place where a qualified-id naming a non-static class member may
720/// appear.
721///
722ExprResult Parser::ParseCXXIdExpression(bool isAddressOfOperand) {
723 // qualified-id:
724 // '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
725 // '::' unqualified-id
726 //
727 CXXScopeSpec SS;
728 ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
729 /*ObjectHasErrors=*/false,
730 /*EnteringContext=*/false);
731
732 Token Replacement;
734 tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
735 if (Result.isUnset()) {
736 // If the ExprResult is valid but null, then typo correction suggested a
737 // keyword replacement that needs to be reparsed.
738 UnconsumeToken(Replacement);
739 Result = tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
740 }
741 assert(!Result.isUnset() && "Typo correction suggested a keyword replacement "
742 "for a previous keyword suggestion");
743 return Result;
744}
745
746/// ParseLambdaExpression - Parse a C++11 lambda expression.
747///
748/// lambda-expression:
749/// lambda-introducer lambda-declarator compound-statement
750/// lambda-introducer '<' template-parameter-list '>'
751/// requires-clause[opt] lambda-declarator compound-statement
752///
753/// lambda-introducer:
754/// '[' lambda-capture[opt] ']'
755///
756/// lambda-capture:
757/// capture-default
758/// capture-list
759/// capture-default ',' capture-list
760///
761/// capture-default:
762/// '&'
763/// '='
764///
765/// capture-list:
766/// capture
767/// capture-list ',' capture
768///
769/// capture:
770/// simple-capture
771/// init-capture [C++1y]
772///
773/// simple-capture:
774/// identifier
775/// '&' identifier
776/// 'this'
777///
778/// init-capture: [C++1y]
779/// identifier initializer
780/// '&' identifier initializer
781///
782/// lambda-declarator:
783/// lambda-specifiers [C++23]
784/// '(' parameter-declaration-clause ')' lambda-specifiers
785/// requires-clause[opt]
786///
787/// lambda-specifiers:
788/// decl-specifier-seq[opt] noexcept-specifier[opt]
789/// attribute-specifier-seq[opt] trailing-return-type[opt]
790///
791ExprResult Parser::ParseLambdaExpression() {
792 // Parse lambda-introducer.
793 LambdaIntroducer Intro;
794 if (ParseLambdaIntroducer(Intro)) {
795 SkipUntil(tok::r_square, StopAtSemi);
796 SkipUntil(tok::l_brace, StopAtSemi);
797 SkipUntil(tok::r_brace, StopAtSemi);
798 return ExprError();
799 }
800
801 return ParseLambdaExpressionAfterIntroducer(Intro);
802}
803
804/// Use lookahead and potentially tentative parsing to determine if we are
805/// looking at a C++11 lambda expression, and parse it if we are.
806///
807/// If we are not looking at a lambda expression, returns ExprError().
808ExprResult Parser::TryParseLambdaExpression() {
809 assert(getLangOpts().CPlusPlus11
810 && 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, diag::warn_cxx98_compat_lambda);
1330
1331 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), LambdaBeginLoc,
1332 "lambda expression parsing");
1333
1334 // Parse lambda-declarator[opt].
1335 DeclSpec DS(AttrFactory);
1337 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1338
1339 ParseScope LambdaScope(this, Scope::LambdaScope | Scope::DeclScope |
1342
1343 Actions.PushLambdaScope();
1345
1346 ParsedAttributes Attributes(AttrFactory);
1347 if (getLangOpts().CUDA) {
1348 // In CUDA code, GNU attributes are allowed to appear immediately after the
1349 // "[...]", even if there is no "(...)" before the lambda body.
1350 //
1351 // Note that we support __noinline__ as a keyword in this mode and thus
1352 // it has to be separately handled.
1353 while (true) {
1354 if (Tok.is(tok::kw___noinline__)) {
1355 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
1356 SourceLocation AttrNameLoc = ConsumeToken();
1357 Attributes.addNew(AttrName, AttrNameLoc, /*ScopeName=*/nullptr,
1358 AttrNameLoc, /*ArgsUnion=*/nullptr,
1359 /*numArgs=*/0, tok::kw___noinline__);
1360 } else if (Tok.is(tok::kw___attribute))
1361 ParseGNUAttributes(Attributes, /*LatePArsedAttrList=*/nullptr, &D);
1362 else
1363 break;
1364 }
1365
1366 D.takeAttributes(Attributes);
1367 }
1368
1369 MultiParseScope TemplateParamScope(*this);
1370 if (Tok.is(tok::less)) {
1372 ? diag::warn_cxx17_compat_lambda_template_parameter_list
1373 : diag::ext_lambda_template_parameter_list);
1374
1375 SmallVector<NamedDecl*, 4> TemplateParams;
1376 SourceLocation LAngleLoc, RAngleLoc;
1377 if (ParseTemplateParameters(TemplateParamScope,
1378 CurTemplateDepthTracker.getDepth(),
1379 TemplateParams, LAngleLoc, RAngleLoc)) {
1380 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1381 return ExprError();
1382 }
1383
1384 if (TemplateParams.empty()) {
1385 Diag(RAngleLoc,
1386 diag::err_lambda_template_parameter_list_empty);
1387 } else {
1388 // We increase the template depth before recursing into a requires-clause.
1389 //
1390 // This depth is used for setting up a LambdaScopeInfo (in
1391 // Sema::RecordParsingTemplateParameterDepth), which is used later when
1392 // inventing template parameters in InventTemplateParameter.
1393 //
1394 // This way, abbreviated generic lambdas could have different template
1395 // depths, avoiding substitution into the wrong template parameters during
1396 // constraint satisfaction check.
1397 ++CurTemplateDepthTracker;
1398 ExprResult RequiresClause;
1399 if (TryConsumeToken(tok::kw_requires)) {
1400 RequiresClause =
1402 /*IsTrailingRequiresClause=*/false));
1403 if (RequiresClause.isInvalid())
1404 SkipUntil({tok::l_brace, tok::l_paren}, StopAtSemi | StopBeforeMatch);
1405 }
1406
1408 Intro, LAngleLoc, TemplateParams, RAngleLoc, RequiresClause);
1409 }
1410 }
1411
1412 // Implement WG21 P2173, which allows attributes immediately before the
1413 // lambda declarator and applies them to the corresponding function operator
1414 // or operator template declaration. We accept this as a conforming extension
1415 // in all language modes that support lambdas.
1416 if (isCXX11AttributeSpecifier()) {
1418 ? diag::warn_cxx20_compat_decl_attrs_on_lambda
1419 : diag::ext_decl_attrs_on_lambda)
1421 MaybeParseCXX11Attributes(D);
1422 }
1423
1424 TypeResult TrailingReturnType;
1425 SourceLocation TrailingReturnTypeLoc;
1426 SourceLocation LParenLoc, RParenLoc;
1427 SourceLocation DeclEndLoc;
1428 bool HasParentheses = false;
1429 bool HasSpecifiers = false;
1430 SourceLocation MutableLoc;
1431
1432 ParseScope Prototype(this, Scope::FunctionPrototypeScope |
1435
1436 // Parse parameter-declaration-clause.
1438 SourceLocation EllipsisLoc;
1439
1440 if (Tok.is(tok::l_paren)) {
1441 BalancedDelimiterTracker T(*this, tok::l_paren);
1442 T.consumeOpen();
1443 LParenLoc = T.getOpenLocation();
1444
1445 if (Tok.isNot(tok::r_paren)) {
1447 CurTemplateDepthTracker.getOriginalDepth());
1448
1449 ParseParameterDeclarationClause(D, Attributes, ParamInfo, EllipsisLoc);
1450 // For a generic lambda, each 'auto' within the parameter declaration
1451 // clause creates a template type parameter, so increment the depth.
1452 // If we've parsed any explicit template parameters, then the depth will
1453 // have already been incremented. So we make sure that at most a single
1454 // depth level is added.
1455 if (Actions.getCurGenericLambda())
1456 CurTemplateDepthTracker.setAddedDepth(1);
1457 }
1458
1459 T.consumeClose();
1460 DeclEndLoc = RParenLoc = T.getCloseLocation();
1461 HasParentheses = true;
1462 }
1463
1464 HasSpecifiers =
1465 Tok.isOneOf(tok::kw_mutable, tok::arrow, tok::kw___attribute,
1466 tok::kw_constexpr, tok::kw_consteval, tok::kw_static,
1467 tok::kw___private, tok::kw___global, tok::kw___local,
1468 tok::kw___constant, tok::kw___generic, tok::kw_groupshared,
1469 tok::kw_requires, tok::kw_noexcept) ||
1471 (Tok.is(tok::l_square) && NextToken().is(tok::l_square));
1472
1473 if (HasSpecifiers && !HasParentheses && !getLangOpts().CPlusPlus23) {
1474 // It's common to forget that one needs '()' before 'mutable', an
1475 // attribute specifier, the result type, or the requires clause. Deal with
1476 // this.
1477 Diag(Tok, diag::ext_lambda_missing_parens)
1478 << FixItHint::CreateInsertion(Tok.getLocation(), "() ");
1479 }
1480
1481 if (HasParentheses || HasSpecifiers) {
1482 // GNU-style attributes must be parsed before the mutable specifier to
1483 // be compatible with GCC. MSVC-style attributes must be parsed before
1484 // the mutable specifier to be compatible with MSVC.
1485 MaybeParseAttributes(PAKM_GNU | PAKM_Declspec, Attributes);
1486 // Parse mutable-opt and/or constexpr-opt or consteval-opt, and update
1487 // the DeclEndLoc.
1488 SourceLocation ConstexprLoc;
1489 SourceLocation ConstevalLoc;
1490 SourceLocation StaticLoc;
1491
1492 tryConsumeLambdaSpecifierToken(*this, MutableLoc, StaticLoc, ConstexprLoc,
1493 ConstevalLoc, DeclEndLoc);
1494
1495 DiagnoseStaticSpecifierRestrictions(*this, StaticLoc, MutableLoc, Intro);
1496
1497 addStaticToLambdaDeclSpecifier(*this, StaticLoc, DS);
1498 addConstexprToLambdaDeclSpecifier(*this, ConstexprLoc, DS);
1499 addConstevalToLambdaDeclSpecifier(*this, ConstevalLoc, DS);
1500 }
1501
1502 Actions.ActOnLambdaClosureParameters(getCurScope(), ParamInfo);
1503
1504 if (!HasParentheses)
1505 Actions.ActOnLambdaClosureQualifiers(Intro, MutableLoc);
1506
1507 if (HasSpecifiers || HasParentheses) {
1508 // Parse exception-specification[opt].
1510 SourceRange ESpecRange;
1511 SmallVector<ParsedType, 2> DynamicExceptions;
1512 SmallVector<SourceRange, 2> DynamicExceptionRanges;
1513 ExprResult NoexceptExpr;
1514 CachedTokens *ExceptionSpecTokens;
1515
1516 ESpecType = tryParseExceptionSpecification(
1517 /*Delayed=*/false, ESpecRange, DynamicExceptions,
1518 DynamicExceptionRanges, NoexceptExpr, ExceptionSpecTokens);
1519
1520 if (ESpecType != EST_None)
1521 DeclEndLoc = ESpecRange.getEnd();
1522
1523 // Parse attribute-specifier[opt].
1524 if (MaybeParseCXX11Attributes(Attributes))
1525 DeclEndLoc = Attributes.Range.getEnd();
1526
1527 // Parse OpenCL addr space attribute.
1528 if (Tok.isOneOf(tok::kw___private, tok::kw___global, tok::kw___local,
1529 tok::kw___constant, tok::kw___generic)) {
1530 ParseOpenCLQualifiers(DS.getAttributes());
1531 ConsumeToken();
1532 }
1533
1534 SourceLocation FunLocalRangeEnd = DeclEndLoc;
1535
1536 // Parse trailing-return-type[opt].
1537 if (Tok.is(tok::arrow)) {
1538 FunLocalRangeEnd = Tok.getLocation();
1540 TrailingReturnType =
1541 ParseTrailingReturnType(Range, /*MayBeFollowedByDirectInit=*/false);
1542 TrailingReturnTypeLoc = Range.getBegin();
1543 if (Range.getEnd().isValid())
1544 DeclEndLoc = Range.getEnd();
1545 }
1546
1547 SourceLocation NoLoc;
1548 D.AddTypeInfo(DeclaratorChunk::getFunction(
1549 /*HasProto=*/true,
1550 /*IsAmbiguous=*/false, LParenLoc, ParamInfo.data(),
1551 ParamInfo.size(), EllipsisLoc, RParenLoc,
1552 /*RefQualifierIsLvalueRef=*/true,
1553 /*RefQualifierLoc=*/NoLoc, MutableLoc, ESpecType,
1554 ESpecRange, DynamicExceptions.data(),
1555 DynamicExceptionRanges.data(), DynamicExceptions.size(),
1556 NoexceptExpr.isUsable() ? NoexceptExpr.get() : nullptr,
1557 /*ExceptionSpecTokens*/ nullptr,
1558 /*DeclsInPrototype=*/std::nullopt, LParenLoc,
1559 FunLocalRangeEnd, D, TrailingReturnType,
1560 TrailingReturnTypeLoc, &DS),
1561 std::move(Attributes), DeclEndLoc);
1562
1563 Actions.ActOnLambdaClosureQualifiers(Intro, MutableLoc);
1564
1565 if (HasParentheses && Tok.is(tok::kw_requires))
1566 ParseTrailingRequiresClause(D);
1567 }
1568
1569 // Emit a warning if we see a CUDA host/device/global attribute
1570 // after '(...)'. nvcc doesn't accept this.
1571 if (getLangOpts().CUDA) {
1572 for (const ParsedAttr &A : Attributes)
1573 if (A.getKind() == ParsedAttr::AT_CUDADevice ||
1574 A.getKind() == ParsedAttr::AT_CUDAHost ||
1575 A.getKind() == ParsedAttr::AT_CUDAGlobal)
1576 Diag(A.getLoc(), diag::warn_cuda_attr_lambda_position)
1577 << A.getAttrName()->getName();
1578 }
1579
1580 Prototype.Exit();
1581
1582 // FIXME: Rename BlockScope -> ClosureScope if we decide to continue using
1583 // it.
1584 unsigned ScopeFlags = Scope::BlockScope | Scope::FnScope | Scope::DeclScope |
1586 ParseScope BodyScope(this, ScopeFlags);
1587
1588 Actions.ActOnStartOfLambdaDefinition(Intro, D, DS);
1589
1590 // Parse compound-statement.
1591 if (!Tok.is(tok::l_brace)) {
1592 Diag(Tok, diag::err_expected_lambda_body);
1593 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1594 return ExprError();
1595 }
1596
1597 StmtResult Stmt(ParseCompoundStatementBody());
1598 BodyScope.Exit();
1599 TemplateParamScope.Exit();
1600 LambdaScope.Exit();
1601
1602 if (!Stmt.isInvalid() && !TrailingReturnType.isInvalid() &&
1603 !D.isInvalidType())
1604 return Actions.ActOnLambdaExpr(LambdaBeginLoc, Stmt.get());
1605
1606 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1607 return ExprError();
1608}
1609
1610/// ParseCXXCasts - This handles the various ways to cast expressions to another
1611/// type.
1612///
1613/// postfix-expression: [C++ 5.2p1]
1614/// 'dynamic_cast' '<' type-name '>' '(' expression ')'
1615/// 'static_cast' '<' type-name '>' '(' expression ')'
1616/// 'reinterpret_cast' '<' type-name '>' '(' expression ')'
1617/// 'const_cast' '<' type-name '>' '(' expression ')'
1618///
1619/// C++ for OpenCL s2.3.1 adds:
1620/// 'addrspace_cast' '<' type-name '>' '(' expression ')'
1621ExprResult Parser::ParseCXXCasts() {
1622 tok::TokenKind Kind = Tok.getKind();
1623 const char *CastName = nullptr; // For error messages
1624
1625 switch (Kind) {
1626 default: llvm_unreachable("Unknown C++ cast!");
1627 case tok::kw_addrspace_cast: CastName = "addrspace_cast"; break;
1628 case tok::kw_const_cast: CastName = "const_cast"; break;
1629 case tok::kw_dynamic_cast: CastName = "dynamic_cast"; break;
1630 case tok::kw_reinterpret_cast: CastName = "reinterpret_cast"; break;
1631 case tok::kw_static_cast: CastName = "static_cast"; break;
1632 }
1633
1634 SourceLocation OpLoc = ConsumeToken();
1635 SourceLocation LAngleBracketLoc = Tok.getLocation();
1636
1637 // Check for "<::" which is parsed as "[:". If found, fix token stream,
1638 // diagnose error, suggest fix, and recover parsing.
1639 if (Tok.is(tok::l_square) && Tok.getLength() == 2) {
1640 Token Next = NextToken();
1641 if (Next.is(tok::colon) && areTokensAdjacent(Tok, Next))
1642 FixDigraph(*this, PP, Tok, Next, Kind, /*AtDigraph*/true);
1643 }
1644
1645 if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName))
1646 return ExprError();
1647
1648 // Parse the common declaration-specifiers piece.
1649 DeclSpec DS(AttrFactory);
1650 ParseSpecifierQualifierList(DS, /*AccessSpecifier=*/AS_none,
1651 DeclSpecContext::DSC_type_specifier);
1652
1653 // Parse the abstract-declarator, if present.
1654 Declarator DeclaratorInfo(DS, ParsedAttributesView::none(),
1656 ParseDeclarator(DeclaratorInfo);
1657
1658 SourceLocation RAngleBracketLoc = Tok.getLocation();
1659
1660 if (ExpectAndConsume(tok::greater))
1661 return ExprError(Diag(LAngleBracketLoc, diag::note_matching) << tok::less);
1662
1663 BalancedDelimiterTracker T(*this, tok::l_paren);
1664
1665 if (T.expectAndConsume(diag::err_expected_lparen_after, CastName))
1666 return ExprError();
1667
1669
1670 // Match the ')'.
1671 T.consumeClose();
1672
1673 if (!Result.isInvalid() && !DeclaratorInfo.isInvalidType())
1674 Result = Actions.ActOnCXXNamedCast(OpLoc, Kind,
1675 LAngleBracketLoc, DeclaratorInfo,
1676 RAngleBracketLoc,
1677 T.getOpenLocation(), Result.get(),
1678 T.getCloseLocation());
1679
1680 return Result;
1681}
1682
1683/// ParseCXXTypeid - This handles the C++ typeid expression.
1684///
1685/// postfix-expression: [C++ 5.2p1]
1686/// 'typeid' '(' expression ')'
1687/// 'typeid' '(' type-id ')'
1688///
1689ExprResult Parser::ParseCXXTypeid() {
1690 assert(Tok.is(tok::kw_typeid) && "Not 'typeid'!");
1691
1692 SourceLocation OpLoc = ConsumeToken();
1693 SourceLocation LParenLoc, RParenLoc;
1694 BalancedDelimiterTracker T(*this, tok::l_paren);
1695
1696 // typeid expressions are always parenthesized.
1697 if (T.expectAndConsume(diag::err_expected_lparen_after, "typeid"))
1698 return ExprError();
1699 LParenLoc = T.getOpenLocation();
1700
1702
1703 // C++0x [expr.typeid]p3:
1704 // When typeid is applied to an expression other than an lvalue of a
1705 // polymorphic class type [...] The expression is an unevaluated
1706 // operand (Clause 5).
1707 //
1708 // Note that we can't tell whether the expression is an lvalue of a
1709 // polymorphic class type until after we've parsed the expression; we
1710 // speculatively assume the subexpression is unevaluated, and fix it up
1711 // later.
1712 //
1713 // We enter the unevaluated context before trying to determine whether we
1714 // have a type-id, because the tentative parse logic will try to resolve
1715 // names, and must treat them as unevaluated.
1719
1720 if (isTypeIdInParens()) {
1722
1723 // Match the ')'.
1724 T.consumeClose();
1725 RParenLoc = T.getCloseLocation();
1726 if (Ty.isInvalid() || RParenLoc.isInvalid())
1727 return ExprError();
1728
1729 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/true,
1730 Ty.get().getAsOpaquePtr(), RParenLoc);
1731 } else {
1733
1734 // Match the ')'.
1735 if (Result.isInvalid())
1736 SkipUntil(tok::r_paren, StopAtSemi);
1737 else {
1738 T.consumeClose();
1739 RParenLoc = T.getCloseLocation();
1740 if (RParenLoc.isInvalid())
1741 return ExprError();
1742
1743 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/false,
1744 Result.get(), RParenLoc);
1745 }
1746 }
1747
1748 return Result;
1749}
1750
1751/// ParseCXXUuidof - This handles the Microsoft C++ __uuidof expression.
1752///
1753/// '__uuidof' '(' expression ')'
1754/// '__uuidof' '(' type-id ')'
1755///
1756ExprResult Parser::ParseCXXUuidof() {
1757 assert(Tok.is(tok::kw___uuidof) && "Not '__uuidof'!");
1758
1759 SourceLocation OpLoc = ConsumeToken();
1760 BalancedDelimiterTracker T(*this, tok::l_paren);
1761
1762 // __uuidof expressions are always parenthesized.
1763 if (T.expectAndConsume(diag::err_expected_lparen_after, "__uuidof"))
1764 return ExprError();
1765
1767
1768 if (isTypeIdInParens()) {
1770
1771 // Match the ')'.
1772 T.consumeClose();
1773
1774 if (Ty.isInvalid())
1775 return ExprError();
1776
1777 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(), /*isType=*/true,
1778 Ty.get().getAsOpaquePtr(),
1779 T.getCloseLocation());
1780 } else {
1784
1785 // Match the ')'.
1786 if (Result.isInvalid())
1787 SkipUntil(tok::r_paren, StopAtSemi);
1788 else {
1789 T.consumeClose();
1790
1791 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(),
1792 /*isType=*/false,
1793 Result.get(), T.getCloseLocation());
1794 }
1795 }
1796
1797 return Result;
1798}
1799
1800/// Parse a C++ pseudo-destructor expression after the base,
1801/// . or -> operator, and nested-name-specifier have already been
1802/// parsed. We're handling this fragment of the grammar:
1803///
1804/// postfix-expression: [C++2a expr.post]
1805/// postfix-expression . template[opt] id-expression
1806/// postfix-expression -> template[opt] id-expression
1807///
1808/// id-expression:
1809/// qualified-id
1810/// unqualified-id
1811///
1812/// qualified-id:
1813/// nested-name-specifier template[opt] unqualified-id
1814///
1815/// nested-name-specifier:
1816/// type-name ::
1817/// decltype-specifier :: FIXME: not implemented, but probably only
1818/// allowed in C++ grammar by accident
1819/// nested-name-specifier identifier ::
1820/// nested-name-specifier template[opt] simple-template-id ::
1821/// [...]
1822///
1823/// unqualified-id:
1824/// ~ type-name
1825/// ~ decltype-specifier
1826/// [...]
1827///
1828/// ... where the all but the last component of the nested-name-specifier
1829/// has already been parsed, and the base expression is not of a non-dependent
1830/// class type.
1832Parser::ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc,
1833 tok::TokenKind OpKind,
1834 CXXScopeSpec &SS,
1835 ParsedType ObjectType) {
1836 // If the last component of the (optional) nested-name-specifier is
1837 // template[opt] simple-template-id, it has already been annotated.
1838 UnqualifiedId FirstTypeName;
1839 SourceLocation CCLoc;
1840 if (Tok.is(tok::identifier)) {
1841 FirstTypeName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1842 ConsumeToken();
1843 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1844 CCLoc = ConsumeToken();
1845 } else if (Tok.is(tok::annot_template_id)) {
1846 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1847 // FIXME: Carry on and build an AST representation for tooling.
1848 if (TemplateId->isInvalid())
1849 return ExprError();
1850 FirstTypeName.setTemplateId(TemplateId);
1851 ConsumeAnnotationToken();
1852 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1853 CCLoc = ConsumeToken();
1854 } else {
1855 assert(SS.isEmpty() && "missing last component of nested name specifier");
1856 FirstTypeName.setIdentifier(nullptr, SourceLocation());
1857 }
1858
1859 // Parse the tilde.
1860 assert(Tok.is(tok::tilde) && "ParseOptionalCXXScopeSpecifier fail");
1861 SourceLocation TildeLoc = ConsumeToken();
1862
1863 if (Tok.is(tok::kw_decltype) && !FirstTypeName.isValid()) {
1864 DeclSpec DS(AttrFactory);
1865 ParseDecltypeSpecifier(DS);
1866 if (DS.getTypeSpecType() == TST_error)
1867 return ExprError();
1868 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
1869 TildeLoc, DS);
1870 }
1871
1872 if (!Tok.is(tok::identifier)) {
1873 Diag(Tok, diag::err_destructor_tilde_identifier);
1874 return ExprError();
1875 }
1876
1877 // pack-index-specifier
1878 if (GetLookAheadToken(1).is(tok::ellipsis) &&
1879 GetLookAheadToken(2).is(tok::l_square)) {
1880 DeclSpec DS(AttrFactory);
1881 ParsePackIndexingType(DS);
1882 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
1883 TildeLoc, DS);
1884 }
1885
1886 // Parse the second type.
1887 UnqualifiedId SecondTypeName;
1888 IdentifierInfo *Name = Tok.getIdentifierInfo();
1889 SourceLocation NameLoc = ConsumeToken();
1890 SecondTypeName.setIdentifier(Name, NameLoc);
1891
1892 // If there is a '<', the second type name is a template-id. Parse
1893 // it as such.
1894 //
1895 // FIXME: This is not a context in which a '<' is assumed to start a template
1896 // argument list. This affects examples such as
1897 // void f(auto *p) { p->~X<int>(); }
1898 // ... but there's no ambiguity, and nowhere to write 'template' in such an
1899 // example, so we accept it anyway.
1900 if (Tok.is(tok::less) &&
1901 ParseUnqualifiedIdTemplateId(
1902 SS, ObjectType, Base && Base->containsErrors(), SourceLocation(),
1903 Name, NameLoc, false, SecondTypeName,
1904 /*AssumeTemplateId=*/true))
1905 return ExprError();
1906
1907 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
1908 SS, FirstTypeName, CCLoc, TildeLoc,
1909 SecondTypeName);
1910}
1911
1912/// ParseCXXBoolLiteral - This handles the C++ Boolean literals.
1913///
1914/// boolean-literal: [C++ 2.13.5]
1915/// 'true'
1916/// 'false'
1917ExprResult Parser::ParseCXXBoolLiteral() {
1918 tok::TokenKind Kind = Tok.getKind();
1919 return Actions.ActOnCXXBoolLiteral(ConsumeToken(), Kind);
1920}
1921
1922/// ParseThrowExpression - This handles the C++ throw expression.
1923///
1924/// throw-expression: [C++ 15]
1925/// 'throw' assignment-expression[opt]
1926ExprResult Parser::ParseThrowExpression() {
1927 assert(Tok.is(tok::kw_throw) && "Not throw!");
1928 SourceLocation ThrowLoc = ConsumeToken(); // Eat the throw token.
1929
1930 // If the current token isn't the start of an assignment-expression,
1931 // then the expression is not present. This handles things like:
1932 // "C ? throw : (void)42", which is crazy but legal.
1933 switch (Tok.getKind()) { // FIXME: move this predicate somewhere common.
1934 case tok::semi:
1935 case tok::r_paren:
1936 case tok::r_square:
1937 case tok::r_brace:
1938 case tok::colon:
1939 case tok::comma:
1940 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, nullptr);
1941
1942 default:
1944 if (Expr.isInvalid()) return Expr;
1945 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, Expr.get());
1946 }
1947}
1948
1949/// Parse the C++ Coroutines co_yield expression.
1950///
1951/// co_yield-expression:
1952/// 'co_yield' assignment-expression[opt]
1953ExprResult Parser::ParseCoyieldExpression() {
1954 assert(Tok.is(tok::kw_co_yield) && "Not co_yield!");
1955
1957 ExprResult Expr = Tok.is(tok::l_brace) ? ParseBraceInitializer()
1959 if (!Expr.isInvalid())
1960 Expr = Actions.ActOnCoyieldExpr(getCurScope(), Loc, Expr.get());
1961 return Expr;
1962}
1963
1964/// ParseCXXThis - This handles the C++ 'this' pointer.
1965///
1966/// C++ 9.3.2: In the body of a non-static member function, the keyword this is
1967/// a non-lvalue expression whose value is the address of the object for which
1968/// the function is called.
1969ExprResult Parser::ParseCXXThis() {
1970 assert(Tok.is(tok::kw_this) && "Not 'this'!");
1971 SourceLocation ThisLoc = ConsumeToken();
1972 return Actions.ActOnCXXThis(ThisLoc);
1973}
1974
1975/// ParseCXXTypeConstructExpression - Parse construction of a specified type.
1976/// Can be interpreted either as function-style casting ("int(x)")
1977/// or class type construction ("ClassType(x,y,z)")
1978/// or creation of a value-initialized type ("int()").
1979/// See [C++ 5.2.3].
1980///
1981/// postfix-expression: [C++ 5.2p1]
1982/// simple-type-specifier '(' expression-list[opt] ')'
1983/// [C++0x] simple-type-specifier braced-init-list
1984/// typename-specifier '(' expression-list[opt] ')'
1985/// [C++0x] typename-specifier braced-init-list
1986///
1987/// In C++1z onwards, the type specifier can also be a template-name.
1989Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) {
1990 Declarator DeclaratorInfo(DS, ParsedAttributesView::none(),
1992 ParsedType TypeRep = Actions.ActOnTypeName(DeclaratorInfo).get();
1993
1994 assert((Tok.is(tok::l_paren) ||
1995 (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)))
1996 && "Expected '(' or '{'!");
1997
1998 if (Tok.is(tok::l_brace)) {
1999 PreferredType.enterTypeCast(Tok.getLocation(), TypeRep.get());
2000 ExprResult Init = ParseBraceInitializer();
2001 if (Init.isInvalid())
2002 return Init;
2003 Expr *InitList = Init.get();
2004 return Actions.ActOnCXXTypeConstructExpr(
2005 TypeRep, InitList->getBeginLoc(), MultiExprArg(&InitList, 1),
2006 InitList->getEndLoc(), /*ListInitialization=*/true);
2007 } else {
2008 BalancedDelimiterTracker T(*this, tok::l_paren);
2009 T.consumeOpen();
2010
2011 PreferredType.enterTypeCast(Tok.getLocation(), TypeRep.get());
2012
2013 ExprVector Exprs;
2014
2015 auto RunSignatureHelp = [&]() {
2016 QualType PreferredType;
2017 if (TypeRep)
2018 PreferredType = Actions.ProduceConstructorSignatureHelp(
2019 TypeRep.get()->getCanonicalTypeInternal(), DS.getEndLoc(), Exprs,
2020 T.getOpenLocation(), /*Braced=*/false);
2021 CalledSignatureHelp = true;
2022 return PreferredType;
2023 };
2024
2025 if (Tok.isNot(tok::r_paren)) {
2026 if (ParseExpressionList(Exprs, [&] {
2027 PreferredType.enterFunctionArgument(Tok.getLocation(),
2028 RunSignatureHelp);
2029 })) {
2030 if (PP.isCodeCompletionReached() && !CalledSignatureHelp)
2031 RunSignatureHelp();
2032 SkipUntil(tok::r_paren, StopAtSemi);
2033 return ExprError();
2034 }
2035 }
2036
2037 // Match the ')'.
2038 T.consumeClose();
2039
2040 // TypeRep could be null, if it references an invalid typedef.
2041 if (!TypeRep)
2042 return ExprError();
2043
2044 return Actions.ActOnCXXTypeConstructExpr(TypeRep, T.getOpenLocation(),
2045 Exprs, T.getCloseLocation(),
2046 /*ListInitialization=*/false);
2047 }
2048}
2049
2051Parser::ParseAliasDeclarationInInitStatement(DeclaratorContext Context,
2052 ParsedAttributes &Attrs) {
2053 assert(Tok.is(tok::kw_using) && "Expected using");
2054 assert((Context == DeclaratorContext::ForInit ||
2056 "Unexpected Declarator Context");
2057 DeclGroupPtrTy DG;
2058 SourceLocation DeclStart = ConsumeToken(), DeclEnd;
2059
2060 DG = ParseUsingDeclaration(Context, {}, DeclStart, DeclEnd, Attrs, AS_none);
2061 if (!DG)
2062 return DG;
2063
2064 Diag(DeclStart, !getLangOpts().CPlusPlus23
2065 ? diag::ext_alias_in_init_statement
2066 : diag::warn_cxx20_alias_in_init_statement)
2067 << SourceRange(DeclStart, DeclEnd);
2068
2069 return DG;
2070}
2071
2072/// ParseCXXCondition - if/switch/while condition expression.
2073///
2074/// condition:
2075/// expression
2076/// type-specifier-seq declarator '=' assignment-expression
2077/// [C++11] type-specifier-seq declarator '=' initializer-clause
2078/// [C++11] type-specifier-seq declarator braced-init-list
2079/// [Clang] type-specifier-seq ref-qualifier[opt] '[' identifier-list ']'
2080/// brace-or-equal-initializer
2081/// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
2082/// '=' assignment-expression
2083///
2084/// In C++1z, a condition may in some contexts be preceded by an
2085/// optional init-statement. This function will parse that too.
2086///
2087/// \param InitStmt If non-null, an init-statement is permitted, and if present
2088/// will be parsed and stored here.
2089///
2090/// \param Loc The location of the start of the statement that requires this
2091/// condition, e.g., the "for" in a for loop.
2092///
2093/// \param MissingOK Whether an empty condition is acceptable here. Otherwise
2094/// it is considered an error to be recovered from.
2095///
2096/// \param FRI If non-null, a for range declaration is permitted, and if
2097/// present will be parsed and stored here, and a null result will be returned.
2098///
2099/// \param EnterForConditionScope If true, enter a continue/break scope at the
2100/// appropriate moment for a 'for' loop.
2101///
2102/// \returns The parsed condition.
2104Parser::ParseCXXCondition(StmtResult *InitStmt, SourceLocation Loc,
2105 Sema::ConditionKind CK, bool MissingOK,
2106 ForRangeInfo *FRI, bool EnterForConditionScope) {
2107 // Helper to ensure we always enter a continue/break scope if requested.
2108 struct ForConditionScopeRAII {
2109 Scope *S;
2110 void enter(bool IsConditionVariable) {
2111 if (S) {
2113 S->setIsConditionVarScope(IsConditionVariable);
2114 }
2115 }
2116 ~ForConditionScopeRAII() {
2117 if (S)
2118 S->setIsConditionVarScope(false);
2119 }
2120 } ForConditionScope{EnterForConditionScope ? getCurScope() : nullptr};
2121
2122 ParenBraceBracketBalancer BalancerRAIIObj(*this);
2123 PreferredType.enterCondition(Actions, Tok.getLocation());
2124
2125 if (Tok.is(tok::code_completion)) {
2126 cutOffParsing();
2128 return Sema::ConditionError();
2129 }
2130
2131 ParsedAttributes attrs(AttrFactory);
2132 MaybeParseCXX11Attributes(attrs);
2133
2134 const auto WarnOnInit = [this, &CK] {
2136 ? diag::warn_cxx14_compat_init_statement
2137 : diag::ext_init_statement)
2138 << (CK == Sema::ConditionKind::Switch);
2139 };
2140
2141 // Determine what kind of thing we have.
2142 switch (isCXXConditionDeclarationOrInitStatement(InitStmt, FRI)) {
2143 case ConditionOrInitStatement::Expression: {
2144 // If this is a for loop, we're entering its condition.
2145 ForConditionScope.enter(/*IsConditionVariable=*/false);
2146
2147 ProhibitAttributes(attrs);
2148
2149 // We can have an empty expression here.
2150 // if (; true);
2151 if (InitStmt && Tok.is(tok::semi)) {
2152 WarnOnInit();
2153 SourceLocation SemiLoc = Tok.getLocation();
2154 if (!Tok.hasLeadingEmptyMacro() && !SemiLoc.isMacroID()) {
2155 Diag(SemiLoc, diag::warn_empty_init_statement)
2157 << FixItHint::CreateRemoval(SemiLoc);
2158 }
2159 ConsumeToken();
2160 *InitStmt = Actions.ActOnNullStmt(SemiLoc);
2161 return ParseCXXCondition(nullptr, Loc, CK, MissingOK);
2162 }
2163
2164 // Parse the expression.
2165 ExprResult Expr = ParseExpression(); // expression
2166 if (Expr.isInvalid())
2167 return Sema::ConditionError();
2168
2169 if (InitStmt && Tok.is(tok::semi)) {
2170 WarnOnInit();
2171 *InitStmt = Actions.ActOnExprStmt(Expr.get());
2172 ConsumeToken();
2173 return ParseCXXCondition(nullptr, Loc, CK, MissingOK);
2174 }
2175
2176 return Actions.ActOnCondition(getCurScope(), Loc, Expr.get(), CK,
2177 MissingOK);
2178 }
2179
2180 case ConditionOrInitStatement::InitStmtDecl: {
2181 WarnOnInit();
2182 DeclGroupPtrTy DG;
2183 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
2184 if (Tok.is(tok::kw_using))
2185 DG = ParseAliasDeclarationInInitStatement(
2187 else {
2188 ParsedAttributes DeclSpecAttrs(AttrFactory);
2189 DG = ParseSimpleDeclaration(DeclaratorContext::SelectionInit, DeclEnd,
2190 attrs, DeclSpecAttrs, /*RequireSemi=*/true);
2191 }
2192 *InitStmt = Actions.ActOnDeclStmt(DG, DeclStart, DeclEnd);
2193 return ParseCXXCondition(nullptr, Loc, CK, MissingOK);
2194 }
2195
2196 case ConditionOrInitStatement::ForRangeDecl: {
2197 // This is 'for (init-stmt; for-range-decl : range-expr)'.
2198 // We're not actually in a for loop yet, so 'break' and 'continue' aren't
2199 // permitted here.
2200 assert(FRI && "should not parse a for range declaration here");
2201 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
2202 ParsedAttributes DeclSpecAttrs(AttrFactory);
2203 DeclGroupPtrTy DG = ParseSimpleDeclaration(
2204 DeclaratorContext::ForInit, DeclEnd, attrs, DeclSpecAttrs, false, FRI);
2205 FRI->LoopVar = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
2206 return Sema::ConditionResult();
2207 }
2208
2209 case ConditionOrInitStatement::ConditionDecl:
2210 case ConditionOrInitStatement::Error:
2211 break;
2212 }
2213
2214 // If this is a for loop, we're entering its condition.
2215 ForConditionScope.enter(/*IsConditionVariable=*/true);
2216
2217 // type-specifier-seq
2218 DeclSpec DS(AttrFactory);
2219 ParseSpecifierQualifierList(DS, AS_none, DeclSpecContext::DSC_condition);
2220
2221 // declarator
2222 Declarator DeclaratorInfo(DS, attrs, DeclaratorContext::Condition);
2223 ParseDeclarator(DeclaratorInfo);
2224
2225 // simple-asm-expr[opt]
2226 if (Tok.is(tok::kw_asm)) {
2227 SourceLocation Loc;
2228 ExprResult AsmLabel(ParseSimpleAsm(/*ForAsmLabel*/ true, &Loc));
2229 if (AsmLabel.isInvalid()) {
2230 SkipUntil(tok::semi, StopAtSemi);
2231 return Sema::ConditionError();
2232 }
2233 DeclaratorInfo.setAsmLabel(AsmLabel.get());
2234 DeclaratorInfo.SetRangeEnd(Loc);
2235 }
2236
2237 // If attributes are present, parse them.
2238 MaybeParseGNUAttributes(DeclaratorInfo);
2239
2240 // Type-check the declaration itself.
2242 DeclaratorInfo);
2243 if (Dcl.isInvalid())
2244 return Sema::ConditionError();
2245 Decl *DeclOut = Dcl.get();
2246
2247 // '=' assignment-expression
2248 // If a '==' or '+=' is found, suggest a fixit to '='.
2249 bool CopyInitialization = isTokenEqualOrEqualTypo();
2250 if (CopyInitialization)
2251 ConsumeToken();
2252
2253 ExprResult InitExpr = ExprError();
2254 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
2255 Diag(Tok.getLocation(),
2256 diag::warn_cxx98_compat_generalized_initializer_lists);
2257 InitExpr = ParseBraceInitializer();
2258 } else if (CopyInitialization) {
2259 PreferredType.enterVariableInit(Tok.getLocation(), DeclOut);
2260 InitExpr = ParseAssignmentExpression();
2261 } else if (Tok.is(tok::l_paren)) {
2262 // This was probably an attempt to initialize the variable.
2263 SourceLocation LParen = ConsumeParen(), RParen = LParen;
2264 if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch))
2265 RParen = ConsumeParen();
2266 Diag(DeclOut->getLocation(),
2267 diag::err_expected_init_in_condition_lparen)
2268 << SourceRange(LParen, RParen);
2269 } else {
2270 Diag(DeclOut->getLocation(), diag::err_expected_init_in_condition);
2271 }
2272
2273 if (!InitExpr.isInvalid())
2274 Actions.AddInitializerToDecl(DeclOut, InitExpr.get(), !CopyInitialization);
2275 else
2276 Actions.ActOnInitializerError(DeclOut);
2277
2278 Actions.FinalizeDeclaration(DeclOut);
2279 return Actions.ActOnConditionVariable(DeclOut, Loc, CK);
2280}
2281
2282/// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
2283/// This should only be called when the current token is known to be part of
2284/// simple-type-specifier.
2285///
2286/// simple-type-specifier:
2287/// '::'[opt] nested-name-specifier[opt] type-name
2288/// '::'[opt] nested-name-specifier 'template' simple-template-id [TODO]
2289/// char
2290/// wchar_t
2291/// bool
2292/// short
2293/// int
2294/// long
2295/// signed
2296/// unsigned
2297/// float
2298/// double
2299/// void
2300/// [GNU] typeof-specifier
2301/// [C++0x] auto [TODO]
2302///
2303/// type-name:
2304/// class-name
2305/// enum-name
2306/// typedef-name
2307///
2308void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) {
2309 DS.SetRangeStart(Tok.getLocation());
2310 const char *PrevSpec;
2311 unsigned DiagID;
2312 SourceLocation Loc = Tok.getLocation();
2313 const clang::PrintingPolicy &Policy =
2314 Actions.getASTContext().getPrintingPolicy();
2315
2316 switch (Tok.getKind()) {
2317 case tok::identifier: // foo::bar
2318 case tok::coloncolon: // ::foo::bar
2319 llvm_unreachable("Annotation token should already be formed!");
2320 default:
2321 llvm_unreachable("Not a simple-type-specifier token!");
2322
2323 // type-name
2324 case tok::annot_typename: {
2325 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID,
2326 getTypeAnnotation(Tok), Policy);
2328 ConsumeAnnotationToken();
2329 DS.Finish(Actions, Policy);
2330 return;
2331 }
2332
2333 case tok::kw__ExtInt:
2334 case tok::kw__BitInt: {
2335 DiagnoseBitIntUse(Tok);
2336 ExprResult ER = ParseExtIntegerArgument();
2337 if (ER.isInvalid())
2338 DS.SetTypeSpecError();
2339 else
2340 DS.SetBitIntType(Loc, ER.get(), PrevSpec, DiagID, Policy);
2341
2342 // Do this here because we have already consumed the close paren.
2343 DS.SetRangeEnd(PrevTokLocation);
2344 DS.Finish(Actions, Policy);
2345 return;
2346 }
2347
2348 // builtin types
2349 case tok::kw_short:
2350 DS.SetTypeSpecWidth(TypeSpecifierWidth::Short, Loc, PrevSpec, DiagID,
2351 Policy);
2352 break;
2353 case tok::kw_long:
2354 DS.SetTypeSpecWidth(TypeSpecifierWidth::Long, Loc, PrevSpec, DiagID,
2355 Policy);
2356 break;
2357 case tok::kw___int64:
2358 DS.SetTypeSpecWidth(TypeSpecifierWidth::LongLong, Loc, PrevSpec, DiagID,
2359 Policy);
2360 break;
2361 case tok::kw_signed:
2362 DS.SetTypeSpecSign(TypeSpecifierSign::Signed, Loc, PrevSpec, DiagID);
2363 break;
2364 case tok::kw_unsigned:
2365 DS.SetTypeSpecSign(TypeSpecifierSign::Unsigned, Loc, PrevSpec, DiagID);
2366 break;
2367 case tok::kw_void:
2368 DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID, Policy);
2369 break;
2370 case tok::kw_auto:
2371 DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec, DiagID, Policy);
2372 break;
2373 case tok::kw_char:
2374 DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID, Policy);
2375 break;
2376 case tok::kw_int:
2377 DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID, Policy);
2378 break;
2379 case tok::kw___int128:
2380 DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec, DiagID, Policy);
2381 break;
2382 case tok::kw___bf16:
2383 DS.SetTypeSpecType(DeclSpec::TST_BFloat16, Loc, PrevSpec, DiagID, Policy);
2384 break;
2385 case tok::kw_half:
2386 DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, DiagID, Policy);
2387 break;
2388 case tok::kw_float:
2389 DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID, Policy);
2390 break;
2391 case tok::kw_double:
2392 DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID, Policy);
2393 break;
2394 case tok::kw__Float16:
2395 DS.SetTypeSpecType(DeclSpec::TST_float16, Loc, PrevSpec, DiagID, Policy);
2396 break;
2397 case tok::kw___float128:
2398 DS.SetTypeSpecType(DeclSpec::TST_float128, Loc, PrevSpec, DiagID, Policy);
2399 break;
2400 case tok::kw___ibm128:
2401 DS.SetTypeSpecType(DeclSpec::TST_ibm128, Loc, PrevSpec, DiagID, Policy);
2402 break;
2403 case tok::kw_wchar_t:
2404 DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID, Policy);
2405 break;
2406 case tok::kw_char8_t:
2407 DS.SetTypeSpecType(DeclSpec::TST_char8, Loc, PrevSpec, DiagID, Policy);
2408 break;
2409 case tok::kw_char16_t:
2410 DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID, Policy);
2411 break;
2412 case tok::kw_char32_t:
2413 DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID, Policy);
2414 break;
2415 case tok::kw_bool:
2416 DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID, Policy);
2417 break;
2418 case tok::kw__Accum:
2419 DS.SetTypeSpecType(DeclSpec::TST_accum, Loc, PrevSpec, DiagID, Policy);
2420 break;
2421 case tok::kw__Fract:
2422 DS.SetTypeSpecType(DeclSpec::TST_fract, Loc, PrevSpec, DiagID, Policy);
2423 break;
2424 case tok::kw__Sat:
2425 DS.SetTypeSpecSat(Loc, PrevSpec, DiagID);
2426 break;
2427#define GENERIC_IMAGE_TYPE(ImgType, Id) \
2428 case tok::kw_##ImgType##_t: \
2429 DS.SetTypeSpecType(DeclSpec::TST_##ImgType##_t, Loc, PrevSpec, DiagID, \
2430 Policy); \
2431 break;
2432#include "clang/Basic/OpenCLImageTypes.def"
2433
2434 case tok::annot_decltype:
2435 case tok::kw_decltype:
2436 DS.SetRangeEnd(ParseDecltypeSpecifier(DS));
2437 return DS.Finish(Actions, Policy);
2438
2439 case tok::annot_pack_indexing_type:
2440 DS.SetRangeEnd(ParsePackIndexingType(DS));
2441 return DS.Finish(Actions, Policy);
2442
2443 // GNU typeof support.
2444 case tok::kw_typeof:
2445 ParseTypeofSpecifier(DS);
2446 DS.Finish(Actions, Policy);
2447 return;
2448 }
2450 DS.SetRangeEnd(PrevTokLocation);
2451 DS.Finish(Actions, Policy);
2452}
2453
2454/// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++
2455/// [dcl.name]), which is a non-empty sequence of type-specifiers,
2456/// e.g., "const short int". Note that the DeclSpec is *not* finished
2457/// by parsing the type-specifier-seq, because these sequences are
2458/// typically followed by some form of declarator. Returns true and
2459/// emits diagnostics if this is not a type-specifier-seq, false
2460/// otherwise.
2461///
2462/// type-specifier-seq: [C++ 8.1]
2463/// type-specifier type-specifier-seq[opt]
2464///
2465bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS, DeclaratorContext Context) {
2466 ParseSpecifierQualifierList(DS, AS_none,
2467 getDeclSpecContextFromDeclaratorContext(Context));
2468 DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy());
2469 return false;
2470}
2471
2472/// Finish parsing a C++ unqualified-id that is a template-id of
2473/// some form.
2474///
2475/// This routine is invoked when a '<' is encountered after an identifier or
2476/// operator-function-id is parsed by \c ParseUnqualifiedId() to determine
2477/// whether the unqualified-id is actually a template-id. This routine will
2478/// then parse the template arguments and form the appropriate template-id to
2479/// return to the caller.
2480///
2481/// \param SS the nested-name-specifier that precedes this template-id, if
2482/// we're actually parsing a qualified-id.
2483///
2484/// \param ObjectType if this unqualified-id occurs within a member access
2485/// expression, the type of the base object whose member is being accessed.
2486///
2487/// \param ObjectHadErrors this unqualified-id occurs within a member access
2488/// expression, indicates whether the original subexpressions had any errors.
2489///
2490/// \param Name for constructor and destructor names, this is the actual
2491/// identifier that may be a template-name.
2492///
2493/// \param NameLoc the location of the class-name in a constructor or
2494/// destructor.
2495///
2496/// \param EnteringContext whether we're entering the scope of the
2497/// nested-name-specifier.
2498///
2499/// \param Id as input, describes the template-name or operator-function-id
2500/// that precedes the '<'. If template arguments were parsed successfully,
2501/// will be updated with the template-id.
2502///
2503/// \param AssumeTemplateId When true, this routine will assume that the name
2504/// refers to a template without performing name lookup to verify.
2505///
2506/// \returns true if a parse error occurred, false otherwise.
2507bool Parser::ParseUnqualifiedIdTemplateId(
2508 CXXScopeSpec &SS, ParsedType ObjectType, bool ObjectHadErrors,
2509 SourceLocation TemplateKWLoc, IdentifierInfo *Name, SourceLocation NameLoc,
2510 bool EnteringContext, UnqualifiedId &Id, bool AssumeTemplateId) {
2511 assert(Tok.is(tok::less) && "Expected '<' to finish parsing a template-id");
2512
2513 TemplateTy Template;
2515 switch (Id.getKind()) {
2519 if (AssumeTemplateId) {
2520 // We defer the injected-class-name checks until we've found whether
2521 // this template-id is used to form a nested-name-specifier or not.
2522 TNK = Actions.ActOnTemplateName(getCurScope(), SS, TemplateKWLoc, Id,
2523 ObjectType, EnteringContext, Template,
2524 /*AllowInjectedClassName*/ true);
2525 } else {
2526 bool MemberOfUnknownSpecialization;
2527 TNK = Actions.isTemplateName(getCurScope(), SS,
2528 TemplateKWLoc.isValid(), Id,
2529 ObjectType, EnteringContext, Template,
2530 MemberOfUnknownSpecialization);
2531 // If lookup found nothing but we're assuming that this is a template
2532 // name, double-check that makes sense syntactically before committing
2533 // to it.
2534 if (TNK == TNK_Undeclared_template &&
2535 isTemplateArgumentList(0) == TPResult::False)
2536 return false;
2537
2538 if (TNK == TNK_Non_template && MemberOfUnknownSpecialization &&
2539 ObjectType && isTemplateArgumentList(0) == TPResult::True) {
2540 // If we had errors before, ObjectType can be dependent even without any
2541 // templates, do not report missing template keyword in that case.
2542 if (!ObjectHadErrors) {
2543 // We have something like t->getAs<T>(), where getAs is a
2544 // member of an unknown specialization. However, this will only
2545 // parse correctly as a template, so suggest the keyword 'template'
2546 // before 'getAs' and treat this as a dependent template name.
2547 std::string Name;
2548 if (Id.getKind() == UnqualifiedIdKind::IK_Identifier)
2549 Name = std::string(Id.Identifier->getName());
2550 else {
2551 Name = "operator ";
2553 Name += getOperatorSpelling(Id.OperatorFunctionId.Operator);
2554 else
2555 Name += Id.Identifier->getName();
2556 }
2557 Diag(Id.StartLocation, diag::err_missing_dependent_template_keyword)
2558 << Name
2559 << FixItHint::CreateInsertion(Id.StartLocation, "template ");
2560 }
2561 TNK = Actions.ActOnTemplateName(
2562 getCurScope(), SS, TemplateKWLoc, Id, ObjectType, EnteringContext,
2563 Template, /*AllowInjectedClassName*/ true);
2564 } else if (TNK == TNK_Non_template) {
2565 return false;
2566 }
2567 }
2568 break;
2569
2572 bool MemberOfUnknownSpecialization;
2573 TemplateName.setIdentifier(Name, NameLoc);
2574 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
2575 TemplateName, ObjectType,
2576 EnteringContext, Template,
2577 MemberOfUnknownSpecialization);
2578 if (TNK == TNK_Non_template)
2579 return false;
2580 break;
2581 }
2582
2585 bool MemberOfUnknownSpecialization;
2586 TemplateName.setIdentifier(Name, NameLoc);
2587 if (ObjectType) {
2588 TNK = Actions.ActOnTemplateName(
2589 getCurScope(), SS, TemplateKWLoc, TemplateName, ObjectType,
2590 EnteringContext, Template, /*AllowInjectedClassName*/ true);
2591 } else {
2592 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
2593 TemplateName, ObjectType,
2594 EnteringContext, Template,
2595 MemberOfUnknownSpecialization);
2596
2597 if (TNK == TNK_Non_template && !Id.DestructorName.get()) {
2598 Diag(NameLoc, diag::err_destructor_template_id)
2599 << Name << SS.getRange();
2600 // Carry on to parse the template arguments before bailing out.
2601 }
2602 }
2603 break;
2604 }
2605
2606 default:
2607 return false;
2608 }
2609
2610 // Parse the enclosed template argument list.
2611 SourceLocation LAngleLoc, RAngleLoc;
2612 TemplateArgList TemplateArgs;
2613 if (ParseTemplateIdAfterTemplateName(true, LAngleLoc, TemplateArgs, RAngleLoc,
2614 Template))
2615 return true;
2616
2617 // If this is a non-template, we already issued a diagnostic.
2618 if (TNK == TNK_Non_template)
2619 return true;
2620
2621 if (Id.getKind() == UnqualifiedIdKind::IK_Identifier ||
2624 // Form a parsed representation of the template-id to be stored in the
2625 // UnqualifiedId.
2626
2627 // FIXME: Store name for literal operator too.
2628 IdentifierInfo *TemplateII =
2629 Id.getKind() == UnqualifiedIdKind::IK_Identifier ? Id.Identifier
2630 : nullptr;
2631 OverloadedOperatorKind OpKind =
2633 ? OO_None
2634 : Id.OperatorFunctionId.Operator;
2635
2637 TemplateKWLoc, Id.StartLocation, TemplateII, OpKind, Template, TNK,
2638 LAngleLoc, RAngleLoc, TemplateArgs, /*ArgsInvalid*/false, TemplateIds);
2639
2640 Id.setTemplateId(TemplateId);
2641 return false;
2642 }
2643
2644 // Bundle the template arguments together.
2645 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
2646
2647 // Constructor and destructor names.
2649 getCurScope(), SS, TemplateKWLoc, Template, Name, NameLoc, LAngleLoc,
2650 TemplateArgsPtr, RAngleLoc, /*IsCtorOrDtorName=*/true);
2651 if (Type.isInvalid())
2652 return true;
2653
2655 Id.setConstructorName(Type.get(), NameLoc, RAngleLoc);
2656 else
2657 Id.setDestructorName(Id.StartLocation, Type.get(), RAngleLoc);
2658
2659 return false;
2660}
2661
2662/// Parse an operator-function-id or conversion-function-id as part
2663/// of a C++ unqualified-id.
2664///
2665/// This routine is responsible only for parsing the operator-function-id or
2666/// conversion-function-id; it does not handle template arguments in any way.
2667///
2668/// \code
2669/// operator-function-id: [C++ 13.5]
2670/// 'operator' operator
2671///
2672/// operator: one of
2673/// new delete new[] delete[]
2674/// + - * / % ^ & | ~
2675/// ! = < > += -= *= /= %=
2676/// ^= &= |= << >> >>= <<= == !=
2677/// <= >= && || ++ -- , ->* ->
2678/// () [] <=>
2679///
2680/// conversion-function-id: [C++ 12.3.2]
2681/// operator conversion-type-id
2682///
2683/// conversion-type-id:
2684/// type-specifier-seq conversion-declarator[opt]
2685///
2686/// conversion-declarator:
2687/// ptr-operator conversion-declarator[opt]
2688/// \endcode
2689///
2690/// \param SS The nested-name-specifier that preceded this unqualified-id. If
2691/// non-empty, then we are parsing the unqualified-id of a qualified-id.
2692///
2693/// \param EnteringContext whether we are entering the scope of the
2694/// nested-name-specifier.
2695///
2696/// \param ObjectType if this unqualified-id occurs within a member access
2697/// expression, the type of the base object whose member is being accessed.
2698///
2699/// \param Result on a successful parse, contains the parsed unqualified-id.
2700///
2701/// \returns true if parsing fails, false otherwise.
2702bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
2703 ParsedType ObjectType,
2705 assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword");
2706
2707 // Consume the 'operator' keyword.
2708 SourceLocation KeywordLoc = ConsumeToken();
2709
2710 // Determine what kind of operator name we have.
2711 unsigned SymbolIdx = 0;
2712 SourceLocation SymbolLocations[3];
2714 switch (Tok.getKind()) {
2715 case tok::kw_new:
2716 case tok::kw_delete: {
2717 bool isNew = Tok.getKind() == tok::kw_new;
2718 // Consume the 'new' or 'delete'.
2719 SymbolLocations[SymbolIdx++] = ConsumeToken();
2720 // Check for array new/delete.
2721 if (Tok.is(tok::l_square) &&
2722 (!getLangOpts().CPlusPlus11 || NextToken().isNot(tok::l_square))) {
2723 // Consume the '[' and ']'.
2724 BalancedDelimiterTracker T(*this, tok::l_square);
2725 T.consumeOpen();
2726 T.consumeClose();
2727 if (T.getCloseLocation().isInvalid())
2728 return true;
2729
2730 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2731 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2732 Op = isNew? OO_Array_New : OO_Array_Delete;
2733 } else {
2734 Op = isNew? OO_New : OO_Delete;
2735 }
2736 break;
2737 }
2738
2739#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2740 case tok::Token: \
2741 SymbolLocations[SymbolIdx++] = ConsumeToken(); \
2742 Op = OO_##Name; \
2743 break;
2744#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2745#include "clang/Basic/OperatorKinds.def"
2746
2747 case tok::l_paren: {
2748 // Consume the '(' and ')'.
2749 BalancedDelimiterTracker T(*this, tok::l_paren);
2750 T.consumeOpen();
2751 T.consumeClose();
2752 if (T.getCloseLocation().isInvalid())
2753 return true;
2754
2755 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2756 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2757 Op = OO_Call;
2758 break;
2759 }
2760
2761 case tok::l_square: {
2762 // Consume the '[' and ']'.
2763 BalancedDelimiterTracker T(*this, tok::l_square);
2764 T.consumeOpen();
2765 T.consumeClose();
2766 if (T.getCloseLocation().isInvalid())
2767 return true;
2768
2769 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2770 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2771 Op = OO_Subscript;
2772 break;
2773 }
2774
2775 case tok::code_completion: {
2776 // Don't try to parse any further.
2777 cutOffParsing();
2778 // Code completion for the operator name.
2780 return true;
2781 }
2782
2783 default:
2784 break;
2785 }
2786
2787 if (Op != OO_None) {
2788 // We have parsed an operator-function-id.
2789 Result.setOperatorFunctionId(KeywordLoc, Op, SymbolLocations);
2790 return false;
2791 }
2792
2793 // Parse a literal-operator-id.
2794 //
2795 // literal-operator-id: C++11 [over.literal]
2796 // operator string-literal identifier
2797 // operator user-defined-string-literal
2798
2799 if (getLangOpts().CPlusPlus11 && isTokenStringLiteral()) {
2800 Diag(Tok.getLocation(), diag::warn_cxx98_compat_literal_operator);
2801
2802 SourceLocation DiagLoc;
2803 unsigned DiagId = 0;
2804
2805 // We're past translation phase 6, so perform string literal concatenation
2806 // before checking for "".
2809 while (isTokenStringLiteral()) {
2810 if (!Tok.is(tok::string_literal) && !DiagId) {
2811 // C++11 [over.literal]p1:
2812 // The string-literal or user-defined-string-literal in a
2813 // literal-operator-id shall have no encoding-prefix [...].
2814 DiagLoc = Tok.getLocation();
2815 DiagId = diag::err_literal_operator_string_prefix;
2816 }
2817 Toks.push_back(Tok);
2818 TokLocs.push_back(ConsumeStringToken());
2819 }
2820
2821 StringLiteralParser Literal(Toks, PP);
2822 if (Literal.hadError)
2823 return true;
2824
2825 // Grab the literal operator's suffix, which will be either the next token
2826 // or a ud-suffix from the string literal.
2827 bool IsUDSuffix = !Literal.getUDSuffix().empty();
2828 IdentifierInfo *II = nullptr;
2829 SourceLocation SuffixLoc;
2830 if (IsUDSuffix) {
2831 II = &PP.getIdentifierTable().get(Literal.getUDSuffix());
2832 SuffixLoc =
2833 Lexer::AdvanceToTokenCharacter(TokLocs[Literal.getUDSuffixToken()],
2834 Literal.getUDSuffixOffset(),
2836 } else if (Tok.is(tok::identifier)) {
2837 II = Tok.getIdentifierInfo();
2838 SuffixLoc = ConsumeToken();
2839 TokLocs.push_back(SuffixLoc);
2840 } else {
2841 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
2842 return true;
2843 }
2844
2845 // The string literal must be empty.
2846 if (!Literal.GetString().empty() || Literal.Pascal) {
2847 // C++11 [over.literal]p1:
2848 // The string-literal or user-defined-string-literal in a
2849 // literal-operator-id shall [...] contain no characters
2850 // other than the implicit terminating '\0'.
2851 DiagLoc = TokLocs.front();
2852 DiagId = diag::err_literal_operator_string_not_empty;
2853 }
2854
2855 if (DiagId) {
2856 // This isn't a valid literal-operator-id, but we think we know
2857 // what the user meant. Tell them what they should have written.
2858 SmallString<32> Str;
2859 Str += "\"\"";
2860 Str += II->getName();
2861 Diag(DiagLoc, DiagId) << FixItHint::CreateReplacement(
2862 SourceRange(TokLocs.front(), TokLocs.back()), Str);
2863 }
2864
2865 Result.setLiteralOperatorId(II, KeywordLoc, SuffixLoc);
2866
2867 return Actions.checkLiteralOperatorId(SS, Result, IsUDSuffix);
2868 }
2869
2870 // Parse a conversion-function-id.
2871 //
2872 // conversion-function-id: [C++ 12.3.2]
2873 // operator conversion-type-id
2874 //
2875 // conversion-type-id:
2876 // type-specifier-seq conversion-declarator[opt]
2877 //
2878 // conversion-declarator:
2879 // ptr-operator conversion-declarator[opt]
2880
2881 // Parse the type-specifier-seq.
2882 DeclSpec DS(AttrFactory);
2883 if (ParseCXXTypeSpecifierSeq(
2884 DS, DeclaratorContext::ConversionId)) // FIXME: ObjectType?
2885 return true;
2886
2887 // Parse the conversion-declarator, which is merely a sequence of
2888 // ptr-operators.
2891 ParseDeclaratorInternal(D, /*DirectDeclParser=*/nullptr);
2892
2893 // Finish up the type.
2894 TypeResult Ty = Actions.ActOnTypeName(D);
2895 if (Ty.isInvalid())
2896 return true;
2897
2898 // Note that this is a conversion-function-id.
2899 Result.setConversionFunctionId(KeywordLoc, Ty.get(),
2900 D.getSourceRange().getEnd());
2901 return false;
2902}
2903
2904/// Parse a C++ unqualified-id (or a C identifier), which describes the
2905/// name of an entity.
2906///
2907/// \code
2908/// unqualified-id: [C++ expr.prim.general]
2909/// identifier
2910/// operator-function-id
2911/// conversion-function-id
2912/// [C++0x] literal-operator-id [TODO]
2913/// ~ class-name
2914/// template-id
2915///
2916/// \endcode
2917///
2918/// \param SS The nested-name-specifier that preceded this unqualified-id. If
2919/// non-empty, then we are parsing the unqualified-id of a qualified-id.
2920///
2921/// \param ObjectType if this unqualified-id occurs within a member access
2922/// expression, the type of the base object whose member is being accessed.
2923///
2924/// \param ObjectHadErrors if this unqualified-id occurs within a member access
2925/// expression, indicates whether the original subexpressions had any errors.
2926/// When true, diagnostics for missing 'template' keyword will be supressed.
2927///
2928/// \param EnteringContext whether we are entering the scope of the
2929/// nested-name-specifier.
2930///
2931/// \param AllowDestructorName whether we allow parsing of a destructor name.
2932///
2933/// \param AllowConstructorName whether we allow parsing a constructor name.
2934///
2935/// \param AllowDeductionGuide whether we allow parsing a deduction guide name.
2936///
2937/// \param Result on a successful parse, contains the parsed unqualified-id.
2938///
2939/// \returns true if parsing fails, false otherwise.
2941 bool ObjectHadErrors, bool EnteringContext,
2942 bool AllowDestructorName,
2943 bool AllowConstructorName,
2944 bool AllowDeductionGuide,
2945 SourceLocation *TemplateKWLoc,
2947 if (TemplateKWLoc)
2948 *TemplateKWLoc = SourceLocation();
2949
2950 // Handle 'A::template B'. This is for template-ids which have not
2951 // already been annotated by ParseOptionalCXXScopeSpecifier().
2952 bool TemplateSpecified = false;
2953 if (Tok.is(tok::kw_template)) {
2954 if (TemplateKWLoc && (ObjectType || SS.isSet())) {
2955 TemplateSpecified = true;
2956 *TemplateKWLoc = ConsumeToken();
2957 } else {
2958 SourceLocation TemplateLoc = ConsumeToken();
2959 Diag(TemplateLoc, diag::err_unexpected_template_in_unqualified_id)
2960 << FixItHint::CreateRemoval(TemplateLoc);
2961 }
2962 }
2963
2964 // unqualified-id:
2965 // identifier
2966 // template-id (when it hasn't already been annotated)
2967 if (Tok.is(tok::identifier)) {
2968 ParseIdentifier:
2969 // Consume the identifier.
2971 SourceLocation IdLoc = ConsumeToken();
2972
2973 if (!getLangOpts().CPlusPlus) {
2974 // If we're not in C++, only identifiers matter. Record the
2975 // identifier and return.
2976 Result.setIdentifier(Id, IdLoc);
2977 return false;
2978 }
2979
2981 if (AllowConstructorName &&
2982 Actions.isCurrentClassName(*Id, getCurScope(), &SS)) {
2983 // We have parsed a constructor name.
2984 ParsedType Ty = Actions.getConstructorName(*Id, IdLoc, getCurScope(), SS,
2985 EnteringContext);
2986 if (!Ty)
2987 return true;
2988 Result.setConstructorName(Ty, IdLoc, IdLoc);
2989 } else if (getLangOpts().CPlusPlus17 && AllowDeductionGuide &&
2990 SS.isEmpty() &&
2991 Actions.isDeductionGuideName(getCurScope(), *Id, IdLoc, SS,
2992 &TemplateName)) {
2993 // We have parsed a template-name naming a deduction guide.
2994 Result.setDeductionGuideName(TemplateName, IdLoc);
2995 } else {
2996 // We have parsed an identifier.
2997 Result.setIdentifier(Id, IdLoc);
2998 }
2999
3000 // If the next token is a '<', we may have a template.
3001 TemplateTy Template;
3002 if (Tok.is(tok::less))
3003 return ParseUnqualifiedIdTemplateId(
3004 SS, ObjectType, ObjectHadErrors,
3005 TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), Id, IdLoc,
3006 EnteringContext, Result, TemplateSpecified);
3007 else if (TemplateSpecified &&
3008 Actions.ActOnTemplateName(
3009 getCurScope(), SS, *TemplateKWLoc, Result, ObjectType,
3010 EnteringContext, Template,
3011 /*AllowInjectedClassName*/ true) == TNK_Non_template)
3012 return true;
3013
3014 return false;
3015 }
3016
3017 // unqualified-id:
3018 // template-id (already parsed and annotated)
3019 if (Tok.is(tok::annot_template_id)) {
3020 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
3021
3022 // FIXME: Consider passing invalid template-ids on to callers; they may
3023 // be able to recover better than we can.
3024 if (TemplateId->isInvalid()) {
3025 ConsumeAnnotationToken();
3026 return true;
3027 }
3028
3029 // If the template-name names the current class, then this is a constructor
3030 if (AllowConstructorName && TemplateId->Name &&
3031 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
3032 if (SS.isSet()) {
3033 // C++ [class.qual]p2 specifies that a qualified template-name
3034 // is taken as the constructor name where a constructor can be
3035 // declared. Thus, the template arguments are extraneous, so
3036 // complain about them and remove them entirely.
3037 Diag(TemplateId->TemplateNameLoc,
3038 diag::err_out_of_line_constructor_template_id)
3039 << TemplateId->Name
3041 SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc));
3042 ParsedType Ty = Actions.getConstructorName(
3043 *TemplateId->Name, TemplateId->TemplateNameLoc, getCurScope(), SS,
3044 EnteringContext);
3045 if (!Ty)
3046 return true;
3047 Result.setConstructorName(Ty, TemplateId->TemplateNameLoc,
3048 TemplateId->RAngleLoc);
3049 ConsumeAnnotationToken();
3050 return false;
3051 }
3052
3053 Result.setConstructorTemplateId(TemplateId);
3054 ConsumeAnnotationToken();
3055 return false;
3056 }
3057
3058 // We have already parsed a template-id; consume the annotation token as
3059 // our unqualified-id.
3060 Result.setTemplateId(TemplateId);
3061 SourceLocation TemplateLoc = TemplateId->TemplateKWLoc;
3062 if (TemplateLoc.isValid()) {
3063 if (TemplateKWLoc && (ObjectType || SS.isSet()))
3064 *TemplateKWLoc = TemplateLoc;
3065 else
3066 Diag(TemplateLoc, diag::err_unexpected_template_in_unqualified_id)
3067 << FixItHint::CreateRemoval(TemplateLoc);
3068 }
3069 ConsumeAnnotationToken();
3070 return false;
3071 }
3072
3073 // unqualified-id:
3074 // operator-function-id
3075 // conversion-function-id
3076 if (Tok.is(tok::kw_operator)) {
3077 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, Result))
3078 return true;
3079
3080 // If we have an operator-function-id or a literal-operator-id and the next
3081 // token is a '<', we may have a
3082 //
3083 // template-id:
3084 // operator-function-id < template-argument-list[opt] >
3085 TemplateTy Template;
3088 Tok.is(tok::less))
3089 return ParseUnqualifiedIdTemplateId(
3090 SS, ObjectType, ObjectHadErrors,
3091 TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), nullptr,
3092 SourceLocation(), EnteringContext, Result, TemplateSpecified);
3093 else if (TemplateSpecified &&
3094 Actions.ActOnTemplateName(
3095 getCurScope(), SS, *TemplateKWLoc, Result, ObjectType,
3096 EnteringContext, Template,
3097 /*AllowInjectedClassName*/ true) == TNK_Non_template)
3098 return true;
3099
3100 return false;
3101 }
3102
3103 if (getLangOpts().CPlusPlus &&
3104 (AllowDestructorName || SS.isSet()) && Tok.is(tok::tilde)) {
3105 // C++ [expr.unary.op]p10:
3106 // There is an ambiguity in the unary-expression ~X(), where X is a
3107 // class-name. The ambiguity is resolved in favor of treating ~ as a
3108 // unary complement rather than treating ~X as referring to a destructor.
3109
3110 // Parse the '~'.
3111 SourceLocation TildeLoc = ConsumeToken();
3112
3113 if (TemplateSpecified) {
3114 // C++ [temp.names]p3:
3115 // A name prefixed by the keyword template shall be a template-id [...]
3116 //
3117 // A template-id cannot begin with a '~' token. This would never work
3118 // anyway: x.~A<int>() would specify that the destructor is a template,
3119 // not that 'A' is a template.
3120 //
3121 // FIXME: Suggest replacing the attempted destructor name with a correct
3122 // destructor name and recover. (This is not trivial if this would become
3123 // a pseudo-destructor name).
3124 Diag(*TemplateKWLoc, diag::err_unexpected_template_in_destructor_name)
3125 << Tok.getLocation();
3126 return true;
3127 }
3128
3129 if (SS.isEmpty() && Tok.is(tok::kw_decltype)) {
3130 DeclSpec DS(AttrFactory);
3131 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
3132 if (ParsedType Type =
3133 Actions.getDestructorTypeForDecltype(DS, ObjectType)) {
3134 Result.setDestructorName(TildeLoc, Type, EndLoc);
3135 return false;
3136 }
3137 return true;
3138 }
3139
3140 // Parse the class-name.
3141 if (Tok.isNot(tok::identifier)) {
3142 Diag(Tok, diag::err_destructor_tilde_identifier);
3143 return true;
3144 }
3145
3146 // If the user wrote ~T::T, correct it to T::~T.
3147 DeclaratorScopeObj DeclScopeObj(*this, SS);
3148 if (NextToken().is(tok::coloncolon)) {
3149 // Don't let ParseOptionalCXXScopeSpecifier() "correct"
3150 // `int A; struct { ~A::A(); };` to `int A; struct { ~A:A(); };`,
3151 // it will confuse this recovery logic.
3152 ColonProtectionRAIIObject ColonRAII(*this, false);
3153
3154 if (SS.isSet()) {
3155 AnnotateScopeToken(SS, /*NewAnnotation*/true);
3156 SS.clear();
3157 }
3158 if (ParseOptionalCXXScopeSpecifier(SS, ObjectType, ObjectHadErrors,
3159 EnteringContext))
3160 return true;
3161 if (SS.isNotEmpty())
3162 ObjectType = nullptr;
3163 if (Tok.isNot(tok::identifier) || NextToken().is(tok::coloncolon) ||
3164 !SS.isSet()) {
3165 Diag(TildeLoc, diag::err_destructor_tilde_scope);
3166 return true;
3167 }
3168
3169 // Recover as if the tilde had been written before the identifier.
3170 Diag(TildeLoc, diag::err_destructor_tilde_scope)
3171 << FixItHint::CreateRemoval(TildeLoc)
3173
3174 // Temporarily enter the scope for the rest of this function.
3175 if (Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
3176 DeclScopeObj.EnterDeclaratorScope();
3177 }
3178
3179 // Parse the class-name (or template-name in a simple-template-id).
3180 IdentifierInfo *ClassName = Tok.getIdentifierInfo();
3181 SourceLocation ClassNameLoc = ConsumeToken();
3182
3183 if (Tok.is(tok::less)) {
3184 Result.setDestructorName(TildeLoc, nullptr, ClassNameLoc);
3185 return ParseUnqualifiedIdTemplateId(
3186 SS, ObjectType, ObjectHadErrors,
3187 TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), ClassName,
3188 ClassNameLoc, EnteringContext, Result, TemplateSpecified);
3189 }
3190
3191 // Note that this is a destructor name.
3192 ParsedType Ty =
3193 Actions.getDestructorName(*ClassName, ClassNameLoc, getCurScope(), SS,
3194 ObjectType, EnteringContext);
3195 if (!Ty)
3196 return true;
3197
3198 Result.setDestructorName(TildeLoc, Ty, ClassNameLoc);
3199 return false;
3200 }
3201
3202 switch (Tok.getKind()) {
3203#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case tok::kw___##Trait:
3204#include "clang/Basic/TransformTypeTraits.def"
3205 if (!NextToken().is(tok::l_paren)) {
3206 Tok.setKind(tok::identifier);
3207 Diag(Tok, diag::ext_keyword_as_ident)
3208 << Tok.getIdentifierInfo()->getName() << 0;
3209 goto ParseIdentifier;
3210 }
3211 [[fallthrough]];
3212 default:
3213 Diag(Tok, diag::err_expected_unqualified_id) << getLangOpts().CPlusPlus;
3214 return true;
3215 }
3216}
3217
3218/// ParseCXXNewExpression - Parse a C++ new-expression. New is used to allocate
3219/// memory in a typesafe manner and call constructors.
3220///
3221/// This method is called to parse the new expression after the optional :: has
3222/// been already parsed. If the :: was present, "UseGlobal" is true and "Start"
3223/// is its location. Otherwise, "Start" is the location of the 'new' token.
3224///
3225/// new-expression:
3226/// '::'[opt] 'new' new-placement[opt] new-type-id
3227/// new-initializer[opt]
3228/// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
3229/// new-initializer[opt]
3230///
3231/// new-placement:
3232/// '(' expression-list ')'
3233///
3234/// new-type-id:
3235/// type-specifier-seq new-declarator[opt]
3236/// [GNU] attributes type-specifier-seq new-declarator[opt]
3237///
3238/// new-declarator:
3239/// ptr-operator new-declarator[opt]
3240/// direct-new-declarator
3241///
3242/// new-initializer:
3243/// '(' expression-list[opt] ')'
3244/// [C++0x] braced-init-list
3245///
3247Parser::ParseCXXNewExpression(bool UseGlobal, SourceLocation Start) {
3248 assert(Tok.is(tok::kw_new) && "expected 'new' token");
3249 ConsumeToken(); // Consume 'new'
3250
3251 // A '(' now can be a new-placement or the '(' wrapping the type-id in the
3252 // second form of new-expression. It can't be a new-type-id.
3253
3254 ExprVector PlacementArgs;
3255 SourceLocation PlacementLParen, PlacementRParen;
3256
3257 SourceRange TypeIdParens;
3258 DeclSpec DS(AttrFactory);
3259 Declarator DeclaratorInfo(DS, ParsedAttributesView::none(),
3261 if (Tok.is(tok::l_paren)) {
3262 // If it turns out to be a placement, we change the type location.
3263 BalancedDelimiterTracker T(*this, tok::l_paren);
3264 T.consumeOpen();
3265 PlacementLParen = T.getOpenLocation();
3266 if (ParseExpressionListOrTypeId(PlacementArgs, DeclaratorInfo)) {
3267 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
3268 return ExprError();
3269 }
3270
3271 T.consumeClose();
3272 PlacementRParen = T.getCloseLocation();
3273 if (PlacementRParen.isInvalid()) {
3274 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
3275 return ExprError();
3276 }
3277
3278 if (PlacementArgs.empty()) {
3279 // Reset the placement locations. There was no placement.
3280 TypeIdParens = T.getRange();
3281 PlacementLParen = PlacementRParen = SourceLocation();
3282 } else {
3283 // We still need the type.
3284 if (Tok.is(tok::l_paren)) {
3285 BalancedDelimiterTracker T(*this, tok::l_paren);
3286 T.consumeOpen();
3287 MaybeParseGNUAttributes(DeclaratorInfo);
3288 ParseSpecifierQualifierList(DS);
3289 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
3290 ParseDeclarator(DeclaratorInfo);
3291 T.consumeClose();
3292 TypeIdParens = T.getRange();
3293 } else {
3294 MaybeParseGNUAttributes(DeclaratorInfo);
3295 if (ParseCXXTypeSpecifierSeq(DS))
3296 DeclaratorInfo.setInvalidType(true);
3297 else {
3298 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
3299 ParseDeclaratorInternal(DeclaratorInfo,
3300 &Parser::ParseDirectNewDeclarator);
3301 }
3302 }
3303 }
3304 } else {
3305 // A new-type-id is a simplified type-id, where essentially the
3306 // direct-declarator is replaced by a direct-new-declarator.
3307 MaybeParseGNUAttributes(DeclaratorInfo);
3308 if (ParseCXXTypeSpecifierSeq(DS, DeclaratorContext::CXXNew))
3309 DeclaratorInfo.setInvalidType(true);
3310 else {
3311 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
3312 ParseDeclaratorInternal(DeclaratorInfo,
3313 &Parser::ParseDirectNewDeclarator);
3314 }
3315 }
3316 if (DeclaratorInfo.isInvalidType()) {
3317 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
3318 return ExprError();
3319 }
3320
3322
3323 if (Tok.is(tok::l_paren)) {
3324 SourceLocation ConstructorLParen, ConstructorRParen;
3325 ExprVector ConstructorArgs;
3326 BalancedDelimiterTracker T(*this, tok::l_paren);
3327 T.consumeOpen();
3328 ConstructorLParen = T.getOpenLocation();
3329 if (Tok.isNot(tok::r_paren)) {
3330 auto RunSignatureHelp = [&]() {
3331 ParsedType TypeRep = Actions.ActOnTypeName(DeclaratorInfo).get();
3332 QualType PreferredType;
3333 // ActOnTypeName might adjust DeclaratorInfo and return a null type even
3334 // the passing DeclaratorInfo is valid, e.g. running SignatureHelp on
3335 // `new decltype(invalid) (^)`.
3336 if (TypeRep)
3337 PreferredType = Actions.ProduceConstructorSignatureHelp(
3338 TypeRep.get()->getCanonicalTypeInternal(),
3339 DeclaratorInfo.getEndLoc(), ConstructorArgs, ConstructorLParen,
3340 /*Braced=*/false);
3341 CalledSignatureHelp = true;
3342 return PreferredType;
3343 };
3344 if (ParseExpressionList(ConstructorArgs, [&] {
3345 PreferredType.enterFunctionArgument(Tok.getLocation(),
3346 RunSignatureHelp);
3347 })) {
3348 if (PP.isCodeCompletionReached() && !CalledSignatureHelp)
3349 RunSignatureHelp();
3350 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
3351 return ExprError();
3352 }
3353 }
3354 T.consumeClose();
3355 ConstructorRParen = T.getCloseLocation();
3356 if (ConstructorRParen.isInvalid()) {
3357 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
3358 return ExprError();
3359 }
3360 Initializer = Actions.ActOnParenListExpr(ConstructorLParen,
3361 ConstructorRParen,
3362 ConstructorArgs);
3363 } else if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus11) {
3364 Diag(Tok.getLocation(),
3365 diag::warn_cxx98_compat_generalized_initializer_lists);
3366 Initializer = ParseBraceInitializer();
3367 }
3368 if (Initializer.isInvalid())
3369 return Initializer;
3370
3371 return Actions.ActOnCXXNew(Start, UseGlobal, PlacementLParen,
3372 PlacementArgs, PlacementRParen,
3373 TypeIdParens, DeclaratorInfo, Initializer.get());
3374}
3375
3376/// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be
3377/// passed to ParseDeclaratorInternal.
3378///
3379/// direct-new-declarator:
3380/// '[' expression[opt] ']'
3381/// direct-new-declarator '[' constant-expression ']'
3382///
3383void Parser::ParseDirectNewDeclarator(Declarator &D) {
3384 // Parse the array dimensions.
3385 bool First = true;
3386 while (Tok.is(tok::l_square)) {
3387 // An array-size expression can't start with a lambda.
3388 if (CheckProhibitedCXX11Attribute())
3389 continue;
3390
3391 BalancedDelimiterTracker T(*this, tok::l_square);
3392 T.consumeOpen();
3393
3395 First ? (Tok.is(tok::r_square) ? ExprResult() : ParseExpression())
3397 if (Size.isInvalid()) {
3398 // Recover
3399 SkipUntil(tok::r_square, StopAtSemi);
3400 return;
3401 }
3402 First = false;
3403
3404 T.consumeClose();
3405
3406 // Attributes here appertain to the array type. C++11 [expr.new]p5.
3407 ParsedAttributes Attrs(AttrFactory);
3408 MaybeParseCXX11Attributes(Attrs);
3409
3411 /*isStatic=*/false, /*isStar=*/false,
3412 Size.get(), T.getOpenLocation(),
3413 T.getCloseLocation()),
3414 std::move(Attrs), T.getCloseLocation());
3415
3416 if (T.getCloseLocation().isInvalid())
3417 return;
3418 }
3419}
3420
3421/// ParseExpressionListOrTypeId - Parse either an expression-list or a type-id.
3422/// This ambiguity appears in the syntax of the C++ new operator.
3423///
3424/// new-expression:
3425/// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
3426/// new-initializer[opt]
3427///
3428/// new-placement:
3429/// '(' expression-list ')'
3430///
3431bool Parser::ParseExpressionListOrTypeId(
3432 SmallVectorImpl<Expr*> &PlacementArgs,
3433 Declarator &D) {
3434 // The '(' was already consumed.
3435 if (isTypeIdInParens()) {
3436 ParseSpecifierQualifierList(D.getMutableDeclSpec());
3438 ParseDeclarator(D);
3439 return D.isInvalidType();
3440 }
3441
3442 // It's not a type, it has to be an expression list.
3443 return ParseExpressionList(PlacementArgs);
3444}
3445
3446/// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used
3447/// to free memory allocated by new.
3448///
3449/// This method is called to parse the 'delete' expression after the optional
3450/// '::' has been already parsed. If the '::' was present, "UseGlobal" is true
3451/// and "Start" is its location. Otherwise, "Start" is the location of the
3452/// 'delete' token.
3453///
3454/// delete-expression:
3455/// '::'[opt] 'delete' cast-expression
3456/// '::'[opt] 'delete' '[' ']' cast-expression
3458Parser::ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start) {
3459 assert(Tok.is(tok::kw_delete) && "Expected 'delete' keyword");
3460 ConsumeToken(); // Consume 'delete'
3461
3462 // Array delete?
3463 bool ArrayDelete = false;
3464 if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) {
3465 // C++11 [expr.delete]p1:
3466 // Whenever the delete keyword is followed by empty square brackets, it
3467 // shall be interpreted as [array delete].
3468 // [Footnote: A lambda expression with a lambda-introducer that consists
3469 // of empty square brackets can follow the delete keyword if
3470 // the lambda expression is enclosed in parentheses.]
3471
3472 const Token Next = GetLookAheadToken(2);
3473
3474 // Basic lookahead to check if we have a lambda expression.
3475 if (Next.isOneOf(tok::l_brace, tok::less) ||
3476 (Next.is(tok::l_paren) &&
3477 (GetLookAheadToken(3).is(tok::r_paren) ||
3478 (GetLookAheadToken(3).is(tok::identifier) &&
3479 GetLookAheadToken(4).is(tok::identifier))))) {
3480 TentativeParsingAction TPA(*this);
3481 SourceLocation LSquareLoc = Tok.getLocation();
3482 SourceLocation RSquareLoc = NextToken().getLocation();
3483
3484 // SkipUntil can't skip pairs of </*...*/>; don't emit a FixIt in this
3485 // case.
3486 SkipUntil({tok::l_brace, tok::less}, StopBeforeMatch);
3487 SourceLocation RBraceLoc;
3488 bool EmitFixIt = false;
3489 if (Tok.is(tok::l_brace)) {
3490 ConsumeBrace();
3491 SkipUntil(tok::r_brace, StopBeforeMatch);
3492 RBraceLoc = Tok.getLocation();
3493 EmitFixIt = true;
3494 }
3495
3496 TPA.Revert();
3497
3498 if (EmitFixIt)
3499 Diag(Start, diag::err_lambda_after_delete)
3500 << SourceRange(Start, RSquareLoc)
3501 << FixItHint::CreateInsertion(LSquareLoc, "(")
3504 RBraceLoc, 0, Actions.getSourceManager(), getLangOpts()),
3505 ")");
3506 else
3507 Diag(Start, diag::err_lambda_after_delete)
3508 << SourceRange(Start, RSquareLoc);
3509
3510 // Warn that the non-capturing lambda isn't surrounded by parentheses
3511 // to disambiguate it from 'delete[]'.
3512 ExprResult Lambda = ParseLambdaExpression();
3513 if (Lambda.isInvalid())
3514 return ExprError();
3515
3516 // Evaluate any postfix expressions used on the lambda.
3517 Lambda = ParsePostfixExpressionSuffix(Lambda);
3518 if (Lambda.isInvalid())
3519 return ExprError();
3520 return Actions.ActOnCXXDelete(Start, UseGlobal, /*ArrayForm=*/false,
3521 Lambda.get());
3522 }
3523
3524 ArrayDelete = true;
3525 BalancedDelimiterTracker T(*this, tok::l_square);
3526
3527 T.consumeOpen();
3528 T.consumeClose();
3529 if (T.getCloseLocation().isInvalid())
3530 return ExprError();
3531 }
3532
3533 ExprResult Operand(ParseCastExpression(AnyCastExpr));
3534 if (Operand.isInvalid())
3535 return Operand;
3536
3537 return Actions.ActOnCXXDelete(Start, UseGlobal, ArrayDelete, Operand.get());
3538}
3539
3540/// ParseRequiresExpression - Parse a C++2a requires-expression.
3541/// C++2a [expr.prim.req]p1
3542/// A requires-expression provides a concise way to express requirements on
3543/// template arguments. A requirement is one that can be checked by name
3544/// lookup (6.4) or by checking properties of types and expressions.
3545///
3546/// requires-expression:
3547/// 'requires' requirement-parameter-list[opt] requirement-body
3548///
3549/// requirement-parameter-list:
3550/// '(' parameter-declaration-clause[opt] ')'
3551///
3552/// requirement-body:
3553/// '{' requirement-seq '}'
3554///
3555/// requirement-seq:
3556/// requirement
3557/// requirement-seq requirement
3558///
3559/// requirement:
3560/// simple-requirement
3561/// type-requirement
3562/// compound-requirement
3563/// nested-requirement
3564ExprResult Parser::ParseRequiresExpression() {
3565 assert(Tok.is(tok::kw_requires) && "Expected 'requires' keyword");
3566 SourceLocation RequiresKWLoc = ConsumeToken(); // Consume 'requires'
3567
3568 llvm::SmallVector<ParmVarDecl *, 2> LocalParameterDecls;
3569 BalancedDelimiterTracker Parens(*this, tok::l_paren);
3570 if (Tok.is(tok::l_paren)) {
3571 // requirement parameter list is present.
3572 ParseScope LocalParametersScope(this, Scope::FunctionPrototypeScope |
3574 Parens.consumeOpen();
3575 if (!Tok.is(tok::r_paren)) {
3576 ParsedAttributes FirstArgAttrs(getAttrFactory());
3577 SourceLocation EllipsisLoc;
3579 ParseParameterDeclarationClause(DeclaratorContext::RequiresExpr,
3580 FirstArgAttrs, LocalParameters,
3581 EllipsisLoc);
3582 if (EllipsisLoc.isValid())
3583 Diag(EllipsisLoc, diag::err_requires_expr_parameter_list_ellipsis);
3584 for (auto &ParamInfo : LocalParameters)
3585 LocalParameterDecls.push_back(cast<ParmVarDecl>(ParamInfo.Param));
3586 }
3587 Parens.consumeClose();
3588 }
3589
3590 BalancedDelimiterTracker Braces(*this, tok::l_brace);
3591 if (Braces.expectAndConsume())
3592 return ExprError();
3593
3594 // Start of requirement list
3596
3597 // C++2a [expr.prim.req]p2
3598 // Expressions appearing within a requirement-body are unevaluated operands.
3601
3602 ParseScope BodyScope(this, Scope::DeclScope);
3603 // Create a separate diagnostic pool for RequiresExprBodyDecl.
3604 // Dependent diagnostics are attached to this Decl and non-depenedent
3605 // diagnostics are surfaced after this parse.
3608 RequiresKWLoc, LocalParameterDecls, getCurScope());
3609
3610 if (Tok.is(tok::r_brace)) {
3611 // Grammar does not allow an empty body.
3612 // requirement-body:
3613 // { requirement-seq }
3614 // requirement-seq:
3615 // requirement
3616 // requirement-seq requirement
3617 Diag(Tok, diag::err_empty_requires_expr);
3618 // Continue anyway and produce a requires expr with no requirements.
3619 } else {
3620 while (!Tok.is(tok::r_brace)) {
3621 switch (Tok.getKind()) {
3622 case tok::l_brace: {
3623 // Compound requirement
3624 // C++ [expr.prim.req.compound]
3625 // compound-requirement:
3626 // '{' expression '}' 'noexcept'[opt]
3627 // return-type-requirement[opt] ';'
3628 // return-type-requirement:
3629 // trailing-return-type
3630 // '->' cv-qualifier-seq[opt] constrained-parameter
3631 // cv-qualifier-seq[opt] abstract-declarator[opt]
3632 BalancedDelimiterTracker ExprBraces(*this, tok::l_brace);
3633 ExprBraces.consumeOpen();
3636 if (!Expression.isUsable()) {
3637 ExprBraces.skipToEnd();
3638 SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3639 break;
3640 }
3641 if (ExprBraces.consumeClose())
3642 ExprBraces.skipToEnd();
3643
3644 concepts::Requirement *Req = nullptr;
3645 SourceLocation NoexceptLoc;
3646 TryConsumeToken(tok::kw_noexcept, NoexceptLoc);
3647 if (Tok.is(tok::semi)) {
3648 Req = Actions.ActOnCompoundRequirement(Expression.get(), NoexceptLoc);
3649 if (Req)
3650 Requirements.push_back(Req);
3651 break;
3652 }
3653 if (!TryConsumeToken(tok::arrow))
3654 // User probably forgot the arrow, remind them and try to continue.
3655 Diag(Tok, diag::err_requires_expr_missing_arrow)
3657 // Try to parse a 'type-constraint'
3658 if (TryAnnotateTypeConstraint()) {
3659 SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3660 break;
3661 }
3662 if (!isTypeConstraintAnnotation()) {
3663 Diag(Tok, diag::err_requires_expr_expected_type_constraint);
3664 SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3665 break;
3666 }
3667 CXXScopeSpec SS;
3668 if (Tok.is(tok::annot_cxxscope)) {
3670 Tok.getAnnotationRange(),
3671 SS);
3672 ConsumeAnnotationToken();
3673 }
3674
3675 Req = Actions.ActOnCompoundRequirement(
3676 Expression.get(), NoexceptLoc, SS, takeTemplateIdAnnotation(Tok),
3677 TemplateParameterDepth);
3678 ConsumeAnnotationToken();
3679 if (Req)
3680 Requirements.push_back(Req);
3681 break;
3682 }
3683 default: {
3684 bool PossibleRequiresExprInSimpleRequirement = false;
3685 if (Tok.is(tok::kw_requires)) {
3686 auto IsNestedRequirement = [&] {
3687 RevertingTentativeParsingAction TPA(*this);
3688 ConsumeToken(); // 'requires'
3689 if (Tok.is(tok::l_brace))
3690 // This is a requires expression
3691 // requires (T t) {
3692 // requires { t++; };
3693 // ... ^
3694 // }
3695 return false;
3696 if (Tok.is(tok::l_paren)) {
3697 // This might be the parameter list of a requires expression
3698 ConsumeParen();
3699 auto Res = TryParseParameterDeclarationClause();
3700 if (Res != TPResult::False) {
3701 // Skip to the closing parenthesis
3702 unsigned Depth = 1;
3703 while (Depth != 0) {
3704 bool FoundParen = SkipUntil(tok::l_paren, tok::r_paren,
3706 if (!FoundParen)
3707 break;
3708 if (Tok.is(tok::l_paren))
3709 Depth++;
3710 else if (Tok.is(tok::r_paren))
3711 Depth--;
3713 }
3714 // requires (T t) {
3715 // requires () ?
3716 // ... ^
3717 // - OR -
3718 // requires (int x) ?
3719 // ... ^
3720 // }
3721 if (Tok.is(tok::l_brace))
3722 // requires (...) {
3723 // ^ - a requires expression as a
3724 // simple-requirement.
3725 return false;
3726 }
3727 }
3728 return true;
3729 };
3730 if (IsNestedRequirement()) {
3731 ConsumeToken();
3732 // Nested requirement
3733 // C++ [expr.prim.req.nested]
3734 // nested-requirement:
3735 // 'requires' constraint-expression ';'
3736 ExprResult ConstraintExpr =
3738 if (ConstraintExpr.isInvalid() || !ConstraintExpr.isUsable()) {
3739 SkipUntil(tok::semi, tok::r_brace,
3741 break;
3742 }
3743 if (auto *Req =
3744 Actions.ActOnNestedRequirement(ConstraintExpr.get()))
3745 Requirements.push_back(Req);
3746 else {
3747 SkipUntil(tok::semi, tok::r_brace,
3749 break;
3750 }
3751 break;
3752 } else
3753 PossibleRequiresExprInSimpleRequirement = true;
3754 } else if (Tok.is(tok::kw_typename)) {
3755 // This might be 'typename T::value_type;' (a type requirement) or
3756 // 'typename T::value_type{};' (a simple requirement).
3757 TentativeParsingAction TPA(*this);
3758
3759 // We need to consume the typename to allow 'requires { typename a; }'
3760 SourceLocation TypenameKWLoc = ConsumeToken();
3762 TPA.Commit();
3763 SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3764 break;
3765 }
3766 CXXScopeSpec SS;
3767 if (Tok.is(tok::annot_cxxscope)) {
3769 Tok.getAnnotationValue(), Tok.getAnnotationRange(), SS);
3770 ConsumeAnnotationToken();
3771 }
3772
3773 if (Tok.isOneOf(tok::identifier, tok::annot_template_id) &&
3774 !NextToken().isOneOf(tok::l_brace, tok::l_paren)) {
3775 TPA.Commit();
3776 SourceLocation NameLoc = Tok.getLocation();
3777 IdentifierInfo *II = nullptr;
3778 TemplateIdAnnotation *TemplateId = nullptr;
3779 if (Tok.is(tok::identifier)) {
3780 II = Tok.getIdentifierInfo();
3781 ConsumeToken();
3782 } else {
3783 TemplateId = takeTemplateIdAnnotation(Tok);
3784 ConsumeAnnotationToken();
3785 if (TemplateId->isInvalid())
3786 break;
3787 }
3788
3789 if (auto *Req = Actions.ActOnTypeRequirement(TypenameKWLoc, SS,
3790 NameLoc, II,
3791 TemplateId)) {
3792 Requirements.push_back(Req);
3793 }
3794 break;
3795 }
3796 TPA.Revert();
3797 }
3798 // Simple requirement
3799 // C++ [expr.prim.req.simple]
3800 // simple-requirement:
3801 // expression ';'
3802 SourceLocation StartLoc = Tok.getLocation();
3805 if (!Expression.isUsable()) {
3806 SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3807 break;
3808 }
3809 if (!Expression.isInvalid() && PossibleRequiresExprInSimpleRequirement)
3810 Diag(StartLoc, diag::err_requires_expr_in_simple_requirement)
3811 << FixItHint::CreateInsertion(StartLoc, "requires");
3812 if (auto *Req = Actions.ActOnSimpleRequirement(Expression.get()))
3813 Requirements.push_back(Req);
3814 else {
3815 SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3816 break;
3817 }
3818 // User may have tried to put some compound requirement stuff here
3819 if (Tok.is(tok::kw_noexcept)) {
3820 Diag(Tok, diag::err_requires_expr_simple_requirement_noexcept)
3821 << FixItHint::CreateInsertion(StartLoc, "{")
3823 SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3824 break;
3825 }
3826 break;
3827 }
3828 }
3829 if (ExpectAndConsumeSemi(diag::err_expected_semi_requirement)) {
3830 SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3831 TryConsumeToken(tok::semi);
3832 break;
3833 }
3834 }
3835 if (Requirements.empty()) {
3836 // Don't emit an empty requires expr here to avoid confusing the user with
3837 // other diagnostics quoting an empty requires expression they never
3838 // wrote.
3839 Braces.consumeClose();
3840 Actions.ActOnFinishRequiresExpr();
3841 return ExprError();
3842 }
3843 }
3844 Braces.consumeClose();
3845 Actions.ActOnFinishRequiresExpr();
3846 ParsingBodyDecl.complete(Body);
3847 return Actions.ActOnRequiresExpr(
3848 RequiresKWLoc, Body, Parens.getOpenLocation(), LocalParameterDecls,
3849 Parens.getCloseLocation(), Requirements, Braces.getCloseLocation());
3850}
3851
3853 switch (kind) {
3854 default: llvm_unreachable("Not a known type trait");
3855#define TYPE_TRAIT_1(Spelling, Name, Key) \
3856case tok::kw_ ## Spelling: return UTT_ ## Name;
3857#define TYPE_TRAIT_2(Spelling, Name, Key) \
3858case tok::kw_ ## Spelling: return BTT_ ## Name;
3859#include "clang/Basic/TokenKinds.def"
3860#define TYPE_TRAIT_N(Spelling, Name, Key) \
3861 case tok::kw_ ## Spelling: return TT_ ## Name;
3862#include "clang/Basic/TokenKinds.def"
3863 }
3864}
3865
3867 switch (kind) {
3868 default:
3869 llvm_unreachable("Not a known array type trait");
3870#define ARRAY_TYPE_TRAIT(Spelling, Name, Key) \
3871 case tok::kw_##Spelling: \
3872 return ATT_##Name;
3873#include "clang/Basic/TokenKinds.def"
3874 }
3875}
3876
3878 switch (kind) {
3879 default:
3880 llvm_unreachable("Not a known unary expression trait.");
3881#define EXPRESSION_TRAIT(Spelling, Name, Key) \
3882 case tok::kw_##Spelling: \
3883 return ET_##Name;
3884#include "clang/Basic/TokenKinds.def"
3885 }
3886}
3887
3888/// Parse the built-in type-trait pseudo-functions that allow
3889/// implementation of the TR1/C++11 type traits templates.
3890///
3891/// primary-expression:
3892/// unary-type-trait '(' type-id ')'
3893/// binary-type-trait '(' type-id ',' type-id ')'
3894/// type-trait '(' type-id-seq ')'
3895///
3896/// type-id-seq:
3897/// type-id ...[opt] type-id-seq[opt]
3898///
3899ExprResult Parser::ParseTypeTrait() {
3900 tok::TokenKind Kind = Tok.getKind();
3901
3903
3904 BalancedDelimiterTracker Parens(*this, tok::l_paren);
3905 if (Parens.expectAndConsume())
3906 return ExprError();
3907
3909 do {
3910 // Parse the next type.
3911 TypeResult Ty =
3912 ParseTypeName(/*SourceRange=*/nullptr,
3915 if (Ty.isInvalid()) {
3916 Parens.skipToEnd();
3917 return ExprError();
3918 }
3919
3920 // Parse the ellipsis, if present.
3921 if (Tok.is(tok::ellipsis)) {
3922 Ty = Actions.ActOnPackExpansion(Ty.get(), ConsumeToken());
3923 if (Ty.isInvalid()) {
3924 Parens.skipToEnd();
3925 return ExprError();
3926 }
3927 }
3928
3929 // Add this type to the list of arguments.
3930 Args.push_back(Ty.get());
3931 } while (TryConsumeToken(tok::comma));
3932
3933 if (Parens.consumeClose())
3934 return ExprError();
3935
3936 SourceLocation EndLoc = Parens.getCloseLocation();
3937
3938 return Actions.ActOnTypeTrait(TypeTraitFromTokKind(Kind), Loc, Args, EndLoc);
3939}
3940
3941/// ParseArrayTypeTrait - Parse the built-in array type-trait
3942/// pseudo-functions.
3943///
3944/// primary-expression:
3945/// [Embarcadero] '__array_rank' '(' type-id ')'
3946/// [Embarcadero] '__array_extent' '(' type-id ',' expression ')'
3947///
3948ExprResult Parser::ParseArrayTypeTrait() {
3951
3952 BalancedDelimiterTracker T(*this, tok::l_paren);
3953 if (T.expectAndConsume())
3954 return ExprError();
3955
3956 TypeResult Ty =
3957 ParseTypeName(/*SourceRange=*/nullptr, DeclaratorContext::TemplateArg);
3958 if (Ty.isInvalid()) {
3959 SkipUntil(tok::comma, StopAtSemi);
3960 SkipUntil(tok::r_paren, StopAtSemi);
3961 return ExprError();
3962 }
3963
3964 switch (ATT) {
3965 case ATT_ArrayRank: {
3966 T.consumeClose();
3967 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), nullptr,
3968 T.getCloseLocation());
3969 }
3970 case ATT_ArrayExtent: {
3971 if (ExpectAndConsume(tok::comma)) {
3972 SkipUntil(tok::r_paren, StopAtSemi);
3973 return ExprError();
3974 }
3975
3976 ExprResult DimExpr = ParseExpression();
3977 T.consumeClose();
3978
3979 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), DimExpr.get(),
3980 T.getCloseLocation());
3981 }
3982 }
3983 llvm_unreachable("Invalid ArrayTypeTrait!");
3984}
3985
3986/// ParseExpressionTrait - Parse built-in expression-trait
3987/// pseudo-functions like __is_lvalue_expr( xxx ).
3988///
3989/// primary-expression:
3990/// [Embarcadero] expression-trait '(' expression ')'
3991///
3992ExprResult Parser::ParseExpressionTrait() {
3995
3996 BalancedDelimiterTracker T(*this, tok::l_paren);
3997 if (T.expectAndConsume())
3998 return ExprError();
3999
4001
4002 T.consumeClose();
4003
4004 return Actions.ActOnExpressionTrait(ET, Loc, Expr.get(),
4005 T.getCloseLocation());
4006}
4007
4008
4009/// ParseCXXAmbiguousParenExpression - We have parsed the left paren of a
4010/// parenthesized ambiguous type-id. This uses tentative parsing to disambiguate
4011/// based on the context past the parens.
4013Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType,
4014 ParsedType &CastTy,
4015 BalancedDelimiterTracker &Tracker,
4016 ColonProtectionRAIIObject &ColonProt) {
4017 assert(getLangOpts().CPlusPlus && "Should only be called for C++!");
4018 assert(ExprType == CastExpr && "Compound literals are not ambiguous!");
4019 assert(isTypeIdInParens() && "Not a type-id!");
4020
4021 ExprResult Result(true);
4022 CastTy = nullptr;
4023
4024 // We need to disambiguate a very ugly part of the C++ syntax:
4025 //
4026 // (T())x; - type-id
4027 // (T())*x; - type-id
4028 // (T())/x; - expression
4029 // (T()); - expression
4030 //
4031 // The bad news is that we cannot use the specialized tentative parser, since
4032 // it can only verify that the thing inside the parens can be parsed as
4033 // type-id, it is not useful for determining the context past the parens.
4034 //
4035 // The good news is that the parser can disambiguate this part without
4036 // making any unnecessary Action calls.
4037 //
4038 // It uses a scheme similar to parsing inline methods. The parenthesized
4039 // tokens are cached, the context that follows is determined (possibly by
4040 // parsing a cast-expression), and then we re-introduce the cached tokens
4041 // into the token stream and parse them appropriately.
4042
4043 ParenParseOption ParseAs;
4044 CachedTokens Toks;
4045
4046 // Store the tokens of the parentheses. We will parse them after we determine
4047 // the context that follows them.
4048 if (!ConsumeAndStoreUntil(tok::r_paren, Toks)) {
4049 // We didn't find the ')' we expected.
4050 Tracker.consumeClose();
4051 return ExprError();
4052 }
4053
4054 if (Tok.is(tok::l_brace)) {
4055 ParseAs = CompoundLiteral;
4056 } else {
4057 bool NotCastExpr;
4058 if (Tok.is(tok::l_paren) && NextToken().is(tok::r_paren)) {
4059 NotCastExpr = true;
4060 } else {
4061 // Try parsing the cast-expression that may follow.
4062 // If it is not a cast-expression, NotCastExpr will be true and no token
4063 // will be consumed.
4064 ColonProt.restore();
4065 Result = ParseCastExpression(AnyCastExpr,
4066 false/*isAddressofOperand*/,
4067 NotCastExpr,
4068 // type-id has priority.
4069 IsTypeCast);
4070 }
4071
4072 // If we parsed a cast-expression, it's really a type-id, otherwise it's
4073 // an expression.
4074 ParseAs = NotCastExpr ? SimpleExpr : CastExpr;
4075 }
4076
4077 // Create a fake EOF to mark end of Toks buffer.
4078 Token AttrEnd;
4079 AttrEnd.startToken();
4080 AttrEnd.setKind(tok::eof);
4081 AttrEnd.setLocation(Tok.getLocation());
4082 AttrEnd.setEofData(Toks.data());
4083 Toks.push_back(AttrEnd);
4084
4085 // The current token should go after the cached tokens.
4086 Toks.push_back(Tok);
4087 // Re-enter the stored parenthesized tokens into the token stream, so we may
4088 // parse them now.
4089 PP.EnterTokenStream(Toks, /*DisableMacroExpansion*/ true,
4090 /*IsReinject*/ true);
4091 // Drop the current token and bring the first cached one. It's the same token
4092 // as when we entered this function.
4094
4095 if (ParseAs >= CompoundLiteral) {
4096 // Parse the type declarator.
4097 DeclSpec DS(AttrFactory);
4098 Declarator DeclaratorInfo(DS, ParsedAttributesView::none(),
4100 {
4101 ColonProtectionRAIIObject InnerColonProtection(*this);
4102 ParseSpecifierQualifierList(DS);
4103 ParseDeclarator(DeclaratorInfo);
4104 }
4105
4106 // Match the ')'.
4107 Tracker.consumeClose();
4108 ColonProt.restore();
4109
4110 // Consume EOF marker for Toks buffer.
4111 assert(Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData());
4113
4114 if (ParseAs == CompoundLiteral) {
4115 ExprType = CompoundLiteral;
4116 if (DeclaratorInfo.isInvalidType())
4117 return ExprError();
4118
4119 TypeResult Ty = Actions.ActOnTypeName(DeclaratorInfo);
4120 return ParseCompoundLiteralExpression(Ty.get(),
4121 Tracker.getOpenLocation(),
4122 Tracker.getCloseLocation());
4123 }
4124
4125 // We parsed '(' type-id ')' and the thing after it wasn't a '{'.
4126 assert(ParseAs == CastExpr);
4127
4128 if (DeclaratorInfo.isInvalidType())
4129 return ExprError();
4130
4131 // Result is what ParseCastExpression returned earlier.
4132 if (!Result.isInvalid())
4133 Result = Actions.ActOnCastExpr(getCurScope(), Tracker.getOpenLocation(),
4134 DeclaratorInfo, CastTy,
4135 Tracker.getCloseLocation(), Result.get());
4136 return Result;
4137 }
4138
4139 // Not a compound literal, and not followed by a cast-expression.
4140 assert(ParseAs == SimpleExpr);
4141
4142 ExprType = SimpleExpr;
4144 if (!Result.isInvalid() && Tok.is(tok::r_paren))
4145 Result = Actions.ActOnParenExpr(Tracker.getOpenLocation(),
4146 Tok.getLocation(), Result.get());
4147
4148 // Match the ')'.
4149 if (Result.isInvalid()) {
4150 while (Tok.isNot(tok::eof))
4152 assert(Tok.getEofData() == AttrEnd.getEofData());
4154 return ExprError();
4155 }
4156
4157 Tracker.consumeClose();
4158 // Consume EOF marker for Toks buffer.
4159 assert(Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData());
4161 return Result;
4162}
4163
4164/// Parse a __builtin_bit_cast(T, E).
4165ExprResult Parser::ParseBuiltinBitCast() {
4166 SourceLocation KWLoc = ConsumeToken();
4167
4168 BalancedDelimiterTracker T(*this, tok::l_paren);
4169 if (T.expectAndConsume(diag::err_expected_lparen_after, "__builtin_bit_cast"))
4170 return ExprError();
4171
4172 // Parse the common declaration-specifiers piece.
4173 DeclSpec DS(AttrFactory);
4174 ParseSpecifierQualifierList(DS);
4175
4176 // Parse the abstract-declarator, if present.
4177 Declarator DeclaratorInfo(DS, ParsedAttributesView::none(),
4179 ParseDeclarator(DeclaratorInfo);
4180
4181 if (ExpectAndConsume(tok::comma)) {
4182 Diag(Tok.getLocation(), diag::err_expected) << tok::comma;
4183 SkipUntil(tok::r_paren, StopAtSemi);
4184 return ExprError();
4185 }
4186
4188
4189 if (T.consumeClose())
4190 return ExprError();
4191
4192 if (Operand.isInvalid() || DeclaratorInfo.isInvalidType())
4193 return ExprError();
4194
4195 return Actions.ActOnBuiltinBitCastExpr(KWLoc, DeclaratorInfo, Operand,
4196 T.getCloseLocation());
4197}
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:2960
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:692
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:3489
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:444
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1899
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition: DeclSpec.h:2046
void SetSourceRange(SourceRange R)
Definition: DeclSpec.h:2085
void AddTypeInfo(const DeclaratorChunk &TI, ParsedAttributes &&attrs, SourceLocation EndLoc)
AddTypeInfo - Add a chunk to this declarator.
Definition: DeclSpec.h:2352
bool isInvalidType() const
Definition: DeclSpec.h:2713
DeclSpec & getMutableDeclSpec()
getMutableDeclSpec - Return a non-const version of the DeclSpec.
Definition: DeclSpec.h:2053
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:831
ParsedAttributes - A collection of parsed attributes.
Definition: ParsedAttr.h:951
Parser - This implements a parser for the C family of languages.
Definition: Parser.h:54
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:46
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:514
AttributeFactory & getAttrFactory()
Definition: Parser.h:465
static TypeResult getTypeAnnotation(const Token &Tok)
getTypeAnnotation - Read a parsed type out of an annotation token.
Definition: Parser.h:843
ExprResult ParseConstraintLogicalOrExpression(bool IsTrailingRequiresClause)
Parse a constraint-logical-or-expression.
Definition: ParseExpr.cpp:374
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:902
SourceLocation ConsumeAnyToken(bool ConsumeCodeCompletionTok=false)
ConsumeAnyToken - Dispatch to the right Consume* method based on the current token type.
Definition: Parser.h:542
ExprResult ParseConstantExpression()
Definition: ParseExpr.cpp:227
bool TryConsumeToken(tok::TokenKind Expected)
Definition: Parser.h:522
OpaquePtr< DeclGroupRef > DeclGroupPtrTy
Definition: Parser.h:479
Scope * getCurScope() const
Definition: Parser.h:468
OpaquePtr< TemplateName > TemplateTy
Definition: Parser.h:480
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:1260
ExprResult ParseAssignmentExpression(TypeCastState isTypeCast=NotTypeCast)
Parse an expr that doesn't include (top-level) commas.
Definition: ParseExpr.cpp:163
const LangOptions & getLangOpts() const
Definition: Parser.h:461
ExprResult ParseExpression(TypeCastState isTypeCast=NotTypeCast)
Simple precedence-based parser for binary/ternary operators.
Definition: ParseExpr.cpp:126
@ StopBeforeMatch
Stop skipping at specified token, but don't skip the token itself.
Definition: Parser.h:1241
@ StopAtSemi
Stop skipping at semicolon.
Definition: Parser.h:1239
const Token & NextToken()
NextToken - This peeks ahead one token and returns it without consuming it.
Definition: Parser.h:838
ExprResult ParseConstraintExpression()
Parse a constraint-expression.
Definition: ParseExpr.cpp:260
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:737
Represents the body of a requires-expression.
Definition: DeclCXX.h:2023
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 ).
ParsedType getConstructorName(IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec &SS, bool EnteringContext)
Definition: SemaExprCXX.cpp:92
ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body)
ActOnLambdaExpr - This is called when the body of a lambda expression was successfully completed.
void CodeCompleteObjCMessageReceiver(Scope *S)
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...
concepts::Requirement * ActOnTypeRequirement(SourceLocation TypenameKWLoc, CXXScopeSpec &SS, SourceLocation NameLoc, IdentifierInfo *TypeName, TemplateIdAnnotation *TemplateId)
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:6116
@ 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:2685
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:48
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:14793
ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E)
ExprResult ActOnCXXThis(SourceLocation loc)
ASTContext & getASTContext() const
Definition: Sema.h:501
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:8694
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:2400
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:1263
ExprResult ActOnBuiltinBitCastExpr(SourceLocation KWLoc, Declarator &Dcl, ExprResult Operand, SourceLocation RParenLoc)
Definition: SemaCast.cpp:387
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:21174
sema::LambdaScopeInfo * PushLambdaScope()
Definition: Sema.cpp:2159
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:5416
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:70
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:278
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:12848
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:4341
SourceManager & getSourceManager() const
Definition: Sema.h:499
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:502
bool ActOnCXXNestedNameSpecifierIndexedPack(CXXScopeSpec &SS, const DeclSpec &DS, SourceLocation ColonColonLoc, QualType Type)
TypeResult ActOnTemplateIdType(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy Template, IdentifierInfo *TemplateII, SourceLocation TemplateIILoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, bool IsCtorOrDtorName=false, bool IsClassName=false, ImplicitTypenameContext AllowImplicitTypename=ImplicitTypenameContext::No)
ParsedType getDestructorName(IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec &SS, ParsedType ObjectType, bool EnteringContext)
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:7383
void ActOnInitializerError(Decl *Dcl)
ActOnInitializerError - Given that there was an error parsing an initializer for the given declaratio...
Definition: SemaDecl.cpp:14015
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:1244
TypeResult ActOnTypeName(Declarator &D)
Definition: SemaType.cpp:6787
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...
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:2166
StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, SourceLocation StartLoc, SourceLocation EndLoc)
Definition: SemaStmt.cpp:75
void CodeCompleteOrdinaryName(Scope *S, ParserCompletionContext CompletionContext)
ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, Declarator &D, ParsedType &Ty, SourceLocation RParenLoc, Expr *CastExpr)
Definition: SemaExpr.cpp:8520
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:9842
void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit)
AddInitializerToDecl - Adds the initializer Init to the declaration dcl.
Definition: SemaDecl.cpp:13503
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:1253
concepts::Requirement * ActOnNestedRequirement(Expr *Constraint)
static ConditionResult ConditionError()
Definition: Sema.h:6103
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:1606
QualType getCanonicalTypeInternal() const
Definition: Type.h:2703
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:59
@ CPlusPlus20
Definition: LangStandard.h:58
@ CPlusPlus
Definition: LangStandard.h:54
@ CPlusPlus11
Definition: LangStandard.h:55
@ CPlusPlus17
Definition: LangStandard.h:57
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:2823
@ CopyInit
[a = b], [a = {b}]
DeclaratorContext
Definition: DeclSpec.h:1849
@ 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 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:1695
Represents a complete lambda introducer.
Definition: DeclSpec.h:2831
bool hasLambdaCapture() const
Definition: DeclSpec.h:2860
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:2865
SourceLocation DefaultLoc
Definition: DeclSpec.h:2854
LambdaCaptureDefault Default
Definition: DeclSpec.h:2855
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:2508
Information about a template-id annotation token.
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.
static TemplateIdAnnotation * Create(SourceLocation TemplateKWLoc, SourceLocation TemplateNameLoc, 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.
ParsedTemplateTy Template
The declaration of the template corresponding to the template-name.
IdentifierInfo * Name
FIXME: Temporarily stores the name of a specialization.