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