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