ParseDeclCXX.cpp revision c9f351700721150a985f21844fbfec55b04e861d
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 "llvm/ADT/SmallString.h"
22#include "RAIIObjectsForParser.h"
23using namespace clang;
24
25/// ParseNamespace - We know that the current token is a namespace keyword. This
26/// may either be a top level namespace or a block-level namespace alias. If
27/// there was an inline keyword, it has already been parsed.
28///
29///       namespace-definition: [C++ 7.3: basic.namespace]
30///         named-namespace-definition
31///         unnamed-namespace-definition
32///
33///       unnamed-namespace-definition:
34///         'inline'[opt] 'namespace' attributes[opt] '{' namespace-body '}'
35///
36///       named-namespace-definition:
37///         original-namespace-definition
38///         extension-namespace-definition
39///
40///       original-namespace-definition:
41///         'inline'[opt] 'namespace' identifier attributes[opt]
42///             '{' namespace-body '}'
43///
44///       extension-namespace-definition:
45///         'inline'[opt] 'namespace' original-namespace-name
46///             '{' namespace-body '}'
47///
48///       namespace-alias-definition:  [C++ 7.3.2: namespace.alias]
49///         'namespace' identifier '=' qualified-namespace-specifier ';'
50///
51Decl *Parser::ParseNamespace(unsigned Context,
52                             SourceLocation &DeclEnd,
53                             SourceLocation InlineLoc) {
54  assert(Tok.is(tok::kw_namespace) && "Not a namespace!");
55  SourceLocation NamespaceLoc = ConsumeToken();  // eat the 'namespace'.
56  ObjCDeclContextSwitch ObjCDC(*this);
57
58  if (Tok.is(tok::code_completion)) {
59    Actions.CodeCompleteNamespaceDecl(getCurScope());
60    cutOffParsing();
61    return 0;
62  }
63
64  SourceLocation IdentLoc;
65  IdentifierInfo *Ident = 0;
66  std::vector<SourceLocation> ExtraIdentLoc;
67  std::vector<IdentifierInfo*> ExtraIdent;
68  std::vector<SourceLocation> ExtraNamespaceLoc;
69
70  Token attrTok;
71
72  if (Tok.is(tok::identifier)) {
73    Ident = Tok.getIdentifierInfo();
74    IdentLoc = ConsumeToken();  // eat the identifier.
75    while (Tok.is(tok::coloncolon) && NextToken().is(tok::identifier)) {
76      ExtraNamespaceLoc.push_back(ConsumeToken());
77      ExtraIdent.push_back(Tok.getIdentifierInfo());
78      ExtraIdentLoc.push_back(ConsumeToken());
79    }
80  }
81
82  // Read label attributes, if present.
83  ParsedAttributes attrs(AttrFactory);
84  if (Tok.is(tok::kw___attribute)) {
85    attrTok = Tok;
86    ParseGNUAttributes(attrs);
87  }
88
89  if (Tok.is(tok::equal)) {
90    if (!attrs.empty())
91      Diag(attrTok, diag::err_unexpected_namespace_attributes_alias);
92    if (InlineLoc.isValid())
93      Diag(InlineLoc, diag::err_inline_namespace_alias)
94          << FixItHint::CreateRemoval(InlineLoc);
95    return ParseNamespaceAlias(NamespaceLoc, IdentLoc, Ident, DeclEnd);
96  }
97
98
99  BalancedDelimiterTracker T(*this, tok::l_brace);
100  if (T.consumeOpen()) {
101    if (!ExtraIdent.empty()) {
102      Diag(ExtraNamespaceLoc[0], diag::err_nested_namespaces_with_double_colon)
103          << SourceRange(ExtraNamespaceLoc.front(), ExtraIdentLoc.back());
104    }
105    Diag(Tok, Ident ? diag::err_expected_lbrace :
106         diag::err_expected_ident_lbrace);
107    return 0;
108  }
109
110  if (getCurScope()->isClassScope() || getCurScope()->isTemplateParamScope() ||
111      getCurScope()->isInObjcMethodScope() || getCurScope()->getBlockParent() ||
112      getCurScope()->getFnParent()) {
113    if (!ExtraIdent.empty()) {
114      Diag(ExtraNamespaceLoc[0], diag::err_nested_namespaces_with_double_colon)
115          << SourceRange(ExtraNamespaceLoc.front(), ExtraIdentLoc.back());
116    }
117    Diag(T.getOpenLocation(), diag::err_namespace_nonnamespace_scope);
118    SkipUntil(tok::r_brace, false);
119    return 0;
120  }
121
122  if (!ExtraIdent.empty()) {
123    TentativeParsingAction TPA(*this);
124    SkipUntil(tok::r_brace, /*StopAtSemi*/false, /*DontConsume*/true);
125    Token rBraceToken = Tok;
126    TPA.Revert();
127
128    if (!rBraceToken.is(tok::r_brace)) {
129      Diag(ExtraNamespaceLoc[0], diag::err_nested_namespaces_with_double_colon)
130          << SourceRange(ExtraNamespaceLoc.front(), ExtraIdentLoc.back());
131    } else {
132      std::string NamespaceFix;
133      for (std::vector<IdentifierInfo*>::iterator I = ExtraIdent.begin(),
134           E = ExtraIdent.end(); I != E; ++I) {
135        NamespaceFix += " { namespace ";
136        NamespaceFix += (*I)->getName();
137      }
138
139      std::string RBraces;
140      for (unsigned i = 0, e = ExtraIdent.size(); i != e; ++i)
141        RBraces +=  "} ";
142
143      Diag(ExtraNamespaceLoc[0], diag::err_nested_namespaces_with_double_colon)
144          << FixItHint::CreateReplacement(SourceRange(ExtraNamespaceLoc.front(),
145                                                      ExtraIdentLoc.back()),
146                                          NamespaceFix)
147          << FixItHint::CreateInsertion(rBraceToken.getLocation(), RBraces);
148    }
149  }
150
151  // If we're still good, complain about inline namespaces in non-C++0x now.
152  if (InlineLoc.isValid())
153    Diag(InlineLoc, getLangOpts().CPlusPlus0x ?
154         diag::warn_cxx98_compat_inline_namespace : diag::ext_inline_namespace);
155
156  // Enter a scope for the namespace.
157  ParseScope NamespaceScope(this, Scope::DeclScope);
158
159  Decl *NamespcDecl =
160    Actions.ActOnStartNamespaceDef(getCurScope(), InlineLoc, NamespaceLoc,
161                                   IdentLoc, Ident, T.getOpenLocation(),
162                                   attrs.getList());
163
164  PrettyDeclStackTraceEntry CrashInfo(Actions, NamespcDecl, NamespaceLoc,
165                                      "parsing namespace");
166
167  // Parse the contents of the namespace.  This includes parsing recovery on
168  // any improperly nested namespaces.
169  ParseInnerNamespace(ExtraIdentLoc, ExtraIdent, ExtraNamespaceLoc, 0,
170                      InlineLoc, attrs, T);
171
172  // Leave the namespace scope.
173  NamespaceScope.Exit();
174
175  DeclEnd = T.getCloseLocation();
176  Actions.ActOnFinishNamespaceDef(NamespcDecl, DeclEnd);
177
178  return NamespcDecl;
179}
180
181/// ParseInnerNamespace - Parse the contents of a namespace.
182void Parser::ParseInnerNamespace(std::vector<SourceLocation>& IdentLoc,
183                                 std::vector<IdentifierInfo*>& Ident,
184                                 std::vector<SourceLocation>& NamespaceLoc,
185                                 unsigned int index, SourceLocation& InlineLoc,
186                                 ParsedAttributes& attrs,
187                                 BalancedDelimiterTracker &Tracker) {
188  if (index == Ident.size()) {
189    while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
190      ParsedAttributesWithRange attrs(AttrFactory);
191      MaybeParseCXX0XAttributes(attrs);
192      MaybeParseMicrosoftAttributes(attrs);
193      ParseExternalDeclaration(attrs);
194    }
195
196    // The caller is what called check -- we are simply calling
197    // the close for it.
198    Tracker.consumeClose();
199
200    return;
201  }
202
203  // Parse improperly nested namespaces.
204  ParseScope NamespaceScope(this, Scope::DeclScope);
205  Decl *NamespcDecl =
206    Actions.ActOnStartNamespaceDef(getCurScope(), SourceLocation(),
207                                   NamespaceLoc[index], IdentLoc[index],
208                                   Ident[index], Tracker.getOpenLocation(),
209                                   attrs.getList());
210
211  ParseInnerNamespace(IdentLoc, Ident, NamespaceLoc, ++index, InlineLoc,
212                      attrs, Tracker);
213
214  NamespaceScope.Exit();
215
216  Actions.ActOnFinishNamespaceDef(NamespcDecl, Tracker.getCloseLocation());
217}
218
219/// ParseNamespaceAlias - Parse the part after the '=' in a namespace
220/// alias definition.
221///
222Decl *Parser::ParseNamespaceAlias(SourceLocation NamespaceLoc,
223                                  SourceLocation AliasLoc,
224                                  IdentifierInfo *Alias,
225                                  SourceLocation &DeclEnd) {
226  assert(Tok.is(tok::equal) && "Not equal token");
227
228  ConsumeToken(); // eat the '='.
229
230  if (Tok.is(tok::code_completion)) {
231    Actions.CodeCompleteNamespaceAliasDecl(getCurScope());
232    cutOffParsing();
233    return 0;
234  }
235
236  CXXScopeSpec SS;
237  // Parse (optional) nested-name-specifier.
238  ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
239
240  if (SS.isInvalid() || Tok.isNot(tok::identifier)) {
241    Diag(Tok, diag::err_expected_namespace_name);
242    // Skip to end of the definition and eat the ';'.
243    SkipUntil(tok::semi);
244    return 0;
245  }
246
247  // Parse identifier.
248  IdentifierInfo *Ident = Tok.getIdentifierInfo();
249  SourceLocation IdentLoc = ConsumeToken();
250
251  // Eat the ';'.
252  DeclEnd = Tok.getLocation();
253  ExpectAndConsume(tok::semi, diag::err_expected_semi_after_namespace_name,
254                   "", tok::semi);
255
256  return Actions.ActOnNamespaceAliasDef(getCurScope(), NamespaceLoc, AliasLoc, Alias,
257                                        SS, IdentLoc, Ident);
258}
259
260/// ParseLinkage - We know that the current token is a string_literal
261/// and just before that, that extern was seen.
262///
263///       linkage-specification: [C++ 7.5p2: dcl.link]
264///         'extern' string-literal '{' declaration-seq[opt] '}'
265///         'extern' string-literal declaration
266///
267Decl *Parser::ParseLinkage(ParsingDeclSpec &DS, unsigned Context) {
268  assert(Tok.is(tok::string_literal) && "Not a string literal!");
269  SmallString<8> LangBuffer;
270  bool Invalid = false;
271  StringRef Lang = PP.getSpelling(Tok, LangBuffer, &Invalid);
272  if (Invalid)
273    return 0;
274
275  // FIXME: This is incorrect: linkage-specifiers are parsed in translation
276  // phase 7, so string-literal concatenation is supposed to occur.
277  //   extern "" "C" "" "+" "+" { } is legal.
278  if (Tok.hasUDSuffix())
279    Diag(Tok, diag::err_invalid_string_udl);
280  SourceLocation Loc = ConsumeStringToken();
281
282  ParseScope LinkageScope(this, Scope::DeclScope);
283  Decl *LinkageSpec
284    = Actions.ActOnStartLinkageSpecification(getCurScope(),
285                                             DS.getSourceRange().getBegin(),
286                                             Loc, Lang,
287                                      Tok.is(tok::l_brace) ? Tok.getLocation()
288                                                           : SourceLocation());
289
290  ParsedAttributesWithRange attrs(AttrFactory);
291  MaybeParseCXX0XAttributes(attrs);
292  MaybeParseMicrosoftAttributes(attrs);
293
294  if (Tok.isNot(tok::l_brace)) {
295    // Reset the source range in DS, as the leading "extern"
296    // does not really belong to the inner declaration ...
297    DS.SetRangeStart(SourceLocation());
298    DS.SetRangeEnd(SourceLocation());
299    // ... but anyway remember that such an "extern" was seen.
300    DS.setExternInLinkageSpec(true);
301    ParseExternalDeclaration(attrs, &DS);
302    return Actions.ActOnFinishLinkageSpecification(getCurScope(), LinkageSpec,
303                                                   SourceLocation());
304  }
305
306  DS.abort();
307
308  ProhibitAttributes(attrs);
309
310  BalancedDelimiterTracker T(*this, tok::l_brace);
311  T.consumeOpen();
312  while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
313    ParsedAttributesWithRange attrs(AttrFactory);
314    MaybeParseCXX0XAttributes(attrs);
315    MaybeParseMicrosoftAttributes(attrs);
316    ParseExternalDeclaration(attrs);
317  }
318
319  T.consumeClose();
320  return Actions.ActOnFinishLinkageSpecification(getCurScope(), LinkageSpec,
321                                                 T.getCloseLocation());
322}
323
324/// ParseUsingDirectiveOrDeclaration - Parse C++ using using-declaration or
325/// using-directive. Assumes that current token is 'using'.
326Decl *Parser::ParseUsingDirectiveOrDeclaration(unsigned Context,
327                                         const ParsedTemplateInfo &TemplateInfo,
328                                               SourceLocation &DeclEnd,
329                                             ParsedAttributesWithRange &attrs,
330                                               Decl **OwnedType) {
331  assert(Tok.is(tok::kw_using) && "Not using token");
332  ObjCDeclContextSwitch ObjCDC(*this);
333
334  // Eat 'using'.
335  SourceLocation UsingLoc = ConsumeToken();
336
337  if (Tok.is(tok::code_completion)) {
338    Actions.CodeCompleteUsing(getCurScope());
339    cutOffParsing();
340    return 0;
341  }
342
343  // 'using namespace' means this is a using-directive.
344  if (Tok.is(tok::kw_namespace)) {
345    // Template parameters are always an error here.
346    if (TemplateInfo.Kind) {
347      SourceRange R = TemplateInfo.getSourceRange();
348      Diag(UsingLoc, diag::err_templated_using_directive)
349        << R << FixItHint::CreateRemoval(R);
350    }
351
352    return ParseUsingDirective(Context, UsingLoc, DeclEnd, attrs);
353  }
354
355  // Otherwise, it must be a using-declaration or an alias-declaration.
356
357  // Using declarations can't have attributes.
358  ProhibitAttributes(attrs);
359
360  return ParseUsingDeclaration(Context, TemplateInfo, UsingLoc, DeclEnd,
361                                    AS_none, OwnedType);
362}
363
364/// ParseUsingDirective - Parse C++ using-directive, assumes
365/// that current token is 'namespace' and 'using' was already parsed.
366///
367///       using-directive: [C++ 7.3.p4: namespace.udir]
368///        'using' 'namespace' ::[opt] nested-name-specifier[opt]
369///                 namespace-name ;
370/// [GNU] using-directive:
371///        'using' 'namespace' ::[opt] nested-name-specifier[opt]
372///                 namespace-name attributes[opt] ;
373///
374Decl *Parser::ParseUsingDirective(unsigned Context,
375                                  SourceLocation UsingLoc,
376                                  SourceLocation &DeclEnd,
377                                  ParsedAttributes &attrs) {
378  assert(Tok.is(tok::kw_namespace) && "Not 'namespace' token");
379
380  // Eat 'namespace'.
381  SourceLocation NamespcLoc = ConsumeToken();
382
383  if (Tok.is(tok::code_completion)) {
384    Actions.CodeCompleteUsingDirective(getCurScope());
385    cutOffParsing();
386    return 0;
387  }
388
389  CXXScopeSpec SS;
390  // Parse (optional) nested-name-specifier.
391  ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
392
393  IdentifierInfo *NamespcName = 0;
394  SourceLocation IdentLoc = SourceLocation();
395
396  // Parse namespace-name.
397  if (SS.isInvalid() || Tok.isNot(tok::identifier)) {
398    Diag(Tok, diag::err_expected_namespace_name);
399    // If there was invalid namespace name, skip to end of decl, and eat ';'.
400    SkipUntil(tok::semi);
401    // FIXME: Are there cases, when we would like to call ActOnUsingDirective?
402    return 0;
403  }
404
405  // Parse identifier.
406  NamespcName = Tok.getIdentifierInfo();
407  IdentLoc = ConsumeToken();
408
409  // Parse (optional) attributes (most likely GNU strong-using extension).
410  bool GNUAttr = false;
411  if (Tok.is(tok::kw___attribute)) {
412    GNUAttr = true;
413    ParseGNUAttributes(attrs);
414  }
415
416  // Eat ';'.
417  DeclEnd = Tok.getLocation();
418  ExpectAndConsume(tok::semi,
419                   GNUAttr ? diag::err_expected_semi_after_attribute_list
420                           : diag::err_expected_semi_after_namespace_name,
421                   "", tok::semi);
422
423  return Actions.ActOnUsingDirective(getCurScope(), UsingLoc, NamespcLoc, SS,
424                                     IdentLoc, NamespcName, attrs.getList());
425}
426
427/// ParseUsingDeclaration - Parse C++ using-declaration or alias-declaration.
428/// Assumes that 'using' was already seen.
429///
430///     using-declaration: [C++ 7.3.p3: namespace.udecl]
431///       'using' 'typename'[opt] ::[opt] nested-name-specifier
432///               unqualified-id
433///       'using' :: unqualified-id
434///
435///     alias-declaration: C++0x [decl.typedef]p2
436///       'using' identifier = type-id ;
437///
438Decl *Parser::ParseUsingDeclaration(unsigned Context,
439                                    const ParsedTemplateInfo &TemplateInfo,
440                                    SourceLocation UsingLoc,
441                                    SourceLocation &DeclEnd,
442                                    AccessSpecifier AS,
443                                    Decl **OwnedType) {
444  CXXScopeSpec SS;
445  SourceLocation TypenameLoc;
446  bool IsTypeName;
447  ParsedAttributesWithRange attrs(AttrFactory);
448
449  // FIXME: Simply skip the attributes and diagnose, don't bother parsing them.
450  MaybeParseCXX0XAttributes(attrs);
451  ProhibitAttributes(attrs);
452  attrs.clear();
453  attrs.Range = SourceRange();
454
455  // Ignore optional 'typename'.
456  // FIXME: This is wrong; we should parse this as a typename-specifier.
457  if (Tok.is(tok::kw_typename)) {
458    TypenameLoc = Tok.getLocation();
459    ConsumeToken();
460    IsTypeName = true;
461  }
462  else
463    IsTypeName = false;
464
465  // Parse nested-name-specifier.
466  ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
467
468  // Check nested-name specifier.
469  if (SS.isInvalid()) {
470    SkipUntil(tok::semi);
471    return 0;
472  }
473
474  // Parse the unqualified-id. We allow parsing of both constructor and
475  // destructor names and allow the action module to diagnose any semantic
476  // errors.
477  SourceLocation TemplateKWLoc;
478  UnqualifiedId Name;
479  if (ParseUnqualifiedId(SS,
480                         /*EnteringContext=*/false,
481                         /*AllowDestructorName=*/true,
482                         /*AllowConstructorName=*/true,
483                         ParsedType(),
484                         TemplateKWLoc,
485                         Name)) {
486    SkipUntil(tok::semi);
487    return 0;
488  }
489
490  MaybeParseCXX0XAttributes(attrs);
491
492  // Maybe this is an alias-declaration.
493  bool IsAliasDecl = Tok.is(tok::equal);
494  TypeResult TypeAlias;
495  if (IsAliasDecl) {
496    // TODO: Attribute support. C++0x attributes may appear before the equals.
497    // Where can GNU attributes appear?
498    ConsumeToken();
499
500    Diag(Tok.getLocation(), getLangOpts().CPlusPlus0x ?
501         diag::warn_cxx98_compat_alias_declaration :
502         diag::ext_alias_declaration);
503
504    // Type alias templates cannot be specialized.
505    int SpecKind = -1;
506    if (TemplateInfo.Kind == ParsedTemplateInfo::Template &&
507        Name.getKind() == UnqualifiedId::IK_TemplateId)
508      SpecKind = 0;
509    if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization)
510      SpecKind = 1;
511    if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
512      SpecKind = 2;
513    if (SpecKind != -1) {
514      SourceRange Range;
515      if (SpecKind == 0)
516        Range = SourceRange(Name.TemplateId->LAngleLoc,
517                            Name.TemplateId->RAngleLoc);
518      else
519        Range = TemplateInfo.getSourceRange();
520      Diag(Range.getBegin(), diag::err_alias_declaration_specialization)
521        << SpecKind << Range;
522      SkipUntil(tok::semi);
523      return 0;
524    }
525
526    // Name must be an identifier.
527    if (Name.getKind() != UnqualifiedId::IK_Identifier) {
528      Diag(Name.StartLocation, diag::err_alias_declaration_not_identifier);
529      // No removal fixit: can't recover from this.
530      SkipUntil(tok::semi);
531      return 0;
532    } else if (IsTypeName)
533      Diag(TypenameLoc, diag::err_alias_declaration_not_identifier)
534        << FixItHint::CreateRemoval(SourceRange(TypenameLoc,
535                             SS.isNotEmpty() ? SS.getEndLoc() : TypenameLoc));
536    else if (SS.isNotEmpty())
537      Diag(SS.getBeginLoc(), diag::err_alias_declaration_not_identifier)
538        << FixItHint::CreateRemoval(SS.getRange());
539
540    TypeAlias = ParseTypeName(0, TemplateInfo.Kind ?
541                              Declarator::AliasTemplateContext :
542                              Declarator::AliasDeclContext, AS, OwnedType);
543  } else {
544    // C++11 attributes are not allowed on a using-declaration, but GNU ones
545    // are.
546    ProhibitAttributes(attrs);
547
548    // Parse (optional) attributes (most likely GNU strong-using extension).
549    MaybeParseGNUAttributes(attrs);
550  }
551
552  // Eat ';'.
553  DeclEnd = Tok.getLocation();
554  ExpectAndConsume(tok::semi, diag::err_expected_semi_after,
555                   !attrs.empty() ? "attributes list" :
556                   IsAliasDecl ? "alias declaration" : "using declaration",
557                   tok::semi);
558
559  // Diagnose an attempt to declare a templated using-declaration.
560  // In C++0x, alias-declarations can be templates:
561  //   template <...> using id = type;
562  if (TemplateInfo.Kind && !IsAliasDecl) {
563    SourceRange R = TemplateInfo.getSourceRange();
564    Diag(UsingLoc, diag::err_templated_using_declaration)
565      << R << FixItHint::CreateRemoval(R);
566
567    // Unfortunately, we have to bail out instead of recovering by
568    // ignoring the parameters, just in case the nested name specifier
569    // depends on the parameters.
570    return 0;
571  }
572
573  // "typename" keyword is allowed for identifiers only,
574  // because it may be a type definition.
575  if (IsTypeName && Name.getKind() != UnqualifiedId::IK_Identifier) {
576    Diag(Name.getSourceRange().getBegin(), diag::err_typename_identifiers_only)
577      << FixItHint::CreateRemoval(SourceRange(TypenameLoc));
578    // Proceed parsing, but reset the IsTypeName flag.
579    IsTypeName = false;
580  }
581
582  if (IsAliasDecl) {
583    TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
584    MultiTemplateParamsArg TemplateParamsArg(Actions,
585      TemplateParams ? TemplateParams->data() : 0,
586      TemplateParams ? TemplateParams->size() : 0);
587    // FIXME: Propagate attributes.
588    return Actions.ActOnAliasDeclaration(getCurScope(), AS, TemplateParamsArg,
589                                         UsingLoc, Name, TypeAlias);
590  }
591
592  return Actions.ActOnUsingDeclaration(getCurScope(), AS, true, UsingLoc, SS,
593                                       Name, attrs.getList(),
594                                       IsTypeName, TypenameLoc);
595}
596
597/// ParseStaticAssertDeclaration - Parse C++0x or C11 static_assert-declaration.
598///
599/// [C++0x] static_assert-declaration:
600///           static_assert ( constant-expression  ,  string-literal  ) ;
601///
602/// [C11]   static_assert-declaration:
603///           _Static_assert ( constant-expression  ,  string-literal  ) ;
604///
605Decl *Parser::ParseStaticAssertDeclaration(SourceLocation &DeclEnd){
606  assert((Tok.is(tok::kw_static_assert) || Tok.is(tok::kw__Static_assert)) &&
607         "Not a static_assert declaration");
608
609  if (Tok.is(tok::kw__Static_assert) && !getLangOpts().C11)
610    Diag(Tok, diag::ext_c11_static_assert);
611  if (Tok.is(tok::kw_static_assert))
612    Diag(Tok, diag::warn_cxx98_compat_static_assert);
613
614  SourceLocation StaticAssertLoc = ConsumeToken();
615
616  BalancedDelimiterTracker T(*this, tok::l_paren);
617  if (T.consumeOpen()) {
618    Diag(Tok, diag::err_expected_lparen);
619    return 0;
620  }
621
622  ExprResult AssertExpr(ParseConstantExpression());
623  if (AssertExpr.isInvalid()) {
624    SkipUntil(tok::semi);
625    return 0;
626  }
627
628  if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "", tok::semi))
629    return 0;
630
631  if (!isTokenStringLiteral()) {
632    Diag(Tok, diag::err_expected_string_literal);
633    SkipUntil(tok::semi);
634    return 0;
635  }
636
637  ExprResult AssertMessage(ParseStringLiteralExpression());
638  if (AssertMessage.isInvalid()) {
639    SkipUntil(tok::semi);
640    return 0;
641  }
642
643  T.consumeClose();
644
645  DeclEnd = Tok.getLocation();
646  ExpectAndConsumeSemi(diag::err_expected_semi_after_static_assert);
647
648  return Actions.ActOnStaticAssertDeclaration(StaticAssertLoc,
649                                              AssertExpr.take(),
650                                              AssertMessage.take(),
651                                              T.getCloseLocation());
652}
653
654/// ParseDecltypeSpecifier - Parse a C++0x decltype specifier.
655///
656/// 'decltype' ( expression )
657///
658SourceLocation Parser::ParseDecltypeSpecifier(DeclSpec &DS) {
659  assert((Tok.is(tok::kw_decltype) || Tok.is(tok::annot_decltype))
660           && "Not a decltype specifier");
661
662
663  ExprResult Result;
664  SourceLocation StartLoc = Tok.getLocation();
665  SourceLocation EndLoc;
666
667  if (Tok.is(tok::annot_decltype)) {
668    Result = getExprAnnotation(Tok);
669    EndLoc = Tok.getAnnotationEndLoc();
670    ConsumeToken();
671    if (Result.isInvalid()) {
672      DS.SetTypeSpecError();
673      return EndLoc;
674    }
675  } else {
676    if (Tok.getIdentifierInfo()->isStr("decltype"))
677      Diag(Tok, diag::warn_cxx98_compat_decltype);
678
679    ConsumeToken();
680
681    BalancedDelimiterTracker T(*this, tok::l_paren);
682    if (T.expectAndConsume(diag::err_expected_lparen_after,
683                           "decltype", tok::r_paren)) {
684      DS.SetTypeSpecError();
685      return T.getOpenLocation() == Tok.getLocation() ?
686             StartLoc : T.getOpenLocation();
687    }
688
689    // Parse the expression
690
691    // C++0x [dcl.type.simple]p4:
692    //   The operand of the decltype specifier is an unevaluated operand.
693    EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
694                                                 0, /*IsDecltype=*/true);
695    Result = ParseExpression();
696    if (Result.isInvalid()) {
697      SkipUntil(tok::r_paren);
698      DS.SetTypeSpecError();
699      return StartLoc;
700    }
701
702    // Match the ')'
703    T.consumeClose();
704    if (T.getCloseLocation().isInvalid()) {
705      DS.SetTypeSpecError();
706      // FIXME: this should return the location of the last token
707      //        that was consumed (by "consumeClose()")
708      return T.getCloseLocation();
709    }
710
711    Result = Actions.ActOnDecltypeExpression(Result.take());
712    if (Result.isInvalid()) {
713      DS.SetTypeSpecError();
714      return T.getCloseLocation();
715    }
716
717    EndLoc = T.getCloseLocation();
718  }
719
720  const char *PrevSpec = 0;
721  unsigned DiagID;
722  // Check for duplicate type specifiers (e.g. "int decltype(a)").
723  if (DS.SetTypeSpecType(DeclSpec::TST_decltype, StartLoc, PrevSpec,
724                         DiagID, Result.release())) {
725    Diag(StartLoc, DiagID) << PrevSpec;
726    DS.SetTypeSpecError();
727  }
728  return EndLoc;
729}
730
731void Parser::AnnotateExistingDecltypeSpecifier(const DeclSpec& DS,
732                                               SourceLocation StartLoc,
733                                               SourceLocation EndLoc) {
734  // make sure we have a token we can turn into an annotation token
735  if (PP.isBacktrackEnabled())
736    PP.RevertCachedTokens(1);
737  else
738    PP.EnterToken(Tok);
739
740  Tok.setKind(tok::annot_decltype);
741  setExprAnnotation(Tok, DS.getTypeSpecType() == TST_decltype ?
742                         DS.getRepAsExpr() : ExprResult());
743  Tok.setAnnotationEndLoc(EndLoc);
744  Tok.setLocation(StartLoc);
745  PP.AnnotateCachedTokens(Tok);
746}
747
748void Parser::ParseUnderlyingTypeSpecifier(DeclSpec &DS) {
749  assert(Tok.is(tok::kw___underlying_type) &&
750         "Not an underlying type specifier");
751
752  SourceLocation StartLoc = ConsumeToken();
753  BalancedDelimiterTracker T(*this, tok::l_paren);
754  if (T.expectAndConsume(diag::err_expected_lparen_after,
755                       "__underlying_type", tok::r_paren)) {
756    return;
757  }
758
759  TypeResult Result = ParseTypeName();
760  if (Result.isInvalid()) {
761    SkipUntil(tok::r_paren);
762    return;
763  }
764
765  // Match the ')'
766  T.consumeClose();
767  if (T.getCloseLocation().isInvalid())
768    return;
769
770  const char *PrevSpec = 0;
771  unsigned DiagID;
772  if (DS.SetTypeSpecType(DeclSpec::TST_underlyingType, StartLoc, PrevSpec,
773                         DiagID, Result.release()))
774    Diag(StartLoc, DiagID) << PrevSpec;
775}
776
777/// ParseBaseTypeSpecifier - Parse a C++ base-type-specifier which is either a
778/// class name or decltype-specifier. Note that we only check that the result
779/// names a type; semantic analysis will need to verify that the type names a
780/// class. The result is either a type or null, depending on whether a type
781/// name was found.
782///
783///       base-type-specifier: [C++ 10.1]
784///         class-or-decltype
785///       class-or-decltype: [C++ 10.1]
786///         nested-name-specifier[opt] class-name
787///         decltype-specifier
788///       class-name: [C++ 9.1]
789///         identifier
790///         simple-template-id
791///
792Parser::TypeResult Parser::ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
793                                                  SourceLocation &EndLocation) {
794  // Ignore attempts to use typename
795  if (Tok.is(tok::kw_typename)) {
796    Diag(Tok, diag::err_expected_class_name_not_template)
797      << FixItHint::CreateRemoval(Tok.getLocation());
798    ConsumeToken();
799  }
800
801  // Parse optional nested-name-specifier
802  CXXScopeSpec SS;
803  ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
804
805  BaseLoc = Tok.getLocation();
806
807  // Parse decltype-specifier
808  // tok == kw_decltype is just error recovery, it can only happen when SS
809  // isn't empty
810  if (Tok.is(tok::kw_decltype) || Tok.is(tok::annot_decltype)) {
811    if (SS.isNotEmpty())
812      Diag(SS.getBeginLoc(), diag::err_unexpected_scope_on_base_decltype)
813        << FixItHint::CreateRemoval(SS.getRange());
814    // Fake up a Declarator to use with ActOnTypeName.
815    DeclSpec DS(AttrFactory);
816
817    EndLocation = ParseDecltypeSpecifier(DS);
818
819    Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
820    return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
821  }
822
823  // Check whether we have a template-id that names a type.
824  if (Tok.is(tok::annot_template_id)) {
825    TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
826    if (TemplateId->Kind == TNK_Type_template ||
827        TemplateId->Kind == TNK_Dependent_template_name) {
828      AnnotateTemplateIdTokenAsType();
829
830      assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
831      ParsedType Type = getTypeAnnotation(Tok);
832      EndLocation = Tok.getAnnotationEndLoc();
833      ConsumeToken();
834
835      if (Type)
836        return Type;
837      return true;
838    }
839
840    // Fall through to produce an error below.
841  }
842
843  if (Tok.isNot(tok::identifier)) {
844    Diag(Tok, diag::err_expected_class_name);
845    return true;
846  }
847
848  IdentifierInfo *Id = Tok.getIdentifierInfo();
849  SourceLocation IdLoc = ConsumeToken();
850
851  if (Tok.is(tok::less)) {
852    // It looks the user intended to write a template-id here, but the
853    // template-name was wrong. Try to fix that.
854    TemplateNameKind TNK = TNK_Type_template;
855    TemplateTy Template;
856    if (!Actions.DiagnoseUnknownTemplateName(*Id, IdLoc, getCurScope(),
857                                             &SS, Template, TNK)) {
858      Diag(IdLoc, diag::err_unknown_template_name)
859        << Id;
860    }
861
862    if (!Template)
863      return true;
864
865    // Form the template name
866    UnqualifiedId TemplateName;
867    TemplateName.setIdentifier(Id, IdLoc);
868
869    // Parse the full template-id, then turn it into a type.
870    if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
871                                TemplateName, true))
872      return true;
873    if (TNK == TNK_Dependent_template_name)
874      AnnotateTemplateIdTokenAsType();
875
876    // If we didn't end up with a typename token, there's nothing more we
877    // can do.
878    if (Tok.isNot(tok::annot_typename))
879      return true;
880
881    // Retrieve the type from the annotation token, consume that token, and
882    // return.
883    EndLocation = Tok.getAnnotationEndLoc();
884    ParsedType Type = getTypeAnnotation(Tok);
885    ConsumeToken();
886    return Type;
887  }
888
889  // We have an identifier; check whether it is actually a type.
890  IdentifierInfo *CorrectedII = 0;
891  ParsedType Type = Actions.getTypeName(*Id, IdLoc, getCurScope(), &SS, true,
892                                        false, ParsedType(),
893                                        /*IsCtorOrDtorName=*/false,
894                                        /*NonTrivialTypeSourceInfo=*/true,
895                                        &CorrectedII);
896  if (!Type) {
897    Diag(IdLoc, diag::err_expected_class_name);
898    return true;
899  }
900
901  // Consume the identifier.
902  EndLocation = IdLoc;
903
904  // Fake up a Declarator to use with ActOnTypeName.
905  DeclSpec DS(AttrFactory);
906  DS.SetRangeStart(IdLoc);
907  DS.SetRangeEnd(EndLocation);
908  DS.getTypeSpecScope() = SS;
909
910  const char *PrevSpec = 0;
911  unsigned DiagID;
912  DS.SetTypeSpecType(TST_typename, IdLoc, PrevSpec, DiagID, Type);
913
914  Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
915  return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
916}
917
918void Parser::ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs) {
919  while (Tok.is(tok::kw___single_inheritance) ||
920         Tok.is(tok::kw___multiple_inheritance) ||
921         Tok.is(tok::kw___virtual_inheritance)) {
922    IdentifierInfo *AttrName = Tok.getIdentifierInfo();
923    SourceLocation AttrNameLoc = ConsumeToken();
924    attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0,
925                 SourceLocation(), 0, 0, AttributeList::AS_GNU);
926  }
927}
928
929/// Determine whether the following tokens are valid after a type-specifier
930/// which could be a standalone declaration. This will conservatively return
931/// true if there's any doubt, and is appropriate for insert-';' fixits.
932bool Parser::isValidAfterTypeSpecifier() {
933  // This switch enumerates the valid "follow" set for type-specifiers.
934  switch (Tok.getKind()) {
935  default: break;
936  case tok::semi:               // struct foo {...} ;
937  case tok::star:               // struct foo {...} *         P;
938  case tok::amp:                // struct foo {...} &         R = ...
939  case tok::identifier:         // struct foo {...} V         ;
940  case tok::r_paren:            //(struct foo {...} )         {4}
941  case tok::annot_cxxscope:     // struct foo {...} a::       b;
942  case tok::annot_typename:     // struct foo {...} a         ::b;
943  case tok::annot_template_id:  // struct foo {...} a<int>    ::b;
944  case tok::l_paren:            // struct foo {...} (         x);
945  case tok::comma:              // __builtin_offsetof(struct foo{...} ,
946    return true;
947  // Type qualifiers
948  case tok::kw_const:           // struct foo {...} const     x;
949  case tok::kw_volatile:        // struct foo {...} volatile  x;
950  case tok::kw_restrict:        // struct foo {...} restrict  x;
951  case tok::kw_inline:          // struct foo {...} inline    foo() {};
952  // Storage-class specifiers
953  case tok::kw_static:          // struct foo {...} static    x;
954  case tok::kw_extern:          // struct foo {...} extern    x;
955  case tok::kw_typedef:         // struct foo {...} typedef   x;
956  case tok::kw_register:        // struct foo {...} register  x;
957  case tok::kw_auto:            // struct foo {...} auto      x;
958  case tok::kw_mutable:         // struct foo {...} mutable   x;
959  case tok::kw_constexpr:       // struct foo {...} constexpr x;
960    // As shown above, type qualifiers and storage class specifiers absolutely
961    // can occur after class specifiers according to the grammar.  However,
962    // almost no one actually writes code like this.  If we see one of these,
963    // it is much more likely that someone missed a semi colon and the
964    // type/storage class specifier we're seeing is part of the *next*
965    // intended declaration, as in:
966    //
967    //   struct foo { ... }
968    //   typedef int X;
969    //
970    // We'd really like to emit a missing semicolon error instead of emitting
971    // an error on the 'int' saying that you can't have two type specifiers in
972    // the same declaration of X.  Because of this, we look ahead past this
973    // token to see if it's a type specifier.  If so, we know the code is
974    // otherwise invalid, so we can produce the expected semi error.
975    if (!isKnownToBeTypeSpecifier(NextToken()))
976      return true;
977    break;
978  case tok::r_brace:  // struct bar { struct foo {...} }
979    // Missing ';' at end of struct is accepted as an extension in C mode.
980    if (!getLangOpts().CPlusPlus)
981      return true;
982    break;
983  }
984  return false;
985}
986
987/// ParseClassSpecifier - Parse a C++ class-specifier [C++ class] or
988/// elaborated-type-specifier [C++ dcl.type.elab]; we can't tell which
989/// until we reach the start of a definition or see a token that
990/// cannot start a definition.
991///
992///       class-specifier: [C++ class]
993///         class-head '{' member-specification[opt] '}'
994///         class-head '{' member-specification[opt] '}' attributes[opt]
995///       class-head:
996///         class-key identifier[opt] base-clause[opt]
997///         class-key nested-name-specifier identifier base-clause[opt]
998///         class-key nested-name-specifier[opt] simple-template-id
999///                          base-clause[opt]
1000/// [GNU]   class-key attributes[opt] identifier[opt] base-clause[opt]
1001/// [GNU]   class-key attributes[opt] nested-name-specifier
1002///                          identifier base-clause[opt]
1003/// [GNU]   class-key attributes[opt] nested-name-specifier[opt]
1004///                          simple-template-id base-clause[opt]
1005///       class-key:
1006///         'class'
1007///         'struct'
1008///         'union'
1009///
1010///       elaborated-type-specifier: [C++ dcl.type.elab]
1011///         class-key ::[opt] nested-name-specifier[opt] identifier
1012///         class-key ::[opt] nested-name-specifier[opt] 'template'[opt]
1013///                          simple-template-id
1014///
1015///  Note that the C++ class-specifier and elaborated-type-specifier,
1016///  together, subsume the C99 struct-or-union-specifier:
1017///
1018///       struct-or-union-specifier: [C99 6.7.2.1]
1019///         struct-or-union identifier[opt] '{' struct-contents '}'
1020///         struct-or-union identifier
1021/// [GNU]   struct-or-union attributes[opt] identifier[opt] '{' struct-contents
1022///                                                         '}' attributes[opt]
1023/// [GNU]   struct-or-union attributes[opt] identifier
1024///       struct-or-union:
1025///         'struct'
1026///         'union'
1027void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind,
1028                                 SourceLocation StartLoc, DeclSpec &DS,
1029                                 const ParsedTemplateInfo &TemplateInfo,
1030                                 AccessSpecifier AS,
1031                                 bool EnteringContext, DeclSpecContext DSC) {
1032  DeclSpec::TST TagType;
1033  if (TagTokKind == tok::kw_struct)
1034    TagType = DeclSpec::TST_struct;
1035  else if (TagTokKind == tok::kw_class)
1036    TagType = DeclSpec::TST_class;
1037  else {
1038    assert(TagTokKind == tok::kw_union && "Not a class specifier");
1039    TagType = DeclSpec::TST_union;
1040  }
1041
1042  if (Tok.is(tok::code_completion)) {
1043    // Code completion for a struct, class, or union name.
1044    Actions.CodeCompleteTag(getCurScope(), TagType);
1045    return cutOffParsing();
1046  }
1047
1048  // C++03 [temp.explicit] 14.7.2/8:
1049  //   The usual access checking rules do not apply to names used to specify
1050  //   explicit instantiations.
1051  //
1052  // As an extension we do not perform access checking on the names used to
1053  // specify explicit specializations either. This is important to allow
1054  // specializing traits classes for private types.
1055  //
1056  // Note that we don't suppress if this turns out to be an elaborated
1057  // type specifier.
1058  bool shouldDelayDiagsInTag =
1059    (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
1060     TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
1061  SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
1062
1063  ParsedAttributesWithRange attrs(AttrFactory);
1064  // If attributes exist after tag, parse them.
1065  if (Tok.is(tok::kw___attribute))
1066    ParseGNUAttributes(attrs);
1067
1068  // If declspecs exist after tag, parse them.
1069  while (Tok.is(tok::kw___declspec))
1070    ParseMicrosoftDeclSpec(attrs);
1071
1072  // Parse inheritance specifiers.
1073  if (Tok.is(tok::kw___single_inheritance) ||
1074      Tok.is(tok::kw___multiple_inheritance) ||
1075      Tok.is(tok::kw___virtual_inheritance))
1076      ParseMicrosoftInheritanceClassAttributes(attrs);
1077
1078  // If C++0x attributes exist here, parse them.
1079  // FIXME: Are we consistent with the ordering of parsing of different
1080  // styles of attributes?
1081  MaybeParseCXX0XAttributes(attrs);
1082
1083  if (TagType == DeclSpec::TST_struct &&
1084      !Tok.is(tok::identifier) &&
1085      Tok.getIdentifierInfo() &&
1086      (Tok.is(tok::kw___is_arithmetic) ||
1087       Tok.is(tok::kw___is_convertible) ||
1088       Tok.is(tok::kw___is_empty) ||
1089       Tok.is(tok::kw___is_floating_point) ||
1090       Tok.is(tok::kw___is_function) ||
1091       Tok.is(tok::kw___is_fundamental) ||
1092       Tok.is(tok::kw___is_integral) ||
1093       Tok.is(tok::kw___is_member_function_pointer) ||
1094       Tok.is(tok::kw___is_member_pointer) ||
1095       Tok.is(tok::kw___is_pod) ||
1096       Tok.is(tok::kw___is_pointer) ||
1097       Tok.is(tok::kw___is_same) ||
1098       Tok.is(tok::kw___is_scalar) ||
1099       Tok.is(tok::kw___is_signed) ||
1100       Tok.is(tok::kw___is_unsigned) ||
1101       Tok.is(tok::kw___is_void))) {
1102    // GNU libstdc++ 4.2 and libc++ use certain intrinsic names as the
1103    // name of struct templates, but some are keywords in GCC >= 4.3
1104    // and Clang. Therefore, when we see the token sequence "struct
1105    // X", make X into a normal identifier rather than a keyword, to
1106    // allow libstdc++ 4.2 and libc++ to work properly.
1107    Tok.getIdentifierInfo()->RevertTokenIDToIdentifier();
1108    Tok.setKind(tok::identifier);
1109  }
1110
1111  // Parse the (optional) nested-name-specifier.
1112  CXXScopeSpec &SS = DS.getTypeSpecScope();
1113  if (getLangOpts().CPlusPlus) {
1114    // "FOO : BAR" is not a potential typo for "FOO::BAR".
1115    ColonProtectionRAIIObject X(*this);
1116
1117    if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext))
1118      DS.SetTypeSpecError();
1119    if (SS.isSet())
1120      if (Tok.isNot(tok::identifier) && Tok.isNot(tok::annot_template_id))
1121        Diag(Tok, diag::err_expected_ident);
1122  }
1123
1124  TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
1125
1126  // Parse the (optional) class name or simple-template-id.
1127  IdentifierInfo *Name = 0;
1128  SourceLocation NameLoc;
1129  TemplateIdAnnotation *TemplateId = 0;
1130  if (Tok.is(tok::identifier)) {
1131    Name = Tok.getIdentifierInfo();
1132    NameLoc = ConsumeToken();
1133
1134    if (Tok.is(tok::less) && getLangOpts().CPlusPlus) {
1135      // The name was supposed to refer to a template, but didn't.
1136      // Eat the template argument list and try to continue parsing this as
1137      // a class (or template thereof).
1138      TemplateArgList TemplateArgs;
1139      SourceLocation LAngleLoc, RAngleLoc;
1140      if (ParseTemplateIdAfterTemplateName(TemplateTy(), NameLoc, SS,
1141                                           true, LAngleLoc,
1142                                           TemplateArgs, RAngleLoc)) {
1143        // We couldn't parse the template argument list at all, so don't
1144        // try to give any location information for the list.
1145        LAngleLoc = RAngleLoc = SourceLocation();
1146      }
1147
1148      Diag(NameLoc, diag::err_explicit_spec_non_template)
1149        << (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
1150        << (TagType == DeclSpec::TST_class? 0
1151            : TagType == DeclSpec::TST_struct? 1
1152            : 2)
1153        << Name
1154        << SourceRange(LAngleLoc, RAngleLoc);
1155
1156      // Strip off the last template parameter list if it was empty, since
1157      // we've removed its template argument list.
1158      if (TemplateParams && TemplateInfo.LastParameterListWasEmpty) {
1159        if (TemplateParams && TemplateParams->size() > 1) {
1160          TemplateParams->pop_back();
1161        } else {
1162          TemplateParams = 0;
1163          const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind
1164            = ParsedTemplateInfo::NonTemplate;
1165        }
1166      } else if (TemplateInfo.Kind
1167                                == ParsedTemplateInfo::ExplicitInstantiation) {
1168        // Pretend this is just a forward declaration.
1169        TemplateParams = 0;
1170        const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind
1171          = ParsedTemplateInfo::NonTemplate;
1172        const_cast<ParsedTemplateInfo&>(TemplateInfo).TemplateLoc
1173          = SourceLocation();
1174        const_cast<ParsedTemplateInfo&>(TemplateInfo).ExternLoc
1175          = SourceLocation();
1176      }
1177    }
1178  } else if (Tok.is(tok::annot_template_id)) {
1179    TemplateId = takeTemplateIdAnnotation(Tok);
1180    NameLoc = ConsumeToken();
1181
1182    if (TemplateId->Kind != TNK_Type_template &&
1183        TemplateId->Kind != TNK_Dependent_template_name) {
1184      // The template-name in the simple-template-id refers to
1185      // something other than a class template. Give an appropriate
1186      // error message and skip to the ';'.
1187      SourceRange Range(NameLoc);
1188      if (SS.isNotEmpty())
1189        Range.setBegin(SS.getBeginLoc());
1190
1191      Diag(TemplateId->LAngleLoc, diag::err_template_spec_syntax_non_template)
1192        << Name << static_cast<int>(TemplateId->Kind) << Range;
1193
1194      DS.SetTypeSpecError();
1195      SkipUntil(tok::semi, false, true);
1196      return;
1197    }
1198  }
1199
1200  // There are four options here.
1201  //  - If we are in a trailing return type, this is always just a reference,
1202  //    and we must not try to parse a definition. For instance,
1203  //      [] () -> struct S { };
1204  //    does not define a type.
1205  //  - If we have 'struct foo {...', 'struct foo :...',
1206  //    'struct foo final :' or 'struct foo final {', then this is a definition.
1207  //  - If we have 'struct foo;', then this is either a forward declaration
1208  //    or a friend declaration, which have to be treated differently.
1209  //  - Otherwise we have something like 'struct foo xyz', a reference.
1210  // However, in type-specifier-seq's, things look like declarations but are
1211  // just references, e.g.
1212  //   new struct s;
1213  // or
1214  //   &T::operator struct s;
1215  // For these, DSC is DSC_type_specifier.
1216  Sema::TagUseKind TUK;
1217  if (DSC == DSC_trailing)
1218    TUK = Sema::TUK_Reference;
1219  else if (Tok.is(tok::l_brace) ||
1220           (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
1221           (isCXX0XFinalKeyword() &&
1222            (NextToken().is(tok::l_brace) || NextToken().is(tok::colon)))) {
1223    if (DS.isFriendSpecified()) {
1224      // C++ [class.friend]p2:
1225      //   A class shall not be defined in a friend declaration.
1226      Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
1227        << SourceRange(DS.getFriendSpecLoc());
1228
1229      // Skip everything up to the semicolon, so that this looks like a proper
1230      // friend class (or template thereof) declaration.
1231      SkipUntil(tok::semi, true, true);
1232      TUK = Sema::TUK_Friend;
1233    } else {
1234      // Okay, this is a class definition.
1235      TUK = Sema::TUK_Definition;
1236    }
1237  } else if (DSC != DSC_type_specifier &&
1238             (Tok.is(tok::semi) ||
1239              (Tok.isAtStartOfLine() && !isValidAfterTypeSpecifier()))) {
1240    TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
1241    if (Tok.isNot(tok::semi)) {
1242      // A semicolon was missing after this declaration. Diagnose and recover.
1243      ExpectAndConsume(tok::semi, diag::err_expected_semi_after_tagdecl,
1244                       TagType == DeclSpec::TST_class ? "class" :
1245                       TagType == DeclSpec::TST_struct ? "struct" : "union");
1246      PP.EnterToken(Tok);
1247      Tok.setKind(tok::semi);
1248    }
1249  } else
1250    TUK = Sema::TUK_Reference;
1251
1252  // If this is an elaborated type specifier, and we delayed
1253  // diagnostics before, just merge them into the current pool.
1254  if (shouldDelayDiagsInTag) {
1255    diagsFromTag.done();
1256    if (TUK == Sema::TUK_Reference)
1257      diagsFromTag.redelay();
1258  }
1259
1260  if (!Name && !TemplateId && (DS.getTypeSpecType() == DeclSpec::TST_error ||
1261                               TUK != Sema::TUK_Definition)) {
1262    if (DS.getTypeSpecType() != DeclSpec::TST_error) {
1263      // We have a declaration or reference to an anonymous class.
1264      Diag(StartLoc, diag::err_anon_type_definition)
1265        << DeclSpec::getSpecifierName(TagType);
1266    }
1267
1268    SkipUntil(tok::comma, true);
1269    return;
1270  }
1271
1272  // Create the tag portion of the class or class template.
1273  DeclResult TagOrTempResult = true; // invalid
1274  TypeResult TypeResult = true; // invalid
1275
1276  bool Owned = false;
1277  if (TemplateId) {
1278    // Explicit specialization, class template partial specialization,
1279    // or explicit instantiation.
1280    ASTTemplateArgsPtr TemplateArgsPtr(Actions,
1281                                       TemplateId->getTemplateArgs(),
1282                                       TemplateId->NumArgs);
1283    if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
1284        TUK == Sema::TUK_Declaration) {
1285      // This is an explicit instantiation of a class template.
1286      ProhibitAttributes(attrs);
1287
1288      TagOrTempResult
1289        = Actions.ActOnExplicitInstantiation(getCurScope(),
1290                                             TemplateInfo.ExternLoc,
1291                                             TemplateInfo.TemplateLoc,
1292                                             TagType,
1293                                             StartLoc,
1294                                             SS,
1295                                             TemplateId->Template,
1296                                             TemplateId->TemplateNameLoc,
1297                                             TemplateId->LAngleLoc,
1298                                             TemplateArgsPtr,
1299                                             TemplateId->RAngleLoc,
1300                                             attrs.getList());
1301
1302    // Friend template-ids are treated as references unless
1303    // they have template headers, in which case they're ill-formed
1304    // (FIXME: "template <class T> friend class A<T>::B<int>;").
1305    // We diagnose this error in ActOnClassTemplateSpecialization.
1306    } else if (TUK == Sema::TUK_Reference ||
1307               (TUK == Sema::TUK_Friend &&
1308                TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate)) {
1309      ProhibitAttributes(attrs);
1310      TypeResult = Actions.ActOnTagTemplateIdType(TUK, TagType, StartLoc,
1311                                                  TemplateId->SS,
1312                                                  TemplateId->TemplateKWLoc,
1313                                                  TemplateId->Template,
1314                                                  TemplateId->TemplateNameLoc,
1315                                                  TemplateId->LAngleLoc,
1316                                                  TemplateArgsPtr,
1317                                                  TemplateId->RAngleLoc);
1318    } else {
1319      // This is an explicit specialization or a class template
1320      // partial specialization.
1321      TemplateParameterLists FakedParamLists;
1322
1323      if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1324        // This looks like an explicit instantiation, because we have
1325        // something like
1326        //
1327        //   template class Foo<X>
1328        //
1329        // but it actually has a definition. Most likely, this was
1330        // meant to be an explicit specialization, but the user forgot
1331        // the '<>' after 'template'.
1332        assert(TUK == Sema::TUK_Definition && "Expected a definition here");
1333
1334        SourceLocation LAngleLoc
1335          = PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
1336        Diag(TemplateId->TemplateNameLoc,
1337             diag::err_explicit_instantiation_with_definition)
1338          << SourceRange(TemplateInfo.TemplateLoc)
1339          << FixItHint::CreateInsertion(LAngleLoc, "<>");
1340
1341        // Create a fake template parameter list that contains only
1342        // "template<>", so that we treat this construct as a class
1343        // template specialization.
1344        FakedParamLists.push_back(
1345          Actions.ActOnTemplateParameterList(0, SourceLocation(),
1346                                             TemplateInfo.TemplateLoc,
1347                                             LAngleLoc,
1348                                             0, 0,
1349                                             LAngleLoc));
1350        TemplateParams = &FakedParamLists;
1351      }
1352
1353      // Build the class template specialization.
1354      TagOrTempResult
1355        = Actions.ActOnClassTemplateSpecialization(getCurScope(), TagType, TUK,
1356                       StartLoc, DS.getModulePrivateSpecLoc(), SS,
1357                       TemplateId->Template,
1358                       TemplateId->TemplateNameLoc,
1359                       TemplateId->LAngleLoc,
1360                       TemplateArgsPtr,
1361                       TemplateId->RAngleLoc,
1362                       attrs.getList(),
1363                       MultiTemplateParamsArg(Actions,
1364                                    TemplateParams? &(*TemplateParams)[0] : 0,
1365                                 TemplateParams? TemplateParams->size() : 0));
1366    }
1367  } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
1368             TUK == Sema::TUK_Declaration) {
1369    // Explicit instantiation of a member of a class template
1370    // specialization, e.g.,
1371    //
1372    //   template struct Outer<int>::Inner;
1373    //
1374    ProhibitAttributes(attrs);
1375
1376    TagOrTempResult
1377      = Actions.ActOnExplicitInstantiation(getCurScope(),
1378                                           TemplateInfo.ExternLoc,
1379                                           TemplateInfo.TemplateLoc,
1380                                           TagType, StartLoc, SS, Name,
1381                                           NameLoc, attrs.getList());
1382  } else if (TUK == Sema::TUK_Friend &&
1383             TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate) {
1384    ProhibitAttributes(attrs);
1385
1386    TagOrTempResult =
1387      Actions.ActOnTemplatedFriendTag(getCurScope(), DS.getFriendSpecLoc(),
1388                                      TagType, StartLoc, SS,
1389                                      Name, NameLoc, attrs.getList(),
1390                                      MultiTemplateParamsArg(Actions,
1391                                    TemplateParams? &(*TemplateParams)[0] : 0,
1392                                 TemplateParams? TemplateParams->size() : 0));
1393  } else {
1394    if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
1395        TUK == Sema::TUK_Definition) {
1396      // FIXME: Diagnose this particular error.
1397    }
1398
1399    if (TUK != Sema::TUK_Declaration && TUK != Sema::TUK_Definition)
1400      ProhibitAttributes(attrs);
1401
1402    bool IsDependent = false;
1403
1404    // Don't pass down template parameter lists if this is just a tag
1405    // reference.  For example, we don't need the template parameters here:
1406    //   template <class T> class A *makeA(T t);
1407    MultiTemplateParamsArg TParams;
1408    if (TUK != Sema::TUK_Reference && TemplateParams)
1409      TParams =
1410        MultiTemplateParamsArg(&(*TemplateParams)[0], TemplateParams->size());
1411
1412    // Declaration or definition of a class type
1413    TagOrTempResult = Actions.ActOnTag(getCurScope(), TagType, TUK, StartLoc,
1414                                       SS, Name, NameLoc, attrs.getList(), AS,
1415                                       DS.getModulePrivateSpecLoc(),
1416                                       TParams, Owned, IsDependent,
1417                                       SourceLocation(), false,
1418                                       clang::TypeResult());
1419
1420    // If ActOnTag said the type was dependent, try again with the
1421    // less common call.
1422    if (IsDependent) {
1423      assert(TUK == Sema::TUK_Reference || TUK == Sema::TUK_Friend);
1424      TypeResult = Actions.ActOnDependentTag(getCurScope(), TagType, TUK,
1425                                             SS, Name, StartLoc, NameLoc);
1426    }
1427  }
1428
1429  // If there is a body, parse it and inform the actions module.
1430  if (TUK == Sema::TUK_Definition) {
1431    assert(Tok.is(tok::l_brace) ||
1432           (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
1433           isCXX0XFinalKeyword());
1434    if (getLangOpts().CPlusPlus)
1435      ParseCXXMemberSpecification(StartLoc, TagType, TagOrTempResult.get());
1436    else
1437      ParseStructUnionBody(StartLoc, TagType, TagOrTempResult.get());
1438  }
1439
1440  const char *PrevSpec = 0;
1441  unsigned DiagID;
1442  bool Result;
1443  if (!TypeResult.isInvalid()) {
1444    Result = DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
1445                                NameLoc.isValid() ? NameLoc : StartLoc,
1446                                PrevSpec, DiagID, TypeResult.get());
1447  } else if (!TagOrTempResult.isInvalid()) {
1448    Result = DS.SetTypeSpecType(TagType, StartLoc,
1449                                NameLoc.isValid() ? NameLoc : StartLoc,
1450                                PrevSpec, DiagID, TagOrTempResult.get(), Owned);
1451  } else {
1452    DS.SetTypeSpecError();
1453    return;
1454  }
1455
1456  if (Result)
1457    Diag(StartLoc, DiagID) << PrevSpec;
1458
1459  // At this point, we've successfully parsed a class-specifier in 'definition'
1460  // form (e.g. "struct foo { int x; }".  While we could just return here, we're
1461  // going to look at what comes after it to improve error recovery.  If an
1462  // impossible token occurs next, we assume that the programmer forgot a ; at
1463  // the end of the declaration and recover that way.
1464  //
1465  // Also enforce C++ [temp]p3:
1466  //   In a template-declaration which defines a class, no declarator
1467  //   is permitted.
1468  if (TUK == Sema::TUK_Definition &&
1469      (TemplateInfo.Kind || !isValidAfterTypeSpecifier())) {
1470    ExpectAndConsume(tok::semi, diag::err_expected_semi_after_tagdecl,
1471                     TagType == DeclSpec::TST_class ? "class" :
1472                     TagType == DeclSpec::TST_struct ? "struct" : "union");
1473    // Push this token back into the preprocessor and change our current token
1474    // to ';' so that the rest of the code recovers as though there were an
1475    // ';' after the definition.
1476    PP.EnterToken(Tok);
1477    Tok.setKind(tok::semi);
1478  }
1479}
1480
1481/// ParseBaseClause - Parse the base-clause of a C++ class [C++ class.derived].
1482///
1483///       base-clause : [C++ class.derived]
1484///         ':' base-specifier-list
1485///       base-specifier-list:
1486///         base-specifier '...'[opt]
1487///         base-specifier-list ',' base-specifier '...'[opt]
1488void Parser::ParseBaseClause(Decl *ClassDecl) {
1489  assert(Tok.is(tok::colon) && "Not a base clause");
1490  ConsumeToken();
1491
1492  // Build up an array of parsed base specifiers.
1493  SmallVector<CXXBaseSpecifier *, 8> BaseInfo;
1494
1495  while (true) {
1496    // Parse a base-specifier.
1497    BaseResult Result = ParseBaseSpecifier(ClassDecl);
1498    if (Result.isInvalid()) {
1499      // Skip the rest of this base specifier, up until the comma or
1500      // opening brace.
1501      SkipUntil(tok::comma, tok::l_brace, true, true);
1502    } else {
1503      // Add this to our array of base specifiers.
1504      BaseInfo.push_back(Result.get());
1505    }
1506
1507    // If the next token is a comma, consume it and keep reading
1508    // base-specifiers.
1509    if (Tok.isNot(tok::comma)) break;
1510
1511    // Consume the comma.
1512    ConsumeToken();
1513  }
1514
1515  // Attach the base specifiers
1516  Actions.ActOnBaseSpecifiers(ClassDecl, BaseInfo.data(), BaseInfo.size());
1517}
1518
1519/// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is
1520/// one entry in the base class list of a class specifier, for example:
1521///    class foo : public bar, virtual private baz {
1522/// 'public bar' and 'virtual private baz' are each base-specifiers.
1523///
1524///       base-specifier: [C++ class.derived]
1525///         ::[opt] nested-name-specifier[opt] class-name
1526///         'virtual' access-specifier[opt] ::[opt] nested-name-specifier[opt]
1527///                        base-type-specifier
1528///         access-specifier 'virtual'[opt] ::[opt] nested-name-specifier[opt]
1529///                        base-type-specifier
1530Parser::BaseResult Parser::ParseBaseSpecifier(Decl *ClassDecl) {
1531  bool IsVirtual = false;
1532  SourceLocation StartLoc = Tok.getLocation();
1533
1534  // Parse the 'virtual' keyword.
1535  if (Tok.is(tok::kw_virtual))  {
1536    ConsumeToken();
1537    IsVirtual = true;
1538  }
1539
1540  // Parse an (optional) access specifier.
1541  AccessSpecifier Access = getAccessSpecifierIfPresent();
1542  if (Access != AS_none)
1543    ConsumeToken();
1544
1545  // Parse the 'virtual' keyword (again!), in case it came after the
1546  // access specifier.
1547  if (Tok.is(tok::kw_virtual))  {
1548    SourceLocation VirtualLoc = ConsumeToken();
1549    if (IsVirtual) {
1550      // Complain about duplicate 'virtual'
1551      Diag(VirtualLoc, diag::err_dup_virtual)
1552        << FixItHint::CreateRemoval(VirtualLoc);
1553    }
1554
1555    IsVirtual = true;
1556  }
1557
1558  // Parse the class-name.
1559  SourceLocation EndLocation;
1560  SourceLocation BaseLoc;
1561  TypeResult BaseType = ParseBaseTypeSpecifier(BaseLoc, EndLocation);
1562  if (BaseType.isInvalid())
1563    return true;
1564
1565  // Parse the optional ellipsis (for a pack expansion). The ellipsis is
1566  // actually part of the base-specifier-list grammar productions, but we
1567  // parse it here for convenience.
1568  SourceLocation EllipsisLoc;
1569  if (Tok.is(tok::ellipsis))
1570    EllipsisLoc = ConsumeToken();
1571
1572  // Find the complete source range for the base-specifier.
1573  SourceRange Range(StartLoc, EndLocation);
1574
1575  // Notify semantic analysis that we have parsed a complete
1576  // base-specifier.
1577  return Actions.ActOnBaseSpecifier(ClassDecl, Range, IsVirtual, Access,
1578                                    BaseType.get(), BaseLoc, EllipsisLoc);
1579}
1580
1581/// getAccessSpecifierIfPresent - Determine whether the next token is
1582/// a C++ access-specifier.
1583///
1584///       access-specifier: [C++ class.derived]
1585///         'private'
1586///         'protected'
1587///         'public'
1588AccessSpecifier Parser::getAccessSpecifierIfPresent() const {
1589  switch (Tok.getKind()) {
1590  default: return AS_none;
1591  case tok::kw_private: return AS_private;
1592  case tok::kw_protected: return AS_protected;
1593  case tok::kw_public: return AS_public;
1594  }
1595}
1596
1597/// \brief If the given declarator has any parts for which parsing has to be
1598/// delayed, e.g., default arguments, create a late-parsed method declaration
1599/// record to handle the parsing at the end of the class definition.
1600void Parser::HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
1601                                            Decl *ThisDecl) {
1602  // We just declared a member function. If this member function
1603  // has any default arguments, we'll need to parse them later.
1604  LateParsedMethodDeclaration *LateMethod = 0;
1605  DeclaratorChunk::FunctionTypeInfo &FTI
1606    = DeclaratorInfo.getFunctionTypeInfo();
1607
1608  for (unsigned ParamIdx = 0; ParamIdx < FTI.NumArgs; ++ParamIdx) {
1609    if (LateMethod || FTI.ArgInfo[ParamIdx].DefaultArgTokens) {
1610      if (!LateMethod) {
1611        // Push this method onto the stack of late-parsed method
1612        // declarations.
1613        LateMethod = new LateParsedMethodDeclaration(this, ThisDecl);
1614        getCurrentClass().LateParsedDeclarations.push_back(LateMethod);
1615        LateMethod->TemplateScope = getCurScope()->isTemplateParamScope();
1616
1617        // Add all of the parameters prior to this one (they don't
1618        // have default arguments).
1619        LateMethod->DefaultArgs.reserve(FTI.NumArgs);
1620        for (unsigned I = 0; I < ParamIdx; ++I)
1621          LateMethod->DefaultArgs.push_back(
1622                             LateParsedDefaultArgument(FTI.ArgInfo[I].Param));
1623      }
1624
1625      // Add this parameter to the list of parameters (it may or may
1626      // not have a default argument).
1627      LateMethod->DefaultArgs.push_back(
1628        LateParsedDefaultArgument(FTI.ArgInfo[ParamIdx].Param,
1629                                  FTI.ArgInfo[ParamIdx].DefaultArgTokens));
1630    }
1631  }
1632}
1633
1634/// isCXX0XVirtSpecifier - Determine whether the given token is a C++0x
1635/// virt-specifier.
1636///
1637///       virt-specifier:
1638///         override
1639///         final
1640VirtSpecifiers::Specifier Parser::isCXX0XVirtSpecifier(const Token &Tok) const {
1641  if (!getLangOpts().CPlusPlus)
1642    return VirtSpecifiers::VS_None;
1643
1644  if (Tok.is(tok::identifier)) {
1645    IdentifierInfo *II = Tok.getIdentifierInfo();
1646
1647    // Initialize the contextual keywords.
1648    if (!Ident_final) {
1649      Ident_final = &PP.getIdentifierTable().get("final");
1650      Ident_override = &PP.getIdentifierTable().get("override");
1651    }
1652
1653    if (II == Ident_override)
1654      return VirtSpecifiers::VS_Override;
1655
1656    if (II == Ident_final)
1657      return VirtSpecifiers::VS_Final;
1658  }
1659
1660  return VirtSpecifiers::VS_None;
1661}
1662
1663/// ParseOptionalCXX0XVirtSpecifierSeq - Parse a virt-specifier-seq.
1664///
1665///       virt-specifier-seq:
1666///         virt-specifier
1667///         virt-specifier-seq virt-specifier
1668void Parser::ParseOptionalCXX0XVirtSpecifierSeq(VirtSpecifiers &VS) {
1669  while (true) {
1670    VirtSpecifiers::Specifier Specifier = isCXX0XVirtSpecifier();
1671    if (Specifier == VirtSpecifiers::VS_None)
1672      return;
1673
1674    // C++ [class.mem]p8:
1675    //   A virt-specifier-seq shall contain at most one of each virt-specifier.
1676    const char *PrevSpec = 0;
1677    if (VS.SetSpecifier(Specifier, Tok.getLocation(), PrevSpec))
1678      Diag(Tok.getLocation(), diag::err_duplicate_virt_specifier)
1679        << PrevSpec
1680        << FixItHint::CreateRemoval(Tok.getLocation());
1681
1682    Diag(Tok.getLocation(), getLangOpts().CPlusPlus0x ?
1683         diag::warn_cxx98_compat_override_control_keyword :
1684         diag::ext_override_control_keyword)
1685      << VirtSpecifiers::getSpecifierName(Specifier);
1686    ConsumeToken();
1687  }
1688}
1689
1690/// isCXX0XFinalKeyword - Determine whether the next token is a C++0x
1691/// contextual 'final' keyword.
1692bool Parser::isCXX0XFinalKeyword() const {
1693  if (!getLangOpts().CPlusPlus)
1694    return false;
1695
1696  if (!Tok.is(tok::identifier))
1697    return false;
1698
1699  // Initialize the contextual keywords.
1700  if (!Ident_final) {
1701    Ident_final = &PP.getIdentifierTable().get("final");
1702    Ident_override = &PP.getIdentifierTable().get("override");
1703  }
1704
1705  return Tok.getIdentifierInfo() == Ident_final;
1706}
1707
1708/// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration.
1709///
1710///       member-declaration:
1711///         decl-specifier-seq[opt] member-declarator-list[opt] ';'
1712///         function-definition ';'[opt]
1713///         ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO]
1714///         using-declaration                                            [TODO]
1715/// [C++0x] static_assert-declaration
1716///         template-declaration
1717/// [GNU]   '__extension__' member-declaration
1718///
1719///       member-declarator-list:
1720///         member-declarator
1721///         member-declarator-list ',' member-declarator
1722///
1723///       member-declarator:
1724///         declarator virt-specifier-seq[opt] pure-specifier[opt]
1725///         declarator constant-initializer[opt]
1726/// [C++11] declarator brace-or-equal-initializer[opt]
1727///         identifier[opt] ':' constant-expression
1728///
1729///       virt-specifier-seq:
1730///         virt-specifier
1731///         virt-specifier-seq virt-specifier
1732///
1733///       virt-specifier:
1734///         override
1735///         final
1736///
1737///       pure-specifier:
1738///         '= 0'
1739///
1740///       constant-initializer:
1741///         '=' constant-expression
1742///
1743void Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS,
1744                                            AttributeList *AccessAttrs,
1745                                       const ParsedTemplateInfo &TemplateInfo,
1746                                       ParsingDeclRAIIObject *TemplateDiags) {
1747  if (Tok.is(tok::at)) {
1748    if (getLangOpts().ObjC1 && NextToken().isObjCAtKeyword(tok::objc_defs))
1749      Diag(Tok, diag::err_at_defs_cxx);
1750    else
1751      Diag(Tok, diag::err_at_in_class);
1752
1753    ConsumeToken();
1754    SkipUntil(tok::r_brace);
1755    return;
1756  }
1757
1758  // Access declarations.
1759  bool MalformedTypeSpec = false;
1760  if (!TemplateInfo.Kind &&
1761      (Tok.is(tok::identifier) || Tok.is(tok::coloncolon))) {
1762    if (TryAnnotateCXXScopeToken())
1763      MalformedTypeSpec = true;
1764
1765    bool isAccessDecl;
1766    if (Tok.isNot(tok::annot_cxxscope))
1767      isAccessDecl = false;
1768    else if (NextToken().is(tok::identifier))
1769      isAccessDecl = GetLookAheadToken(2).is(tok::semi);
1770    else
1771      isAccessDecl = NextToken().is(tok::kw_operator);
1772
1773    if (isAccessDecl) {
1774      // Collect the scope specifier token we annotated earlier.
1775      CXXScopeSpec SS;
1776      ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
1777                                     /*EnteringContext=*/false);
1778
1779      // Try to parse an unqualified-id.
1780      SourceLocation TemplateKWLoc;
1781      UnqualifiedId Name;
1782      if (ParseUnqualifiedId(SS, false, true, true, ParsedType(),
1783                             TemplateKWLoc, Name)) {
1784        SkipUntil(tok::semi);
1785        return;
1786      }
1787
1788      // TODO: recover from mistakenly-qualified operator declarations.
1789      if (ExpectAndConsume(tok::semi,
1790                           diag::err_expected_semi_after,
1791                           "access declaration",
1792                           tok::semi))
1793        return;
1794
1795      Actions.ActOnUsingDeclaration(getCurScope(), AS,
1796                                    false, SourceLocation(),
1797                                    SS, Name,
1798                                    /* AttrList */ 0,
1799                                    /* IsTypeName */ false,
1800                                    SourceLocation());
1801      return;
1802    }
1803  }
1804
1805  // static_assert-declaration
1806  if (Tok.is(tok::kw_static_assert) || Tok.is(tok::kw__Static_assert)) {
1807    // FIXME: Check for templates
1808    SourceLocation DeclEnd;
1809    ParseStaticAssertDeclaration(DeclEnd);
1810    return;
1811  }
1812
1813  if (Tok.is(tok::kw_template)) {
1814    assert(!TemplateInfo.TemplateParams &&
1815           "Nested template improperly parsed?");
1816    SourceLocation DeclEnd;
1817    ParseDeclarationStartingWithTemplate(Declarator::MemberContext, DeclEnd,
1818                                         AS, AccessAttrs);
1819    return;
1820  }
1821
1822  // Handle:  member-declaration ::= '__extension__' member-declaration
1823  if (Tok.is(tok::kw___extension__)) {
1824    // __extension__ silences extension warnings in the subexpression.
1825    ExtensionRAIIObject O(Diags);  // Use RAII to do this.
1826    ConsumeToken();
1827    return ParseCXXClassMemberDeclaration(AS, AccessAttrs,
1828                                          TemplateInfo, TemplateDiags);
1829  }
1830
1831  // Don't parse FOO:BAR as if it were a typo for FOO::BAR, in this context it
1832  // is a bitfield.
1833  ColonProtectionRAIIObject X(*this);
1834
1835  ParsedAttributesWithRange attrs(AttrFactory);
1836  // Optional C++0x attribute-specifier
1837  MaybeParseCXX0XAttributes(attrs);
1838  MaybeParseMicrosoftAttributes(attrs);
1839
1840  if (Tok.is(tok::kw_using)) {
1841    ProhibitAttributes(attrs);
1842
1843    // Eat 'using'.
1844    SourceLocation UsingLoc = ConsumeToken();
1845
1846    if (Tok.is(tok::kw_namespace)) {
1847      Diag(UsingLoc, diag::err_using_namespace_in_class);
1848      SkipUntil(tok::semi, true, true);
1849    } else {
1850      SourceLocation DeclEnd;
1851      // Otherwise, it must be a using-declaration or an alias-declaration.
1852      ParseUsingDeclaration(Declarator::MemberContext, TemplateInfo,
1853                            UsingLoc, DeclEnd, AS);
1854    }
1855    return;
1856  }
1857
1858  // Hold late-parsed attributes so we can attach a Decl to them later.
1859  LateParsedAttrList CommonLateParsedAttrs;
1860
1861  // decl-specifier-seq:
1862  // Parse the common declaration-specifiers piece.
1863  ParsingDeclSpec DS(*this, TemplateDiags);
1864  DS.takeAttributesFrom(attrs);
1865  if (MalformedTypeSpec)
1866    DS.SetTypeSpecError();
1867  ParseDeclarationSpecifiers(DS, TemplateInfo, AS, DSC_class,
1868                             &CommonLateParsedAttrs);
1869
1870  MultiTemplateParamsArg TemplateParams(Actions,
1871      TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->data() : 0,
1872      TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->size() : 0);
1873
1874  if (Tok.is(tok::semi)) {
1875    ConsumeToken();
1876    Decl *TheDecl =
1877      Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS, DS, TemplateParams);
1878    DS.complete(TheDecl);
1879    return;
1880  }
1881
1882  ParsingDeclarator DeclaratorInfo(*this, DS, Declarator::MemberContext);
1883  VirtSpecifiers VS;
1884
1885  // Hold late-parsed attributes so we can attach a Decl to them later.
1886  LateParsedAttrList LateParsedAttrs;
1887
1888  SourceLocation EqualLoc;
1889  bool HasInitializer = false;
1890  ExprResult Init;
1891  if (Tok.isNot(tok::colon)) {
1892    // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
1893    ColonProtectionRAIIObject X(*this);
1894
1895    // Parse the first declarator.
1896    ParseDeclarator(DeclaratorInfo);
1897    // Error parsing the declarator?
1898    if (!DeclaratorInfo.hasName()) {
1899      // If so, skip until the semi-colon or a }.
1900      SkipUntil(tok::r_brace, true, true);
1901      if (Tok.is(tok::semi))
1902        ConsumeToken();
1903      return;
1904    }
1905
1906    ParseOptionalCXX0XVirtSpecifierSeq(VS);
1907
1908    // If attributes exist after the declarator, but before an '{', parse them.
1909    MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
1910
1911    // MSVC permits pure specifier on inline functions declared at class scope.
1912    // Hence check for =0 before checking for function definition.
1913    if (getLangOpts().MicrosoftExt && Tok.is(tok::equal) &&
1914        DeclaratorInfo.isFunctionDeclarator() &&
1915        NextToken().is(tok::numeric_constant)) {
1916      EqualLoc = ConsumeToken();
1917      Init = ParseInitializer();
1918      if (Init.isInvalid())
1919        SkipUntil(tok::comma, true, true);
1920      else
1921        HasInitializer = true;
1922    }
1923
1924    FunctionDefinitionKind DefinitionKind = FDK_Declaration;
1925    // function-definition:
1926    //
1927    // In C++11, a non-function declarator followed by an open brace is a
1928    // braced-init-list for an in-class member initialization, not an
1929    // erroneous function definition.
1930    if (Tok.is(tok::l_brace) && !getLangOpts().CPlusPlus0x) {
1931      DefinitionKind = FDK_Definition;
1932    } else if (DeclaratorInfo.isFunctionDeclarator()) {
1933      if (Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try)) {
1934        DefinitionKind = FDK_Definition;
1935      } else if (Tok.is(tok::equal)) {
1936        const Token &KW = NextToken();
1937        if (KW.is(tok::kw_default))
1938          DefinitionKind = FDK_Defaulted;
1939        else if (KW.is(tok::kw_delete))
1940          DefinitionKind = FDK_Deleted;
1941      }
1942    }
1943
1944    if (DefinitionKind) {
1945      if (!DeclaratorInfo.isFunctionDeclarator()) {
1946        Diag(DeclaratorInfo.getIdentifierLoc(), diag::err_func_def_no_params);
1947        ConsumeBrace();
1948        SkipUntil(tok::r_brace, /*StopAtSemi*/false);
1949
1950        // Consume the optional ';'
1951        if (Tok.is(tok::semi))
1952          ConsumeToken();
1953        return;
1954      }
1955
1956      if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
1957        Diag(DeclaratorInfo.getIdentifierLoc(),
1958             diag::err_function_declared_typedef);
1959        // This recovery skips the entire function body. It would be nice
1960        // to simply call ParseCXXInlineMethodDef() below, however Sema
1961        // assumes the declarator represents a function, not a typedef.
1962        ConsumeBrace();
1963        SkipUntil(tok::r_brace, /*StopAtSemi*/false);
1964
1965        // Consume the optional ';'
1966        if (Tok.is(tok::semi))
1967          ConsumeToken();
1968        return;
1969      }
1970
1971      Decl *FunDecl =
1972        ParseCXXInlineMethodDef(AS, AccessAttrs, DeclaratorInfo, TemplateInfo,
1973                                VS, DefinitionKind, Init);
1974
1975      for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i) {
1976        CommonLateParsedAttrs[i]->addDecl(FunDecl);
1977      }
1978      for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i) {
1979        LateParsedAttrs[i]->addDecl(FunDecl);
1980      }
1981      LateParsedAttrs.clear();
1982
1983      // Consume the ';' - it's optional unless we have a delete or default
1984      if (Tok.is(tok::semi))
1985        ConsumeExtraSemi(AfterDefinition);
1986
1987      return;
1988    }
1989  }
1990
1991  // member-declarator-list:
1992  //   member-declarator
1993  //   member-declarator-list ',' member-declarator
1994
1995  SmallVector<Decl *, 8> DeclsInGroup;
1996  ExprResult BitfieldSize;
1997  bool ExpectSemi = true;
1998
1999  while (1) {
2000    // member-declarator:
2001    //   declarator pure-specifier[opt]
2002    //   declarator brace-or-equal-initializer[opt]
2003    //   identifier[opt] ':' constant-expression
2004    if (Tok.is(tok::colon)) {
2005      ConsumeToken();
2006      BitfieldSize = ParseConstantExpression();
2007      if (BitfieldSize.isInvalid())
2008        SkipUntil(tok::comma, true, true);
2009    }
2010
2011    // If a simple-asm-expr is present, parse it.
2012    if (Tok.is(tok::kw_asm)) {
2013      SourceLocation Loc;
2014      ExprResult AsmLabel(ParseSimpleAsm(&Loc));
2015      if (AsmLabel.isInvalid())
2016        SkipUntil(tok::comma, true, true);
2017
2018      DeclaratorInfo.setAsmLabel(AsmLabel.release());
2019      DeclaratorInfo.SetRangeEnd(Loc);
2020    }
2021
2022    // If attributes exist after the declarator, parse them.
2023    MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
2024
2025    // FIXME: When g++ adds support for this, we'll need to check whether it
2026    // goes before or after the GNU attributes and __asm__.
2027    ParseOptionalCXX0XVirtSpecifierSeq(VS);
2028
2029    InClassInitStyle HasInClassInit = ICIS_NoInit;
2030    if ((Tok.is(tok::equal) || Tok.is(tok::l_brace)) && !HasInitializer) {
2031      if (BitfieldSize.get()) {
2032        Diag(Tok, diag::err_bitfield_member_init);
2033        SkipUntil(tok::comma, true, true);
2034      } else {
2035        HasInitializer = true;
2036        if (!DeclaratorInfo.isDeclarationOfFunction() &&
2037            DeclaratorInfo.getDeclSpec().getStorageClassSpec()
2038              != DeclSpec::SCS_static &&
2039            DeclaratorInfo.getDeclSpec().getStorageClassSpec()
2040              != DeclSpec::SCS_typedef)
2041          HasInClassInit = Tok.is(tok::equal) ? ICIS_CopyInit : ICIS_ListInit;
2042      }
2043    }
2044
2045    // NOTE: If Sema is the Action module and declarator is an instance field,
2046    // this call will *not* return the created decl; It will return null.
2047    // See Sema::ActOnCXXMemberDeclarator for details.
2048
2049    Decl *ThisDecl = 0;
2050    if (DS.isFriendSpecified()) {
2051      // TODO: handle initializers, bitfields, 'delete'
2052      ThisDecl = Actions.ActOnFriendFunctionDecl(getCurScope(), DeclaratorInfo,
2053                                                 move(TemplateParams));
2054    } else {
2055      ThisDecl = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS,
2056                                                  DeclaratorInfo,
2057                                                  move(TemplateParams),
2058                                                  BitfieldSize.release(),
2059                                                  VS, HasInClassInit);
2060      if (AccessAttrs)
2061        Actions.ProcessDeclAttributeList(getCurScope(), ThisDecl, AccessAttrs,
2062                                         false, true);
2063    }
2064
2065    // Set the Decl for any late parsed attributes
2066    for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i) {
2067      CommonLateParsedAttrs[i]->addDecl(ThisDecl);
2068    }
2069    for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i) {
2070      LateParsedAttrs[i]->addDecl(ThisDecl);
2071    }
2072    LateParsedAttrs.clear();
2073
2074    // Handle the initializer.
2075    if (HasInClassInit != ICIS_NoInit) {
2076      // The initializer was deferred; parse it and cache the tokens.
2077      Diag(Tok, getLangOpts().CPlusPlus0x ?
2078           diag::warn_cxx98_compat_nonstatic_member_init :
2079           diag::ext_nonstatic_member_init);
2080
2081      if (DeclaratorInfo.isArrayOfUnknownBound()) {
2082        // C++11 [dcl.array]p3: An array bound may also be omitted when the
2083        // declarator is followed by an initializer.
2084        //
2085        // A brace-or-equal-initializer for a member-declarator is not an
2086        // initializer in the grammar, so this is ill-formed.
2087        Diag(Tok, diag::err_incomplete_array_member_init);
2088        SkipUntil(tok::comma, true, true);
2089        if (ThisDecl)
2090          // Avoid later warnings about a class member of incomplete type.
2091          ThisDecl->setInvalidDecl();
2092      } else
2093        ParseCXXNonStaticMemberInitializer(ThisDecl);
2094    } else if (HasInitializer) {
2095      // Normal initializer.
2096      if (!Init.isUsable())
2097        Init = ParseCXXMemberInitializer(ThisDecl,
2098                 DeclaratorInfo.isDeclarationOfFunction(), EqualLoc);
2099
2100      if (Init.isInvalid())
2101        SkipUntil(tok::comma, true, true);
2102      else if (ThisDecl)
2103        Actions.AddInitializerToDecl(ThisDecl, Init.get(), EqualLoc.isInvalid(),
2104                                   DS.getTypeSpecType() == DeclSpec::TST_auto);
2105    } else if (ThisDecl && DS.getStorageClassSpec() == DeclSpec::SCS_static) {
2106      // No initializer.
2107      Actions.ActOnUninitializedDecl(ThisDecl,
2108                                   DS.getTypeSpecType() == DeclSpec::TST_auto);
2109    }
2110
2111    if (ThisDecl) {
2112      Actions.FinalizeDeclaration(ThisDecl);
2113      DeclsInGroup.push_back(ThisDecl);
2114    }
2115
2116    if (ThisDecl && DeclaratorInfo.isFunctionDeclarator() &&
2117        DeclaratorInfo.getDeclSpec().getStorageClassSpec()
2118          != DeclSpec::SCS_typedef) {
2119      HandleMemberFunctionDeclDelays(DeclaratorInfo, ThisDecl);
2120    }
2121
2122    DeclaratorInfo.complete(ThisDecl);
2123
2124    // If we don't have a comma, it is either the end of the list (a ';')
2125    // or an error, bail out.
2126    if (Tok.isNot(tok::comma))
2127      break;
2128
2129    // Consume the comma.
2130    SourceLocation CommaLoc = ConsumeToken();
2131
2132    if (Tok.isAtStartOfLine() &&
2133        !MightBeDeclarator(Declarator::MemberContext)) {
2134      // This comma was followed by a line-break and something which can't be
2135      // the start of a declarator. The comma was probably a typo for a
2136      // semicolon.
2137      Diag(CommaLoc, diag::err_expected_semi_declaration)
2138        << FixItHint::CreateReplacement(CommaLoc, ";");
2139      ExpectSemi = false;
2140      break;
2141    }
2142
2143    // Parse the next declarator.
2144    DeclaratorInfo.clear();
2145    VS.clear();
2146    BitfieldSize = true;
2147    Init = true;
2148    HasInitializer = false;
2149    DeclaratorInfo.setCommaLoc(CommaLoc);
2150
2151    // Attributes are only allowed on the second declarator.
2152    MaybeParseGNUAttributes(DeclaratorInfo);
2153
2154    if (Tok.isNot(tok::colon))
2155      ParseDeclarator(DeclaratorInfo);
2156  }
2157
2158  if (ExpectSemi &&
2159      ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list)) {
2160    // Skip to end of block or statement.
2161    SkipUntil(tok::r_brace, true, true);
2162    // If we stopped at a ';', eat it.
2163    if (Tok.is(tok::semi)) ConsumeToken();
2164    return;
2165  }
2166
2167  Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup.data(),
2168                                  DeclsInGroup.size());
2169}
2170
2171/// ParseCXXMemberInitializer - Parse the brace-or-equal-initializer or
2172/// pure-specifier. Also detect and reject any attempted defaulted/deleted
2173/// function definition. The location of the '=', if any, will be placed in
2174/// EqualLoc.
2175///
2176///   pure-specifier:
2177///     '= 0'
2178///
2179///   brace-or-equal-initializer:
2180///     '=' initializer-expression
2181///     braced-init-list
2182///
2183///   initializer-clause:
2184///     assignment-expression
2185///     braced-init-list
2186///
2187///   defaulted/deleted function-definition:
2188///     '=' 'default'
2189///     '=' 'delete'
2190///
2191/// Prior to C++0x, the assignment-expression in an initializer-clause must
2192/// be a constant-expression.
2193ExprResult Parser::ParseCXXMemberInitializer(Decl *D, bool IsFunction,
2194                                             SourceLocation &EqualLoc) {
2195  assert((Tok.is(tok::equal) || Tok.is(tok::l_brace))
2196         && "Data member initializer not starting with '=' or '{'");
2197
2198  EnterExpressionEvaluationContext Context(Actions,
2199                                           Sema::PotentiallyEvaluated,
2200                                           D);
2201  if (Tok.is(tok::equal)) {
2202    EqualLoc = ConsumeToken();
2203    if (Tok.is(tok::kw_delete)) {
2204      // In principle, an initializer of '= delete p;' is legal, but it will
2205      // never type-check. It's better to diagnose it as an ill-formed expression
2206      // than as an ill-formed deleted non-function member.
2207      // An initializer of '= delete p, foo' will never be parsed, because
2208      // a top-level comma always ends the initializer expression.
2209      const Token &Next = NextToken();
2210      if (IsFunction || Next.is(tok::semi) || Next.is(tok::comma) ||
2211           Next.is(tok::eof)) {
2212        if (IsFunction)
2213          Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2214            << 1 /* delete */;
2215        else
2216          Diag(ConsumeToken(), diag::err_deleted_non_function);
2217        return ExprResult();
2218      }
2219    } else if (Tok.is(tok::kw_default)) {
2220      if (IsFunction)
2221        Diag(Tok, diag::err_default_delete_in_multiple_declaration)
2222          << 0 /* default */;
2223      else
2224        Diag(ConsumeToken(), diag::err_default_special_members);
2225      return ExprResult();
2226    }
2227
2228  }
2229  return ParseInitializer();
2230}
2231
2232/// ParseCXXMemberSpecification - Parse the class definition.
2233///
2234///       member-specification:
2235///         member-declaration member-specification[opt]
2236///         access-specifier ':' member-specification[opt]
2237///
2238void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc,
2239                                         unsigned TagType, Decl *TagDecl) {
2240  assert((TagType == DeclSpec::TST_struct ||
2241         TagType == DeclSpec::TST_union  ||
2242         TagType == DeclSpec::TST_class) && "Invalid TagType!");
2243
2244  PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc,
2245                                      "parsing struct/union/class body");
2246
2247  // Determine whether this is a non-nested class. Note that local
2248  // classes are *not* considered to be nested classes.
2249  bool NonNestedClass = true;
2250  if (!ClassStack.empty()) {
2251    for (const Scope *S = getCurScope(); S; S = S->getParent()) {
2252      if (S->isClassScope()) {
2253        // We're inside a class scope, so this is a nested class.
2254        NonNestedClass = false;
2255        break;
2256      }
2257
2258      if ((S->getFlags() & Scope::FnScope)) {
2259        // If we're in a function or function template declared in the
2260        // body of a class, then this is a local class rather than a
2261        // nested class.
2262        const Scope *Parent = S->getParent();
2263        if (Parent->isTemplateParamScope())
2264          Parent = Parent->getParent();
2265        if (Parent->isClassScope())
2266          break;
2267      }
2268    }
2269  }
2270
2271  // Enter a scope for the class.
2272  ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
2273
2274  // Note that we are parsing a new (potentially-nested) class definition.
2275  ParsingClassDefinition ParsingDef(*this, TagDecl, NonNestedClass);
2276
2277  if (TagDecl)
2278    Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
2279
2280  SourceLocation FinalLoc;
2281
2282  // Parse the optional 'final' keyword.
2283  if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
2284    assert(isCXX0XFinalKeyword() && "not a class definition");
2285    FinalLoc = ConsumeToken();
2286
2287    Diag(FinalLoc, getLangOpts().CPlusPlus0x ?
2288         diag::warn_cxx98_compat_override_control_keyword :
2289         diag::ext_override_control_keyword) << "final";
2290  }
2291
2292  if (Tok.is(tok::colon)) {
2293    ParseBaseClause(TagDecl);
2294
2295    if (!Tok.is(tok::l_brace)) {
2296      Diag(Tok, diag::err_expected_lbrace_after_base_specifiers);
2297
2298      if (TagDecl)
2299        Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
2300      return;
2301    }
2302  }
2303
2304  assert(Tok.is(tok::l_brace));
2305  BalancedDelimiterTracker T(*this, tok::l_brace);
2306  T.consumeOpen();
2307
2308  if (TagDecl)
2309    Actions.ActOnStartCXXMemberDeclarations(getCurScope(), TagDecl, FinalLoc,
2310                                            T.getOpenLocation());
2311
2312  // C++ 11p3: Members of a class defined with the keyword class are private
2313  // by default. Members of a class defined with the keywords struct or union
2314  // are public by default.
2315  AccessSpecifier CurAS;
2316  if (TagType == DeclSpec::TST_class)
2317    CurAS = AS_private;
2318  else
2319    CurAS = AS_public;
2320  ParsedAttributes AccessAttrs(AttrFactory);
2321
2322  if (TagDecl) {
2323    // While we still have something to read, read the member-declarations.
2324    while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
2325      // Each iteration of this loop reads one member-declaration.
2326
2327      if (getLangOpts().MicrosoftExt && (Tok.is(tok::kw___if_exists) ||
2328          Tok.is(tok::kw___if_not_exists))) {
2329        ParseMicrosoftIfExistsClassDeclaration((DeclSpec::TST)TagType, CurAS);
2330        continue;
2331      }
2332
2333      // Check for extraneous top-level semicolon.
2334      if (Tok.is(tok::semi)) {
2335        ConsumeExtraSemi(InsideStruct,
2336                         DeclSpec::getSpecifierName((DeclSpec::TST)TagType));
2337        continue;
2338      }
2339
2340      if (Tok.is(tok::annot_pragma_vis)) {
2341        HandlePragmaVisibility();
2342        continue;
2343      }
2344
2345      if (Tok.is(tok::annot_pragma_pack)) {
2346        HandlePragmaPack();
2347        continue;
2348      }
2349
2350      AccessSpecifier AS = getAccessSpecifierIfPresent();
2351      if (AS != AS_none) {
2352        // Current token is a C++ access specifier.
2353        CurAS = AS;
2354        SourceLocation ASLoc = Tok.getLocation();
2355        unsigned TokLength = Tok.getLength();
2356        ConsumeToken();
2357        AccessAttrs.clear();
2358        MaybeParseGNUAttributes(AccessAttrs);
2359
2360        SourceLocation EndLoc;
2361        if (Tok.is(tok::colon)) {
2362          EndLoc = Tok.getLocation();
2363          ConsumeToken();
2364        } else if (Tok.is(tok::semi)) {
2365          EndLoc = Tok.getLocation();
2366          ConsumeToken();
2367          Diag(EndLoc, diag::err_expected_colon)
2368            << FixItHint::CreateReplacement(EndLoc, ":");
2369        } else {
2370          EndLoc = ASLoc.getLocWithOffset(TokLength);
2371          Diag(EndLoc, diag::err_expected_colon)
2372            << FixItHint::CreateInsertion(EndLoc, ":");
2373        }
2374
2375        if (Actions.ActOnAccessSpecifier(AS, ASLoc, EndLoc,
2376                                         AccessAttrs.getList())) {
2377          // found another attribute than only annotations
2378          AccessAttrs.clear();
2379        }
2380
2381        continue;
2382      }
2383
2384      // FIXME: Make sure we don't have a template here.
2385
2386      // Parse all the comma separated declarators.
2387      ParseCXXClassMemberDeclaration(CurAS, AccessAttrs.getList());
2388    }
2389
2390    T.consumeClose();
2391  } else {
2392    SkipUntil(tok::r_brace, false, false);
2393  }
2394
2395  // If attributes exist after class contents, parse them.
2396  ParsedAttributes attrs(AttrFactory);
2397  MaybeParseGNUAttributes(attrs);
2398
2399  if (TagDecl)
2400    Actions.ActOnFinishCXXMemberSpecification(getCurScope(), RecordLoc, TagDecl,
2401                                              T.getOpenLocation(),
2402                                              T.getCloseLocation(),
2403                                              attrs.getList());
2404
2405  // C++11 [class.mem]p2:
2406  //   Within the class member-specification, the class is regarded as complete
2407  //   within function bodies, default arguments, and
2408  //   brace-or-equal-initializers for non-static data members (including such
2409  //   things in nested classes).
2410  if (TagDecl && NonNestedClass) {
2411    // We are not inside a nested class. This class and its nested classes
2412    // are complete and we can parse the delayed portions of method
2413    // declarations and the lexed inline method definitions, along with any
2414    // delayed attributes.
2415    SourceLocation SavedPrevTokLocation = PrevTokLocation;
2416    ParseLexedAttributes(getCurrentClass());
2417    ParseLexedMethodDeclarations(getCurrentClass());
2418
2419    // We've finished with all pending member declarations.
2420    Actions.ActOnFinishCXXMemberDecls();
2421
2422    ParseLexedMemberInitializers(getCurrentClass());
2423    ParseLexedMethodDefs(getCurrentClass());
2424    PrevTokLocation = SavedPrevTokLocation;
2425  }
2426
2427  if (TagDecl)
2428    Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl,
2429                                     T.getCloseLocation());
2430
2431  // Leave the class scope.
2432  ParsingDef.Pop();
2433  ClassScope.Exit();
2434}
2435
2436/// ParseConstructorInitializer - Parse a C++ constructor initializer,
2437/// which explicitly initializes the members or base classes of a
2438/// class (C++ [class.base.init]). For example, the three initializers
2439/// after the ':' in the Derived constructor below:
2440///
2441/// @code
2442/// class Base { };
2443/// class Derived : Base {
2444///   int x;
2445///   float f;
2446/// public:
2447///   Derived(float f) : Base(), x(17), f(f) { }
2448/// };
2449/// @endcode
2450///
2451/// [C++]  ctor-initializer:
2452///          ':' mem-initializer-list
2453///
2454/// [C++]  mem-initializer-list:
2455///          mem-initializer ...[opt]
2456///          mem-initializer ...[opt] , mem-initializer-list
2457void Parser::ParseConstructorInitializer(Decl *ConstructorDecl) {
2458  assert(Tok.is(tok::colon) && "Constructor initializer always starts with ':'");
2459
2460  // Poison the SEH identifiers so they are flagged as illegal in constructor initializers
2461  PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
2462  SourceLocation ColonLoc = ConsumeToken();
2463
2464  SmallVector<CXXCtorInitializer*, 4> MemInitializers;
2465  bool AnyErrors = false;
2466
2467  do {
2468    if (Tok.is(tok::code_completion)) {
2469      Actions.CodeCompleteConstructorInitializer(ConstructorDecl,
2470                                                 MemInitializers.data(),
2471                                                 MemInitializers.size());
2472      return cutOffParsing();
2473    } else {
2474      MemInitResult MemInit = ParseMemInitializer(ConstructorDecl);
2475      if (!MemInit.isInvalid())
2476        MemInitializers.push_back(MemInit.get());
2477      else
2478        AnyErrors = true;
2479    }
2480
2481    if (Tok.is(tok::comma))
2482      ConsumeToken();
2483    else if (Tok.is(tok::l_brace))
2484      break;
2485    // If the next token looks like a base or member initializer, assume that
2486    // we're just missing a comma.
2487    else if (Tok.is(tok::identifier) || Tok.is(tok::coloncolon)) {
2488      SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation);
2489      Diag(Loc, diag::err_ctor_init_missing_comma)
2490        << FixItHint::CreateInsertion(Loc, ", ");
2491    } else {
2492      // Skip over garbage, until we get to '{'.  Don't eat the '{'.
2493      Diag(Tok.getLocation(), diag::err_expected_lbrace_or_comma);
2494      SkipUntil(tok::l_brace, true, true);
2495      break;
2496    }
2497  } while (true);
2498
2499  Actions.ActOnMemInitializers(ConstructorDecl, ColonLoc,
2500                               MemInitializers.data(), MemInitializers.size(),
2501                               AnyErrors);
2502}
2503
2504/// ParseMemInitializer - Parse a C++ member initializer, which is
2505/// part of a constructor initializer that explicitly initializes one
2506/// member or base class (C++ [class.base.init]). See
2507/// ParseConstructorInitializer for an example.
2508///
2509/// [C++] mem-initializer:
2510///         mem-initializer-id '(' expression-list[opt] ')'
2511/// [C++0x] mem-initializer-id braced-init-list
2512///
2513/// [C++] mem-initializer-id:
2514///         '::'[opt] nested-name-specifier[opt] class-name
2515///         identifier
2516Parser::MemInitResult Parser::ParseMemInitializer(Decl *ConstructorDecl) {
2517  // parse '::'[opt] nested-name-specifier[opt]
2518  CXXScopeSpec SS;
2519  ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
2520  ParsedType TemplateTypeTy;
2521  if (Tok.is(tok::annot_template_id)) {
2522    TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
2523    if (TemplateId->Kind == TNK_Type_template ||
2524        TemplateId->Kind == TNK_Dependent_template_name) {
2525      AnnotateTemplateIdTokenAsType();
2526      assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
2527      TemplateTypeTy = getTypeAnnotation(Tok);
2528    }
2529  }
2530  // Uses of decltype will already have been converted to annot_decltype by
2531  // ParseOptionalCXXScopeSpecifier at this point.
2532  if (!TemplateTypeTy && Tok.isNot(tok::identifier)
2533      && Tok.isNot(tok::annot_decltype)) {
2534    Diag(Tok, diag::err_expected_member_or_base_name);
2535    return true;
2536  }
2537
2538  IdentifierInfo *II = 0;
2539  DeclSpec DS(AttrFactory);
2540  SourceLocation IdLoc = Tok.getLocation();
2541  if (Tok.is(tok::annot_decltype)) {
2542    // Get the decltype expression, if there is one.
2543    ParseDecltypeSpecifier(DS);
2544  } else {
2545    if (Tok.is(tok::identifier))
2546      // Get the identifier. This may be a member name or a class name,
2547      // but we'll let the semantic analysis determine which it is.
2548      II = Tok.getIdentifierInfo();
2549    ConsumeToken();
2550  }
2551
2552
2553  // Parse the '('.
2554  if (getLangOpts().CPlusPlus0x && Tok.is(tok::l_brace)) {
2555    Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
2556
2557    ExprResult InitList = ParseBraceInitializer();
2558    if (InitList.isInvalid())
2559      return true;
2560
2561    SourceLocation EllipsisLoc;
2562    if (Tok.is(tok::ellipsis))
2563      EllipsisLoc = ConsumeToken();
2564
2565    return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
2566                                       TemplateTypeTy, DS, IdLoc,
2567                                       InitList.take(), EllipsisLoc);
2568  } else if(Tok.is(tok::l_paren)) {
2569    BalancedDelimiterTracker T(*this, tok::l_paren);
2570    T.consumeOpen();
2571
2572    // Parse the optional expression-list.
2573    ExprVector ArgExprs(Actions);
2574    CommaLocsTy CommaLocs;
2575    if (Tok.isNot(tok::r_paren) && ParseExpressionList(ArgExprs, CommaLocs)) {
2576      SkipUntil(tok::r_paren);
2577      return true;
2578    }
2579
2580    T.consumeClose();
2581
2582    SourceLocation EllipsisLoc;
2583    if (Tok.is(tok::ellipsis))
2584      EllipsisLoc = ConsumeToken();
2585
2586    return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
2587                                       TemplateTypeTy, DS, IdLoc,
2588                                       T.getOpenLocation(), ArgExprs.take(),
2589                                       ArgExprs.size(), T.getCloseLocation(),
2590                                       EllipsisLoc);
2591  }
2592
2593  Diag(Tok, getLangOpts().CPlusPlus0x ? diag::err_expected_lparen_or_lbrace
2594                                  : diag::err_expected_lparen);
2595  return true;
2596}
2597
2598/// \brief Parse a C++ exception-specification if present (C++0x [except.spec]).
2599///
2600///       exception-specification:
2601///         dynamic-exception-specification
2602///         noexcept-specification
2603///
2604///       noexcept-specification:
2605///         'noexcept'
2606///         'noexcept' '(' constant-expression ')'
2607ExceptionSpecificationType
2608Parser::tryParseExceptionSpecification(
2609                    SourceRange &SpecificationRange,
2610                    SmallVectorImpl<ParsedType> &DynamicExceptions,
2611                    SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
2612                    ExprResult &NoexceptExpr) {
2613  ExceptionSpecificationType Result = EST_None;
2614
2615  // See if there's a dynamic specification.
2616  if (Tok.is(tok::kw_throw)) {
2617    Result = ParseDynamicExceptionSpecification(SpecificationRange,
2618                                                DynamicExceptions,
2619                                                DynamicExceptionRanges);
2620    assert(DynamicExceptions.size() == DynamicExceptionRanges.size() &&
2621           "Produced different number of exception types and ranges.");
2622  }
2623
2624  // If there's no noexcept specification, we're done.
2625  if (Tok.isNot(tok::kw_noexcept))
2626    return Result;
2627
2628  Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
2629
2630  // If we already had a dynamic specification, parse the noexcept for,
2631  // recovery, but emit a diagnostic and don't store the results.
2632  SourceRange NoexceptRange;
2633  ExceptionSpecificationType NoexceptType = EST_None;
2634
2635  SourceLocation KeywordLoc = ConsumeToken();
2636  if (Tok.is(tok::l_paren)) {
2637    // There is an argument.
2638    BalancedDelimiterTracker T(*this, tok::l_paren);
2639    T.consumeOpen();
2640    NoexceptType = EST_ComputedNoexcept;
2641    NoexceptExpr = ParseConstantExpression();
2642    // The argument must be contextually convertible to bool. We use
2643    // ActOnBooleanCondition for this purpose.
2644    if (!NoexceptExpr.isInvalid())
2645      NoexceptExpr = Actions.ActOnBooleanCondition(getCurScope(), KeywordLoc,
2646                                                   NoexceptExpr.get());
2647    T.consumeClose();
2648    NoexceptRange = SourceRange(KeywordLoc, T.getCloseLocation());
2649  } else {
2650    // There is no argument.
2651    NoexceptType = EST_BasicNoexcept;
2652    NoexceptRange = SourceRange(KeywordLoc, KeywordLoc);
2653  }
2654
2655  if (Result == EST_None) {
2656    SpecificationRange = NoexceptRange;
2657    Result = NoexceptType;
2658
2659    // If there's a dynamic specification after a noexcept specification,
2660    // parse that and ignore the results.
2661    if (Tok.is(tok::kw_throw)) {
2662      Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
2663      ParseDynamicExceptionSpecification(NoexceptRange, DynamicExceptions,
2664                                         DynamicExceptionRanges);
2665    }
2666  } else {
2667    Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
2668  }
2669
2670  return Result;
2671}
2672
2673/// ParseDynamicExceptionSpecification - Parse a C++
2674/// dynamic-exception-specification (C++ [except.spec]).
2675///
2676///       dynamic-exception-specification:
2677///         'throw' '(' type-id-list [opt] ')'
2678/// [MS]    'throw' '(' '...' ')'
2679///
2680///       type-id-list:
2681///         type-id ... [opt]
2682///         type-id-list ',' type-id ... [opt]
2683///
2684ExceptionSpecificationType Parser::ParseDynamicExceptionSpecification(
2685                                  SourceRange &SpecificationRange,
2686                                  SmallVectorImpl<ParsedType> &Exceptions,
2687                                  SmallVectorImpl<SourceRange> &Ranges) {
2688  assert(Tok.is(tok::kw_throw) && "expected throw");
2689
2690  SpecificationRange.setBegin(ConsumeToken());
2691  BalancedDelimiterTracker T(*this, tok::l_paren);
2692  if (T.consumeOpen()) {
2693    Diag(Tok, diag::err_expected_lparen_after) << "throw";
2694    SpecificationRange.setEnd(SpecificationRange.getBegin());
2695    return EST_DynamicNone;
2696  }
2697
2698  // Parse throw(...), a Microsoft extension that means "this function
2699  // can throw anything".
2700  if (Tok.is(tok::ellipsis)) {
2701    SourceLocation EllipsisLoc = ConsumeToken();
2702    if (!getLangOpts().MicrosoftExt)
2703      Diag(EllipsisLoc, diag::ext_ellipsis_exception_spec);
2704    T.consumeClose();
2705    SpecificationRange.setEnd(T.getCloseLocation());
2706    return EST_MSAny;
2707  }
2708
2709  // Parse the sequence of type-ids.
2710  SourceRange Range;
2711  while (Tok.isNot(tok::r_paren)) {
2712    TypeResult Res(ParseTypeName(&Range));
2713
2714    if (Tok.is(tok::ellipsis)) {
2715      // C++0x [temp.variadic]p5:
2716      //   - In a dynamic-exception-specification (15.4); the pattern is a
2717      //     type-id.
2718      SourceLocation Ellipsis = ConsumeToken();
2719      Range.setEnd(Ellipsis);
2720      if (!Res.isInvalid())
2721        Res = Actions.ActOnPackExpansion(Res.get(), Ellipsis);
2722    }
2723
2724    if (!Res.isInvalid()) {
2725      Exceptions.push_back(Res.get());
2726      Ranges.push_back(Range);
2727    }
2728
2729    if (Tok.is(tok::comma))
2730      ConsumeToken();
2731    else
2732      break;
2733  }
2734
2735  T.consumeClose();
2736  SpecificationRange.setEnd(T.getCloseLocation());
2737  return Exceptions.empty() ? EST_DynamicNone : EST_Dynamic;
2738}
2739
2740/// ParseTrailingReturnType - Parse a trailing return type on a new-style
2741/// function declaration.
2742TypeResult Parser::ParseTrailingReturnType(SourceRange &Range) {
2743  assert(Tok.is(tok::arrow) && "expected arrow");
2744
2745  ConsumeToken();
2746
2747  return ParseTypeName(&Range, Declarator::TrailingReturnContext);
2748}
2749
2750/// \brief We have just started parsing the definition of a new class,
2751/// so push that class onto our stack of classes that is currently
2752/// being parsed.
2753Sema::ParsingClassState
2754Parser::PushParsingClass(Decl *ClassDecl, bool NonNestedClass) {
2755  assert((NonNestedClass || !ClassStack.empty()) &&
2756         "Nested class without outer class");
2757  ClassStack.push(new ParsingClass(ClassDecl, NonNestedClass));
2758  return Actions.PushParsingClass();
2759}
2760
2761/// \brief Deallocate the given parsed class and all of its nested
2762/// classes.
2763void Parser::DeallocateParsedClasses(Parser::ParsingClass *Class) {
2764  for (unsigned I = 0, N = Class->LateParsedDeclarations.size(); I != N; ++I)
2765    delete Class->LateParsedDeclarations[I];
2766  delete Class;
2767}
2768
2769/// \brief Pop the top class of the stack of classes that are
2770/// currently being parsed.
2771///
2772/// This routine should be called when we have finished parsing the
2773/// definition of a class, but have not yet popped the Scope
2774/// associated with the class's definition.
2775///
2776/// \returns true if the class we've popped is a top-level class,
2777/// false otherwise.
2778void Parser::PopParsingClass(Sema::ParsingClassState state) {
2779  assert(!ClassStack.empty() && "Mismatched push/pop for class parsing");
2780
2781  Actions.PopParsingClass(state);
2782
2783  ParsingClass *Victim = ClassStack.top();
2784  ClassStack.pop();
2785  if (Victim->TopLevelClass) {
2786    // Deallocate all of the nested classes of this class,
2787    // recursively: we don't need to keep any of this information.
2788    DeallocateParsedClasses(Victim);
2789    return;
2790  }
2791  assert(!ClassStack.empty() && "Missing top-level class?");
2792
2793  if (Victim->LateParsedDeclarations.empty()) {
2794    // The victim is a nested class, but we will not need to perform
2795    // any processing after the definition of this class since it has
2796    // no members whose handling was delayed. Therefore, we can just
2797    // remove this nested class.
2798    DeallocateParsedClasses(Victim);
2799    return;
2800  }
2801
2802  // This nested class has some members that will need to be processed
2803  // after the top-level class is completely defined. Therefore, add
2804  // it to the list of nested classes within its parent.
2805  assert(getCurScope()->isClassScope() && "Nested class outside of class scope?");
2806  ClassStack.top()->LateParsedDeclarations.push_back(new LateParsedClass(this, Victim));
2807  Victim->TemplateScope = getCurScope()->getParent()->isTemplateParamScope();
2808}
2809
2810/// \brief Try to parse an 'identifier' which appears within an attribute-token.
2811///
2812/// \return the parsed identifier on success, and 0 if the next token is not an
2813/// attribute-token.
2814///
2815/// C++11 [dcl.attr.grammar]p3:
2816///   If a keyword or an alternative token that satisfies the syntactic
2817///   requirements of an identifier is contained in an attribute-token,
2818///   it is considered an identifier.
2819IdentifierInfo *Parser::TryParseCXX11AttributeIdentifier(SourceLocation &Loc) {
2820  switch (Tok.getKind()) {
2821  default:
2822    // Identifiers and keywords have identifier info attached.
2823    if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
2824      Loc = ConsumeToken();
2825      return II;
2826    }
2827    return 0;
2828
2829  case tok::ampamp:       // 'and'
2830  case tok::pipe:         // 'bitor'
2831  case tok::pipepipe:     // 'or'
2832  case tok::caret:        // 'xor'
2833  case tok::tilde:        // 'compl'
2834  case tok::amp:          // 'bitand'
2835  case tok::ampequal:     // 'and_eq'
2836  case tok::pipeequal:    // 'or_eq'
2837  case tok::caretequal:   // 'xor_eq'
2838  case tok::exclaim:      // 'not'
2839  case tok::exclaimequal: // 'not_eq'
2840    // Alternative tokens do not have identifier info, but their spelling
2841    // starts with an alphabetical character.
2842    llvm::SmallString<8> SpellingBuf;
2843    StringRef Spelling = PP.getSpelling(Tok.getLocation(), SpellingBuf);
2844    if (std::isalpha(Spelling[0])) {
2845      Loc = ConsumeToken();
2846      return &PP.getIdentifierTable().get(Spelling);
2847    }
2848    return 0;
2849  }
2850}
2851
2852/// ParseCXX11AttributeSpecifier - Parse a C++11 attribute-specifier. Currently
2853/// only parses standard attributes.
2854///
2855/// [C++11] attribute-specifier:
2856///         '[' '[' attribute-list ']' ']'
2857///         alignment-specifier
2858///
2859/// [C++11] attribute-list:
2860///         attribute[opt]
2861///         attribute-list ',' attribute[opt]
2862///         attribute '...'
2863///         attribute-list ',' attribute '...'
2864///
2865/// [C++11] attribute:
2866///         attribute-token attribute-argument-clause[opt]
2867///
2868/// [C++11] attribute-token:
2869///         identifier
2870///         attribute-scoped-token
2871///
2872/// [C++11] attribute-scoped-token:
2873///         attribute-namespace '::' identifier
2874///
2875/// [C++11] attribute-namespace:
2876///         identifier
2877///
2878/// [C++11] attribute-argument-clause:
2879///         '(' balanced-token-seq ')'
2880///
2881/// [C++11] balanced-token-seq:
2882///         balanced-token
2883///         balanced-token-seq balanced-token
2884///
2885/// [C++11] balanced-token:
2886///         '(' balanced-token-seq ')'
2887///         '[' balanced-token-seq ']'
2888///         '{' balanced-token-seq '}'
2889///         any token but '(', ')', '[', ']', '{', or '}'
2890void Parser::ParseCXX11AttributeSpecifier(ParsedAttributes &attrs,
2891                                          SourceLocation *endLoc) {
2892  if (Tok.is(tok::kw_alignas)) {
2893    Diag(Tok.getLocation(), diag::warn_cxx98_compat_alignas);
2894    ParseAlignmentSpecifier(attrs, endLoc);
2895    return;
2896  }
2897
2898  assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square)
2899      && "Not a C++11 attribute list");
2900
2901  Diag(Tok.getLocation(), diag::warn_cxx98_compat_attribute);
2902
2903  ConsumeBracket();
2904  ConsumeBracket();
2905
2906  while (Tok.isNot(tok::r_square)) {
2907    // attribute not present
2908    if (Tok.is(tok::comma)) {
2909      ConsumeToken();
2910      continue;
2911    }
2912
2913    SourceLocation ScopeLoc, AttrLoc;
2914    IdentifierInfo *ScopeName = 0, *AttrName = 0;
2915
2916    AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
2917    if (!AttrName)
2918      // Break out to the "expected ']'" diagnostic.
2919      break;
2920
2921    // scoped attribute
2922    if (Tok.is(tok::coloncolon)) {
2923      ConsumeToken();
2924
2925      ScopeName = AttrName;
2926      ScopeLoc = AttrLoc;
2927
2928      AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
2929      if (!AttrName) {
2930        Diag(Tok.getLocation(), diag::err_expected_ident);
2931        SkipUntil(tok::r_square, tok::comma, true, true);
2932        continue;
2933      }
2934    }
2935
2936    bool AttrParsed = false;
2937    switch (AttributeList::getKind(AttrName, ScopeName,
2938                                   AttributeList::AS_CXX11)) {
2939    // No arguments
2940    case AttributeList::AT_CarriesDependency:
2941    // FIXME: implement generic support of attributes with C++11 syntax
2942    // see Parse/ParseDecl.cpp: ParseGNUAttributes
2943    case AttributeList::AT_FallThrough:
2944    case AttributeList::AT_NoReturn: {
2945      if (Tok.is(tok::l_paren)) {
2946        Diag(Tok.getLocation(), diag::err_cxx11_attribute_forbids_arguments)
2947          << AttrName->getName();
2948        break;
2949      }
2950
2951      attrs.addNew(AttrName,
2952                   SourceRange(ScopeLoc.isValid() ? ScopeLoc : AttrLoc,
2953                               AttrLoc),
2954                   ScopeName, ScopeLoc, 0,
2955                   SourceLocation(), 0, 0, AttributeList::AS_CXX11);
2956      AttrParsed = true;
2957      break;
2958    }
2959
2960    // Silence warnings
2961    default: break;
2962    }
2963
2964    // Skip the entire parameter clause, if any
2965    if (!AttrParsed && Tok.is(tok::l_paren)) {
2966      ConsumeParen();
2967      // SkipUntil maintains the balancedness of tokens.
2968      SkipUntil(tok::r_paren, false);
2969    }
2970
2971    if (Tok.is(tok::ellipsis)) {
2972      if (AttrParsed)
2973        Diag(Tok, diag::err_cxx11_attribute_forbids_ellipsis)
2974          << AttrName->getName();
2975      ConsumeToken();
2976    }
2977  }
2978
2979  if (ExpectAndConsume(tok::r_square, diag::err_expected_rsquare))
2980    SkipUntil(tok::r_square, false);
2981  if (endLoc)
2982    *endLoc = Tok.getLocation();
2983  if (ExpectAndConsume(tok::r_square, diag::err_expected_rsquare))
2984    SkipUntil(tok::r_square, false);
2985}
2986
2987/// ParseCXX11Attributes - Parse a C++11 attribute-specifier-seq.
2988///
2989/// attribute-specifier-seq:
2990///       attribute-specifier-seq[opt] attribute-specifier
2991void Parser::ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
2992                                  SourceLocation *endLoc) {
2993  SourceLocation StartLoc = Tok.getLocation(), Loc;
2994  if (!endLoc)
2995    endLoc = &Loc;
2996
2997  do {
2998    ParseCXX11AttributeSpecifier(attrs, endLoc);
2999  } while (isCXX11AttributeSpecifier());
3000
3001  attrs.Range = SourceRange(StartLoc, *endLoc);
3002}
3003
3004/// ParseMicrosoftAttributes - Parse a Microsoft attribute [Attr]
3005///
3006/// [MS] ms-attribute:
3007///             '[' token-seq ']'
3008///
3009/// [MS] ms-attribute-seq:
3010///             ms-attribute[opt]
3011///             ms-attribute ms-attribute-seq
3012void Parser::ParseMicrosoftAttributes(ParsedAttributes &attrs,
3013                                      SourceLocation *endLoc) {
3014  assert(Tok.is(tok::l_square) && "Not a Microsoft attribute list");
3015
3016  while (Tok.is(tok::l_square)) {
3017    // FIXME: If this is actually a C++11 attribute, parse it as one.
3018    ConsumeBracket();
3019    SkipUntil(tok::r_square, true, true);
3020    if (endLoc) *endLoc = Tok.getLocation();
3021    ExpectAndConsume(tok::r_square, diag::err_expected_rsquare);
3022  }
3023}
3024
3025void Parser::ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType,
3026                                                    AccessSpecifier& CurAS) {
3027  IfExistsCondition Result;
3028  if (ParseMicrosoftIfExistsCondition(Result))
3029    return;
3030
3031  BalancedDelimiterTracker Braces(*this, tok::l_brace);
3032  if (Braces.consumeOpen()) {
3033    Diag(Tok, diag::err_expected_lbrace);
3034    return;
3035  }
3036
3037  switch (Result.Behavior) {
3038  case IEB_Parse:
3039    // Parse the declarations below.
3040    break;
3041
3042  case IEB_Dependent:
3043    Diag(Result.KeywordLoc, diag::warn_microsoft_dependent_exists)
3044      << Result.IsIfExists;
3045    // Fall through to skip.
3046
3047  case IEB_Skip:
3048    Braces.skipToEnd();
3049    return;
3050  }
3051
3052  while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
3053    // __if_exists, __if_not_exists can nest.
3054    if ((Tok.is(tok::kw___if_exists) || Tok.is(tok::kw___if_not_exists))) {
3055      ParseMicrosoftIfExistsClassDeclaration((DeclSpec::TST)TagType, CurAS);
3056      continue;
3057    }
3058
3059    // Check for extraneous top-level semicolon.
3060    if (Tok.is(tok::semi)) {
3061      ConsumeExtraSemi(InsideStruct,
3062                       DeclSpec::getSpecifierName((DeclSpec::TST)TagType));
3063      continue;
3064    }
3065
3066    AccessSpecifier AS = getAccessSpecifierIfPresent();
3067    if (AS != AS_none) {
3068      // Current token is a C++ access specifier.
3069      CurAS = AS;
3070      SourceLocation ASLoc = Tok.getLocation();
3071      ConsumeToken();
3072      if (Tok.is(tok::colon))
3073        Actions.ActOnAccessSpecifier(AS, ASLoc, Tok.getLocation());
3074      else
3075        Diag(Tok, diag::err_expected_colon);
3076      ConsumeToken();
3077      continue;
3078    }
3079
3080    // Parse all the comma separated declarators.
3081    ParseCXXClassMemberDeclaration(CurAS, 0);
3082  }
3083
3084  Braces.consumeClose();
3085}
3086