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