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