Clang Project

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