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