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