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