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