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