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