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