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