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