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