ParseDeclCXX.cpp revision 45ab4b5f8961dadcef6545ed6956da5daf95c6cb
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
56  if (Tok.is(tok::code_completion)) {
57    Actions.CodeCompleteNamespaceDecl(getCurScope());
58    ConsumeCodeCompletionToken();
59  }
60
61  SourceLocation IdentLoc;
62  IdentifierInfo *Ident = 0;
63
64  Token attrTok;
65
66  if (Tok.is(tok::identifier)) {
67    Ident = Tok.getIdentifierInfo();
68    IdentLoc = ConsumeToken();  // eat the identifier.
69  }
70
71  // Read label attributes, if present.
72  AttributeList *AttrList = 0;
73  if (Tok.is(tok::kw___attribute)) {
74    attrTok = Tok;
75
76    // FIXME: save these somewhere.
77    AttrList = ParseGNUAttributes();
78  }
79
80  if (Tok.is(tok::equal)) {
81    if (AttrList)
82      Diag(attrTok, diag::err_unexpected_namespace_attributes_alias);
83    if (InlineLoc.isValid())
84      Diag(InlineLoc, diag::err_inline_namespace_alias)
85          << FixItHint::CreateRemoval(InlineLoc);
86
87    return ParseNamespaceAlias(NamespaceLoc, IdentLoc, Ident, DeclEnd);
88  }
89
90  if (Tok.isNot(tok::l_brace)) {
91    Diag(Tok, Ident ? diag::err_expected_lbrace :
92         diag::err_expected_ident_lbrace);
93    return 0;
94  }
95
96  SourceLocation LBrace = ConsumeBrace();
97
98  if (getCurScope()->isClassScope() || getCurScope()->isTemplateParamScope() ||
99      getCurScope()->isInObjcMethodScope() || getCurScope()->getBlockParent() ||
100      getCurScope()->getFnParent()) {
101    Diag(LBrace, diag::err_namespace_nonnamespace_scope);
102    SkipUntil(tok::r_brace, false);
103    return 0;
104  }
105
106  // If we're still good, complain about inline namespaces in non-C++0x now.
107  if (!getLang().CPlusPlus0x && InlineLoc.isValid())
108    Diag(InlineLoc, diag::ext_inline_namespace);
109
110  // Enter a scope for the namespace.
111  ParseScope NamespaceScope(this, Scope::DeclScope);
112
113  Decl *NamespcDecl =
114    Actions.ActOnStartNamespaceDef(getCurScope(), InlineLoc, IdentLoc, Ident,
115                                   LBrace, AttrList);
116
117  PrettyDeclStackTraceEntry CrashInfo(Actions, NamespcDecl, NamespaceLoc,
118                                      "parsing namespace");
119
120  while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
121    CXX0XAttributeList Attr;
122    if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier())
123      Attr = ParseCXX0XAttributes();
124    if (getLang().Microsoft && Tok.is(tok::l_square))
125      ParseMicrosoftAttributes();
126    ParseExternalDeclaration(Attr);
127  }
128
129  // Leave the namespace scope.
130  NamespaceScope.Exit();
131
132  SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBrace);
133  Actions.ActOnFinishNamespaceDef(NamespcDecl, RBraceLoc);
134
135  DeclEnd = RBraceLoc;
136  return NamespcDecl;
137}
138
139/// ParseNamespaceAlias - Parse the part after the '=' in a namespace
140/// alias definition.
141///
142Decl *Parser::ParseNamespaceAlias(SourceLocation NamespaceLoc,
143                                              SourceLocation AliasLoc,
144                                              IdentifierInfo *Alias,
145                                              SourceLocation &DeclEnd) {
146  assert(Tok.is(tok::equal) && "Not equal token");
147
148  ConsumeToken(); // eat the '='.
149
150  if (Tok.is(tok::code_completion)) {
151    Actions.CodeCompleteNamespaceAliasDecl(getCurScope());
152    ConsumeCodeCompletionToken();
153  }
154
155  CXXScopeSpec SS;
156  // Parse (optional) nested-name-specifier.
157  ParseOptionalCXXScopeSpecifier(SS, ParsedType(), false);
158
159  if (SS.isInvalid() || Tok.isNot(tok::identifier)) {
160    Diag(Tok, diag::err_expected_namespace_name);
161    // Skip to end of the definition and eat the ';'.
162    SkipUntil(tok::semi);
163    return 0;
164  }
165
166  // Parse identifier.
167  IdentifierInfo *Ident = Tok.getIdentifierInfo();
168  SourceLocation IdentLoc = ConsumeToken();
169
170  // Eat the ';'.
171  DeclEnd = Tok.getLocation();
172  ExpectAndConsume(tok::semi, diag::err_expected_semi_after_namespace_name,
173                   "", tok::semi);
174
175  return Actions.ActOnNamespaceAliasDef(getCurScope(), NamespaceLoc, AliasLoc, Alias,
176                                        SS, IdentLoc, Ident);
177}
178
179/// ParseLinkage - We know that the current token is a string_literal
180/// and just before that, that extern was seen.
181///
182///       linkage-specification: [C++ 7.5p2: dcl.link]
183///         'extern' string-literal '{' declaration-seq[opt] '}'
184///         'extern' string-literal declaration
185///
186Decl *Parser::ParseLinkage(ParsingDeclSpec &DS, unsigned Context) {
187  assert(Tok.is(tok::string_literal) && "Not a string literal!");
188  llvm::SmallString<8> LangBuffer;
189  bool Invalid = false;
190  llvm::StringRef Lang = PP.getSpelling(Tok, LangBuffer, &Invalid);
191  if (Invalid)
192    return 0;
193
194  SourceLocation Loc = ConsumeStringToken();
195
196  ParseScope LinkageScope(this, Scope::DeclScope);
197  Decl *LinkageSpec
198    = Actions.ActOnStartLinkageSpecification(getCurScope(),
199                                             /*FIXME: */SourceLocation(),
200                                             Loc, Lang,
201                                       Tok.is(tok::l_brace)? Tok.getLocation()
202                                                           : SourceLocation());
203
204  CXX0XAttributeList Attr;
205  if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier())
206    Attr = ParseCXX0XAttributes();
207
208  if (getLang().Microsoft && Tok.is(tok::l_square))
209    ParseMicrosoftAttributes();
210
211  if (Tok.isNot(tok::l_brace)) {
212    DS.setExternInLinkageSpec(true);
213    ParseExternalDeclaration(Attr, &DS);
214    return Actions.ActOnFinishLinkageSpecification(getCurScope(), LinkageSpec,
215                                                   SourceLocation());
216  }
217
218  DS.abort();
219
220  if (Attr.HasAttr)
221    Diag(Attr.Range.getBegin(), diag::err_attributes_not_allowed)
222      << Attr.Range;
223
224  SourceLocation LBrace = ConsumeBrace();
225  while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
226    CXX0XAttributeList Attr;
227    if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier())
228      Attr = ParseCXX0XAttributes();
229    if (getLang().Microsoft && Tok.is(tok::l_square))
230      ParseMicrosoftAttributes();
231    ParseExternalDeclaration(Attr);
232  }
233
234  SourceLocation RBrace = MatchRHSPunctuation(tok::r_brace, LBrace);
235  return Actions.ActOnFinishLinkageSpecification(getCurScope(), LinkageSpec,
236                                                 RBrace);
237}
238
239/// ParseUsingDirectiveOrDeclaration - Parse C++ using using-declaration or
240/// using-directive. Assumes that current token is 'using'.
241Decl *Parser::ParseUsingDirectiveOrDeclaration(unsigned Context,
242                                         const ParsedTemplateInfo &TemplateInfo,
243                                               SourceLocation &DeclEnd,
244                                               CXX0XAttributeList Attr) {
245  assert(Tok.is(tok::kw_using) && "Not using token");
246
247  // Eat 'using'.
248  SourceLocation UsingLoc = ConsumeToken();
249
250  if (Tok.is(tok::code_completion)) {
251    Actions.CodeCompleteUsing(getCurScope());
252    ConsumeCodeCompletionToken();
253  }
254
255  // 'using namespace' means this is a using-directive.
256  if (Tok.is(tok::kw_namespace)) {
257    // Template parameters are always an error here.
258    if (TemplateInfo.Kind) {
259      SourceRange R = TemplateInfo.getSourceRange();
260      Diag(UsingLoc, diag::err_templated_using_directive)
261        << R << FixItHint::CreateRemoval(R);
262    }
263
264    return ParseUsingDirective(Context, UsingLoc, DeclEnd, Attr.AttrList);
265  }
266
267  // Otherwise, it must be a using-declaration.
268
269  // Using declarations can't have attributes.
270  if (Attr.HasAttr)
271    Diag(Attr.Range.getBegin(), diag::err_attributes_not_allowed)
272      << Attr.Range;
273
274  return ParseUsingDeclaration(Context, TemplateInfo, UsingLoc, DeclEnd);
275}
276
277/// ParseUsingDirective - Parse C++ using-directive, assumes
278/// that current token is 'namespace' and 'using' was already parsed.
279///
280///       using-directive: [C++ 7.3.p4: namespace.udir]
281///        'using' 'namespace' ::[opt] nested-name-specifier[opt]
282///                 namespace-name ;
283/// [GNU] using-directive:
284///        'using' 'namespace' ::[opt] nested-name-specifier[opt]
285///                 namespace-name attributes[opt] ;
286///
287Decl *Parser::ParseUsingDirective(unsigned Context,
288                                  SourceLocation UsingLoc,
289                                  SourceLocation &DeclEnd,
290                                  AttributeList *Attr) {
291  assert(Tok.is(tok::kw_namespace) && "Not 'namespace' token");
292
293  // Eat 'namespace'.
294  SourceLocation NamespcLoc = ConsumeToken();
295
296  if (Tok.is(tok::code_completion)) {
297    Actions.CodeCompleteUsingDirective(getCurScope());
298    ConsumeCodeCompletionToken();
299  }
300
301  CXXScopeSpec SS;
302  // Parse (optional) nested-name-specifier.
303  ParseOptionalCXXScopeSpecifier(SS, ParsedType(), false);
304
305  IdentifierInfo *NamespcName = 0;
306  SourceLocation IdentLoc = SourceLocation();
307
308  // Parse namespace-name.
309  if (SS.isInvalid() || Tok.isNot(tok::identifier)) {
310    Diag(Tok, diag::err_expected_namespace_name);
311    // If there was invalid namespace name, skip to end of decl, and eat ';'.
312    SkipUntil(tok::semi);
313    // FIXME: Are there cases, when we would like to call ActOnUsingDirective?
314    return 0;
315  }
316
317  // Parse identifier.
318  NamespcName = Tok.getIdentifierInfo();
319  IdentLoc = ConsumeToken();
320
321  // Parse (optional) attributes (most likely GNU strong-using extension).
322  bool GNUAttr = false;
323  if (Tok.is(tok::kw___attribute)) {
324    GNUAttr = true;
325    Attr = addAttributeLists(Attr, ParseGNUAttributes());
326  }
327
328  // Eat ';'.
329  DeclEnd = Tok.getLocation();
330  ExpectAndConsume(tok::semi,
331                   GNUAttr ? diag::err_expected_semi_after_attribute_list
332                           : diag::err_expected_semi_after_namespace_name,
333                   "", tok::semi);
334
335  return Actions.ActOnUsingDirective(getCurScope(), UsingLoc, NamespcLoc, SS,
336                                      IdentLoc, NamespcName, Attr);
337}
338
339/// ParseUsingDeclaration - Parse C++ using-declaration. Assumes that
340/// 'using' was already seen.
341///
342///     using-declaration: [C++ 7.3.p3: namespace.udecl]
343///       'using' 'typename'[opt] ::[opt] nested-name-specifier
344///               unqualified-id
345///       'using' :: unqualified-id
346///
347Decl *Parser::ParseUsingDeclaration(unsigned Context,
348                                    const ParsedTemplateInfo &TemplateInfo,
349                                    SourceLocation UsingLoc,
350                                    SourceLocation &DeclEnd,
351                                    AccessSpecifier AS) {
352  CXXScopeSpec SS;
353  SourceLocation TypenameLoc;
354  bool IsTypeName;
355
356  // TODO: in C++0x, if we have template parameters this must be a
357  // template alias:
358  //   template <...> using id = type;
359
360  // Ignore optional 'typename'.
361  // FIXME: This is wrong; we should parse this as a typename-specifier.
362  if (Tok.is(tok::kw_typename)) {
363    TypenameLoc = Tok.getLocation();
364    ConsumeToken();
365    IsTypeName = true;
366  }
367  else
368    IsTypeName = false;
369
370  // Parse nested-name-specifier.
371  ParseOptionalCXXScopeSpecifier(SS, ParsedType(), false);
372
373  // Check nested-name specifier.
374  if (SS.isInvalid()) {
375    SkipUntil(tok::semi);
376    return 0;
377  }
378
379  // Parse the unqualified-id. We allow parsing of both constructor and
380  // destructor names and allow the action module to diagnose any semantic
381  // errors.
382  UnqualifiedId Name;
383  if (ParseUnqualifiedId(SS,
384                         /*EnteringContext=*/false,
385                         /*AllowDestructorName=*/true,
386                         /*AllowConstructorName=*/true,
387                         ParsedType(),
388                         Name)) {
389    SkipUntil(tok::semi);
390    return 0;
391  }
392
393  // Parse (optional) attributes (most likely GNU strong-using extension).
394  AttributeList *AttrList = 0;
395  if (Tok.is(tok::kw___attribute))
396    AttrList = ParseGNUAttributes();
397
398  // Eat ';'.
399  DeclEnd = Tok.getLocation();
400  ExpectAndConsume(tok::semi, diag::err_expected_semi_after,
401                   AttrList ? "attributes list" : "using declaration",
402                   tok::semi);
403
404  // Diagnose an attempt to declare a templated using-declaration.
405  if (TemplateInfo.Kind) {
406    SourceRange R = TemplateInfo.getSourceRange();
407    Diag(UsingLoc, diag::err_templated_using_declaration)
408      << R << FixItHint::CreateRemoval(R);
409
410    // Unfortunately, we have to bail out instead of recovering by
411    // ignoring the parameters, just in case the nested name specifier
412    // depends on the parameters.
413    return 0;
414  }
415
416  return Actions.ActOnUsingDeclaration(getCurScope(), AS, true, UsingLoc, SS,
417                                       Name, AttrList, IsTypeName, TypenameLoc);
418}
419
420/// ParseStaticAssertDeclaration - Parse C++0x static_assert-declaratoion.
421///
422///      static_assert-declaration:
423///        static_assert ( constant-expression  ,  string-literal  ) ;
424///
425Decl *Parser::ParseStaticAssertDeclaration(SourceLocation &DeclEnd){
426  assert(Tok.is(tok::kw_static_assert) && "Not a static_assert declaration");
427  SourceLocation StaticAssertLoc = ConsumeToken();
428
429  if (Tok.isNot(tok::l_paren)) {
430    Diag(Tok, diag::err_expected_lparen);
431    return 0;
432  }
433
434  SourceLocation LParenLoc = ConsumeParen();
435
436  ExprResult AssertExpr(ParseConstantExpression());
437  if (AssertExpr.isInvalid()) {
438    SkipUntil(tok::semi);
439    return 0;
440  }
441
442  if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "", tok::semi))
443    return 0;
444
445  if (Tok.isNot(tok::string_literal)) {
446    Diag(Tok, diag::err_expected_string_literal);
447    SkipUntil(tok::semi);
448    return 0;
449  }
450
451  ExprResult AssertMessage(ParseStringLiteralExpression());
452  if (AssertMessage.isInvalid())
453    return 0;
454
455  MatchRHSPunctuation(tok::r_paren, LParenLoc);
456
457  DeclEnd = Tok.getLocation();
458  ExpectAndConsumeSemi(diag::err_expected_semi_after_static_assert);
459
460  return Actions.ActOnStaticAssertDeclaration(StaticAssertLoc,
461                                              AssertExpr.take(),
462                                              AssertMessage.take());
463}
464
465/// ParseDecltypeSpecifier - Parse a C++0x decltype specifier.
466///
467/// 'decltype' ( expression )
468///
469void Parser::ParseDecltypeSpecifier(DeclSpec &DS) {
470  assert(Tok.is(tok::kw_decltype) && "Not a decltype specifier");
471
472  SourceLocation StartLoc = ConsumeToken();
473  SourceLocation LParenLoc = Tok.getLocation();
474
475  if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
476                       "decltype")) {
477    SkipUntil(tok::r_paren);
478    return;
479  }
480
481  // Parse the expression
482
483  // C++0x [dcl.type.simple]p4:
484  //   The operand of the decltype specifier is an unevaluated operand.
485  EnterExpressionEvaluationContext Unevaluated(Actions,
486                                               Sema::Unevaluated);
487  ExprResult Result = ParseExpression();
488  if (Result.isInvalid()) {
489    SkipUntil(tok::r_paren);
490    return;
491  }
492
493  // Match the ')'
494  SourceLocation RParenLoc;
495  if (Tok.is(tok::r_paren))
496    RParenLoc = ConsumeParen();
497  else
498    MatchRHSPunctuation(tok::r_paren, LParenLoc);
499
500  if (RParenLoc.isInvalid())
501    return;
502
503  const char *PrevSpec = 0;
504  unsigned DiagID;
505  // Check for duplicate type specifiers (e.g. "int decltype(a)").
506  if (DS.SetTypeSpecType(DeclSpec::TST_decltype, StartLoc, PrevSpec,
507                         DiagID, Result.release()))
508    Diag(StartLoc, DiagID) << PrevSpec;
509}
510
511/// ParseClassName - Parse a C++ class-name, which names a class. Note
512/// that we only check that the result names a type; semantic analysis
513/// will need to verify that the type names a class. The result is
514/// either a type or NULL, depending on whether a type name was
515/// found.
516///
517///       class-name: [C++ 9.1]
518///         identifier
519///         simple-template-id
520///
521Parser::TypeResult Parser::ParseClassName(SourceLocation &EndLocation,
522                                          CXXScopeSpec *SS) {
523  // Check whether we have a template-id that names a type.
524  if (Tok.is(tok::annot_template_id)) {
525    TemplateIdAnnotation *TemplateId
526      = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
527    if (TemplateId->Kind == TNK_Type_template ||
528        TemplateId->Kind == TNK_Dependent_template_name) {
529      AnnotateTemplateIdTokenAsType(SS);
530
531      assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
532      ParsedType Type = getTypeAnnotation(Tok);
533      EndLocation = Tok.getAnnotationEndLoc();
534      ConsumeToken();
535
536      if (Type)
537        return Type;
538      return true;
539    }
540
541    // Fall through to produce an error below.
542  }
543
544  if (Tok.isNot(tok::identifier)) {
545    Diag(Tok, diag::err_expected_class_name);
546    return true;
547  }
548
549  IdentifierInfo *Id = Tok.getIdentifierInfo();
550  SourceLocation IdLoc = ConsumeToken();
551
552  if (Tok.is(tok::less)) {
553    // It looks the user intended to write a template-id here, but the
554    // template-name was wrong. Try to fix that.
555    TemplateNameKind TNK = TNK_Type_template;
556    TemplateTy Template;
557    if (!Actions.DiagnoseUnknownTemplateName(*Id, IdLoc, getCurScope(),
558                                             SS, Template, TNK)) {
559      Diag(IdLoc, diag::err_unknown_template_name)
560        << Id;
561    }
562
563    if (!Template)
564      return true;
565
566    // Form the template name
567    UnqualifiedId TemplateName;
568    TemplateName.setIdentifier(Id, IdLoc);
569
570    // Parse the full template-id, then turn it into a type.
571    if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateName,
572                                SourceLocation(), true))
573      return true;
574    if (TNK == TNK_Dependent_template_name)
575      AnnotateTemplateIdTokenAsType(SS);
576
577    // If we didn't end up with a typename token, there's nothing more we
578    // can do.
579    if (Tok.isNot(tok::annot_typename))
580      return true;
581
582    // Retrieve the type from the annotation token, consume that token, and
583    // return.
584    EndLocation = Tok.getAnnotationEndLoc();
585    ParsedType Type = getTypeAnnotation(Tok);
586    ConsumeToken();
587    return Type;
588  }
589
590  // We have an identifier; check whether it is actually a type.
591  ParsedType Type = Actions.getTypeName(*Id, IdLoc, getCurScope(), SS, true);
592  if (!Type) {
593    Diag(IdLoc, diag::err_expected_class_name);
594    return true;
595  }
596
597  // Consume the identifier.
598  EndLocation = IdLoc;
599
600  // Fake up a Declarator to use with ActOnTypeName.
601  DeclSpec DS;
602  DS.SetRangeStart(IdLoc);
603  DS.SetRangeEnd(EndLocation);
604  DS.getTypeSpecScope() = *SS;
605
606  const char *PrevSpec = 0;
607  unsigned DiagID;
608  DS.SetTypeSpecType(TST_typename, IdLoc, PrevSpec, DiagID, Type);
609
610  Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
611  return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
612}
613
614/// ParseClassSpecifier - Parse a C++ class-specifier [C++ class] or
615/// elaborated-type-specifier [C++ dcl.type.elab]; we can't tell which
616/// until we reach the start of a definition or see a token that
617/// cannot start a definition. If SuppressDeclarations is true, we do know.
618///
619///       class-specifier: [C++ class]
620///         class-head '{' member-specification[opt] '}'
621///         class-head '{' member-specification[opt] '}' attributes[opt]
622///       class-head:
623///         class-key identifier[opt] base-clause[opt]
624///         class-key nested-name-specifier identifier base-clause[opt]
625///         class-key nested-name-specifier[opt] simple-template-id
626///                          base-clause[opt]
627/// [GNU]   class-key attributes[opt] identifier[opt] base-clause[opt]
628/// [GNU]   class-key attributes[opt] nested-name-specifier
629///                          identifier base-clause[opt]
630/// [GNU]   class-key attributes[opt] nested-name-specifier[opt]
631///                          simple-template-id base-clause[opt]
632///       class-key:
633///         'class'
634///         'struct'
635///         'union'
636///
637///       elaborated-type-specifier: [C++ dcl.type.elab]
638///         class-key ::[opt] nested-name-specifier[opt] identifier
639///         class-key ::[opt] nested-name-specifier[opt] 'template'[opt]
640///                          simple-template-id
641///
642///  Note that the C++ class-specifier and elaborated-type-specifier,
643///  together, subsume the C99 struct-or-union-specifier:
644///
645///       struct-or-union-specifier: [C99 6.7.2.1]
646///         struct-or-union identifier[opt] '{' struct-contents '}'
647///         struct-or-union identifier
648/// [GNU]   struct-or-union attributes[opt] identifier[opt] '{' struct-contents
649///                                                         '}' attributes[opt]
650/// [GNU]   struct-or-union attributes[opt] identifier
651///       struct-or-union:
652///         'struct'
653///         'union'
654void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind,
655                                 SourceLocation StartLoc, DeclSpec &DS,
656                                 const ParsedTemplateInfo &TemplateInfo,
657                                 AccessSpecifier AS, bool SuppressDeclarations){
658  DeclSpec::TST TagType;
659  if (TagTokKind == tok::kw_struct)
660    TagType = DeclSpec::TST_struct;
661  else if (TagTokKind == tok::kw_class)
662    TagType = DeclSpec::TST_class;
663  else {
664    assert(TagTokKind == tok::kw_union && "Not a class specifier");
665    TagType = DeclSpec::TST_union;
666  }
667
668  if (Tok.is(tok::code_completion)) {
669    // Code completion for a struct, class, or union name.
670    Actions.CodeCompleteTag(getCurScope(), TagType);
671    ConsumeCodeCompletionToken();
672  }
673
674  // C++03 [temp.explicit] 14.7.2/8:
675  //   The usual access checking rules do not apply to names used to specify
676  //   explicit instantiations.
677  //
678  // As an extension we do not perform access checking on the names used to
679  // specify explicit specializations either. This is important to allow
680  // specializing traits classes for private types.
681  bool SuppressingAccessChecks = false;
682  if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
683      TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization) {
684    Actions.ActOnStartSuppressingAccessChecks();
685    SuppressingAccessChecks = true;
686  }
687
688  AttributeList *AttrList = 0;
689  // If attributes exist after tag, parse them.
690  if (Tok.is(tok::kw___attribute))
691    AttrList = ParseGNUAttributes();
692
693  // If declspecs exist after tag, parse them.
694  while (Tok.is(tok::kw___declspec))
695    AttrList = ParseMicrosoftDeclSpec(AttrList);
696
697  // If C++0x attributes exist here, parse them.
698  // FIXME: Are we consistent with the ordering of parsing of different
699  // styles of attributes?
700  if (isCXX0XAttributeSpecifier())
701    AttrList = addAttributeLists(AttrList, ParseCXX0XAttributes().AttrList);
702
703  if (TagType == DeclSpec::TST_struct && Tok.is(tok::kw___is_pod)) {
704    // GNU libstdc++ 4.2 uses __is_pod as the name of a struct template, but
705    // __is_pod is a keyword in GCC >= 4.3. Therefore, when we see the
706    // token sequence "struct __is_pod", make __is_pod into a normal
707    // identifier rather than a keyword, to allow libstdc++ 4.2 to work
708    // properly.
709    Tok.getIdentifierInfo()->RevertTokenIDToIdentifier();
710    Tok.setKind(tok::identifier);
711  }
712
713  if (TagType == DeclSpec::TST_struct && Tok.is(tok::kw___is_empty)) {
714    // GNU libstdc++ 4.2 uses __is_empty as the name of a struct template, but
715    // __is_empty is a keyword in GCC >= 4.3. Therefore, when we see the
716    // token sequence "struct __is_empty", make __is_empty into a normal
717    // identifier rather than a keyword, to allow libstdc++ 4.2 to work
718    // properly.
719    Tok.getIdentifierInfo()->RevertTokenIDToIdentifier();
720    Tok.setKind(tok::identifier);
721  }
722
723  // Parse the (optional) nested-name-specifier.
724  CXXScopeSpec &SS = DS.getTypeSpecScope();
725  if (getLang().CPlusPlus) {
726    // "FOO : BAR" is not a potential typo for "FOO::BAR".
727    ColonProtectionRAIIObject X(*this);
728
729    if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), true))
730      DS.SetTypeSpecError();
731    if (SS.isSet())
732      if (Tok.isNot(tok::identifier) && Tok.isNot(tok::annot_template_id))
733        Diag(Tok, diag::err_expected_ident);
734  }
735
736  TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
737
738  // Parse the (optional) class name or simple-template-id.
739  IdentifierInfo *Name = 0;
740  SourceLocation NameLoc;
741  TemplateIdAnnotation *TemplateId = 0;
742  if (Tok.is(tok::identifier)) {
743    Name = Tok.getIdentifierInfo();
744    NameLoc = ConsumeToken();
745
746    if (Tok.is(tok::less) && getLang().CPlusPlus) {
747      // The name was supposed to refer to a template, but didn't.
748      // Eat the template argument list and try to continue parsing this as
749      // a class (or template thereof).
750      TemplateArgList TemplateArgs;
751      SourceLocation LAngleLoc, RAngleLoc;
752      if (ParseTemplateIdAfterTemplateName(TemplateTy(), NameLoc, &SS,
753                                           true, LAngleLoc,
754                                           TemplateArgs, RAngleLoc)) {
755        // We couldn't parse the template argument list at all, so don't
756        // try to give any location information for the list.
757        LAngleLoc = RAngleLoc = SourceLocation();
758      }
759
760      Diag(NameLoc, diag::err_explicit_spec_non_template)
761        << (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
762        << (TagType == DeclSpec::TST_class? 0
763            : TagType == DeclSpec::TST_struct? 1
764            : 2)
765        << Name
766        << SourceRange(LAngleLoc, RAngleLoc);
767
768      // Strip off the last template parameter list if it was empty, since
769      // we've removed its template argument list.
770      if (TemplateParams && TemplateInfo.LastParameterListWasEmpty) {
771        if (TemplateParams && TemplateParams->size() > 1) {
772          TemplateParams->pop_back();
773        } else {
774          TemplateParams = 0;
775          const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind
776            = ParsedTemplateInfo::NonTemplate;
777        }
778      } else if (TemplateInfo.Kind
779                                == ParsedTemplateInfo::ExplicitInstantiation) {
780        // Pretend this is just a forward declaration.
781        TemplateParams = 0;
782        const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind
783          = ParsedTemplateInfo::NonTemplate;
784        const_cast<ParsedTemplateInfo&>(TemplateInfo).TemplateLoc
785          = SourceLocation();
786        const_cast<ParsedTemplateInfo&>(TemplateInfo).ExternLoc
787          = SourceLocation();
788      }
789    }
790  } else if (Tok.is(tok::annot_template_id)) {
791    TemplateId = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
792    NameLoc = ConsumeToken();
793
794    if (TemplateId->Kind != TNK_Type_template) {
795      // The template-name in the simple-template-id refers to
796      // something other than a class template. Give an appropriate
797      // error message and skip to the ';'.
798      SourceRange Range(NameLoc);
799      if (SS.isNotEmpty())
800        Range.setBegin(SS.getBeginLoc());
801
802      Diag(TemplateId->LAngleLoc, diag::err_template_spec_syntax_non_template)
803        << Name << static_cast<int>(TemplateId->Kind) << Range;
804
805      DS.SetTypeSpecError();
806      SkipUntil(tok::semi, false, true);
807      TemplateId->Destroy();
808      if (SuppressingAccessChecks)
809        Actions.ActOnStopSuppressingAccessChecks();
810
811      return;
812    }
813  }
814
815  // As soon as we're finished parsing the class's template-id, turn access
816  // checking back on.
817  if (SuppressingAccessChecks)
818    Actions.ActOnStopSuppressingAccessChecks();
819
820  // There are four options here.  If we have 'struct foo;', then this
821  // is either a forward declaration or a friend declaration, which
822  // have to be treated differently.  If we have 'struct foo {...' or
823  // 'struct foo :...' then this is a definition. Otherwise we have
824  // something like 'struct foo xyz', a reference.
825  // However, in some contexts, things look like declarations but are just
826  // references, e.g.
827  // new struct s;
828  // or
829  // &T::operator struct s;
830  // For these, SuppressDeclarations is true.
831  Sema::TagUseKind TUK;
832  if (SuppressDeclarations)
833    TUK = Sema::TUK_Reference;
834  else if (Tok.is(tok::l_brace) || (getLang().CPlusPlus && Tok.is(tok::colon))){
835    if (DS.isFriendSpecified()) {
836      // C++ [class.friend]p2:
837      //   A class shall not be defined in a friend declaration.
838      Diag(Tok.getLocation(), diag::err_friend_decl_defines_class)
839        << SourceRange(DS.getFriendSpecLoc());
840
841      // Skip everything up to the semicolon, so that this looks like a proper
842      // friend class (or template thereof) declaration.
843      SkipUntil(tok::semi, true, true);
844      TUK = Sema::TUK_Friend;
845    } else {
846      // Okay, this is a class definition.
847      TUK = Sema::TUK_Definition;
848    }
849  } else if (Tok.is(tok::semi))
850    TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
851  else
852    TUK = Sema::TUK_Reference;
853
854  if (!Name && !TemplateId && (DS.getTypeSpecType() == DeclSpec::TST_error ||
855                               TUK != Sema::TUK_Definition)) {
856    if (DS.getTypeSpecType() != DeclSpec::TST_error) {
857      // We have a declaration or reference to an anonymous class.
858      Diag(StartLoc, diag::err_anon_type_definition)
859        << DeclSpec::getSpecifierName(TagType);
860    }
861
862    SkipUntil(tok::comma, true);
863
864    if (TemplateId)
865      TemplateId->Destroy();
866    return;
867  }
868
869  // Create the tag portion of the class or class template.
870  DeclResult TagOrTempResult = true; // invalid
871  TypeResult TypeResult = true; // invalid
872
873  bool Owned = false;
874  if (TemplateId) {
875    // Explicit specialization, class template partial specialization,
876    // or explicit instantiation.
877    ASTTemplateArgsPtr TemplateArgsPtr(Actions,
878                                       TemplateId->getTemplateArgs(),
879                                       TemplateId->NumArgs);
880    if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
881        TUK == Sema::TUK_Declaration) {
882      // This is an explicit instantiation of a class template.
883      TagOrTempResult
884        = Actions.ActOnExplicitInstantiation(getCurScope(),
885                                             TemplateInfo.ExternLoc,
886                                             TemplateInfo.TemplateLoc,
887                                             TagType,
888                                             StartLoc,
889                                             SS,
890                                             TemplateId->Template,
891                                             TemplateId->TemplateNameLoc,
892                                             TemplateId->LAngleLoc,
893                                             TemplateArgsPtr,
894                                             TemplateId->RAngleLoc,
895                                             AttrList);
896
897    // Friend template-ids are treated as references unless
898    // they have template headers, in which case they're ill-formed
899    // (FIXME: "template <class T> friend class A<T>::B<int>;").
900    // We diagnose this error in ActOnClassTemplateSpecialization.
901    } else if (TUK == Sema::TUK_Reference ||
902               (TUK == Sema::TUK_Friend &&
903                TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate)) {
904      TypeResult
905        = Actions.ActOnTemplateIdType(TemplateId->Template,
906                                      TemplateId->TemplateNameLoc,
907                                      TemplateId->LAngleLoc,
908                                      TemplateArgsPtr,
909                                      TemplateId->RAngleLoc);
910
911      TypeResult = Actions.ActOnTagTemplateIdType(SS, TypeResult, TUK,
912                                                  TagType, StartLoc);
913    } else {
914      // This is an explicit specialization or a class template
915      // partial specialization.
916      TemplateParameterLists FakedParamLists;
917
918      if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
919        // This looks like an explicit instantiation, because we have
920        // something like
921        //
922        //   template class Foo<X>
923        //
924        // but it actually has a definition. Most likely, this was
925        // meant to be an explicit specialization, but the user forgot
926        // the '<>' after 'template'.
927        assert(TUK == Sema::TUK_Definition && "Expected a definition here");
928
929        SourceLocation LAngleLoc
930          = PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
931        Diag(TemplateId->TemplateNameLoc,
932             diag::err_explicit_instantiation_with_definition)
933          << SourceRange(TemplateInfo.TemplateLoc)
934          << FixItHint::CreateInsertion(LAngleLoc, "<>");
935
936        // Create a fake template parameter list that contains only
937        // "template<>", so that we treat this construct as a class
938        // template specialization.
939        FakedParamLists.push_back(
940          Actions.ActOnTemplateParameterList(0, SourceLocation(),
941                                             TemplateInfo.TemplateLoc,
942                                             LAngleLoc,
943                                             0, 0,
944                                             LAngleLoc));
945        TemplateParams = &FakedParamLists;
946      }
947
948      // Build the class template specialization.
949      TagOrTempResult
950        = Actions.ActOnClassTemplateSpecialization(getCurScope(), TagType, TUK,
951                       StartLoc, SS,
952                       TemplateId->Template,
953                       TemplateId->TemplateNameLoc,
954                       TemplateId->LAngleLoc,
955                       TemplateArgsPtr,
956                       TemplateId->RAngleLoc,
957                       AttrList,
958                       MultiTemplateParamsArg(Actions,
959                                    TemplateParams? &(*TemplateParams)[0] : 0,
960                                 TemplateParams? TemplateParams->size() : 0));
961    }
962    TemplateId->Destroy();
963  } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
964             TUK == Sema::TUK_Declaration) {
965    // Explicit instantiation of a member of a class template
966    // specialization, e.g.,
967    //
968    //   template struct Outer<int>::Inner;
969    //
970    TagOrTempResult
971      = Actions.ActOnExplicitInstantiation(getCurScope(),
972                                           TemplateInfo.ExternLoc,
973                                           TemplateInfo.TemplateLoc,
974                                           TagType, StartLoc, SS, Name,
975                                           NameLoc, AttrList);
976  } else if (TUK == Sema::TUK_Friend &&
977             TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate) {
978    TagOrTempResult =
979      Actions.ActOnTemplatedFriendTag(getCurScope(), DS.getFriendSpecLoc(),
980                                      TagType, StartLoc, SS,
981                                      Name, NameLoc, AttrList,
982                                      MultiTemplateParamsArg(Actions,
983                                    TemplateParams? &(*TemplateParams)[0] : 0,
984                                 TemplateParams? TemplateParams->size() : 0));
985  } else {
986    if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
987        TUK == Sema::TUK_Definition) {
988      // FIXME: Diagnose this particular error.
989    }
990
991    bool IsDependent = false;
992
993    // Don't pass down template parameter lists if this is just a tag
994    // reference.  For example, we don't need the template parameters here:
995    //   template <class T> class A *makeA(T t);
996    MultiTemplateParamsArg TParams;
997    if (TUK != Sema::TUK_Reference && TemplateParams)
998      TParams =
999        MultiTemplateParamsArg(&(*TemplateParams)[0], TemplateParams->size());
1000
1001    // Declaration or definition of a class type
1002    TagOrTempResult = Actions.ActOnTag(getCurScope(), TagType, TUK, StartLoc,
1003                                       SS, Name, NameLoc, AttrList, AS,
1004                                       TParams, Owned, IsDependent, false,
1005                                       clang::TypeResult());
1006
1007    // If ActOnTag said the type was dependent, try again with the
1008    // less common call.
1009    if (IsDependent) {
1010      assert(TUK == Sema::TUK_Reference || TUK == Sema::TUK_Friend);
1011      TypeResult = Actions.ActOnDependentTag(getCurScope(), TagType, TUK,
1012                                             SS, Name, StartLoc, NameLoc);
1013    }
1014  }
1015
1016  // If there is a body, parse it and inform the actions module.
1017  if (TUK == Sema::TUK_Definition) {
1018    assert(Tok.is(tok::l_brace) ||
1019           (getLang().CPlusPlus && Tok.is(tok::colon)));
1020    if (getLang().CPlusPlus)
1021      ParseCXXMemberSpecification(StartLoc, TagType, TagOrTempResult.get());
1022    else
1023      ParseStructUnionBody(StartLoc, TagType, TagOrTempResult.get());
1024  }
1025
1026  // FIXME: The DeclSpec should keep the locations of both the keyword and the
1027  // name (if there is one).
1028  SourceLocation TSTLoc = NameLoc.isValid()? NameLoc : StartLoc;
1029
1030  const char *PrevSpec = 0;
1031  unsigned DiagID;
1032  bool Result;
1033  if (!TypeResult.isInvalid()) {
1034    Result = DS.SetTypeSpecType(DeclSpec::TST_typename, TSTLoc,
1035                                PrevSpec, DiagID, TypeResult.get());
1036  } else if (!TagOrTempResult.isInvalid()) {
1037    Result = DS.SetTypeSpecType(TagType, TSTLoc, PrevSpec, DiagID,
1038                                TagOrTempResult.get(), Owned);
1039  } else {
1040    DS.SetTypeSpecError();
1041    return;
1042  }
1043
1044  if (Result)
1045    Diag(StartLoc, DiagID) << PrevSpec;
1046
1047  // At this point, we've successfully parsed a class-specifier in 'definition'
1048  // form (e.g. "struct foo { int x; }".  While we could just return here, we're
1049  // going to look at what comes after it to improve error recovery.  If an
1050  // impossible token occurs next, we assume that the programmer forgot a ; at
1051  // the end of the declaration and recover that way.
1052  //
1053  // This switch enumerates the valid "follow" set for definition.
1054  if (TUK == Sema::TUK_Definition) {
1055    bool ExpectedSemi = true;
1056    switch (Tok.getKind()) {
1057    default: break;
1058    case tok::semi:               // struct foo {...} ;
1059    case tok::star:               // struct foo {...} *         P;
1060    case tok::amp:                // struct foo {...} &         R = ...
1061    case tok::identifier:         // struct foo {...} V         ;
1062    case tok::r_paren:            //(struct foo {...} )         {4}
1063    case tok::annot_cxxscope:     // struct foo {...} a::       b;
1064    case tok::annot_typename:     // struct foo {...} a         ::b;
1065    case tok::annot_template_id:  // struct foo {...} a<int>    ::b;
1066    case tok::l_paren:            // struct foo {...} (         x);
1067    case tok::comma:              // __builtin_offsetof(struct foo{...} ,
1068      ExpectedSemi = false;
1069      break;
1070    // Type qualifiers
1071    case tok::kw_const:           // struct foo {...} const     x;
1072    case tok::kw_volatile:        // struct foo {...} volatile  x;
1073    case tok::kw_restrict:        // struct foo {...} restrict  x;
1074    case tok::kw_inline:          // struct foo {...} inline    foo() {};
1075    // Storage-class specifiers
1076    case tok::kw_static:          // struct foo {...} static    x;
1077    case tok::kw_extern:          // struct foo {...} extern    x;
1078    case tok::kw_typedef:         // struct foo {...} typedef   x;
1079    case tok::kw_register:        // struct foo {...} register  x;
1080    case tok::kw_auto:            // struct foo {...} auto      x;
1081    case tok::kw_mutable:         // struct foo {...} mutable      x;
1082      // As shown above, type qualifiers and storage class specifiers absolutely
1083      // can occur after class specifiers according to the grammar.  However,
1084      // almost noone actually writes code like this.  If we see one of these,
1085      // it is much more likely that someone missed a semi colon and the
1086      // type/storage class specifier we're seeing is part of the *next*
1087      // intended declaration, as in:
1088      //
1089      //   struct foo { ... }
1090      //   typedef int X;
1091      //
1092      // We'd really like to emit a missing semicolon error instead of emitting
1093      // an error on the 'int' saying that you can't have two type specifiers in
1094      // the same declaration of X.  Because of this, we look ahead past this
1095      // token to see if it's a type specifier.  If so, we know the code is
1096      // otherwise invalid, so we can produce the expected semi error.
1097      if (!isKnownToBeTypeSpecifier(NextToken()))
1098        ExpectedSemi = false;
1099      break;
1100
1101    case tok::r_brace:  // struct bar { struct foo {...} }
1102      // Missing ';' at end of struct is accepted as an extension in C mode.
1103      if (!getLang().CPlusPlus)
1104        ExpectedSemi = false;
1105      break;
1106    }
1107
1108    if (ExpectedSemi) {
1109      ExpectAndConsume(tok::semi, diag::err_expected_semi_after_tagdecl,
1110                       TagType == DeclSpec::TST_class ? "class"
1111                       : TagType == DeclSpec::TST_struct? "struct" : "union");
1112      // Push this token back into the preprocessor and change our current token
1113      // to ';' so that the rest of the code recovers as though there were an
1114      // ';' after the definition.
1115      PP.EnterToken(Tok);
1116      Tok.setKind(tok::semi);
1117    }
1118  }
1119}
1120
1121/// ParseBaseClause - Parse the base-clause of a C++ class [C++ class.derived].
1122///
1123///       base-clause : [C++ class.derived]
1124///         ':' base-specifier-list
1125///       base-specifier-list:
1126///         base-specifier '...'[opt]
1127///         base-specifier-list ',' base-specifier '...'[opt]
1128void Parser::ParseBaseClause(Decl *ClassDecl) {
1129  assert(Tok.is(tok::colon) && "Not a base clause");
1130  ConsumeToken();
1131
1132  // Build up an array of parsed base specifiers.
1133  llvm::SmallVector<CXXBaseSpecifier *, 8> BaseInfo;
1134
1135  while (true) {
1136    // Parse a base-specifier.
1137    BaseResult Result = ParseBaseSpecifier(ClassDecl);
1138    if (Result.isInvalid()) {
1139      // Skip the rest of this base specifier, up until the comma or
1140      // opening brace.
1141      SkipUntil(tok::comma, tok::l_brace, true, true);
1142    } else {
1143      // Add this to our array of base specifiers.
1144      BaseInfo.push_back(Result.get());
1145    }
1146
1147    // If the next token is a comma, consume it and keep reading
1148    // base-specifiers.
1149    if (Tok.isNot(tok::comma)) break;
1150
1151    // Consume the comma.
1152    ConsumeToken();
1153  }
1154
1155  // Attach the base specifiers
1156  Actions.ActOnBaseSpecifiers(ClassDecl, BaseInfo.data(), BaseInfo.size());
1157}
1158
1159/// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is
1160/// one entry in the base class list of a class specifier, for example:
1161///    class foo : public bar, virtual private baz {
1162/// 'public bar' and 'virtual private baz' are each base-specifiers.
1163///
1164///       base-specifier: [C++ class.derived]
1165///         ::[opt] nested-name-specifier[opt] class-name
1166///         'virtual' access-specifier[opt] ::[opt] nested-name-specifier[opt]
1167///                        class-name
1168///         access-specifier 'virtual'[opt] ::[opt] nested-name-specifier[opt]
1169///                        class-name
1170Parser::BaseResult Parser::ParseBaseSpecifier(Decl *ClassDecl) {
1171  bool IsVirtual = false;
1172  SourceLocation StartLoc = Tok.getLocation();
1173
1174  // Parse the 'virtual' keyword.
1175  if (Tok.is(tok::kw_virtual))  {
1176    ConsumeToken();
1177    IsVirtual = true;
1178  }
1179
1180  // Parse an (optional) access specifier.
1181  AccessSpecifier Access = getAccessSpecifierIfPresent();
1182  if (Access != AS_none)
1183    ConsumeToken();
1184
1185  // Parse the 'virtual' keyword (again!), in case it came after the
1186  // access specifier.
1187  if (Tok.is(tok::kw_virtual))  {
1188    SourceLocation VirtualLoc = ConsumeToken();
1189    if (IsVirtual) {
1190      // Complain about duplicate 'virtual'
1191      Diag(VirtualLoc, diag::err_dup_virtual)
1192        << FixItHint::CreateRemoval(VirtualLoc);
1193    }
1194
1195    IsVirtual = true;
1196  }
1197
1198  // Parse optional '::' and optional nested-name-specifier.
1199  CXXScopeSpec SS;
1200  ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
1201
1202  // The location of the base class itself.
1203  SourceLocation BaseLoc = Tok.getLocation();
1204
1205  // Parse the class-name.
1206  SourceLocation EndLocation;
1207  TypeResult BaseType = ParseClassName(EndLocation, &SS);
1208  if (BaseType.isInvalid())
1209    return true;
1210
1211  // Find the complete source range for the base-specifier.
1212  SourceRange Range(StartLoc, EndLocation);
1213
1214  // Notify semantic analysis that we have parsed a complete
1215  // base-specifier.
1216  return Actions.ActOnBaseSpecifier(ClassDecl, Range, IsVirtual, Access,
1217                                    BaseType.get(), BaseLoc);
1218}
1219
1220/// getAccessSpecifierIfPresent - Determine whether the next token is
1221/// a C++ access-specifier.
1222///
1223///       access-specifier: [C++ class.derived]
1224///         'private'
1225///         'protected'
1226///         'public'
1227AccessSpecifier Parser::getAccessSpecifierIfPresent() const {
1228  switch (Tok.getKind()) {
1229  default: return AS_none;
1230  case tok::kw_private: return AS_private;
1231  case tok::kw_protected: return AS_protected;
1232  case tok::kw_public: return AS_public;
1233  }
1234}
1235
1236void Parser::HandleMemberFunctionDefaultArgs(Declarator& DeclaratorInfo,
1237                                             Decl *ThisDecl) {
1238  // We just declared a member function. If this member function
1239  // has any default arguments, we'll need to parse them later.
1240  LateParsedMethodDeclaration *LateMethod = 0;
1241  DeclaratorChunk::FunctionTypeInfo &FTI
1242    = DeclaratorInfo.getTypeObject(0).Fun;
1243  for (unsigned ParamIdx = 0; ParamIdx < FTI.NumArgs; ++ParamIdx) {
1244    if (LateMethod || FTI.ArgInfo[ParamIdx].DefaultArgTokens) {
1245      if (!LateMethod) {
1246        // Push this method onto the stack of late-parsed method
1247        // declarations.
1248        LateMethod = new LateParsedMethodDeclaration(this, ThisDecl);
1249        getCurrentClass().LateParsedDeclarations.push_back(LateMethod);
1250        LateMethod->TemplateScope = getCurScope()->isTemplateParamScope();
1251
1252        // Add all of the parameters prior to this one (they don't
1253        // have default arguments).
1254        LateMethod->DefaultArgs.reserve(FTI.NumArgs);
1255        for (unsigned I = 0; I < ParamIdx; ++I)
1256          LateMethod->DefaultArgs.push_back(
1257                             LateParsedDefaultArgument(FTI.ArgInfo[I].Param));
1258      }
1259
1260      // Add this parameter to the list of parameters (it or may
1261      // not have a default argument).
1262      LateMethod->DefaultArgs.push_back(
1263        LateParsedDefaultArgument(FTI.ArgInfo[ParamIdx].Param,
1264                                  FTI.ArgInfo[ParamIdx].DefaultArgTokens));
1265    }
1266  }
1267}
1268
1269/// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration.
1270///
1271///       member-declaration:
1272///         decl-specifier-seq[opt] member-declarator-list[opt] ';'
1273///         function-definition ';'[opt]
1274///         ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO]
1275///         using-declaration                                            [TODO]
1276/// [C++0x] static_assert-declaration
1277///         template-declaration
1278/// [GNU]   '__extension__' member-declaration
1279///
1280///       member-declarator-list:
1281///         member-declarator
1282///         member-declarator-list ',' member-declarator
1283///
1284///       member-declarator:
1285///         declarator pure-specifier[opt]
1286///         declarator constant-initializer[opt]
1287///         identifier[opt] ':' constant-expression
1288///
1289///       pure-specifier:
1290///         '= 0'
1291///
1292///       constant-initializer:
1293///         '=' constant-expression
1294///
1295void Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS,
1296                                       const ParsedTemplateInfo &TemplateInfo,
1297                                       ParsingDeclRAIIObject *TemplateDiags) {
1298  // Access declarations.
1299  if (!TemplateInfo.Kind &&
1300      (Tok.is(tok::identifier) || Tok.is(tok::coloncolon)) &&
1301      !TryAnnotateCXXScopeToken() &&
1302      Tok.is(tok::annot_cxxscope)) {
1303    bool isAccessDecl = false;
1304    if (NextToken().is(tok::identifier))
1305      isAccessDecl = GetLookAheadToken(2).is(tok::semi);
1306    else
1307      isAccessDecl = NextToken().is(tok::kw_operator);
1308
1309    if (isAccessDecl) {
1310      // Collect the scope specifier token we annotated earlier.
1311      CXXScopeSpec SS;
1312      ParseOptionalCXXScopeSpecifier(SS, ParsedType(), false);
1313
1314      // Try to parse an unqualified-id.
1315      UnqualifiedId Name;
1316      if (ParseUnqualifiedId(SS, false, true, true, ParsedType(), Name)) {
1317        SkipUntil(tok::semi);
1318        return;
1319      }
1320
1321      // TODO: recover from mistakenly-qualified operator declarations.
1322      if (ExpectAndConsume(tok::semi,
1323                           diag::err_expected_semi_after,
1324                           "access declaration",
1325                           tok::semi))
1326        return;
1327
1328      Actions.ActOnUsingDeclaration(getCurScope(), AS,
1329                                    false, SourceLocation(),
1330                                    SS, Name,
1331                                    /* AttrList */ 0,
1332                                    /* IsTypeName */ false,
1333                                    SourceLocation());
1334      return;
1335    }
1336  }
1337
1338  // static_assert-declaration
1339  if (Tok.is(tok::kw_static_assert)) {
1340    // FIXME: Check for templates
1341    SourceLocation DeclEnd;
1342    ParseStaticAssertDeclaration(DeclEnd);
1343    return;
1344  }
1345
1346  if (Tok.is(tok::kw_template)) {
1347    assert(!TemplateInfo.TemplateParams &&
1348           "Nested template improperly parsed?");
1349    SourceLocation DeclEnd;
1350    ParseDeclarationStartingWithTemplate(Declarator::MemberContext, DeclEnd,
1351                                         AS);
1352    return;
1353  }
1354
1355  // Handle:  member-declaration ::= '__extension__' member-declaration
1356  if (Tok.is(tok::kw___extension__)) {
1357    // __extension__ silences extension warnings in the subexpression.
1358    ExtensionRAIIObject O(Diags);  // Use RAII to do this.
1359    ConsumeToken();
1360    return ParseCXXClassMemberDeclaration(AS, TemplateInfo, TemplateDiags);
1361  }
1362
1363  // Don't parse FOO:BAR as if it were a typo for FOO::BAR, in this context it
1364  // is a bitfield.
1365  ColonProtectionRAIIObject X(*this);
1366
1367  CXX0XAttributeList AttrList;
1368  // Optional C++0x attribute-specifier
1369  if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier())
1370    AttrList = ParseCXX0XAttributes();
1371  if (getLang().Microsoft && Tok.is(tok::l_square))
1372    ParseMicrosoftAttributes();
1373
1374  if (Tok.is(tok::kw_using)) {
1375    // FIXME: Check for template aliases
1376
1377    if (AttrList.HasAttr)
1378      Diag(AttrList.Range.getBegin(), diag::err_attributes_not_allowed)
1379        << AttrList.Range;
1380
1381    // Eat 'using'.
1382    SourceLocation UsingLoc = ConsumeToken();
1383
1384    if (Tok.is(tok::kw_namespace)) {
1385      Diag(UsingLoc, diag::err_using_namespace_in_class);
1386      SkipUntil(tok::semi, true, true);
1387    } else {
1388      SourceLocation DeclEnd;
1389      // Otherwise, it must be using-declaration.
1390      ParseUsingDeclaration(Declarator::MemberContext, TemplateInfo,
1391                            UsingLoc, DeclEnd, AS);
1392    }
1393    return;
1394  }
1395
1396  SourceLocation DSStart = Tok.getLocation();
1397  // decl-specifier-seq:
1398  // Parse the common declaration-specifiers piece.
1399  ParsingDeclSpec DS(*this, TemplateDiags);
1400  DS.AddAttributes(AttrList.AttrList);
1401  ParseDeclarationSpecifiers(DS, TemplateInfo, AS, DSC_class);
1402
1403  MultiTemplateParamsArg TemplateParams(Actions,
1404      TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->data() : 0,
1405      TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->size() : 0);
1406
1407  if (Tok.is(tok::semi)) {
1408    ConsumeToken();
1409    Decl *TheDecl =
1410      Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS, DS);
1411    DS.complete(TheDecl);
1412    return;
1413  }
1414
1415  ParsingDeclarator DeclaratorInfo(*this, DS, Declarator::MemberContext);
1416
1417  if (Tok.isNot(tok::colon)) {
1418    // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
1419    ColonProtectionRAIIObject X(*this);
1420
1421    // Parse the first declarator.
1422    ParseDeclarator(DeclaratorInfo);
1423    // Error parsing the declarator?
1424    if (!DeclaratorInfo.hasName()) {
1425      // If so, skip until the semi-colon or a }.
1426      SkipUntil(tok::r_brace, true);
1427      if (Tok.is(tok::semi))
1428        ConsumeToken();
1429      return;
1430    }
1431
1432    // If attributes exist after the declarator, but before an '{', parse them.
1433    if (Tok.is(tok::kw___attribute)) {
1434      SourceLocation Loc;
1435      AttributeList *AttrList = ParseGNUAttributes(&Loc);
1436      DeclaratorInfo.AddAttributes(AttrList, Loc);
1437    }
1438
1439    // function-definition:
1440    if (Tok.is(tok::l_brace)
1441        || (DeclaratorInfo.isFunctionDeclarator() &&
1442            (Tok.is(tok::colon) || Tok.is(tok::kw_try)))) {
1443      if (!DeclaratorInfo.isFunctionDeclarator()) {
1444        Diag(Tok, diag::err_func_def_no_params);
1445        ConsumeBrace();
1446        SkipUntil(tok::r_brace, true);
1447        return;
1448      }
1449
1450      if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
1451        Diag(Tok, diag::err_function_declared_typedef);
1452        // This recovery skips the entire function body. It would be nice
1453        // to simply call ParseCXXInlineMethodDef() below, however Sema
1454        // assumes the declarator represents a function, not a typedef.
1455        ConsumeBrace();
1456        SkipUntil(tok::r_brace, true);
1457        return;
1458      }
1459
1460      ParseCXXInlineMethodDef(AS, DeclaratorInfo, TemplateInfo);
1461      return;
1462    }
1463  }
1464
1465  // member-declarator-list:
1466  //   member-declarator
1467  //   member-declarator-list ',' member-declarator
1468
1469  llvm::SmallVector<Decl *, 8> DeclsInGroup;
1470  ExprResult BitfieldSize;
1471  ExprResult Init;
1472  bool Deleted = false;
1473
1474  while (1) {
1475    // member-declarator:
1476    //   declarator pure-specifier[opt]
1477    //   declarator constant-initializer[opt]
1478    //   identifier[opt] ':' constant-expression
1479    if (Tok.is(tok::colon)) {
1480      ConsumeToken();
1481      BitfieldSize = ParseConstantExpression();
1482      if (BitfieldSize.isInvalid())
1483        SkipUntil(tok::comma, true, true);
1484    }
1485
1486    // pure-specifier:
1487    //   '= 0'
1488    //
1489    // constant-initializer:
1490    //   '=' constant-expression
1491    //
1492    // defaulted/deleted function-definition:
1493    //   '=' 'default'                          [TODO]
1494    //   '=' 'delete'
1495    if (Tok.is(tok::equal)) {
1496      ConsumeToken();
1497      if (Tok.is(tok::kw_delete)) {
1498        if (!getLang().CPlusPlus0x)
1499          Diag(Tok, diag::warn_deleted_function_accepted_as_extension);
1500        ConsumeToken();
1501        Deleted = true;
1502      } else {
1503        Init = ParseInitializer();
1504        if (Init.isInvalid())
1505          SkipUntil(tok::comma, true, true);
1506      }
1507    }
1508
1509    // If a simple-asm-expr is present, parse it.
1510    if (Tok.is(tok::kw_asm)) {
1511      SourceLocation Loc;
1512      ExprResult AsmLabel(ParseSimpleAsm(&Loc));
1513      if (AsmLabel.isInvalid())
1514        SkipUntil(tok::comma, true, true);
1515
1516      DeclaratorInfo.setAsmLabel(AsmLabel.release());
1517      DeclaratorInfo.SetRangeEnd(Loc);
1518    }
1519
1520    // If attributes exist after the declarator, parse them.
1521    if (Tok.is(tok::kw___attribute)) {
1522      SourceLocation Loc;
1523      AttributeList *AttrList = ParseGNUAttributes(&Loc);
1524      DeclaratorInfo.AddAttributes(AttrList, Loc);
1525    }
1526
1527    // NOTE: If Sema is the Action module and declarator is an instance field,
1528    // this call will *not* return the created decl; It will return null.
1529    // See Sema::ActOnCXXMemberDeclarator for details.
1530
1531    Decl *ThisDecl = 0;
1532    if (DS.isFriendSpecified()) {
1533      // TODO: handle initializers, bitfields, 'delete'
1534      ThisDecl = Actions.ActOnFriendFunctionDecl(getCurScope(), DeclaratorInfo,
1535                                                 /*IsDefinition*/ false,
1536                                                 move(TemplateParams));
1537    } else {
1538      ThisDecl = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS,
1539                                                  DeclaratorInfo,
1540                                                  move(TemplateParams),
1541                                                  BitfieldSize.release(),
1542                                                  Init.release(),
1543                                                  /*IsDefinition*/Deleted,
1544                                                  Deleted);
1545    }
1546    if (ThisDecl)
1547      DeclsInGroup.push_back(ThisDecl);
1548
1549    if (DeclaratorInfo.isFunctionDeclarator() &&
1550        DeclaratorInfo.getDeclSpec().getStorageClassSpec()
1551          != DeclSpec::SCS_typedef) {
1552      HandleMemberFunctionDefaultArgs(DeclaratorInfo, ThisDecl);
1553    }
1554
1555    DeclaratorInfo.complete(ThisDecl);
1556
1557    // If we don't have a comma, it is either the end of the list (a ';')
1558    // or an error, bail out.
1559    if (Tok.isNot(tok::comma))
1560      break;
1561
1562    // Consume the comma.
1563    ConsumeToken();
1564
1565    // Parse the next declarator.
1566    DeclaratorInfo.clear();
1567    BitfieldSize = 0;
1568    Init = 0;
1569    Deleted = false;
1570
1571    // Attributes are only allowed on the second declarator.
1572    if (Tok.is(tok::kw___attribute)) {
1573      SourceLocation Loc;
1574      AttributeList *AttrList = ParseGNUAttributes(&Loc);
1575      DeclaratorInfo.AddAttributes(AttrList, Loc);
1576    }
1577
1578    if (Tok.isNot(tok::colon))
1579      ParseDeclarator(DeclaratorInfo);
1580  }
1581
1582  if (ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list)) {
1583    // Skip to end of block or statement.
1584    SkipUntil(tok::r_brace, true, true);
1585    // If we stopped at a ';', eat it.
1586    if (Tok.is(tok::semi)) ConsumeToken();
1587    return;
1588  }
1589
1590  Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup.data(),
1591                                  DeclsInGroup.size());
1592}
1593
1594/// ParseCXXMemberSpecification - Parse the class definition.
1595///
1596///       member-specification:
1597///         member-declaration member-specification[opt]
1598///         access-specifier ':' member-specification[opt]
1599///
1600void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc,
1601                                         unsigned TagType, Decl *TagDecl) {
1602  assert((TagType == DeclSpec::TST_struct ||
1603         TagType == DeclSpec::TST_union  ||
1604         TagType == DeclSpec::TST_class) && "Invalid TagType!");
1605
1606  PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc,
1607                                      "parsing struct/union/class body");
1608
1609  // Determine whether this is a non-nested class. Note that local
1610  // classes are *not* considered to be nested classes.
1611  bool NonNestedClass = true;
1612  if (!ClassStack.empty()) {
1613    for (const Scope *S = getCurScope(); S; S = S->getParent()) {
1614      if (S->isClassScope()) {
1615        // We're inside a class scope, so this is a nested class.
1616        NonNestedClass = false;
1617        break;
1618      }
1619
1620      if ((S->getFlags() & Scope::FnScope)) {
1621        // If we're in a function or function template declared in the
1622        // body of a class, then this is a local class rather than a
1623        // nested class.
1624        const Scope *Parent = S->getParent();
1625        if (Parent->isTemplateParamScope())
1626          Parent = Parent->getParent();
1627        if (Parent->isClassScope())
1628          break;
1629      }
1630    }
1631  }
1632
1633  // Enter a scope for the class.
1634  ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
1635
1636  // Note that we are parsing a new (potentially-nested) class definition.
1637  ParsingClassDefinition ParsingDef(*this, TagDecl, NonNestedClass);
1638
1639  if (TagDecl)
1640    Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
1641
1642  if (Tok.is(tok::colon)) {
1643    ParseBaseClause(TagDecl);
1644
1645    if (!Tok.is(tok::l_brace)) {
1646      Diag(Tok, diag::err_expected_lbrace_after_base_specifiers);
1647
1648      if (TagDecl)
1649        Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
1650      return;
1651    }
1652  }
1653
1654  assert(Tok.is(tok::l_brace));
1655
1656  SourceLocation LBraceLoc = ConsumeBrace();
1657
1658  if (TagDecl)
1659    Actions.ActOnStartCXXMemberDeclarations(getCurScope(), TagDecl, LBraceLoc);
1660
1661  // C++ 11p3: Members of a class defined with the keyword class are private
1662  // by default. Members of a class defined with the keywords struct or union
1663  // are public by default.
1664  AccessSpecifier CurAS;
1665  if (TagType == DeclSpec::TST_class)
1666    CurAS = AS_private;
1667  else
1668    CurAS = AS_public;
1669
1670  SourceLocation RBraceLoc;
1671  if (TagDecl) {
1672    // While we still have something to read, read the member-declarations.
1673    while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
1674      // Each iteration of this loop reads one member-declaration.
1675
1676      // Check for extraneous top-level semicolon.
1677      if (Tok.is(tok::semi)) {
1678        Diag(Tok, diag::ext_extra_struct_semi)
1679          << DeclSpec::getSpecifierName((DeclSpec::TST)TagType)
1680          << FixItHint::CreateRemoval(Tok.getLocation());
1681        ConsumeToken();
1682        continue;
1683      }
1684
1685      AccessSpecifier AS = getAccessSpecifierIfPresent();
1686      if (AS != AS_none) {
1687        // Current token is a C++ access specifier.
1688        CurAS = AS;
1689        SourceLocation ASLoc = Tok.getLocation();
1690        ConsumeToken();
1691        if (Tok.is(tok::colon))
1692          Actions.ActOnAccessSpecifier(AS, ASLoc, Tok.getLocation());
1693        else
1694          Diag(Tok, diag::err_expected_colon);
1695        ConsumeToken();
1696        continue;
1697      }
1698
1699      // FIXME: Make sure we don't have a template here.
1700
1701      // Parse all the comma separated declarators.
1702      ParseCXXClassMemberDeclaration(CurAS);
1703    }
1704
1705    RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc);
1706  } else {
1707    SkipUntil(tok::r_brace, false, false);
1708  }
1709
1710  // If attributes exist after class contents, parse them.
1711  AttributeList *AttrList = 0;
1712  if (Tok.is(tok::kw___attribute))
1713    AttrList = ParseGNUAttributes();
1714
1715  if (TagDecl)
1716    Actions.ActOnFinishCXXMemberSpecification(getCurScope(), RecordLoc, TagDecl,
1717                                              LBraceLoc, RBraceLoc,
1718                                              AttrList);
1719
1720  // C++ 9.2p2: Within the class member-specification, the class is regarded as
1721  // complete within function bodies, default arguments,
1722  // exception-specifications, and constructor ctor-initializers (including
1723  // such things in nested classes).
1724  //
1725  // FIXME: Only function bodies and constructor ctor-initializers are
1726  // parsed correctly, fix the rest.
1727  if (TagDecl && NonNestedClass) {
1728    // We are not inside a nested class. This class and its nested classes
1729    // are complete and we can parse the delayed portions of method
1730    // declarations and the lexed inline method definitions.
1731    SourceLocation SavedPrevTokLocation = PrevTokLocation;
1732    ParseLexedMethodDeclarations(getCurrentClass());
1733    ParseLexedMethodDefs(getCurrentClass());
1734    PrevTokLocation = SavedPrevTokLocation;
1735  }
1736
1737  if (TagDecl)
1738    Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, RBraceLoc);
1739
1740  // Leave the class scope.
1741  ParsingDef.Pop();
1742  ClassScope.Exit();
1743}
1744
1745/// ParseConstructorInitializer - Parse a C++ constructor initializer,
1746/// which explicitly initializes the members or base classes of a
1747/// class (C++ [class.base.init]). For example, the three initializers
1748/// after the ':' in the Derived constructor below:
1749///
1750/// @code
1751/// class Base { };
1752/// class Derived : Base {
1753///   int x;
1754///   float f;
1755/// public:
1756///   Derived(float f) : Base(), x(17), f(f) { }
1757/// };
1758/// @endcode
1759///
1760/// [C++]  ctor-initializer:
1761///          ':' mem-initializer-list
1762///
1763/// [C++]  mem-initializer-list:
1764///          mem-initializer
1765///          mem-initializer , mem-initializer-list
1766void Parser::ParseConstructorInitializer(Decl *ConstructorDecl) {
1767  assert(Tok.is(tok::colon) && "Constructor initializer always starts with ':'");
1768
1769  SourceLocation ColonLoc = ConsumeToken();
1770
1771  llvm::SmallVector<CXXBaseOrMemberInitializer*, 4> MemInitializers;
1772  bool AnyErrors = false;
1773
1774  do {
1775    if (Tok.is(tok::code_completion)) {
1776      Actions.CodeCompleteConstructorInitializer(ConstructorDecl,
1777                                                 MemInitializers.data(),
1778                                                 MemInitializers.size());
1779      ConsumeCodeCompletionToken();
1780    } else {
1781      MemInitResult MemInit = ParseMemInitializer(ConstructorDecl);
1782      if (!MemInit.isInvalid())
1783        MemInitializers.push_back(MemInit.get());
1784      else
1785        AnyErrors = true;
1786    }
1787
1788    if (Tok.is(tok::comma))
1789      ConsumeToken();
1790    else if (Tok.is(tok::l_brace))
1791      break;
1792    // If the next token looks like a base or member initializer, assume that
1793    // we're just missing a comma.
1794    else if (Tok.is(tok::identifier) || Tok.is(tok::coloncolon)) {
1795      SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation);
1796      Diag(Loc, diag::err_ctor_init_missing_comma)
1797        << FixItHint::CreateInsertion(Loc, ", ");
1798    } else {
1799      // Skip over garbage, until we get to '{'.  Don't eat the '{'.
1800      Diag(Tok.getLocation(), diag::err_expected_lbrace_or_comma);
1801      SkipUntil(tok::l_brace, true, true);
1802      break;
1803    }
1804  } while (true);
1805
1806  Actions.ActOnMemInitializers(ConstructorDecl, ColonLoc,
1807                               MemInitializers.data(), MemInitializers.size(),
1808                               AnyErrors);
1809}
1810
1811/// ParseMemInitializer - Parse a C++ member initializer, which is
1812/// part of a constructor initializer that explicitly initializes one
1813/// member or base class (C++ [class.base.init]). See
1814/// ParseConstructorInitializer for an example.
1815///
1816/// [C++] mem-initializer:
1817///         mem-initializer-id '(' expression-list[opt] ')'
1818///
1819/// [C++] mem-initializer-id:
1820///         '::'[opt] nested-name-specifier[opt] class-name
1821///         identifier
1822Parser::MemInitResult Parser::ParseMemInitializer(Decl *ConstructorDecl) {
1823  // parse '::'[opt] nested-name-specifier[opt]
1824  CXXScopeSpec SS;
1825  ParseOptionalCXXScopeSpecifier(SS, ParsedType(), false);
1826  ParsedType TemplateTypeTy;
1827  if (Tok.is(tok::annot_template_id)) {
1828    TemplateIdAnnotation *TemplateId
1829      = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
1830    if (TemplateId->Kind == TNK_Type_template ||
1831        TemplateId->Kind == TNK_Dependent_template_name) {
1832      AnnotateTemplateIdTokenAsType(&SS);
1833      assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
1834      TemplateTypeTy = getTypeAnnotation(Tok);
1835    }
1836  }
1837  if (!TemplateTypeTy && Tok.isNot(tok::identifier)) {
1838    Diag(Tok, diag::err_expected_member_or_base_name);
1839    return true;
1840  }
1841
1842  // Get the identifier. This may be a member name or a class name,
1843  // but we'll let the semantic analysis determine which it is.
1844  IdentifierInfo *II = Tok.is(tok::identifier) ? Tok.getIdentifierInfo() : 0;
1845  SourceLocation IdLoc = ConsumeToken();
1846
1847  // Parse the '('.
1848  if (Tok.isNot(tok::l_paren)) {
1849    Diag(Tok, diag::err_expected_lparen);
1850    return true;
1851  }
1852  SourceLocation LParenLoc = ConsumeParen();
1853
1854  // Parse the optional expression-list.
1855  ExprVector ArgExprs(Actions);
1856  CommaLocsTy CommaLocs;
1857  if (Tok.isNot(tok::r_paren) && ParseExpressionList(ArgExprs, CommaLocs)) {
1858    SkipUntil(tok::r_paren);
1859    return true;
1860  }
1861
1862  SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
1863
1864  return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
1865                                     TemplateTypeTy, IdLoc,
1866                                     LParenLoc, ArgExprs.take(),
1867                                     ArgExprs.size(), RParenLoc);
1868}
1869
1870/// ParseExceptionSpecification - Parse a C++ exception-specification
1871/// (C++ [except.spec]).
1872///
1873///       exception-specification:
1874///         'throw' '(' type-id-list [opt] ')'
1875/// [MS]    'throw' '(' '...' ')'
1876///
1877///       type-id-list:
1878///         type-id
1879///         type-id-list ',' type-id
1880///
1881bool Parser::ParseExceptionSpecification(SourceLocation &EndLoc,
1882                                         llvm::SmallVectorImpl<ParsedType>
1883                                             &Exceptions,
1884                                         llvm::SmallVectorImpl<SourceRange>
1885                                             &Ranges,
1886                                         bool &hasAnyExceptionSpec) {
1887  assert(Tok.is(tok::kw_throw) && "expected throw");
1888
1889  SourceLocation ThrowLoc = ConsumeToken();
1890
1891  if (!Tok.is(tok::l_paren)) {
1892    return Diag(Tok, diag::err_expected_lparen_after) << "throw";
1893  }
1894  SourceLocation LParenLoc = ConsumeParen();
1895
1896  // Parse throw(...), a Microsoft extension that means "this function
1897  // can throw anything".
1898  if (Tok.is(tok::ellipsis)) {
1899    hasAnyExceptionSpec = true;
1900    SourceLocation EllipsisLoc = ConsumeToken();
1901    if (!getLang().Microsoft)
1902      Diag(EllipsisLoc, diag::ext_ellipsis_exception_spec);
1903    EndLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
1904    return false;
1905  }
1906
1907  // Parse the sequence of type-ids.
1908  SourceRange Range;
1909  while (Tok.isNot(tok::r_paren)) {
1910    TypeResult Res(ParseTypeName(&Range));
1911    if (!Res.isInvalid()) {
1912      Exceptions.push_back(Res.get());
1913      Ranges.push_back(Range);
1914    }
1915    if (Tok.is(tok::comma))
1916      ConsumeToken();
1917    else
1918      break;
1919  }
1920
1921  EndLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
1922  return false;
1923}
1924
1925/// ParseTrailingReturnType - Parse a trailing return type on a new-style
1926/// function declaration.
1927TypeResult Parser::ParseTrailingReturnType() {
1928  assert(Tok.is(tok::arrow) && "expected arrow");
1929
1930  ConsumeToken();
1931
1932  // FIXME: Need to suppress declarations when parsing this typename.
1933  // Otherwise in this function definition:
1934  //
1935  //   auto f() -> struct X {}
1936  //
1937  // struct X is parsed as class definition because of the trailing
1938  // brace.
1939
1940  SourceRange Range;
1941  return ParseTypeName(&Range);
1942}
1943
1944/// \brief We have just started parsing the definition of a new class,
1945/// so push that class onto our stack of classes that is currently
1946/// being parsed.
1947void Parser::PushParsingClass(Decl *ClassDecl, bool NonNestedClass) {
1948  assert((NonNestedClass || !ClassStack.empty()) &&
1949         "Nested class without outer class");
1950  ClassStack.push(new ParsingClass(ClassDecl, NonNestedClass));
1951}
1952
1953/// \brief Deallocate the given parsed class and all of its nested
1954/// classes.
1955void Parser::DeallocateParsedClasses(Parser::ParsingClass *Class) {
1956  for (unsigned I = 0, N = Class->LateParsedDeclarations.size(); I != N; ++I)
1957    delete Class->LateParsedDeclarations[I];
1958  delete Class;
1959}
1960
1961/// \brief Pop the top class of the stack of classes that are
1962/// currently being parsed.
1963///
1964/// This routine should be called when we have finished parsing the
1965/// definition of a class, but have not yet popped the Scope
1966/// associated with the class's definition.
1967///
1968/// \returns true if the class we've popped is a top-level class,
1969/// false otherwise.
1970void Parser::PopParsingClass() {
1971  assert(!ClassStack.empty() && "Mismatched push/pop for class parsing");
1972
1973  ParsingClass *Victim = ClassStack.top();
1974  ClassStack.pop();
1975  if (Victim->TopLevelClass) {
1976    // Deallocate all of the nested classes of this class,
1977    // recursively: we don't need to keep any of this information.
1978    DeallocateParsedClasses(Victim);
1979    return;
1980  }
1981  assert(!ClassStack.empty() && "Missing top-level class?");
1982
1983  if (Victim->LateParsedDeclarations.empty()) {
1984    // The victim is a nested class, but we will not need to perform
1985    // any processing after the definition of this class since it has
1986    // no members whose handling was delayed. Therefore, we can just
1987    // remove this nested class.
1988    DeallocateParsedClasses(Victim);
1989    return;
1990  }
1991
1992  // This nested class has some members that will need to be processed
1993  // after the top-level class is completely defined. Therefore, add
1994  // it to the list of nested classes within its parent.
1995  assert(getCurScope()->isClassScope() && "Nested class outside of class scope?");
1996  ClassStack.top()->LateParsedDeclarations.push_back(new LateParsedClass(this, Victim));
1997  Victim->TemplateScope = getCurScope()->getParent()->isTemplateParamScope();
1998}
1999
2000/// ParseCXX0XAttributes - Parse a C++0x attribute-specifier. Currently only
2001/// parses standard attributes.
2002///
2003/// [C++0x] attribute-specifier:
2004///         '[' '[' attribute-list ']' ']'
2005///
2006/// [C++0x] attribute-list:
2007///         attribute[opt]
2008///         attribute-list ',' attribute[opt]
2009///
2010/// [C++0x] attribute:
2011///         attribute-token attribute-argument-clause[opt]
2012///
2013/// [C++0x] attribute-token:
2014///         identifier
2015///         attribute-scoped-token
2016///
2017/// [C++0x] attribute-scoped-token:
2018///         attribute-namespace '::' identifier
2019///
2020/// [C++0x] attribute-namespace:
2021///         identifier
2022///
2023/// [C++0x] attribute-argument-clause:
2024///         '(' balanced-token-seq ')'
2025///
2026/// [C++0x] balanced-token-seq:
2027///         balanced-token
2028///         balanced-token-seq balanced-token
2029///
2030/// [C++0x] balanced-token:
2031///         '(' balanced-token-seq ')'
2032///         '[' balanced-token-seq ']'
2033///         '{' balanced-token-seq '}'
2034///         any token but '(', ')', '[', ']', '{', or '}'
2035CXX0XAttributeList Parser::ParseCXX0XAttributes(SourceLocation *EndLoc) {
2036  assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square)
2037      && "Not a C++0x attribute list");
2038
2039  SourceLocation StartLoc = Tok.getLocation(), Loc;
2040  AttributeList *CurrAttr = 0;
2041
2042  ConsumeBracket();
2043  ConsumeBracket();
2044
2045  if (Tok.is(tok::comma)) {
2046    Diag(Tok.getLocation(), diag::err_expected_ident);
2047    ConsumeToken();
2048  }
2049
2050  while (Tok.is(tok::identifier) || Tok.is(tok::comma)) {
2051    // attribute not present
2052    if (Tok.is(tok::comma)) {
2053      ConsumeToken();
2054      continue;
2055    }
2056
2057    IdentifierInfo *ScopeName = 0, *AttrName = Tok.getIdentifierInfo();
2058    SourceLocation ScopeLoc, AttrLoc = ConsumeToken();
2059
2060    // scoped attribute
2061    if (Tok.is(tok::coloncolon)) {
2062      ConsumeToken();
2063
2064      if (!Tok.is(tok::identifier)) {
2065        Diag(Tok.getLocation(), diag::err_expected_ident);
2066        SkipUntil(tok::r_square, tok::comma, true, true);
2067        continue;
2068      }
2069
2070      ScopeName = AttrName;
2071      ScopeLoc = AttrLoc;
2072
2073      AttrName = Tok.getIdentifierInfo();
2074      AttrLoc = ConsumeToken();
2075    }
2076
2077    bool AttrParsed = false;
2078    // No scoped names are supported; ideally we could put all non-standard
2079    // attributes into namespaces.
2080    if (!ScopeName) {
2081      switch(AttributeList::getKind(AttrName))
2082      {
2083      // No arguments
2084      case AttributeList::AT_base_check:
2085      case AttributeList::AT_carries_dependency:
2086      case AttributeList::AT_final:
2087      case AttributeList::AT_hiding:
2088      case AttributeList::AT_noreturn:
2089      case AttributeList::AT_override: {
2090        if (Tok.is(tok::l_paren)) {
2091          Diag(Tok.getLocation(), diag::err_cxx0x_attribute_forbids_arguments)
2092            << AttrName->getName();
2093          break;
2094        }
2095
2096        CurrAttr = AttrFactory.Create(AttrName, AttrLoc, 0, AttrLoc, 0,
2097                                      SourceLocation(), 0, 0, CurrAttr, false,
2098                                      true);
2099        AttrParsed = true;
2100        break;
2101      }
2102
2103      // One argument; must be a type-id or assignment-expression
2104      case AttributeList::AT_aligned: {
2105        if (Tok.isNot(tok::l_paren)) {
2106          Diag(Tok.getLocation(), diag::err_cxx0x_attribute_requires_arguments)
2107            << AttrName->getName();
2108          break;
2109        }
2110        SourceLocation ParamLoc = ConsumeParen();
2111
2112        ExprResult ArgExpr = ParseCXX0XAlignArgument(ParamLoc);
2113
2114        MatchRHSPunctuation(tok::r_paren, ParamLoc);
2115
2116        ExprVector ArgExprs(Actions);
2117        ArgExprs.push_back(ArgExpr.release());
2118        CurrAttr = AttrFactory.Create(AttrName, AttrLoc, 0, AttrLoc,
2119                                      0, ParamLoc, ArgExprs.take(), 1, CurrAttr,
2120                                      false, true);
2121
2122        AttrParsed = true;
2123        break;
2124      }
2125
2126      // Silence warnings
2127      default: break;
2128      }
2129    }
2130
2131    // Skip the entire parameter clause, if any
2132    if (!AttrParsed && Tok.is(tok::l_paren)) {
2133      ConsumeParen();
2134      // SkipUntil maintains the balancedness of tokens.
2135      SkipUntil(tok::r_paren, false);
2136    }
2137  }
2138
2139  if (ExpectAndConsume(tok::r_square, diag::err_expected_rsquare))
2140    SkipUntil(tok::r_square, false);
2141  Loc = Tok.getLocation();
2142  if (ExpectAndConsume(tok::r_square, diag::err_expected_rsquare))
2143    SkipUntil(tok::r_square, false);
2144
2145  CXX0XAttributeList Attr (CurrAttr, SourceRange(StartLoc, Loc), true);
2146  return Attr;
2147}
2148
2149/// ParseCXX0XAlignArgument - Parse the argument to C++0x's [[align]]
2150/// attribute.
2151///
2152/// FIXME: Simply returns an alignof() expression if the argument is a
2153/// type. Ideally, the type should be propagated directly into Sema.
2154///
2155/// [C++0x] 'align' '(' type-id ')'
2156/// [C++0x] 'align' '(' assignment-expression ')'
2157ExprResult Parser::ParseCXX0XAlignArgument(SourceLocation Start) {
2158  if (isTypeIdInParens()) {
2159    EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
2160    SourceLocation TypeLoc = Tok.getLocation();
2161    ParsedType Ty = ParseTypeName().get();
2162    SourceRange TypeRange(Start, Tok.getLocation());
2163    return Actions.ActOnSizeOfAlignOfExpr(TypeLoc, false, true,
2164                                          Ty.getAsOpaquePtr(), TypeRange);
2165  } else
2166    return ParseConstantExpression();
2167}
2168
2169/// ParseMicrosoftAttributes - Parse a Microsoft attribute [Attr]
2170///
2171/// [MS] ms-attribute:
2172///             '[' token-seq ']'
2173///
2174/// [MS] ms-attribute-seq:
2175///             ms-attribute[opt]
2176///             ms-attribute ms-attribute-seq
2177void Parser::ParseMicrosoftAttributes() {
2178  assert(Tok.is(tok::l_square) && "Not a Microsoft attribute list");
2179
2180  while (Tok.is(tok::l_square)) {
2181    ConsumeBracket();
2182    SkipUntil(tok::r_square, true, true);
2183    ExpectAndConsume(tok::r_square, diag::err_expected_rsquare);
2184  }
2185}
2186