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;
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 } else {
1086 EndLoc = Tok.getLocation();
1087 }
1088 }
1089 return EndLoc;
1090 }
1091
1092 Result = Actions.ActOnDecltypeExpression(Result.get());
1093 }
1094
1095 // Match the ')'
1096 T.consumeClose();
1097 DS.setTypeArgumentRange(T.getRange());
1098 if (T.getCloseLocation().isInvalid()) {
1099 DS.SetTypeSpecError();
1100 // FIXME: this should return the location of the last token
1101 // that was consumed (by "consumeClose()")
1102 return T.getCloseLocation();
1103 }
1104
1105 if (Result.isInvalid()) {
1106 DS.SetTypeSpecError();
1107 return T.getCloseLocation();
1108 }
1109
1110 EndLoc = T.getCloseLocation();
1111 }
1112 assert(!Result.isInvalid());
1113
1114 const char *PrevSpec = nullptr;
1115 unsigned DiagID;
1116 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
1117 // Check for duplicate type specifiers (e.g. "int decltype(a)").
1118 if (Result.get() ? DS.SetTypeSpecType(DeclSpec::TST_decltype, StartLoc,
1119 PrevSpec, DiagID, Result.get(), Policy)
1121 PrevSpec, DiagID, Policy)) {
1122 Diag(StartLoc, DiagID) << PrevSpec;
1123 DS.SetTypeSpecError();
1124 }
1125 DS.SetRangeEnd(EndLoc);
1126 return EndLoc;
1127}
1128
1129void Parser::AnnotateExistingDecltypeSpecifier(const DeclSpec &DS,
1130 SourceLocation StartLoc,
1131 SourceLocation EndLoc) {
1132 // make sure we have a token we can turn into an annotation token
1133 if (PP.isBacktrackEnabled()) {
1134 PP.RevertCachedTokens(1);
1135 } else
1136 PP.EnterToken(Tok, /*IsReinject*/ true);
1137
1138 Tok.setKind(tok::annot_decltype);
1139 setExprAnnotation(Tok,
1142 : ExprError());
1143 Tok.setAnnotationEndLoc(EndLoc);
1144 Tok.setLocation(StartLoc);
1145 PP.AnnotateCachedTokens(Tok);
1146}
1147
1148SourceLocation Parser::ParsePackIndexingType(DeclSpec &DS) {
1149 assert(Tok.isOneOf(tok::annot_pack_indexing_type, tok::identifier) &&
1150 "Expected an identifier");
1151
1153 SourceLocation StartLoc;
1154 SourceLocation EllipsisLoc;
1155 const char *PrevSpec;
1156 unsigned DiagID;
1157 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
1158
1159 if (Tok.is(tok::annot_pack_indexing_type)) {
1160 StartLoc = Tok.getLocation();
1161 SourceLocation EndLoc;
1162 Type = getTypeAnnotation(Tok);
1163 EndLoc = Tok.getAnnotationEndLoc();
1164 // Unfortunately, we don't know the LParen source location as the annotated
1165 // token doesn't have it.
1166 DS.setTypeArgumentRange(SourceRange(SourceLocation(), EndLoc));
1167 ConsumeAnnotationToken();
1168 if (Type.isInvalid()) {
1169 DS.SetTypeSpecError();
1170 return EndLoc;
1171 }
1173 DiagID, Type, Policy);
1174 return EndLoc;
1175 }
1176 if (!NextToken().is(tok::ellipsis) ||
1177 !GetLookAheadToken(2).is(tok::l_square)) {
1178 DS.SetTypeSpecError();
1179 return Tok.getEndLoc();
1180 }
1181
1182 ParsedType Ty = Actions.getTypeName(*Tok.getIdentifierInfo(),
1183 Tok.getLocation(), getCurScope());
1184 if (!Ty) {
1185 DS.SetTypeSpecError();
1186 return Tok.getEndLoc();
1187 }
1188 Type = Ty;
1189
1190 StartLoc = ConsumeToken();
1191 EllipsisLoc = ConsumeToken();
1192 BalancedDelimiterTracker T(*this, tok::l_square);
1193 T.consumeOpen();
1194 ExprResult IndexExpr = ParseConstantExpression();
1195 T.consumeClose();
1196
1197 DS.SetRangeStart(StartLoc);
1198 DS.SetRangeEnd(T.getCloseLocation());
1199
1200 if (!IndexExpr.isUsable()) {
1201 ASTContext &C = Actions.getASTContext();
1202 IndexExpr = IntegerLiteral::Create(C, C.MakeIntValue(0, C.getSizeType()),
1203 C.getSizeType(), SourceLocation());
1204 }
1205
1206 DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc, PrevSpec, DiagID, Type,
1207 Policy);
1208 DS.SetPackIndexingExpr(EllipsisLoc, IndexExpr.get());
1209 return T.getCloseLocation();
1210}
1211
1212void Parser::AnnotateExistingIndexedTypeNamePack(ParsedType T,
1213 SourceLocation StartLoc,
1214 SourceLocation EndLoc) {
1215 // make sure we have a token we can turn into an annotation token
1216 if (PP.isBacktrackEnabled()) {
1217 PP.RevertCachedTokens(1);
1218 if (!T) {
1219 // We encountered an error in parsing 'decltype(...)' so lets annotate all
1220 // the tokens in the backtracking cache - that we likely had to skip over
1221 // to get to a token that allows us to resume parsing, such as a
1222 // semi-colon.
1223 EndLoc = PP.getLastCachedTokenLocation();
1224 }
1225 } else
1226 PP.EnterToken(Tok, /*IsReinject*/ true);
1227
1228 Tok.setKind(tok::annot_pack_indexing_type);
1229 setTypeAnnotation(Tok, T);
1230 Tok.setAnnotationEndLoc(EndLoc);
1231 Tok.setLocation(StartLoc);
1232 PP.AnnotateCachedTokens(Tok);
1233}
1234
1235DeclSpec::TST Parser::TypeTransformTokToDeclSpec() {
1236 switch (Tok.getKind()) {
1237#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) \
1238 case tok::kw___##Trait: \
1239 return DeclSpec::TST_##Trait;
1240#include "clang/Basic/TransformTypeTraits.def"
1241 default:
1242 llvm_unreachable("passed in an unhandled type transformation built-in");
1243 }
1244}
1245
1246bool Parser::MaybeParseTypeTransformTypeSpecifier(DeclSpec &DS) {
1247 if (!NextToken().is(tok::l_paren)) {
1248 Tok.setKind(tok::identifier);
1249 return false;
1250 }
1251 DeclSpec::TST TypeTransformTST = TypeTransformTokToDeclSpec();
1252 SourceLocation StartLoc = ConsumeToken();
1253
1254 BalancedDelimiterTracker T(*this, tok::l_paren);
1255 if (T.expectAndConsume(diag::err_expected_lparen_after, Tok.getName(),
1256 tok::r_paren))
1257 return true;
1258
1260 if (Result.isInvalid()) {
1261 SkipUntil(tok::r_paren, StopAtSemi);
1262 return true;
1263 }
1264
1265 T.consumeClose();
1266 if (T.getCloseLocation().isInvalid())
1267 return true;
1268
1269 const char *PrevSpec = nullptr;
1270 unsigned DiagID;
1271 if (DS.SetTypeSpecType(TypeTransformTST, StartLoc, PrevSpec, DiagID,
1272 Result.get(),
1273 Actions.getASTContext().getPrintingPolicy()))
1274 Diag(StartLoc, DiagID) << PrevSpec;
1275 DS.setTypeArgumentRange(T.getRange());
1276 return true;
1277}
1278
1279TypeResult Parser::ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
1280 SourceLocation &EndLocation) {
1281 // Ignore attempts to use typename
1282 if (Tok.is(tok::kw_typename)) {
1283 Diag(Tok, diag::err_expected_class_name_not_template)
1284 << FixItHint::CreateRemoval(Tok.getLocation());
1285 ConsumeToken();
1286 }
1287
1288 // Parse optional nested-name-specifier
1289 CXXScopeSpec SS;
1290 if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
1291 /*ObjectHasErrors=*/false,
1292 /*EnteringContext=*/false))
1293 return true;
1294
1295 BaseLoc = Tok.getLocation();
1296
1297 // Parse decltype-specifier
1298 // tok == kw_decltype is just error recovery, it can only happen when SS
1299 // isn't empty
1300 if (Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)) {
1301 if (SS.isNotEmpty())
1302 Diag(SS.getBeginLoc(), diag::err_unexpected_scope_on_base_decltype)
1304 // Fake up a Declarator to use with ActOnTypeName.
1305 DeclSpec DS(AttrFactory);
1306
1307 EndLocation = ParseDecltypeSpecifier(DS);
1308
1309 Declarator DeclaratorInfo(DS, ParsedAttributesView::none(),
1311 return Actions.ActOnTypeName(DeclaratorInfo);
1312 }
1313
1314 if (Tok.is(tok::annot_pack_indexing_type)) {
1315 DeclSpec DS(AttrFactory);
1316 ParsePackIndexingType(DS);
1317 Declarator DeclaratorInfo(DS, ParsedAttributesView::none(),
1319 return Actions.ActOnTypeName(DeclaratorInfo);
1320 }
1321
1322 // Check whether we have a template-id that names a type.
1323 // FIXME: identifier and annot_template_id handling in ParseUsingDeclaration
1324 // work very similarly. It should be refactored into a separate function.
1325 if (Tok.is(tok::annot_template_id)) {
1326 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1327 if (TemplateId->mightBeType()) {
1328 AnnotateTemplateIdTokenAsType(SS, ImplicitTypenameContext::No,
1329 /*IsClassName=*/true);
1330
1331 assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
1333 EndLocation = Tok.getAnnotationEndLoc();
1334 ConsumeAnnotationToken();
1335 return Type;
1336 }
1337
1338 // Fall through to produce an error below.
1339 }
1340
1341 if (Tok.isNot(tok::identifier)) {
1342 Diag(Tok, diag::err_expected_class_name);
1343 return true;
1344 }
1345
1346 IdentifierInfo *Id = Tok.getIdentifierInfo();
1347 SourceLocation IdLoc = ConsumeToken();
1348
1349 if (Tok.is(tok::less)) {
1350 // It looks the user intended to write a template-id here, but the
1351 // template-name was wrong. Try to fix that.
1352 // FIXME: Invoke ParseOptionalCXXScopeSpecifier in a "'template' is neither
1353 // required nor permitted" mode, and do this there.
1356 if (!Actions.DiagnoseUnknownTemplateName(*Id, IdLoc, getCurScope(), &SS,
1357 Template, TNK)) {
1358 Diag(IdLoc, diag::err_unknown_template_name) << Id;
1359 }
1360
1361 // Form the template name
1363 TemplateName.setIdentifier(Id, IdLoc);
1364
1365 // Parse the full template-id, then turn it into a type.
1366 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
1367 TemplateName))
1368 return true;
1369 if (Tok.is(tok::annot_template_id) &&
1370 takeTemplateIdAnnotation(Tok)->mightBeType())
1371 AnnotateTemplateIdTokenAsType(SS, ImplicitTypenameContext::No,
1372 /*IsClassName=*/true);
1373
1374 // If we didn't end up with a typename token, there's nothing more we
1375 // can do.
1376 if (Tok.isNot(tok::annot_typename))
1377 return true;
1378
1379 // Retrieve the type from the annotation token, consume that token, and
1380 // return.
1381 EndLocation = Tok.getAnnotationEndLoc();
1383 ConsumeAnnotationToken();
1384 return Type;
1385 }
1386
1387 // We have an identifier; check whether it is actually a type.
1388 IdentifierInfo *CorrectedII = nullptr;
1389 ParsedType Type = Actions.getTypeName(
1390 *Id, IdLoc, getCurScope(), &SS, /*isClassName=*/true, false, nullptr,
1391 /*IsCtorOrDtorName=*/false,
1392 /*WantNontrivialTypeSourceInfo=*/true,
1393 /*IsClassTemplateDeductionContext=*/false, ImplicitTypenameContext::No,
1394 &CorrectedII);
1395 if (!Type) {
1396 Diag(IdLoc, diag::err_expected_class_name);
1397 return true;
1398 }
1399
1400 // Consume the identifier.
1401 EndLocation = IdLoc;
1402
1403 // Fake up a Declarator to use with ActOnTypeName.
1404 DeclSpec DS(AttrFactory);
1405 DS.SetRangeStart(IdLoc);
1406 DS.SetRangeEnd(EndLocation);
1407 DS.getTypeSpecScope() = std::move(SS);
1408
1409 const char *PrevSpec = nullptr;
1410 unsigned DiagID;
1411 DS.SetTypeSpecType(TST_typename, IdLoc, PrevSpec, DiagID, Type,
1412 Actions.getASTContext().getPrintingPolicy());
1413
1414 Declarator DeclaratorInfo(DS, ParsedAttributesView::none(),
1416 return Actions.ActOnTypeName(DeclaratorInfo);
1417}
1418
1419void Parser::ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs) {
1420 while (Tok.isOneOf(tok::kw___single_inheritance,
1421 tok::kw___multiple_inheritance,
1422 tok::kw___virtual_inheritance)) {
1423 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
1424 auto Kind = Tok.getKind();
1425 SourceLocation AttrNameLoc = ConsumeToken();
1426 attrs.addNew(AttrName, AttrNameLoc, AttributeScopeInfo(), nullptr, 0, Kind);
1427 }
1428}
1429
1430void Parser::ParseNullabilityClassAttributes(ParsedAttributes &attrs) {
1431 while (Tok.is(tok::kw__Nullable)) {
1432 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
1433 auto Kind = Tok.getKind();
1434 SourceLocation AttrNameLoc = ConsumeToken();
1435 attrs.addNew(AttrName, AttrNameLoc, AttributeScopeInfo(), nullptr, 0, Kind);
1436 }
1437}
1438
1439bool Parser::isValidAfterTypeSpecifier(bool CouldBeBitfield) {
1440 // This switch enumerates the valid "follow" set for type-specifiers.
1441 switch (Tok.getKind()) {
1442 default:
1443 if (Tok.isRegularKeywordAttribute())
1444 return true;
1445 break;
1446 case tok::semi: // struct foo {...} ;
1447 case tok::star: // struct foo {...} * P;
1448 case tok::amp: // struct foo {...} & R = ...
1449 case tok::ampamp: // struct foo {...} && R = ...
1450 case tok::identifier: // struct foo {...} V ;
1451 case tok::r_paren: //(struct foo {...} ) {4}
1452 case tok::coloncolon: // struct foo {...} :: a::b;
1453 case tok::annot_cxxscope: // struct foo {...} a:: b;
1454 case tok::annot_typename: // struct foo {...} a ::b;
1455 case tok::annot_template_id: // struct foo {...} a<int> ::b;
1456 case tok::kw_decltype: // struct foo {...} decltype (a)::b;
1457 case tok::l_paren: // struct foo {...} ( x);
1458 case tok::comma: // __builtin_offsetof(struct foo{...} ,
1459 case tok::kw_operator: // struct foo operator ++() {...}
1460 case tok::kw___declspec: // struct foo {...} __declspec(...)
1461 case tok::l_square: // void f(struct f [ 3])
1462 case tok::ellipsis: // void f(struct f ... [Ns])
1463 // FIXME: we should emit semantic diagnostic when declaration
1464 // attribute is in type attribute position.
1465 case tok::kw___attribute: // struct foo __attribute__((used)) x;
1466 case tok::annot_pragma_pack: // struct foo {...} _Pragma(pack(pop));
1467 // struct foo {...} _Pragma(section(...));
1468 case tok::annot_pragma_ms_pragma:
1469 // struct foo {...} _Pragma(vtordisp(pop));
1470 case tok::annot_pragma_ms_vtordisp:
1471 // struct foo {...} _Pragma(pointers_to_members(...));
1472 case tok::annot_pragma_ms_pointers_to_members:
1473 // struct foo {...} _Pragma(export(...));
1474 case tok::annot_pragma_export:
1475 return true;
1476 case tok::colon:
1477 return CouldBeBitfield || // enum E { ... } : 2;
1478 ColonIsSacred; // _Generic(..., enum E : 2);
1479 // Microsoft compatibility
1480 case tok::kw___cdecl: // struct foo {...} __cdecl x;
1481 case tok::kw___fastcall: // struct foo {...} __fastcall x;
1482 case tok::kw___stdcall: // struct foo {...} __stdcall x;
1483 case tok::kw___thiscall: // struct foo {...} __thiscall x;
1484 case tok::kw___vectorcall: // struct foo {...} __vectorcall x;
1485 // We will diagnose these calling-convention specifiers on non-function
1486 // declarations later, so claim they are valid after a type specifier.
1487 return getLangOpts().MicrosoftExt;
1488 // Type qualifiers
1489 case tok::kw_const: // struct foo {...} const x;
1490 case tok::kw_volatile: // struct foo {...} volatile x;
1491 case tok::kw_restrict: // struct foo {...} restrict x;
1492 case tok::kw__Atomic: // struct foo {...} _Atomic x;
1493 case tok::kw___unaligned: // struct foo {...} __unaligned *x;
1494 // Function specifiers
1495 // Note, no 'explicit'. An explicit function must be either a conversion
1496 // operator or a constructor. Either way, it can't have a return type.
1497 case tok::kw_inline: // struct foo inline f();
1498 case tok::kw_virtual: // struct foo virtual f();
1499 case tok::kw_friend: // struct foo friend f();
1500 // Storage-class specifiers
1501 case tok::kw_static: // struct foo {...} static x;
1502 case tok::kw_extern: // struct foo {...} extern x;
1503 case tok::kw_typedef: // struct foo {...} typedef x;
1504 case tok::kw_register: // struct foo {...} register x;
1505 case tok::kw_auto: // struct foo {...} auto x;
1506 case tok::kw_mutable: // struct foo {...} mutable x;
1507 case tok::kw_thread_local: // struct foo {...} thread_local x;
1508 case tok::kw_constexpr: // struct foo {...} constexpr x;
1509 case tok::kw_consteval: // struct foo {...} consteval x;
1510 case tok::kw_constinit: // struct foo {...} constinit x;
1511 // As shown above, type qualifiers and storage class specifiers absolutely
1512 // can occur after class specifiers according to the grammar. However,
1513 // almost no one actually writes code like this. If we see one of these,
1514 // it is much more likely that someone missed a semi colon and the
1515 // type/storage class specifier we're seeing is part of the *next*
1516 // intended declaration, as in:
1517 //
1518 // struct foo { ... }
1519 // typedef int X;
1520 //
1521 // We'd really like to emit a missing semicolon error instead of emitting
1522 // an error on the 'int' saying that you can't have two type specifiers in
1523 // the same declaration of X. Because of this, we look ahead past this
1524 // token to see if it's a type specifier. If so, we know the code is
1525 // otherwise invalid, so we can produce the expected semi error.
1526 if (!isKnownToBeTypeSpecifier(NextToken()))
1527 return true;
1528 break;
1529 case tok::r_brace: // struct bar { struct foo {...} }
1530 // Missing ';' at end of struct is accepted as an extension in C mode.
1531 if (!getLangOpts().CPlusPlus)
1532 return true;
1533 break;
1534 case tok::greater:
1535 // template<class T = class X>
1536 return getLangOpts().CPlusPlus;
1537 }
1538 return false;
1539}
1540
1541void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind,
1542 SourceLocation StartLoc, DeclSpec &DS,
1543 ParsedTemplateInfo &TemplateInfo,
1544 AccessSpecifier AS, bool EnteringContext,
1545 DeclSpecContext DSC,
1546 ParsedAttributes &Attributes) {
1547 DeclSpec::TST TagType;
1548 if (TagTokKind == tok::kw_struct)
1549 TagType = DeclSpec::TST_struct;
1550 else if (TagTokKind == tok::kw___interface)
1551 TagType = DeclSpec::TST_interface;
1552 else if (TagTokKind == tok::kw_class)
1553 TagType = DeclSpec::TST_class;
1554 else {
1555 assert(TagTokKind == tok::kw_union && "Not a class specifier");
1556 TagType = DeclSpec::TST_union;
1557 }
1558
1559 if (Tok.is(tok::code_completion)) {
1560 // Code completion for a struct, class, or union name.
1561 cutOffParsing();
1562 Actions.CodeCompletion().CodeCompleteTag(getCurScope(), TagType);
1563 return;
1564 }
1565
1566 // C++20 [temp.class.spec] 13.7.5/10
1567 // The usual access checking rules do not apply to non-dependent names
1568 // used to specify template arguments of the simple-template-id of the
1569 // partial specialization.
1570 // C++20 [temp.spec] 13.9/6:
1571 // The usual access checking rules do not apply to names in a declaration
1572 // of an explicit instantiation or explicit specialization...
1573 const bool shouldDelayDiagsInTag =
1574 (TemplateInfo.Kind != ParsedTemplateKind::NonTemplate);
1575 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
1576
1577 ParsedAttributes attrs(AttrFactory);
1578 // If attributes exist after tag, parse them.
1579 for (;;) {
1580 MaybeParseAttributes(PAKM_CXX11 | PAKM_Declspec | PAKM_GNU, attrs);
1581 // Parse inheritance specifiers.
1582 if (Tok.isOneOf(tok::kw___single_inheritance,
1583 tok::kw___multiple_inheritance,
1584 tok::kw___virtual_inheritance)) {
1585 ParseMicrosoftInheritanceClassAttributes(attrs);
1586 continue;
1587 }
1588 if (Tok.is(tok::kw__Nullable)) {
1589 ParseNullabilityClassAttributes(attrs);
1590 continue;
1591 }
1592 break;
1593 }
1594
1595 // Source location used by FIXIT to insert misplaced
1596 // C++11 attributes
1597 SourceLocation AttrFixitLoc = Tok.getLocation();
1598
1599 if (TagType == DeclSpec::TST_struct && Tok.isNot(tok::identifier) &&
1600 !Tok.isAnnotation() && Tok.getIdentifierInfo() &&
1601 Tok.isOneOf(
1602#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) tok::kw___##Trait,
1603#include "clang/Basic/TransformTypeTraits.def"
1604 tok::kw___is_abstract,
1605 tok::kw___is_aggregate,
1606 tok::kw___is_arithmetic,
1607 tok::kw___is_array,
1608 tok::kw___is_assignable,
1609 tok::kw___is_base_of,
1610 tok::kw___is_bounded_array,
1611 tok::kw___is_class,
1612 tok::kw___is_complete_type,
1613 tok::kw___is_compound,
1614 tok::kw___is_const,
1615 tok::kw___is_constructible,
1616 tok::kw___is_convertible,
1617 tok::kw___is_convertible_to,
1618 tok::kw___is_destructible,
1619 tok::kw___is_empty,
1620 tok::kw___is_enum,
1621 tok::kw___is_floating_point,
1622 tok::kw___is_final,
1623 tok::kw___is_function,
1624 tok::kw___is_fundamental,
1625 tok::kw___is_integral,
1626 tok::kw___is_interface_class,
1627 tok::kw___is_literal,
1628 tok::kw___is_lvalue_expr,
1629 tok::kw___is_lvalue_reference,
1630 tok::kw___is_member_function_pointer,
1631 tok::kw___is_member_object_pointer,
1632 tok::kw___is_member_pointer,
1633 tok::kw___is_nothrow_assignable,
1634 tok::kw___is_nothrow_constructible,
1635 tok::kw___is_nothrow_convertible,
1636 tok::kw___is_nothrow_destructible,
1637 tok::kw___is_object,
1638 tok::kw___is_pod,
1639 tok::kw___is_pointer,
1640 tok::kw___is_polymorphic,
1641 tok::kw___is_reference,
1642 tok::kw___is_rvalue_expr,
1643 tok::kw___is_rvalue_reference,
1644 tok::kw___is_same,
1645 tok::kw___is_scalar,
1646 tok::kw___is_scoped_enum,
1647 tok::kw___is_sealed,
1648 tok::kw___is_signed,
1649 tok::kw___is_standard_layout,
1650 tok::kw___is_trivial,
1651 tok::kw___is_trivially_equality_comparable,
1652 tok::kw___is_trivially_assignable,
1653 tok::kw___is_trivially_constructible,
1654 tok::kw___is_trivially_copyable,
1655 tok::kw___is_unbounded_array,
1656 tok::kw___is_union,
1657 tok::kw___is_unsigned,
1658 tok::kw___is_void,
1659 tok::kw___is_volatile
1660 ))
1661 // GNU libstdc++ 4.2 and libc++ use certain intrinsic names as the
1662 // name of struct templates, but some are keywords in GCC >= 4.3
1663 // and Clang. Therefore, when we see the token sequence "struct
1664 // X", make X into a normal identifier rather than a keyword, to
1665 // allow libstdc++ 4.2 and libc++ to work properly.
1666 TryKeywordIdentFallback(true);
1667
1668 struct PreserveAtomicIdentifierInfoRAII {
1669 PreserveAtomicIdentifierInfoRAII(Token &Tok, bool Enabled)
1670 : AtomicII(nullptr) {
1671 if (!Enabled)
1672 return;
1673 assert(Tok.is(tok::kw__Atomic));
1674 AtomicII = Tok.getIdentifierInfo();
1675 AtomicII->revertTokenIDToIdentifier();
1676 Tok.setKind(tok::identifier);
1677 }
1678 ~PreserveAtomicIdentifierInfoRAII() {
1679 if (!AtomicII)
1680 return;
1681 AtomicII->revertIdentifierToTokenID(tok::kw__Atomic);
1682 }
1683 IdentifierInfo *AtomicII;
1684 };
1685
1686 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
1687 // implementation for VS2013 uses _Atomic as an identifier for one of the
1688 // classes in <atomic>. When we are parsing 'struct _Atomic', don't consider
1689 // '_Atomic' to be a keyword. We are careful to undo this so that clang can
1690 // use '_Atomic' in its own header files.
1691 bool ShouldChangeAtomicToIdentifier = getLangOpts().MSVCCompat &&
1692 Tok.is(tok::kw__Atomic) &&
1693 TagType == DeclSpec::TST_struct;
1694 PreserveAtomicIdentifierInfoRAII AtomicTokenGuard(
1695 Tok, ShouldChangeAtomicToIdentifier);
1696
1697 // Parse the (optional) nested-name-specifier.
1698 CXXScopeSpec &SS = DS.getTypeSpecScope();
1699 if (getLangOpts().CPlusPlus) {
1700 // "FOO : BAR" is not a potential typo for "FOO::BAR". In this context it
1701 // is a base-specifier-list.
1703
1704 CXXScopeSpec Spec;
1705 if (TemplateInfo.TemplateParams)
1706 Spec.setTemplateParamLists(*TemplateInfo.TemplateParams);
1707
1708 bool HasValidSpec = true;
1709 if (ParseOptionalCXXScopeSpecifier(Spec, /*ObjectType=*/nullptr,
1710 /*ObjectHasErrors=*/false,
1711 EnteringContext)) {
1712 DS.SetTypeSpecError();
1713 HasValidSpec = false;
1714 }
1715 if (Spec.isSet())
1716 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::annot_template_id)) {
1717 Diag(Tok, diag::err_expected) << tok::identifier;
1718 HasValidSpec = false;
1719 }
1720 if (HasValidSpec)
1721 SS = Spec;
1722 }
1723
1724 TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
1725
1726 auto RecoverFromUndeclaredTemplateName = [&](IdentifierInfo *Name,
1727 SourceLocation NameLoc,
1728 SourceRange TemplateArgRange,
1729 bool KnownUndeclared) {
1730 Diag(NameLoc, diag::err_explicit_spec_non_template)
1731 << (TemplateInfo.Kind == ParsedTemplateKind::ExplicitInstantiation)
1732 << TagTokKind << Name << TemplateArgRange << KnownUndeclared;
1733
1734 // Strip off the last template parameter list if it was empty, since
1735 // we've removed its template argument list.
1736 if (TemplateParams && TemplateInfo.LastParameterListWasEmpty) {
1737 if (TemplateParams->size() > 1) {
1738 TemplateParams->pop_back();
1739 } else {
1740 TemplateParams = nullptr;
1741 TemplateInfo.Kind = ParsedTemplateKind::NonTemplate;
1742 }
1743 } else if (TemplateInfo.Kind == ParsedTemplateKind::ExplicitInstantiation) {
1744 // Pretend this is just a forward declaration.
1745 TemplateParams = nullptr;
1746 TemplateInfo.Kind = ParsedTemplateKind::NonTemplate;
1747 TemplateInfo.TemplateLoc = SourceLocation();
1748 TemplateInfo.ExternLoc = SourceLocation();
1749 }
1750 };
1751
1752 // Parse the (optional) class name or simple-template-id.
1753 IdentifierInfo *Name = nullptr;
1754 SourceLocation NameLoc;
1755 TemplateIdAnnotation *TemplateId = nullptr;
1756 if (Tok.is(tok::identifier)) {
1757 Name = Tok.getIdentifierInfo();
1758 NameLoc = ConsumeToken();
1759 DS.SetRangeEnd(NameLoc);
1760
1761 if (Tok.is(tok::less) && getLangOpts().CPlusPlus) {
1762 // The name was supposed to refer to a template, but didn't.
1763 // Eat the template argument list and try to continue parsing this as
1764 // a class (or template thereof).
1765 TemplateArgList TemplateArgs;
1766 SourceLocation LAngleLoc, RAngleLoc;
1767 if (ParseTemplateIdAfterTemplateName(true, LAngleLoc, TemplateArgs,
1768 RAngleLoc)) {
1769 // We couldn't parse the template argument list at all, so don't
1770 // try to give any location information for the list.
1771 LAngleLoc = RAngleLoc = SourceLocation();
1772 }
1773 RecoverFromUndeclaredTemplateName(
1774 Name, NameLoc, SourceRange(LAngleLoc, RAngleLoc), false);
1775 }
1776 } else if (Tok.is(tok::annot_template_id)) {
1777 TemplateId = takeTemplateIdAnnotation(Tok);
1778 NameLoc = ConsumeAnnotationToken();
1779
1780 if (TemplateId->Kind == TNK_Undeclared_template) {
1781 // Try to resolve the template name to a type template. May update Kind.
1782 Actions.ActOnUndeclaredTypeTemplateName(
1783 getCurScope(), TemplateId->Template, TemplateId->Kind, NameLoc, Name);
1784 if (TemplateId->Kind == TNK_Undeclared_template) {
1785 RecoverFromUndeclaredTemplateName(
1786 Name, NameLoc,
1787 SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc), true);
1788 TemplateId = nullptr;
1789 }
1790 }
1791
1792 if (TemplateId && !TemplateId->mightBeType()) {
1793 // The template-name in the simple-template-id refers to
1794 // something other than a type template. Give an appropriate
1795 // error message and skip to the ';'.
1796 SourceRange Range(NameLoc);
1797 if (SS.isNotEmpty())
1798 Range.setBegin(SS.getBeginLoc());
1799
1800 // FIXME: Name may be null here.
1801 Diag(TemplateId->LAngleLoc, diag::err_template_spec_syntax_non_template)
1802 << TemplateId->Name << static_cast<int>(TemplateId->Kind) << Range;
1803
1804 DS.SetTypeSpecError();
1805 SkipUntil(tok::semi, StopBeforeMatch);
1806 return;
1807 }
1808 }
1809
1810 // There are four options here.
1811 // - If we are in a trailing return type, this is always just a reference,
1812 // and we must not try to parse a definition. For instance,
1813 // [] () -> struct S { };
1814 // does not define a type.
1815 // - If we have 'struct foo {...', 'struct foo :...',
1816 // 'struct foo final :' or 'struct foo final {', then this is a definition.
1817 // - If we have 'struct foo;', then this is either a forward declaration
1818 // or a friend declaration, which have to be treated differently.
1819 // - Otherwise we have something like 'struct foo xyz', a reference.
1820 //
1821 // We also detect these erroneous cases to provide better diagnostic for
1822 // C++11 attributes parsing.
1823 // - attributes follow class name:
1824 // struct foo [[]] {};
1825 // - attributes appear before or after 'final':
1826 // struct foo [[]] final [[]] {};
1827 //
1828 // However, in type-specifier-seq's, things look like declarations but are
1829 // just references, e.g.
1830 // new struct s;
1831 // or
1832 // &T::operator struct s;
1833 // For these, DSC is DeclSpecContext::DSC_type_specifier or
1834 // DeclSpecContext::DSC_alias_declaration.
1835
1836 // If there are attributes after class name, parse them.
1837 MaybeParseCXX11Attributes(Attributes);
1838
1839 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
1840 TagUseKind TUK;
1841
1842 // C++26 [class.mem.general]p10: If a name-declaration matches the
1843 // syntactic requirements of friend-type-declaration, it is a
1844 // friend-type-declaration.
1846 Tok.isOneOf(tok::comma, tok::ellipsis))
1847 TUK = TagUseKind::Friend;
1848 else if (isDefiningTypeSpecifierContext(DSC, getLangOpts().CPlusPlus) ==
1849 AllowDefiningTypeSpec::No ||
1850 (getLangOpts().OpenMP && OpenMPDirectiveParsing))
1852 else if (Tok.is(tok::l_brace) ||
1853 (DSC != DeclSpecContext::DSC_association &&
1854 getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
1855 (isClassCompatibleKeyword() &&
1856 (NextToken().is(tok::l_brace) || NextToken().is(tok::colon) ||
1857 isClassCompatibleKeyword(NextToken())))) {
1858 if (DS.isFriendSpecified()) {
1859 // C++ [class.friend]p2:
1860 // A class shall not be defined in a friend declaration.
1861 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
1862 << SourceRange(DS.getFriendSpecLoc());
1863
1864 // Skip everything up to the semicolon, so that this looks like a proper
1865 // friend class (or template thereof) declaration.
1866 SkipUntil(tok::semi, StopBeforeMatch);
1867 TUK = TagUseKind::Friend;
1868 } else {
1869 // Okay, this is a class definition.
1871 }
1872 } else if (isClassCompatibleKeyword() &&
1873 (NextToken().is(tok::l_square) ||
1874 NextToken().is(tok::kw_alignas) ||
1876 isCXX11VirtSpecifier(NextToken()) != VirtSpecifiers::VS_None)) {
1877 // We can't tell if this is a definition or reference
1878 // until we skipped the 'final' and C++11 attribute specifiers.
1879 TentativeParsingAction PA(*this);
1880
1881 // Skip the 'final', abstract'... keywords.
1882 while (isClassCompatibleKeyword())
1883 ConsumeToken();
1884
1885 // Skip C++11 attribute specifiers.
1886 while (true) {
1887 if (Tok.is(tok::l_square) && NextToken().is(tok::l_square)) {
1888 ConsumeBracket();
1889 if (!SkipUntil(tok::r_square, StopAtSemi))
1890 break;
1891 } else if (Tok.is(tok::kw_alignas) && NextToken().is(tok::l_paren)) {
1892 ConsumeToken();
1893 ConsumeParen();
1894 if (!SkipUntil(tok::r_paren, StopAtSemi))
1895 break;
1896 } else if (Tok.isRegularKeywordAttribute()) {
1897 bool TakesArgs = doesKeywordAttributeTakeArgs(Tok.getKind());
1898 ConsumeToken();
1899 if (TakesArgs) {
1900 BalancedDelimiterTracker T(*this, tok::l_paren);
1901 if (!T.consumeOpen())
1902 T.skipToEnd();
1903 }
1904 } else {
1905 break;
1906 }
1907 }
1908
1909 if (Tok.isOneOf(tok::l_brace, tok::colon))
1911 else
1913
1914 PA.Revert();
1915 } else if (!isTypeSpecifier(DSC) &&
1916 (Tok.is(tok::semi) ||
1917 (Tok.isAtStartOfLine() && !isValidAfterTypeSpecifier(false)))) {
1919 if (Tok.isNot(tok::semi)) {
1920 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
1921 // A semicolon was missing after this declaration. Diagnose and recover.
1922 ExpectAndConsume(tok::semi, diag::err_expected_after,
1923 DeclSpec::getSpecifierName(TagType, PPol));
1924 PP.EnterToken(Tok, /*IsReinject*/ true);
1925 Tok.setKind(tok::semi);
1926 }
1927 } else
1929
1930 // Forbid misplaced attributes. In cases of a reference, we pass attributes
1931 // to caller to handle.
1932 if (TUK != TagUseKind::Reference) {
1933 // If this is not a reference, then the only possible
1934 // valid place for C++11 attributes to appear here
1935 // is between class-key and class-name. If there are
1936 // any attributes after class-name, we try a fixit to move
1937 // them to the right place.
1938 SourceRange AttrRange = Attributes.Range;
1939 if (AttrRange.isValid()) {
1940 auto *FirstAttr = Attributes.empty() ? nullptr : &Attributes.front();
1941 auto Loc = AttrRange.getBegin();
1942 (FirstAttr && FirstAttr->isRegularKeywordAttribute()
1943 ? Diag(Loc, diag::err_keyword_not_allowed) << FirstAttr
1944 : Diag(Loc, diag::err_attributes_not_allowed))
1945 << AttrRange
1947 AttrFixitLoc, CharSourceRange(AttrRange, true))
1948 << FixItHint::CreateRemoval(AttrRange);
1949
1950 // Recover by adding misplaced attributes to the attribute list
1951 // of the class so they can be applied on the class later.
1952 attrs.takeAllAppendingFrom(Attributes);
1953 }
1954 }
1955
1956 if (!Name && !TemplateId &&
1958 TUK != TagUseKind::Definition)) {
1960 // We have a declaration or reference to an anonymous class.
1961 Diag(StartLoc, diag::err_anon_type_definition)
1962 << DeclSpec::getSpecifierName(TagType, Policy);
1963 }
1964
1965 // If we are parsing a definition and stop at a base-clause, continue on
1966 // until the semicolon. Continuing from the comma will just trick us into
1967 // thinking we are seeing a variable declaration.
1968 if (TUK == TagUseKind::Definition && Tok.is(tok::colon))
1969 SkipUntil(tok::semi, StopBeforeMatch);
1970 else
1971 SkipUntil(tok::comma, StopAtSemi);
1972 return;
1973 }
1974
1975 // Create the tag portion of the class or class template.
1976 DeclResult TagOrTempResult = true; // invalid
1977 TypeResult TypeResult = true; // invalid
1978
1979 bool Owned = false;
1980 SkipBodyInfo SkipBody;
1981 if (TemplateId) {
1982 // Explicit specialization, class template partial specialization,
1983 // or explicit instantiation.
1984 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1985 TemplateId->NumArgs);
1986 if (TemplateId->isInvalid()) {
1987 // Can't build the declaration.
1988 } else if (TemplateInfo.Kind == ParsedTemplateKind::ExplicitInstantiation &&
1989 TUK == TagUseKind::Declaration) {
1990 // This is an explicit instantiation of a class template.
1991 ProhibitCXX11Attributes(attrs, diag::err_attributes_not_allowed,
1992 diag::err_keyword_not_allowed,
1993 /*DiagnoseEmptyAttrs=*/true);
1994
1995 TagOrTempResult = Actions.ActOnExplicitInstantiation(
1996 getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc,
1997 TagType, StartLoc, SS, TemplateId->Template,
1998 TemplateId->TemplateNameLoc, TemplateId->LAngleLoc, TemplateArgsPtr,
1999 TemplateId->RAngleLoc, attrs);
2000
2001 // Friend template-ids are treated as references unless
2002 // they have template headers, in which case they're ill-formed
2003 // (FIXME: "template <class T> friend class A<T>::B<int>;").
2004 // We diagnose this error in ActOnClassTemplateSpecialization.
2005 } else if (TUK == TagUseKind::Reference ||
2006 (TUK == TagUseKind::Friend &&
2007 TemplateInfo.Kind == ParsedTemplateKind::NonTemplate)) {
2008 ProhibitCXX11Attributes(attrs, diag::err_attributes_not_allowed,
2009 diag::err_keyword_not_allowed,
2010 /*DiagnoseEmptyAttrs=*/true);
2011 TypeResult = Actions.ActOnTagTemplateIdType(
2012 TUK, TagType, StartLoc, SS, TemplateId->TemplateKWLoc,
2013 TemplateId->Template, TemplateId->TemplateNameLoc,
2014 TemplateId->LAngleLoc, TemplateArgsPtr, TemplateId->RAngleLoc);
2015 } else {
2016 // This is an explicit specialization or a class template
2017 // partial specialization.
2018 TemplateParameterLists FakedParamLists;
2019 if (TemplateInfo.Kind == ParsedTemplateKind::ExplicitInstantiation) {
2020 // This looks like an explicit instantiation, because we have
2021 // something like
2022 //
2023 // template class Foo<X>
2024 //
2025 // but it actually has a definition. Most likely, this was
2026 // meant to be an explicit specialization, but the user forgot
2027 // the '<>' after 'template'.
2028 // It this is friend declaration however, since it cannot have a
2029 // template header, it is most likely that the user meant to
2030 // remove the 'template' keyword.
2031 assert((TUK == TagUseKind::Definition || TUK == TagUseKind::Friend) &&
2032 "Expected a definition here");
2033
2034 if (TUK == TagUseKind::Friend) {
2035 Diag(DS.getFriendSpecLoc(), diag::err_friend_explicit_instantiation);
2036 TemplateParams = nullptr;
2037 } else {
2038 SourceLocation LAngleLoc =
2039 PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
2040 Diag(TemplateId->TemplateNameLoc,
2041 diag::err_explicit_instantiation_with_definition)
2042 << SourceRange(TemplateInfo.TemplateLoc)
2043 << FixItHint::CreateInsertion(LAngleLoc, "<>");
2044
2045 // Create a fake template parameter list that contains only
2046 // "template<>", so that we treat this construct as a class
2047 // template specialization.
2048 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
2049 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, {},
2050 LAngleLoc, nullptr));
2051 TemplateParams = &FakedParamLists;
2052 }
2053 }
2054
2055 // Build the class template specialization.
2056 TagOrTempResult = Actions.ActOnClassTemplateSpecialization(
2057 getCurScope(), TagType, TUK, StartLoc, DS.getModulePrivateSpecLoc(),
2058 SS, *TemplateId, attrs,
2059 MultiTemplateParamsArg(TemplateParams ? &(*TemplateParams)[0]
2060 : nullptr,
2061 TemplateParams ? TemplateParams->size() : 0),
2062 &SkipBody);
2063 }
2064 } else if (TemplateInfo.Kind == ParsedTemplateKind::ExplicitInstantiation &&
2065 TUK == TagUseKind::Declaration) {
2066 // Explicit instantiation of a member of a class template
2067 // specialization, e.g.,
2068 //
2069 // template struct Outer<int>::Inner;
2070 //
2071 ProhibitAttributes(attrs);
2072
2073 TagOrTempResult = Actions.ActOnExplicitInstantiation(
2074 getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc,
2075 TagType, StartLoc, SS, Name, NameLoc, attrs);
2076 } else if (TUK == TagUseKind::Friend &&
2077 TemplateInfo.Kind != ParsedTemplateKind::NonTemplate) {
2078 ProhibitCXX11Attributes(attrs, diag::err_attributes_not_allowed,
2079 diag::err_keyword_not_allowed,
2080 /*DiagnoseEmptyAttrs=*/true);
2081
2082 // Consume '...' first so we error on the ',' after it if there is one.
2083 SourceLocation EllipsisLoc;
2084 TryConsumeToken(tok::ellipsis, EllipsisLoc);
2085
2086 // CWG 2917: In a template-declaration whose declaration is a
2087 // friend-type-declaration, the friend-type-specifier-list shall
2088 // consist of exactly one friend-type-specifier.
2089 //
2090 // Essentially, the following is obviously nonsense, so disallow it:
2091 //
2092 // template <typename>
2093 // friend class S, int;
2094 //
2095 if (Tok.is(tok::comma)) {
2096 Diag(Tok.getLocation(),
2097 diag::err_friend_template_decl_multiple_specifiers);
2098 SkipUntil(tok::semi, StopBeforeMatch);
2099 }
2100
2101 TagOrTempResult = Actions.ActOnTemplatedFriendTag(
2102 getCurScope(), DS.getFriendSpecLoc(), TagType, StartLoc, SS, Name,
2103 NameLoc, EllipsisLoc, attrs,
2104 MultiTemplateParamsArg(TemplateParams ? &(*TemplateParams)[0] : nullptr,
2105 TemplateParams ? TemplateParams->size() : 0));
2106 } else {
2108 ProhibitCXX11Attributes(attrs, diag::err_attributes_not_allowed,
2109 diag::err_keyword_not_allowed,
2110 /* DiagnoseEmptyAttrs=*/true);
2111
2112 if (TUK == TagUseKind::Definition &&
2113 TemplateInfo.Kind == ParsedTemplateKind::ExplicitInstantiation) {
2114 // If the declarator-id is not a template-id, issue a diagnostic and
2115 // recover by ignoring the 'template' keyword.
2116 Diag(Tok, diag::err_template_defn_explicit_instantiation)
2117 << 1 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
2118 TemplateParams = nullptr;
2119 }
2120
2121 bool IsDependent = false;
2122
2123 // Don't pass down template parameter lists if this is just a tag
2124 // reference. For example, we don't need the template parameters here:
2125 // template <class T> class A *makeA(T t);
2126 MultiTemplateParamsArg TParams;
2127 if (TUK != TagUseKind::Reference && TemplateParams)
2128 TParams =
2129 MultiTemplateParamsArg(&(*TemplateParams)[0], TemplateParams->size());
2130
2131 stripTypeAttributesOffDeclSpec(attrs, DS, TUK);
2132
2133 // Declaration or definition of a class type
2134 TagOrTempResult = Actions.ActOnTag(
2135 getCurScope(), TagType, TUK, StartLoc, SS, Name, NameLoc, attrs, AS,
2136 DS.getModulePrivateSpecLoc(), TParams, Owned, IsDependent,
2137 SourceLocation(), false, clang::TypeResult(),
2138 DSC == DeclSpecContext::DSC_type_specifier,
2139 DSC == DeclSpecContext::DSC_template_param ||
2140 DSC == DeclSpecContext::DSC_template_type_arg,
2141 OffsetOfState, &SkipBody);
2142
2143 // If ActOnTag said the type was dependent, try again with the
2144 // less common call.
2145 if (IsDependent) {
2146 assert(TUK == TagUseKind::Reference || TUK == TagUseKind::Friend);
2147 TypeResult = Actions.ActOnDependentTag(getCurScope(), TagType, TUK, SS,
2148 Name, StartLoc, NameLoc);
2149 }
2150 }
2151
2152 // If this is an elaborated type specifier in function template,
2153 // and we delayed diagnostics before,
2154 // just merge them into the current pool.
2155 if (shouldDelayDiagsInTag) {
2156 diagsFromTag.done();
2157 if (TUK == TagUseKind::Reference &&
2158 TemplateInfo.Kind == ParsedTemplateKind::Template)
2159 diagsFromTag.redelay();
2160 }
2161
2162 // If there is a body, parse it and inform the actions module.
2163 if (TUK == TagUseKind::Definition) {
2164 assert(Tok.is(tok::l_brace) ||
2165 (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
2166 isClassCompatibleKeyword());
2167 if (SkipBody.ShouldSkip)
2168 SkipCXXMemberSpecification(StartLoc, AttrFixitLoc, TagType,
2169 TagOrTempResult.get());
2170 else if (getLangOpts().CPlusPlus)
2171 ParseCXXMemberSpecification(StartLoc, AttrFixitLoc, attrs, TagType,
2172 TagOrTempResult.get());
2173 else {
2174 Decl *D =
2175 SkipBody.CheckSameAsPrevious ? SkipBody.New : TagOrTempResult.get();
2176 // Parse the definition body.
2177 ParseStructUnionBody(StartLoc, TagType, cast<RecordDecl>(D));
2178 if (SkipBody.CheckSameAsPrevious &&
2179 !Actions.ActOnDuplicateDefinition(getCurScope(),
2180 TagOrTempResult.get(), SkipBody)) {
2181 DS.SetTypeSpecError();
2182 return;
2183 }
2184 }
2185 }
2186
2187 if (!TagOrTempResult.isInvalid())
2188 // Delayed processing of attributes.
2189 Actions.ProcessDeclAttributeDelayed(TagOrTempResult.get(), attrs);
2190
2191 const char *PrevSpec = nullptr;
2192 unsigned DiagID;
2193 bool Result;
2194 if (!TypeResult.isInvalid()) {
2196 NameLoc.isValid() ? NameLoc : StartLoc,
2197 PrevSpec, DiagID, TypeResult.get(), Policy);
2198 } else if (!TagOrTempResult.isInvalid()) {
2200 TagType, StartLoc, NameLoc.isValid() ? NameLoc : StartLoc, PrevSpec,
2201 DiagID, TagOrTempResult.get(), Owned, Policy);
2202 } else {
2203 DS.SetTypeSpecError();
2204 return;
2205 }
2206
2207 if (Result)
2208 Diag(StartLoc, DiagID) << PrevSpec;
2209
2210 // At this point, we've successfully parsed a class-specifier in 'definition'
2211 // form (e.g. "struct foo { int x; }". While we could just return here, we're
2212 // going to look at what comes after it to improve error recovery. If an
2213 // impossible token occurs next, we assume that the programmer forgot a ; at
2214 // the end of the declaration and recover that way.
2215 //
2216 // Also enforce C++ [temp]p3:
2217 // In a template-declaration which defines a class, no declarator
2218 // is permitted.
2219 //
2220 // After a type-specifier, we don't expect a semicolon. This only happens in
2221 // C, since definitions are not permitted in this context in C++.
2222 if (TUK == TagUseKind::Definition &&
2223 (getLangOpts().CPlusPlus || !isTypeSpecifier(DSC)) &&
2224 (TemplateInfo.Kind != ParsedTemplateKind::NonTemplate || !isValidAfterTypeSpecifier(false))) {
2225 if (Tok.isNot(tok::semi)) {
2226 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
2227 ExpectAndConsume(tok::semi, diag::err_expected_after,
2228 DeclSpec::getSpecifierName(TagType, PPol));
2229 // Push this token back into the preprocessor and change our current token
2230 // to ';' so that the rest of the code recovers as though there were an
2231 // ';' after the definition.
2232 PP.EnterToken(Tok, /*IsReinject=*/true);
2233 Tok.setKind(tok::semi);
2234 }
2235 }
2236}
2237
2238void Parser::ParseBaseClause(Decl *ClassDecl) {
2239 assert(Tok.is(tok::colon) && "Not a base clause");
2240 ConsumeToken();
2241
2242 // Build up an array of parsed base specifiers.
2243 SmallVector<CXXBaseSpecifier *, 8> BaseInfo;
2244
2245 while (true) {
2246 // Parse a base-specifier.
2247 BaseResult Result = ParseBaseSpecifier(ClassDecl);
2248 if (!Result.isUsable()) {
2249 // Skip the rest of this base specifier, up until the comma or
2250 // opening brace.
2251 SkipUntil(tok::comma, tok::l_brace, StopAtSemi | StopBeforeMatch);
2252 } else {
2253 // Add this to our array of base specifiers.
2254 BaseInfo.push_back(Result.get());
2255 }
2256
2257 // If the next token is a comma, consume it and keep reading
2258 // base-specifiers.
2259 if (!TryConsumeToken(tok::comma))
2260 break;
2261 }
2262
2263 // Attach the base specifiers
2264 Actions.ActOnBaseSpecifiers(ClassDecl, BaseInfo);
2265}
2266
2267BaseResult Parser::ParseBaseSpecifier(Decl *ClassDecl) {
2268 bool IsVirtual = false;
2269 SourceLocation StartLoc = Tok.getLocation();
2270
2271 ParsedAttributes Attributes(AttrFactory);
2272 MaybeParseCXX11Attributes(Attributes);
2273
2274 // Parse the 'virtual' keyword.
2275 if (TryConsumeToken(tok::kw_virtual))
2276 IsVirtual = true;
2277
2278 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2279
2280 // Parse an (optional) access specifier.
2281 AccessSpecifier Access = getAccessSpecifierIfPresent();
2282 if (Access != AS_none) {
2283 ConsumeToken();
2284 if (getLangOpts().HLSL)
2285 Diag(Tok.getLocation(), diag::ext_hlsl_access_specifiers);
2286 }
2287
2288 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2289
2290 // Parse the 'virtual' keyword (again!), in case it came after the
2291 // access specifier.
2292 if (Tok.is(tok::kw_virtual)) {
2293 SourceLocation VirtualLoc = ConsumeToken();
2294 if (IsVirtual) {
2295 // Complain about duplicate 'virtual'
2296 Diag(VirtualLoc, diag::err_dup_virtual)
2297 << FixItHint::CreateRemoval(VirtualLoc);
2298 }
2299
2300 IsVirtual = true;
2301 }
2302
2303 if (getLangOpts().HLSL && IsVirtual)
2304 Diag(Tok.getLocation(), diag::err_hlsl_virtual_inheritance);
2305
2306 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2307
2308 // Parse the class-name.
2309
2310 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
2311 // implementation for VS2013 uses _Atomic as an identifier for one of the
2312 // classes in <atomic>. Treat '_Atomic' to be an identifier when we are
2313 // parsing the class-name for a base specifier.
2314 if (getLangOpts().MSVCCompat && Tok.is(tok::kw__Atomic) &&
2315 NextToken().is(tok::less))
2316 Tok.setKind(tok::identifier);
2317
2318 SourceLocation EndLocation;
2319 SourceLocation BaseLoc;
2320 TypeResult BaseType = ParseBaseTypeSpecifier(BaseLoc, EndLocation);
2321 if (BaseType.isInvalid())
2322 return true;
2323
2324 // Parse the optional ellipsis (for a pack expansion). The ellipsis is
2325 // actually part of the base-specifier-list grammar productions, but we
2326 // parse it here for convenience.
2327 SourceLocation EllipsisLoc;
2328 TryConsumeToken(tok::ellipsis, EllipsisLoc);
2329
2330 // Find the complete source range for the base-specifier.
2331 SourceRange Range(StartLoc, EndLocation);
2332
2333 // Notify semantic analysis that we have parsed a complete
2334 // base-specifier.
2335 return Actions.ActOnBaseSpecifier(ClassDecl, Range, Attributes, IsVirtual,
2336 Access, BaseType.get(), BaseLoc,
2337 EllipsisLoc);
2338}
2339
2340AccessSpecifier Parser::getAccessSpecifierIfPresent() const {
2341 switch (Tok.getKind()) {
2342 default:
2343 return AS_none;
2344 case tok::kw_private:
2345 return AS_private;
2346 case tok::kw_protected:
2347 return AS_protected;
2348 case tok::kw_public:
2349 return AS_public;
2350 }
2351}
2352
2353void Parser::HandleMemberFunctionDeclDelays(Declarator &DeclaratorInfo,
2354 Decl *ThisDecl) {
2355 DeclaratorChunk::FunctionTypeInfo &FTI = DeclaratorInfo.getFunctionTypeInfo();
2356 // If there was a late-parsed exception-specification, we'll need a
2357 // late parse
2358 bool NeedLateParse = FTI.getExceptionSpecType() == EST_Unparsed;
2359
2360 if (!NeedLateParse) {
2361 // Look ahead to see if there are any default args
2362 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx) {
2363 const auto *Param = cast<ParmVarDecl>(FTI.Params[ParamIdx].Param);
2364 if (Param->hasUnparsedDefaultArg()) {
2365 NeedLateParse = true;
2366 break;
2367 }
2368 }
2369 }
2370
2371 if (NeedLateParse) {
2372 // Push this method onto the stack of late-parsed method
2373 // declarations.
2374 auto LateMethod = new LateParsedMethodDeclaration(this, ThisDecl);
2375 getCurrentClass().LateParsedDeclarations.push_back(LateMethod);
2376
2377 // Push tokens for each parameter. Those that do not have defaults will be
2378 // NULL. We need to track all the parameters so that we can push them into
2379 // scope for later parameters and perhaps for the exception specification.
2380 LateMethod->DefaultArgs.reserve(FTI.NumParams);
2381 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx)
2382 LateMethod->DefaultArgs.push_back(LateParsedDefaultArgument(
2383 FTI.Params[ParamIdx].Param,
2384 std::move(FTI.Params[ParamIdx].DefaultArgTokens)));
2385
2386 // Stash the exception-specification tokens in the late-pased method.
2387 if (FTI.getExceptionSpecType() == EST_Unparsed) {
2388 LateMethod->ExceptionSpecTokens = FTI.ExceptionSpecTokens;
2389 FTI.ExceptionSpecTokens = nullptr;
2390 }
2391 }
2392}
2393
2394VirtSpecifiers::Specifier Parser::isCXX11VirtSpecifier(const Token &Tok) const {
2395 if (!getLangOpts().CPlusPlus || Tok.isNot(tok::identifier))
2397
2398 const IdentifierInfo *II = Tok.getIdentifierInfo();
2399
2400 // Initialize the contextual keywords.
2401 if (!Ident_final) {
2402 Ident_final = &PP.getIdentifierTable().get("final");
2403 if (getLangOpts().GNUKeywords)
2404 Ident_GNU_final = &PP.getIdentifierTable().get("__final");
2405 if (getLangOpts().MicrosoftExt) {
2406 Ident_sealed = &PP.getIdentifierTable().get("sealed");
2407 Ident_abstract = &PP.getIdentifierTable().get("abstract");
2408 }
2409 Ident_override = &PP.getIdentifierTable().get("override");
2410 }
2411
2412 if (II == Ident_override)
2414
2415 if (II == Ident_sealed)
2417
2418 if (II == Ident_abstract)
2420
2421 if (II == Ident_final)
2423
2424 if (II == Ident_GNU_final)
2426
2428}
2429
2430void Parser::ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS,
2431 bool IsInterface,
2432 SourceLocation FriendLoc) {
2433 while (true) {
2434 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
2435 if (Specifier == VirtSpecifiers::VS_None)
2436 return;
2437
2438 if (FriendLoc.isValid()) {
2439 Diag(Tok.getLocation(), diag::err_friend_decl_spec)
2441 << FixItHint::CreateRemoval(Tok.getLocation())
2442 << SourceRange(FriendLoc, FriendLoc);
2443 ConsumeToken();
2444 continue;
2445 }
2446
2447 // C++ [class.mem]p8:
2448 // A virt-specifier-seq shall contain at most one of each virt-specifier.
2449 const char *PrevSpec = nullptr;
2450 if (VS.SetSpecifier(Specifier, Tok.getLocation(), PrevSpec))
2451 Diag(Tok.getLocation(), diag::err_duplicate_virt_specifier)
2452 << PrevSpec << FixItHint::CreateRemoval(Tok.getLocation());
2453
2454 if (IsInterface && (Specifier == VirtSpecifiers::VS_Final ||
2455 Specifier == VirtSpecifiers::VS_Sealed)) {
2456 Diag(Tok.getLocation(), diag::err_override_control_interface)
2458 } else if (Specifier == VirtSpecifiers::VS_Sealed) {
2459 Diag(Tok.getLocation(), diag::ext_ms_sealed_keyword);
2460 } else if (Specifier == VirtSpecifiers::VS_Abstract) {
2461 Diag(Tok.getLocation(), diag::ext_ms_abstract_keyword);
2462 } else if (Specifier == VirtSpecifiers::VS_GNU_Final) {
2463 Diag(Tok.getLocation(), diag::ext_warn_gnu_final);
2464 } else {
2465 Diag(Tok.getLocation(),
2467 ? diag::warn_cxx98_compat_override_control_keyword
2468 : diag::ext_override_control_keyword)
2470 }
2471 ConsumeToken();
2472 }
2473}
2474
2475bool Parser::isCXX11FinalKeyword() const {
2476 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
2480}
2481
2482bool Parser::isClassCompatibleKeyword(Token Tok) const {
2483 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier(Tok);
2488}
2489
2490bool Parser::isClassCompatibleKeyword() const {
2491 return isClassCompatibleKeyword(Tok);
2492}
2493
2494/// Parse a C++ member-declarator up to, but not including, the optional
2495/// brace-or-equal-initializer or pure-specifier.
2496bool Parser::ParseCXXMemberDeclaratorBeforeInitializer(
2497 Declarator &DeclaratorInfo, VirtSpecifiers &VS, ExprResult &BitfieldSize,
2498 LateParsedAttrList &LateParsedAttrs) {
2499 // member-declarator:
2500 // declarator virt-specifier-seq[opt] pure-specifier[opt]
2501 // declarator requires-clause
2502 // declarator brace-or-equal-initializer[opt]
2503 // identifier attribute-specifier-seq[opt] ':' constant-expression
2504 // brace-or-equal-initializer[opt]
2505 // ':' constant-expression
2506 //
2507 // NOTE: the latter two productions are a proposed bugfix rather than the
2508 // current grammar rules as of C++20.
2509 if (Tok.isNot(tok::colon))
2510 ParseDeclarator(DeclaratorInfo);
2511 else
2512 DeclaratorInfo.SetIdentifier(nullptr, Tok.getLocation());
2513
2514 if (getLangOpts().HLSL)
2515 MaybeParseHLSLAnnotations(DeclaratorInfo, nullptr,
2516 /*CouldBeBitField*/ true);
2517
2518 if (!DeclaratorInfo.isFunctionDeclarator() && TryConsumeToken(tok::colon)) {
2519 assert(DeclaratorInfo.isPastIdentifier() &&
2520 "don't know where identifier would go yet?");
2521 BitfieldSize = ParseConstantExpression();
2522 if (BitfieldSize.isInvalid())
2523 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2524 } else if (Tok.is(tok::kw_requires)) {
2525 ParseTrailingRequiresClause(DeclaratorInfo);
2526 } else {
2527 ParseOptionalCXX11VirtSpecifierSeq(
2528 VS, getCurrentClass().IsInterface,
2529 DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
2530 if (!VS.isUnset())
2531 MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo,
2532 VS);
2533 }
2534
2535 // If a simple-asm-expr is present, parse it.
2536 if (Tok.is(tok::kw_asm)) {
2537 SourceLocation Loc;
2538 ExprResult AsmLabel(ParseSimpleAsm(/*ForAsmLabel*/ true, &Loc));
2539 if (AsmLabel.isInvalid())
2540 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2541
2542 DeclaratorInfo.setAsmLabel(AsmLabel.get());
2543 DeclaratorInfo.SetRangeEnd(Loc);
2544 }
2545
2546 // If attributes exist after the declarator, but before an '{', parse them.
2547 // However, this does not apply for [[]] attributes (which could show up
2548 // before or after the __attribute__ attributes).
2549 DiagnoseAndSkipCXX11Attributes();
2550 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
2551 DiagnoseAndSkipCXX11Attributes();
2552
2553 // For compatibility with code written to older Clang, also accept a
2554 // virt-specifier *after* the GNU attributes.
2555 if (BitfieldSize.isUnset() && VS.isUnset()) {
2556 ParseOptionalCXX11VirtSpecifierSeq(
2557 VS, getCurrentClass().IsInterface,
2558 DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
2559 if (!VS.isUnset()) {
2560 // If we saw any GNU-style attributes that are known to GCC followed by a
2561 // virt-specifier, issue a GCC-compat warning.
2562 for (const ParsedAttr &AL : DeclaratorInfo.getAttributes())
2563 if (AL.isKnownToGCC() && !AL.isCXX11Attribute())
2564 Diag(AL.getLoc(), diag::warn_gcc_attribute_location);
2565
2566 MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo,
2567 VS);
2568 }
2569 }
2570
2571 // If this has neither a name nor a bit width, something has gone seriously
2572 // wrong. Skip until the semi-colon or }.
2573 if (!DeclaratorInfo.hasName() && BitfieldSize.isUnset()) {
2574 // If so, skip until the semi-colon or a }.
2575 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2576 return true;
2577 }
2578 return false;
2579}
2580
2581void Parser::MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(
2582 Declarator &D, VirtSpecifiers &VS) {
2583 DeclSpec DS(AttrFactory);
2584
2585 // GNU-style and C++11 attributes are not allowed here, but they will be
2586 // handled by the caller. Diagnose everything else.
2587 ParseTypeQualifierListOpt(
2588 DS, AR_NoAttributesParsed, /*AtomicOrPtrauthAllowed=*/false,
2589 /*IdentifierRequired=*/false, [&]() {
2590 Actions.CodeCompletion().CodeCompleteFunctionQualifiers(DS, D, &VS);
2591 });
2592 D.ExtendWithDeclSpec(DS);
2593
2594 if (D.isFunctionDeclarator()) {
2595 auto &Function = D.getFunctionTypeInfo();
2597 auto DeclSpecCheck = [&](DeclSpec::TQ TypeQual, StringRef FixItName,
2598 SourceLocation SpecLoc) {
2599 FixItHint Insertion;
2600 auto &MQ = Function.getOrCreateMethodQualifiers();
2601 if (!(MQ.getTypeQualifiers() & TypeQual)) {
2602 std::string Name(FixItName.data());
2603 Name += " ";
2604 Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), Name);
2605 MQ.SetTypeQual(TypeQual, SpecLoc);
2606 }
2607 Diag(SpecLoc, diag::err_declspec_after_virtspec)
2608 << FixItName
2610 << FixItHint::CreateRemoval(SpecLoc) << Insertion;
2611 };
2612 DS.forEachQualifier(DeclSpecCheck);
2613 }
2614
2615 // Parse ref-qualifiers.
2616 bool RefQualifierIsLValueRef = true;
2617 SourceLocation RefQualifierLoc;
2618 if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc)) {
2619 const char *Name = (RefQualifierIsLValueRef ? "& " : "&& ");
2620 FixItHint Insertion =
2622 Function.RefQualifierIsLValueRef = RefQualifierIsLValueRef;
2623 Function.RefQualifierLoc = RefQualifierLoc;
2624
2625 Diag(RefQualifierLoc, diag::err_declspec_after_virtspec)
2626 << (RefQualifierIsLValueRef ? "&" : "&&")
2628 << FixItHint::CreateRemoval(RefQualifierLoc) << Insertion;
2629 D.SetRangeEnd(RefQualifierLoc);
2630 }
2631 }
2632}
2633
2634Parser::DeclGroupPtrTy Parser::ParseCXXClassMemberDeclaration(
2635 AccessSpecifier AS, ParsedAttributes &AccessAttrs,
2636 ParsedTemplateInfo &TemplateInfo, ParsingDeclRAIIObject *TemplateDiags) {
2637 assert(getLangOpts().CPlusPlus &&
2638 "ParseCXXClassMemberDeclaration should only be called in C++ mode");
2639 if (Tok.is(tok::at)) {
2640 if (getLangOpts().ObjC && NextToken().isObjCAtKeyword(tok::objc_defs))
2641 Diag(Tok, diag::err_at_defs_cxx);
2642 else
2643 Diag(Tok, diag::err_at_in_class);
2644
2645 ConsumeToken();
2646 SkipUntil(tok::r_brace, StopAtSemi);
2647 return nullptr;
2648 }
2649
2650 // Turn on colon protection early, while parsing declspec, although there is
2651 // nothing to protect there. It prevents from false errors if error recovery
2652 // incorrectly determines where the declspec ends, as in the example:
2653 // struct A { enum class B { C }; };
2654 // const int C = 4;
2655 // struct D { A::B : C; };
2657
2658 // Access declarations.
2659 bool MalformedTypeSpec = false;
2660 if (TemplateInfo.Kind == ParsedTemplateKind::NonTemplate &&
2661 Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw___super)) {
2663 MalformedTypeSpec = true;
2664
2665 bool isAccessDecl;
2666 if (Tok.isNot(tok::annot_cxxscope))
2667 isAccessDecl = false;
2668 else if (NextToken().is(tok::identifier))
2669 isAccessDecl = GetLookAheadToken(2).is(tok::semi);
2670 else
2671 isAccessDecl = NextToken().is(tok::kw_operator);
2672
2673 if (isAccessDecl) {
2674 // Collect the scope specifier token we annotated earlier.
2675 CXXScopeSpec SS;
2676 ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
2677 /*ObjectHasErrors=*/false,
2678 /*EnteringContext=*/false);
2679
2680 if (SS.isInvalid()) {
2681 SkipUntil(tok::semi);
2682 return nullptr;
2683 }
2684
2685 // Try to parse an unqualified-id.
2686 SourceLocation TemplateKWLoc;
2687 UnqualifiedId Name;
2688 if (ParseUnqualifiedId(SS, /*ObjectType=*/nullptr,
2689 /*ObjectHadErrors=*/false, false, true, true,
2690 false, &TemplateKWLoc, Name)) {
2691 SkipUntil(tok::semi);
2692 return nullptr;
2693 }
2694
2695 // TODO: recover from mistakenly-qualified operator declarations.
2696 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
2697 "access declaration")) {
2698 SkipUntil(tok::semi);
2699 return nullptr;
2700 }
2701
2702 // FIXME: We should do something with the 'template' keyword here.
2703 return DeclGroupPtrTy::make(DeclGroupRef(Actions.ActOnUsingDeclaration(
2704 getCurScope(), AS, /*UsingLoc*/ SourceLocation(),
2705 /*TypenameLoc*/ SourceLocation(), SS, Name,
2706 /*EllipsisLoc*/ SourceLocation(),
2707 /*AttrList*/ ParsedAttributesView())));
2708 }
2709 }
2710
2711 // static_assert-declaration. A templated static_assert declaration is
2712 // diagnosed in Parser::ParseDeclarationAfterTemplate.
2713 if (TemplateInfo.Kind == ParsedTemplateKind::NonTemplate &&
2714 Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert)) {
2715 SourceLocation DeclEnd;
2716 return DeclGroupPtrTy::make(
2717 DeclGroupRef(ParseStaticAssertDeclaration(DeclEnd)));
2718 }
2719
2720 if (Tok.is(tok::kw_template)) {
2721 assert(!TemplateInfo.TemplateParams &&
2722 "Nested template improperly parsed?");
2723 ObjCDeclContextSwitch ObjCDC(*this);
2724 SourceLocation DeclEnd;
2725 return ParseTemplateDeclarationOrSpecialization(DeclaratorContext::Member,
2726 DeclEnd, AccessAttrs, AS);
2727 }
2728
2729 // Handle: member-declaration ::= '__extension__' member-declaration
2730 if (Tok.is(tok::kw___extension__)) {
2731 // __extension__ silences extension warnings in the subexpression.
2732 ExtensionRAIIObject O(Diags); // Use RAII to do this.
2733 ConsumeToken();
2734 return ParseCXXClassMemberDeclaration(AS, AccessAttrs, TemplateInfo,
2735 TemplateDiags);
2736 }
2737
2738 ParsedAttributes DeclAttrs(AttrFactory);
2739 // Optional C++11 attribute-specifier
2740 MaybeParseCXX11Attributes(DeclAttrs);
2741
2742 // The next token may be an OpenMP pragma annotation token. That would
2743 // normally be handled from ParseCXXClassMemberDeclarationWithPragmas, but in
2744 // this case, it came from an *attribute* rather than a pragma. Handle it now.
2745 if (Tok.is(tok::annot_attr_openmp))
2746 return ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, DeclAttrs);
2747
2748 if (Tok.is(tok::kw_using)) {
2749 // Eat 'using'.
2750 SourceLocation UsingLoc = ConsumeToken();
2751
2752 // Consume unexpected 'template' keywords.
2753 while (Tok.is(tok::kw_template)) {
2754 SourceLocation TemplateLoc = ConsumeToken();
2755 Diag(TemplateLoc, diag::err_unexpected_template_after_using)
2756 << FixItHint::CreateRemoval(TemplateLoc);
2757 }
2758
2759 if (Tok.is(tok::kw_namespace)) {
2760 Diag(UsingLoc, diag::err_using_namespace_in_class);
2761 SkipUntil(tok::semi, StopBeforeMatch);
2762 return nullptr;
2763 }
2764 SourceLocation DeclEnd;
2765 // Otherwise, it must be a using-declaration or an alias-declaration.
2766 return ParseUsingDeclaration(DeclaratorContext::Member, TemplateInfo,
2767 UsingLoc, DeclEnd, DeclAttrs, AS);
2768 }
2769
2770 ParsedAttributes DeclSpecAttrs(AttrFactory);
2771 // Hold late-parsed attributes so we can attach a Decl to them later.
2772 LateParsedAttrList CommonLateParsedAttrs;
2773
2774 while (MaybeParseCXX11Attributes(DeclAttrs) ||
2775 MaybeParseGNUAttributes(DeclSpecAttrs, &CommonLateParsedAttrs) ||
2776 MaybeParseMicrosoftAttributes(DeclSpecAttrs))
2777 ;
2778
2779 SourceLocation DeclStart;
2780 if (DeclAttrs.Range.isValid()) {
2781 DeclStart = DeclSpecAttrs.Range.isInvalid()
2782 ? DeclAttrs.Range.getBegin()
2783 : std::min(DeclAttrs.Range.getBegin(),
2784 DeclSpecAttrs.Range.getBegin());
2785 } else {
2786 DeclStart = DeclSpecAttrs.Range.getBegin();
2787 }
2788
2789 // decl-specifier-seq:
2790 // Parse the common declaration-specifiers piece.
2791 ParsingDeclSpec DS(*this, TemplateDiags);
2792 DS.takeAttributesAppendingingFrom(DeclSpecAttrs);
2793
2794 if (MalformedTypeSpec)
2795 DS.SetTypeSpecError();
2796
2797 // Turn off usual access checking for templates explicit specialization
2798 // and instantiation.
2799 // C++20 [temp.spec] 13.9/6.
2800 // This disables the access checking rules for member function template
2801 // explicit instantiation and explicit specialization.
2802 bool IsTemplateSpecOrInst =
2803 (TemplateInfo.Kind == ParsedTemplateKind::ExplicitInstantiation ||
2804 TemplateInfo.Kind == ParsedTemplateKind::ExplicitSpecialization);
2805 SuppressAccessChecks diagsFromTag(*this, IsTemplateSpecOrInst);
2806
2807 ParseDeclarationSpecifiers(DS, TemplateInfo, AS, DeclSpecContext::DSC_class,
2808 &CommonLateParsedAttrs);
2809
2810 if (IsTemplateSpecOrInst)
2811 diagsFromTag.done();
2812
2813 // Turn off colon protection that was set for declspec.
2814 X.restore();
2815
2816 if (DeclStart.isValid())
2817 DS.SetRangeStart(DeclStart);
2818
2819 // If we had a free-standing type definition with a missing semicolon, we
2820 // may get this far before the problem becomes obvious.
2821 if (DS.hasTagDefinition() &&
2822 TemplateInfo.Kind == ParsedTemplateKind::NonTemplate &&
2823 DiagnoseMissingSemiAfterTagDefinition(DS, AS, DeclSpecContext::DSC_class,
2824 &CommonLateParsedAttrs))
2825 return nullptr;
2826
2827 MultiTemplateParamsArg TemplateParams(
2828 TemplateInfo.TemplateParams ? TemplateInfo.TemplateParams->data()
2829 : nullptr,
2830 TemplateInfo.TemplateParams ? TemplateInfo.TemplateParams->size() : 0);
2831
2832 if (TryConsumeToken(tok::semi)) {
2833 if (DS.isFriendSpecified())
2834 ProhibitAttributes(DeclAttrs);
2835
2836 RecordDecl *AnonRecord = nullptr;
2837 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(
2838 getCurScope(), AS, DS, DeclAttrs, TemplateParams, false, AnonRecord);
2839 Actions.ActOnDefinedDeclarationSpecifier(TheDecl);
2840 DS.complete(TheDecl);
2841 if (AnonRecord) {
2842 Decl *decls[] = {AnonRecord, TheDecl};
2843 return Actions.BuildDeclaratorGroup(decls);
2844 }
2845 return Actions.ConvertDeclToDeclGroup(TheDecl);
2846 }
2847
2848 if (DS.hasTagDefinition())
2849 Actions.ActOnDefinedDeclarationSpecifier(DS.getRepAsDecl());
2850
2851 // Handle C++26's variadic friend declarations. These don't even have
2852 // declarators, so we get them out of the way early here.
2853 if (DS.isFriendSpecifiedFirst() && Tok.isOneOf(tok::comma, tok::ellipsis)) {
2854 Diag(Tok.getLocation(), getLangOpts().CPlusPlus26
2855 ? diag::warn_cxx23_variadic_friends
2856 : diag::ext_variadic_friends);
2857
2858 SourceLocation FriendLoc = DS.getFriendSpecLoc();
2859 SmallVector<Decl *> Decls;
2860
2861 // Handles a single friend-type-specifier.
2862 auto ParsedFriendDecl = [&](ParsingDeclSpec &DeclSpec) {
2863 SourceLocation VariadicLoc;
2864 TryConsumeToken(tok::ellipsis, VariadicLoc);
2865
2866 RecordDecl *AnonRecord = nullptr;
2867 Decl *D = Actions.ParsedFreeStandingDeclSpec(
2868 getCurScope(), AS, DeclSpec, DeclAttrs, TemplateParams, false,
2869 AnonRecord, VariadicLoc);
2870 DeclSpec.complete(D);
2871 if (!D) {
2872 SkipUntil(tok::semi, tok::r_brace);
2873 return true;
2874 }
2875
2876 Decls.push_back(D);
2877 return false;
2878 };
2879
2880 if (ParsedFriendDecl(DS))
2881 return nullptr;
2882
2883 while (TryConsumeToken(tok::comma)) {
2884 ParsingDeclSpec DeclSpec(*this, TemplateDiags);
2885 const char *PrevSpec = nullptr;
2886 unsigned DiagId = 0;
2887 DeclSpec.SetFriendSpec(FriendLoc, PrevSpec, DiagId);
2888 ParseDeclarationSpecifiers(DeclSpec, TemplateInfo, AS,
2889 DeclSpecContext::DSC_class, nullptr);
2890 if (ParsedFriendDecl(DeclSpec))
2891 return nullptr;
2892 }
2893
2894 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_stmt,
2895 "friend declaration");
2896
2897 return Actions.BuildDeclaratorGroup(Decls);
2898 }
2899
2900 // Befriending a concept is invalid and would already fail if
2901 // we did nothing here, but this allows us to issue a more
2902 // helpful diagnostic.
2903 if (Tok.is(tok::kw_concept)) {
2904 Diag(
2905 Tok.getLocation(),
2906 DS.isFriendSpecified() || NextToken().is(tok::kw_friend)
2907 ? llvm::to_underlying(diag::err_friend_concept)
2908 : llvm::to_underlying(
2909 diag::
2910 err_concept_decls_may_only_appear_in_global_namespace_scope));
2911 SkipUntil(tok::semi, tok::r_brace, StopBeforeMatch);
2912 return nullptr;
2913 }
2914
2915 ParsingDeclarator DeclaratorInfo(*this, DS, DeclAttrs,
2917 if (TemplateInfo.TemplateParams)
2918 DeclaratorInfo.setTemplateParameterLists(TemplateParams);
2919 VirtSpecifiers VS;
2920
2921 // Hold late-parsed attributes so we can attach a Decl to them later.
2922 LateParsedAttrList LateParsedAttrs;
2923
2924 SourceLocation EqualLoc;
2925 SourceLocation PureSpecLoc;
2926
2927 auto TryConsumePureSpecifier = [&](bool AllowDefinition) {
2928 if (Tok.isNot(tok::equal))
2929 return false;
2930
2931 auto &Zero = NextToken();
2932 SmallString<8> Buffer;
2933 if (Zero.isNot(tok::numeric_constant) ||
2934 PP.getSpelling(Zero, Buffer) != "0")
2935 return false;
2936
2937 auto &After = GetLookAheadToken(2);
2938 if (!After.isOneOf(tok::semi, tok::comma) &&
2939 !(AllowDefinition &&
2940 After.isOneOf(tok::l_brace, tok::colon, tok::kw_try)))
2941 return false;
2942
2943 EqualLoc = ConsumeToken();
2944 PureSpecLoc = ConsumeToken();
2945 return true;
2946 };
2947
2948 SmallVector<Decl *, 8> DeclsInGroup;
2949 ExprResult BitfieldSize;
2950 ExprResult TrailingRequiresClause;
2951 bool ExpectSemi = true;
2952
2953 // C++20 [temp.spec] 13.9/6.
2954 // This disables the access checking rules for member function template
2955 // explicit instantiation and explicit specialization.
2956 SuppressAccessChecks SAC(*this, IsTemplateSpecOrInst);
2957
2958 // Parse the first declarator.
2959 if (ParseCXXMemberDeclaratorBeforeInitializer(
2960 DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs)) {
2961 TryConsumeToken(tok::semi);
2962 return nullptr;
2963 }
2964
2965 if (IsTemplateSpecOrInst)
2966 SAC.done();
2967
2968 // Check for a member function definition.
2969 if (BitfieldSize.isUnset()) {
2970 // MSVC permits pure specifier on inline functions defined at class scope.
2971 // Hence check for =0 before checking for function definition.
2972 if (getLangOpts().MicrosoftExt && DeclaratorInfo.isDeclarationOfFunction())
2973 TryConsumePureSpecifier(/*AllowDefinition*/ true);
2974
2976 // function-definition:
2977 //
2978 // In C++11, a non-function declarator followed by an open brace is a
2979 // braced-init-list for an in-class member initialization, not an
2980 // erroneous function definition.
2981 if (Tok.is(tok::l_brace) && !getLangOpts().CPlusPlus11) {
2982 DefinitionKind = FunctionDefinitionKind::Definition;
2983 } else if (DeclaratorInfo.isFunctionDeclarator()) {
2984 if (Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try)) {
2985 DefinitionKind = FunctionDefinitionKind::Definition;
2986 } else if (Tok.is(tok::equal)) {
2987 const Token &KW = NextToken();
2988 if (KW.is(tok::kw_default))
2989 DefinitionKind = FunctionDefinitionKind::Defaulted;
2990 else if (KW.is(tok::kw_delete))
2991 DefinitionKind = FunctionDefinitionKind::Deleted;
2992 else if (KW.is(tok::code_completion)) {
2993 cutOffParsing();
2994 Actions.CodeCompletion().CodeCompleteAfterFunctionEquals(
2995 DeclaratorInfo);
2996 return nullptr;
2997 }
2998 }
2999 }
3000 DeclaratorInfo.setFunctionDefinitionKind(DefinitionKind);
3001
3002 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
3003 // to a friend declaration, that declaration shall be a definition.
3004 if (DeclaratorInfo.isFunctionDeclarator() &&
3005 DefinitionKind == FunctionDefinitionKind::Declaration &&
3006 DS.isFriendSpecified()) {
3007 // Diagnose attributes that appear before decl specifier:
3008 // [[]] friend int foo();
3009 ProhibitAttributes(DeclAttrs);
3010 }
3011
3012 if (DefinitionKind != FunctionDefinitionKind::Declaration) {
3013 if (!DeclaratorInfo.isFunctionDeclarator()) {
3014 Diag(DeclaratorInfo.getIdentifierLoc(), diag::err_func_def_no_params);
3015 ConsumeBrace();
3016 SkipUntil(tok::r_brace);
3017
3018 // Consume the optional ';'
3019 TryConsumeToken(tok::semi);
3020
3021 return nullptr;
3022 }
3023
3025 Diag(DeclaratorInfo.getIdentifierLoc(),
3026 diag::err_function_declared_typedef);
3027
3028 // Recover by treating the 'typedef' as spurious.
3030 }
3031
3032 Decl *FunDecl = ParseCXXInlineMethodDef(AS, AccessAttrs, DeclaratorInfo,
3033 TemplateInfo, VS, PureSpecLoc);
3034
3035 if (FunDecl) {
3036 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i) {
3037 CommonLateParsedAttrs[i]->addDecl(FunDecl);
3038 }
3039 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i) {
3040 LateParsedAttrs[i]->addDecl(FunDecl);
3041 }
3042 }
3043 LateParsedAttrs.clear();
3044
3045 // Consume the ';' - it's optional unless we have a delete or default
3046 if (Tok.is(tok::semi))
3048
3049 return DeclGroupPtrTy::make(DeclGroupRef(FunDecl));
3050 }
3051 }
3052
3053 // member-declarator-list:
3054 // member-declarator
3055 // member-declarator-list ',' member-declarator
3056
3057 while (true) {
3058 InClassInitStyle HasInClassInit = ICIS_NoInit;
3059 bool HasStaticInitializer = false;
3060 if (Tok.isOneOf(tok::equal, tok::l_brace) && PureSpecLoc.isInvalid()) {
3061 // DRXXXX: Anonymous bit-fields cannot have a brace-or-equal-initializer.
3062 if (BitfieldSize.isUsable() && !DeclaratorInfo.hasName()) {
3063 // Diagnose the error and pretend there is no in-class initializer.
3064 Diag(Tok, diag::err_anon_bitfield_member_init);
3065 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
3066 } else if (DeclaratorInfo.isDeclarationOfFunction()) {
3067 // It's a pure-specifier.
3068 if (!TryConsumePureSpecifier(/*AllowFunctionDefinition*/ false))
3069 // Parse it as an expression so that Sema can diagnose it.
3070 HasStaticInitializer = true;
3071 } else if (DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
3073 DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
3075 !DS.isFriendSpecified() &&
3076 TemplateInfo.Kind == ParsedTemplateKind::NonTemplate) {
3077 // It's a default member initializer.
3078 if (BitfieldSize.get())
3080 ? diag::warn_cxx17_compat_bitfield_member_init
3081 : diag::ext_bitfield_member_init);
3082 HasInClassInit = Tok.is(tok::equal) ? ICIS_CopyInit : ICIS_ListInit;
3083 } else {
3084 HasStaticInitializer = true;
3085 }
3086 }
3087
3088 // NOTE: If Sema is the Action module and declarator is an instance field,
3089 // this call will *not* return the created decl; It will return null.
3090 // See Sema::ActOnCXXMemberDeclarator for details.
3091
3092 NamedDecl *ThisDecl = nullptr;
3093 if (DS.isFriendSpecified()) {
3094 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
3095 // to a friend declaration, that declaration shall be a definition.
3096 //
3097 // Diagnose attributes that appear in a friend member function declarator:
3098 // friend int foo [[]] ();
3099 for (const ParsedAttr &AL : DeclaratorInfo.getAttributes())
3100 if (AL.isCXX11Attribute() || AL.isRegularKeywordAttribute()) {
3101 auto Loc = AL.getRange().getBegin();
3102 (AL.isRegularKeywordAttribute()
3103 ? Diag(Loc, diag::err_keyword_not_allowed) << AL
3104 : Diag(Loc, diag::err_attributes_not_allowed))
3105 << AL.getRange();
3106 }
3107
3108 ThisDecl = Actions.ActOnFriendFunctionDecl(getCurScope(), DeclaratorInfo,
3109 TemplateParams);
3110 } else {
3111 ThisDecl = Actions.ActOnCXXMemberDeclarator(
3112 getCurScope(), AS, DeclaratorInfo, TemplateParams, BitfieldSize.get(),
3113 VS, HasInClassInit);
3114
3115 if (VarTemplateDecl *VT =
3116 ThisDecl ? dyn_cast<VarTemplateDecl>(ThisDecl) : nullptr)
3117 // Re-direct this decl to refer to the templated decl so that we can
3118 // initialize it.
3119 ThisDecl = VT->getTemplatedDecl();
3120
3121 if (ThisDecl)
3122 Actions.ProcessDeclAttributeList(getCurScope(), ThisDecl, AccessAttrs);
3123 }
3124
3125 // Error recovery might have converted a non-static member into a static
3126 // member.
3127 if (HasInClassInit != ICIS_NoInit &&
3128 DeclaratorInfo.getDeclSpec().getStorageClassSpec() ==
3130 HasInClassInit = ICIS_NoInit;
3131 HasStaticInitializer = true;
3132 }
3133
3134 if (PureSpecLoc.isValid() && VS.getAbstractLoc().isValid()) {
3135 Diag(PureSpecLoc, diag::err_duplicate_virt_specifier) << "abstract";
3136 }
3137 if (ThisDecl && PureSpecLoc.isValid())
3138 Actions.ActOnPureSpecifier(ThisDecl, PureSpecLoc);
3139 else if (ThisDecl && VS.getAbstractLoc().isValid())
3140 Actions.ActOnPureSpecifier(ThisDecl, VS.getAbstractLoc());
3141
3142 // Handle the initializer.
3143 if (HasInClassInit != ICIS_NoInit) {
3144 // The initializer was deferred; parse it and cache the tokens.
3146 ? diag::warn_cxx98_compat_nonstatic_member_init
3147 : diag::ext_nonstatic_member_init);
3148
3149 if (DeclaratorInfo.isArrayOfUnknownBound()) {
3150 // C++11 [dcl.array]p3: An array bound may also be omitted when the
3151 // declarator is followed by an initializer.
3152 //
3153 // A brace-or-equal-initializer for a member-declarator is not an
3154 // initializer in the grammar, so this is ill-formed.
3155 Diag(Tok, diag::err_incomplete_array_member_init);
3156 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
3157
3158 // Avoid later warnings about a class member of incomplete type.
3159 if (ThisDecl)
3160 ThisDecl->setInvalidDecl();
3161 } else
3162 ParseCXXNonStaticMemberInitializer(ThisDecl);
3163 } else if (HasStaticInitializer) {
3164 // Normal initializer.
3165 ExprResult Init = ParseCXXMemberInitializer(
3166 ThisDecl, DeclaratorInfo.isDeclarationOfFunction(), EqualLoc);
3167
3168 if (Init.isInvalid()) {
3169 if (ThisDecl)
3170 Actions.ActOnUninitializedDecl(ThisDecl);
3171 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
3172 } else if (ThisDecl)
3173 Actions.AddInitializerToDecl(ThisDecl, Init.get(),
3174 EqualLoc.isInvalid());
3175 } else if (ThisDecl && DeclaratorInfo.isStaticMember())
3176 // No initializer.
3177 Actions.ActOnUninitializedDecl(ThisDecl);
3178
3179 if (ThisDecl) {
3180 if (!ThisDecl->isInvalidDecl()) {
3181 // Set the Decl for any late parsed attributes
3182 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i)
3183 CommonLateParsedAttrs[i]->addDecl(ThisDecl);
3184
3185 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i)
3186 LateParsedAttrs[i]->addDecl(ThisDecl);
3187 }
3188 Actions.FinalizeDeclaration(ThisDecl);
3189 DeclsInGroup.push_back(ThisDecl);
3190
3191 if (DeclaratorInfo.isFunctionDeclarator() &&
3192 DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
3194 HandleMemberFunctionDeclDelays(DeclaratorInfo, ThisDecl);
3195 }
3196 LateParsedAttrs.clear();
3197
3198 DeclaratorInfo.complete(ThisDecl);
3199
3200 // If we don't have a comma, it is either the end of the list (a ';')
3201 // or an error, bail out.
3202 SourceLocation CommaLoc;
3203 if (!TryConsumeToken(tok::comma, CommaLoc))
3204 break;
3205
3206 if (Tok.isAtStartOfLine() &&
3207 !MightBeDeclarator(DeclaratorContext::Member)) {
3208 // This comma was followed by a line-break and something which can't be
3209 // the start of a declarator. The comma was probably a typo for a
3210 // semicolon.
3211 Diag(CommaLoc, diag::err_expected_semi_declaration)
3212 << FixItHint::CreateReplacement(CommaLoc, ";");
3213 ExpectSemi = false;
3214 break;
3215 }
3216
3217 // C++23 [temp.pre]p5:
3218 // In a template-declaration, explicit specialization, or explicit
3219 // instantiation the init-declarator-list in the declaration shall
3220 // contain at most one declarator.
3221 if (TemplateInfo.Kind != ParsedTemplateKind::NonTemplate &&
3222 DeclaratorInfo.isFirstDeclarator()) {
3223 Diag(CommaLoc, diag::err_multiple_template_declarators)
3224 << TemplateInfo.Kind;
3225 }
3226
3227 // Parse the next declarator.
3228 DeclaratorInfo.clear();
3229 VS.clear();
3230 BitfieldSize = ExprResult(/*Invalid=*/false);
3231 EqualLoc = PureSpecLoc = SourceLocation();
3232 DeclaratorInfo.setCommaLoc(CommaLoc);
3233
3234 // GNU attributes are allowed before the second and subsequent declarator.
3235 // However, this does not apply for [[]] attributes (which could show up
3236 // before or after the __attribute__ attributes).
3237 DiagnoseAndSkipCXX11Attributes();
3238 MaybeParseGNUAttributes(DeclaratorInfo);
3239 DiagnoseAndSkipCXX11Attributes();
3240
3241 if (ParseCXXMemberDeclaratorBeforeInitializer(
3242 DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs))
3243 break;
3244 }
3245
3246 if (ExpectSemi &&
3247 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list) &&
3248 !isLikelyAtStartOfNewDeclaration()) {
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 auto D = Diag(LParenLoc, diag::err_cxx11_attribute_forbids_arguments)
4536 << AttrName;
4537 if (EndLoc)
4538 D << FixItHint::CreateRemoval(SourceRange(LParenLoc, *EndLoc));
4539 Attr.setInvalid(true);
4540 }
4541 }
4542 return true;
4543}
4544
4545void Parser::ParseCXX11AttributeSpecifierInternal(ParsedAttributes &Attrs,
4546 CachedTokens &OpenMPTokens,
4547 SourceLocation *EndLoc) {
4548 if (Tok.is(tok::kw_alignas)) {
4549 // alignas is a valid token in C23 but it is not an attribute, it's a type-
4550 // specifier-qualifier, which means it has different parsing behavior. We
4551 // handle this in ParseDeclarationSpecifiers() instead of here in C. We
4552 // should not get here for C any longer.
4553 assert(getLangOpts().CPlusPlus && "'alignas' is not an attribute in C");
4554 Diag(Tok.getLocation(), diag::warn_cxx98_compat_alignas);
4555 ParseAlignmentSpecifier(Attrs, EndLoc);
4556 return;
4557 }
4558
4559 if (Tok.isRegularKeywordAttribute()) {
4560 SourceLocation Loc = Tok.getLocation();
4561 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
4562 ParsedAttr::Form Form = ParsedAttr::Form(Tok.getKind());
4563 bool TakesArgs = doesKeywordAttributeTakeArgs(Tok.getKind());
4564 ConsumeToken();
4565 if (TakesArgs) {
4566 if (!Tok.is(tok::l_paren))
4567 Diag(Tok.getLocation(), diag::err_expected_lparen_after) << AttrName;
4568 else
4569 ParseAttributeArgsCommon(AttrName, Loc, Attrs, EndLoc,
4570 /*ScopeName*/ nullptr,
4571 /*ScopeLoc*/ Loc, Form);
4572 } else
4573 Attrs.addNew(AttrName, Loc, AttributeScopeInfo(), nullptr, 0, Form);
4574 return;
4575 }
4576
4577 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square) &&
4578 "Not a double square bracket attribute list");
4579
4580 SourceLocation OpenLoc = Tok.getLocation();
4581 if (getLangOpts().CPlusPlus) {
4582 Diag(OpenLoc, getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_attribute
4583 : diag::warn_ext_cxx11_attributes);
4584 } else {
4585 Diag(OpenLoc, getLangOpts().C23 ? diag::warn_pre_c23_compat_attributes
4586 : diag::warn_ext_c23_attributes);
4587 }
4588
4589 ConsumeBracket();
4590 checkCompoundToken(OpenLoc, tok::l_square, CompoundToken::AttrBegin);
4591 ConsumeBracket();
4592
4593 SourceLocation CommonScopeLoc;
4594 IdentifierInfo *CommonScopeName = nullptr;
4595 if (Tok.is(tok::kw_using)) {
4596 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
4597 ? diag::warn_cxx14_compat_using_attribute_ns
4598 : diag::ext_using_attribute_ns);
4599 ConsumeToken();
4600
4601 CommonScopeName = TryParseCXX11AttributeIdentifier(
4603 if (!CommonScopeName) {
4604 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
4605 SkipUntil(tok::r_square, tok::colon, StopBeforeMatch);
4606 }
4607 if (!TryConsumeToken(tok::colon) && CommonScopeName)
4608 Diag(Tok.getLocation(), diag::err_expected) << tok::colon;
4609 }
4610
4611 bool AttrParsed = false;
4612 while (!Tok.isOneOf(tok::r_square, tok::semi, tok::eof)) {
4613 if (AttrParsed) {
4614 // If we parsed an attribute, a comma is required before parsing any
4615 // additional attributes.
4616 if (ExpectAndConsume(tok::comma)) {
4617 SkipUntil(tok::r_square, StopAtSemi | StopBeforeMatch);
4618 continue;
4619 }
4620 AttrParsed = false;
4621 }
4622
4623 // Eat all remaining superfluous commas before parsing the next attribute.
4624 while (TryConsumeToken(tok::comma))
4625 ;
4626
4627 SourceLocation ScopeLoc, AttrLoc;
4628 IdentifierInfo *ScopeName = nullptr, *AttrName = nullptr;
4629
4630 AttrName = TryParseCXX11AttributeIdentifier(
4632 CommonScopeName);
4633 if (!AttrName)
4634 // Break out to the "expected ']'" diagnostic.
4635 break;
4636
4637 // scoped attribute
4638 if (TryConsumeToken(tok::coloncolon)) {
4639 ScopeName = AttrName;
4640 ScopeLoc = AttrLoc;
4641
4642 AttrName = TryParseCXX11AttributeIdentifier(
4644 ScopeName);
4645 if (!AttrName) {
4646 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
4647 SkipUntil(tok::r_square, tok::comma, StopAtSemi | StopBeforeMatch);
4648 continue;
4649 }
4650 }
4651
4652 if (CommonScopeName) {
4653 if (ScopeName) {
4654 Diag(ScopeLoc, diag::err_using_attribute_ns_conflict)
4655 << SourceRange(CommonScopeLoc);
4656 } else {
4657 ScopeName = CommonScopeName;
4658 ScopeLoc = CommonScopeLoc;
4659 }
4660 }
4661
4662 // Parse attribute arguments
4663 if (Tok.is(tok::l_paren))
4664 AttrParsed = ParseCXX11AttributeArgs(AttrName, AttrLoc, Attrs, EndLoc,
4665 ScopeName, ScopeLoc, OpenMPTokens);
4666
4667 if (!AttrParsed) {
4668 Attrs.addNew(AttrName,
4669 SourceRange(ScopeLoc.isValid() && CommonScopeLoc.isInvalid()
4670 ? ScopeLoc
4671 : AttrLoc,
4672 AttrLoc),
4673 AttributeScopeInfo(ScopeName, ScopeLoc, CommonScopeLoc),
4674 nullptr, 0,
4675 getLangOpts().CPlusPlus ? ParsedAttr::Form::CXX11()
4676 : ParsedAttr::Form::C23());
4677 AttrParsed = true;
4678 }
4679
4680 if (TryConsumeToken(tok::ellipsis))
4681 Diag(Tok, diag::err_cxx11_attribute_forbids_ellipsis) << AttrName;
4682 }
4683
4684 // If we hit an error and recovered by parsing up to a semicolon, eat the
4685 // semicolon and don't issue further diagnostics about missing brackets.
4686 if (Tok.is(tok::semi)) {
4687 ConsumeToken();
4688 return;
4689 }
4690
4691 SourceLocation CloseLoc = Tok.getLocation();
4692 if (ExpectAndConsume(tok::r_square))
4693 SkipUntil(tok::r_square);
4694 else if (Tok.is(tok::r_square))
4695 checkCompoundToken(CloseLoc, tok::r_square, CompoundToken::AttrEnd);
4696 if (EndLoc)
4697 *EndLoc = Tok.getLocation();
4698 if (ExpectAndConsume(tok::r_square))
4699 SkipUntil(tok::r_square);
4700}
4701
4702void Parser::ParseCXX11Attributes(ParsedAttributes &Attrs) {
4703 SourceLocation StartLoc = Tok.getLocation();
4704 SourceLocation EndLoc = StartLoc;
4705
4706 do {
4707 ParseCXX11AttributeSpecifier(Attrs, &EndLoc);
4708 } while (isAllowedCXX11AttributeSpecifier());
4709
4710 Attrs.Range = SourceRange(StartLoc, EndLoc);
4711}
4712
4713void Parser::DiagnoseAndSkipCXX11Attributes() {
4714 auto Keyword =
4715 Tok.isRegularKeywordAttribute() ? Tok.getIdentifierInfo() : nullptr;
4716 // Start and end location of an attribute or an attribute list.
4717 SourceLocation StartLoc = Tok.getLocation();
4718 SourceLocation EndLoc = SkipCXX11Attributes();
4719
4720 if (EndLoc.isValid()) {
4721 SourceRange Range(StartLoc, EndLoc);
4722 (Keyword ? Diag(StartLoc, diag::err_keyword_not_allowed) << Keyword
4723 : Diag(StartLoc, diag::err_attributes_not_allowed))
4724 << Range;
4725 }
4726}
4727
4728SourceLocation Parser::SkipCXX11Attributes() {
4729 SourceLocation EndLoc;
4730
4731 if (isCXX11AttributeSpecifier() == CXX11AttributeKind::NotAttributeSpecifier)
4732 return EndLoc;
4733
4734 do {
4735 if (Tok.is(tok::l_square)) {
4736 BalancedDelimiterTracker T(*this, tok::l_square);
4737 T.consumeOpen();
4738 T.skipToEnd();
4739 EndLoc = T.getCloseLocation();
4740 } else if (Tok.isRegularKeywordAttribute() &&
4741 !doesKeywordAttributeTakeArgs(Tok.getKind())) {
4742 EndLoc = Tok.getLocation();
4743 ConsumeToken();
4744 } else {
4745 assert((Tok.is(tok::kw_alignas) || Tok.isRegularKeywordAttribute()) &&
4746 "not an attribute specifier");
4747 ConsumeToken();
4748 BalancedDelimiterTracker T(*this, tok::l_paren);
4749 if (!T.consumeOpen())
4750 T.skipToEnd();
4751 EndLoc = T.getCloseLocation();
4752 }
4753 } while (isCXX11AttributeSpecifier() !=
4755
4756 return EndLoc;
4757}
4758
4759void Parser::ParseMicrosoftUuidAttributeArgs(ParsedAttributes &Attrs) {
4760 assert(Tok.is(tok::identifier) && "Not a Microsoft attribute list");
4761 IdentifierInfo *UuidIdent = Tok.getIdentifierInfo();
4762 assert(UuidIdent->getName() == "uuid" && "Not a Microsoft attribute list");
4763
4764 SourceLocation UuidLoc = Tok.getLocation();
4765 ConsumeToken();
4766
4767 // Ignore the left paren location for now.
4768 BalancedDelimiterTracker T(*this, tok::l_paren);
4769 if (T.consumeOpen()) {
4770 Diag(Tok, diag::err_expected) << tok::l_paren;
4771 return;
4772 }
4773
4774 ArgsVector ArgExprs;
4775 if (isTokenStringLiteral()) {
4776 // Easy case: uuid("...") -- quoted string.
4778 if (StringResult.isInvalid())
4779 return;
4780 ArgExprs.push_back(StringResult.get());
4781 } else {
4782 // something like uuid({000000A0-0000-0000-C000-000000000049}) -- no
4783 // quotes in the parens. Just append the spelling of all tokens encountered
4784 // until the closing paren.
4785
4786 SmallString<42> StrBuffer; // 2 "", 36 bytes UUID, 2 optional {}, 1 nul
4787 StrBuffer += "\"";
4788
4789 // Since none of C++'s keywords match [a-f]+, accepting just tok::l_brace,
4790 // tok::r_brace, tok::minus, tok::identifier (think C000) and
4791 // tok::numeric_constant (0000) should be enough. But the spelling of the
4792 // uuid argument is checked later anyways, so there's no harm in accepting
4793 // almost anything here.
4794 // cl is very strict about whitespace in this form and errors out if any
4795 // is present, so check the space flags on the tokens.
4796 SourceLocation StartLoc = Tok.getLocation();
4797 while (Tok.isNot(tok::r_paren)) {
4798 if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
4799 Diag(Tok, diag::err_attribute_uuid_malformed_guid);
4800 SkipUntil(tok::r_paren, StopAtSemi);
4801 return;
4802 }
4803 SmallString<16> SpellingBuffer;
4804 SpellingBuffer.resize(Tok.getLength() + 1);
4805 bool Invalid = false;
4806 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
4807 if (Invalid) {
4808 SkipUntil(tok::r_paren, StopAtSemi);
4809 return;
4810 }
4811 StrBuffer += TokSpelling;
4813 }
4814 StrBuffer += "\"";
4815
4816 if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
4817 Diag(Tok, diag::err_attribute_uuid_malformed_guid);
4818 ConsumeParen();
4819 return;
4820 }
4821
4822 // Pretend the user wrote the appropriate string literal here.
4823 // ActOnStringLiteral() copies the string data into the literal, so it's
4824 // ok that the Token points to StrBuffer.
4825 Token Toks[1];
4826 Toks[0].startToken();
4827 Toks[0].setKind(tok::string_literal);
4828 Toks[0].setLocation(StartLoc);
4829 Toks[0].setLiteralData(StrBuffer.data());
4830 Toks[0].setLength(StrBuffer.size());
4831 StringLiteral *UuidString =
4832 cast<StringLiteral>(Actions.ActOnUnevaluatedStringLiteral(Toks).get());
4833 ArgExprs.push_back(UuidString);
4834 }
4835
4836 if (!T.consumeClose()) {
4837 Attrs.addNew(UuidIdent, SourceRange(UuidLoc, T.getCloseLocation()),
4838 AttributeScopeInfo(), ArgExprs.data(), ArgExprs.size(),
4839 ParsedAttr::Form::Microsoft());
4840 }
4841}
4842
4843void Parser::ParseHLSLRootSignatureAttributeArgs(ParsedAttributes &Attrs) {
4844 assert(Tok.is(tok::identifier) &&
4845 "Expected an identifier to denote which MS attribute to consider");
4846 IdentifierInfo *RootSignatureIdent = Tok.getIdentifierInfo();
4847 assert(RootSignatureIdent->getName() == "RootSignature" &&
4848 "Expected RootSignature identifier for root signature attribute");
4849
4850 SourceLocation RootSignatureLoc = Tok.getLocation();
4851 ConsumeToken();
4852
4853 // Ignore the left paren location for now.
4854 BalancedDelimiterTracker T(*this, tok::l_paren);
4855 if (T.consumeOpen()) {
4856 Diag(Tok, diag::err_expected) << tok::l_paren;
4857 return;
4858 }
4859
4860 auto ProcessStringLiteral = [this]() -> std::optional<StringLiteral *> {
4861 if (!isTokenStringLiteral())
4862 return std::nullopt;
4863
4865 if (StringResult.isInvalid())
4866 return std::nullopt;
4867
4868 if (auto Lit = dyn_cast<StringLiteral>(StringResult.get()))
4869 return Lit;
4870
4871 return std::nullopt;
4872 };
4873
4874 auto Signature = ProcessStringLiteral();
4875 if (!Signature.has_value()) {
4876 Diag(Tok, diag::err_expected_string_literal)
4877 << /*in attributes...*/ 4 << "RootSignature";
4878 return;
4879 }
4880
4881 // Construct our identifier
4882 IdentifierInfo *DeclIdent = hlsl::ParseHLSLRootSignature(
4883 Actions, getLangOpts().HLSLRootSigVer, *Signature);
4884 if (!DeclIdent) {
4885 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
4886 T.consumeClose();
4887 return;
4888 }
4889
4890 // Create the arg for the ParsedAttr
4891 IdentifierLoc *ILoc = ::new (Actions.getASTContext())
4892 IdentifierLoc(RootSignatureLoc, DeclIdent);
4893
4894 ArgsVector Args = {ILoc};
4895
4896 if (!T.consumeClose())
4897 Attrs.addNew(RootSignatureIdent,
4898 SourceRange(RootSignatureLoc, T.getCloseLocation()),
4899 AttributeScopeInfo(), Args.data(), Args.size(),
4900 ParsedAttr::Form::Microsoft());
4901}
4902
4903void Parser::ParseMicrosoftAttributes(ParsedAttributes &Attrs) {
4904 assert(Tok.is(tok::l_square) && "Not a Microsoft attribute list");
4905
4906 SourceLocation StartLoc = Tok.getLocation();
4907 SourceLocation EndLoc = StartLoc;
4908 do {
4909 // FIXME: If this is actually a C++11 attribute, parse it as one.
4910 BalancedDelimiterTracker T(*this, tok::l_square);
4911 T.consumeOpen();
4912
4913 // Skip most ms attributes except for a specific list.
4914 while (true) {
4915 SkipUntil(tok::r_square, tok::identifier,
4917 if (Tok.is(tok::code_completion)) {
4918 cutOffParsing();
4919 Actions.CodeCompletion().CodeCompleteAttribute(
4922 /*Scope=*/nullptr);
4923 break;
4924 }
4925 if (Tok.isNot(tok::identifier)) // ']', but also eof
4926 break;
4927 if (Tok.getIdentifierInfo()->getName() == "uuid")
4928 ParseMicrosoftUuidAttributeArgs(Attrs);
4929 else if (Tok.getIdentifierInfo()->getName() == "RootSignature")
4930 ParseHLSLRootSignatureAttributeArgs(Attrs);
4931 else {
4932 IdentifierInfo *II = Tok.getIdentifierInfo();
4933 SourceLocation NameLoc = Tok.getLocation();
4934 ConsumeToken();
4935 ParsedAttr::Kind AttrKind =
4937 // For HLSL we want to handle all attributes, but for MSVC compat, we
4938 // silently ignore unknown Microsoft attributes.
4939 if (getLangOpts().HLSL || AttrKind != ParsedAttr::UnknownAttribute) {
4940 bool AttrParsed = false;
4941 if (Tok.is(tok::l_paren)) {
4942 CachedTokens OpenMPTokens;
4943 AttrParsed =
4944 ParseCXX11AttributeArgs(II, NameLoc, Attrs, &EndLoc, nullptr,
4945 SourceLocation(), OpenMPTokens);
4946 ReplayOpenMPAttributeTokens(OpenMPTokens);
4947 }
4948 if (!AttrParsed) {
4949 Attrs.addNew(II, NameLoc, AttributeScopeInfo(), nullptr, 0,
4950 ParsedAttr::Form::Microsoft());
4951 }
4952 }
4953 }
4954 }
4955
4956 T.consumeClose();
4957 EndLoc = T.getCloseLocation();
4958 } while (Tok.is(tok::l_square));
4959
4960 Attrs.Range = SourceRange(StartLoc, EndLoc);
4961}
4962
4963void Parser::ParseMicrosoftIfExistsClassDeclaration(
4964 DeclSpec::TST TagType, ParsedAttributes &AccessAttrs,
4965 AccessSpecifier &CurAS) {
4966 IfExistsCondition Result;
4967 if (ParseMicrosoftIfExistsCondition(Result))
4968 return;
4969
4970 BalancedDelimiterTracker Braces(*this, tok::l_brace);
4971 if (Braces.consumeOpen()) {
4972 Diag(Tok, diag::err_expected) << tok::l_brace;
4973 return;
4974 }
4975
4976 switch (Result.Behavior) {
4978 // Parse the declarations below.
4979 break;
4980
4982 Diag(Result.KeywordLoc, diag::warn_microsoft_dependent_exists)
4983 << Result.IsIfExists;
4984 // Fall through to skip.
4985 [[fallthrough]];
4986
4988 Braces.skipToEnd();
4989 return;
4990 }
4991
4992 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
4993 // __if_exists, __if_not_exists can nest.
4994 if (Tok.isOneOf(tok::kw___if_exists, tok::kw___if_not_exists)) {
4995 ParseMicrosoftIfExistsClassDeclaration(TagType, AccessAttrs, CurAS);
4996 continue;
4997 }
4998
4999 // Check for extraneous top-level semicolon.
5000 if (Tok.is(tok::semi)) {
5001 ConsumeExtraSemi(ExtraSemiKind::InsideStruct, TagType);
5002 continue;
5003 }
5004
5005 AccessSpecifier AS = getAccessSpecifierIfPresent();
5006 if (AS != AS_none) {
5007 // Current token is a C++ access specifier.
5008 CurAS = AS;
5009 SourceLocation ASLoc = Tok.getLocation();
5010 ConsumeToken();
5011 if (Tok.is(tok::colon))
5012 Actions.ActOnAccessSpecifier(AS, ASLoc, Tok.getLocation(),
5013 ParsedAttributesView{});
5014 else
5015 Diag(Tok, diag::err_expected) << tok::colon;
5016 ConsumeToken();
5017 continue;
5018 }
5019
5020 ParsedTemplateInfo TemplateInfo;
5021 // Parse all the comma separated declarators.
5022 ParseCXXClassMemberDeclaration(CurAS, AccessAttrs, TemplateInfo);
5023 }
5024
5025 Braces.consumeClose();
5026}
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.
bool is(tok::TokenKind Kind) const
Token Tok
The Token.
FormatToken * Next
The next token in the unwrapped line.
#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:181
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition DeclSpec.h:186
SourceRange getRange() const
Definition DeclSpec.h:80
SourceLocation getBeginLoc() const
Definition DeclSpec.h:84
bool isSet() const
Deprecated.
Definition DeclSpec.h:199
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition DeclSpec.h:184
void setTemplateParamLists(ArrayRef< TemplateParameterList * > L)
Definition DeclSpec.h:87
static CharSourceRange getTokenRange(SourceRange R)
Captures information about "declaration specifiers".
Definition DeclSpec.h:218
void setTypeArgumentRange(SourceRange range)
Definition DeclSpec.h:576
static const TST TST_typename
Definition DeclSpec.h:277
void ClearStorageClassSpecs()
Definition DeclSpec.h:498
TST getTypeSpecType() const
Definition DeclSpec.h:520
SCS getStorageClassSpec() const
Definition DeclSpec.h:484
bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
Definition DeclSpec.cpp:846
SourceRange getSourceRange() const LLVM_READONLY
Definition DeclSpec.h:557
void SetPackIndexingExpr(SourceLocation EllipsisLoc, Expr *Pack)
Definition DeclSpec.cpp:978
void SetRangeEnd(SourceLocation Loc)
Definition DeclSpec.h:714
static const TST TST_interface
Definition DeclSpec.h:275
unsigned getTypeQualifiers() const
getTypeQualifiers - Return a set of TQs.
Definition DeclSpec.h:600
void SetRangeStart(SourceLocation Loc)
Definition DeclSpec.h:713
static const TST TST_union
Definition DeclSpec.h:273
static const TST TST_typename_pack_indexing
Definition DeclSpec.h:284
SourceLocation getFriendSpecLoc() const
Definition DeclSpec.h:832
SourceLocation getModulePrivateSpecLoc() const
Definition DeclSpec.h:835
bool isFriendSpecifiedFirst() const
Definition DeclSpec.h:830
Expr * getRepAsExpr() const
Definition DeclSpec.h:538
static const TST TST_decltype
Definition DeclSpec.h:282
void takeAttributesAppendingingFrom(ParsedAttributes &attrs)
Definition DeclSpec.h:881
static const TST TST_class
Definition DeclSpec.h:276
TypeSpecifierType TST
Definition DeclSpec.h:248
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:949
Decl * getRepAsDecl() const
Definition DeclSpec.h:534
CXXScopeSpec & getTypeSpecScope()
Definition DeclSpec.h:554
static const TST TST_decltype_auto
Definition DeclSpec.h:283
void setExternInLinkageSpec(bool Value)
Definition DeclSpec.h:489
static const TST TST_error
Definition DeclSpec.h:299
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:826
static const TST TST_struct
Definition DeclSpec.h:274
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:596
SourceLocation getLocation() const
Definition DeclBase.h:447
void setLocation(SourceLocation L)
Definition DeclBase.h:448
Information about one declarator, including the parsed type information and the identifier.
Definition DeclSpec.h:1921
bool isFunctionDeclarator(unsigned &idx) const
isFunctionDeclarator - This method returns true if the declarator is a function declarator (looking t...
Definition DeclSpec.h:2477
bool isPastIdentifier() const
isPastIdentifier - Return true if we have parsed beyond the point where the name would appear.
Definition DeclSpec.h:2335
bool isArrayOfUnknownBound() const
isArrayOfUnknownBound - This method returns true if the declarator is a declarator for an array of un...
Definition DeclSpec.h:2467
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:2744
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition DeclSpec.h:2068
const ParsedAttributes & getAttributes() const
Definition DeclSpec.h:2704
SourceLocation getIdentifierLoc() const
Definition DeclSpec.h:2357
void SetIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Set the name of this declarator to be the given identifier.
Definition DeclSpec.h:2360
void setTrailingRequiresClause(Expr *TRC)
Sets a trailing requires clause for this declarator.
Definition DeclSpec.h:2647
void setTemplateParameterLists(ArrayRef< TemplateParameterList * > TPLs)
Sets the template parameter lists that preceded the declarator.
Definition DeclSpec.h:2665
bool isFirstDeclarator() const
Definition DeclSpec.h:2742
void setFunctionDefinitionKind(FunctionDefinitionKind Val)
Definition DeclSpec.h:2754
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition DeclSpec.h:2083
bool hasName() const
hasName - Whether this declarator has a name, which might be an identifier (accessible via getIdentif...
Definition DeclSpec.h:2341
void clear()
Reset the contents of this Declarator.
Definition DeclSpec.h:2131
void setAsmLabel(Expr *E)
Definition DeclSpec.h:2722
void ExtendWithDeclSpec(const DeclSpec &DS)
ExtendWithDeclSpec - Extend the declarator source range to include the given declspec,...
Definition DeclSpec.h:2122
void SetRangeEnd(SourceLocation Loc)
SetRangeEnd - Set the end of the source range to Loc, unless it's invalid.
Definition DeclSpec.h:2115
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:2508
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:80
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:117
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:141
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:130
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:104
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:975
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:408
Parser - This implements a parser for the C family of languages.
Definition Parser.h:172
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:263
bool ParseTopLevelDecl()
Definition Parser.h:252
static TypeResult getTypeAnnotation(const Token &Tok)
getTypeAnnotation - Read a parsed type out of an annotation token.
Definition Parser.h:328
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:197
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:291
const Token & GetLookAheadToken(unsigned N)
GetLookAheadToken - This peeks ahead N tokens and returns that token without consuming any tokens.
Definition Parser.h:317
ExprResult ParseConstantExpression()
ExprResult ParseConditionalExpression()
Definition ParseExpr.cpp:95
bool TryConsumeToken(tok::TokenKind Expected)
Definition Parser.h:271
OpaquePtr< DeclGroupRef > DeclGroupPtrTy
Definition Parser.h:220
Scope * getCurScope() const
Definition Parser.h:212
const TargetInfo & getTargetInfo() const
Definition Parser.h:206
OpaquePtr< TemplateName > TemplateTy
Definition Parser.h:221
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:507
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:198
const LangOptions & getLangOpts() const
Definition Parser.h:205
friend class ParenBraceBracketBalancer
Definition Parser.h:199
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:488
@ StopAtCodeCompletion
Stop at code completion.
Definition Parser.h:489
@ StopAtSemi
Stop skipping at semicolon.
Definition Parser.h:486
ExprResult ParseUnevaluatedStringLiteralExpression()
const Token & NextToken()
NextToken - This peeks ahead one token and returns it without consuming it.
Definition Parser.h:325
friend class BalancedDelimiterTracker
Definition Parser.h:200
SmallVector< TemplateParameterList *, 4 > TemplateParameterLists
Definition Parser.h:7834
bool TryAnnotateCXXScopeToken(bool EnteringContext=false)
TryAnnotateScopeToken - Like TryAnnotateTypeOrScopeToken but only annotates C++ scope specifiers and ...
Definition Parser.cpp:2105
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:6630
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
Definition Sema.h:6810
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
Definition Sema.h:6820
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6789
@ PotentiallyEvaluatedIfUsed
The current expression is potentially evaluated, but any declarations referenced inside that expressi...
Definition Sema.h:6830
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:3732
Token - This structure provides full information about a lexed token.
Definition Token.h:36
IdentifierInfo * getIdentifierInfo() const
Definition Token.h:197
void setLiteralData(const char *Ptr)
Definition Token.h:239
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file.
Definition Token.h:142
void setLength(unsigned Len)
Definition Token.h:151
void setKind(tok::TokenKind K)
Definition Token.h:100
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:104
tok::TokenKind getKind() const
Definition Token.h:99
void setLocation(SourceLocation L)
Definition Token.h:150
bool hasUDSuffix() const
Return true if this token is a string or character literal which has a ud-suffix.
Definition Token.h:321
void startToken()
Reset all flags to cleared.
Definition Token.h:187
Represents a C++11 virt-specifier-seq.
Definition DeclSpec.h:2801
Specifier getLastSpecifier() const
Definition DeclSpec.h:2834
SourceLocation getFirstLocation() const
Definition DeclSpec.h:2832
bool isUnset() const
Definition DeclSpec.h:2818
SourceLocation getAbstractLoc() const
Definition DeclSpec.h:2826
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:93
@ TST_decltype
Definition Specifiers.h:90
@ TST_typename
Definition Specifiers.h:85
@ TST_decltype_auto
Definition Specifiers.h:94
bool doesKeywordAttributeTakeArgs(tok::TokenKind Kind)
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ NotAttributeSpecifier
This is not an attribute specifier.
Definition Parser.h:159
@ 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:1864
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:272
@ ICIS_CopyInit
Copy initialization.
Definition Specifiers.h:274
@ ICIS_ListInit
Direct list-initialization.
Definition Specifiers.h:275
@ ICIS_NoInit
No in-class initializer.
Definition Specifiers.h:273
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:1025
@ IK_Identifier
An identifier.
Definition DeclSpec.h:1011
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition Specifiers.h:124
@ AS_public
Definition Specifiers.h:125
@ AS_protected
Definition Specifiers.h:126
@ AS_none
Definition Specifiers.h:128
@ AS_private
Definition Specifiers.h:127
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:1871
@ 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
@ 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:1250
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:5967
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Braces
New-expression has a C++11 list-initializer.
Definition ExprCXX.h:2252
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:1461
ParamInfo * Params
Params - This is a pointer to a new[]'d array of ParamInfo objects that describe the parameters speci...
Definition DeclSpec.h:1441
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
Definition DeclSpec.h:1416
unsigned HasTrailingReturnType
HasTrailingReturnType - If this is true, a trailing return type was specified.
Definition DeclSpec.h:1403
ExceptionSpecificationType getExceptionSpecType() const
Get the type of exception specification this function has.
Definition DeclSpec.h:1580
std::unique_ptr< CachedTokens > DefaultArgTokens
DefaultArgTokens - When the parameter's default argument cannot be parsed immediately (because it occ...
Definition DeclSpec.h:1356
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.