ParseDeclCXX.cpp revision 42c39f39184c5ce9d7f489e5dcb7eec770728a9a
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/Parse/DeclSpec.h"
18#include "clang/Parse/Scope.h"
19#include "ExtensionRAIIObject.h"
20using namespace clang;
21
22/// ParseNamespace - We know that the current token is a namespace keyword. This
23/// may either be a top level namespace or a block-level namespace alias.
24///
25///       namespace-definition: [C++ 7.3: basic.namespace]
26///         named-namespace-definition
27///         unnamed-namespace-definition
28///
29///       unnamed-namespace-definition:
30///         'namespace' attributes[opt] '{' namespace-body '}'
31///
32///       named-namespace-definition:
33///         original-namespace-definition
34///         extension-namespace-definition
35///
36///       original-namespace-definition:
37///         'namespace' identifier attributes[opt] '{' namespace-body '}'
38///
39///       extension-namespace-definition:
40///         'namespace' original-namespace-name '{' namespace-body '}'
41///
42///       namespace-alias-definition:  [C++ 7.3.2: namespace.alias]
43///         'namespace' identifier '=' qualified-namespace-specifier ';'
44///
45Parser::DeclPtrTy Parser::ParseNamespace(unsigned Context,
46                                         SourceLocation &DeclEnd) {
47  assert(Tok.is(tok::kw_namespace) && "Not a namespace!");
48  SourceLocation NamespaceLoc = ConsumeToken();  // eat the 'namespace'.
49
50  SourceLocation IdentLoc;
51  IdentifierInfo *Ident = 0;
52
53  Token attrTok;
54
55  if (Tok.is(tok::identifier)) {
56    Ident = Tok.getIdentifierInfo();
57    IdentLoc = ConsumeToken();  // eat the identifier.
58  }
59
60  // Read label attributes, if present.
61  Action::AttrTy *AttrList = 0;
62  if (Tok.is(tok::kw___attribute)) {
63    attrTok = Tok;
64
65    // FIXME: save these somewhere.
66    AttrList = ParseAttributes();
67  }
68
69  if (Tok.is(tok::equal)) {
70    if (AttrList)
71      Diag(attrTok, diag::err_unexpected_namespace_attributes_alias);
72
73    return ParseNamespaceAlias(NamespaceLoc, IdentLoc, Ident, DeclEnd);
74  }
75
76  if (Tok.isNot(tok::l_brace)) {
77    Diag(Tok, Ident ? diag::err_expected_lbrace :
78         diag::err_expected_ident_lbrace);
79    return DeclPtrTy();
80  }
81
82  SourceLocation LBrace = ConsumeBrace();
83
84  // Enter a scope for the namespace.
85  ParseScope NamespaceScope(this, Scope::DeclScope);
86
87  DeclPtrTy NamespcDecl =
88    Actions.ActOnStartNamespaceDef(CurScope, IdentLoc, Ident, LBrace);
89
90  PrettyStackTraceActionsDecl CrashInfo(NamespcDecl, NamespaceLoc, Actions,
91                                        PP.getSourceManager(),
92                                        "parsing namespace");
93
94  while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof))
95    ParseExternalDeclaration();
96
97  // Leave the namespace scope.
98  NamespaceScope.Exit();
99
100  SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBrace);
101  Actions.ActOnFinishNamespaceDef(NamespcDecl, RBraceLoc);
102
103  DeclEnd = RBraceLoc;
104  return NamespcDecl;
105}
106
107/// ParseNamespaceAlias - Parse the part after the '=' in a namespace
108/// alias definition.
109///
110Parser::DeclPtrTy Parser::ParseNamespaceAlias(SourceLocation NamespaceLoc,
111                                              SourceLocation AliasLoc,
112                                              IdentifierInfo *Alias,
113                                              SourceLocation &DeclEnd) {
114  assert(Tok.is(tok::equal) && "Not equal token");
115
116  ConsumeToken(); // eat the '='.
117
118  CXXScopeSpec SS;
119  // Parse (optional) nested-name-specifier.
120  ParseOptionalCXXScopeSpecifier(SS);
121
122  if (SS.isInvalid() || Tok.isNot(tok::identifier)) {
123    Diag(Tok, diag::err_expected_namespace_name);
124    // Skip to end of the definition and eat the ';'.
125    SkipUntil(tok::semi);
126    return DeclPtrTy();
127  }
128
129  // Parse identifier.
130  IdentifierInfo *Ident = Tok.getIdentifierInfo();
131  SourceLocation IdentLoc = ConsumeToken();
132
133  // Eat the ';'.
134  DeclEnd = Tok.getLocation();
135  ExpectAndConsume(tok::semi, diag::err_expected_semi_after_namespace_name,
136                   "", tok::semi);
137
138  return Actions.ActOnNamespaceAliasDef(CurScope, NamespaceLoc, AliasLoc, Alias,
139                                        SS, IdentLoc, Ident);
140}
141
142/// ParseLinkage - We know that the current token is a string_literal
143/// and just before that, that extern was seen.
144///
145///       linkage-specification: [C++ 7.5p2: dcl.link]
146///         'extern' string-literal '{' declaration-seq[opt] '}'
147///         'extern' string-literal declaration
148///
149Parser::DeclPtrTy Parser::ParseLinkage(unsigned Context) {
150  assert(Tok.is(tok::string_literal) && "Not a string literal!");
151  llvm::SmallVector<char, 8> LangBuffer;
152  // LangBuffer is guaranteed to be big enough.
153  LangBuffer.resize(Tok.getLength());
154  const char *LangBufPtr = &LangBuffer[0];
155  unsigned StrSize = PP.getSpelling(Tok, LangBufPtr);
156
157  SourceLocation Loc = ConsumeStringToken();
158
159  ParseScope LinkageScope(this, Scope::DeclScope);
160  DeclPtrTy LinkageSpec
161    = Actions.ActOnStartLinkageSpecification(CurScope,
162                                             /*FIXME: */SourceLocation(),
163                                             Loc, LangBufPtr, StrSize,
164                                       Tok.is(tok::l_brace)? Tok.getLocation()
165                                                           : SourceLocation());
166
167  if (Tok.isNot(tok::l_brace)) {
168    ParseDeclarationOrFunctionDefinition();
169    return Actions.ActOnFinishLinkageSpecification(CurScope, LinkageSpec,
170                                                   SourceLocation());
171  }
172
173  SourceLocation LBrace = ConsumeBrace();
174  while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
175    ParseExternalDeclaration();
176  }
177
178  SourceLocation RBrace = MatchRHSPunctuation(tok::r_brace, LBrace);
179  return Actions.ActOnFinishLinkageSpecification(CurScope, LinkageSpec, RBrace);
180}
181
182/// ParseUsingDirectiveOrDeclaration - Parse C++ using using-declaration or
183/// using-directive. Assumes that current token is 'using'.
184Parser::DeclPtrTy Parser::ParseUsingDirectiveOrDeclaration(unsigned Context,
185                                                     SourceLocation &DeclEnd) {
186  assert(Tok.is(tok::kw_using) && "Not using token");
187
188  // Eat 'using'.
189  SourceLocation UsingLoc = ConsumeToken();
190
191  if (Tok.is(tok::kw_namespace))
192    // Next token after 'using' is 'namespace' so it must be using-directive
193    return ParseUsingDirective(Context, UsingLoc, DeclEnd);
194
195  // Otherwise, it must be using-declaration.
196  return ParseUsingDeclaration(Context, UsingLoc, DeclEnd);
197}
198
199/// ParseUsingDirective - Parse C++ using-directive, assumes
200/// that current token is 'namespace' and 'using' was already parsed.
201///
202///       using-directive: [C++ 7.3.p4: namespace.udir]
203///        'using' 'namespace' ::[opt] nested-name-specifier[opt]
204///                 namespace-name ;
205/// [GNU] using-directive:
206///        'using' 'namespace' ::[opt] nested-name-specifier[opt]
207///                 namespace-name attributes[opt] ;
208///
209Parser::DeclPtrTy Parser::ParseUsingDirective(unsigned Context,
210                                              SourceLocation UsingLoc,
211                                              SourceLocation &DeclEnd) {
212  assert(Tok.is(tok::kw_namespace) && "Not 'namespace' token");
213
214  // Eat 'namespace'.
215  SourceLocation NamespcLoc = ConsumeToken();
216
217  CXXScopeSpec SS;
218  // Parse (optional) nested-name-specifier.
219  ParseOptionalCXXScopeSpecifier(SS);
220
221  AttributeList *AttrList = 0;
222  IdentifierInfo *NamespcName = 0;
223  SourceLocation IdentLoc = SourceLocation();
224
225  // Parse namespace-name.
226  if (SS.isInvalid() || Tok.isNot(tok::identifier)) {
227    Diag(Tok, diag::err_expected_namespace_name);
228    // If there was invalid namespace name, skip to end of decl, and eat ';'.
229    SkipUntil(tok::semi);
230    // FIXME: Are there cases, when we would like to call ActOnUsingDirective?
231    return DeclPtrTy();
232  }
233
234  // Parse identifier.
235  NamespcName = Tok.getIdentifierInfo();
236  IdentLoc = ConsumeToken();
237
238  // Parse (optional) attributes (most likely GNU strong-using extension).
239  if (Tok.is(tok::kw___attribute))
240    AttrList = ParseAttributes();
241
242  // Eat ';'.
243  DeclEnd = Tok.getLocation();
244  ExpectAndConsume(tok::semi,
245                   AttrList ? diag::err_expected_semi_after_attribute_list :
246                   diag::err_expected_semi_after_namespace_name, "", tok::semi);
247
248  return Actions.ActOnUsingDirective(CurScope, UsingLoc, NamespcLoc, SS,
249                                      IdentLoc, NamespcName, AttrList);
250}
251
252/// ParseUsingDeclaration - Parse C++ using-declaration. Assumes that
253/// 'using' was already seen.
254///
255///     using-declaration: [C++ 7.3.p3: namespace.udecl]
256///       'using' 'typename'[opt] ::[opt] nested-name-specifier
257///               unqualified-id
258///       'using' :: unqualified-id
259///
260Parser::DeclPtrTy Parser::ParseUsingDeclaration(unsigned Context,
261                                                SourceLocation UsingLoc,
262                                                SourceLocation &DeclEnd) {
263  CXXScopeSpec SS;
264  bool IsTypeName;
265
266  // Ignore optional 'typename'.
267  if (Tok.is(tok::kw_typename)) {
268    ConsumeToken();
269    IsTypeName = true;
270  }
271  else
272    IsTypeName = false;
273
274  // Parse nested-name-specifier.
275  ParseOptionalCXXScopeSpecifier(SS);
276
277  AttributeList *AttrList = 0;
278
279  // Check nested-name specifier.
280  if (SS.isInvalid()) {
281    SkipUntil(tok::semi);
282    return DeclPtrTy();
283  }
284  if (Tok.is(tok::annot_template_id)) {
285    Diag(Tok, diag::err_unexpected_template_spec_in_using);
286    SkipUntil(tok::semi);
287    return DeclPtrTy();
288  }
289
290  IdentifierInfo *TargetName = 0;
291  OverloadedOperatorKind Op = OO_None;
292  SourceLocation IdentLoc;
293
294  if (Tok.is(tok::kw_operator)) {
295    IdentLoc = Tok.getLocation();
296
297    Op = TryParseOperatorFunctionId();
298    if (!Op) {
299      // If there was an invalid operator, skip to end of decl, and eat ';'.
300      SkipUntil(tok::semi);
301      return DeclPtrTy();
302    }
303  } else if (Tok.is(tok::identifier)) {
304    // Parse identifier.
305    TargetName = Tok.getIdentifierInfo();
306    IdentLoc = ConsumeToken();
307  } else {
308    // FIXME: Use a better diagnostic here.
309    Diag(Tok, diag::err_expected_ident_in_using);
310
311    // If there was invalid identifier, skip to end of decl, and eat ';'.
312    SkipUntil(tok::semi);
313    return DeclPtrTy();
314  }
315
316  // Parse (optional) attributes (most likely GNU strong-using extension).
317  if (Tok.is(tok::kw___attribute))
318    AttrList = ParseAttributes();
319
320  // Eat ';'.
321  DeclEnd = Tok.getLocation();
322  ExpectAndConsume(tok::semi, diag::err_expected_semi_after,
323                   AttrList ? "attributes list" : "namespace name", tok::semi);
324
325  return Actions.ActOnUsingDeclaration(CurScope, UsingLoc, SS,
326                                       IdentLoc, TargetName, Op,
327                                       AttrList, IsTypeName);
328}
329
330/// ParseStaticAssertDeclaration - Parse C++0x static_assert-declaratoion.
331///
332///      static_assert-declaration:
333///        static_assert ( constant-expression  ,  string-literal  ) ;
334///
335Parser::DeclPtrTy Parser::ParseStaticAssertDeclaration(SourceLocation &DeclEnd){
336  assert(Tok.is(tok::kw_static_assert) && "Not a static_assert declaration");
337  SourceLocation StaticAssertLoc = ConsumeToken();
338
339  if (Tok.isNot(tok::l_paren)) {
340    Diag(Tok, diag::err_expected_lparen);
341    return DeclPtrTy();
342  }
343
344  SourceLocation LParenLoc = ConsumeParen();
345
346  OwningExprResult AssertExpr(ParseConstantExpression());
347  if (AssertExpr.isInvalid()) {
348    SkipUntil(tok::semi);
349    return DeclPtrTy();
350  }
351
352  if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "", tok::semi))
353    return DeclPtrTy();
354
355  if (Tok.isNot(tok::string_literal)) {
356    Diag(Tok, diag::err_expected_string_literal);
357    SkipUntil(tok::semi);
358    return DeclPtrTy();
359  }
360
361  OwningExprResult AssertMessage(ParseStringLiteralExpression());
362  if (AssertMessage.isInvalid())
363    return DeclPtrTy();
364
365  MatchRHSPunctuation(tok::r_paren, LParenLoc);
366
367  DeclEnd = Tok.getLocation();
368  ExpectAndConsume(tok::semi, diag::err_expected_semi_after_static_assert);
369
370  return Actions.ActOnStaticAssertDeclaration(StaticAssertLoc, move(AssertExpr),
371                                              move(AssertMessage));
372}
373
374/// ParseDecltypeSpecifier - Parse a C++0x decltype specifier.
375///
376/// 'decltype' ( expression )
377///
378void Parser::ParseDecltypeSpecifier(DeclSpec &DS) {
379  assert(Tok.is(tok::kw_decltype) && "Not a decltype specifier");
380
381  SourceLocation StartLoc = ConsumeToken();
382  SourceLocation LParenLoc = Tok.getLocation();
383
384  if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
385                       "decltype")) {
386    SkipUntil(tok::r_paren);
387    return;
388  }
389
390  // Parse the expression
391
392  // C++0x [dcl.type.simple]p4:
393  //   The operand of the decltype specifier is an unevaluated operand.
394  EnterExpressionEvaluationContext Unevaluated(Actions,
395                                               Action::Unevaluated);
396  OwningExprResult Result = ParseExpression();
397  if (Result.isInvalid()) {
398    SkipUntil(tok::r_paren);
399    return;
400  }
401
402  // Match the ')'
403  SourceLocation RParenLoc;
404  if (Tok.is(tok::r_paren))
405    RParenLoc = ConsumeParen();
406  else
407    MatchRHSPunctuation(tok::r_paren, LParenLoc);
408
409  if (RParenLoc.isInvalid())
410    return;
411
412  const char *PrevSpec = 0;
413  unsigned DiagID;
414  // Check for duplicate type specifiers (e.g. "int decltype(a)").
415  if (DS.SetTypeSpecType(DeclSpec::TST_decltype, StartLoc, PrevSpec,
416                         DiagID, Result.release()))
417    Diag(StartLoc, DiagID) << PrevSpec;
418}
419
420/// ParseClassName - Parse a C++ class-name, which names a class. Note
421/// that we only check that the result names a type; semantic analysis
422/// will need to verify that the type names a class. The result is
423/// either a type or NULL, depending on whether a type name was
424/// found.
425///
426///       class-name: [C++ 9.1]
427///         identifier
428///         simple-template-id
429///
430Parser::TypeResult Parser::ParseClassName(SourceLocation &EndLocation,
431                                          const CXXScopeSpec *SS,
432                                          bool DestrExpected) {
433  // Check whether we have a template-id that names a type.
434  if (Tok.is(tok::annot_template_id)) {
435    TemplateIdAnnotation *TemplateId
436      = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
437    if (TemplateId->Kind == TNK_Type_template) {
438      AnnotateTemplateIdTokenAsType(SS);
439
440      assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
441      TypeTy *Type = Tok.getAnnotationValue();
442      EndLocation = Tok.getAnnotationEndLoc();
443      ConsumeToken();
444
445      if (Type)
446        return Type;
447      return true;
448    }
449
450    // Fall through to produce an error below.
451  }
452
453  if (Tok.isNot(tok::identifier)) {
454    Diag(Tok, diag::err_expected_class_name);
455    return true;
456  }
457
458  // We have an identifier; check whether it is actually a type.
459  TypeTy *Type = Actions.getTypeName(*Tok.getIdentifierInfo(),
460                                     Tok.getLocation(), CurScope, SS,
461                                     true);
462  if (!Type) {
463    Diag(Tok, DestrExpected ? diag::err_destructor_class_name
464                            : diag::err_expected_class_name);
465    return true;
466  }
467
468  // Consume the identifier.
469  EndLocation = ConsumeToken();
470  return Type;
471}
472
473/// ParseClassSpecifier - Parse a C++ class-specifier [C++ class] or
474/// elaborated-type-specifier [C++ dcl.type.elab]; we can't tell which
475/// until we reach the start of a definition or see a token that
476/// cannot start a definition.
477///
478///       class-specifier: [C++ class]
479///         class-head '{' member-specification[opt] '}'
480///         class-head '{' member-specification[opt] '}' attributes[opt]
481///       class-head:
482///         class-key identifier[opt] base-clause[opt]
483///         class-key nested-name-specifier identifier base-clause[opt]
484///         class-key nested-name-specifier[opt] simple-template-id
485///                          base-clause[opt]
486/// [GNU]   class-key attributes[opt] identifier[opt] base-clause[opt]
487/// [GNU]   class-key attributes[opt] nested-name-specifier
488///                          identifier base-clause[opt]
489/// [GNU]   class-key attributes[opt] nested-name-specifier[opt]
490///                          simple-template-id base-clause[opt]
491///       class-key:
492///         'class'
493///         'struct'
494///         'union'
495///
496///       elaborated-type-specifier: [C++ dcl.type.elab]
497///         class-key ::[opt] nested-name-specifier[opt] identifier
498///         class-key ::[opt] nested-name-specifier[opt] 'template'[opt]
499///                          simple-template-id
500///
501///  Note that the C++ class-specifier and elaborated-type-specifier,
502///  together, subsume the C99 struct-or-union-specifier:
503///
504///       struct-or-union-specifier: [C99 6.7.2.1]
505///         struct-or-union identifier[opt] '{' struct-contents '}'
506///         struct-or-union identifier
507/// [GNU]   struct-or-union attributes[opt] identifier[opt] '{' struct-contents
508///                                                         '}' attributes[opt]
509/// [GNU]   struct-or-union attributes[opt] identifier
510///       struct-or-union:
511///         'struct'
512///         'union'
513void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind,
514                                 SourceLocation StartLoc, DeclSpec &DS,
515                                 const ParsedTemplateInfo &TemplateInfo,
516                                 AccessSpecifier AS) {
517  DeclSpec::TST TagType;
518  if (TagTokKind == tok::kw_struct)
519    TagType = DeclSpec::TST_struct;
520  else if (TagTokKind == tok::kw_class)
521    TagType = DeclSpec::TST_class;
522  else {
523    assert(TagTokKind == tok::kw_union && "Not a class specifier");
524    TagType = DeclSpec::TST_union;
525  }
526
527  AttributeList *Attr = 0;
528  // If attributes exist after tag, parse them.
529  if (Tok.is(tok::kw___attribute))
530    Attr = ParseAttributes();
531
532  // If declspecs exist after tag, parse them.
533  if (Tok.is(tok::kw___declspec))
534    Attr = ParseMicrosoftDeclSpec(Attr);
535
536  // Parse the (optional) nested-name-specifier.
537  CXXScopeSpec SS;
538  if (getLang().CPlusPlus && ParseOptionalCXXScopeSpecifier(SS, true))
539    if (Tok.isNot(tok::identifier) && Tok.isNot(tok::annot_template_id))
540      Diag(Tok, diag::err_expected_ident);
541
542  // Parse the (optional) class name or simple-template-id.
543  IdentifierInfo *Name = 0;
544  SourceLocation NameLoc;
545  TemplateIdAnnotation *TemplateId = 0;
546  if (Tok.is(tok::identifier)) {
547    Name = Tok.getIdentifierInfo();
548    NameLoc = ConsumeToken();
549  } else if (Tok.is(tok::annot_template_id)) {
550    TemplateId = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
551    NameLoc = ConsumeToken();
552
553    if (TemplateId->Kind != TNK_Type_template) {
554      // The template-name in the simple-template-id refers to
555      // something other than a class template. Give an appropriate
556      // error message and skip to the ';'.
557      SourceRange Range(NameLoc);
558      if (SS.isNotEmpty())
559        Range.setBegin(SS.getBeginLoc());
560
561      Diag(TemplateId->LAngleLoc, diag::err_template_spec_syntax_non_template)
562        << Name << static_cast<int>(TemplateId->Kind) << Range;
563
564      DS.SetTypeSpecError();
565      SkipUntil(tok::semi, false, true);
566      TemplateId->Destroy();
567      return;
568    }
569  }
570
571  // There are four options here.  If we have 'struct foo;', then this
572  // is either a forward declaration or a friend declaration, which
573  // have to be treated differently.  If we have 'struct foo {...' or
574  // 'struct foo :...' then this is a definition. Otherwise we have
575  // something like 'struct foo xyz', a reference.
576  Action::TagUseKind TUK;
577  if (Tok.is(tok::l_brace) || (getLang().CPlusPlus && Tok.is(tok::colon)))
578    TUK = Action::TUK_Definition;
579  else if (Tok.is(tok::semi))
580    TUK = DS.isFriendSpecified() ? Action::TUK_Friend : Action::TUK_Declaration;
581  else
582    TUK = Action::TUK_Reference;
583
584  if (!Name && !TemplateId && TUK != Action::TUK_Definition) {
585    // We have a declaration or reference to an anonymous class.
586    Diag(StartLoc, diag::err_anon_type_definition)
587      << DeclSpec::getSpecifierName(TagType);
588
589    // Skip the rest of this declarator, up until the comma or semicolon.
590    SkipUntil(tok::comma, true);
591
592    if (TemplateId)
593      TemplateId->Destroy();
594    return;
595  }
596
597  // Create the tag portion of the class or class template.
598  Action::DeclResult TagOrTempResult;
599  TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
600
601  // FIXME: When TUK == TUK_Reference and we have a template-id, we need
602  // to turn that template-id into a type.
603
604  bool Owned = false;
605  if (TemplateId && TUK != Action::TUK_Reference && TUK != Action::TUK_Friend) {
606    // Explicit specialization, class template partial specialization,
607    // or explicit instantiation.
608    ASTTemplateArgsPtr TemplateArgsPtr(Actions,
609                                       TemplateId->getTemplateArgs(),
610                                       TemplateId->getTemplateArgIsType(),
611                                       TemplateId->NumArgs);
612    if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
613        TUK == Action::TUK_Declaration) {
614      // This is an explicit instantiation of a class template.
615      TagOrTempResult
616        = Actions.ActOnExplicitInstantiation(CurScope,
617                                             TemplateInfo.TemplateLoc,
618                                             TagType,
619                                             StartLoc,
620                                             SS,
621                                     TemplateTy::make(TemplateId->Template),
622                                             TemplateId->TemplateNameLoc,
623                                             TemplateId->LAngleLoc,
624                                             TemplateArgsPtr,
625                                      TemplateId->getTemplateArgLocations(),
626                                             TemplateId->RAngleLoc,
627                                             Attr);
628    } else {
629      // This is an explicit specialization or a class template
630      // partial specialization.
631      TemplateParameterLists FakedParamLists;
632
633      if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
634        // This looks like an explicit instantiation, because we have
635        // something like
636        //
637        //   template class Foo<X>
638        //
639        // but it actually has a definition. Most likely, this was
640        // meant to be an explicit specialization, but the user forgot
641        // the '<>' after 'template'.
642        assert(TUK == Action::TUK_Definition && "Expected a definition here");
643
644        SourceLocation LAngleLoc
645          = PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
646        Diag(TemplateId->TemplateNameLoc,
647             diag::err_explicit_instantiation_with_definition)
648          << SourceRange(TemplateInfo.TemplateLoc)
649          << CodeModificationHint::CreateInsertion(LAngleLoc, "<>");
650
651        // Create a fake template parameter list that contains only
652        // "template<>", so that we treat this construct as a class
653        // template specialization.
654        FakedParamLists.push_back(
655          Actions.ActOnTemplateParameterList(0, SourceLocation(),
656                                             TemplateInfo.TemplateLoc,
657                                             LAngleLoc,
658                                             0, 0,
659                                             LAngleLoc));
660        TemplateParams = &FakedParamLists;
661      }
662
663      // Build the class template specialization.
664      TagOrTempResult
665        = Actions.ActOnClassTemplateSpecialization(CurScope, TagType, TUK,
666                       StartLoc, SS,
667                       TemplateTy::make(TemplateId->Template),
668                       TemplateId->TemplateNameLoc,
669                       TemplateId->LAngleLoc,
670                       TemplateArgsPtr,
671                       TemplateId->getTemplateArgLocations(),
672                       TemplateId->RAngleLoc,
673                       Attr,
674                       Action::MultiTemplateParamsArg(Actions,
675                                    TemplateParams? &(*TemplateParams)[0] : 0,
676                                 TemplateParams? TemplateParams->size() : 0));
677    }
678    TemplateId->Destroy();
679  } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
680             TUK == Action::TUK_Declaration) {
681    // Explicit instantiation of a member of a class template
682    // specialization, e.g.,
683    //
684    //   template struct Outer<int>::Inner;
685    //
686    TagOrTempResult
687      = Actions.ActOnExplicitInstantiation(CurScope,
688                                           TemplateInfo.TemplateLoc,
689                                           TagType, StartLoc, SS, Name,
690                                           NameLoc, Attr);
691  } else {
692    if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
693        TUK == Action::TUK_Definition) {
694      // FIXME: Diagnose this particular error.
695    }
696
697    // Declaration or definition of a class type
698    TagOrTempResult = Actions.ActOnTag(CurScope, TagType, TUK, StartLoc, SS,
699                                       Name, NameLoc, Attr, AS,
700                                  Action::MultiTemplateParamsArg(Actions,
701                                    TemplateParams? &(*TemplateParams)[0] : 0,
702                                    TemplateParams? TemplateParams->size() : 0),
703                                       Owned);
704  }
705
706  // Parse the optional base clause (C++ only).
707  if (getLang().CPlusPlus && Tok.is(tok::colon))
708    ParseBaseClause(TagOrTempResult.get());
709
710  // If there is a body, parse it and inform the actions module.
711  if (Tok.is(tok::l_brace))
712    if (getLang().CPlusPlus)
713      ParseCXXMemberSpecification(StartLoc, TagType, TagOrTempResult.get());
714    else
715      ParseStructUnionBody(StartLoc, TagType, TagOrTempResult.get());
716  else if (TUK == Action::TUK_Definition) {
717    // FIXME: Complain that we have a base-specifier list but no
718    // definition.
719    Diag(Tok, diag::err_expected_lbrace);
720  }
721
722  if (TagOrTempResult.isInvalid()) {
723    DS.SetTypeSpecError();
724    return;
725  }
726
727  const char *PrevSpec = 0;
728  unsigned DiagID;
729  if (DS.SetTypeSpecType(TagType, StartLoc, PrevSpec, DiagID,
730                         TagOrTempResult.get().getAs<void>(), Owned))
731    Diag(StartLoc, DiagID) << PrevSpec;
732}
733
734/// ParseBaseClause - Parse the base-clause of a C++ class [C++ class.derived].
735///
736///       base-clause : [C++ class.derived]
737///         ':' base-specifier-list
738///       base-specifier-list:
739///         base-specifier '...'[opt]
740///         base-specifier-list ',' base-specifier '...'[opt]
741void Parser::ParseBaseClause(DeclPtrTy ClassDecl) {
742  assert(Tok.is(tok::colon) && "Not a base clause");
743  ConsumeToken();
744
745  // Build up an array of parsed base specifiers.
746  llvm::SmallVector<BaseTy *, 8> BaseInfo;
747
748  while (true) {
749    // Parse a base-specifier.
750    BaseResult Result = ParseBaseSpecifier(ClassDecl);
751    if (Result.isInvalid()) {
752      // Skip the rest of this base specifier, up until the comma or
753      // opening brace.
754      SkipUntil(tok::comma, tok::l_brace, true, true);
755    } else {
756      // Add this to our array of base specifiers.
757      BaseInfo.push_back(Result.get());
758    }
759
760    // If the next token is a comma, consume it and keep reading
761    // base-specifiers.
762    if (Tok.isNot(tok::comma)) break;
763
764    // Consume the comma.
765    ConsumeToken();
766  }
767
768  // Attach the base specifiers
769  Actions.ActOnBaseSpecifiers(ClassDecl, BaseInfo.data(), BaseInfo.size());
770}
771
772/// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is
773/// one entry in the base class list of a class specifier, for example:
774///    class foo : public bar, virtual private baz {
775/// 'public bar' and 'virtual private baz' are each base-specifiers.
776///
777///       base-specifier: [C++ class.derived]
778///         ::[opt] nested-name-specifier[opt] class-name
779///         'virtual' access-specifier[opt] ::[opt] nested-name-specifier[opt]
780///                        class-name
781///         access-specifier 'virtual'[opt] ::[opt] nested-name-specifier[opt]
782///                        class-name
783Parser::BaseResult Parser::ParseBaseSpecifier(DeclPtrTy ClassDecl) {
784  bool IsVirtual = false;
785  SourceLocation StartLoc = Tok.getLocation();
786
787  // Parse the 'virtual' keyword.
788  if (Tok.is(tok::kw_virtual))  {
789    ConsumeToken();
790    IsVirtual = true;
791  }
792
793  // Parse an (optional) access specifier.
794  AccessSpecifier Access = getAccessSpecifierIfPresent();
795  if (Access)
796    ConsumeToken();
797
798  // Parse the 'virtual' keyword (again!), in case it came after the
799  // access specifier.
800  if (Tok.is(tok::kw_virtual))  {
801    SourceLocation VirtualLoc = ConsumeToken();
802    if (IsVirtual) {
803      // Complain about duplicate 'virtual'
804      Diag(VirtualLoc, diag::err_dup_virtual)
805        << CodeModificationHint::CreateRemoval(SourceRange(VirtualLoc));
806    }
807
808    IsVirtual = true;
809  }
810
811  // Parse optional '::' and optional nested-name-specifier.
812  CXXScopeSpec SS;
813  ParseOptionalCXXScopeSpecifier(SS, true);
814
815  // The location of the base class itself.
816  SourceLocation BaseLoc = Tok.getLocation();
817
818  // Parse the class-name.
819  SourceLocation EndLocation;
820  TypeResult BaseType = ParseClassName(EndLocation, &SS);
821  if (BaseType.isInvalid())
822    return true;
823
824  // Find the complete source range for the base-specifier.
825  SourceRange Range(StartLoc, EndLocation);
826
827  // Notify semantic analysis that we have parsed a complete
828  // base-specifier.
829  return Actions.ActOnBaseSpecifier(ClassDecl, Range, IsVirtual, Access,
830                                    BaseType.get(), BaseLoc);
831}
832
833/// getAccessSpecifierIfPresent - Determine whether the next token is
834/// a C++ access-specifier.
835///
836///       access-specifier: [C++ class.derived]
837///         'private'
838///         'protected'
839///         'public'
840AccessSpecifier Parser::getAccessSpecifierIfPresent() const
841{
842  switch (Tok.getKind()) {
843  default: return AS_none;
844  case tok::kw_private: return AS_private;
845  case tok::kw_protected: return AS_protected;
846  case tok::kw_public: return AS_public;
847  }
848}
849
850void Parser::HandleMemberFunctionDefaultArgs(Declarator& DeclaratorInfo,
851                                             DeclPtrTy ThisDecl) {
852  // We just declared a member function. If this member function
853  // has any default arguments, we'll need to parse them later.
854  LateParsedMethodDeclaration *LateMethod = 0;
855  DeclaratorChunk::FunctionTypeInfo &FTI
856    = DeclaratorInfo.getTypeObject(0).Fun;
857  for (unsigned ParamIdx = 0; ParamIdx < FTI.NumArgs; ++ParamIdx) {
858    if (LateMethod || FTI.ArgInfo[ParamIdx].DefaultArgTokens) {
859      if (!LateMethod) {
860        // Push this method onto the stack of late-parsed method
861        // declarations.
862        getCurrentClass().MethodDecls.push_back(
863                                LateParsedMethodDeclaration(ThisDecl));
864        LateMethod = &getCurrentClass().MethodDecls.back();
865        LateMethod->TemplateScope = CurScope->isTemplateParamScope();
866
867        // Add all of the parameters prior to this one (they don't
868        // have default arguments).
869        LateMethod->DefaultArgs.reserve(FTI.NumArgs);
870        for (unsigned I = 0; I < ParamIdx; ++I)
871          LateMethod->DefaultArgs.push_back(
872                    LateParsedDefaultArgument(FTI.ArgInfo[ParamIdx].Param));
873      }
874
875      // Add this parameter to the list of parameters (it or may
876      // not have a default argument).
877      LateMethod->DefaultArgs.push_back(
878        LateParsedDefaultArgument(FTI.ArgInfo[ParamIdx].Param,
879                                  FTI.ArgInfo[ParamIdx].DefaultArgTokens));
880    }
881  }
882}
883
884/// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration.
885///
886///       member-declaration:
887///         decl-specifier-seq[opt] member-declarator-list[opt] ';'
888///         function-definition ';'[opt]
889///         ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO]
890///         using-declaration                                            [TODO]
891/// [C++0x] static_assert-declaration
892///         template-declaration
893/// [GNU]   '__extension__' member-declaration
894///
895///       member-declarator-list:
896///         member-declarator
897///         member-declarator-list ',' member-declarator
898///
899///       member-declarator:
900///         declarator pure-specifier[opt]
901///         declarator constant-initializer[opt]
902///         identifier[opt] ':' constant-expression
903///
904///       pure-specifier:
905///         '= 0'
906///
907///       constant-initializer:
908///         '=' constant-expression
909///
910void Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS,
911                                       const ParsedTemplateInfo &TemplateInfo) {
912  // static_assert-declaration
913  if (Tok.is(tok::kw_static_assert)) {
914    // FIXME: Check for templates
915    SourceLocation DeclEnd;
916    ParseStaticAssertDeclaration(DeclEnd);
917    return;
918  }
919
920  if (Tok.is(tok::kw_template)) {
921    assert(!TemplateInfo.TemplateParams &&
922           "Nested template improperly parsed?");
923    SourceLocation DeclEnd;
924    ParseDeclarationStartingWithTemplate(Declarator::MemberContext, DeclEnd,
925                                         AS);
926    return;
927  }
928
929  // Handle:  member-declaration ::= '__extension__' member-declaration
930  if (Tok.is(tok::kw___extension__)) {
931    // __extension__ silences extension warnings in the subexpression.
932    ExtensionRAIIObject O(Diags);  // Use RAII to do this.
933    ConsumeToken();
934    return ParseCXXClassMemberDeclaration(AS, TemplateInfo);
935  }
936
937  if (Tok.is(tok::kw_using)) {
938    // FIXME: Check for template aliases
939
940    // Eat 'using'.
941    SourceLocation UsingLoc = ConsumeToken();
942
943    if (Tok.is(tok::kw_namespace)) {
944      Diag(UsingLoc, diag::err_using_namespace_in_class);
945      SkipUntil(tok::semi, true, true);
946    }
947    else {
948      SourceLocation DeclEnd;
949      // Otherwise, it must be using-declaration.
950      ParseUsingDeclaration(Declarator::MemberContext, UsingLoc, DeclEnd);
951    }
952    return;
953  }
954
955  SourceLocation DSStart = Tok.getLocation();
956  // decl-specifier-seq:
957  // Parse the common declaration-specifiers piece.
958  DeclSpec DS;
959  ParseDeclarationSpecifiers(DS, TemplateInfo, AS, DSC_class);
960
961  if (Tok.is(tok::semi)) {
962    ConsumeToken();
963
964    // FIXME: Friend templates?
965    if (DS.isFriendSpecified())
966      Actions.ActOnFriendDecl(CurScope, &DS, /*IsDefinition*/ false);
967    else
968      Actions.ParsedFreeStandingDeclSpec(CurScope, DS);
969
970    return;
971  }
972
973  Declarator DeclaratorInfo(DS, Declarator::MemberContext);
974
975  if (Tok.isNot(tok::colon)) {
976    // Parse the first declarator.
977    ParseDeclarator(DeclaratorInfo);
978    // Error parsing the declarator?
979    if (!DeclaratorInfo.hasName()) {
980      // If so, skip until the semi-colon or a }.
981      SkipUntil(tok::r_brace, true);
982      if (Tok.is(tok::semi))
983        ConsumeToken();
984      return;
985    }
986
987    // function-definition:
988    if (Tok.is(tok::l_brace)
989        || (DeclaratorInfo.isFunctionDeclarator() &&
990            (Tok.is(tok::colon) || Tok.is(tok::kw_try)))) {
991      if (!DeclaratorInfo.isFunctionDeclarator()) {
992        Diag(Tok, diag::err_func_def_no_params);
993        ConsumeBrace();
994        SkipUntil(tok::r_brace, true);
995        return;
996      }
997
998      if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
999        Diag(Tok, diag::err_function_declared_typedef);
1000        // This recovery skips the entire function body. It would be nice
1001        // to simply call ParseCXXInlineMethodDef() below, however Sema
1002        // assumes the declarator represents a function, not a typedef.
1003        ConsumeBrace();
1004        SkipUntil(tok::r_brace, true);
1005        return;
1006      }
1007
1008      ParseCXXInlineMethodDef(AS, DeclaratorInfo, TemplateInfo);
1009      return;
1010    }
1011  }
1012
1013  // member-declarator-list:
1014  //   member-declarator
1015  //   member-declarator-list ',' member-declarator
1016
1017  llvm::SmallVector<DeclPtrTy, 8> DeclsInGroup;
1018  OwningExprResult BitfieldSize(Actions);
1019  OwningExprResult Init(Actions);
1020  bool Deleted = false;
1021
1022  while (1) {
1023
1024    // member-declarator:
1025    //   declarator pure-specifier[opt]
1026    //   declarator constant-initializer[opt]
1027    //   identifier[opt] ':' constant-expression
1028
1029    if (Tok.is(tok::colon)) {
1030      ConsumeToken();
1031      BitfieldSize = ParseConstantExpression();
1032      if (BitfieldSize.isInvalid())
1033        SkipUntil(tok::comma, true, true);
1034    }
1035
1036    // pure-specifier:
1037    //   '= 0'
1038    //
1039    // constant-initializer:
1040    //   '=' constant-expression
1041    //
1042    // defaulted/deleted function-definition:
1043    //   '=' 'default'                          [TODO]
1044    //   '=' 'delete'
1045
1046    if (Tok.is(tok::equal)) {
1047      ConsumeToken();
1048      if (getLang().CPlusPlus0x && Tok.is(tok::kw_delete)) {
1049        ConsumeToken();
1050        Deleted = true;
1051      } else {
1052        Init = ParseInitializer();
1053        if (Init.isInvalid())
1054          SkipUntil(tok::comma, true, true);
1055      }
1056    }
1057
1058    // If attributes exist after the declarator, parse them.
1059    if (Tok.is(tok::kw___attribute)) {
1060      SourceLocation Loc;
1061      AttributeList *AttrList = ParseAttributes(&Loc);
1062      DeclaratorInfo.AddAttributes(AttrList, Loc);
1063    }
1064
1065    // NOTE: If Sema is the Action module and declarator is an instance field,
1066    // this call will *not* return the created decl; It will return null.
1067    // See Sema::ActOnCXXMemberDeclarator for details.
1068
1069    DeclPtrTy ThisDecl;
1070    if (DS.isFriendSpecified()) {
1071      // TODO: handle initializers, bitfields, 'delete', friend templates
1072      ThisDecl = Actions.ActOnFriendDecl(CurScope, &DeclaratorInfo,
1073                                         /*IsDefinition*/ false);
1074    } else {
1075      Action::MultiTemplateParamsArg TemplateParams(Actions,
1076          TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->data() : 0,
1077          TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->size() : 0);
1078      ThisDecl = Actions.ActOnCXXMemberDeclarator(CurScope, AS,
1079                                                  DeclaratorInfo,
1080                                                  move(TemplateParams),
1081                                                  BitfieldSize.release(),
1082                                                  Init.release(),
1083                                                  Deleted);
1084    }
1085    if (ThisDecl)
1086      DeclsInGroup.push_back(ThisDecl);
1087
1088    if (DeclaratorInfo.isFunctionDeclarator() &&
1089        DeclaratorInfo.getDeclSpec().getStorageClassSpec()
1090          != DeclSpec::SCS_typedef) {
1091      HandleMemberFunctionDefaultArgs(DeclaratorInfo, ThisDecl);
1092    }
1093
1094    // If we don't have a comma, it is either the end of the list (a ';')
1095    // or an error, bail out.
1096    if (Tok.isNot(tok::comma))
1097      break;
1098
1099    // Consume the comma.
1100    ConsumeToken();
1101
1102    // Parse the next declarator.
1103    DeclaratorInfo.clear();
1104    BitfieldSize = 0;
1105    Init = 0;
1106    Deleted = false;
1107
1108    // Attributes are only allowed on the second declarator.
1109    if (Tok.is(tok::kw___attribute)) {
1110      SourceLocation Loc;
1111      AttributeList *AttrList = ParseAttributes(&Loc);
1112      DeclaratorInfo.AddAttributes(AttrList, Loc);
1113    }
1114
1115    if (Tok.isNot(tok::colon))
1116      ParseDeclarator(DeclaratorInfo);
1117  }
1118
1119  if (Tok.is(tok::semi)) {
1120    ConsumeToken();
1121    Actions.FinalizeDeclaratorGroup(CurScope, DS, DeclsInGroup.data(),
1122                                    DeclsInGroup.size());
1123    return;
1124  }
1125
1126  Diag(Tok, diag::err_expected_semi_decl_list);
1127  // Skip to end of block or statement
1128  SkipUntil(tok::r_brace, true, true);
1129  if (Tok.is(tok::semi))
1130    ConsumeToken();
1131  return;
1132}
1133
1134/// ParseCXXMemberSpecification - Parse the class definition.
1135///
1136///       member-specification:
1137///         member-declaration member-specification[opt]
1138///         access-specifier ':' member-specification[opt]
1139///
1140void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc,
1141                                         unsigned TagType, DeclPtrTy TagDecl) {
1142  assert((TagType == DeclSpec::TST_struct ||
1143         TagType == DeclSpec::TST_union  ||
1144         TagType == DeclSpec::TST_class) && "Invalid TagType!");
1145
1146  PrettyStackTraceActionsDecl CrashInfo(TagDecl, RecordLoc, Actions,
1147                                        PP.getSourceManager(),
1148                                        "parsing struct/union/class body");
1149
1150  SourceLocation LBraceLoc = ConsumeBrace();
1151
1152  // Determine whether this is a top-level (non-nested) class.
1153  bool TopLevelClass = ClassStack.empty() ||
1154    CurScope->isInCXXInlineMethodScope();
1155
1156  // Enter a scope for the class.
1157  ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
1158
1159  // Note that we are parsing a new (potentially-nested) class definition.
1160  ParsingClassDefinition ParsingDef(*this, TagDecl, TopLevelClass);
1161
1162  if (TagDecl)
1163    Actions.ActOnTagStartDefinition(CurScope, TagDecl);
1164  else {
1165    SkipUntil(tok::r_brace, false, false);
1166    return;
1167  }
1168
1169  // C++ 11p3: Members of a class defined with the keyword class are private
1170  // by default. Members of a class defined with the keywords struct or union
1171  // are public by default.
1172  AccessSpecifier CurAS;
1173  if (TagType == DeclSpec::TST_class)
1174    CurAS = AS_private;
1175  else
1176    CurAS = AS_public;
1177
1178  // While we still have something to read, read the member-declarations.
1179  while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
1180    // Each iteration of this loop reads one member-declaration.
1181
1182    // Check for extraneous top-level semicolon.
1183    if (Tok.is(tok::semi)) {
1184      Diag(Tok, diag::ext_extra_struct_semi);
1185      ConsumeToken();
1186      continue;
1187    }
1188
1189    AccessSpecifier AS = getAccessSpecifierIfPresent();
1190    if (AS != AS_none) {
1191      // Current token is a C++ access specifier.
1192      CurAS = AS;
1193      ConsumeToken();
1194      ExpectAndConsume(tok::colon, diag::err_expected_colon);
1195      continue;
1196    }
1197
1198    // FIXME: Make sure we don't have a template here.
1199
1200    // Parse all the comma separated declarators.
1201    ParseCXXClassMemberDeclaration(CurAS);
1202  }
1203
1204  SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc);
1205
1206  AttributeList *AttrList = 0;
1207  // If attributes exist after class contents, parse them.
1208  if (Tok.is(tok::kw___attribute))
1209    AttrList = ParseAttributes(); // FIXME: where should I put them?
1210
1211  Actions.ActOnFinishCXXMemberSpecification(CurScope, RecordLoc, TagDecl,
1212                                            LBraceLoc, RBraceLoc);
1213
1214  // C++ 9.2p2: Within the class member-specification, the class is regarded as
1215  // complete within function bodies, default arguments,
1216  // exception-specifications, and constructor ctor-initializers (including
1217  // such things in nested classes).
1218  //
1219  // FIXME: Only function bodies and constructor ctor-initializers are
1220  // parsed correctly, fix the rest.
1221  if (TopLevelClass) {
1222    // We are not inside a nested class. This class and its nested classes
1223    // are complete and we can parse the delayed portions of method
1224    // declarations and the lexed inline method definitions.
1225    ParseLexedMethodDeclarations(getCurrentClass());
1226    ParseLexedMethodDefs(getCurrentClass());
1227  }
1228
1229  // Leave the class scope.
1230  ParsingDef.Pop();
1231  ClassScope.Exit();
1232
1233  Actions.ActOnTagFinishDefinition(CurScope, TagDecl, RBraceLoc);
1234}
1235
1236/// ParseConstructorInitializer - Parse a C++ constructor initializer,
1237/// which explicitly initializes the members or base classes of a
1238/// class (C++ [class.base.init]). For example, the three initializers
1239/// after the ':' in the Derived constructor below:
1240///
1241/// @code
1242/// class Base { };
1243/// class Derived : Base {
1244///   int x;
1245///   float f;
1246/// public:
1247///   Derived(float f) : Base(), x(17), f(f) { }
1248/// };
1249/// @endcode
1250///
1251/// [C++]  ctor-initializer:
1252///          ':' mem-initializer-list
1253///
1254/// [C++]  mem-initializer-list:
1255///          mem-initializer
1256///          mem-initializer , mem-initializer-list
1257void Parser::ParseConstructorInitializer(DeclPtrTy ConstructorDecl) {
1258  assert(Tok.is(tok::colon) && "Constructor initializer always starts with ':'");
1259
1260  SourceLocation ColonLoc = ConsumeToken();
1261
1262  llvm::SmallVector<MemInitTy*, 4> MemInitializers;
1263
1264  do {
1265    MemInitResult MemInit = ParseMemInitializer(ConstructorDecl);
1266    if (!MemInit.isInvalid())
1267      MemInitializers.push_back(MemInit.get());
1268
1269    if (Tok.is(tok::comma))
1270      ConsumeToken();
1271    else if (Tok.is(tok::l_brace))
1272      break;
1273    else {
1274      // Skip over garbage, until we get to '{'.  Don't eat the '{'.
1275      Diag(Tok.getLocation(), diag::err_expected_lbrace_or_comma);
1276      SkipUntil(tok::l_brace, true, true);
1277      break;
1278    }
1279  } while (true);
1280
1281  Actions.ActOnMemInitializers(ConstructorDecl, ColonLoc,
1282                               MemInitializers.data(), MemInitializers.size());
1283}
1284
1285/// ParseMemInitializer - Parse a C++ member initializer, which is
1286/// part of a constructor initializer that explicitly initializes one
1287/// member or base class (C++ [class.base.init]). See
1288/// ParseConstructorInitializer for an example.
1289///
1290/// [C++] mem-initializer:
1291///         mem-initializer-id '(' expression-list[opt] ')'
1292///
1293/// [C++] mem-initializer-id:
1294///         '::'[opt] nested-name-specifier[opt] class-name
1295///         identifier
1296Parser::MemInitResult Parser::ParseMemInitializer(DeclPtrTy ConstructorDecl) {
1297  // parse '::'[opt] nested-name-specifier[opt]
1298  CXXScopeSpec SS;
1299  ParseOptionalCXXScopeSpecifier(SS);
1300  TypeTy *TemplateTypeTy = 0;
1301  if (Tok.is(tok::annot_template_id)) {
1302    TemplateIdAnnotation *TemplateId
1303      = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
1304    if (TemplateId->Kind == TNK_Type_template) {
1305      AnnotateTemplateIdTokenAsType(&SS);
1306      assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
1307      TemplateTypeTy = Tok.getAnnotationValue();
1308    }
1309    // FIXME. May need to check for TNK_Dependent_template as well.
1310  }
1311  if (!TemplateTypeTy && Tok.isNot(tok::identifier)) {
1312    Diag(Tok, diag::err_expected_member_or_base_name);
1313    return true;
1314  }
1315
1316  // Get the identifier. This may be a member name or a class name,
1317  // but we'll let the semantic analysis determine which it is.
1318  IdentifierInfo *II = Tok.is(tok::identifier) ? Tok.getIdentifierInfo() : 0;
1319  SourceLocation IdLoc = ConsumeToken();
1320
1321  // Parse the '('.
1322  if (Tok.isNot(tok::l_paren)) {
1323    Diag(Tok, diag::err_expected_lparen);
1324    return true;
1325  }
1326  SourceLocation LParenLoc = ConsumeParen();
1327
1328  // Parse the optional expression-list.
1329  ExprVector ArgExprs(Actions);
1330  CommaLocsTy CommaLocs;
1331  if (Tok.isNot(tok::r_paren) && ParseExpressionList(ArgExprs, CommaLocs)) {
1332    SkipUntil(tok::r_paren);
1333    return true;
1334  }
1335
1336  SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
1337
1338  return Actions.ActOnMemInitializer(ConstructorDecl, CurScope, SS, II,
1339                                     TemplateTypeTy, IdLoc,
1340                                     LParenLoc, ArgExprs.take(),
1341                                     ArgExprs.size(), CommaLocs.data(),
1342                                     RParenLoc);
1343}
1344
1345/// ParseExceptionSpecification - Parse a C++ exception-specification
1346/// (C++ [except.spec]).
1347///
1348///       exception-specification:
1349///         'throw' '(' type-id-list [opt] ')'
1350/// [MS]    'throw' '(' '...' ')'
1351///
1352///       type-id-list:
1353///         type-id
1354///         type-id-list ',' type-id
1355///
1356bool Parser::ParseExceptionSpecification(SourceLocation &EndLoc,
1357                                         llvm::SmallVector<TypeTy*, 2>
1358                                             &Exceptions,
1359                                         llvm::SmallVector<SourceRange, 2>
1360                                             &Ranges,
1361                                         bool &hasAnyExceptionSpec) {
1362  assert(Tok.is(tok::kw_throw) && "expected throw");
1363
1364  SourceLocation ThrowLoc = ConsumeToken();
1365
1366  if (!Tok.is(tok::l_paren)) {
1367    return Diag(Tok, diag::err_expected_lparen_after) << "throw";
1368  }
1369  SourceLocation LParenLoc = ConsumeParen();
1370
1371  // Parse throw(...), a Microsoft extension that means "this function
1372  // can throw anything".
1373  if (Tok.is(tok::ellipsis)) {
1374    hasAnyExceptionSpec = true;
1375    SourceLocation EllipsisLoc = ConsumeToken();
1376    if (!getLang().Microsoft)
1377      Diag(EllipsisLoc, diag::ext_ellipsis_exception_spec);
1378    EndLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
1379    return false;
1380  }
1381
1382  // Parse the sequence of type-ids.
1383  SourceRange Range;
1384  while (Tok.isNot(tok::r_paren)) {
1385    TypeResult Res(ParseTypeName(&Range));
1386    if (!Res.isInvalid()) {
1387      Exceptions.push_back(Res.get());
1388      Ranges.push_back(Range);
1389    }
1390    if (Tok.is(tok::comma))
1391      ConsumeToken();
1392    else
1393      break;
1394  }
1395
1396  EndLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
1397  return false;
1398}
1399
1400/// \brief We have just started parsing the definition of a new class,
1401/// so push that class onto our stack of classes that is currently
1402/// being parsed.
1403void Parser::PushParsingClass(DeclPtrTy ClassDecl, bool TopLevelClass) {
1404  assert((TopLevelClass || !ClassStack.empty()) &&
1405         "Nested class without outer class");
1406  ClassStack.push(new ParsingClass(ClassDecl, TopLevelClass));
1407}
1408
1409/// \brief Deallocate the given parsed class and all of its nested
1410/// classes.
1411void Parser::DeallocateParsedClasses(Parser::ParsingClass *Class) {
1412  for (unsigned I = 0, N = Class->NestedClasses.size(); I != N; ++I)
1413    DeallocateParsedClasses(Class->NestedClasses[I]);
1414  delete Class;
1415}
1416
1417/// \brief Pop the top class of the stack of classes that are
1418/// currently being parsed.
1419///
1420/// This routine should be called when we have finished parsing the
1421/// definition of a class, but have not yet popped the Scope
1422/// associated with the class's definition.
1423///
1424/// \returns true if the class we've popped is a top-level class,
1425/// false otherwise.
1426void Parser::PopParsingClass() {
1427  assert(!ClassStack.empty() && "Mismatched push/pop for class parsing");
1428
1429  ParsingClass *Victim = ClassStack.top();
1430  ClassStack.pop();
1431  if (Victim->TopLevelClass) {
1432    // Deallocate all of the nested classes of this class,
1433    // recursively: we don't need to keep any of this information.
1434    DeallocateParsedClasses(Victim);
1435    return;
1436  }
1437  assert(!ClassStack.empty() && "Missing top-level class?");
1438
1439  if (Victim->MethodDecls.empty() && Victim->MethodDefs.empty() &&
1440      Victim->NestedClasses.empty()) {
1441    // The victim is a nested class, but we will not need to perform
1442    // any processing after the definition of this class since it has
1443    // no members whose handling was delayed. Therefore, we can just
1444    // remove this nested class.
1445    delete Victim;
1446    return;
1447  }
1448
1449  // This nested class has some members that will need to be processed
1450  // after the top-level class is completely defined. Therefore, add
1451  // it to the list of nested classes within its parent.
1452  assert(CurScope->isClassScope() && "Nested class outside of class scope?");
1453  ClassStack.top()->NestedClasses.push_back(Victim);
1454  Victim->TemplateScope = CurScope->getParent()->isTemplateParamScope();
1455}
1456