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