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