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