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