Home | History | Annotate | Download | only in Parse
      1 //===--- ParseDeclCXX.cpp - C++ Declaration Parsing -------------*- C++ -*-===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 //  This file implements the C++ Declaration portions of the Parser interfaces.
     11 //
     12 //===----------------------------------------------------------------------===//
     13 
     14 #include "clang/Parse/Parser.h"
     15 #include "RAIIObjectsForParser.h"
     16 #include "clang/AST/ASTContext.h"
     17 #include "clang/AST/DeclTemplate.h"
     18 #include "clang/Basic/Attributes.h"
     19 #include "clang/Basic/CharInfo.h"
     20 #include "clang/Basic/OperatorKinds.h"
     21 #include "clang/Basic/TargetInfo.h"
     22 #include "clang/Parse/ParseDiagnostic.h"
     23 #include "clang/Sema/DeclSpec.h"
     24 #include "clang/Sema/ParsedTemplate.h"
     25 #include "clang/Sema/PrettyDeclStackTrace.h"
     26 #include "clang/Sema/Scope.h"
     27 #include "clang/Sema/SemaDiagnostic.h"
     28 #include "llvm/ADT/SmallString.h"
     29 
     30 using namespace clang;
     31 
     32 /// ParseNamespace - We know that the current token is a namespace keyword. This
     33 /// may either be a top level namespace or a block-level namespace alias. If
     34 /// there was an inline keyword, it has already been parsed.
     35 ///
     36 ///       namespace-definition: [C++ 7.3: basic.namespace]
     37 ///         named-namespace-definition
     38 ///         unnamed-namespace-definition
     39 ///
     40 ///       unnamed-namespace-definition:
     41 ///         'inline'[opt] 'namespace' attributes[opt] '{' namespace-body '}'
     42 ///
     43 ///       named-namespace-definition:
     44 ///         original-namespace-definition
     45 ///         extension-namespace-definition
     46 ///
     47 ///       original-namespace-definition:
     48 ///         'inline'[opt] 'namespace' identifier attributes[opt]
     49 ///             '{' namespace-body '}'
     50 ///
     51 ///       extension-namespace-definition:
     52 ///         'inline'[opt] 'namespace' original-namespace-name
     53 ///             '{' namespace-body '}'
     54 ///
     55 ///       namespace-alias-definition:  [C++ 7.3.2: namespace.alias]
     56 ///         'namespace' identifier '=' qualified-namespace-specifier ';'
     57 ///
     58 Parser::DeclGroupPtrTy Parser::ParseNamespace(unsigned Context,
     59                                               SourceLocation &DeclEnd,
     60                                               SourceLocation InlineLoc) {
     61   assert(Tok.is(tok::kw_namespace) && "Not a namespace!");
     62   SourceLocation NamespaceLoc = ConsumeToken();  // eat the 'namespace'.
     63   ObjCDeclContextSwitch ObjCDC(*this);
     64 
     65   if (Tok.is(tok::code_completion)) {
     66     Actions.CodeCompleteNamespaceDecl(getCurScope());
     67     cutOffParsing();
     68     return nullptr;
     69   }
     70 
     71   SourceLocation IdentLoc;
     72   IdentifierInfo *Ident = nullptr;
     73   std::vector<SourceLocation> ExtraIdentLoc;
     74   std::vector<IdentifierInfo*> ExtraIdent;
     75   std::vector<SourceLocation> ExtraNamespaceLoc;
     76 
     77   ParsedAttributesWithRange attrs(AttrFactory);
     78   SourceLocation attrLoc;
     79   if (getLangOpts().CPlusPlus11 && isCXX11AttributeSpecifier()) {
     80     if (!getLangOpts().CPlusPlus1z)
     81       Diag(Tok.getLocation(), diag::warn_cxx14_compat_attribute)
     82           << 0 /*namespace*/;
     83     attrLoc = Tok.getLocation();
     84     ParseCXX11Attributes(attrs);
     85   }
     86 
     87   if (Tok.is(tok::identifier)) {
     88     Ident = Tok.getIdentifierInfo();
     89     IdentLoc = ConsumeToken();  // eat the identifier.
     90     while (Tok.is(tok::coloncolon) && NextToken().is(tok::identifier)) {
     91       ExtraNamespaceLoc.push_back(ConsumeToken());
     92       ExtraIdent.push_back(Tok.getIdentifierInfo());
     93       ExtraIdentLoc.push_back(ConsumeToken());
     94     }
     95   }
     96 
     97   // A nested namespace definition cannot have attributes.
     98   if (!ExtraNamespaceLoc.empty() && attrLoc.isValid())
     99     Diag(attrLoc, diag::err_unexpected_nested_namespace_attribute);
    100 
    101   // Read label attributes, if present.
    102   if (Tok.is(tok::kw___attribute)) {
    103     attrLoc = Tok.getLocation();
    104     ParseGNUAttributes(attrs);
    105   }
    106 
    107   if (Tok.is(tok::equal)) {
    108     if (!Ident) {
    109       Diag(Tok, diag::err_expected) << tok::identifier;
    110       // Skip to end of the definition and eat the ';'.
    111       SkipUntil(tok::semi);
    112       return nullptr;
    113     }
    114     if (attrLoc.isValid())
    115       Diag(attrLoc, diag::err_unexpected_namespace_attributes_alias);
    116     if (InlineLoc.isValid())
    117       Diag(InlineLoc, diag::err_inline_namespace_alias)
    118           << FixItHint::CreateRemoval(InlineLoc);
    119     Decl *NSAlias = ParseNamespaceAlias(NamespaceLoc, IdentLoc, Ident, DeclEnd);
    120     return Actions.ConvertDeclToDeclGroup(NSAlias);
    121 }
    122 
    123   BalancedDelimiterTracker T(*this, tok::l_brace);
    124   if (T.consumeOpen()) {
    125     if (Ident)
    126       Diag(Tok, diag::err_expected) << tok::l_brace;
    127     else
    128       Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace;
    129     return nullptr;
    130   }
    131 
    132   if (getCurScope()->isClassScope() || getCurScope()->isTemplateParamScope() ||
    133       getCurScope()->isInObjcMethodScope() || getCurScope()->getBlockParent() ||
    134       getCurScope()->getFnParent()) {
    135     Diag(T.getOpenLocation(), diag::err_namespace_nonnamespace_scope);
    136     SkipUntil(tok::r_brace);
    137     return nullptr;
    138   }
    139 
    140   if (ExtraIdent.empty()) {
    141     // Normal namespace definition, not a nested-namespace-definition.
    142   } else if (InlineLoc.isValid()) {
    143     Diag(InlineLoc, diag::err_inline_nested_namespace_definition);
    144   } else if (getLangOpts().CPlusPlus1z) {
    145     Diag(ExtraNamespaceLoc[0],
    146          diag::warn_cxx14_compat_nested_namespace_definition);
    147   } else {
    148     TentativeParsingAction TPA(*this);
    149     SkipUntil(tok::r_brace, StopBeforeMatch);
    150     Token rBraceToken = Tok;
    151     TPA.Revert();
    152 
    153     if (!rBraceToken.is(tok::r_brace)) {
    154       Diag(ExtraNamespaceLoc[0], diag::ext_nested_namespace_definition)
    155           << SourceRange(ExtraNamespaceLoc.front(), ExtraIdentLoc.back());
    156     } else {
    157       std::string NamespaceFix;
    158       for (std::vector<IdentifierInfo*>::iterator I = ExtraIdent.begin(),
    159            E = ExtraIdent.end(); I != E; ++I) {
    160         NamespaceFix += " { namespace ";
    161         NamespaceFix += (*I)->getName();
    162       }
    163 
    164       std::string RBraces;
    165       for (unsigned i = 0, e = ExtraIdent.size(); i != e; ++i)
    166         RBraces +=  "} ";
    167 
    168       Diag(ExtraNamespaceLoc[0], diag::ext_nested_namespace_definition)
    169           << FixItHint::CreateReplacement(SourceRange(ExtraNamespaceLoc.front(),
    170                                                       ExtraIdentLoc.back()),
    171                                           NamespaceFix)
    172           << FixItHint::CreateInsertion(rBraceToken.getLocation(), RBraces);
    173     }
    174   }
    175 
    176   // If we're still good, complain about inline namespaces in non-C++0x now.
    177   if (InlineLoc.isValid())
    178     Diag(InlineLoc, getLangOpts().CPlusPlus11 ?
    179          diag::warn_cxx98_compat_inline_namespace : diag::ext_inline_namespace);
    180 
    181   // Enter a scope for the namespace.
    182   ParseScope NamespaceScope(this, Scope::DeclScope);
    183 
    184   UsingDirectiveDecl *ImplicitUsingDirectiveDecl = nullptr;
    185   Decl *NamespcDecl =
    186     Actions.ActOnStartNamespaceDef(getCurScope(), InlineLoc, NamespaceLoc,
    187                                    IdentLoc, Ident, T.getOpenLocation(),
    188                                    attrs.getList(), ImplicitUsingDirectiveDecl);
    189 
    190   PrettyDeclStackTraceEntry CrashInfo(Actions, NamespcDecl, NamespaceLoc,
    191                                       "parsing namespace");
    192 
    193   // Parse the contents of the namespace.  This includes parsing recovery on
    194   // any improperly nested namespaces.
    195   ParseInnerNamespace(ExtraIdentLoc, ExtraIdent, ExtraNamespaceLoc, 0,
    196                       InlineLoc, attrs, T);
    197 
    198   // Leave the namespace scope.
    199   NamespaceScope.Exit();
    200 
    201   DeclEnd = T.getCloseLocation();
    202   Actions.ActOnFinishNamespaceDef(NamespcDecl, DeclEnd);
    203 
    204   return Actions.ConvertDeclToDeclGroup(NamespcDecl,
    205                                         ImplicitUsingDirectiveDecl);
    206 }
    207 
    208 /// ParseInnerNamespace - Parse the contents of a namespace.
    209 void Parser::ParseInnerNamespace(std::vector<SourceLocation> &IdentLoc,
    210                                  std::vector<IdentifierInfo *> &Ident,
    211                                  std::vector<SourceLocation> &NamespaceLoc,
    212                                  unsigned int index, SourceLocation &InlineLoc,
    213                                  ParsedAttributes &attrs,
    214                                  BalancedDelimiterTracker &Tracker) {
    215   if (index == Ident.size()) {
    216     while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
    217            Tok.isNot(tok::eof)) {
    218       ParsedAttributesWithRange attrs(AttrFactory);
    219       MaybeParseCXX11Attributes(attrs);
    220       MaybeParseMicrosoftAttributes(attrs);
    221       ParseExternalDeclaration(attrs);
    222     }
    223 
    224     // The caller is what called check -- we are simply calling
    225     // the close for it.
    226     Tracker.consumeClose();
    227 
    228     return;
    229   }
    230 
    231   // Handle a nested namespace definition.
    232   // FIXME: Preserve the source information through to the AST rather than
    233   // desugaring it here.
    234   ParseScope NamespaceScope(this, Scope::DeclScope);
    235   UsingDirectiveDecl *ImplicitUsingDirectiveDecl = nullptr;
    236   Decl *NamespcDecl =
    237     Actions.ActOnStartNamespaceDef(getCurScope(), SourceLocation(),
    238                                    NamespaceLoc[index], IdentLoc[index],
    239                                    Ident[index], Tracker.getOpenLocation(),
    240                                    attrs.getList(), ImplicitUsingDirectiveDecl);
    241   assert(!ImplicitUsingDirectiveDecl &&
    242          "nested namespace definition cannot define anonymous namespace");
    243 
    244   ParseInnerNamespace(IdentLoc, Ident, NamespaceLoc, ++index, InlineLoc,
    245                       attrs, Tracker);
    246 
    247   NamespaceScope.Exit();
    248   Actions.ActOnFinishNamespaceDef(NamespcDecl, Tracker.getCloseLocation());
    249 }
    250 
    251 /// ParseNamespaceAlias - Parse the part after the '=' in a namespace
    252 /// alias definition.
    253 ///
    254 Decl *Parser::ParseNamespaceAlias(SourceLocation NamespaceLoc,
    255                                   SourceLocation AliasLoc,
    256                                   IdentifierInfo *Alias,
    257                                   SourceLocation &DeclEnd) {
    258   assert(Tok.is(tok::equal) && "Not equal token");
    259 
    260   ConsumeToken(); // eat the '='.
    261 
    262   if (Tok.is(tok::code_completion)) {
    263     Actions.CodeCompleteNamespaceAliasDecl(getCurScope());
    264     cutOffParsing();
    265     return nullptr;
    266   }
    267 
    268   CXXScopeSpec SS;
    269   // Parse (optional) nested-name-specifier.
    270   ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false);
    271 
    272   if (SS.isInvalid() || Tok.isNot(tok::identifier)) {
    273     Diag(Tok, diag::err_expected_namespace_name);
    274     // Skip to end of the definition and eat the ';'.
    275     SkipUntil(tok::semi);
    276     return nullptr;
    277   }
    278 
    279   // Parse identifier.
    280   IdentifierInfo *Ident = Tok.getIdentifierInfo();
    281   SourceLocation IdentLoc = ConsumeToken();
    282 
    283   // Eat the ';'.
    284   DeclEnd = Tok.getLocation();
    285   if (ExpectAndConsume(tok::semi, diag::err_expected_semi_after_namespace_name))
    286     SkipUntil(tok::semi);
    287 
    288   return Actions.ActOnNamespaceAliasDef(getCurScope(), NamespaceLoc, AliasLoc,
    289                                         Alias, SS, IdentLoc, Ident);
    290 }
    291 
    292 /// ParseLinkage - We know that the current token is a string_literal
    293 /// and just before that, that extern was seen.
    294 ///
    295 ///       linkage-specification: [C++ 7.5p2: dcl.link]
    296 ///         'extern' string-literal '{' declaration-seq[opt] '}'
    297 ///         'extern' string-literal declaration
    298 ///
    299 Decl *Parser::ParseLinkage(ParsingDeclSpec &DS, unsigned Context) {
    300   assert(isTokenStringLiteral() && "Not a string literal!");
    301   ExprResult Lang = ParseStringLiteralExpression(false);
    302 
    303   ParseScope LinkageScope(this, Scope::DeclScope);
    304   Decl *LinkageSpec =
    305       Lang.isInvalid()
    306           ? nullptr
    307           : Actions.ActOnStartLinkageSpecification(
    308                 getCurScope(), DS.getSourceRange().getBegin(), Lang.get(),
    309                 Tok.is(tok::l_brace) ? Tok.getLocation() : SourceLocation());
    310 
    311   ParsedAttributesWithRange attrs(AttrFactory);
    312   MaybeParseCXX11Attributes(attrs);
    313   MaybeParseMicrosoftAttributes(attrs);
    314 
    315   if (Tok.isNot(tok::l_brace)) {
    316     // Reset the source range in DS, as the leading "extern"
    317     // does not really belong to the inner declaration ...
    318     DS.SetRangeStart(SourceLocation());
    319     DS.SetRangeEnd(SourceLocation());
    320     // ... but anyway remember that such an "extern" was seen.
    321     DS.setExternInLinkageSpec(true);
    322     ParseExternalDeclaration(attrs, &DS);
    323     return LinkageSpec ? Actions.ActOnFinishLinkageSpecification(
    324                              getCurScope(), LinkageSpec, SourceLocation())
    325                        : nullptr;
    326   }
    327 
    328   DS.abort();
    329 
    330   ProhibitAttributes(attrs);
    331 
    332   BalancedDelimiterTracker T(*this, tok::l_brace);
    333   T.consumeOpen();
    334 
    335   unsigned NestedModules = 0;
    336   while (true) {
    337     switch (Tok.getKind()) {
    338     case tok::annot_module_begin:
    339       ++NestedModules;
    340       ParseTopLevelDecl();
    341       continue;
    342 
    343     case tok::annot_module_end:
    344       if (!NestedModules)
    345         break;
    346       --NestedModules;
    347       ParseTopLevelDecl();
    348       continue;
    349 
    350     case tok::annot_module_include:
    351       ParseTopLevelDecl();
    352       continue;
    353 
    354     case tok::eof:
    355       break;
    356 
    357     case tok::r_brace:
    358       if (!NestedModules)
    359         break;
    360       // Fall through.
    361     default:
    362       ParsedAttributesWithRange attrs(AttrFactory);
    363       MaybeParseCXX11Attributes(attrs);
    364       MaybeParseMicrosoftAttributes(attrs);
    365       ParseExternalDeclaration(attrs);
    366       continue;
    367     }
    368 
    369     break;
    370   }
    371 
    372   T.consumeClose();
    373   return LinkageSpec ? Actions.ActOnFinishLinkageSpecification(
    374                            getCurScope(), LinkageSpec, T.getCloseLocation())
    375                      : nullptr;
    376 }
    377 
    378 /// ParseUsingDirectiveOrDeclaration - Parse C++ using using-declaration or
    379 /// using-directive. Assumes that current token is 'using'.
    380 Decl *Parser::ParseUsingDirectiveOrDeclaration(unsigned Context,
    381                                          const ParsedTemplateInfo &TemplateInfo,
    382                                                SourceLocation &DeclEnd,
    383                                              ParsedAttributesWithRange &attrs,
    384                                                Decl **OwnedType) {
    385   assert(Tok.is(tok::kw_using) && "Not using token");
    386   ObjCDeclContextSwitch ObjCDC(*this);
    387 
    388   // Eat 'using'.
    389   SourceLocation UsingLoc = ConsumeToken();
    390 
    391   if (Tok.is(tok::code_completion)) {
    392     Actions.CodeCompleteUsing(getCurScope());
    393     cutOffParsing();
    394     return nullptr;
    395   }
    396 
    397   // 'using namespace' means this is a using-directive.
    398   if (Tok.is(tok::kw_namespace)) {
    399     // Template parameters are always an error here.
    400     if (TemplateInfo.Kind) {
    401       SourceRange R = TemplateInfo.getSourceRange();
    402       Diag(UsingLoc, diag::err_templated_using_directive_declaration)
    403         << 0 /* directive */ << R << FixItHint::CreateRemoval(R);
    404     }
    405 
    406     return ParseUsingDirective(Context, UsingLoc, DeclEnd, attrs);
    407   }
    408 
    409   // Otherwise, it must be a using-declaration or an alias-declaration.
    410 
    411   // Using declarations can't have attributes.
    412   ProhibitAttributes(attrs);
    413 
    414   return ParseUsingDeclaration(Context, TemplateInfo, UsingLoc, DeclEnd,
    415                                     AS_none, OwnedType);
    416 }
    417 
    418 /// ParseUsingDirective - Parse C++ using-directive, assumes
    419 /// that current token is 'namespace' and 'using' was already parsed.
    420 ///
    421 ///       using-directive: [C++ 7.3.p4: namespace.udir]
    422 ///        'using' 'namespace' ::[opt] nested-name-specifier[opt]
    423 ///                 namespace-name ;
    424 /// [GNU] using-directive:
    425 ///        'using' 'namespace' ::[opt] nested-name-specifier[opt]
    426 ///                 namespace-name attributes[opt] ;
    427 ///
    428 Decl *Parser::ParseUsingDirective(unsigned Context,
    429                                   SourceLocation UsingLoc,
    430                                   SourceLocation &DeclEnd,
    431                                   ParsedAttributes &attrs) {
    432   assert(Tok.is(tok::kw_namespace) && "Not 'namespace' token");
    433 
    434   // Eat 'namespace'.
    435   SourceLocation NamespcLoc = ConsumeToken();
    436 
    437   if (Tok.is(tok::code_completion)) {
    438     Actions.CodeCompleteUsingDirective(getCurScope());
    439     cutOffParsing();
    440     return nullptr;
    441   }
    442 
    443   CXXScopeSpec SS;
    444   // Parse (optional) nested-name-specifier.
    445   ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false);
    446 
    447   IdentifierInfo *NamespcName = nullptr;
    448   SourceLocation IdentLoc = SourceLocation();
    449 
    450   // Parse namespace-name.
    451   if (SS.isInvalid() || Tok.isNot(tok::identifier)) {
    452     Diag(Tok, diag::err_expected_namespace_name);
    453     // If there was invalid namespace name, skip to end of decl, and eat ';'.
    454     SkipUntil(tok::semi);
    455     // FIXME: Are there cases, when we would like to call ActOnUsingDirective?
    456     return nullptr;
    457   }
    458 
    459   // Parse identifier.
    460   NamespcName = Tok.getIdentifierInfo();
    461   IdentLoc = ConsumeToken();
    462 
    463   // Parse (optional) attributes (most likely GNU strong-using extension).
    464   bool GNUAttr = false;
    465   if (Tok.is(tok::kw___attribute)) {
    466     GNUAttr = true;
    467     ParseGNUAttributes(attrs);
    468   }
    469 
    470   // Eat ';'.
    471   DeclEnd = Tok.getLocation();
    472   if (ExpectAndConsume(tok::semi,
    473                        GNUAttr ? diag::err_expected_semi_after_attribute_list
    474                                : diag::err_expected_semi_after_namespace_name))
    475     SkipUntil(tok::semi);
    476 
    477   return Actions.ActOnUsingDirective(getCurScope(), UsingLoc, NamespcLoc, SS,
    478                                      IdentLoc, NamespcName, attrs.getList());
    479 }
    480 
    481 /// ParseUsingDeclaration - Parse C++ using-declaration or alias-declaration.
    482 /// Assumes that 'using' was already seen.
    483 ///
    484 ///     using-declaration: [C++ 7.3.p3: namespace.udecl]
    485 ///       'using' 'typename'[opt] ::[opt] nested-name-specifier
    486 ///               unqualified-id
    487 ///       'using' :: unqualified-id
    488 ///
    489 ///     alias-declaration: C++11 [dcl.dcl]p1
    490 ///       'using' identifier attribute-specifier-seq[opt] = type-id ;
    491 ///
    492 Decl *Parser::ParseUsingDeclaration(unsigned Context,
    493                                     const ParsedTemplateInfo &TemplateInfo,
    494                                     SourceLocation UsingLoc,
    495                                     SourceLocation &DeclEnd,
    496                                     AccessSpecifier AS,
    497                                     Decl **OwnedType) {
    498   CXXScopeSpec SS;
    499   SourceLocation TypenameLoc;
    500   bool HasTypenameKeyword = false;
    501 
    502   // Check for misplaced attributes before the identifier in an
    503   // alias-declaration.
    504   ParsedAttributesWithRange MisplacedAttrs(AttrFactory);
    505   MaybeParseCXX11Attributes(MisplacedAttrs);
    506 
    507   // Ignore optional 'typename'.
    508   // FIXME: This is wrong; we should parse this as a typename-specifier.
    509   if (TryConsumeToken(tok::kw_typename, TypenameLoc))
    510     HasTypenameKeyword = true;
    511 
    512   if (Tok.is(tok::kw___super)) {
    513     Diag(Tok.getLocation(), diag::err_super_in_using_declaration);
    514     SkipUntil(tok::semi);
    515     return nullptr;
    516   }
    517 
    518   // Parse nested-name-specifier.
    519   IdentifierInfo *LastII = nullptr;
    520   ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false,
    521                                  /*MayBePseudoDtor=*/nullptr,
    522                                  /*IsTypename=*/false,
    523                                  /*LastII=*/&LastII);
    524 
    525   // Check nested-name specifier.
    526   if (SS.isInvalid()) {
    527     SkipUntil(tok::semi);
    528     return nullptr;
    529   }
    530 
    531   SourceLocation TemplateKWLoc;
    532   UnqualifiedId Name;
    533 
    534   // Parse the unqualified-id. We allow parsing of both constructor and
    535   // destructor names and allow the action module to diagnose any semantic
    536   // errors.
    537   //
    538   // C++11 [class.qual]p2:
    539   //   [...] in a using-declaration that is a member-declaration, if the name
    540   //   specified after the nested-name-specifier is the same as the identifier
    541   //   or the simple-template-id's template-name in the last component of the
    542   //   nested-name-specifier, the name is [...] considered to name the
    543   //   constructor.
    544   if (getLangOpts().CPlusPlus11 && Context == Declarator::MemberContext &&
    545       Tok.is(tok::identifier) && NextToken().is(tok::semi) &&
    546       SS.isNotEmpty() && LastII == Tok.getIdentifierInfo() &&
    547       !SS.getScopeRep()->getAsNamespace() &&
    548       !SS.getScopeRep()->getAsNamespaceAlias()) {
    549     SourceLocation IdLoc = ConsumeToken();
    550     ParsedType Type = Actions.getInheritingConstructorName(SS, IdLoc, *LastII);
    551     Name.setConstructorName(Type, IdLoc, IdLoc);
    552   } else if (ParseUnqualifiedId(
    553                  SS, /*EnteringContext=*/false,
    554                  /*AllowDestructorName=*/true,
    555                  /*AllowConstructorName=*/!(Tok.is(tok::identifier) &&
    556                                             NextToken().is(tok::equal)),
    557                  nullptr, TemplateKWLoc, Name)) {
    558     SkipUntil(tok::semi);
    559     return nullptr;
    560   }
    561 
    562   ParsedAttributesWithRange Attrs(AttrFactory);
    563   MaybeParseGNUAttributes(Attrs);
    564   MaybeParseCXX11Attributes(Attrs);
    565 
    566   // Maybe this is an alias-declaration.
    567   TypeResult TypeAlias;
    568   bool IsAliasDecl = Tok.is(tok::equal);
    569   Decl *DeclFromDeclSpec = nullptr;
    570   if (IsAliasDecl) {
    571     // If we had any misplaced attributes from earlier, this is where they
    572     // should have been written.
    573     if (MisplacedAttrs.Range.isValid()) {
    574       Diag(MisplacedAttrs.Range.getBegin(), diag::err_attributes_not_allowed)
    575         << FixItHint::CreateInsertionFromRange(
    576                Tok.getLocation(),
    577                CharSourceRange::getTokenRange(MisplacedAttrs.Range))
    578         << FixItHint::CreateRemoval(MisplacedAttrs.Range);
    579       Attrs.takeAllFrom(MisplacedAttrs);
    580     }
    581 
    582     ConsumeToken();
    583 
    584     Diag(Tok.getLocation(), getLangOpts().CPlusPlus11 ?
    585          diag::warn_cxx98_compat_alias_declaration :
    586          diag::ext_alias_declaration);
    587 
    588     // Type alias templates cannot be specialized.
    589     int SpecKind = -1;
    590     if (TemplateInfo.Kind == ParsedTemplateInfo::Template &&
    591         Name.getKind() == UnqualifiedId::IK_TemplateId)
    592       SpecKind = 0;
    593     if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization)
    594       SpecKind = 1;
    595     if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
    596       SpecKind = 2;
    597     if (SpecKind != -1) {
    598       SourceRange Range;
    599       if (SpecKind == 0)
    600         Range = SourceRange(Name.TemplateId->LAngleLoc,
    601                             Name.TemplateId->RAngleLoc);
    602       else
    603         Range = TemplateInfo.getSourceRange();
    604       Diag(Range.getBegin(), diag::err_alias_declaration_specialization)
    605         << SpecKind << Range;
    606       SkipUntil(tok::semi);
    607       return nullptr;
    608     }
    609 
    610     // Name must be an identifier.
    611     if (Name.getKind() != UnqualifiedId::IK_Identifier) {
    612       Diag(Name.StartLocation, diag::err_alias_declaration_not_identifier);
    613       // No removal fixit: can't recover from this.
    614       SkipUntil(tok::semi);
    615       return nullptr;
    616     } else if (HasTypenameKeyword)
    617       Diag(TypenameLoc, diag::err_alias_declaration_not_identifier)
    618         << FixItHint::CreateRemoval(SourceRange(TypenameLoc,
    619                              SS.isNotEmpty() ? SS.getEndLoc() : TypenameLoc));
    620     else if (SS.isNotEmpty())
    621       Diag(SS.getBeginLoc(), diag::err_alias_declaration_not_identifier)
    622         << FixItHint::CreateRemoval(SS.getRange());
    623 
    624     TypeAlias = ParseTypeName(nullptr, TemplateInfo.Kind
    625                                            ? Declarator::AliasTemplateContext
    626                                            : Declarator::AliasDeclContext,
    627                               AS, &DeclFromDeclSpec, &Attrs);
    628     if (OwnedType)
    629       *OwnedType = DeclFromDeclSpec;
    630   } else {
    631     // C++11 attributes are not allowed on a using-declaration, but GNU ones
    632     // are.
    633     ProhibitAttributes(MisplacedAttrs);
    634     ProhibitAttributes(Attrs);
    635 
    636     // Parse (optional) attributes (most likely GNU strong-using extension).
    637     MaybeParseGNUAttributes(Attrs);
    638   }
    639 
    640   // Eat ';'.
    641   DeclEnd = Tok.getLocation();
    642   if (ExpectAndConsume(tok::semi, diag::err_expected_after,
    643                        !Attrs.empty() ? "attributes list"
    644                                       : IsAliasDecl ? "alias declaration"
    645                                                     : "using declaration"))
    646     SkipUntil(tok::semi);
    647 
    648   // Diagnose an attempt to declare a templated using-declaration.
    649   // In C++11, alias-declarations can be templates:
    650   //   template <...> using id = type;
    651   if (TemplateInfo.Kind && !IsAliasDecl) {
    652     SourceRange R = TemplateInfo.getSourceRange();
    653     Diag(UsingLoc, diag::err_templated_using_directive_declaration)
    654       << 1 /* declaration */ << R << FixItHint::CreateRemoval(R);
    655 
    656     // Unfortunately, we have to bail out instead of recovering by
    657     // ignoring the parameters, just in case the nested name specifier
    658     // depends on the parameters.
    659     return nullptr;
    660   }
    661 
    662   // "typename" keyword is allowed for identifiers only,
    663   // because it may be a type definition.
    664   if (HasTypenameKeyword && Name.getKind() != UnqualifiedId::IK_Identifier) {
    665     Diag(Name.getSourceRange().getBegin(), diag::err_typename_identifiers_only)
    666       << FixItHint::CreateRemoval(SourceRange(TypenameLoc));
    667     // Proceed parsing, but reset the HasTypenameKeyword flag.
    668     HasTypenameKeyword = false;
    669   }
    670 
    671   if (IsAliasDecl) {
    672     TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
    673     MultiTemplateParamsArg TemplateParamsArg(
    674       TemplateParams ? TemplateParams->data() : nullptr,
    675       TemplateParams ? TemplateParams->size() : 0);
    676     return Actions.ActOnAliasDeclaration(getCurScope(), AS, TemplateParamsArg,
    677                                          UsingLoc, Name, Attrs.getList(),
    678                                          TypeAlias, DeclFromDeclSpec);
    679   }
    680 
    681   return Actions.ActOnUsingDeclaration(getCurScope(), AS,
    682                                        /* HasUsingKeyword */ true, UsingLoc,
    683                                        SS, Name, Attrs.getList(),
    684                                        HasTypenameKeyword, TypenameLoc);
    685 }
    686 
    687 /// ParseStaticAssertDeclaration - Parse C++0x or C11 static_assert-declaration.
    688 ///
    689 /// [C++0x] static_assert-declaration:
    690 ///           static_assert ( constant-expression  ,  string-literal  ) ;
    691 ///
    692 /// [C11]   static_assert-declaration:
    693 ///           _Static_assert ( constant-expression  ,  string-literal  ) ;
    694 ///
    695 Decl *Parser::ParseStaticAssertDeclaration(SourceLocation &DeclEnd){
    696   assert(Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert) &&
    697          "Not a static_assert declaration");
    698 
    699   if (Tok.is(tok::kw__Static_assert) && !getLangOpts().C11)
    700     Diag(Tok, diag::ext_c11_static_assert);
    701   if (Tok.is(tok::kw_static_assert))
    702     Diag(Tok, diag::warn_cxx98_compat_static_assert);
    703 
    704   SourceLocation StaticAssertLoc = ConsumeToken();
    705 
    706   BalancedDelimiterTracker T(*this, tok::l_paren);
    707   if (T.consumeOpen()) {
    708     Diag(Tok, diag::err_expected) << tok::l_paren;
    709     SkipMalformedDecl();
    710     return nullptr;
    711   }
    712 
    713   ExprResult AssertExpr(ParseConstantExpression());
    714   if (AssertExpr.isInvalid()) {
    715     SkipMalformedDecl();
    716     return nullptr;
    717   }
    718 
    719   ExprResult AssertMessage;
    720   if (Tok.is(tok::r_paren)) {
    721     Diag(Tok, getLangOpts().CPlusPlus1z
    722                   ? diag::warn_cxx14_compat_static_assert_no_message
    723                   : diag::ext_static_assert_no_message)
    724       << (getLangOpts().CPlusPlus1z
    725               ? FixItHint()
    726               : FixItHint::CreateInsertion(Tok.getLocation(), ", \"\""));
    727   } else {
    728     if (ExpectAndConsume(tok::comma)) {
    729       SkipUntil(tok::semi);
    730       return nullptr;
    731     }
    732 
    733     if (!isTokenStringLiteral()) {
    734       Diag(Tok, diag::err_expected_string_literal)
    735         << /*Source='static_assert'*/1;
    736       SkipMalformedDecl();
    737       return nullptr;
    738     }
    739 
    740     AssertMessage = ParseStringLiteralExpression();
    741     if (AssertMessage.isInvalid()) {
    742       SkipMalformedDecl();
    743       return nullptr;
    744     }
    745   }
    746 
    747   T.consumeClose();
    748 
    749   DeclEnd = Tok.getLocation();
    750   ExpectAndConsumeSemi(diag::err_expected_semi_after_static_assert);
    751 
    752   return Actions.ActOnStaticAssertDeclaration(StaticAssertLoc,
    753                                               AssertExpr.get(),
    754                                               AssertMessage.get(),
    755                                               T.getCloseLocation());
    756 }
    757 
    758 /// ParseDecltypeSpecifier - Parse a C++11 decltype specifier.
    759 ///
    760 /// 'decltype' ( expression )
    761 /// 'decltype' ( 'auto' )      [C++1y]
    762 ///
    763 SourceLocation Parser::ParseDecltypeSpecifier(DeclSpec &DS) {
    764   assert(Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)
    765            && "Not a decltype specifier");
    766 
    767   ExprResult Result;
    768   SourceLocation StartLoc = Tok.getLocation();
    769   SourceLocation EndLoc;
    770 
    771   if (Tok.is(tok::annot_decltype)) {
    772     Result = getExprAnnotation(Tok);
    773     EndLoc = Tok.getAnnotationEndLoc();
    774     ConsumeToken();
    775     if (Result.isInvalid()) {
    776       DS.SetTypeSpecError();
    777       return EndLoc;
    778     }
    779   } else {
    780     if (Tok.getIdentifierInfo()->isStr("decltype"))
    781       Diag(Tok, diag::warn_cxx98_compat_decltype);
    782 
    783     ConsumeToken();
    784 
    785     BalancedDelimiterTracker T(*this, tok::l_paren);
    786     if (T.expectAndConsume(diag::err_expected_lparen_after,
    787                            "decltype", tok::r_paren)) {
    788       DS.SetTypeSpecError();
    789       return T.getOpenLocation() == Tok.getLocation() ?
    790              StartLoc : T.getOpenLocation();
    791     }
    792 
    793     // Check for C++1y 'decltype(auto)'.
    794     if (Tok.is(tok::kw_auto)) {
    795       // No need to disambiguate here: an expression can't start with 'auto',
    796       // because the typename-specifier in a function-style cast operation can't
    797       // be 'auto'.
    798       Diag(Tok.getLocation(),
    799            getLangOpts().CPlusPlus14
    800              ? diag::warn_cxx11_compat_decltype_auto_type_specifier
    801              : diag::ext_decltype_auto_type_specifier);
    802       ConsumeToken();
    803     } else {
    804       // Parse the expression
    805 
    806       // C++11 [dcl.type.simple]p4:
    807       //   The operand of the decltype specifier is an unevaluated operand.
    808       EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
    809                                                    nullptr,/*IsDecltype=*/true);
    810       Result =
    811           Actions.CorrectDelayedTyposInExpr(ParseExpression(), [](Expr *E) {
    812             return E->hasPlaceholderType() ? ExprError() : E;
    813           });
    814       if (Result.isInvalid()) {
    815         DS.SetTypeSpecError();
    816         if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch)) {
    817           EndLoc = ConsumeParen();
    818         } else {
    819           if (PP.isBacktrackEnabled() && Tok.is(tok::semi)) {
    820             // Backtrack to get the location of the last token before the semi.
    821             PP.RevertCachedTokens(2);
    822             ConsumeToken(); // the semi.
    823             EndLoc = ConsumeAnyToken();
    824             assert(Tok.is(tok::semi));
    825           } else {
    826             EndLoc = Tok.getLocation();
    827           }
    828         }
    829         return EndLoc;
    830       }
    831 
    832       Result = Actions.ActOnDecltypeExpression(Result.get());
    833     }
    834 
    835     // Match the ')'
    836     T.consumeClose();
    837     if (T.getCloseLocation().isInvalid()) {
    838       DS.SetTypeSpecError();
    839       // FIXME: this should return the location of the last token
    840       //        that was consumed (by "consumeClose()")
    841       return T.getCloseLocation();
    842     }
    843 
    844     if (Result.isInvalid()) {
    845       DS.SetTypeSpecError();
    846       return T.getCloseLocation();
    847     }
    848 
    849     EndLoc = T.getCloseLocation();
    850   }
    851   assert(!Result.isInvalid());
    852 
    853   const char *PrevSpec = nullptr;
    854   unsigned DiagID;
    855   const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
    856   // Check for duplicate type specifiers (e.g. "int decltype(a)").
    857   if (Result.get()
    858         ? DS.SetTypeSpecType(DeclSpec::TST_decltype, StartLoc, PrevSpec,
    859                              DiagID, Result.get(), Policy)
    860         : DS.SetTypeSpecType(DeclSpec::TST_decltype_auto, StartLoc, PrevSpec,
    861                              DiagID, Policy)) {
    862     Diag(StartLoc, DiagID) << PrevSpec;
    863     DS.SetTypeSpecError();
    864   }
    865   return EndLoc;
    866 }
    867 
    868 void Parser::AnnotateExistingDecltypeSpecifier(const DeclSpec& DS,
    869                                                SourceLocation StartLoc,
    870                                                SourceLocation EndLoc) {
    871   // make sure we have a token we can turn into an annotation token
    872   if (PP.isBacktrackEnabled())
    873     PP.RevertCachedTokens(1);
    874   else
    875     PP.EnterToken(Tok);
    876 
    877   Tok.setKind(tok::annot_decltype);
    878   setExprAnnotation(Tok,
    879                     DS.getTypeSpecType() == TST_decltype ? DS.getRepAsExpr() :
    880                     DS.getTypeSpecType() == TST_decltype_auto ? ExprResult() :
    881                     ExprError());
    882   Tok.setAnnotationEndLoc(EndLoc);
    883   Tok.setLocation(StartLoc);
    884   PP.AnnotateCachedTokens(Tok);
    885 }
    886 
    887 void Parser::ParseUnderlyingTypeSpecifier(DeclSpec &DS) {
    888   assert(Tok.is(tok::kw___underlying_type) &&
    889          "Not an underlying type specifier");
    890 
    891   SourceLocation StartLoc = ConsumeToken();
    892   BalancedDelimiterTracker T(*this, tok::l_paren);
    893   if (T.expectAndConsume(diag::err_expected_lparen_after,
    894                        "__underlying_type", tok::r_paren)) {
    895     return;
    896   }
    897 
    898   TypeResult Result = ParseTypeName();
    899   if (Result.isInvalid()) {
    900     SkipUntil(tok::r_paren, StopAtSemi);
    901     return;
    902   }
    903 
    904   // Match the ')'
    905   T.consumeClose();
    906   if (T.getCloseLocation().isInvalid())
    907     return;
    908 
    909   const char *PrevSpec = nullptr;
    910   unsigned DiagID;
    911   if (DS.SetTypeSpecType(DeclSpec::TST_underlyingType, StartLoc, PrevSpec,
    912                          DiagID, Result.get(),
    913                          Actions.getASTContext().getPrintingPolicy()))
    914     Diag(StartLoc, DiagID) << PrevSpec;
    915   DS.setTypeofParensRange(T.getRange());
    916 }
    917 
    918 /// ParseBaseTypeSpecifier - Parse a C++ base-type-specifier which is either a
    919 /// class name or decltype-specifier. Note that we only check that the result
    920 /// names a type; semantic analysis will need to verify that the type names a
    921 /// class. The result is either a type or null, depending on whether a type
    922 /// name was found.
    923 ///
    924 ///       base-type-specifier: [C++11 class.derived]
    925 ///         class-or-decltype
    926 ///       class-or-decltype: [C++11 class.derived]
    927 ///         nested-name-specifier[opt] class-name
    928 ///         decltype-specifier
    929 ///       class-name: [C++ class.name]
    930 ///         identifier
    931 ///         simple-template-id
    932 ///
    933 /// In C++98, instead of base-type-specifier, we have:
    934 ///
    935 ///         ::[opt] nested-name-specifier[opt] class-name
    936 TypeResult Parser::ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
    937                                           SourceLocation &EndLocation) {
    938   // Ignore attempts to use typename
    939   if (Tok.is(tok::kw_typename)) {
    940     Diag(Tok, diag::err_expected_class_name_not_template)
    941       << FixItHint::CreateRemoval(Tok.getLocation());
    942     ConsumeToken();
    943   }
    944 
    945   // Parse optional nested-name-specifier
    946   CXXScopeSpec SS;
    947   ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false);
    948 
    949   BaseLoc = Tok.getLocation();
    950 
    951   // Parse decltype-specifier
    952   // tok == kw_decltype is just error recovery, it can only happen when SS
    953   // isn't empty
    954   if (Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)) {
    955     if (SS.isNotEmpty())
    956       Diag(SS.getBeginLoc(), diag::err_unexpected_scope_on_base_decltype)
    957         << FixItHint::CreateRemoval(SS.getRange());
    958     // Fake up a Declarator to use with ActOnTypeName.
    959     DeclSpec DS(AttrFactory);
    960 
    961     EndLocation = ParseDecltypeSpecifier(DS);
    962 
    963     Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
    964     return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
    965   }
    966 
    967   // Check whether we have a template-id that names a type.
    968   if (Tok.is(tok::annot_template_id)) {
    969     TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
    970     if (TemplateId->Kind == TNK_Type_template ||
    971         TemplateId->Kind == TNK_Dependent_template_name) {
    972       AnnotateTemplateIdTokenAsType();
    973 
    974       assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
    975       ParsedType Type = getTypeAnnotation(Tok);
    976       EndLocation = Tok.getAnnotationEndLoc();
    977       ConsumeToken();
    978 
    979       if (Type)
    980         return Type;
    981       return true;
    982     }
    983 
    984     // Fall through to produce an error below.
    985   }
    986 
    987   if (Tok.isNot(tok::identifier)) {
    988     Diag(Tok, diag::err_expected_class_name);
    989     return true;
    990   }
    991 
    992   IdentifierInfo *Id = Tok.getIdentifierInfo();
    993   SourceLocation IdLoc = ConsumeToken();
    994 
    995   if (Tok.is(tok::less)) {
    996     // It looks the user intended to write a template-id here, but the
    997     // template-name was wrong. Try to fix that.
    998     TemplateNameKind TNK = TNK_Type_template;
    999     TemplateTy Template;
   1000     if (!Actions.DiagnoseUnknownTemplateName(*Id, IdLoc, getCurScope(),
   1001                                              &SS, Template, TNK)) {
   1002       Diag(IdLoc, diag::err_unknown_template_name)
   1003         << Id;
   1004     }
   1005 
   1006     if (!Template) {
   1007       TemplateArgList TemplateArgs;
   1008       SourceLocation LAngleLoc, RAngleLoc;
   1009       ParseTemplateIdAfterTemplateName(nullptr, IdLoc, SS, true, LAngleLoc,
   1010                                        TemplateArgs, RAngleLoc);
   1011       return true;
   1012     }
   1013 
   1014     // Form the template name
   1015     UnqualifiedId TemplateName;
   1016     TemplateName.setIdentifier(Id, IdLoc);
   1017 
   1018     // Parse the full template-id, then turn it into a type.
   1019     if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
   1020                                 TemplateName, true))
   1021       return true;
   1022     if (TNK == TNK_Dependent_template_name)
   1023       AnnotateTemplateIdTokenAsType();
   1024 
   1025     // If we didn't end up with a typename token, there's nothing more we
   1026     // can do.
   1027     if (Tok.isNot(tok::annot_typename))
   1028       return true;
   1029 
   1030     // Retrieve the type from the annotation token, consume that token, and
   1031     // return.
   1032     EndLocation = Tok.getAnnotationEndLoc();
   1033     ParsedType Type = getTypeAnnotation(Tok);
   1034     ConsumeToken();
   1035     return Type;
   1036   }
   1037 
   1038   // We have an identifier; check whether it is actually a type.
   1039   IdentifierInfo *CorrectedII = nullptr;
   1040   ParsedType Type =
   1041       Actions.getTypeName(*Id, IdLoc, getCurScope(), &SS, true, false, nullptr,
   1042                           /*IsCtorOrDtorName=*/false,
   1043                           /*NonTrivialTypeSourceInfo=*/true, &CorrectedII);
   1044   if (!Type) {
   1045     Diag(IdLoc, diag::err_expected_class_name);
   1046     return true;
   1047   }
   1048 
   1049   // Consume the identifier.
   1050   EndLocation = IdLoc;
   1051 
   1052   // Fake up a Declarator to use with ActOnTypeName.
   1053   DeclSpec DS(AttrFactory);
   1054   DS.SetRangeStart(IdLoc);
   1055   DS.SetRangeEnd(EndLocation);
   1056   DS.getTypeSpecScope() = SS;
   1057 
   1058   const char *PrevSpec = nullptr;
   1059   unsigned DiagID;
   1060   DS.SetTypeSpecType(TST_typename, IdLoc, PrevSpec, DiagID, Type,
   1061                      Actions.getASTContext().getPrintingPolicy());
   1062 
   1063   Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
   1064   return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
   1065 }
   1066 
   1067 void Parser::ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs) {
   1068   while (Tok.isOneOf(tok::kw___single_inheritance,
   1069                      tok::kw___multiple_inheritance,
   1070                      tok::kw___virtual_inheritance)) {
   1071     IdentifierInfo *AttrName = Tok.getIdentifierInfo();
   1072     SourceLocation AttrNameLoc = ConsumeToken();
   1073     attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
   1074                  AttributeList::AS_Keyword);
   1075   }
   1076 }
   1077 
   1078 /// Determine whether the following tokens are valid after a type-specifier
   1079 /// which could be a standalone declaration. This will conservatively return
   1080 /// true if there's any doubt, and is appropriate for insert-';' fixits.
   1081 bool Parser::isValidAfterTypeSpecifier(bool CouldBeBitfield) {
   1082   // This switch enumerates the valid "follow" set for type-specifiers.
   1083   switch (Tok.getKind()) {
   1084   default: break;
   1085   case tok::semi:               // struct foo {...} ;
   1086   case tok::star:               // struct foo {...} *         P;
   1087   case tok::amp:                // struct foo {...} &         R = ...
   1088   case tok::ampamp:             // struct foo {...} &&        R = ...
   1089   case tok::identifier:         // struct foo {...} V         ;
   1090   case tok::r_paren:            //(struct foo {...} )         {4}
   1091   case tok::annot_cxxscope:     // struct foo {...} a::       b;
   1092   case tok::annot_typename:     // struct foo {...} a         ::b;
   1093   case tok::annot_template_id:  // struct foo {...} a<int>    ::b;
   1094   case tok::l_paren:            // struct foo {...} (         x);
   1095   case tok::comma:              // __builtin_offsetof(struct foo{...} ,
   1096   case tok::kw_operator:        // struct foo       operator  ++() {...}
   1097   case tok::kw___declspec:      // struct foo {...} __declspec(...)
   1098   case tok::l_square:           // void f(struct f  [         3])
   1099   case tok::ellipsis:           // void f(struct f  ...       [Ns])
   1100   // FIXME: we should emit semantic diagnostic when declaration
   1101   // attribute is in type attribute position.
   1102   case tok::kw___attribute:     // struct foo __attribute__((used)) x;
   1103   case tok::annot_pragma_pack:  // struct foo {...} _Pragma(pack(pop));
   1104   // struct foo {...} _Pragma(section(...));
   1105   case tok::annot_pragma_ms_pragma:
   1106   // struct foo {...} _Pragma(vtordisp(pop));
   1107   case tok::annot_pragma_ms_vtordisp:
   1108   // struct foo {...} _Pragma(pointers_to_members(...));
   1109   case tok::annot_pragma_ms_pointers_to_members:
   1110     return true;
   1111   case tok::colon:
   1112     return CouldBeBitfield;     // enum E { ... }   :         2;
   1113   // Microsoft compatibility
   1114   case tok::kw___cdecl:         // struct foo {...} __cdecl      x;
   1115   case tok::kw___fastcall:      // struct foo {...} __fastcall   x;
   1116   case tok::kw___stdcall:       // struct foo {...} __stdcall    x;
   1117   case tok::kw___thiscall:      // struct foo {...} __thiscall   x;
   1118   case tok::kw___vectorcall:    // struct foo {...} __vectorcall x;
   1119     // We will diagnose these calling-convention specifiers on non-function
   1120     // declarations later, so claim they are valid after a type specifier.
   1121     return getLangOpts().MicrosoftExt;
   1122   // Type qualifiers
   1123   case tok::kw_const:           // struct foo {...} const     x;
   1124   case tok::kw_volatile:        // struct foo {...} volatile  x;
   1125   case tok::kw_restrict:        // struct foo {...} restrict  x;
   1126   case tok::kw__Atomic:         // struct foo {...} _Atomic   x;
   1127   case tok::kw___unaligned:     // struct foo {...} __unaligned *x;
   1128   // Function specifiers
   1129   // Note, no 'explicit'. An explicit function must be either a conversion
   1130   // operator or a constructor. Either way, it can't have a return type.
   1131   case tok::kw_inline:          // struct foo       inline    f();
   1132   case tok::kw_virtual:         // struct foo       virtual   f();
   1133   case tok::kw_friend:          // struct foo       friend    f();
   1134   // Storage-class specifiers
   1135   case tok::kw_static:          // struct foo {...} static    x;
   1136   case tok::kw_extern:          // struct foo {...} extern    x;
   1137   case tok::kw_typedef:         // struct foo {...} typedef   x;
   1138   case tok::kw_register:        // struct foo {...} register  x;
   1139   case tok::kw_auto:            // struct foo {...} auto      x;
   1140   case tok::kw_mutable:         // struct foo {...} mutable   x;
   1141   case tok::kw_thread_local:    // struct foo {...} thread_local x;
   1142   case tok::kw_constexpr:       // struct foo {...} constexpr x;
   1143     // As shown above, type qualifiers and storage class specifiers absolutely
   1144     // can occur after class specifiers according to the grammar.  However,
   1145     // almost no one actually writes code like this.  If we see one of these,
   1146     // it is much more likely that someone missed a semi colon and the
   1147     // type/storage class specifier we're seeing is part of the *next*
   1148     // intended declaration, as in:
   1149     //
   1150     //   struct foo { ... }
   1151     //   typedef int X;
   1152     //
   1153     // We'd really like to emit a missing semicolon error instead of emitting
   1154     // an error on the 'int' saying that you can't have two type specifiers in
   1155     // the same declaration of X.  Because of this, we look ahead past this
   1156     // token to see if it's a type specifier.  If so, we know the code is
   1157     // otherwise invalid, so we can produce the expected semi error.
   1158     if (!isKnownToBeTypeSpecifier(NextToken()))
   1159       return true;
   1160     break;
   1161   case tok::r_brace:  // struct bar { struct foo {...} }
   1162     // Missing ';' at end of struct is accepted as an extension in C mode.
   1163     if (!getLangOpts().CPlusPlus)
   1164       return true;
   1165     break;
   1166   case tok::greater:
   1167     // template<class T = class X>
   1168     return getLangOpts().CPlusPlus;
   1169   }
   1170   return false;
   1171 }
   1172 
   1173 /// ParseClassSpecifier - Parse a C++ class-specifier [C++ class] or
   1174 /// elaborated-type-specifier [C++ dcl.type.elab]; we can't tell which
   1175 /// until we reach the start of a definition or see a token that
   1176 /// cannot start a definition.
   1177 ///
   1178 ///       class-specifier: [C++ class]
   1179 ///         class-head '{' member-specification[opt] '}'
   1180 ///         class-head '{' member-specification[opt] '}' attributes[opt]
   1181 ///       class-head:
   1182 ///         class-key identifier[opt] base-clause[opt]
   1183 ///         class-key nested-name-specifier identifier base-clause[opt]
   1184 ///         class-key nested-name-specifier[opt] simple-template-id
   1185 ///                          base-clause[opt]
   1186 /// [GNU]   class-key attributes[opt] identifier[opt] base-clause[opt]
   1187 /// [GNU]   class-key attributes[opt] nested-name-specifier
   1188 ///                          identifier base-clause[opt]
   1189 /// [GNU]   class-key attributes[opt] nested-name-specifier[opt]
   1190 ///                          simple-template-id base-clause[opt]
   1191 ///       class-key:
   1192 ///         'class'
   1193 ///         'struct'
   1194 ///         'union'
   1195 ///
   1196 ///       elaborated-type-specifier: [C++ dcl.type.elab]
   1197 ///         class-key ::[opt] nested-name-specifier[opt] identifier
   1198 ///         class-key ::[opt] nested-name-specifier[opt] 'template'[opt]
   1199 ///                          simple-template-id
   1200 ///
   1201 ///  Note that the C++ class-specifier and elaborated-type-specifier,
   1202 ///  together, subsume the C99 struct-or-union-specifier:
   1203 ///
   1204 ///       struct-or-union-specifier: [C99 6.7.2.1]
   1205 ///         struct-or-union identifier[opt] '{' struct-contents '}'
   1206 ///         struct-or-union identifier
   1207 /// [GNU]   struct-or-union attributes[opt] identifier[opt] '{' struct-contents
   1208 ///                                                         '}' attributes[opt]
   1209 /// [GNU]   struct-or-union attributes[opt] identifier
   1210 ///       struct-or-union:
   1211 ///         'struct'
   1212 ///         'union'
   1213 void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind,
   1214                                  SourceLocation StartLoc, DeclSpec &DS,
   1215                                  const ParsedTemplateInfo &TemplateInfo,
   1216                                  AccessSpecifier AS,
   1217                                  bool EnteringContext, DeclSpecContext DSC,
   1218                                  ParsedAttributesWithRange &Attributes) {
   1219   DeclSpec::TST TagType;
   1220   if (TagTokKind == tok::kw_struct)
   1221     TagType = DeclSpec::TST_struct;
   1222   else if (TagTokKind == tok::kw___interface)
   1223     TagType = DeclSpec::TST_interface;
   1224   else if (TagTokKind == tok::kw_class)
   1225     TagType = DeclSpec::TST_class;
   1226   else {
   1227     assert(TagTokKind == tok::kw_union && "Not a class specifier");
   1228     TagType = DeclSpec::TST_union;
   1229   }
   1230 
   1231   if (Tok.is(tok::code_completion)) {
   1232     // Code completion for a struct, class, or union name.
   1233     Actions.CodeCompleteTag(getCurScope(), TagType);
   1234     return cutOffParsing();
   1235   }
   1236 
   1237   // C++03 [temp.explicit] 14.7.2/8:
   1238   //   The usual access checking rules do not apply to names used to specify
   1239   //   explicit instantiations.
   1240   //
   1241   // As an extension we do not perform access checking on the names used to
   1242   // specify explicit specializations either. This is important to allow
   1243   // specializing traits classes for private types.
   1244   //
   1245   // Note that we don't suppress if this turns out to be an elaborated
   1246   // type specifier.
   1247   bool shouldDelayDiagsInTag =
   1248     (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
   1249      TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
   1250   SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
   1251 
   1252   ParsedAttributesWithRange attrs(AttrFactory);
   1253   // If attributes exist after tag, parse them.
   1254   MaybeParseGNUAttributes(attrs);
   1255   MaybeParseMicrosoftDeclSpecs(attrs);
   1256 
   1257   // Parse inheritance specifiers.
   1258   if (Tok.isOneOf(tok::kw___single_inheritance,
   1259                   tok::kw___multiple_inheritance,
   1260                   tok::kw___virtual_inheritance))
   1261     ParseMicrosoftInheritanceClassAttributes(attrs);
   1262 
   1263   // If C++0x attributes exist here, parse them.
   1264   // FIXME: Are we consistent with the ordering of parsing of different
   1265   // styles of attributes?
   1266   MaybeParseCXX11Attributes(attrs);
   1267 
   1268   // Source location used by FIXIT to insert misplaced
   1269   // C++11 attributes
   1270   SourceLocation AttrFixitLoc = Tok.getLocation();
   1271 
   1272   if (TagType == DeclSpec::TST_struct &&
   1273       Tok.isNot(tok::identifier) &&
   1274       !Tok.isAnnotation() &&
   1275       Tok.getIdentifierInfo() &&
   1276       Tok.isOneOf(tok::kw___is_abstract,
   1277                   tok::kw___is_arithmetic,
   1278                   tok::kw___is_array,
   1279                   tok::kw___is_assignable,
   1280                   tok::kw___is_base_of,
   1281                   tok::kw___is_class,
   1282                   tok::kw___is_complete_type,
   1283                   tok::kw___is_compound,
   1284                   tok::kw___is_const,
   1285                   tok::kw___is_constructible,
   1286                   tok::kw___is_convertible,
   1287                   tok::kw___is_convertible_to,
   1288                   tok::kw___is_destructible,
   1289                   tok::kw___is_empty,
   1290                   tok::kw___is_enum,
   1291                   tok::kw___is_floating_point,
   1292                   tok::kw___is_final,
   1293                   tok::kw___is_function,
   1294                   tok::kw___is_fundamental,
   1295                   tok::kw___is_integral,
   1296                   tok::kw___is_interface_class,
   1297                   tok::kw___is_literal,
   1298                   tok::kw___is_lvalue_expr,
   1299                   tok::kw___is_lvalue_reference,
   1300                   tok::kw___is_member_function_pointer,
   1301                   tok::kw___is_member_object_pointer,
   1302                   tok::kw___is_member_pointer,
   1303                   tok::kw___is_nothrow_assignable,
   1304                   tok::kw___is_nothrow_constructible,
   1305                   tok::kw___is_nothrow_destructible,
   1306                   tok::kw___is_object,
   1307                   tok::kw___is_pod,
   1308                   tok::kw___is_pointer,
   1309                   tok::kw___is_polymorphic,
   1310                   tok::kw___is_reference,
   1311                   tok::kw___is_rvalue_expr,
   1312                   tok::kw___is_rvalue_reference,
   1313                   tok::kw___is_same,
   1314                   tok::kw___is_scalar,
   1315                   tok::kw___is_sealed,
   1316                   tok::kw___is_signed,
   1317                   tok::kw___is_standard_layout,
   1318                   tok::kw___is_trivial,
   1319                   tok::kw___is_trivially_assignable,
   1320                   tok::kw___is_trivially_constructible,
   1321                   tok::kw___is_trivially_copyable,
   1322                   tok::kw___is_union,
   1323                   tok::kw___is_unsigned,
   1324                   tok::kw___is_void,
   1325                   tok::kw___is_volatile))
   1326     // GNU libstdc++ 4.2 and libc++ use certain intrinsic names as the
   1327     // name of struct templates, but some are keywords in GCC >= 4.3
   1328     // and Clang. Therefore, when we see the token sequence "struct
   1329     // X", make X into a normal identifier rather than a keyword, to
   1330     // allow libstdc++ 4.2 and libc++ to work properly.
   1331     TryKeywordIdentFallback(true);
   1332 
   1333   struct PreserveAtomicIdentifierInfoRAII {
   1334     PreserveAtomicIdentifierInfoRAII(Token &Tok, bool Enabled)
   1335         : AtomicII(nullptr) {
   1336       if (!Enabled)
   1337         return;
   1338       assert(Tok.is(tok::kw__Atomic));
   1339       AtomicII = Tok.getIdentifierInfo();
   1340       AtomicII->revertTokenIDToIdentifier();
   1341       Tok.setKind(tok::identifier);
   1342     }
   1343     ~PreserveAtomicIdentifierInfoRAII() {
   1344       if (!AtomicII)
   1345         return;
   1346       AtomicII->revertIdentifierToTokenID(tok::kw__Atomic);
   1347     }
   1348     IdentifierInfo *AtomicII;
   1349   };
   1350 
   1351   // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
   1352   // implementation for VS2013 uses _Atomic as an identifier for one of the
   1353   // classes in <atomic>.  When we are parsing 'struct _Atomic', don't consider
   1354   // '_Atomic' to be a keyword.  We are careful to undo this so that clang can
   1355   // use '_Atomic' in its own header files.
   1356   bool ShouldChangeAtomicToIdentifier = getLangOpts().MSVCCompat &&
   1357                                         Tok.is(tok::kw__Atomic) &&
   1358                                         TagType == DeclSpec::TST_struct;
   1359   PreserveAtomicIdentifierInfoRAII AtomicTokenGuard(
   1360       Tok, ShouldChangeAtomicToIdentifier);
   1361 
   1362   // Parse the (optional) nested-name-specifier.
   1363   CXXScopeSpec &SS = DS.getTypeSpecScope();
   1364   if (getLangOpts().CPlusPlus) {
   1365     // "FOO : BAR" is not a potential typo for "FOO::BAR".  In this context it
   1366     // is a base-specifier-list.
   1367     ColonProtectionRAIIObject X(*this);
   1368 
   1369     CXXScopeSpec Spec;
   1370     bool HasValidSpec = true;
   1371     if (ParseOptionalCXXScopeSpecifier(Spec, nullptr, EnteringContext)) {
   1372       DS.SetTypeSpecError();
   1373       HasValidSpec = false;
   1374     }
   1375     if (Spec.isSet())
   1376       if (Tok.isNot(tok::identifier) && Tok.isNot(tok::annot_template_id)) {
   1377         Diag(Tok, diag::err_expected) << tok::identifier;
   1378         HasValidSpec = false;
   1379       }
   1380     if (HasValidSpec)
   1381       SS = Spec;
   1382   }
   1383 
   1384   TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
   1385 
   1386   // Parse the (optional) class name or simple-template-id.
   1387   IdentifierInfo *Name = nullptr;
   1388   SourceLocation NameLoc;
   1389   TemplateIdAnnotation *TemplateId = nullptr;
   1390   if (Tok.is(tok::identifier)) {
   1391     Name = Tok.getIdentifierInfo();
   1392     NameLoc = ConsumeToken();
   1393 
   1394     if (Tok.is(tok::less) && getLangOpts().CPlusPlus) {
   1395       // The name was supposed to refer to a template, but didn't.
   1396       // Eat the template argument list and try to continue parsing this as
   1397       // a class (or template thereof).
   1398       TemplateArgList TemplateArgs;
   1399       SourceLocation LAngleLoc, RAngleLoc;
   1400       if (ParseTemplateIdAfterTemplateName(
   1401               nullptr, NameLoc, SS, true, LAngleLoc, TemplateArgs, RAngleLoc)) {
   1402         // We couldn't parse the template argument list at all, so don't
   1403         // try to give any location information for the list.
   1404         LAngleLoc = RAngleLoc = SourceLocation();
   1405       }
   1406 
   1407       Diag(NameLoc, diag::err_explicit_spec_non_template)
   1408           << (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
   1409           << TagTokKind << Name << SourceRange(LAngleLoc, RAngleLoc);
   1410 
   1411       // Strip off the last template parameter list if it was empty, since
   1412       // we've removed its template argument list.
   1413       if (TemplateParams && TemplateInfo.LastParameterListWasEmpty) {
   1414         if (TemplateParams->size() > 1) {
   1415           TemplateParams->pop_back();
   1416         } else {
   1417           TemplateParams = nullptr;
   1418           const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind
   1419             = ParsedTemplateInfo::NonTemplate;
   1420         }
   1421       } else if (TemplateInfo.Kind
   1422                                 == ParsedTemplateInfo::ExplicitInstantiation) {
   1423         // Pretend this is just a forward declaration.
   1424         TemplateParams = nullptr;
   1425         const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind
   1426           = ParsedTemplateInfo::NonTemplate;
   1427         const_cast<ParsedTemplateInfo&>(TemplateInfo).TemplateLoc
   1428           = SourceLocation();
   1429         const_cast<ParsedTemplateInfo&>(TemplateInfo).ExternLoc
   1430           = SourceLocation();
   1431       }
   1432     }
   1433   } else if (Tok.is(tok::annot_template_id)) {
   1434     TemplateId = takeTemplateIdAnnotation(Tok);
   1435     NameLoc = ConsumeToken();
   1436 
   1437     if (TemplateId->Kind != TNK_Type_template &&
   1438         TemplateId->Kind != TNK_Dependent_template_name) {
   1439       // The template-name in the simple-template-id refers to
   1440       // something other than a class template. Give an appropriate
   1441       // error message and skip to the ';'.
   1442       SourceRange Range(NameLoc);
   1443       if (SS.isNotEmpty())
   1444         Range.setBegin(SS.getBeginLoc());
   1445 
   1446       // FIXME: Name may be null here.
   1447       Diag(TemplateId->LAngleLoc, diag::err_template_spec_syntax_non_template)
   1448         << TemplateId->Name << static_cast<int>(TemplateId->Kind) << Range;
   1449 
   1450       DS.SetTypeSpecError();
   1451       SkipUntil(tok::semi, StopBeforeMatch);
   1452       return;
   1453     }
   1454   }
   1455 
   1456   // There are four options here.
   1457   //  - If we are in a trailing return type, this is always just a reference,
   1458   //    and we must not try to parse a definition. For instance,
   1459   //      [] () -> struct S { };
   1460   //    does not define a type.
   1461   //  - If we have 'struct foo {...', 'struct foo :...',
   1462   //    'struct foo final :' or 'struct foo final {', then this is a definition.
   1463   //  - If we have 'struct foo;', then this is either a forward declaration
   1464   //    or a friend declaration, which have to be treated differently.
   1465   //  - Otherwise we have something like 'struct foo xyz', a reference.
   1466   //
   1467   //  We also detect these erroneous cases to provide better diagnostic for
   1468   //  C++11 attributes parsing.
   1469   //  - attributes follow class name:
   1470   //    struct foo [[]] {};
   1471   //  - attributes appear before or after 'final':
   1472   //    struct foo [[]] final [[]] {};
   1473   //
   1474   // However, in type-specifier-seq's, things look like declarations but are
   1475   // just references, e.g.
   1476   //   new struct s;
   1477   // or
   1478   //   &T::operator struct s;
   1479   // For these, DSC is DSC_type_specifier or DSC_alias_declaration.
   1480 
   1481   // If there are attributes after class name, parse them.
   1482   MaybeParseCXX11Attributes(Attributes);
   1483 
   1484   const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
   1485   Sema::TagUseKind TUK;
   1486   if (DSC == DSC_trailing)
   1487     TUK = Sema::TUK_Reference;
   1488   else if (Tok.is(tok::l_brace) ||
   1489            (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
   1490            (isCXX11FinalKeyword() &&
   1491             (NextToken().is(tok::l_brace) || NextToken().is(tok::colon)))) {
   1492     if (DS.isFriendSpecified()) {
   1493       // C++ [class.friend]p2:
   1494       //   A class shall not be defined in a friend declaration.
   1495       Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
   1496         << SourceRange(DS.getFriendSpecLoc());
   1497 
   1498       // Skip everything up to the semicolon, so that this looks like a proper
   1499       // friend class (or template thereof) declaration.
   1500       SkipUntil(tok::semi, StopBeforeMatch);
   1501       TUK = Sema::TUK_Friend;
   1502     } else {
   1503       // Okay, this is a class definition.
   1504       TUK = Sema::TUK_Definition;
   1505     }
   1506   } else if (isCXX11FinalKeyword() && (NextToken().is(tok::l_square) ||
   1507                                        NextToken().is(tok::kw_alignas))) {
   1508     // We can't tell if this is a definition or reference
   1509     // until we skipped the 'final' and C++11 attribute specifiers.
   1510     TentativeParsingAction PA(*this);
   1511 
   1512     // Skip the 'final' keyword.
   1513     ConsumeToken();
   1514 
   1515     // Skip C++11 attribute specifiers.
   1516     while (true) {
   1517       if (Tok.is(tok::l_square) && NextToken().is(tok::l_square)) {
   1518         ConsumeBracket();
   1519         if (!SkipUntil(tok::r_square, StopAtSemi))
   1520           break;
   1521       } else if (Tok.is(tok::kw_alignas) && NextToken().is(tok::l_paren)) {
   1522         ConsumeToken();
   1523         ConsumeParen();
   1524         if (!SkipUntil(tok::r_paren, StopAtSemi))
   1525           break;
   1526       } else {
   1527         break;
   1528       }
   1529     }
   1530 
   1531     if (Tok.isOneOf(tok::l_brace, tok::colon))
   1532       TUK = Sema::TUK_Definition;
   1533     else
   1534       TUK = Sema::TUK_Reference;
   1535 
   1536     PA.Revert();
   1537   } else if (!isTypeSpecifier(DSC) &&
   1538              (Tok.is(tok::semi) ||
   1539               (Tok.isAtStartOfLine() && !isValidAfterTypeSpecifier(false)))) {
   1540     TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
   1541     if (Tok.isNot(tok::semi)) {
   1542       const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
   1543       // A semicolon was missing after this declaration. Diagnose and recover.
   1544       ExpectAndConsume(tok::semi, diag::err_expected_after,
   1545                        DeclSpec::getSpecifierName(TagType, PPol));
   1546       PP.EnterToken(Tok);
   1547       Tok.setKind(tok::semi);
   1548     }
   1549   } else
   1550     TUK = Sema::TUK_Reference;
   1551 
   1552   // Forbid misplaced attributes. In cases of a reference, we pass attributes
   1553   // to caller to handle.
   1554   if (TUK != Sema::TUK_Reference) {
   1555     // If this is not a reference, then the only possible
   1556     // valid place for C++11 attributes to appear here
   1557     // is between class-key and class-name. If there are
   1558     // any attributes after class-name, we try a fixit to move
   1559     // them to the right place.
   1560     SourceRange AttrRange = Attributes.Range;
   1561     if (AttrRange.isValid()) {
   1562       Diag(AttrRange.getBegin(), diag::err_attributes_not_allowed)
   1563         << AttrRange
   1564         << FixItHint::CreateInsertionFromRange(AttrFixitLoc,
   1565                                                CharSourceRange(AttrRange, true))
   1566         << FixItHint::CreateRemoval(AttrRange);
   1567 
   1568       // Recover by adding misplaced attributes to the attribute list
   1569       // of the class so they can be applied on the class later.
   1570       attrs.takeAllFrom(Attributes);
   1571     }
   1572   }
   1573 
   1574   // If this is an elaborated type specifier, and we delayed
   1575   // diagnostics before, just merge them into the current pool.
   1576   if (shouldDelayDiagsInTag) {
   1577     diagsFromTag.done();
   1578     if (TUK == Sema::TUK_Reference)
   1579       diagsFromTag.redelay();
   1580   }
   1581 
   1582   if (!Name && !TemplateId && (DS.getTypeSpecType() == DeclSpec::TST_error ||
   1583                                TUK != Sema::TUK_Definition)) {
   1584     if (DS.getTypeSpecType() != DeclSpec::TST_error) {
   1585       // We have a declaration or reference to an anonymous class.
   1586       Diag(StartLoc, diag::err_anon_type_definition)
   1587         << DeclSpec::getSpecifierName(TagType, Policy);
   1588     }
   1589 
   1590     // If we are parsing a definition and stop at a base-clause, continue on
   1591     // until the semicolon.  Continuing from the comma will just trick us into
   1592     // thinking we are seeing a variable declaration.
   1593     if (TUK == Sema::TUK_Definition && Tok.is(tok::colon))
   1594       SkipUntil(tok::semi, StopBeforeMatch);
   1595     else
   1596       SkipUntil(tok::comma, StopAtSemi);
   1597     return;
   1598   }
   1599 
   1600   // Create the tag portion of the class or class template.
   1601   DeclResult TagOrTempResult = true; // invalid
   1602   TypeResult TypeResult = true; // invalid
   1603 
   1604   bool Owned = false;
   1605   Sema::SkipBodyInfo SkipBody;
   1606   if (TemplateId) {
   1607     // Explicit specialization, class template partial specialization,
   1608     // or explicit instantiation.
   1609     ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
   1610                                        TemplateId->NumArgs);
   1611     if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
   1612         TUK == Sema::TUK_Declaration) {
   1613       // This is an explicit instantiation of a class template.
   1614       ProhibitAttributes(attrs);
   1615 
   1616       TagOrTempResult
   1617         = Actions.ActOnExplicitInstantiation(getCurScope(),
   1618                                              TemplateInfo.ExternLoc,
   1619                                              TemplateInfo.TemplateLoc,
   1620                                              TagType,
   1621                                              StartLoc,
   1622                                              SS,
   1623                                              TemplateId->Template,
   1624                                              TemplateId->TemplateNameLoc,
   1625                                              TemplateId->LAngleLoc,
   1626                                              TemplateArgsPtr,
   1627                                              TemplateId->RAngleLoc,
   1628                                              attrs.getList());
   1629 
   1630     // Friend template-ids are treated as references unless
   1631     // they have template headers, in which case they're ill-formed
   1632     // (FIXME: "template <class T> friend class A<T>::B<int>;").
   1633     // We diagnose this error in ActOnClassTemplateSpecialization.
   1634     } else if (TUK == Sema::TUK_Reference ||
   1635                (TUK == Sema::TUK_Friend &&
   1636                 TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate)) {
   1637       ProhibitAttributes(attrs);
   1638       TypeResult = Actions.ActOnTagTemplateIdType(TUK, TagType, StartLoc,
   1639                                                   TemplateId->SS,
   1640                                                   TemplateId->TemplateKWLoc,
   1641                                                   TemplateId->Template,
   1642                                                   TemplateId->TemplateNameLoc,
   1643                                                   TemplateId->LAngleLoc,
   1644                                                   TemplateArgsPtr,
   1645                                                   TemplateId->RAngleLoc);
   1646     } else {
   1647       // This is an explicit specialization or a class template
   1648       // partial specialization.
   1649       TemplateParameterLists FakedParamLists;
   1650       if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
   1651         // This looks like an explicit instantiation, because we have
   1652         // something like
   1653         //
   1654         //   template class Foo<X>
   1655         //
   1656         // but it actually has a definition. Most likely, this was
   1657         // meant to be an explicit specialization, but the user forgot
   1658         // the '<>' after 'template'.
   1659         // It this is friend declaration however, since it cannot have a
   1660         // template header, it is most likely that the user meant to
   1661         // remove the 'template' keyword.
   1662         assert((TUK == Sema::TUK_Definition || TUK == Sema::TUK_Friend) &&
   1663                "Expected a definition here");
   1664 
   1665         if (TUK == Sema::TUK_Friend) {
   1666           Diag(DS.getFriendSpecLoc(), diag::err_friend_explicit_instantiation);
   1667           TemplateParams = nullptr;
   1668         } else {
   1669           SourceLocation LAngleLoc =
   1670               PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
   1671           Diag(TemplateId->TemplateNameLoc,
   1672                diag::err_explicit_instantiation_with_definition)
   1673               << SourceRange(TemplateInfo.TemplateLoc)
   1674               << FixItHint::CreateInsertion(LAngleLoc, "<>");
   1675 
   1676           // Create a fake template parameter list that contains only
   1677           // "template<>", so that we treat this construct as a class
   1678           // template specialization.
   1679           FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
   1680               0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
   1681               LAngleLoc, nullptr));
   1682           TemplateParams = &FakedParamLists;
   1683         }
   1684       }
   1685 
   1686       // Build the class template specialization.
   1687       TagOrTempResult = Actions.ActOnClassTemplateSpecialization(
   1688           getCurScope(), TagType, TUK, StartLoc, DS.getModulePrivateSpecLoc(),
   1689           *TemplateId, attrs.getList(),
   1690           MultiTemplateParamsArg(TemplateParams ? &(*TemplateParams)[0]
   1691                                                 : nullptr,
   1692                                  TemplateParams ? TemplateParams->size() : 0),
   1693           &SkipBody);
   1694     }
   1695   } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
   1696              TUK == Sema::TUK_Declaration) {
   1697     // Explicit instantiation of a member of a class template
   1698     // specialization, e.g.,
   1699     //
   1700     //   template struct Outer<int>::Inner;
   1701     //
   1702     ProhibitAttributes(attrs);
   1703 
   1704     TagOrTempResult
   1705       = Actions.ActOnExplicitInstantiation(getCurScope(),
   1706                                            TemplateInfo.ExternLoc,
   1707                                            TemplateInfo.TemplateLoc,
   1708                                            TagType, StartLoc, SS, Name,
   1709                                            NameLoc, attrs.getList());
   1710   } else if (TUK == Sema::TUK_Friend &&
   1711              TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate) {
   1712     ProhibitAttributes(attrs);
   1713 
   1714     TagOrTempResult =
   1715       Actions.ActOnTemplatedFriendTag(getCurScope(), DS.getFriendSpecLoc(),
   1716                                       TagType, StartLoc, SS,
   1717                                       Name, NameLoc, attrs.getList(),
   1718                                       MultiTemplateParamsArg(
   1719                                     TemplateParams? &(*TemplateParams)[0]
   1720                                                   : nullptr,
   1721                                  TemplateParams? TemplateParams->size() : 0));
   1722   } else {
   1723     if (TUK != Sema::TUK_Declaration && TUK != Sema::TUK_Definition)
   1724       ProhibitAttributes(attrs);
   1725 
   1726     if (TUK == Sema::TUK_Definition &&
   1727         TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
   1728       // If the declarator-id is not a template-id, issue a diagnostic and
   1729       // recover by ignoring the 'template' keyword.
   1730       Diag(Tok, diag::err_template_defn_explicit_instantiation)
   1731         << 1 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
   1732       TemplateParams = nullptr;
   1733     }
   1734 
   1735     bool IsDependent = false;
   1736 
   1737     // Don't pass down template parameter lists if this is just a tag
   1738     // reference.  For example, we don't need the template parameters here:
   1739     //   template <class T> class A *makeA(T t);
   1740     MultiTemplateParamsArg TParams;
   1741     if (TUK != Sema::TUK_Reference && TemplateParams)
   1742       TParams =
   1743         MultiTemplateParamsArg(&(*TemplateParams)[0], TemplateParams->size());
   1744 
   1745     handleDeclspecAlignBeforeClassKey(attrs, DS, TUK);
   1746 
   1747     // Declaration or definition of a class type
   1748     TagOrTempResult = Actions.ActOnTag(getCurScope(), TagType, TUK, StartLoc,
   1749                                        SS, Name, NameLoc, attrs.getList(), AS,
   1750                                        DS.getModulePrivateSpecLoc(),
   1751                                        TParams, Owned, IsDependent,
   1752                                        SourceLocation(), false,
   1753                                        clang::TypeResult(),
   1754                                        DSC == DSC_type_specifier,
   1755                                        &SkipBody);
   1756 
   1757     // If ActOnTag said the type was dependent, try again with the
   1758     // less common call.
   1759     if (IsDependent) {
   1760       assert(TUK == Sema::TUK_Reference || TUK == Sema::TUK_Friend);
   1761       TypeResult = Actions.ActOnDependentTag(getCurScope(), TagType, TUK,
   1762                                              SS, Name, StartLoc, NameLoc);
   1763     }
   1764   }
   1765 
   1766   // If there is a body, parse it and inform the actions module.
   1767   if (TUK == Sema::TUK_Definition) {
   1768     assert(Tok.is(tok::l_brace) ||
   1769            (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
   1770            isCXX11FinalKeyword());
   1771     if (SkipBody.ShouldSkip)
   1772       SkipCXXMemberSpecification(StartLoc, AttrFixitLoc, TagType,
   1773                                  TagOrTempResult.get());
   1774     else if (getLangOpts().CPlusPlus)
   1775       ParseCXXMemberSpecification(StartLoc, AttrFixitLoc, attrs, TagType,
   1776                                   TagOrTempResult.get());
   1777     else
   1778       ParseStructUnionBody(StartLoc, TagType, TagOrTempResult.get());
   1779   }
   1780 
   1781   const char *PrevSpec = nullptr;
   1782   unsigned DiagID;
   1783   bool Result;
   1784   if (!TypeResult.isInvalid()) {
   1785     Result = DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
   1786                                 NameLoc.isValid() ? NameLoc : StartLoc,
   1787                                 PrevSpec, DiagID, TypeResult.get(), Policy);
   1788   } else if (!TagOrTempResult.isInvalid()) {
   1789     Result = DS.SetTypeSpecType(TagType, StartLoc,
   1790                                 NameLoc.isValid() ? NameLoc : StartLoc,
   1791                                 PrevSpec, DiagID, TagOrTempResult.get(), Owned,
   1792                                 Policy);
   1793   } else {
   1794     DS.SetTypeSpecError();
   1795     return;
   1796   }
   1797 
   1798   if (Result)
   1799     Diag(StartLoc, DiagID) << PrevSpec;
   1800 
   1801   // At this point, we've successfully parsed a class-specifier in 'definition'
   1802   // form (e.g. "struct foo { int x; }".  While we could just return here, we're
   1803   // going to look at what comes after it to improve error recovery.  If an
   1804   // impossible token occurs next, we assume that the programmer forgot a ; at
   1805   // the end of the declaration and recover that way.
   1806   //
   1807   // Also enforce C++ [temp]p3:
   1808   //   In a template-declaration which defines a class, no declarator
   1809   //   is permitted.
   1810   //
   1811   // After a type-specifier, we don't expect a semicolon. This only happens in
   1812   // C, since definitions are not permitted in this context in C++.
   1813   if (TUK == Sema::TUK_Definition &&
   1814       (getLangOpts().CPlusPlus || !isTypeSpecifier(DSC)) &&
   1815       (TemplateInfo.Kind || !isValidAfterTypeSpecifier(false))) {
   1816     if (Tok.isNot(tok::semi)) {
   1817       const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
   1818       ExpectAndConsume(tok::semi, diag::err_expected_after,
   1819                        DeclSpec::getSpecifierName(TagType, PPol));
   1820       // Push this token back into the preprocessor and change our current token
   1821       // to ';' so that the rest of the code recovers as though there were an
   1822       // ';' after the definition.
   1823       PP.EnterToken(Tok);
   1824       Tok.setKind(tok::semi);
   1825     }
   1826   }
   1827 }
   1828 
   1829 /// ParseBaseClause - Parse the base-clause of a C++ class [C++ class.derived].
   1830 ///
   1831 ///       base-clause : [C++ class.derived]
   1832 ///         ':' base-specifier-list
   1833 ///       base-specifier-list:
   1834 ///         base-specifier '...'[opt]
   1835 ///         base-specifier-list ',' base-specifier '...'[opt]
   1836 void Parser::ParseBaseClause(Decl *ClassDecl) {
   1837   assert(Tok.is(tok::colon) && "Not a base clause");
   1838   ConsumeToken();
   1839 
   1840   // Build up an array of parsed base specifiers.
   1841   SmallVector<CXXBaseSpecifier *, 8> BaseInfo;
   1842 
   1843   while (true) {
   1844     // Parse a base-specifier.
   1845     BaseResult Result = ParseBaseSpecifier(ClassDecl);
   1846     if (Result.isInvalid()) {
   1847       // Skip the rest of this base specifier, up until the comma or
   1848       // opening brace.
   1849       SkipUntil(tok::comma, tok::l_brace, StopAtSemi | StopBeforeMatch);
   1850     } else {
   1851       // Add this to our array of base specifiers.
   1852       BaseInfo.push_back(Result.get());
   1853     }
   1854 
   1855     // If the next token is a comma, consume it and keep reading
   1856     // base-specifiers.
   1857     if (!TryConsumeToken(tok::comma))
   1858       break;
   1859   }
   1860 
   1861   // Attach the base specifiers
   1862   Actions.ActOnBaseSpecifiers(ClassDecl, BaseInfo);
   1863 }
   1864 
   1865 /// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is
   1866 /// one entry in the base class list of a class specifier, for example:
   1867 ///    class foo : public bar, virtual private baz {
   1868 /// 'public bar' and 'virtual private baz' are each base-specifiers.
   1869 ///
   1870 ///       base-specifier: [C++ class.derived]
   1871 ///         attribute-specifier-seq[opt] base-type-specifier
   1872 ///         attribute-specifier-seq[opt] 'virtual' access-specifier[opt]
   1873 ///                 base-type-specifier
   1874 ///         attribute-specifier-seq[opt] access-specifier 'virtual'[opt]
   1875 ///                 base-type-specifier
   1876 BaseResult Parser::ParseBaseSpecifier(Decl *ClassDecl) {
   1877   bool IsVirtual = false;
   1878   SourceLocation StartLoc = Tok.getLocation();
   1879 
   1880   ParsedAttributesWithRange Attributes(AttrFactory);
   1881   MaybeParseCXX11Attributes(Attributes);
   1882 
   1883   // Parse the 'virtual' keyword.
   1884   if (TryConsumeToken(tok::kw_virtual))
   1885     IsVirtual = true;
   1886 
   1887   CheckMisplacedCXX11Attribute(Attributes, StartLoc);
   1888 
   1889   // Parse an (optional) access specifier.
   1890   AccessSpecifier Access = getAccessSpecifierIfPresent();
   1891   if (Access != AS_none)
   1892     ConsumeToken();
   1893 
   1894   CheckMisplacedCXX11Attribute(Attributes, StartLoc);
   1895 
   1896   // Parse the 'virtual' keyword (again!), in case it came after the
   1897   // access specifier.
   1898   if (Tok.is(tok::kw_virtual))  {
   1899     SourceLocation VirtualLoc = ConsumeToken();
   1900     if (IsVirtual) {
   1901       // Complain about duplicate 'virtual'
   1902       Diag(VirtualLoc, diag::err_dup_virtual)
   1903         << FixItHint::CreateRemoval(VirtualLoc);
   1904     }
   1905 
   1906     IsVirtual = true;
   1907   }
   1908 
   1909   CheckMisplacedCXX11Attribute(Attributes, StartLoc);
   1910 
   1911   // Parse the class-name.
   1912 
   1913   // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
   1914   // implementation for VS2013 uses _Atomic as an identifier for one of the
   1915   // classes in <atomic>.  Treat '_Atomic' to be an identifier when we are
   1916   // parsing the class-name for a base specifier.
   1917   if (getLangOpts().MSVCCompat && Tok.is(tok::kw__Atomic) &&
   1918       NextToken().is(tok::less))
   1919     Tok.setKind(tok::identifier);
   1920 
   1921   SourceLocation EndLocation;
   1922   SourceLocation BaseLoc;
   1923   TypeResult BaseType = ParseBaseTypeSpecifier(BaseLoc, EndLocation);
   1924   if (BaseType.isInvalid())
   1925     return true;
   1926 
   1927   // Parse the optional ellipsis (for a pack expansion). The ellipsis is
   1928   // actually part of the base-specifier-list grammar productions, but we
   1929   // parse it here for convenience.
   1930   SourceLocation EllipsisLoc;
   1931   TryConsumeToken(tok::ellipsis, EllipsisLoc);
   1932 
   1933   // Find the complete source range for the base-specifier.
   1934   SourceRange Range(StartLoc, EndLocation);
   1935 
   1936   // Notify semantic analysis that we have parsed a complete
   1937   // base-specifier.
   1938   return Actions.ActOnBaseSpecifier(ClassDecl, Range, Attributes, IsVirtual,
   1939                                     Access, BaseType.get(), BaseLoc,
   1940                                     EllipsisLoc);
   1941 }
   1942 
   1943 /// getAccessSpecifierIfPresent - Determine whether the next token is
   1944 /// a C++ access-specifier.
   1945 ///
   1946 ///       access-specifier: [C++ class.derived]
   1947 ///         'private'
   1948 ///         'protected'
   1949 ///         'public'
   1950 AccessSpecifier Parser::getAccessSpecifierIfPresent() const {
   1951   switch (Tok.getKind()) {
   1952   default: return AS_none;
   1953   case tok::kw_private: return AS_private;
   1954   case tok::kw_protected: return AS_protected;
   1955   case tok::kw_public: return AS_public;
   1956   }
   1957 }
   1958 
   1959 /// \brief If the given declarator has any parts for which parsing has to be
   1960 /// delayed, e.g., default arguments or an exception-specification, create a
   1961 /// late-parsed method declaration record to handle the parsing at the end of
   1962 /// the class definition.
   1963 void Parser::HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
   1964                                             Decl *ThisDecl) {
   1965   DeclaratorChunk::FunctionTypeInfo &FTI
   1966     = DeclaratorInfo.getFunctionTypeInfo();
   1967   // If there was a late-parsed exception-specification, we'll need a
   1968   // late parse
   1969   bool NeedLateParse = FTI.getExceptionSpecType() == EST_Unparsed;
   1970 
   1971   if (!NeedLateParse) {
   1972     // Look ahead to see if there are any default args
   1973     for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx) {
   1974       auto Param = cast<ParmVarDecl>(FTI.Params[ParamIdx].Param);
   1975       if (Param->hasUnparsedDefaultArg()) {
   1976         NeedLateParse = true;
   1977         break;
   1978       }
   1979     }
   1980   }
   1981 
   1982   if (NeedLateParse) {
   1983     // Push this method onto the stack of late-parsed method
   1984     // declarations.
   1985     auto LateMethod = new LateParsedMethodDeclaration(this, ThisDecl);
   1986     getCurrentClass().LateParsedDeclarations.push_back(LateMethod);
   1987     LateMethod->TemplateScope = getCurScope()->isTemplateParamScope();
   1988 
   1989     // Stash the exception-specification tokens in the late-pased method.
   1990     LateMethod->ExceptionSpecTokens = FTI.ExceptionSpecTokens;
   1991     FTI.ExceptionSpecTokens = nullptr;
   1992 
   1993     // Push tokens for each parameter.  Those that do not have
   1994     // defaults will be NULL.
   1995     LateMethod->DefaultArgs.reserve(FTI.NumParams);
   1996     for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx)
   1997       LateMethod->DefaultArgs.push_back(LateParsedDefaultArgument(
   1998         FTI.Params[ParamIdx].Param, FTI.Params[ParamIdx].DefaultArgTokens));
   1999   }
   2000 }
   2001 
   2002 /// isCXX11VirtSpecifier - Determine whether the given token is a C++11
   2003 /// virt-specifier.
   2004 ///
   2005 ///       virt-specifier:
   2006 ///         override
   2007 ///         final
   2008 VirtSpecifiers::Specifier Parser::isCXX11VirtSpecifier(const Token &Tok) const {
   2009   if (!getLangOpts().CPlusPlus || Tok.isNot(tok::identifier))
   2010     return VirtSpecifiers::VS_None;
   2011 
   2012   IdentifierInfo *II = Tok.getIdentifierInfo();
   2013 
   2014   // Initialize the contextual keywords.
   2015   if (!Ident_final) {
   2016     Ident_final = &PP.getIdentifierTable().get("final");
   2017     if (getLangOpts().MicrosoftExt)
   2018       Ident_sealed = &PP.getIdentifierTable().get("sealed");
   2019     Ident_override = &PP.getIdentifierTable().get("override");
   2020   }
   2021 
   2022   if (II == Ident_override)
   2023     return VirtSpecifiers::VS_Override;
   2024 
   2025   if (II == Ident_sealed)
   2026     return VirtSpecifiers::VS_Sealed;
   2027 
   2028   if (II == Ident_final)
   2029     return VirtSpecifiers::VS_Final;
   2030 
   2031   return VirtSpecifiers::VS_None;
   2032 }
   2033 
   2034 /// ParseOptionalCXX11VirtSpecifierSeq - Parse a virt-specifier-seq.
   2035 ///
   2036 ///       virt-specifier-seq:
   2037 ///         virt-specifier
   2038 ///         virt-specifier-seq virt-specifier
   2039 void Parser::ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS,
   2040                                                 bool IsInterface,
   2041                                                 SourceLocation FriendLoc) {
   2042   while (true) {
   2043     VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
   2044     if (Specifier == VirtSpecifiers::VS_None)
   2045       return;
   2046 
   2047     if (FriendLoc.isValid()) {
   2048       Diag(Tok.getLocation(), diag::err_friend_decl_spec)
   2049         << VirtSpecifiers::getSpecifierName(Specifier)
   2050         << FixItHint::CreateRemoval(Tok.getLocation())
   2051         << SourceRange(FriendLoc, FriendLoc);
   2052       ConsumeToken();
   2053       continue;
   2054     }
   2055 
   2056     // C++ [class.mem]p8:
   2057     //   A virt-specifier-seq shall contain at most one of each virt-specifier.
   2058     const char *PrevSpec = nullptr;
   2059     if (VS.SetSpecifier(Specifier, Tok.getLocation(), PrevSpec))
   2060       Diag(Tok.getLocation(), diag::err_duplicate_virt_specifier)
   2061         << PrevSpec
   2062         << FixItHint::CreateRemoval(Tok.getLocation());
   2063 
   2064     if (IsInterface && (Specifier == VirtSpecifiers::VS_Final ||
   2065                         Specifier == VirtSpecifiers::VS_Sealed)) {
   2066       Diag(Tok.getLocation(), diag::err_override_control_interface)
   2067         << VirtSpecifiers::getSpecifierName(Specifier);
   2068     } else if (Specifier == VirtSpecifiers::VS_Sealed) {
   2069       Diag(Tok.getLocation(), diag::ext_ms_sealed_keyword);
   2070     } else {
   2071       Diag(Tok.getLocation(),
   2072            getLangOpts().CPlusPlus11
   2073                ? diag::warn_cxx98_compat_override_control_keyword
   2074                : diag::ext_override_control_keyword)
   2075           << VirtSpecifiers::getSpecifierName(Specifier);
   2076     }
   2077     ConsumeToken();
   2078   }
   2079 }
   2080 
   2081 /// isCXX11FinalKeyword - Determine whether the next token is a C++11
   2082 /// 'final' or Microsoft 'sealed' contextual keyword.
   2083 bool Parser::isCXX11FinalKeyword() const {
   2084   VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
   2085   return Specifier == VirtSpecifiers::VS_Final ||
   2086          Specifier == VirtSpecifiers::VS_Sealed;
   2087 }
   2088 
   2089 /// \brief Parse a C++ member-declarator up to, but not including, the optional
   2090 /// brace-or-equal-initializer or pure-specifier.
   2091 bool Parser::ParseCXXMemberDeclaratorBeforeInitializer(
   2092     Declarator &DeclaratorInfo, VirtSpecifiers &VS, ExprResult &BitfieldSize,
   2093     LateParsedAttrList &LateParsedAttrs) {
   2094   // member-declarator:
   2095   //   declarator pure-specifier[opt]
   2096   //   declarator brace-or-equal-initializer[opt]
   2097   //   identifier[opt] ':' constant-expression
   2098   if (Tok.isNot(tok::colon))
   2099     ParseDeclarator(DeclaratorInfo);
   2100   else
   2101     DeclaratorInfo.SetIdentifier(nullptr, Tok.getLocation());
   2102 
   2103   if (!DeclaratorInfo.isFunctionDeclarator() && TryConsumeToken(tok::colon)) {
   2104     assert(DeclaratorInfo.isPastIdentifier() &&
   2105            "don't know where identifier would go yet?");
   2106     BitfieldSize = ParseConstantExpression();
   2107     if (BitfieldSize.isInvalid())
   2108       SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
   2109   } else {
   2110     ParseOptionalCXX11VirtSpecifierSeq(
   2111         VS, getCurrentClass().IsInterface,
   2112         DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
   2113     if (!VS.isUnset())
   2114       MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo, VS);
   2115   }
   2116 
   2117   // If a simple-asm-expr is present, parse it.
   2118   if (Tok.is(tok::kw_asm)) {
   2119     SourceLocation Loc;
   2120     ExprResult AsmLabel(ParseSimpleAsm(&Loc));
   2121     if (AsmLabel.isInvalid())
   2122       SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
   2123 
   2124     DeclaratorInfo.setAsmLabel(AsmLabel.get());
   2125     DeclaratorInfo.SetRangeEnd(Loc);
   2126   }
   2127 
   2128   // If attributes exist after the declarator, but before an '{', parse them.
   2129   MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
   2130 
   2131   // For compatibility with code written to older Clang, also accept a
   2132   // virt-specifier *after* the GNU attributes.
   2133   if (BitfieldSize.isUnset() && VS.isUnset()) {
   2134     ParseOptionalCXX11VirtSpecifierSeq(
   2135         VS, getCurrentClass().IsInterface,
   2136         DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
   2137     if (!VS.isUnset()) {
   2138       // If we saw any GNU-style attributes that are known to GCC followed by a
   2139       // virt-specifier, issue a GCC-compat warning.
   2140       const AttributeList *Attr = DeclaratorInfo.getAttributes();
   2141       while (Attr) {
   2142         if (Attr->isKnownToGCC() && !Attr->isCXX11Attribute())
   2143           Diag(Attr->getLoc(), diag::warn_gcc_attribute_location);
   2144         Attr = Attr->getNext();
   2145       }
   2146       MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo, VS);
   2147     }
   2148   }
   2149 
   2150   // If this has neither a name nor a bit width, something has gone seriously
   2151   // wrong. Skip until the semi-colon or }.
   2152   if (!DeclaratorInfo.hasName() && BitfieldSize.isUnset()) {
   2153     // If so, skip until the semi-colon or a }.
   2154     SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
   2155     return true;
   2156   }
   2157   return false;
   2158 }
   2159 
   2160 /// \brief Look for declaration specifiers possibly occurring after C++11
   2161 /// virt-specifier-seq and diagnose them.
   2162 void Parser::MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(
   2163     Declarator &D,
   2164     VirtSpecifiers &VS) {
   2165   DeclSpec DS(AttrFactory);
   2166 
   2167   // GNU-style and C++11 attributes are not allowed here, but they will be
   2168   // handled by the caller.  Diagnose everything else.
   2169   ParseTypeQualifierListOpt(DS, AR_NoAttributesParsed, false);
   2170   D.ExtendWithDeclSpec(DS);
   2171 
   2172   if (D.isFunctionDeclarator()) {
   2173     auto &Function = D.getFunctionTypeInfo();
   2174     if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
   2175       auto DeclSpecCheck = [&] (DeclSpec::TQ TypeQual,
   2176                                 const char *FixItName,
   2177                                 SourceLocation SpecLoc,
   2178                                 unsigned* QualifierLoc) {
   2179         FixItHint Insertion;
   2180         if (DS.getTypeQualifiers() & TypeQual) {
   2181           if (!(Function.TypeQuals & TypeQual)) {
   2182             std::string Name(FixItName);
   2183             Name += " ";
   2184             Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), Name.c_str());
   2185             Function.TypeQuals |= TypeQual;
   2186             *QualifierLoc = SpecLoc.getRawEncoding();
   2187           }
   2188           Diag(SpecLoc, diag::err_declspec_after_virtspec)
   2189             << FixItName
   2190             << VirtSpecifiers::getSpecifierName(VS.getLastSpecifier())
   2191             << FixItHint::CreateRemoval(SpecLoc)
   2192             << Insertion;
   2193         }
   2194       };
   2195       DeclSpecCheck(DeclSpec::TQ_const, "const", DS.getConstSpecLoc(),
   2196                     &Function.ConstQualifierLoc);
   2197       DeclSpecCheck(DeclSpec::TQ_volatile, "volatile", DS.getVolatileSpecLoc(),
   2198                     &Function.VolatileQualifierLoc);
   2199       DeclSpecCheck(DeclSpec::TQ_restrict, "restrict", DS.getRestrictSpecLoc(),
   2200                     &Function.RestrictQualifierLoc);
   2201     }
   2202 
   2203     // Parse ref-qualifiers.
   2204     bool RefQualifierIsLValueRef = true;
   2205     SourceLocation RefQualifierLoc;
   2206     if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc)) {
   2207       const char *Name = (RefQualifierIsLValueRef ? "& " : "&& ");
   2208       FixItHint Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), Name);
   2209       Function.RefQualifierIsLValueRef = RefQualifierIsLValueRef;
   2210       Function.RefQualifierLoc = RefQualifierLoc.getRawEncoding();
   2211 
   2212       Diag(RefQualifierLoc, diag::err_declspec_after_virtspec)
   2213         << (RefQualifierIsLValueRef ? "&" : "&&")
   2214         << VirtSpecifiers::getSpecifierName(VS.getLastSpecifier())
   2215         << FixItHint::CreateRemoval(RefQualifierLoc)
   2216         << Insertion;
   2217       D.SetRangeEnd(RefQualifierLoc);
   2218     }
   2219   }
   2220 }
   2221 
   2222 /// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration.
   2223 ///
   2224 ///       member-declaration:
   2225 ///         decl-specifier-seq[opt] member-declarator-list[opt] ';'
   2226 ///         function-definition ';'[opt]
   2227 ///         ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO]
   2228 ///         using-declaration                                            [TODO]
   2229 /// [C++0x] static_assert-declaration
   2230 ///         template-declaration
   2231 /// [GNU]   '__extension__' member-declaration
   2232 ///
   2233 ///       member-declarator-list:
   2234 ///         member-declarator
   2235 ///         member-declarator-list ',' member-declarator
   2236 ///
   2237 ///       member-declarator:
   2238 ///         declarator virt-specifier-seq[opt] pure-specifier[opt]
   2239 ///         declarator constant-initializer[opt]
   2240 /// [C++11] declarator brace-or-equal-initializer[opt]
   2241 ///         identifier[opt] ':' constant-expression
   2242 ///
   2243 ///       virt-specifier-seq:
   2244 ///         virt-specifier
   2245 ///         virt-specifier-seq virt-specifier
   2246 ///
   2247 ///       virt-specifier:
   2248 ///         override
   2249 ///         final
   2250 /// [MS]    sealed
   2251 ///
   2252 ///       pure-specifier:
   2253 ///         '= 0'
   2254 ///
   2255 ///       constant-initializer:
   2256 ///         '=' constant-expression
   2257 ///
   2258 Parser::DeclGroupPtrTy
   2259 Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS,
   2260                                        AttributeList *AccessAttrs,
   2261                                        const ParsedTemplateInfo &TemplateInfo,
   2262                                        ParsingDeclRAIIObject *TemplateDiags) {
   2263   if (Tok.is(tok::at)) {
   2264     if (getLangOpts().ObjC1 && NextToken().isObjCAtKeyword(tok::objc_defs))
   2265       Diag(Tok, diag::err_at_defs_cxx);
   2266     else
   2267       Diag(Tok, diag::err_at_in_class);
   2268 
   2269     ConsumeToken();
   2270     SkipUntil(tok::r_brace, StopAtSemi);
   2271     return nullptr;
   2272   }
   2273 
   2274   // Turn on colon protection early, while parsing declspec, although there is
   2275   // nothing to protect there. It prevents from false errors if error recovery
   2276   // incorrectly determines where the declspec ends, as in the example:
   2277   //   struct A { enum class B { C }; };
   2278   //   const int C = 4;
   2279   //   struct D { A::B : C; };
   2280   ColonProtectionRAIIObject X(*this);
   2281 
   2282   // Access declarations.
   2283   bool MalformedTypeSpec = false;
   2284   if (!TemplateInfo.Kind &&
   2285       Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw___super)) {
   2286     if (TryAnnotateCXXScopeToken())
   2287       MalformedTypeSpec = true;
   2288 
   2289     bool isAccessDecl;
   2290     if (Tok.isNot(tok::annot_cxxscope))
   2291       isAccessDecl = false;
   2292     else if (NextToken().is(tok::identifier))
   2293       isAccessDecl = GetLookAheadToken(2).is(tok::semi);
   2294     else
   2295       isAccessDecl = NextToken().is(tok::kw_operator);
   2296 
   2297     if (isAccessDecl) {
   2298       // Collect the scope specifier token we annotated earlier.
   2299       CXXScopeSpec SS;
   2300       ParseOptionalCXXScopeSpecifier(SS, nullptr,
   2301                                      /*EnteringContext=*/false);
   2302 
   2303       if (SS.isInvalid()) {
   2304         SkipUntil(tok::semi);
   2305         return nullptr;
   2306       }
   2307 
   2308       // Try to parse an unqualified-id.
   2309       SourceLocation TemplateKWLoc;
   2310       UnqualifiedId Name;
   2311       if (ParseUnqualifiedId(SS, false, true, true, nullptr, TemplateKWLoc,
   2312                              Name)) {
   2313         SkipUntil(tok::semi);
   2314         return nullptr;
   2315       }
   2316 
   2317       // TODO: recover from mistakenly-qualified operator declarations.
   2318       if (ExpectAndConsume(tok::semi, diag::err_expected_after,
   2319                            "access declaration")) {
   2320         SkipUntil(tok::semi);
   2321         return nullptr;
   2322       }
   2323 
   2324       return DeclGroupPtrTy::make(DeclGroupRef(Actions.ActOnUsingDeclaration(
   2325           getCurScope(), AS,
   2326           /* HasUsingKeyword */ false, SourceLocation(), SS, Name,
   2327           /* AttrList */ nullptr,
   2328           /* HasTypenameKeyword */ false, SourceLocation())));
   2329     }
   2330   }
   2331 
   2332   // static_assert-declaration. A templated static_assert declaration is
   2333   // diagnosed in Parser::ParseSingleDeclarationAfterTemplate.
   2334   if (!TemplateInfo.Kind &&
   2335       Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert)) {
   2336     SourceLocation DeclEnd;
   2337     return DeclGroupPtrTy::make(
   2338         DeclGroupRef(ParseStaticAssertDeclaration(DeclEnd)));
   2339   }
   2340 
   2341   if (Tok.is(tok::kw_template)) {
   2342     assert(!TemplateInfo.TemplateParams &&
   2343            "Nested template improperly parsed?");
   2344     SourceLocation DeclEnd;
   2345     return DeclGroupPtrTy::make(
   2346         DeclGroupRef(ParseDeclarationStartingWithTemplate(
   2347             Declarator::MemberContext, DeclEnd, AS, AccessAttrs)));
   2348   }
   2349 
   2350   // Handle:  member-declaration ::= '__extension__' member-declaration
   2351   if (Tok.is(tok::kw___extension__)) {
   2352     // __extension__ silences extension warnings in the subexpression.
   2353     ExtensionRAIIObject O(Diags);  // Use RAII to do this.
   2354     ConsumeToken();
   2355     return ParseCXXClassMemberDeclaration(AS, AccessAttrs,
   2356                                           TemplateInfo, TemplateDiags);
   2357   }
   2358 
   2359   ParsedAttributesWithRange attrs(AttrFactory);
   2360   ParsedAttributesWithRange FnAttrs(AttrFactory);
   2361   // Optional C++11 attribute-specifier
   2362   MaybeParseCXX11Attributes(attrs);
   2363   // We need to keep these attributes for future diagnostic
   2364   // before they are taken over by declaration specifier.
   2365   FnAttrs.addAll(attrs.getList());
   2366   FnAttrs.Range = attrs.Range;
   2367 
   2368   MaybeParseMicrosoftAttributes(attrs);
   2369 
   2370   if (Tok.is(tok::kw_using)) {
   2371     ProhibitAttributes(attrs);
   2372 
   2373     // Eat 'using'.
   2374     SourceLocation UsingLoc = ConsumeToken();
   2375 
   2376     if (Tok.is(tok::kw_namespace)) {
   2377       Diag(UsingLoc, diag::err_using_namespace_in_class);
   2378       SkipUntil(tok::semi, StopBeforeMatch);
   2379       return nullptr;
   2380     }
   2381     SourceLocation DeclEnd;
   2382     // Otherwise, it must be a using-declaration or an alias-declaration.
   2383     return DeclGroupPtrTy::make(DeclGroupRef(ParseUsingDeclaration(
   2384         Declarator::MemberContext, TemplateInfo, UsingLoc, DeclEnd, AS)));
   2385   }
   2386 
   2387   // Hold late-parsed attributes so we can attach a Decl to them later.
   2388   LateParsedAttrList CommonLateParsedAttrs;
   2389 
   2390   // decl-specifier-seq:
   2391   // Parse the common declaration-specifiers piece.
   2392   ParsingDeclSpec DS(*this, TemplateDiags);
   2393   DS.takeAttributesFrom(attrs);
   2394   if (MalformedTypeSpec)
   2395     DS.SetTypeSpecError();
   2396 
   2397   ParseDeclarationSpecifiers(DS, TemplateInfo, AS, DSC_class,
   2398                              &CommonLateParsedAttrs);
   2399 
   2400   // Turn off colon protection that was set for declspec.
   2401   X.restore();
   2402 
   2403   // If we had a free-standing type definition with a missing semicolon, we
   2404   // may get this far before the problem becomes obvious.
   2405   if (DS.hasTagDefinition() &&
   2406       TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate &&
   2407       DiagnoseMissingSemiAfterTagDefinition(DS, AS, DSC_class,
   2408                                             &CommonLateParsedAttrs))
   2409     return nullptr;
   2410 
   2411   MultiTemplateParamsArg TemplateParams(
   2412       TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->data()
   2413                                  : nullptr,
   2414       TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->size() : 0);
   2415 
   2416   if (TryConsumeToken(tok::semi)) {
   2417     if (DS.isFriendSpecified())
   2418       ProhibitAttributes(FnAttrs);
   2419 
   2420     RecordDecl *AnonRecord = nullptr;
   2421     Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(
   2422         getCurScope(), AS, DS, TemplateParams, false, AnonRecord);
   2423     DS.complete(TheDecl);
   2424     if (AnonRecord) {
   2425       Decl* decls[] = {AnonRecord, TheDecl};
   2426       return Actions.BuildDeclaratorGroup(decls, /*TypeMayContainAuto=*/false);
   2427     }
   2428     return Actions.ConvertDeclToDeclGroup(TheDecl);
   2429   }
   2430 
   2431   ParsingDeclarator DeclaratorInfo(*this, DS, Declarator::MemberContext);
   2432   VirtSpecifiers VS;
   2433 
   2434   // Hold late-parsed attributes so we can attach a Decl to them later.
   2435   LateParsedAttrList LateParsedAttrs;
   2436 
   2437   SourceLocation EqualLoc;
   2438   SourceLocation PureSpecLoc;
   2439 
   2440   auto TryConsumePureSpecifier = [&] (bool AllowDefinition) {
   2441     if (Tok.isNot(tok::equal))
   2442       return false;
   2443 
   2444     auto &Zero = NextToken();
   2445     SmallString<8> Buffer;
   2446     if (Zero.isNot(tok::numeric_constant) || Zero.getLength() != 1 ||
   2447         PP.getSpelling(Zero, Buffer) != "0")
   2448       return false;
   2449 
   2450     auto &After = GetLookAheadToken(2);
   2451     if (!After.isOneOf(tok::semi, tok::comma) &&
   2452         !(AllowDefinition &&
   2453           After.isOneOf(tok::l_brace, tok::colon, tok::kw_try)))
   2454       return false;
   2455 
   2456     EqualLoc = ConsumeToken();
   2457     PureSpecLoc = ConsumeToken();
   2458     return true;
   2459   };
   2460 
   2461   SmallVector<Decl *, 8> DeclsInGroup;
   2462   ExprResult BitfieldSize;
   2463   bool ExpectSemi = true;
   2464 
   2465   // Parse the first declarator.
   2466   if (ParseCXXMemberDeclaratorBeforeInitializer(
   2467           DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs)) {
   2468     TryConsumeToken(tok::semi);
   2469     return nullptr;
   2470   }
   2471 
   2472   // Check for a member function definition.
   2473   if (BitfieldSize.isUnset()) {
   2474     // MSVC permits pure specifier on inline functions defined at class scope.
   2475     // Hence check for =0 before checking for function definition.
   2476     if (getLangOpts().MicrosoftExt && DeclaratorInfo.isDeclarationOfFunction())
   2477       TryConsumePureSpecifier(/*AllowDefinition*/ true);
   2478 
   2479     FunctionDefinitionKind DefinitionKind = FDK_Declaration;
   2480     // function-definition:
   2481     //
   2482     // In C++11, a non-function declarator followed by an open brace is a
   2483     // braced-init-list for an in-class member initialization, not an
   2484     // erroneous function definition.
   2485     if (Tok.is(tok::l_brace) && !getLangOpts().CPlusPlus11) {
   2486       DefinitionKind = FDK_Definition;
   2487     } else if (DeclaratorInfo.isFunctionDeclarator()) {
   2488       if (Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try)) {
   2489         DefinitionKind = FDK_Definition;
   2490       } else if (Tok.is(tok::equal)) {
   2491         const Token &KW = NextToken();
   2492         if (KW.is(tok::kw_default))
   2493           DefinitionKind = FDK_Defaulted;
   2494         else if (KW.is(tok::kw_delete))
   2495           DefinitionKind = FDK_Deleted;
   2496       }
   2497     }
   2498     DeclaratorInfo.setFunctionDefinitionKind(DefinitionKind);
   2499 
   2500     // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
   2501     // to a friend declaration, that declaration shall be a definition.
   2502     if (DeclaratorInfo.isFunctionDeclarator() &&
   2503         DefinitionKind != FDK_Definition && DS.isFriendSpecified()) {
   2504       // Diagnose attributes that appear before decl specifier:
   2505       // [[]] friend int foo();
   2506       ProhibitAttributes(FnAttrs);
   2507     }
   2508 
   2509     if (DefinitionKind != FDK_Declaration) {
   2510       if (!DeclaratorInfo.isFunctionDeclarator()) {
   2511         Diag(DeclaratorInfo.getIdentifierLoc(), diag::err_func_def_no_params);
   2512         ConsumeBrace();
   2513         SkipUntil(tok::r_brace);
   2514 
   2515         // Consume the optional ';'
   2516         TryConsumeToken(tok::semi);
   2517 
   2518         return nullptr;
   2519       }
   2520 
   2521       if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
   2522         Diag(DeclaratorInfo.getIdentifierLoc(),
   2523              diag::err_function_declared_typedef);
   2524 
   2525         // Recover by treating the 'typedef' as spurious.
   2526         DS.ClearStorageClassSpecs();
   2527       }
   2528 
   2529       Decl *FunDecl =
   2530         ParseCXXInlineMethodDef(AS, AccessAttrs, DeclaratorInfo, TemplateInfo,
   2531                                 VS, PureSpecLoc);
   2532 
   2533       if (FunDecl) {
   2534         for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i) {
   2535           CommonLateParsedAttrs[i]->addDecl(FunDecl);
   2536         }
   2537         for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i) {
   2538           LateParsedAttrs[i]->addDecl(FunDecl);
   2539         }
   2540       }
   2541       LateParsedAttrs.clear();
   2542 
   2543       // Consume the ';' - it's optional unless we have a delete or default
   2544       if (Tok.is(tok::semi))
   2545         ConsumeExtraSemi(AfterMemberFunctionDefinition);
   2546 
   2547       return DeclGroupPtrTy::make(DeclGroupRef(FunDecl));
   2548     }
   2549   }
   2550 
   2551   // member-declarator-list:
   2552   //   member-declarator
   2553   //   member-declarator-list ',' member-declarator
   2554 
   2555   while (1) {
   2556     InClassInitStyle HasInClassInit = ICIS_NoInit;
   2557     bool HasStaticInitializer = false;
   2558     if (Tok.isOneOf(tok::equal, tok::l_brace) && PureSpecLoc.isInvalid()) {
   2559       if (BitfieldSize.get()) {
   2560         Diag(Tok, diag::err_bitfield_member_init);
   2561         SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
   2562       } else if (DeclaratorInfo.isDeclarationOfFunction()) {
   2563         // It's a pure-specifier.
   2564         if (!TryConsumePureSpecifier(/*AllowFunctionDefinition*/ false))
   2565           // Parse it as an expression so that Sema can diagnose it.
   2566           HasStaticInitializer = true;
   2567       } else if (DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
   2568                      DeclSpec::SCS_static &&
   2569                  DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
   2570                      DeclSpec::SCS_typedef &&
   2571                  !DS.isFriendSpecified()) {
   2572         // It's a default member initializer.
   2573         HasInClassInit = Tok.is(tok::equal) ? ICIS_CopyInit : ICIS_ListInit;
   2574       } else {
   2575         HasStaticInitializer = true;
   2576       }
   2577     }
   2578 
   2579     // NOTE: If Sema is the Action module and declarator is an instance field,
   2580     // this call will *not* return the created decl; It will return null.
   2581     // See Sema::ActOnCXXMemberDeclarator for details.
   2582 
   2583     NamedDecl *ThisDecl = nullptr;
   2584     if (DS.isFriendSpecified()) {
   2585       // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
   2586       // to a friend declaration, that declaration shall be a definition.
   2587       //
   2588       // Diagnose attributes that appear in a friend member function declarator:
   2589       //   friend int foo [[]] ();
   2590       SmallVector<SourceRange, 4> Ranges;
   2591       DeclaratorInfo.getCXX11AttributeRanges(Ranges);
   2592       for (SmallVectorImpl<SourceRange>::iterator I = Ranges.begin(),
   2593            E = Ranges.end(); I != E; ++I)
   2594         Diag((*I).getBegin(), diag::err_attributes_not_allowed) << *I;
   2595 
   2596       ThisDecl = Actions.ActOnFriendFunctionDecl(getCurScope(), DeclaratorInfo,
   2597                                                  TemplateParams);
   2598     } else {
   2599       ThisDecl = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS,
   2600                                                   DeclaratorInfo,
   2601                                                   TemplateParams,
   2602                                                   BitfieldSize.get(),
   2603                                                   VS, HasInClassInit);
   2604 
   2605       if (VarTemplateDecl *VT =
   2606               ThisDecl ? dyn_cast<VarTemplateDecl>(ThisDecl) : nullptr)
   2607         // Re-direct this decl to refer to the templated decl so that we can
   2608         // initialize it.
   2609         ThisDecl = VT->getTemplatedDecl();
   2610 
   2611       if (ThisDecl && AccessAttrs)
   2612         Actions.ProcessDeclAttributeList(getCurScope(), ThisDecl, AccessAttrs);
   2613     }
   2614 
   2615     // Error recovery might have converted a non-static member into a static
   2616     // member.
   2617     if (HasInClassInit != ICIS_NoInit &&
   2618         DeclaratorInfo.getDeclSpec().getStorageClassSpec() ==
   2619             DeclSpec::SCS_static) {
   2620       HasInClassInit = ICIS_NoInit;
   2621       HasStaticInitializer = true;
   2622     }
   2623 
   2624     if (ThisDecl && PureSpecLoc.isValid())
   2625       Actions.ActOnPureSpecifier(ThisDecl, PureSpecLoc);
   2626 
   2627     // Handle the initializer.
   2628     if (HasInClassInit != ICIS_NoInit) {
   2629       // The initializer was deferred; parse it and cache the tokens.
   2630       Diag(Tok, getLangOpts().CPlusPlus11
   2631                     ? diag::warn_cxx98_compat_nonstatic_member_init
   2632                     : diag::ext_nonstatic_member_init);
   2633 
   2634       if (DeclaratorInfo.isArrayOfUnknownBound()) {
   2635         // C++11 [dcl.array]p3: An array bound may also be omitted when the
   2636         // declarator is followed by an initializer.
   2637         //
   2638         // A brace-or-equal-initializer for a member-declarator is not an
   2639         // initializer in the grammar, so this is ill-formed.
   2640         Diag(Tok, diag::err_incomplete_array_member_init);
   2641         SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
   2642 
   2643         // Avoid later warnings about a class member of incomplete type.
   2644         if (ThisDecl)
   2645           ThisDecl->setInvalidDecl();
   2646       } else
   2647         ParseCXXNonStaticMemberInitializer(ThisDecl);
   2648     } else if (HasStaticInitializer) {
   2649       // Normal initializer.
   2650       ExprResult Init = ParseCXXMemberInitializer(
   2651           ThisDecl, DeclaratorInfo.isDeclarationOfFunction(), EqualLoc);
   2652 
   2653       if (Init.isInvalid())
   2654         SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
   2655       else if (ThisDecl)
   2656         Actions.AddInitializerToDecl(ThisDecl, Init.get(), EqualLoc.isInvalid(),
   2657                                      DS.containsPlaceholderType());
   2658     } else if (ThisDecl && DS.getStorageClassSpec() == DeclSpec::SCS_static)
   2659       // No initializer.
   2660       Actions.ActOnUninitializedDecl(ThisDecl, DS.containsPlaceholderType());
   2661 
   2662     if (ThisDecl) {
   2663       if (!ThisDecl->isInvalidDecl()) {
   2664         // Set the Decl for any late parsed attributes
   2665         for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i)
   2666           CommonLateParsedAttrs[i]->addDecl(ThisDecl);
   2667 
   2668         for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i)
   2669           LateParsedAttrs[i]->addDecl(ThisDecl);
   2670       }
   2671       Actions.FinalizeDeclaration(ThisDecl);
   2672       DeclsInGroup.push_back(ThisDecl);
   2673 
   2674       if (DeclaratorInfo.isFunctionDeclarator() &&
   2675           DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
   2676               DeclSpec::SCS_typedef)
   2677         HandleMemberFunctionDeclDelays(DeclaratorInfo, ThisDecl);
   2678     }
   2679     LateParsedAttrs.clear();
   2680 
   2681     DeclaratorInfo.complete(ThisDecl);
   2682 
   2683     // If we don't have a comma, it is either the end of the list (a ';')
   2684     // or an error, bail out.
   2685     SourceLocation CommaLoc;
   2686     if (!TryConsumeToken(tok::comma, CommaLoc))
   2687       break;
   2688 
   2689     if (Tok.isAtStartOfLine() &&
   2690         !MightBeDeclarator(Declarator::MemberContext)) {
   2691       // This comma was followed by a line-break and something which can't be
   2692       // the start of a declarator. The comma was probably a typo for a
   2693       // semicolon.
   2694       Diag(CommaLoc, diag::err_expected_semi_declaration)
   2695         << FixItHint::CreateReplacement(CommaLoc, ";");
   2696       ExpectSemi = false;
   2697       break;
   2698     }
   2699 
   2700     // Parse the next declarator.
   2701     DeclaratorInfo.clear();
   2702     VS.clear();
   2703     BitfieldSize = ExprResult(/*Invalid=*/false);
   2704     EqualLoc = PureSpecLoc = SourceLocation();
   2705     DeclaratorInfo.setCommaLoc(CommaLoc);
   2706 
   2707     // GNU attributes are allowed before the second and subsequent declarator.
   2708     MaybeParseGNUAttributes(DeclaratorInfo);
   2709 
   2710     if (ParseCXXMemberDeclaratorBeforeInitializer(
   2711             DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs))
   2712       break;
   2713   }
   2714 
   2715   if (ExpectSemi &&
   2716       ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list)) {
   2717     // Skip to end of block or statement.
   2718     SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
   2719     // If we stopped at a ';', eat it.
   2720     TryConsumeToken(tok::semi);
   2721     return nullptr;
   2722   }
   2723 
   2724   return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
   2725 }
   2726 
   2727 /// ParseCXXMemberInitializer - Parse the brace-or-equal-initializer.
   2728 /// Also detect and reject any attempted defaulted/deleted function definition.
   2729 /// The location of the '=', if any, will be placed in EqualLoc.
   2730 ///
   2731 /// This does not check for a pure-specifier; that's handled elsewhere.
   2732 ///
   2733 ///   brace-or-equal-initializer:
   2734 ///     '=' initializer-expression
   2735 ///     braced-init-list
   2736 ///
   2737 ///   initializer-clause:
   2738 ///     assignment-expression
   2739 ///     braced-init-list
   2740 ///
   2741 ///   defaulted/deleted function-definition:
   2742 ///     '=' 'default'
   2743 ///     '=' 'delete'
   2744 ///
   2745 /// Prior to C++0x, the assignment-expression in an initializer-clause must
   2746 /// be a constant-expression.
   2747 ExprResult Parser::ParseCXXMemberInitializer(Decl *D, bool IsFunction,
   2748                                              SourceLocation &EqualLoc) {
   2749   assert(Tok.isOneOf(tok::equal, tok::l_brace)
   2750          && "Data member initializer not starting with '=' or '{'");
   2751 
   2752   EnterExpressionEvaluationContext Context(Actions,
   2753                                            Sema::PotentiallyEvaluated,
   2754                                            D);
   2755   if (TryConsumeToken(tok::equal, EqualLoc)) {
   2756     if (Tok.is(tok::kw_delete)) {
   2757       // In principle, an initializer of '= delete p;' is legal, but it will
   2758       // never type-check. It's better to diagnose it as an ill-formed expression
   2759       // than as an ill-formed deleted non-function member.
   2760       // An initializer of '= delete p, foo' will never be parsed, because
   2761       // a top-level comma always ends the initializer expression.
   2762       const Token &Next = NextToken();
   2763       if (IsFunction || Next.isOneOf(tok::semi, tok::comma, tok::eof)) {
   2764         if (IsFunction)
   2765           Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
   2766             << 1 /* delete */;
   2767         else
   2768           Diag(ConsumeToken(), diag::err_deleted_non_function);
   2769         return ExprError();
   2770       }
   2771     } else if (Tok.is(tok::kw_default)) {
   2772       if (IsFunction)
   2773         Diag(Tok, diag::err_default_delete_in_multiple_declaration)
   2774           << 0 /* default */;
   2775       else
   2776         Diag(ConsumeToken(), diag::err_default_special_members);
   2777       return ExprError();
   2778     }
   2779   }
   2780   if (const auto *PD = dyn_cast_or_null<MSPropertyDecl>(D)) {
   2781     Diag(Tok, diag::err_ms_property_initializer) << PD;
   2782     return ExprError();
   2783   }
   2784   return ParseInitializer();
   2785 }
   2786 
   2787 void Parser::SkipCXXMemberSpecification(SourceLocation RecordLoc,
   2788                                         SourceLocation AttrFixitLoc,
   2789                                         unsigned TagType, Decl *TagDecl) {
   2790   // Skip the optional 'final' keyword.
   2791   if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
   2792     assert(isCXX11FinalKeyword() && "not a class definition");
   2793     ConsumeToken();
   2794 
   2795     // Diagnose any C++11 attributes after 'final' keyword.
   2796     // We deliberately discard these attributes.
   2797     ParsedAttributesWithRange Attrs(AttrFactory);
   2798     CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
   2799 
   2800     // This can only happen if we had malformed misplaced attributes;
   2801     // we only get called if there is a colon or left-brace after the
   2802     // attributes.
   2803     if (Tok.isNot(tok::colon) && Tok.isNot(tok::l_brace))
   2804       return;
   2805   }
   2806 
   2807   // Skip the base clauses. This requires actually parsing them, because
   2808   // otherwise we can't be sure where they end (a left brace may appear
   2809   // within a template argument).
   2810   if (Tok.is(tok::colon)) {
   2811     // Enter the scope of the class so that we can correctly parse its bases.
   2812     ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
   2813     ParsingClassDefinition ParsingDef(*this, TagDecl, /*NonNestedClass*/ true,
   2814                                       TagType == DeclSpec::TST_interface);
   2815     auto OldContext =
   2816         Actions.ActOnTagStartSkippedDefinition(getCurScope(), TagDecl);
   2817 
   2818     // Parse the bases but don't attach them to the class.
   2819     ParseBaseClause(nullptr);
   2820 
   2821     Actions.ActOnTagFinishSkippedDefinition(OldContext);
   2822 
   2823     if (!Tok.is(tok::l_brace)) {
   2824       Diag(PP.getLocForEndOfToken(PrevTokLocation),
   2825            diag::err_expected_lbrace_after_base_specifiers);
   2826       return;
   2827     }
   2828   }
   2829 
   2830   // Skip the body.
   2831   assert(Tok.is(tok::l_brace));
   2832   BalancedDelimiterTracker T(*this, tok::l_brace);
   2833   T.consumeOpen();
   2834   T.skipToEnd();
   2835 
   2836   // Parse and discard any trailing attributes.
   2837   ParsedAttributes Attrs(AttrFactory);
   2838   if (Tok.is(tok::kw___attribute))
   2839     MaybeParseGNUAttributes(Attrs);
   2840 }
   2841 
   2842 Parser::DeclGroupPtrTy Parser::ParseCXXClassMemberDeclarationWithPragmas(
   2843     AccessSpecifier &AS, ParsedAttributesWithRange &AccessAttrs,
   2844     DeclSpec::TST TagType, Decl *TagDecl) {
   2845   if (getLangOpts().MicrosoftExt &&
   2846       Tok.isOneOf(tok::kw___if_exists, tok::kw___if_not_exists)) {
   2847     ParseMicrosoftIfExistsClassDeclaration(TagType, AS);
   2848     return nullptr;
   2849   }
   2850 
   2851   // Check for extraneous top-level semicolon.
   2852   if (Tok.is(tok::semi)) {
   2853     ConsumeExtraSemi(InsideStruct, TagType);
   2854     return nullptr;
   2855   }
   2856 
   2857   if (Tok.is(tok::annot_pragma_vis)) {
   2858     HandlePragmaVisibility();
   2859     return nullptr;
   2860   }
   2861 
   2862   if (Tok.is(tok::annot_pragma_pack)) {
   2863     HandlePragmaPack();
   2864     return nullptr;
   2865   }
   2866 
   2867   if (Tok.is(tok::annot_pragma_align)) {
   2868     HandlePragmaAlign();
   2869     return nullptr;
   2870   }
   2871 
   2872   if (Tok.is(tok::annot_pragma_ms_pointers_to_members)) {
   2873     HandlePragmaMSPointersToMembers();
   2874     return nullptr;
   2875   }
   2876 
   2877   if (Tok.is(tok::annot_pragma_ms_pragma)) {
   2878     HandlePragmaMSPragma();
   2879     return nullptr;
   2880   }
   2881 
   2882   if (Tok.is(tok::annot_pragma_ms_vtordisp)) {
   2883     HandlePragmaMSVtorDisp();
   2884     return nullptr;
   2885   }
   2886 
   2887   // If we see a namespace here, a close brace was missing somewhere.
   2888   if (Tok.is(tok::kw_namespace)) {
   2889     DiagnoseUnexpectedNamespace(cast<NamedDecl>(TagDecl));
   2890     return nullptr;
   2891   }
   2892 
   2893   AccessSpecifier NewAS = getAccessSpecifierIfPresent();
   2894   if (NewAS != AS_none) {
   2895     // Current token is a C++ access specifier.
   2896     AS = NewAS;
   2897     SourceLocation ASLoc = Tok.getLocation();
   2898     unsigned TokLength = Tok.getLength();
   2899     ConsumeToken();
   2900     AccessAttrs.clear();
   2901     MaybeParseGNUAttributes(AccessAttrs);
   2902 
   2903     SourceLocation EndLoc;
   2904     if (TryConsumeToken(tok::colon, EndLoc)) {
   2905     } else if (TryConsumeToken(tok::semi, EndLoc)) {
   2906       Diag(EndLoc, diag::err_expected)
   2907           << tok::colon << FixItHint::CreateReplacement(EndLoc, ":");
   2908     } else {
   2909       EndLoc = ASLoc.getLocWithOffset(TokLength);
   2910       Diag(EndLoc, diag::err_expected)
   2911           << tok::colon << FixItHint::CreateInsertion(EndLoc, ":");
   2912     }
   2913 
   2914     // The Microsoft extension __interface does not permit non-public
   2915     // access specifiers.
   2916     if (TagType == DeclSpec::TST_interface && AS != AS_public) {
   2917       Diag(ASLoc, diag::err_access_specifier_interface) << (AS == AS_protected);
   2918     }
   2919 
   2920     if (Actions.ActOnAccessSpecifier(NewAS, ASLoc, EndLoc,
   2921                                      AccessAttrs.getList())) {
   2922       // found another attribute than only annotations
   2923       AccessAttrs.clear();
   2924     }
   2925 
   2926     return nullptr;
   2927   }
   2928 
   2929   if (Tok.is(tok::annot_pragma_openmp))
   2930     return ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, AccessAttrs, TagType,
   2931                                                       TagDecl);
   2932 
   2933   // Parse all the comma separated declarators.
   2934   return ParseCXXClassMemberDeclaration(AS, AccessAttrs.getList());
   2935 }
   2936 
   2937 /// ParseCXXMemberSpecification - Parse the class definition.
   2938 ///
   2939 ///       member-specification:
   2940 ///         member-declaration member-specification[opt]
   2941 ///         access-specifier ':' member-specification[opt]
   2942 ///
   2943 void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc,
   2944                                          SourceLocation AttrFixitLoc,
   2945                                          ParsedAttributesWithRange &Attrs,
   2946                                          unsigned TagType, Decl *TagDecl) {
   2947   assert((TagType == DeclSpec::TST_struct ||
   2948          TagType == DeclSpec::TST_interface ||
   2949          TagType == DeclSpec::TST_union  ||
   2950          TagType == DeclSpec::TST_class) && "Invalid TagType!");
   2951 
   2952   PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc,
   2953                                       "parsing struct/union/class body");
   2954 
   2955   // Determine whether this is a non-nested class. Note that local
   2956   // classes are *not* considered to be nested classes.
   2957   bool NonNestedClass = true;
   2958   if (!ClassStack.empty()) {
   2959     for (const Scope *S = getCurScope(); S; S = S->getParent()) {
   2960       if (S->isClassScope()) {
   2961         // We're inside a class scope, so this is a nested class.
   2962         NonNestedClass = false;
   2963 
   2964         // The Microsoft extension __interface does not permit nested classes.
   2965         if (getCurrentClass().IsInterface) {
   2966           Diag(RecordLoc, diag::err_invalid_member_in_interface)
   2967             << /*ErrorType=*/6
   2968             << (isa<NamedDecl>(TagDecl)
   2969                   ? cast<NamedDecl>(TagDecl)->getQualifiedNameAsString()
   2970                   : "(anonymous)");
   2971         }
   2972         break;
   2973       }
   2974 
   2975       if ((S->getFlags() & Scope::FnScope))
   2976         // If we're in a function or function template then this is a local
   2977         // class rather than a nested class.
   2978         break;
   2979     }
   2980   }
   2981 
   2982   // Enter a scope for the class.
   2983   ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
   2984 
   2985   // Note that we are parsing a new (potentially-nested) class definition.
   2986   ParsingClassDefinition ParsingDef(*this, TagDecl, NonNestedClass,
   2987                                     TagType == DeclSpec::TST_interface);
   2988 
   2989   if (TagDecl)
   2990     Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
   2991 
   2992   SourceLocation FinalLoc;
   2993   bool IsFinalSpelledSealed = false;
   2994 
   2995   // Parse the optional 'final' keyword.
   2996   if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
   2997     VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier(Tok);
   2998     assert((Specifier == VirtSpecifiers::VS_Final ||
   2999             Specifier == VirtSpecifiers::VS_Sealed) &&
   3000            "not a class definition");
   3001     FinalLoc = ConsumeToken();
   3002     IsFinalSpelledSealed = Specifier == VirtSpecifiers::VS_Sealed;
   3003 
   3004     if (TagType == DeclSpec::TST_interface)
   3005       Diag(FinalLoc, diag::err_override_control_interface)
   3006         << VirtSpecifiers::getSpecifierName(Specifier);
   3007     else if (Specifier == VirtSpecifiers::VS_Final)
   3008       Diag(FinalLoc, getLangOpts().CPlusPlus11
   3009                          ? diag::warn_cxx98_compat_override_control_keyword
   3010                          : diag::ext_override_control_keyword)
   3011         << VirtSpecifiers::getSpecifierName(Specifier);
   3012     else if (Specifier == VirtSpecifiers::VS_Sealed)
   3013       Diag(FinalLoc, diag::ext_ms_sealed_keyword);
   3014 
   3015     // Parse any C++11 attributes after 'final' keyword.
   3016     // These attributes are not allowed to appear here,
   3017     // and the only possible place for them to appertain
   3018     // to the class would be between class-key and class-name.
   3019     CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
   3020 
   3021     // ParseClassSpecifier() does only a superficial check for attributes before
   3022     // deciding to call this method.  For example, for
   3023     // `class C final alignas ([l) {` it will decide that this looks like a
   3024     // misplaced attribute since it sees `alignas '(' ')'`.  But the actual
   3025     // attribute parsing code will try to parse the '[' as a constexpr lambda
   3026     // and consume enough tokens that the alignas parsing code will eat the
   3027     // opening '{'.  So bail out if the next token isn't one we expect.
   3028     if (!Tok.is(tok::colon) && !Tok.is(tok::l_brace)) {
   3029       if (TagDecl)
   3030         Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
   3031       return;
   3032     }
   3033   }
   3034 
   3035   if (Tok.is(tok::colon)) {
   3036     ParseBaseClause(TagDecl);
   3037     if (!Tok.is(tok::l_brace)) {
   3038       bool SuggestFixIt = false;
   3039       SourceLocation BraceLoc = PP.getLocForEndOfToken(PrevTokLocation);
   3040       if (Tok.isAtStartOfLine()) {
   3041         switch (Tok.getKind()) {
   3042         case tok::kw_private:
   3043         case tok::kw_protected:
   3044         case tok::kw_public:
   3045           SuggestFixIt = NextToken().getKind() == tok::colon;
   3046           break;
   3047         case tok::kw_static_assert:
   3048         case tok::r_brace:
   3049         case tok::kw_using:
   3050         // base-clause can have simple-template-id; 'template' can't be there
   3051         case tok::kw_template:
   3052           SuggestFixIt = true;
   3053           break;
   3054         case tok::identifier:
   3055           SuggestFixIt = isConstructorDeclarator(true);
   3056           break;
   3057         default:
   3058           SuggestFixIt = isCXXSimpleDeclaration(/*AllowForRangeDecl=*/false);
   3059           break;
   3060         }
   3061       }
   3062       DiagnosticBuilder LBraceDiag =
   3063           Diag(BraceLoc, diag::err_expected_lbrace_after_base_specifiers);
   3064       if (SuggestFixIt) {
   3065         LBraceDiag << FixItHint::CreateInsertion(BraceLoc, " {");
   3066         // Try recovering from missing { after base-clause.
   3067         PP.EnterToken(Tok);
   3068         Tok.setKind(tok::l_brace);
   3069       } else {
   3070         if (TagDecl)
   3071           Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
   3072         return;
   3073       }
   3074     }
   3075   }
   3076 
   3077   assert(Tok.is(tok::l_brace));
   3078   BalancedDelimiterTracker T(*this, tok::l_brace);
   3079   T.consumeOpen();
   3080 
   3081   if (TagDecl)
   3082     Actions.ActOnStartCXXMemberDeclarations(getCurScope(), TagDecl, FinalLoc,
   3083                                             IsFinalSpelledSealed,
   3084                                             T.getOpenLocation());
   3085 
   3086   // C++ 11p3: Members of a class defined with the keyword class are private
   3087   // by default. Members of a class defined with the keywords struct or union
   3088   // are public by default.
   3089   AccessSpecifier CurAS;
   3090   if (TagType == DeclSpec::TST_class)
   3091     CurAS = AS_private;
   3092   else
   3093     CurAS = AS_public;
   3094   ParsedAttributesWithRange AccessAttrs(AttrFactory);
   3095 
   3096   if (TagDecl) {
   3097     // While we still have something to read, read the member-declarations.
   3098     while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
   3099            Tok.isNot(tok::eof)) {
   3100       // Each iteration of this loop reads one member-declaration.
   3101       ParseCXXClassMemberDeclarationWithPragmas(
   3102           CurAS, AccessAttrs, static_cast<DeclSpec::TST>(TagType), TagDecl);
   3103     }
   3104     T.consumeClose();
   3105   } else {
   3106     SkipUntil(tok::r_brace);
   3107   }
   3108 
   3109   // If attributes exist after class contents, parse them.
   3110   ParsedAttributes attrs(AttrFactory);
   3111   MaybeParseGNUAttributes(attrs);
   3112 
   3113   if (TagDecl)
   3114     Actions.ActOnFinishCXXMemberSpecification(getCurScope(), RecordLoc, TagDecl,
   3115                                               T.getOpenLocation(),
   3116                                               T.getCloseLocation(),
   3117                                               attrs.getList());
   3118 
   3119   // C++11 [class.mem]p2:
   3120   //   Within the class member-specification, the class is regarded as complete
   3121   //   within function bodies, default arguments, exception-specifications, and
   3122   //   brace-or-equal-initializers for non-static data members (including such
   3123   //   things in nested classes).
   3124   if (TagDecl && NonNestedClass) {
   3125     // We are not inside a nested class. This class and its nested classes
   3126     // are complete and we can parse the delayed portions of method
   3127     // declarations and the lexed inline method definitions, along with any
   3128     // delayed attributes.
   3129     SourceLocation SavedPrevTokLocation = PrevTokLocation;
   3130     ParseLexedAttributes(getCurrentClass());
   3131     ParseLexedMethodDeclarations(getCurrentClass());
   3132 
   3133     // We've finished with all pending member declarations.
   3134     Actions.ActOnFinishCXXMemberDecls();
   3135 
   3136     ParseLexedMemberInitializers(getCurrentClass());
   3137     ParseLexedMethodDefs(getCurrentClass());
   3138     PrevTokLocation = SavedPrevTokLocation;
   3139 
   3140     // We've finished parsing everything, including default argument
   3141     // initializers.
   3142     Actions.ActOnFinishCXXNonNestedClass(TagDecl);
   3143   }
   3144 
   3145   if (TagDecl)
   3146     Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl,
   3147                                      T.getCloseLocation());
   3148 
   3149   // Leave the class scope.
   3150   ParsingDef.Pop();
   3151   ClassScope.Exit();
   3152 }
   3153 
   3154 void Parser::DiagnoseUnexpectedNamespace(NamedDecl *D) {
   3155   assert(Tok.is(tok::kw_namespace));
   3156 
   3157   // FIXME: Suggest where the close brace should have gone by looking
   3158   // at indentation changes within the definition body.
   3159   Diag(D->getLocation(),
   3160        diag::err_missing_end_of_definition) << D;
   3161   Diag(Tok.getLocation(),
   3162        diag::note_missing_end_of_definition_before) << D;
   3163 
   3164   // Push '};' onto the token stream to recover.
   3165   PP.EnterToken(Tok);
   3166 
   3167   Tok.startToken();
   3168   Tok.setLocation(PP.getLocForEndOfToken(PrevTokLocation));
   3169   Tok.setKind(tok::semi);
   3170   PP.EnterToken(Tok);
   3171 
   3172   Tok.setKind(tok::r_brace);
   3173 }
   3174 
   3175 /// ParseConstructorInitializer - Parse a C++ constructor initializer,
   3176 /// which explicitly initializes the members or base classes of a
   3177 /// class (C++ [class.base.init]). For example, the three initializers
   3178 /// after the ':' in the Derived constructor below:
   3179 ///
   3180 /// @code
   3181 /// class Base { };
   3182 /// class Derived : Base {
   3183 ///   int x;
   3184 ///   float f;
   3185 /// public:
   3186 ///   Derived(float f) : Base(), x(17), f(f) { }
   3187 /// };
   3188 /// @endcode
   3189 ///
   3190 /// [C++]  ctor-initializer:
   3191 ///          ':' mem-initializer-list
   3192 ///
   3193 /// [C++]  mem-initializer-list:
   3194 ///          mem-initializer ...[opt]
   3195 ///          mem-initializer ...[opt] , mem-initializer-list
   3196 void Parser::ParseConstructorInitializer(Decl *ConstructorDecl) {
   3197   assert(Tok.is(tok::colon) &&
   3198          "Constructor initializer always starts with ':'");
   3199 
   3200   // Poison the SEH identifiers so they are flagged as illegal in constructor
   3201   // initializers.
   3202   PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
   3203   SourceLocation ColonLoc = ConsumeToken();
   3204 
   3205   SmallVector<CXXCtorInitializer*, 4> MemInitializers;
   3206   bool AnyErrors = false;
   3207 
   3208   do {
   3209     if (Tok.is(tok::code_completion)) {
   3210       Actions.CodeCompleteConstructorInitializer(ConstructorDecl,
   3211                                                  MemInitializers);
   3212       return cutOffParsing();
   3213     }
   3214 
   3215     MemInitResult MemInit = ParseMemInitializer(ConstructorDecl);
   3216     if (!MemInit.isInvalid())
   3217       MemInitializers.push_back(MemInit.get());
   3218     else
   3219       AnyErrors = true;
   3220 
   3221     if (Tok.is(tok::comma))
   3222       ConsumeToken();
   3223     else if (Tok.is(tok::l_brace))
   3224       break;
   3225     // If the previous initializer was valid and the next token looks like a
   3226     // base or member initializer, assume that we're just missing a comma.
   3227     else if (!MemInit.isInvalid() &&
   3228              Tok.isOneOf(tok::identifier, tok::coloncolon)) {
   3229       SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation);
   3230       Diag(Loc, diag::err_ctor_init_missing_comma)
   3231         << FixItHint::CreateInsertion(Loc, ", ");
   3232     } else {
   3233       // Skip over garbage, until we get to '{'.  Don't eat the '{'.
   3234       if (!MemInit.isInvalid())
   3235         Diag(Tok.getLocation(), diag::err_expected_either) << tok::l_brace
   3236                                                            << tok::comma;
   3237       SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
   3238       break;
   3239     }
   3240   } while (true);
   3241 
   3242   Actions.ActOnMemInitializers(ConstructorDecl, ColonLoc, MemInitializers,
   3243                                AnyErrors);
   3244 }
   3245 
   3246 /// ParseMemInitializer - Parse a C++ member initializer, which is
   3247 /// part of a constructor initializer that explicitly initializes one
   3248 /// member or base class (C++ [class.base.init]). See
   3249 /// ParseConstructorInitializer for an example.
   3250 ///
   3251 /// [C++] mem-initializer:
   3252 ///         mem-initializer-id '(' expression-list[opt] ')'
   3253 /// [C++0x] mem-initializer-id braced-init-list
   3254 ///
   3255 /// [C++] mem-initializer-id:
   3256 ///         '::'[opt] nested-name-specifier[opt] class-name
   3257 ///         identifier
   3258 MemInitResult Parser::ParseMemInitializer(Decl *ConstructorDecl) {
   3259   // parse '::'[opt] nested-name-specifier[opt]
   3260   CXXScopeSpec SS;
   3261   ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false);
   3262   ParsedType TemplateTypeTy;
   3263   if (Tok.is(tok::annot_template_id)) {
   3264     TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
   3265     if (TemplateId->Kind == TNK_Type_template ||
   3266         TemplateId->Kind == TNK_Dependent_template_name) {
   3267       AnnotateTemplateIdTokenAsType();
   3268       assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
   3269       TemplateTypeTy = getTypeAnnotation(Tok);
   3270     }
   3271   }
   3272   // Uses of decltype will already have been converted to annot_decltype by
   3273   // ParseOptionalCXXScopeSpecifier at this point.
   3274   if (!TemplateTypeTy && Tok.isNot(tok::identifier)
   3275       && Tok.isNot(tok::annot_decltype)) {
   3276     Diag(Tok, diag::err_expected_member_or_base_name);
   3277     return true;
   3278   }
   3279 
   3280   IdentifierInfo *II = nullptr;
   3281   DeclSpec DS(AttrFactory);
   3282   SourceLocation IdLoc = Tok.getLocation();
   3283   if (Tok.is(tok::annot_decltype)) {
   3284     // Get the decltype expression, if there is one.
   3285     ParseDecltypeSpecifier(DS);
   3286   } else {
   3287     if (Tok.is(tok::identifier))
   3288       // Get the identifier. This may be a member name or a class name,
   3289       // but we'll let the semantic analysis determine which it is.
   3290       II = Tok.getIdentifierInfo();
   3291     ConsumeToken();
   3292   }
   3293 
   3294 
   3295   // Parse the '('.
   3296   if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
   3297     Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
   3298 
   3299     ExprResult InitList = ParseBraceInitializer();
   3300     if (InitList.isInvalid())
   3301       return true;
   3302 
   3303     SourceLocation EllipsisLoc;
   3304     TryConsumeToken(tok::ellipsis, EllipsisLoc);
   3305 
   3306     return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
   3307                                        TemplateTypeTy, DS, IdLoc,
   3308                                        InitList.get(), EllipsisLoc);
   3309   } else if(Tok.is(tok::l_paren)) {
   3310     BalancedDelimiterTracker T(*this, tok::l_paren);
   3311     T.consumeOpen();
   3312 
   3313     // Parse the optional expression-list.
   3314     ExprVector ArgExprs;
   3315     CommaLocsTy CommaLocs;
   3316     if (Tok.isNot(tok::r_paren) && ParseExpressionList(ArgExprs, CommaLocs)) {
   3317       SkipUntil(tok::r_paren, StopAtSemi);
   3318       return true;
   3319     }
   3320 
   3321     T.consumeClose();
   3322 
   3323     SourceLocation EllipsisLoc;
   3324     TryConsumeToken(tok::ellipsis, EllipsisLoc);
   3325 
   3326     return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
   3327                                        TemplateTypeTy, DS, IdLoc,
   3328                                        T.getOpenLocation(), ArgExprs,
   3329                                        T.getCloseLocation(), EllipsisLoc);
   3330   }
   3331 
   3332   if (getLangOpts().CPlusPlus11)
   3333     return Diag(Tok, diag::err_expected_either) << tok::l_paren << tok::l_brace;
   3334   else
   3335     return Diag(Tok, diag::err_expected) << tok::l_paren;
   3336 }
   3337 
   3338 /// \brief Parse a C++ exception-specification if present (C++0x [except.spec]).
   3339 ///
   3340 ///       exception-specification:
   3341 ///         dynamic-exception-specification
   3342 ///         noexcept-specification
   3343 ///
   3344 ///       noexcept-specification:
   3345 ///         'noexcept'
   3346 ///         'noexcept' '(' constant-expression ')'
   3347 ExceptionSpecificationType
   3348 Parser::tryParseExceptionSpecification(bool Delayed,
   3349                     SourceRange &SpecificationRange,
   3350                     SmallVectorImpl<ParsedType> &DynamicExceptions,
   3351                     SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
   3352                     ExprResult &NoexceptExpr,
   3353                     CachedTokens *&ExceptionSpecTokens) {
   3354   ExceptionSpecificationType Result = EST_None;
   3355   ExceptionSpecTokens = nullptr;
   3356 
   3357   // Handle delayed parsing of exception-specifications.
   3358   if (Delayed) {
   3359     if (Tok.isNot(tok::kw_throw) && Tok.isNot(tok::kw_noexcept))
   3360       return EST_None;
   3361 
   3362     // Consume and cache the starting token.
   3363     bool IsNoexcept = Tok.is(tok::kw_noexcept);
   3364     Token StartTok = Tok;
   3365     SpecificationRange = SourceRange(ConsumeToken());
   3366 
   3367     // Check for a '('.
   3368     if (!Tok.is(tok::l_paren)) {
   3369       // If this is a bare 'noexcept', we're done.
   3370       if (IsNoexcept) {
   3371         Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
   3372         NoexceptExpr = nullptr;
   3373         return EST_BasicNoexcept;
   3374       }
   3375 
   3376       Diag(Tok, diag::err_expected_lparen_after) << "throw";
   3377       return EST_DynamicNone;
   3378     }
   3379 
   3380     // Cache the tokens for the exception-specification.
   3381     ExceptionSpecTokens = new CachedTokens;
   3382     ExceptionSpecTokens->push_back(StartTok); // 'throw' or 'noexcept'
   3383     ExceptionSpecTokens->push_back(Tok); // '('
   3384     SpecificationRange.setEnd(ConsumeParen()); // '('
   3385 
   3386     ConsumeAndStoreUntil(tok::r_paren, *ExceptionSpecTokens,
   3387                          /*StopAtSemi=*/true,
   3388                          /*ConsumeFinalToken=*/true);
   3389     SpecificationRange.setEnd(ExceptionSpecTokens->back().getLocation());
   3390 
   3391     return EST_Unparsed;
   3392   }
   3393 
   3394   // See if there's a dynamic specification.
   3395   if (Tok.is(tok::kw_throw)) {
   3396     Result = ParseDynamicExceptionSpecification(SpecificationRange,
   3397                                                 DynamicExceptions,
   3398                                                 DynamicExceptionRanges);
   3399     assert(DynamicExceptions.size() == DynamicExceptionRanges.size() &&
   3400            "Produced different number of exception types and ranges.");
   3401   }
   3402 
   3403   // If there's no noexcept specification, we're done.
   3404   if (Tok.isNot(tok::kw_noexcept))
   3405     return Result;
   3406 
   3407   Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
   3408 
   3409   // If we already had a dynamic specification, parse the noexcept for,
   3410   // recovery, but emit a diagnostic and don't store the results.
   3411   SourceRange NoexceptRange;
   3412   ExceptionSpecificationType NoexceptType = EST_None;
   3413 
   3414   SourceLocation KeywordLoc = ConsumeToken();
   3415   if (Tok.is(tok::l_paren)) {
   3416     // There is an argument.
   3417     BalancedDelimiterTracker T(*this, tok::l_paren);
   3418     T.consumeOpen();
   3419     NoexceptType = EST_ComputedNoexcept;
   3420     NoexceptExpr = ParseConstantExpression();
   3421     T.consumeClose();
   3422     // The argument must be contextually convertible to bool. We use
   3423     // CheckBooleanCondition for this purpose.
   3424     // FIXME: Add a proper Sema entry point for this.
   3425     if (!NoexceptExpr.isInvalid()) {
   3426       NoexceptExpr =
   3427           Actions.CheckBooleanCondition(KeywordLoc, NoexceptExpr.get());
   3428       NoexceptRange = SourceRange(KeywordLoc, T.getCloseLocation());
   3429     } else {
   3430       NoexceptType = EST_None;
   3431     }
   3432   } else {
   3433     // There is no argument.
   3434     NoexceptType = EST_BasicNoexcept;
   3435     NoexceptRange = SourceRange(KeywordLoc, KeywordLoc);
   3436   }
   3437 
   3438   if (Result == EST_None) {
   3439     SpecificationRange = NoexceptRange;
   3440     Result = NoexceptType;
   3441 
   3442     // If there's a dynamic specification after a noexcept specification,
   3443     // parse that and ignore the results.
   3444     if (Tok.is(tok::kw_throw)) {
   3445       Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
   3446       ParseDynamicExceptionSpecification(NoexceptRange, DynamicExceptions,
   3447                                          DynamicExceptionRanges);
   3448     }
   3449   } else {
   3450     Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
   3451   }
   3452 
   3453   return Result;
   3454 }
   3455 
   3456 static void diagnoseDynamicExceptionSpecification(
   3457     Parser &P, SourceRange Range, bool IsNoexcept) {
   3458   if (P.getLangOpts().CPlusPlus11) {
   3459     const char *Replacement = IsNoexcept ? "noexcept" : "noexcept(false)";
   3460     P.Diag(Range.getBegin(), diag::warn_exception_spec_deprecated) << Range;
   3461     P.Diag(Range.getBegin(), diag::note_exception_spec_deprecated)
   3462       << Replacement << FixItHint::CreateReplacement(Range, Replacement);
   3463   }
   3464 }
   3465 
   3466 /// ParseDynamicExceptionSpecification - Parse a C++
   3467 /// dynamic-exception-specification (C++ [except.spec]).
   3468 ///
   3469 ///       dynamic-exception-specification:
   3470 ///         'throw' '(' type-id-list [opt] ')'
   3471 /// [MS]    'throw' '(' '...' ')'
   3472 ///
   3473 ///       type-id-list:
   3474 ///         type-id ... [opt]
   3475 ///         type-id-list ',' type-id ... [opt]
   3476 ///
   3477 ExceptionSpecificationType Parser::ParseDynamicExceptionSpecification(
   3478                                   SourceRange &SpecificationRange,
   3479                                   SmallVectorImpl<ParsedType> &Exceptions,
   3480                                   SmallVectorImpl<SourceRange> &Ranges) {
   3481   assert(Tok.is(tok::kw_throw) && "expected throw");
   3482 
   3483   SpecificationRange.setBegin(ConsumeToken());
   3484   BalancedDelimiterTracker T(*this, tok::l_paren);
   3485   if (T.consumeOpen()) {
   3486     Diag(Tok, diag::err_expected_lparen_after) << "throw";
   3487     SpecificationRange.setEnd(SpecificationRange.getBegin());
   3488     return EST_DynamicNone;
   3489   }
   3490 
   3491   // Parse throw(...), a Microsoft extension that means "this function
   3492   // can throw anything".
   3493   if (Tok.is(tok::ellipsis)) {
   3494     SourceLocation EllipsisLoc = ConsumeToken();
   3495     if (!getLangOpts().MicrosoftExt)
   3496       Diag(EllipsisLoc, diag::ext_ellipsis_exception_spec);
   3497     T.consumeClose();
   3498     SpecificationRange.setEnd(T.getCloseLocation());
   3499     diagnoseDynamicExceptionSpecification(*this, SpecificationRange, false);
   3500     return EST_MSAny;
   3501   }
   3502 
   3503   // Parse the sequence of type-ids.
   3504   SourceRange Range;
   3505   while (Tok.isNot(tok::r_paren)) {
   3506     TypeResult Res(ParseTypeName(&Range));
   3507 
   3508     if (Tok.is(tok::ellipsis)) {
   3509       // C++0x [temp.variadic]p5:
   3510       //   - In a dynamic-exception-specification (15.4); the pattern is a
   3511       //     type-id.
   3512       SourceLocation Ellipsis = ConsumeToken();
   3513       Range.setEnd(Ellipsis);
   3514       if (!Res.isInvalid())
   3515         Res = Actions.ActOnPackExpansion(Res.get(), Ellipsis);
   3516     }
   3517 
   3518     if (!Res.isInvalid()) {
   3519       Exceptions.push_back(Res.get());
   3520       Ranges.push_back(Range);
   3521     }
   3522 
   3523     if (!TryConsumeToken(tok::comma))
   3524       break;
   3525   }
   3526 
   3527   T.consumeClose();
   3528   SpecificationRange.setEnd(T.getCloseLocation());
   3529   diagnoseDynamicExceptionSpecification(*this, SpecificationRange,
   3530                                         Exceptions.empty());
   3531   return Exceptions.empty() ? EST_DynamicNone : EST_Dynamic;
   3532 }
   3533 
   3534 /// ParseTrailingReturnType - Parse a trailing return type on a new-style
   3535 /// function declaration.
   3536 TypeResult Parser::ParseTrailingReturnType(SourceRange &Range) {
   3537   assert(Tok.is(tok::arrow) && "expected arrow");
   3538 
   3539   ConsumeToken();
   3540 
   3541   return ParseTypeName(&Range, Declarator::TrailingReturnContext);
   3542 }
   3543 
   3544 /// \brief We have just started parsing the definition of a new class,
   3545 /// so push that class onto our stack of classes that is currently
   3546 /// being parsed.
   3547 Sema::ParsingClassState
   3548 Parser::PushParsingClass(Decl *ClassDecl, bool NonNestedClass,
   3549                          bool IsInterface) {
   3550   assert((NonNestedClass || !ClassStack.empty()) &&
   3551          "Nested class without outer class");
   3552   ClassStack.push(new ParsingClass(ClassDecl, NonNestedClass, IsInterface));
   3553   return Actions.PushParsingClass();
   3554 }
   3555 
   3556 /// \brief Deallocate the given parsed class and all of its nested
   3557 /// classes.
   3558 void Parser::DeallocateParsedClasses(Parser::ParsingClass *Class) {
   3559   for (unsigned I = 0, N = Class->LateParsedDeclarations.size(); I != N; ++I)
   3560     delete Class->LateParsedDeclarations[I];
   3561   delete Class;
   3562 }
   3563 
   3564 /// \brief Pop the top class of the stack of classes that are
   3565 /// currently being parsed.
   3566 ///
   3567 /// This routine should be called when we have finished parsing the
   3568 /// definition of a class, but have not yet popped the Scope
   3569 /// associated with the class's definition.
   3570 void Parser::PopParsingClass(Sema::ParsingClassState state) {
   3571   assert(!ClassStack.empty() && "Mismatched push/pop for class parsing");
   3572 
   3573   Actions.PopParsingClass(state);
   3574 
   3575   ParsingClass *Victim = ClassStack.top();
   3576   ClassStack.pop();
   3577   if (Victim->TopLevelClass) {
   3578     // Deallocate all of the nested classes of this class,
   3579     // recursively: we don't need to keep any of this information.
   3580     DeallocateParsedClasses(Victim);
   3581     return;
   3582   }
   3583   assert(!ClassStack.empty() && "Missing top-level class?");
   3584 
   3585   if (Victim->LateParsedDeclarations.empty()) {
   3586     // The victim is a nested class, but we will not need to perform
   3587     // any processing after the definition of this class since it has
   3588     // no members whose handling was delayed. Therefore, we can just
   3589     // remove this nested class.
   3590     DeallocateParsedClasses(Victim);
   3591     return;
   3592   }
   3593 
   3594   // This nested class has some members that will need to be processed
   3595   // after the top-level class is completely defined. Therefore, add
   3596   // it to the list of nested classes within its parent.
   3597   assert(getCurScope()->isClassScope() && "Nested class outside of class scope?");
   3598   ClassStack.top()->LateParsedDeclarations.push_back(new LateParsedClass(this, Victim));
   3599   Victim->TemplateScope = getCurScope()->getParent()->isTemplateParamScope();
   3600 }
   3601 
   3602 /// \brief Try to parse an 'identifier' which appears within an attribute-token.
   3603 ///
   3604 /// \return the parsed identifier on success, and 0 if the next token is not an
   3605 /// attribute-token.
   3606 ///
   3607 /// C++11 [dcl.attr.grammar]p3:
   3608 ///   If a keyword or an alternative token that satisfies the syntactic
   3609 ///   requirements of an identifier is contained in an attribute-token,
   3610 ///   it is considered an identifier.
   3611 IdentifierInfo *Parser::TryParseCXX11AttributeIdentifier(SourceLocation &Loc) {
   3612   switch (Tok.getKind()) {
   3613   default:
   3614     // Identifiers and keywords have identifier info attached.
   3615     if (!Tok.isAnnotation()) {
   3616       if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
   3617         Loc = ConsumeToken();
   3618         return II;
   3619       }
   3620     }
   3621     return nullptr;
   3622 
   3623   case tok::ampamp:       // 'and'
   3624   case tok::pipe:         // 'bitor'
   3625   case tok::pipepipe:     // 'or'
   3626   case tok::caret:        // 'xor'
   3627   case tok::tilde:        // 'compl'
   3628   case tok::amp:          // 'bitand'
   3629   case tok::ampequal:     // 'and_eq'
   3630   case tok::pipeequal:    // 'or_eq'
   3631   case tok::caretequal:   // 'xor_eq'
   3632   case tok::exclaim:      // 'not'
   3633   case tok::exclaimequal: // 'not_eq'
   3634     // Alternative tokens do not have identifier info, but their spelling
   3635     // starts with an alphabetical character.
   3636     SmallString<8> SpellingBuf;
   3637     SourceLocation SpellingLoc =
   3638         PP.getSourceManager().getSpellingLoc(Tok.getLocation());
   3639     StringRef Spelling = PP.getSpelling(SpellingLoc, SpellingBuf);
   3640     if (isLetter(Spelling[0])) {
   3641       Loc = ConsumeToken();
   3642       return &PP.getIdentifierTable().get(Spelling);
   3643     }
   3644     return nullptr;
   3645   }
   3646 }
   3647 
   3648 static bool IsBuiltInOrStandardCXX11Attribute(IdentifierInfo *AttrName,
   3649                                                IdentifierInfo *ScopeName) {
   3650   switch (AttributeList::getKind(AttrName, ScopeName,
   3651                                  AttributeList::AS_CXX11)) {
   3652   case AttributeList::AT_CarriesDependency:
   3653   case AttributeList::AT_Deprecated:
   3654   case AttributeList::AT_FallThrough:
   3655   case AttributeList::AT_CXX11NoReturn:
   3656     return true;
   3657   case AttributeList::AT_WarnUnusedResult:
   3658     return !ScopeName && AttrName->getName().equals("nodiscard");
   3659   case AttributeList::AT_Unused:
   3660     return !ScopeName && AttrName->getName().equals("maybe_unused");
   3661   default:
   3662     return false;
   3663   }
   3664 }
   3665 
   3666 /// ParseCXX11AttributeArgs -- Parse a C++11 attribute-argument-clause.
   3667 ///
   3668 /// [C++11] attribute-argument-clause:
   3669 ///         '(' balanced-token-seq ')'
   3670 ///
   3671 /// [C++11] balanced-token-seq:
   3672 ///         balanced-token
   3673 ///         balanced-token-seq balanced-token
   3674 ///
   3675 /// [C++11] balanced-token:
   3676 ///         '(' balanced-token-seq ')'
   3677 ///         '[' balanced-token-seq ']'
   3678 ///         '{' balanced-token-seq '}'
   3679 ///         any token but '(', ')', '[', ']', '{', or '}'
   3680 bool Parser::ParseCXX11AttributeArgs(IdentifierInfo *AttrName,
   3681                                      SourceLocation AttrNameLoc,
   3682                                      ParsedAttributes &Attrs,
   3683                                      SourceLocation *EndLoc,
   3684                                      IdentifierInfo *ScopeName,
   3685                                      SourceLocation ScopeLoc) {
   3686   assert(Tok.is(tok::l_paren) && "Not a C++11 attribute argument list");
   3687   SourceLocation LParenLoc = Tok.getLocation();
   3688 
   3689   // If the attribute isn't known, we will not attempt to parse any
   3690   // arguments.
   3691   if (!hasAttribute(AttrSyntax::CXX, ScopeName, AttrName,
   3692                     getTargetInfo(), getLangOpts())) {
   3693     // Eat the left paren, then skip to the ending right paren.
   3694     ConsumeParen();
   3695     SkipUntil(tok::r_paren);
   3696     return false;
   3697   }
   3698 
   3699   if (ScopeName && ScopeName->getName() == "gnu")
   3700     // GNU-scoped attributes have some special cases to handle GNU-specific
   3701     // behaviors.
   3702     ParseGNUAttributeArgs(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
   3703                           ScopeLoc, AttributeList::AS_CXX11, nullptr);
   3704   else {
   3705     unsigned NumArgs =
   3706         ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc,
   3707                                  ScopeName, ScopeLoc, AttributeList::AS_CXX11);
   3708 
   3709     const AttributeList *Attr = Attrs.getList();
   3710     if (Attr && IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName)) {
   3711       // If the attribute is a standard or built-in attribute and we are
   3712       // parsing an argument list, we need to determine whether this attribute
   3713       // was allowed to have an argument list (such as [[deprecated]]), and how
   3714       // many arguments were parsed (so we can diagnose on [[deprecated()]]).
   3715       if (Attr->getMaxArgs() && !NumArgs) {
   3716         // The attribute was allowed to have arguments, but none were provided
   3717         // even though the attribute parsed successfully. This is an error.
   3718         Diag(LParenLoc, diag::err_attribute_requires_arguments) << AttrName;
   3719         Attr->setInvalid(true);
   3720       } else if (!Attr->getMaxArgs()) {
   3721         // The attribute parsed successfully, but was not allowed to have any
   3722         // arguments. It doesn't matter whether any were provided -- the
   3723         // presence of the argument list (even if empty) is diagnosed.
   3724         Diag(LParenLoc, diag::err_cxx11_attribute_forbids_arguments)
   3725             << AttrName
   3726             << FixItHint::CreateRemoval(SourceRange(LParenLoc, *EndLoc));
   3727         Attr->setInvalid(true);
   3728       }
   3729     }
   3730   }
   3731   return true;
   3732 }
   3733 
   3734 /// ParseCXX11AttributeSpecifier - Parse a C++11 attribute-specifier.
   3735 ///
   3736 /// [C++11] attribute-specifier:
   3737 ///         '[' '[' attribute-list ']' ']'
   3738 ///         alignment-specifier
   3739 ///
   3740 /// [C++11] attribute-list:
   3741 ///         attribute[opt]
   3742 ///         attribute-list ',' attribute[opt]
   3743 ///         attribute '...'
   3744 ///         attribute-list ',' attribute '...'
   3745 ///
   3746 /// [C++11] attribute:
   3747 ///         attribute-token attribute-argument-clause[opt]
   3748 ///
   3749 /// [C++11] attribute-token:
   3750 ///         identifier
   3751 ///         attribute-scoped-token
   3752 ///
   3753 /// [C++11] attribute-scoped-token:
   3754 ///         attribute-namespace '::' identifier
   3755 ///
   3756 /// [C++11] attribute-namespace:
   3757 ///         identifier
   3758 void Parser::ParseCXX11AttributeSpecifier(ParsedAttributes &attrs,
   3759                                           SourceLocation *endLoc) {
   3760   if (Tok.is(tok::kw_alignas)) {
   3761     Diag(Tok.getLocation(), diag::warn_cxx98_compat_alignas);
   3762     ParseAlignmentSpecifier(attrs, endLoc);
   3763     return;
   3764   }
   3765 
   3766   assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square)
   3767       && "Not a C++11 attribute list");
   3768 
   3769   Diag(Tok.getLocation(), diag::warn_cxx98_compat_attribute);
   3770 
   3771   ConsumeBracket();
   3772   ConsumeBracket();
   3773 
   3774   SourceLocation CommonScopeLoc;
   3775   IdentifierInfo *CommonScopeName = nullptr;
   3776   if (Tok.is(tok::kw_using)) {
   3777     Diag(Tok.getLocation(), getLangOpts().CPlusPlus1z
   3778                                 ? diag::warn_cxx14_compat_using_attribute_ns
   3779                                 : diag::ext_using_attribute_ns);
   3780     ConsumeToken();
   3781 
   3782     CommonScopeName = TryParseCXX11AttributeIdentifier(CommonScopeLoc);
   3783     if (!CommonScopeName) {
   3784       Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
   3785       SkipUntil(tok::r_square, tok::colon, StopBeforeMatch);
   3786     }
   3787     if (!TryConsumeToken(tok::colon) && CommonScopeName)
   3788       Diag(Tok.getLocation(), diag::err_expected) << tok::colon;
   3789   }
   3790 
   3791   llvm::SmallDenseMap<IdentifierInfo*, SourceLocation, 4> SeenAttrs;
   3792 
   3793   while (Tok.isNot(tok::r_square)) {
   3794     // attribute not present
   3795     if (TryConsumeToken(tok::comma))
   3796       continue;
   3797 
   3798     SourceLocation ScopeLoc, AttrLoc;
   3799     IdentifierInfo *ScopeName = nullptr, *AttrName = nullptr;
   3800 
   3801     AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
   3802     if (!AttrName)
   3803       // Break out to the "expected ']'" diagnostic.
   3804       break;
   3805 
   3806     // scoped attribute
   3807     if (TryConsumeToken(tok::coloncolon)) {
   3808       ScopeName = AttrName;
   3809       ScopeLoc = AttrLoc;
   3810 
   3811       AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
   3812       if (!AttrName) {
   3813         Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
   3814         SkipUntil(tok::r_square, tok::comma, StopAtSemi | StopBeforeMatch);
   3815         continue;
   3816       }
   3817     }
   3818 
   3819     if (CommonScopeName) {
   3820       if (ScopeName) {
   3821         Diag(ScopeLoc, diag::err_using_attribute_ns_conflict)
   3822             << SourceRange(CommonScopeLoc);
   3823       } else {
   3824         ScopeName = CommonScopeName;
   3825         ScopeLoc = CommonScopeLoc;
   3826       }
   3827     }
   3828 
   3829     bool StandardAttr = IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName);
   3830     bool AttrParsed = false;
   3831 
   3832     if (StandardAttr &&
   3833         !SeenAttrs.insert(std::make_pair(AttrName, AttrLoc)).second)
   3834       Diag(AttrLoc, diag::err_cxx11_attribute_repeated)
   3835           << AttrName << SourceRange(SeenAttrs[AttrName]);
   3836 
   3837     // Parse attribute arguments
   3838     if (Tok.is(tok::l_paren))
   3839       AttrParsed = ParseCXX11AttributeArgs(AttrName, AttrLoc, attrs, endLoc,
   3840                                            ScopeName, ScopeLoc);
   3841 
   3842     if (!AttrParsed)
   3843       attrs.addNew(AttrName,
   3844                    SourceRange(ScopeLoc.isValid() ? ScopeLoc : AttrLoc,
   3845                                AttrLoc),
   3846                    ScopeName, ScopeLoc, nullptr, 0, AttributeList::AS_CXX11);
   3847 
   3848     if (TryConsumeToken(tok::ellipsis))
   3849       Diag(Tok, diag::err_cxx11_attribute_forbids_ellipsis)
   3850         << AttrName->getName();
   3851   }
   3852 
   3853   if (ExpectAndConsume(tok::r_square))
   3854     SkipUntil(tok::r_square);
   3855   if (endLoc)
   3856     *endLoc = Tok.getLocation();
   3857   if (ExpectAndConsume(tok::r_square))
   3858     SkipUntil(tok::r_square);
   3859 }
   3860 
   3861 /// ParseCXX11Attributes - Parse a C++11 attribute-specifier-seq.
   3862 ///
   3863 /// attribute-specifier-seq:
   3864 ///       attribute-specifier-seq[opt] attribute-specifier
   3865 void Parser::ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
   3866                                   SourceLocation *endLoc) {
   3867   assert(getLangOpts().CPlusPlus11);
   3868 
   3869   SourceLocation StartLoc = Tok.getLocation(), Loc;
   3870   if (!endLoc)
   3871     endLoc = &Loc;
   3872 
   3873   do {
   3874     ParseCXX11AttributeSpecifier(attrs, endLoc);
   3875   } while (isCXX11AttributeSpecifier());
   3876 
   3877   attrs.Range = SourceRange(StartLoc, *endLoc);
   3878 }
   3879 
   3880 void Parser::DiagnoseAndSkipCXX11Attributes() {
   3881   // Start and end location of an attribute or an attribute list.
   3882   SourceLocation StartLoc = Tok.getLocation();
   3883   SourceLocation EndLoc = SkipCXX11Attributes();
   3884 
   3885   if (EndLoc.isValid()) {
   3886     SourceRange Range(StartLoc, EndLoc);
   3887     Diag(StartLoc, diag::err_attributes_not_allowed)
   3888       << Range;
   3889   }
   3890 }
   3891 
   3892 SourceLocation Parser::SkipCXX11Attributes() {
   3893   SourceLocation EndLoc;
   3894 
   3895   if (!isCXX11AttributeSpecifier())
   3896     return EndLoc;
   3897 
   3898   do {
   3899     if (Tok.is(tok::l_square)) {
   3900       BalancedDelimiterTracker T(*this, tok::l_square);
   3901       T.consumeOpen();
   3902       T.skipToEnd();
   3903       EndLoc = T.getCloseLocation();
   3904     } else {
   3905       assert(Tok.is(tok::kw_alignas) && "not an attribute specifier");
   3906       ConsumeToken();
   3907       BalancedDelimiterTracker T(*this, tok::l_paren);
   3908       if (!T.consumeOpen())
   3909         T.skipToEnd();
   3910       EndLoc = T.getCloseLocation();
   3911     }
   3912   } while (isCXX11AttributeSpecifier());
   3913 
   3914   return EndLoc;
   3915 }
   3916 
   3917 /// ParseMicrosoftAttributes - Parse Microsoft attributes [Attr]
   3918 ///
   3919 /// [MS] ms-attribute:
   3920 ///             '[' token-seq ']'
   3921 ///
   3922 /// [MS] ms-attribute-seq:
   3923 ///             ms-attribute[opt]
   3924 ///             ms-attribute ms-attribute-seq
   3925 void Parser::ParseMicrosoftAttributes(ParsedAttributes &attrs,
   3926                                       SourceLocation *endLoc) {
   3927   assert(Tok.is(tok::l_square) && "Not a Microsoft attribute list");
   3928 
   3929   do {
   3930     // FIXME: If this is actually a C++11 attribute, parse it as one.
   3931     BalancedDelimiterTracker T(*this, tok::l_square);
   3932     T.consumeOpen();
   3933     SkipUntil(tok::r_square, StopAtSemi | StopBeforeMatch);
   3934     T.consumeClose();
   3935     if (endLoc)
   3936       *endLoc = T.getCloseLocation();
   3937   } while (Tok.is(tok::l_square));
   3938 }
   3939 
   3940 void Parser::ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType,
   3941                                                     AccessSpecifier& CurAS) {
   3942   IfExistsCondition Result;
   3943   if (ParseMicrosoftIfExistsCondition(Result))
   3944     return;
   3945 
   3946   BalancedDelimiterTracker Braces(*this, tok::l_brace);
   3947   if (Braces.consumeOpen()) {
   3948     Diag(Tok, diag::err_expected) << tok::l_brace;
   3949     return;
   3950   }
   3951 
   3952   switch (Result.Behavior) {
   3953   case IEB_Parse:
   3954     // Parse the declarations below.
   3955     break;
   3956 
   3957   case IEB_Dependent:
   3958     Diag(Result.KeywordLoc, diag::warn_microsoft_dependent_exists)
   3959       << Result.IsIfExists;
   3960     // Fall through to skip.
   3961 
   3962   case IEB_Skip:
   3963     Braces.skipToEnd();
   3964     return;
   3965   }
   3966 
   3967   while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
   3968     // __if_exists, __if_not_exists can nest.
   3969     if (Tok.isOneOf(tok::kw___if_exists, tok::kw___if_not_exists)) {
   3970       ParseMicrosoftIfExistsClassDeclaration((DeclSpec::TST)TagType, CurAS);
   3971       continue;
   3972     }
   3973 
   3974     // Check for extraneous top-level semicolon.
   3975     if (Tok.is(tok::semi)) {
   3976       ConsumeExtraSemi(InsideStruct, TagType);
   3977       continue;
   3978     }
   3979 
   3980     AccessSpecifier AS = getAccessSpecifierIfPresent();
   3981     if (AS != AS_none) {
   3982       // Current token is a C++ access specifier.
   3983       CurAS = AS;
   3984       SourceLocation ASLoc = Tok.getLocation();
   3985       ConsumeToken();
   3986       if (Tok.is(tok::colon))
   3987         Actions.ActOnAccessSpecifier(AS, ASLoc, Tok.getLocation());
   3988       else
   3989         Diag(Tok, diag::err_expected) << tok::colon;
   3990       ConsumeToken();
   3991       continue;
   3992     }
   3993 
   3994     // Parse all the comma separated declarators.
   3995     ParseCXXClassMemberDeclaration(CurAS, nullptr);
   3996   }
   3997 
   3998   Braces.consumeClose();
   3999 }
   4000