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