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