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