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