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