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