clang  7.0.0svn
ParseExprCXX.cpp
Go to the documentation of this file.
1 //===--- ParseExprCXX.cpp - C++ Expression Parsing ------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Expression parsing implementation for C++.
11 //
12 //===----------------------------------------------------------------------===//
13 #include "clang/Parse/Parser.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/DeclTemplate.h"
20 #include "clang/Sema/DeclSpec.h"
22 #include "clang/Sema/Scope.h"
23 #include "llvm/Support/ErrorHandling.h"
24 
25 
26 using namespace clang;
27 
29  switch (Kind) {
30  // template name
31  case tok::unknown: return 0;
32  // casts
33  case tok::kw_const_cast: return 1;
34  case tok::kw_dynamic_cast: return 2;
35  case tok::kw_reinterpret_cast: return 3;
36  case tok::kw_static_cast: return 4;
37  default:
38  llvm_unreachable("Unknown type for digraph error message.");
39  }
40 }
41 
42 // Are the two tokens adjacent in the same source file?
43 bool Parser::areTokensAdjacent(const Token &First, const Token &Second) {
45  SourceLocation FirstLoc = SM.getSpellingLoc(First.getLocation());
46  SourceLocation FirstEnd = FirstLoc.getLocWithOffset(First.getLength());
47  return FirstEnd == SM.getSpellingLoc(Second.getLocation());
48 }
49 
50 // Suggest fixit for "<::" after a cast.
51 static void FixDigraph(Parser &P, Preprocessor &PP, Token &DigraphToken,
52  Token &ColonToken, tok::TokenKind Kind, bool AtDigraph) {
53  // Pull '<:' and ':' off token stream.
54  if (!AtDigraph)
55  PP.Lex(DigraphToken);
56  PP.Lex(ColonToken);
57 
58  SourceRange Range;
59  Range.setBegin(DigraphToken.getLocation());
60  Range.setEnd(ColonToken.getLocation());
61  P.Diag(DigraphToken.getLocation(), diag::err_missing_whitespace_digraph)
63  << FixItHint::CreateReplacement(Range, "< ::");
64 
65  // Update token information to reflect their change in token type.
66  ColonToken.setKind(tok::coloncolon);
67  ColonToken.setLocation(ColonToken.getLocation().getLocWithOffset(-1));
68  ColonToken.setLength(2);
69  DigraphToken.setKind(tok::less);
70  DigraphToken.setLength(1);
71 
72  // Push new tokens back to token stream.
73  PP.EnterToken(ColonToken);
74  if (!AtDigraph)
75  PP.EnterToken(DigraphToken);
76 }
77 
78 // Check for '<::' which should be '< ::' instead of '[:' when following
79 // a template name.
80 void Parser::CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectType,
81  bool EnteringContext,
82  IdentifierInfo &II, CXXScopeSpec &SS) {
83  if (!Next.is(tok::l_square) || Next.getLength() != 2)
84  return;
85 
86  Token SecondToken = GetLookAheadToken(2);
87  if (!SecondToken.is(tok::colon) || !areTokensAdjacent(Next, SecondToken))
88  return;
89 
90  TemplateTy Template;
92  TemplateName.setIdentifier(&II, Tok.getLocation());
93  bool MemberOfUnknownSpecialization;
94  if (!Actions.isTemplateName(getCurScope(), SS, /*hasTemplateKeyword=*/false,
95  TemplateName, ObjectType, EnteringContext,
96  Template, MemberOfUnknownSpecialization))
97  return;
98 
99  FixDigraph(*this, PP, Next, SecondToken, tok::unknown,
100  /*AtDigraph*/false);
101 }
102 
103 /// Parse global scope or nested-name-specifier if present.
104 ///
105 /// Parses a C++ global scope specifier ('::') or nested-name-specifier (which
106 /// may be preceded by '::'). Note that this routine will not parse ::new or
107 /// ::delete; it will just leave them in the token stream.
108 ///
109 /// '::'[opt] nested-name-specifier
110 /// '::'
111 ///
112 /// nested-name-specifier:
113 /// type-name '::'
114 /// namespace-name '::'
115 /// nested-name-specifier identifier '::'
116 /// nested-name-specifier 'template'[opt] simple-template-id '::'
117 ///
118 ///
119 /// \param SS the scope specifier that will be set to the parsed
120 /// nested-name-specifier (or empty)
121 ///
122 /// \param ObjectType if this nested-name-specifier is being parsed following
123 /// the "." or "->" of a member access expression, this parameter provides the
124 /// type of the object whose members are being accessed.
125 ///
126 /// \param EnteringContext whether we will be entering into the context of
127 /// the nested-name-specifier after parsing it.
128 ///
129 /// \param MayBePseudoDestructor When non-NULL, points to a flag that
130 /// indicates whether this nested-name-specifier may be part of a
131 /// pseudo-destructor name. In this case, the flag will be set false
132 /// if we don't actually end up parsing a destructor name. Moreorover,
133 /// if we do end up determining that we are parsing a destructor name,
134 /// the last component of the nested-name-specifier is not parsed as
135 /// part of the scope specifier.
136 ///
137 /// \param IsTypename If \c true, this nested-name-specifier is known to be
138 /// part of a type name. This is used to improve error recovery.
139 ///
140 /// \param LastII When non-NULL, points to an IdentifierInfo* that will be
141 /// filled in with the leading identifier in the last component of the
142 /// nested-name-specifier, if any.
143 ///
144 /// \param OnlyNamespace If true, only considers namespaces in lookup.
145 ///
146 /// \returns true if there was an error parsing a scope specifier
147 bool Parser::ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS,
148  ParsedType ObjectType,
149  bool EnteringContext,
150  bool *MayBePseudoDestructor,
151  bool IsTypename,
152  IdentifierInfo **LastII,
153  bool OnlyNamespace) {
154  assert(getLangOpts().CPlusPlus &&
155  "Call sites of this function should be guarded by checking for C++");
156 
157  if (Tok.is(tok::annot_cxxscope)) {
158  assert(!LastII && "want last identifier but have already annotated scope");
159  assert(!MayBePseudoDestructor && "unexpected annot_cxxscope");
161  Tok.getAnnotationRange(),
162  SS);
163  ConsumeAnnotationToken();
164  return false;
165  }
166 
167  if (Tok.is(tok::annot_template_id)) {
168  // If the current token is an annotated template id, it may already have
169  // a scope specifier. Restore it.
170  TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
171  SS = TemplateId->SS;
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.
198  if (Actions.ActOnCXXGlobalScopeSpecifier(ConsumeToken(), SS))
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.
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  while (true) {
237  if (HasScopeSpecifier) {
238  // C++ [basic.lookup.classref]p5:
239  // If the qualified-id has the form
240  //
241  // ::class-name-or-namespace-name::...
242  //
243  // the class-name-or-namespace-name is looked up in global scope as a
244  // class-name or namespace-name.
245  //
246  // To implement this, we clear out the object type as soon as we've
247  // seen a leading '::' or part of a nested-name-specifier.
248  ObjectType = nullptr;
249 
250  if (Tok.is(tok::code_completion)) {
251  // Code completion for a nested-name-specifier, where the code
252  // completion token follows the '::'.
253  Actions.CodeCompleteQualifiedId(getCurScope(), SS, EnteringContext);
254  // Include code completion token into the range of the scope otherwise
255  // when we try to annotate the scope tokens the dangling code completion
256  // token will cause assertion in
257  // Preprocessor::AnnotatePreviousCachedTokens.
258  SS.setEndLoc(Tok.getLocation());
259  cutOffParsing();
260  return true;
261  }
262  }
263 
264  // nested-name-specifier:
265  // nested-name-specifier 'template'[opt] simple-template-id '::'
266 
267  // Parse the optional 'template' keyword, then make sure we have
268  // 'identifier <' after it.
269  if (Tok.is(tok::kw_template)) {
270  // If we don't have a scope specifier or an object type, this isn't a
271  // nested-name-specifier, since they aren't allowed to start with
272  // 'template'.
273  if (!HasScopeSpecifier && !ObjectType)
274  break;
275 
276  TentativeParsingAction TPA(*this);
277  SourceLocation TemplateKWLoc = ConsumeToken();
278 
280  if (Tok.is(tok::identifier)) {
281  // Consume the identifier.
282  TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
283  ConsumeToken();
284  } else if (Tok.is(tok::kw_operator)) {
285  // We don't need to actually parse the unqualified-id in this case,
286  // because a simple-template-id cannot start with 'operator', but
287  // go ahead and parse it anyway for consistency with the case where
288  // we already annotated the template-id.
289  if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType,
290  TemplateName)) {
291  TPA.Commit();
292  break;
293  }
294 
295  if (TemplateName.getKind() != UnqualifiedIdKind::IK_OperatorFunctionId &&
297  Diag(TemplateName.getSourceRange().getBegin(),
298  diag::err_id_after_template_in_nested_name_spec)
299  << TemplateName.getSourceRange();
300  TPA.Commit();
301  break;
302  }
303  } else {
304  TPA.Revert();
305  break;
306  }
307 
308  // If the next token is not '<', we have a qualified-id that refers
309  // to a template name, such as T::template apply, but is not a
310  // template-id.
311  if (Tok.isNot(tok::less)) {
312  TPA.Revert();
313  break;
314  }
315 
316  // Commit to parsing the template-id.
317  TPA.Commit();
318  TemplateTy Template;
320  getCurScope(), SS, TemplateKWLoc, TemplateName, ObjectType,
321  EnteringContext, Template, /*AllowInjectedClassName*/ true)) {
322  if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateKWLoc,
323  TemplateName, false))
324  return true;
325  } else
326  return true;
327 
328  continue;
329  }
330 
331  if (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) {
332  // We have
333  //
334  // template-id '::'
335  //
336  // So we need to check whether the template-id is a simple-template-id of
337  // the right kind (it should name a type or be dependent), and then
338  // convert it into a type within the nested-name-specifier.
339  TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
340  if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde)) {
341  *MayBePseudoDestructor = true;
342  return false;
343  }
344 
345  if (LastII)
346  *LastII = TemplateId->Name;
347 
348  // Consume the template-id token.
349  ConsumeAnnotationToken();
350 
351  assert(Tok.is(tok::coloncolon) && "NextToken() not working properly!");
352  SourceLocation CCLoc = ConsumeToken();
353 
354  HasScopeSpecifier = true;
355 
356  ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
357  TemplateId->NumArgs);
358 
360  SS,
361  TemplateId->TemplateKWLoc,
362  TemplateId->Template,
363  TemplateId->TemplateNameLoc,
364  TemplateId->LAngleLoc,
365  TemplateArgsPtr,
366  TemplateId->RAngleLoc,
367  CCLoc,
368  EnteringContext)) {
369  SourceLocation StartLoc
370  = SS.getBeginLoc().isValid()? SS.getBeginLoc()
371  : TemplateId->TemplateNameLoc;
372  SS.SetInvalid(SourceRange(StartLoc, CCLoc));
373  }
374 
375  continue;
376  }
377 
378  // The rest of the nested-name-specifier possibilities start with
379  // tok::identifier.
380  if (Tok.isNot(tok::identifier))
381  break;
382 
383  IdentifierInfo &II = *Tok.getIdentifierInfo();
384 
385  // nested-name-specifier:
386  // type-name '::'
387  // namespace-name '::'
388  // nested-name-specifier identifier '::'
389  Token Next = NextToken();
390  Sema::NestedNameSpecInfo IdInfo(&II, Tok.getLocation(), Next.getLocation(),
391  ObjectType);
392 
393  // If we get foo:bar, this is almost certainly a typo for foo::bar. Recover
394  // and emit a fixit hint for it.
395  if (Next.is(tok::colon) && !ColonIsSacred) {
396  if (Actions.IsInvalidUnlessNestedName(getCurScope(), SS, IdInfo,
397  EnteringContext) &&
398  // If the token after the colon isn't an identifier, it's still an
399  // error, but they probably meant something else strange so don't
400  // recover like this.
401  PP.LookAhead(1).is(tok::identifier)) {
402  Diag(Next, diag::err_unexpected_colon_in_nested_name_spec)
403  << FixItHint::CreateReplacement(Next.getLocation(), "::");
404  // Recover as if the user wrote '::'.
405  Next.setKind(tok::coloncolon);
406  }
407  }
408 
409  if (Next.is(tok::coloncolon) && GetLookAheadToken(2).is(tok::l_brace)) {
410  // It is invalid to have :: {, consume the scope qualifier and pretend
411  // like we never saw it.
412  Token Identifier = Tok; // Stash away the identifier.
413  ConsumeToken(); // Eat the identifier, current token is now '::'.
414  Diag(PP.getLocForEndOfToken(ConsumeToken()), diag::err_expected)
415  << tok::identifier;
416  UnconsumeToken(Identifier); // Stick the identifier back.
417  Next = NextToken(); // Point Next at the '{' token.
418  }
419 
420  if (Next.is(tok::coloncolon)) {
421  if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde) &&
422  !Actions.isNonTypeNestedNameSpecifier(getCurScope(), SS, IdInfo)) {
423  *MayBePseudoDestructor = true;
424  return false;
425  }
426 
427  if (ColonIsSacred) {
428  const Token &Next2 = GetLookAheadToken(2);
429  if (Next2.is(tok::kw_private) || Next2.is(tok::kw_protected) ||
430  Next2.is(tok::kw_public) || Next2.is(tok::kw_virtual)) {
431  Diag(Next2, diag::err_unexpected_token_in_nested_name_spec)
432  << Next2.getName()
434  Token ColonColon;
435  PP.Lex(ColonColon);
436  ColonColon.setKind(tok::colon);
437  PP.EnterToken(ColonColon);
438  break;
439  }
440  }
441 
442  if (LastII)
443  *LastII = &II;
444 
445  // We have an identifier followed by a '::'. Lookup this name
446  // as the name in a nested-name-specifier.
447  Token Identifier = Tok;
448  SourceLocation IdLoc = ConsumeToken();
449  assert(Tok.isOneOf(tok::coloncolon, tok::colon) &&
450  "NextToken() not working properly!");
451  Token ColonColon = Tok;
452  SourceLocation CCLoc = ConsumeToken();
453 
454  bool IsCorrectedToColon = false;
455  bool *CorrectionFlagPtr = ColonIsSacred ? &IsCorrectedToColon : nullptr;
456  if (Actions.ActOnCXXNestedNameSpecifier(
457  getCurScope(), IdInfo, EnteringContext, SS, false,
458  CorrectionFlagPtr, OnlyNamespace)) {
459  // Identifier is not recognized as a nested name, but we can have
460  // mistyped '::' instead of ':'.
461  if (CorrectionFlagPtr && IsCorrectedToColon) {
462  ColonColon.setKind(tok::colon);
463  PP.EnterToken(Tok);
464  PP.EnterToken(ColonColon);
465  Tok = Identifier;
466  break;
467  }
468  SS.SetInvalid(SourceRange(IdLoc, CCLoc));
469  }
470  HasScopeSpecifier = true;
471  continue;
472  }
473 
474  CheckForTemplateAndDigraph(Next, ObjectType, EnteringContext, II, SS);
475 
476  // nested-name-specifier:
477  // type-name '<'
478  if (Next.is(tok::less)) {
479  TemplateTy Template;
481  TemplateName.setIdentifier(&II, Tok.getLocation());
482  bool MemberOfUnknownSpecialization;
483  if (TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
484  /*hasTemplateKeyword=*/false,
485  TemplateName,
486  ObjectType,
487  EnteringContext,
488  Template,
489  MemberOfUnknownSpecialization)) {
490  // We have found a template name, so annotate this token
491  // with a template-id annotation. We do not permit the
492  // template-id to be translated into a type annotation,
493  // because some clients (e.g., the parsing of class template
494  // specializations) still want to see the original template-id
495  // token.
496  ConsumeToken();
497  if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
498  TemplateName, false))
499  return true;
500  continue;
501  }
502 
503  if (MemberOfUnknownSpecialization && (ObjectType || SS.isSet()) &&
504  (IsTypename || IsTemplateArgumentList(1))) {
505  // We have something like t::getAs<T>, where getAs is a
506  // member of an unknown specialization. However, this will only
507  // parse correctly as a template, so suggest the keyword 'template'
508  // before 'getAs' and treat this as a dependent template name.
509  unsigned DiagID = diag::err_missing_dependent_template_keyword;
510  if (getLangOpts().MicrosoftExt)
511  DiagID = diag::warn_missing_dependent_template_keyword;
512 
513  Diag(Tok.getLocation(), DiagID)
514  << II.getName()
515  << FixItHint::CreateInsertion(Tok.getLocation(), "template ");
516 
518  getCurScope(), SS, Tok.getLocation(), TemplateName, ObjectType,
519  EnteringContext, Template, /*AllowInjectedClassName*/ true)) {
520  // Consume the identifier.
521  ConsumeToken();
522  if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
523  TemplateName, false))
524  return true;
525  }
526  else
527  return true;
528 
529  continue;
530  }
531  }
532 
533  // We don't have any tokens that form the beginning of a
534  // nested-name-specifier, so we're done.
535  break;
536  }
537 
538  // Even if we didn't see any pieces of a nested-name-specifier, we
539  // still check whether there is a tilde in this position, which
540  // indicates a potential pseudo-destructor.
541  if (CheckForDestructor && Tok.is(tok::tilde))
542  *MayBePseudoDestructor = true;
543 
544  return false;
545 }
546 
547 ExprResult Parser::tryParseCXXIdExpression(CXXScopeSpec &SS, bool isAddressOfOperand,
548  Token &Replacement) {
549  SourceLocation TemplateKWLoc;
550  UnqualifiedId Name;
551  if (ParseUnqualifiedId(SS,
552  /*EnteringContext=*/false,
553  /*AllowDestructorName=*/false,
554  /*AllowConstructorName=*/false,
555  /*AllowDeductionGuide=*/false,
556  /*ObjectType=*/nullptr, &TemplateKWLoc, Name))
557  return ExprError();
558 
559  // This is only the direct operand of an & operator if it is not
560  // followed by a postfix-expression suffix.
561  if (isAddressOfOperand && isPostfixExpressionSuffixStart())
562  isAddressOfOperand = false;
563 
564  return Actions.ActOnIdExpression(getCurScope(), SS, TemplateKWLoc, Name,
565  Tok.is(tok::l_paren), isAddressOfOperand,
566  nullptr, /*IsInlineAsmIdentifier=*/false,
567  &Replacement);
568 }
569 
570 /// ParseCXXIdExpression - Handle id-expression.
571 ///
572 /// id-expression:
573 /// unqualified-id
574 /// qualified-id
575 ///
576 /// qualified-id:
577 /// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
578 /// '::' identifier
579 /// '::' operator-function-id
580 /// '::' template-id
581 ///
582 /// NOTE: The standard specifies that, for qualified-id, the parser does not
583 /// expect:
584 ///
585 /// '::' conversion-function-id
586 /// '::' '~' class-name
587 ///
588 /// This may cause a slight inconsistency on diagnostics:
589 ///
590 /// class C {};
591 /// namespace A {}
592 /// void f() {
593 /// :: A :: ~ C(); // Some Sema error about using destructor with a
594 /// // namespace.
595 /// :: ~ C(); // Some Parser error like 'unexpected ~'.
596 /// }
597 ///
598 /// We simplify the parser a bit and make it work like:
599 ///
600 /// qualified-id:
601 /// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
602 /// '::' unqualified-id
603 ///
604 /// That way Sema can handle and report similar errors for namespaces and the
605 /// global scope.
606 ///
607 /// The isAddressOfOperand parameter indicates that this id-expression is a
608 /// direct operand of the address-of operator. This is, besides member contexts,
609 /// the only place where a qualified-id naming a non-static class member may
610 /// appear.
611 ///
612 ExprResult Parser::ParseCXXIdExpression(bool isAddressOfOperand) {
613  // qualified-id:
614  // '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
615  // '::' unqualified-id
616  //
617  CXXScopeSpec SS;
618  ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false);
619 
622  tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
623  if (Result.isUnset()) {
624  // If the ExprResult is valid but null, then typo correction suggested a
625  // keyword replacement that needs to be reparsed.
626  UnconsumeToken(Replacement);
627  Result = tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
628  }
629  assert(!Result.isUnset() && "Typo correction suggested a keyword replacement "
630  "for a previous keyword suggestion");
631  return Result;
632 }
633 
634 /// ParseLambdaExpression - Parse a C++11 lambda expression.
635 ///
636 /// lambda-expression:
637 /// lambda-introducer lambda-declarator[opt] compound-statement
638 ///
639 /// lambda-introducer:
640 /// '[' lambda-capture[opt] ']'
641 ///
642 /// lambda-capture:
643 /// capture-default
644 /// capture-list
645 /// capture-default ',' capture-list
646 ///
647 /// capture-default:
648 /// '&'
649 /// '='
650 ///
651 /// capture-list:
652 /// capture
653 /// capture-list ',' capture
654 ///
655 /// capture:
656 /// simple-capture
657 /// init-capture [C++1y]
658 ///
659 /// simple-capture:
660 /// identifier
661 /// '&' identifier
662 /// 'this'
663 ///
664 /// init-capture: [C++1y]
665 /// identifier initializer
666 /// '&' identifier initializer
667 ///
668 /// lambda-declarator:
669 /// '(' parameter-declaration-clause ')' attribute-specifier[opt]
670 /// 'mutable'[opt] exception-specification[opt]
671 /// trailing-return-type[opt]
672 ///
673 ExprResult Parser::ParseLambdaExpression() {
674  // Parse lambda-introducer.
675  LambdaIntroducer Intro;
676  Optional<unsigned> DiagID = ParseLambdaIntroducer(Intro);
677  if (DiagID) {
678  Diag(Tok, DiagID.getValue());
679  SkipUntil(tok::r_square, StopAtSemi);
680  SkipUntil(tok::l_brace, StopAtSemi);
681  SkipUntil(tok::r_brace, StopAtSemi);
682  return ExprError();
683  }
684 
685  return ParseLambdaExpressionAfterIntroducer(Intro);
686 }
687 
688 /// TryParseLambdaExpression - Use lookahead and potentially tentative
689 /// parsing to determine if we are looking at a C++0x lambda expression, and parse
690 /// it if we are.
691 ///
692 /// If we are not looking at a lambda expression, returns ExprError().
693 ExprResult Parser::TryParseLambdaExpression() {
694  assert(getLangOpts().CPlusPlus11
695  && Tok.is(tok::l_square)
696  && "Not at the start of a possible lambda expression.");
697 
698  const Token Next = NextToken();
699  if (Next.is(tok::eof)) // Nothing else to lookup here...
700  return ExprEmpty();
701 
702  const Token After = GetLookAheadToken(2);
703  // If lookahead indicates this is a lambda...
704  if (Next.is(tok::r_square) || // []
705  Next.is(tok::equal) || // [=
706  (Next.is(tok::amp) && // [&] or [&,
707  (After.is(tok::r_square) ||
708  After.is(tok::comma))) ||
709  (Next.is(tok::identifier) && // [identifier]
710  After.is(tok::r_square))) {
711  return ParseLambdaExpression();
712  }
713 
714  // If lookahead indicates an ObjC message send...
715  // [identifier identifier
716  if (Next.is(tok::identifier) && After.is(tok::identifier)) {
717  return ExprEmpty();
718  }
719 
720  // Here, we're stuck: lambda introducers and Objective-C message sends are
721  // unambiguous, but it requires arbitrary lookhead. [a,b,c,d,e,f,g] is a
722  // lambda, and [a,b,c,d,e,f,g h] is a Objective-C message send. Instead of
723  // writing two routines to parse a lambda introducer, just try to parse
724  // a lambda introducer first, and fall back if that fails.
725  // (TryParseLambdaIntroducer never produces any diagnostic output.)
726  LambdaIntroducer Intro;
727  if (TryParseLambdaIntroducer(Intro))
728  return ExprEmpty();
729 
730  return ParseLambdaExpressionAfterIntroducer(Intro);
731 }
732 
733 /// Parse a lambda introducer.
734 /// \param Intro A LambdaIntroducer filled in with information about the
735 /// contents of the lambda-introducer.
736 /// \param SkippedInits If non-null, we are disambiguating between an Obj-C
737 /// message send and a lambda expression. In this mode, we will
738 /// sometimes skip the initializers for init-captures and not fully
739 /// populate \p Intro. This flag will be set to \c true if we do so.
740 /// \return A DiagnosticID if it hit something unexpected. The location for
741 /// the diagnostic is that of the current token.
742 Optional<unsigned> Parser::ParseLambdaIntroducer(LambdaIntroducer &Intro,
743  bool *SkippedInits) {
744  typedef Optional<unsigned> DiagResult;
745 
746  assert(Tok.is(tok::l_square) && "Lambda expressions begin with '['.");
747  BalancedDelimiterTracker T(*this, tok::l_square);
748  T.consumeOpen();
749 
750  Intro.Range.setBegin(T.getOpenLocation());
751 
752  bool first = true;
753 
754  // Parse capture-default.
755  if (Tok.is(tok::amp) &&
756  (NextToken().is(tok::comma) || NextToken().is(tok::r_square))) {
757  Intro.Default = LCD_ByRef;
758  Intro.DefaultLoc = ConsumeToken();
759  first = false;
760  } else if (Tok.is(tok::equal)) {
761  Intro.Default = LCD_ByCopy;
762  Intro.DefaultLoc = ConsumeToken();
763  first = false;
764  }
765 
766  while (Tok.isNot(tok::r_square)) {
767  if (!first) {
768  if (Tok.isNot(tok::comma)) {
769  // Provide a completion for a lambda introducer here. Except
770  // in Objective-C, where this is Almost Surely meant to be a message
771  // send. In that case, fail here and let the ObjC message
772  // expression parser perform the completion.
773  if (Tok.is(tok::code_completion) &&
774  !(getLangOpts().ObjC1 && Intro.Default == LCD_None &&
775  !Intro.Captures.empty())) {
776  Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
777  /*AfterAmpersand=*/false);
778  cutOffParsing();
779  break;
780  }
781 
782  return DiagResult(diag::err_expected_comma_or_rsquare);
783  }
784  ConsumeToken();
785  }
786 
787  if (Tok.is(tok::code_completion)) {
788  // If we're in Objective-C++ and we have a bare '[', then this is more
789  // likely to be a message receiver.
790  if (getLangOpts().ObjC1 && first)
792  else
793  Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
794  /*AfterAmpersand=*/false);
795  cutOffParsing();
796  break;
797  }
798 
799  first = false;
800 
801  // Parse capture.
804  SourceLocation Loc;
805  IdentifierInfo *Id = nullptr;
806  SourceLocation EllipsisLoc;
807  ExprResult Init;
808 
809  if (Tok.is(tok::star)) {
810  Loc = ConsumeToken();
811  if (Tok.is(tok::kw_this)) {
812  ConsumeToken();
813  Kind = LCK_StarThis;
814  } else {
815  return DiagResult(diag::err_expected_star_this_capture);
816  }
817  } else if (Tok.is(tok::kw_this)) {
818  Kind = LCK_This;
819  Loc = ConsumeToken();
820  } else {
821  if (Tok.is(tok::amp)) {
822  Kind = LCK_ByRef;
823  ConsumeToken();
824 
825  if (Tok.is(tok::code_completion)) {
826  Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
827  /*AfterAmpersand=*/true);
828  cutOffParsing();
829  break;
830  }
831  }
832 
833  if (Tok.is(tok::identifier)) {
834  Id = Tok.getIdentifierInfo();
835  Loc = ConsumeToken();
836  } else if (Tok.is(tok::kw_this)) {
837  // FIXME: If we want to suggest a fixit here, will need to return more
838  // than just DiagnosticID. Perhaps full DiagnosticBuilder that can be
839  // Clear()ed to prevent emission in case of tentative parsing?
840  return DiagResult(diag::err_this_captured_by_reference);
841  } else {
842  return DiagResult(diag::err_expected_capture);
843  }
844 
845  if (Tok.is(tok::l_paren)) {
846  BalancedDelimiterTracker Parens(*this, tok::l_paren);
847  Parens.consumeOpen();
848 
850 
851  ExprVector Exprs;
852  CommaLocsTy Commas;
853  if (SkippedInits) {
854  Parens.skipToEnd();
855  *SkippedInits = true;
856  } else if (ParseExpressionList(Exprs, Commas)) {
857  Parens.skipToEnd();
858  Init = ExprError();
859  } else {
860  Parens.consumeClose();
861  Init = Actions.ActOnParenListExpr(Parens.getOpenLocation(),
862  Parens.getCloseLocation(),
863  Exprs);
864  }
865  } else if (Tok.isOneOf(tok::l_brace, tok::equal)) {
866  // Each lambda init-capture forms its own full expression, which clears
867  // Actions.MaybeODRUseExprs. So create an expression evaluation context
868  // to save the necessary state, and restore it later.
871 
872  if (TryConsumeToken(tok::equal))
874  else
876 
877  if (!SkippedInits) {
878  Init = ParseInitializer();
879  } else if (Tok.is(tok::l_brace)) {
880  BalancedDelimiterTracker Braces(*this, tok::l_brace);
881  Braces.consumeOpen();
882  Braces.skipToEnd();
883  *SkippedInits = true;
884  } else {
885  // We're disambiguating this:
886  //
887  // [..., x = expr
888  //
889  // We need to find the end of the following expression in order to
890  // determine whether this is an Obj-C message send's receiver, a
891  // C99 designator, or a lambda init-capture.
892  //
893  // Parse the expression to find where it ends, and annotate it back
894  // onto the tokens. We would have parsed this expression the same way
895  // in either case: both the RHS of an init-capture and the RHS of an
896  // assignment expression are parsed as an initializer-clause, and in
897  // neither case can anything be added to the scope between the '[' and
898  // here.
899  //
900  // FIXME: This is horrible. Adding a mechanism to skip an expression
901  // would be much cleaner.
902  // FIXME: If there is a ',' before the next ']' or ':', we can skip to
903  // that instead. (And if we see a ':' with no matching '?', we can
904  // classify this as an Obj-C message send.)
905  SourceLocation StartLoc = Tok.getLocation();
906  InMessageExpressionRAIIObject MaybeInMessageExpression(*this, true);
907  Init = ParseInitializer();
908  if (!Init.isInvalid())
909  Init = Actions.CorrectDelayedTyposInExpr(Init.get());
910 
911  if (Tok.getLocation() != StartLoc) {
912  // Back out the lexing of the token after the initializer.
913  PP.RevertCachedTokens(1);
914 
915  // Replace the consumed tokens with an appropriate annotation.
916  Tok.setLocation(StartLoc);
917  Tok.setKind(tok::annot_primary_expr);
918  setExprAnnotation(Tok, Init);
920  PP.AnnotateCachedTokens(Tok);
921 
922  // Consume the annotated initializer.
923  ConsumeAnnotationToken();
924  }
925  }
926  } else
927  TryConsumeToken(tok::ellipsis, EllipsisLoc);
928  }
929  // If this is an init capture, process the initialization expression
930  // right away. For lambda init-captures such as the following:
931  // const int x = 10;
932  // auto L = [i = x+1](int a) {
933  // return [j = x+2,
934  // &k = x](char b) { };
935  // };
936  // keep in mind that each lambda init-capture has to have:
937  // - its initialization expression executed in the context
938  // of the enclosing/parent decl-context.
939  // - but the variable itself has to be 'injected' into the
940  // decl-context of its lambda's call-operator (which has
941  // not yet been created).
942  // Each init-expression is a full-expression that has to get
943  // Sema-analyzed (for capturing etc.) before its lambda's
944  // call-operator's decl-context, scope & scopeinfo are pushed on their
945  // respective stacks. Thus if any variable is odr-used in the init-capture
946  // it will correctly get captured in the enclosing lambda, if one exists.
947  // The init-variables above are created later once the lambdascope and
948  // call-operators decl-context is pushed onto its respective stack.
949 
950  // Since the lambda init-capture's initializer expression occurs in the
951  // context of the enclosing function or lambda, therefore we can not wait
952  // till a lambda scope has been pushed on before deciding whether the
953  // variable needs to be captured. We also need to process all
954  // lvalue-to-rvalue conversions and discarded-value conversions,
955  // so that we can avoid capturing certain constant variables.
956  // For e.g.,
957  // void test() {
958  // const int x = 10;
959  // auto L = [&z = x](char a) { <-- don't capture by the current lambda
960  // return [y = x](int i) { <-- don't capture by enclosing lambda
961  // return y;
962  // }
963  // };
964  // }
965  // If x was not const, the second use would require 'L' to capture, and
966  // that would be an error.
967 
968  ParsedType InitCaptureType;
969  if (!Init.isInvalid())
970  Init = Actions.CorrectDelayedTyposInExpr(Init.get());
971  if (Init.isUsable()) {
972  // Get the pointer and store it in an lvalue, so we can use it as an
973  // out argument.
974  Expr *InitExpr = Init.get();
975  // This performs any lvalue-to-rvalue conversions if necessary, which
976  // can affect what gets captured in the containing decl-context.
977  InitCaptureType = Actions.actOnLambdaInitCaptureInitialization(
978  Loc, Kind == LCK_ByRef, Id, InitKind, InitExpr);
979  Init = InitExpr;
980  }
981  Intro.addCapture(Kind, Loc, Id, EllipsisLoc, InitKind, Init,
982  InitCaptureType);
983  }
984 
985  T.consumeClose();
986  Intro.Range.setEnd(T.getCloseLocation());
987  return DiagResult();
988 }
989 
990 /// TryParseLambdaIntroducer - Tentatively parse a lambda introducer.
991 ///
992 /// Returns true if it hit something unexpected.
993 bool Parser::TryParseLambdaIntroducer(LambdaIntroducer &Intro) {
994  {
995  bool SkippedInits = false;
996  TentativeParsingAction PA1(*this);
997 
998  if (ParseLambdaIntroducer(Intro, &SkippedInits)) {
999  PA1.Revert();
1000  return true;
1001  }
1002 
1003  if (!SkippedInits) {
1004  PA1.Commit();
1005  return false;
1006  }
1007 
1008  PA1.Revert();
1009  }
1010 
1011  // Try to parse it again, but this time parse the init-captures too.
1012  Intro = LambdaIntroducer();
1013  TentativeParsingAction PA2(*this);
1014 
1015  if (!ParseLambdaIntroducer(Intro)) {
1016  PA2.Commit();
1017  return false;
1018  }
1019 
1020  PA2.Revert();
1021  return true;
1022 }
1023 
1024 static void
1026  SourceLocation &ConstexprLoc,
1027  SourceLocation &DeclEndLoc) {
1028  assert(MutableLoc.isInvalid());
1029  assert(ConstexprLoc.isInvalid());
1030  // Consume constexpr-opt mutable-opt in any sequence, and set the DeclEndLoc
1031  // to the final of those locations. Emit an error if we have multiple
1032  // copies of those keywords and recover.
1033 
1034  while (true) {
1035  switch (P.getCurToken().getKind()) {
1036  case tok::kw_mutable: {
1037  if (MutableLoc.isValid()) {
1038  P.Diag(P.getCurToken().getLocation(),
1039  diag::err_lambda_decl_specifier_repeated)
1041  }
1042  MutableLoc = P.ConsumeToken();
1043  DeclEndLoc = MutableLoc;
1044  break /*switch*/;
1045  }
1046  case tok::kw_constexpr:
1047  if (ConstexprLoc.isValid()) {
1048  P.Diag(P.getCurToken().getLocation(),
1049  diag::err_lambda_decl_specifier_repeated)
1051  }
1052  ConstexprLoc = P.ConsumeToken();
1053  DeclEndLoc = ConstexprLoc;
1054  break /*switch*/;
1055  default:
1056  return;
1057  }
1058  }
1059 }
1060 
1061 static void
1063  DeclSpec &DS) {
1064  if (ConstexprLoc.isValid()) {
1065  P.Diag(ConstexprLoc, !P.getLangOpts().CPlusPlus17
1066  ? diag::ext_constexpr_on_lambda_cxx17
1067  : diag::warn_cxx14_compat_constexpr_on_lambda);
1068  const char *PrevSpec = nullptr;
1069  unsigned DiagID = 0;
1070  DS.SetConstexprSpec(ConstexprLoc, PrevSpec, DiagID);
1071  assert(PrevSpec == nullptr && DiagID == 0 &&
1072  "Constexpr cannot have been set previously!");
1073  }
1074 }
1075 
1076 /// ParseLambdaExpressionAfterIntroducer - Parse the rest of a lambda
1077 /// expression.
1078 ExprResult Parser::ParseLambdaExpressionAfterIntroducer(
1079  LambdaIntroducer &Intro) {
1080  SourceLocation LambdaBeginLoc = Intro.Range.getBegin();
1081  Diag(LambdaBeginLoc, diag::warn_cxx98_compat_lambda);
1082 
1083  PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), LambdaBeginLoc,
1084  "lambda expression parsing");
1085 
1086 
1087 
1088  // FIXME: Call into Actions to add any init-capture declarations to the
1089  // scope while parsing the lambda-declarator and compound-statement.
1090 
1091  // Parse lambda-declarator[opt].
1092  DeclSpec DS(AttrFactory);
1094  TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1095  Actions.PushLambdaScope();
1096 
1097  ParsedAttributes Attr(AttrFactory);
1098  SourceLocation DeclLoc = Tok.getLocation();
1099  if (getLangOpts().CUDA) {
1100  // In CUDA code, GNU attributes are allowed to appear immediately after the
1101  // "[...]", even if there is no "(...)" before the lambda body.
1102  MaybeParseGNUAttributes(D);
1103  }
1104 
1105  // Helper to emit a warning if we see a CUDA host/device/global attribute
1106  // after '(...)'. nvcc doesn't accept this.
1107  auto WarnIfHasCUDATargetAttr = [&] {
1108  if (getLangOpts().CUDA)
1109  for (auto *A = Attr.getList(); A != nullptr; A = A->getNext())
1110  if (A->getKind() == AttributeList::AT_CUDADevice ||
1111  A->getKind() == AttributeList::AT_CUDAHost ||
1112  A->getKind() == AttributeList::AT_CUDAGlobal)
1113  Diag(A->getLoc(), diag::warn_cuda_attr_lambda_position)
1114  << A->getName()->getName();
1115  };
1116 
1117  TypeResult TrailingReturnType;
1118  if (Tok.is(tok::l_paren)) {
1119  ParseScope PrototypeScope(this,
1123 
1124  BalancedDelimiterTracker T(*this, tok::l_paren);
1125  T.consumeOpen();
1126  SourceLocation LParenLoc = T.getOpenLocation();
1127 
1128  // Parse parameter-declaration-clause.
1130  SourceLocation EllipsisLoc;
1131 
1132  if (Tok.isNot(tok::r_paren)) {
1133  Actions.RecordParsingTemplateParameterDepth(TemplateParameterDepth);
1134  ParseParameterDeclarationClause(D, Attr, ParamInfo, EllipsisLoc);
1135  // For a generic lambda, each 'auto' within the parameter declaration
1136  // clause creates a template type parameter, so increment the depth.
1137  if (Actions.getCurGenericLambda())
1138  ++CurTemplateDepthTracker;
1139  }
1140  T.consumeClose();
1141  SourceLocation RParenLoc = T.getCloseLocation();
1142  SourceLocation DeclEndLoc = RParenLoc;
1143 
1144  // GNU-style attributes must be parsed before the mutable specifier to be
1145  // compatible with GCC.
1146  MaybeParseGNUAttributes(Attr, &DeclEndLoc);
1147 
1148  // MSVC-style attributes must be parsed before the mutable specifier to be
1149  // compatible with MSVC.
1150  MaybeParseMicrosoftDeclSpecs(Attr, &DeclEndLoc);
1151 
1152  // Parse mutable-opt and/or constexpr-opt, and update the DeclEndLoc.
1153  SourceLocation MutableLoc;
1154  SourceLocation ConstexprLoc;
1155  tryConsumeMutableOrConstexprToken(*this, MutableLoc, ConstexprLoc,
1156  DeclEndLoc);
1157 
1158  addConstexprToLambdaDeclSpecifier(*this, ConstexprLoc, DS);
1159 
1160  // Parse exception-specification[opt].
1162  SourceRange ESpecRange;
1163  SmallVector<ParsedType, 2> DynamicExceptions;
1164  SmallVector<SourceRange, 2> DynamicExceptionRanges;
1165  ExprResult NoexceptExpr;
1166  CachedTokens *ExceptionSpecTokens;
1167  ESpecType = tryParseExceptionSpecification(/*Delayed=*/false,
1168  ESpecRange,
1169  DynamicExceptions,
1170  DynamicExceptionRanges,
1171  NoexceptExpr,
1172  ExceptionSpecTokens);
1173 
1174  if (ESpecType != EST_None)
1175  DeclEndLoc = ESpecRange.getEnd();
1176 
1177  // Parse attribute-specifier[opt].
1178  MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
1179 
1180  SourceLocation FunLocalRangeEnd = DeclEndLoc;
1181 
1182  // Parse trailing-return-type[opt].
1183  if (Tok.is(tok::arrow)) {
1184  FunLocalRangeEnd = Tok.getLocation();
1185  SourceRange Range;
1186  TrailingReturnType =
1187  ParseTrailingReturnType(Range, /*MayBeFollowedByDirectInit*/ false);
1188  if (Range.getEnd().isValid())
1189  DeclEndLoc = Range.getEnd();
1190  }
1191 
1192  PrototypeScope.Exit();
1193 
1194  WarnIfHasCUDATargetAttr();
1195 
1196  SourceLocation NoLoc;
1197  D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true,
1198  /*isAmbiguous=*/false,
1199  LParenLoc,
1200  ParamInfo.data(), ParamInfo.size(),
1201  EllipsisLoc, RParenLoc,
1202  DS.getTypeQualifiers(),
1203  /*RefQualifierIsLValueRef=*/true,
1204  /*RefQualifierLoc=*/NoLoc,
1205  /*ConstQualifierLoc=*/NoLoc,
1206  /*VolatileQualifierLoc=*/NoLoc,
1207  /*RestrictQualifierLoc=*/NoLoc,
1208  MutableLoc,
1209  ESpecType, ESpecRange,
1210  DynamicExceptions.data(),
1211  DynamicExceptionRanges.data(),
1212  DynamicExceptions.size(),
1213  NoexceptExpr.isUsable() ?
1214  NoexceptExpr.get() : nullptr,
1215  /*ExceptionSpecTokens*/nullptr,
1216  /*DeclsInPrototype=*/None,
1217  LParenLoc, FunLocalRangeEnd, D,
1218  TrailingReturnType),
1219  Attr, DeclEndLoc);
1220  } else if (Tok.isOneOf(tok::kw_mutable, tok::arrow, tok::kw___attribute,
1221  tok::kw_constexpr) ||
1222  (Tok.is(tok::l_square) && NextToken().is(tok::l_square))) {
1223  // It's common to forget that one needs '()' before 'mutable', an attribute
1224  // specifier, or the result type. Deal with this.
1225  unsigned TokKind = 0;
1226  switch (Tok.getKind()) {
1227  case tok::kw_mutable: TokKind = 0; break;
1228  case tok::arrow: TokKind = 1; break;
1229  case tok::kw___attribute:
1230  case tok::l_square: TokKind = 2; break;
1231  case tok::kw_constexpr: TokKind = 3; break;
1232  default: llvm_unreachable("Unknown token kind");
1233  }
1234 
1235  Diag(Tok, diag::err_lambda_missing_parens)
1236  << TokKind
1237  << FixItHint::CreateInsertion(Tok.getLocation(), "() ");
1238  SourceLocation DeclEndLoc = DeclLoc;
1239 
1240  // GNU-style attributes must be parsed before the mutable specifier to be
1241  // compatible with GCC.
1242  MaybeParseGNUAttributes(Attr, &DeclEndLoc);
1243 
1244  // Parse 'mutable', if it's there.
1245  SourceLocation MutableLoc;
1246  if (Tok.is(tok::kw_mutable)) {
1247  MutableLoc = ConsumeToken();
1248  DeclEndLoc = MutableLoc;
1249  }
1250 
1251  // Parse attribute-specifier[opt].
1252  MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
1253 
1254  // Parse the return type, if there is one.
1255  if (Tok.is(tok::arrow)) {
1256  SourceRange Range;
1257  TrailingReturnType =
1258  ParseTrailingReturnType(Range, /*MayBeFollowedByDirectInit*/ false);
1259  if (Range.getEnd().isValid())
1260  DeclEndLoc = Range.getEnd();
1261  }
1262 
1263  WarnIfHasCUDATargetAttr();
1264 
1265  SourceLocation NoLoc;
1266  D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true,
1267  /*isAmbiguous=*/false,
1268  /*LParenLoc=*/NoLoc,
1269  /*Params=*/nullptr,
1270  /*NumParams=*/0,
1271  /*EllipsisLoc=*/NoLoc,
1272  /*RParenLoc=*/NoLoc,
1273  /*TypeQuals=*/0,
1274  /*RefQualifierIsLValueRef=*/true,
1275  /*RefQualifierLoc=*/NoLoc,
1276  /*ConstQualifierLoc=*/NoLoc,
1277  /*VolatileQualifierLoc=*/NoLoc,
1278  /*RestrictQualifierLoc=*/NoLoc,
1279  MutableLoc,
1280  EST_None,
1281  /*ESpecRange=*/SourceRange(),
1282  /*Exceptions=*/nullptr,
1283  /*ExceptionRanges=*/nullptr,
1284  /*NumExceptions=*/0,
1285  /*NoexceptExpr=*/nullptr,
1286  /*ExceptionSpecTokens=*/nullptr,
1287  /*DeclsInPrototype=*/None,
1288  DeclLoc, DeclEndLoc, D,
1289  TrailingReturnType),
1290  Attr, DeclEndLoc);
1291  }
1292 
1293  // FIXME: Rename BlockScope -> ClosureScope if we decide to continue using
1294  // it.
1295  unsigned ScopeFlags = Scope::BlockScope | Scope::FnScope | Scope::DeclScope |
1297  ParseScope BodyScope(this, ScopeFlags);
1298 
1299  Actions.ActOnStartOfLambdaDefinition(Intro, D, getCurScope());
1300 
1301  // Parse compound-statement.
1302  if (!Tok.is(tok::l_brace)) {
1303  Diag(Tok, diag::err_expected_lambda_body);
1304  Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1305  return ExprError();
1306  }
1307 
1308  StmtResult Stmt(ParseCompoundStatementBody());
1309  BodyScope.Exit();
1310 
1311  if (!Stmt.isInvalid() && !TrailingReturnType.isInvalid())
1312  return Actions.ActOnLambdaExpr(LambdaBeginLoc, Stmt.get(), getCurScope());
1313 
1314  Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1315  return ExprError();
1316 }
1317 
1318 /// ParseCXXCasts - This handles the various ways to cast expressions to another
1319 /// type.
1320 ///
1321 /// postfix-expression: [C++ 5.2p1]
1322 /// 'dynamic_cast' '<' type-name '>' '(' expression ')'
1323 /// 'static_cast' '<' type-name '>' '(' expression ')'
1324 /// 'reinterpret_cast' '<' type-name '>' '(' expression ')'
1325 /// 'const_cast' '<' type-name '>' '(' expression ')'
1326 ///
1327 ExprResult Parser::ParseCXXCasts() {
1328  tok::TokenKind Kind = Tok.getKind();
1329  const char *CastName = nullptr; // For error messages
1330 
1331  switch (Kind) {
1332  default: llvm_unreachable("Unknown C++ cast!");
1333  case tok::kw_const_cast: CastName = "const_cast"; break;
1334  case tok::kw_dynamic_cast: CastName = "dynamic_cast"; break;
1335  case tok::kw_reinterpret_cast: CastName = "reinterpret_cast"; break;
1336  case tok::kw_static_cast: CastName = "static_cast"; break;
1337  }
1338 
1339  SourceLocation OpLoc = ConsumeToken();
1340  SourceLocation LAngleBracketLoc = Tok.getLocation();
1341 
1342  // Check for "<::" which is parsed as "[:". If found, fix token stream,
1343  // diagnose error, suggest fix, and recover parsing.
1344  if (Tok.is(tok::l_square) && Tok.getLength() == 2) {
1345  Token Next = NextToken();
1346  if (Next.is(tok::colon) && areTokensAdjacent(Tok, Next))
1347  FixDigraph(*this, PP, Tok, Next, Kind, /*AtDigraph*/true);
1348  }
1349 
1350  if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName))
1351  return ExprError();
1352 
1353  // Parse the common declaration-specifiers piece.
1354  DeclSpec DS(AttrFactory);
1355  ParseSpecifierQualifierList(DS);
1356 
1357  // Parse the abstract-declarator, if present.
1358  Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
1359  ParseDeclarator(DeclaratorInfo);
1360 
1361  SourceLocation RAngleBracketLoc = Tok.getLocation();
1362 
1363  if (ExpectAndConsume(tok::greater))
1364  return ExprError(Diag(LAngleBracketLoc, diag::note_matching) << tok::less);
1365 
1366  BalancedDelimiterTracker T(*this, tok::l_paren);
1367 
1368  if (T.expectAndConsume(diag::err_expected_lparen_after, CastName))
1369  return ExprError();
1370 
1372 
1373  // Match the ')'.
1374  T.consumeClose();
1375 
1376  if (!Result.isInvalid() && !DeclaratorInfo.isInvalidType())
1377  Result = Actions.ActOnCXXNamedCast(OpLoc, Kind,
1378  LAngleBracketLoc, DeclaratorInfo,
1379  RAngleBracketLoc,
1380  T.getOpenLocation(), Result.get(),
1381  T.getCloseLocation());
1382 
1383  return Result;
1384 }
1385 
1386 /// ParseCXXTypeid - This handles the C++ typeid expression.
1387 ///
1388 /// postfix-expression: [C++ 5.2p1]
1389 /// 'typeid' '(' expression ')'
1390 /// 'typeid' '(' type-id ')'
1391 ///
1392 ExprResult Parser::ParseCXXTypeid() {
1393  assert(Tok.is(tok::kw_typeid) && "Not 'typeid'!");
1394 
1395  SourceLocation OpLoc = ConsumeToken();
1396  SourceLocation LParenLoc, RParenLoc;
1397  BalancedDelimiterTracker T(*this, tok::l_paren);
1398 
1399  // typeid expressions are always parenthesized.
1400  if (T.expectAndConsume(diag::err_expected_lparen_after, "typeid"))
1401  return ExprError();
1402  LParenLoc = T.getOpenLocation();
1403 
1405 
1406  // C++0x [expr.typeid]p3:
1407  // When typeid is applied to an expression other than an lvalue of a
1408  // polymorphic class type [...] The expression is an unevaluated
1409  // operand (Clause 5).
1410  //
1411  // Note that we can't tell whether the expression is an lvalue of a
1412  // polymorphic class type until after we've parsed the expression; we
1413  // speculatively assume the subexpression is unevaluated, and fix it up
1414  // later.
1415  //
1416  // We enter the unevaluated context before trying to determine whether we
1417  // have a type-id, because the tentative parse logic will try to resolve
1418  // names, and must treat them as unevaluated.
1422 
1423  if (isTypeIdInParens()) {
1424  TypeResult Ty = ParseTypeName();
1425 
1426  // Match the ')'.
1427  T.consumeClose();
1428  RParenLoc = T.getCloseLocation();
1429  if (Ty.isInvalid() || RParenLoc.isInvalid())
1430  return ExprError();
1431 
1432  Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/true,
1433  Ty.get().getAsOpaquePtr(), RParenLoc);
1434  } else {
1435  Result = ParseExpression();
1436 
1437  // Match the ')'.
1438  if (Result.isInvalid())
1439  SkipUntil(tok::r_paren, StopAtSemi);
1440  else {
1441  T.consumeClose();
1442  RParenLoc = T.getCloseLocation();
1443  if (RParenLoc.isInvalid())
1444  return ExprError();
1445 
1446  Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/false,
1447  Result.get(), RParenLoc);
1448  }
1449  }
1450 
1451  return Result;
1452 }
1453 
1454 /// ParseCXXUuidof - This handles the Microsoft C++ __uuidof expression.
1455 ///
1456 /// '__uuidof' '(' expression ')'
1457 /// '__uuidof' '(' type-id ')'
1458 ///
1459 ExprResult Parser::ParseCXXUuidof() {
1460  assert(Tok.is(tok::kw___uuidof) && "Not '__uuidof'!");
1461 
1462  SourceLocation OpLoc = ConsumeToken();
1463  BalancedDelimiterTracker T(*this, tok::l_paren);
1464 
1465  // __uuidof expressions are always parenthesized.
1466  if (T.expectAndConsume(diag::err_expected_lparen_after, "__uuidof"))
1467  return ExprError();
1468 
1470 
1471  if (isTypeIdInParens()) {
1472  TypeResult Ty = ParseTypeName();
1473 
1474  // Match the ')'.
1475  T.consumeClose();
1476 
1477  if (Ty.isInvalid())
1478  return ExprError();
1479 
1480  Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(), /*isType=*/true,
1481  Ty.get().getAsOpaquePtr(),
1482  T.getCloseLocation());
1483  } else {
1486  Result = ParseExpression();
1487 
1488  // Match the ')'.
1489  if (Result.isInvalid())
1490  SkipUntil(tok::r_paren, StopAtSemi);
1491  else {
1492  T.consumeClose();
1493 
1494  Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(),
1495  /*isType=*/false,
1496  Result.get(), T.getCloseLocation());
1497  }
1498  }
1499 
1500  return Result;
1501 }
1502 
1503 /// Parse a C++ pseudo-destructor expression after the base,
1504 /// . or -> operator, and nested-name-specifier have already been
1505 /// parsed.
1506 ///
1507 /// postfix-expression: [C++ 5.2]
1508 /// postfix-expression . pseudo-destructor-name
1509 /// postfix-expression -> pseudo-destructor-name
1510 ///
1511 /// pseudo-destructor-name:
1512 /// ::[opt] nested-name-specifier[opt] type-name :: ~type-name
1513 /// ::[opt] nested-name-specifier template simple-template-id ::
1514 /// ~type-name
1515 /// ::[opt] nested-name-specifier[opt] ~type-name
1516 ///
1517 ExprResult
1518 Parser::ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc,
1519  tok::TokenKind OpKind,
1520  CXXScopeSpec &SS,
1521  ParsedType ObjectType) {
1522  // We're parsing either a pseudo-destructor-name or a dependent
1523  // member access that has the same form as a
1524  // pseudo-destructor-name. We parse both in the same way and let
1525  // the action model sort them out.
1526  //
1527  // Note that the ::[opt] nested-name-specifier[opt] has already
1528  // been parsed, and if there was a simple-template-id, it has
1529  // been coalesced into a template-id annotation token.
1530  UnqualifiedId FirstTypeName;
1531  SourceLocation CCLoc;
1532  if (Tok.is(tok::identifier)) {
1533  FirstTypeName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1534  ConsumeToken();
1535  assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1536  CCLoc = ConsumeToken();
1537  } else if (Tok.is(tok::annot_template_id)) {
1538  // FIXME: retrieve TemplateKWLoc from template-id annotation and
1539  // store it in the pseudo-dtor node (to be used when instantiating it).
1540  FirstTypeName.setTemplateId(
1542  ConsumeAnnotationToken();
1543  assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1544  CCLoc = ConsumeToken();
1545  } else {
1546  FirstTypeName.setIdentifier(nullptr, SourceLocation());
1547  }
1548 
1549  // Parse the tilde.
1550  assert(Tok.is(tok::tilde) && "ParseOptionalCXXScopeSpecifier fail");
1551  SourceLocation TildeLoc = ConsumeToken();
1552 
1553  if (Tok.is(tok::kw_decltype) && !FirstTypeName.isValid() && SS.isEmpty()) {
1554  DeclSpec DS(AttrFactory);
1555  ParseDecltypeSpecifier(DS);
1556  if (DS.getTypeSpecType() == TST_error)
1557  return ExprError();
1558  return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
1559  TildeLoc, DS);
1560  }
1561 
1562  if (!Tok.is(tok::identifier)) {
1563  Diag(Tok, diag::err_destructor_tilde_identifier);
1564  return ExprError();
1565  }
1566 
1567  // Parse the second type.
1568  UnqualifiedId SecondTypeName;
1569  IdentifierInfo *Name = Tok.getIdentifierInfo();
1570  SourceLocation NameLoc = ConsumeToken();
1571  SecondTypeName.setIdentifier(Name, NameLoc);
1572 
1573  // If there is a '<', the second type name is a template-id. Parse
1574  // it as such.
1575  if (Tok.is(tok::less) &&
1576  ParseUnqualifiedIdTemplateId(SS, SourceLocation(),
1577  Name, NameLoc,
1578  false, ObjectType, SecondTypeName,
1579  /*AssumeTemplateName=*/true))
1580  return ExprError();
1581 
1582  return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
1583  SS, FirstTypeName, CCLoc, TildeLoc,
1584  SecondTypeName);
1585 }
1586 
1587 /// ParseCXXBoolLiteral - This handles the C++ Boolean literals.
1588 ///
1589 /// boolean-literal: [C++ 2.13.5]
1590 /// 'true'
1591 /// 'false'
1592 ExprResult Parser::ParseCXXBoolLiteral() {
1593  tok::TokenKind Kind = Tok.getKind();
1594  return Actions.ActOnCXXBoolLiteral(ConsumeToken(), Kind);
1595 }
1596 
1597 /// ParseThrowExpression - This handles the C++ throw expression.
1598 ///
1599 /// throw-expression: [C++ 15]
1600 /// 'throw' assignment-expression[opt]
1601 ExprResult Parser::ParseThrowExpression() {
1602  assert(Tok.is(tok::kw_throw) && "Not throw!");
1603  SourceLocation ThrowLoc = ConsumeToken(); // Eat the throw token.
1604 
1605  // If the current token isn't the start of an assignment-expression,
1606  // then the expression is not present. This handles things like:
1607  // "C ? throw : (void)42", which is crazy but legal.
1608  switch (Tok.getKind()) { // FIXME: move this predicate somewhere common.
1609  case tok::semi:
1610  case tok::r_paren:
1611  case tok::r_square:
1612  case tok::r_brace:
1613  case tok::colon:
1614  case tok::comma:
1615  return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, nullptr);
1616 
1617  default:
1619  if (Expr.isInvalid()) return Expr;
1620  return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, Expr.get());
1621  }
1622 }
1623 
1624 /// Parse the C++ Coroutines co_yield expression.
1625 ///
1626 /// co_yield-expression:
1627 /// 'co_yield' assignment-expression[opt]
1628 ExprResult Parser::ParseCoyieldExpression() {
1629  assert(Tok.is(tok::kw_co_yield) && "Not co_yield!");
1630 
1631  SourceLocation Loc = ConsumeToken();
1632  ExprResult Expr = Tok.is(tok::l_brace) ? ParseBraceInitializer()
1634  if (!Expr.isInvalid())
1635  Expr = Actions.ActOnCoyieldExpr(getCurScope(), Loc, Expr.get());
1636  return Expr;
1637 }
1638 
1639 /// ParseCXXThis - This handles the C++ 'this' pointer.
1640 ///
1641 /// C++ 9.3.2: In the body of a non-static member function, the keyword this is
1642 /// a non-lvalue expression whose value is the address of the object for which
1643 /// the function is called.
1644 ExprResult Parser::ParseCXXThis() {
1645  assert(Tok.is(tok::kw_this) && "Not 'this'!");
1646  SourceLocation ThisLoc = ConsumeToken();
1647  return Actions.ActOnCXXThis(ThisLoc);
1648 }
1649 
1650 /// ParseCXXTypeConstructExpression - Parse construction of a specified type.
1651 /// Can be interpreted either as function-style casting ("int(x)")
1652 /// or class type construction ("ClassType(x,y,z)")
1653 /// or creation of a value-initialized type ("int()").
1654 /// See [C++ 5.2.3].
1655 ///
1656 /// postfix-expression: [C++ 5.2p1]
1657 /// simple-type-specifier '(' expression-list[opt] ')'
1658 /// [C++0x] simple-type-specifier braced-init-list
1659 /// typename-specifier '(' expression-list[opt] ')'
1660 /// [C++0x] typename-specifier braced-init-list
1661 ///
1662 /// In C++1z onwards, the type specifier can also be a template-name.
1663 ExprResult
1664 Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) {
1666  ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
1667 
1668  assert((Tok.is(tok::l_paren) ||
1669  (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)))
1670  && "Expected '(' or '{'!");
1671 
1672  if (Tok.is(tok::l_brace)) {
1673  ExprResult Init = ParseBraceInitializer();
1674  if (Init.isInvalid())
1675  return Init;
1676  Expr *InitList = Init.get();
1677  return Actions.ActOnCXXTypeConstructExpr(
1678  TypeRep, InitList->getLocStart(), MultiExprArg(&InitList, 1),
1679  InitList->getLocEnd(), /*ListInitialization=*/true);
1680  } else {
1681  BalancedDelimiterTracker T(*this, tok::l_paren);
1682  T.consumeOpen();
1683 
1684  ExprVector Exprs;
1685  CommaLocsTy CommaLocs;
1686 
1687  if (Tok.isNot(tok::r_paren)) {
1688  if (ParseExpressionList(Exprs, CommaLocs, [&] {
1690  TypeRep.get()->getCanonicalTypeInternal(),
1691  DS.getLocEnd(), Exprs);
1692  })) {
1693  SkipUntil(tok::r_paren, StopAtSemi);
1694  return ExprError();
1695  }
1696  }
1697 
1698  // Match the ')'.
1699  T.consumeClose();
1700 
1701  // TypeRep could be null, if it references an invalid typedef.
1702  if (!TypeRep)
1703  return ExprError();
1704 
1705  assert((Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&&
1706  "Unexpected number of commas!");
1707  return Actions.ActOnCXXTypeConstructExpr(TypeRep, T.getOpenLocation(),
1708  Exprs, T.getCloseLocation(),
1709  /*ListInitialization=*/false);
1710  }
1711 }
1712 
1713 /// ParseCXXCondition - if/switch/while condition expression.
1714 ///
1715 /// condition:
1716 /// expression
1717 /// type-specifier-seq declarator '=' assignment-expression
1718 /// [C++11] type-specifier-seq declarator '=' initializer-clause
1719 /// [C++11] type-specifier-seq declarator braced-init-list
1720 /// [Clang] type-specifier-seq ref-qualifier[opt] '[' identifier-list ']'
1721 /// brace-or-equal-initializer
1722 /// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
1723 /// '=' assignment-expression
1724 ///
1725 /// In C++1z, a condition may in some contexts be preceded by an
1726 /// optional init-statement. This function will parse that too.
1727 ///
1728 /// \param InitStmt If non-null, an init-statement is permitted, and if present
1729 /// will be parsed and stored here.
1730 ///
1731 /// \param Loc The location of the start of the statement that requires this
1732 /// condition, e.g., the "for" in a for loop.
1733 ///
1734 /// \returns The parsed condition.
1735 Sema::ConditionResult Parser::ParseCXXCondition(StmtResult *InitStmt,
1736  SourceLocation Loc,
1737  Sema::ConditionKind CK) {
1738  if (Tok.is(tok::code_completion)) {
1740  cutOffParsing();
1741  return Sema::ConditionError();
1742  }
1743 
1744  ParsedAttributesWithRange attrs(AttrFactory);
1745  MaybeParseCXX11Attributes(attrs);
1746 
1747  const auto WarnOnInit = [this, &CK] {
1748  Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
1749  ? diag::warn_cxx14_compat_init_statement
1750  : diag::ext_init_statement)
1751  << (CK == Sema::ConditionKind::Switch);
1752  };
1753 
1754  // Determine what kind of thing we have.
1755  switch (isCXXConditionDeclarationOrInitStatement(InitStmt)) {
1756  case ConditionOrInitStatement::Expression: {
1757  ProhibitAttributes(attrs);
1758 
1759  // We can have an empty expression here.
1760  // if (; true);
1761  if (InitStmt && Tok.is(tok::semi)) {
1762  WarnOnInit();
1763  SourceLocation SemiLoc = ConsumeToken();
1764  *InitStmt = Actions.ActOnNullStmt(SemiLoc);
1765  return ParseCXXCondition(nullptr, Loc, CK);
1766  }
1767 
1768  // Parse the expression.
1769  ExprResult Expr = ParseExpression(); // expression
1770  if (Expr.isInvalid())
1771  return Sema::ConditionError();
1772 
1773  if (InitStmt && Tok.is(tok::semi)) {
1774  WarnOnInit();
1775  *InitStmt = Actions.ActOnExprStmt(Expr.get());
1776  ConsumeToken();
1777  return ParseCXXCondition(nullptr, Loc, CK);
1778  }
1779 
1780  return Actions.ActOnCondition(getCurScope(), Loc, Expr.get(), CK);
1781  }
1782 
1783  case ConditionOrInitStatement::InitStmtDecl: {
1784  WarnOnInit();
1785  SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
1786  DeclGroupPtrTy DG =
1787  ParseSimpleDeclaration(DeclaratorContext::InitStmtContext, DeclEnd,
1788  attrs, /*RequireSemi=*/true);
1789  *InitStmt = Actions.ActOnDeclStmt(DG, DeclStart, DeclEnd);
1790  return ParseCXXCondition(nullptr, Loc, CK);
1791  }
1792 
1793  case ConditionOrInitStatement::ConditionDecl:
1794  case ConditionOrInitStatement::Error:
1795  break;
1796  }
1797 
1798  // type-specifier-seq
1799  DeclSpec DS(AttrFactory);
1800  DS.takeAttributesFrom(attrs);
1801  ParseSpecifierQualifierList(DS, AS_none, DeclSpecContext::DSC_condition);
1802 
1803  // declarator
1804  Declarator DeclaratorInfo(DS, DeclaratorContext::ConditionContext);
1805  ParseDeclarator(DeclaratorInfo);
1806 
1807  // simple-asm-expr[opt]
1808  if (Tok.is(tok::kw_asm)) {
1809  SourceLocation Loc;
1810  ExprResult AsmLabel(ParseSimpleAsm(&Loc));
1811  if (AsmLabel.isInvalid()) {
1812  SkipUntil(tok::semi, StopAtSemi);
1813  return Sema::ConditionError();
1814  }
1815  DeclaratorInfo.setAsmLabel(AsmLabel.get());
1816  DeclaratorInfo.SetRangeEnd(Loc);
1817  }
1818 
1819  // If attributes are present, parse them.
1820  MaybeParseGNUAttributes(DeclaratorInfo);
1821 
1822  // Type-check the declaration itself.
1824  DeclaratorInfo);
1825  if (Dcl.isInvalid())
1826  return Sema::ConditionError();
1827  Decl *DeclOut = Dcl.get();
1828 
1829  // '=' assignment-expression
1830  // If a '==' or '+=' is found, suggest a fixit to '='.
1831  bool CopyInitialization = isTokenEqualOrEqualTypo();
1832  if (CopyInitialization)
1833  ConsumeToken();
1834 
1835  ExprResult InitExpr = ExprError();
1836  if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
1837  Diag(Tok.getLocation(),
1838  diag::warn_cxx98_compat_generalized_initializer_lists);
1839  InitExpr = ParseBraceInitializer();
1840  } else if (CopyInitialization) {
1841  InitExpr = ParseAssignmentExpression();
1842  } else if (Tok.is(tok::l_paren)) {
1843  // This was probably an attempt to initialize the variable.
1844  SourceLocation LParen = ConsumeParen(), RParen = LParen;
1845  if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch))
1846  RParen = ConsumeParen();
1847  Diag(DeclOut->getLocation(),
1848  diag::err_expected_init_in_condition_lparen)
1849  << SourceRange(LParen, RParen);
1850  } else {
1851  Diag(DeclOut->getLocation(), diag::err_expected_init_in_condition);
1852  }
1853 
1854  if (!InitExpr.isInvalid())
1855  Actions.AddInitializerToDecl(DeclOut, InitExpr.get(), !CopyInitialization);
1856  else
1857  Actions.ActOnInitializerError(DeclOut);
1858 
1859  Actions.FinalizeDeclaration(DeclOut);
1860  return Actions.ActOnConditionVariable(DeclOut, Loc, CK);
1861 }
1862 
1863 /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
1864 /// This should only be called when the current token is known to be part of
1865 /// simple-type-specifier.
1866 ///
1867 /// simple-type-specifier:
1868 /// '::'[opt] nested-name-specifier[opt] type-name
1869 /// '::'[opt] nested-name-specifier 'template' simple-template-id [TODO]
1870 /// char
1871 /// wchar_t
1872 /// bool
1873 /// short
1874 /// int
1875 /// long
1876 /// signed
1877 /// unsigned
1878 /// float
1879 /// double
1880 /// void
1881 /// [GNU] typeof-specifier
1882 /// [C++0x] auto [TODO]
1883 ///
1884 /// type-name:
1885 /// class-name
1886 /// enum-name
1887 /// typedef-name
1888 ///
1889 void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) {
1890  DS.SetRangeStart(Tok.getLocation());
1891  const char *PrevSpec;
1892  unsigned DiagID;
1893  SourceLocation Loc = Tok.getLocation();
1894  const clang::PrintingPolicy &Policy =
1895  Actions.getASTContext().getPrintingPolicy();
1896 
1897  switch (Tok.getKind()) {
1898  case tok::identifier: // foo::bar
1899  case tok::coloncolon: // ::foo::bar
1900  llvm_unreachable("Annotation token should already be formed!");
1901  default:
1902  llvm_unreachable("Not a simple-type-specifier token!");
1903 
1904  // type-name
1905  case tok::annot_typename: {
1906  if (getTypeAnnotation(Tok))
1907  DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID,
1908  getTypeAnnotation(Tok), Policy);
1909  else
1910  DS.SetTypeSpecError();
1911 
1912  DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1913  ConsumeAnnotationToken();
1914 
1915  DS.Finish(Actions, Policy);
1916  return;
1917  }
1918 
1919  // builtin types
1920  case tok::kw_short:
1921  DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID, Policy);
1922  break;
1923  case tok::kw_long:
1924  DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, DiagID, Policy);
1925  break;
1926  case tok::kw___int64:
1927  DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, DiagID, Policy);
1928  break;
1929  case tok::kw_signed:
1930  DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID);
1931  break;
1932  case tok::kw_unsigned:
1933  DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, DiagID);
1934  break;
1935  case tok::kw_void:
1936  DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID, Policy);
1937  break;
1938  case tok::kw_char:
1939  DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID, Policy);
1940  break;
1941  case tok::kw_int:
1942  DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID, Policy);
1943  break;
1944  case tok::kw___int128:
1945  DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec, DiagID, Policy);
1946  break;
1947  case tok::kw_half:
1948  DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, DiagID, Policy);
1949  break;
1950  case tok::kw_float:
1951  DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID, Policy);
1952  break;
1953  case tok::kw_double:
1954  DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID, Policy);
1955  break;
1956  case tok::kw__Float16:
1957  DS.SetTypeSpecType(DeclSpec::TST_float16, Loc, PrevSpec, DiagID, Policy);
1958  break;
1959  case tok::kw___float128:
1960  DS.SetTypeSpecType(DeclSpec::TST_float128, Loc, PrevSpec, DiagID, Policy);
1961  break;
1962  case tok::kw_wchar_t:
1963  DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID, Policy);
1964  break;
1965  case tok::kw_char8_t:
1966  DS.SetTypeSpecType(DeclSpec::TST_char8, Loc, PrevSpec, DiagID, Policy);
1967  break;
1968  case tok::kw_char16_t:
1969  DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID, Policy);
1970  break;
1971  case tok::kw_char32_t:
1972  DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID, Policy);
1973  break;
1974  case tok::kw_bool:
1975  DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID, Policy);
1976  break;
1977  case tok::annot_decltype:
1978  case tok::kw_decltype:
1979  DS.SetRangeEnd(ParseDecltypeSpecifier(DS));
1980  return DS.Finish(Actions, Policy);
1981 
1982  // GNU typeof support.
1983  case tok::kw_typeof:
1984  ParseTypeofSpecifier(DS);
1985  DS.Finish(Actions, Policy);
1986  return;
1987  }
1988  ConsumeAnyToken();
1989  DS.SetRangeEnd(PrevTokLocation);
1990  DS.Finish(Actions, Policy);
1991 }
1992 
1993 /// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++
1994 /// [dcl.name]), which is a non-empty sequence of type-specifiers,
1995 /// e.g., "const short int". Note that the DeclSpec is *not* finished
1996 /// by parsing the type-specifier-seq, because these sequences are
1997 /// typically followed by some form of declarator. Returns true and
1998 /// emits diagnostics if this is not a type-specifier-seq, false
1999 /// otherwise.
2000 ///
2001 /// type-specifier-seq: [C++ 8.1]
2002 /// type-specifier type-specifier-seq[opt]
2003 ///
2004 bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) {
2005  ParseSpecifierQualifierList(DS, AS_none, DeclSpecContext::DSC_type_specifier);
2006  DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy());
2007  return false;
2008 }
2009 
2010 /// Finish parsing a C++ unqualified-id that is a template-id of
2011 /// some form.
2012 ///
2013 /// This routine is invoked when a '<' is encountered after an identifier or
2014 /// operator-function-id is parsed by \c ParseUnqualifiedId() to determine
2015 /// whether the unqualified-id is actually a template-id. This routine will
2016 /// then parse the template arguments and form the appropriate template-id to
2017 /// return to the caller.
2018 ///
2019 /// \param SS the nested-name-specifier that precedes this template-id, if
2020 /// we're actually parsing a qualified-id.
2021 ///
2022 /// \param Name for constructor and destructor names, this is the actual
2023 /// identifier that may be a template-name.
2024 ///
2025 /// \param NameLoc the location of the class-name in a constructor or
2026 /// destructor.
2027 ///
2028 /// \param EnteringContext whether we're entering the scope of the
2029 /// nested-name-specifier.
2030 ///
2031 /// \param ObjectType if this unqualified-id occurs within a member access
2032 /// expression, the type of the base object whose member is being accessed.
2033 ///
2034 /// \param Id as input, describes the template-name or operator-function-id
2035 /// that precedes the '<'. If template arguments were parsed successfully,
2036 /// will be updated with the template-id.
2037 ///
2038 /// \param AssumeTemplateId When true, this routine will assume that the name
2039 /// refers to a template without performing name lookup to verify.
2040 ///
2041 /// \returns true if a parse error occurred, false otherwise.
2042 bool Parser::ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
2043  SourceLocation TemplateKWLoc,
2044  IdentifierInfo *Name,
2045  SourceLocation NameLoc,
2046  bool EnteringContext,
2047  ParsedType ObjectType,
2048  UnqualifiedId &Id,
2049  bool AssumeTemplateId) {
2050  assert(Tok.is(tok::less) && "Expected '<' to finish parsing a template-id");
2051 
2052  TemplateTy Template;
2054  switch (Id.getKind()) {
2058  if (AssumeTemplateId) {
2059  // We defer the injected-class-name checks until we've found whether
2060  // this template-id is used to form a nested-name-specifier or not.
2061  TNK = Actions.ActOnDependentTemplateName(
2062  getCurScope(), SS, TemplateKWLoc, Id, ObjectType, EnteringContext,
2063  Template, /*AllowInjectedClassName*/ true);
2064  if (TNK == TNK_Non_template)
2065  return true;
2066  } else {
2067  bool MemberOfUnknownSpecialization;
2068  TNK = Actions.isTemplateName(getCurScope(), SS,
2069  TemplateKWLoc.isValid(), Id,
2070  ObjectType, EnteringContext, Template,
2071  MemberOfUnknownSpecialization);
2072 
2073  if (TNK == TNK_Non_template && MemberOfUnknownSpecialization &&
2074  ObjectType && IsTemplateArgumentList()) {
2075  // We have something like t->getAs<T>(), where getAs is a
2076  // member of an unknown specialization. However, this will only
2077  // parse correctly as a template, so suggest the keyword 'template'
2078  // before 'getAs' and treat this as a dependent template name.
2079  std::string Name;
2081  Name = Id.Identifier->getName();
2082  else {
2083  Name = "operator ";
2086  else
2087  Name += Id.Identifier->getName();
2088  }
2089  Diag(Id.StartLocation, diag::err_missing_dependent_template_keyword)
2090  << Name
2091  << FixItHint::CreateInsertion(Id.StartLocation, "template ");
2092  TNK = Actions.ActOnDependentTemplateName(
2093  getCurScope(), SS, TemplateKWLoc, Id, ObjectType, EnteringContext,
2094  Template, /*AllowInjectedClassName*/ true);
2095  if (TNK == TNK_Non_template)
2096  return true;
2097  }
2098  }
2099  break;
2100 
2103  bool MemberOfUnknownSpecialization;
2104  TemplateName.setIdentifier(Name, NameLoc);
2105  TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
2106  TemplateName, ObjectType,
2107  EnteringContext, Template,
2108  MemberOfUnknownSpecialization);
2109  break;
2110  }
2111 
2114  bool MemberOfUnknownSpecialization;
2115  TemplateName.setIdentifier(Name, NameLoc);
2116  if (ObjectType) {
2117  TNK = Actions.ActOnDependentTemplateName(
2118  getCurScope(), SS, TemplateKWLoc, TemplateName, ObjectType,
2119  EnteringContext, Template, /*AllowInjectedClassName*/ true);
2120  if (TNK == TNK_Non_template)
2121  return true;
2122  } else {
2123  TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
2124  TemplateName, ObjectType,
2125  EnteringContext, Template,
2126  MemberOfUnknownSpecialization);
2127 
2128  if (TNK == TNK_Non_template && !Id.DestructorName.get()) {
2129  Diag(NameLoc, diag::err_destructor_template_id)
2130  << Name << SS.getRange();
2131  return true;
2132  }
2133  }
2134  break;
2135  }
2136 
2137  default:
2138  return false;
2139  }
2140 
2141  if (TNK == TNK_Non_template)
2142  return false;
2143 
2144  // Parse the enclosed template argument list.
2145  SourceLocation LAngleLoc, RAngleLoc;
2146  TemplateArgList TemplateArgs;
2147  if (ParseTemplateIdAfterTemplateName(true, LAngleLoc, TemplateArgs,
2148  RAngleLoc))
2149  return true;
2150 
2154  // Form a parsed representation of the template-id to be stored in the
2155  // UnqualifiedId.
2156 
2157  // FIXME: Store name for literal operator too.
2158  IdentifierInfo *TemplateII =
2160  : nullptr;
2161  OverloadedOperatorKind OpKind =
2163  ? OO_None
2165 
2167  SS, TemplateKWLoc, Id.StartLocation, TemplateII, OpKind, Template, TNK,
2168  LAngleLoc, RAngleLoc, TemplateArgs, TemplateIds);
2169 
2170  Id.setTemplateId(TemplateId);
2171  return false;
2172  }
2173 
2174  // Bundle the template arguments together.
2175  ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
2176 
2177  // Constructor and destructor names.
2179  = Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
2180  Template, Name, NameLoc,
2181  LAngleLoc, TemplateArgsPtr, RAngleLoc,
2182  /*IsCtorOrDtorName=*/true);
2183  if (Type.isInvalid())
2184  return true;
2185 
2187  Id.setConstructorName(Type.get(), NameLoc, RAngleLoc);
2188  else
2189  Id.setDestructorName(Id.StartLocation, Type.get(), RAngleLoc);
2190 
2191  return false;
2192 }
2193 
2194 /// Parse an operator-function-id or conversion-function-id as part
2195 /// of a C++ unqualified-id.
2196 ///
2197 /// This routine is responsible only for parsing the operator-function-id or
2198 /// conversion-function-id; it does not handle template arguments in any way.
2199 ///
2200 /// \code
2201 /// operator-function-id: [C++ 13.5]
2202 /// 'operator' operator
2203 ///
2204 /// operator: one of
2205 /// new delete new[] delete[]
2206 /// + - * / % ^ & | ~
2207 /// ! = < > += -= *= /= %=
2208 /// ^= &= |= << >> >>= <<= == !=
2209 /// <= >= && || ++ -- , ->* ->
2210 /// () [] <=>
2211 ///
2212 /// conversion-function-id: [C++ 12.3.2]
2213 /// operator conversion-type-id
2214 ///
2215 /// conversion-type-id:
2216 /// type-specifier-seq conversion-declarator[opt]
2217 ///
2218 /// conversion-declarator:
2219 /// ptr-operator conversion-declarator[opt]
2220 /// \endcode
2221 ///
2222 /// \param SS The nested-name-specifier that preceded this unqualified-id. If
2223 /// non-empty, then we are parsing the unqualified-id of a qualified-id.
2224 ///
2225 /// \param EnteringContext whether we are entering the scope of the
2226 /// nested-name-specifier.
2227 ///
2228 /// \param ObjectType if this unqualified-id occurs within a member access
2229 /// expression, the type of the base object whose member is being accessed.
2230 ///
2231 /// \param Result on a successful parse, contains the parsed unqualified-id.
2232 ///
2233 /// \returns true if parsing fails, false otherwise.
2234 bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
2235  ParsedType ObjectType,
2236  UnqualifiedId &Result) {
2237  assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword");
2238 
2239  // Consume the 'operator' keyword.
2240  SourceLocation KeywordLoc = ConsumeToken();
2241 
2242  // Determine what kind of operator name we have.
2243  unsigned SymbolIdx = 0;
2244  SourceLocation SymbolLocations[3];
2246  switch (Tok.getKind()) {
2247  case tok::kw_new:
2248  case tok::kw_delete: {
2249  bool isNew = Tok.getKind() == tok::kw_new;
2250  // Consume the 'new' or 'delete'.
2251  SymbolLocations[SymbolIdx++] = ConsumeToken();
2252  // Check for array new/delete.
2253  if (Tok.is(tok::l_square) &&
2254  (!getLangOpts().CPlusPlus11 || NextToken().isNot(tok::l_square))) {
2255  // Consume the '[' and ']'.
2256  BalancedDelimiterTracker T(*this, tok::l_square);
2257  T.consumeOpen();
2258  T.consumeClose();
2259  if (T.getCloseLocation().isInvalid())
2260  return true;
2261 
2262  SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2263  SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2264  Op = isNew? OO_Array_New : OO_Array_Delete;
2265  } else {
2266  Op = isNew? OO_New : OO_Delete;
2267  }
2268  break;
2269  }
2270 
2271 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2272  case tok::Token: \
2273  SymbolLocations[SymbolIdx++] = ConsumeToken(); \
2274  Op = OO_##Name; \
2275  break;
2276 #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2277 #include "clang/Basic/OperatorKinds.def"
2278 
2279  case tok::l_paren: {
2280  // Consume the '(' and ')'.
2281  BalancedDelimiterTracker T(*this, tok::l_paren);
2282  T.consumeOpen();
2283  T.consumeClose();
2284  if (T.getCloseLocation().isInvalid())
2285  return true;
2286 
2287  SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2288  SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2289  Op = OO_Call;
2290  break;
2291  }
2292 
2293  case tok::l_square: {
2294  // Consume the '[' and ']'.
2295  BalancedDelimiterTracker T(*this, tok::l_square);
2296  T.consumeOpen();
2297  T.consumeClose();
2298  if (T.getCloseLocation().isInvalid())
2299  return true;
2300 
2301  SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2302  SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2303  Op = OO_Subscript;
2304  break;
2305  }
2306 
2307  case tok::code_completion: {
2308  // Code completion for the operator name.
2310  cutOffParsing();
2311  // Don't try to parse any further.
2312  return true;
2313  }
2314 
2315  default:
2316  break;
2317  }
2318 
2319  if (Op != OO_None) {
2320  // We have parsed an operator-function-id.
2321  Result.setOperatorFunctionId(KeywordLoc, Op, SymbolLocations);
2322  return false;
2323  }
2324 
2325  // Parse a literal-operator-id.
2326  //
2327  // literal-operator-id: C++11 [over.literal]
2328  // operator string-literal identifier
2329  // operator user-defined-string-literal
2330 
2331  if (getLangOpts().CPlusPlus11 && isTokenStringLiteral()) {
2332  Diag(Tok.getLocation(), diag::warn_cxx98_compat_literal_operator);
2333 
2334  SourceLocation DiagLoc;
2335  unsigned DiagId = 0;
2336 
2337  // We're past translation phase 6, so perform string literal concatenation
2338  // before checking for "".
2339  SmallVector<Token, 4> Toks;
2341  while (isTokenStringLiteral()) {
2342  if (!Tok.is(tok::string_literal) && !DiagId) {
2343  // C++11 [over.literal]p1:
2344  // The string-literal or user-defined-string-literal in a
2345  // literal-operator-id shall have no encoding-prefix [...].
2346  DiagLoc = Tok.getLocation();
2347  DiagId = diag::err_literal_operator_string_prefix;
2348  }
2349  Toks.push_back(Tok);
2350  TokLocs.push_back(ConsumeStringToken());
2351  }
2352 
2353  StringLiteralParser Literal(Toks, PP);
2354  if (Literal.hadError)
2355  return true;
2356 
2357  // Grab the literal operator's suffix, which will be either the next token
2358  // or a ud-suffix from the string literal.
2359  IdentifierInfo *II = nullptr;
2360  SourceLocation SuffixLoc;
2361  if (!Literal.getUDSuffix().empty()) {
2362  II = &PP.getIdentifierTable().get(Literal.getUDSuffix());
2363  SuffixLoc =
2365  Literal.getUDSuffixOffset(),
2366  PP.getSourceManager(), getLangOpts());
2367  } else if (Tok.is(tok::identifier)) {
2368  II = Tok.getIdentifierInfo();
2369  SuffixLoc = ConsumeToken();
2370  TokLocs.push_back(SuffixLoc);
2371  } else {
2372  Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
2373  return true;
2374  }
2375 
2376  // The string literal must be empty.
2377  if (!Literal.GetString().empty() || Literal.Pascal) {
2378  // C++11 [over.literal]p1:
2379  // The string-literal or user-defined-string-literal in a
2380  // literal-operator-id shall [...] contain no characters
2381  // other than the implicit terminating '\0'.
2382  DiagLoc = TokLocs.front();
2383  DiagId = diag::err_literal_operator_string_not_empty;
2384  }
2385 
2386  if (DiagId) {
2387  // This isn't a valid literal-operator-id, but we think we know
2388  // what the user meant. Tell them what they should have written.
2389  SmallString<32> Str;
2390  Str += "\"\"";
2391  Str += II->getName();
2392  Diag(DiagLoc, DiagId) << FixItHint::CreateReplacement(
2393  SourceRange(TokLocs.front(), TokLocs.back()), Str);
2394  }
2395 
2396  Result.setLiteralOperatorId(II, KeywordLoc, SuffixLoc);
2397 
2398  return Actions.checkLiteralOperatorId(SS, Result);
2399  }
2400 
2401  // Parse a conversion-function-id.
2402  //
2403  // conversion-function-id: [C++ 12.3.2]
2404  // operator conversion-type-id
2405  //
2406  // conversion-type-id:
2407  // type-specifier-seq conversion-declarator[opt]
2408  //
2409  // conversion-declarator:
2410  // ptr-operator conversion-declarator[opt]
2411 
2412  // Parse the type-specifier-seq.
2413  DeclSpec DS(AttrFactory);
2414  if (ParseCXXTypeSpecifierSeq(DS)) // FIXME: ObjectType?
2415  return true;
2416 
2417  // Parse the conversion-declarator, which is merely a sequence of
2418  // ptr-operators.
2420  ParseDeclaratorInternal(D, /*DirectDeclParser=*/nullptr);
2421 
2422  // Finish up the type.
2423  TypeResult Ty = Actions.ActOnTypeName(getCurScope(), D);
2424  if (Ty.isInvalid())
2425  return true;
2426 
2427  // Note that this is a conversion-function-id.
2428  Result.setConversionFunctionId(KeywordLoc, Ty.get(),
2429  D.getSourceRange().getEnd());
2430  return false;
2431 }
2432 
2433 /// Parse a C++ unqualified-id (or a C identifier), which describes the
2434 /// name of an entity.
2435 ///
2436 /// \code
2437 /// unqualified-id: [C++ expr.prim.general]
2438 /// identifier
2439 /// operator-function-id
2440 /// conversion-function-id
2441 /// [C++0x] literal-operator-id [TODO]
2442 /// ~ class-name
2443 /// template-id
2444 ///
2445 /// \endcode
2446 ///
2447 /// \param SS The nested-name-specifier that preceded this unqualified-id. If
2448 /// non-empty, then we are parsing the unqualified-id of a qualified-id.
2449 ///
2450 /// \param EnteringContext whether we are entering the scope of the
2451 /// nested-name-specifier.
2452 ///
2453 /// \param AllowDestructorName whether we allow parsing of a destructor name.
2454 ///
2455 /// \param AllowConstructorName whether we allow parsing a constructor name.
2456 ///
2457 /// \param AllowDeductionGuide whether we allow parsing a deduction guide name.
2458 ///
2459 /// \param ObjectType if this unqualified-id occurs within a member access
2460 /// expression, the type of the base object whose member is being accessed.
2461 ///
2462 /// \param Result on a successful parse, contains the parsed unqualified-id.
2463 ///
2464 /// \returns true if parsing fails, false otherwise.
2465 bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
2466  bool AllowDestructorName,
2467  bool AllowConstructorName,
2468  bool AllowDeductionGuide,
2469  ParsedType ObjectType,
2470  SourceLocation *TemplateKWLoc,
2471  UnqualifiedId &Result) {
2472  if (TemplateKWLoc)
2473  *TemplateKWLoc = SourceLocation();
2474 
2475  // Handle 'A::template B'. This is for template-ids which have not
2476  // already been annotated by ParseOptionalCXXScopeSpecifier().
2477  bool TemplateSpecified = false;
2478  if (Tok.is(tok::kw_template)) {
2479  if (TemplateKWLoc && (ObjectType || SS.isSet())) {
2480  TemplateSpecified = true;
2481  *TemplateKWLoc = ConsumeToken();
2482  } else {
2483  SourceLocation TemplateLoc = ConsumeToken();
2484  Diag(TemplateLoc, diag::err_unexpected_template_in_unqualified_id)
2485  << FixItHint::CreateRemoval(TemplateLoc);
2486  }
2487  }
2488 
2489  // unqualified-id:
2490  // identifier
2491  // template-id (when it hasn't already been annotated)
2492  if (Tok.is(tok::identifier)) {
2493  // Consume the identifier.
2494  IdentifierInfo *Id = Tok.getIdentifierInfo();
2495  SourceLocation IdLoc = ConsumeToken();
2496 
2497  if (!getLangOpts().CPlusPlus) {
2498  // If we're not in C++, only identifiers matter. Record the
2499  // identifier and return.
2500  Result.setIdentifier(Id, IdLoc);
2501  return false;
2502  }
2503 
2505  if (AllowConstructorName &&
2506  Actions.isCurrentClassName(*Id, getCurScope(), &SS)) {
2507  // We have parsed a constructor name.
2508  ParsedType Ty = Actions.getTypeName(*Id, IdLoc, getCurScope(), &SS, false,
2509  false, nullptr,
2510  /*IsCtorOrDtorName=*/true,
2511  /*NonTrivialTypeSourceInfo=*/true);
2512  Result.setConstructorName(Ty, IdLoc, IdLoc);
2513  } else if (getLangOpts().CPlusPlus17 &&
2514  AllowDeductionGuide && SS.isEmpty() &&
2515  Actions.isDeductionGuideName(getCurScope(), *Id, IdLoc,
2516  &TemplateName)) {
2517  // We have parsed a template-name naming a deduction guide.
2518  Result.setDeductionGuideName(TemplateName, IdLoc);
2519  } else {
2520  // We have parsed an identifier.
2521  Result.setIdentifier(Id, IdLoc);
2522  }
2523 
2524  // If the next token is a '<', we may have a template.
2525  TemplateTy Template;
2526  if (Tok.is(tok::less))
2527  return ParseUnqualifiedIdTemplateId(
2528  SS, TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), Id, IdLoc,
2529  EnteringContext, ObjectType, Result, TemplateSpecified);
2530  else if (TemplateSpecified &&
2532  getCurScope(), SS, *TemplateKWLoc, Result, ObjectType,
2533  EnteringContext, Template,
2534  /*AllowInjectedClassName*/ true) == TNK_Non_template)
2535  return true;
2536 
2537  return false;
2538  }
2539 
2540  // unqualified-id:
2541  // template-id (already parsed and annotated)
2542  if (Tok.is(tok::annot_template_id)) {
2543  TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
2544 
2545  // If the template-name names the current class, then this is a constructor
2546  if (AllowConstructorName && TemplateId->Name &&
2547  Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
2548  if (SS.isSet()) {
2549  // C++ [class.qual]p2 specifies that a qualified template-name
2550  // is taken as the constructor name where a constructor can be
2551  // declared. Thus, the template arguments are extraneous, so
2552  // complain about them and remove them entirely.
2553  Diag(TemplateId->TemplateNameLoc,
2554  diag::err_out_of_line_constructor_template_id)
2555  << TemplateId->Name
2557  SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc));
2558  ParsedType Ty =
2559  Actions.getTypeName(*TemplateId->Name, TemplateId->TemplateNameLoc,
2560  getCurScope(), &SS, false, false, nullptr,
2561  /*IsCtorOrDtorName=*/true,
2562  /*NontrivialTypeSourceInfo=*/true);
2563  Result.setConstructorName(Ty, TemplateId->TemplateNameLoc,
2564  TemplateId->RAngleLoc);
2565  ConsumeAnnotationToken();
2566  return false;
2567  }
2568 
2569  Result.setConstructorTemplateId(TemplateId);
2570  ConsumeAnnotationToken();
2571  return false;
2572  }
2573 
2574  // We have already parsed a template-id; consume the annotation token as
2575  // our unqualified-id.
2576  Result.setTemplateId(TemplateId);
2577  SourceLocation TemplateLoc = TemplateId->TemplateKWLoc;
2578  if (TemplateLoc.isValid()) {
2579  if (TemplateKWLoc && (ObjectType || SS.isSet()))
2580  *TemplateKWLoc = TemplateLoc;
2581  else
2582  Diag(TemplateLoc, diag::err_unexpected_template_in_unqualified_id)
2583  << FixItHint::CreateRemoval(TemplateLoc);
2584  }
2585  ConsumeAnnotationToken();
2586  return false;
2587  }
2588 
2589  // unqualified-id:
2590  // operator-function-id
2591  // conversion-function-id
2592  if (Tok.is(tok::kw_operator)) {
2593  if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, Result))
2594  return true;
2595 
2596  // If we have an operator-function-id or a literal-operator-id and the next
2597  // token is a '<', we may have a
2598  //
2599  // template-id:
2600  // operator-function-id < template-argument-list[opt] >
2601  TemplateTy Template;
2604  Tok.is(tok::less))
2605  return ParseUnqualifiedIdTemplateId(
2606  SS, TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), nullptr,
2607  SourceLocation(), EnteringContext, ObjectType, Result,
2608  TemplateSpecified);
2609  else if (TemplateSpecified &&
2611  getCurScope(), SS, *TemplateKWLoc, Result, ObjectType,
2612  EnteringContext, Template,
2613  /*AllowInjectedClassName*/ true) == TNK_Non_template)
2614  return true;
2615 
2616  return false;
2617  }
2618 
2619  if (getLangOpts().CPlusPlus &&
2620  (AllowDestructorName || SS.isSet()) && Tok.is(tok::tilde)) {
2621  // C++ [expr.unary.op]p10:
2622  // There is an ambiguity in the unary-expression ~X(), where X is a
2623  // class-name. The ambiguity is resolved in favor of treating ~ as a
2624  // unary complement rather than treating ~X as referring to a destructor.
2625 
2626  // Parse the '~'.
2627  SourceLocation TildeLoc = ConsumeToken();
2628 
2629  if (SS.isEmpty() && Tok.is(tok::kw_decltype)) {
2630  DeclSpec DS(AttrFactory);
2631  SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
2632  if (ParsedType Type =
2633  Actions.getDestructorTypeForDecltype(DS, ObjectType)) {
2634  Result.setDestructorName(TildeLoc, Type, EndLoc);
2635  return false;
2636  }
2637  return true;
2638  }
2639 
2640  // Parse the class-name.
2641  if (Tok.isNot(tok::identifier)) {
2642  Diag(Tok, diag::err_destructor_tilde_identifier);
2643  return true;
2644  }
2645 
2646  // If the user wrote ~T::T, correct it to T::~T.
2647  DeclaratorScopeObj DeclScopeObj(*this, SS);
2648  if (!TemplateSpecified && NextToken().is(tok::coloncolon)) {
2649  // Don't let ParseOptionalCXXScopeSpecifier() "correct"
2650  // `int A; struct { ~A::A(); };` to `int A; struct { ~A:A(); };`,
2651  // it will confuse this recovery logic.
2652  ColonProtectionRAIIObject ColonRAII(*this, false);
2653 
2654  if (SS.isSet()) {
2655  AnnotateScopeToken(SS, /*NewAnnotation*/true);
2656  SS.clear();
2657  }
2658  if (ParseOptionalCXXScopeSpecifier(SS, ObjectType, EnteringContext))
2659  return true;
2660  if (SS.isNotEmpty())
2661  ObjectType = nullptr;
2662  if (Tok.isNot(tok::identifier) || NextToken().is(tok::coloncolon) ||
2663  !SS.isSet()) {
2664  Diag(TildeLoc, diag::err_destructor_tilde_scope);
2665  return true;
2666  }
2667 
2668  // Recover as if the tilde had been written before the identifier.
2669  Diag(TildeLoc, diag::err_destructor_tilde_scope)
2670  << FixItHint::CreateRemoval(TildeLoc)
2671  << FixItHint::CreateInsertion(Tok.getLocation(), "~");
2672 
2673  // Temporarily enter the scope for the rest of this function.
2674  if (Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
2675  DeclScopeObj.EnterDeclaratorScope();
2676  }
2677 
2678  // Parse the class-name (or template-name in a simple-template-id).
2679  IdentifierInfo *ClassName = Tok.getIdentifierInfo();
2680  SourceLocation ClassNameLoc = ConsumeToken();
2681 
2682  if (Tok.is(tok::less)) {
2683  Result.setDestructorName(TildeLoc, nullptr, ClassNameLoc);
2684  return ParseUnqualifiedIdTemplateId(
2685  SS, TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), ClassName,
2686  ClassNameLoc, EnteringContext, ObjectType, Result, TemplateSpecified);
2687  }
2688 
2689  // Note that this is a destructor name.
2690  ParsedType Ty = Actions.getDestructorName(TildeLoc, *ClassName,
2691  ClassNameLoc, getCurScope(),
2692  SS, ObjectType,
2693  EnteringContext);
2694  if (!Ty)
2695  return true;
2696 
2697  Result.setDestructorName(TildeLoc, Ty, ClassNameLoc);
2698  return false;
2699  }
2700 
2701  Diag(Tok, diag::err_expected_unqualified_id)
2702  << getLangOpts().CPlusPlus;
2703  return true;
2704 }
2705 
2706 /// ParseCXXNewExpression - Parse a C++ new-expression. New is used to allocate
2707 /// memory in a typesafe manner and call constructors.
2708 ///
2709 /// This method is called to parse the new expression after the optional :: has
2710 /// been already parsed. If the :: was present, "UseGlobal" is true and "Start"
2711 /// is its location. Otherwise, "Start" is the location of the 'new' token.
2712 ///
2713 /// new-expression:
2714 /// '::'[opt] 'new' new-placement[opt] new-type-id
2715 /// new-initializer[opt]
2716 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2717 /// new-initializer[opt]
2718 ///
2719 /// new-placement:
2720 /// '(' expression-list ')'
2721 ///
2722 /// new-type-id:
2723 /// type-specifier-seq new-declarator[opt]
2724 /// [GNU] attributes type-specifier-seq new-declarator[opt]
2725 ///
2726 /// new-declarator:
2727 /// ptr-operator new-declarator[opt]
2728 /// direct-new-declarator
2729 ///
2730 /// new-initializer:
2731 /// '(' expression-list[opt] ')'
2732 /// [C++0x] braced-init-list
2733 ///
2734 ExprResult
2735 Parser::ParseCXXNewExpression(bool UseGlobal, SourceLocation Start) {
2736  assert(Tok.is(tok::kw_new) && "expected 'new' token");
2737  ConsumeToken(); // Consume 'new'
2738 
2739  // A '(' now can be a new-placement or the '(' wrapping the type-id in the
2740  // second form of new-expression. It can't be a new-type-id.
2741 
2742  ExprVector PlacementArgs;
2743  SourceLocation PlacementLParen, PlacementRParen;
2744 
2745  SourceRange TypeIdParens;
2746  DeclSpec DS(AttrFactory);
2747  Declarator DeclaratorInfo(DS, DeclaratorContext::CXXNewContext);
2748  if (Tok.is(tok::l_paren)) {
2749  // If it turns out to be a placement, we change the type location.
2750  BalancedDelimiterTracker T(*this, tok::l_paren);
2751  T.consumeOpen();
2752  PlacementLParen = T.getOpenLocation();
2753  if (ParseExpressionListOrTypeId(PlacementArgs, DeclaratorInfo)) {
2754  SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2755  return ExprError();
2756  }
2757 
2758  T.consumeClose();
2759  PlacementRParen = T.getCloseLocation();
2760  if (PlacementRParen.isInvalid()) {
2761  SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2762  return ExprError();
2763  }
2764 
2765  if (PlacementArgs.empty()) {
2766  // Reset the placement locations. There was no placement.
2767  TypeIdParens = T.getRange();
2768  PlacementLParen = PlacementRParen = SourceLocation();
2769  } else {
2770  // We still need the type.
2771  if (Tok.is(tok::l_paren)) {
2772  BalancedDelimiterTracker T(*this, tok::l_paren);
2773  T.consumeOpen();
2774  MaybeParseGNUAttributes(DeclaratorInfo);
2775  ParseSpecifierQualifierList(DS);
2776  DeclaratorInfo.SetSourceRange(DS.getSourceRange());
2777  ParseDeclarator(DeclaratorInfo);
2778  T.consumeClose();
2779  TypeIdParens = T.getRange();
2780  } else {
2781  MaybeParseGNUAttributes(DeclaratorInfo);
2782  if (ParseCXXTypeSpecifierSeq(DS))
2783  DeclaratorInfo.setInvalidType(true);
2784  else {
2785  DeclaratorInfo.SetSourceRange(DS.getSourceRange());
2786  ParseDeclaratorInternal(DeclaratorInfo,
2787  &Parser::ParseDirectNewDeclarator);
2788  }
2789  }
2790  }
2791  } else {
2792  // A new-type-id is a simplified type-id, where essentially the
2793  // direct-declarator is replaced by a direct-new-declarator.
2794  MaybeParseGNUAttributes(DeclaratorInfo);
2795  if (ParseCXXTypeSpecifierSeq(DS))
2796  DeclaratorInfo.setInvalidType(true);
2797  else {
2798  DeclaratorInfo.SetSourceRange(DS.getSourceRange());
2799  ParseDeclaratorInternal(DeclaratorInfo,
2800  &Parser::ParseDirectNewDeclarator);
2801  }
2802  }
2803  if (DeclaratorInfo.isInvalidType()) {
2804  SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2805  return ExprError();
2806  }
2807 
2808  ExprResult Initializer;
2809 
2810  if (Tok.is(tok::l_paren)) {
2811  SourceLocation ConstructorLParen, ConstructorRParen;
2812  ExprVector ConstructorArgs;
2813  BalancedDelimiterTracker T(*this, tok::l_paren);
2814  T.consumeOpen();
2815  ConstructorLParen = T.getOpenLocation();
2816  if (Tok.isNot(tok::r_paren)) {
2817  CommaLocsTy CommaLocs;
2818  if (ParseExpressionList(ConstructorArgs, CommaLocs, [&] {
2819  ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(),
2820  DeclaratorInfo).get();
2822  TypeRep.get()->getCanonicalTypeInternal(),
2823  DeclaratorInfo.getLocEnd(),
2824  ConstructorArgs);
2825  })) {
2826  SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2827  return ExprError();
2828  }
2829  }
2830  T.consumeClose();
2831  ConstructorRParen = T.getCloseLocation();
2832  if (ConstructorRParen.isInvalid()) {
2833  SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2834  return ExprError();
2835  }
2836  Initializer = Actions.ActOnParenListExpr(ConstructorLParen,
2837  ConstructorRParen,
2838  ConstructorArgs);
2839  } else if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus11) {
2840  Diag(Tok.getLocation(),
2841  diag::warn_cxx98_compat_generalized_initializer_lists);
2842  Initializer = ParseBraceInitializer();
2843  }
2844  if (Initializer.isInvalid())
2845  return Initializer;
2846 
2847  return Actions.ActOnCXXNew(Start, UseGlobal, PlacementLParen,
2848  PlacementArgs, PlacementRParen,
2849  TypeIdParens, DeclaratorInfo, Initializer.get());
2850 }
2851 
2852 /// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be
2853 /// passed to ParseDeclaratorInternal.
2854 ///
2855 /// direct-new-declarator:
2856 /// '[' expression ']'
2857 /// direct-new-declarator '[' constant-expression ']'
2858 ///
2859 void Parser::ParseDirectNewDeclarator(Declarator &D) {
2860  // Parse the array dimensions.
2861  bool first = true;
2862  while (Tok.is(tok::l_square)) {
2863  // An array-size expression can't start with a lambda.
2864  if (CheckProhibitedCXX11Attribute())
2865  continue;
2866 
2867  BalancedDelimiterTracker T(*this, tok::l_square);
2868  T.consumeOpen();
2869 
2870  ExprResult Size(first ? ParseExpression()
2872  if (Size.isInvalid()) {
2873  // Recover
2874  SkipUntil(tok::r_square, StopAtSemi);
2875  return;
2876  }
2877  first = false;
2878 
2879  T.consumeClose();
2880 
2881  // Attributes here appertain to the array type. C++11 [expr.new]p5.
2882  ParsedAttributes Attrs(AttrFactory);
2883  MaybeParseCXX11Attributes(Attrs);
2884 
2886  /*static=*/false, /*star=*/false,
2887  Size.get(),
2888  T.getOpenLocation(),
2889  T.getCloseLocation()),
2890  Attrs, T.getCloseLocation());
2891 
2892  if (T.getCloseLocation().isInvalid())
2893  return;
2894  }
2895 }
2896 
2897 /// ParseExpressionListOrTypeId - Parse either an expression-list or a type-id.
2898 /// This ambiguity appears in the syntax of the C++ new operator.
2899 ///
2900 /// new-expression:
2901 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2902 /// new-initializer[opt]
2903 ///
2904 /// new-placement:
2905 /// '(' expression-list ')'
2906 ///
2907 bool Parser::ParseExpressionListOrTypeId(
2908  SmallVectorImpl<Expr*> &PlacementArgs,
2909  Declarator &D) {
2910  // The '(' was already consumed.
2911  if (isTypeIdInParens()) {
2912  ParseSpecifierQualifierList(D.getMutableDeclSpec());
2914  ParseDeclarator(D);
2915  return D.isInvalidType();
2916  }
2917 
2918  // It's not a type, it has to be an expression list.
2919  // Discard the comma locations - ActOnCXXNew has enough parameters.
2920  CommaLocsTy CommaLocs;
2921  return ParseExpressionList(PlacementArgs, CommaLocs);
2922 }
2923 
2924 /// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used
2925 /// to free memory allocated by new.
2926 ///
2927 /// This method is called to parse the 'delete' expression after the optional
2928 /// '::' has been already parsed. If the '::' was present, "UseGlobal" is true
2929 /// and "Start" is its location. Otherwise, "Start" is the location of the
2930 /// 'delete' token.
2931 ///
2932 /// delete-expression:
2933 /// '::'[opt] 'delete' cast-expression
2934 /// '::'[opt] 'delete' '[' ']' cast-expression
2935 ExprResult
2936 Parser::ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start) {
2937  assert(Tok.is(tok::kw_delete) && "Expected 'delete' keyword");
2938  ConsumeToken(); // Consume 'delete'
2939 
2940  // Array delete?
2941  bool ArrayDelete = false;
2942  if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) {
2943  // C++11 [expr.delete]p1:
2944  // Whenever the delete keyword is followed by empty square brackets, it
2945  // shall be interpreted as [array delete].
2946  // [Footnote: A lambda expression with a lambda-introducer that consists
2947  // of empty square brackets can follow the delete keyword if
2948  // the lambda expression is enclosed in parentheses.]
2949  // FIXME: Produce a better diagnostic if the '[]' is unambiguously a
2950  // lambda-introducer.
2951  ArrayDelete = true;
2952  BalancedDelimiterTracker T(*this, tok::l_square);
2953 
2954  T.consumeOpen();
2955  T.consumeClose();
2956  if (T.getCloseLocation().isInvalid())
2957  return ExprError();
2958  }
2959 
2960  ExprResult Operand(ParseCastExpression(false));
2961  if (Operand.isInvalid())
2962  return Operand;
2963 
2964  return Actions.ActOnCXXDelete(Start, UseGlobal, ArrayDelete, Operand.get());
2965 }
2966 
2968  switch (kind) {
2969  default: llvm_unreachable("Not a known type trait");
2970 #define TYPE_TRAIT_1(Spelling, Name, Key) \
2971 case tok::kw_ ## Spelling: return UTT_ ## Name;
2972 #define TYPE_TRAIT_2(Spelling, Name, Key) \
2973 case tok::kw_ ## Spelling: return BTT_ ## Name;
2974 #include "clang/Basic/TokenKinds.def"
2975 #define TYPE_TRAIT_N(Spelling, Name, Key) \
2976  case tok::kw_ ## Spelling: return TT_ ## Name;
2977 #include "clang/Basic/TokenKinds.def"
2978  }
2979 }
2980 
2982  switch(kind) {
2983  default: llvm_unreachable("Not a known binary type trait");
2984  case tok::kw___array_rank: return ATT_ArrayRank;
2985  case tok::kw___array_extent: return ATT_ArrayExtent;
2986  }
2987 }
2988 
2990  switch(kind) {
2991  default: llvm_unreachable("Not a known unary expression trait.");
2992  case tok::kw___is_lvalue_expr: return ET_IsLValueExpr;
2993  case tok::kw___is_rvalue_expr: return ET_IsRValueExpr;
2994  }
2995 }
2996 
2998  switch (kind) {
2999  default: llvm_unreachable("Not a known type trait");
3000 #define TYPE_TRAIT(N,Spelling,K) case tok::kw_##Spelling: return N;
3001 #include "clang/Basic/TokenKinds.def"
3002  }
3003 }
3004 
3005 /// Parse the built-in type-trait pseudo-functions that allow
3006 /// implementation of the TR1/C++11 type traits templates.
3007 ///
3008 /// primary-expression:
3009 /// unary-type-trait '(' type-id ')'
3010 /// binary-type-trait '(' type-id ',' type-id ')'
3011 /// type-trait '(' type-id-seq ')'
3012 ///
3013 /// type-id-seq:
3014 /// type-id ...[opt] type-id-seq[opt]
3015 ///
3016 ExprResult Parser::ParseTypeTrait() {
3017  tok::TokenKind Kind = Tok.getKind();
3018  unsigned Arity = TypeTraitArity(Kind);
3019 
3020  SourceLocation Loc = ConsumeToken();
3021 
3022  BalancedDelimiterTracker Parens(*this, tok::l_paren);
3023  if (Parens.expectAndConsume())
3024  return ExprError();
3025 
3027  do {
3028  // Parse the next type.
3029  TypeResult Ty = ParseTypeName();
3030  if (Ty.isInvalid()) {
3031  Parens.skipToEnd();
3032  return ExprError();
3033  }
3034 
3035  // Parse the ellipsis, if present.
3036  if (Tok.is(tok::ellipsis)) {
3037  Ty = Actions.ActOnPackExpansion(Ty.get(), ConsumeToken());
3038  if (Ty.isInvalid()) {
3039  Parens.skipToEnd();
3040  return ExprError();
3041  }
3042  }
3043 
3044  // Add this type to the list of arguments.
3045  Args.push_back(Ty.get());
3046  } while (TryConsumeToken(tok::comma));
3047 
3048  if (Parens.consumeClose())
3049  return ExprError();
3050 
3051  SourceLocation EndLoc = Parens.getCloseLocation();
3052 
3053  if (Arity && Args.size() != Arity) {
3054  Diag(EndLoc, diag::err_type_trait_arity)
3055  << Arity << 0 << (Arity > 1) << (int)Args.size() << SourceRange(Loc);
3056  return ExprError();
3057  }
3058 
3059  if (!Arity && Args.empty()) {
3060  Diag(EndLoc, diag::err_type_trait_arity)
3061  << 1 << 1 << 1 << (int)Args.size() << SourceRange(Loc);
3062  return ExprError();
3063  }
3064 
3065  return Actions.ActOnTypeTrait(TypeTraitFromTokKind(Kind), Loc, Args, EndLoc);
3066 }
3067 
3068 /// ParseArrayTypeTrait - Parse the built-in array type-trait
3069 /// pseudo-functions.
3070 ///
3071 /// primary-expression:
3072 /// [Embarcadero] '__array_rank' '(' type-id ')'
3073 /// [Embarcadero] '__array_extent' '(' type-id ',' expression ')'
3074 ///
3075 ExprResult Parser::ParseArrayTypeTrait() {
3077  SourceLocation Loc = ConsumeToken();
3078 
3079  BalancedDelimiterTracker T(*this, tok::l_paren);
3080  if (T.expectAndConsume())
3081  return ExprError();
3082 
3083  TypeResult Ty = ParseTypeName();
3084  if (Ty.isInvalid()) {
3085  SkipUntil(tok::comma, StopAtSemi);
3086  SkipUntil(tok::r_paren, StopAtSemi);
3087  return ExprError();
3088  }
3089 
3090  switch (ATT) {
3091  case ATT_ArrayRank: {
3092  T.consumeClose();
3093  return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), nullptr,
3094  T.getCloseLocation());
3095  }
3096  case ATT_ArrayExtent: {
3097  if (ExpectAndConsume(tok::comma)) {
3098  SkipUntil(tok::r_paren, StopAtSemi);
3099  return ExprError();
3100  }
3101 
3102  ExprResult DimExpr = ParseExpression();
3103  T.consumeClose();
3104 
3105  return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), DimExpr.get(),
3106  T.getCloseLocation());
3107  }
3108  }
3109  llvm_unreachable("Invalid ArrayTypeTrait!");
3110 }
3111 
3112 /// ParseExpressionTrait - Parse built-in expression-trait
3113 /// pseudo-functions like __is_lvalue_expr( xxx ).
3114 ///
3115 /// primary-expression:
3116 /// [Embarcadero] expression-trait '(' expression ')'
3117 ///
3118 ExprResult Parser::ParseExpressionTrait() {
3120  SourceLocation Loc = ConsumeToken();
3121 
3122  BalancedDelimiterTracker T(*this, tok::l_paren);
3123  if (T.expectAndConsume())
3124  return ExprError();
3125 
3127 
3128  T.consumeClose();
3129 
3130  return Actions.ActOnExpressionTrait(ET, Loc, Expr.get(),
3131  T.getCloseLocation());
3132 }
3133 
3134 
3135 /// ParseCXXAmbiguousParenExpression - We have parsed the left paren of a
3136 /// parenthesized ambiguous type-id. This uses tentative parsing to disambiguate
3137 /// based on the context past the parens.
3138 ExprResult
3139 Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType,
3140  ParsedType &CastTy,
3141  BalancedDelimiterTracker &Tracker,
3142  ColonProtectionRAIIObject &ColonProt) {
3143  assert(getLangOpts().CPlusPlus && "Should only be called for C++!");
3144  assert(ExprType == CastExpr && "Compound literals are not ambiguous!");
3145  assert(isTypeIdInParens() && "Not a type-id!");
3146 
3147  ExprResult Result(true);
3148  CastTy = nullptr;
3149 
3150  // We need to disambiguate a very ugly part of the C++ syntax:
3151  //
3152  // (T())x; - type-id
3153  // (T())*x; - type-id
3154  // (T())/x; - expression
3155  // (T()); - expression
3156  //
3157  // The bad news is that we cannot use the specialized tentative parser, since
3158  // it can only verify that the thing inside the parens can be parsed as
3159  // type-id, it is not useful for determining the context past the parens.
3160  //
3161  // The good news is that the parser can disambiguate this part without
3162  // making any unnecessary Action calls.
3163  //
3164  // It uses a scheme similar to parsing inline methods. The parenthesized
3165  // tokens are cached, the context that follows is determined (possibly by
3166  // parsing a cast-expression), and then we re-introduce the cached tokens
3167  // into the token stream and parse them appropriately.
3168 
3169  ParenParseOption ParseAs;
3170  CachedTokens Toks;
3171 
3172  // Store the tokens of the parentheses. We will parse them after we determine
3173  // the context that follows them.
3174  if (!ConsumeAndStoreUntil(tok::r_paren, Toks)) {
3175  // We didn't find the ')' we expected.
3176  Tracker.consumeClose();
3177  return ExprError();
3178  }
3179 
3180  if (Tok.is(tok::l_brace)) {
3181  ParseAs = CompoundLiteral;
3182  } else {
3183  bool NotCastExpr;
3184  if (Tok.is(tok::l_paren) && NextToken().is(tok::r_paren)) {
3185  NotCastExpr = true;
3186  } else {
3187  // Try parsing the cast-expression that may follow.
3188  // If it is not a cast-expression, NotCastExpr will be true and no token
3189  // will be consumed.
3190  ColonProt.restore();
3191  Result = ParseCastExpression(false/*isUnaryExpression*/,
3192  false/*isAddressofOperand*/,
3193  NotCastExpr,
3194  // type-id has priority.
3195  IsTypeCast);
3196  }
3197 
3198  // If we parsed a cast-expression, it's really a type-id, otherwise it's
3199  // an expression.
3200  ParseAs = NotCastExpr ? SimpleExpr : CastExpr;
3201  }
3202 
3203  // Create a fake EOF to mark end of Toks buffer.
3204  Token AttrEnd;
3205  AttrEnd.startToken();
3206  AttrEnd.setKind(tok::eof);
3207  AttrEnd.setLocation(Tok.getLocation());
3208  AttrEnd.setEofData(Toks.data());
3209  Toks.push_back(AttrEnd);
3210 
3211  // The current token should go after the cached tokens.
3212  Toks.push_back(Tok);
3213  // Re-enter the stored parenthesized tokens into the token stream, so we may
3214  // parse them now.
3215  PP.EnterTokenStream(Toks, true /*DisableMacroExpansion*/);
3216  // Drop the current token and bring the first cached one. It's the same token
3217  // as when we entered this function.
3218  ConsumeAnyToken();
3219 
3220  if (ParseAs >= CompoundLiteral) {
3221  // Parse the type declarator.
3222  DeclSpec DS(AttrFactory);
3223  Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
3224  {
3225  ColonProtectionRAIIObject InnerColonProtection(*this);
3226  ParseSpecifierQualifierList(DS);
3227  ParseDeclarator(DeclaratorInfo);
3228  }
3229 
3230  // Match the ')'.
3231  Tracker.consumeClose();
3232  ColonProt.restore();
3233 
3234  // Consume EOF marker for Toks buffer.
3235  assert(Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData());
3236  ConsumeAnyToken();
3237 
3238  if (ParseAs == CompoundLiteral) {
3239  ExprType = CompoundLiteral;
3240  if (DeclaratorInfo.isInvalidType())
3241  return ExprError();
3242 
3243  TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
3244  return ParseCompoundLiteralExpression(Ty.get(),
3245  Tracker.getOpenLocation(),
3246  Tracker.getCloseLocation());
3247  }
3248 
3249  // We parsed '(' type-id ')' and the thing after it wasn't a '{'.
3250  assert(ParseAs == CastExpr);
3251 
3252  if (DeclaratorInfo.isInvalidType())
3253  return ExprError();
3254 
3255  // Result is what ParseCastExpression returned earlier.
3256  if (!Result.isInvalid())
3257  Result = Actions.ActOnCastExpr(getCurScope(), Tracker.getOpenLocation(),
3258  DeclaratorInfo, CastTy,
3259  Tracker.getCloseLocation(), Result.get());
3260  return Result;
3261  }
3262 
3263  // Not a compound literal, and not followed by a cast-expression.
3264  assert(ParseAs == SimpleExpr);
3265 
3266  ExprType = SimpleExpr;
3267  Result = ParseExpression();
3268  if (!Result.isInvalid() && Tok.is(tok::r_paren))
3269  Result = Actions.ActOnParenExpr(Tracker.getOpenLocation(),
3270  Tok.getLocation(), Result.get());
3271 
3272  // Match the ')'.
3273  if (Result.isInvalid()) {
3274  while (Tok.isNot(tok::eof))
3275  ConsumeAnyToken();
3276  assert(Tok.getEofData() == AttrEnd.getEofData());
3277  ConsumeAnyToken();
3278  return ExprError();
3279  }
3280 
3281  Tracker.consumeClose();
3282  // Consume EOF marker for Toks buffer.
3283  assert(Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData());
3284  ConsumeAnyToken();
3285  return Result;
3286 }
static TypeTrait TypeTraitFromTokKind(tok::TokenKind kind)
Defines the clang::ASTContext interface.
void setConstructorName(ParsedType ClassType, SourceLocation ClassNameLoc, SourceLocation EndLoc)
Specify that this unqualified-id was parsed as a constructor name.
Definition: DeclSpec.h:1068
ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr, ConditionKind CK)
Definition: SemaExpr.cpp:15697
ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc, ParsedType LhsTy, Expr *DimExpr, SourceLocation RParen)
ActOnArrayTypeTrait - Parsed one of the binary type trait support pseudo-functions.
StringRef getUDSuffix() const
ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, Declarator &D, ParsedType &Ty, SourceLocation RParenLoc, Expr *CastExpr)
Definition: SemaExpr.cpp:6083
SourceLocation getLocWithOffset(int Offset) const
Return a source location with the specified offset from this SourceLocation.
no exception specification
PtrTy get() const
Definition: Ownership.h:81
ExprResult ParseExpression(TypeCastState isTypeCast=NotTypeCast)
Simple precedence-based parser for binary/ternary operators.
Definition: ParseExpr.cpp:123
void restore()
restore - This can be used to restore the state early, before the dtor is run.
Keeps information about an identifier in a nested-name-spec.
Definition: Sema.h:5346
This is a scope that corresponds to the parameters within a function prototype.
Definition: Scope.h:81
ConditionResult ActOnConditionVariable(Decl *ConditionVar, SourceLocation StmtLoc, ConditionKind CK)
bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id)
AttributeList * getNext() const
SourceRange getSourceRange() const LLVM_READONLY
Return the source range that covers this unqualified-id.
Definition: DeclSpec.h:1120
static const TSS TSS_unsigned
Definition: DeclSpec.h:268
bool ActOnCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo, bool EnteringContext, CXXScopeSpec &SS, bool ErrorRecoveryLookup=false, bool *IsCorrectedToColon=nullptr, bool OnlyNamespace=false)
The parser has parsed a nested-name-specifier &#39;identifier::&#39;.
SourceLocation StartLocation
The location of the first token that describes this unqualified-id, which will be the location of the...
Definition: DeclSpec.h:978
IdentifierInfo * Name
FIXME: Temporarily stores the name of a specialization.
static const TST TST_wchar
Definition: DeclSpec.h:275
ExprResult ActOnParenListExpr(SourceLocation L, SourceLocation R, MultiExprArg Val)
Definition: SemaExpr.cpp:6256
SourceLocation TemplateNameLoc
TemplateNameLoc - The location of the template name within the source.
static ConditionResult ConditionError()
Definition: Sema.h:9818
const Token & LookAhead(unsigned N)
Peeks ahead N tokens and returns that token without consuming any tokens.
Stmt - This represents one statement.
Definition: Stmt.h:66
IdentifierInfo * Identifier
When Kind == IK_Identifier, the parsed identifier, or when Kind == IK_UserLiteralId, the identifier suffix.
Definition: DeclSpec.h:948
TemplateNameKind isTemplateName(Scope *S, CXXScopeSpec &SS, bool hasTemplateKeyword, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool &MemberOfUnknownSpecialization)
StmtResult ActOnExprStmt(ExprResult Arg)
Definition: SemaStmt.cpp:45
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:95
bool isEmpty() const
No scope specifier.
Definition: DeclSpec.h:189
DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D)
ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a C++ if/switch/while/for statem...
void setEndLoc(SourceLocation Loc)
Definition: DeclSpec.h:71
static const TST TST_char16
Definition: DeclSpec.h:277
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
Defines the PrettyStackTraceEntry class, which is used to make crashes give more contextual informati...
bool SetConstexprSpec(SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID)
Definition: DeclSpec.cpp:979
Defines the C++ template declaration subclasses.
StringRef P
The base class of the type hierarchy.
Definition: Type.h:1420
SourceLocation getCloseLocation() const
This indicates that the scope corresponds to a function, which means that labels are set here...
Definition: Scope.h:47
void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, bool EnteringContext)
Parser - This implements a parser for the C family of languages.
Definition: Parser.h:56
An overloaded operator name, e.g., operator+.
bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS, NestedNameSpecInfo &IdInfo, bool EnteringContext)
IsInvalidUnlessNestedName - This method is used for error recovery purposes to determine whether the ...
ExprResult ActOnExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc, Expr *Queried, SourceLocation RParen)
ActOnExpressionTrait - Parsed one of the unary type trait support pseudo-functions.
static TemplateIdAnnotation * Create(CXXScopeSpec SS, SourceLocation TemplateKWLoc, SourceLocation TemplateNameLoc, IdentifierInfo *Name, OverloadedOperatorKind OperatorKind, ParsedTemplateTy OpaqueTemplateName, TemplateNameKind TemplateKind, SourceLocation LAngleLoc, SourceLocation RAngleLoc, ArrayRef< ParsedTemplateArgument > TemplateArgs, SmallVectorImpl< TemplateIdAnnotation *> &CleanupList)
Creates a new TemplateIdAnnotation with NumArgs arguments and appends it to List. ...
void CodeCompleteObjCMessageReceiver(Scope *S)
RAII object that enters a new expression evaluation context.
Definition: Sema.h:10728
void EnterToken(const Token &Tok)
Enters a token in the token stream to be lexed next.
ActionResult< Stmt * > StmtResult
Definition: Ownership.h:268
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1764
static const TST TST_char
Definition: DeclSpec.h:274
Like System, but searched after the system directories.
void setBegin(SourceLocation b)
Describes how types, statements, expressions, and declarations should be printed. ...
Definition: PrettyPrinter.h:38
ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec *SS=nullptr, bool isClassName=false, bool HasTrailingDot=false, ParsedType ObjectType=nullptr, bool IsCtorOrDtorName=false, bool WantNontrivialTypeSourceInfo=false, bool IsClassTemplateDeductionContext=true, IdentifierInfo **CorrectedII=nullptr)
If the identifier refers to a type name within this scope, return the declaration of that type...
Definition: SemaDecl.cpp:277
ColonProtectionRAIIObject - This sets the Parser::ColonIsSacred bool and restores it when destroyed...
AttributeList * getList() const
bool isUnset() const
Definition: Ownership.h:172
tok::TokenKind getKind() const
Definition: Token.h:90
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:948
Information about a template-id annotation token.
void CodeCompleteOrdinaryName(Scope *S, ParserCompletionContext CompletionContext)
const Token & NextToken()
NextToken - This peeks ahead one token and returns it without consuming it.
Definition: Parser.h:616
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Computes the source location just past the end of the token at this source location.
bool TryConsumeToken(tok::TokenKind Expected)
Definition: Parser.h:327
bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS, const DeclSpec &DS, SourceLocation ColonColonLoc)
One of these records is kept for each identifier that is lexed.
void setConstructorTemplateId(TemplateIdAnnotation *TemplateId)
Specify that this unqualified-id was parsed as a template-id that names a constructor.
Definition: DeclSpec.cpp:39
SourceLocation getAnnotationEndLoc() const
Definition: Token.h:138
sema::LambdaScopeInfo * getCurGenericLambda()
Retrieve the current generic lambda info, if any.
Definition: Sema.cpp:1505
static const TST TST_char8
Definition: DeclSpec.h:276
ExprResult ExprEmpty()
Definition: Ownership.h:289
void AddTypeInfo(const DeclaratorChunk &TI, ParsedAttributes &attrs, SourceLocation EndLoc)
AddTypeInfo - Add a chunk to this declarator.
Definition: DeclSpec.h:2147
void setConversionFunctionId(SourceLocation OperatorLoc, ParsedType Ty, SourceLocation EndLoc)
Specify that this unqualified-id was parsed as a conversion-function-id.
Definition: DeclSpec.h:1036
void CodeCompleteConstructor(Scope *S, QualType Type, SourceLocation Loc, ArrayRef< Expr *> Args)
LambdaCaptureKind
The different capture forms in a lambda introducer.
Definition: Lambda.h:34
The current expression is potentially evaluated at run time, which means that code may be generated t...
bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS)
OverloadedOperatorKind Operator
The kind of overloaded operator.
Definition: DeclSpec.h:931
static const TST TST_double
Definition: DeclSpec.h:283
struct OFI OperatorFunctionId
When Kind == IK_OperatorFunctionId, the overloaded operator that we parsed.
Definition: DeclSpec.h:952
ExprResult ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc, bool isType, void *TyOrExpr, SourceLocation RParenLoc)
ActOnCXXUuidof - Parse __uuidof( something ).
Token - This structure provides full information about a lexed token.
Definition: Token.h:35
void setKind(tok::TokenKind K)
Definition: Token.h:91
RAII class that helps handle the parsing of an open/close delimiter pair, such as braces { ...
ParsedType getDestructorName(SourceLocation TildeLoc, IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec &SS, ParsedType ObjectType, bool EnteringContext)
Definition: SemaExprCXX.cpp:83
A user-defined literal name, e.g., operator "" _i.
void SetSourceRange(SourceRange R)
Definition: DeclSpec.h:1892
bool isInvalidType() const
Definition: DeclSpec.h:2436
void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro, bool AfterAmpersand)
UnionParsedType DestructorName
When Kind == IK_DestructorName, the type referred to by the class-name.
Definition: DeclSpec.h:964
This is a scope that corresponds to a block/closure object.
Definition: Scope.h:71
ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr)
ActOnCXXThrow - Parse throw expressions.
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:920
static ParsedType getTypeAnnotation(const Token &Tok)
getTypeAnnotation - Read a parsed type out of an annotation token.
Definition: Parser.h:621
PtrTy get() const
Definition: Ownership.h:174
< Capturing the *this object by copy
Definition: Lambda.h:37
void ActOnInitializerError(Decl *Dcl)
ActOnInitializerError - Given that there was an error parsing an initializer for the given declaratio...
Definition: SemaDecl.cpp:11011
ExprResult CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl=nullptr, 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...
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:636
SourceRange getAnnotationRange() const
SourceRange of the group of tokens that this annotation token represents.
Definition: Token.h:158
ParsedTemplateArgument * getTemplateArgs()
Retrieves a pointer to the template arguments.
If a crash happens while one of these objects are live, the message is printed out along with the spe...
void SetInvalid(SourceRange R)
Indicate that this nested-name-specifier is invalid.
Definition: DeclSpec.h:199
ExprResult ActOnCXXThis(SourceLocation loc)
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:349
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:63
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition: Expr.h:2747
SourceLocation getSpellingLoc(SourceLocation Loc) const
Given a SourceLocation object, return the spelling location referenced by the ID. ...
ArrayTypeTrait
Names for the array type traits.
Definition: TypeTraits.h:91
SourceLocation ConsumeAnyToken(bool ConsumeCodeCompletionTok=false)
ConsumeAnyToken - Dispatch to the right Consume* method based on the current token type...
Definition: Parser.h:347
void setTemplateId(TemplateIdAnnotation *TemplateId)
Specify that this unqualified-id was parsed as a template-id.
Definition: DeclSpec.cpp:31
LambdaCaptureInitKind
Definition: DeclSpec.h:2534
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclSpec.h:507
const char * getName() const
Definition: Token.h:166
bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS, NestedNameSpecInfo &IdInfo)
SourceLocation TemplateKWLoc
TemplateKWLoc - The location of the template keyword.
static const TST TST_float
Definition: DeclSpec.h:282
TypeTrait
Names for traits that operate specifically on types.
Definition: TypeTraits.h:21
SourceLocation LAngleLoc
The location of the &#39;<&#39; before the template argument list.
DeclSpec & getMutableDeclSpec()
getMutableDeclSpec - Return a non-const version of the DeclSpec.
Definition: DeclSpec.h:1860
static const TSW TSW_long
Definition: DeclSpec.h:255
StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, SourceLocation StartLoc, SourceLocation EndLoc)
Definition: SemaStmt.cpp:73
void SetRangeStart(SourceLocation Loc)
Definition: DeclSpec.h:614
SourceLocation getLocEnd() const LLVM_READONLY
Definition: Stmt.cpp:291
SourceRange getRange() const
Definition: DeclSpec.h:68
SmallVector< LambdaCapture, 4 > Captures
Definition: DeclSpec.h:2563
TST getTypeSpecType() const
Definition: DeclSpec.h:483
ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body, Scope *CurScope)
ActOnLambdaExpr - This is called when the body of a lambda expression was successfully completed...
Expr - This represents one expression.
Definition: Expr.h:106
bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS)
The parser has parsed a global nested-name-specifier &#39;::&#39;.
void setDeductionGuideName(ParsedTemplateTy Template, SourceLocation TemplateLoc)
Specify that this unqualified-id was parsed as a template-name for a deduction-guide.
Definition: DeclSpec.h:1112
static DeclaratorChunk getFunction(bool HasProto, bool IsAmbiguous, SourceLocation LParenLoc, ParamInfo *Params, unsigned NumParams, SourceLocation EllipsisLoc, SourceLocation RParenLoc, unsigned TypeQuals, bool RefQualifierIsLvalueRef, SourceLocation RefQualifierLoc, SourceLocation ConstQualifierLoc, SourceLocation VolatileQualifierLoc, SourceLocation RestrictQualifierLoc, 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())
DeclaratorChunk::getFunction - Return a DeclaratorChunk for a function.
Definition: DeclSpec.cpp:152
int Id
Definition: ASTDiff.cpp:191
void AnnotateCachedTokens(const Token &Tok)
We notify the Preprocessor that if it is caching tokens (because backtrack is enabled) it should repl...
const FunctionProtoType * T
ParsedType getDestructorTypeForDecltype(const DeclSpec &DS, ParsedType ObjectType)
This file defines the classes used to store parsed information about declaration-specifiers and decla...
bool ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext, bool AllowDestructorName, bool AllowConstructorName, bool AllowDeductionGuide, ParsedType ObjectType, SourceLocation *TemplateKWLoc, UnqualifiedId &Result)
Parse a C++ unqualified-id (or a C identifier), which describes the name of an entity.
TypeResult ActOnTypeName(Scope *S, Declarator &D)
Definition: SemaType.cpp:5714
OpaquePtr< T > get() const
Definition: Ownership.h:105
void setEofData(const void *D)
Definition: Token.h:194
void RevertCachedTokens(unsigned N)
When backtracking is enabled and tokens are cached, this allows to revert a specific number of tokens...
ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, CXXScopeSpec &SS, UnqualifiedId &FirstTypeName, SourceLocation CCLoc, SourceLocation TildeLoc, UnqualifiedId &SecondTypeName)
const Token & getCurToken() const
Definition: Parser.h:280
OpaquePtr< TemplateName > TemplateTy
Definition: Parser.h:291
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file. ...
Definition: Token.h:124
void setAsmLabel(Expr *E)
Definition: DeclSpec.h:2423
SourceLocation getBeginLoc() const
Definition: DeclSpec.h:72
Represents a C++ template name within the type system.
Definition: TemplateName.h:178
This is a compound statement scope.
Definition: Scope.h:130
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition: DeclSpec.h:1002
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7)...
TemplateNameKind
Specifies the kind of template name that an identifier refers to.
Definition: TemplateKinds.h:21
ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc, ArrayRef< ParsedType > Args, SourceLocation RParenLoc)
Parsed one of the type trait support pseudo-functions.
void setLiteralOperatorId(const IdentifierInfo *Id, SourceLocation OpLoc, SourceLocation IdLoc)
Specific that this unqualified-id was parsed as a literal-operator-id.
Definition: DeclSpec.h:1053
static const TST TST_int
Definition: DeclSpec.h:279
StmtResult ActOnNullStmt(SourceLocation SemiLoc, bool HasLeadingEmptyMacro=false)
Definition: SemaStmt.cpp:68
ConditionKind
Definition: Sema.h:9820
bool isInvalid() const
Definition: Ownership.h:170
SourceLocation getEnd() const
bool SetTypeSpecSign(TSS S, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID)
Definition: DeclSpec.cpp:661
SourceLocation getOpenLocation() const
static const TST TST_half
Definition: DeclSpec.h:281
ExprResult ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal, bool ArrayForm, Expr *Operand)
ActOnCXXDelete - Parsed a C++ &#39;delete&#39; expression.
bool isUsable() const
Definition: Ownership.h:171
sema::LambdaScopeInfo * PushLambdaScope()
Definition: Sema.cpp:1387
The result type of a method or function.
static const TSW TSW_short
Definition: DeclSpec.h:254
StringRef GetString() const
ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg, SourceLocation EllipsisLoc)
Invoked when parsing a template argument followed by an ellipsis, which creates a pack expansion...
const SourceManager & SM
Definition: Format.cpp:1468
bool isValid() const
Determine whether this unqualified-id refers to a valid name.
Definition: DeclSpec.h:996
OpaquePtr< DeclGroupRef > DeclGroupPtrTy
Definition: Parser.h:290
const LangOptions & getLangOpts() const
Definition: Parser.h:274
bool SetTypeSpecWidth(TSW 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:634
This is a scope that corresponds to the parameters within a function prototype for a function declara...
Definition: Scope.h:87
ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E)
Definition: SemaExpr.cpp:3501
SourceManager & getSourceManager() const
Definition: Preprocessor.h:819
static const TST TST_char32
Definition: DeclSpec.h:278
unsigned getUDSuffixOffset() const
Get the spelling offset of the first byte of the ud-suffix.
SourceLocation DefaultLoc
Definition: DeclSpec.h:2561
Kind
Stop skipping at semicolon.
Definition: Parser.h:928
ActionResult - This structure is used while parsing/acting on expressions, stmts, etc...
Definition: Ownership.h:157
unsigned getUDSuffixToken() const
Get the index of a token containing a ud-suffix.
ASTContext & getASTContext() const
Definition: Sema.h:1200
static const TST TST_float16
Definition: DeclSpec.h:284
Encodes a location in the source.
void addCapture(LambdaCaptureKind Kind, SourceLocation Loc, IdentifierInfo *Id, SourceLocation EllipsisLoc, LambdaCaptureInitKind InitKind, ExprResult Init, ParsedType InitCaptureType)
Append a capture in a lambda introducer.
Definition: DeclSpec.h:2569
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
void setLength(unsigned Len)
Definition: Token.h:133
static void addConstexprToLambdaDeclSpecifier(Parser &P, SourceLocation ConstexprLoc, DeclSpec &DS)
void FinalizeDeclaration(Decl *D)
FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform any semantic actions neces...
Definition: SemaDecl.cpp:11603
MutableArrayRef< Expr * > MultiExprArg
Definition: Ownership.h:277
bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name, SourceLocation NameLoc, ParsedTemplateTy *Template=nullptr)
Determine whether a particular identifier might be the name in a C++1z deduction-guide declaration...
IdentifierInfo * getIdentifierInfo() const
Definition: Token.h:177
void setAnnotationEndLoc(SourceLocation L)
Definition: Token.h:142
IdentifierTable & getIdentifierTable()
Definition: Preprocessor.h:823
static const TSS TSS_signed
Definition: DeclSpec.h:267
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}_cast&#39;s.
Definition: SemaCast.cpp:217
void CodeCompleteOperatorName(Scope *S)
void Lex(Token &Result)
Lex the next token for this preprocessor.
ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep, SourceLocation LParenOrBraceLoc, MultiExprArg Exprs, SourceLocation RParenOrBraceLoc, bool ListInitialization)
ActOnCXXTypeConstructExpr - Parse construction of a specified type.
const void * getEofData() const
Definition: Token.h:190
TemplateNameKind ActOnDependentTemplateName(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool AllowInjectedClassName=false)
Form a dependent template name.
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition: TokenKinds.h:25
Scope * getCurScope() const
Definition: Parser.h:281
static DeclaratorChunk getArray(unsigned TypeQuals, bool isStatic, bool isStar, Expr *NumElts, SourceLocation LBLoc, SourceLocation RBLoc)
Return a DeclaratorChunk for an array.
Definition: DeclSpec.h:1566
ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, SourceLocation PlacementLParen, MultiExprArg PlacementArgs, SourceLocation PlacementRParen, SourceRange TypeIdParens, Declarator &D, Expr *Initializer)
ActOnCXXNew - Parsed a C++ &#39;new&#39; expression.
static void FixDigraph(Parser &P, Preprocessor &PP, Token &DigraphToken, Token &ColonToken, tok::TokenKind Kind, bool AtDigraph)
StringRef getName() const
Return the actual identifier string.
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition: DeclSpec.h:1888
bool isNot(tok::TokenKind K) const
Definition: Token.h:96
static const TST TST_decltype_auto
Definition: DeclSpec.h:301
The name does not refer to a template.
Definition: TemplateKinds.h:23
Dataflow Directional Tag Classes.
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...
bool isValid() const
Return true if this is a valid SourceLocation object.
LambdaCaptureDefault Default
Definition: DeclSpec.h:2562
bool expectAndConsume(unsigned DiagID=diag::err_expected, const char *Msg="", tok::TokenKind SkipToTok=tok::unknown)
Definition: Parser.cpp:2243
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:22
static const TST TST_void
Definition: DeclSpec.h:273
CXXScopeSpec SS
The nested-name-specifier that precedes the template name.
SourceLocation RAngleLoc
The location of the &#39;>&#39; after the template argument list.
static const TST TST_int128
Definition: DeclSpec.h:280
void RecordParsingTemplateParameterDepth(unsigned Depth)
This is used to inform Sema what the current TemplateParameterDepth is during Parsing.
Definition: Sema.cpp:1393
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:118
bool isOneOf(tok::TokenKind K1, tok::TokenKind K2) const
Definition: Token.h:97
SourceLocation getLocEnd() const LLVM_READONLY
Definition: DeclSpec.h:509
SourceLocation getLastCachedTokenLocation() const
Get the location of the last cached token, suitable for setting the end location of an annotation tok...
bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc, SourceLocation ColonColonLoc, CXXScopeSpec &SS)
The parser has parsed a &#39;__super&#39; nested-name-specifier.
unsigned getLength() const
Definition: Token.h:127
void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit)
AddInitializerToDecl - Adds the initializer Init to the declaration dcl.
Definition: SemaDecl.cpp:10597
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...
Not an overloaded operator.
Definition: OperatorKinds.h:23
void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro, Declarator &ParamInfo, Scope *CurScope)
ActOnStartOfLambdaDefinition - This is called just before we start parsing the body of a lambda; it a...
Definition: SemaLambda.cpp:825
QualType getCanonicalTypeInternal() const
Definition: Type.h:2198
void takeAttributesFrom(ParsedAttributes &attrs)
Definition: DeclSpec.h:751
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Definition: Parser.cpp:72
static void tryConsumeMutableOrConstexprToken(Parser &P, SourceLocation &MutableLoc, SourceLocation &ConstexprLoc, SourceLocation &DeclEndLoc)
void RestoreNestedNameSpecifierAnnotation(void *Annotation, SourceRange AnnotationRange, CXXScopeSpec &SS)
Given an annotation pointer for a nested-name-specifier, restore the nested-name-specifier structure...
const char * getOperatorSpelling(OverloadedOperatorKind Operator)
Retrieve the spelling of the given overloaded operator, without the preceding "operator" keyword...
ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind)
ActOnCXXBoolLiteral - Parse {true,false} literals.
void setOperatorFunctionId(SourceLocation OperatorLoc, OverloadedOperatorKind Op, SourceLocation SymbolLocations[3])
Specify that this unqualified-id was parsed as an operator-function-id.
Definition: DeclSpec.cpp:1312
static const TST TST_typename
Definition: DeclSpec.h:297
void SetRangeEnd(SourceLocation Loc)
SetRangeEnd - Set the end of the source range to Loc, unless it&#39;s invalid.
Definition: DeclSpec.h:1900
ExprResult ParseAssignmentExpression(TypeCastState isTypeCast=NotTypeCast)
Parse an expr that doesn&#39;t include (top-level) commas.
Definition: ParseExpr.cpp:160
ExprResult ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc, bool isType, void *TyOrExpr, SourceLocation RParenLoc)
ActOnCXXTypeid - Parse typeid( something ).
ExceptionSpecificationType
The various types of exception specifications that exist in C++11.
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:92
ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E)
Capturing the *this object by reference.
Definition: Lambda.h:35
const Expr * Replacement
Definition: AttributeList.h:66
This is a scope that can contain a declaration.
Definition: Scope.h:59
bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
Definition: DeclSpec.cpp:750
ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand, std::unique_ptr< CorrectionCandidateCallback > CCC=nullptr, bool IsInlineAsmIdentifier=false, Token *KeywordReplacement=nullptr)
Definition: SemaExpr.cpp:2023
bool isSet() const
Deprecated.
Definition: DeclSpec.h:209
ExprResult ParseConstantExpression(TypeCastState isTypeCast=NotTypeCast)
Definition: ParseExpr.cpp:210
void setInvalidType(bool Val=true)
Definition: DeclSpec.h:2435
An integral condition for a &#39;switch&#39; statement.
TypeResult ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy Template, IdentifierInfo *TemplateII, SourceLocation TemplateIILoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, bool IsCtorOrDtorName=false, bool IsClassName=false)
Captures information about "declaration specifiers".
Definition: DeclSpec.h:228
void setEnd(SourceLocation e)
SourceLocation ConsumeToken()
ConsumeToken - Consume the current &#39;peek token&#39; and lex the next one.
Definition: Parser.h:319
static ExpressionTrait ExpressionTraitFromTokKind(tok::TokenKind kind)
static int SelectDigraphErrorMessage(tok::TokenKind Kind)
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition: DeclSpec.h:191
Capturing by reference.
Definition: Lambda.h:38
static const TST TST_float128
Definition: DeclSpec.h:287
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition: DeclSpec.h:1853
static const TST TST_bool
Definition: DeclSpec.h:288
StringLiteralParser - This decodes string escape characters and performs wide string analysis and Tra...
unsigned kind
All of the diagnostics that can be emitted by the frontend.
Definition: DiagnosticIDs.h:61
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:129
void Finish(Sema &S, const PrintingPolicy &Policy)
Finish - This does final analysis of the declspec, issuing diagnostics for things like "_Imaginary" (...
Definition: DeclSpec.cpp:1013
Represents a complete lambda introducer.
Definition: DeclSpec.h:2542
ExprResult ExprError()
Definition: Ownership.h:283
static const TSW TSW_longlong
Definition: DeclSpec.h:256
Code completion occurs within the condition of an if, while, switch, or for statement.
Definition: Sema.h:10219
static unsigned TypeTraitArity(tok::TokenKind kind)
void setLocation(SourceLocation L)
Definition: Token.h:132
A trivial tuple used to represent a source range.
void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Specify that this unqualified-id was parsed as an identifier.
Definition: DeclSpec.h:1009
bool SetTypeSpecError()
Definition: DeclSpec.cpp:844
unsigned NumArgs
NumArgs - The number of template arguments.
void * getAnnotationValue() const
Definition: Token.h:224
void setDestructorName(SourceLocation TildeLoc, ParsedType ClassType, SourceLocation EndLoc)
Specify that this unqualified-id was parsed as a destructor name.
Definition: DeclSpec.h:1091
SourceLocation getLocEnd() const LLVM_READONLY
Definition: DeclSpec.h:1890
void SetRangeEnd(SourceLocation Loc)
Definition: DeclSpec.h:615
SourceLocation getLocStart() const LLVM_READONLY
Definition: Stmt.cpp:278
SourceLocation getBegin() const
ParsedAttributes - A collection of parsed attributes.
This class handles loading and caching of source files into memory.
TypeResult ParseTypeName(SourceRange *Range=nullptr, DeclaratorContext Context=DeclaratorContext::TypeNameContext, 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:44
static ArrayTypeTrait ArrayTypeTraitFromTokKind(tok::TokenKind kind)
Attr - This represents one attribute.
Definition: Attr.h:43
SourceLocation getLocation() const
Definition: DeclBase.h:417
void startToken()
Reset all flags to cleared.
Definition: Token.h:169
ParsedType actOnLambdaInitCaptureInitialization(SourceLocation Loc, bool ByRef, 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:5542
ParsedTemplateTy Template
The declaration of the template corresponding to the template-name.
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:127
Stop skipping at specified token, but don&#39;t skip the token itself.
Definition: Parser.h:930