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