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