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