ParseDeclCXX.cpp revision 1.1.1.1
1//===--- ParseDeclCXX.cpp - C++ Declaration Parsing -------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9//  This file implements the C++ Declaration portions of the Parser interfaces.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/Parse/Parser.h"
14#include "clang/AST/ASTContext.h"
15#include "clang/AST/DeclTemplate.h"
16#include "clang/AST/PrettyDeclStackTrace.h"
17#include "clang/Basic/Attributes.h"
18#include "clang/Basic/CharInfo.h"
19#include "clang/Basic/OperatorKinds.h"
20#include "clang/Basic/TargetInfo.h"
21#include "clang/Parse/ParseDiagnostic.h"
22#include "clang/Parse/RAIIObjectsForParser.h"
23#include "clang/Sema/DeclSpec.h"
24#include "clang/Sema/ParsedTemplate.h"
25#include "clang/Sema/Scope.h"
26#include "llvm/ADT/SmallString.h"
27#include "llvm/Support/TimeProfiler.h"
28
29using namespace clang;
30
31/// ParseNamespace - We know that the current token is a namespace keyword. This
32/// may either be a top level namespace or a block-level namespace alias. If
33/// there was an inline keyword, it has already been parsed.
34///
35///       namespace-definition: [C++: namespace.def]
36///         named-namespace-definition
37///         unnamed-namespace-definition
38///         nested-namespace-definition
39///
40///       named-namespace-definition:
41///         'inline'[opt] 'namespace' attributes[opt] identifier '{'
42///         namespace-body '}'
43///
44///       unnamed-namespace-definition:
45///         'inline'[opt] 'namespace' attributes[opt] '{' namespace-body '}'
46///
47///       nested-namespace-definition:
48///         'namespace' enclosing-namespace-specifier '::' 'inline'[opt]
49///         identifier '{' namespace-body '}'
50///
51///       enclosing-namespace-specifier:
52///         identifier
53///         enclosing-namespace-specifier '::' 'inline'[opt] identifier
54///
55///       namespace-alias-definition:  [C++ 7.3.2: namespace.alias]
56///         'namespace' identifier '=' qualified-namespace-specifier ';'
57///
58Parser::DeclGroupPtrTy Parser::ParseNamespace(DeclaratorContext Context,
59                                              SourceLocation &DeclEnd,
60                                              SourceLocation InlineLoc) {
61  assert(Tok.is(tok::kw_namespace) && "Not a namespace!");
62  SourceLocation NamespaceLoc = ConsumeToken();  // eat the 'namespace'.
63  ObjCDeclContextSwitch ObjCDC(*this);
64
65  if (Tok.is(tok::code_completion)) {
66    Actions.CodeCompleteNamespaceDecl(getCurScope());
67    cutOffParsing();
68    return nullptr;
69  }
70
71  SourceLocation IdentLoc;
72  IdentifierInfo *Ident = nullptr;
73  InnerNamespaceInfoList ExtraNSs;
74  SourceLocation FirstNestedInlineLoc;
75
76  ParsedAttributesWithRange attrs(AttrFactory);
77  SourceLocation attrLoc;
78  if (getLangOpts().CPlusPlus11 && isCXX11AttributeSpecifier()) {
79    Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
80                                ? diag::warn_cxx14_compat_ns_enum_attribute
81                                : diag::ext_ns_enum_attribute)
82      << 0 /*namespace*/;
83    attrLoc = Tok.getLocation();
84    ParseCXX11Attributes(attrs);
85  }
86
87  if (Tok.is(tok::identifier)) {
88    Ident = Tok.getIdentifierInfo();
89    IdentLoc = ConsumeToken();  // eat the identifier.
90    while (Tok.is(tok::coloncolon) &&
91           (NextToken().is(tok::identifier) ||
92            (NextToken().is(tok::kw_inline) &&
93             GetLookAheadToken(2).is(tok::identifier)))) {
94
95      InnerNamespaceInfo Info;
96      Info.NamespaceLoc = ConsumeToken();
97
98      if (Tok.is(tok::kw_inline)) {
99        Info.InlineLoc = ConsumeToken();
100        if (FirstNestedInlineLoc.isInvalid())
101          FirstNestedInlineLoc = Info.InlineLoc;
102      }
103
104      Info.Ident = Tok.getIdentifierInfo();
105      Info.IdentLoc = ConsumeToken();
106
107      ExtraNSs.push_back(Info);
108    }
109  }
110
111  // A nested namespace definition cannot have attributes.
112  if (!ExtraNSs.empty() && attrLoc.isValid())
113    Diag(attrLoc, diag::err_unexpected_nested_namespace_attribute);
114
115  // Read label attributes, if present.
116  if (Tok.is(tok::kw___attribute)) {
117    attrLoc = Tok.getLocation();
118    ParseGNUAttributes(attrs);
119  }
120
121  if (Tok.is(tok::equal)) {
122    if (!Ident) {
123      Diag(Tok, diag::err_expected) << tok::identifier;
124      // Skip to end of the definition and eat the ';'.
125      SkipUntil(tok::semi);
126      return nullptr;
127    }
128    if (attrLoc.isValid())
129      Diag(attrLoc, diag::err_unexpected_namespace_attributes_alias);
130    if (InlineLoc.isValid())
131      Diag(InlineLoc, diag::err_inline_namespace_alias)
132          << FixItHint::CreateRemoval(InlineLoc);
133    Decl *NSAlias = ParseNamespaceAlias(NamespaceLoc, IdentLoc, Ident, DeclEnd);
134    return Actions.ConvertDeclToDeclGroup(NSAlias);
135}
136
137  BalancedDelimiterTracker T(*this, tok::l_brace);
138  if (T.consumeOpen()) {
139    if (Ident)
140      Diag(Tok, diag::err_expected) << tok::l_brace;
141    else
142      Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace;
143    return nullptr;
144  }
145
146  if (getCurScope()->isClassScope() || getCurScope()->isTemplateParamScope() ||
147      getCurScope()->isInObjcMethodScope() || getCurScope()->getBlockParent() ||
148      getCurScope()->getFnParent()) {
149    Diag(T.getOpenLocation(), diag::err_namespace_nonnamespace_scope);
150    SkipUntil(tok::r_brace);
151    return nullptr;
152  }
153
154  if (ExtraNSs.empty()) {
155    // Normal namespace definition, not a nested-namespace-definition.
156  } else if (InlineLoc.isValid()) {
157    Diag(InlineLoc, diag::err_inline_nested_namespace_definition);
158  } else if (getLangOpts().CPlusPlus2a) {
159    Diag(ExtraNSs[0].NamespaceLoc,
160         diag::warn_cxx14_compat_nested_namespace_definition);
161    if (FirstNestedInlineLoc.isValid())
162      Diag(FirstNestedInlineLoc,
163           diag::warn_cxx17_compat_inline_nested_namespace_definition);
164  } else if (getLangOpts().CPlusPlus17) {
165    Diag(ExtraNSs[0].NamespaceLoc,
166         diag::warn_cxx14_compat_nested_namespace_definition);
167    if (FirstNestedInlineLoc.isValid())
168      Diag(FirstNestedInlineLoc, diag::ext_inline_nested_namespace_definition);
169  } else {
170    TentativeParsingAction TPA(*this);
171    SkipUntil(tok::r_brace, StopBeforeMatch);
172    Token rBraceToken = Tok;
173    TPA.Revert();
174
175    if (!rBraceToken.is(tok::r_brace)) {
176      Diag(ExtraNSs[0].NamespaceLoc, diag::ext_nested_namespace_definition)
177          << SourceRange(ExtraNSs.front().NamespaceLoc,
178                         ExtraNSs.back().IdentLoc);
179    } else {
180      std::string NamespaceFix;
181      for (const auto &ExtraNS : ExtraNSs) {
182        NamespaceFix += " { ";
183        if (ExtraNS.InlineLoc.isValid())
184          NamespaceFix += "inline ";
185        NamespaceFix += "namespace ";
186        NamespaceFix += ExtraNS.Ident->getName();
187      }
188
189      std::string RBraces;
190      for (unsigned i = 0, e = ExtraNSs.size(); i != e; ++i)
191        RBraces +=  "} ";
192
193      Diag(ExtraNSs[0].NamespaceLoc, diag::ext_nested_namespace_definition)
194          << FixItHint::CreateReplacement(
195                 SourceRange(ExtraNSs.front().NamespaceLoc,
196                             ExtraNSs.back().IdentLoc),
197                 NamespaceFix)
198          << FixItHint::CreateInsertion(rBraceToken.getLocation(), RBraces);
199    }
200
201    // Warn about nested inline namespaces.
202    if (FirstNestedInlineLoc.isValid())
203      Diag(FirstNestedInlineLoc, diag::ext_inline_nested_namespace_definition);
204  }
205
206  // If we're still good, complain about inline namespaces in non-C++0x now.
207  if (InlineLoc.isValid())
208    Diag(InlineLoc, getLangOpts().CPlusPlus11 ?
209         diag::warn_cxx98_compat_inline_namespace : diag::ext_inline_namespace);
210
211  // Enter a scope for the namespace.
212  ParseScope NamespaceScope(this, Scope::DeclScope);
213
214  UsingDirectiveDecl *ImplicitUsingDirectiveDecl = nullptr;
215  Decl *NamespcDecl = Actions.ActOnStartNamespaceDef(
216      getCurScope(), InlineLoc, NamespaceLoc, IdentLoc, Ident,
217      T.getOpenLocation(), attrs, ImplicitUsingDirectiveDecl);
218
219  PrettyDeclStackTraceEntry CrashInfo(Actions.Context, NamespcDecl,
220                                      NamespaceLoc, "parsing namespace");
221
222  // Parse the contents of the namespace.  This includes parsing recovery on
223  // any improperly nested namespaces.
224  ParseInnerNamespace(ExtraNSs, 0, InlineLoc, attrs, T);
225
226  // Leave the namespace scope.
227  NamespaceScope.Exit();
228
229  DeclEnd = T.getCloseLocation();
230  Actions.ActOnFinishNamespaceDef(NamespcDecl, DeclEnd);
231
232  return Actions.ConvertDeclToDeclGroup(NamespcDecl,
233                                        ImplicitUsingDirectiveDecl);
234}
235
236/// ParseInnerNamespace - Parse the contents of a namespace.
237void Parser::ParseInnerNamespace(const InnerNamespaceInfoList &InnerNSs,
238                                 unsigned int index, SourceLocation &InlineLoc,
239                                 ParsedAttributes &attrs,
240                                 BalancedDelimiterTracker &Tracker) {
241  if (index == InnerNSs.size()) {
242    while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
243           Tok.isNot(tok::eof)) {
244      ParsedAttributesWithRange attrs(AttrFactory);
245      MaybeParseCXX11Attributes(attrs);
246      ParseExternalDeclaration(attrs);
247    }
248
249    // The caller is what called check -- we are simply calling
250    // the close for it.
251    Tracker.consumeClose();
252
253    return;
254  }
255
256  // Handle a nested namespace definition.
257  // FIXME: Preserve the source information through to the AST rather than
258  // desugaring it here.
259  ParseScope NamespaceScope(this, Scope::DeclScope);
260  UsingDirectiveDecl *ImplicitUsingDirectiveDecl = nullptr;
261  Decl *NamespcDecl = Actions.ActOnStartNamespaceDef(
262      getCurScope(), InnerNSs[index].InlineLoc, InnerNSs[index].NamespaceLoc,
263      InnerNSs[index].IdentLoc, InnerNSs[index].Ident,
264      Tracker.getOpenLocation(), attrs, ImplicitUsingDirectiveDecl);
265  assert(!ImplicitUsingDirectiveDecl &&
266         "nested namespace definition cannot define anonymous namespace");
267
268  ParseInnerNamespace(InnerNSs, ++index, InlineLoc, attrs, Tracker);
269
270  NamespaceScope.Exit();
271  Actions.ActOnFinishNamespaceDef(NamespcDecl, Tracker.getCloseLocation());
272}
273
274/// ParseNamespaceAlias - Parse the part after the '=' in a namespace
275/// alias definition.
276///
277Decl *Parser::ParseNamespaceAlias(SourceLocation NamespaceLoc,
278                                  SourceLocation AliasLoc,
279                                  IdentifierInfo *Alias,
280                                  SourceLocation &DeclEnd) {
281  assert(Tok.is(tok::equal) && "Not equal token");
282
283  ConsumeToken(); // eat the '='.
284
285  if (Tok.is(tok::code_completion)) {
286    Actions.CodeCompleteNamespaceAliasDecl(getCurScope());
287    cutOffParsing();
288    return nullptr;
289  }
290
291  CXXScopeSpec SS;
292  // Parse (optional) nested-name-specifier.
293  ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false,
294                                 /*MayBePseudoDestructor=*/nullptr,
295                                 /*IsTypename=*/false,
296                                 /*LastII=*/nullptr,
297                                 /*OnlyNamespace=*/true);
298
299  if (Tok.isNot(tok::identifier)) {
300    Diag(Tok, diag::err_expected_namespace_name);
301    // Skip to end of the definition and eat the ';'.
302    SkipUntil(tok::semi);
303    return nullptr;
304  }
305
306  if (SS.isInvalid()) {
307    // Diagnostics have been emitted in ParseOptionalCXXScopeSpecifier.
308    // Skip to end of the definition and eat the ';'.
309    SkipUntil(tok::semi);
310    return nullptr;
311  }
312
313  // Parse identifier.
314  IdentifierInfo *Ident = Tok.getIdentifierInfo();
315  SourceLocation IdentLoc = ConsumeToken();
316
317  // Eat the ';'.
318  DeclEnd = Tok.getLocation();
319  if (ExpectAndConsume(tok::semi, diag::err_expected_semi_after_namespace_name))
320    SkipUntil(tok::semi);
321
322  return Actions.ActOnNamespaceAliasDef(getCurScope(), NamespaceLoc, AliasLoc,
323                                        Alias, SS, IdentLoc, Ident);
324}
325
326/// ParseLinkage - We know that the current token is a string_literal
327/// and just before that, that extern was seen.
328///
329///       linkage-specification: [C++ 7.5p2: dcl.link]
330///         'extern' string-literal '{' declaration-seq[opt] '}'
331///         'extern' string-literal declaration
332///
333Decl *Parser::ParseLinkage(ParsingDeclSpec &DS, DeclaratorContext Context) {
334  assert(isTokenStringLiteral() && "Not a string literal!");
335  ExprResult Lang = ParseStringLiteralExpression(false);
336
337  ParseScope LinkageScope(this, Scope::DeclScope);
338  Decl *LinkageSpec =
339      Lang.isInvalid()
340          ? nullptr
341          : Actions.ActOnStartLinkageSpecification(
342                getCurScope(), DS.getSourceRange().getBegin(), Lang.get(),
343                Tok.is(tok::l_brace) ? Tok.getLocation() : SourceLocation());
344
345  ParsedAttributesWithRange attrs(AttrFactory);
346  MaybeParseCXX11Attributes(attrs);
347
348  if (Tok.isNot(tok::l_brace)) {
349    // Reset the source range in DS, as the leading "extern"
350    // does not really belong to the inner declaration ...
351    DS.SetRangeStart(SourceLocation());
352    DS.SetRangeEnd(SourceLocation());
353    // ... but anyway remember that such an "extern" was seen.
354    DS.setExternInLinkageSpec(true);
355    ParseExternalDeclaration(attrs, &DS);
356    return LinkageSpec ? Actions.ActOnFinishLinkageSpecification(
357                             getCurScope(), LinkageSpec, SourceLocation())
358                       : nullptr;
359  }
360
361  DS.abort();
362
363  ProhibitAttributes(attrs);
364
365  BalancedDelimiterTracker T(*this, tok::l_brace);
366  T.consumeOpen();
367
368  unsigned NestedModules = 0;
369  while (true) {
370    switch (Tok.getKind()) {
371    case tok::annot_module_begin:
372      ++NestedModules;
373      ParseTopLevelDecl();
374      continue;
375
376    case tok::annot_module_end:
377      if (!NestedModules)
378        break;
379      --NestedModules;
380      ParseTopLevelDecl();
381      continue;
382
383    case tok::annot_module_include:
384      ParseTopLevelDecl();
385      continue;
386
387    case tok::eof:
388      break;
389
390    case tok::r_brace:
391      if (!NestedModules)
392        break;
393      LLVM_FALLTHROUGH;
394    default:
395      ParsedAttributesWithRange attrs(AttrFactory);
396      MaybeParseCXX11Attributes(attrs);
397      ParseExternalDeclaration(attrs);
398      continue;
399    }
400
401    break;
402  }
403
404  T.consumeClose();
405  return LinkageSpec ? Actions.ActOnFinishLinkageSpecification(
406                           getCurScope(), LinkageSpec, T.getCloseLocation())
407                     : nullptr;
408}
409
410/// Parse a C++ Modules TS export-declaration.
411///
412///       export-declaration:
413///         'export' declaration
414///         'export' '{' declaration-seq[opt] '}'
415///
416Decl *Parser::ParseExportDeclaration() {
417  assert(Tok.is(tok::kw_export));
418  SourceLocation ExportLoc = ConsumeToken();
419
420  ParseScope ExportScope(this, Scope::DeclScope);
421  Decl *ExportDecl = Actions.ActOnStartExportDecl(
422      getCurScope(), ExportLoc,
423      Tok.is(tok::l_brace) ? Tok.getLocation() : SourceLocation());
424
425  if (Tok.isNot(tok::l_brace)) {
426    // FIXME: Factor out a ParseExternalDeclarationWithAttrs.
427    ParsedAttributesWithRange Attrs(AttrFactory);
428    MaybeParseCXX11Attributes(Attrs);
429    MaybeParseMicrosoftAttributes(Attrs);
430    ParseExternalDeclaration(Attrs);
431    return Actions.ActOnFinishExportDecl(getCurScope(), ExportDecl,
432                                         SourceLocation());
433  }
434
435  BalancedDelimiterTracker T(*this, tok::l_brace);
436  T.consumeOpen();
437
438  // The Modules TS draft says "An export-declaration shall declare at least one
439  // entity", but the intent is that it shall contain at least one declaration.
440  if (Tok.is(tok::r_brace) && getLangOpts().ModulesTS) {
441    Diag(ExportLoc, diag::err_export_empty)
442        << SourceRange(ExportLoc, Tok.getLocation());
443  }
444
445  while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
446         Tok.isNot(tok::eof)) {
447    ParsedAttributesWithRange Attrs(AttrFactory);
448    MaybeParseCXX11Attributes(Attrs);
449    MaybeParseMicrosoftAttributes(Attrs);
450    ParseExternalDeclaration(Attrs);
451  }
452
453  T.consumeClose();
454  return Actions.ActOnFinishExportDecl(getCurScope(), ExportDecl,
455                                       T.getCloseLocation());
456}
457
458/// ParseUsingDirectiveOrDeclaration - Parse C++ using using-declaration or
459/// using-directive. Assumes that current token is 'using'.
460Parser::DeclGroupPtrTy
461Parser::ParseUsingDirectiveOrDeclaration(DeclaratorContext Context,
462                                         const ParsedTemplateInfo &TemplateInfo,
463                                         SourceLocation &DeclEnd,
464                                         ParsedAttributesWithRange &attrs) {
465  assert(Tok.is(tok::kw_using) && "Not using token");
466  ObjCDeclContextSwitch ObjCDC(*this);
467
468  // Eat 'using'.
469  SourceLocation UsingLoc = ConsumeToken();
470
471  if (Tok.is(tok::code_completion)) {
472    Actions.CodeCompleteUsing(getCurScope());
473    cutOffParsing();
474    return nullptr;
475  }
476
477  // Consume unexpected 'template' keywords.
478  while (Tok.is(tok::kw_template)) {
479    SourceLocation TemplateLoc = ConsumeToken();
480    Diag(TemplateLoc, diag::err_unexpected_template_after_using)
481        << FixItHint::CreateRemoval(TemplateLoc);
482  }
483
484  // 'using namespace' means this is a using-directive.
485  if (Tok.is(tok::kw_namespace)) {
486    // Template parameters are always an error here.
487    if (TemplateInfo.Kind) {
488      SourceRange R = TemplateInfo.getSourceRange();
489      Diag(UsingLoc, diag::err_templated_using_directive_declaration)
490        << 0 /* directive */ << R << FixItHint::CreateRemoval(R);
491    }
492
493    Decl *UsingDir = ParseUsingDirective(Context, UsingLoc, DeclEnd, attrs);
494    return Actions.ConvertDeclToDeclGroup(UsingDir);
495  }
496
497  // Otherwise, it must be a using-declaration or an alias-declaration.
498
499  // Using declarations can't have attributes.
500  ProhibitAttributes(attrs);
501
502  return ParseUsingDeclaration(Context, TemplateInfo, UsingLoc, DeclEnd,
503                               AS_none);
504}
505
506/// ParseUsingDirective - Parse C++ using-directive, assumes
507/// that current token is 'namespace' and 'using' was already parsed.
508///
509///       using-directive: [C++ 7.3.p4: namespace.udir]
510///        'using' 'namespace' ::[opt] nested-name-specifier[opt]
511///                 namespace-name ;
512/// [GNU] using-directive:
513///        'using' 'namespace' ::[opt] nested-name-specifier[opt]
514///                 namespace-name attributes[opt] ;
515///
516Decl *Parser::ParseUsingDirective(DeclaratorContext Context,
517                                  SourceLocation UsingLoc,
518                                  SourceLocation &DeclEnd,
519                                  ParsedAttributes &attrs) {
520  assert(Tok.is(tok::kw_namespace) && "Not 'namespace' token");
521
522  // Eat 'namespace'.
523  SourceLocation NamespcLoc = ConsumeToken();
524
525  if (Tok.is(tok::code_completion)) {
526    Actions.CodeCompleteUsingDirective(getCurScope());
527    cutOffParsing();
528    return nullptr;
529  }
530
531  CXXScopeSpec SS;
532  // Parse (optional) nested-name-specifier.
533  ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false,
534                                 /*MayBePseudoDestructor=*/nullptr,
535                                 /*IsTypename=*/false,
536                                 /*LastII=*/nullptr,
537                                 /*OnlyNamespace=*/true);
538
539  IdentifierInfo *NamespcName = nullptr;
540  SourceLocation IdentLoc = SourceLocation();
541
542  // Parse namespace-name.
543  if (Tok.isNot(tok::identifier)) {
544    Diag(Tok, diag::err_expected_namespace_name);
545    // If there was invalid namespace name, skip to end of decl, and eat ';'.
546    SkipUntil(tok::semi);
547    // FIXME: Are there cases, when we would like to call ActOnUsingDirective?
548    return nullptr;
549  }
550
551  if (SS.isInvalid()) {
552    // Diagnostics have been emitted in ParseOptionalCXXScopeSpecifier.
553    // Skip to end of the definition and eat the ';'.
554    SkipUntil(tok::semi);
555    return nullptr;
556  }
557
558  // Parse identifier.
559  NamespcName = Tok.getIdentifierInfo();
560  IdentLoc = ConsumeToken();
561
562  // Parse (optional) attributes (most likely GNU strong-using extension).
563  bool GNUAttr = false;
564  if (Tok.is(tok::kw___attribute)) {
565    GNUAttr = true;
566    ParseGNUAttributes(attrs);
567  }
568
569  // Eat ';'.
570  DeclEnd = Tok.getLocation();
571  if (ExpectAndConsume(tok::semi,
572                       GNUAttr ? diag::err_expected_semi_after_attribute_list
573                               : diag::err_expected_semi_after_namespace_name))
574    SkipUntil(tok::semi);
575
576  return Actions.ActOnUsingDirective(getCurScope(), UsingLoc, NamespcLoc, SS,
577                                     IdentLoc, NamespcName, attrs);
578}
579
580/// Parse a using-declarator (or the identifier in a C++11 alias-declaration).
581///
582///     using-declarator:
583///       'typename'[opt] nested-name-specifier unqualified-id
584///
585bool Parser::ParseUsingDeclarator(DeclaratorContext Context,
586                                  UsingDeclarator &D) {
587  D.clear();
588
589  // Ignore optional 'typename'.
590  // FIXME: This is wrong; we should parse this as a typename-specifier.
591  TryConsumeToken(tok::kw_typename, D.TypenameLoc);
592
593  if (Tok.is(tok::kw___super)) {
594    Diag(Tok.getLocation(), diag::err_super_in_using_declaration);
595    return true;
596  }
597
598  // Parse nested-name-specifier.
599  IdentifierInfo *LastII = nullptr;
600  if (ParseOptionalCXXScopeSpecifier(D.SS, nullptr, /*EnteringContext=*/false,
601                                     /*MayBePseudoDtor=*/nullptr,
602                                     /*IsTypename=*/false,
603                                     /*LastII=*/&LastII,
604                                     /*OnlyNamespace=*/false,
605                                     /*InUsingDeclaration=*/true))
606
607    return true;
608  if (D.SS.isInvalid())
609    return true;
610
611  // Parse the unqualified-id. We allow parsing of both constructor and
612  // destructor names and allow the action module to diagnose any semantic
613  // errors.
614  //
615  // C++11 [class.qual]p2:
616  //   [...] in a using-declaration that is a member-declaration, if the name
617  //   specified after the nested-name-specifier is the same as the identifier
618  //   or the simple-template-id's template-name in the last component of the
619  //   nested-name-specifier, the name is [...] considered to name the
620  //   constructor.
621  if (getLangOpts().CPlusPlus11 &&
622      Context == DeclaratorContext::MemberContext &&
623      Tok.is(tok::identifier) &&
624      (NextToken().is(tok::semi) || NextToken().is(tok::comma) ||
625       NextToken().is(tok::ellipsis)) &&
626      D.SS.isNotEmpty() && LastII == Tok.getIdentifierInfo() &&
627      !D.SS.getScopeRep()->getAsNamespace() &&
628      !D.SS.getScopeRep()->getAsNamespaceAlias()) {
629    SourceLocation IdLoc = ConsumeToken();
630    ParsedType Type =
631        Actions.getInheritingConstructorName(D.SS, IdLoc, *LastII);
632    D.Name.setConstructorName(Type, IdLoc, IdLoc);
633  } else {
634    if (ParseUnqualifiedId(
635            D.SS, /*EnteringContext=*/false,
636            /*AllowDestructorName=*/true,
637            /*AllowConstructorName=*/!(Tok.is(tok::identifier) &&
638                                       NextToken().is(tok::equal)),
639            /*AllowDeductionGuide=*/false,
640            nullptr, nullptr, D.Name))
641      return true;
642  }
643
644  if (TryConsumeToken(tok::ellipsis, D.EllipsisLoc))
645    Diag(Tok.getLocation(), getLangOpts().CPlusPlus17 ?
646         diag::warn_cxx17_compat_using_declaration_pack :
647         diag::ext_using_declaration_pack);
648
649  return false;
650}
651
652/// ParseUsingDeclaration - Parse C++ using-declaration or alias-declaration.
653/// Assumes that 'using' was already seen.
654///
655///     using-declaration: [C++ 7.3.p3: namespace.udecl]
656///       'using' using-declarator-list[opt] ;
657///
658///     using-declarator-list: [C++1z]
659///       using-declarator '...'[opt]
660///       using-declarator-list ',' using-declarator '...'[opt]
661///
662///     using-declarator-list: [C++98-14]
663///       using-declarator
664///
665///     alias-declaration: C++11 [dcl.dcl]p1
666///       'using' identifier attribute-specifier-seq[opt] = type-id ;
667///
668Parser::DeclGroupPtrTy
669Parser::ParseUsingDeclaration(DeclaratorContext Context,
670                              const ParsedTemplateInfo &TemplateInfo,
671                              SourceLocation UsingLoc, SourceLocation &DeclEnd,
672                              AccessSpecifier AS) {
673  // Check for misplaced attributes before the identifier in an
674  // alias-declaration.
675  ParsedAttributesWithRange MisplacedAttrs(AttrFactory);
676  MaybeParseCXX11Attributes(MisplacedAttrs);
677
678  UsingDeclarator D;
679  bool InvalidDeclarator = ParseUsingDeclarator(Context, D);
680
681  ParsedAttributesWithRange Attrs(AttrFactory);
682  MaybeParseGNUAttributes(Attrs);
683  MaybeParseCXX11Attributes(Attrs);
684
685  // Maybe this is an alias-declaration.
686  if (Tok.is(tok::equal)) {
687    if (InvalidDeclarator) {
688      SkipUntil(tok::semi);
689      return nullptr;
690    }
691
692    // If we had any misplaced attributes from earlier, this is where they
693    // should have been written.
694    if (MisplacedAttrs.Range.isValid()) {
695      Diag(MisplacedAttrs.Range.getBegin(), diag::err_attributes_not_allowed)
696        << FixItHint::CreateInsertionFromRange(
697               Tok.getLocation(),
698               CharSourceRange::getTokenRange(MisplacedAttrs.Range))
699        << FixItHint::CreateRemoval(MisplacedAttrs.Range);
700      Attrs.takeAllFrom(MisplacedAttrs);
701    }
702
703    Decl *DeclFromDeclSpec = nullptr;
704    Decl *AD = ParseAliasDeclarationAfterDeclarator(
705        TemplateInfo, UsingLoc, D, DeclEnd, AS, Attrs, &DeclFromDeclSpec);
706    return Actions.ConvertDeclToDeclGroup(AD, DeclFromDeclSpec);
707  }
708
709  // C++11 attributes are not allowed on a using-declaration, but GNU ones
710  // are.
711  ProhibitAttributes(MisplacedAttrs);
712  ProhibitAttributes(Attrs);
713
714  // Diagnose an attempt to declare a templated using-declaration.
715  // In C++11, alias-declarations can be templates:
716  //   template <...> using id = type;
717  if (TemplateInfo.Kind) {
718    SourceRange R = TemplateInfo.getSourceRange();
719    Diag(UsingLoc, diag::err_templated_using_directive_declaration)
720      << 1 /* declaration */ << R << FixItHint::CreateRemoval(R);
721
722    // Unfortunately, we have to bail out instead of recovering by
723    // ignoring the parameters, just in case the nested name specifier
724    // depends on the parameters.
725    return nullptr;
726  }
727
728  SmallVector<Decl *, 8> DeclsInGroup;
729  while (true) {
730    // Parse (optional) attributes (most likely GNU strong-using extension).
731    MaybeParseGNUAttributes(Attrs);
732
733    if (InvalidDeclarator)
734      SkipUntil(tok::comma, tok::semi, StopBeforeMatch);
735    else {
736      // "typename" keyword is allowed for identifiers only,
737      // because it may be a type definition.
738      if (D.TypenameLoc.isValid() &&
739          D.Name.getKind() != UnqualifiedIdKind::IK_Identifier) {
740        Diag(D.Name.getSourceRange().getBegin(),
741             diag::err_typename_identifiers_only)
742            << FixItHint::CreateRemoval(SourceRange(D.TypenameLoc));
743        // Proceed parsing, but discard the typename keyword.
744        D.TypenameLoc = SourceLocation();
745      }
746
747      Decl *UD = Actions.ActOnUsingDeclaration(getCurScope(), AS, UsingLoc,
748                                               D.TypenameLoc, D.SS, D.Name,
749                                               D.EllipsisLoc, Attrs);
750      if (UD)
751        DeclsInGroup.push_back(UD);
752    }
753
754    if (!TryConsumeToken(tok::comma))
755      break;
756
757    // Parse another using-declarator.
758    Attrs.clear();
759    InvalidDeclarator = ParseUsingDeclarator(Context, D);
760  }
761
762  if (DeclsInGroup.size() > 1)
763    Diag(Tok.getLocation(), getLangOpts().CPlusPlus17 ?
764         diag::warn_cxx17_compat_multi_using_declaration :
765         diag::ext_multi_using_declaration);
766
767  // Eat ';'.
768  DeclEnd = Tok.getLocation();
769  if (ExpectAndConsume(tok::semi, diag::err_expected_after,
770                       !Attrs.empty() ? "attributes list"
771                                      : "using declaration"))
772    SkipUntil(tok::semi);
773
774  return Actions.BuildDeclaratorGroup(DeclsInGroup);
775}
776
777Decl *Parser::ParseAliasDeclarationAfterDeclarator(
778    const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc,
779    UsingDeclarator &D, SourceLocation &DeclEnd, AccessSpecifier AS,
780    ParsedAttributes &Attrs, Decl **OwnedType) {
781  if (ExpectAndConsume(tok::equal)) {
782    SkipUntil(tok::semi);
783    return nullptr;
784  }
785
786  Diag(Tok.getLocation(), getLangOpts().CPlusPlus11 ?
787       diag::warn_cxx98_compat_alias_declaration :
788       diag::ext_alias_declaration);
789
790  // Type alias templates cannot be specialized.
791  int SpecKind = -1;
792  if (TemplateInfo.Kind == ParsedTemplateInfo::Template &&
793      D.Name.getKind() == UnqualifiedIdKind::IK_TemplateId)
794    SpecKind = 0;
795  if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization)
796    SpecKind = 1;
797  if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
798    SpecKind = 2;
799  if (SpecKind != -1) {
800    SourceRange Range;
801    if (SpecKind == 0)
802      Range = SourceRange(D.Name.TemplateId->LAngleLoc,
803                          D.Name.TemplateId->RAngleLoc);
804    else
805      Range = TemplateInfo.getSourceRange();
806    Diag(Range.getBegin(), diag::err_alias_declaration_specialization)
807      << SpecKind << Range;
808    SkipUntil(tok::semi);
809    return nullptr;
810  }
811
812  // Name must be an identifier.
813  if (D.Name.getKind() != UnqualifiedIdKind::IK_Identifier) {
814    Diag(D.Name.StartLocation, diag::err_alias_declaration_not_identifier);
815    // No removal fixit: can't recover from this.
816    SkipUntil(tok::semi);
817    return nullptr;
818  } else if (D.TypenameLoc.isValid())
819    Diag(D.TypenameLoc, diag::err_alias_declaration_not_identifier)
820        << FixItHint::CreateRemoval(SourceRange(
821               D.TypenameLoc,
822               D.SS.isNotEmpty() ? D.SS.getEndLoc() : D.TypenameLoc));
823  else if (D.SS.isNotEmpty())
824    Diag(D.SS.getBeginLoc(), diag::err_alias_declaration_not_identifier)
825      << FixItHint::CreateRemoval(D.SS.getRange());
826  if (D.EllipsisLoc.isValid())
827    Diag(D.EllipsisLoc, diag::err_alias_declaration_pack_expansion)
828      << FixItHint::CreateRemoval(SourceRange(D.EllipsisLoc));
829
830  Decl *DeclFromDeclSpec = nullptr;
831  TypeResult TypeAlias = ParseTypeName(
832      nullptr,
833      TemplateInfo.Kind ? DeclaratorContext::AliasTemplateContext
834                        : DeclaratorContext::AliasDeclContext,
835      AS, &DeclFromDeclSpec, &Attrs);
836  if (OwnedType)
837    *OwnedType = DeclFromDeclSpec;
838
839  // Eat ';'.
840  DeclEnd = Tok.getLocation();
841  if (ExpectAndConsume(tok::semi, diag::err_expected_after,
842                       !Attrs.empty() ? "attributes list"
843                                      : "alias declaration"))
844    SkipUntil(tok::semi);
845
846  TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
847  MultiTemplateParamsArg TemplateParamsArg(
848    TemplateParams ? TemplateParams->data() : nullptr,
849    TemplateParams ? TemplateParams->size() : 0);
850  return Actions.ActOnAliasDeclaration(getCurScope(), AS, TemplateParamsArg,
851                                       UsingLoc, D.Name, Attrs, TypeAlias,
852                                       DeclFromDeclSpec);
853}
854
855/// ParseStaticAssertDeclaration - Parse C++0x or C11 static_assert-declaration.
856///
857/// [C++0x] static_assert-declaration:
858///           static_assert ( constant-expression  ,  string-literal  ) ;
859///
860/// [C11]   static_assert-declaration:
861///           _Static_assert ( constant-expression  ,  string-literal  ) ;
862///
863Decl *Parser::ParseStaticAssertDeclaration(SourceLocation &DeclEnd){
864  assert(Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert) &&
865         "Not a static_assert declaration");
866
867  if (Tok.is(tok::kw__Static_assert) && !getLangOpts().C11)
868    Diag(Tok, diag::ext_c11_feature) << Tok.getName();
869  if (Tok.is(tok::kw_static_assert))
870    Diag(Tok, diag::warn_cxx98_compat_static_assert);
871
872  SourceLocation StaticAssertLoc = ConsumeToken();
873
874  BalancedDelimiterTracker T(*this, tok::l_paren);
875  if (T.consumeOpen()) {
876    Diag(Tok, diag::err_expected) << tok::l_paren;
877    SkipMalformedDecl();
878    return nullptr;
879  }
880
881  EnterExpressionEvaluationContext ConstantEvaluated(
882      Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
883  ExprResult AssertExpr(ParseConstantExpressionInExprEvalContext());
884  if (AssertExpr.isInvalid()) {
885    SkipMalformedDecl();
886    return nullptr;
887  }
888
889  ExprResult AssertMessage;
890  if (Tok.is(tok::r_paren)) {
891    Diag(Tok, getLangOpts().CPlusPlus17
892                  ? diag::warn_cxx14_compat_static_assert_no_message
893                  : diag::ext_static_assert_no_message)
894      << (getLangOpts().CPlusPlus17
895              ? FixItHint()
896              : FixItHint::CreateInsertion(Tok.getLocation(), ", \"\""));
897  } else {
898    if (ExpectAndConsume(tok::comma)) {
899      SkipUntil(tok::semi);
900      return nullptr;
901    }
902
903    if (!isTokenStringLiteral()) {
904      Diag(Tok, diag::err_expected_string_literal)
905        << /*Source='static_assert'*/1;
906      SkipMalformedDecl();
907      return nullptr;
908    }
909
910    AssertMessage = ParseStringLiteralExpression();
911    if (AssertMessage.isInvalid()) {
912      SkipMalformedDecl();
913      return nullptr;
914    }
915  }
916
917  T.consumeClose();
918
919  DeclEnd = Tok.getLocation();
920  ExpectAndConsumeSemi(diag::err_expected_semi_after_static_assert);
921
922  return Actions.ActOnStaticAssertDeclaration(StaticAssertLoc,
923                                              AssertExpr.get(),
924                                              AssertMessage.get(),
925                                              T.getCloseLocation());
926}
927
928/// ParseDecltypeSpecifier - Parse a C++11 decltype specifier.
929///
930/// 'decltype' ( expression )
931/// 'decltype' ( 'auto' )      [C++1y]
932///
933SourceLocation Parser::ParseDecltypeSpecifier(DeclSpec &DS) {
934  assert(Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)
935           && "Not a decltype specifier");
936
937  ExprResult Result;
938  SourceLocation StartLoc = Tok.getLocation();
939  SourceLocation EndLoc;
940
941  if (Tok.is(tok::annot_decltype)) {
942    Result = getExprAnnotation(Tok);
943    EndLoc = Tok.getAnnotationEndLoc();
944    ConsumeAnnotationToken();
945    if (Result.isInvalid()) {
946      DS.SetTypeSpecError();
947      return EndLoc;
948    }
949  } else {
950    if (Tok.getIdentifierInfo()->isStr("decltype"))
951      Diag(Tok, diag::warn_cxx98_compat_decltype);
952
953    ConsumeToken();
954
955    BalancedDelimiterTracker T(*this, tok::l_paren);
956    if (T.expectAndConsume(diag::err_expected_lparen_after,
957                           "decltype", tok::r_paren)) {
958      DS.SetTypeSpecError();
959      return T.getOpenLocation() == Tok.getLocation() ?
960             StartLoc : T.getOpenLocation();
961    }
962
963    // Check for C++1y 'decltype(auto)'.
964    if (Tok.is(tok::kw_auto)) {
965      // No need to disambiguate here: an expression can't start with 'auto',
966      // because the typename-specifier in a function-style cast operation can't
967      // be 'auto'.
968      Diag(Tok.getLocation(),
969           getLangOpts().CPlusPlus14
970             ? diag::warn_cxx11_compat_decltype_auto_type_specifier
971             : diag::ext_decltype_auto_type_specifier);
972      ConsumeToken();
973    } else {
974      // Parse the expression
975
976      // C++11 [dcl.type.simple]p4:
977      //   The operand of the decltype specifier is an unevaluated operand.
978      EnterExpressionEvaluationContext Unevaluated(
979          Actions, Sema::ExpressionEvaluationContext::Unevaluated, nullptr,
980          Sema::ExpressionEvaluationContextRecord::EK_Decltype);
981      Result =
982          Actions.CorrectDelayedTyposInExpr(ParseExpression(), [](Expr *E) {
983            return E->hasPlaceholderType() ? ExprError() : E;
984          });
985      if (Result.isInvalid()) {
986        DS.SetTypeSpecError();
987        if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch)) {
988          EndLoc = ConsumeParen();
989        } else {
990          if (PP.isBacktrackEnabled() && Tok.is(tok::semi)) {
991            // Backtrack to get the location of the last token before the semi.
992            PP.RevertCachedTokens(2);
993            ConsumeToken(); // the semi.
994            EndLoc = ConsumeAnyToken();
995            assert(Tok.is(tok::semi));
996          } else {
997            EndLoc = Tok.getLocation();
998          }
999        }
1000        return EndLoc;
1001      }
1002
1003      Result = Actions.ActOnDecltypeExpression(Result.get());
1004    }
1005
1006    // Match the ')'
1007    T.consumeClose();
1008    if (T.getCloseLocation().isInvalid()) {
1009      DS.SetTypeSpecError();
1010      // FIXME: this should return the location of the last token
1011      //        that was consumed (by "consumeClose()")
1012      return T.getCloseLocation();
1013    }
1014
1015    if (Result.isInvalid()) {
1016      DS.SetTypeSpecError();
1017      return T.getCloseLocation();
1018    }
1019
1020    EndLoc = T.getCloseLocation();
1021  }
1022  assert(!Result.isInvalid());
1023
1024  const char *PrevSpec = nullptr;
1025  unsigned DiagID;
1026  const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
1027  // Check for duplicate type specifiers (e.g. "int decltype(a)").
1028  if (Result.get()
1029        ? DS.SetTypeSpecType(DeclSpec::TST_decltype, StartLoc, PrevSpec,
1030                             DiagID, Result.get(), Policy)
1031        : DS.SetTypeSpecType(DeclSpec::TST_decltype_auto, StartLoc, PrevSpec,
1032                             DiagID, Policy)) {
1033    Diag(StartLoc, DiagID) << PrevSpec;
1034    DS.SetTypeSpecError();
1035  }
1036  return EndLoc;
1037}
1038
1039void Parser::AnnotateExistingDecltypeSpecifier(const DeclSpec& DS,
1040                                               SourceLocation StartLoc,
1041                                               SourceLocation EndLoc) {
1042  // make sure we have a token we can turn into an annotation token
1043  if (PP.isBacktrackEnabled())
1044    PP.RevertCachedTokens(1);
1045  else
1046    PP.EnterToken(Tok, /*IsReinject*/true);
1047
1048  Tok.setKind(tok::annot_decltype);
1049  setExprAnnotation(Tok,
1050                    DS.getTypeSpecType() == TST_decltype ? DS.getRepAsExpr() :
1051                    DS.getTypeSpecType() == TST_decltype_auto ? ExprResult() :
1052                    ExprError());
1053  Tok.setAnnotationEndLoc(EndLoc);
1054  Tok.setLocation(StartLoc);
1055  PP.AnnotateCachedTokens(Tok);
1056}
1057
1058void Parser::ParseUnderlyingTypeSpecifier(DeclSpec &DS) {
1059  assert(Tok.is(tok::kw___underlying_type) &&
1060         "Not an underlying type specifier");
1061
1062  SourceLocation StartLoc = ConsumeToken();
1063  BalancedDelimiterTracker T(*this, tok::l_paren);
1064  if (T.expectAndConsume(diag::err_expected_lparen_after,
1065                       "__underlying_type", tok::r_paren)) {
1066    return;
1067  }
1068
1069  TypeResult Result = ParseTypeName();
1070  if (Result.isInvalid()) {
1071    SkipUntil(tok::r_paren, StopAtSemi);
1072    return;
1073  }
1074
1075  // Match the ')'
1076  T.consumeClose();
1077  if (T.getCloseLocation().isInvalid())
1078    return;
1079
1080  const char *PrevSpec = nullptr;
1081  unsigned DiagID;
1082  if (DS.SetTypeSpecType(DeclSpec::TST_underlyingType, StartLoc, PrevSpec,
1083                         DiagID, Result.get(),
1084                         Actions.getASTContext().getPrintingPolicy()))
1085    Diag(StartLoc, DiagID) << PrevSpec;
1086  DS.setTypeofParensRange(T.getRange());
1087}
1088
1089/// ParseBaseTypeSpecifier - Parse a C++ base-type-specifier which is either a
1090/// class name or decltype-specifier. Note that we only check that the result
1091/// names a type; semantic analysis will need to verify that the type names a
1092/// class. The result is either a type or null, depending on whether a type
1093/// name was found.
1094///
1095///       base-type-specifier: [C++11 class.derived]
1096///         class-or-decltype
1097///       class-or-decltype: [C++11 class.derived]
1098///         nested-name-specifier[opt] class-name
1099///         decltype-specifier
1100///       class-name: [C++ class.name]
1101///         identifier
1102///         simple-template-id
1103///
1104/// In C++98, instead of base-type-specifier, we have:
1105///
1106///         ::[opt] nested-name-specifier[opt] class-name
1107TypeResult Parser::ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
1108                                          SourceLocation &EndLocation) {
1109  // Ignore attempts to use typename
1110  if (Tok.is(tok::kw_typename)) {
1111    Diag(Tok, diag::err_expected_class_name_not_template)
1112      << FixItHint::CreateRemoval(Tok.getLocation());
1113    ConsumeToken();
1114  }
1115
1116  // Parse optional nested-name-specifier
1117  CXXScopeSpec SS;
1118  if (ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false))
1119    return true;
1120
1121  BaseLoc = Tok.getLocation();
1122
1123  // Parse decltype-specifier
1124  // tok == kw_decltype is just error recovery, it can only happen when SS
1125  // isn't empty
1126  if (Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)) {
1127    if (SS.isNotEmpty())
1128      Diag(SS.getBeginLoc(), diag::err_unexpected_scope_on_base_decltype)
1129        << FixItHint::CreateRemoval(SS.getRange());
1130    // Fake up a Declarator to use with ActOnTypeName.
1131    DeclSpec DS(AttrFactory);
1132
1133    EndLocation = ParseDecltypeSpecifier(DS);
1134
1135    Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
1136    return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
1137  }
1138
1139  // Check whether we have a template-id that names a type.
1140  if (Tok.is(tok::annot_template_id)) {
1141    TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1142    if (TemplateId->Kind == TNK_Type_template ||
1143        TemplateId->Kind == TNK_Dependent_template_name ||
1144        TemplateId->Kind == TNK_Undeclared_template) {
1145      AnnotateTemplateIdTokenAsType(/*IsClassName*/true);
1146
1147      assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
1148      ParsedType Type = getTypeAnnotation(Tok);
1149      EndLocation = Tok.getAnnotationEndLoc();
1150      ConsumeAnnotationToken();
1151
1152      if (Type)
1153        return Type;
1154      return true;
1155    }
1156
1157    // Fall through to produce an error below.
1158  }
1159
1160  if (Tok.isNot(tok::identifier)) {
1161    Diag(Tok, diag::err_expected_class_name);
1162    return true;
1163  }
1164
1165  IdentifierInfo *Id = Tok.getIdentifierInfo();
1166  SourceLocation IdLoc = ConsumeToken();
1167
1168  if (Tok.is(tok::less)) {
1169    // It looks the user intended to write a template-id here, but the
1170    // template-name was wrong. Try to fix that.
1171    TemplateNameKind TNK = TNK_Type_template;
1172    TemplateTy Template;
1173    if (!Actions.DiagnoseUnknownTemplateName(*Id, IdLoc, getCurScope(),
1174                                             &SS, Template, TNK)) {
1175      Diag(IdLoc, diag::err_unknown_template_name)
1176        << Id;
1177    }
1178
1179    if (!Template) {
1180      TemplateArgList TemplateArgs;
1181      SourceLocation LAngleLoc, RAngleLoc;
1182      ParseTemplateIdAfterTemplateName(true, LAngleLoc, TemplateArgs,
1183                                       RAngleLoc);
1184      return true;
1185    }
1186
1187    // Form the template name
1188    UnqualifiedId TemplateName;
1189    TemplateName.setIdentifier(Id, IdLoc);
1190
1191    // Parse the full template-id, then turn it into a type.
1192    if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
1193                                TemplateName))
1194      return true;
1195    if (TNK == TNK_Type_template || TNK == TNK_Dependent_template_name)
1196      AnnotateTemplateIdTokenAsType(/*IsClassName*/true);
1197
1198    // If we didn't end up with a typename token, there's nothing more we
1199    // can do.
1200    if (Tok.isNot(tok::annot_typename))
1201      return true;
1202
1203    // Retrieve the type from the annotation token, consume that token, and
1204    // return.
1205    EndLocation = Tok.getAnnotationEndLoc();
1206    ParsedType Type = getTypeAnnotation(Tok);
1207    ConsumeAnnotationToken();
1208    return Type;
1209  }
1210
1211  // We have an identifier; check whether it is actually a type.
1212  IdentifierInfo *CorrectedII = nullptr;
1213  ParsedType Type = Actions.getTypeName(
1214      *Id, IdLoc, getCurScope(), &SS, /*isClassName=*/true, false, nullptr,
1215      /*IsCtorOrDtorName=*/false,
1216      /*WantNontrivialTypeSourceInfo=*/true,
1217      /*IsClassTemplateDeductionContext*/ false, &CorrectedII);
1218  if (!Type) {
1219    Diag(IdLoc, diag::err_expected_class_name);
1220    return true;
1221  }
1222
1223  // Consume the identifier.
1224  EndLocation = IdLoc;
1225
1226  // Fake up a Declarator to use with ActOnTypeName.
1227  DeclSpec DS(AttrFactory);
1228  DS.SetRangeStart(IdLoc);
1229  DS.SetRangeEnd(EndLocation);
1230  DS.getTypeSpecScope() = SS;
1231
1232  const char *PrevSpec = nullptr;
1233  unsigned DiagID;
1234  DS.SetTypeSpecType(TST_typename, IdLoc, PrevSpec, DiagID, Type,
1235                     Actions.getASTContext().getPrintingPolicy());
1236
1237  Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
1238  return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
1239}
1240
1241void Parser::ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs) {
1242  while (Tok.isOneOf(tok::kw___single_inheritance,
1243                     tok::kw___multiple_inheritance,
1244                     tok::kw___virtual_inheritance)) {
1245    IdentifierInfo *AttrName = Tok.getIdentifierInfo();
1246    SourceLocation AttrNameLoc = ConsumeToken();
1247    attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
1248                 ParsedAttr::AS_Keyword);
1249  }
1250}
1251
1252/// Determine whether the following tokens are valid after a type-specifier
1253/// which could be a standalone declaration. This will conservatively return
1254/// true if there's any doubt, and is appropriate for insert-';' fixits.
1255bool Parser::isValidAfterTypeSpecifier(bool CouldBeBitfield) {
1256  // This switch enumerates the valid "follow" set for type-specifiers.
1257  switch (Tok.getKind()) {
1258  default: break;
1259  case tok::semi:               // struct foo {...} ;
1260  case tok::star:               // struct foo {...} *         P;
1261  case tok::amp:                // struct foo {...} &         R = ...
1262  case tok::ampamp:             // struct foo {...} &&        R = ...
1263  case tok::identifier:         // struct foo {...} V         ;
1264  case tok::r_paren:            //(struct foo {...} )         {4}
1265  case tok::coloncolon:         // struct foo {...} ::        a::b;
1266  case tok::annot_cxxscope:     // struct foo {...} a::       b;
1267  case tok::annot_typename:     // struct foo {...} a         ::b;
1268  case tok::annot_template_id:  // struct foo {...} a<int>    ::b;
1269  case tok::kw_decltype:        // struct foo {...} decltype  (a)::b;
1270  case tok::l_paren:            // struct foo {...} (         x);
1271  case tok::comma:              // __builtin_offsetof(struct foo{...} ,
1272  case tok::kw_operator:        // struct foo       operator  ++() {...}
1273  case tok::kw___declspec:      // struct foo {...} __declspec(...)
1274  case tok::l_square:           // void f(struct f  [         3])
1275  case tok::ellipsis:           // void f(struct f  ...       [Ns])
1276  // FIXME: we should emit semantic diagnostic when declaration
1277  // attribute is in type attribute position.
1278  case tok::kw___attribute:     // struct foo __attribute__((used)) x;
1279  case tok::annot_pragma_pack:  // struct foo {...} _Pragma(pack(pop));
1280  // struct foo {...} _Pragma(section(...));
1281  case tok::annot_pragma_ms_pragma:
1282  // struct foo {...} _Pragma(vtordisp(pop));
1283  case tok::annot_pragma_ms_vtordisp:
1284  // struct foo {...} _Pragma(pointers_to_members(...));
1285  case tok::annot_pragma_ms_pointers_to_members:
1286    return true;
1287  case tok::colon:
1288    return CouldBeBitfield;     // enum E { ... }   :         2;
1289  // Microsoft compatibility
1290  case tok::kw___cdecl:         // struct foo {...} __cdecl      x;
1291  case tok::kw___fastcall:      // struct foo {...} __fastcall   x;
1292  case tok::kw___stdcall:       // struct foo {...} __stdcall    x;
1293  case tok::kw___thiscall:      // struct foo {...} __thiscall   x;
1294  case tok::kw___vectorcall:    // struct foo {...} __vectorcall x;
1295    // We will diagnose these calling-convention specifiers on non-function
1296    // declarations later, so claim they are valid after a type specifier.
1297    return getLangOpts().MicrosoftExt;
1298  // Type qualifiers
1299  case tok::kw_const:           // struct foo {...} const     x;
1300  case tok::kw_volatile:        // struct foo {...} volatile  x;
1301  case tok::kw_restrict:        // struct foo {...} restrict  x;
1302  case tok::kw__Atomic:         // struct foo {...} _Atomic   x;
1303  case tok::kw___unaligned:     // struct foo {...} __unaligned *x;
1304  // Function specifiers
1305  // Note, no 'explicit'. An explicit function must be either a conversion
1306  // operator or a constructor. Either way, it can't have a return type.
1307  case tok::kw_inline:          // struct foo       inline    f();
1308  case tok::kw_virtual:         // struct foo       virtual   f();
1309  case tok::kw_friend:          // struct foo       friend    f();
1310  // Storage-class specifiers
1311  case tok::kw_static:          // struct foo {...} static    x;
1312  case tok::kw_extern:          // struct foo {...} extern    x;
1313  case tok::kw_typedef:         // struct foo {...} typedef   x;
1314  case tok::kw_register:        // struct foo {...} register  x;
1315  case tok::kw_auto:            // struct foo {...} auto      x;
1316  case tok::kw_mutable:         // struct foo {...} mutable   x;
1317  case tok::kw_thread_local:    // struct foo {...} thread_local x;
1318  case tok::kw_constexpr:       // struct foo {...} constexpr x;
1319  case tok::kw_consteval:       // struct foo {...} consteval x;
1320  case tok::kw_constinit:       // struct foo {...} constinit x;
1321    // As shown above, type qualifiers and storage class specifiers absolutely
1322    // can occur after class specifiers according to the grammar.  However,
1323    // almost no one actually writes code like this.  If we see one of these,
1324    // it is much more likely that someone missed a semi colon and the
1325    // type/storage class specifier we're seeing is part of the *next*
1326    // intended declaration, as in:
1327    //
1328    //   struct foo { ... }
1329    //   typedef int X;
1330    //
1331    // We'd really like to emit a missing semicolon error instead of emitting
1332    // an error on the 'int' saying that you can't have two type specifiers in
1333    // the same declaration of X.  Because of this, we look ahead past this
1334    // token to see if it's a type specifier.  If so, we know the code is
1335    // otherwise invalid, so we can produce the expected semi error.
1336    if (!isKnownToBeTypeSpecifier(NextToken()))
1337      return true;
1338    break;
1339  case tok::r_brace:  // struct bar { struct foo {...} }
1340    // Missing ';' at end of struct is accepted as an extension in C mode.
1341    if (!getLangOpts().CPlusPlus)
1342      return true;
1343    break;
1344  case tok::greater:
1345    // template<class T = class X>
1346    return getLangOpts().CPlusPlus;
1347  }
1348  return false;
1349}
1350
1351/// ParseClassSpecifier - Parse a C++ class-specifier [C++ class] or
1352/// elaborated-type-specifier [C++ dcl.type.elab]; we can't tell which
1353/// until we reach the start of a definition or see a token that
1354/// cannot start a definition.
1355///
1356///       class-specifier: [C++ class]
1357///         class-head '{' member-specification[opt] '}'
1358///         class-head '{' member-specification[opt] '}' attributes[opt]
1359///       class-head:
1360///         class-key identifier[opt] base-clause[opt]
1361///         class-key nested-name-specifier identifier base-clause[opt]
1362///         class-key nested-name-specifier[opt] simple-template-id
1363///                          base-clause[opt]
1364/// [GNU]   class-key attributes[opt] identifier[opt] base-clause[opt]
1365/// [GNU]   class-key attributes[opt] nested-name-specifier
1366///                          identifier base-clause[opt]
1367/// [GNU]   class-key attributes[opt] nested-name-specifier[opt]
1368///                          simple-template-id base-clause[opt]
1369///       class-key:
1370///         'class'
1371///         'struct'
1372///         'union'
1373///
1374///       elaborated-type-specifier: [C++ dcl.type.elab]
1375///         class-key ::[opt] nested-name-specifier[opt] identifier
1376///         class-key ::[opt] nested-name-specifier[opt] 'template'[opt]
1377///                          simple-template-id
1378///
1379///  Note that the C++ class-specifier and elaborated-type-specifier,
1380///  together, subsume the C99 struct-or-union-specifier:
1381///
1382///       struct-or-union-specifier: [C99 6.7.2.1]
1383///         struct-or-union identifier[opt] '{' struct-contents '}'
1384///         struct-or-union identifier
1385/// [GNU]   struct-or-union attributes[opt] identifier[opt] '{' struct-contents
1386///                                                         '}' attributes[opt]
1387/// [GNU]   struct-or-union attributes[opt] identifier
1388///       struct-or-union:
1389///         'struct'
1390///         'union'
1391void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind,
1392                                 SourceLocation StartLoc, DeclSpec &DS,
1393                                 const ParsedTemplateInfo &TemplateInfo,
1394                                 AccessSpecifier AS,
1395                                 bool EnteringContext, DeclSpecContext DSC,
1396                                 ParsedAttributesWithRange &Attributes) {
1397  DeclSpec::TST TagType;
1398  if (TagTokKind == tok::kw_struct)
1399    TagType = DeclSpec::TST_struct;
1400  else if (TagTokKind == tok::kw___interface)
1401    TagType = DeclSpec::TST_interface;
1402  else if (TagTokKind == tok::kw_class)
1403    TagType = DeclSpec::TST_class;
1404  else {
1405    assert(TagTokKind == tok::kw_union && "Not a class specifier");
1406    TagType = DeclSpec::TST_union;
1407  }
1408
1409  if (Tok.is(tok::code_completion)) {
1410    // Code completion for a struct, class, or union name.
1411    Actions.CodeCompleteTag(getCurScope(), TagType);
1412    return cutOffParsing();
1413  }
1414
1415  // C++03 [temp.explicit] 14.7.2/8:
1416  //   The usual access checking rules do not apply to names used to specify
1417  //   explicit instantiations.
1418  //
1419  // As an extension we do not perform access checking on the names used to
1420  // specify explicit specializations either. This is important to allow
1421  // specializing traits classes for private types.
1422  //
1423  // Note that we don't suppress if this turns out to be an elaborated
1424  // type specifier.
1425  bool shouldDelayDiagsInTag =
1426    (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
1427     TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
1428  SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
1429
1430  ParsedAttributesWithRange attrs(AttrFactory);
1431  // If attributes exist after tag, parse them.
1432  MaybeParseGNUAttributes(attrs);
1433  MaybeParseMicrosoftDeclSpecs(attrs);
1434
1435  // Parse inheritance specifiers.
1436  if (Tok.isOneOf(tok::kw___single_inheritance,
1437                  tok::kw___multiple_inheritance,
1438                  tok::kw___virtual_inheritance))
1439    ParseMicrosoftInheritanceClassAttributes(attrs);
1440
1441  // If C++0x attributes exist here, parse them.
1442  // FIXME: Are we consistent with the ordering of parsing of different
1443  // styles of attributes?
1444  MaybeParseCXX11Attributes(attrs);
1445
1446  // Source location used by FIXIT to insert misplaced
1447  // C++11 attributes
1448  SourceLocation AttrFixitLoc = Tok.getLocation();
1449
1450  if (TagType == DeclSpec::TST_struct &&
1451      Tok.isNot(tok::identifier) &&
1452      !Tok.isAnnotation() &&
1453      Tok.getIdentifierInfo() &&
1454      Tok.isOneOf(tok::kw___is_abstract,
1455                  tok::kw___is_aggregate,
1456                  tok::kw___is_arithmetic,
1457                  tok::kw___is_array,
1458                  tok::kw___is_assignable,
1459                  tok::kw___is_base_of,
1460                  tok::kw___is_class,
1461                  tok::kw___is_complete_type,
1462                  tok::kw___is_compound,
1463                  tok::kw___is_const,
1464                  tok::kw___is_constructible,
1465                  tok::kw___is_convertible,
1466                  tok::kw___is_convertible_to,
1467                  tok::kw___is_destructible,
1468                  tok::kw___is_empty,
1469                  tok::kw___is_enum,
1470                  tok::kw___is_floating_point,
1471                  tok::kw___is_final,
1472                  tok::kw___is_function,
1473                  tok::kw___is_fundamental,
1474                  tok::kw___is_integral,
1475                  tok::kw___is_interface_class,
1476                  tok::kw___is_literal,
1477                  tok::kw___is_lvalue_expr,
1478                  tok::kw___is_lvalue_reference,
1479                  tok::kw___is_member_function_pointer,
1480                  tok::kw___is_member_object_pointer,
1481                  tok::kw___is_member_pointer,
1482                  tok::kw___is_nothrow_assignable,
1483                  tok::kw___is_nothrow_constructible,
1484                  tok::kw___is_nothrow_destructible,
1485                  tok::kw___is_object,
1486                  tok::kw___is_pod,
1487                  tok::kw___is_pointer,
1488                  tok::kw___is_polymorphic,
1489                  tok::kw___is_reference,
1490                  tok::kw___is_rvalue_expr,
1491                  tok::kw___is_rvalue_reference,
1492                  tok::kw___is_same,
1493                  tok::kw___is_scalar,
1494                  tok::kw___is_sealed,
1495                  tok::kw___is_signed,
1496                  tok::kw___is_standard_layout,
1497                  tok::kw___is_trivial,
1498                  tok::kw___is_trivially_assignable,
1499                  tok::kw___is_trivially_constructible,
1500                  tok::kw___is_trivially_copyable,
1501                  tok::kw___is_union,
1502                  tok::kw___is_unsigned,
1503                  tok::kw___is_void,
1504                  tok::kw___is_volatile))
1505    // GNU libstdc++ 4.2 and libc++ use certain intrinsic names as the
1506    // name of struct templates, but some are keywords in GCC >= 4.3
1507    // and Clang. Therefore, when we see the token sequence "struct
1508    // X", make X into a normal identifier rather than a keyword, to
1509    // allow libstdc++ 4.2 and libc++ to work properly.
1510    TryKeywordIdentFallback(true);
1511
1512  struct PreserveAtomicIdentifierInfoRAII {
1513    PreserveAtomicIdentifierInfoRAII(Token &Tok, bool Enabled)
1514        : AtomicII(nullptr) {
1515      if (!Enabled)
1516        return;
1517      assert(Tok.is(tok::kw__Atomic));
1518      AtomicII = Tok.getIdentifierInfo();
1519      AtomicII->revertTokenIDToIdentifier();
1520      Tok.setKind(tok::identifier);
1521    }
1522    ~PreserveAtomicIdentifierInfoRAII() {
1523      if (!AtomicII)
1524        return;
1525      AtomicII->revertIdentifierToTokenID(tok::kw__Atomic);
1526    }
1527    IdentifierInfo *AtomicII;
1528  };
1529
1530  // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
1531  // implementation for VS2013 uses _Atomic as an identifier for one of the
1532  // classes in <atomic>.  When we are parsing 'struct _Atomic', don't consider
1533  // '_Atomic' to be a keyword.  We are careful to undo this so that clang can
1534  // use '_Atomic' in its own header files.
1535  bool ShouldChangeAtomicToIdentifier = getLangOpts().MSVCCompat &&
1536                                        Tok.is(tok::kw__Atomic) &&
1537                                        TagType == DeclSpec::TST_struct;
1538  PreserveAtomicIdentifierInfoRAII AtomicTokenGuard(
1539      Tok, ShouldChangeAtomicToIdentifier);
1540
1541  // Parse the (optional) nested-name-specifier.
1542  CXXScopeSpec &SS = DS.getTypeSpecScope();
1543  if (getLangOpts().CPlusPlus) {
1544    // "FOO : BAR" is not a potential typo for "FOO::BAR".  In this context it
1545    // is a base-specifier-list.
1546    ColonProtectionRAIIObject X(*this);
1547
1548    CXXScopeSpec Spec;
1549    bool HasValidSpec = true;
1550    if (ParseOptionalCXXScopeSpecifier(Spec, nullptr, EnteringContext)) {
1551      DS.SetTypeSpecError();
1552      HasValidSpec = false;
1553    }
1554    if (Spec.isSet())
1555      if (Tok.isNot(tok::identifier) && Tok.isNot(tok::annot_template_id)) {
1556        Diag(Tok, diag::err_expected) << tok::identifier;
1557        HasValidSpec = false;
1558      }
1559    if (HasValidSpec)
1560      SS = Spec;
1561  }
1562
1563  TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
1564
1565  auto RecoverFromUndeclaredTemplateName = [&](IdentifierInfo *Name,
1566                                               SourceLocation NameLoc,
1567                                               SourceRange TemplateArgRange,
1568                                               bool KnownUndeclared) {
1569    Diag(NameLoc, diag::err_explicit_spec_non_template)
1570        << (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
1571        << TagTokKind << Name << TemplateArgRange << KnownUndeclared;
1572
1573    // Strip off the last template parameter list if it was empty, since
1574    // we've removed its template argument list.
1575    if (TemplateParams && TemplateInfo.LastParameterListWasEmpty) {
1576      if (TemplateParams->size() > 1) {
1577        TemplateParams->pop_back();
1578      } else {
1579        TemplateParams = nullptr;
1580        const_cast<ParsedTemplateInfo &>(TemplateInfo).Kind =
1581            ParsedTemplateInfo::NonTemplate;
1582      }
1583    } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1584      // Pretend this is just a forward declaration.
1585      TemplateParams = nullptr;
1586      const_cast<ParsedTemplateInfo &>(TemplateInfo).Kind =
1587          ParsedTemplateInfo::NonTemplate;
1588      const_cast<ParsedTemplateInfo &>(TemplateInfo).TemplateLoc =
1589          SourceLocation();
1590      const_cast<ParsedTemplateInfo &>(TemplateInfo).ExternLoc =
1591          SourceLocation();
1592    }
1593  };
1594
1595  // Parse the (optional) class name or simple-template-id.
1596  IdentifierInfo *Name = nullptr;
1597  SourceLocation NameLoc;
1598  TemplateIdAnnotation *TemplateId = nullptr;
1599  if (Tok.is(tok::identifier)) {
1600    Name = Tok.getIdentifierInfo();
1601    NameLoc = ConsumeToken();
1602
1603    if (Tok.is(tok::less) && getLangOpts().CPlusPlus) {
1604      // The name was supposed to refer to a template, but didn't.
1605      // Eat the template argument list and try to continue parsing this as
1606      // a class (or template thereof).
1607      TemplateArgList TemplateArgs;
1608      SourceLocation LAngleLoc, RAngleLoc;
1609      if (ParseTemplateIdAfterTemplateName(true, LAngleLoc, TemplateArgs,
1610                                           RAngleLoc)) {
1611        // We couldn't parse the template argument list at all, so don't
1612        // try to give any location information for the list.
1613        LAngleLoc = RAngleLoc = SourceLocation();
1614      }
1615      RecoverFromUndeclaredTemplateName(
1616          Name, NameLoc, SourceRange(LAngleLoc, RAngleLoc), false);
1617    }
1618  } else if (Tok.is(tok::annot_template_id)) {
1619    TemplateId = takeTemplateIdAnnotation(Tok);
1620    NameLoc = ConsumeAnnotationToken();
1621
1622    if (TemplateId->Kind == TNK_Undeclared_template) {
1623      // Try to resolve the template name to a type template.
1624      Actions.ActOnUndeclaredTypeTemplateName(getCurScope(), TemplateId->Template,
1625                                              TemplateId->Kind, NameLoc, Name);
1626      if (TemplateId->Kind == TNK_Undeclared_template) {
1627        RecoverFromUndeclaredTemplateName(
1628            Name, NameLoc,
1629            SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc), true);
1630        TemplateId = nullptr;
1631      }
1632    }
1633
1634    if (TemplateId && TemplateId->Kind != TNK_Type_template &&
1635        TemplateId->Kind != TNK_Dependent_template_name) {
1636      // The template-name in the simple-template-id refers to
1637      // something other than a class template. Give an appropriate
1638      // error message and skip to the ';'.
1639      SourceRange Range(NameLoc);
1640      if (SS.isNotEmpty())
1641        Range.setBegin(SS.getBeginLoc());
1642
1643      // FIXME: Name may be null here.
1644      Diag(TemplateId->LAngleLoc, diag::err_template_spec_syntax_non_template)
1645          << TemplateId->Name << static_cast<int>(TemplateId->Kind) << Range;
1646
1647      DS.SetTypeSpecError();
1648      SkipUntil(tok::semi, StopBeforeMatch);
1649      return;
1650    }
1651  }
1652
1653  // There are four options here.
1654  //  - If we are in a trailing return type, this is always just a reference,
1655  //    and we must not try to parse a definition. For instance,
1656  //      [] () -> struct S { };
1657  //    does not define a type.
1658  //  - If we have 'struct foo {...', 'struct foo :...',
1659  //    'struct foo final :' or 'struct foo final {', then this is a definition.
1660  //  - If we have 'struct foo;', then this is either a forward declaration
1661  //    or a friend declaration, which have to be treated differently.
1662  //  - Otherwise we have something like 'struct foo xyz', a reference.
1663  //
1664  //  We also detect these erroneous cases to provide better diagnostic for
1665  //  C++11 attributes parsing.
1666  //  - attributes follow class name:
1667  //    struct foo [[]] {};
1668  //  - attributes appear before or after 'final':
1669  //    struct foo [[]] final [[]] {};
1670  //
1671  // However, in type-specifier-seq's, things look like declarations but are
1672  // just references, e.g.
1673  //   new struct s;
1674  // or
1675  //   &T::operator struct s;
1676  // For these, DSC is DeclSpecContext::DSC_type_specifier or
1677  // DeclSpecContext::DSC_alias_declaration.
1678
1679  // If there are attributes after class name, parse them.
1680  MaybeParseCXX11Attributes(Attributes);
1681
1682  const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
1683  Sema::TagUseKind TUK;
1684  if (DSC == DeclSpecContext::DSC_trailing)
1685    TUK = Sema::TUK_Reference;
1686  else if (Tok.is(tok::l_brace) ||
1687           (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
1688           (isCXX11FinalKeyword() &&
1689            (NextToken().is(tok::l_brace) || NextToken().is(tok::colon)))) {
1690    if (DS.isFriendSpecified()) {
1691      // C++ [class.friend]p2:
1692      //   A class shall not be defined in a friend declaration.
1693      Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
1694        << SourceRange(DS.getFriendSpecLoc());
1695
1696      // Skip everything up to the semicolon, so that this looks like a proper
1697      // friend class (or template thereof) declaration.
1698      SkipUntil(tok::semi, StopBeforeMatch);
1699      TUK = Sema::TUK_Friend;
1700    } else {
1701      // Okay, this is a class definition.
1702      TUK = Sema::TUK_Definition;
1703    }
1704  } else if (isCXX11FinalKeyword() && (NextToken().is(tok::l_square) ||
1705                                       NextToken().is(tok::kw_alignas))) {
1706    // We can't tell if this is a definition or reference
1707    // until we skipped the 'final' and C++11 attribute specifiers.
1708    TentativeParsingAction PA(*this);
1709
1710    // Skip the 'final' keyword.
1711    ConsumeToken();
1712
1713    // Skip C++11 attribute specifiers.
1714    while (true) {
1715      if (Tok.is(tok::l_square) && NextToken().is(tok::l_square)) {
1716        ConsumeBracket();
1717        if (!SkipUntil(tok::r_square, StopAtSemi))
1718          break;
1719      } else if (Tok.is(tok::kw_alignas) && NextToken().is(tok::l_paren)) {
1720        ConsumeToken();
1721        ConsumeParen();
1722        if (!SkipUntil(tok::r_paren, StopAtSemi))
1723          break;
1724      } else {
1725        break;
1726      }
1727    }
1728
1729    if (Tok.isOneOf(tok::l_brace, tok::colon))
1730      TUK = Sema::TUK_Definition;
1731    else
1732      TUK = Sema::TUK_Reference;
1733
1734    PA.Revert();
1735  } else if (!isTypeSpecifier(DSC) &&
1736             (Tok.is(tok::semi) ||
1737              (Tok.isAtStartOfLine() && !isValidAfterTypeSpecifier(false)))) {
1738    TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
1739    if (Tok.isNot(tok::semi)) {
1740      const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
1741      // A semicolon was missing after this declaration. Diagnose and recover.
1742      ExpectAndConsume(tok::semi, diag::err_expected_after,
1743                       DeclSpec::getSpecifierName(TagType, PPol));
1744      PP.EnterToken(Tok, /*IsReinject*/true);
1745      Tok.setKind(tok::semi);
1746    }
1747  } else
1748    TUK = Sema::TUK_Reference;
1749
1750  // Forbid misplaced attributes. In cases of a reference, we pass attributes
1751  // to caller to handle.
1752  if (TUK != Sema::TUK_Reference) {
1753    // If this is not a reference, then the only possible
1754    // valid place for C++11 attributes to appear here
1755    // is between class-key and class-name. If there are
1756    // any attributes after class-name, we try a fixit to move
1757    // them to the right place.
1758    SourceRange AttrRange = Attributes.Range;
1759    if (AttrRange.isValid()) {
1760      Diag(AttrRange.getBegin(), diag::err_attributes_not_allowed)
1761        << AttrRange
1762        << FixItHint::CreateInsertionFromRange(AttrFixitLoc,
1763                                               CharSourceRange(AttrRange, true))
1764        << FixItHint::CreateRemoval(AttrRange);
1765
1766      // Recover by adding misplaced attributes to the attribute list
1767      // of the class so they can be applied on the class later.
1768      attrs.takeAllFrom(Attributes);
1769    }
1770  }
1771
1772  // If this is an elaborated type specifier, and we delayed
1773  // diagnostics before, just merge them into the current pool.
1774  if (shouldDelayDiagsInTag) {
1775    diagsFromTag.done();
1776    if (TUK == Sema::TUK_Reference)
1777      diagsFromTag.redelay();
1778  }
1779
1780  if (!Name && !TemplateId && (DS.getTypeSpecType() == DeclSpec::TST_error ||
1781                               TUK != Sema::TUK_Definition)) {
1782    if (DS.getTypeSpecType() != DeclSpec::TST_error) {
1783      // We have a declaration or reference to an anonymous class.
1784      Diag(StartLoc, diag::err_anon_type_definition)
1785        << DeclSpec::getSpecifierName(TagType, Policy);
1786    }
1787
1788    // If we are parsing a definition and stop at a base-clause, continue on
1789    // until the semicolon.  Continuing from the comma will just trick us into
1790    // thinking we are seeing a variable declaration.
1791    if (TUK == Sema::TUK_Definition && Tok.is(tok::colon))
1792      SkipUntil(tok::semi, StopBeforeMatch);
1793    else
1794      SkipUntil(tok::comma, StopAtSemi);
1795    return;
1796  }
1797
1798  // Create the tag portion of the class or class template.
1799  DeclResult TagOrTempResult = true; // invalid
1800  TypeResult TypeResult = true; // invalid
1801
1802  bool Owned = false;
1803  Sema::SkipBodyInfo SkipBody;
1804  if (TemplateId) {
1805    // Explicit specialization, class template partial specialization,
1806    // or explicit instantiation.
1807    ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1808                                       TemplateId->NumArgs);
1809    if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
1810        TUK == Sema::TUK_Declaration) {
1811      // This is an explicit instantiation of a class template.
1812      ProhibitAttributes(attrs);
1813
1814      TagOrTempResult = Actions.ActOnExplicitInstantiation(
1815          getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc,
1816          TagType, StartLoc, SS, TemplateId->Template,
1817          TemplateId->TemplateNameLoc, TemplateId->LAngleLoc, TemplateArgsPtr,
1818          TemplateId->RAngleLoc, attrs);
1819
1820      // Friend template-ids are treated as references unless
1821      // they have template headers, in which case they're ill-formed
1822      // (FIXME: "template <class T> friend class A<T>::B<int>;").
1823      // We diagnose this error in ActOnClassTemplateSpecialization.
1824    } else if (TUK == Sema::TUK_Reference ||
1825               (TUK == Sema::TUK_Friend &&
1826                TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate)) {
1827      ProhibitAttributes(attrs);
1828      TypeResult = Actions.ActOnTagTemplateIdType(TUK, TagType, StartLoc,
1829                                                  TemplateId->SS,
1830                                                  TemplateId->TemplateKWLoc,
1831                                                  TemplateId->Template,
1832                                                  TemplateId->TemplateNameLoc,
1833                                                  TemplateId->LAngleLoc,
1834                                                  TemplateArgsPtr,
1835                                                  TemplateId->RAngleLoc);
1836    } else {
1837      // This is an explicit specialization or a class template
1838      // partial specialization.
1839      TemplateParameterLists FakedParamLists;
1840      if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1841        // This looks like an explicit instantiation, because we have
1842        // something like
1843        //
1844        //   template class Foo<X>
1845        //
1846        // but it actually has a definition. Most likely, this was
1847        // meant to be an explicit specialization, but the user forgot
1848        // the '<>' after 'template'.
1849        // It this is friend declaration however, since it cannot have a
1850        // template header, it is most likely that the user meant to
1851        // remove the 'template' keyword.
1852        assert((TUK == Sema::TUK_Definition || TUK == Sema::TUK_Friend) &&
1853               "Expected a definition here");
1854
1855        if (TUK == Sema::TUK_Friend) {
1856          Diag(DS.getFriendSpecLoc(), diag::err_friend_explicit_instantiation);
1857          TemplateParams = nullptr;
1858        } else {
1859          SourceLocation LAngleLoc =
1860              PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
1861          Diag(TemplateId->TemplateNameLoc,
1862               diag::err_explicit_instantiation_with_definition)
1863              << SourceRange(TemplateInfo.TemplateLoc)
1864              << FixItHint::CreateInsertion(LAngleLoc, "<>");
1865
1866          // Create a fake template parameter list that contains only
1867          // "template<>", so that we treat this construct as a class
1868          // template specialization.
1869          FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
1870              0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
1871              LAngleLoc, nullptr));
1872          TemplateParams = &FakedParamLists;
1873        }
1874      }
1875
1876      // Build the class template specialization.
1877      TagOrTempResult = Actions.ActOnClassTemplateSpecialization(
1878          getCurScope(), TagType, TUK, StartLoc, DS.getModulePrivateSpecLoc(),
1879          *TemplateId, attrs,
1880          MultiTemplateParamsArg(TemplateParams ? &(*TemplateParams)[0]
1881                                                : nullptr,
1882                                 TemplateParams ? TemplateParams->size() : 0),
1883          &SkipBody);
1884    }
1885  } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
1886             TUK == Sema::TUK_Declaration) {
1887    // Explicit instantiation of a member of a class template
1888    // specialization, e.g.,
1889    //
1890    //   template struct Outer<int>::Inner;
1891    //
1892    ProhibitAttributes(attrs);
1893
1894    TagOrTempResult = Actions.ActOnExplicitInstantiation(
1895        getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc,
1896        TagType, StartLoc, SS, Name, NameLoc, attrs);
1897  } else if (TUK == Sema::TUK_Friend &&
1898             TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate) {
1899    ProhibitAttributes(attrs);
1900
1901    TagOrTempResult = Actions.ActOnTemplatedFriendTag(
1902        getCurScope(), DS.getFriendSpecLoc(), TagType, StartLoc, SS, Name,
1903        NameLoc, attrs,
1904        MultiTemplateParamsArg(TemplateParams ? &(*TemplateParams)[0] : nullptr,
1905                               TemplateParams ? TemplateParams->size() : 0));
1906  } else {
1907    if (TUK != Sema::TUK_Declaration && TUK != Sema::TUK_Definition)
1908      ProhibitAttributes(attrs);
1909
1910    if (TUK == Sema::TUK_Definition &&
1911        TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1912      // If the declarator-id is not a template-id, issue a diagnostic and
1913      // recover by ignoring the 'template' keyword.
1914      Diag(Tok, diag::err_template_defn_explicit_instantiation)
1915        << 1 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
1916      TemplateParams = nullptr;
1917    }
1918
1919    bool IsDependent = false;
1920
1921    // Don't pass down template parameter lists if this is just a tag
1922    // reference.  For example, we don't need the template parameters here:
1923    //   template <class T> class A *makeA(T t);
1924    MultiTemplateParamsArg TParams;
1925    if (TUK != Sema::TUK_Reference && TemplateParams)
1926      TParams =
1927        MultiTemplateParamsArg(&(*TemplateParams)[0], TemplateParams->size());
1928
1929    stripTypeAttributesOffDeclSpec(attrs, DS, TUK);
1930
1931    // Declaration or definition of a class type
1932    TagOrTempResult = Actions.ActOnTag(
1933        getCurScope(), TagType, TUK, StartLoc, SS, Name, NameLoc, attrs, AS,
1934        DS.getModulePrivateSpecLoc(), TParams, Owned, IsDependent,
1935        SourceLocation(), false, clang::TypeResult(),
1936        DSC == DeclSpecContext::DSC_type_specifier,
1937        DSC == DeclSpecContext::DSC_template_param ||
1938            DSC == DeclSpecContext::DSC_template_type_arg,
1939        &SkipBody);
1940
1941    // If ActOnTag said the type was dependent, try again with the
1942    // less common call.
1943    if (IsDependent) {
1944      assert(TUK == Sema::TUK_Reference || TUK == Sema::TUK_Friend);
1945      TypeResult = Actions.ActOnDependentTag(getCurScope(), TagType, TUK,
1946                                             SS, Name, StartLoc, NameLoc);
1947    }
1948  }
1949
1950  // If there is a body, parse it and inform the actions module.
1951  if (TUK == Sema::TUK_Definition) {
1952    assert(Tok.is(tok::l_brace) ||
1953           (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
1954           isCXX11FinalKeyword());
1955    if (SkipBody.ShouldSkip)
1956      SkipCXXMemberSpecification(StartLoc, AttrFixitLoc, TagType,
1957                                 TagOrTempResult.get());
1958    else if (getLangOpts().CPlusPlus)
1959      ParseCXXMemberSpecification(StartLoc, AttrFixitLoc, attrs, TagType,
1960                                  TagOrTempResult.get());
1961    else {
1962      Decl *D =
1963          SkipBody.CheckSameAsPrevious ? SkipBody.New : TagOrTempResult.get();
1964      // Parse the definition body.
1965      ParseStructUnionBody(StartLoc, TagType, D);
1966      if (SkipBody.CheckSameAsPrevious &&
1967          !Actions.ActOnDuplicateDefinition(DS, TagOrTempResult.get(),
1968                                            SkipBody)) {
1969        DS.SetTypeSpecError();
1970        return;
1971      }
1972    }
1973  }
1974
1975  if (!TagOrTempResult.isInvalid())
1976    // Delayed processing of attributes.
1977    Actions.ProcessDeclAttributeDelayed(TagOrTempResult.get(), attrs);
1978
1979  const char *PrevSpec = nullptr;
1980  unsigned DiagID;
1981  bool Result;
1982  if (!TypeResult.isInvalid()) {
1983    Result = DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
1984                                NameLoc.isValid() ? NameLoc : StartLoc,
1985                                PrevSpec, DiagID, TypeResult.get(), Policy);
1986  } else if (!TagOrTempResult.isInvalid()) {
1987    Result = DS.SetTypeSpecType(TagType, StartLoc,
1988                                NameLoc.isValid() ? NameLoc : StartLoc,
1989                                PrevSpec, DiagID, TagOrTempResult.get(), Owned,
1990                                Policy);
1991  } else {
1992    DS.SetTypeSpecError();
1993    return;
1994  }
1995
1996  if (Result)
1997    Diag(StartLoc, DiagID) << PrevSpec;
1998
1999  // At this point, we've successfully parsed a class-specifier in 'definition'
2000  // form (e.g. "struct foo { int x; }".  While we could just return here, we're
2001  // going to look at what comes after it to improve error recovery.  If an
2002  // impossible token occurs next, we assume that the programmer forgot a ; at
2003  // the end of the declaration and recover that way.
2004  //
2005  // Also enforce C++ [temp]p3:
2006  //   In a template-declaration which defines a class, no declarator
2007  //   is permitted.
2008  //
2009  // After a type-specifier, we don't expect a semicolon. This only happens in
2010  // C, since definitions are not permitted in this context in C++.
2011  if (TUK == Sema::TUK_Definition &&
2012      (getLangOpts().CPlusPlus || !isTypeSpecifier(DSC)) &&
2013      (TemplateInfo.Kind || !isValidAfterTypeSpecifier(false))) {
2014    if (Tok.isNot(tok::semi)) {
2015      const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
2016      ExpectAndConsume(tok::semi, diag::err_expected_after,
2017                       DeclSpec::getSpecifierName(TagType, PPol));
2018      // Push this token back into the preprocessor and change our current token
2019      // to ';' so that the rest of the code recovers as though there were an
2020      // ';' after the definition.
2021      PP.EnterToken(Tok, /*IsReinject=*/true);
2022      Tok.setKind(tok::semi);
2023    }
2024  }
2025}
2026
2027/// ParseBaseClause - Parse the base-clause of a C++ class [C++ class.derived].
2028///
2029///       base-clause : [C++ class.derived]
2030///         ':' base-specifier-list
2031///       base-specifier-list:
2032///         base-specifier '...'[opt]
2033///         base-specifier-list ',' base-specifier '...'[opt]
2034void Parser::ParseBaseClause(Decl *ClassDecl) {
2035  assert(Tok.is(tok::colon) && "Not a base clause");
2036  ConsumeToken();
2037
2038  // Build up an array of parsed base specifiers.
2039  SmallVector<CXXBaseSpecifier *, 8> BaseInfo;
2040
2041  while (true) {
2042    // Parse a base-specifier.
2043    BaseResult Result = ParseBaseSpecifier(ClassDecl);
2044    if (Result.isInvalid()) {
2045      // Skip the rest of this base specifier, up until the comma or
2046      // opening brace.
2047      SkipUntil(tok::comma, tok::l_brace, StopAtSemi | StopBeforeMatch);
2048    } else {
2049      // Add this to our array of base specifiers.
2050      BaseInfo.push_back(Result.get());
2051    }
2052
2053    // If the next token is a comma, consume it and keep reading
2054    // base-specifiers.
2055    if (!TryConsumeToken(tok::comma))
2056      break;
2057  }
2058
2059  // Attach the base specifiers
2060  Actions.ActOnBaseSpecifiers(ClassDecl, BaseInfo);
2061}
2062
2063/// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is
2064/// one entry in the base class list of a class specifier, for example:
2065///    class foo : public bar, virtual private baz {
2066/// 'public bar' and 'virtual private baz' are each base-specifiers.
2067///
2068///       base-specifier: [C++ class.derived]
2069///         attribute-specifier-seq[opt] base-type-specifier
2070///         attribute-specifier-seq[opt] 'virtual' access-specifier[opt]
2071///                 base-type-specifier
2072///         attribute-specifier-seq[opt] access-specifier 'virtual'[opt]
2073///                 base-type-specifier
2074BaseResult Parser::ParseBaseSpecifier(Decl *ClassDecl) {
2075  bool IsVirtual = false;
2076  SourceLocation StartLoc = Tok.getLocation();
2077
2078  ParsedAttributesWithRange Attributes(AttrFactory);
2079  MaybeParseCXX11Attributes(Attributes);
2080
2081  // Parse the 'virtual' keyword.
2082  if (TryConsumeToken(tok::kw_virtual))
2083    IsVirtual = true;
2084
2085  CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2086
2087  // Parse an (optional) access specifier.
2088  AccessSpecifier Access = getAccessSpecifierIfPresent();
2089  if (Access != AS_none)
2090    ConsumeToken();
2091
2092  CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2093
2094  // Parse the 'virtual' keyword (again!), in case it came after the
2095  // access specifier.
2096  if (Tok.is(tok::kw_virtual))  {
2097    SourceLocation VirtualLoc = ConsumeToken();
2098    if (IsVirtual) {
2099      // Complain about duplicate 'virtual'
2100      Diag(VirtualLoc, diag::err_dup_virtual)
2101        << FixItHint::CreateRemoval(VirtualLoc);
2102    }
2103
2104    IsVirtual = true;
2105  }
2106
2107  CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2108
2109  // Parse the class-name.
2110
2111  // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
2112  // implementation for VS2013 uses _Atomic as an identifier for one of the
2113  // classes in <atomic>.  Treat '_Atomic' to be an identifier when we are
2114  // parsing the class-name for a base specifier.
2115  if (getLangOpts().MSVCCompat && Tok.is(tok::kw__Atomic) &&
2116      NextToken().is(tok::less))
2117    Tok.setKind(tok::identifier);
2118
2119  SourceLocation EndLocation;
2120  SourceLocation BaseLoc;
2121  TypeResult BaseType = ParseBaseTypeSpecifier(BaseLoc, EndLocation);
2122  if (BaseType.isInvalid())
2123    return true;
2124
2125  // Parse the optional ellipsis (for a pack expansion). The ellipsis is
2126  // actually part of the base-specifier-list grammar productions, but we
2127  // parse it here for convenience.
2128  SourceLocation EllipsisLoc;
2129  TryConsumeToken(tok::ellipsis, EllipsisLoc);
2130
2131  // Find the complete source range for the base-specifier.
2132  SourceRange Range(StartLoc, EndLocation);
2133
2134  // Notify semantic analysis that we have parsed a complete
2135  // base-specifier.
2136  return Actions.ActOnBaseSpecifier(ClassDecl, Range, Attributes, IsVirtual,
2137                                    Access, BaseType.get(), BaseLoc,
2138                                    EllipsisLoc);
2139}
2140
2141/// getAccessSpecifierIfPresent - Determine whether the next token is
2142/// a C++ access-specifier.
2143///
2144///       access-specifier: [C++ class.derived]
2145///         'private'
2146///         'protected'
2147///         'public'
2148AccessSpecifier Parser::getAccessSpecifierIfPresent() const {
2149  switch (Tok.getKind()) {
2150  default: return AS_none;
2151  case tok::kw_private: return AS_private;
2152  case tok::kw_protected: return AS_protected;
2153  case tok::kw_public: return AS_public;
2154  }
2155}
2156
2157/// If the given declarator has any parts for which parsing has to be
2158/// delayed, e.g., default arguments or an exception-specification, create a
2159/// late-parsed method declaration record to handle the parsing at the end of
2160/// the class definition.
2161void Parser::HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
2162                                            Decl *ThisDecl) {
2163  DeclaratorChunk::FunctionTypeInfo &FTI
2164    = DeclaratorInfo.getFunctionTypeInfo();
2165  // If there was a late-parsed exception-specification, we'll need a
2166  // late parse
2167  bool NeedLateParse = FTI.getExceptionSpecType() == EST_Unparsed;
2168
2169  if (!NeedLateParse) {
2170    // Look ahead to see if there are any default args
2171    for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx) {
2172      auto Param = cast<ParmVarDecl>(FTI.Params[ParamIdx].Param);
2173      if (Param->hasUnparsedDefaultArg()) {
2174        NeedLateParse = true;
2175        break;
2176      }
2177    }
2178  }
2179
2180  if (NeedLateParse) {
2181    // Push this method onto the stack of late-parsed method
2182    // declarations.
2183    auto LateMethod = new LateParsedMethodDeclaration(this, ThisDecl);
2184    getCurrentClass().LateParsedDeclarations.push_back(LateMethod);
2185    LateMethod->TemplateScope = getCurScope()->isTemplateParamScope();
2186
2187    // Stash the exception-specification tokens in the late-pased method.
2188    LateMethod->ExceptionSpecTokens = FTI.ExceptionSpecTokens;
2189    FTI.ExceptionSpecTokens = nullptr;
2190
2191    // Push tokens for each parameter.  Those that do not have
2192    // defaults will be NULL.
2193    LateMethod->DefaultArgs.reserve(FTI.NumParams);
2194    for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx)
2195      LateMethod->DefaultArgs.push_back(LateParsedDefaultArgument(
2196          FTI.Params[ParamIdx].Param,
2197          std::move(FTI.Params[ParamIdx].DefaultArgTokens)));
2198  }
2199}
2200
2201/// isCXX11VirtSpecifier - Determine whether the given token is a C++11
2202/// virt-specifier.
2203///
2204///       virt-specifier:
2205///         override
2206///         final
2207///         __final
2208VirtSpecifiers::Specifier Parser::isCXX11VirtSpecifier(const Token &Tok) const {
2209  if (!getLangOpts().CPlusPlus || Tok.isNot(tok::identifier))
2210    return VirtSpecifiers::VS_None;
2211
2212  IdentifierInfo *II = Tok.getIdentifierInfo();
2213
2214  // Initialize the contextual keywords.
2215  if (!Ident_final) {
2216    Ident_final = &PP.getIdentifierTable().get("final");
2217    if (getLangOpts().GNUKeywords)
2218      Ident_GNU_final = &PP.getIdentifierTable().get("__final");
2219    if (getLangOpts().MicrosoftExt)
2220      Ident_sealed = &PP.getIdentifierTable().get("sealed");
2221    Ident_override = &PP.getIdentifierTable().get("override");
2222  }
2223
2224  if (II == Ident_override)
2225    return VirtSpecifiers::VS_Override;
2226
2227  if (II == Ident_sealed)
2228    return VirtSpecifiers::VS_Sealed;
2229
2230  if (II == Ident_final)
2231    return VirtSpecifiers::VS_Final;
2232
2233  if (II == Ident_GNU_final)
2234    return VirtSpecifiers::VS_GNU_Final;
2235
2236  return VirtSpecifiers::VS_None;
2237}
2238
2239/// ParseOptionalCXX11VirtSpecifierSeq - Parse a virt-specifier-seq.
2240///
2241///       virt-specifier-seq:
2242///         virt-specifier
2243///         virt-specifier-seq virt-specifier
2244void Parser::ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS,
2245                                                bool IsInterface,
2246                                                SourceLocation FriendLoc) {
2247  while (true) {
2248    VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
2249    if (Specifier == VirtSpecifiers::VS_None)
2250      return;
2251
2252    if (FriendLoc.isValid()) {
2253      Diag(Tok.getLocation(), diag::err_friend_decl_spec)
2254        << VirtSpecifiers::getSpecifierName(Specifier)
2255        << FixItHint::CreateRemoval(Tok.getLocation())
2256        << SourceRange(FriendLoc, FriendLoc);
2257      ConsumeToken();
2258      continue;
2259    }
2260
2261    // C++ [class.mem]p8:
2262    //   A virt-specifier-seq shall contain at most one of each virt-specifier.
2263    const char *PrevSpec = nullptr;
2264    if (VS.SetSpecifier(Specifier, Tok.getLocation(), PrevSpec))
2265      Diag(Tok.getLocation(), diag::err_duplicate_virt_specifier)
2266        << PrevSpec
2267        << FixItHint::CreateRemoval(Tok.getLocation());
2268
2269    if (IsInterface && (Specifier == VirtSpecifiers::VS_Final ||
2270                        Specifier == VirtSpecifiers::VS_Sealed)) {
2271      Diag(Tok.getLocation(), diag::err_override_control_interface)
2272        << VirtSpecifiers::getSpecifierName(Specifier);
2273    } else if (Specifier == VirtSpecifiers::VS_Sealed) {
2274      Diag(Tok.getLocation(), diag::ext_ms_sealed_keyword);
2275    } else if (Specifier == VirtSpecifiers::VS_GNU_Final) {
2276      Diag(Tok.getLocation(), diag::ext_warn_gnu_final);
2277    } else {
2278      Diag(Tok.getLocation(),
2279           getLangOpts().CPlusPlus11
2280               ? diag::warn_cxx98_compat_override_control_keyword
2281               : diag::ext_override_control_keyword)
2282          << VirtSpecifiers::getSpecifierName(Specifier);
2283    }
2284    ConsumeToken();
2285  }
2286}
2287
2288/// isCXX11FinalKeyword - Determine whether the next token is a C++11
2289/// 'final' or Microsoft 'sealed' contextual keyword.
2290bool Parser::isCXX11FinalKeyword() const {
2291  VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
2292  return Specifier == VirtSpecifiers::VS_Final ||
2293         Specifier == VirtSpecifiers::VS_GNU_Final ||
2294         Specifier == VirtSpecifiers::VS_Sealed;
2295}
2296
2297/// Parse a C++ member-declarator up to, but not including, the optional
2298/// brace-or-equal-initializer or pure-specifier.
2299bool Parser::ParseCXXMemberDeclaratorBeforeInitializer(
2300    Declarator &DeclaratorInfo, VirtSpecifiers &VS, ExprResult &BitfieldSize,
2301    LateParsedAttrList &LateParsedAttrs) {
2302  // member-declarator:
2303  //   declarator pure-specifier[opt]
2304  //   declarator brace-or-equal-initializer[opt]
2305  //   identifier[opt] ':' constant-expression
2306  if (Tok.isNot(tok::colon))
2307    ParseDeclarator(DeclaratorInfo);
2308  else
2309    DeclaratorInfo.SetIdentifier(nullptr, Tok.getLocation());
2310
2311  if (!DeclaratorInfo.isFunctionDeclarator() && TryConsumeToken(tok::colon)) {
2312    assert(DeclaratorInfo.isPastIdentifier() &&
2313           "don't know where identifier would go yet?");
2314    BitfieldSize = ParseConstantExpression();
2315    if (BitfieldSize.isInvalid())
2316      SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2317  } else {
2318    ParseOptionalCXX11VirtSpecifierSeq(
2319        VS, getCurrentClass().IsInterface,
2320        DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
2321    if (!VS.isUnset())
2322      MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo, VS);
2323  }
2324
2325  // If a simple-asm-expr is present, parse it.
2326  if (Tok.is(tok::kw_asm)) {
2327    SourceLocation Loc;
2328    ExprResult AsmLabel(ParseSimpleAsm(&Loc));
2329    if (AsmLabel.isInvalid())
2330      SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2331
2332    DeclaratorInfo.setAsmLabel(AsmLabel.get());
2333    DeclaratorInfo.SetRangeEnd(Loc);
2334  }
2335
2336  // If attributes exist after the declarator, but before an '{', parse them.
2337  MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
2338
2339  // For compatibility with code written to older Clang, also accept a
2340  // virt-specifier *after* the GNU attributes.
2341  if (BitfieldSize.isUnset() && VS.isUnset()) {
2342    ParseOptionalCXX11VirtSpecifierSeq(
2343        VS, getCurrentClass().IsInterface,
2344        DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
2345    if (!VS.isUnset()) {
2346      // If we saw any GNU-style attributes that are known to GCC followed by a
2347      // virt-specifier, issue a GCC-compat warning.
2348      for (const ParsedAttr &AL : DeclaratorInfo.getAttributes())
2349        if (AL.isKnownToGCC() && !AL.isCXX11Attribute())
2350          Diag(AL.getLoc(), diag::warn_gcc_attribute_location);
2351
2352      MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo, VS);
2353    }
2354  }
2355
2356  // If this has neither a name nor a bit width, something has gone seriously
2357  // wrong. Skip until the semi-colon or }.
2358  if (!DeclaratorInfo.hasName() && BitfieldSize.isUnset()) {
2359    // If so, skip until the semi-colon or a }.
2360    SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2361    return true;
2362  }
2363  return false;
2364}
2365
2366/// Look for declaration specifiers possibly occurring after C++11
2367/// virt-specifier-seq and diagnose them.
2368void Parser::MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(
2369    Declarator &D,
2370    VirtSpecifiers &VS) {
2371  DeclSpec DS(AttrFactory);
2372
2373  // GNU-style and C++11 attributes are not allowed here, but they will be
2374  // handled by the caller.  Diagnose everything else.
2375  ParseTypeQualifierListOpt(
2376      DS, AR_NoAttributesParsed, false,
2377      /*IdentifierRequired=*/false, llvm::function_ref<void()>([&]() {
2378        Actions.CodeCompleteFunctionQualifiers(DS, D, &VS);
2379      }));
2380  D.ExtendWithDeclSpec(DS);
2381
2382  if (D.isFunctionDeclarator()) {
2383    auto &Function = D.getFunctionTypeInfo();
2384    if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
2385      auto DeclSpecCheck = [&](DeclSpec::TQ TypeQual, StringRef FixItName,
2386                               SourceLocation SpecLoc) {
2387        FixItHint Insertion;
2388        auto &MQ = Function.getOrCreateMethodQualifiers();
2389        if (!(MQ.getTypeQualifiers() & TypeQual)) {
2390          std::string Name(FixItName.data());
2391          Name += " ";
2392          Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), Name);
2393          MQ.SetTypeQual(TypeQual, SpecLoc);
2394        }
2395        Diag(SpecLoc, diag::err_declspec_after_virtspec)
2396            << FixItName
2397            << VirtSpecifiers::getSpecifierName(VS.getLastSpecifier())
2398            << FixItHint::CreateRemoval(SpecLoc) << Insertion;
2399      };
2400      DS.forEachQualifier(DeclSpecCheck);
2401    }
2402
2403    // Parse ref-qualifiers.
2404    bool RefQualifierIsLValueRef = true;
2405    SourceLocation RefQualifierLoc;
2406    if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc)) {
2407      const char *Name = (RefQualifierIsLValueRef ? "& " : "&& ");
2408      FixItHint Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), Name);
2409      Function.RefQualifierIsLValueRef = RefQualifierIsLValueRef;
2410      Function.RefQualifierLoc = RefQualifierLoc.getRawEncoding();
2411
2412      Diag(RefQualifierLoc, diag::err_declspec_after_virtspec)
2413        << (RefQualifierIsLValueRef ? "&" : "&&")
2414        << VirtSpecifiers::getSpecifierName(VS.getLastSpecifier())
2415        << FixItHint::CreateRemoval(RefQualifierLoc)
2416        << Insertion;
2417      D.SetRangeEnd(RefQualifierLoc);
2418    }
2419  }
2420}
2421
2422/// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration.
2423///
2424///       member-declaration:
2425///         decl-specifier-seq[opt] member-declarator-list[opt] ';'
2426///         function-definition ';'[opt]
2427///         ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO]
2428///         using-declaration                                            [TODO]
2429/// [C++0x] static_assert-declaration
2430///         template-declaration
2431/// [GNU]   '__extension__' member-declaration
2432///
2433///       member-declarator-list:
2434///         member-declarator
2435///         member-declarator-list ',' member-declarator
2436///
2437///       member-declarator:
2438///         declarator virt-specifier-seq[opt] pure-specifier[opt]
2439///         declarator constant-initializer[opt]
2440/// [C++11] declarator brace-or-equal-initializer[opt]
2441///         identifier[opt] ':' constant-expression
2442///
2443///       virt-specifier-seq:
2444///         virt-specifier
2445///         virt-specifier-seq virt-specifier
2446///
2447///       virt-specifier:
2448///         override
2449///         final
2450/// [MS]    sealed
2451///
2452///       pure-specifier:
2453///         '= 0'
2454///
2455///       constant-initializer:
2456///         '=' constant-expression
2457///
2458Parser::DeclGroupPtrTy
2459Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS,
2460                                       ParsedAttributes &AccessAttrs,
2461                                       const ParsedTemplateInfo &TemplateInfo,
2462                                       ParsingDeclRAIIObject *TemplateDiags) {
2463  if (Tok.is(tok::at)) {
2464    if (getLangOpts().ObjC && NextToken().isObjCAtKeyword(tok::objc_defs))
2465      Diag(Tok, diag::err_at_defs_cxx);
2466    else
2467      Diag(Tok, diag::err_at_in_class);
2468
2469    ConsumeToken();
2470    SkipUntil(tok::r_brace, StopAtSemi);
2471    return nullptr;
2472  }
2473
2474  // Turn on colon protection early, while parsing declspec, although there is
2475  // nothing to protect there. It prevents from false errors if error recovery
2476  // incorrectly determines where the declspec ends, as in the example:
2477  //   struct A { enum class B { C }; };
2478  //   const int C = 4;
2479  //   struct D { A::B : C; };
2480  ColonProtectionRAIIObject X(*this);
2481
2482  // Access declarations.
2483  bool MalformedTypeSpec = false;
2484  if (!TemplateInfo.Kind &&
2485      Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw___super)) {
2486    if (TryAnnotateCXXScopeToken())
2487      MalformedTypeSpec = true;
2488
2489    bool isAccessDecl;
2490    if (Tok.isNot(tok::annot_cxxscope))
2491      isAccessDecl = false;
2492    else if (NextToken().is(tok::identifier))
2493      isAccessDecl = GetLookAheadToken(2).is(tok::semi);
2494    else
2495      isAccessDecl = NextToken().is(tok::kw_operator);
2496
2497    if (isAccessDecl) {
2498      // Collect the scope specifier token we annotated earlier.
2499      CXXScopeSpec SS;
2500      ParseOptionalCXXScopeSpecifier(SS, nullptr,
2501                                     /*EnteringContext=*/false);
2502
2503      if (SS.isInvalid()) {
2504        SkipUntil(tok::semi);
2505        return nullptr;
2506      }
2507
2508      // Try to parse an unqualified-id.
2509      SourceLocation TemplateKWLoc;
2510      UnqualifiedId Name;
2511      if (ParseUnqualifiedId(SS, false, true, true, false, nullptr,
2512                             &TemplateKWLoc, Name)) {
2513        SkipUntil(tok::semi);
2514        return nullptr;
2515      }
2516
2517      // TODO: recover from mistakenly-qualified operator declarations.
2518      if (ExpectAndConsume(tok::semi, diag::err_expected_after,
2519                           "access declaration")) {
2520        SkipUntil(tok::semi);
2521        return nullptr;
2522      }
2523
2524      // FIXME: We should do something with the 'template' keyword here.
2525      return DeclGroupPtrTy::make(DeclGroupRef(Actions.ActOnUsingDeclaration(
2526          getCurScope(), AS, /*UsingLoc*/ SourceLocation(),
2527          /*TypenameLoc*/ SourceLocation(), SS, Name,
2528          /*EllipsisLoc*/ SourceLocation(),
2529          /*AttrList*/ ParsedAttributesView())));
2530    }
2531  }
2532
2533  // static_assert-declaration. A templated static_assert declaration is
2534  // diagnosed in Parser::ParseSingleDeclarationAfterTemplate.
2535  if (!TemplateInfo.Kind &&
2536      Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert)) {
2537    SourceLocation DeclEnd;
2538    return DeclGroupPtrTy::make(
2539        DeclGroupRef(ParseStaticAssertDeclaration(DeclEnd)));
2540  }
2541
2542  if (Tok.is(tok::kw_template)) {
2543    assert(!TemplateInfo.TemplateParams &&
2544           "Nested template improperly parsed?");
2545    ObjCDeclContextSwitch ObjCDC(*this);
2546    SourceLocation DeclEnd;
2547    return DeclGroupPtrTy::make(
2548        DeclGroupRef(ParseTemplateDeclarationOrSpecialization(
2549            DeclaratorContext::MemberContext, DeclEnd, AccessAttrs, AS)));
2550  }
2551
2552  // Handle:  member-declaration ::= '__extension__' member-declaration
2553  if (Tok.is(tok::kw___extension__)) {
2554    // __extension__ silences extension warnings in the subexpression.
2555    ExtensionRAIIObject O(Diags);  // Use RAII to do this.
2556    ConsumeToken();
2557    return ParseCXXClassMemberDeclaration(AS, AccessAttrs,
2558                                          TemplateInfo, TemplateDiags);
2559  }
2560
2561  ParsedAttributesWithRange attrs(AttrFactory);
2562  ParsedAttributesViewWithRange FnAttrs;
2563  // Optional C++11 attribute-specifier
2564  MaybeParseCXX11Attributes(attrs);
2565  // We need to keep these attributes for future diagnostic
2566  // before they are taken over by declaration specifier.
2567  FnAttrs.addAll(attrs.begin(), attrs.end());
2568  FnAttrs.Range = attrs.Range;
2569
2570  MaybeParseMicrosoftAttributes(attrs);
2571
2572  if (Tok.is(tok::kw_using)) {
2573    ProhibitAttributes(attrs);
2574
2575    // Eat 'using'.
2576    SourceLocation UsingLoc = ConsumeToken();
2577
2578    // Consume unexpected 'template' keywords.
2579    while (Tok.is(tok::kw_template)) {
2580      SourceLocation TemplateLoc = ConsumeToken();
2581      Diag(TemplateLoc, diag::err_unexpected_template_after_using)
2582          << FixItHint::CreateRemoval(TemplateLoc);
2583    }
2584
2585    if (Tok.is(tok::kw_namespace)) {
2586      Diag(UsingLoc, diag::err_using_namespace_in_class);
2587      SkipUntil(tok::semi, StopBeforeMatch);
2588      return nullptr;
2589    }
2590    SourceLocation DeclEnd;
2591    // Otherwise, it must be a using-declaration or an alias-declaration.
2592    return ParseUsingDeclaration(DeclaratorContext::MemberContext, TemplateInfo,
2593                                 UsingLoc, DeclEnd, AS);
2594  }
2595
2596  // Hold late-parsed attributes so we can attach a Decl to them later.
2597  LateParsedAttrList CommonLateParsedAttrs;
2598
2599  // decl-specifier-seq:
2600  // Parse the common declaration-specifiers piece.
2601  ParsingDeclSpec DS(*this, TemplateDiags);
2602  DS.takeAttributesFrom(attrs);
2603  if (MalformedTypeSpec)
2604    DS.SetTypeSpecError();
2605
2606  ParseDeclarationSpecifiers(DS, TemplateInfo, AS, DeclSpecContext::DSC_class,
2607                             &CommonLateParsedAttrs);
2608
2609  // Turn off colon protection that was set for declspec.
2610  X.restore();
2611
2612  // If we had a free-standing type definition with a missing semicolon, we
2613  // may get this far before the problem becomes obvious.
2614  if (DS.hasTagDefinition() &&
2615      TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate &&
2616      DiagnoseMissingSemiAfterTagDefinition(DS, AS, DeclSpecContext::DSC_class,
2617                                            &CommonLateParsedAttrs))
2618    return nullptr;
2619
2620  MultiTemplateParamsArg TemplateParams(
2621      TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->data()
2622                                 : nullptr,
2623      TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->size() : 0);
2624
2625  if (TryConsumeToken(tok::semi)) {
2626    if (DS.isFriendSpecified())
2627      ProhibitAttributes(FnAttrs);
2628
2629    RecordDecl *AnonRecord = nullptr;
2630    Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(
2631        getCurScope(), AS, DS, TemplateParams, false, AnonRecord);
2632    DS.complete(TheDecl);
2633    if (AnonRecord) {
2634      Decl* decls[] = {AnonRecord, TheDecl};
2635      return Actions.BuildDeclaratorGroup(decls);
2636    }
2637    return Actions.ConvertDeclToDeclGroup(TheDecl);
2638  }
2639
2640  ParsingDeclarator DeclaratorInfo(*this, DS, DeclaratorContext::MemberContext);
2641  VirtSpecifiers VS;
2642
2643  // Hold late-parsed attributes so we can attach a Decl to them later.
2644  LateParsedAttrList LateParsedAttrs;
2645
2646  SourceLocation EqualLoc;
2647  SourceLocation PureSpecLoc;
2648
2649  auto TryConsumePureSpecifier = [&] (bool AllowDefinition) {
2650    if (Tok.isNot(tok::equal))
2651      return false;
2652
2653    auto &Zero = NextToken();
2654    SmallString<8> Buffer;
2655    if (Zero.isNot(tok::numeric_constant) || Zero.getLength() != 1 ||
2656        PP.getSpelling(Zero, Buffer) != "0")
2657      return false;
2658
2659    auto &After = GetLookAheadToken(2);
2660    if (!After.isOneOf(tok::semi, tok::comma) &&
2661        !(AllowDefinition &&
2662          After.isOneOf(tok::l_brace, tok::colon, tok::kw_try)))
2663      return false;
2664
2665    EqualLoc = ConsumeToken();
2666    PureSpecLoc = ConsumeToken();
2667    return true;
2668  };
2669
2670  SmallVector<Decl *, 8> DeclsInGroup;
2671  ExprResult BitfieldSize;
2672  bool ExpectSemi = true;
2673
2674  // Parse the first declarator.
2675  if (ParseCXXMemberDeclaratorBeforeInitializer(
2676          DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs)) {
2677    TryConsumeToken(tok::semi);
2678    return nullptr;
2679  }
2680
2681  // Check for a member function definition.
2682  if (BitfieldSize.isUnset()) {
2683    // MSVC permits pure specifier on inline functions defined at class scope.
2684    // Hence check for =0 before checking for function definition.
2685    if (getLangOpts().MicrosoftExt && DeclaratorInfo.isDeclarationOfFunction())
2686      TryConsumePureSpecifier(/*AllowDefinition*/ true);
2687
2688    FunctionDefinitionKind DefinitionKind = FDK_Declaration;
2689    // function-definition:
2690    //
2691    // In C++11, a non-function declarator followed by an open brace is a
2692    // braced-init-list for an in-class member initialization, not an
2693    // erroneous function definition.
2694    if (Tok.is(tok::l_brace) && !getLangOpts().CPlusPlus11) {
2695      DefinitionKind = FDK_Definition;
2696    } else if (DeclaratorInfo.isFunctionDeclarator()) {
2697      if (Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try)) {
2698        DefinitionKind = FDK_Definition;
2699      } else if (Tok.is(tok::equal)) {
2700        const Token &KW = NextToken();
2701        if (KW.is(tok::kw_default))
2702          DefinitionKind = FDK_Defaulted;
2703        else if (KW.is(tok::kw_delete))
2704          DefinitionKind = FDK_Deleted;
2705      }
2706    }
2707    DeclaratorInfo.setFunctionDefinitionKind(DefinitionKind);
2708
2709    // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
2710    // to a friend declaration, that declaration shall be a definition.
2711    if (DeclaratorInfo.isFunctionDeclarator() &&
2712        DefinitionKind != FDK_Definition && DS.isFriendSpecified()) {
2713      // Diagnose attributes that appear before decl specifier:
2714      // [[]] friend int foo();
2715      ProhibitAttributes(FnAttrs);
2716    }
2717
2718    if (DefinitionKind != FDK_Declaration) {
2719      if (!DeclaratorInfo.isFunctionDeclarator()) {
2720        Diag(DeclaratorInfo.getIdentifierLoc(), diag::err_func_def_no_params);
2721        ConsumeBrace();
2722        SkipUntil(tok::r_brace);
2723
2724        // Consume the optional ';'
2725        TryConsumeToken(tok::semi);
2726
2727        return nullptr;
2728      }
2729
2730      if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
2731        Diag(DeclaratorInfo.getIdentifierLoc(),
2732             diag::err_function_declared_typedef);
2733
2734        // Recover by treating the 'typedef' as spurious.
2735        DS.ClearStorageClassSpecs();
2736      }
2737
2738      Decl *FunDecl =
2739        ParseCXXInlineMethodDef(AS, AccessAttrs, DeclaratorInfo, TemplateInfo,
2740                                VS, PureSpecLoc);
2741
2742      if (FunDecl) {
2743        for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i) {
2744          CommonLateParsedAttrs[i]->addDecl(FunDecl);
2745        }
2746        for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i) {
2747          LateParsedAttrs[i]->addDecl(FunDecl);
2748        }
2749      }
2750      LateParsedAttrs.clear();
2751
2752      // Consume the ';' - it's optional unless we have a delete or default
2753      if (Tok.is(tok::semi))
2754        ConsumeExtraSemi(AfterMemberFunctionDefinition);
2755
2756      return DeclGroupPtrTy::make(DeclGroupRef(FunDecl));
2757    }
2758  }
2759
2760  // member-declarator-list:
2761  //   member-declarator
2762  //   member-declarator-list ',' member-declarator
2763
2764  while (1) {
2765    InClassInitStyle HasInClassInit = ICIS_NoInit;
2766    bool HasStaticInitializer = false;
2767    if (Tok.isOneOf(tok::equal, tok::l_brace) && PureSpecLoc.isInvalid()) {
2768      if (DeclaratorInfo.isDeclarationOfFunction()) {
2769        // It's a pure-specifier.
2770        if (!TryConsumePureSpecifier(/*AllowFunctionDefinition*/ false))
2771          // Parse it as an expression so that Sema can diagnose it.
2772          HasStaticInitializer = true;
2773      } else if (DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2774                     DeclSpec::SCS_static &&
2775                 DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2776                     DeclSpec::SCS_typedef &&
2777                 !DS.isFriendSpecified()) {
2778        // It's a default member initializer.
2779        if (BitfieldSize.get())
2780          Diag(Tok, getLangOpts().CPlusPlus2a
2781                        ? diag::warn_cxx17_compat_bitfield_member_init
2782                        : diag::ext_bitfield_member_init);
2783        HasInClassInit = Tok.is(tok::equal) ? ICIS_CopyInit : ICIS_ListInit;
2784      } else {
2785        HasStaticInitializer = true;
2786      }
2787    }
2788
2789    // NOTE: If Sema is the Action module and declarator is an instance field,
2790    // this call will *not* return the created decl; It will return null.
2791    // See Sema::ActOnCXXMemberDeclarator for details.
2792
2793    NamedDecl *ThisDecl = nullptr;
2794    if (DS.isFriendSpecified()) {
2795      // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
2796      // to a friend declaration, that declaration shall be a definition.
2797      //
2798      // Diagnose attributes that appear in a friend member function declarator:
2799      //   friend int foo [[]] ();
2800      SmallVector<SourceRange, 4> Ranges;
2801      DeclaratorInfo.getCXX11AttributeRanges(Ranges);
2802      for (SmallVectorImpl<SourceRange>::iterator I = Ranges.begin(),
2803           E = Ranges.end(); I != E; ++I)
2804        Diag((*I).getBegin(), diag::err_attributes_not_allowed) << *I;
2805
2806      ThisDecl = Actions.ActOnFriendFunctionDecl(getCurScope(), DeclaratorInfo,
2807                                                 TemplateParams);
2808    } else {
2809      ThisDecl = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS,
2810                                                  DeclaratorInfo,
2811                                                  TemplateParams,
2812                                                  BitfieldSize.get(),
2813                                                  VS, HasInClassInit);
2814
2815      if (VarTemplateDecl *VT =
2816              ThisDecl ? dyn_cast<VarTemplateDecl>(ThisDecl) : nullptr)
2817        // Re-direct this decl to refer to the templated decl so that we can
2818        // initialize it.
2819        ThisDecl = VT->getTemplatedDecl();
2820
2821      if (ThisDecl)
2822        Actions.ProcessDeclAttributeList(getCurScope(), ThisDecl, AccessAttrs);
2823    }
2824
2825    // Error recovery might have converted a non-static member into a static
2826    // member.
2827    if (HasInClassInit != ICIS_NoInit &&
2828        DeclaratorInfo.getDeclSpec().getStorageClassSpec() ==
2829            DeclSpec::SCS_static) {
2830      HasInClassInit = ICIS_NoInit;
2831      HasStaticInitializer = true;
2832    }
2833
2834    if (ThisDecl && PureSpecLoc.isValid())
2835      Actions.ActOnPureSpecifier(ThisDecl, PureSpecLoc);
2836
2837    // Handle the initializer.
2838    if (HasInClassInit != ICIS_NoInit) {
2839      // The initializer was deferred; parse it and cache the tokens.
2840      Diag(Tok, getLangOpts().CPlusPlus11
2841                    ? diag::warn_cxx98_compat_nonstatic_member_init
2842                    : diag::ext_nonstatic_member_init);
2843
2844      if (DeclaratorInfo.isArrayOfUnknownBound()) {
2845        // C++11 [dcl.array]p3: An array bound may also be omitted when the
2846        // declarator is followed by an initializer.
2847        //
2848        // A brace-or-equal-initializer for a member-declarator is not an
2849        // initializer in the grammar, so this is ill-formed.
2850        Diag(Tok, diag::err_incomplete_array_member_init);
2851        SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2852
2853        // Avoid later warnings about a class member of incomplete type.
2854        if (ThisDecl)
2855          ThisDecl->setInvalidDecl();
2856      } else
2857        ParseCXXNonStaticMemberInitializer(ThisDecl);
2858    } else if (HasStaticInitializer) {
2859      // Normal initializer.
2860      ExprResult Init = ParseCXXMemberInitializer(
2861          ThisDecl, DeclaratorInfo.isDeclarationOfFunction(), EqualLoc);
2862
2863      if (Init.isInvalid())
2864        SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2865      else if (ThisDecl)
2866        Actions.AddInitializerToDecl(ThisDecl, Init.get(), EqualLoc.isInvalid());
2867    } else if (ThisDecl && DS.getStorageClassSpec() == DeclSpec::SCS_static)
2868      // No initializer.
2869      Actions.ActOnUninitializedDecl(ThisDecl);
2870
2871    if (ThisDecl) {
2872      if (!ThisDecl->isInvalidDecl()) {
2873        // Set the Decl for any late parsed attributes
2874        for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i)
2875          CommonLateParsedAttrs[i]->addDecl(ThisDecl);
2876
2877        for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i)
2878          LateParsedAttrs[i]->addDecl(ThisDecl);
2879      }
2880      Actions.FinalizeDeclaration(ThisDecl);
2881      DeclsInGroup.push_back(ThisDecl);
2882
2883      if (DeclaratorInfo.isFunctionDeclarator() &&
2884          DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2885              DeclSpec::SCS_typedef)
2886        HandleMemberFunctionDeclDelays(DeclaratorInfo, ThisDecl);
2887    }
2888    LateParsedAttrs.clear();
2889
2890    DeclaratorInfo.complete(ThisDecl);
2891
2892    // If we don't have a comma, it is either the end of the list (a ';')
2893    // or an error, bail out.
2894    SourceLocation CommaLoc;
2895    if (!TryConsumeToken(tok::comma, CommaLoc))
2896      break;
2897
2898    if (Tok.isAtStartOfLine() &&
2899        !MightBeDeclarator(DeclaratorContext::MemberContext)) {
2900      // This comma was followed by a line-break and something which can't be
2901      // the start of a declarator. The comma was probably a typo for a
2902      // semicolon.
2903      Diag(CommaLoc, diag::err_expected_semi_declaration)
2904        << FixItHint::CreateReplacement(CommaLoc, ";");
2905      ExpectSemi = false;
2906      break;
2907    }
2908
2909    // Parse the next declarator.
2910    DeclaratorInfo.clear();
2911    VS.clear();
2912    BitfieldSize = ExprResult(/*Invalid=*/false);
2913    EqualLoc = PureSpecLoc = SourceLocation();
2914    DeclaratorInfo.setCommaLoc(CommaLoc);
2915
2916    // GNU attributes are allowed before the second and subsequent declarator.
2917    MaybeParseGNUAttributes(DeclaratorInfo);
2918
2919    if (ParseCXXMemberDeclaratorBeforeInitializer(
2920            DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs))
2921      break;
2922  }
2923
2924  if (ExpectSemi &&
2925      ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list)) {
2926    // Skip to end of block or statement.
2927    SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2928    // If we stopped at a ';', eat it.
2929    TryConsumeToken(tok::semi);
2930    return nullptr;
2931  }
2932
2933  return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
2934}
2935
2936/// ParseCXXMemberInitializer - Parse the brace-or-equal-initializer.
2937/// Also detect and reject any attempted defaulted/deleted function definition.
2938/// The location of the '=', if any, will be placed in EqualLoc.
2939///
2940/// This does not check for a pure-specifier; that's handled elsewhere.
2941///
2942///   brace-or-equal-initializer:
2943///     '=' initializer-expression
2944///     braced-init-list
2945///
2946///   initializer-clause:
2947///     assignment-expression
2948///     braced-init-list
2949///
2950///   defaulted/deleted function-definition:
2951///     '=' 'default'
2952///     '=' 'delete'
2953///
2954/// Prior to C++0x, the assignment-expression in an initializer-clause must
2955/// be a constant-expression.
2956ExprResult Parser::ParseCXXMemberInitializer(Decl *D, bool IsFunction,
2957                                             SourceLocation &EqualLoc) {
2958  assert(Tok.isOneOf(tok::equal, tok::l_brace)
2959         && "Data member initializer not starting with '=' or '{'");
2960
2961  EnterExpressionEvaluationContext Context(
2962      Actions, Sema::ExpressionEvaluationContext::PotentiallyEvaluated, D);
2963  if (TryConsumeToken(tok::equal, EqualLoc)) {
2964    if (Tok.is(tok::kw_delete)) {
2965      // In principle, an initializer of '= delete p;' is legal, but it will
2966      // never type-check. It's better to diagnose it as an ill-formed expression
2967      // than as an ill-formed deleted non-function member.
2968      // An initializer of '= delete p, foo' will never be parsed, because
2969      // a top-level comma always ends the initializer expression.
2970      const Token &Next = NextToken();
2971      if (IsFunction || Next.isOneOf(tok::semi, tok::comma, tok::eof)) {
2972        if (IsFunction)
2973          Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2974            << 1 /* delete */;
2975        else
2976          Diag(ConsumeToken(), diag::err_deleted_non_function);
2977        return ExprError();
2978      }
2979    } else if (Tok.is(tok::kw_default)) {
2980      if (IsFunction)
2981        Diag(Tok, diag::err_default_delete_in_multiple_declaration)
2982          << 0 /* default */;
2983      else
2984        Diag(ConsumeToken(), diag::err_default_special_members)
2985            << getLangOpts().CPlusPlus2a;
2986      return ExprError();
2987    }
2988  }
2989  if (const auto *PD = dyn_cast_or_null<MSPropertyDecl>(D)) {
2990    Diag(Tok, diag::err_ms_property_initializer) << PD;
2991    return ExprError();
2992  }
2993  return ParseInitializer();
2994}
2995
2996void Parser::SkipCXXMemberSpecification(SourceLocation RecordLoc,
2997                                        SourceLocation AttrFixitLoc,
2998                                        unsigned TagType, Decl *TagDecl) {
2999  // Skip the optional 'final' keyword.
3000  if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
3001    assert(isCXX11FinalKeyword() && "not a class definition");
3002    ConsumeToken();
3003
3004    // Diagnose any C++11 attributes after 'final' keyword.
3005    // We deliberately discard these attributes.
3006    ParsedAttributesWithRange Attrs(AttrFactory);
3007    CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
3008
3009    // This can only happen if we had malformed misplaced attributes;
3010    // we only get called if there is a colon or left-brace after the
3011    // attributes.
3012    if (Tok.isNot(tok::colon) && Tok.isNot(tok::l_brace))
3013      return;
3014  }
3015
3016  // Skip the base clauses. This requires actually parsing them, because
3017  // otherwise we can't be sure where they end (a left brace may appear
3018  // within a template argument).
3019  if (Tok.is(tok::colon)) {
3020    // Enter the scope of the class so that we can correctly parse its bases.
3021    ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
3022    ParsingClassDefinition ParsingDef(*this, TagDecl, /*NonNestedClass*/ true,
3023                                      TagType == DeclSpec::TST_interface);
3024    auto OldContext =
3025        Actions.ActOnTagStartSkippedDefinition(getCurScope(), TagDecl);
3026
3027    // Parse the bases but don't attach them to the class.
3028    ParseBaseClause(nullptr);
3029
3030    Actions.ActOnTagFinishSkippedDefinition(OldContext);
3031
3032    if (!Tok.is(tok::l_brace)) {
3033      Diag(PP.getLocForEndOfToken(PrevTokLocation),
3034           diag::err_expected_lbrace_after_base_specifiers);
3035      return;
3036    }
3037  }
3038
3039  // Skip the body.
3040  assert(Tok.is(tok::l_brace));
3041  BalancedDelimiterTracker T(*this, tok::l_brace);
3042  T.consumeOpen();
3043  T.skipToEnd();
3044
3045  // Parse and discard any trailing attributes.
3046  ParsedAttributes Attrs(AttrFactory);
3047  if (Tok.is(tok::kw___attribute))
3048    MaybeParseGNUAttributes(Attrs);
3049}
3050
3051Parser::DeclGroupPtrTy Parser::ParseCXXClassMemberDeclarationWithPragmas(
3052    AccessSpecifier &AS, ParsedAttributesWithRange &AccessAttrs,
3053    DeclSpec::TST TagType, Decl *TagDecl) {
3054  ParenBraceBracketBalancer BalancerRAIIObj(*this);
3055
3056  switch (Tok.getKind()) {
3057  case tok::kw___if_exists:
3058  case tok::kw___if_not_exists:
3059    ParseMicrosoftIfExistsClassDeclaration(TagType, AccessAttrs, AS);
3060    return nullptr;
3061
3062  case tok::semi:
3063    // Check for extraneous top-level semicolon.
3064    ConsumeExtraSemi(InsideStruct, TagType);
3065    return nullptr;
3066
3067    // Handle pragmas that can appear as member declarations.
3068  case tok::annot_pragma_vis:
3069    HandlePragmaVisibility();
3070    return nullptr;
3071  case tok::annot_pragma_pack:
3072    HandlePragmaPack();
3073    return nullptr;
3074  case tok::annot_pragma_align:
3075    HandlePragmaAlign();
3076    return nullptr;
3077  case tok::annot_pragma_ms_pointers_to_members:
3078    HandlePragmaMSPointersToMembers();
3079    return nullptr;
3080  case tok::annot_pragma_ms_pragma:
3081    HandlePragmaMSPragma();
3082    return nullptr;
3083  case tok::annot_pragma_ms_vtordisp:
3084    HandlePragmaMSVtorDisp();
3085    return nullptr;
3086  case tok::annot_pragma_dump:
3087    HandlePragmaDump();
3088    return nullptr;
3089
3090  case tok::kw_namespace:
3091    // If we see a namespace here, a close brace was missing somewhere.
3092    DiagnoseUnexpectedNamespace(cast<NamedDecl>(TagDecl));
3093    return nullptr;
3094
3095  case tok::kw_private:
3096    // FIXME: We don't accept GNU attributes on access specifiers in OpenCL mode
3097    // yet.
3098    if (getLangOpts().OpenCL && !NextToken().is(tok::colon))
3099      return ParseCXXClassMemberDeclaration(AS, AccessAttrs);
3100    LLVM_FALLTHROUGH;
3101  case tok::kw_public:
3102  case tok::kw_protected: {
3103    AccessSpecifier NewAS = getAccessSpecifierIfPresent();
3104    assert(NewAS != AS_none);
3105    // Current token is a C++ access specifier.
3106    AS = NewAS;
3107    SourceLocation ASLoc = Tok.getLocation();
3108    unsigned TokLength = Tok.getLength();
3109    ConsumeToken();
3110    AccessAttrs.clear();
3111    MaybeParseGNUAttributes(AccessAttrs);
3112
3113    SourceLocation EndLoc;
3114    if (TryConsumeToken(tok::colon, EndLoc)) {
3115    } else if (TryConsumeToken(tok::semi, EndLoc)) {
3116      Diag(EndLoc, diag::err_expected)
3117          << tok::colon << FixItHint::CreateReplacement(EndLoc, ":");
3118    } else {
3119      EndLoc = ASLoc.getLocWithOffset(TokLength);
3120      Diag(EndLoc, diag::err_expected)
3121          << tok::colon << FixItHint::CreateInsertion(EndLoc, ":");
3122    }
3123
3124    // The Microsoft extension __interface does not permit non-public
3125    // access specifiers.
3126    if (TagType == DeclSpec::TST_interface && AS != AS_public) {
3127      Diag(ASLoc, diag::err_access_specifier_interface) << (AS == AS_protected);
3128    }
3129
3130    if (Actions.ActOnAccessSpecifier(NewAS, ASLoc, EndLoc, AccessAttrs)) {
3131      // found another attribute than only annotations
3132      AccessAttrs.clear();
3133    }
3134
3135    return nullptr;
3136  }
3137
3138  case tok::annot_pragma_openmp:
3139    return ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, AccessAttrs, TagType,
3140                                                      TagDecl);
3141
3142  default:
3143    if (tok::isPragmaAnnotation(Tok.getKind())) {
3144      Diag(Tok.getLocation(), diag::err_pragma_misplaced_in_decl)
3145          << DeclSpec::getSpecifierName(TagType,
3146                                   Actions.getASTContext().getPrintingPolicy());
3147      ConsumeAnnotationToken();
3148      return nullptr;
3149    }
3150    return ParseCXXClassMemberDeclaration(AS, AccessAttrs);
3151  }
3152}
3153
3154/// ParseCXXMemberSpecification - Parse the class definition.
3155///
3156///       member-specification:
3157///         member-declaration member-specification[opt]
3158///         access-specifier ':' member-specification[opt]
3159///
3160void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc,
3161                                         SourceLocation AttrFixitLoc,
3162                                         ParsedAttributesWithRange &Attrs,
3163                                         unsigned TagType, Decl *TagDecl) {
3164  assert((TagType == DeclSpec::TST_struct ||
3165         TagType == DeclSpec::TST_interface ||
3166         TagType == DeclSpec::TST_union  ||
3167         TagType == DeclSpec::TST_class) && "Invalid TagType!");
3168
3169  llvm::TimeTraceScope TimeScope("ParseClass", [&]() {
3170    if (auto *TD = dyn_cast_or_null<NamedDecl>(TagDecl))
3171      return TD->getQualifiedNameAsString();
3172    return std::string("<anonymous>");
3173  });
3174
3175  PrettyDeclStackTraceEntry CrashInfo(Actions.Context, TagDecl, RecordLoc,
3176                                      "parsing struct/union/class body");
3177
3178  // Determine whether this is a non-nested class. Note that local
3179  // classes are *not* considered to be nested classes.
3180  bool NonNestedClass = true;
3181  if (!ClassStack.empty()) {
3182    for (const Scope *S = getCurScope(); S; S = S->getParent()) {
3183      if (S->isClassScope()) {
3184        // We're inside a class scope, so this is a nested class.
3185        NonNestedClass = false;
3186
3187        // The Microsoft extension __interface does not permit nested classes.
3188        if (getCurrentClass().IsInterface) {
3189          Diag(RecordLoc, diag::err_invalid_member_in_interface)
3190            << /*ErrorType=*/6
3191            << (isa<NamedDecl>(TagDecl)
3192                  ? cast<NamedDecl>(TagDecl)->getQualifiedNameAsString()
3193                  : "(anonymous)");
3194        }
3195        break;
3196      }
3197
3198      if ((S->getFlags() & Scope::FnScope))
3199        // If we're in a function or function template then this is a local
3200        // class rather than a nested class.
3201        break;
3202    }
3203  }
3204
3205  // Enter a scope for the class.
3206  ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
3207
3208  // Note that we are parsing a new (potentially-nested) class definition.
3209  ParsingClassDefinition ParsingDef(*this, TagDecl, NonNestedClass,
3210                                    TagType == DeclSpec::TST_interface);
3211
3212  if (TagDecl)
3213    Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
3214
3215  SourceLocation FinalLoc;
3216  bool IsFinalSpelledSealed = false;
3217
3218  // Parse the optional 'final' keyword.
3219  if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
3220    VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier(Tok);
3221    assert((Specifier == VirtSpecifiers::VS_Final ||
3222            Specifier == VirtSpecifiers::VS_GNU_Final ||
3223            Specifier == VirtSpecifiers::VS_Sealed) &&
3224           "not a class definition");
3225    FinalLoc = ConsumeToken();
3226    IsFinalSpelledSealed = Specifier == VirtSpecifiers::VS_Sealed;
3227
3228    if (TagType == DeclSpec::TST_interface)
3229      Diag(FinalLoc, diag::err_override_control_interface)
3230        << VirtSpecifiers::getSpecifierName(Specifier);
3231    else if (Specifier == VirtSpecifiers::VS_Final)
3232      Diag(FinalLoc, getLangOpts().CPlusPlus11
3233                         ? diag::warn_cxx98_compat_override_control_keyword
3234                         : diag::ext_override_control_keyword)
3235        << VirtSpecifiers::getSpecifierName(Specifier);
3236    else if (Specifier == VirtSpecifiers::VS_Sealed)
3237      Diag(FinalLoc, diag::ext_ms_sealed_keyword);
3238    else if (Specifier == VirtSpecifiers::VS_GNU_Final)
3239      Diag(FinalLoc, diag::ext_warn_gnu_final);
3240
3241    // Parse any C++11 attributes after 'final' keyword.
3242    // These attributes are not allowed to appear here,
3243    // and the only possible place for them to appertain
3244    // to the class would be between class-key and class-name.
3245    CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
3246
3247    // ParseClassSpecifier() does only a superficial check for attributes before
3248    // deciding to call this method.  For example, for
3249    // `class C final alignas ([l) {` it will decide that this looks like a
3250    // misplaced attribute since it sees `alignas '(' ')'`.  But the actual
3251    // attribute parsing code will try to parse the '[' as a constexpr lambda
3252    // and consume enough tokens that the alignas parsing code will eat the
3253    // opening '{'.  So bail out if the next token isn't one we expect.
3254    if (!Tok.is(tok::colon) && !Tok.is(tok::l_brace)) {
3255      if (TagDecl)
3256        Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
3257      return;
3258    }
3259  }
3260
3261  if (Tok.is(tok::colon)) {
3262    ParseScope InheritanceScope(this, getCurScope()->getFlags() |
3263                                          Scope::ClassInheritanceScope);
3264
3265    ParseBaseClause(TagDecl);
3266    if (!Tok.is(tok::l_brace)) {
3267      bool SuggestFixIt = false;
3268      SourceLocation BraceLoc = PP.getLocForEndOfToken(PrevTokLocation);
3269      if (Tok.isAtStartOfLine()) {
3270        switch (Tok.getKind()) {
3271        case tok::kw_private:
3272        case tok::kw_protected:
3273        case tok::kw_public:
3274          SuggestFixIt = NextToken().getKind() == tok::colon;
3275          break;
3276        case tok::kw_static_assert:
3277        case tok::r_brace:
3278        case tok::kw_using:
3279        // base-clause can have simple-template-id; 'template' can't be there
3280        case tok::kw_template:
3281          SuggestFixIt = true;
3282          break;
3283        case tok::identifier:
3284          SuggestFixIt = isConstructorDeclarator(true);
3285          break;
3286        default:
3287          SuggestFixIt = isCXXSimpleDeclaration(/*AllowForRangeDecl=*/false);
3288          break;
3289        }
3290      }
3291      DiagnosticBuilder LBraceDiag =
3292          Diag(BraceLoc, diag::err_expected_lbrace_after_base_specifiers);
3293      if (SuggestFixIt) {
3294        LBraceDiag << FixItHint::CreateInsertion(BraceLoc, " {");
3295        // Try recovering from missing { after base-clause.
3296        PP.EnterToken(Tok, /*IsReinject*/true);
3297        Tok.setKind(tok::l_brace);
3298      } else {
3299        if (TagDecl)
3300          Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
3301        return;
3302      }
3303    }
3304  }
3305
3306  assert(Tok.is(tok::l_brace));
3307  BalancedDelimiterTracker T(*this, tok::l_brace);
3308  T.consumeOpen();
3309
3310  if (TagDecl)
3311    Actions.ActOnStartCXXMemberDeclarations(getCurScope(), TagDecl, FinalLoc,
3312                                            IsFinalSpelledSealed,
3313                                            T.getOpenLocation());
3314
3315  // C++ 11p3: Members of a class defined with the keyword class are private
3316  // by default. Members of a class defined with the keywords struct or union
3317  // are public by default.
3318  AccessSpecifier CurAS;
3319  if (TagType == DeclSpec::TST_class)
3320    CurAS = AS_private;
3321  else
3322    CurAS = AS_public;
3323  ParsedAttributesWithRange AccessAttrs(AttrFactory);
3324
3325  if (TagDecl) {
3326    // While we still have something to read, read the member-declarations.
3327    while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
3328           Tok.isNot(tok::eof)) {
3329      // Each iteration of this loop reads one member-declaration.
3330      ParseCXXClassMemberDeclarationWithPragmas(
3331          CurAS, AccessAttrs, static_cast<DeclSpec::TST>(TagType), TagDecl);
3332    }
3333    T.consumeClose();
3334  } else {
3335    SkipUntil(tok::r_brace);
3336  }
3337
3338  // If attributes exist after class contents, parse them.
3339  ParsedAttributes attrs(AttrFactory);
3340  MaybeParseGNUAttributes(attrs);
3341
3342  if (TagDecl)
3343    Actions.ActOnFinishCXXMemberSpecification(getCurScope(), RecordLoc, TagDecl,
3344                                              T.getOpenLocation(),
3345                                              T.getCloseLocation(), attrs);
3346
3347  // C++11 [class.mem]p2:
3348  //   Within the class member-specification, the class is regarded as complete
3349  //   within function bodies, default arguments, exception-specifications, and
3350  //   brace-or-equal-initializers for non-static data members (including such
3351  //   things in nested classes).
3352  if (TagDecl && NonNestedClass) {
3353    // We are not inside a nested class. This class and its nested classes
3354    // are complete and we can parse the delayed portions of method
3355    // declarations and the lexed inline method definitions, along with any
3356    // delayed attributes.
3357    SourceLocation SavedPrevTokLocation = PrevTokLocation;
3358    ParseLexedAttributes(getCurrentClass());
3359    ParseLexedMethodDeclarations(getCurrentClass());
3360
3361    // We've finished with all pending member declarations.
3362    Actions.ActOnFinishCXXMemberDecls();
3363
3364    ParseLexedMemberInitializers(getCurrentClass());
3365    ParseLexedMethodDefs(getCurrentClass());
3366    PrevTokLocation = SavedPrevTokLocation;
3367
3368    // We've finished parsing everything, including default argument
3369    // initializers.
3370    Actions.ActOnFinishCXXNonNestedClass(TagDecl);
3371  }
3372
3373  if (TagDecl)
3374    Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getRange());
3375
3376  // Leave the class scope.
3377  ParsingDef.Pop();
3378  ClassScope.Exit();
3379}
3380
3381void Parser::DiagnoseUnexpectedNamespace(NamedDecl *D) {
3382  assert(Tok.is(tok::kw_namespace));
3383
3384  // FIXME: Suggest where the close brace should have gone by looking
3385  // at indentation changes within the definition body.
3386  Diag(D->getLocation(),
3387       diag::err_missing_end_of_definition) << D;
3388  Diag(Tok.getLocation(),
3389       diag::note_missing_end_of_definition_before) << D;
3390
3391  // Push '};' onto the token stream to recover.
3392  PP.EnterToken(Tok, /*IsReinject*/ true);
3393
3394  Tok.startToken();
3395  Tok.setLocation(PP.getLocForEndOfToken(PrevTokLocation));
3396  Tok.setKind(tok::semi);
3397  PP.EnterToken(Tok, /*IsReinject*/ true);
3398
3399  Tok.setKind(tok::r_brace);
3400}
3401
3402/// ParseConstructorInitializer - Parse a C++ constructor initializer,
3403/// which explicitly initializes the members or base classes of a
3404/// class (C++ [class.base.init]). For example, the three initializers
3405/// after the ':' in the Derived constructor below:
3406///
3407/// @code
3408/// class Base { };
3409/// class Derived : Base {
3410///   int x;
3411///   float f;
3412/// public:
3413///   Derived(float f) : Base(), x(17), f(f) { }
3414/// };
3415/// @endcode
3416///
3417/// [C++]  ctor-initializer:
3418///          ':' mem-initializer-list
3419///
3420/// [C++]  mem-initializer-list:
3421///          mem-initializer ...[opt]
3422///          mem-initializer ...[opt] , mem-initializer-list
3423void Parser::ParseConstructorInitializer(Decl *ConstructorDecl) {
3424  assert(Tok.is(tok::colon) &&
3425         "Constructor initializer always starts with ':'");
3426
3427  // Poison the SEH identifiers so they are flagged as illegal in constructor
3428  // initializers.
3429  PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
3430  SourceLocation ColonLoc = ConsumeToken();
3431
3432  SmallVector<CXXCtorInitializer*, 4> MemInitializers;
3433  bool AnyErrors = false;
3434
3435  do {
3436    if (Tok.is(tok::code_completion)) {
3437      Actions.CodeCompleteConstructorInitializer(ConstructorDecl,
3438                                                 MemInitializers);
3439      return cutOffParsing();
3440    }
3441
3442    MemInitResult MemInit = ParseMemInitializer(ConstructorDecl);
3443    if (!MemInit.isInvalid())
3444      MemInitializers.push_back(MemInit.get());
3445    else
3446      AnyErrors = true;
3447
3448    if (Tok.is(tok::comma))
3449      ConsumeToken();
3450    else if (Tok.is(tok::l_brace))
3451      break;
3452    // If the previous initializer was valid and the next token looks like a
3453    // base or member initializer, assume that we're just missing a comma.
3454    else if (!MemInit.isInvalid() &&
3455             Tok.isOneOf(tok::identifier, tok::coloncolon)) {
3456      SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation);
3457      Diag(Loc, diag::err_ctor_init_missing_comma)
3458        << FixItHint::CreateInsertion(Loc, ", ");
3459    } else {
3460      // Skip over garbage, until we get to '{'.  Don't eat the '{'.
3461      if (!MemInit.isInvalid())
3462        Diag(Tok.getLocation(), diag::err_expected_either) << tok::l_brace
3463                                                           << tok::comma;
3464      SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
3465      break;
3466    }
3467  } while (true);
3468
3469  Actions.ActOnMemInitializers(ConstructorDecl, ColonLoc, MemInitializers,
3470                               AnyErrors);
3471}
3472
3473/// ParseMemInitializer - Parse a C++ member initializer, which is
3474/// part of a constructor initializer that explicitly initializes one
3475/// member or base class (C++ [class.base.init]). See
3476/// ParseConstructorInitializer for an example.
3477///
3478/// [C++] mem-initializer:
3479///         mem-initializer-id '(' expression-list[opt] ')'
3480/// [C++0x] mem-initializer-id braced-init-list
3481///
3482/// [C++] mem-initializer-id:
3483///         '::'[opt] nested-name-specifier[opt] class-name
3484///         identifier
3485MemInitResult Parser::ParseMemInitializer(Decl *ConstructorDecl) {
3486  // parse '::'[opt] nested-name-specifier[opt]
3487  CXXScopeSpec SS;
3488  if (ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false))
3489    return true;
3490
3491  // : identifier
3492  IdentifierInfo *II = nullptr;
3493  SourceLocation IdLoc = Tok.getLocation();
3494  // : declype(...)
3495  DeclSpec DS(AttrFactory);
3496  // : template_name<...>
3497  ParsedType TemplateTypeTy;
3498
3499  if (Tok.is(tok::identifier)) {
3500    // Get the identifier. This may be a member name or a class name,
3501    // but we'll let the semantic analysis determine which it is.
3502    II = Tok.getIdentifierInfo();
3503    ConsumeToken();
3504  } else if (Tok.is(tok::annot_decltype)) {
3505    // Get the decltype expression, if there is one.
3506    // Uses of decltype will already have been converted to annot_decltype by
3507    // ParseOptionalCXXScopeSpecifier at this point.
3508    // FIXME: Can we get here with a scope specifier?
3509    ParseDecltypeSpecifier(DS);
3510  } else {
3511    TemplateIdAnnotation *TemplateId = Tok.is(tok::annot_template_id)
3512                                           ? takeTemplateIdAnnotation(Tok)
3513                                           : nullptr;
3514    if (TemplateId && (TemplateId->Kind == TNK_Type_template ||
3515                       TemplateId->Kind == TNK_Dependent_template_name ||
3516                       TemplateId->Kind == TNK_Undeclared_template)) {
3517      AnnotateTemplateIdTokenAsType(/*IsClassName*/true);
3518      assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
3519      TemplateTypeTy = getTypeAnnotation(Tok);
3520      ConsumeAnnotationToken();
3521      if (!TemplateTypeTy)
3522        return true;
3523    } else {
3524      Diag(Tok, diag::err_expected_member_or_base_name);
3525      return true;
3526    }
3527  }
3528
3529  // Parse the '('.
3530  if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
3531    Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
3532
3533    // FIXME: Add support for signature help inside initializer lists.
3534    ExprResult InitList = ParseBraceInitializer();
3535    if (InitList.isInvalid())
3536      return true;
3537
3538    SourceLocation EllipsisLoc;
3539    TryConsumeToken(tok::ellipsis, EllipsisLoc);
3540
3541    return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
3542                                       TemplateTypeTy, DS, IdLoc,
3543                                       InitList.get(), EllipsisLoc);
3544  } else if(Tok.is(tok::l_paren)) {
3545    BalancedDelimiterTracker T(*this, tok::l_paren);
3546    T.consumeOpen();
3547
3548    // Parse the optional expression-list.
3549    ExprVector ArgExprs;
3550    CommaLocsTy CommaLocs;
3551    auto RunSignatureHelp = [&] {
3552      QualType PreferredType = Actions.ProduceCtorInitMemberSignatureHelp(
3553          getCurScope(), ConstructorDecl, SS, TemplateTypeTy, ArgExprs, II,
3554          T.getOpenLocation());
3555      CalledSignatureHelp = true;
3556      return PreferredType;
3557    };
3558    if (Tok.isNot(tok::r_paren) &&
3559        ParseExpressionList(ArgExprs, CommaLocs, [&] {
3560          PreferredType.enterFunctionArgument(Tok.getLocation(),
3561                                              RunSignatureHelp);
3562        })) {
3563      if (PP.isCodeCompletionReached() && !CalledSignatureHelp)
3564        RunSignatureHelp();
3565      SkipUntil(tok::r_paren, StopAtSemi);
3566      return true;
3567    }
3568
3569    T.consumeClose();
3570
3571    SourceLocation EllipsisLoc;
3572    TryConsumeToken(tok::ellipsis, EllipsisLoc);
3573
3574    return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
3575                                       TemplateTypeTy, DS, IdLoc,
3576                                       T.getOpenLocation(), ArgExprs,
3577                                       T.getCloseLocation(), EllipsisLoc);
3578  }
3579
3580  if (getLangOpts().CPlusPlus11)
3581    return Diag(Tok, diag::err_expected_either) << tok::l_paren << tok::l_brace;
3582  else
3583    return Diag(Tok, diag::err_expected) << tok::l_paren;
3584}
3585
3586/// Parse a C++ exception-specification if present (C++0x [except.spec]).
3587///
3588///       exception-specification:
3589///         dynamic-exception-specification
3590///         noexcept-specification
3591///
3592///       noexcept-specification:
3593///         'noexcept'
3594///         'noexcept' '(' constant-expression ')'
3595ExceptionSpecificationType
3596Parser::tryParseExceptionSpecification(bool Delayed,
3597                    SourceRange &SpecificationRange,
3598                    SmallVectorImpl<ParsedType> &DynamicExceptions,
3599                    SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
3600                    ExprResult &NoexceptExpr,
3601                    CachedTokens *&ExceptionSpecTokens) {
3602  ExceptionSpecificationType Result = EST_None;
3603  ExceptionSpecTokens = nullptr;
3604
3605  // Handle delayed parsing of exception-specifications.
3606  if (Delayed) {
3607    if (Tok.isNot(tok::kw_throw) && Tok.isNot(tok::kw_noexcept))
3608      return EST_None;
3609
3610    // Consume and cache the starting token.
3611    bool IsNoexcept = Tok.is(tok::kw_noexcept);
3612    Token StartTok = Tok;
3613    SpecificationRange = SourceRange(ConsumeToken());
3614
3615    // Check for a '('.
3616    if (!Tok.is(tok::l_paren)) {
3617      // If this is a bare 'noexcept', we're done.
3618      if (IsNoexcept) {
3619        Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
3620        NoexceptExpr = nullptr;
3621        return EST_BasicNoexcept;
3622      }
3623
3624      Diag(Tok, diag::err_expected_lparen_after) << "throw";
3625      return EST_DynamicNone;
3626    }
3627
3628    // Cache the tokens for the exception-specification.
3629    ExceptionSpecTokens = new CachedTokens;
3630    ExceptionSpecTokens->push_back(StartTok); // 'throw' or 'noexcept'
3631    ExceptionSpecTokens->push_back(Tok); // '('
3632    SpecificationRange.setEnd(ConsumeParen()); // '('
3633
3634    ConsumeAndStoreUntil(tok::r_paren, *ExceptionSpecTokens,
3635                         /*StopAtSemi=*/true,
3636                         /*ConsumeFinalToken=*/true);
3637    SpecificationRange.setEnd(ExceptionSpecTokens->back().getLocation());
3638
3639    return EST_Unparsed;
3640  }
3641
3642  // See if there's a dynamic specification.
3643  if (Tok.is(tok::kw_throw)) {
3644    Result = ParseDynamicExceptionSpecification(SpecificationRange,
3645                                                DynamicExceptions,
3646                                                DynamicExceptionRanges);
3647    assert(DynamicExceptions.size() == DynamicExceptionRanges.size() &&
3648           "Produced different number of exception types and ranges.");
3649  }
3650
3651  // If there's no noexcept specification, we're done.
3652  if (Tok.isNot(tok::kw_noexcept))
3653    return Result;
3654
3655  Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
3656
3657  // If we already had a dynamic specification, parse the noexcept for,
3658  // recovery, but emit a diagnostic and don't store the results.
3659  SourceRange NoexceptRange;
3660  ExceptionSpecificationType NoexceptType = EST_None;
3661
3662  SourceLocation KeywordLoc = ConsumeToken();
3663  if (Tok.is(tok::l_paren)) {
3664    // There is an argument.
3665    BalancedDelimiterTracker T(*this, tok::l_paren);
3666    T.consumeOpen();
3667    NoexceptExpr = ParseConstantExpression();
3668    T.consumeClose();
3669    if (!NoexceptExpr.isInvalid()) {
3670      NoexceptExpr = Actions.ActOnNoexceptSpec(KeywordLoc, NoexceptExpr.get(),
3671                                               NoexceptType);
3672      NoexceptRange = SourceRange(KeywordLoc, T.getCloseLocation());
3673    } else {
3674      NoexceptType = EST_BasicNoexcept;
3675    }
3676  } else {
3677    // There is no argument.
3678    NoexceptType = EST_BasicNoexcept;
3679    NoexceptRange = SourceRange(KeywordLoc, KeywordLoc);
3680  }
3681
3682  if (Result == EST_None) {
3683    SpecificationRange = NoexceptRange;
3684    Result = NoexceptType;
3685
3686    // If there's a dynamic specification after a noexcept specification,
3687    // parse that and ignore the results.
3688    if (Tok.is(tok::kw_throw)) {
3689      Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
3690      ParseDynamicExceptionSpecification(NoexceptRange, DynamicExceptions,
3691                                         DynamicExceptionRanges);
3692    }
3693  } else {
3694    Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
3695  }
3696
3697  return Result;
3698}
3699
3700static void diagnoseDynamicExceptionSpecification(
3701    Parser &P, SourceRange Range, bool IsNoexcept) {
3702  if (P.getLangOpts().CPlusPlus11) {
3703    const char *Replacement = IsNoexcept ? "noexcept" : "noexcept(false)";
3704    P.Diag(Range.getBegin(),
3705           P.getLangOpts().CPlusPlus17 && !IsNoexcept
3706               ? diag::ext_dynamic_exception_spec
3707               : diag::warn_exception_spec_deprecated)
3708        << Range;
3709    P.Diag(Range.getBegin(), diag::note_exception_spec_deprecated)
3710      << Replacement << FixItHint::CreateReplacement(Range, Replacement);
3711  }
3712}
3713
3714/// ParseDynamicExceptionSpecification - Parse a C++
3715/// dynamic-exception-specification (C++ [except.spec]).
3716///
3717///       dynamic-exception-specification:
3718///         'throw' '(' type-id-list [opt] ')'
3719/// [MS]    'throw' '(' '...' ')'
3720///
3721///       type-id-list:
3722///         type-id ... [opt]
3723///         type-id-list ',' type-id ... [opt]
3724///
3725ExceptionSpecificationType Parser::ParseDynamicExceptionSpecification(
3726                                  SourceRange &SpecificationRange,
3727                                  SmallVectorImpl<ParsedType> &Exceptions,
3728                                  SmallVectorImpl<SourceRange> &Ranges) {
3729  assert(Tok.is(tok::kw_throw) && "expected throw");
3730
3731  SpecificationRange.setBegin(ConsumeToken());
3732  BalancedDelimiterTracker T(*this, tok::l_paren);
3733  if (T.consumeOpen()) {
3734    Diag(Tok, diag::err_expected_lparen_after) << "throw";
3735    SpecificationRange.setEnd(SpecificationRange.getBegin());
3736    return EST_DynamicNone;
3737  }
3738
3739  // Parse throw(...), a Microsoft extension that means "this function
3740  // can throw anything".
3741  if (Tok.is(tok::ellipsis)) {
3742    SourceLocation EllipsisLoc = ConsumeToken();
3743    if (!getLangOpts().MicrosoftExt)
3744      Diag(EllipsisLoc, diag::ext_ellipsis_exception_spec);
3745    T.consumeClose();
3746    SpecificationRange.setEnd(T.getCloseLocation());
3747    diagnoseDynamicExceptionSpecification(*this, SpecificationRange, false);
3748    return EST_MSAny;
3749  }
3750
3751  // Parse the sequence of type-ids.
3752  SourceRange Range;
3753  while (Tok.isNot(tok::r_paren)) {
3754    TypeResult Res(ParseTypeName(&Range));
3755
3756    if (Tok.is(tok::ellipsis)) {
3757      // C++0x [temp.variadic]p5:
3758      //   - In a dynamic-exception-specification (15.4); the pattern is a
3759      //     type-id.
3760      SourceLocation Ellipsis = ConsumeToken();
3761      Range.setEnd(Ellipsis);
3762      if (!Res.isInvalid())
3763        Res = Actions.ActOnPackExpansion(Res.get(), Ellipsis);
3764    }
3765
3766    if (!Res.isInvalid()) {
3767      Exceptions.push_back(Res.get());
3768      Ranges.push_back(Range);
3769    }
3770
3771    if (!TryConsumeToken(tok::comma))
3772      break;
3773  }
3774
3775  T.consumeClose();
3776  SpecificationRange.setEnd(T.getCloseLocation());
3777  diagnoseDynamicExceptionSpecification(*this, SpecificationRange,
3778                                        Exceptions.empty());
3779  return Exceptions.empty() ? EST_DynamicNone : EST_Dynamic;
3780}
3781
3782/// ParseTrailingReturnType - Parse a trailing return type on a new-style
3783/// function declaration.
3784TypeResult Parser::ParseTrailingReturnType(SourceRange &Range,
3785                                           bool MayBeFollowedByDirectInit) {
3786  assert(Tok.is(tok::arrow) && "expected arrow");
3787
3788  ConsumeToken();
3789
3790  return ParseTypeName(&Range, MayBeFollowedByDirectInit
3791                                   ? DeclaratorContext::TrailingReturnVarContext
3792                                   : DeclaratorContext::TrailingReturnContext);
3793}
3794
3795/// We have just started parsing the definition of a new class,
3796/// so push that class onto our stack of classes that is currently
3797/// being parsed.
3798Sema::ParsingClassState
3799Parser::PushParsingClass(Decl *ClassDecl, bool NonNestedClass,
3800                         bool IsInterface) {
3801  assert((NonNestedClass || !ClassStack.empty()) &&
3802         "Nested class without outer class");
3803  ClassStack.push(new ParsingClass(ClassDecl, NonNestedClass, IsInterface));
3804  return Actions.PushParsingClass();
3805}
3806
3807/// Deallocate the given parsed class and all of its nested
3808/// classes.
3809void Parser::DeallocateParsedClasses(Parser::ParsingClass *Class) {
3810  for (unsigned I = 0, N = Class->LateParsedDeclarations.size(); I != N; ++I)
3811    delete Class->LateParsedDeclarations[I];
3812  delete Class;
3813}
3814
3815/// Pop the top class of the stack of classes that are
3816/// currently being parsed.
3817///
3818/// This routine should be called when we have finished parsing the
3819/// definition of a class, but have not yet popped the Scope
3820/// associated with the class's definition.
3821void Parser::PopParsingClass(Sema::ParsingClassState state) {
3822  assert(!ClassStack.empty() && "Mismatched push/pop for class parsing");
3823
3824  Actions.PopParsingClass(state);
3825
3826  ParsingClass *Victim = ClassStack.top();
3827  ClassStack.pop();
3828  if (Victim->TopLevelClass) {
3829    // Deallocate all of the nested classes of this class,
3830    // recursively: we don't need to keep any of this information.
3831    DeallocateParsedClasses(Victim);
3832    return;
3833  }
3834  assert(!ClassStack.empty() && "Missing top-level class?");
3835
3836  if (Victim->LateParsedDeclarations.empty()) {
3837    // The victim is a nested class, but we will not need to perform
3838    // any processing after the definition of this class since it has
3839    // no members whose handling was delayed. Therefore, we can just
3840    // remove this nested class.
3841    DeallocateParsedClasses(Victim);
3842    return;
3843  }
3844
3845  // This nested class has some members that will need to be processed
3846  // after the top-level class is completely defined. Therefore, add
3847  // it to the list of nested classes within its parent.
3848  assert(getCurScope()->isClassScope() && "Nested class outside of class scope?");
3849  ClassStack.top()->LateParsedDeclarations.push_back(new LateParsedClass(this, Victim));
3850  Victim->TemplateScope = getCurScope()->getParent()->isTemplateParamScope();
3851}
3852
3853/// Try to parse an 'identifier' which appears within an attribute-token.
3854///
3855/// \return the parsed identifier on success, and 0 if the next token is not an
3856/// attribute-token.
3857///
3858/// C++11 [dcl.attr.grammar]p3:
3859///   If a keyword or an alternative token that satisfies the syntactic
3860///   requirements of an identifier is contained in an attribute-token,
3861///   it is considered an identifier.
3862IdentifierInfo *Parser::TryParseCXX11AttributeIdentifier(SourceLocation &Loc) {
3863  switch (Tok.getKind()) {
3864  default:
3865    // Identifiers and keywords have identifier info attached.
3866    if (!Tok.isAnnotation()) {
3867      if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
3868        Loc = ConsumeToken();
3869        return II;
3870      }
3871    }
3872    return nullptr;
3873
3874  case tok::numeric_constant: {
3875    // If we got a numeric constant, check to see if it comes from a macro that
3876    // corresponds to the predefined __clang__ macro. If it does, warn the user
3877    // and recover by pretending they said _Clang instead.
3878    if (Tok.getLocation().isMacroID()) {
3879      SmallString<8> ExpansionBuf;
3880      SourceLocation ExpansionLoc =
3881          PP.getSourceManager().getExpansionLoc(Tok.getLocation());
3882      StringRef Spelling = PP.getSpelling(ExpansionLoc, ExpansionBuf);
3883      if (Spelling == "__clang__") {
3884        SourceRange TokRange(
3885            ExpansionLoc,
3886            PP.getSourceManager().getExpansionLoc(Tok.getEndLoc()));
3887        Diag(Tok, diag::warn_wrong_clang_attr_namespace)
3888            << FixItHint::CreateReplacement(TokRange, "_Clang");
3889        Loc = ConsumeToken();
3890        return &PP.getIdentifierTable().get("_Clang");
3891      }
3892    }
3893    return nullptr;
3894  }
3895
3896  case tok::ampamp:       // 'and'
3897  case tok::pipe:         // 'bitor'
3898  case tok::pipepipe:     // 'or'
3899  case tok::caret:        // 'xor'
3900  case tok::tilde:        // 'compl'
3901  case tok::amp:          // 'bitand'
3902  case tok::ampequal:     // 'and_eq'
3903  case tok::pipeequal:    // 'or_eq'
3904  case tok::caretequal:   // 'xor_eq'
3905  case tok::exclaim:      // 'not'
3906  case tok::exclaimequal: // 'not_eq'
3907    // Alternative tokens do not have identifier info, but their spelling
3908    // starts with an alphabetical character.
3909    SmallString<8> SpellingBuf;
3910    SourceLocation SpellingLoc =
3911        PP.getSourceManager().getSpellingLoc(Tok.getLocation());
3912    StringRef Spelling = PP.getSpelling(SpellingLoc, SpellingBuf);
3913    if (isLetter(Spelling[0])) {
3914      Loc = ConsumeToken();
3915      return &PP.getIdentifierTable().get(Spelling);
3916    }
3917    return nullptr;
3918  }
3919}
3920
3921static bool IsBuiltInOrStandardCXX11Attribute(IdentifierInfo *AttrName,
3922                                              IdentifierInfo *ScopeName) {
3923  switch (
3924      ParsedAttr::getParsedKind(AttrName, ScopeName, ParsedAttr::AS_CXX11)) {
3925  case ParsedAttr::AT_CarriesDependency:
3926  case ParsedAttr::AT_Deprecated:
3927  case ParsedAttr::AT_FallThrough:
3928  case ParsedAttr::AT_CXX11NoReturn:
3929  case ParsedAttr::AT_NoUniqueAddress:
3930    return true;
3931  case ParsedAttr::AT_WarnUnusedResult:
3932    return !ScopeName && AttrName->getName().equals("nodiscard");
3933  case ParsedAttr::AT_Unused:
3934    return !ScopeName && AttrName->getName().equals("maybe_unused");
3935  default:
3936    return false;
3937  }
3938}
3939
3940/// ParseCXX11AttributeArgs -- Parse a C++11 attribute-argument-clause.
3941///
3942/// [C++11] attribute-argument-clause:
3943///         '(' balanced-token-seq ')'
3944///
3945/// [C++11] balanced-token-seq:
3946///         balanced-token
3947///         balanced-token-seq balanced-token
3948///
3949/// [C++11] balanced-token:
3950///         '(' balanced-token-seq ')'
3951///         '[' balanced-token-seq ']'
3952///         '{' balanced-token-seq '}'
3953///         any token but '(', ')', '[', ']', '{', or '}'
3954bool Parser::ParseCXX11AttributeArgs(IdentifierInfo *AttrName,
3955                                     SourceLocation AttrNameLoc,
3956                                     ParsedAttributes &Attrs,
3957                                     SourceLocation *EndLoc,
3958                                     IdentifierInfo *ScopeName,
3959                                     SourceLocation ScopeLoc) {
3960  assert(Tok.is(tok::l_paren) && "Not a C++11 attribute argument list");
3961  SourceLocation LParenLoc = Tok.getLocation();
3962  const LangOptions &LO = getLangOpts();
3963  ParsedAttr::Syntax Syntax =
3964      LO.CPlusPlus ? ParsedAttr::AS_CXX11 : ParsedAttr::AS_C2x;
3965
3966  // If the attribute isn't known, we will not attempt to parse any
3967  // arguments.
3968  if (!hasAttribute(LO.CPlusPlus ? AttrSyntax::CXX : AttrSyntax::C, ScopeName,
3969                    AttrName, getTargetInfo(), getLangOpts())) {
3970    // Eat the left paren, then skip to the ending right paren.
3971    ConsumeParen();
3972    SkipUntil(tok::r_paren);
3973    return false;
3974  }
3975
3976  if (ScopeName && (ScopeName->isStr("gnu") || ScopeName->isStr("__gnu__"))) {
3977    // GNU-scoped attributes have some special cases to handle GNU-specific
3978    // behaviors.
3979    ParseGNUAttributeArgs(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
3980                          ScopeLoc, Syntax, nullptr);
3981    return true;
3982  }
3983
3984  unsigned NumArgs;
3985  // Some Clang-scoped attributes have some special parsing behavior.
3986  if (ScopeName && (ScopeName->isStr("clang") || ScopeName->isStr("_Clang")))
3987    NumArgs = ParseClangAttributeArgs(AttrName, AttrNameLoc, Attrs, EndLoc,
3988                                      ScopeName, ScopeLoc, Syntax);
3989  else
3990    NumArgs =
3991        ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc,
3992                                 ScopeName, ScopeLoc, Syntax);
3993
3994  if (!Attrs.empty() &&
3995      IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName)) {
3996    ParsedAttr &Attr = Attrs.back();
3997    // If the attribute is a standard or built-in attribute and we are
3998    // parsing an argument list, we need to determine whether this attribute
3999    // was allowed to have an argument list (such as [[deprecated]]), and how
4000    // many arguments were parsed (so we can diagnose on [[deprecated()]]).
4001    if (Attr.getMaxArgs() && !NumArgs) {
4002      // The attribute was allowed to have arguments, but none were provided
4003      // even though the attribute parsed successfully. This is an error.
4004      Diag(LParenLoc, diag::err_attribute_requires_arguments) << AttrName;
4005      Attr.setInvalid(true);
4006    } else if (!Attr.getMaxArgs()) {
4007      // The attribute parsed successfully, but was not allowed to have any
4008      // arguments. It doesn't matter whether any were provided -- the
4009      // presence of the argument list (even if empty) is diagnosed.
4010      Diag(LParenLoc, diag::err_cxx11_attribute_forbids_arguments)
4011          << AttrName
4012          << FixItHint::CreateRemoval(SourceRange(LParenLoc, *EndLoc));
4013      Attr.setInvalid(true);
4014    }
4015  }
4016  return true;
4017}
4018
4019/// ParseCXX11AttributeSpecifier - Parse a C++11 or C2x attribute-specifier.
4020///
4021/// [C++11] attribute-specifier:
4022///         '[' '[' attribute-list ']' ']'
4023///         alignment-specifier
4024///
4025/// [C++11] attribute-list:
4026///         attribute[opt]
4027///         attribute-list ',' attribute[opt]
4028///         attribute '...'
4029///         attribute-list ',' attribute '...'
4030///
4031/// [C++11] attribute:
4032///         attribute-token attribute-argument-clause[opt]
4033///
4034/// [C++11] attribute-token:
4035///         identifier
4036///         attribute-scoped-token
4037///
4038/// [C++11] attribute-scoped-token:
4039///         attribute-namespace '::' identifier
4040///
4041/// [C++11] attribute-namespace:
4042///         identifier
4043void Parser::ParseCXX11AttributeSpecifier(ParsedAttributes &attrs,
4044                                          SourceLocation *endLoc) {
4045  if (Tok.is(tok::kw_alignas)) {
4046    Diag(Tok.getLocation(), diag::warn_cxx98_compat_alignas);
4047    ParseAlignmentSpecifier(attrs, endLoc);
4048    return;
4049  }
4050
4051  assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square) &&
4052         "Not a double square bracket attribute list");
4053
4054  Diag(Tok.getLocation(), diag::warn_cxx98_compat_attribute);
4055
4056  ConsumeBracket();
4057  ConsumeBracket();
4058
4059  SourceLocation CommonScopeLoc;
4060  IdentifierInfo *CommonScopeName = nullptr;
4061  if (Tok.is(tok::kw_using)) {
4062    Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
4063                                ? diag::warn_cxx14_compat_using_attribute_ns
4064                                : diag::ext_using_attribute_ns);
4065    ConsumeToken();
4066
4067    CommonScopeName = TryParseCXX11AttributeIdentifier(CommonScopeLoc);
4068    if (!CommonScopeName) {
4069      Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
4070      SkipUntil(tok::r_square, tok::colon, StopBeforeMatch);
4071    }
4072    if (!TryConsumeToken(tok::colon) && CommonScopeName)
4073      Diag(Tok.getLocation(), diag::err_expected) << tok::colon;
4074  }
4075
4076  llvm::SmallDenseMap<IdentifierInfo*, SourceLocation, 4> SeenAttrs;
4077
4078  while (Tok.isNot(tok::r_square)) {
4079    // attribute not present
4080    if (TryConsumeToken(tok::comma))
4081      continue;
4082
4083    SourceLocation ScopeLoc, AttrLoc;
4084    IdentifierInfo *ScopeName = nullptr, *AttrName = nullptr;
4085
4086    AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
4087    if (!AttrName)
4088      // Break out to the "expected ']'" diagnostic.
4089      break;
4090
4091    // scoped attribute
4092    if (TryConsumeToken(tok::coloncolon)) {
4093      ScopeName = AttrName;
4094      ScopeLoc = AttrLoc;
4095
4096      AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
4097      if (!AttrName) {
4098        Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
4099        SkipUntil(tok::r_square, tok::comma, StopAtSemi | StopBeforeMatch);
4100        continue;
4101      }
4102    }
4103
4104    if (CommonScopeName) {
4105      if (ScopeName) {
4106        Diag(ScopeLoc, diag::err_using_attribute_ns_conflict)
4107            << SourceRange(CommonScopeLoc);
4108      } else {
4109        ScopeName = CommonScopeName;
4110        ScopeLoc = CommonScopeLoc;
4111      }
4112    }
4113
4114    bool StandardAttr = IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName);
4115    bool AttrParsed = false;
4116
4117    if (StandardAttr &&
4118        !SeenAttrs.insert(std::make_pair(AttrName, AttrLoc)).second)
4119      Diag(AttrLoc, diag::err_cxx11_attribute_repeated)
4120          << AttrName << SourceRange(SeenAttrs[AttrName]);
4121
4122    // Parse attribute arguments
4123    if (Tok.is(tok::l_paren))
4124      AttrParsed = ParseCXX11AttributeArgs(AttrName, AttrLoc, attrs, endLoc,
4125                                           ScopeName, ScopeLoc);
4126
4127    if (!AttrParsed)
4128      attrs.addNew(
4129          AttrName,
4130          SourceRange(ScopeLoc.isValid() ? ScopeLoc : AttrLoc, AttrLoc),
4131          ScopeName, ScopeLoc, nullptr, 0,
4132          getLangOpts().CPlusPlus ? ParsedAttr::AS_CXX11 : ParsedAttr::AS_C2x);
4133
4134    if (TryConsumeToken(tok::ellipsis))
4135      Diag(Tok, diag::err_cxx11_attribute_forbids_ellipsis)
4136        << AttrName;
4137  }
4138
4139  if (ExpectAndConsume(tok::r_square))
4140    SkipUntil(tok::r_square);
4141  if (endLoc)
4142    *endLoc = Tok.getLocation();
4143  if (ExpectAndConsume(tok::r_square))
4144    SkipUntil(tok::r_square);
4145}
4146
4147/// ParseCXX11Attributes - Parse a C++11 or C2x attribute-specifier-seq.
4148///
4149/// attribute-specifier-seq:
4150///       attribute-specifier-seq[opt] attribute-specifier
4151void Parser::ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
4152                                  SourceLocation *endLoc) {
4153  assert(standardAttributesAllowed());
4154
4155  SourceLocation StartLoc = Tok.getLocation(), Loc;
4156  if (!endLoc)
4157    endLoc = &Loc;
4158
4159  do {
4160    ParseCXX11AttributeSpecifier(attrs, endLoc);
4161  } while (isCXX11AttributeSpecifier());
4162
4163  attrs.Range = SourceRange(StartLoc, *endLoc);
4164}
4165
4166void Parser::DiagnoseAndSkipCXX11Attributes() {
4167  // Start and end location of an attribute or an attribute list.
4168  SourceLocation StartLoc = Tok.getLocation();
4169  SourceLocation EndLoc = SkipCXX11Attributes();
4170
4171  if (EndLoc.isValid()) {
4172    SourceRange Range(StartLoc, EndLoc);
4173    Diag(StartLoc, diag::err_attributes_not_allowed)
4174      << Range;
4175  }
4176}
4177
4178SourceLocation Parser::SkipCXX11Attributes() {
4179  SourceLocation EndLoc;
4180
4181  if (!isCXX11AttributeSpecifier())
4182    return EndLoc;
4183
4184  do {
4185    if (Tok.is(tok::l_square)) {
4186      BalancedDelimiterTracker T(*this, tok::l_square);
4187      T.consumeOpen();
4188      T.skipToEnd();
4189      EndLoc = T.getCloseLocation();
4190    } else {
4191      assert(Tok.is(tok::kw_alignas) && "not an attribute specifier");
4192      ConsumeToken();
4193      BalancedDelimiterTracker T(*this, tok::l_paren);
4194      if (!T.consumeOpen())
4195        T.skipToEnd();
4196      EndLoc = T.getCloseLocation();
4197    }
4198  } while (isCXX11AttributeSpecifier());
4199
4200  return EndLoc;
4201}
4202
4203/// Parse uuid() attribute when it appears in a [] Microsoft attribute.
4204void Parser::ParseMicrosoftUuidAttributeArgs(ParsedAttributes &Attrs) {
4205  assert(Tok.is(tok::identifier) && "Not a Microsoft attribute list");
4206  IdentifierInfo *UuidIdent = Tok.getIdentifierInfo();
4207  assert(UuidIdent->getName() == "uuid" && "Not a Microsoft attribute list");
4208
4209  SourceLocation UuidLoc = Tok.getLocation();
4210  ConsumeToken();
4211
4212  // Ignore the left paren location for now.
4213  BalancedDelimiterTracker T(*this, tok::l_paren);
4214  if (T.consumeOpen()) {
4215    Diag(Tok, diag::err_expected) << tok::l_paren;
4216    return;
4217  }
4218
4219  ArgsVector ArgExprs;
4220  if (Tok.is(tok::string_literal)) {
4221    // Easy case: uuid("...") -- quoted string.
4222    ExprResult StringResult = ParseStringLiteralExpression();
4223    if (StringResult.isInvalid())
4224      return;
4225    ArgExprs.push_back(StringResult.get());
4226  } else {
4227    // something like uuid({000000A0-0000-0000-C000-000000000049}) -- no
4228    // quotes in the parens. Just append the spelling of all tokens encountered
4229    // until the closing paren.
4230
4231    SmallString<42> StrBuffer; // 2 "", 36 bytes UUID, 2 optional {}, 1 nul
4232    StrBuffer += "\"";
4233
4234    // Since none of C++'s keywords match [a-f]+, accepting just tok::l_brace,
4235    // tok::r_brace, tok::minus, tok::identifier (think C000) and
4236    // tok::numeric_constant (0000) should be enough. But the spelling of the
4237    // uuid argument is checked later anyways, so there's no harm in accepting
4238    // almost anything here.
4239    // cl is very strict about whitespace in this form and errors out if any
4240    // is present, so check the space flags on the tokens.
4241    SourceLocation StartLoc = Tok.getLocation();
4242    while (Tok.isNot(tok::r_paren)) {
4243      if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
4244        Diag(Tok, diag::err_attribute_uuid_malformed_guid);
4245        SkipUntil(tok::r_paren, StopAtSemi);
4246        return;
4247      }
4248      SmallString<16> SpellingBuffer;
4249      SpellingBuffer.resize(Tok.getLength() + 1);
4250      bool Invalid = false;
4251      StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
4252      if (Invalid) {
4253        SkipUntil(tok::r_paren, StopAtSemi);
4254        return;
4255      }
4256      StrBuffer += TokSpelling;
4257      ConsumeAnyToken();
4258    }
4259    StrBuffer += "\"";
4260
4261    if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
4262      Diag(Tok, diag::err_attribute_uuid_malformed_guid);
4263      ConsumeParen();
4264      return;
4265    }
4266
4267    // Pretend the user wrote the appropriate string literal here.
4268    // ActOnStringLiteral() copies the string data into the literal, so it's
4269    // ok that the Token points to StrBuffer.
4270    Token Toks[1];
4271    Toks[0].startToken();
4272    Toks[0].setKind(tok::string_literal);
4273    Toks[0].setLocation(StartLoc);
4274    Toks[0].setLiteralData(StrBuffer.data());
4275    Toks[0].setLength(StrBuffer.size());
4276    StringLiteral *UuidString =
4277        cast<StringLiteral>(Actions.ActOnStringLiteral(Toks, nullptr).get());
4278    ArgExprs.push_back(UuidString);
4279  }
4280
4281  if (!T.consumeClose()) {
4282    Attrs.addNew(UuidIdent, SourceRange(UuidLoc, T.getCloseLocation()), nullptr,
4283                 SourceLocation(), ArgExprs.data(), ArgExprs.size(),
4284                 ParsedAttr::AS_Microsoft);
4285  }
4286}
4287
4288/// ParseMicrosoftAttributes - Parse Microsoft attributes [Attr]
4289///
4290/// [MS] ms-attribute:
4291///             '[' token-seq ']'
4292///
4293/// [MS] ms-attribute-seq:
4294///             ms-attribute[opt]
4295///             ms-attribute ms-attribute-seq
4296void Parser::ParseMicrosoftAttributes(ParsedAttributes &attrs,
4297                                      SourceLocation *endLoc) {
4298  assert(Tok.is(tok::l_square) && "Not a Microsoft attribute list");
4299
4300  do {
4301    // FIXME: If this is actually a C++11 attribute, parse it as one.
4302    BalancedDelimiterTracker T(*this, tok::l_square);
4303    T.consumeOpen();
4304
4305    // Skip most ms attributes except for a whitelist.
4306    while (true) {
4307      SkipUntil(tok::r_square, tok::identifier, StopAtSemi | StopBeforeMatch);
4308      if (Tok.isNot(tok::identifier)) // ']', but also eof
4309        break;
4310      if (Tok.getIdentifierInfo()->getName() == "uuid")
4311        ParseMicrosoftUuidAttributeArgs(attrs);
4312      else
4313        ConsumeToken();
4314    }
4315
4316    T.consumeClose();
4317    if (endLoc)
4318      *endLoc = T.getCloseLocation();
4319  } while (Tok.is(tok::l_square));
4320}
4321
4322void Parser::ParseMicrosoftIfExistsClassDeclaration(
4323    DeclSpec::TST TagType, ParsedAttributes &AccessAttrs,
4324    AccessSpecifier &CurAS) {
4325  IfExistsCondition Result;
4326  if (ParseMicrosoftIfExistsCondition(Result))
4327    return;
4328
4329  BalancedDelimiterTracker Braces(*this, tok::l_brace);
4330  if (Braces.consumeOpen()) {
4331    Diag(Tok, diag::err_expected) << tok::l_brace;
4332    return;
4333  }
4334
4335  switch (Result.Behavior) {
4336  case IEB_Parse:
4337    // Parse the declarations below.
4338    break;
4339
4340  case IEB_Dependent:
4341    Diag(Result.KeywordLoc, diag::warn_microsoft_dependent_exists)
4342      << Result.IsIfExists;
4343    // Fall through to skip.
4344    LLVM_FALLTHROUGH;
4345
4346  case IEB_Skip:
4347    Braces.skipToEnd();
4348    return;
4349  }
4350
4351  while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
4352    // __if_exists, __if_not_exists can nest.
4353    if (Tok.isOneOf(tok::kw___if_exists, tok::kw___if_not_exists)) {
4354      ParseMicrosoftIfExistsClassDeclaration(TagType,
4355                                             AccessAttrs, CurAS);
4356      continue;
4357    }
4358
4359    // Check for extraneous top-level semicolon.
4360    if (Tok.is(tok::semi)) {
4361      ConsumeExtraSemi(InsideStruct, TagType);
4362      continue;
4363    }
4364
4365    AccessSpecifier AS = getAccessSpecifierIfPresent();
4366    if (AS != AS_none) {
4367      // Current token is a C++ access specifier.
4368      CurAS = AS;
4369      SourceLocation ASLoc = Tok.getLocation();
4370      ConsumeToken();
4371      if (Tok.is(tok::colon))
4372        Actions.ActOnAccessSpecifier(AS, ASLoc, Tok.getLocation(),
4373                                     ParsedAttributesView{});
4374      else
4375        Diag(Tok, diag::err_expected) << tok::colon;
4376      ConsumeToken();
4377      continue;
4378    }
4379
4380    // Parse all the comma separated declarators.
4381    ParseCXXClassMemberDeclaration(CurAS, AccessAttrs);
4382  }
4383
4384  Braces.consumeClose();
4385}
4386