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