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