clang  6.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"
17 #include "clang/Basic/Attributes.h"
18 #include "clang/Basic/CharInfo.h"
20 #include "clang/Basic/TargetInfo.h"
23 #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(unsigned 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().CPlusPlus1z
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().CPlusPlus1z) {
146  Diag(ExtraNamespaceLoc[0],
147  diag::warn_cxx14_compat_nested_namespace_definition);
148  } else {
149  TentativeParsingAction TPA(*this);
150  SkipUntil(tok::r_brace, StopBeforeMatch);
151  Token rBraceToken = Tok;
152  TPA.Revert();
153 
154  if (!rBraceToken.is(tok::r_brace)) {
155  Diag(ExtraNamespaceLoc[0], diag::ext_nested_namespace_definition)
156  << SourceRange(ExtraNamespaceLoc.front(), ExtraIdentLoc.back());
157  } else {
158  std::string NamespaceFix;
159  for (std::vector<IdentifierInfo*>::iterator I = ExtraIdent.begin(),
160  E = ExtraIdent.end(); I != E; ++I) {
161  NamespaceFix += " { namespace ";
162  NamespaceFix += (*I)->getName();
163  }
164 
165  std::string RBraces;
166  for (unsigned i = 0, e = ExtraIdent.size(); i != e; ++i)
167  RBraces += "} ";
168 
169  Diag(ExtraNamespaceLoc[0], diag::ext_nested_namespace_definition)
170  << FixItHint::CreateReplacement(SourceRange(ExtraNamespaceLoc.front(),
171  ExtraIdentLoc.back()),
172  NamespaceFix)
173  << FixItHint::CreateInsertion(rBraceToken.getLocation(), RBraces);
174  }
175  }
176 
177  // If we're still good, complain about inline namespaces in non-C++0x now.
178  if (InlineLoc.isValid())
179  Diag(InlineLoc, getLangOpts().CPlusPlus11 ?
180  diag::warn_cxx98_compat_inline_namespace : diag::ext_inline_namespace);
181 
182  // Enter a scope for the namespace.
183  ParseScope NamespaceScope(this, Scope::DeclScope);
184 
185  UsingDirectiveDecl *ImplicitUsingDirectiveDecl = nullptr;
186  Decl *NamespcDecl =
187  Actions.ActOnStartNamespaceDef(getCurScope(), InlineLoc, NamespaceLoc,
188  IdentLoc, Ident, T.getOpenLocation(),
189  attrs.getList(), ImplicitUsingDirectiveDecl);
190 
191  PrettyDeclStackTraceEntry CrashInfo(Actions, NamespcDecl, NamespaceLoc,
192  "parsing namespace");
193 
194  // Parse the contents of the namespace. This includes parsing recovery on
195  // any improperly nested namespaces.
196  ParseInnerNamespace(ExtraIdentLoc, ExtraIdent, ExtraNamespaceLoc, 0,
197  InlineLoc, attrs, T);
198 
199  // Leave the namespace scope.
200  NamespaceScope.Exit();
201 
202  DeclEnd = T.getCloseLocation();
203  Actions.ActOnFinishNamespaceDef(NamespcDecl, DeclEnd);
204 
205  return Actions.ConvertDeclToDeclGroup(NamespcDecl,
206  ImplicitUsingDirectiveDecl);
207 }
208 
209 /// ParseInnerNamespace - Parse the contents of a namespace.
210 void Parser::ParseInnerNamespace(std::vector<SourceLocation> &IdentLoc,
211  std::vector<IdentifierInfo *> &Ident,
212  std::vector<SourceLocation> &NamespaceLoc,
213  unsigned int index, SourceLocation &InlineLoc,
214  ParsedAttributes &attrs,
215  BalancedDelimiterTracker &Tracker) {
216  if (index == Ident.size()) {
217  while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
218  Tok.isNot(tok::eof)) {
219  ParsedAttributesWithRange attrs(AttrFactory);
220  MaybeParseCXX11Attributes(attrs);
221  ParseExternalDeclaration(attrs);
222  }
223 
224  // The caller is what called check -- we are simply calling
225  // the close for it.
226  Tracker.consumeClose();
227 
228  return;
229  }
230 
231  // Handle a nested namespace definition.
232  // FIXME: Preserve the source information through to the AST rather than
233  // desugaring it here.
234  ParseScope NamespaceScope(this, Scope::DeclScope);
235  UsingDirectiveDecl *ImplicitUsingDirectiveDecl = nullptr;
236  Decl *NamespcDecl =
238  NamespaceLoc[index], IdentLoc[index],
239  Ident[index], Tracker.getOpenLocation(),
240  attrs.getList(), ImplicitUsingDirectiveDecl);
241  assert(!ImplicitUsingDirectiveDecl &&
242  "nested namespace definition cannot define anonymous namespace");
243 
244  ParseInnerNamespace(IdentLoc, Ident, NamespaceLoc, ++index, InlineLoc,
245  attrs, Tracker);
246 
247  NamespaceScope.Exit();
248  Actions.ActOnFinishNamespaceDef(NamespcDecl, Tracker.getCloseLocation());
249 }
250 
251 /// ParseNamespaceAlias - Parse the part after the '=' in a namespace
252 /// alias definition.
253 ///
254 Decl *Parser::ParseNamespaceAlias(SourceLocation NamespaceLoc,
255  SourceLocation AliasLoc,
256  IdentifierInfo *Alias,
257  SourceLocation &DeclEnd) {
258  assert(Tok.is(tok::equal) && "Not equal token");
259 
260  ConsumeToken(); // eat the '='.
261 
262  if (Tok.is(tok::code_completion)) {
264  cutOffParsing();
265  return nullptr;
266  }
267 
268  CXXScopeSpec SS;
269  // Parse (optional) nested-name-specifier.
270  ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false,
271  /*MayBePseudoDestructor=*/nullptr,
272  /*IsTypename=*/false,
273  /*LastII=*/nullptr,
274  /*OnlyNamespace=*/true);
275 
276  if (Tok.isNot(tok::identifier)) {
277  Diag(Tok, diag::err_expected_namespace_name);
278  // Skip to end of the definition and eat the ';'.
279  SkipUntil(tok::semi);
280  return nullptr;
281  }
282 
283  if (SS.isInvalid()) {
284  // Diagnostics have been emitted in ParseOptionalCXXScopeSpecifier.
285  // Skip to end of the definition and eat the ';'.
286  SkipUntil(tok::semi);
287  return nullptr;
288  }
289 
290  // Parse identifier.
291  IdentifierInfo *Ident = Tok.getIdentifierInfo();
292  SourceLocation IdentLoc = ConsumeToken();
293 
294  // Eat the ';'.
295  DeclEnd = Tok.getLocation();
296  if (ExpectAndConsume(tok::semi, diag::err_expected_semi_after_namespace_name))
297  SkipUntil(tok::semi);
298 
299  return Actions.ActOnNamespaceAliasDef(getCurScope(), NamespaceLoc, AliasLoc,
300  Alias, SS, IdentLoc, Ident);
301 }
302 
303 /// ParseLinkage - We know that the current token is a string_literal
304 /// and just before that, that extern was seen.
305 ///
306 /// linkage-specification: [C++ 7.5p2: dcl.link]
307 /// 'extern' string-literal '{' declaration-seq[opt] '}'
308 /// 'extern' string-literal declaration
309 ///
310 Decl *Parser::ParseLinkage(ParsingDeclSpec &DS, unsigned Context) {
311  assert(isTokenStringLiteral() && "Not a string literal!");
312  ExprResult Lang = ParseStringLiteralExpression(false);
313 
314  ParseScope LinkageScope(this, Scope::DeclScope);
315  Decl *LinkageSpec =
316  Lang.isInvalid()
317  ? nullptr
319  getCurScope(), DS.getSourceRange().getBegin(), Lang.get(),
320  Tok.is(tok::l_brace) ? Tok.getLocation() : SourceLocation());
321 
322  ParsedAttributesWithRange attrs(AttrFactory);
323  MaybeParseCXX11Attributes(attrs);
324 
325  if (Tok.isNot(tok::l_brace)) {
326  // Reset the source range in DS, as the leading "extern"
327  // does not really belong to the inner declaration ...
330  // ... but anyway remember that such an "extern" was seen.
331  DS.setExternInLinkageSpec(true);
332  ParseExternalDeclaration(attrs, &DS);
333  return LinkageSpec ? Actions.ActOnFinishLinkageSpecification(
334  getCurScope(), LinkageSpec, SourceLocation())
335  : nullptr;
336  }
337 
338  DS.abort();
339 
340  ProhibitAttributes(attrs);
341 
342  BalancedDelimiterTracker T(*this, tok::l_brace);
343  T.consumeOpen();
344 
345  unsigned NestedModules = 0;
346  while (true) {
347  switch (Tok.getKind()) {
348  case tok::annot_module_begin:
349  ++NestedModules;
351  continue;
352 
353  case tok::annot_module_end:
354  if (!NestedModules)
355  break;
356  --NestedModules;
358  continue;
359 
360  case tok::annot_module_include:
362  continue;
363 
364  case tok::eof:
365  break;
366 
367  case tok::r_brace:
368  if (!NestedModules)
369  break;
370  // Fall through.
371  default:
372  ParsedAttributesWithRange attrs(AttrFactory);
373  MaybeParseCXX11Attributes(attrs);
374  ParseExternalDeclaration(attrs);
375  continue;
376  }
377 
378  break;
379  }
380 
381  T.consumeClose();
382  return LinkageSpec ? Actions.ActOnFinishLinkageSpecification(
383  getCurScope(), LinkageSpec, T.getCloseLocation())
384  : nullptr;
385 }
386 
387 /// Parse a C++ Modules TS export-declaration.
388 ///
389 /// export-declaration:
390 /// 'export' declaration
391 /// 'export' '{' declaration-seq[opt] '}'
392 ///
393 Decl *Parser::ParseExportDeclaration() {
394  assert(Tok.is(tok::kw_export));
395  SourceLocation ExportLoc = ConsumeToken();
396 
397  ParseScope ExportScope(this, Scope::DeclScope);
399  getCurScope(), ExportLoc,
400  Tok.is(tok::l_brace) ? Tok.getLocation() : SourceLocation());
401 
402  if (Tok.isNot(tok::l_brace)) {
403  // FIXME: Factor out a ParseExternalDeclarationWithAttrs.
404  ParsedAttributesWithRange Attrs(AttrFactory);
405  MaybeParseCXX11Attributes(Attrs);
406  MaybeParseMicrosoftAttributes(Attrs);
407  ParseExternalDeclaration(Attrs);
408  return Actions.ActOnFinishExportDecl(getCurScope(), ExportDecl,
409  SourceLocation());
410  }
411 
412  BalancedDelimiterTracker T(*this, tok::l_brace);
413  T.consumeOpen();
414 
415  // The Modules TS draft says "An export-declaration shall declare at least one
416  // entity", but the intent is that it shall contain at least one declaration.
417  if (Tok.is(tok::r_brace))
418  Diag(ExportLoc, diag::err_export_empty)
419  << SourceRange(ExportLoc, Tok.getLocation());
420 
421  while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
422  Tok.isNot(tok::eof)) {
423  ParsedAttributesWithRange Attrs(AttrFactory);
424  MaybeParseCXX11Attributes(Attrs);
425  MaybeParseMicrosoftAttributes(Attrs);
426  ParseExternalDeclaration(Attrs);
427  }
428 
429  T.consumeClose();
430  return Actions.ActOnFinishExportDecl(getCurScope(), ExportDecl,
431  T.getCloseLocation());
432 }
433 
434 /// ParseUsingDirectiveOrDeclaration - Parse C++ using using-declaration or
435 /// using-directive. Assumes that current token is 'using'.
437 Parser::ParseUsingDirectiveOrDeclaration(unsigned Context,
438  const ParsedTemplateInfo &TemplateInfo,
439  SourceLocation &DeclEnd,
440  ParsedAttributesWithRange &attrs) {
441  assert(Tok.is(tok::kw_using) && "Not using token");
442  ObjCDeclContextSwitch ObjCDC(*this);
443 
444  // Eat 'using'.
445  SourceLocation UsingLoc = ConsumeToken();
446 
447  if (Tok.is(tok::code_completion)) {
448  Actions.CodeCompleteUsing(getCurScope());
449  cutOffParsing();
450  return nullptr;
451  }
452 
453  // 'using namespace' means this is a using-directive.
454  if (Tok.is(tok::kw_namespace)) {
455  // Template parameters are always an error here.
456  if (TemplateInfo.Kind) {
457  SourceRange R = TemplateInfo.getSourceRange();
458  Diag(UsingLoc, diag::err_templated_using_directive_declaration)
459  << 0 /* directive */ << R << FixItHint::CreateRemoval(R);
460  }
461 
462  Decl *UsingDir = ParseUsingDirective(Context, UsingLoc, DeclEnd, attrs);
463  return Actions.ConvertDeclToDeclGroup(UsingDir);
464  }
465 
466  // Otherwise, it must be a using-declaration or an alias-declaration.
467 
468  // Using declarations can't have attributes.
469  ProhibitAttributes(attrs);
470 
471  return ParseUsingDeclaration(Context, TemplateInfo, UsingLoc, DeclEnd,
472  AS_none);
473 }
474 
475 /// ParseUsingDirective - Parse C++ using-directive, assumes
476 /// that current token is 'namespace' and 'using' was already parsed.
477 ///
478 /// using-directive: [C++ 7.3.p4: namespace.udir]
479 /// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
480 /// namespace-name ;
481 /// [GNU] using-directive:
482 /// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
483 /// namespace-name attributes[opt] ;
484 ///
485 Decl *Parser::ParseUsingDirective(unsigned Context,
486  SourceLocation UsingLoc,
487  SourceLocation &DeclEnd,
488  ParsedAttributes &attrs) {
489  assert(Tok.is(tok::kw_namespace) && "Not 'namespace' token");
490 
491  // Eat 'namespace'.
492  SourceLocation NamespcLoc = ConsumeToken();
493 
494  if (Tok.is(tok::code_completion)) {
496  cutOffParsing();
497  return nullptr;
498  }
499 
500  CXXScopeSpec SS;
501  // Parse (optional) nested-name-specifier.
502  ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false,
503  /*MayBePseudoDestructor=*/nullptr,
504  /*IsTypename=*/false,
505  /*LastII=*/nullptr,
506  /*OnlyNamespace=*/true);
507 
508  IdentifierInfo *NamespcName = nullptr;
509  SourceLocation IdentLoc = SourceLocation();
510 
511  // Parse namespace-name.
512  if (Tok.isNot(tok::identifier)) {
513  Diag(Tok, diag::err_expected_namespace_name);
514  // If there was invalid namespace name, skip to end of decl, and eat ';'.
515  SkipUntil(tok::semi);
516  // FIXME: Are there cases, when we would like to call ActOnUsingDirective?
517  return nullptr;
518  }
519 
520  if (SS.isInvalid()) {
521  // Diagnostics have been emitted in ParseOptionalCXXScopeSpecifier.
522  // Skip to end of the definition and eat the ';'.
523  SkipUntil(tok::semi);
524  return nullptr;
525  }
526 
527  // Parse identifier.
528  NamespcName = Tok.getIdentifierInfo();
529  IdentLoc = ConsumeToken();
530 
531  // Parse (optional) attributes (most likely GNU strong-using extension).
532  bool GNUAttr = false;
533  if (Tok.is(tok::kw___attribute)) {
534  GNUAttr = true;
535  ParseGNUAttributes(attrs);
536  }
537 
538  // Eat ';'.
539  DeclEnd = Tok.getLocation();
540  if (ExpectAndConsume(tok::semi,
541  GNUAttr ? diag::err_expected_semi_after_attribute_list
542  : diag::err_expected_semi_after_namespace_name))
543  SkipUntil(tok::semi);
544 
545  return Actions.ActOnUsingDirective(getCurScope(), UsingLoc, NamespcLoc, SS,
546  IdentLoc, NamespcName, attrs.getList());
547 }
548 
549 /// Parse a using-declarator (or the identifier in a C++11 alias-declaration).
550 ///
551 /// using-declarator:
552 /// 'typename'[opt] nested-name-specifier unqualified-id
553 ///
554 bool Parser::ParseUsingDeclarator(unsigned Context, UsingDeclarator &D) {
555  D.clear();
556 
557  // Ignore optional 'typename'.
558  // FIXME: This is wrong; we should parse this as a typename-specifier.
559  TryConsumeToken(tok::kw_typename, D.TypenameLoc);
560 
561  if (Tok.is(tok::kw___super)) {
562  Diag(Tok.getLocation(), diag::err_super_in_using_declaration);
563  return true;
564  }
565 
566  // Parse nested-name-specifier.
567  IdentifierInfo *LastII = nullptr;
568  ParseOptionalCXXScopeSpecifier(D.SS, nullptr, /*EnteringContext=*/false,
569  /*MayBePseudoDtor=*/nullptr,
570  /*IsTypename=*/false,
571  /*LastII=*/&LastII);
572  if (D.SS.isInvalid())
573  return true;
574 
575  // Parse the unqualified-id. We allow parsing of both constructor and
576  // destructor names and allow the action module to diagnose any semantic
577  // errors.
578  //
579  // C++11 [class.qual]p2:
580  // [...] in a using-declaration that is a member-declaration, if the name
581  // specified after the nested-name-specifier is the same as the identifier
582  // or the simple-template-id's template-name in the last component of the
583  // nested-name-specifier, the name is [...] considered to name the
584  // constructor.
585  if (getLangOpts().CPlusPlus11 && Context == Declarator::MemberContext &&
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, D.TemplateKWLoc, D.Name))
604  return true;
605  }
606 
607  if (TryConsumeToken(tok::ellipsis, D.EllipsisLoc))
608  Diag(Tok.getLocation(), getLangOpts().CPlusPlus1z ?
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(unsigned 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() != UnqualifiedId::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.getList());
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().CPlusPlus1z ?
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() == UnqualifiedId::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() != UnqualifiedId::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  ParseTypeName(nullptr,
796  TemplateInfo.Kind ? Declarator::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.getList(),
815  TypeAlias, 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().CPlusPlus1z
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.
943  /*IsDecltype=*/true);
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, Declarator::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, Declarator::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 DSC_type_specifier or DSC_alias_declaration.
1616 
1617  // If there are attributes after class name, parse them.
1618  MaybeParseCXX11Attributes(Attributes);
1619 
1620  const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
1621  Sema::TagUseKind TUK;
1622  if (DSC == DSC_trailing)
1623  TUK = Sema::TUK_Reference;
1624  else if (Tok.is(tok::l_brace) ||
1625  (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
1626  (isCXX11FinalKeyword() &&
1627  (NextToken().is(tok::l_brace) || NextToken().is(tok::colon)))) {
1628  if (DS.isFriendSpecified()) {
1629  // C++ [class.friend]p2:
1630  // A class shall not be defined in a friend declaration.
1631  Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
1632  << SourceRange(DS.getFriendSpecLoc());
1633 
1634  // Skip everything up to the semicolon, so that this looks like a proper
1635  // friend class (or template thereof) declaration.
1636  SkipUntil(tok::semi, StopBeforeMatch);
1637  TUK = Sema::TUK_Friend;
1638  } else {
1639  // Okay, this is a class definition.
1640  TUK = Sema::TUK_Definition;
1641  }
1642  } else if (isCXX11FinalKeyword() && (NextToken().is(tok::l_square) ||
1643  NextToken().is(tok::kw_alignas))) {
1644  // We can't tell if this is a definition or reference
1645  // until we skipped the 'final' and C++11 attribute specifiers.
1646  TentativeParsingAction PA(*this);
1647 
1648  // Skip the 'final' keyword.
1649  ConsumeToken();
1650 
1651  // Skip C++11 attribute specifiers.
1652  while (true) {
1653  if (Tok.is(tok::l_square) && NextToken().is(tok::l_square)) {
1654  ConsumeBracket();
1655  if (!SkipUntil(tok::r_square, StopAtSemi))
1656  break;
1657  } else if (Tok.is(tok::kw_alignas) && NextToken().is(tok::l_paren)) {
1658  ConsumeToken();
1659  ConsumeParen();
1660  if (!SkipUntil(tok::r_paren, StopAtSemi))
1661  break;
1662  } else {
1663  break;
1664  }
1665  }
1666 
1667  if (Tok.isOneOf(tok::l_brace, tok::colon))
1668  TUK = Sema::TUK_Definition;
1669  else
1670  TUK = Sema::TUK_Reference;
1671 
1672  PA.Revert();
1673  } else if (!isTypeSpecifier(DSC) &&
1674  (Tok.is(tok::semi) ||
1675  (Tok.isAtStartOfLine() && !isValidAfterTypeSpecifier(false)))) {
1677  if (Tok.isNot(tok::semi)) {
1678  const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
1679  // A semicolon was missing after this declaration. Diagnose and recover.
1680  ExpectAndConsume(tok::semi, diag::err_expected_after,
1681  DeclSpec::getSpecifierName(TagType, PPol));
1682  PP.EnterToken(Tok);
1683  Tok.setKind(tok::semi);
1684  }
1685  } else
1686  TUK = Sema::TUK_Reference;
1687 
1688  // Forbid misplaced attributes. In cases of a reference, we pass attributes
1689  // to caller to handle.
1690  if (TUK != Sema::TUK_Reference) {
1691  // If this is not a reference, then the only possible
1692  // valid place for C++11 attributes to appear here
1693  // is between class-key and class-name. If there are
1694  // any attributes after class-name, we try a fixit to move
1695  // them to the right place.
1696  SourceRange AttrRange = Attributes.Range;
1697  if (AttrRange.isValid()) {
1698  Diag(AttrRange.getBegin(), diag::err_attributes_not_allowed)
1699  << AttrRange
1700  << FixItHint::CreateInsertionFromRange(AttrFixitLoc,
1701  CharSourceRange(AttrRange, true))
1702  << FixItHint::CreateRemoval(AttrRange);
1703 
1704  // Recover by adding misplaced attributes to the attribute list
1705  // of the class so they can be applied on the class later.
1706  attrs.takeAllFrom(Attributes);
1707  }
1708  }
1709 
1710  // If this is an elaborated type specifier, and we delayed
1711  // diagnostics before, just merge them into the current pool.
1712  if (shouldDelayDiagsInTag) {
1713  diagsFromTag.done();
1714  if (TUK == Sema::TUK_Reference)
1715  diagsFromTag.redelay();
1716  }
1717 
1718  if (!Name && !TemplateId && (DS.getTypeSpecType() == DeclSpec::TST_error ||
1719  TUK != Sema::TUK_Definition)) {
1720  if (DS.getTypeSpecType() != DeclSpec::TST_error) {
1721  // We have a declaration or reference to an anonymous class.
1722  Diag(StartLoc, diag::err_anon_type_definition)
1723  << DeclSpec::getSpecifierName(TagType, Policy);
1724  }
1725 
1726  // If we are parsing a definition and stop at a base-clause, continue on
1727  // until the semicolon. Continuing from the comma will just trick us into
1728  // thinking we are seeing a variable declaration.
1729  if (TUK == Sema::TUK_Definition && Tok.is(tok::colon))
1730  SkipUntil(tok::semi, StopBeforeMatch);
1731  else
1732  SkipUntil(tok::comma, StopAtSemi);
1733  return;
1734  }
1735 
1736  // Create the tag portion of the class or class template.
1737  DeclResult TagOrTempResult = true; // invalid
1738  TypeResult TypeResult = true; // invalid
1739 
1740  bool Owned = false;
1741  Sema::SkipBodyInfo SkipBody;
1742  if (TemplateId) {
1743  // Explicit specialization, class template partial specialization,
1744  // or explicit instantiation.
1745  ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1746  TemplateId->NumArgs);
1747  if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
1748  TUK == Sema::TUK_Declaration) {
1749  // This is an explicit instantiation of a class template.
1750  ProhibitAttributes(attrs);
1751 
1752  TagOrTempResult
1753  = Actions.ActOnExplicitInstantiation(getCurScope(),
1754  TemplateInfo.ExternLoc,
1755  TemplateInfo.TemplateLoc,
1756  TagType,
1757  StartLoc,
1758  SS,
1759  TemplateId->Template,
1760  TemplateId->TemplateNameLoc,
1761  TemplateId->LAngleLoc,
1762  TemplateArgsPtr,
1763  TemplateId->RAngleLoc,
1764  attrs.getList());
1765 
1766  // Friend template-ids are treated as references unless
1767  // they have template headers, in which case they're ill-formed
1768  // (FIXME: "template <class T> friend class A<T>::B<int>;").
1769  // We diagnose this error in ActOnClassTemplateSpecialization.
1770  } else if (TUK == Sema::TUK_Reference ||
1771  (TUK == Sema::TUK_Friend &&
1772  TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate)) {
1773  ProhibitAttributes(attrs);
1774  TypeResult = Actions.ActOnTagTemplateIdType(TUK, TagType, StartLoc,
1775  TemplateId->SS,
1776  TemplateId->TemplateKWLoc,
1777  TemplateId->Template,
1778  TemplateId->TemplateNameLoc,
1779  TemplateId->LAngleLoc,
1780  TemplateArgsPtr,
1781  TemplateId->RAngleLoc);
1782  } else {
1783  // This is an explicit specialization or a class template
1784  // partial specialization.
1785  TemplateParameterLists FakedParamLists;
1786  if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1787  // This looks like an explicit instantiation, because we have
1788  // something like
1789  //
1790  // template class Foo<X>
1791  //
1792  // but it actually has a definition. Most likely, this was
1793  // meant to be an explicit specialization, but the user forgot
1794  // the '<>' after 'template'.
1795  // It this is friend declaration however, since it cannot have a
1796  // template header, it is most likely that the user meant to
1797  // remove the 'template' keyword.
1798  assert((TUK == Sema::TUK_Definition || TUK == Sema::TUK_Friend) &&
1799  "Expected a definition here");
1800 
1801  if (TUK == Sema::TUK_Friend) {
1802  Diag(DS.getFriendSpecLoc(), diag::err_friend_explicit_instantiation);
1803  TemplateParams = nullptr;
1804  } else {
1805  SourceLocation LAngleLoc =
1806  PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
1807  Diag(TemplateId->TemplateNameLoc,
1808  diag::err_explicit_instantiation_with_definition)
1809  << SourceRange(TemplateInfo.TemplateLoc)
1810  << FixItHint::CreateInsertion(LAngleLoc, "<>");
1811 
1812  // Create a fake template parameter list that contains only
1813  // "template<>", so that we treat this construct as a class
1814  // template specialization.
1815  FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
1816  0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
1817  LAngleLoc, nullptr));
1818  TemplateParams = &FakedParamLists;
1819  }
1820  }
1821 
1822  // Build the class template specialization.
1823  TagOrTempResult = Actions.ActOnClassTemplateSpecialization(
1824  getCurScope(), TagType, TUK, StartLoc, DS.getModulePrivateSpecLoc(),
1825  *TemplateId, attrs.getList(),
1826  MultiTemplateParamsArg(TemplateParams ? &(*TemplateParams)[0]
1827  : nullptr,
1828  TemplateParams ? TemplateParams->size() : 0),
1829  &SkipBody);
1830  }
1831  } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
1832  TUK == Sema::TUK_Declaration) {
1833  // Explicit instantiation of a member of a class template
1834  // specialization, e.g.,
1835  //
1836  // template struct Outer<int>::Inner;
1837  //
1838  ProhibitAttributes(attrs);
1839 
1840  TagOrTempResult
1841  = Actions.ActOnExplicitInstantiation(getCurScope(),
1842  TemplateInfo.ExternLoc,
1843  TemplateInfo.TemplateLoc,
1844  TagType, StartLoc, SS, Name,
1845  NameLoc, attrs.getList());
1846  } else if (TUK == Sema::TUK_Friend &&
1847  TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate) {
1848  ProhibitAttributes(attrs);
1849 
1850  TagOrTempResult =
1851  Actions.ActOnTemplatedFriendTag(getCurScope(), DS.getFriendSpecLoc(),
1852  TagType, StartLoc, SS,
1853  Name, NameLoc, attrs.getList(),
1855  TemplateParams? &(*TemplateParams)[0]
1856  : nullptr,
1857  TemplateParams? TemplateParams->size() : 0));
1858  } else {
1859  if (TUK != Sema::TUK_Declaration && TUK != Sema::TUK_Definition)
1860  ProhibitAttributes(attrs);
1861 
1862  if (TUK == Sema::TUK_Definition &&
1863  TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1864  // If the declarator-id is not a template-id, issue a diagnostic and
1865  // recover by ignoring the 'template' keyword.
1866  Diag(Tok, diag::err_template_defn_explicit_instantiation)
1867  << 1 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
1868  TemplateParams = nullptr;
1869  }
1870 
1871  bool IsDependent = false;
1872 
1873  // Don't pass down template parameter lists if this is just a tag
1874  // reference. For example, we don't need the template parameters here:
1875  // template <class T> class A *makeA(T t);
1876  MultiTemplateParamsArg TParams;
1877  if (TUK != Sema::TUK_Reference && TemplateParams)
1878  TParams =
1879  MultiTemplateParamsArg(&(*TemplateParams)[0], TemplateParams->size());
1880 
1881  stripTypeAttributesOffDeclSpec(attrs, DS, TUK);
1882 
1883  // Declaration or definition of a class type
1884  TagOrTempResult = Actions.ActOnTag(getCurScope(), TagType, TUK, StartLoc,
1885  SS, Name, NameLoc, attrs.getList(), AS,
1887  TParams, Owned, IsDependent,
1888  SourceLocation(), false,
1890  DSC == DSC_type_specifier,
1891  DSC == DSC_template_param ||
1892  DSC == DSC_template_type_arg, &SkipBody);
1893 
1894  // If ActOnTag said the type was dependent, try again with the
1895  // less common call.
1896  if (IsDependent) {
1897  assert(TUK == Sema::TUK_Reference || TUK == Sema::TUK_Friend);
1898  TypeResult = Actions.ActOnDependentTag(getCurScope(), TagType, TUK,
1899  SS, Name, StartLoc, NameLoc);
1900  }
1901  }
1902 
1903  // If there is a body, parse it and inform the actions module.
1904  if (TUK == Sema::TUK_Definition) {
1905  assert(Tok.is(tok::l_brace) ||
1906  (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
1907  isCXX11FinalKeyword());
1908  if (SkipBody.ShouldSkip)
1909  SkipCXXMemberSpecification(StartLoc, AttrFixitLoc, TagType,
1910  TagOrTempResult.get());
1911  else if (getLangOpts().CPlusPlus)
1912  ParseCXXMemberSpecification(StartLoc, AttrFixitLoc, attrs, TagType,
1913  TagOrTempResult.get());
1914  else {
1915  Decl *D =
1916  SkipBody.CheckSameAsPrevious ? SkipBody.New : TagOrTempResult.get();
1917  // Parse the definition body.
1918  ParseStructUnionBody(StartLoc, TagType, D);
1919  if (SkipBody.CheckSameAsPrevious &&
1920  !Actions.ActOnDuplicateDefinition(DS, TagOrTempResult.get(),
1921  SkipBody)) {
1922  DS.SetTypeSpecError();
1923  return;
1924  }
1925  }
1926  }
1927 
1928  if (!TagOrTempResult.isInvalid())
1929  // Delayed processing of attributes.
1930  Actions.ProcessDeclAttributeDelayed(TagOrTempResult.get(), attrs.getList());
1931 
1932  const char *PrevSpec = nullptr;
1933  unsigned DiagID;
1934  bool Result;
1935  if (!TypeResult.isInvalid()) {
1936  Result = DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
1937  NameLoc.isValid() ? NameLoc : StartLoc,
1938  PrevSpec, DiagID, TypeResult.get(), Policy);
1939  } else if (!TagOrTempResult.isInvalid()) {
1940  Result = DS.SetTypeSpecType(TagType, StartLoc,
1941  NameLoc.isValid() ? NameLoc : StartLoc,
1942  PrevSpec, DiagID, TagOrTempResult.get(), Owned,
1943  Policy);
1944  } else {
1945  DS.SetTypeSpecError();
1946  return;
1947  }
1948 
1949  if (Result)
1950  Diag(StartLoc, DiagID) << PrevSpec;
1951 
1952  // At this point, we've successfully parsed a class-specifier in 'definition'
1953  // form (e.g. "struct foo { int x; }". While we could just return here, we're
1954  // going to look at what comes after it to improve error recovery. If an
1955  // impossible token occurs next, we assume that the programmer forgot a ; at
1956  // the end of the declaration and recover that way.
1957  //
1958  // Also enforce C++ [temp]p3:
1959  // In a template-declaration which defines a class, no declarator
1960  // is permitted.
1961  //
1962  // After a type-specifier, we don't expect a semicolon. This only happens in
1963  // C, since definitions are not permitted in this context in C++.
1964  if (TUK == Sema::TUK_Definition &&
1965  (getLangOpts().CPlusPlus || !isTypeSpecifier(DSC)) &&
1966  (TemplateInfo.Kind || !isValidAfterTypeSpecifier(false))) {
1967  if (Tok.isNot(tok::semi)) {
1968  const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
1969  ExpectAndConsume(tok::semi, diag::err_expected_after,
1970  DeclSpec::getSpecifierName(TagType, PPol));
1971  // Push this token back into the preprocessor and change our current token
1972  // to ';' so that the rest of the code recovers as though there were an
1973  // ';' after the definition.
1974  PP.EnterToken(Tok);
1975  Tok.setKind(tok::semi);
1976  }
1977  }
1978 }
1979 
1980 /// ParseBaseClause - Parse the base-clause of a C++ class [C++ class.derived].
1981 ///
1982 /// base-clause : [C++ class.derived]
1983 /// ':' base-specifier-list
1984 /// base-specifier-list:
1985 /// base-specifier '...'[opt]
1986 /// base-specifier-list ',' base-specifier '...'[opt]
1987 void Parser::ParseBaseClause(Decl *ClassDecl) {
1988  assert(Tok.is(tok::colon) && "Not a base clause");
1989  ConsumeToken();
1990 
1991  // Build up an array of parsed base specifiers.
1993 
1994  while (true) {
1995  // Parse a base-specifier.
1996  BaseResult Result = ParseBaseSpecifier(ClassDecl);
1997  if (Result.isInvalid()) {
1998  // Skip the rest of this base specifier, up until the comma or
1999  // opening brace.
2000  SkipUntil(tok::comma, tok::l_brace, StopAtSemi | StopBeforeMatch);
2001  } else {
2002  // Add this to our array of base specifiers.
2003  BaseInfo.push_back(Result.get());
2004  }
2005 
2006  // If the next token is a comma, consume it and keep reading
2007  // base-specifiers.
2008  if (!TryConsumeToken(tok::comma))
2009  break;
2010  }
2011 
2012  // Attach the base specifiers
2013  Actions.ActOnBaseSpecifiers(ClassDecl, BaseInfo);
2014 }
2015 
2016 /// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is
2017 /// one entry in the base class list of a class specifier, for example:
2018 /// class foo : public bar, virtual private baz {
2019 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2020 ///
2021 /// base-specifier: [C++ class.derived]
2022 /// attribute-specifier-seq[opt] base-type-specifier
2023 /// attribute-specifier-seq[opt] 'virtual' access-specifier[opt]
2024 /// base-type-specifier
2025 /// attribute-specifier-seq[opt] access-specifier 'virtual'[opt]
2026 /// base-type-specifier
2027 BaseResult Parser::ParseBaseSpecifier(Decl *ClassDecl) {
2028  bool IsVirtual = false;
2029  SourceLocation StartLoc = Tok.getLocation();
2030 
2031  ParsedAttributesWithRange Attributes(AttrFactory);
2032  MaybeParseCXX11Attributes(Attributes);
2033 
2034  // Parse the 'virtual' keyword.
2035  if (TryConsumeToken(tok::kw_virtual))
2036  IsVirtual = true;
2037 
2038  CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2039 
2040  // Parse an (optional) access specifier.
2041  AccessSpecifier Access = getAccessSpecifierIfPresent();
2042  if (Access != AS_none)
2043  ConsumeToken();
2044 
2045  CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2046 
2047  // Parse the 'virtual' keyword (again!), in case it came after the
2048  // access specifier.
2049  if (Tok.is(tok::kw_virtual)) {
2050  SourceLocation VirtualLoc = ConsumeToken();
2051  if (IsVirtual) {
2052  // Complain about duplicate 'virtual'
2053  Diag(VirtualLoc, diag::err_dup_virtual)
2054  << FixItHint::CreateRemoval(VirtualLoc);
2055  }
2056 
2057  IsVirtual = true;
2058  }
2059 
2060  CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2061 
2062  // Parse the class-name.
2063 
2064  // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
2065  // implementation for VS2013 uses _Atomic as an identifier for one of the
2066  // classes in <atomic>. Treat '_Atomic' to be an identifier when we are
2067  // parsing the class-name for a base specifier.
2068  if (getLangOpts().MSVCCompat && Tok.is(tok::kw__Atomic) &&
2069  NextToken().is(tok::less))
2070  Tok.setKind(tok::identifier);
2071 
2072  SourceLocation EndLocation;
2073  SourceLocation BaseLoc;
2074  TypeResult BaseType = ParseBaseTypeSpecifier(BaseLoc, EndLocation);
2075  if (BaseType.isInvalid())
2076  return true;
2077 
2078  // Parse the optional ellipsis (for a pack expansion). The ellipsis is
2079  // actually part of the base-specifier-list grammar productions, but we
2080  // parse it here for convenience.
2081  SourceLocation EllipsisLoc;
2082  TryConsumeToken(tok::ellipsis, EllipsisLoc);
2083 
2084  // Find the complete source range for the base-specifier.
2085  SourceRange Range(StartLoc, EndLocation);
2086 
2087  // Notify semantic analysis that we have parsed a complete
2088  // base-specifier.
2089  return Actions.ActOnBaseSpecifier(ClassDecl, Range, Attributes, IsVirtual,
2090  Access, BaseType.get(), BaseLoc,
2091  EllipsisLoc);
2092 }
2093 
2094 /// getAccessSpecifierIfPresent - Determine whether the next token is
2095 /// a C++ access-specifier.
2096 ///
2097 /// access-specifier: [C++ class.derived]
2098 /// 'private'
2099 /// 'protected'
2100 /// 'public'
2101 AccessSpecifier Parser::getAccessSpecifierIfPresent() const {
2102  switch (Tok.getKind()) {
2103  default: return AS_none;
2104  case tok::kw_private: return AS_private;
2105  case tok::kw_protected: return AS_protected;
2106  case tok::kw_public: return AS_public;
2107  }
2108 }
2109 
2110 /// \brief If the given declarator has any parts for which parsing has to be
2111 /// delayed, e.g., default arguments or an exception-specification, create a
2112 /// late-parsed method declaration record to handle the parsing at the end of
2113 /// the class definition.
2114 void Parser::HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
2115  Decl *ThisDecl) {
2117  = DeclaratorInfo.getFunctionTypeInfo();
2118  // If there was a late-parsed exception-specification, we'll need a
2119  // late parse
2120  bool NeedLateParse = FTI.getExceptionSpecType() == EST_Unparsed;
2121 
2122  if (!NeedLateParse) {
2123  // Look ahead to see if there are any default args
2124  for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx) {
2125  auto Param = cast<ParmVarDecl>(FTI.Params[ParamIdx].Param);
2126  if (Param->hasUnparsedDefaultArg()) {
2127  NeedLateParse = true;
2128  break;
2129  }
2130  }
2131  }
2132 
2133  if (NeedLateParse) {
2134  // Push this method onto the stack of late-parsed method
2135  // declarations.
2136  auto LateMethod = new LateParsedMethodDeclaration(this, ThisDecl);
2137  getCurrentClass().LateParsedDeclarations.push_back(LateMethod);
2138  LateMethod->TemplateScope = getCurScope()->isTemplateParamScope();
2139 
2140  // Stash the exception-specification tokens in the late-pased method.
2141  LateMethod->ExceptionSpecTokens = FTI.ExceptionSpecTokens;
2142  FTI.ExceptionSpecTokens = nullptr;
2143 
2144  // Push tokens for each parameter. Those that do not have
2145  // defaults will be NULL.
2146  LateMethod->DefaultArgs.reserve(FTI.NumParams);
2147  for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx)
2148  LateMethod->DefaultArgs.push_back(LateParsedDefaultArgument(
2149  FTI.Params[ParamIdx].Param,
2150  std::move(FTI.Params[ParamIdx].DefaultArgTokens)));
2151  }
2152 }
2153 
2154 /// isCXX11VirtSpecifier - Determine whether the given token is a C++11
2155 /// virt-specifier.
2156 ///
2157 /// virt-specifier:
2158 /// override
2159 /// final
2160 /// __final
2161 VirtSpecifiers::Specifier Parser::isCXX11VirtSpecifier(const Token &Tok) const {
2162  if (!getLangOpts().CPlusPlus || Tok.isNot(tok::identifier))
2163  return VirtSpecifiers::VS_None;
2164 
2165  IdentifierInfo *II = Tok.getIdentifierInfo();
2166 
2167  // Initialize the contextual keywords.
2168  if (!Ident_final) {
2169  Ident_final = &PP.getIdentifierTable().get("final");
2170  if (getLangOpts().GNUKeywords)
2171  Ident_GNU_final = &PP.getIdentifierTable().get("__final");
2172  if (getLangOpts().MicrosoftExt)
2173  Ident_sealed = &PP.getIdentifierTable().get("sealed");
2174  Ident_override = &PP.getIdentifierTable().get("override");
2175  }
2176 
2177  if (II == Ident_override)
2179 
2180  if (II == Ident_sealed)
2182 
2183  if (II == Ident_final)
2184  return VirtSpecifiers::VS_Final;
2185 
2186  if (II == Ident_GNU_final)
2188 
2189  return VirtSpecifiers::VS_None;
2190 }
2191 
2192 /// ParseOptionalCXX11VirtSpecifierSeq - Parse a virt-specifier-seq.
2193 ///
2194 /// virt-specifier-seq:
2195 /// virt-specifier
2196 /// virt-specifier-seq virt-specifier
2197 void Parser::ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS,
2198  bool IsInterface,
2199  SourceLocation FriendLoc) {
2200  while (true) {
2201  VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
2202  if (Specifier == VirtSpecifiers::VS_None)
2203  return;
2204 
2205  if (FriendLoc.isValid()) {
2206  Diag(Tok.getLocation(), diag::err_friend_decl_spec)
2207  << VirtSpecifiers::getSpecifierName(Specifier)
2209  << SourceRange(FriendLoc, FriendLoc);
2210  ConsumeToken();
2211  continue;
2212  }
2213 
2214  // C++ [class.mem]p8:
2215  // A virt-specifier-seq shall contain at most one of each virt-specifier.
2216  const char *PrevSpec = nullptr;
2217  if (VS.SetSpecifier(Specifier, Tok.getLocation(), PrevSpec))
2218  Diag(Tok.getLocation(), diag::err_duplicate_virt_specifier)
2219  << PrevSpec
2221 
2222  if (IsInterface && (Specifier == VirtSpecifiers::VS_Final ||
2223  Specifier == VirtSpecifiers::VS_Sealed)) {
2224  Diag(Tok.getLocation(), diag::err_override_control_interface)
2225  << VirtSpecifiers::getSpecifierName(Specifier);
2226  } else if (Specifier == VirtSpecifiers::VS_Sealed) {
2227  Diag(Tok.getLocation(), diag::ext_ms_sealed_keyword);
2228  } else if (Specifier == VirtSpecifiers::VS_GNU_Final) {
2229  Diag(Tok.getLocation(), diag::ext_warn_gnu_final);
2230  } else {
2231  Diag(Tok.getLocation(),
2232  getLangOpts().CPlusPlus11
2233  ? diag::warn_cxx98_compat_override_control_keyword
2234  : diag::ext_override_control_keyword)
2235  << VirtSpecifiers::getSpecifierName(Specifier);
2236  }
2237  ConsumeToken();
2238  }
2239 }
2240 
2241 /// isCXX11FinalKeyword - Determine whether the next token is a C++11
2242 /// 'final' or Microsoft 'sealed' contextual keyword.
2243 bool Parser::isCXX11FinalKeyword() const {
2244  VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
2245  return Specifier == VirtSpecifiers::VS_Final ||
2246  Specifier == VirtSpecifiers::VS_GNU_Final ||
2247  Specifier == VirtSpecifiers::VS_Sealed;
2248 }
2249 
2250 /// \brief Parse a C++ member-declarator up to, but not including, the optional
2251 /// brace-or-equal-initializer or pure-specifier.
2252 bool Parser::ParseCXXMemberDeclaratorBeforeInitializer(
2253  Declarator &DeclaratorInfo, VirtSpecifiers &VS, ExprResult &BitfieldSize,
2254  LateParsedAttrList &LateParsedAttrs) {
2255  // member-declarator:
2256  // declarator pure-specifier[opt]
2257  // declarator brace-or-equal-initializer[opt]
2258  // identifier[opt] ':' constant-expression
2259  if (Tok.isNot(tok::colon))
2260  ParseDeclarator(DeclaratorInfo);
2261  else
2262  DeclaratorInfo.SetIdentifier(nullptr, Tok.getLocation());
2263 
2264  if (!DeclaratorInfo.isFunctionDeclarator() && TryConsumeToken(tok::colon)) {
2265  assert(DeclaratorInfo.isPastIdentifier() &&
2266  "don't know where identifier would go yet?");
2267  BitfieldSize = ParseConstantExpression();
2268  if (BitfieldSize.isInvalid())
2269  SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2270  } else {
2271  ParseOptionalCXX11VirtSpecifierSeq(
2272  VS, getCurrentClass().IsInterface,
2273  DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
2274  if (!VS.isUnset())
2275  MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo, VS);
2276  }
2277 
2278  // If a simple-asm-expr is present, parse it.
2279  if (Tok.is(tok::kw_asm)) {
2280  SourceLocation Loc;
2281  ExprResult AsmLabel(ParseSimpleAsm(&Loc));
2282  if (AsmLabel.isInvalid())
2283  SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2284 
2285  DeclaratorInfo.setAsmLabel(AsmLabel.get());
2286  DeclaratorInfo.SetRangeEnd(Loc);
2287  }
2288 
2289  // If attributes exist after the declarator, but before an '{', parse them.
2290  MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
2291 
2292  // For compatibility with code written to older Clang, also accept a
2293  // virt-specifier *after* the GNU attributes.
2294  if (BitfieldSize.isUnset() && VS.isUnset()) {
2295  ParseOptionalCXX11VirtSpecifierSeq(
2296  VS, getCurrentClass().IsInterface,
2297  DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
2298  if (!VS.isUnset()) {
2299  // If we saw any GNU-style attributes that are known to GCC followed by a
2300  // virt-specifier, issue a GCC-compat warning.
2301  const AttributeList *Attr = DeclaratorInfo.getAttributes();
2302  while (Attr) {
2303  if (Attr->isKnownToGCC() && !Attr->isCXX11Attribute())
2304  Diag(Attr->getLoc(), diag::warn_gcc_attribute_location);
2305  Attr = Attr->getNext();
2306  }
2307  MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo, VS);
2308  }
2309  }
2310 
2311  // If this has neither a name nor a bit width, something has gone seriously
2312  // wrong. Skip until the semi-colon or }.
2313  if (!DeclaratorInfo.hasName() && BitfieldSize.isUnset()) {
2314  // If so, skip until the semi-colon or a }.
2315  SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2316  return true;
2317  }
2318  return false;
2319 }
2320 
2321 /// \brief Look for declaration specifiers possibly occurring after C++11
2322 /// virt-specifier-seq and diagnose them.
2323 void Parser::MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(
2324  Declarator &D,
2325  VirtSpecifiers &VS) {
2326  DeclSpec DS(AttrFactory);
2327 
2328  // GNU-style and C++11 attributes are not allowed here, but they will be
2329  // handled by the caller. Diagnose everything else.
2330  ParseTypeQualifierListOpt(
2331  DS, AR_NoAttributesParsed, false,
2332  /*IdentifierRequired=*/false, llvm::function_ref<void()>([&]() {
2333  Actions.CodeCompleteFunctionQualifiers(DS, D, &VS);
2334  }));
2335  D.ExtendWithDeclSpec(DS);
2336 
2337  if (D.isFunctionDeclarator()) {
2338  auto &Function = D.getFunctionTypeInfo();
2340  auto DeclSpecCheck = [&] (DeclSpec::TQ TypeQual,
2341  const char *FixItName,
2342  SourceLocation SpecLoc,
2343  unsigned* QualifierLoc) {
2344  FixItHint Insertion;
2345  if (DS.getTypeQualifiers() & TypeQual) {
2346  if (!(Function.TypeQuals & TypeQual)) {
2347  std::string Name(FixItName);
2348  Name += " ";
2349  Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), Name);
2350  Function.TypeQuals |= TypeQual;
2351  *QualifierLoc = SpecLoc.getRawEncoding();
2352  }
2353  Diag(SpecLoc, diag::err_declspec_after_virtspec)
2354  << FixItName
2356  << FixItHint::CreateRemoval(SpecLoc)
2357  << Insertion;
2358  }
2359  };
2360  DeclSpecCheck(DeclSpec::TQ_const, "const", DS.getConstSpecLoc(),
2361  &Function.ConstQualifierLoc);
2362  DeclSpecCheck(DeclSpec::TQ_volatile, "volatile", DS.getVolatileSpecLoc(),
2363  &Function.VolatileQualifierLoc);
2364  DeclSpecCheck(DeclSpec::TQ_restrict, "restrict", DS.getRestrictSpecLoc(),
2365  &Function.RestrictQualifierLoc);
2366  }
2367 
2368  // Parse ref-qualifiers.
2369  bool RefQualifierIsLValueRef = true;
2370  SourceLocation RefQualifierLoc;
2371  if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc)) {
2372  const char *Name = (RefQualifierIsLValueRef ? "& " : "&& ");
2373  FixItHint Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), Name);
2374  Function.RefQualifierIsLValueRef = RefQualifierIsLValueRef;
2375  Function.RefQualifierLoc = RefQualifierLoc.getRawEncoding();
2376 
2377  Diag(RefQualifierLoc, diag::err_declspec_after_virtspec)
2378  << (RefQualifierIsLValueRef ? "&" : "&&")
2380  << FixItHint::CreateRemoval(RefQualifierLoc)
2381  << Insertion;
2382  D.SetRangeEnd(RefQualifierLoc);
2383  }
2384  }
2385 }
2386 
2387 /// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration.
2388 ///
2389 /// member-declaration:
2390 /// decl-specifier-seq[opt] member-declarator-list[opt] ';'
2391 /// function-definition ';'[opt]
2392 /// ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO]
2393 /// using-declaration [TODO]
2394 /// [C++0x] static_assert-declaration
2395 /// template-declaration
2396 /// [GNU] '__extension__' member-declaration
2397 ///
2398 /// member-declarator-list:
2399 /// member-declarator
2400 /// member-declarator-list ',' member-declarator
2401 ///
2402 /// member-declarator:
2403 /// declarator virt-specifier-seq[opt] pure-specifier[opt]
2404 /// declarator constant-initializer[opt]
2405 /// [C++11] declarator brace-or-equal-initializer[opt]
2406 /// identifier[opt] ':' constant-expression
2407 ///
2408 /// virt-specifier-seq:
2409 /// virt-specifier
2410 /// virt-specifier-seq virt-specifier
2411 ///
2412 /// virt-specifier:
2413 /// override
2414 /// final
2415 /// [MS] sealed
2416 ///
2417 /// pure-specifier:
2418 /// '= 0'
2419 ///
2420 /// constant-initializer:
2421 /// '=' constant-expression
2422 ///
2424 Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS,
2425  AttributeList *AccessAttrs,
2426  const ParsedTemplateInfo &TemplateInfo,
2427  ParsingDeclRAIIObject *TemplateDiags) {
2428  if (Tok.is(tok::at)) {
2429  if (getLangOpts().ObjC1 && NextToken().isObjCAtKeyword(tok::objc_defs))
2430  Diag(Tok, diag::err_at_defs_cxx);
2431  else
2432  Diag(Tok, diag::err_at_in_class);
2433 
2434  ConsumeToken();
2435  SkipUntil(tok::r_brace, StopAtSemi);
2436  return nullptr;
2437  }
2438 
2439  // Turn on colon protection early, while parsing declspec, although there is
2440  // nothing to protect there. It prevents from false errors if error recovery
2441  // incorrectly determines where the declspec ends, as in the example:
2442  // struct A { enum class B { C }; };
2443  // const int C = 4;
2444  // struct D { A::B : C; };
2446 
2447  // Access declarations.
2448  bool MalformedTypeSpec = false;
2449  if (!TemplateInfo.Kind &&
2450  Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw___super)) {
2452  MalformedTypeSpec = true;
2453 
2454  bool isAccessDecl;
2455  if (Tok.isNot(tok::annot_cxxscope))
2456  isAccessDecl = false;
2457  else if (NextToken().is(tok::identifier))
2458  isAccessDecl = GetLookAheadToken(2).is(tok::semi);
2459  else
2460  isAccessDecl = NextToken().is(tok::kw_operator);
2461 
2462  if (isAccessDecl) {
2463  // Collect the scope specifier token we annotated earlier.
2464  CXXScopeSpec SS;
2465  ParseOptionalCXXScopeSpecifier(SS, nullptr,
2466  /*EnteringContext=*/false);
2467 
2468  if (SS.isInvalid()) {
2469  SkipUntil(tok::semi);
2470  return nullptr;
2471  }
2472 
2473  // Try to parse an unqualified-id.
2474  SourceLocation TemplateKWLoc;
2475  UnqualifiedId Name;
2476  if (ParseUnqualifiedId(SS, false, true, true, false, nullptr,
2477  TemplateKWLoc, Name)) {
2478  SkipUntil(tok::semi);
2479  return nullptr;
2480  }
2481 
2482  // TODO: recover from mistakenly-qualified operator declarations.
2483  if (ExpectAndConsume(tok::semi, diag::err_expected_after,
2484  "access declaration")) {
2485  SkipUntil(tok::semi);
2486  return nullptr;
2487  }
2488 
2489  return DeclGroupPtrTy::make(DeclGroupRef(Actions.ActOnUsingDeclaration(
2490  getCurScope(), AS, /*UsingLoc*/ SourceLocation(),
2491  /*TypenameLoc*/ SourceLocation(), SS, Name,
2492  /*EllipsisLoc*/ SourceLocation(), /*AttrList*/ nullptr)));
2493  }
2494  }
2495 
2496  // static_assert-declaration. A templated static_assert declaration is
2497  // diagnosed in Parser::ParseSingleDeclarationAfterTemplate.
2498  if (!TemplateInfo.Kind &&
2499  Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert)) {
2500  SourceLocation DeclEnd;
2501  return DeclGroupPtrTy::make(
2502  DeclGroupRef(ParseStaticAssertDeclaration(DeclEnd)));
2503  }
2504 
2505  if (Tok.is(tok::kw_template)) {
2506  assert(!TemplateInfo.TemplateParams &&
2507  "Nested template improperly parsed?");
2508  ObjCDeclContextSwitch ObjCDC(*this);
2509  SourceLocation DeclEnd;
2510  return DeclGroupPtrTy::make(
2511  DeclGroupRef(ParseTemplateDeclarationOrSpecialization(
2512  Declarator::MemberContext, DeclEnd, AS, AccessAttrs)));
2513  }
2514 
2515  // Handle: member-declaration ::= '__extension__' member-declaration
2516  if (Tok.is(tok::kw___extension__)) {
2517  // __extension__ silences extension warnings in the subexpression.
2518  ExtensionRAIIObject O(Diags); // Use RAII to do this.
2519  ConsumeToken();
2520  return ParseCXXClassMemberDeclaration(AS, AccessAttrs,
2521  TemplateInfo, TemplateDiags);
2522  }
2523 
2524  ParsedAttributesWithRange attrs(AttrFactory);
2525  ParsedAttributesWithRange FnAttrs(AttrFactory);
2526  // Optional C++11 attribute-specifier
2527  MaybeParseCXX11Attributes(attrs);
2528  // We need to keep these attributes for future diagnostic
2529  // before they are taken over by declaration specifier.
2530  FnAttrs.addAll(attrs.getList());
2531  FnAttrs.Range = attrs.Range;
2532 
2533  MaybeParseMicrosoftAttributes(attrs);
2534 
2535  if (Tok.is(tok::kw_using)) {
2536  ProhibitAttributes(attrs);
2537 
2538  // Eat 'using'.
2539  SourceLocation UsingLoc = ConsumeToken();
2540 
2541  if (Tok.is(tok::kw_namespace)) {
2542  Diag(UsingLoc, diag::err_using_namespace_in_class);
2543  SkipUntil(tok::semi, StopBeforeMatch);
2544  return nullptr;
2545  }
2546  SourceLocation DeclEnd;
2547  // Otherwise, it must be a using-declaration or an alias-declaration.
2548  return ParseUsingDeclaration(Declarator::MemberContext, TemplateInfo,
2549  UsingLoc, DeclEnd, AS);
2550  }
2551 
2552  // Hold late-parsed attributes so we can attach a Decl to them later.
2553  LateParsedAttrList CommonLateParsedAttrs;
2554 
2555  // decl-specifier-seq:
2556  // Parse the common declaration-specifiers piece.
2557  ParsingDeclSpec DS(*this, TemplateDiags);
2558  DS.takeAttributesFrom(attrs);
2559  if (MalformedTypeSpec)
2560  DS.SetTypeSpecError();
2561 
2562  ParseDeclarationSpecifiers(DS, TemplateInfo, AS, DSC_class,
2563  &CommonLateParsedAttrs);
2564 
2565  // Turn off colon protection that was set for declspec.
2566  X.restore();
2567 
2568  // If we had a free-standing type definition with a missing semicolon, we
2569  // may get this far before the problem becomes obvious.
2570  if (DS.hasTagDefinition() &&
2571  TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate &&
2572  DiagnoseMissingSemiAfterTagDefinition(DS, AS, DSC_class,
2573  &CommonLateParsedAttrs))
2574  return nullptr;
2575 
2576  MultiTemplateParamsArg TemplateParams(
2577  TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->data()
2578  : nullptr,
2579  TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->size() : 0);
2580 
2581  if (TryConsumeToken(tok::semi)) {
2582  if (DS.isFriendSpecified())
2583  ProhibitAttributes(FnAttrs);
2584 
2585  RecordDecl *AnonRecord = nullptr;
2586  Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(
2587  getCurScope(), AS, DS, TemplateParams, false, AnonRecord);
2588  DS.complete(TheDecl);
2589  if (AnonRecord) {
2590  Decl* decls[] = {AnonRecord, TheDecl};
2591  return Actions.BuildDeclaratorGroup(decls);
2592  }
2593  return Actions.ConvertDeclToDeclGroup(TheDecl);
2594  }
2595 
2596  ParsingDeclarator DeclaratorInfo(*this, DS, Declarator::MemberContext);
2597  VirtSpecifiers VS;
2598 
2599  // Hold late-parsed attributes so we can attach a Decl to them later.
2600  LateParsedAttrList LateParsedAttrs;
2601 
2602  SourceLocation EqualLoc;
2603  SourceLocation PureSpecLoc;
2604 
2605  auto TryConsumePureSpecifier = [&] (bool AllowDefinition) {
2606  if (Tok.isNot(tok::equal))
2607  return false;
2608 
2609  auto &Zero = NextToken();
2610  SmallString<8> Buffer;
2611  if (Zero.isNot(tok::numeric_constant) || Zero.getLength() != 1 ||
2612  PP.getSpelling(Zero, Buffer) != "0")
2613  return false;
2614 
2615  auto &After = GetLookAheadToken(2);
2616  if (!After.isOneOf(tok::semi, tok::comma) &&
2617  !(AllowDefinition &&
2618  After.isOneOf(tok::l_brace, tok::colon, tok::kw_try)))
2619  return false;
2620 
2621  EqualLoc = ConsumeToken();
2622  PureSpecLoc = ConsumeToken();
2623  return true;
2624  };
2625 
2626  SmallVector<Decl *, 8> DeclsInGroup;
2627  ExprResult BitfieldSize;
2628  bool ExpectSemi = true;
2629 
2630  // Parse the first declarator.
2631  if (ParseCXXMemberDeclaratorBeforeInitializer(
2632  DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs)) {
2633  TryConsumeToken(tok::semi);
2634  return nullptr;
2635  }
2636 
2637  // Check for a member function definition.
2638  if (BitfieldSize.isUnset()) {
2639  // MSVC permits pure specifier on inline functions defined at class scope.
2640  // Hence check for =0 before checking for function definition.
2641  if (getLangOpts().MicrosoftExt && DeclaratorInfo.isDeclarationOfFunction())
2642  TryConsumePureSpecifier(/*AllowDefinition*/ true);
2643 
2644  FunctionDefinitionKind DefinitionKind = FDK_Declaration;
2645  // function-definition:
2646  //
2647  // In C++11, a non-function declarator followed by an open brace is a
2648  // braced-init-list for an in-class member initialization, not an
2649  // erroneous function definition.
2650  if (Tok.is(tok::l_brace) && !getLangOpts().CPlusPlus11) {
2651  DefinitionKind = FDK_Definition;
2652  } else if (DeclaratorInfo.isFunctionDeclarator()) {
2653  if (Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try)) {
2654  DefinitionKind = FDK_Definition;
2655  } else if (Tok.is(tok::equal)) {
2656  const Token &KW = NextToken();
2657  if (KW.is(tok::kw_default))
2658  DefinitionKind = FDK_Defaulted;
2659  else if (KW.is(tok::kw_delete))
2660  DefinitionKind = FDK_Deleted;
2661  }
2662  }
2663  DeclaratorInfo.setFunctionDefinitionKind(DefinitionKind);
2664 
2665  // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
2666  // to a friend declaration, that declaration shall be a definition.
2667  if (DeclaratorInfo.isFunctionDeclarator() &&
2668  DefinitionKind != FDK_Definition && DS.isFriendSpecified()) {
2669  // Diagnose attributes that appear before decl specifier:
2670  // [[]] friend int foo();
2671  ProhibitAttributes(FnAttrs);
2672  }
2673 
2674  if (DefinitionKind != FDK_Declaration) {
2675  if (!DeclaratorInfo.isFunctionDeclarator()) {
2676  Diag(DeclaratorInfo.getIdentifierLoc(), diag::err_func_def_no_params);
2677  ConsumeBrace();
2678  SkipUntil(tok::r_brace);
2679 
2680  // Consume the optional ';'
2681  TryConsumeToken(tok::semi);
2682 
2683  return nullptr;
2684  }
2685 
2687  Diag(DeclaratorInfo.getIdentifierLoc(),
2688  diag::err_function_declared_typedef);
2689 
2690  // Recover by treating the 'typedef' as spurious.
2692  }
2693 
2694  Decl *FunDecl =
2695  ParseCXXInlineMethodDef(AS, AccessAttrs, DeclaratorInfo, TemplateInfo,
2696  VS, PureSpecLoc);
2697 
2698  if (FunDecl) {
2699  for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i) {
2700  CommonLateParsedAttrs[i]->addDecl(FunDecl);
2701  }
2702  for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i) {
2703  LateParsedAttrs[i]->addDecl(FunDecl);
2704  }
2705  }
2706  LateParsedAttrs.clear();
2707 
2708  // Consume the ';' - it's optional unless we have a delete or default
2709  if (Tok.is(tok::semi))
2710  ConsumeExtraSemi(AfterMemberFunctionDefinition);
2711 
2712  return DeclGroupPtrTy::make(DeclGroupRef(FunDecl));
2713  }
2714  }
2715 
2716  // member-declarator-list:
2717  // member-declarator
2718  // member-declarator-list ',' member-declarator
2719 
2720  while (1) {
2721  InClassInitStyle HasInClassInit = ICIS_NoInit;
2722  bool HasStaticInitializer = false;
2723  if (Tok.isOneOf(tok::equal, tok::l_brace) && PureSpecLoc.isInvalid()) {
2724  if (DeclaratorInfo.isDeclarationOfFunction()) {
2725  // It's a pure-specifier.
2726  if (!TryConsumePureSpecifier(/*AllowFunctionDefinition*/ false))
2727  // Parse it as an expression so that Sema can diagnose it.
2728  HasStaticInitializer = true;
2729  } else if (DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2731  DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2733  !DS.isFriendSpecified()) {
2734  // It's a default member initializer.
2735  if (BitfieldSize.get())
2736  Diag(Tok, getLangOpts().CPlusPlus2a
2737  ? diag::warn_cxx17_compat_bitfield_member_init
2738  : diag::ext_bitfield_member_init);
2739  HasInClassInit = Tok.is(tok::equal) ? ICIS_CopyInit : ICIS_ListInit;
2740  } else {
2741  HasStaticInitializer = true;
2742  }
2743  }
2744 
2745  // NOTE: If Sema is the Action module and declarator is an instance field,
2746  // this call will *not* return the created decl; It will return null.
2747  // See Sema::ActOnCXXMemberDeclarator for details.
2748 
2749  NamedDecl *ThisDecl = nullptr;
2750  if (DS.isFriendSpecified()) {
2751  // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
2752  // to a friend declaration, that declaration shall be a definition.
2753  //
2754  // Diagnose attributes that appear in a friend member function declarator:
2755  // friend int foo [[]] ();
2757  DeclaratorInfo.getCXX11AttributeRanges(Ranges);
2758  for (SmallVectorImpl<SourceRange>::iterator I = Ranges.begin(),
2759  E = Ranges.end(); I != E; ++I)
2760  Diag((*I).getBegin(), diag::err_attributes_not_allowed) << *I;
2761 
2762  ThisDecl = Actions.ActOnFriendFunctionDecl(getCurScope(), DeclaratorInfo,
2763  TemplateParams);
2764  } else {
2765  ThisDecl = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS,
2766  DeclaratorInfo,
2767  TemplateParams,
2768  BitfieldSize.get(),
2769  VS, HasInClassInit);
2770 
2771  if (VarTemplateDecl *VT =
2772  ThisDecl ? dyn_cast<VarTemplateDecl>(ThisDecl) : nullptr)
2773  // Re-direct this decl to refer to the templated decl so that we can
2774  // initialize it.
2775  ThisDecl = VT->getTemplatedDecl();
2776 
2777  if (ThisDecl && AccessAttrs)
2778  Actions.ProcessDeclAttributeList(getCurScope(), ThisDecl, AccessAttrs);
2779  }
2780 
2781  // Error recovery might have converted a non-static member into a static
2782  // member.
2783  if (HasInClassInit != ICIS_NoInit &&
2784  DeclaratorInfo.getDeclSpec().getStorageClassSpec() ==
2786  HasInClassInit = ICIS_NoInit;
2787  HasStaticInitializer = true;
2788  }
2789 
2790  if (ThisDecl && PureSpecLoc.isValid())
2791  Actions.ActOnPureSpecifier(ThisDecl, PureSpecLoc);
2792 
2793  // Handle the initializer.
2794  if (HasInClassInit != ICIS_NoInit) {
2795  // The initializer was deferred; parse it and cache the tokens.
2797  ? diag::warn_cxx98_compat_nonstatic_member_init
2798  : diag::ext_nonstatic_member_init);
2799 
2800  if (DeclaratorInfo.isArrayOfUnknownBound()) {
2801  // C++11 [dcl.array]p3: An array bound may also be omitted when the
2802  // declarator is followed by an initializer.
2803  //
2804  // A brace-or-equal-initializer for a member-declarator is not an
2805  // initializer in the grammar, so this is ill-formed.
2806  Diag(Tok, diag::err_incomplete_array_member_init);
2807  SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2808 
2809  // Avoid later warnings about a class member of incomplete type.
2810  if (ThisDecl)
2811  ThisDecl->setInvalidDecl();
2812  } else
2813  ParseCXXNonStaticMemberInitializer(ThisDecl);
2814  } else if (HasStaticInitializer) {
2815  // Normal initializer.
2816  ExprResult Init = ParseCXXMemberInitializer(
2817  ThisDecl, DeclaratorInfo.isDeclarationOfFunction(), EqualLoc);
2818 
2819  if (Init.isInvalid())
2820  SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2821  else if (ThisDecl)
2822  Actions.AddInitializerToDecl(ThisDecl, Init.get(), EqualLoc.isInvalid());
2823  } else if (ThisDecl && DS.getStorageClassSpec() == DeclSpec::SCS_static)
2824  // No initializer.
2825  Actions.ActOnUninitializedDecl(ThisDecl);
2826 
2827  if (ThisDecl) {
2828  if (!ThisDecl->isInvalidDecl()) {
2829  // Set the Decl for any late parsed attributes
2830  for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i)
2831  CommonLateParsedAttrs[i]->addDecl(ThisDecl);
2832 
2833  for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i)
2834  LateParsedAttrs[i]->addDecl(ThisDecl);
2835  }
2836  Actions.FinalizeDeclaration(ThisDecl);
2837  DeclsInGroup.push_back(ThisDecl);
2838 
2839  if (DeclaratorInfo.isFunctionDeclarator() &&
2840  DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2842  HandleMemberFunctionDeclDelays(DeclaratorInfo, ThisDecl);
2843  }
2844  LateParsedAttrs.clear();
2845 
2846  DeclaratorInfo.complete(ThisDecl);
2847 
2848  // If we don't have a comma, it is either the end of the list (a ';')
2849  // or an error, bail out.
2850  SourceLocation CommaLoc;
2851  if (!TryConsumeToken(tok::comma, CommaLoc))
2852  break;
2853 
2854  if (Tok.isAtStartOfLine() &&
2855  !MightBeDeclarator(Declarator::MemberContext)) {
2856  // This comma was followed by a line-break and something which can't be
2857  // the start of a declarator. The comma was probably a typo for a
2858  // semicolon.
2859  Diag(CommaLoc, diag::err_expected_semi_declaration)
2860  << FixItHint::CreateReplacement(CommaLoc, ";");
2861  ExpectSemi = false;
2862  break;
2863  }
2864 
2865  // Parse the next declarator.
2866  DeclaratorInfo.clear();
2867  VS.clear();
2868  BitfieldSize = ExprResult(/*Invalid=*/false);
2869  EqualLoc = PureSpecLoc = SourceLocation();
2870  DeclaratorInfo.setCommaLoc(CommaLoc);
2871 
2872  // GNU attributes are allowed before the second and subsequent declarator.
2873  MaybeParseGNUAttributes(DeclaratorInfo);
2874 
2875  if (ParseCXXMemberDeclaratorBeforeInitializer(
2876  DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs))
2877  break;
2878  }
2879 
2880  if (ExpectSemi &&
2881  ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list)) {
2882  // Skip to end of block or statement.
2883  SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2884  // If we stopped at a ';', eat it.
2885  TryConsumeToken(tok::semi);
2886  return nullptr;
2887  }
2888 
2889  return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
2890 }
2891 
2892 /// ParseCXXMemberInitializer - Parse the brace-or-equal-initializer.
2893 /// Also detect and reject any attempted defaulted/deleted function definition.
2894 /// The location of the '=', if any, will be placed in EqualLoc.
2895 ///
2896 /// This does not check for a pure-specifier; that's handled elsewhere.
2897 ///
2898 /// brace-or-equal-initializer:
2899 /// '=' initializer-expression
2900 /// braced-init-list
2901 ///
2902 /// initializer-clause:
2903 /// assignment-expression
2904 /// braced-init-list
2905 ///
2906 /// defaulted/deleted function-definition:
2907 /// '=' 'default'
2908 /// '=' 'delete'
2909 ///
2910 /// Prior to C++0x, the assignment-expression in an initializer-clause must
2911 /// be a constant-expression.
2912 ExprResult Parser::ParseCXXMemberInitializer(Decl *D, bool IsFunction,
2913  SourceLocation &EqualLoc) {
2914  assert(Tok.isOneOf(tok::equal, tok::l_brace)
2915  && "Data member initializer not starting with '=' or '{'");
2916 
2919  if (TryConsumeToken(tok::equal, EqualLoc)) {
2920  if (Tok.is(tok::kw_delete)) {
2921  // In principle, an initializer of '= delete p;' is legal, but it will
2922  // never type-check. It's better to diagnose it as an ill-formed expression
2923  // than as an ill-formed deleted non-function member.
2924  // An initializer of '= delete p, foo' will never be parsed, because
2925  // a top-level comma always ends the initializer expression.
2926  const Token &Next = NextToken();
2927  if (IsFunction || Next.isOneOf(tok::semi, tok::comma, tok::eof)) {
2928  if (IsFunction)
2929  Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2930  << 1 /* delete */;
2931  else
2932  Diag(ConsumeToken(), diag::err_deleted_non_function);
2933  return ExprError();
2934  }
2935  } else if (Tok.is(tok::kw_default)) {
2936  if (IsFunction)
2937  Diag(Tok, diag::err_default_delete_in_multiple_declaration)
2938  << 0 /* default */;
2939  else
2940  Diag(ConsumeToken(), diag::err_default_special_members);
2941  return ExprError();
2942  }
2943  }
2944  if (const auto *PD = dyn_cast_or_null<MSPropertyDecl>(D)) {
2945  Diag(Tok, diag::err_ms_property_initializer) << PD;
2946  return ExprError();
2947  }
2948  return ParseInitializer();
2949 }
2950 
2951 void Parser::SkipCXXMemberSpecification(SourceLocation RecordLoc,
2952  SourceLocation AttrFixitLoc,
2953  unsigned TagType, Decl *TagDecl) {
2954  // Skip the optional 'final' keyword.
2955  if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
2956  assert(isCXX11FinalKeyword() && "not a class definition");
2957  ConsumeToken();
2958 
2959  // Diagnose any C++11 attributes after 'final' keyword.
2960  // We deliberately discard these attributes.
2961  ParsedAttributesWithRange Attrs(AttrFactory);
2962  CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
2963 
2964  // This can only happen if we had malformed misplaced attributes;
2965  // we only get called if there is a colon or left-brace after the
2966  // attributes.
2967  if (Tok.isNot(tok::colon) && Tok.isNot(tok::l_brace))
2968  return;
2969  }
2970 
2971  // Skip the base clauses. This requires actually parsing them, because
2972  // otherwise we can't be sure where they end (a left brace may appear
2973  // within a template argument).
2974  if (Tok.is(tok::colon)) {
2975  // Enter the scope of the class so that we can correctly parse its bases.
2976  ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
2977  ParsingClassDefinition ParsingDef(*this, TagDecl, /*NonNestedClass*/ true,
2978  TagType == DeclSpec::TST_interface);
2979  auto OldContext =
2980  Actions.ActOnTagStartSkippedDefinition(getCurScope(), TagDecl);
2981 
2982  // Parse the bases but don't attach them to the class.
2983  ParseBaseClause(nullptr);
2984 
2985  Actions.ActOnTagFinishSkippedDefinition(OldContext);
2986 
2987  if (!Tok.is(tok::l_brace)) {
2988  Diag(PP.getLocForEndOfToken(PrevTokLocation),
2989  diag::err_expected_lbrace_after_base_specifiers);
2990  return;
2991  }
2992  }
2993 
2994  // Skip the body.
2995  assert(Tok.is(tok::l_brace));
2996  BalancedDelimiterTracker T(*this, tok::l_brace);
2997  T.consumeOpen();
2998  T.skipToEnd();
2999 
3000  // Parse and discard any trailing attributes.
3001  ParsedAttributes Attrs(AttrFactory);
3002  if (Tok.is(tok::kw___attribute))
3003  MaybeParseGNUAttributes(Attrs);
3004 }
3005 
3006 Parser::DeclGroupPtrTy Parser::ParseCXXClassMemberDeclarationWithPragmas(
3007  AccessSpecifier &AS, ParsedAttributesWithRange &AccessAttrs,
3008  DeclSpec::TST TagType, Decl *TagDecl) {
3009  switch (Tok.getKind()) {
3010  case tok::kw___if_exists:
3011  case tok::kw___if_not_exists:
3012  ParseMicrosoftIfExistsClassDeclaration(TagType, AS);
3013  return nullptr;
3014 
3015  case tok::semi:
3016  // Check for extraneous top-level semicolon.
3017  ConsumeExtraSemi(InsideStruct, TagType);
3018  return nullptr;
3019 
3020  // Handle pragmas that can appear as member declarations.
3021  case tok::annot_pragma_vis:
3022  HandlePragmaVisibility();
3023  return nullptr;
3024  case tok::annot_pragma_pack:
3025  HandlePragmaPack();
3026  return nullptr;
3027  case tok::annot_pragma_align:
3028  HandlePragmaAlign();
3029  return nullptr;
3030  case tok::annot_pragma_ms_pointers_to_members:
3031  HandlePragmaMSPointersToMembers();
3032  return nullptr;
3033  case tok::annot_pragma_ms_pragma:
3034  HandlePragmaMSPragma();
3035  return nullptr;
3036  case tok::annot_pragma_ms_vtordisp:
3037  HandlePragmaMSVtorDisp();
3038  return nullptr;
3039  case tok::annot_pragma_dump:
3040  HandlePragmaDump();
3041  return nullptr;
3042 
3043  case tok::kw_namespace:
3044  // If we see a namespace here, a close brace was missing somewhere.
3045  DiagnoseUnexpectedNamespace(cast<NamedDecl>(TagDecl));
3046  return nullptr;
3047 
3048  case tok::kw_public:
3049  case tok::kw_protected:
3050  case tok::kw_private: {
3051  AccessSpecifier NewAS = getAccessSpecifierIfPresent();
3052  assert(NewAS != AS_none);
3053  // Current token is a C++ access specifier.
3054  AS = NewAS;
3055  SourceLocation ASLoc = Tok.getLocation();
3056  unsigned TokLength = Tok.getLength();
3057  ConsumeToken();
3058  AccessAttrs.clear();
3059  MaybeParseGNUAttributes(AccessAttrs);
3060 
3061  SourceLocation EndLoc;
3062  if (TryConsumeToken(tok::colon, EndLoc)) {
3063  } else if (TryConsumeToken(tok::semi, EndLoc)) {
3064  Diag(EndLoc, diag::err_expected)
3065  << tok::colon << FixItHint::CreateReplacement(EndLoc, ":");
3066  } else {
3067  EndLoc = ASLoc.getLocWithOffset(TokLength);
3068  Diag(EndLoc, diag::err_expected)
3069  << tok::colon << FixItHint::CreateInsertion(EndLoc, ":");
3070  }
3071 
3072  // The Microsoft extension __interface does not permit non-public
3073  // access specifiers.
3074  if (TagType == DeclSpec::TST_interface && AS != AS_public) {
3075  Diag(ASLoc, diag::err_access_specifier_interface) << (AS == AS_protected);
3076  }
3077 
3078  if (Actions.ActOnAccessSpecifier(NewAS, ASLoc, EndLoc,
3079  AccessAttrs.getList())) {
3080  // found another attribute than only annotations
3081  AccessAttrs.clear();
3082  }
3083 
3084  return nullptr;
3085  }
3086 
3087  case tok::annot_pragma_openmp:
3088  return ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, AccessAttrs, TagType,
3089  TagDecl);
3090 
3091  default:
3092  return ParseCXXClassMemberDeclaration(AS, AccessAttrs.getList());
3093  }
3094 }
3095 
3096 /// ParseCXXMemberSpecification - Parse the class definition.
3097 ///
3098 /// member-specification:
3099 /// member-declaration member-specification[opt]
3100 /// access-specifier ':' member-specification[opt]
3101 ///
3102 void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc,
3103  SourceLocation AttrFixitLoc,
3104  ParsedAttributesWithRange &Attrs,
3105  unsigned TagType, Decl *TagDecl) {
3106  assert((TagType == DeclSpec::TST_struct ||
3107  TagType == DeclSpec::TST_interface ||
3108  TagType == DeclSpec::TST_union ||
3109  TagType == DeclSpec::TST_class) && "Invalid TagType!");
3110 
3111  PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc,
3112  "parsing struct/union/class body");
3113 
3114  // Determine whether this is a non-nested class. Note that local
3115  // classes are *not* considered to be nested classes.
3116  bool NonNestedClass = true;
3117  if (!ClassStack.empty()) {
3118  for (const Scope *S = getCurScope(); S; S = S->getParent()) {
3119  if (S->isClassScope()) {
3120  // We're inside a class scope, so this is a nested class.
3121  NonNestedClass = false;
3122 
3123  // The Microsoft extension __interface does not permit nested classes.
3124  if (getCurrentClass().IsInterface) {
3125  Diag(RecordLoc, diag::err_invalid_member_in_interface)
3126  << /*ErrorType=*/6
3127  << (isa<NamedDecl>(TagDecl)
3128  ? cast<NamedDecl>(TagDecl)->getQualifiedNameAsString()
3129  : "(anonymous)");
3130  }
3131  break;
3132  }
3133 
3134  if ((S->getFlags() & Scope::FnScope))
3135  // If we're in a function or function template then this is a local
3136  // class rather than a nested class.
3137  break;
3138  }
3139  }
3140 
3141  // Enter a scope for the class.
3142  ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
3143 
3144  // Note that we are parsing a new (potentially-nested) class definition.
3145  ParsingClassDefinition ParsingDef(*this, TagDecl, NonNestedClass,
3146  TagType == DeclSpec::TST_interface);
3147 
3148  if (TagDecl)
3149  Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
3150 
3151  SourceLocation FinalLoc;
3152  bool IsFinalSpelledSealed = false;
3153 
3154  // Parse the optional 'final' keyword.
3155  if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
3156  VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier(Tok);
3157  assert((Specifier == VirtSpecifiers::VS_Final ||
3158  Specifier == VirtSpecifiers::VS_GNU_Final ||
3159  Specifier == VirtSpecifiers::VS_Sealed) &&
3160  "not a class definition");
3161  FinalLoc = ConsumeToken();
3162  IsFinalSpelledSealed = Specifier == VirtSpecifiers::VS_Sealed;
3163 
3164  if (TagType == DeclSpec::TST_interface)
3165  Diag(FinalLoc, diag::err_override_control_interface)
3166  << VirtSpecifiers::getSpecifierName(Specifier);
3167  else if (Specifier == VirtSpecifiers::VS_Final)
3168  Diag(FinalLoc, getLangOpts().CPlusPlus11
3169  ? diag::warn_cxx98_compat_override_control_keyword
3170  : diag::ext_override_control_keyword)
3171  << VirtSpecifiers::getSpecifierName(Specifier);
3172  else if (Specifier == VirtSpecifiers::VS_Sealed)
3173  Diag(FinalLoc, diag::ext_ms_sealed_keyword);
3174  else if (Specifier == VirtSpecifiers::VS_GNU_Final)
3175  Diag(FinalLoc, diag::ext_warn_gnu_final);
3176 
3177  // Parse any C++11 attributes after 'final' keyword.
3178  // These attributes are not allowed to appear here,
3179  // and the only possible place for them to appertain
3180  // to the class would be between class-key and class-name.
3181  CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
3182 
3183  // ParseClassSpecifier() does only a superficial check for attributes before
3184  // deciding to call this method. For example, for
3185  // `class C final alignas ([l) {` it will decide that this looks like a
3186  // misplaced attribute since it sees `alignas '(' ')'`. But the actual
3187  // attribute parsing code will try to parse the '[' as a constexpr lambda
3188  // and consume enough tokens that the alignas parsing code will eat the
3189  // opening '{'. So bail out if the next token isn't one we expect.
3190  if (!Tok.is(tok::colon) && !Tok.is(tok::l_brace)) {
3191  if (TagDecl)
3192  Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
3193  return;
3194  }
3195  }
3196 
3197  if (Tok.is(tok::colon)) {
3198  ParseBaseClause(TagDecl);
3199  if (!Tok.is(tok::l_brace)) {
3200  bool SuggestFixIt = false;
3201  SourceLocation BraceLoc = PP.getLocForEndOfToken(PrevTokLocation);
3202  if (Tok.isAtStartOfLine()) {
3203  switch (Tok.getKind()) {
3204  case tok::kw_private:
3205  case tok::kw_protected:
3206  case tok::kw_public:
3207  SuggestFixIt = NextToken().getKind() == tok::colon;
3208  break;
3209  case tok::kw_static_assert:
3210  case tok::r_brace:
3211  case tok::kw_using:
3212  // base-clause can have simple-template-id; 'template' can't be there
3213  case tok::kw_template:
3214  SuggestFixIt = true;
3215  break;
3216  case tok::identifier:
3217  SuggestFixIt = isConstructorDeclarator(true);
3218  break;
3219  default:
3220  SuggestFixIt = isCXXSimpleDeclaration(/*AllowForRangeDecl=*/false);
3221  break;
3222  }
3223  }
3224  DiagnosticBuilder LBraceDiag =
3225  Diag(BraceLoc, diag::err_expected_lbrace_after_base_specifiers);
3226  if (SuggestFixIt) {
3227  LBraceDiag << FixItHint::CreateInsertion(BraceLoc, " {");
3228  // Try recovering from missing { after base-clause.
3229  PP.EnterToken(Tok);
3230  Tok.setKind(tok::l_brace);
3231  } else {
3232  if (TagDecl)
3233  Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
3234  return;
3235  }
3236  }
3237  }
3238 
3239  assert(Tok.is(tok::l_brace));
3240  BalancedDelimiterTracker T(*this, tok::l_brace);
3241  T.consumeOpen();
3242 
3243  if (TagDecl)
3244  Actions.ActOnStartCXXMemberDeclarations(getCurScope(), TagDecl, FinalLoc,
3245  IsFinalSpelledSealed,
3246  T.getOpenLocation());
3247 
3248  // C++ 11p3: Members of a class defined with the keyword class are private
3249  // by default. Members of a class defined with the keywords struct or union
3250  // are public by default.
3251  AccessSpecifier CurAS;
3252  if (TagType == DeclSpec::TST_class)
3253  CurAS = AS_private;
3254  else
3255  CurAS = AS_public;
3256  ParsedAttributesWithRange AccessAttrs(AttrFactory);
3257 
3258  if (TagDecl) {
3259  // While we still have something to read, read the member-declarations.
3260  while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
3261  Tok.isNot(tok::eof)) {
3262  // Each iteration of this loop reads one member-declaration.
3263  ParseCXXClassMemberDeclarationWithPragmas(
3264  CurAS, AccessAttrs, static_cast<DeclSpec::TST>(TagType), TagDecl);
3265  }
3266  T.consumeClose();
3267  } else {
3268  SkipUntil(tok::r_brace);
3269  }
3270 
3271  // If attributes exist after class contents, parse them.
3272  ParsedAttributes attrs(AttrFactory);
3273  MaybeParseGNUAttributes(attrs);
3274 
3275  if (TagDecl)
3276  Actions.ActOnFinishCXXMemberSpecification(getCurScope(), RecordLoc, TagDecl,
3277  T.getOpenLocation(),
3278  T.getCloseLocation(),
3279  attrs.getList());
3280 
3281  // C++11 [class.mem]p2:
3282  // Within the class member-specification, the class is regarded as complete
3283  // within function bodies, default arguments, exception-specifications, and
3284  // brace-or-equal-initializers for non-static data members (including such
3285  // things in nested classes).
3286  if (TagDecl && NonNestedClass) {
3287  // We are not inside a nested class. This class and its nested classes
3288  // are complete and we can parse the delayed portions of method
3289  // declarations and the lexed inline method definitions, along with any
3290  // delayed attributes.
3291  SourceLocation SavedPrevTokLocation = PrevTokLocation;
3292  ParseLexedAttributes(getCurrentClass());
3293  ParseLexedMethodDeclarations(getCurrentClass());
3294 
3295  // We've finished with all pending member declarations.
3296  Actions.ActOnFinishCXXMemberDecls();
3297 
3298  ParseLexedMemberInitializers(getCurrentClass());
3299  ParseLexedMethodDefs(getCurrentClass());
3300  PrevTokLocation = SavedPrevTokLocation;
3301 
3302  // We've finished parsing everything, including default argument
3303  // initializers.
3304  Actions.ActOnFinishCXXNonNestedClass(TagDecl);
3305  }
3306 
3307  if (TagDecl)
3308  Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getRange());
3309 
3310  // Leave the class scope.
3311  ParsingDef.Pop();
3312  ClassScope.Exit();
3313 }
3314 
3315 void Parser::DiagnoseUnexpectedNamespace(NamedDecl *D) {
3316  assert(Tok.is(tok::kw_namespace));
3317 
3318  // FIXME: Suggest where the close brace should have gone by looking
3319  // at indentation changes within the definition body.
3320  Diag(D->getLocation(),
3321  diag::err_missing_end_of_definition) << D;
3322  Diag(Tok.getLocation(),
3323  diag::note_missing_end_of_definition_before) << D;
3324 
3325  // Push '};' onto the token stream to recover.
3326  PP.EnterToken(Tok);
3327 
3328  Tok.startToken();
3329  Tok.setLocation(PP.getLocForEndOfToken(PrevTokLocation));
3330  Tok.setKind(tok::semi);
3331  PP.EnterToken(Tok);
3332 
3333  Tok.setKind(tok::r_brace);
3334 }
3335 
3336 /// ParseConstructorInitializer - Parse a C++ constructor initializer,
3337 /// which explicitly initializes the members or base classes of a
3338 /// class (C++ [class.base.init]). For example, the three initializers
3339 /// after the ':' in the Derived constructor below:
3340 ///
3341 /// @code
3342 /// class Base { };
3343 /// class Derived : Base {
3344 /// int x;
3345 /// float f;
3346 /// public:
3347 /// Derived(float f) : Base(), x(17), f(f) { }
3348 /// };
3349 /// @endcode
3350 ///
3351 /// [C++] ctor-initializer:
3352 /// ':' mem-initializer-list
3353 ///
3354 /// [C++] mem-initializer-list:
3355 /// mem-initializer ...[opt]
3356 /// mem-initializer ...[opt] , mem-initializer-list
3357 void Parser::ParseConstructorInitializer(Decl *ConstructorDecl) {
3358  assert(Tok.is(tok::colon) &&
3359  "Constructor initializer always starts with ':'");
3360 
3361  // Poison the SEH identifiers so they are flagged as illegal in constructor
3362  // initializers.
3363  PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
3365 
3366  SmallVector<CXXCtorInitializer*, 4> MemInitializers;
3367  bool AnyErrors = false;
3368 
3369  do {
3370  if (Tok.is(tok::code_completion)) {
3371  Actions.CodeCompleteConstructorInitializer(ConstructorDecl,
3372  MemInitializers);
3373  return cutOffParsing();
3374  }
3375 
3376  MemInitResult MemInit = ParseMemInitializer(ConstructorDecl);
3377  if (!MemInit.isInvalid())
3378  MemInitializers.push_back(MemInit.get());
3379  else
3380  AnyErrors = true;
3381 
3382  if (Tok.is(tok::comma))
3383  ConsumeToken();
3384  else if (Tok.is(tok::l_brace))
3385  break;
3386  // If the previous initializer was valid and the next token looks like a
3387  // base or member initializer, assume that we're just missing a comma.
3388  else if (!MemInit.isInvalid() &&
3389  Tok.isOneOf(tok::identifier, tok::coloncolon)) {
3390  SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation);
3391  Diag(Loc, diag::err_ctor_init_missing_comma)
3392  << FixItHint::CreateInsertion(Loc, ", ");
3393  } else {
3394  // Skip over garbage, until we get to '{'. Don't eat the '{'.
3395  if (!MemInit.isInvalid())
3396  Diag(Tok.getLocation(), diag::err_expected_either) << tok::l_brace
3397  << tok::comma;
3398  SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
3399  break;
3400  }
3401  } while (true);
3402 
3403  Actions.ActOnMemInitializers(ConstructorDecl, ColonLoc, MemInitializers,
3404  AnyErrors);
3405 }
3406 
3407 /// ParseMemInitializer - Parse a C++ member initializer, which is
3408 /// part of a constructor initializer that explicitly initializes one
3409 /// member or base class (C++ [class.base.init]). See
3410 /// ParseConstructorInitializer for an example.
3411 ///
3412 /// [C++] mem-initializer:
3413 /// mem-initializer-id '(' expression-list[opt] ')'
3414 /// [C++0x] mem-initializer-id braced-init-list
3415 ///
3416 /// [C++] mem-initializer-id:
3417 /// '::'[opt] nested-name-specifier[opt] class-name
3418 /// identifier
3419 MemInitResult Parser::ParseMemInitializer(Decl *ConstructorDecl) {
3420  // parse '::'[opt] nested-name-specifier[opt]
3421  CXXScopeSpec SS;
3422  ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false);
3423 
3424  // : identifier
3425  IdentifierInfo *II = nullptr;
3426  SourceLocation IdLoc = Tok.getLocation();
3427  // : declype(...)
3428  DeclSpec DS(AttrFactory);
3429  // : template_name<...>
3430  ParsedType TemplateTypeTy;
3431 
3432  if (Tok.is(tok::identifier)) {
3433  // Get the identifier. This may be a member name or a class name,
3434  // but we'll let the semantic analysis determine which it is.
3435  II = Tok.getIdentifierInfo();
3436  ConsumeToken();
3437  } else if (Tok.is(tok::annot_decltype)) {
3438  // Get the decltype expression, if there is one.
3439  // Uses of decltype will already have been converted to annot_decltype by
3440  // ParseOptionalCXXScopeSpecifier at this point.
3441  // FIXME: Can we get here with a scope specifier?
3442  ParseDecltypeSpecifier(DS);
3443  } else {
3444  TemplateIdAnnotation *TemplateId = Tok.is(tok::annot_template_id)
3445  ? takeTemplateIdAnnotation(Tok)
3446  : nullptr;
3447  if (TemplateId && (TemplateId->Kind == TNK_Type_template ||
3448  TemplateId->Kind == TNK_Dependent_template_name)) {
3449  AnnotateTemplateIdTokenAsType(/*IsClassName*/true);
3450  assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
3451  TemplateTypeTy = getTypeAnnotation(Tok);
3452  ConsumeAnnotationToken();
3453  } else {
3454  Diag(Tok, diag::err_expected_member_or_base_name);
3455  return true;
3456  }
3457  }
3458 
3459  // Parse the '('.
3460  if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
3461  Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
3462 
3463  ExprResult InitList = ParseBraceInitializer();
3464  if (InitList.isInvalid())
3465  return true;
3466 
3467  SourceLocation EllipsisLoc;
3468  TryConsumeToken(tok::ellipsis, EllipsisLoc);
3469 
3470  return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
3471  TemplateTypeTy, DS, IdLoc,
3472  InitList.get(), EllipsisLoc);
3473  } else if(Tok.is(tok::l_paren)) {
3474  BalancedDelimiterTracker T(*this, tok::l_paren);
3475  T.consumeOpen();
3476 
3477  // Parse the optional expression-list.
3478  ExprVector ArgExprs;
3479  CommaLocsTy CommaLocs;
3480  if (Tok.isNot(tok::r_paren) && ParseExpressionList(ArgExprs, CommaLocs)) {
3481  SkipUntil(tok::r_paren, StopAtSemi);
3482  return true;
3483  }
3484 
3485  T.consumeClose();
3486 
3487  SourceLocation EllipsisLoc;
3488  TryConsumeToken(tok::ellipsis, EllipsisLoc);
3489 
3490  return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
3491  TemplateTypeTy, DS, IdLoc,
3492  T.getOpenLocation(), ArgExprs,
3493  T.getCloseLocation(), EllipsisLoc);
3494  }
3495 
3496  if (getLangOpts().CPlusPlus11)
3497  return Diag(Tok, diag::err_expected_either) << tok::l_paren << tok::l_brace;
3498  else
3499  return Diag(Tok, diag::err_expected) << tok::l_paren;
3500 }
3501 
3502 /// \brief Parse a C++ exception-specification if present (C++0x [except.spec]).
3503 ///
3504 /// exception-specification:
3505 /// dynamic-exception-specification
3506 /// noexcept-specification
3507 ///
3508 /// noexcept-specification:
3509 /// 'noexcept'
3510 /// 'noexcept' '(' constant-expression ')'
3512 Parser::tryParseExceptionSpecification(bool Delayed,
3513  SourceRange &SpecificationRange,
3514  SmallVectorImpl<ParsedType> &DynamicExceptions,
3515  SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
3516  ExprResult &NoexceptExpr,
3517  CachedTokens *&ExceptionSpecTokens) {
3519  ExceptionSpecTokens = nullptr;
3520 
3521  // Handle delayed parsing of exception-specifications.
3522  if (Delayed) {
3523  if (Tok.isNot(tok::kw_throw) && Tok.isNot(tok::kw_noexcept))
3524  return EST_None;
3525 
3526  // Consume and cache the starting token.
3527  bool IsNoexcept = Tok.is(tok::kw_noexcept);
3528  Token StartTok = Tok;
3529  SpecificationRange = SourceRange(ConsumeToken());
3530 
3531  // Check for a '('.
3532  if (!Tok.is(tok::l_paren)) {
3533  // If this is a bare 'noexcept', we're done.
3534  if (IsNoexcept) {
3535  Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
3536  NoexceptExpr = nullptr;
3537  return EST_BasicNoexcept;
3538  }
3539 
3540  Diag(Tok, diag::err_expected_lparen_after) << "throw";
3541  return EST_DynamicNone;
3542  }
3543 
3544  // Cache the tokens for the exception-specification.
3545  ExceptionSpecTokens = new CachedTokens;
3546  ExceptionSpecTokens->push_back(StartTok); // 'throw' or 'noexcept'
3547  ExceptionSpecTokens->push_back(Tok); // '('
3548  SpecificationRange.setEnd(ConsumeParen()); // '('
3549 
3550  ConsumeAndStoreUntil(tok::r_paren, *ExceptionSpecTokens,
3551  /*StopAtSemi=*/true,
3552  /*ConsumeFinalToken=*/true);
3553  SpecificationRange.setEnd(ExceptionSpecTokens->back().getLocation());
3554 
3555  return EST_Unparsed;
3556  }
3557 
3558  // See if there's a dynamic specification.
3559  if (Tok.is(tok::kw_throw)) {
3560  Result = ParseDynamicExceptionSpecification(SpecificationRange,
3561  DynamicExceptions,
3562  DynamicExceptionRanges);
3563  assert(DynamicExceptions.size() == DynamicExceptionRanges.size() &&
3564  "Produced different number of exception types and ranges.");
3565  }
3566 
3567  // If there's no noexcept specification, we're done.
3568  if (Tok.isNot(tok::kw_noexcept))
3569  return Result;
3570 
3571  Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
3572 
3573  // If we already had a dynamic specification, parse the noexcept for,
3574  // recovery, but emit a diagnostic and don't store the results.
3575  SourceRange NoexceptRange;
3576  ExceptionSpecificationType NoexceptType = EST_None;
3577 
3578  SourceLocation KeywordLoc = ConsumeToken();
3579  if (Tok.is(tok::l_paren)) {
3580  // There is an argument.
3581  BalancedDelimiterTracker T(*this, tok::l_paren);
3582  T.consumeOpen();
3583  NoexceptType = EST_ComputedNoexcept;
3584  NoexceptExpr = ParseConstantExpression();
3585  T.consumeClose();
3586  // The argument must be contextually convertible to bool. We use
3587  // CheckBooleanCondition for this purpose.
3588  // FIXME: Add a proper Sema entry point for this.
3589  if (!NoexceptExpr.isInvalid()) {
3590  NoexceptExpr =
3591  Actions.CheckBooleanCondition(KeywordLoc, NoexceptExpr.get());
3592  NoexceptRange = SourceRange(KeywordLoc, T.getCloseLocation());
3593  } else {
3594  NoexceptType = EST_BasicNoexcept;
3595  }
3596  } else {
3597  // There is no argument.
3598  NoexceptType = EST_BasicNoexcept;
3599  NoexceptRange = SourceRange(KeywordLoc, KeywordLoc);
3600  }
3601 
3602  if (Result == EST_None) {
3603  SpecificationRange = NoexceptRange;
3604  Result = NoexceptType;
3605 
3606  // If there's a dynamic specification after a noexcept specification,
3607  // parse that and ignore the results.
3608  if (Tok.is(tok::kw_throw)) {
3609  Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
3610  ParseDynamicExceptionSpecification(NoexceptRange, DynamicExceptions,
3611  DynamicExceptionRanges);
3612  }
3613  } else {
3614  Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
3615  }
3616 
3617  return Result;
3618 }
3619 
3621  Parser &P, SourceRange Range, bool IsNoexcept) {
3622  if (P.getLangOpts().CPlusPlus11) {
3623  const char *Replacement = IsNoexcept ? "noexcept" : "noexcept(false)";
3624  P.Diag(Range.getBegin(),
3625  P.getLangOpts().CPlusPlus1z && !IsNoexcept
3626  ? diag::ext_dynamic_exception_spec
3627  : diag::warn_exception_spec_deprecated)
3628  << Range;
3629  P.Diag(Range.getBegin(), diag::note_exception_spec_deprecated)
3630  << Replacement << FixItHint::CreateReplacement(Range, Replacement);
3631  }
3632 }
3633 
3634 /// ParseDynamicExceptionSpecification - Parse a C++
3635 /// dynamic-exception-specification (C++ [except.spec]).
3636 ///
3637 /// dynamic-exception-specification:
3638 /// 'throw' '(' type-id-list [opt] ')'
3639 /// [MS] 'throw' '(' '...' ')'
3640 ///
3641 /// type-id-list:
3642 /// type-id ... [opt]
3643 /// type-id-list ',' type-id ... [opt]
3644 ///
3645 ExceptionSpecificationType Parser::ParseDynamicExceptionSpecification(
3646  SourceRange &SpecificationRange,
3647  SmallVectorImpl<ParsedType> &Exceptions,
3648  SmallVectorImpl<SourceRange> &Ranges) {
3649  assert(Tok.is(tok::kw_throw) && "expected throw");
3650 
3651  SpecificationRange.setBegin(ConsumeToken());
3652  BalancedDelimiterTracker T(*this, tok::l_paren);
3653  if (T.consumeOpen()) {
3654  Diag(Tok, diag::err_expected_lparen_after) << "throw";
3655  SpecificationRange.setEnd(SpecificationRange.getBegin());
3656  return EST_DynamicNone;
3657  }
3658 
3659  // Parse throw(...), a Microsoft extension that means "this function
3660  // can throw anything".
3661  if (Tok.is(tok::ellipsis)) {
3662  SourceLocation EllipsisLoc = ConsumeToken();
3663  if (!getLangOpts().MicrosoftExt)
3664  Diag(EllipsisLoc, diag::ext_ellipsis_exception_spec);
3665  T.consumeClose();
3666  SpecificationRange.setEnd(T.getCloseLocation());
3667  diagnoseDynamicExceptionSpecification(*this, SpecificationRange, false);
3668  return EST_MSAny;
3669  }
3670 
3671  // Parse the sequence of type-ids.
3672  SourceRange Range;
3673  while (Tok.isNot(tok::r_paren)) {
3674  TypeResult Res(ParseTypeName(&Range));
3675 
3676  if (Tok.is(tok::ellipsis)) {
3677  // C++0x [temp.variadic]p5:
3678  // - In a dynamic-exception-specification (15.4); the pattern is a
3679  // type-id.
3680  SourceLocation Ellipsis = ConsumeToken();
3681  Range.setEnd(Ellipsis);
3682  if (!Res.isInvalid())
3683  Res = Actions.ActOnPackExpansion(Res.get(), Ellipsis);
3684  }
3685 
3686  if (!Res.isInvalid()) {
3687  Exceptions.push_back(Res.get());
3688  Ranges.push_back(Range);
3689  }
3690 
3691  if (!TryConsumeToken(tok::comma))
3692  break;
3693  }
3694 
3695  T.consumeClose();
3696  SpecificationRange.setEnd(T.getCloseLocation());
3697  diagnoseDynamicExceptionSpecification(*this, SpecificationRange,
3698  Exceptions.empty());
3699  return Exceptions.empty() ? EST_DynamicNone : EST_Dynamic;
3700 }
3701 
3702 /// ParseTrailingReturnType - Parse a trailing return type on a new-style
3703 /// function declaration.
3704 TypeResult Parser::ParseTrailingReturnType(SourceRange &Range) {
3705  assert(Tok.is(tok::arrow) && "expected arrow");
3706 
3707  ConsumeToken();
3708 
3710 }
3711 
3712 /// \brief We have just started parsing the definition of a new class,
3713 /// so push that class onto our stack of classes that is currently
3714 /// being parsed.
3716 Parser::PushParsingClass(Decl *ClassDecl, bool NonNestedClass,
3717  bool IsInterface) {
3718  assert((NonNestedClass || !ClassStack.empty()) &&
3719  "Nested class without outer class");
3720  ClassStack.push(new ParsingClass(ClassDecl, NonNestedClass, IsInterface));
3721  return Actions.PushParsingClass();
3722 }
3723 
3724 /// \brief Deallocate the given parsed class and all of its nested
3725 /// classes.
3726 void Parser::DeallocateParsedClasses(Parser::ParsingClass *Class) {
3727  for (unsigned I = 0, N = Class->LateParsedDeclarations.size(); I != N; ++I)
3728  delete Class->LateParsedDeclarations[I];
3729  delete Class;
3730 }
3731 
3732 /// \brief Pop the top class of the stack of classes that are
3733 /// currently being parsed.
3734 ///
3735 /// This routine should be called when we have finished parsing the
3736 /// definition of a class, but have not yet popped the Scope
3737 /// associated with the class's definition.
3738 void Parser::PopParsingClass(Sema::ParsingClassState state) {
3739  assert(!ClassStack.empty() && "Mismatched push/pop for class parsing");
3740 
3741  Actions.PopParsingClass(state);
3742 
3743  ParsingClass *Victim = ClassStack.top();
3744  ClassStack.pop();
3745  if (Victim->TopLevelClass) {
3746  // Deallocate all of the nested classes of this class,
3747  // recursively: we don't need to keep any of this information.
3748  DeallocateParsedClasses(Victim);
3749  return;
3750  }
3751  assert(!ClassStack.empty() && "Missing top-level class?");
3752 
3753  if (Victim->LateParsedDeclarations.empty()) {
3754  // The victim is a nested class, but we will not need to perform
3755  // any processing after the definition of this class since it has
3756  // no members whose handling was delayed. Therefore, we can just
3757  // remove this nested class.
3758  DeallocateParsedClasses(Victim);
3759  return;
3760  }
3761 
3762  // This nested class has some members that will need to be processed
3763  // after the top-level class is completely defined. Therefore, add
3764  // it to the list of nested classes within its parent.
3765  assert(getCurScope()->isClassScope() && "Nested class outside of class scope?");
3766  ClassStack.top()->LateParsedDeclarations.push_back(new LateParsedClass(this, Victim));
3767  Victim->TemplateScope = getCurScope()->getParent()->isTemplateParamScope();
3768 }
3769 
3770 /// \brief Try to parse an 'identifier' which appears within an attribute-token.
3771 ///
3772 /// \return the parsed identifier on success, and 0 if the next token is not an
3773 /// attribute-token.
3774 ///
3775 /// C++11 [dcl.attr.grammar]p3:
3776 /// If a keyword or an alternative token that satisfies the syntactic
3777 /// requirements of an identifier is contained in an attribute-token,
3778 /// it is considered an identifier.
3779 IdentifierInfo *Parser::TryParseCXX11AttributeIdentifier(SourceLocation &Loc) {
3780  switch (Tok.getKind()) {
3781  default:
3782  // Identifiers and keywords have identifier info attached.
3783  if (!Tok.isAnnotation()) {
3784  if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
3785  Loc = ConsumeToken();
3786  return II;
3787  }
3788  }
3789  return nullptr;
3790 
3791  case tok::ampamp: // 'and'
3792  case tok::pipe: // 'bitor'
3793  case tok::pipepipe: // 'or'
3794  case tok::caret: // 'xor'
3795  case tok::tilde: // 'compl'
3796  case tok::amp: // 'bitand'
3797  case tok::ampequal: // 'and_eq'
3798  case tok::pipeequal: // 'or_eq'
3799  case tok::caretequal: // 'xor_eq'
3800  case tok::exclaim: // 'not'
3801  case tok::exclaimequal: // 'not_eq'
3802  // Alternative tokens do not have identifier info, but their spelling
3803  // starts with an alphabetical character.
3804  SmallString<8> SpellingBuf;
3805  SourceLocation SpellingLoc =
3806  PP.getSourceManager().getSpellingLoc(Tok.getLocation());
3807  StringRef Spelling = PP.getSpelling(SpellingLoc, SpellingBuf);
3808  if (isLetter(Spelling[0])) {
3809  Loc = ConsumeToken();
3810  return &PP.getIdentifierTable().get(Spelling);
3811  }
3812  return nullptr;
3813  }
3814 }
3815 
3817  IdentifierInfo *ScopeName) {
3818  switch (AttributeList::getKind(AttrName, ScopeName,
3820  case AttributeList::AT_CarriesDependency:
3821  case AttributeList::AT_Deprecated:
3822  case AttributeList::AT_FallThrough:
3823  case AttributeList::AT_CXX11NoReturn:
3824  return true;
3825  case AttributeList::AT_WarnUnusedResult:
3826  return !ScopeName && AttrName->getName().equals("nodiscard");
3827  case AttributeList::AT_Unused:
3828  return !ScopeName && AttrName->getName().equals("maybe_unused");
3829  default:
3830  return false;
3831  }
3832 }
3833 
3834 /// ParseCXX11AttributeArgs -- Parse a C++11 attribute-argument-clause.
3835 ///
3836 /// [C++11] attribute-argument-clause:
3837 /// '(' balanced-token-seq ')'
3838 ///
3839 /// [C++11] balanced-token-seq:
3840 /// balanced-token
3841 /// balanced-token-seq balanced-token
3842 ///
3843 /// [C++11] balanced-token:
3844 /// '(' balanced-token-seq ')'
3845 /// '[' balanced-token-seq ']'
3846 /// '{' balanced-token-seq '}'
3847 /// any token but '(', ')', '[', ']', '{', or '}'
3848 bool Parser::ParseCXX11AttributeArgs(IdentifierInfo *AttrName,
3849  SourceLocation AttrNameLoc,
3850  ParsedAttributes &Attrs,
3851  SourceLocation *EndLoc,
3852  IdentifierInfo *ScopeName,
3853  SourceLocation ScopeLoc) {
3854  assert(Tok.is(tok::l_paren) && "Not a C++11 attribute argument list");
3855  SourceLocation LParenLoc = Tok.getLocation();
3856  const LangOptions &LO = getLangOpts();
3857  AttributeList::Syntax Syntax =
3859 
3860  // If the attribute isn't known, we will not attempt to parse any
3861  // arguments.
3862  if (!hasAttribute(LO.CPlusPlus ? AttrSyntax::CXX : AttrSyntax::C, ScopeName,
3863  AttrName, getTargetInfo(), getLangOpts())) {
3864  // Eat the left paren, then skip to the ending right paren.
3865  ConsumeParen();
3866  SkipUntil(tok::r_paren);
3867  return false;
3868  }
3869 
3870  if (ScopeName && ScopeName->getName() == "gnu") {
3871  // GNU-scoped attributes have some special cases to handle GNU-specific
3872  // behaviors.
3873  ParseGNUAttributeArgs(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
3874  ScopeLoc, Syntax, nullptr);
3875  return true;
3876  }
3877 
3878  unsigned NumArgs;
3879  // Some Clang-scoped attributes have some special parsing behavior.
3880  if (ScopeName && ScopeName->getName() == "clang")
3881  NumArgs =
3882  ParseClangAttributeArgs(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
3883  ScopeLoc, Syntax);
3884  else
3885  NumArgs =
3886  ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc,
3887  ScopeName, ScopeLoc, Syntax);
3888 
3889  const AttributeList *Attr = Attrs.getList();
3890  if (Attr && IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName)) {
3891  // If the attribute is a standard or built-in attribute and we are
3892  // parsing an argument list, we need to determine whether this attribute
3893  // was allowed to have an argument list (such as [[deprecated]]), and how
3894  // many arguments were parsed (so we can diagnose on [[deprecated()]]).
3895  if (Attr->getMaxArgs() && !NumArgs) {
3896  // The attribute was allowed to have arguments, but none were provided
3897  // even though the attribute parsed successfully. This is an error.
3898  Diag(LParenLoc, diag::err_attribute_requires_arguments) << AttrName;
3899  Attr->setInvalid(true);
3900  } else if (!Attr->getMaxArgs()) {
3901  // The attribute parsed successfully, but was not allowed to have any
3902  // arguments. It doesn't matter whether any were provided -- the
3903  // presence of the argument list (even if empty) is diagnosed.
3904  Diag(LParenLoc, diag::err_cxx11_attribute_forbids_arguments)
3905  << AttrName
3906  << FixItHint::CreateRemoval(SourceRange(LParenLoc, *EndLoc));
3907  Attr->setInvalid(true);
3908  }
3909  }
3910  return true;
3911 }
3912 
3913 /// ParseCXX11AttributeSpecifier - Parse a C++11 or C2x attribute-specifier.
3914 ///
3915 /// [C++11] attribute-specifier:
3916 /// '[' '[' attribute-list ']' ']'
3917 /// alignment-specifier
3918 ///
3919 /// [C++11] attribute-list:
3920 /// attribute[opt]
3921 /// attribute-list ',' attribute[opt]
3922 /// attribute '...'
3923 /// attribute-list ',' attribute '...'
3924 ///
3925 /// [C++11] attribute:
3926 /// attribute-token attribute-argument-clause[opt]
3927 ///
3928 /// [C++11] attribute-token:
3929 /// identifier
3930 /// attribute-scoped-token
3931 ///
3932 /// [C++11] attribute-scoped-token:
3933 /// attribute-namespace '::' identifier
3934 ///
3935 /// [C++11] attribute-namespace:
3936 /// identifier
3937 void Parser::ParseCXX11AttributeSpecifier(ParsedAttributes &attrs,
3938  SourceLocation *endLoc) {
3939  if (Tok.is(tok::kw_alignas)) {
3940  Diag(Tok.getLocation(), diag::warn_cxx98_compat_alignas);
3941  ParseAlignmentSpecifier(attrs, endLoc);
3942  return;
3943  }
3944 
3945  assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square) &&
3946  "Not a double square bracket attribute list");
3947 
3948  Diag(Tok.getLocation(), diag::warn_cxx98_compat_attribute);
3949 
3950  ConsumeBracket();
3951  ConsumeBracket();
3952 
3953  SourceLocation CommonScopeLoc;
3954  IdentifierInfo *CommonScopeName = nullptr;
3955  if (Tok.is(tok::kw_using)) {
3956  Diag(Tok.getLocation(), getLangOpts().CPlusPlus1z
3957  ? diag::warn_cxx14_compat_using_attribute_ns
3958  : diag::ext_using_attribute_ns);
3959  ConsumeToken();
3960 
3961  CommonScopeName = TryParseCXX11AttributeIdentifier(CommonScopeLoc);
3962  if (!CommonScopeName) {
3963  Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
3964  SkipUntil(tok::r_square, tok::colon, StopBeforeMatch);
3965  }
3966  if (!TryConsumeToken(tok::colon) && CommonScopeName)
3967  Diag(Tok.getLocation(), diag::err_expected) << tok::colon;
3968  }
3969 
3970  llvm::SmallDenseMap<IdentifierInfo*, SourceLocation, 4> SeenAttrs;
3971 
3972  while (Tok.isNot(tok::r_square)) {
3973  // attribute not present
3974  if (TryConsumeToken(tok::comma))
3975  continue;
3976 
3977  SourceLocation ScopeLoc, AttrLoc;
3978  IdentifierInfo *ScopeName = nullptr, *AttrName = nullptr;
3979 
3980  AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
3981  if (!AttrName)
3982  // Break out to the "expected ']'" diagnostic.
3983  break;
3984 
3985  // scoped attribute
3986  if (TryConsumeToken(tok::coloncolon)) {
3987  ScopeName = AttrName;
3988  ScopeLoc = AttrLoc;
3989 
3990  AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
3991  if (!AttrName) {
3992  Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
3993  SkipUntil(tok::r_square, tok::comma, StopAtSemi | StopBeforeMatch);
3994  continue;
3995  }
3996  }
3997 
3998  if (CommonScopeName) {
3999  if (ScopeName) {
4000  Diag(ScopeLoc, diag::err_using_attribute_ns_conflict)
4001  << SourceRange(CommonScopeLoc);
4002  } else {
4003  ScopeName = CommonScopeName;
4004  ScopeLoc = CommonScopeLoc;
4005  }
4006  }
4007 
4008  bool StandardAttr = IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName);
4009  bool AttrParsed = false;
4010 
4011  if (StandardAttr &&
4012  !SeenAttrs.insert(std::make_pair(AttrName, AttrLoc)).second)
4013  Diag(AttrLoc, diag::err_cxx11_attribute_repeated)
4014  << AttrName << SourceRange(SeenAttrs[AttrName]);
4015 
4016  // Parse attribute arguments
4017  if (Tok.is(tok::l_paren))
4018  AttrParsed = ParseCXX11AttributeArgs(AttrName, AttrLoc, attrs, endLoc,
4019  ScopeName, ScopeLoc);
4020 
4021  if (!AttrParsed)
4022  attrs.addNew(
4023  AttrName,
4024  SourceRange(ScopeLoc.isValid() ? ScopeLoc : AttrLoc, AttrLoc),
4025  ScopeName, ScopeLoc, nullptr, 0,
4026  getLangOpts().CPlusPlus ? AttributeList::AS_CXX11
4028 
4029  if (TryConsumeToken(tok::ellipsis))
4030  Diag(Tok, diag::err_cxx11_attribute_forbids_ellipsis)
4031  << AttrName->getName();
4032  }
4033 
4034  if (ExpectAndConsume(tok::r_square))
4035  SkipUntil(tok::r_square);
4036  if (endLoc)
4037  *endLoc = Tok.getLocation();
4038  if (ExpectAndConsume(tok::r_square))
4039  SkipUntil(tok::r_square);
4040 }
4041 
4042 /// ParseCXX11Attributes - Parse a C++11 or C2x attribute-specifier-seq.
4043 ///
4044 /// attribute-specifier-seq:
4045 /// attribute-specifier-seq[opt] attribute-specifier
4046 void Parser::ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
4047  SourceLocation *endLoc) {
4048  assert(standardAttributesAllowed());
4049 
4050  SourceLocation StartLoc = Tok.getLocation(), Loc;
4051  if (!endLoc)
4052  endLoc = &Loc;
4053 
4054  do {
4055  ParseCXX11AttributeSpecifier(attrs, endLoc);
4056  } while (isCXX11AttributeSpecifier());
4057 
4058  attrs.Range = SourceRange(StartLoc, *endLoc);
4059 }
4060 
4061 void Parser::DiagnoseAndSkipCXX11Attributes() {
4062  // Start and end location of an attribute or an attribute list.
4063  SourceLocation StartLoc = Tok.getLocation();
4064  SourceLocation EndLoc = SkipCXX11Attributes();
4065 
4066  if (EndLoc.isValid()) {
4067  SourceRange Range(StartLoc, EndLoc);
4068  Diag(StartLoc, diag::err_attributes_not_allowed)
4069  << Range;
4070  }
4071 }
4072 
4073 SourceLocation Parser::SkipCXX11Attributes() {
4074  SourceLocation EndLoc;
4075 
4076  if (!isCXX11AttributeSpecifier())
4077  return EndLoc;
4078 
4079  do {
4080  if (Tok.is(tok::l_square)) {
4081  BalancedDelimiterTracker T(*this, tok::l_square);
4082  T.consumeOpen();
4083  T.skipToEnd();
4084  EndLoc = T.getCloseLocation();
4085  } else {
4086  assert(Tok.is(tok::kw_alignas) && "not an attribute specifier");
4087  ConsumeToken();
4088  BalancedDelimiterTracker T(*this, tok::l_paren);
4089  if (!T.consumeOpen())
4090  T.skipToEnd();
4091  EndLoc = T.getCloseLocation();
4092  }
4093  } while (isCXX11AttributeSpecifier());
4094 
4095  return EndLoc;
4096 }
4097 
4098 /// Parse uuid() attribute when it appears in a [] Microsoft attribute.
4099 void Parser::ParseMicrosoftUuidAttributeArgs(ParsedAttributes &Attrs) {
4100  assert(Tok.is(tok::identifier) && "Not a Microsoft attribute list");
4101  IdentifierInfo *UuidIdent = Tok.getIdentifierInfo();
4102  assert(UuidIdent->getName() == "uuid" && "Not a Microsoft attribute list");
4103 
4104  SourceLocation UuidLoc = Tok.getLocation();
4105  ConsumeToken();
4106 
4107  // Ignore the left paren location for now.
4108  BalancedDelimiterTracker T(*this, tok::l_paren);
4109  if (T.consumeOpen()) {
4110  Diag(Tok, diag::err_expected) << tok::l_paren;
4111  return;
4112  }
4113 
4114  ArgsVector ArgExprs;
4115  if (Tok.is(tok::string_literal)) {
4116  // Easy case: uuid("...") -- quoted string.
4117  ExprResult StringResult = ParseStringLiteralExpression();
4118  if (StringResult.isInvalid())
4119  return;
4120  ArgExprs.push_back(StringResult.get());
4121  } else {
4122  // something like uuid({000000A0-0000-0000-C000-000000000049}) -- no
4123  // quotes in the parens. Just append the spelling of all tokens encountered
4124  // until the closing paren.
4125 
4126  SmallString<42> StrBuffer; // 2 "", 36 bytes UUID, 2 optional {}, 1 nul
4127  StrBuffer += "\"";
4128 
4129  // Since none of C++'s keywords match [a-f]+, accepting just tok::l_brace,
4130  // tok::r_brace, tok::minus, tok::identifier (think C000) and
4131  // tok::numeric_constant (0000) should be enough. But the spelling of the
4132  // uuid argument is checked later anyways, so there's no harm in accepting
4133  // almost anything here.
4134  // cl is very strict about whitespace in this form and errors out if any
4135  // is present, so check the space flags on the tokens.
4136  SourceLocation StartLoc = Tok.getLocation();
4137  while (Tok.isNot(tok::r_paren)) {
4138  if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
4139  Diag(Tok, diag::err_attribute_uuid_malformed_guid);
4140  SkipUntil(tok::r_paren, StopAtSemi);
4141  return;
4142  }
4143  SmallString<16> SpellingBuffer;
4144  SpellingBuffer.resize(Tok.getLength() + 1);
4145  bool Invalid = false;
4146  StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
4147  if (Invalid) {
4148  SkipUntil(tok::r_paren, StopAtSemi);
4149  return;
4150  }
4151  StrBuffer += TokSpelling;
4152  ConsumeAnyToken();
4153  }
4154  StrBuffer += "\"";
4155 
4156  if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
4157  Diag(Tok, diag::err_attribute_uuid_malformed_guid);
4158  ConsumeParen();
4159  return;
4160  }
4161 
4162  // Pretend the user wrote the appropriate string literal here.
4163  // ActOnStringLiteral() copies the string data into the literal, so it's
4164  // ok that the Token points to StrBuffer.
4165  Token Toks[1];
4166  Toks[0].startToken();
4167  Toks[0].setKind(tok::string_literal);
4168  Toks[0].setLocation(StartLoc);
4169  Toks[0].setLiteralData(StrBuffer.data());
4170  Toks[0].setLength(StrBuffer.size());
4171  StringLiteral *UuidString =
4172  cast<StringLiteral>(Actions.ActOnStringLiteral(Toks, nullptr).get());
4173  ArgExprs.push_back(UuidString);
4174  }
4175 
4176  if (!T.consumeClose()) {
4177  Attrs.addNew(UuidIdent, SourceRange(UuidLoc, T.getCloseLocation()), nullptr,
4178  SourceLocation(), ArgExprs.data(), ArgExprs.size(),
4180  }
4181 }
4182 
4183 /// ParseMicrosoftAttributes - Parse Microsoft attributes [Attr]
4184 ///
4185 /// [MS] ms-attribute:
4186 /// '[' token-seq ']'
4187 ///
4188 /// [MS] ms-attribute-seq:
4189 /// ms-attribute[opt]
4190 /// ms-attribute ms-attribute-seq
4191 void Parser::ParseMicrosoftAttributes(ParsedAttributes &attrs,
4192  SourceLocation *endLoc) {
4193  assert(Tok.is(tok::l_square) && "Not a Microsoft attribute list");
4194 
4195  do {
4196  // FIXME: If this is actually a C++11 attribute, parse it as one.
4197  BalancedDelimiterTracker T(*this, tok::l_square);
4198  T.consumeOpen();
4199 
4200  // Skip most ms attributes except for a whitelist.
4201  while (true) {
4202  SkipUntil(tok::r_square, tok::identifier, StopAtSemi | StopBeforeMatch);
4203  if (Tok.isNot(tok::identifier)) // ']', but also eof
4204  break;
4205  if (Tok.getIdentifierInfo()->getName() == "uuid")
4206  ParseMicrosoftUuidAttributeArgs(attrs);
4207  else
4208  ConsumeToken();
4209  }
4210 
4211  T.consumeClose();
4212  if (endLoc)
4213  *endLoc = T.getCloseLocation();
4214  } while (Tok.is(tok::l_square));
4215 }
4216 
4217 void Parser::ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType,
4218  AccessSpecifier& CurAS) {
4219  IfExistsCondition Result;
4220  if (ParseMicrosoftIfExistsCondition(Result))
4221  return;
4222 
4223  BalancedDelimiterTracker Braces(*this, tok::l_brace);
4224  if (Braces.consumeOpen()) {
4225  Diag(Tok, diag::err_expected) << tok::l_brace;
4226  return;
4227  }
4228 
4229  switch (Result.Behavior) {
4230  case IEB_Parse:
4231  // Parse the declarations below.
4232  break;
4233 
4234  case IEB_Dependent:
4235  Diag(Result.KeywordLoc, diag::warn_microsoft_dependent_exists)
4236  << Result.IsIfExists;
4237  // Fall through to skip.
4238  LLVM_FALLTHROUGH;
4239 
4240  case IEB_Skip:
4241  Braces.skipToEnd();
4242  return;
4243  }
4244 
4245  while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
4246  // __if_exists, __if_not_exists can nest.
4247  if (Tok.isOneOf(tok::kw___if_exists, tok::kw___if_not_exists)) {
4248  ParseMicrosoftIfExistsClassDeclaration((DeclSpec::TST)TagType, CurAS);
4249  continue;
4250  }
4251 
4252  // Check for extraneous top-level semicolon.
4253  if (Tok.is(tok::semi)) {
4254  ConsumeExtraSemi(InsideStruct, TagType);
4255  continue;
4256  }
4257 
4258  AccessSpecifier AS = getAccessSpecifierIfPresent();
4259  if (AS != AS_none) {
4260  // Current token is a C++ access specifier.
4261  CurAS = AS;
4262  SourceLocation ASLoc = Tok.getLocation();
4263  ConsumeToken();
4264  if (Tok.is(tok::colon))
4265  Actions.ActOnAccessSpecifier(AS, ASLoc, Tok.getLocation());
4266  else
4267  Diag(Tok, diag::err_expected) << tok::colon;
4268  ConsumeToken();
4269  continue;
4270  }
4271 
4272  // Parse all the comma separated declarators.
4273  ParseCXXClassMemberDeclaration(CurAS, nullptr);
4274  }
4275 
4276  Braces.consumeClose();
4277 }
MutableArrayRef< TemplateParameterList * > MultiTemplateParamsArg
Definition: Ownership.h:265
Defines the clang::ASTContext interface.
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
getFunctionTypeInfo - Retrieves the function type info object (looking through parentheses).
Definition: DeclSpec.h:2246
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:119
unsigned getRawEncoding() const
When a SourceLocation itself cannot be used, this returns an (opaque) 32-bit integer encoding for it...
void clear()
Reset the contents of this Declarator.
Definition: DeclSpec.h:1913
AttributeList * getNext() const
void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace)
ActOnFinishNamespaceDef - This callback is called after a namespace is exited.
IdentifierInfo * Name
FIXME: Temporarily stores the name of a specialization.
SourceLocation TemplateNameLoc
TemplateNameLoc - The location of the template name within the source.
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition: Expr.h:472
bool is(tok::TokenKind K) const
is/isNot - Predicates to check if this token is a specific kind, as in "if (Tok.is(tok::l_brace)) {...
Definition: Token.h:95
static CharSourceRange getTokenRange(SourceRange R)
The name refers to a dependent template name:
Definition: TemplateKinds.h:46
ActionResult< Expr * > ExprResult
Definition: Ownership.h:251
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:81
static LLVM_READONLY bool isLetter(unsigned char c)
Return true if this character is an ASCII letter: [a-zA-Z].
Definition: CharInfo.h:112
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:368
The base class of the type hierarchy.
Definition: Type.h:1300
bool TryAnnotateCXXScopeToken(bool EnteringContext=false)
TryAnnotateScopeToken - Like TryAnnotateTypeOrScopeToken but only annotates C++ scope specifiers and ...
Definition: Parser.cpp:1844
SourceLocation getCloseLocation() const
This indicates that the scope corresponds to a function, which means that labels are set here...
Definition: Scope.h:46
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:2215
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:103
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:495
std::unique_ptr< CachedTokens > DefaultArgTokens
DefaultArgTokens - When the parameter&#39;s default argument cannot be parsed immediately (because it occ...
Definition: DeclSpec.h:1222
static const char * getSpecifierName(Specifier VS)
Definition: DeclSpec.cpp:1333
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition: Specifiers.h:95
TemplateNameKind Kind
The kind of template that Template refers to.
const NestedNameSpecifier * Specifier
Wrapper for void* pointer.
Definition: Ownership.h:45
Parser - This implements a parser for the C family of languages.
Definition: Parser.h:57
void SetIdentifier(IdentifierInfo *Id, SourceLocation IdLoc)
Set the name of this declarator to be the given identifier.
Definition: DeclSpec.h:2124
RAII object that enters a new expression evaluation context.
Definition: Sema.h:10617
void EnterToken(const Token &Tok)
Enters a token in the token stream to be lexed next.
static const TST TST_underlyingType
Definition: DeclSpec.h:299
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1734
void setTypeofParensRange(SourceRange range)
Definition: DeclSpec.h:521
TypeSpecifierType
Specifies the kind of type.
Definition: Specifiers.h:45
static const TST TST_interface
Definition: DeclSpec.h:292
bool isInvalidDecl() const
Definition: DeclBase.h:532
Like System, but searched after the system directories.
void setBegin(SourceLocation b)
Describes how types, statements, expressions, and declarations should be printed. ...
Definition: PrettyPrinter.h:38
ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec *SS=nullptr, bool isClassName=false, bool HasTrailingDot=false, ParsedType ObjectType=nullptr, bool IsCtorOrDtorName=false, bool WantNontrivialTypeSourceInfo=false, bool IsClassTemplateDeductionContext=true, IdentifierInfo **CorrectedII=nullptr)
If the identifier refers to a type name within this scope, return the declaration of that type...
Definition: SemaDecl.cpp:274
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:160
AttributeList * getList() const
tok::TokenKind getKind() const
Definition: Token.h:90
bool SkipUntil(tok::TokenKind T, SkipUntilFlags Flags=static_cast< SkipUntilFlags >(0))
SkipUntil - Read tokens until we get to the specified token, then consume it (unless StopBeforeMatch ...
Definition: Parser.h:939
Information about a template-id annotation token.
bool isUnset() const
Definition: DeclSpec.h:2488
SourceLocation getFriendSpecLoc() const
Definition: DeclSpec.h:704
RecordDecl - Represents a struct/union/class.
Definition: Decl.h:3384
Decl * ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS, MultiTemplateParamsArg TemplateParams, SourceLocation UsingLoc, UnqualifiedId &Name, AttributeList *AttrList, TypeResult Type, Decl *DeclFromDeclSpec)
const Token & NextToken()
NextToken - This peeks ahead one token and returns it without consuming it.
Definition: Parser.h:607
SourceLocation getLoc() const
bool TryConsumeToken(tok::TokenKind Expected)
Definition: Parser.h:324
__ptr16, alignas(...), etc.
One of these records is kept for each identifier that is lexed.
Kind getKind() const
Decl * ActOnNamespaceAliasDef(Scope *CurScope, SourceLocation NamespaceLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *Ident)
SourceLocation getAnnotationEndLoc() const
Definition: Token.h:138
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
Copy initialization.
Definition: Specifiers.h:228
static const TST TST_class
Definition: DeclSpec.h:293
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:307
Token - This structure provides full information about a lexed token.
Definition: Token.h:35
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.
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:402
void ClearStorageClassSpecs()
Definition: DeclSpec.h:463
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:48
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:46
void setExternInLinkageSpec(bool Value)
Definition: DeclSpec.h:454
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:900
static ParsedType getTypeAnnotation(const Token &Tok)
getTypeAnnotation - Read a parsed type out of an annotation token.
Definition: Parser.h:612
PtrTy get() const
Definition: Ownership.h:162
Microsoft throw(...) extension.
DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef< Decl *> Group)
BuildDeclaratorGroup - convert a list of declarations into a declaration group, performing any necess...
Definition: SemaDecl.cpp:11627
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:610
void takeAllFrom(ParsedAttributes &attrs)
ParsedTemplateArgument * getTemplateArgs()
Retrieves a pointer to the template arguments.
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:39
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:344
SourceLocation getConstSpecLoc() const
Definition: DeclSpec.h:544
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:504
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
SourceLocation TemplateKWLoc
TemplateKWLoc - The location of the template keyword.
SourceLocation LAngleLoc
The location of the &#39;<&#39; before the template argument list.
A little helper class used to produce diagnostics.
Definition: Diagnostic.h:953
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:308
bool isPastIdentifier() const
isPastIdentifier - Return true if we have parsed beyond the point where the name would appear...
Definition: DeclSpec.h:2099
void SetRangeStart(SourceLocation Loc)
Definition: DeclSpec.h:610
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
Definition: DeclSpec.h:1280
SourceRange getRange() const
Definition: DeclSpec.h:68
TypeResult ParseTypeName(SourceRange *Range=nullptr, Declarator::TheContext Context=Declarator::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:45
TST getTypeSpecType() const
Definition: DeclSpec.h:481
[uuid("...")] class Foo
Decl * ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, Expr *AssertExpr, Expr *AssertMessageExpr, SourceLocation RParenLoc)
Expr - This represents one expression.
Definition: Expr.h:106
static bool IsBuiltInOrStandardCXX11Attribute(IdentifierInfo *AttrName, IdentifierInfo *ScopeName)
Represents a character-granular source range.
int Id
Definition: ASTDiff.cpp:191
void AnnotateCachedTokens(const Token &Tok)
We notify the Preprocessor that if it is caching tokens (because backtrack is enabled) it should repl...
const FunctionProtoType * T
bool isKnownToGCC() const
This file defines the classes used to store parsed information about declaration-specifiers and decla...
void SkipMalformedDecl()
SkipMalformedDecl - Read tokens until we get to some likely good stopping point for skipping past a s...
Definition: ParseDecl.cpp:1817
Specifier getLastSpecifier() const
Definition: DeclSpec.h:2503
TypeResult ActOnTypeName(Scope *S, Declarator &D)
Definition: SemaType.cpp:5584
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:112
SourceLocation getVolatileSpecLoc() const
Definition: DeclSpec.h:546
OpaquePtr< TemplateName > TemplateTy
Definition: Parser.h:288
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:2405
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:16461
Represents a C++ template name within the type system.
Definition: TemplateName.h:176
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7)...
CachedTokens * ExceptionSpecTokens
Pointer to the cached tokens for an exception-specification that has not yet been parsed...
Definition: DeclSpec.h:1334
TemplateNameKind
Specifies the kind of template name that an identifier refers to.
Definition: TemplateKinds.h:21
InClassInitStyle
In-class initialization styles for non-static data members.
Definition: Specifiers.h:226
bool isInvalid() const
Definition: Ownership.h:158
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:703
The result type of a method or function.
bool isCXX11Attribute() const
void CodeCompleteNamespaceDecl(Scope *S)
PrettyDeclStackTraceEntry - If a crash occurs in the parser while parsing something related to a decl...
const LangOptions & getLangOpts() const
Definition: Parser.h:271
A class for parsing a DeclSpec.
Represents a C++ Modules TS module export declaration.
Definition: Decl.h:3924
ExprResult ActOnDecltypeExpression(Expr *E)
Process the expression contained within a decltype.
const AttributeList * getAttributes() const
Definition: DeclSpec.h:2380
bool isArrayOfUnknownBound() const
isArrayOfUnknownBound - This method returns true if the declarator is a declarator for an array of un...
Definition: DeclSpec.h:2205
Kind
Stop skipping at semicolon.
Definition: Parser.h:919
ActionResult - This structure is used while parsing/acting on expressions, stmts, etc...
Definition: Ownership.h:144
SCS getStorageClassSpec() const
Definition: DeclSpec.h:449
bool ParseTopLevelDecl()
Definition: Parser.h:306
ASTContext & getASTContext() const
Definition: Sema.h:1200
bool hasName() const
hasName - Whether this declarator has a name, which might be an identifier (accessible via getIdentif...
Definition: DeclSpec.h:2105
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
TagDecl - Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:2846
static const TST TST_union
Definition: DeclSpec.h:290
IdentifierInfo * getIdentifierInfo() const
Definition: Token.h:177
void setAnnotationEndLoc(SourceLocation L)
Definition: Token.h:142
ExtensionRAIIObject - This saves the state of extension warnings when constructed and disables them...
bool isAtStartOfLine() const
isAtStartOfLine - Return true if this token is at the start of a line.
Definition: Token.h:266
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition: TokenKinds.h:25
Direct list-initialization.
Definition: Specifiers.h:229
Represents a C++11 virt-specifier-seq.
Definition: DeclSpec.h:2472
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:16436
FunctionDefinitionKind
Described the kind of function definition (if any) provided for a function.
Definition: DeclSpec.h:1715
Decl * ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS, SourceLocation UsingLoc, SourceLocation TypenameLoc, CXXScopeSpec &SS, UnqualifiedId &Name, SourceLocation EllipsisLoc, AttributeList *AttrList)
Scope * getCurScope() const
Definition: Parser.h:278
ExprResult ParseConstantExpressionInExprEvalContext(TypeCastState isTypeCast=NotTypeCast)
Definition: ParseExpr.cpp:196
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition: DeclSpec.h:194
void setFunctionDefinitionKind(FunctionDefinitionKind Val)
Definition: DeclSpec.h:2433
Decl * ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc, SourceLocation NamespcLoc, CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *NamespcName, AttributeList *AttrList)
SourceLocation getModulePrivateSpecLoc() const
Definition: DeclSpec.h:707
StringRef getName() const
Return the actual identifier string.
The scope of a struct/union/class definition.
Definition: Scope.h:64
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:298
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:297
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition: Scope.h:221
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:116
bool isOneOf(tok::TokenKind K1, tok::TokenKind K2) const
Definition: Token.h:97
The name refers to a template whose specialization produces a type.
Definition: TemplateKinds.h:30
unsigned getLength() const
Definition: Token.h:127
void CodeCompleteNamespaceAliasDecl(Scope *S)
void setLiteralData(const char *Ptr)
Definition: Token.h:219
void CodeCompleteUsingDirective(Scope *S)
Syntax
The style used to specify an attribute.
Definition: AttributeList.h:98
Decl * ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc, SourceLocation NamespaceLoc, SourceLocation IdentLoc, IdentifierInfo *Ident, SourceLocation LBrace, AttributeList *AttrList, UsingDirectiveDecl *&UsingDecl)
ActOnStartNamespaceDef - This is called at the start of a namespace definition.
const TargetInfo & getTargetInfo() const
Definition: Parser.h:272
bool SetSpecifier(Specifier VS, SourceLocation Loc, const char *&PrevSpec)
Definition: DeclSpec.cpp:1308
unsigned getTypeQualifiers() const
getTypeQualifiers - Return a set of TQs.
Definition: DeclSpec.h:543
void takeAttributesFrom(ParsedAttributes &attrs)
Definition: DeclSpec.h:755
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Definition: Parser.cpp:72
void setInvalid(bool b=true) const
static const TST TST_typename
Definition: DeclSpec.h:294
void SetRangeEnd(SourceLocation Loc)
SetRangeEnd - Set the end of the source range to Loc, unless it&#39;s invalid.
Definition: DeclSpec.h:1897
ExceptionSpecificationType
The various types of exception specifications that exist in C++11.
ActionResult< ParsedType > TypeResult
Definition: Ownership.h:253
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:90
ExceptionSpecificationType getExceptionSpecType() const
Get the type of exception specification this function has.
Definition: DeclSpec.h:1441
A template-id, e.g., f<int>.
Definition: DeclSpec.h:923
SmallVector< TemplateParameterList *, 4 > TemplateParameterLists
Definition: Parser.h:290
CXXScopeSpec & getTypeSpecScope()
Definition: DeclSpec.h:501
AttributeList * addNew(IdentifierInfo *attrName, SourceRange attrRange, IdentifierInfo *scopeName, SourceLocation scopeLoc, ArgsUnion *args, unsigned numArgs, AttributeList::Syntax syntax, SourceLocation ellipsisLoc=SourceLocation())
Add attribute with expression arguments.
const Expr * Replacement
Definition: AttributeList.h:59
This is a scope that can contain a declaration.
Definition: Scope.h:58
unsigned getMaxArgs() const
bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
Definition: DeclSpec.cpp:742
SourceLocation getIdentifierLoc() const
Definition: DeclSpec.h:2121
bool isSet() const
Deprecated.
Definition: DeclSpec.h:209
void getCXX11AttributeRanges(SmallVectorImpl< SourceRange > &Ranges)
Return a source range list of C++11 attributes associated with the declarator.
Definition: DeclSpec.h:2396
X
Add a minimal nested name specifier fixit hint to allow lookup of a tag name from an outer enclosing ...
Definition: SemaDecl.cpp:13161
ExprResult ParseConstantExpression(TypeCastState isTypeCast=NotTypeCast)
Definition: ParseExpr.cpp:206
Captures information about "declaration specifiers".
Definition: DeclSpec.h:228
SourceLocation getRestrictSpecLoc() const
Definition: DeclSpec.h:545
void setEnd(SourceLocation e)
SourceLocation ConsumeToken()
ConsumeToken - Consume the current &#39;peek token&#39; and lex the next one.
Definition: Parser.h:316
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:1850
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:127
void revertTokenIDToIdentifier()
Revert TokenID to tok::identifier; used for GNU libstdc++ 4.2 compatibility.
SourceLocation getFirstLocation() const
Definition: DeclSpec.h:2501
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1509
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:1904
ExprResult ExprError()
Definition: Ownership.h:267
static OpaquePtr make(PtrTy P)
Definition: Ownership.h:54
static const TST TST_struct
Definition: DeclSpec.h:291
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:64
void setLocation(SourceLocation L)
Definition: Token.h:132
A trivial tuple used to represent a source range.
NamedDecl - This represents a decl with a name.
Definition: Decl.h:213
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:823
Expr * getRepAsExpr() const
Definition: DeclSpec.h:497
Represents C++ using-directive.
Definition: DeclCXX.h:2779
unsigned NumArgs
NumArgs - The number of template arguments.
void SetRangeEnd(SourceLocation Loc)
Definition: DeclSpec.h:611
SourceLocation getBegin() const
ParsedAttributes - A collection of parsed attributes.
SourceLocation ColonLoc
Location of &#39;:&#39;.
Definition: OpenMPClause.h:90
void setCommaLoc(SourceLocation CL)
Definition: DeclSpec.h:2427
bool hasLeadingSpace() const
Return true if this token has whitespace before it.
Definition: Token.h:270
No in-class initializer.
Definition: Specifiers.h:227
ParamInfo * Params
Params - This is a pointer to a new[]&#39;d array of ParamInfo objects that describe the parameters speci...
Definition: DeclSpec.h:1320
Attr - This represents one attribute.
Definition: Attr.h:43
SourceLocation getLocation() const
Definition: DeclBase.h:407
void startToken()
Reset all flags to cleared.
Definition: Token.h:169
ParsedTemplateTy Template
The declaration of the template corresponding to the template-name.
AttributeList - Represents a syntactic attribute.
Definition: AttributeList.h:95
Stop skipping at specified token, but don&#39;t skip the token itself.
Definition: Parser.h:921