clang  8.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  ExprResult E = Actions.ActOnIdExpression(
565  getCurScope(), SS, TemplateKWLoc, Name, Tok.is(tok::l_paren),
566  isAddressOfOperand, nullptr, /*IsInlineAsmIdentifier=*/false,
567  &Replacement);
568  if (!E.isInvalid() && !E.isUnset() && Tok.is(tok::less))
569  checkPotentialAngleBracket(E);
570  return E;
571 }
572 
573 /// ParseCXXIdExpression - Handle id-expression.
574 ///
575 /// id-expression:
576 /// unqualified-id
577 /// qualified-id
578 ///
579 /// qualified-id:
580 /// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
581 /// '::' identifier
582 /// '::' operator-function-id
583 /// '::' template-id
584 ///
585 /// NOTE: The standard specifies that, for qualified-id, the parser does not
586 /// expect:
587 ///
588 /// '::' conversion-function-id
589 /// '::' '~' class-name
590 ///
591 /// This may cause a slight inconsistency on diagnostics:
592 ///
593 /// class C {};
594 /// namespace A {}
595 /// void f() {
596 /// :: A :: ~ C(); // Some Sema error about using destructor with a
597 /// // namespace.
598 /// :: ~ C(); // Some Parser error like 'unexpected ~'.
599 /// }
600 ///
601 /// We simplify the parser a bit and make it work like:
602 ///
603 /// qualified-id:
604 /// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
605 /// '::' unqualified-id
606 ///
607 /// That way Sema can handle and report similar errors for namespaces and the
608 /// global scope.
609 ///
610 /// The isAddressOfOperand parameter indicates that this id-expression is a
611 /// direct operand of the address-of operator. This is, besides member contexts,
612 /// the only place where a qualified-id naming a non-static class member may
613 /// appear.
614 ///
615 ExprResult Parser::ParseCXXIdExpression(bool isAddressOfOperand) {
616  // qualified-id:
617  // '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
618  // '::' unqualified-id
619  //
620  CXXScopeSpec SS;
621  ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false);
622 
623  Token Replacement;
625  tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
626  if (Result.isUnset()) {
627  // If the ExprResult is valid but null, then typo correction suggested a
628  // keyword replacement that needs to be reparsed.
629  UnconsumeToken(Replacement);
630  Result = tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
631  }
632  assert(!Result.isUnset() && "Typo correction suggested a keyword replacement "
633  "for a previous keyword suggestion");
634  return Result;
635 }
636 
637 /// ParseLambdaExpression - Parse a C++11 lambda expression.
638 ///
639 /// lambda-expression:
640 /// lambda-introducer lambda-declarator[opt] compound-statement
641 ///
642 /// lambda-introducer:
643 /// '[' lambda-capture[opt] ']'
644 ///
645 /// lambda-capture:
646 /// capture-default
647 /// capture-list
648 /// capture-default ',' capture-list
649 ///
650 /// capture-default:
651 /// '&'
652 /// '='
653 ///
654 /// capture-list:
655 /// capture
656 /// capture-list ',' capture
657 ///
658 /// capture:
659 /// simple-capture
660 /// init-capture [C++1y]
661 ///
662 /// simple-capture:
663 /// identifier
664 /// '&' identifier
665 /// 'this'
666 ///
667 /// init-capture: [C++1y]
668 /// identifier initializer
669 /// '&' identifier initializer
670 ///
671 /// lambda-declarator:
672 /// '(' parameter-declaration-clause ')' attribute-specifier[opt]
673 /// 'mutable'[opt] exception-specification[opt]
674 /// trailing-return-type[opt]
675 ///
676 ExprResult Parser::ParseLambdaExpression() {
677  // Parse lambda-introducer.
678  LambdaIntroducer Intro;
679  Optional<unsigned> DiagID = ParseLambdaIntroducer(Intro);
680  if (DiagID) {
681  Diag(Tok, DiagID.getValue());
682  SkipUntil(tok::r_square, StopAtSemi);
683  SkipUntil(tok::l_brace, StopAtSemi);
684  SkipUntil(tok::r_brace, StopAtSemi);
685  return ExprError();
686  }
687 
688  return ParseLambdaExpressionAfterIntroducer(Intro);
689 }
690 
691 /// TryParseLambdaExpression - Use lookahead and potentially tentative
692 /// parsing to determine if we are looking at a C++0x lambda expression, and parse
693 /// it if we are.
694 ///
695 /// If we are not looking at a lambda expression, returns ExprError().
696 ExprResult Parser::TryParseLambdaExpression() {
697  assert(getLangOpts().CPlusPlus11
698  && Tok.is(tok::l_square)
699  && "Not at the start of a possible lambda expression.");
700 
701  const Token Next = NextToken();
702  if (Next.is(tok::eof)) // Nothing else to lookup here...
703  return ExprEmpty();
704 
705  const Token After = GetLookAheadToken(2);
706  // If lookahead indicates this is a lambda...
707  if (Next.is(tok::r_square) || // []
708  Next.is(tok::equal) || // [=
709  (Next.is(tok::amp) && // [&] or [&,
710  (After.is(tok::r_square) ||
711  After.is(tok::comma))) ||
712  (Next.is(tok::identifier) && // [identifier]
713  After.is(tok::r_square))) {
714  return ParseLambdaExpression();
715  }
716 
717  // If lookahead indicates an ObjC message send...
718  // [identifier identifier
719  if (Next.is(tok::identifier) && After.is(tok::identifier)) {
720  return ExprEmpty();
721  }
722 
723  // Here, we're stuck: lambda introducers and Objective-C message sends are
724  // unambiguous, but it requires arbitrary lookhead. [a,b,c,d,e,f,g] is a
725  // lambda, and [a,b,c,d,e,f,g h] is a Objective-C message send. Instead of
726  // writing two routines to parse a lambda introducer, just try to parse
727  // a lambda introducer first, and fall back if that fails.
728  // (TryParseLambdaIntroducer never produces any diagnostic output.)
729  LambdaIntroducer Intro;
730  if (TryParseLambdaIntroducer(Intro))
731  return ExprEmpty();
732 
733  return ParseLambdaExpressionAfterIntroducer(Intro);
734 }
735 
736 /// Parse a lambda introducer.
737 /// \param Intro A LambdaIntroducer filled in with information about the
738 /// contents of the lambda-introducer.
739 /// \param SkippedInits If non-null, we are disambiguating between an Obj-C
740 /// message send and a lambda expression. In this mode, we will
741 /// sometimes skip the initializers for init-captures and not fully
742 /// populate \p Intro. This flag will be set to \c true if we do so.
743 /// \return A DiagnosticID if it hit something unexpected. The location for
744 /// the diagnostic is that of the current token.
745 Optional<unsigned> Parser::ParseLambdaIntroducer(LambdaIntroducer &Intro,
746  bool *SkippedInits) {
747  typedef Optional<unsigned> DiagResult;
748 
749  assert(Tok.is(tok::l_square) && "Lambda expressions begin with '['.");
750  BalancedDelimiterTracker T(*this, tok::l_square);
751  T.consumeOpen();
752 
753  Intro.Range.setBegin(T.getOpenLocation());
754 
755  bool first = true;
756 
757  // Parse capture-default.
758  if (Tok.is(tok::amp) &&
759  (NextToken().is(tok::comma) || NextToken().is(tok::r_square))) {
760  Intro.Default = LCD_ByRef;
761  Intro.DefaultLoc = ConsumeToken();
762  first = false;
763  } else if (Tok.is(tok::equal)) {
764  Intro.Default = LCD_ByCopy;
765  Intro.DefaultLoc = ConsumeToken();
766  first = false;
767  }
768 
769  while (Tok.isNot(tok::r_square)) {
770  if (!first) {
771  if (Tok.isNot(tok::comma)) {
772  // Provide a completion for a lambda introducer here. Except
773  // in Objective-C, where this is Almost Surely meant to be a message
774  // send. In that case, fail here and let the ObjC message
775  // expression parser perform the completion.
776  if (Tok.is(tok::code_completion) &&
777  !(getLangOpts().ObjC1 && Intro.Default == LCD_None &&
778  !Intro.Captures.empty())) {
779  Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
780  /*AfterAmpersand=*/false);
781  cutOffParsing();
782  break;
783  }
784 
785  return DiagResult(diag::err_expected_comma_or_rsquare);
786  }
787  ConsumeToken();
788  }
789 
790  if (Tok.is(tok::code_completion)) {
791  // If we're in Objective-C++ and we have a bare '[', then this is more
792  // likely to be a message receiver.
793  if (getLangOpts().ObjC1 && first)
795  else
796  Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
797  /*AfterAmpersand=*/false);
798  cutOffParsing();
799  break;
800  }
801 
802  first = false;
803 
804  // Parse capture.
807  SourceLocation Loc;
808  IdentifierInfo *Id = nullptr;
809  SourceLocation EllipsisLoc;
810  ExprResult Init;
811  SourceLocation LocStart = Tok.getLocation();
812 
813  if (Tok.is(tok::star)) {
814  Loc = ConsumeToken();
815  if (Tok.is(tok::kw_this)) {
816  ConsumeToken();
817  Kind = LCK_StarThis;
818  } else {
819  return DiagResult(diag::err_expected_star_this_capture);
820  }
821  } else if (Tok.is(tok::kw_this)) {
822  Kind = LCK_This;
823  Loc = ConsumeToken();
824  } else {
825  if (Tok.is(tok::amp)) {
826  Kind = LCK_ByRef;
827  ConsumeToken();
828 
829  if (Tok.is(tok::code_completion)) {
830  Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
831  /*AfterAmpersand=*/true);
832  cutOffParsing();
833  break;
834  }
835  }
836 
837  if (Tok.is(tok::identifier)) {
838  Id = Tok.getIdentifierInfo();
839  Loc = ConsumeToken();
840  } else if (Tok.is(tok::kw_this)) {
841  // FIXME: If we want to suggest a fixit here, will need to return more
842  // than just DiagnosticID. Perhaps full DiagnosticBuilder that can be
843  // Clear()ed to prevent emission in case of tentative parsing?
844  return DiagResult(diag::err_this_captured_by_reference);
845  } else {
846  return DiagResult(diag::err_expected_capture);
847  }
848 
849  if (Tok.is(tok::l_paren)) {
850  BalancedDelimiterTracker Parens(*this, tok::l_paren);
851  Parens.consumeOpen();
852 
854 
855  ExprVector Exprs;
856  CommaLocsTy Commas;
857  if (SkippedInits) {
858  Parens.skipToEnd();
859  *SkippedInits = true;
860  } else if (ParseExpressionList(Exprs, Commas)) {
861  Parens.skipToEnd();
862  Init = ExprError();
863  } else {
864  Parens.consumeClose();
865  Init = Actions.ActOnParenListExpr(Parens.getOpenLocation(),
866  Parens.getCloseLocation(),
867  Exprs);
868  }
869  } else if (Tok.isOneOf(tok::l_brace, tok::equal)) {
870  // Each lambda init-capture forms its own full expression, which clears
871  // Actions.MaybeODRUseExprs. So create an expression evaluation context
872  // to save the necessary state, and restore it later.
875 
876  if (TryConsumeToken(tok::equal))
878  else
880 
881  if (!SkippedInits) {
882  Init = ParseInitializer();
883  } else if (Tok.is(tok::l_brace)) {
884  BalancedDelimiterTracker Braces(*this, tok::l_brace);
885  Braces.consumeOpen();
886  Braces.skipToEnd();
887  *SkippedInits = true;
888  } else {
889  // We're disambiguating this:
890  //
891  // [..., x = expr
892  //
893  // We need to find the end of the following expression in order to
894  // determine whether this is an Obj-C message send's receiver, a
895  // C99 designator, or a lambda init-capture.
896  //
897  // Parse the expression to find where it ends, and annotate it back
898  // onto the tokens. We would have parsed this expression the same way
899  // in either case: both the RHS of an init-capture and the RHS of an
900  // assignment expression are parsed as an initializer-clause, and in
901  // neither case can anything be added to the scope between the '[' and
902  // here.
903  //
904  // FIXME: This is horrible. Adding a mechanism to skip an expression
905  // would be much cleaner.
906  // FIXME: If there is a ',' before the next ']' or ':', we can skip to
907  // that instead. (And if we see a ':' with no matching '?', we can
908  // classify this as an Obj-C message send.)
909  SourceLocation StartLoc = Tok.getLocation();
910  InMessageExpressionRAIIObject MaybeInMessageExpression(*this, true);
911  Init = ParseInitializer();
912  if (!Init.isInvalid())
913  Init = Actions.CorrectDelayedTyposInExpr(Init.get());
914 
915  if (Tok.getLocation() != StartLoc) {
916  // Back out the lexing of the token after the initializer.
917  PP.RevertCachedTokens(1);
918 
919  // Replace the consumed tokens with an appropriate annotation.
920  Tok.setLocation(StartLoc);
921  Tok.setKind(tok::annot_primary_expr);
922  setExprAnnotation(Tok, Init);
924  PP.AnnotateCachedTokens(Tok);
925 
926  // Consume the annotated initializer.
927  ConsumeAnnotationToken();
928  }
929  }
930  } else
931  TryConsumeToken(tok::ellipsis, EllipsisLoc);
932  }
933  // If this is an init capture, process the initialization expression
934  // right away. For lambda init-captures such as the following:
935  // const int x = 10;
936  // auto L = [i = x+1](int a) {
937  // return [j = x+2,
938  // &k = x](char b) { };
939  // };
940  // keep in mind that each lambda init-capture has to have:
941  // - its initialization expression executed in the context
942  // of the enclosing/parent decl-context.
943  // - but the variable itself has to be 'injected' into the
944  // decl-context of its lambda's call-operator (which has
945  // not yet been created).
946  // Each init-expression is a full-expression that has to get
947  // Sema-analyzed (for capturing etc.) before its lambda's
948  // call-operator's decl-context, scope & scopeinfo are pushed on their
949  // respective stacks. Thus if any variable is odr-used in the init-capture
950  // it will correctly get captured in the enclosing lambda, if one exists.
951  // The init-variables above are created later once the lambdascope and
952  // call-operators decl-context is pushed onto its respective stack.
953 
954  // Since the lambda init-capture's initializer expression occurs in the
955  // context of the enclosing function or lambda, therefore we can not wait
956  // till a lambda scope has been pushed on before deciding whether the
957  // variable needs to be captured. We also need to process all
958  // lvalue-to-rvalue conversions and discarded-value conversions,
959  // so that we can avoid capturing certain constant variables.
960  // For e.g.,
961  // void test() {
962  // const int x = 10;
963  // auto L = [&z = x](char a) { <-- don't capture by the current lambda
964  // return [y = x](int i) { <-- don't capture by enclosing lambda
965  // return y;
966  // }
967  // };
968  // }
969  // If x was not const, the second use would require 'L' to capture, and
970  // that would be an error.
971 
972  ParsedType InitCaptureType;
973  if (!Init.isInvalid())
974  Init = Actions.CorrectDelayedTyposInExpr(Init.get());
975  if (Init.isUsable()) {
976  // Get the pointer and store it in an lvalue, so we can use it as an
977  // out argument.
978  Expr *InitExpr = Init.get();
979  // This performs any lvalue-to-rvalue conversions if necessary, which
980  // can affect what gets captured in the containing decl-context.
981  InitCaptureType = Actions.actOnLambdaInitCaptureInitialization(
982  Loc, Kind == LCK_ByRef, Id, InitKind, InitExpr);
983  Init = InitExpr;
984  }
985 
986  SourceLocation LocEnd = PrevTokLocation;
987 
988  Intro.addCapture(Kind, Loc, Id, EllipsisLoc, InitKind, Init,
989  InitCaptureType, SourceRange(LocStart, LocEnd));
990  }
991 
992  T.consumeClose();
993  Intro.Range.setEnd(T.getCloseLocation());
994  return DiagResult();
995 }
996 
997 /// TryParseLambdaIntroducer - Tentatively parse a lambda introducer.
998 ///
999 /// Returns true if it hit something unexpected.
1000 bool Parser::TryParseLambdaIntroducer(LambdaIntroducer &Intro) {
1001  {
1002  bool SkippedInits = false;
1003  TentativeParsingAction PA1(*this);
1004 
1005  if (ParseLambdaIntroducer(Intro, &SkippedInits)) {
1006  PA1.Revert();
1007  return true;
1008  }
1009 
1010  if (!SkippedInits) {
1011  PA1.Commit();
1012  return false;
1013  }
1014 
1015  PA1.Revert();
1016  }
1017 
1018  // Try to parse it again, but this time parse the init-captures too.
1019  Intro = LambdaIntroducer();
1020  TentativeParsingAction PA2(*this);
1021 
1022  if (!ParseLambdaIntroducer(Intro)) {
1023  PA2.Commit();
1024  return false;
1025  }
1026 
1027  PA2.Revert();
1028  return true;
1029 }
1030 
1031 static void
1033  SourceLocation &ConstexprLoc,
1034  SourceLocation &DeclEndLoc) {
1035  assert(MutableLoc.isInvalid());
1036  assert(ConstexprLoc.isInvalid());
1037  // Consume constexpr-opt mutable-opt in any sequence, and set the DeclEndLoc
1038  // to the final of those locations. Emit an error if we have multiple
1039  // copies of those keywords and recover.
1040 
1041  while (true) {
1042  switch (P.getCurToken().getKind()) {
1043  case tok::kw_mutable: {
1044  if (MutableLoc.isValid()) {
1045  P.Diag(P.getCurToken().getLocation(),
1046  diag::err_lambda_decl_specifier_repeated)
1048  }
1049  MutableLoc = P.ConsumeToken();
1050  DeclEndLoc = MutableLoc;
1051  break /*switch*/;
1052  }
1053  case tok::kw_constexpr:
1054  if (ConstexprLoc.isValid()) {
1055  P.Diag(P.getCurToken().getLocation(),
1056  diag::err_lambda_decl_specifier_repeated)
1058  }
1059  ConstexprLoc = P.ConsumeToken();
1060  DeclEndLoc = ConstexprLoc;
1061  break /*switch*/;
1062  default:
1063  return;
1064  }
1065  }
1066 }
1067 
1068 static void
1070  DeclSpec &DS) {
1071  if (ConstexprLoc.isValid()) {
1072  P.Diag(ConstexprLoc, !P.getLangOpts().CPlusPlus17
1073  ? diag::ext_constexpr_on_lambda_cxx17
1074  : diag::warn_cxx14_compat_constexpr_on_lambda);
1075  const char *PrevSpec = nullptr;
1076  unsigned DiagID = 0;
1077  DS.SetConstexprSpec(ConstexprLoc, PrevSpec, DiagID);
1078  assert(PrevSpec == nullptr && DiagID == 0 &&
1079  "Constexpr cannot have been set previously!");
1080  }
1081 }
1082 
1083 /// ParseLambdaExpressionAfterIntroducer - Parse the rest of a lambda
1084 /// expression.
1085 ExprResult Parser::ParseLambdaExpressionAfterIntroducer(
1086  LambdaIntroducer &Intro) {
1087  SourceLocation LambdaBeginLoc = Intro.Range.getBegin();
1088  Diag(LambdaBeginLoc, diag::warn_cxx98_compat_lambda);
1089 
1090  PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), LambdaBeginLoc,
1091  "lambda expression parsing");
1092 
1093 
1094 
1095  // FIXME: Call into Actions to add any init-capture declarations to the
1096  // scope while parsing the lambda-declarator and compound-statement.
1097 
1098  // Parse lambda-declarator[opt].
1099  DeclSpec DS(AttrFactory);
1101  TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1102  Actions.PushLambdaScope();
1103 
1104  ParsedAttributes Attr(AttrFactory);
1105  SourceLocation DeclLoc = Tok.getLocation();
1106  if (getLangOpts().CUDA) {
1107  // In CUDA code, GNU attributes are allowed to appear immediately after the
1108  // "[...]", even if there is no "(...)" before the lambda body.
1109  MaybeParseGNUAttributes(D);
1110  }
1111 
1112  // Helper to emit a warning if we see a CUDA host/device/global attribute
1113  // after '(...)'. nvcc doesn't accept this.
1114  auto WarnIfHasCUDATargetAttr = [&] {
1115  if (getLangOpts().CUDA)
1116  for (const ParsedAttr &A : Attr)
1117  if (A.getKind() == ParsedAttr::AT_CUDADevice ||
1118  A.getKind() == ParsedAttr::AT_CUDAHost ||
1119  A.getKind() == ParsedAttr::AT_CUDAGlobal)
1120  Diag(A.getLoc(), diag::warn_cuda_attr_lambda_position)
1121  << A.getName()->getName();
1122  };
1123 
1124  TypeResult TrailingReturnType;
1125  if (Tok.is(tok::l_paren)) {
1126  ParseScope PrototypeScope(this,
1130 
1131  BalancedDelimiterTracker T(*this, tok::l_paren);
1132  T.consumeOpen();
1133  SourceLocation LParenLoc = T.getOpenLocation();
1134 
1135  // Parse parameter-declaration-clause.
1137  SourceLocation EllipsisLoc;
1138 
1139  if (Tok.isNot(tok::r_paren)) {
1140  Actions.RecordParsingTemplateParameterDepth(TemplateParameterDepth);
1141  ParseParameterDeclarationClause(D, Attr, ParamInfo, EllipsisLoc);
1142  // For a generic lambda, each 'auto' within the parameter declaration
1143  // clause creates a template type parameter, so increment the depth.
1144  if (Actions.getCurGenericLambda())
1145  ++CurTemplateDepthTracker;
1146  }
1147  T.consumeClose();
1148  SourceLocation RParenLoc = T.getCloseLocation();
1149  SourceLocation DeclEndLoc = RParenLoc;
1150 
1151  // GNU-style attributes must be parsed before the mutable specifier to be
1152  // compatible with GCC.
1153  MaybeParseGNUAttributes(Attr, &DeclEndLoc);
1154 
1155  // MSVC-style attributes must be parsed before the mutable specifier to be
1156  // compatible with MSVC.
1157  MaybeParseMicrosoftDeclSpecs(Attr, &DeclEndLoc);
1158 
1159  // Parse mutable-opt and/or constexpr-opt, and update the DeclEndLoc.
1160  SourceLocation MutableLoc;
1161  SourceLocation ConstexprLoc;
1162  tryConsumeMutableOrConstexprToken(*this, MutableLoc, ConstexprLoc,
1163  DeclEndLoc);
1164 
1165  addConstexprToLambdaDeclSpecifier(*this, ConstexprLoc, DS);
1166 
1167  // Parse exception-specification[opt].
1169  SourceRange ESpecRange;
1170  SmallVector<ParsedType, 2> DynamicExceptions;
1171  SmallVector<SourceRange, 2> DynamicExceptionRanges;
1172  ExprResult NoexceptExpr;
1173  CachedTokens *ExceptionSpecTokens;
1174  ESpecType = tryParseExceptionSpecification(/*Delayed=*/false,
1175  ESpecRange,
1176  DynamicExceptions,
1177  DynamicExceptionRanges,
1178  NoexceptExpr,
1179  ExceptionSpecTokens);
1180 
1181  if (ESpecType != EST_None)
1182  DeclEndLoc = ESpecRange.getEnd();
1183 
1184  // Parse attribute-specifier[opt].
1185  MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
1186 
1187  SourceLocation FunLocalRangeEnd = DeclEndLoc;
1188 
1189  // Parse trailing-return-type[opt].
1190  if (Tok.is(tok::arrow)) {
1191  FunLocalRangeEnd = Tok.getLocation();
1192  SourceRange Range;
1193  TrailingReturnType =
1194  ParseTrailingReturnType(Range, /*MayBeFollowedByDirectInit*/ false);
1195  if (Range.getEnd().isValid())
1196  DeclEndLoc = Range.getEnd();
1197  }
1198 
1199  PrototypeScope.Exit();
1200 
1201  WarnIfHasCUDATargetAttr();
1202 
1203  SourceLocation NoLoc;
1205  /*hasProto=*/true,
1206  /*isAmbiguous=*/false, LParenLoc, ParamInfo.data(),
1207  ParamInfo.size(), EllipsisLoc, RParenLoc,
1208  DS.getTypeQualifiers(),
1209  /*RefQualifierIsLValueRef=*/true,
1210  /*RefQualifierLoc=*/NoLoc,
1211  /*ConstQualifierLoc=*/NoLoc,
1212  /*VolatileQualifierLoc=*/NoLoc,
1213  /*RestrictQualifierLoc=*/NoLoc, MutableLoc, ESpecType,
1214  ESpecRange, DynamicExceptions.data(),
1215  DynamicExceptionRanges.data(), DynamicExceptions.size(),
1216  NoexceptExpr.isUsable() ? NoexceptExpr.get() : nullptr,
1217  /*ExceptionSpecTokens*/ nullptr,
1218  /*DeclsInPrototype=*/None, LParenLoc, FunLocalRangeEnd, D,
1219  TrailingReturnType),
1220  std::move(Attr), DeclEndLoc);
1221  } else if (Tok.isOneOf(tok::kw_mutable, tok::arrow, tok::kw___attribute,
1222  tok::kw_constexpr) ||
1223  (Tok.is(tok::l_square) && NextToken().is(tok::l_square))) {
1224  // It's common to forget that one needs '()' before 'mutable', an attribute
1225  // specifier, or the result type. Deal with this.
1226  unsigned TokKind = 0;
1227  switch (Tok.getKind()) {
1228  case tok::kw_mutable: TokKind = 0; break;
1229  case tok::arrow: TokKind = 1; break;
1230  case tok::kw___attribute:
1231  case tok::l_square: TokKind = 2; break;
1232  case tok::kw_constexpr: TokKind = 3; break;
1233  default: llvm_unreachable("Unknown token kind");
1234  }
1235 
1236  Diag(Tok, diag::err_lambda_missing_parens)
1237  << TokKind
1238  << FixItHint::CreateInsertion(Tok.getLocation(), "() ");
1239  SourceLocation DeclEndLoc = DeclLoc;
1240 
1241  // GNU-style attributes must be parsed before the mutable specifier to be
1242  // compatible with GCC.
1243  MaybeParseGNUAttributes(Attr, &DeclEndLoc);
1244 
1245  // Parse 'mutable', if it's there.
1246  SourceLocation MutableLoc;
1247  if (Tok.is(tok::kw_mutable)) {
1248  MutableLoc = ConsumeToken();
1249  DeclEndLoc = MutableLoc;
1250  }
1251 
1252  // Parse attribute-specifier[opt].
1253  MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
1254 
1255  // Parse the return type, if there is one.
1256  if (Tok.is(tok::arrow)) {
1257  SourceRange Range;
1258  TrailingReturnType =
1259  ParseTrailingReturnType(Range, /*MayBeFollowedByDirectInit*/ false);
1260  if (Range.getEnd().isValid())
1261  DeclEndLoc = Range.getEnd();
1262  }
1263 
1264  WarnIfHasCUDATargetAttr();
1265 
1266  SourceLocation NoLoc;
1268  /*hasProto=*/true,
1269  /*isAmbiguous=*/false,
1270  /*LParenLoc=*/NoLoc,
1271  /*Params=*/nullptr,
1272  /*NumParams=*/0,
1273  /*EllipsisLoc=*/NoLoc,
1274  /*RParenLoc=*/NoLoc,
1275  /*TypeQuals=*/0,
1276  /*RefQualifierIsLValueRef=*/true,
1277  /*RefQualifierLoc=*/NoLoc,
1278  /*ConstQualifierLoc=*/NoLoc,
1279  /*VolatileQualifierLoc=*/NoLoc,
1280  /*RestrictQualifierLoc=*/NoLoc, MutableLoc, EST_None,
1281  /*ESpecRange=*/SourceRange(),
1282  /*Exceptions=*/nullptr,
1283  /*ExceptionRanges=*/nullptr,
1284  /*NumExceptions=*/0,
1285  /*NoexceptExpr=*/nullptr,
1286  /*ExceptionSpecTokens=*/nullptr,
1287  /*DeclsInPrototype=*/None, DeclLoc, DeclEndLoc, D,
1288  TrailingReturnType),
1289  std::move(Attr), DeclEndLoc);
1290  }
1291 
1292  // FIXME: Rename BlockScope -> ClosureScope if we decide to continue using
1293  // it.
1294  unsigned ScopeFlags = Scope::BlockScope | Scope::FnScope | Scope::DeclScope |
1296  ParseScope BodyScope(this, ScopeFlags);
1297 
1298  Actions.ActOnStartOfLambdaDefinition(Intro, D, getCurScope());
1299 
1300  // Parse compound-statement.
1301  if (!Tok.is(tok::l_brace)) {
1302  Diag(Tok, diag::err_expected_lambda_body);
1303  Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1304  return ExprError();
1305  }
1306 
1307  StmtResult Stmt(ParseCompoundStatementBody());
1308  BodyScope.Exit();
1309 
1310  if (!Stmt.isInvalid() && !TrailingReturnType.isInvalid())
1311  return Actions.ActOnLambdaExpr(LambdaBeginLoc, Stmt.get(), getCurScope());
1312 
1313  Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1314  return ExprError();
1315 }
1316 
1317 /// ParseCXXCasts - This handles the various ways to cast expressions to another
1318 /// type.
1319 ///
1320 /// postfix-expression: [C++ 5.2p1]
1321 /// 'dynamic_cast' '<' type-name '>' '(' expression ')'
1322 /// 'static_cast' '<' type-name '>' '(' expression ')'
1323 /// 'reinterpret_cast' '<' type-name '>' '(' expression ')'
1324 /// 'const_cast' '<' type-name '>' '(' expression ')'
1325 ///
1326 ExprResult Parser::ParseCXXCasts() {
1327  tok::TokenKind Kind = Tok.getKind();
1328  const char *CastName = nullptr; // For error messages
1329 
1330  switch (Kind) {
1331  default: llvm_unreachable("Unknown C++ cast!");
1332  case tok::kw_const_cast: CastName = "const_cast"; break;
1333  case tok::kw_dynamic_cast: CastName = "dynamic_cast"; break;
1334  case tok::kw_reinterpret_cast: CastName = "reinterpret_cast"; break;
1335  case tok::kw_static_cast: CastName = "static_cast"; break;
1336  }
1337 
1338  SourceLocation OpLoc = ConsumeToken();
1339  SourceLocation LAngleBracketLoc = Tok.getLocation();
1340 
1341  // Check for "<::" which is parsed as "[:". If found, fix token stream,
1342  // diagnose error, suggest fix, and recover parsing.
1343  if (Tok.is(tok::l_square) && Tok.getLength() == 2) {
1344  Token Next = NextToken();
1345  if (Next.is(tok::colon) && areTokensAdjacent(Tok, Next))
1346  FixDigraph(*this, PP, Tok, Next, Kind, /*AtDigraph*/true);
1347  }
1348 
1349  if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName))
1350  return ExprError();
1351 
1352  // Parse the common declaration-specifiers piece.
1353  DeclSpec DS(AttrFactory);
1354  ParseSpecifierQualifierList(DS);
1355 
1356  // Parse the abstract-declarator, if present.
1357  Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
1358  ParseDeclarator(DeclaratorInfo);
1359 
1360  SourceLocation RAngleBracketLoc = Tok.getLocation();
1361 
1362  if (ExpectAndConsume(tok::greater))
1363  return ExprError(Diag(LAngleBracketLoc, diag::note_matching) << tok::less);
1364 
1365  BalancedDelimiterTracker T(*this, tok::l_paren);
1366 
1367  if (T.expectAndConsume(diag::err_expected_lparen_after, CastName))
1368  return ExprError();
1369 
1371 
1372  // Match the ')'.
1373  T.consumeClose();
1374 
1375  if (!Result.isInvalid() && !DeclaratorInfo.isInvalidType())
1376  Result = Actions.ActOnCXXNamedCast(OpLoc, Kind,
1377  LAngleBracketLoc, DeclaratorInfo,
1378  RAngleBracketLoc,
1379  T.getOpenLocation(), Result.get(),
1380  T.getCloseLocation());
1381 
1382  return Result;
1383 }
1384 
1385 /// ParseCXXTypeid - This handles the C++ typeid expression.
1386 ///
1387 /// postfix-expression: [C++ 5.2p1]
1388 /// 'typeid' '(' expression ')'
1389 /// 'typeid' '(' type-id ')'
1390 ///
1391 ExprResult Parser::ParseCXXTypeid() {
1392  assert(Tok.is(tok::kw_typeid) && "Not 'typeid'!");
1393 
1394  SourceLocation OpLoc = ConsumeToken();
1395  SourceLocation LParenLoc, RParenLoc;
1396  BalancedDelimiterTracker T(*this, tok::l_paren);
1397 
1398  // typeid expressions are always parenthesized.
1399  if (T.expectAndConsume(diag::err_expected_lparen_after, "typeid"))
1400  return ExprError();
1401  LParenLoc = T.getOpenLocation();
1402 
1404 
1405  // C++0x [expr.typeid]p3:
1406  // When typeid is applied to an expression other than an lvalue of a
1407  // polymorphic class type [...] The expression is an unevaluated
1408  // operand (Clause 5).
1409  //
1410  // Note that we can't tell whether the expression is an lvalue of a
1411  // polymorphic class type until after we've parsed the expression; we
1412  // speculatively assume the subexpression is unevaluated, and fix it up
1413  // later.
1414  //
1415  // We enter the unevaluated context before trying to determine whether we
1416  // have a type-id, because the tentative parse logic will try to resolve
1417  // names, and must treat them as unevaluated.
1421 
1422  if (isTypeIdInParens()) {
1423  TypeResult Ty = ParseTypeName();
1424 
1425  // Match the ')'.
1426  T.consumeClose();
1427  RParenLoc = T.getCloseLocation();
1428  if (Ty.isInvalid() || RParenLoc.isInvalid())
1429  return ExprError();
1430 
1431  Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/true,
1432  Ty.get().getAsOpaquePtr(), RParenLoc);
1433  } else {
1434  Result = ParseExpression();
1435 
1436  // Match the ')'.
1437  if (Result.isInvalid())
1438  SkipUntil(tok::r_paren, StopAtSemi);
1439  else {
1440  T.consumeClose();
1441  RParenLoc = T.getCloseLocation();
1442  if (RParenLoc.isInvalid())
1443  return ExprError();
1444 
1445  Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/false,
1446  Result.get(), RParenLoc);
1447  }
1448  }
1449 
1450  return Result;
1451 }
1452 
1453 /// ParseCXXUuidof - This handles the Microsoft C++ __uuidof expression.
1454 ///
1455 /// '__uuidof' '(' expression ')'
1456 /// '__uuidof' '(' type-id ')'
1457 ///
1458 ExprResult Parser::ParseCXXUuidof() {
1459  assert(Tok.is(tok::kw___uuidof) && "Not '__uuidof'!");
1460 
1461  SourceLocation OpLoc = ConsumeToken();
1462  BalancedDelimiterTracker T(*this, tok::l_paren);
1463 
1464  // __uuidof expressions are always parenthesized.
1465  if (T.expectAndConsume(diag::err_expected_lparen_after, "__uuidof"))
1466  return ExprError();
1467 
1469 
1470  if (isTypeIdInParens()) {
1471  TypeResult Ty = ParseTypeName();
1472 
1473  // Match the ')'.
1474  T.consumeClose();
1475 
1476  if (Ty.isInvalid())
1477  return ExprError();
1478 
1479  Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(), /*isType=*/true,
1480  Ty.get().getAsOpaquePtr(),
1481  T.getCloseLocation());
1482  } else {
1485  Result = ParseExpression();
1486 
1487  // Match the ')'.
1488  if (Result.isInvalid())
1489  SkipUntil(tok::r_paren, StopAtSemi);
1490  else {
1491  T.consumeClose();
1492 
1493  Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(),
1494  /*isType=*/false,
1495  Result.get(), T.getCloseLocation());
1496  }
1497  }
1498 
1499  return Result;
1500 }
1501 
1502 /// Parse a C++ pseudo-destructor expression after the base,
1503 /// . or -> operator, and nested-name-specifier have already been
1504 /// parsed.
1505 ///
1506 /// postfix-expression: [C++ 5.2]
1507 /// postfix-expression . pseudo-destructor-name
1508 /// postfix-expression -> pseudo-destructor-name
1509 ///
1510 /// pseudo-destructor-name:
1511 /// ::[opt] nested-name-specifier[opt] type-name :: ~type-name
1512 /// ::[opt] nested-name-specifier template simple-template-id ::
1513 /// ~type-name
1514 /// ::[opt] nested-name-specifier[opt] ~type-name
1515 ///
1516 ExprResult
1517 Parser::ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc,
1518  tok::TokenKind OpKind,
1519  CXXScopeSpec &SS,
1520  ParsedType ObjectType) {
1521  // We're parsing either a pseudo-destructor-name or a dependent
1522  // member access that has the same form as a
1523  // pseudo-destructor-name. We parse both in the same way and let
1524  // the action model sort them out.
1525  //
1526  // Note that the ::[opt] nested-name-specifier[opt] has already
1527  // been parsed, and if there was a simple-template-id, it has
1528  // been coalesced into a template-id annotation token.
1529  UnqualifiedId FirstTypeName;
1530  SourceLocation CCLoc;
1531  if (Tok.is(tok::identifier)) {
1532  FirstTypeName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1533  ConsumeToken();
1534  assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1535  CCLoc = ConsumeToken();
1536  } else if (Tok.is(tok::annot_template_id)) {
1537  // FIXME: retrieve TemplateKWLoc from template-id annotation and
1538  // store it in the pseudo-dtor node (to be used when instantiating it).
1539  FirstTypeName.setTemplateId(
1541  ConsumeAnnotationToken();
1542  assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1543  CCLoc = ConsumeToken();
1544  } else {
1545  FirstTypeName.setIdentifier(nullptr, SourceLocation());
1546  }
1547 
1548  // Parse the tilde.
1549  assert(Tok.is(tok::tilde) && "ParseOptionalCXXScopeSpecifier fail");
1550  SourceLocation TildeLoc = ConsumeToken();
1551 
1552  if (Tok.is(tok::kw_decltype) && !FirstTypeName.isValid() && SS.isEmpty()) {
1553  DeclSpec DS(AttrFactory);
1554  ParseDecltypeSpecifier(DS);
1555  if (DS.getTypeSpecType() == TST_error)
1556  return ExprError();
1557  return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
1558  TildeLoc, DS);
1559  }
1560 
1561  if (!Tok.is(tok::identifier)) {
1562  Diag(Tok, diag::err_destructor_tilde_identifier);
1563  return ExprError();
1564  }
1565 
1566  // Parse the second type.
1567  UnqualifiedId SecondTypeName;
1568  IdentifierInfo *Name = Tok.getIdentifierInfo();
1569  SourceLocation NameLoc = ConsumeToken();
1570  SecondTypeName.setIdentifier(Name, NameLoc);
1571 
1572  // If there is a '<', the second type name is a template-id. Parse
1573  // it as such.
1574  if (Tok.is(tok::less) &&
1575  ParseUnqualifiedIdTemplateId(SS, SourceLocation(),
1576  Name, NameLoc,
1577  false, ObjectType, SecondTypeName,
1578  /*AssumeTemplateName=*/true))
1579  return ExprError();
1580 
1581  return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
1582  SS, FirstTypeName, CCLoc, TildeLoc,
1583  SecondTypeName);
1584 }
1585 
1586 /// ParseCXXBoolLiteral - This handles the C++ Boolean literals.
1587 ///
1588 /// boolean-literal: [C++ 2.13.5]
1589 /// 'true'
1590 /// 'false'
1591 ExprResult Parser::ParseCXXBoolLiteral() {
1592  tok::TokenKind Kind = Tok.getKind();
1593  return Actions.ActOnCXXBoolLiteral(ConsumeToken(), Kind);
1594 }
1595 
1596 /// ParseThrowExpression - This handles the C++ throw expression.
1597 ///
1598 /// throw-expression: [C++ 15]
1599 /// 'throw' assignment-expression[opt]
1600 ExprResult Parser::ParseThrowExpression() {
1601  assert(Tok.is(tok::kw_throw) && "Not throw!");
1602  SourceLocation ThrowLoc = ConsumeToken(); // Eat the throw token.
1603 
1604  // If the current token isn't the start of an assignment-expression,
1605  // then the expression is not present. This handles things like:
1606  // "C ? throw : (void)42", which is crazy but legal.
1607  switch (Tok.getKind()) { // FIXME: move this predicate somewhere common.
1608  case tok::semi:
1609  case tok::r_paren:
1610  case tok::r_square:
1611  case tok::r_brace:
1612  case tok::colon:
1613  case tok::comma:
1614  return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, nullptr);
1615 
1616  default:
1618  if (Expr.isInvalid()) return Expr;
1619  return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, Expr.get());
1620  }
1621 }
1622 
1623 /// Parse the C++ Coroutines co_yield expression.
1624 ///
1625 /// co_yield-expression:
1626 /// 'co_yield' assignment-expression[opt]
1627 ExprResult Parser::ParseCoyieldExpression() {
1628  assert(Tok.is(tok::kw_co_yield) && "Not co_yield!");
1629 
1630  SourceLocation Loc = ConsumeToken();
1631  ExprResult Expr = Tok.is(tok::l_brace) ? ParseBraceInitializer()
1633  if (!Expr.isInvalid())
1634  Expr = Actions.ActOnCoyieldExpr(getCurScope(), Loc, Expr.get());
1635  return Expr;
1636 }
1637 
1638 /// ParseCXXThis - This handles the C++ 'this' pointer.
1639 ///
1640 /// C++ 9.3.2: In the body of a non-static member function, the keyword this is
1641 /// a non-lvalue expression whose value is the address of the object for which
1642 /// the function is called.
1643 ExprResult Parser::ParseCXXThis() {
1644  assert(Tok.is(tok::kw_this) && "Not 'this'!");
1645  SourceLocation ThisLoc = ConsumeToken();
1646  return Actions.ActOnCXXThis(ThisLoc);
1647 }
1648 
1649 /// ParseCXXTypeConstructExpression - Parse construction of a specified type.
1650 /// Can be interpreted either as function-style casting ("int(x)")
1651 /// or class type construction ("ClassType(x,y,z)")
1652 /// or creation of a value-initialized type ("int()").
1653 /// See [C++ 5.2.3].
1654 ///
1655 /// postfix-expression: [C++ 5.2p1]
1656 /// simple-type-specifier '(' expression-list[opt] ')'
1657 /// [C++0x] simple-type-specifier braced-init-list
1658 /// typename-specifier '(' expression-list[opt] ')'
1659 /// [C++0x] typename-specifier braced-init-list
1660 ///
1661 /// In C++1z onwards, the type specifier can also be a template-name.
1662 ExprResult
1663 Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) {
1665  ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
1666 
1667  assert((Tok.is(tok::l_paren) ||
1668  (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)))
1669  && "Expected '(' or '{'!");
1670 
1671  if (Tok.is(tok::l_brace)) {
1672  ExprResult Init = ParseBraceInitializer();
1673  if (Init.isInvalid())
1674  return Init;
1675  Expr *InitList = Init.get();
1676  return Actions.ActOnCXXTypeConstructExpr(
1677  TypeRep, InitList->getBeginLoc(), MultiExprArg(&InitList, 1),
1678  InitList->getEndLoc(), /*ListInitialization=*/true);
1679  } else {
1680  BalancedDelimiterTracker T(*this, tok::l_paren);
1681  T.consumeOpen();
1682 
1683  ExprVector Exprs;
1684  CommaLocsTy CommaLocs;
1685 
1686  if (Tok.isNot(tok::r_paren)) {
1687  if (ParseExpressionList(Exprs, CommaLocs, [&] {
1688  QualType PreferredType = Actions.ProduceConstructorSignatureHelp(
1689  getCurScope(), TypeRep.get()->getCanonicalTypeInternal(),
1690  DS.getEndLoc(), Exprs, T.getOpenLocation());
1691  CalledSignatureHelp = true;
1692  Actions.CodeCompleteExpression(getCurScope(), PreferredType);
1693  })) {
1694  if (PP.isCodeCompletionReached() && !CalledSignatureHelp) {
1696  getCurScope(), TypeRep.get()->getCanonicalTypeInternal(),
1697  DS.getEndLoc(), Exprs, T.getOpenLocation());
1698  CalledSignatureHelp = true;
1699  }
1700  SkipUntil(tok::r_paren, StopAtSemi);
1701  return ExprError();
1702  }
1703  }
1704 
1705  // Match the ')'.
1706  T.consumeClose();
1707 
1708  // TypeRep could be null, if it references an invalid typedef.
1709  if (!TypeRep)
1710  return ExprError();
1711 
1712  assert((Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&&
1713  "Unexpected number of commas!");
1714  return Actions.ActOnCXXTypeConstructExpr(TypeRep, T.getOpenLocation(),
1715  Exprs, T.getCloseLocation(),
1716  /*ListInitialization=*/false);
1717  }
1718 }
1719 
1720 /// ParseCXXCondition - if/switch/while condition expression.
1721 ///
1722 /// condition:
1723 /// expression
1724 /// type-specifier-seq declarator '=' assignment-expression
1725 /// [C++11] type-specifier-seq declarator '=' initializer-clause
1726 /// [C++11] type-specifier-seq declarator braced-init-list
1727 /// [Clang] type-specifier-seq ref-qualifier[opt] '[' identifier-list ']'
1728 /// brace-or-equal-initializer
1729 /// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
1730 /// '=' assignment-expression
1731 ///
1732 /// In C++1z, a condition may in some contexts be preceded by an
1733 /// optional init-statement. This function will parse that too.
1734 ///
1735 /// \param InitStmt If non-null, an init-statement is permitted, and if present
1736 /// will be parsed and stored here.
1737 ///
1738 /// \param Loc The location of the start of the statement that requires this
1739 /// condition, e.g., the "for" in a for loop.
1740 ///
1741 /// \param FRI If non-null, a for range declaration is permitted, and if
1742 /// present will be parsed and stored here, and a null result will be returned.
1743 ///
1744 /// \returns The parsed condition.
1745 Sema::ConditionResult Parser::ParseCXXCondition(StmtResult *InitStmt,
1746  SourceLocation Loc,
1748  ForRangeInfo *FRI) {
1749  ParenBraceBracketBalancer BalancerRAIIObj(*this);
1750 
1751  if (Tok.is(tok::code_completion)) {
1753  cutOffParsing();
1754  return Sema::ConditionError();
1755  }
1756 
1757  ParsedAttributesWithRange attrs(AttrFactory);
1758  MaybeParseCXX11Attributes(attrs);
1759 
1760  const auto WarnOnInit = [this, &CK] {
1761  Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
1762  ? diag::warn_cxx14_compat_init_statement
1763  : diag::ext_init_statement)
1764  << (CK == Sema::ConditionKind::Switch);
1765  };
1766 
1767  // Determine what kind of thing we have.
1768  switch (isCXXConditionDeclarationOrInitStatement(InitStmt, FRI)) {
1769  case ConditionOrInitStatement::Expression: {
1770  ProhibitAttributes(attrs);
1771 
1772  // We can have an empty expression here.
1773  // if (; true);
1774  if (InitStmt && Tok.is(tok::semi)) {
1775  WarnOnInit();
1776  SourceLocation SemiLoc = ConsumeToken();
1777  *InitStmt = Actions.ActOnNullStmt(SemiLoc);
1778  return ParseCXXCondition(nullptr, Loc, CK);
1779  }
1780 
1781  // Parse the expression.
1782  ExprResult Expr = ParseExpression(); // expression
1783  if (Expr.isInvalid())
1784  return Sema::ConditionError();
1785 
1786  if (InitStmt && Tok.is(tok::semi)) {
1787  WarnOnInit();
1788  *InitStmt = Actions.ActOnExprStmt(Expr.get());
1789  ConsumeToken();
1790  return ParseCXXCondition(nullptr, Loc, CK);
1791  }
1792 
1793  return Actions.ActOnCondition(getCurScope(), Loc, Expr.get(), CK);
1794  }
1795 
1796  case ConditionOrInitStatement::InitStmtDecl: {
1797  WarnOnInit();
1798  SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
1799  DeclGroupPtrTy DG =
1800  ParseSimpleDeclaration(DeclaratorContext::InitStmtContext, DeclEnd,
1801  attrs, /*RequireSemi=*/true);
1802  *InitStmt = Actions.ActOnDeclStmt(DG, DeclStart, DeclEnd);
1803  return ParseCXXCondition(nullptr, Loc, CK);
1804  }
1805 
1806  case ConditionOrInitStatement::ForRangeDecl: {
1807  assert(FRI && "should not parse a for range declaration here");
1808  SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
1809  DeclGroupPtrTy DG = ParseSimpleDeclaration(
1810  DeclaratorContext::ForContext, DeclEnd, attrs, false, FRI);
1811  FRI->LoopVar = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
1812  return Sema::ConditionResult();
1813  }
1814 
1815  case ConditionOrInitStatement::ConditionDecl:
1816  case ConditionOrInitStatement::Error:
1817  break;
1818  }
1819 
1820  // type-specifier-seq
1821  DeclSpec DS(AttrFactory);
1822  DS.takeAttributesFrom(attrs);
1823  ParseSpecifierQualifierList(DS, AS_none, DeclSpecContext::DSC_condition);
1824 
1825  // declarator
1826  Declarator DeclaratorInfo(DS, DeclaratorContext::ConditionContext);
1827  ParseDeclarator(DeclaratorInfo);
1828 
1829  // simple-asm-expr[opt]
1830  if (Tok.is(tok::kw_asm)) {
1831  SourceLocation Loc;
1832  ExprResult AsmLabel(ParseSimpleAsm(&Loc));
1833  if (AsmLabel.isInvalid()) {
1834  SkipUntil(tok::semi, StopAtSemi);
1835  return Sema::ConditionError();
1836  }
1837  DeclaratorInfo.setAsmLabel(AsmLabel.get());
1838  DeclaratorInfo.SetRangeEnd(Loc);
1839  }
1840 
1841  // If attributes are present, parse them.
1842  MaybeParseGNUAttributes(DeclaratorInfo);
1843 
1844  // Type-check the declaration itself.
1846  DeclaratorInfo);
1847  if (Dcl.isInvalid())
1848  return Sema::ConditionError();
1849  Decl *DeclOut = Dcl.get();
1850 
1851  // '=' assignment-expression
1852  // If a '==' or '+=' is found, suggest a fixit to '='.
1853  bool CopyInitialization = isTokenEqualOrEqualTypo();
1854  if (CopyInitialization)
1855  ConsumeToken();
1856 
1857  ExprResult InitExpr = ExprError();
1858  if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
1859  Diag(Tok.getLocation(),
1860  diag::warn_cxx98_compat_generalized_initializer_lists);
1861  InitExpr = ParseBraceInitializer();
1862  } else if (CopyInitialization) {
1863  InitExpr = ParseAssignmentExpression();
1864  } else if (Tok.is(tok::l_paren)) {
1865  // This was probably an attempt to initialize the variable.
1866  SourceLocation LParen = ConsumeParen(), RParen = LParen;
1867  if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch))
1868  RParen = ConsumeParen();
1869  Diag(DeclOut->getLocation(),
1870  diag::err_expected_init_in_condition_lparen)
1871  << SourceRange(LParen, RParen);
1872  } else {
1873  Diag(DeclOut->getLocation(), diag::err_expected_init_in_condition);
1874  }
1875 
1876  if (!InitExpr.isInvalid())
1877  Actions.AddInitializerToDecl(DeclOut, InitExpr.get(), !CopyInitialization);
1878  else
1879  Actions.ActOnInitializerError(DeclOut);
1880 
1881  Actions.FinalizeDeclaration(DeclOut);
1882  return Actions.ActOnConditionVariable(DeclOut, Loc, CK);
1883 }
1884 
1885 /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
1886 /// This should only be called when the current token is known to be part of
1887 /// simple-type-specifier.
1888 ///
1889 /// simple-type-specifier:
1890 /// '::'[opt] nested-name-specifier[opt] type-name
1891 /// '::'[opt] nested-name-specifier 'template' simple-template-id [TODO]
1892 /// char
1893 /// wchar_t
1894 /// bool
1895 /// short
1896 /// int
1897 /// long
1898 /// signed
1899 /// unsigned
1900 /// float
1901 /// double
1902 /// void
1903 /// [GNU] typeof-specifier
1904 /// [C++0x] auto [TODO]
1905 ///
1906 /// type-name:
1907 /// class-name
1908 /// enum-name
1909 /// typedef-name
1910 ///
1911 void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) {
1912  DS.SetRangeStart(Tok.getLocation());
1913  const char *PrevSpec;
1914  unsigned DiagID;
1915  SourceLocation Loc = Tok.getLocation();
1916  const clang::PrintingPolicy &Policy =
1917  Actions.getASTContext().getPrintingPolicy();
1918 
1919  switch (Tok.getKind()) {
1920  case tok::identifier: // foo::bar
1921  case tok::coloncolon: // ::foo::bar
1922  llvm_unreachable("Annotation token should already be formed!");
1923  default:
1924  llvm_unreachable("Not a simple-type-specifier token!");
1925 
1926  // type-name
1927  case tok::annot_typename: {
1928  if (getTypeAnnotation(Tok))
1929  DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID,
1930  getTypeAnnotation(Tok), Policy);
1931  else
1932  DS.SetTypeSpecError();
1933 
1934  DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1935  ConsumeAnnotationToken();
1936 
1937  DS.Finish(Actions, Policy);
1938  return;
1939  }
1940 
1941  // builtin types
1942  case tok::kw_short:
1943  DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID, Policy);
1944  break;
1945  case tok::kw_long:
1946  DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, DiagID, Policy);
1947  break;
1948  case tok::kw___int64:
1949  DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, DiagID, Policy);
1950  break;
1951  case tok::kw_signed:
1952  DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID);
1953  break;
1954  case tok::kw_unsigned:
1955  DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, DiagID);
1956  break;
1957  case tok::kw_void:
1958  DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID, Policy);
1959  break;
1960  case tok::kw_char:
1961  DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID, Policy);
1962  break;
1963  case tok::kw_int:
1964  DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID, Policy);
1965  break;
1966  case tok::kw___int128:
1967  DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec, DiagID, Policy);
1968  break;
1969  case tok::kw_half:
1970  DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, DiagID, Policy);
1971  break;
1972  case tok::kw_float:
1973  DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID, Policy);
1974  break;
1975  case tok::kw_double:
1976  DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID, Policy);
1977  break;
1978  case tok::kw__Float16:
1979  DS.SetTypeSpecType(DeclSpec::TST_float16, Loc, PrevSpec, DiagID, Policy);
1980  break;
1981  case tok::kw___float128:
1982  DS.SetTypeSpecType(DeclSpec::TST_float128, Loc, PrevSpec, DiagID, Policy);
1983  break;
1984  case tok::kw_wchar_t:
1985  DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID, Policy);
1986  break;
1987  case tok::kw_char8_t:
1988  DS.SetTypeSpecType(DeclSpec::TST_char8, Loc, PrevSpec, DiagID, Policy);
1989  break;
1990  case tok::kw_char16_t:
1991  DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID, Policy);
1992  break;
1993  case tok::kw_char32_t:
1994  DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID, Policy);
1995  break;
1996  case tok::kw_bool:
1997  DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID, Policy);
1998  break;
1999  case tok::annot_decltype:
2000  case tok::kw_decltype:
2001  DS.SetRangeEnd(ParseDecltypeSpecifier(DS));
2002  return DS.Finish(Actions, Policy);
2003 
2004  // GNU typeof support.
2005  case tok::kw_typeof:
2006  ParseTypeofSpecifier(DS);
2007  DS.Finish(Actions, Policy);
2008  return;
2009  }
2010  ConsumeAnyToken();
2011  DS.SetRangeEnd(PrevTokLocation);
2012  DS.Finish(Actions, Policy);
2013 }
2014 
2015 /// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++
2016 /// [dcl.name]), which is a non-empty sequence of type-specifiers,
2017 /// e.g., "const short int". Note that the DeclSpec is *not* finished
2018 /// by parsing the type-specifier-seq, because these sequences are
2019 /// typically followed by some form of declarator. Returns true and
2020 /// emits diagnostics if this is not a type-specifier-seq, false
2021 /// otherwise.
2022 ///
2023 /// type-specifier-seq: [C++ 8.1]
2024 /// type-specifier type-specifier-seq[opt]
2025 ///
2026 bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) {
2027  ParseSpecifierQualifierList(DS, AS_none, DeclSpecContext::DSC_type_specifier);
2028  DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy());
2029  return false;
2030 }
2031 
2032 /// Finish parsing a C++ unqualified-id that is a template-id of
2033 /// some form.
2034 ///
2035 /// This routine is invoked when a '<' is encountered after an identifier or
2036 /// operator-function-id is parsed by \c ParseUnqualifiedId() to determine
2037 /// whether the unqualified-id is actually a template-id. This routine will
2038 /// then parse the template arguments and form the appropriate template-id to
2039 /// return to the caller.
2040 ///
2041 /// \param SS the nested-name-specifier that precedes this template-id, if
2042 /// we're actually parsing a qualified-id.
2043 ///
2044 /// \param Name for constructor and destructor names, this is the actual
2045 /// identifier that may be a template-name.
2046 ///
2047 /// \param NameLoc the location of the class-name in a constructor or
2048 /// destructor.
2049 ///
2050 /// \param EnteringContext whether we're entering the scope of the
2051 /// nested-name-specifier.
2052 ///
2053 /// \param ObjectType if this unqualified-id occurs within a member access
2054 /// expression, the type of the base object whose member is being accessed.
2055 ///
2056 /// \param Id as input, describes the template-name or operator-function-id
2057 /// that precedes the '<'. If template arguments were parsed successfully,
2058 /// will be updated with the template-id.
2059 ///
2060 /// \param AssumeTemplateId When true, this routine will assume that the name
2061 /// refers to a template without performing name lookup to verify.
2062 ///
2063 /// \returns true if a parse error occurred, false otherwise.
2064 bool Parser::ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
2065  SourceLocation TemplateKWLoc,
2066  IdentifierInfo *Name,
2067  SourceLocation NameLoc,
2068  bool EnteringContext,
2069  ParsedType ObjectType,
2070  UnqualifiedId &Id,
2071  bool AssumeTemplateId) {
2072  assert(Tok.is(tok::less) && "Expected '<' to finish parsing a template-id");
2073 
2074  TemplateTy Template;
2076  switch (Id.getKind()) {
2080  if (AssumeTemplateId) {
2081  // We defer the injected-class-name checks until we've found whether
2082  // this template-id is used to form a nested-name-specifier or not.
2083  TNK = Actions.ActOnDependentTemplateName(
2084  getCurScope(), SS, TemplateKWLoc, Id, ObjectType, EnteringContext,
2085  Template, /*AllowInjectedClassName*/ true);
2086  if (TNK == TNK_Non_template)
2087  return true;
2088  } else {
2089  bool MemberOfUnknownSpecialization;
2090  TNK = Actions.isTemplateName(getCurScope(), SS,
2091  TemplateKWLoc.isValid(), Id,
2092  ObjectType, EnteringContext, Template,
2093  MemberOfUnknownSpecialization);
2094 
2095  if (TNK == TNK_Non_template && MemberOfUnknownSpecialization &&
2096  ObjectType && IsTemplateArgumentList()) {
2097  // We have something like t->getAs<T>(), where getAs is a
2098  // member of an unknown specialization. However, this will only
2099  // parse correctly as a template, so suggest the keyword 'template'
2100  // before 'getAs' and treat this as a dependent template name.
2101  std::string Name;
2103  Name = Id.Identifier->getName();
2104  else {
2105  Name = "operator ";
2108  else
2109  Name += Id.Identifier->getName();
2110  }
2111  Diag(Id.StartLocation, diag::err_missing_dependent_template_keyword)
2112  << Name
2113  << FixItHint::CreateInsertion(Id.StartLocation, "template ");
2114  TNK = Actions.ActOnDependentTemplateName(
2115  getCurScope(), SS, TemplateKWLoc, Id, ObjectType, EnteringContext,
2116  Template, /*AllowInjectedClassName*/ true);
2117  if (TNK == TNK_Non_template)
2118  return true;
2119  }
2120  }
2121  break;
2122 
2125  bool MemberOfUnknownSpecialization;
2126  TemplateName.setIdentifier(Name, NameLoc);
2127  TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
2128  TemplateName, ObjectType,
2129  EnteringContext, Template,
2130  MemberOfUnknownSpecialization);
2131  break;
2132  }
2133 
2136  bool MemberOfUnknownSpecialization;
2137  TemplateName.setIdentifier(Name, NameLoc);
2138  if (ObjectType) {
2139  TNK = Actions.ActOnDependentTemplateName(
2140  getCurScope(), SS, TemplateKWLoc, TemplateName, ObjectType,
2141  EnteringContext, Template, /*AllowInjectedClassName*/ true);
2142  if (TNK == TNK_Non_template)
2143  return true;
2144  } else {
2145  TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
2146  TemplateName, ObjectType,
2147  EnteringContext, Template,
2148  MemberOfUnknownSpecialization);
2149 
2150  if (TNK == TNK_Non_template && !Id.DestructorName.get()) {
2151  Diag(NameLoc, diag::err_destructor_template_id)
2152  << Name << SS.getRange();
2153  return true;
2154  }
2155  }
2156  break;
2157  }
2158 
2159  default:
2160  return false;
2161  }
2162 
2163  if (TNK == TNK_Non_template)
2164  return false;
2165 
2166  // Parse the enclosed template argument list.
2167  SourceLocation LAngleLoc, RAngleLoc;
2168  TemplateArgList TemplateArgs;
2169  if (ParseTemplateIdAfterTemplateName(true, LAngleLoc, TemplateArgs,
2170  RAngleLoc))
2171  return true;
2172 
2176  // Form a parsed representation of the template-id to be stored in the
2177  // UnqualifiedId.
2178 
2179  // FIXME: Store name for literal operator too.
2180  IdentifierInfo *TemplateII =
2182  : nullptr;
2183  OverloadedOperatorKind OpKind =
2185  ? OO_None
2187 
2189  SS, TemplateKWLoc, Id.StartLocation, TemplateII, OpKind, Template, TNK,
2190  LAngleLoc, RAngleLoc, TemplateArgs, TemplateIds);
2191 
2192  Id.setTemplateId(TemplateId);
2193  return false;
2194  }
2195 
2196  // Bundle the template arguments together.
2197  ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
2198 
2199  // Constructor and destructor names.
2201  = Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
2202  Template, Name, NameLoc,
2203  LAngleLoc, TemplateArgsPtr, RAngleLoc,
2204  /*IsCtorOrDtorName=*/true);
2205  if (Type.isInvalid())
2206  return true;
2207 
2209  Id.setConstructorName(Type.get(), NameLoc, RAngleLoc);
2210  else
2211  Id.setDestructorName(Id.StartLocation, Type.get(), RAngleLoc);
2212 
2213  return false;
2214 }
2215 
2216 /// Parse an operator-function-id or conversion-function-id as part
2217 /// of a C++ unqualified-id.
2218 ///
2219 /// This routine is responsible only for parsing the operator-function-id or
2220 /// conversion-function-id; it does not handle template arguments in any way.
2221 ///
2222 /// \code
2223 /// operator-function-id: [C++ 13.5]
2224 /// 'operator' operator
2225 ///
2226 /// operator: one of
2227 /// new delete new[] delete[]
2228 /// + - * / % ^ & | ~
2229 /// ! = < > += -= *= /= %=
2230 /// ^= &= |= << >> >>= <<= == !=
2231 /// <= >= && || ++ -- , ->* ->
2232 /// () [] <=>
2233 ///
2234 /// conversion-function-id: [C++ 12.3.2]
2235 /// operator conversion-type-id
2236 ///
2237 /// conversion-type-id:
2238 /// type-specifier-seq conversion-declarator[opt]
2239 ///
2240 /// conversion-declarator:
2241 /// ptr-operator conversion-declarator[opt]
2242 /// \endcode
2243 ///
2244 /// \param SS The nested-name-specifier that preceded this unqualified-id. If
2245 /// non-empty, then we are parsing the unqualified-id of a qualified-id.
2246 ///
2247 /// \param EnteringContext whether we are entering the scope of the
2248 /// nested-name-specifier.
2249 ///
2250 /// \param ObjectType if this unqualified-id occurs within a member access
2251 /// expression, the type of the base object whose member is being accessed.
2252 ///
2253 /// \param Result on a successful parse, contains the parsed unqualified-id.
2254 ///
2255 /// \returns true if parsing fails, false otherwise.
2256 bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
2257  ParsedType ObjectType,
2258  UnqualifiedId &Result) {
2259  assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword");
2260 
2261  // Consume the 'operator' keyword.
2262  SourceLocation KeywordLoc = ConsumeToken();
2263 
2264  // Determine what kind of operator name we have.
2265  unsigned SymbolIdx = 0;
2266  SourceLocation SymbolLocations[3];
2268  switch (Tok.getKind()) {
2269  case tok::kw_new:
2270  case tok::kw_delete: {
2271  bool isNew = Tok.getKind() == tok::kw_new;
2272  // Consume the 'new' or 'delete'.
2273  SymbolLocations[SymbolIdx++] = ConsumeToken();
2274  // Check for array new/delete.
2275  if (Tok.is(tok::l_square) &&
2276  (!getLangOpts().CPlusPlus11 || NextToken().isNot(tok::l_square))) {
2277  // Consume the '[' and ']'.
2278  BalancedDelimiterTracker T(*this, tok::l_square);
2279  T.consumeOpen();
2280  T.consumeClose();
2281  if (T.getCloseLocation().isInvalid())
2282  return true;
2283 
2284  SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2285  SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2286  Op = isNew? OO_Array_New : OO_Array_Delete;
2287  } else {
2288  Op = isNew? OO_New : OO_Delete;
2289  }
2290  break;
2291  }
2292 
2293 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2294  case tok::Token: \
2295  SymbolLocations[SymbolIdx++] = ConsumeToken(); \
2296  Op = OO_##Name; \
2297  break;
2298 #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2299 #include "clang/Basic/OperatorKinds.def"
2300 
2301  case tok::l_paren: {
2302  // Consume the '(' and ')'.
2303  BalancedDelimiterTracker T(*this, tok::l_paren);
2304  T.consumeOpen();
2305  T.consumeClose();
2306  if (T.getCloseLocation().isInvalid())
2307  return true;
2308 
2309  SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2310  SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2311  Op = OO_Call;
2312  break;
2313  }
2314 
2315  case tok::l_square: {
2316  // Consume the '[' and ']'.
2317  BalancedDelimiterTracker T(*this, tok::l_square);
2318  T.consumeOpen();
2319  T.consumeClose();
2320  if (T.getCloseLocation().isInvalid())
2321  return true;
2322 
2323  SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2324  SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2325  Op = OO_Subscript;
2326  break;
2327  }
2328 
2329  case tok::code_completion: {
2330  // Code completion for the operator name.
2332  cutOffParsing();
2333  // Don't try to parse any further.
2334  return true;
2335  }
2336 
2337  default:
2338  break;
2339  }
2340 
2341  if (Op != OO_None) {
2342  // We have parsed an operator-function-id.
2343  Result.setOperatorFunctionId(KeywordLoc, Op, SymbolLocations);
2344  return false;
2345  }
2346 
2347  // Parse a literal-operator-id.
2348  //
2349  // literal-operator-id: C++11 [over.literal]
2350  // operator string-literal identifier
2351  // operator user-defined-string-literal
2352 
2353  if (getLangOpts().CPlusPlus11 && isTokenStringLiteral()) {
2354  Diag(Tok.getLocation(), diag::warn_cxx98_compat_literal_operator);
2355 
2356  SourceLocation DiagLoc;
2357  unsigned DiagId = 0;
2358 
2359  // We're past translation phase 6, so perform string literal concatenation
2360  // before checking for "".
2361  SmallVector<Token, 4> Toks;
2363  while (isTokenStringLiteral()) {
2364  if (!Tok.is(tok::string_literal) && !DiagId) {
2365  // C++11 [over.literal]p1:
2366  // The string-literal or user-defined-string-literal in a
2367  // literal-operator-id shall have no encoding-prefix [...].
2368  DiagLoc = Tok.getLocation();
2369  DiagId = diag::err_literal_operator_string_prefix;
2370  }
2371  Toks.push_back(Tok);
2372  TokLocs.push_back(ConsumeStringToken());
2373  }
2374 
2375  StringLiteralParser Literal(Toks, PP);
2376  if (Literal.hadError)
2377  return true;
2378 
2379  // Grab the literal operator's suffix, which will be either the next token
2380  // or a ud-suffix from the string literal.
2381  IdentifierInfo *II = nullptr;
2382  SourceLocation SuffixLoc;
2383  if (!Literal.getUDSuffix().empty()) {
2384  II = &PP.getIdentifierTable().get(Literal.getUDSuffix());
2385  SuffixLoc =
2387  Literal.getUDSuffixOffset(),
2388  PP.getSourceManager(), getLangOpts());
2389  } else if (Tok.is(tok::identifier)) {
2390  II = Tok.getIdentifierInfo();
2391  SuffixLoc = ConsumeToken();
2392  TokLocs.push_back(SuffixLoc);
2393  } else {
2394  Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
2395  return true;
2396  }
2397 
2398  // The string literal must be empty.
2399  if (!Literal.GetString().empty() || Literal.Pascal) {
2400  // C++11 [over.literal]p1:
2401  // The string-literal or user-defined-string-literal in a
2402  // literal-operator-id shall [...] contain no characters
2403  // other than the implicit terminating '\0'.
2404  DiagLoc = TokLocs.front();
2405  DiagId = diag::err_literal_operator_string_not_empty;
2406  }
2407 
2408  if (DiagId) {
2409  // This isn't a valid literal-operator-id, but we think we know
2410  // what the user meant. Tell them what they should have written.
2411  SmallString<32> Str;
2412  Str += "\"\"";
2413  Str += II->getName();
2414  Diag(DiagLoc, DiagId) << FixItHint::CreateReplacement(
2415  SourceRange(TokLocs.front(), TokLocs.back()), Str);
2416  }
2417 
2418  Result.setLiteralOperatorId(II, KeywordLoc, SuffixLoc);
2419 
2420  return Actions.checkLiteralOperatorId(SS, Result);
2421  }
2422 
2423  // Parse a conversion-function-id.
2424  //
2425  // conversion-function-id: [C++ 12.3.2]
2426  // operator conversion-type-id
2427  //
2428  // conversion-type-id:
2429  // type-specifier-seq conversion-declarator[opt]
2430  //
2431  // conversion-declarator:
2432  // ptr-operator conversion-declarator[opt]
2433 
2434  // Parse the type-specifier-seq.
2435  DeclSpec DS(AttrFactory);
2436  if (ParseCXXTypeSpecifierSeq(DS)) // FIXME: ObjectType?
2437  return true;
2438 
2439  // Parse the conversion-declarator, which is merely a sequence of
2440  // ptr-operators.
2442  ParseDeclaratorInternal(D, /*DirectDeclParser=*/nullptr);
2443 
2444  // Finish up the type.
2445  TypeResult Ty = Actions.ActOnTypeName(getCurScope(), D);
2446  if (Ty.isInvalid())
2447  return true;
2448 
2449  // Note that this is a conversion-function-id.
2450  Result.setConversionFunctionId(KeywordLoc, Ty.get(),
2451  D.getSourceRange().getEnd());
2452  return false;
2453 }
2454 
2455 /// Parse a C++ unqualified-id (or a C identifier), which describes the
2456 /// name of an entity.
2457 ///
2458 /// \code
2459 /// unqualified-id: [C++ expr.prim.general]
2460 /// identifier
2461 /// operator-function-id
2462 /// conversion-function-id
2463 /// [C++0x] literal-operator-id [TODO]
2464 /// ~ class-name
2465 /// template-id
2466 ///
2467 /// \endcode
2468 ///
2469 /// \param SS The nested-name-specifier that preceded this unqualified-id. If
2470 /// non-empty, then we are parsing the unqualified-id of a qualified-id.
2471 ///
2472 /// \param EnteringContext whether we are entering the scope of the
2473 /// nested-name-specifier.
2474 ///
2475 /// \param AllowDestructorName whether we allow parsing of a destructor name.
2476 ///
2477 /// \param AllowConstructorName whether we allow parsing a constructor name.
2478 ///
2479 /// \param AllowDeductionGuide whether we allow parsing a deduction guide name.
2480 ///
2481 /// \param ObjectType if this unqualified-id occurs within a member access
2482 /// expression, the type of the base object whose member is being accessed.
2483 ///
2484 /// \param Result on a successful parse, contains the parsed unqualified-id.
2485 ///
2486 /// \returns true if parsing fails, false otherwise.
2487 bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
2488  bool AllowDestructorName,
2489  bool AllowConstructorName,
2490  bool AllowDeductionGuide,
2491  ParsedType ObjectType,
2492  SourceLocation *TemplateKWLoc,
2493  UnqualifiedId &Result) {
2494  if (TemplateKWLoc)
2495  *TemplateKWLoc = SourceLocation();
2496 
2497  // Handle 'A::template B'. This is for template-ids which have not
2498  // already been annotated by ParseOptionalCXXScopeSpecifier().
2499  bool TemplateSpecified = false;
2500  if (Tok.is(tok::kw_template)) {
2501  if (TemplateKWLoc && (ObjectType || SS.isSet())) {
2502  TemplateSpecified = true;
2503  *TemplateKWLoc = ConsumeToken();
2504  } else {
2505  SourceLocation TemplateLoc = ConsumeToken();
2506  Diag(TemplateLoc, diag::err_unexpected_template_in_unqualified_id)
2507  << FixItHint::CreateRemoval(TemplateLoc);
2508  }
2509  }
2510 
2511  // unqualified-id:
2512  // identifier
2513  // template-id (when it hasn't already been annotated)
2514  if (Tok.is(tok::identifier)) {
2515  // Consume the identifier.
2516  IdentifierInfo *Id = Tok.getIdentifierInfo();
2517  SourceLocation IdLoc = ConsumeToken();
2518 
2519  if (!getLangOpts().CPlusPlus) {
2520  // If we're not in C++, only identifiers matter. Record the
2521  // identifier and return.
2522  Result.setIdentifier(Id, IdLoc);
2523  return false;
2524  }
2525 
2527  if (AllowConstructorName &&
2528  Actions.isCurrentClassName(*Id, getCurScope(), &SS)) {
2529  // We have parsed a constructor name.
2530  ParsedType Ty = Actions.getConstructorName(*Id, IdLoc, getCurScope(), SS,
2531  EnteringContext);
2532  if (!Ty)
2533  return true;
2534  Result.setConstructorName(Ty, IdLoc, IdLoc);
2535  } else if (getLangOpts().CPlusPlus17 &&
2536  AllowDeductionGuide && SS.isEmpty() &&
2537  Actions.isDeductionGuideName(getCurScope(), *Id, IdLoc,
2538  &TemplateName)) {
2539  // We have parsed a template-name naming a deduction guide.
2540  Result.setDeductionGuideName(TemplateName, IdLoc);
2541  } else {
2542  // We have parsed an identifier.
2543  Result.setIdentifier(Id, IdLoc);
2544  }
2545 
2546  // If the next token is a '<', we may have a template.
2547  TemplateTy Template;
2548  if (Tok.is(tok::less))
2549  return ParseUnqualifiedIdTemplateId(
2550  SS, TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), Id, IdLoc,
2551  EnteringContext, ObjectType, Result, TemplateSpecified);
2552  else if (TemplateSpecified &&
2554  getCurScope(), SS, *TemplateKWLoc, Result, ObjectType,
2555  EnteringContext, Template,
2556  /*AllowInjectedClassName*/ true) == TNK_Non_template)
2557  return true;
2558 
2559  return false;
2560  }
2561 
2562  // unqualified-id:
2563  // template-id (already parsed and annotated)
2564  if (Tok.is(tok::annot_template_id)) {
2565  TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
2566 
2567  // If the template-name names the current class, then this is a constructor
2568  if (AllowConstructorName && TemplateId->Name &&
2569  Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
2570  if (SS.isSet()) {
2571  // C++ [class.qual]p2 specifies that a qualified template-name
2572  // is taken as the constructor name where a constructor can be
2573  // declared. Thus, the template arguments are extraneous, so
2574  // complain about them and remove them entirely.
2575  Diag(TemplateId->TemplateNameLoc,
2576  diag::err_out_of_line_constructor_template_id)
2577  << TemplateId->Name
2579  SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc));
2580  ParsedType Ty = Actions.getConstructorName(
2581  *TemplateId->Name, TemplateId->TemplateNameLoc, getCurScope(), SS,
2582  EnteringContext);
2583  if (!Ty)
2584  return true;
2585  Result.setConstructorName(Ty, TemplateId->TemplateNameLoc,
2586  TemplateId->RAngleLoc);
2587  ConsumeAnnotationToken();
2588  return false;
2589  }
2590 
2591  Result.setConstructorTemplateId(TemplateId);
2592  ConsumeAnnotationToken();
2593  return false;
2594  }
2595 
2596  // We have already parsed a template-id; consume the annotation token as
2597  // our unqualified-id.
2598  Result.setTemplateId(TemplateId);
2599  SourceLocation TemplateLoc = TemplateId->TemplateKWLoc;
2600  if (TemplateLoc.isValid()) {
2601  if (TemplateKWLoc && (ObjectType || SS.isSet()))
2602  *TemplateKWLoc = TemplateLoc;
2603  else
2604  Diag(TemplateLoc, diag::err_unexpected_template_in_unqualified_id)
2605  << FixItHint::CreateRemoval(TemplateLoc);
2606  }
2607  ConsumeAnnotationToken();
2608  return false;
2609  }
2610 
2611  // unqualified-id:
2612  // operator-function-id
2613  // conversion-function-id
2614  if (Tok.is(tok::kw_operator)) {
2615  if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, Result))
2616  return true;
2617 
2618  // If we have an operator-function-id or a literal-operator-id and the next
2619  // token is a '<', we may have a
2620  //
2621  // template-id:
2622  // operator-function-id < template-argument-list[opt] >
2623  TemplateTy Template;
2626  Tok.is(tok::less))
2627  return ParseUnqualifiedIdTemplateId(
2628  SS, TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), nullptr,
2629  SourceLocation(), EnteringContext, ObjectType, Result,
2630  TemplateSpecified);
2631  else if (TemplateSpecified &&
2633  getCurScope(), SS, *TemplateKWLoc, Result, ObjectType,
2634  EnteringContext, Template,
2635  /*AllowInjectedClassName*/ true) == TNK_Non_template)
2636  return true;
2637 
2638  return false;
2639  }
2640 
2641  if (getLangOpts().CPlusPlus &&
2642  (AllowDestructorName || SS.isSet()) && Tok.is(tok::tilde)) {
2643  // C++ [expr.unary.op]p10:
2644  // There is an ambiguity in the unary-expression ~X(), where X is a
2645  // class-name. The ambiguity is resolved in favor of treating ~ as a
2646  // unary complement rather than treating ~X as referring to a destructor.
2647 
2648  // Parse the '~'.
2649  SourceLocation TildeLoc = ConsumeToken();
2650 
2651  if (SS.isEmpty() && Tok.is(tok::kw_decltype)) {
2652  DeclSpec DS(AttrFactory);
2653  SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
2654  if (ParsedType Type =
2655  Actions.getDestructorTypeForDecltype(DS, ObjectType)) {
2656  Result.setDestructorName(TildeLoc, Type, EndLoc);
2657  return false;
2658  }
2659  return true;
2660  }
2661 
2662  // Parse the class-name.
2663  if (Tok.isNot(tok::identifier)) {
2664  Diag(Tok, diag::err_destructor_tilde_identifier);
2665  return true;
2666  }
2667 
2668  // If the user wrote ~T::T, correct it to T::~T.
2669  DeclaratorScopeObj DeclScopeObj(*this, SS);
2670  if (!TemplateSpecified && NextToken().is(tok::coloncolon)) {
2671  // Don't let ParseOptionalCXXScopeSpecifier() "correct"
2672  // `int A; struct { ~A::A(); };` to `int A; struct { ~A:A(); };`,
2673  // it will confuse this recovery logic.
2674  ColonProtectionRAIIObject ColonRAII(*this, false);
2675 
2676  if (SS.isSet()) {
2677  AnnotateScopeToken(SS, /*NewAnnotation*/true);
2678  SS.clear();
2679  }
2680  if (ParseOptionalCXXScopeSpecifier(SS, ObjectType, EnteringContext))
2681  return true;
2682  if (SS.isNotEmpty())
2683  ObjectType = nullptr;
2684  if (Tok.isNot(tok::identifier) || NextToken().is(tok::coloncolon) ||
2685  !SS.isSet()) {
2686  Diag(TildeLoc, diag::err_destructor_tilde_scope);
2687  return true;
2688  }
2689 
2690  // Recover as if the tilde had been written before the identifier.
2691  Diag(TildeLoc, diag::err_destructor_tilde_scope)
2692  << FixItHint::CreateRemoval(TildeLoc)
2693  << FixItHint::CreateInsertion(Tok.getLocation(), "~");
2694 
2695  // Temporarily enter the scope for the rest of this function.
2696  if (Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
2697  DeclScopeObj.EnterDeclaratorScope();
2698  }
2699 
2700  // Parse the class-name (or template-name in a simple-template-id).
2701  IdentifierInfo *ClassName = Tok.getIdentifierInfo();
2702  SourceLocation ClassNameLoc = ConsumeToken();
2703 
2704  if (Tok.is(tok::less)) {
2705  Result.setDestructorName(TildeLoc, nullptr, ClassNameLoc);
2706  return ParseUnqualifiedIdTemplateId(
2707  SS, TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), ClassName,
2708  ClassNameLoc, EnteringContext, ObjectType, Result, TemplateSpecified);
2709  }
2710 
2711  // Note that this is a destructor name.
2712  ParsedType Ty = Actions.getDestructorName(TildeLoc, *ClassName,
2713  ClassNameLoc, getCurScope(),
2714  SS, ObjectType,
2715  EnteringContext);
2716  if (!Ty)
2717  return true;
2718 
2719  Result.setDestructorName(TildeLoc, Ty, ClassNameLoc);
2720  return false;
2721  }
2722 
2723  Diag(Tok, diag::err_expected_unqualified_id)
2724  << getLangOpts().CPlusPlus;
2725  return true;
2726 }
2727 
2728 /// ParseCXXNewExpression - Parse a C++ new-expression. New is used to allocate
2729 /// memory in a typesafe manner and call constructors.
2730 ///
2731 /// This method is called to parse the new expression after the optional :: has
2732 /// been already parsed. If the :: was present, "UseGlobal" is true and "Start"
2733 /// is its location. Otherwise, "Start" is the location of the 'new' token.
2734 ///
2735 /// new-expression:
2736 /// '::'[opt] 'new' new-placement[opt] new-type-id
2737 /// new-initializer[opt]
2738 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2739 /// new-initializer[opt]
2740 ///
2741 /// new-placement:
2742 /// '(' expression-list ')'
2743 ///
2744 /// new-type-id:
2745 /// type-specifier-seq new-declarator[opt]
2746 /// [GNU] attributes type-specifier-seq new-declarator[opt]
2747 ///
2748 /// new-declarator:
2749 /// ptr-operator new-declarator[opt]
2750 /// direct-new-declarator
2751 ///
2752 /// new-initializer:
2753 /// '(' expression-list[opt] ')'
2754 /// [C++0x] braced-init-list
2755 ///
2756 ExprResult
2757 Parser::ParseCXXNewExpression(bool UseGlobal, SourceLocation Start) {
2758  assert(Tok.is(tok::kw_new) && "expected 'new' token");
2759  ConsumeToken(); // Consume 'new'
2760 
2761  // A '(' now can be a new-placement or the '(' wrapping the type-id in the
2762  // second form of new-expression. It can't be a new-type-id.
2763 
2764  ExprVector PlacementArgs;
2765  SourceLocation PlacementLParen, PlacementRParen;
2766 
2767  SourceRange TypeIdParens;
2768  DeclSpec DS(AttrFactory);
2769  Declarator DeclaratorInfo(DS, DeclaratorContext::CXXNewContext);
2770  if (Tok.is(tok::l_paren)) {
2771  // If it turns out to be a placement, we change the type location.
2772  BalancedDelimiterTracker T(*this, tok::l_paren);
2773  T.consumeOpen();
2774  PlacementLParen = T.getOpenLocation();
2775  if (ParseExpressionListOrTypeId(PlacementArgs, DeclaratorInfo)) {
2776  SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2777  return ExprError();
2778  }
2779 
2780  T.consumeClose();
2781  PlacementRParen = T.getCloseLocation();
2782  if (PlacementRParen.isInvalid()) {
2783  SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2784  return ExprError();
2785  }
2786 
2787  if (PlacementArgs.empty()) {
2788  // Reset the placement locations. There was no placement.
2789  TypeIdParens = T.getRange();
2790  PlacementLParen = PlacementRParen = SourceLocation();
2791  } else {
2792  // We still need the type.
2793  if (Tok.is(tok::l_paren)) {
2794  BalancedDelimiterTracker T(*this, tok::l_paren);
2795  T.consumeOpen();
2796  MaybeParseGNUAttributes(DeclaratorInfo);
2797  ParseSpecifierQualifierList(DS);
2798  DeclaratorInfo.SetSourceRange(DS.getSourceRange());
2799  ParseDeclarator(DeclaratorInfo);
2800  T.consumeClose();
2801  TypeIdParens = T.getRange();
2802  } else {
2803  MaybeParseGNUAttributes(DeclaratorInfo);
2804  if (ParseCXXTypeSpecifierSeq(DS))
2805  DeclaratorInfo.setInvalidType(true);
2806  else {
2807  DeclaratorInfo.SetSourceRange(DS.getSourceRange());
2808  ParseDeclaratorInternal(DeclaratorInfo,
2809  &Parser::ParseDirectNewDeclarator);
2810  }
2811  }
2812  }
2813  } else {
2814  // A new-type-id is a simplified type-id, where essentially the
2815  // direct-declarator is replaced by a direct-new-declarator.
2816  MaybeParseGNUAttributes(DeclaratorInfo);
2817  if (ParseCXXTypeSpecifierSeq(DS))
2818  DeclaratorInfo.setInvalidType(true);
2819  else {
2820  DeclaratorInfo.SetSourceRange(DS.getSourceRange());
2821  ParseDeclaratorInternal(DeclaratorInfo,
2822  &Parser::ParseDirectNewDeclarator);
2823  }
2824  }
2825  if (DeclaratorInfo.isInvalidType()) {
2826  SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2827  return ExprError();
2828  }
2829 
2830  ExprResult Initializer;
2831 
2832  if (Tok.is(tok::l_paren)) {
2833  SourceLocation ConstructorLParen, ConstructorRParen;
2834  ExprVector ConstructorArgs;
2835  BalancedDelimiterTracker T(*this, tok::l_paren);
2836  T.consumeOpen();
2837  ConstructorLParen = T.getOpenLocation();
2838  if (Tok.isNot(tok::r_paren)) {
2839  CommaLocsTy CommaLocs;
2840  if (ParseExpressionList(ConstructorArgs, CommaLocs, [&] {
2841  ParsedType TypeRep =
2842  Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
2843  QualType PreferredType = Actions.ProduceConstructorSignatureHelp(
2844  getCurScope(), TypeRep.get()->getCanonicalTypeInternal(),
2845  DeclaratorInfo.getEndLoc(), ConstructorArgs, ConstructorLParen);
2846  CalledSignatureHelp = true;
2847  Actions.CodeCompleteExpression(getCurScope(), PreferredType);
2848  })) {
2849  if (PP.isCodeCompletionReached() && !CalledSignatureHelp) {
2850  ParsedType TypeRep =
2851  Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
2853  getCurScope(), TypeRep.get()->getCanonicalTypeInternal(),
2854  DeclaratorInfo.getEndLoc(), ConstructorArgs, ConstructorLParen);
2855  CalledSignatureHelp = true;
2856  }
2857  SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2858  return ExprError();
2859  }
2860  }
2861  T.consumeClose();
2862  ConstructorRParen = T.getCloseLocation();
2863  if (ConstructorRParen.isInvalid()) {
2864  SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2865  return ExprError();
2866  }
2867  Initializer = Actions.ActOnParenListExpr(ConstructorLParen,
2868  ConstructorRParen,
2869  ConstructorArgs);
2870  } else if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus11) {
2871  Diag(Tok.getLocation(),
2872  diag::warn_cxx98_compat_generalized_initializer_lists);
2873  Initializer = ParseBraceInitializer();
2874  }
2875  if (Initializer.isInvalid())
2876  return Initializer;
2877 
2878  return Actions.ActOnCXXNew(Start, UseGlobal, PlacementLParen,
2879  PlacementArgs, PlacementRParen,
2880  TypeIdParens, DeclaratorInfo, Initializer.get());
2881 }
2882 
2883 /// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be
2884 /// passed to ParseDeclaratorInternal.
2885 ///
2886 /// direct-new-declarator:
2887 /// '[' expression ']'
2888 /// direct-new-declarator '[' constant-expression ']'
2889 ///
2890 void Parser::ParseDirectNewDeclarator(Declarator &D) {
2891  // Parse the array dimensions.
2892  bool first = true;
2893  while (Tok.is(tok::l_square)) {
2894  // An array-size expression can't start with a lambda.
2895  if (CheckProhibitedCXX11Attribute())
2896  continue;
2897 
2898  BalancedDelimiterTracker T(*this, tok::l_square);
2899  T.consumeOpen();
2900 
2901  ExprResult Size(first ? ParseExpression()
2903  if (Size.isInvalid()) {
2904  // Recover
2905  SkipUntil(tok::r_square, StopAtSemi);
2906  return;
2907  }
2908  first = false;
2909 
2910  T.consumeClose();
2911 
2912  // Attributes here appertain to the array type. C++11 [expr.new]p5.
2913  ParsedAttributes Attrs(AttrFactory);
2914  MaybeParseCXX11Attributes(Attrs);
2915 
2917  /*static=*/false, /*star=*/false,
2918  Size.get(), T.getOpenLocation(),
2919  T.getCloseLocation()),
2920  std::move(Attrs), T.getCloseLocation());
2921 
2922  if (T.getCloseLocation().isInvalid())
2923  return;
2924  }
2925 }
2926 
2927 /// ParseExpressionListOrTypeId - Parse either an expression-list or a type-id.
2928 /// This ambiguity appears in the syntax of the C++ new operator.
2929 ///
2930 /// new-expression:
2931 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2932 /// new-initializer[opt]
2933 ///
2934 /// new-placement:
2935 /// '(' expression-list ')'
2936 ///
2937 bool Parser::ParseExpressionListOrTypeId(
2938  SmallVectorImpl<Expr*> &PlacementArgs,
2939  Declarator &D) {
2940  // The '(' was already consumed.
2941  if (isTypeIdInParens()) {
2942  ParseSpecifierQualifierList(D.getMutableDeclSpec());
2944  ParseDeclarator(D);
2945  return D.isInvalidType();
2946  }
2947 
2948  // It's not a type, it has to be an expression list.
2949  // Discard the comma locations - ActOnCXXNew has enough parameters.
2950  CommaLocsTy CommaLocs;
2951  return ParseExpressionList(PlacementArgs, CommaLocs);
2952 }
2953 
2954 /// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used
2955 /// to free memory allocated by new.
2956 ///
2957 /// This method is called to parse the 'delete' expression after the optional
2958 /// '::' has been already parsed. If the '::' was present, "UseGlobal" is true
2959 /// and "Start" is its location. Otherwise, "Start" is the location of the
2960 /// 'delete' token.
2961 ///
2962 /// delete-expression:
2963 /// '::'[opt] 'delete' cast-expression
2964 /// '::'[opt] 'delete' '[' ']' cast-expression
2965 ExprResult
2966 Parser::ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start) {
2967  assert(Tok.is(tok::kw_delete) && "Expected 'delete' keyword");
2968  ConsumeToken(); // Consume 'delete'
2969 
2970  // Array delete?
2971  bool ArrayDelete = false;
2972  if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) {
2973  // C++11 [expr.delete]p1:
2974  // Whenever the delete keyword is followed by empty square brackets, it
2975  // shall be interpreted as [array delete].
2976  // [Footnote: A lambda expression with a lambda-introducer that consists
2977  // of empty square brackets can follow the delete keyword if
2978  // the lambda expression is enclosed in parentheses.]
2979  // FIXME: Produce a better diagnostic if the '[]' is unambiguously a
2980  // lambda-introducer.
2981  ArrayDelete = true;
2982  BalancedDelimiterTracker T(*this, tok::l_square);
2983 
2984  T.consumeOpen();
2985  T.consumeClose();
2986  if (T.getCloseLocation().isInvalid())
2987  return ExprError();
2988  }
2989 
2990  ExprResult Operand(ParseCastExpression(false));
2991  if (Operand.isInvalid())
2992  return Operand;
2993 
2994  return Actions.ActOnCXXDelete(Start, UseGlobal, ArrayDelete, Operand.get());
2995 }
2996 
2998  switch (kind) {
2999  default: llvm_unreachable("Not a known type trait");
3000 #define TYPE_TRAIT_1(Spelling, Name, Key) \
3001 case tok::kw_ ## Spelling: return UTT_ ## Name;
3002 #define TYPE_TRAIT_2(Spelling, Name, Key) \
3003 case tok::kw_ ## Spelling: return BTT_ ## Name;
3004 #include "clang/Basic/TokenKinds.def"
3005 #define TYPE_TRAIT_N(Spelling, Name, Key) \
3006  case tok::kw_ ## Spelling: return TT_ ## Name;
3007 #include "clang/Basic/TokenKinds.def"
3008  }
3009 }
3010 
3012  switch(kind) {
3013  default: llvm_unreachable("Not a known binary type trait");
3014  case tok::kw___array_rank: return ATT_ArrayRank;
3015  case tok::kw___array_extent: return ATT_ArrayExtent;
3016  }
3017 }
3018 
3020  switch(kind) {
3021  default: llvm_unreachable("Not a known unary expression trait.");
3022  case tok::kw___is_lvalue_expr: return ET_IsLValueExpr;
3023  case tok::kw___is_rvalue_expr: return ET_IsRValueExpr;
3024  }
3025 }
3026 
3028  switch (kind) {
3029  default: llvm_unreachable("Not a known type trait");
3030 #define TYPE_TRAIT(N,Spelling,K) case tok::kw_##Spelling: return N;
3031 #include "clang/Basic/TokenKinds.def"
3032  }
3033 }
3034 
3035 /// Parse the built-in type-trait pseudo-functions that allow
3036 /// implementation of the TR1/C++11 type traits templates.
3037 ///
3038 /// primary-expression:
3039 /// unary-type-trait '(' type-id ')'
3040 /// binary-type-trait '(' type-id ',' type-id ')'
3041 /// type-trait '(' type-id-seq ')'
3042 ///
3043 /// type-id-seq:
3044 /// type-id ...[opt] type-id-seq[opt]
3045 ///
3046 ExprResult Parser::ParseTypeTrait() {
3047  tok::TokenKind Kind = Tok.getKind();
3048  unsigned Arity = TypeTraitArity(Kind);
3049 
3050  SourceLocation Loc = ConsumeToken();
3051 
3052  BalancedDelimiterTracker Parens(*this, tok::l_paren);
3053  if (Parens.expectAndConsume())
3054  return ExprError();
3055 
3057  do {
3058  // Parse the next type.
3059  TypeResult Ty = ParseTypeName();
3060  if (Ty.isInvalid()) {
3061  Parens.skipToEnd();
3062  return ExprError();
3063  }
3064 
3065  // Parse the ellipsis, if present.
3066  if (Tok.is(tok::ellipsis)) {
3067  Ty = Actions.ActOnPackExpansion(Ty.get(), ConsumeToken());
3068  if (Ty.isInvalid()) {
3069  Parens.skipToEnd();
3070  return ExprError();
3071  }
3072  }
3073 
3074  // Add this type to the list of arguments.
3075  Args.push_back(Ty.get());
3076  } while (TryConsumeToken(tok::comma));
3077 
3078  if (Parens.consumeClose())
3079  return ExprError();
3080 
3081  SourceLocation EndLoc = Parens.getCloseLocation();
3082 
3083  if (Arity && Args.size() != Arity) {
3084  Diag(EndLoc, diag::err_type_trait_arity)
3085  << Arity << 0 << (Arity > 1) << (int)Args.size() << SourceRange(Loc);
3086  return ExprError();
3087  }
3088 
3089  if (!Arity && Args.empty()) {
3090  Diag(EndLoc, diag::err_type_trait_arity)
3091  << 1 << 1 << 1 << (int)Args.size() << SourceRange(Loc);
3092  return ExprError();
3093  }
3094 
3095  return Actions.ActOnTypeTrait(TypeTraitFromTokKind(Kind), Loc, Args, EndLoc);
3096 }
3097 
3098 /// ParseArrayTypeTrait - Parse the built-in array type-trait
3099 /// pseudo-functions.
3100 ///
3101 /// primary-expression:
3102 /// [Embarcadero] '__array_rank' '(' type-id ')'
3103 /// [Embarcadero] '__array_extent' '(' type-id ',' expression ')'
3104 ///
3105 ExprResult Parser::ParseArrayTypeTrait() {
3107  SourceLocation Loc = ConsumeToken();
3108 
3109  BalancedDelimiterTracker T(*this, tok::l_paren);
3110  if (T.expectAndConsume())
3111  return ExprError();
3112 
3113  TypeResult Ty = ParseTypeName();
3114  if (Ty.isInvalid()) {
3115  SkipUntil(tok::comma, StopAtSemi);
3116  SkipUntil(tok::r_paren, StopAtSemi);
3117  return ExprError();
3118  }
3119 
3120  switch (ATT) {
3121  case ATT_ArrayRank: {
3122  T.consumeClose();
3123  return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), nullptr,
3124  T.getCloseLocation());
3125  }
3126  case ATT_ArrayExtent: {
3127  if (ExpectAndConsume(tok::comma)) {
3128  SkipUntil(tok::r_paren, StopAtSemi);
3129  return ExprError();
3130  }
3131 
3132  ExprResult DimExpr = ParseExpression();
3133  T.consumeClose();
3134 
3135  return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), DimExpr.get(),
3136  T.getCloseLocation());
3137  }
3138  }
3139  llvm_unreachable("Invalid ArrayTypeTrait!");
3140 }
3141 
3142 /// ParseExpressionTrait - Parse built-in expression-trait
3143 /// pseudo-functions like __is_lvalue_expr( xxx ).
3144 ///
3145 /// primary-expression:
3146 /// [Embarcadero] expression-trait '(' expression ')'
3147 ///
3148 ExprResult Parser::ParseExpressionTrait() {
3150  SourceLocation Loc = ConsumeToken();
3151 
3152  BalancedDelimiterTracker T(*this, tok::l_paren);
3153  if (T.expectAndConsume())
3154  return ExprError();
3155 
3157 
3158  T.consumeClose();
3159 
3160  return Actions.ActOnExpressionTrait(ET, Loc, Expr.get(),
3161  T.getCloseLocation());
3162 }
3163 
3164 
3165 /// ParseCXXAmbiguousParenExpression - We have parsed the left paren of a
3166 /// parenthesized ambiguous type-id. This uses tentative parsing to disambiguate
3167 /// based on the context past the parens.
3168 ExprResult
3169 Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType,
3170  ParsedType &CastTy,
3171  BalancedDelimiterTracker &Tracker,
3172  ColonProtectionRAIIObject &ColonProt) {
3173  assert(getLangOpts().CPlusPlus && "Should only be called for C++!");
3174  assert(ExprType == CastExpr && "Compound literals are not ambiguous!");
3175  assert(isTypeIdInParens() && "Not a type-id!");
3176 
3177  ExprResult Result(true);
3178  CastTy = nullptr;
3179 
3180  // We need to disambiguate a very ugly part of the C++ syntax:
3181  //
3182  // (T())x; - type-id
3183  // (T())*x; - type-id
3184  // (T())/x; - expression
3185  // (T()); - expression
3186  //
3187  // The bad news is that we cannot use the specialized tentative parser, since
3188  // it can only verify that the thing inside the parens can be parsed as
3189  // type-id, it is not useful for determining the context past the parens.
3190  //
3191  // The good news is that the parser can disambiguate this part without
3192  // making any unnecessary Action calls.
3193  //
3194  // It uses a scheme similar to parsing inline methods. The parenthesized
3195  // tokens are cached, the context that follows is determined (possibly by
3196  // parsing a cast-expression), and then we re-introduce the cached tokens
3197  // into the token stream and parse them appropriately.
3198 
3199  ParenParseOption ParseAs;
3200  CachedTokens Toks;
3201 
3202  // Store the tokens of the parentheses. We will parse them after we determine
3203  // the context that follows them.
3204  if (!ConsumeAndStoreUntil(tok::r_paren, Toks)) {
3205  // We didn't find the ')' we expected.
3206  Tracker.consumeClose();
3207  return ExprError();
3208  }
3209 
3210  if (Tok.is(tok::l_brace)) {
3211  ParseAs = CompoundLiteral;
3212  } else {
3213  bool NotCastExpr;
3214  if (Tok.is(tok::l_paren) && NextToken().is(tok::r_paren)) {
3215  NotCastExpr = true;
3216  } else {
3217  // Try parsing the cast-expression that may follow.
3218  // If it is not a cast-expression, NotCastExpr will be true and no token
3219  // will be consumed.
3220  ColonProt.restore();
3221  Result = ParseCastExpression(false/*isUnaryExpression*/,
3222  false/*isAddressofOperand*/,
3223  NotCastExpr,
3224  // type-id has priority.
3225  IsTypeCast);
3226  }
3227 
3228  // If we parsed a cast-expression, it's really a type-id, otherwise it's
3229  // an expression.
3230  ParseAs = NotCastExpr ? SimpleExpr : CastExpr;
3231  }
3232 
3233  // Create a fake EOF to mark end of Toks buffer.
3234  Token AttrEnd;
3235  AttrEnd.startToken();
3236  AttrEnd.setKind(tok::eof);
3237  AttrEnd.setLocation(Tok.getLocation());
3238  AttrEnd.setEofData(Toks.data());
3239  Toks.push_back(AttrEnd);
3240 
3241  // The current token should go after the cached tokens.
3242  Toks.push_back(Tok);
3243  // Re-enter the stored parenthesized tokens into the token stream, so we may
3244  // parse them now.
3245  PP.EnterTokenStream(Toks, true /*DisableMacroExpansion*/);
3246  // Drop the current token and bring the first cached one. It's the same token
3247  // as when we entered this function.
3248  ConsumeAnyToken();
3249 
3250  if (ParseAs >= CompoundLiteral) {
3251  // Parse the type declarator.
3252  DeclSpec DS(AttrFactory);
3253  Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
3254  {
3255  ColonProtectionRAIIObject InnerColonProtection(*this);
3256  ParseSpecifierQualifierList(DS);
3257  ParseDeclarator(DeclaratorInfo);
3258  }
3259 
3260  // Match the ')'.
3261  Tracker.consumeClose();
3262  ColonProt.restore();
3263 
3264  // Consume EOF marker for Toks buffer.
3265  assert(Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData());
3266  ConsumeAnyToken();
3267 
3268  if (ParseAs == CompoundLiteral) {
3269  ExprType = CompoundLiteral;
3270  if (DeclaratorInfo.isInvalidType())
3271  return ExprError();
3272 
3273  TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
3274  return ParseCompoundLiteralExpression(Ty.get(),
3275  Tracker.getOpenLocation(),
3276  Tracker.getCloseLocation());
3277  }
3278 
3279  // We parsed '(' type-id ')' and the thing after it wasn't a '{'.
3280  assert(ParseAs == CastExpr);
3281 
3282  if (DeclaratorInfo.isInvalidType())
3283  return ExprError();
3284 
3285  // Result is what ParseCastExpression returned earlier.
3286  if (!Result.isInvalid())
3287  Result = Actions.ActOnCastExpr(getCurScope(), Tracker.getOpenLocation(),
3288  DeclaratorInfo, CastTy,
3289  Tracker.getCloseLocation(), Result.get());
3290  return Result;
3291  }
3292 
3293  // Not a compound literal, and not followed by a cast-expression.
3294  assert(ParseAs == SimpleExpr);
3295 
3296  ExprType = SimpleExpr;
3297  Result = ParseExpression();
3298  if (!Result.isInvalid() && Tok.is(tok::r_paren))
3299  Result = Actions.ActOnParenExpr(Tracker.getOpenLocation(),
3300  Tok.getLocation(), Result.get());
3301 
3302  // Match the ')'.
3303  if (Result.isInvalid()) {
3304  while (Tok.isNot(tok::eof))
3305  ConsumeAnyToken();
3306  assert(Tok.getEofData() == AttrEnd.getEofData());
3307  ConsumeAnyToken();
3308  return ExprError();
3309  }
3310 
3311  Tracker.consumeClose();
3312  // Consume EOF marker for Toks buffer.
3313  assert(Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData());
3314  ConsumeAnyToken();
3315  return Result;
3316 }
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:15880
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
StringRef Identifier
Definition: Format.cpp:1627
ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, Declarator &D, ParsedType &Ty, SourceLocation RParenLoc, Expr *CastExpr)
Definition: SemaExpr.cpp:6206
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.
A (possibly-)qualified type.
Definition: Type.h:642
Keeps information about an identifier in a nested-name-spec.
Definition: Sema.h:5360
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)
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:6379
SourceLocation TemplateNameLoc
TemplateNameLoc - The location of the template name within the source.
static ConditionResult ConditionError()
Definition: Sema.h:9863
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:87
bool isCodeCompletionReached() const
Returns true if code-completion is enabled and we have hit the code-completion point.
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:978
void CodeCompleteExpression(Scope *S, const CodeCompleteExpressionData &Data)
Perform code-completion in an expression context when we know what type we&#39;re looking for...
Defines the C++ template declaration subclasses.
StringRef P
The base class of the type hierarchy.
Definition: Type.h:1415
SourceLocation getCloseLocation() const
This indicates that the scope corresponds to a function, which means that labels are set here...
Definition: Scope.h:47
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclSpec.h:1874
void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, bool EnteringContext)
Parser - This implements a parser for the C family of languages.
Definition: Parser.h:57
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:10796
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:1748
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
RAII object that makes sure paren/bracket/brace count is correct after declaration/statement parsing...
ColonProtectionRAIIObject - This sets the Parser::ColonIsSacred bool and restores it when destroyed...
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:1050
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:718
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:419
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:1570
static const TST TST_char8
Definition: DeclSpec.h:276
ExprResult ExprEmpty()
Definition: Ownership.h:289
void setConversionFunctionId(SourceLocation OperatorLoc, ParsedType Ty, SourceLocation EndLoc)
Specify that this unqualified-id was parsed as a conversion-function-id.
Definition: DeclSpec.h:1036
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:280
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)
A user-defined literal name, e.g., operator "" _i.
void SetSourceRange(SourceRange R)
Definition: DeclSpec.h:1876
bool isInvalidType() const
Definition: DeclSpec.h:2426
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:723
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:11358
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...
QualType ProduceConstructorSignatureHelp(Scope *S, QualType Type, SourceLocation Loc, ArrayRef< Expr *> Args, SourceLocation OpenParLoc)
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:663
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:2790
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:439
void setTemplateId(TemplateIdAnnotation *TemplateId)
Specify that this unqualified-id was parsed as a template-id.
Definition: DeclSpec.cpp:31
LambdaCaptureInitKind
Definition: DeclSpec.h:2524
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:1844
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
void addCapture(LambdaCaptureKind Kind, SourceLocation Loc, IdentifierInfo *Id, SourceLocation EllipsisLoc, LambdaCaptureInitKind InitKind, ExprResult Init, ParsedType InitCaptureType, SourceRange ExplicitRange)
Append a capture in a lambda introducer.
Definition: DeclSpec.h:2563
SourceRange getRange() const
Definition: DeclSpec.h:68
SmallVector< LambdaCapture, 4 > Captures
Definition: DeclSpec.h:2557
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...
This represents one expression.
Definition: Expr.h:105
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...
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:5673
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:372
OpaquePtr< TemplateName > TemplateTy
Definition: Parser.h:383
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:2413
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:9865
bool isInvalid() const
Definition: Ownership.h:170
SourceLocation getEnd() const
bool SetTypeSpecSign(TSS S, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID)
Definition: DeclSpec.cpp:660
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:1393
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:1490
bool isValid() const
Determine whether this unqualified-id refers to a valid name.
Definition: DeclSpec.h:996
OpaquePtr< DeclGroupRef > DeclGroupPtrTy
Definition: Parser.h:382
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:293
const LangOptions & getLangOpts() const
Definition: Parser.h:366
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:633
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:3566
SourceManager & getSourceManager() const
Definition: Preprocessor.h:831
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:2555
Kind
Stop skipping at semicolon.
Definition: Parser.h:1030
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:1220
static const TST TST_float16
Definition: DeclSpec.h:284
Encodes a location in the source.
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:11929
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...
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclSpec.h:509
IdentifierInfo * getIdentifierInfo() const
Definition: Token.h:177
void setAnnotationEndLoc(SourceLocation L)
Definition: Token.h:142
IdentifierTable & getIdentifierTable()
Definition: Preprocessor.h:835
ParsedAttr - Represents a syntactic attribute.
Definition: ParsedAttr.h:117
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:235
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:373
static DeclaratorChunk getArray(unsigned TypeQuals, bool isStatic, bool isStar, Expr *NumElts, SourceLocation LBLoc, SourceLocation RBLoc)
Return a DeclaratorChunk for an array.
Definition: DeclSpec.h:1555
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:1872
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:2556
bool expectAndConsume(unsigned DiagID=diag::err_expected, const char *Msg="", tok::TokenKind SkipToTok=tok::unknown)
Definition: Parser.cpp:2256
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:1399
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 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:10941
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...
ParsedType getConstructorName(IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec &SS, bool EnteringContext)
Definition: SemaExprCXX.cpp:83
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:829
QualType getCanonicalTypeInternal() const
Definition: Type.h:2354
void takeAttributesFrom(ParsedAttributes &attrs)
Definition: DeclSpec.h:751
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Definition: Parser.cpp:73
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:1303
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:1884
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
void AddTypeInfo(const DeclaratorChunk &TI, ParsedAttributes &&attrs, SourceLocation EndLoc)
AddTypeInfo - Add a chunk to this declarator.
Definition: DeclSpec.h:2133
ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E)
Capturing the *this object by reference.
Definition: Lambda.h:35
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:749
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:2033
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:2425
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:411
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:1837
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:1004
Represents a complete lambda introducer.
Definition: DeclSpec.h:2532
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:10264
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:843
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
void SetRangeEnd(SourceLocation Loc)
Definition: DeclSpec.h:615
SourceLocation getBegin() const
ParsedAttributes - A collection of parsed attributes.
Definition: ParsedAttr.h:850
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:418
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:5556
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:1032