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