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