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