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