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