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