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

source code of clang/lib/Parse/ParseDeclCXX.cpp