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