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