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