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