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