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