clang 23.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;
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/TransformTypeTraits.def"
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/TransformTypeTraits.def"
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 // Explicit specialization, class template partial specialization,
1991 // or explicit instantiation.
1992 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1993 TemplateId->NumArgs);
1994 if (TemplateId->isInvalid()) {
1995 // Can't build the declaration.
1996 } else if (TemplateInfo.Kind == ParsedTemplateKind::ExplicitInstantiation &&
1997 TUK == TagUseKind::Declaration) {
1998 // This is an explicit instantiation of a class template.
1999 ProhibitCXX11Attributes(attrs, diag::err_attributes_not_allowed,
2000 diag::err_keyword_not_allowed,
2001 /*DiagnoseEmptyAttrs=*/true);
2002
2003 TagOrTempResult = Actions.ActOnExplicitInstantiation(
2004 getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc,
2005 TagType, StartLoc, SS, TemplateId->Template,
2006 TemplateId->TemplateNameLoc, TemplateId->LAngleLoc, TemplateArgsPtr,
2007 TemplateId->RAngleLoc, attrs);
2008
2009 // Friend template-ids are treated as references unless
2010 // they have template headers, in which case they're ill-formed
2011 // (FIXME: "template <class T> friend class A<T>::B<int>;").
2012 // We diagnose this error in ActOnClassTemplateSpecialization.
2013 } else if (TUK == TagUseKind::Reference ||
2014 (TUK == TagUseKind::Friend &&
2015 TemplateInfo.Kind == ParsedTemplateKind::NonTemplate)) {
2016 ProhibitCXX11Attributes(attrs, diag::err_attributes_not_allowed,
2017 diag::err_keyword_not_allowed,
2018 /*DiagnoseEmptyAttrs=*/true);
2019 TypeResult = Actions.ActOnTagTemplateIdType(
2020 TUK, TagType, StartLoc, SS, TemplateId->TemplateKWLoc,
2021 TemplateId->Template, TemplateId->TemplateNameLoc,
2022 TemplateId->LAngleLoc, TemplateArgsPtr, TemplateId->RAngleLoc);
2023 } else {
2024 // This is an explicit specialization or a class template
2025 // partial specialization.
2026 TemplateParameterLists FakedParamLists;
2027 if (TemplateInfo.Kind == ParsedTemplateKind::ExplicitInstantiation) {
2028 // This looks like an explicit instantiation, because we have
2029 // something like
2030 //
2031 // template class Foo<X>
2032 //
2033 // but it actually has a definition. Most likely, this was
2034 // meant to be an explicit specialization, but the user forgot
2035 // the '<>' after 'template'.
2036 // It this is friend declaration however, since it cannot have a
2037 // template header, it is most likely that the user meant to
2038 // remove the 'template' keyword.
2039 assert((TUK == TagUseKind::Definition || TUK == TagUseKind::Friend) &&
2040 "Expected a definition here");
2041
2042 if (TUK == TagUseKind::Friend) {
2043 Diag(DS.getFriendSpecLoc(), diag::err_friend_explicit_instantiation);
2044 TemplateParams = nullptr;
2045 } else {
2046 SourceLocation LAngleLoc =
2047 PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
2048 Diag(TemplateId->TemplateNameLoc,
2049 diag::err_explicit_instantiation_with_definition)
2050 << SourceRange(TemplateInfo.TemplateLoc)
2051 << FixItHint::CreateInsertion(LAngleLoc, "<>");
2052
2053 // Create a fake template parameter list that contains only
2054 // "template<>", so that we treat this construct as a class
2055 // template specialization.
2056 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
2057 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, {},
2058 LAngleLoc, nullptr));
2059 TemplateParams = &FakedParamLists;
2060 }
2061 }
2062
2063 // Build the class template specialization.
2064 TagOrTempResult = Actions.ActOnClassTemplateSpecialization(
2065 getCurScope(), TagType, TUK, StartLoc, DS.getModulePrivateSpecLoc(),
2066 SS, *TemplateId, attrs,
2067 MultiTemplateParamsArg(TemplateParams ? &(*TemplateParams)[0]
2068 : nullptr,
2069 TemplateParams ? TemplateParams->size() : 0),
2070 &SkipBody);
2071 }
2072 } else if (TemplateInfo.Kind == ParsedTemplateKind::ExplicitInstantiation &&
2073 TUK == TagUseKind::Declaration) {
2074 // Explicit instantiation of a member of a class template
2075 // specialization, e.g.,
2076 //
2077 // template struct Outer<int>::Inner;
2078 //
2079 ProhibitAttributes(attrs);
2080
2081 TagOrTempResult = Actions.ActOnExplicitInstantiation(
2082 getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc,
2083 TagType, StartLoc, SS, Name, NameLoc, attrs);
2084 } else if (TUK == TagUseKind::Friend &&
2085 TemplateInfo.Kind != ParsedTemplateKind::NonTemplate) {
2086 ProhibitCXX11Attributes(attrs, diag::err_attributes_not_allowed,
2087 diag::err_keyword_not_allowed,
2088 /*DiagnoseEmptyAttrs=*/true);
2089
2090 // Consume '...' first so we error on the ',' after it if there is one.
2091 SourceLocation EllipsisLoc;
2092 TryConsumeToken(tok::ellipsis, EllipsisLoc);
2093
2094 // CWG 2917: In a template-declaration whose declaration is a
2095 // friend-type-declaration, the friend-type-specifier-list shall
2096 // consist of exactly one friend-type-specifier.
2097 //
2098 // Essentially, the following is obviously nonsense, so disallow it:
2099 //
2100 // template <typename>
2101 // friend class S, int;
2102 //
2103 if (Tok.is(tok::comma)) {
2104 Diag(Tok.getLocation(),
2105 diag::err_friend_template_decl_multiple_specifiers);
2106 SkipUntil(tok::semi, StopBeforeMatch);
2107 }
2108
2109 TagOrTempResult = Actions.ActOnTemplatedFriendTag(
2110 getCurScope(), DS.getFriendSpecLoc(), TagType, StartLoc, SS, Name,
2111 NameLoc, EllipsisLoc, attrs,
2112 MultiTemplateParamsArg(TemplateParams ? &(*TemplateParams)[0] : nullptr,
2113 TemplateParams ? TemplateParams->size() : 0));
2114 } else {
2116 ProhibitCXX11Attributes(attrs, diag::err_attributes_not_allowed,
2117 diag::err_keyword_not_allowed,
2118 /* DiagnoseEmptyAttrs=*/true);
2119
2120 if (TUK == TagUseKind::Definition &&
2121 TemplateInfo.Kind == ParsedTemplateKind::ExplicitInstantiation) {
2122 // If the declarator-id is not a template-id, issue a diagnostic and
2123 // recover by ignoring the 'template' keyword.
2124 Diag(Tok, diag::err_template_defn_explicit_instantiation)
2125 << 1 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
2126 TemplateParams = nullptr;
2127 }
2128
2129 bool IsDependent = false;
2130
2131 // Don't pass down template parameter lists if this is just a tag
2132 // reference. For example, we don't need the template parameters here:
2133 // template <class T> class A *makeA(T t);
2134 MultiTemplateParamsArg TParams;
2135 if (TUK != TagUseKind::Reference && TemplateParams)
2136 TParams =
2137 MultiTemplateParamsArg(&(*TemplateParams)[0], TemplateParams->size());
2138
2139 stripTypeAttributesOffDeclSpec(attrs, DS, TUK);
2140
2141 // Declaration or definition of a class type
2142 TagOrTempResult = Actions.ActOnTag(
2143 getCurScope(), TagType, TUK, StartLoc, SS, Name, NameLoc, attrs, AS,
2144 DS.getModulePrivateSpecLoc(), TParams, Owned, IsDependent,
2145 SourceLocation(), false, clang::TypeResult(),
2146 DSC == DeclSpecContext::DSC_type_specifier,
2147 DSC == DeclSpecContext::DSC_template_param ||
2148 DSC == DeclSpecContext::DSC_template_type_arg,
2149 OffsetOfState, &SkipBody);
2150
2151 // If ActOnTag said the type was dependent, try again with the
2152 // less common call.
2153 if (IsDependent) {
2154 assert(TUK == TagUseKind::Reference || TUK == TagUseKind::Friend);
2155 TypeResult = Actions.ActOnDependentTag(getCurScope(), TagType, TUK, SS,
2156 Name, StartLoc, NameLoc);
2157 }
2158 }
2159
2160 // If this is an elaborated type specifier in function template,
2161 // and we delayed diagnostics before,
2162 // just merge them into the current pool.
2163 if (shouldDelayDiagsInTag) {
2164 diagsFromTag.done();
2165 if (TUK == TagUseKind::Reference &&
2166 TemplateInfo.Kind == ParsedTemplateKind::Template)
2167 diagsFromTag.redelay();
2168 }
2169
2170 // If there is a body, parse it and inform the actions module.
2171 if (TUK == TagUseKind::Definition) {
2172 assert(Tok.is(tok::l_brace) ||
2173 (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
2174 isClassCompatibleKeyword());
2175 if (SkipBody.ShouldSkip)
2176 SkipCXXMemberSpecification(StartLoc, AttrFixitLoc, TagType,
2177 TagOrTempResult.get());
2178 else if (getLangOpts().CPlusPlus)
2179 ParseCXXMemberSpecification(StartLoc, AttrFixitLoc, attrs, TagType,
2180 TagOrTempResult.get());
2181 else {
2182 Decl *D =
2183 SkipBody.CheckSameAsPrevious ? SkipBody.New : TagOrTempResult.get();
2184 // Parse the definition body.
2185 ParseStructUnionBody(StartLoc, TagType, cast<RecordDecl>(D));
2186 if (SkipBody.CheckSameAsPrevious &&
2187 !Actions.ActOnDuplicateDefinition(getCurScope(),
2188 TagOrTempResult.get(), SkipBody)) {
2189 DS.SetTypeSpecError();
2190 return;
2191 }
2192 }
2193 }
2194
2195 if (!TagOrTempResult.isInvalid())
2196 // Delayed processing of attributes.
2197 Actions.ProcessDeclAttributeDelayed(TagOrTempResult.get(), attrs);
2198
2199 const char *PrevSpec = nullptr;
2200 unsigned DiagID;
2201 bool Result;
2202 if (!TypeResult.isInvalid()) {
2204 NameLoc.isValid() ? NameLoc : StartLoc,
2205 PrevSpec, DiagID, TypeResult.get(), Policy);
2206 } else if (!TagOrTempResult.isInvalid()) {
2208 TagType, StartLoc, NameLoc.isValid() ? NameLoc : StartLoc, PrevSpec,
2209 DiagID, TagOrTempResult.get(), Owned, Policy);
2210 } else {
2211 DS.SetTypeSpecError();
2212 return;
2213 }
2214
2215 if (Result)
2216 Diag(StartLoc, DiagID) << PrevSpec;
2217
2218 // At this point, we've successfully parsed a class-specifier in 'definition'
2219 // form (e.g. "struct foo { int x; }". While we could just return here, we're
2220 // going to look at what comes after it to improve error recovery. If an
2221 // impossible token occurs next, we assume that the programmer forgot a ; at
2222 // the end of the declaration and recover that way.
2223 //
2224 // Also enforce C++ [temp]p3:
2225 // In a template-declaration which defines a class, no declarator
2226 // is permitted.
2227 //
2228 // After a type-specifier, we don't expect a semicolon. This only happens in
2229 // C, since definitions are not permitted in this context in C++.
2230 if (TUK == TagUseKind::Definition &&
2231 (getLangOpts().CPlusPlus || !isTypeSpecifier(DSC)) &&
2232 (TemplateInfo.Kind != ParsedTemplateKind::NonTemplate || !isValidAfterTypeSpecifier(false))) {
2233 if (Tok.isNot(tok::semi)) {
2234 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
2235 ExpectAndConsume(tok::semi, diag::err_expected_after,
2236 DeclSpec::getSpecifierName(TagType, PPol));
2237 // Push this token back into the preprocessor and change our current token
2238 // to ';' so that the rest of the code recovers as though there were an
2239 // ';' after the definition.
2240 PP.EnterToken(Tok, /*IsReinject=*/true);
2241 Tok.setKind(tok::semi);
2242 }
2243 }
2244}
2245
2246void Parser::ParseBaseClause(Decl *ClassDecl) {
2247 assert(Tok.is(tok::colon) && "Not a base clause");
2248 ConsumeToken();
2249
2250 // Build up an array of parsed base specifiers.
2251 SmallVector<CXXBaseSpecifier *, 8> BaseInfo;
2252
2253 while (true) {
2254 // Parse a base-specifier.
2255 BaseResult Result = ParseBaseSpecifier(ClassDecl);
2256 if (!Result.isUsable()) {
2257 // Skip the rest of this base specifier, up until the comma or
2258 // opening brace.
2259 SkipUntil(tok::comma, tok::l_brace, StopAtSemi | StopBeforeMatch);
2260 } else {
2261 // Add this to our array of base specifiers.
2262 BaseInfo.push_back(Result.get());
2263 }
2264
2265 // If the next token is a comma, consume it and keep reading
2266 // base-specifiers.
2267 if (!TryConsumeToken(tok::comma))
2268 break;
2269 }
2270
2271 // Attach the base specifiers
2272 Actions.ActOnBaseSpecifiers(ClassDecl, BaseInfo);
2273}
2274
2275BaseResult Parser::ParseBaseSpecifier(Decl *ClassDecl) {
2276 bool IsVirtual = false;
2277 SourceLocation StartLoc = Tok.getLocation();
2278
2279 ParsedAttributes Attributes(AttrFactory);
2280 MaybeParseCXX11Attributes(Attributes);
2281
2282 // Parse the 'virtual' keyword.
2283 if (TryConsumeToken(tok::kw_virtual))
2284 IsVirtual = true;
2285
2286 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2287
2288 // Parse an (optional) access specifier.
2289 AccessSpecifier Access = getAccessSpecifierIfPresent();
2290 if (Access != AS_none) {
2291 ConsumeToken();
2292 if (getLangOpts().HLSL)
2293 Diag(Tok.getLocation(), diag::ext_hlsl_access_specifiers);
2294 }
2295
2296 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2297
2298 // Parse the 'virtual' keyword (again!), in case it came after the
2299 // access specifier.
2300 if (Tok.is(tok::kw_virtual)) {
2301 SourceLocation VirtualLoc = ConsumeToken();
2302 if (IsVirtual) {
2303 // Complain about duplicate 'virtual'
2304 Diag(VirtualLoc, diag::err_dup_virtual)
2305 << FixItHint::CreateRemoval(VirtualLoc);
2306 }
2307
2308 IsVirtual = true;
2309 }
2310
2311 if (getLangOpts().HLSL && IsVirtual)
2312 Diag(Tok.getLocation(), diag::err_hlsl_virtual_inheritance);
2313
2314 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2315
2316 // Parse the class-name.
2317
2318 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
2319 // implementation for VS2013 uses _Atomic as an identifier for one of the
2320 // classes in <atomic>. Treat '_Atomic' to be an identifier when we are
2321 // parsing the class-name for a base specifier.
2322 if (getLangOpts().MSVCCompat && Tok.is(tok::kw__Atomic) &&
2323 NextToken().is(tok::less))
2324 Tok.setKind(tok::identifier);
2325
2326 SourceLocation EndLocation;
2327 SourceLocation BaseLoc;
2328 TypeResult BaseType = ParseBaseTypeSpecifier(BaseLoc, EndLocation);
2329 if (BaseType.isInvalid())
2330 return true;
2331
2332 // Parse the optional ellipsis (for a pack expansion). The ellipsis is
2333 // actually part of the base-specifier-list grammar productions, but we
2334 // parse it here for convenience.
2335 SourceLocation EllipsisLoc;
2336 TryConsumeToken(tok::ellipsis, EllipsisLoc);
2337
2338 // Find the complete source range for the base-specifier.
2339 SourceRange Range(StartLoc, EndLocation);
2340
2341 // Notify semantic analysis that we have parsed a complete
2342 // base-specifier.
2343 return Actions.ActOnBaseSpecifier(ClassDecl, Range, Attributes, IsVirtual,
2344 Access, BaseType.get(), BaseLoc,
2345 EllipsisLoc);
2346}
2347
2348AccessSpecifier Parser::getAccessSpecifierIfPresent() const {
2349 switch (Tok.getKind()) {
2350 default:
2351 return AS_none;
2352 case tok::kw_private:
2353 return AS_private;
2354 case tok::kw_protected:
2355 return AS_protected;
2356 case tok::kw_public:
2357 return AS_public;
2358 }
2359}
2360
2361void Parser::HandleMemberFunctionDeclDelays(Declarator &DeclaratorInfo,
2362 Decl *ThisDecl) {
2363 DeclaratorChunk::FunctionTypeInfo &FTI = DeclaratorInfo.getFunctionTypeInfo();
2364 // If there was a late-parsed exception-specification, we'll need a
2365 // late parse
2366 bool NeedLateParse = FTI.getExceptionSpecType() == EST_Unparsed;
2367
2368 if (!NeedLateParse) {
2369 // Look ahead to see if there are any default args
2370 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx) {
2371 const auto *Param = cast<ParmVarDecl>(FTI.Params[ParamIdx].Param);
2372 if (Param->hasUnparsedDefaultArg()) {
2373 NeedLateParse = true;
2374 break;
2375 }
2376 }
2377 }
2378
2379 if (NeedLateParse) {
2380 // Push this method onto the stack of late-parsed method
2381 // declarations.
2382 auto LateMethod = new LateParsedMethodDeclaration(this, ThisDecl);
2383 getCurrentClass().LateParsedDeclarations.push_back(LateMethod);
2384
2385 // Push tokens for each parameter. Those that do not have defaults will be
2386 // NULL. We need to track all the parameters so that we can push them into
2387 // scope for later parameters and perhaps for the exception specification.
2388 LateMethod->DefaultArgs.reserve(FTI.NumParams);
2389 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx)
2390 LateMethod->DefaultArgs.push_back(LateParsedDefaultArgument(
2391 FTI.Params[ParamIdx].Param,
2392 std::move(FTI.Params[ParamIdx].DefaultArgTokens)));
2393
2394 // Stash the exception-specification tokens in the late-pased method.
2395 if (FTI.getExceptionSpecType() == EST_Unparsed) {
2396 LateMethod->ExceptionSpecTokens = FTI.ExceptionSpecTokens;
2397 FTI.ExceptionSpecTokens = nullptr;
2398 }
2399 }
2400}
2401
2402VirtSpecifiers::Specifier Parser::isCXX11VirtSpecifier(const Token &Tok) const {
2403 if (!getLangOpts().CPlusPlus || Tok.isNot(tok::identifier))
2405
2406 const IdentifierInfo *II = Tok.getIdentifierInfo();
2407
2408 // Initialize the contextual keywords.
2409 if (!Ident_final) {
2410 Ident_final = &PP.getIdentifierTable().get("final");
2411 if (getLangOpts().GNUKeywords)
2412 Ident_GNU_final = &PP.getIdentifierTable().get("__final");
2413 if (getLangOpts().MicrosoftExt) {
2414 Ident_sealed = &PP.getIdentifierTable().get("sealed");
2415 Ident_abstract = &PP.getIdentifierTable().get("abstract");
2416 }
2417 Ident_override = &PP.getIdentifierTable().get("override");
2418 }
2419
2420 if (II == Ident_override)
2422
2423 if (II == Ident_sealed)
2425
2426 if (II == Ident_abstract)
2428
2429 if (II == Ident_final)
2431
2432 if (II == Ident_GNU_final)
2434
2436}
2437
2438void Parser::ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS,
2439 bool IsInterface,
2440 SourceLocation FriendLoc) {
2441 while (true) {
2442 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
2443 if (Specifier == VirtSpecifiers::VS_None)
2444 return;
2445
2446 if (FriendLoc.isValid()) {
2447 Diag(Tok.getLocation(), diag::err_friend_decl_spec)
2449 << FixItHint::CreateRemoval(Tok.getLocation())
2450 << SourceRange(FriendLoc, FriendLoc);
2451 ConsumeToken();
2452 continue;
2453 }
2454
2455 // C++ [class.mem]p8:
2456 // A virt-specifier-seq shall contain at most one of each virt-specifier.
2457 const char *PrevSpec = nullptr;
2458 if (VS.SetSpecifier(Specifier, Tok.getLocation(), PrevSpec))
2459 Diag(Tok.getLocation(), diag::err_duplicate_virt_specifier)
2460 << PrevSpec << FixItHint::CreateRemoval(Tok.getLocation());
2461
2462 if (IsInterface && (Specifier == VirtSpecifiers::VS_Final ||
2463 Specifier == VirtSpecifiers::VS_Sealed)) {
2464 Diag(Tok.getLocation(), diag::err_override_control_interface)
2466 } else if (Specifier == VirtSpecifiers::VS_Sealed) {
2467 Diag(Tok.getLocation(), diag::ext_ms_sealed_keyword);
2468 } else if (Specifier == VirtSpecifiers::VS_Abstract) {
2469 Diag(Tok.getLocation(), diag::ext_ms_abstract_keyword);
2470 } else if (Specifier == VirtSpecifiers::VS_GNU_Final) {
2471 Diag(Tok.getLocation(), diag::ext_warn_gnu_final);
2472 } else {
2473 Diag(Tok.getLocation(),
2475 ? diag::warn_cxx98_compat_override_control_keyword
2476 : diag::ext_override_control_keyword)
2478 }
2479 ConsumeToken();
2480 }
2481}
2482
2483bool Parser::isCXX11FinalKeyword() const {
2484 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
2488}
2489
2490bool Parser::isClassCompatibleKeyword(Token Tok) const {
2491 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier(Tok);
2496}
2497
2498bool Parser::isClassCompatibleKeyword() const {
2499 return isClassCompatibleKeyword(Tok);
2500}
2501
2502/// Parse a C++ member-declarator up to, but not including, the optional
2503/// brace-or-equal-initializer or pure-specifier.
2504bool Parser::ParseCXXMemberDeclaratorBeforeInitializer(
2505 Declarator &DeclaratorInfo, VirtSpecifiers &VS, ExprResult &BitfieldSize,
2506 LateParsedAttrList &LateParsedAttrs) {
2507 // member-declarator:
2508 // declarator virt-specifier-seq[opt] pure-specifier[opt]
2509 // declarator requires-clause
2510 // declarator brace-or-equal-initializer[opt]
2511 // identifier attribute-specifier-seq[opt] ':' constant-expression
2512 // brace-or-equal-initializer[opt]
2513 // ':' constant-expression
2514 //
2515 // NOTE: the latter two productions are a proposed bugfix rather than the
2516 // current grammar rules as of C++20.
2517 if (Tok.isNot(tok::colon))
2518 ParseDeclarator(DeclaratorInfo);
2519 else
2520 DeclaratorInfo.SetIdentifier(nullptr, Tok.getLocation());
2521
2522 bool IsFunctionDeclarator = DeclaratorInfo.isFunctionDeclarator();
2523 if (!IsFunctionDeclarator && !getLangOpts().MSVCCompat)
2524 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
2525
2526 if (getLangOpts().HLSL)
2527 MaybeParseHLSLAnnotations(DeclaratorInfo, nullptr,
2528 /*CouldBeBitField*/ true);
2529
2530 if (!IsFunctionDeclarator && TryConsumeToken(tok::colon)) {
2531 assert(DeclaratorInfo.isPastIdentifier() &&
2532 "don't know where identifier would go yet?");
2533 BitfieldSize = ParseConstantExpression();
2534 if (BitfieldSize.isInvalid())
2535 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2536 } else if (Tok.is(tok::kw_requires)) {
2537 ParseTrailingRequiresClauseWithScope(DeclaratorInfo);
2538 } else {
2539 ParseOptionalCXX11VirtSpecifierSeq(
2540 VS, getCurrentClass().IsInterface,
2541 DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
2542 if (!VS.isUnset())
2543 MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo,
2544 VS);
2545 }
2546
2547 // If a simple-asm-expr is present, parse it.
2548 if (Tok.is(tok::kw_asm)) {
2549 SourceLocation Loc;
2550 ExprResult AsmLabel(ParseSimpleAsm(/*ForAsmLabel*/ true, &Loc));
2551 if (AsmLabel.isInvalid())
2552 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2553
2554 DeclaratorInfo.setAsmLabel(AsmLabel.get());
2555 DeclaratorInfo.SetRangeEnd(Loc);
2556 }
2557
2558 // If attributes exist after the declarator, but before an '{', parse them.
2559 // However, this does not apply for [[]] attributes (which could show up
2560 // before or after the __attribute__ attributes).
2561 DiagnoseAndSkipCXX11Attributes();
2562 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
2563 DiagnoseAndSkipCXX11Attributes();
2564
2565 // For compatibility with code written to older Clang, also accept a
2566 // virt-specifier *after* the GNU attributes.
2567 if (BitfieldSize.isUnset() && VS.isUnset()) {
2568 ParseOptionalCXX11VirtSpecifierSeq(
2569 VS, getCurrentClass().IsInterface,
2570 DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
2571 if (!VS.isUnset()) {
2572 // If we saw any GNU-style attributes that are known to GCC followed by a
2573 // virt-specifier, issue a GCC-compat warning.
2574 for (const ParsedAttr &AL : DeclaratorInfo.getAttributes())
2575 if (AL.isKnownToGCC() && !AL.isCXX11Attribute())
2576 Diag(AL.getLoc(), diag::warn_gcc_attribute_location);
2577
2578 MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo,
2579 VS);
2580 }
2581 }
2582
2583 // If this has neither a name nor a bit width, something has gone seriously
2584 // wrong. Skip until the semi-colon or }.
2585 if (!DeclaratorInfo.hasName() && BitfieldSize.isUnset()) {
2586 // If so, skip until the semi-colon or a }.
2587 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2588 return true;
2589 }
2590 return false;
2591}
2592
2593void Parser::MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(
2594 Declarator &D, VirtSpecifiers &VS) {
2595 DeclSpec DS(AttrFactory);
2596
2597 // GNU-style and C++11 attributes are not allowed here, but they will be
2598 // handled by the caller. Diagnose everything else.
2599 ParseTypeQualifierListOpt(
2600 DS, AR_NoAttributesParsed, /*AtomicOrPtrauthAllowed=*/false,
2601 /*IdentifierRequired=*/false, [&]() {
2602 Actions.CodeCompletion().CodeCompleteFunctionQualifiers(DS, D, &VS);
2603 });
2604 D.ExtendWithDeclSpec(DS);
2605
2606 if (D.isFunctionDeclarator()) {
2607 auto &Function = D.getFunctionTypeInfo();
2609 auto DeclSpecCheck = [&](DeclSpec::TQ TypeQual, StringRef FixItName,
2610 SourceLocation SpecLoc) {
2611 FixItHint Insertion;
2612 auto &MQ = Function.getOrCreateMethodQualifiers();
2613 if (!(MQ.getTypeQualifiers() & TypeQual)) {
2614 std::string Name(FixItName.data());
2615 Name += " ";
2616 Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), Name);
2617 MQ.SetTypeQual(TypeQual, SpecLoc);
2618 }
2619 Diag(SpecLoc, diag::err_declspec_after_virtspec)
2620 << FixItName
2622 << FixItHint::CreateRemoval(SpecLoc) << Insertion;
2623 };
2624 DS.forEachQualifier(DeclSpecCheck);
2625 }
2626
2627 // Parse ref-qualifiers.
2628 bool RefQualifierIsLValueRef = true;
2629 SourceLocation RefQualifierLoc;
2630 if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc)) {
2631 const char *Name = (RefQualifierIsLValueRef ? "& " : "&& ");
2632 FixItHint Insertion =
2634 Function.RefQualifierIsLValueRef = RefQualifierIsLValueRef;
2635 Function.RefQualifierLoc = RefQualifierLoc;
2636
2637 Diag(RefQualifierLoc, diag::err_declspec_after_virtspec)
2638 << (RefQualifierIsLValueRef ? "&" : "&&")
2640 << FixItHint::CreateRemoval(RefQualifierLoc) << Insertion;
2641 D.SetRangeEnd(RefQualifierLoc);
2642 }
2643 }
2644}
2645
2646Parser::DeclGroupPtrTy Parser::ParseCXXClassMemberDeclaration(
2647 AccessSpecifier AS, ParsedAttributes &AccessAttrs,
2648 ParsedTemplateInfo &TemplateInfo, ParsingDeclRAIIObject *TemplateDiags) {
2649 assert(getLangOpts().CPlusPlus &&
2650 "ParseCXXClassMemberDeclaration should only be called in C++ mode");
2651 if (Tok.is(tok::at)) {
2652 if (getLangOpts().ObjC && NextToken().isObjCAtKeyword(tok::objc_defs))
2653 Diag(Tok, diag::err_at_defs_cxx);
2654 else
2655 Diag(Tok, diag::err_at_in_class);
2656
2657 ConsumeToken();
2658 SkipUntil(tok::r_brace, StopAtSemi);
2659 return nullptr;
2660 }
2661
2662 // Turn on colon protection early, while parsing declspec, although there is
2663 // nothing to protect there. It prevents from false errors if error recovery
2664 // incorrectly determines where the declspec ends, as in the example:
2665 // struct A { enum class B { C }; };
2666 // const int C = 4;
2667 // struct D { A::B : C; };
2669
2670 // Access declarations.
2671 bool MalformedTypeSpec = false;
2672 if (TemplateInfo.Kind == ParsedTemplateKind::NonTemplate &&
2673 Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw___super)) {
2675 MalformedTypeSpec = true;
2676
2677 bool isAccessDecl;
2678 if (Tok.isNot(tok::annot_cxxscope))
2679 isAccessDecl = false;
2680 else if (NextToken().is(tok::identifier))
2681 isAccessDecl = GetLookAheadToken(2).is(tok::semi);
2682 else
2683 isAccessDecl = NextToken().is(tok::kw_operator);
2684
2685 if (isAccessDecl) {
2686 // Collect the scope specifier token we annotated earlier.
2687 CXXScopeSpec SS;
2688 ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
2689 /*ObjectHasErrors=*/false,
2690 /*EnteringContext=*/false);
2691
2692 if (SS.isInvalid()) {
2693 SkipUntil(tok::semi);
2694 return nullptr;
2695 }
2696
2697 // Try to parse an unqualified-id.
2698 SourceLocation TemplateKWLoc;
2699 UnqualifiedId Name;
2700 if (ParseUnqualifiedId(SS, /*ObjectType=*/nullptr,
2701 /*ObjectHadErrors=*/false, false, true, true,
2702 false, &TemplateKWLoc, Name)) {
2703 SkipUntil(tok::semi);
2704 return nullptr;
2705 }
2706
2707 // TODO: recover from mistakenly-qualified operator declarations.
2708 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
2709 "access declaration")) {
2710 SkipUntil(tok::semi);
2711 return nullptr;
2712 }
2713
2714 // FIXME: We should do something with the 'template' keyword here.
2715 return DeclGroupPtrTy::make(DeclGroupRef(Actions.ActOnUsingDeclaration(
2716 getCurScope(), AS, /*UsingLoc*/ SourceLocation(),
2717 /*TypenameLoc*/ SourceLocation(), SS, Name,
2718 /*EllipsisLoc*/ SourceLocation(),
2719 /*AttrList*/ ParsedAttributesView())));
2720 }
2721 }
2722
2723 // static_assert-declaration. A templated static_assert declaration is
2724 // diagnosed in Parser::ParseDeclarationAfterTemplate.
2725 if (TemplateInfo.Kind == ParsedTemplateKind::NonTemplate &&
2726 Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert)) {
2727 SourceLocation DeclEnd;
2728 return DeclGroupPtrTy::make(
2729 DeclGroupRef(ParseStaticAssertDeclaration(DeclEnd)));
2730 }
2731
2732 if (Tok.is(tok::kw_template)) {
2733 assert(!TemplateInfo.TemplateParams &&
2734 "Nested template improperly parsed?");
2735 ObjCDeclContextSwitch ObjCDC(*this);
2736 SourceLocation DeclEnd;
2737 return ParseTemplateDeclarationOrSpecialization(DeclaratorContext::Member,
2738 DeclEnd, AccessAttrs, AS);
2739 }
2740
2741 // Handle: member-declaration ::= '__extension__' member-declaration
2742 if (Tok.is(tok::kw___extension__)) {
2743 // __extension__ silences extension warnings in the subexpression.
2744 ExtensionRAIIObject O(Diags); // Use RAII to do this.
2745 ConsumeToken();
2746 return ParseCXXClassMemberDeclaration(AS, AccessAttrs, TemplateInfo,
2747 TemplateDiags);
2748 }
2749
2750 ParsedAttributes DeclAttrs(AttrFactory);
2751 // Optional C++11 attribute-specifier
2752 MaybeParseCXX11Attributes(DeclAttrs);
2753
2754 // The next token may be an OpenMP pragma annotation token. That would
2755 // normally be handled from ParseCXXClassMemberDeclarationWithPragmas, but in
2756 // this case, it came from an *attribute* rather than a pragma. Handle it now.
2757 if (Tok.is(tok::annot_attr_openmp))
2758 return ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, DeclAttrs);
2759
2760 if (Tok.is(tok::kw_using)) {
2761 // Eat 'using'.
2762 SourceLocation UsingLoc = ConsumeToken();
2763
2764 // Consume unexpected 'template' keywords.
2765 while (Tok.is(tok::kw_template)) {
2766 SourceLocation TemplateLoc = ConsumeToken();
2767 Diag(TemplateLoc, diag::err_unexpected_template_after_using)
2768 << FixItHint::CreateRemoval(TemplateLoc);
2769 }
2770
2771 if (Tok.is(tok::kw_namespace)) {
2772 Diag(UsingLoc, diag::err_using_namespace_in_class);
2773 SkipUntil(tok::semi, StopBeforeMatch);
2774 return nullptr;
2775 }
2776 SourceLocation DeclEnd;
2777 // Otherwise, it must be a using-declaration or an alias-declaration.
2778 return ParseUsingDeclaration(DeclaratorContext::Member, TemplateInfo,
2779 UsingLoc, DeclEnd, DeclAttrs, AS);
2780 }
2781
2782 ParsedAttributes DeclSpecAttrs(AttrFactory);
2783 // Hold late-parsed attributes so we can attach a Decl to them later.
2784 LateParsedAttrList CommonLateParsedAttrs;
2785
2786 while (MaybeParseCXX11Attributes(DeclAttrs) ||
2787 MaybeParseGNUAttributes(DeclSpecAttrs, &CommonLateParsedAttrs) ||
2788 MaybeParseMicrosoftAttributes(DeclSpecAttrs))
2789 ;
2790
2791 SourceLocation DeclStart;
2792 if (DeclAttrs.Range.isValid()) {
2793 DeclStart = DeclSpecAttrs.Range.isInvalid()
2794 ? DeclAttrs.Range.getBegin()
2795 : std::min(DeclAttrs.Range.getBegin(),
2796 DeclSpecAttrs.Range.getBegin());
2797 } else {
2798 DeclStart = DeclSpecAttrs.Range.getBegin();
2799 }
2800
2801 // decl-specifier-seq:
2802 // Parse the common declaration-specifiers piece.
2803 ParsingDeclSpec DS(*this, TemplateDiags);
2804 DS.takeAttributesAppendingingFrom(DeclSpecAttrs);
2805
2806 if (MalformedTypeSpec)
2807 DS.SetTypeSpecError();
2808
2809 // Turn off usual access checking for templates explicit specialization
2810 // and instantiation.
2811 // C++20 [temp.spec] 13.9/6.
2812 // This disables the access checking rules for member function template
2813 // explicit instantiation and explicit specialization.
2814 bool IsTemplateSpecOrInst =
2815 (TemplateInfo.Kind == ParsedTemplateKind::ExplicitInstantiation ||
2816 TemplateInfo.Kind == ParsedTemplateKind::ExplicitSpecialization);
2817 SuppressAccessChecks diagsFromTag(*this, IsTemplateSpecOrInst);
2818
2819 ParseDeclarationSpecifiers(DS, TemplateInfo, AS, DeclSpecContext::DSC_class,
2820 &CommonLateParsedAttrs);
2821
2822 if (IsTemplateSpecOrInst)
2823 diagsFromTag.done();
2824
2825 // Turn off colon protection that was set for declspec.
2826 X.restore();
2827
2828 if (DeclStart.isValid())
2829 DS.SetRangeStart(DeclStart);
2830
2831 // If we had a free-standing type definition with a missing semicolon, we
2832 // may get this far before the problem becomes obvious.
2833 if (DS.hasTagDefinition() &&
2834 TemplateInfo.Kind == ParsedTemplateKind::NonTemplate &&
2835 DiagnoseMissingSemiAfterTagDefinition(DS, AS, DeclSpecContext::DSC_class,
2836 &CommonLateParsedAttrs))
2837 return nullptr;
2838
2839 MultiTemplateParamsArg TemplateParams(
2840 TemplateInfo.TemplateParams ? TemplateInfo.TemplateParams->data()
2841 : nullptr,
2842 TemplateInfo.TemplateParams ? TemplateInfo.TemplateParams->size() : 0);
2843
2844 if (TryConsumeToken(tok::semi)) {
2845 if (DS.isFriendSpecified())
2846 ProhibitAttributes(DeclAttrs);
2847
2848 RecordDecl *AnonRecord = nullptr;
2849 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(
2850 getCurScope(), AS, DS, DeclAttrs, TemplateParams, false, AnonRecord);
2851 Actions.ActOnDefinedDeclarationSpecifier(TheDecl);
2852 DS.complete(TheDecl);
2853 if (AnonRecord) {
2854 Decl *decls[] = {AnonRecord, TheDecl};
2855 return Actions.BuildDeclaratorGroup(decls);
2856 }
2857 return Actions.ConvertDeclToDeclGroup(TheDecl);
2858 }
2859
2860 if (DS.hasTagDefinition())
2861 Actions.ActOnDefinedDeclarationSpecifier(DS.getRepAsDecl());
2862
2863 // Handle C++26's variadic friend declarations. These don't even have
2864 // declarators, so we get them out of the way early here.
2865 if (DS.isFriendSpecifiedFirst() && Tok.isOneOf(tok::comma, tok::ellipsis)) {
2866 Diag(Tok.getLocation(), getLangOpts().CPlusPlus26
2867 ? diag::warn_cxx23_variadic_friends
2868 : diag::ext_variadic_friends);
2869
2870 SourceLocation FriendLoc = DS.getFriendSpecLoc();
2871 SmallVector<Decl *> Decls;
2872
2873 // Handles a single friend-type-specifier.
2874 auto ParsedFriendDecl = [&](ParsingDeclSpec &DeclSpec) {
2875 SourceLocation VariadicLoc;
2876 TryConsumeToken(tok::ellipsis, VariadicLoc);
2877
2878 RecordDecl *AnonRecord = nullptr;
2879 Decl *D = Actions.ParsedFreeStandingDeclSpec(
2880 getCurScope(), AS, DeclSpec, DeclAttrs, TemplateParams, false,
2881 AnonRecord, VariadicLoc);
2882 DeclSpec.complete(D);
2883 if (!D) {
2884 SkipUntil(tok::semi, tok::r_brace);
2885 return true;
2886 }
2887
2888 Decls.push_back(D);
2889 return false;
2890 };
2891
2892 if (ParsedFriendDecl(DS))
2893 return nullptr;
2894
2895 while (TryConsumeToken(tok::comma)) {
2896 ParsingDeclSpec DeclSpec(*this, TemplateDiags);
2897 const char *PrevSpec = nullptr;
2898 unsigned DiagId = 0;
2899 DeclSpec.SetFriendSpec(FriendLoc, PrevSpec, DiagId);
2900 ParseDeclarationSpecifiers(DeclSpec, TemplateInfo, AS,
2901 DeclSpecContext::DSC_class, nullptr);
2902 if (ParsedFriendDecl(DeclSpec))
2903 return nullptr;
2904 }
2905
2906 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_stmt,
2907 "friend declaration");
2908
2909 return Actions.BuildDeclaratorGroup(Decls);
2910 }
2911
2912 // Befriending a concept is invalid and would already fail if
2913 // we did nothing here, but this allows us to issue a more
2914 // helpful diagnostic.
2915 if (Tok.is(tok::kw_concept)) {
2916 Diag(
2917 Tok.getLocation(),
2918 DS.isFriendSpecified() || NextToken().is(tok::kw_friend)
2919 ? llvm::to_underlying(diag::err_friend_concept)
2920 : llvm::to_underlying(
2921 diag::
2922 err_concept_decls_may_only_appear_in_global_namespace_scope));
2923 SkipUntil(tok::semi, tok::r_brace, StopBeforeMatch);
2924 return nullptr;
2925 }
2926
2927 ParsingDeclarator DeclaratorInfo(*this, DS, DeclAttrs,
2929 if (TemplateInfo.TemplateParams)
2930 DeclaratorInfo.setTemplateParameterLists(TemplateParams);
2931 VirtSpecifiers VS;
2932
2933 // Hold late-parsed attributes so we can attach a Decl to them later.
2934 LateParsedAttrList LateParsedAttrs;
2935
2936 SourceLocation EqualLoc;
2937 SourceLocation PureSpecLoc;
2938
2939 auto TryConsumePureSpecifier = [&](bool AllowDefinition) {
2940 if (Tok.isNot(tok::equal))
2941 return false;
2942
2943 auto &Zero = NextToken();
2944 SmallString<8> Buffer;
2945 if (Zero.isNot(tok::numeric_constant) ||
2946 PP.getSpelling(Zero, Buffer) != "0")
2947 return false;
2948
2949 auto &After = GetLookAheadToken(2);
2950 if (!After.isOneOf(tok::semi, tok::comma) &&
2951 !(AllowDefinition &&
2952 After.isOneOf(tok::l_brace, tok::colon, tok::kw_try)))
2953 return false;
2954
2955 EqualLoc = ConsumeToken();
2956 PureSpecLoc = ConsumeToken();
2957 return true;
2958 };
2959
2960 SmallVector<Decl *, 8> DeclsInGroup;
2961 ExprResult BitfieldSize;
2962 ExprResult TrailingRequiresClause;
2963 bool ExpectSemi = true;
2964
2965 // C++20 [temp.spec] 13.9/6.
2966 // This disables the access checking rules for member function template
2967 // explicit instantiation and explicit specialization.
2968 SuppressAccessChecks SAC(*this, IsTemplateSpecOrInst);
2969
2970 // Parse the first declarator.
2971 if (ParseCXXMemberDeclaratorBeforeInitializer(
2972 DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs)) {
2973 TryConsumeToken(tok::semi);
2974 return nullptr;
2975 }
2976
2977 if (IsTemplateSpecOrInst)
2978 SAC.done();
2979
2980 // Check for a member function definition.
2981 if (BitfieldSize.isUnset()) {
2982 // MSVC permits pure specifier on inline functions defined at class scope.
2983 // Hence check for =0 before checking for function definition.
2984 if (getLangOpts().MicrosoftExt && DeclaratorInfo.isDeclarationOfFunction())
2985 TryConsumePureSpecifier(/*AllowDefinition*/ true);
2986
2988 // function-definition:
2989 //
2990 // In C++11, a non-function declarator followed by an open brace is a
2991 // braced-init-list for an in-class member initialization, not an
2992 // erroneous function definition.
2993 if (Tok.is(tok::l_brace) && !getLangOpts().CPlusPlus11) {
2994 DefinitionKind = FunctionDefinitionKind::Definition;
2995 } else if (DeclaratorInfo.isFunctionDeclarator()) {
2996 if (Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try)) {
2997 DefinitionKind = FunctionDefinitionKind::Definition;
2998 } else if (Tok.is(tok::equal)) {
2999 const Token &KW = NextToken();
3000 if (KW.is(tok::kw_default))
3001 DefinitionKind = FunctionDefinitionKind::Defaulted;
3002 else if (KW.is(tok::kw_delete))
3003 DefinitionKind = FunctionDefinitionKind::Deleted;
3004 else if (KW.is(tok::code_completion)) {
3005 cutOffParsing();
3006 Actions.CodeCompletion().CodeCompleteAfterFunctionEquals(
3007 DeclaratorInfo);
3008 return nullptr;
3009 }
3010 }
3011 }
3012 DeclaratorInfo.setFunctionDefinitionKind(DefinitionKind);
3013
3014 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
3015 // to a friend declaration, that declaration shall be a definition.
3016 if (DeclaratorInfo.isFunctionDeclarator() &&
3017 DefinitionKind == FunctionDefinitionKind::Declaration &&
3018 DS.isFriendSpecified()) {
3019 // Diagnose attributes that appear before decl specifier:
3020 // [[]] friend int foo();
3021 ProhibitAttributes(DeclAttrs);
3022 }
3023
3024 if (DefinitionKind != FunctionDefinitionKind::Declaration) {
3025 if (!DeclaratorInfo.isFunctionDeclarator()) {
3026 Diag(DeclaratorInfo.getIdentifierLoc(), diag::err_func_def_no_params);
3027 ConsumeBrace();
3028 SkipUntil(tok::r_brace);
3029
3030 // Consume the optional ';'
3031 TryConsumeToken(tok::semi);
3032
3033 return nullptr;
3034 }
3035
3037 Diag(DeclaratorInfo.getIdentifierLoc(),
3038 diag::err_function_declared_typedef);
3039
3040 // Recover by treating the 'typedef' as spurious.
3042 }
3043
3044 Decl *FunDecl = ParseCXXInlineMethodDef(AS, AccessAttrs, DeclaratorInfo,
3045 TemplateInfo, VS, PureSpecLoc);
3046
3047 if (FunDecl) {
3048 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i) {
3049 CommonLateParsedAttrs[i]->addDecl(FunDecl);
3050 }
3051 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i) {
3052 LateParsedAttrs[i]->addDecl(FunDecl);
3053 }
3054 }
3055 LateParsedAttrs.clear();
3056
3057 // Consume the ';' - it's optional unless we have a delete or default
3058 if (Tok.is(tok::semi))
3060
3061 return DeclGroupPtrTy::make(DeclGroupRef(FunDecl));
3062 }
3063 }
3064
3065 // member-declarator-list:
3066 // member-declarator
3067 // member-declarator-list ',' member-declarator
3068
3069 while (true) {
3070 InClassInitStyle HasInClassInit = ICIS_NoInit;
3071 bool HasStaticInitializer = false;
3072 if (Tok.isOneOf(tok::equal, tok::l_brace) && PureSpecLoc.isInvalid()) {
3073 // DRXXXX: Anonymous bit-fields cannot have a brace-or-equal-initializer.
3074 if (BitfieldSize.isUsable() && !DeclaratorInfo.hasName()) {
3075 // Diagnose the error and pretend there is no in-class initializer.
3076 Diag(Tok, diag::err_anon_bitfield_member_init);
3077 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
3078 } else if (DeclaratorInfo.isDeclarationOfFunction()) {
3079 // It's a pure-specifier.
3080 if (!TryConsumePureSpecifier(/*AllowFunctionDefinition*/ false))
3081 // Parse it as an expression so that Sema can diagnose it.
3082 HasStaticInitializer = true;
3083 } else if (DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
3085 DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
3087 !DS.isFriendSpecified() &&
3088 TemplateInfo.Kind == ParsedTemplateKind::NonTemplate) {
3089 // It's a default member initializer.
3090 if (BitfieldSize.get())
3092 ? diag::warn_cxx17_compat_bitfield_member_init
3093 : diag::ext_bitfield_member_init);
3094 HasInClassInit = Tok.is(tok::equal) ? ICIS_CopyInit : ICIS_ListInit;
3095 } else {
3096 HasStaticInitializer = true;
3097 }
3098 }
3099
3100 // NOTE: If Sema is the Action module and declarator is an instance field,
3101 // this call will *not* return the created decl; It will return null.
3102 // See Sema::ActOnCXXMemberDeclarator for details.
3103
3104 NamedDecl *ThisDecl = nullptr;
3105 if (DS.isFriendSpecified()) {
3106 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
3107 // to a friend declaration, that declaration shall be a definition.
3108 //
3109 // Diagnose attributes that appear in a friend member function declarator:
3110 // friend int foo [[]] ();
3111 for (const ParsedAttr &AL : DeclaratorInfo.getAttributes())
3112 if (AL.isCXX11Attribute() || AL.isRegularKeywordAttribute()) {
3113 auto Loc = AL.getRange().getBegin();
3114 (AL.isRegularKeywordAttribute()
3115 ? Diag(Loc, diag::err_keyword_not_allowed) << AL
3116 : Diag(Loc, diag::err_attributes_not_allowed))
3117 << AL.getRange();
3118 }
3119
3120 ThisDecl = Actions.ActOnFriendFunctionDecl(getCurScope(), DeclaratorInfo,
3121 TemplateParams);
3122 } else {
3123 ThisDecl = Actions.ActOnCXXMemberDeclarator(
3124 getCurScope(), AS, DeclaratorInfo, TemplateParams, BitfieldSize.get(),
3125 VS, HasInClassInit);
3126
3127 if (VarTemplateDecl *VT =
3128 ThisDecl ? dyn_cast<VarTemplateDecl>(ThisDecl) : nullptr)
3129 // Re-direct this decl to refer to the templated decl so that we can
3130 // initialize it.
3131 ThisDecl = VT->getTemplatedDecl();
3132
3133 if (ThisDecl)
3134 Actions.ProcessDeclAttributeList(getCurScope(), ThisDecl, AccessAttrs);
3135 }
3136
3137 // Error recovery might have converted a non-static member into a static
3138 // member.
3139 if (HasInClassInit != ICIS_NoInit &&
3140 DeclaratorInfo.getDeclSpec().getStorageClassSpec() ==
3142 HasInClassInit = ICIS_NoInit;
3143 HasStaticInitializer = true;
3144 }
3145
3146 if (PureSpecLoc.isValid() && VS.getAbstractLoc().isValid()) {
3147 Diag(PureSpecLoc, diag::err_duplicate_virt_specifier) << "abstract";
3148 }
3149 if (ThisDecl && PureSpecLoc.isValid())
3150 Actions.ActOnPureSpecifier(ThisDecl, PureSpecLoc);
3151 else if (ThisDecl && VS.getAbstractLoc().isValid())
3152 Actions.ActOnPureSpecifier(ThisDecl, VS.getAbstractLoc());
3153
3154 // Handle the initializer.
3155 if (HasInClassInit != ICIS_NoInit) {
3156 // The initializer was deferred; parse it and cache the tokens.
3158 ? diag::warn_cxx98_compat_nonstatic_member_init
3159 : diag::ext_nonstatic_member_init);
3160
3161 if (DeclaratorInfo.isArrayOfUnknownBound()) {
3162 // C++11 [dcl.array]p3: An array bound may also be omitted when the
3163 // declarator is followed by an initializer.
3164 //
3165 // A brace-or-equal-initializer for a member-declarator is not an
3166 // initializer in the grammar, so this is ill-formed.
3167 Diag(Tok, diag::err_incomplete_array_member_init);
3168 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
3169
3170 // Avoid later warnings about a class member of incomplete type.
3171 if (ThisDecl)
3172 ThisDecl->setInvalidDecl();
3173 } else
3174 ParseCXXNonStaticMemberInitializer(ThisDecl);
3175 } else if (HasStaticInitializer) {
3176 // Normal initializer.
3177 ExprResult Init = ParseCXXMemberInitializer(
3178 ThisDecl, DeclaratorInfo.isDeclarationOfFunction(), EqualLoc);
3179
3180 if (Init.isInvalid()) {
3181 if (ThisDecl)
3182 Actions.ActOnUninitializedDecl(ThisDecl);
3183 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
3184 } else if (ThisDecl)
3185 Actions.AddInitializerToDecl(ThisDecl, Init.get(),
3186 EqualLoc.isInvalid());
3187 } else if (ThisDecl && DeclaratorInfo.isStaticMember())
3188 // No initializer.
3189 Actions.ActOnUninitializedDecl(ThisDecl);
3190
3191 if (ThisDecl) {
3192 if (!ThisDecl->isInvalidDecl()) {
3193 // Set the Decl for any late parsed attributes
3194 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i)
3195 CommonLateParsedAttrs[i]->addDecl(ThisDecl);
3196
3197 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i)
3198 LateParsedAttrs[i]->addDecl(ThisDecl);
3199 }
3200 Actions.FinalizeDeclaration(ThisDecl);
3201 DeclsInGroup.push_back(ThisDecl);
3202
3203 if (DeclaratorInfo.isFunctionDeclarator() &&
3204 DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
3206 HandleMemberFunctionDeclDelays(DeclaratorInfo, ThisDecl);
3207 }
3208 LateParsedAttrs.clear();
3209
3210 DeclaratorInfo.complete(ThisDecl);
3211
3212 // If we don't have a comma, it is either the end of the list (a ';')
3213 // or an error, bail out.
3214 SourceLocation CommaLoc;
3215 if (!TryConsumeToken(tok::comma, CommaLoc))
3216 break;
3217
3218 if (Tok.isAtStartOfLine() &&
3219 !MightBeDeclarator(DeclaratorContext::Member)) {
3220 // This comma was followed by a line-break and something which can't be
3221 // the start of a declarator. The comma was probably a typo for a
3222 // semicolon.
3223 Diag(CommaLoc, diag::err_expected_semi_declaration)
3224 << FixItHint::CreateReplacement(CommaLoc, ";");
3225 ExpectSemi = false;
3226 break;
3227 }
3228
3229 // C++23 [temp.pre]p5:
3230 // In a template-declaration, explicit specialization, or explicit
3231 // instantiation the init-declarator-list in the declaration shall
3232 // contain at most one declarator.
3233 if (TemplateInfo.Kind != ParsedTemplateKind::NonTemplate &&
3234 DeclaratorInfo.isFirstDeclarator()) {
3235 Diag(CommaLoc, diag::err_multiple_template_declarators)
3236 << TemplateInfo.Kind;
3237 }
3238
3239 // Parse the next declarator.
3240 DeclaratorInfo.clear();
3241 VS.clear();
3242 BitfieldSize = ExprResult(/*Invalid=*/false);
3243 EqualLoc = PureSpecLoc = SourceLocation();
3244 DeclaratorInfo.setCommaLoc(CommaLoc);
3245
3246 // GNU attributes are allowed before the second and subsequent declarator.
3247 // However, this does not apply for [[]] attributes (which could show up
3248 // before or after the __attribute__ attributes).
3249 DiagnoseAndSkipCXX11Attributes();
3250 MaybeParseGNUAttributes(DeclaratorInfo);
3251 DiagnoseAndSkipCXX11Attributes();
3252
3253 if (ParseCXXMemberDeclaratorBeforeInitializer(
3254 DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs))
3255 break;
3256 }
3257
3258 if (ExpectSemi &&
3259 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list) &&
3260 !isLikelyAtStartOfNewDeclaration()) {
3261 // Skip to end of block or statement.
3262 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
3263 // If we stopped at a ';', eat it.
3264 TryConsumeToken(tok::semi);
3265 return nullptr;
3266 }
3267
3268 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
3269}
3270
3271ExprResult Parser::ParseCXXMemberInitializer(Decl *D, bool IsFunction,
3272 SourceLocation &EqualLoc) {
3273 assert(Tok.isOneOf(tok::equal, tok::l_brace) &&
3274 "Data member initializer not starting with '=' or '{'");
3275
3276 bool IsFieldInitialization = isa_and_present<FieldDecl>(D);
3277
3278 EnterExpressionEvaluationContext Context(
3279 Actions,
3280 IsFieldInitialization
3283 D);
3284
3285 // CWG2760
3286 // Default member initializers used to initialize a base or member subobject
3287 // [...] are considered to be part of the function body
3288 Actions.ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
3289 IsFieldInitialization;
3290
3291 if (TryConsumeToken(tok::equal, EqualLoc)) {
3292 if (Tok.is(tok::kw_delete)) {
3293 // In principle, an initializer of '= delete p;' is legal, but it will
3294 // never type-check. It's better to diagnose it as an ill-formed
3295 // expression than as an ill-formed deleted non-function member. An
3296 // initializer of '= delete p, foo' will never be parsed, because a
3297 // top-level comma always ends the initializer expression.
3298 const Token &Next = NextToken();
3299 if (IsFunction || Next.isOneOf(tok::semi, tok::comma, tok::eof)) {
3300 if (IsFunction)
3301 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
3302 << 1 /* delete */;
3303 else
3304 Diag(ConsumeToken(), diag::err_deleted_non_function);
3305 SkipDeletedFunctionBody();
3306 return ExprError();
3307 }
3308 } else if (Tok.is(tok::kw_default)) {
3309 if (IsFunction)
3310 Diag(Tok, diag::err_default_delete_in_multiple_declaration)
3311 << 0 /* default */;
3312 else
3313 Diag(ConsumeToken(), diag::err_default_special_members)
3314 << getLangOpts().CPlusPlus20;
3315 return ExprError();
3316 }
3317 }
3318 if (const auto *PD = dyn_cast_or_null<MSPropertyDecl>(D)) {
3319 Diag(Tok, diag::err_ms_property_initializer) << PD;
3320 return ExprError();
3321 }
3322 return ParseInitializer(D);
3323}
3324
3325void Parser::SkipCXXMemberSpecification(SourceLocation RecordLoc,
3326 SourceLocation AttrFixitLoc,
3327 unsigned TagType, Decl *TagDecl) {
3328 // Skip the optional 'final' keyword.
3329 while (isClassCompatibleKeyword())
3330 ConsumeToken();
3331
3332 // Diagnose any C++11 attributes after 'final' keyword.
3333 // We deliberately discard these attributes.
3334 ParsedAttributes Attrs(AttrFactory);
3335 CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
3336
3337 // This can only happen if we had malformed misplaced attributes;
3338 // we only get called if there is a colon or left-brace after the
3339 // attributes.
3340 if (Tok.isNot(tok::colon) && Tok.isNot(tok::l_brace))
3341 return;
3342
3343 // Skip the base clauses. This requires actually parsing them, because
3344 // otherwise we can't be sure where they end (a left brace may appear
3345 // within a template argument).
3346 if (Tok.is(tok::colon)) {
3347 // Enter the scope of the class so that we can correctly parse its bases.
3348 ParseScope ClassScope(this, Scope::ClassScope | Scope::DeclScope);
3349 ParsingClassDefinition ParsingDef(*this, TagDecl, /*NonNestedClass*/ true,
3350 TagType == DeclSpec::TST_interface);
3351 auto OldContext =
3352 Actions.ActOnTagStartSkippedDefinition(getCurScope(), TagDecl);
3353
3354 // Parse the bases but don't attach them to the class.
3355 ParseBaseClause(nullptr);
3356
3357 Actions.ActOnTagFinishSkippedDefinition(OldContext);
3358
3359 if (!Tok.is(tok::l_brace)) {
3360 Diag(PP.getLocForEndOfToken(PrevTokLocation),
3361 diag::err_expected_lbrace_after_base_specifiers);
3362 return;
3363 }
3364 }
3365
3366 // Skip the body.
3367 assert(Tok.is(tok::l_brace));
3368 BalancedDelimiterTracker T(*this, tok::l_brace);
3369 T.consumeOpen();
3370 T.skipToEnd();
3371
3372 // Parse and discard any trailing attributes.
3373 if (Tok.is(tok::kw___attribute)) {
3374 ParsedAttributes Attrs(AttrFactory);
3375 MaybeParseGNUAttributes(Attrs);
3376 }
3377}
3378
3379Parser::DeclGroupPtrTy Parser::ParseCXXClassMemberDeclarationWithPragmas(
3380 AccessSpecifier &AS, ParsedAttributes &AccessAttrs, DeclSpec::TST TagType,
3381 Decl *TagDecl) {
3382 ParenBraceBracketBalancer BalancerRAIIObj(*this);
3383
3384 switch (Tok.getKind()) {
3385 case tok::kw___if_exists:
3386 case tok::kw___if_not_exists:
3387 ParseMicrosoftIfExistsClassDeclaration(TagType, AccessAttrs, AS);
3388 return nullptr;
3389
3390 case tok::semi:
3391 // Check for extraneous top-level semicolon.
3392 ConsumeExtraSemi(ExtraSemiKind::InsideStruct, TagType);
3393 return nullptr;
3394
3395 // Handle pragmas that can appear as member declarations.
3396 case tok::annot_pragma_vis:
3397 HandlePragmaVisibility();
3398 return nullptr;
3399 case tok::annot_pragma_pack:
3400 HandlePragmaPack();
3401 return nullptr;
3402 case tok::annot_pragma_align:
3403 HandlePragmaAlign();
3404 return nullptr;
3405 case tok::annot_pragma_ms_pointers_to_members:
3406 HandlePragmaMSPointersToMembers();
3407 return nullptr;
3408 case tok::annot_pragma_ms_pragma:
3409 HandlePragmaMSPragma();
3410 return nullptr;
3411 case tok::annot_pragma_ms_vtordisp:
3412 HandlePragmaMSVtorDisp();
3413 return nullptr;
3414 case tok::annot_pragma_export:
3415 HandlePragmaExport();
3416 return nullptr;
3417 case tok::annot_pragma_dump:
3418 HandlePragmaDump();
3419 return nullptr;
3420
3421 case tok::kw_namespace:
3422 // If we see a namespace here, a close brace was missing somewhere.
3423 DiagnoseUnexpectedNamespace(cast<NamedDecl>(TagDecl));
3424 return nullptr;
3425
3426 case tok::kw_private:
3427 // FIXME: We don't accept GNU attributes on access specifiers in OpenCL mode
3428 // yet.
3429 if (getLangOpts().OpenCL && !NextToken().is(tok::colon)) {
3430 ParsedTemplateInfo TemplateInfo;
3431 return ParseCXXClassMemberDeclaration(AS, AccessAttrs, TemplateInfo);
3432 }
3433 [[fallthrough]];
3434 case tok::kw_public:
3435 case tok::kw_protected: {
3436 if (getLangOpts().HLSL)
3437 Diag(Tok.getLocation(), diag::ext_hlsl_access_specifiers);
3438 AccessSpecifier NewAS = getAccessSpecifierIfPresent();
3439 assert(NewAS != AS_none);
3440 // Current token is a C++ access specifier.
3441 AS = NewAS;
3442 SourceLocation ASLoc = Tok.getLocation();
3443 unsigned TokLength = Tok.getLength();
3444 ConsumeToken();
3445 AccessAttrs.clear();
3446 MaybeParseGNUAttributes(AccessAttrs);
3447
3448 SourceLocation EndLoc;
3449 if (TryConsumeToken(tok::colon, EndLoc)) {
3450 } else if (TryConsumeToken(tok::semi, EndLoc)) {
3451 Diag(EndLoc, diag::err_expected)
3452 << tok::colon << FixItHint::CreateReplacement(EndLoc, ":");
3453 } else {
3454 EndLoc = ASLoc.getLocWithOffset(TokLength);
3455 Diag(EndLoc, diag::err_expected)
3456 << tok::colon << FixItHint::CreateInsertion(EndLoc, ":");
3457 }
3458
3459 // The Microsoft extension __interface does not permit non-public
3460 // access specifiers.
3461 if (TagType == DeclSpec::TST_interface && AS != AS_public) {
3462 Diag(ASLoc, diag::err_access_specifier_interface) << (AS == AS_protected);
3463 }
3464
3465 if (Actions.ActOnAccessSpecifier(NewAS, ASLoc, EndLoc, AccessAttrs)) {
3466 // found another attribute than only annotations
3467 AccessAttrs.clear();
3468 }
3469
3470 return nullptr;
3471 }
3472
3473 case tok::annot_attr_openmp:
3474 case tok::annot_pragma_openmp:
3475 return ParseOpenMPDeclarativeDirectiveWithExtDecl(
3476 AS, AccessAttrs, /*Delayed=*/true, TagType, TagDecl);
3477 case tok::annot_pragma_openacc:
3478 return ParseOpenACCDirectiveDecl(AS, AccessAttrs, TagType, TagDecl);
3479
3480 default:
3481 if (tok::isPragmaAnnotation(Tok.getKind())) {
3482 Diag(Tok.getLocation(), diag::err_pragma_misplaced_in_decl)
3484 TagType, Actions.getASTContext().getPrintingPolicy());
3485 ConsumeAnnotationToken();
3486 return nullptr;
3487 }
3488 ParsedTemplateInfo TemplateInfo;
3489 return ParseCXXClassMemberDeclaration(AS, AccessAttrs, TemplateInfo);
3490 }
3491}
3492
3493void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc,
3494 SourceLocation AttrFixitLoc,
3495 ParsedAttributes &Attrs,
3496 unsigned TagType, Decl *TagDecl) {
3497 assert((TagType == DeclSpec::TST_struct ||
3498 TagType == DeclSpec::TST_interface ||
3499 TagType == DeclSpec::TST_union || TagType == DeclSpec::TST_class) &&
3500 "Invalid TagType!");
3501
3502 llvm::TimeTraceScope TimeScope("ParseClass", [&]() {
3503 if (auto *TD = dyn_cast_or_null<NamedDecl>(TagDecl))
3504 return TD->getQualifiedNameAsString();
3505 return std::string("<anonymous>");
3506 });
3507
3508 PrettyDeclStackTraceEntry CrashInfo(Actions.Context, TagDecl, RecordLoc,
3509 "parsing struct/union/class body");
3510
3511 // Determine whether this is a non-nested class. Note that local
3512 // classes are *not* considered to be nested classes.
3513 bool NonNestedClass = true;
3514 if (!ClassStack.empty()) {
3515 for (const Scope *S = getCurScope(); S; S = S->getParent()) {
3516 if (S->isClassScope()) {
3517 // We're inside a class scope, so this is a nested class.
3518 NonNestedClass = false;
3519
3520 // The Microsoft extension __interface does not permit nested classes.
3521 if (getCurrentClass().IsInterface) {
3522 Diag(RecordLoc, diag::err_invalid_member_in_interface)
3523 << /*ErrorType=*/6
3524 << (isa<NamedDecl>(TagDecl)
3525 ? cast<NamedDecl>(TagDecl)->getQualifiedNameAsString()
3526 : "(anonymous)");
3527 }
3528 break;
3529 }
3530
3531 if (S->isFunctionScope())
3532 // If we're in a function or function template then this is a local
3533 // class rather than a nested class.
3534 break;
3535 }
3536 }
3537
3538 // Enter a scope for the class.
3539 ParseScope ClassScope(this, Scope::ClassScope | Scope::DeclScope);
3540
3541 // Note that we are parsing a new (potentially-nested) class definition.
3542 ParsingClassDefinition ParsingDef(*this, TagDecl, NonNestedClass,
3543 TagType == DeclSpec::TST_interface);
3544
3545 if (TagDecl)
3546 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
3547
3548 SourceLocation FinalLoc;
3549 SourceLocation AbstractLoc;
3550 bool IsFinalSpelledSealed = false;
3551 bool IsAbstract = false;
3552
3553 // Parse the optional 'final' keyword.
3554 if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
3555 while (true) {
3556 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier(Tok);
3557 if (Specifier == VirtSpecifiers::VS_None) {
3558 break;
3559 }
3560 if (isCXX11FinalKeyword()) {
3561 if (FinalLoc.isValid()) {
3562 auto Skipped = ConsumeToken();
3563 Diag(Skipped, diag::err_duplicate_class_virt_specifier)
3565 } else {
3566 FinalLoc = ConsumeToken();
3567 if (Specifier == VirtSpecifiers::VS_Sealed)
3568 IsFinalSpelledSealed = true;
3569 }
3570 } else {
3571 if (AbstractLoc.isValid()) {
3572 auto Skipped = ConsumeToken();
3573 Diag(Skipped, diag::err_duplicate_class_virt_specifier)
3575 } else {
3576 AbstractLoc = ConsumeToken();
3577 IsAbstract = true;
3578 }
3579 }
3580 if (TagType == DeclSpec::TST_interface)
3581 Diag(FinalLoc, diag::err_override_control_interface)
3583 else if (Specifier == VirtSpecifiers::VS_Final)
3584 Diag(FinalLoc, getLangOpts().CPlusPlus11
3585 ? diag::warn_cxx98_compat_override_control_keyword
3586 : diag::ext_override_control_keyword)
3588 else if (Specifier == VirtSpecifiers::VS_Sealed)
3589 Diag(FinalLoc, diag::ext_ms_sealed_keyword);
3590 else if (Specifier == VirtSpecifiers::VS_Abstract)
3591 Diag(AbstractLoc, diag::ext_ms_abstract_keyword);
3592 else if (Specifier == VirtSpecifiers::VS_GNU_Final)
3593 Diag(FinalLoc, diag::ext_warn_gnu_final);
3594 }
3595 assert((FinalLoc.isValid() || AbstractLoc.isValid()) &&
3596 "not a class definition");
3597
3598 // Parse any C++11 attributes after 'final' keyword.
3599 // These attributes are not allowed to appear here,
3600 // and the only possible place for them to appertain
3601 // to the class would be between class-key and class-name.
3602 CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
3603
3604 // ParseClassSpecifier() does only a superficial check for attributes before
3605 // deciding to call this method. For example, for
3606 // `class C final alignas ([l) {` it will decide that this looks like a
3607 // misplaced attribute since it sees `alignas '(' ')'`. But the actual
3608 // attribute parsing code will try to parse the '[' as a constexpr lambda
3609 // and consume enough tokens that the alignas parsing code will eat the
3610 // opening '{'. So bail out if the next token isn't one we expect.
3611 if (!Tok.is(tok::colon) && !Tok.is(tok::l_brace)) {
3612 if (TagDecl)
3613 Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
3614 return;
3615 }
3616 }
3617
3618 if (Tok.is(tok::colon)) {
3619 ParseScope InheritanceScope(this, getCurScope()->getFlags() |
3621
3622 ParseBaseClause(TagDecl);
3623 if (!Tok.is(tok::l_brace)) {
3624 bool SuggestFixIt = false;
3625 SourceLocation BraceLoc = PP.getLocForEndOfToken(PrevTokLocation);
3626 if (Tok.isAtStartOfLine()) {
3627 switch (Tok.getKind()) {
3628 case tok::kw_private:
3629 case tok::kw_protected:
3630 case tok::kw_public:
3631 SuggestFixIt = NextToken().getKind() == tok::colon;
3632 break;
3633 case tok::kw_static_assert:
3634 case tok::r_brace:
3635 case tok::kw_using:
3636 // base-clause can have simple-template-id; 'template' can't be there
3637 case tok::kw_template:
3638 SuggestFixIt = true;
3639 break;
3640 case tok::identifier:
3641 SuggestFixIt = isConstructorDeclarator(true);
3642 break;
3643 default:
3644 SuggestFixIt = isCXXSimpleDeclaration(/*AllowForRangeDecl=*/false);
3645 break;
3646 }
3647 }
3648 DiagnosticBuilder LBraceDiag =
3649 Diag(BraceLoc, diag::err_expected_lbrace_after_base_specifiers);
3650 if (SuggestFixIt) {
3651 LBraceDiag << FixItHint::CreateInsertion(BraceLoc, " {");
3652 // Try recovering from missing { after base-clause.
3653 PP.EnterToken(Tok, /*IsReinject*/ true);
3654 Tok.setKind(tok::l_brace);
3655 } else {
3656 if (TagDecl)
3657 Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
3658 return;
3659 }
3660 }
3661 }
3662
3663 assert(Tok.is(tok::l_brace));
3664 BalancedDelimiterTracker T(*this, tok::l_brace);
3665 T.consumeOpen();
3666
3667 if (TagDecl)
3668 Actions.ActOnStartCXXMemberDeclarations(getCurScope(), TagDecl, FinalLoc,
3669 IsFinalSpelledSealed, IsAbstract,
3670 T.getOpenLocation());
3671
3672 // C++ 11p3: Members of a class defined with the keyword class are private
3673 // by default. Members of a class defined with the keywords struct or union
3674 // are public by default.
3675 // HLSL: In HLSL members of a class are public by default.
3676 AccessSpecifier CurAS;
3677 if (TagType == DeclSpec::TST_class && !getLangOpts().HLSL)
3678 CurAS = AS_private;
3679 else
3680 CurAS = AS_public;
3681 ParsedAttributes AccessAttrs(AttrFactory);
3682
3683 if (TagDecl) {
3684 // While we still have something to read, read the member-declarations.
3685 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
3686 Tok.isNot(tok::eof)) {
3687 // Each iteration of this loop reads one member-declaration.
3688 ParseCXXClassMemberDeclarationWithPragmas(
3689 CurAS, AccessAttrs, static_cast<DeclSpec::TST>(TagType), TagDecl);
3690 MaybeDestroyTemplateIds();
3691 }
3692 T.consumeClose();
3693 } else {
3694 SkipUntil(tok::r_brace);
3695 }
3696
3697 // If attributes exist after class contents, parse them.
3698 ParsedAttributes attrs(AttrFactory);
3699 MaybeParseGNUAttributes(attrs);
3700
3701 if (TagDecl)
3702 Actions.ActOnFinishCXXMemberSpecification(getCurScope(), RecordLoc, TagDecl,
3703 T.getOpenLocation(),
3704 T.getCloseLocation(), attrs);
3705
3706 // C++11 [class.mem]p2:
3707 // Within the class member-specification, the class is regarded as complete
3708 // within function bodies, default arguments, exception-specifications, and
3709 // brace-or-equal-initializers for non-static data members (including such
3710 // things in nested classes).
3711 if (TagDecl && NonNestedClass) {
3712 // We are not inside a nested class. This class and its nested classes
3713 // are complete and we can parse the delayed portions of method
3714 // declarations and the lexed inline method definitions, along with any
3715 // delayed attributes.
3716
3717 SourceLocation SavedPrevTokLocation = PrevTokLocation;
3718 ParseLexedPragmas(getCurrentClass());
3719 ParseLexedAttributes(getCurrentClass());
3720 ParseLexedMethodDeclarations(getCurrentClass());
3721
3722 // We've finished with all pending member declarations.
3723 Actions.ActOnFinishCXXMemberDecls();
3724
3725 ParseLexedMemberInitializers(getCurrentClass());
3726 ParseLexedMethodDefs(getCurrentClass());
3727 PrevTokLocation = SavedPrevTokLocation;
3728
3729 // We've finished parsing everything, including default argument
3730 // initializers.
3731 Actions.ActOnFinishCXXNonNestedClass();
3732 }
3733
3734 if (TagDecl)
3735 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getRange());
3736
3737 // Leave the class scope.
3738 ParsingDef.Pop();
3739 ClassScope.Exit();
3740}
3741
3742void Parser::DiagnoseUnexpectedNamespace(NamedDecl *D) {
3743 assert(Tok.is(tok::kw_namespace));
3744
3745 // FIXME: Suggest where the close brace should have gone by looking
3746 // at indentation changes within the definition body.
3747 Diag(D->getLocation(), diag::err_missing_end_of_definition) << D;
3748 Diag(Tok.getLocation(), diag::note_missing_end_of_definition_before) << D;
3749
3750 // Push '};' onto the token stream to recover.
3751 PP.EnterToken(Tok, /*IsReinject*/ true);
3752
3753 Tok.startToken();
3754 Tok.setLocation(PP.getLocForEndOfToken(PrevTokLocation));
3755 Tok.setKind(tok::semi);
3756 PP.EnterToken(Tok, /*IsReinject*/ true);
3757
3758 Tok.setKind(tok::r_brace);
3759}
3760
3761void Parser::ParseConstructorInitializer(Decl *ConstructorDecl) {
3762 assert(Tok.is(tok::colon) &&
3763 "Constructor initializer always starts with ':'");
3764
3765 // Poison the SEH identifiers so they are flagged as illegal in constructor
3766 // initializers.
3767 PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
3768 SourceLocation ColonLoc = ConsumeToken();
3769
3770 SmallVector<CXXCtorInitializer *, 4> MemInitializers;
3771 bool AnyErrors = false;
3772
3773 do {
3774 if (Tok.is(tok::code_completion)) {
3775 cutOffParsing();
3776 Actions.CodeCompletion().CodeCompleteConstructorInitializer(
3777 ConstructorDecl, MemInitializers);
3778 return;
3779 }
3780
3781 MemInitResult MemInit = ParseMemInitializer(ConstructorDecl);
3782 if (!MemInit.isInvalid())
3783 MemInitializers.push_back(MemInit.get());
3784 else
3785 AnyErrors = true;
3786
3787 if (Tok.is(tok::comma))
3788 ConsumeToken();
3789 else if (Tok.is(tok::l_brace))
3790 break;
3791 // If the previous initializer was valid and the next token looks like a
3792 // base or member initializer, assume that we're just missing a comma.
3793 else if (!MemInit.isInvalid() &&
3794 Tok.isOneOf(tok::identifier, tok::coloncolon)) {
3795 SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation);
3796 Diag(Loc, diag::err_ctor_init_missing_comma)
3797 << FixItHint::CreateInsertion(Loc, ", ");
3798 } else {
3799 // Skip over garbage, until we get to '{'. Don't eat the '{'.
3800 if (!MemInit.isInvalid())
3801 Diag(Tok.getLocation(), diag::err_expected_either)
3802 << tok::l_brace << tok::comma;
3803 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
3804 break;
3805 }
3806 } while (true);
3807
3808 Actions.ActOnMemInitializers(ConstructorDecl, ColonLoc, MemInitializers,
3809 AnyErrors);
3810}
3811
3812MemInitResult Parser::ParseMemInitializer(Decl *ConstructorDecl) {
3813 // parse '::'[opt] nested-name-specifier[opt]
3814 CXXScopeSpec SS;
3815 if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
3816 /*ObjectHasErrors=*/false,
3817 /*EnteringContext=*/false))
3818 return true;
3819
3820 // : identifier
3821 IdentifierInfo *II = nullptr;
3822 SourceLocation IdLoc = Tok.getLocation();
3823 // : declype(...)
3824 DeclSpec DS(AttrFactory);
3825 // : template_name<...>
3826 TypeResult TemplateTypeTy;
3827
3828 if (Tok.is(tok::identifier)) {
3829 // Get the identifier. This may be a member name or a class name,
3830 // but we'll let the semantic analysis determine which it is.
3831 II = Tok.getIdentifierInfo();
3832 ConsumeToken();
3833 } else if (Tok.is(tok::annot_decltype)) {
3834 // Get the decltype expression, if there is one.
3835 // Uses of decltype will already have been converted to annot_decltype by
3836 // ParseOptionalCXXScopeSpecifier at this point.
3837 // FIXME: Can we get here with a scope specifier?
3838 ParseDecltypeSpecifier(DS);
3839 } else if (Tok.is(tok::annot_pack_indexing_type)) {
3840 // Uses of T...[N] will already have been converted to
3841 // annot_pack_indexing_type by ParseOptionalCXXScopeSpecifier at this point.
3842 ParsePackIndexingType(DS);
3843 } else {
3844 TemplateIdAnnotation *TemplateId = Tok.is(tok::annot_template_id)
3845 ? takeTemplateIdAnnotation(Tok)
3846 : nullptr;
3847 if (TemplateId && TemplateId->mightBeType()) {
3848 AnnotateTemplateIdTokenAsType(SS, ImplicitTypenameContext::No,
3849 /*IsClassName=*/true);
3850 assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
3851 TemplateTypeTy = getTypeAnnotation(Tok);
3852 ConsumeAnnotationToken();
3853 } else {
3854 Diag(Tok, diag::err_expected_member_or_base_name);
3855 return true;
3856 }
3857 }
3858
3859 // Parse the '('.
3860 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
3861 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
3862
3863 // FIXME: Add support for signature help inside initializer lists.
3864 ExprResult InitList = ParseBraceInitializer();
3865 if (InitList.isInvalid())
3866 return true;
3867
3868 SourceLocation EllipsisLoc;
3869 TryConsumeToken(tok::ellipsis, EllipsisLoc);
3870
3871 if (TemplateTypeTy.isInvalid())
3872 return true;
3873 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
3874 TemplateTypeTy.get(), DS, IdLoc,
3875 InitList.get(), EllipsisLoc);
3876 } else if (Tok.is(tok::l_paren)) {
3877 BalancedDelimiterTracker T(*this, tok::l_paren);
3878 T.consumeOpen();
3879
3880 // Parse the optional expression-list.
3881 ExprVector ArgExprs;
3882 auto RunSignatureHelp = [&] {
3883 if (TemplateTypeTy.isInvalid())
3884 return QualType();
3885 QualType PreferredType =
3886 Actions.CodeCompletion().ProduceCtorInitMemberSignatureHelp(
3887 ConstructorDecl, SS, TemplateTypeTy.get(), ArgExprs, II,
3888 T.getOpenLocation(), /*Braced=*/false);
3889 CalledSignatureHelp = true;
3890 return PreferredType;
3891 };
3892 if (Tok.isNot(tok::r_paren) && ParseExpressionList(ArgExprs, [&] {
3893 PreferredType.enterFunctionArgument(Tok.getLocation(),
3894 RunSignatureHelp);
3895 })) {
3896 if (PP.isCodeCompletionReached() && !CalledSignatureHelp)
3897 RunSignatureHelp();
3898 SkipUntil(tok::r_paren, StopAtSemi);
3899 return true;
3900 }
3901
3902 T.consumeClose();
3903
3904 SourceLocation EllipsisLoc;
3905 TryConsumeToken(tok::ellipsis, EllipsisLoc);
3906
3907 if (TemplateTypeTy.isInvalid())
3908 return true;
3909 return Actions.ActOnMemInitializer(
3910 ConstructorDecl, getCurScope(), SS, II, TemplateTypeTy.get(), DS, IdLoc,
3911 T.getOpenLocation(), ArgExprs, T.getCloseLocation(), EllipsisLoc);
3912 }
3913
3914 if (TemplateTypeTy.isInvalid())
3915 return true;
3916
3918 return Diag(Tok, diag::err_expected_either) << tok::l_paren << tok::l_brace;
3919 else
3920 return Diag(Tok, diag::err_expected) << tok::l_paren;
3921}
3922
3923ExceptionSpecificationType Parser::tryParseExceptionSpecification(
3924 bool Delayed, SourceRange &SpecificationRange,
3925 SmallVectorImpl<ParsedType> &DynamicExceptions,
3926 SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
3927 ExprResult &NoexceptExpr, CachedTokens *&ExceptionSpecTokens) {
3929 ExceptionSpecTokens = nullptr;
3930
3931 // Handle delayed parsing of exception-specifications.
3932 if (Delayed) {
3933 if (Tok.isNot(tok::kw_throw) && Tok.isNot(tok::kw_noexcept))
3934 return EST_None;
3935
3936 // Consume and cache the starting token.
3937 bool IsNoexcept = Tok.is(tok::kw_noexcept);
3938 Token StartTok = Tok;
3939 SpecificationRange = SourceRange(ConsumeToken());
3940
3941 // Check for a '('.
3942 if (!Tok.is(tok::l_paren)) {
3943 // If this is a bare 'noexcept', we're done.
3944 if (IsNoexcept) {
3945 Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
3946 NoexceptExpr = nullptr;
3947 return EST_BasicNoexcept;
3948 }
3949
3950 Diag(Tok, diag::err_expected_lparen_after) << "throw";
3951 return EST_DynamicNone;
3952 }
3953
3954 // Cache the tokens for the exception-specification.
3955 ExceptionSpecTokens = new CachedTokens;
3956 ExceptionSpecTokens->push_back(StartTok); // 'throw' or 'noexcept'
3957 ExceptionSpecTokens->push_back(Tok); // '('
3958 SpecificationRange.setEnd(ConsumeParen()); // '('
3959
3960 ConsumeAndStoreUntil(tok::r_paren, *ExceptionSpecTokens,
3961 /*StopAtSemi=*/true,
3962 /*ConsumeFinalToken=*/true);
3963 SpecificationRange.setEnd(ExceptionSpecTokens->back().getLocation());
3964
3965 return EST_Unparsed;
3966 }
3967
3968 // See if there's a dynamic specification.
3969 if (Tok.is(tok::kw_throw)) {
3970 Result = ParseDynamicExceptionSpecification(
3971 SpecificationRange, DynamicExceptions, DynamicExceptionRanges);
3972 assert(DynamicExceptions.size() == DynamicExceptionRanges.size() &&
3973 "Produced different number of exception types and ranges.");
3974 }
3975
3976 // If there's no noexcept specification, we're done.
3977 if (Tok.isNot(tok::kw_noexcept))
3978 return Result;
3979
3980 Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
3981
3982 // If we already had a dynamic specification, parse the noexcept for,
3983 // recovery, but emit a diagnostic and don't store the results.
3984 SourceRange NoexceptRange;
3985 ExceptionSpecificationType NoexceptType = EST_None;
3986
3987 SourceLocation KeywordLoc = ConsumeToken();
3988 if (Tok.is(tok::l_paren)) {
3989 // There is an argument.
3990 BalancedDelimiterTracker T(*this, tok::l_paren);
3991 T.consumeOpen();
3992
3993 EnterExpressionEvaluationContext ConstantEvaluated(
3996
3997 T.consumeClose();
3998 if (!NoexceptExpr.isInvalid()) {
3999 NoexceptExpr =
4000 Actions.ActOnNoexceptSpec(NoexceptExpr.get(), NoexceptType);
4001 NoexceptRange = SourceRange(KeywordLoc, T.getCloseLocation());
4002 } else {
4003 NoexceptType = EST_BasicNoexcept;
4004 }
4005 } else {
4006 // There is no argument.
4007 NoexceptType = EST_BasicNoexcept;
4008 NoexceptRange = SourceRange(KeywordLoc, KeywordLoc);
4009 }
4010
4011 if (Result == EST_None) {
4012 SpecificationRange = NoexceptRange;
4013 Result = NoexceptType;
4014
4015 // If there's a dynamic specification after a noexcept specification,
4016 // parse that and ignore the results.
4017 if (Tok.is(tok::kw_throw)) {
4018 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
4019 ParseDynamicExceptionSpecification(NoexceptRange, DynamicExceptions,
4020 DynamicExceptionRanges);
4021 }
4022 } else {
4023 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
4024 }
4025
4026 return Result;
4027}
4028
4030 bool IsNoexcept) {
4031 if (P.getLangOpts().CPlusPlus11) {
4032 const char *Replacement = IsNoexcept ? "noexcept" : "noexcept(false)";
4033 P.Diag(Range.getBegin(), P.getLangOpts().CPlusPlus17 && !IsNoexcept
4034 ? diag::ext_dynamic_exception_spec
4035 : diag::warn_exception_spec_deprecated)
4036 << Range;
4037 P.Diag(Range.getBegin(), diag::note_exception_spec_deprecated)
4038 << Replacement << FixItHint::CreateReplacement(Range, Replacement);
4039 }
4040}
4041
4042ExceptionSpecificationType Parser::ParseDynamicExceptionSpecification(
4043 SourceRange &SpecificationRange, SmallVectorImpl<ParsedType> &Exceptions,
4045 assert(Tok.is(tok::kw_throw) && "expected throw");
4046
4047 SpecificationRange.setBegin(ConsumeToken());
4048 BalancedDelimiterTracker T(*this, tok::l_paren);
4049 if (T.consumeOpen()) {
4050 Diag(Tok, diag::err_expected_lparen_after) << "throw";
4051 SpecificationRange.setEnd(SpecificationRange.getBegin());
4052 return EST_DynamicNone;
4053 }
4054
4055 // Parse throw(...), a Microsoft extension that means "this function
4056 // can throw anything".
4057 if (Tok.is(tok::ellipsis)) {
4058 SourceLocation EllipsisLoc = ConsumeToken();
4059 if (!getLangOpts().MicrosoftExt)
4060 Diag(EllipsisLoc, diag::ext_ellipsis_exception_spec);
4061 T.consumeClose();
4062 SpecificationRange.setEnd(T.getCloseLocation());
4063 diagnoseDynamicExceptionSpecification(*this, SpecificationRange, false);
4064 return EST_MSAny;
4065 }
4066
4067 // Parse the sequence of type-ids.
4068 SourceRange Range;
4069 while (Tok.isNot(tok::r_paren)) {
4070 TypeResult Res(ParseTypeName(&Range));
4071
4072 if (Tok.is(tok::ellipsis)) {
4073 // C++0x [temp.variadic]p5:
4074 // - In a dynamic-exception-specification (15.4); the pattern is a
4075 // type-id.
4076 SourceLocation Ellipsis = ConsumeToken();
4077 Range.setEnd(Ellipsis);
4078 if (!Res.isInvalid())
4079 Res = Actions.ActOnPackExpansion(Res.get(), Ellipsis);
4080 }
4081
4082 if (!Res.isInvalid()) {
4083 Exceptions.push_back(Res.get());
4084 Ranges.push_back(Range);
4085 }
4086
4087 if (!TryConsumeToken(tok::comma))
4088 break;
4089 }
4090
4091 T.consumeClose();
4092 SpecificationRange.setEnd(T.getCloseLocation());
4093 diagnoseDynamicExceptionSpecification(*this, SpecificationRange,
4094 Exceptions.empty());
4095 return Exceptions.empty() ? EST_DynamicNone : EST_Dynamic;
4096}
4097
4098TypeResult Parser::ParseTrailingReturnType(SourceRange &Range,
4099 bool MayBeFollowedByDirectInit) {
4100 assert(Tok.is(tok::arrow) && "expected arrow");
4101
4102 ConsumeToken();
4103
4104 return ParseTypeName(&Range, MayBeFollowedByDirectInit
4107}
4108
4109void Parser::ParseTrailingRequiresClauseWithScope(Declarator &D) {
4110 assert(Tok.is(tok::kw_requires) && "expected requires");
4111
4112 // C++23 [basic.scope.namespace]p1:
4113 // For each non-friend redeclaration or specialization whose target scope
4114 // is or is contained by the scope, the portion after the declarator-id,
4115 // class-head-name, or enum-head-name is also included in the scope.
4116 // C++23 [basic.scope.class]p1:
4117 // For each non-friend redeclaration or specialization whose target scope
4118 // is or is contained by the scope, the portion after the declarator-id,
4119 // class-head-name, or enum-head-name is also included in the scope.
4120 //
4121 // FIXME: We should really be calling ParseTrailingRequiresClause in
4122 // ParseDirectDeclarator, when we are already in the declarator scope.
4123 // This would also correctly suppress access checks for specializations
4124 // and explicit instantiations, which we currently do not do.
4125 CXXScopeSpec &SS = D.getCXXScopeSpec();
4126 DeclaratorScopeObj DeclScopeObj(*this, SS);
4127 if (SS.isValid() && Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
4128 DeclScopeObj.EnterDeclaratorScope();
4129
4130 ParseScope ParamScope(this, Scope::DeclScope |
4133
4134 ParseTrailingRequiresClause(D);
4135}
4136
4137void Parser::ParseTrailingRequiresClause(Declarator &D) {
4138 assert(Tok.is(tok::kw_requires) && "expected requires");
4139 assert(
4140 getCurScope()->isFunctionPrototypeScope() &&
4141 "trailing requires-clause must be parsed in a function prototype scope");
4142
4143 SourceLocation RequiresKWLoc = ConsumeToken();
4144
4145 ExprResult TrailingRequiresClause;
4146 Actions.ActOnStartTrailingRequiresClause(getCurScope(), D);
4147
4148 std::optional<Sema::CXXThisScopeRAII> ThisScope;
4149 InitCXXThisScopeForDeclaratorIfRelevant(D, D.getDeclSpec(), ThisScope);
4150
4151 TrailingRequiresClause =
4152 ParseConstraintLogicalOrExpression(/*IsTrailingRequiresClause=*/true);
4153
4154 TrailingRequiresClause =
4155 Actions.ActOnFinishTrailingRequiresClause(TrailingRequiresClause);
4156
4157 if (!D.isDeclarationOfFunction()) {
4158 Diag(RequiresKWLoc,
4159 diag::err_requires_clause_on_declarator_not_declaring_a_function);
4160 return;
4161 }
4162
4163 if (TrailingRequiresClause.isInvalid())
4164 SkipUntil({tok::l_brace, tok::arrow, tok::kw_try, tok::comma, tok::colon},
4166 else
4167 D.setTrailingRequiresClause(TrailingRequiresClause.get());
4168
4169 // Did the user swap the trailing return type and requires clause?
4170 if (D.isFunctionDeclarator() && Tok.is(tok::arrow) &&
4172 SourceLocation ArrowLoc = Tok.getLocation();
4173 SourceRange Range;
4174 TypeResult TrailingReturnType =
4175 ParseTrailingReturnType(Range, /*MayBeFollowedByDirectInit=*/false);
4176
4177 if (!TrailingReturnType.isInvalid()) {
4178 Diag(ArrowLoc,
4179 diag::err_requires_clause_must_appear_after_trailing_return)
4180 << Range;
4181 auto &FunctionChunk = D.getFunctionTypeInfo();
4182 FunctionChunk.HasTrailingReturnType = TrailingReturnType.isUsable();
4183 FunctionChunk.TrailingReturnType = TrailingReturnType.get();
4184 FunctionChunk.TrailingReturnTypeLoc = Range.getBegin();
4185 } else
4186 SkipUntil({tok::equal, tok::l_brace, tok::arrow, tok::kw_try, tok::comma},
4188 }
4189}
4190
4191Sema::ParsingClassState Parser::PushParsingClass(Decl *ClassDecl,
4192 bool NonNestedClass,
4193 bool IsInterface) {
4194 assert((NonNestedClass || !ClassStack.empty()) &&
4195 "Nested class without outer class");
4196 ClassStack.push(new ParsingClass(ClassDecl, NonNestedClass, IsInterface));
4197 return Actions.PushParsingClass();
4198}
4199
4200void Parser::DeallocateParsedClasses(Parser::ParsingClass *Class) {
4201 for (unsigned I = 0, N = Class->LateParsedDeclarations.size(); I != N; ++I)
4202 delete Class->LateParsedDeclarations[I];
4203 delete Class;
4204}
4205
4206void Parser::PopParsingClass(Sema::ParsingClassState state) {
4207 assert(!ClassStack.empty() && "Mismatched push/pop for class parsing");
4208
4209 Actions.PopParsingClass(state);
4210
4211 ParsingClass *Victim = ClassStack.top();
4212 ClassStack.pop();
4213 if (Victim->TopLevelClass) {
4214 // Deallocate all of the nested classes of this class,
4215 // recursively: we don't need to keep any of this information.
4216 DeallocateParsedClasses(Victim);
4217 return;
4218 }
4219 assert(!ClassStack.empty() && "Missing top-level class?");
4220
4221 if (Victim->LateParsedDeclarations.empty()) {
4222 // The victim is a nested class, but we will not need to perform
4223 // any processing after the definition of this class since it has
4224 // no members whose handling was delayed. Therefore, we can just
4225 // remove this nested class.
4226 DeallocateParsedClasses(Victim);
4227 return;
4228 }
4229
4230 // This nested class has some members that will need to be processed
4231 // after the top-level class is completely defined. Therefore, add
4232 // it to the list of nested classes within its parent.
4233 assert(getCurScope()->isClassScope() &&
4234 "Nested class outside of class scope?");
4235 ClassStack.top()->LateParsedDeclarations.push_back(
4236 new LateParsedClass(this, Victim));
4237}
4238
4239IdentifierInfo *Parser::TryParseCXX11AttributeIdentifier(
4241 const IdentifierInfo *Scope) {
4242 switch (Tok.getKind()) {
4243 default:
4244 // Identifiers and keywords have identifier info attached.
4245 if (!Tok.isAnnotation()) {
4246 if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
4247 Loc = ConsumeToken();
4248 return II;
4249 }
4250 }
4251 return nullptr;
4252
4253 case tok::code_completion:
4254 cutOffParsing();
4255 Actions.CodeCompletion().CodeCompleteAttribute(
4257 Completion, Scope);
4258 return nullptr;
4259
4260 case tok::numeric_constant: {
4261 // If we got a numeric constant, check to see if it comes from a macro that
4262 // corresponds to the predefined __clang__ macro. If it does, warn the user
4263 // and recover by pretending they said _Clang instead.
4264 if (Tok.getLocation().isMacroID()) {
4265 SmallString<8> ExpansionBuf;
4266 SourceLocation ExpansionLoc =
4267 PP.getSourceManager().getExpansionLoc(Tok.getLocation());
4268 StringRef Spelling = PP.getSpelling(ExpansionLoc, ExpansionBuf);
4269 if (Spelling == "__clang__") {
4270 SourceRange TokRange(
4271 ExpansionLoc,
4272 PP.getSourceManager().getExpansionLoc(Tok.getEndLoc()));
4273 Diag(Tok, diag::warn_wrong_clang_attr_namespace)
4274 << FixItHint::CreateReplacement(TokRange, "_Clang");
4275 Loc = ConsumeToken();
4276 return &PP.getIdentifierTable().get("_Clang");
4277 }
4278 }
4279 return nullptr;
4280 }
4281
4282 case tok::ampamp: // 'and'
4283 case tok::pipe: // 'bitor'
4284 case tok::pipepipe: // 'or'
4285 case tok::caret: // 'xor'
4286 case tok::tilde: // 'compl'
4287 case tok::amp: // 'bitand'
4288 case tok::ampequal: // 'and_eq'
4289 case tok::pipeequal: // 'or_eq'
4290 case tok::caretequal: // 'xor_eq'
4291 case tok::exclaim: // 'not'
4292 case tok::exclaimequal: // 'not_eq'
4293 // Alternative tokens do not have identifier info, but their spelling
4294 // starts with an alphabetical character.
4295 SmallString<8> SpellingBuf;
4296 SourceLocation SpellingLoc =
4297 PP.getSourceManager().getSpellingLoc(Tok.getLocation());
4298 StringRef Spelling = PP.getSpelling(SpellingLoc, SpellingBuf);
4299 if (isLetter(Spelling[0])) {
4300 Loc = ConsumeToken();
4301 return &PP.getIdentifierTable().get(Spelling);
4302 }
4303 return nullptr;
4304 }
4305}
4306
4307void Parser::ParseOpenMPAttributeArgs(const IdentifierInfo *AttrName,
4308 CachedTokens &OpenMPTokens) {
4309 // Both 'sequence' and 'directive' attributes require arguments, so parse the
4310 // open paren for the argument list.
4311 BalancedDelimiterTracker T(*this, tok::l_paren);
4312 if (T.consumeOpen()) {
4313 Diag(Tok, diag::err_expected) << tok::l_paren;
4314 return;
4315 }
4316
4317 if (AttrName->isStr("directive")) {
4318 // If the attribute is named `directive`, we can consume its argument list
4319 // and push the tokens from it into the cached token stream for a new OpenMP
4320 // pragma directive.
4321 Token OMPBeginTok;
4322 OMPBeginTok.startToken();
4323 OMPBeginTok.setKind(tok::annot_attr_openmp);
4324 OMPBeginTok.setLocation(Tok.getLocation());
4325 OpenMPTokens.push_back(OMPBeginTok);
4326
4327 ConsumeAndStoreUntil(tok::r_paren, OpenMPTokens, /*StopAtSemi=*/false,
4328 /*ConsumeFinalToken*/ false);
4329 Token OMPEndTok;
4330 OMPEndTok.startToken();
4331 OMPEndTok.setKind(tok::annot_pragma_openmp_end);
4332 OMPEndTok.setLocation(Tok.getLocation());
4333 OpenMPTokens.push_back(OMPEndTok);
4334 } else {
4335 assert(AttrName->isStr("sequence") &&
4336 "Expected either 'directive' or 'sequence'");
4337 // If the attribute is named 'sequence', its argument is a list of one or
4338 // more OpenMP attributes (either 'omp::directive' or 'omp::sequence',
4339 // where the 'omp::' is optional).
4340 do {
4341 // We expect to see one of the following:
4342 // * An identifier (omp) for the attribute namespace followed by ::
4343 // * An identifier (directive) or an identifier (sequence).
4344 SourceLocation IdentLoc;
4345 const IdentifierInfo *Ident = TryParseCXX11AttributeIdentifier(IdentLoc);
4346
4347 // If there is an identifier and it is 'omp', a double colon is required
4348 // followed by the actual identifier we're after.
4349 if (Ident && Ident->isStr("omp") && !ExpectAndConsume(tok::coloncolon))
4350 Ident = TryParseCXX11AttributeIdentifier(IdentLoc);
4351
4352 // If we failed to find an identifier (scoped or otherwise), or we found
4353 // an unexpected identifier, diagnose.
4354 if (!Ident || (!Ident->isStr("directive") && !Ident->isStr("sequence"))) {
4355 Diag(Tok.getLocation(), diag::err_expected_sequence_or_directive);
4356 SkipUntil(tok::r_paren, StopBeforeMatch);
4357 continue;
4358 }
4359 // We read an identifier. If the identifier is one of the ones we
4360 // expected, we can recurse to parse the args.
4361 ParseOpenMPAttributeArgs(Ident, OpenMPTokens);
4362
4363 // There may be a comma to signal that we expect another directive in the
4364 // sequence.
4365 } while (TryConsumeToken(tok::comma));
4366 }
4367 // Parse the closing paren for the argument list.
4368 T.consumeClose();
4369}
4370
4372 IdentifierInfo *ScopeName) {
4373 switch (
4374 ParsedAttr::getParsedKind(AttrName, ScopeName, ParsedAttr::AS_CXX11)) {
4375 case ParsedAttr::AT_CarriesDependency:
4376 case ParsedAttr::AT_Deprecated:
4377 case ParsedAttr::AT_FallThrough:
4378 case ParsedAttr::AT_CXX11NoReturn:
4379 case ParsedAttr::AT_NoUniqueAddress:
4380 case ParsedAttr::AT_Likely:
4381 case ParsedAttr::AT_Unlikely:
4382 return true;
4383 case ParsedAttr::AT_WarnUnusedResult:
4384 return !ScopeName && AttrName->getName() == "nodiscard";
4385 case ParsedAttr::AT_Unused:
4386 return !ScopeName && AttrName->getName() == "maybe_unused";
4387 default:
4388 return false;
4389 }
4390}
4391
4392bool Parser::ParseCXXAssumeAttributeArg(
4393 ParsedAttributes &Attrs, IdentifierInfo *AttrName,
4394 SourceLocation AttrNameLoc, IdentifierInfo *ScopeName,
4395 SourceLocation ScopeLoc, SourceLocation *EndLoc, ParsedAttr::Form Form) {
4396 assert(Tok.is(tok::l_paren) && "Not a C++11 attribute argument list");
4397 BalancedDelimiterTracker T(*this, tok::l_paren);
4398 T.consumeOpen();
4399
4400 // [dcl.attr.assume]: The expression is potentially evaluated.
4401 EnterExpressionEvaluationContext Unevaluated(
4403
4404 TentativeParsingAction TPA(*this);
4406 if (Res.isInvalid()) {
4407 TPA.Commit();
4408 SkipUntil(tok::r_paren, tok::r_square, StopAtSemi | StopBeforeMatch);
4409 if (Tok.is(tok::r_paren))
4410 T.consumeClose();
4411 return true;
4412 }
4413
4414 if (!Tok.isOneOf(tok::r_paren, tok::r_square)) {
4415 // Emit a better diagnostic if this is an otherwise valid expression that
4416 // is not allowed here.
4417 TPA.Revert();
4418 Res = ParseExpression();
4419 if (!Res.isInvalid()) {
4420 auto *E = Res.get();
4421 Diag(E->getExprLoc(), diag::err_assume_attr_expects_cond_expr)
4422 << AttrName << FixItHint::CreateInsertion(E->getBeginLoc(), "(")
4423 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(E->getEndLoc()),
4424 ")")
4425 << E->getSourceRange();
4426 }
4427
4428 T.consumeClose();
4429 return true;
4430 }
4431
4432 TPA.Commit();
4433 ArgsUnion Assumption = Res.get();
4434 auto RParen = Tok.getLocation();
4435 T.consumeClose();
4436 Attrs.addNew(AttrName, SourceRange(AttrNameLoc, RParen),
4437 AttributeScopeInfo(ScopeName, ScopeLoc), &Assumption, 1, Form);
4438
4439 if (EndLoc)
4440 *EndLoc = RParen;
4441
4442 return false;
4443}
4444
4445bool Parser::ParseCXX11AttributeArgs(
4446 IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
4447 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
4448 SourceLocation ScopeLoc, CachedTokens &OpenMPTokens) {
4449 assert(Tok.is(tok::l_paren) && "Not a C++11 attribute argument list");
4450 SourceLocation LParenLoc = Tok.getLocation();
4451 const LangOptions &LO = getLangOpts();
4452 ParsedAttr::Form Form =
4453 LO.CPlusPlus ? ParsedAttr::Form::CXX11() : ParsedAttr::Form::C23();
4454
4455 // Try parsing microsoft attributes
4456 if (getLangOpts().MicrosoftExt || getLangOpts().HLSL) {
4458 AttrName, getTargetInfo(), getLangOpts()))
4459 Form = ParsedAttr::Form::Microsoft();
4460 }
4461
4462 if (LO.CPlusPlus) {
4463 TentativeParsingAction TPA(*this);
4464 bool HasInvalidArgument = false;
4465 while (Tok.isNot(tok::r_paren) && Tok.isNot(tok::eof)) {
4466 if (Tok.isOneOf(tok::hash, tok::hashhash)) {
4467 Diag(Tok.getLocation(), diag::ext_invalid_attribute_argument)
4468 << PP.getSpelling(Tok);
4469 HasInvalidArgument = true;
4470 }
4471 ConsumeAnyToken();
4472 }
4473
4474 if (HasInvalidArgument) {
4475 SkipUntil(tok::r_paren);
4476 TPA.Commit();
4477 return true;
4478 }
4479
4480 TPA.Revert();
4481 }
4482
4483 // If the attribute isn't known, we will not attempt to parse any
4484 // arguments.
4485 if (Form.getSyntax() != ParsedAttr::AS_Microsoft &&
4488 ScopeName, AttrName, getTargetInfo(), getLangOpts())) {
4489 // Eat the left paren, then skip to the ending right paren.
4490 ConsumeParen();
4491 SkipUntil(tok::r_paren);
4492 return false;
4493 }
4494
4495 if (ScopeName && (ScopeName->isStr("gnu") || ScopeName->isStr("__gnu__"))) {
4496 // GNU-scoped attributes have some special cases to handle GNU-specific
4497 // behaviors.
4498 ParseGNUAttributeArgs(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
4499 ScopeLoc, Form, nullptr);
4500 return true;
4501 }
4502
4503 // [[omp::directive]] and [[omp::sequence]] need special handling.
4504 if (ScopeName && ScopeName->isStr("omp") &&
4505 (AttrName->isStr("directive") || AttrName->isStr("sequence"))) {
4506 Diag(AttrNameLoc, getLangOpts().OpenMP >= 51
4507 ? diag::warn_omp51_compat_attributes
4508 : diag::ext_omp_attributes);
4509
4510 ParseOpenMPAttributeArgs(AttrName, OpenMPTokens);
4511
4512 // We claim that an attribute was parsed and added so that one is not
4513 // created for us by the caller.
4514 return true;
4515 }
4516
4517 unsigned NumArgs;
4518 // Some Clang-scoped attributes have some special parsing behavior.
4519 if (ScopeName && (ScopeName->isStr("clang") || ScopeName->isStr("_Clang")))
4520 NumArgs = ParseClangAttributeArgs(AttrName, AttrNameLoc, Attrs, EndLoc,
4521 ScopeName, ScopeLoc, Form);
4522 // So does C++23's assume() attribute.
4523 else if (!ScopeName && AttrName->isStr("assume")) {
4524 if (ParseCXXAssumeAttributeArg(Attrs, AttrName, AttrNameLoc, nullptr,
4525 SourceLocation{}, EndLoc, Form))
4526 return true;
4527 NumArgs = 1;
4528 } else
4529 NumArgs = ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc,
4530 ScopeName, ScopeLoc, Form);
4531
4532 if (!Attrs.empty() &&
4533 IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName)) {
4534 ParsedAttr &Attr = Attrs.back();
4535
4536 // Ignore attributes that don't exist for the target.
4537 if (!Attr.existsInTarget(getTargetInfo())) {
4538 Actions.DiagnoseUnknownAttribute(Attr);
4539 Attr.setInvalid(true);
4540 return true;
4541 }
4542
4543 // If the attribute is a standard or built-in attribute and we are
4544 // parsing an argument list, we need to determine whether this attribute
4545 // was allowed to have an argument list (such as [[deprecated]]), and how
4546 // many arguments were parsed (so we can diagnose on [[deprecated()]]).
4547 if (Attr.getMaxArgs() && !NumArgs) {
4548 // The attribute was allowed to have arguments, but none were provided
4549 // even though the attribute parsed successfully. This is an error.
4550 Diag(LParenLoc, diag::err_attribute_requires_arguments) << AttrName;
4551 Attr.setInvalid(true);
4552 } else if (!Attr.getMaxArgs()) {
4553 // The attribute parsed successfully, but was not allowed to have any
4554 // arguments. It doesn't matter whether any were provided -- the
4555 // presence of the argument list (even if empty) is diagnosed.
4556 auto D = Diag(LParenLoc, diag::err_cxx11_attribute_forbids_arguments)
4557 << AttrName;
4558 if (EndLoc)
4559 D << FixItHint::CreateRemoval(SourceRange(LParenLoc, *EndLoc));
4560 Attr.setInvalid(true);
4561 }
4562 }
4563 return true;
4564}
4565
4566void Parser::ParseCXX11AttributeSpecifierInternal(ParsedAttributes &Attrs,
4567 CachedTokens &OpenMPTokens,
4568 SourceLocation *EndLoc) {
4569 if (Tok.is(tok::kw_alignas)) {
4570 // alignas is a valid token in C23 but it is not an attribute, it's a type-
4571 // specifier-qualifier, which means it has different parsing behavior. We
4572 // handle this in ParseDeclarationSpecifiers() instead of here in C. We
4573 // should not get here for C any longer.
4574 assert(getLangOpts().CPlusPlus && "'alignas' is not an attribute in C");
4575 Diag(Tok.getLocation(), diag::warn_cxx98_compat_alignas);
4576 ParseAlignmentSpecifier(Attrs, EndLoc);
4577 return;
4578 }
4579
4580 if (Tok.isRegularKeywordAttribute()) {
4581 SourceLocation Loc = Tok.getLocation();
4582 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
4583 ParsedAttr::Form Form = ParsedAttr::Form(Tok.getKind());
4584 bool TakesArgs = doesKeywordAttributeTakeArgs(Tok.getKind());
4585 ConsumeToken();
4586 if (TakesArgs) {
4587 if (!Tok.is(tok::l_paren))
4588 Diag(Tok.getLocation(), diag::err_expected_lparen_after) << AttrName;
4589 else
4590 ParseAttributeArgsCommon(AttrName, Loc, Attrs, EndLoc,
4591 /*ScopeName*/ nullptr,
4592 /*ScopeLoc*/ Loc, Form);
4593 } else
4594 Attrs.addNew(AttrName, Loc, AttributeScopeInfo(), nullptr, 0, Form);
4595 return;
4596 }
4597
4598 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square) &&
4599 "Not a double square bracket attribute list");
4600
4601 SourceLocation OpenLoc = Tok.getLocation();
4602 if (getLangOpts().CPlusPlus) {
4603 Diag(OpenLoc, getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_attribute
4604 : diag::warn_ext_cxx11_attributes);
4605 } else {
4606 Diag(OpenLoc, getLangOpts().C23 ? diag::warn_pre_c23_compat_attributes
4607 : diag::warn_ext_c23_attributes);
4608 }
4609
4610 ConsumeBracket();
4611 checkCompoundToken(OpenLoc, tok::l_square, CompoundToken::AttrBegin);
4612 ConsumeBracket();
4613
4614 SourceLocation CommonScopeLoc;
4615 IdentifierInfo *CommonScopeName = nullptr;
4616 if (Tok.is(tok::kw_using)) {
4617 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
4618 ? diag::warn_cxx14_compat_using_attribute_ns
4619 : diag::ext_using_attribute_ns);
4620 ConsumeToken();
4621
4622 CommonScopeName = TryParseCXX11AttributeIdentifier(
4624 if (!CommonScopeName) {
4625 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
4626 SkipUntil(tok::r_square, tok::colon, StopBeforeMatch);
4627 }
4628 if (!TryConsumeToken(tok::colon) && CommonScopeName)
4629 Diag(Tok.getLocation(), diag::err_expected) << tok::colon;
4630 }
4631
4632 bool AttrParsed = false;
4633 while (!Tok.isOneOf(tok::r_square, tok::semi, tok::eof)) {
4634 if (AttrParsed) {
4635 // If we parsed an attribute, a comma is required before parsing any
4636 // additional attributes.
4637 if (ExpectAndConsume(tok::comma)) {
4638 SkipUntil(tok::r_square, StopAtSemi | StopBeforeMatch);
4639 continue;
4640 }
4641 AttrParsed = false;
4642 }
4643
4644 // Eat all remaining superfluous commas before parsing the next attribute.
4645 while (TryConsumeToken(tok::comma))
4646 ;
4647
4648 SourceLocation ScopeLoc, AttrLoc;
4649 IdentifierInfo *ScopeName = nullptr, *AttrName = nullptr;
4650
4651 AttrName = TryParseCXX11AttributeIdentifier(
4653 CommonScopeName);
4654 if (!AttrName)
4655 // Break out to the "expected ']'" diagnostic.
4656 break;
4657
4658 // scoped attribute
4659 if (TryConsumeToken(tok::coloncolon)) {
4660 ScopeName = AttrName;
4661 ScopeLoc = AttrLoc;
4662
4663 AttrName = TryParseCXX11AttributeIdentifier(
4665 ScopeName);
4666 if (!AttrName) {
4667 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
4668 SkipUntil(tok::r_square, tok::comma, StopAtSemi | StopBeforeMatch);
4669 continue;
4670 }
4671 }
4672
4673 if (CommonScopeName) {
4674 if (ScopeName) {
4675 Diag(ScopeLoc, diag::err_using_attribute_ns_conflict)
4676 << SourceRange(CommonScopeLoc);
4677 } else {
4678 ScopeName = CommonScopeName;
4679 ScopeLoc = CommonScopeLoc;
4680 }
4681 }
4682
4683 // Parse attribute arguments
4684 if (Tok.is(tok::l_paren))
4685 AttrParsed = ParseCXX11AttributeArgs(AttrName, AttrLoc, Attrs, EndLoc,
4686 ScopeName, ScopeLoc, OpenMPTokens);
4687
4688 if (!AttrParsed) {
4689 Attrs.addNew(AttrName,
4690 SourceRange(ScopeLoc.isValid() && CommonScopeLoc.isInvalid()
4691 ? ScopeLoc
4692 : AttrLoc,
4693 AttrLoc),
4694 AttributeScopeInfo(ScopeName, ScopeLoc, CommonScopeLoc),
4695 nullptr, 0,
4696 getLangOpts().CPlusPlus ? ParsedAttr::Form::CXX11()
4697 : ParsedAttr::Form::C23());
4698 AttrParsed = true;
4699 }
4700
4701 if (TryConsumeToken(tok::ellipsis))
4702 Diag(Tok, diag::err_cxx11_attribute_forbids_ellipsis) << AttrName;
4703 }
4704
4705 // If we hit an error and recovered by parsing up to a semicolon, eat the
4706 // semicolon and don't issue further diagnostics about missing brackets.
4707 if (Tok.is(tok::semi)) {
4708 ConsumeToken();
4709 return;
4710 }
4711
4712 SourceLocation CloseLoc = Tok.getLocation();
4713 if (ExpectAndConsume(tok::r_square))
4714 SkipUntil(tok::r_square);
4715 else if (Tok.is(tok::r_square))
4716 checkCompoundToken(CloseLoc, tok::r_square, CompoundToken::AttrEnd);
4717 if (EndLoc)
4718 *EndLoc = Tok.getLocation();
4719 if (ExpectAndConsume(tok::r_square))
4720 SkipUntil(tok::r_square);
4721}
4722
4723void Parser::ParseCXX11Attributes(ParsedAttributes &Attrs) {
4724 SourceLocation StartLoc = Tok.getLocation();
4725 SourceLocation EndLoc = StartLoc;
4726
4727 do {
4728 ParseCXX11AttributeSpecifier(Attrs, &EndLoc);
4729 } while (isAllowedCXX11AttributeSpecifier());
4730
4731 Attrs.Range = SourceRange(StartLoc, EndLoc);
4732}
4733
4734void Parser::DiagnoseAndSkipCXX11Attributes() {
4735 auto Keyword =
4736 Tok.isRegularKeywordAttribute() ? Tok.getIdentifierInfo() : nullptr;
4737 // Start and end location of an attribute or an attribute list.
4738 SourceLocation StartLoc = Tok.getLocation();
4739 SourceLocation EndLoc = SkipCXX11Attributes();
4740
4741 if (EndLoc.isValid()) {
4742 SourceRange Range(StartLoc, EndLoc);
4743 (Keyword ? Diag(StartLoc, diag::err_keyword_not_allowed) << Keyword
4744 : Diag(StartLoc, diag::err_attributes_not_allowed))
4745 << Range;
4746 }
4747}
4748
4749SourceLocation Parser::SkipCXX11Attributes() {
4750 SourceLocation EndLoc;
4751
4752 if (isCXX11AttributeSpecifier() == CXX11AttributeKind::NotAttributeSpecifier)
4753 return EndLoc;
4754
4755 do {
4756 if (Tok.is(tok::l_square)) {
4757 BalancedDelimiterTracker T(*this, tok::l_square);
4758 T.consumeOpen();
4759 T.skipToEnd();
4760 EndLoc = T.getCloseLocation();
4761 } else if (Tok.isRegularKeywordAttribute() &&
4762 !doesKeywordAttributeTakeArgs(Tok.getKind())) {
4763 EndLoc = Tok.getLocation();
4764 ConsumeToken();
4765 } else {
4766 assert((Tok.is(tok::kw_alignas) || Tok.isRegularKeywordAttribute()) &&
4767 "not an attribute specifier");
4768 ConsumeToken();
4769 BalancedDelimiterTracker T(*this, tok::l_paren);
4770 if (!T.consumeOpen())
4771 T.skipToEnd();
4772 EndLoc = T.getCloseLocation();
4773 }
4774 } while (isCXX11AttributeSpecifier() !=
4776
4777 return EndLoc;
4778}
4779
4780void Parser::ParseMicrosoftUuidAttributeArgs(ParsedAttributes &Attrs) {
4781 assert(Tok.is(tok::identifier) && "Not a Microsoft attribute list");
4782 IdentifierInfo *UuidIdent = Tok.getIdentifierInfo();
4783 assert(UuidIdent->getName() == "uuid" && "Not a Microsoft attribute list");
4784
4785 SourceLocation UuidLoc = Tok.getLocation();
4786 ConsumeToken();
4787
4788 // Ignore the left paren location for now.
4789 BalancedDelimiterTracker T(*this, tok::l_paren);
4790 if (T.consumeOpen()) {
4791 Diag(Tok, diag::err_expected) << tok::l_paren;
4792 return;
4793 }
4794
4795 ArgsVector ArgExprs;
4796 if (isTokenStringLiteral()) {
4797 // Easy case: uuid("...") -- quoted string.
4799 if (StringResult.isInvalid())
4800 return;
4801 ArgExprs.push_back(StringResult.get());
4802 } else {
4803 // something like uuid({000000A0-0000-0000-C000-000000000049}) -- no
4804 // quotes in the parens. Just append the spelling of all tokens encountered
4805 // until the closing paren.
4806
4807 SmallString<42> StrBuffer; // 2 "", 36 bytes UUID, 2 optional {}, 1 nul
4808 StrBuffer += "\"";
4809
4810 // Since none of C++'s keywords match [a-f]+, accepting just tok::l_brace,
4811 // tok::r_brace, tok::minus, tok::identifier (think C000) and
4812 // tok::numeric_constant (0000) should be enough. But the spelling of the
4813 // uuid argument is checked later anyways, so there's no harm in accepting
4814 // almost anything here.
4815 // cl is very strict about whitespace in this form and errors out if any
4816 // is present, so check the space flags on the tokens.
4817 SourceLocation StartLoc = Tok.getLocation();
4818 while (Tok.isNot(tok::r_paren)) {
4819 if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
4820 Diag(Tok, diag::err_attribute_uuid_malformed_guid);
4821 SkipUntil(tok::r_paren, StopAtSemi);
4822 return;
4823 }
4824 SmallString<16> SpellingBuffer;
4825 SpellingBuffer.resize(Tok.getLength() + 1);
4826 bool Invalid = false;
4827 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
4828 if (Invalid) {
4829 SkipUntil(tok::r_paren, StopAtSemi);
4830 return;
4831 }
4832 StrBuffer += TokSpelling;
4834 }
4835 StrBuffer += "\"";
4836
4837 if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
4838 Diag(Tok, diag::err_attribute_uuid_malformed_guid);
4839 ConsumeParen();
4840 return;
4841 }
4842
4843 // Pretend the user wrote the appropriate string literal here.
4844 // ActOnStringLiteral() copies the string data into the literal, so it's
4845 // ok that the Token points to StrBuffer.
4846 Token Toks[1];
4847 Toks[0].startToken();
4848 Toks[0].setKind(tok::string_literal);
4849 Toks[0].setLocation(StartLoc);
4850 Toks[0].setLiteralData(StrBuffer.data());
4851 Toks[0].setLength(StrBuffer.size());
4852 StringLiteral *UuidString =
4853 cast<StringLiteral>(Actions.ActOnUnevaluatedStringLiteral(Toks).get());
4854 ArgExprs.push_back(UuidString);
4855 }
4856
4857 if (!T.consumeClose()) {
4858 Attrs.addNew(UuidIdent, SourceRange(UuidLoc, T.getCloseLocation()),
4859 AttributeScopeInfo(), ArgExprs.data(), ArgExprs.size(),
4860 ParsedAttr::Form::Microsoft());
4861 }
4862}
4863
4864void Parser::ParseHLSLRootSignatureAttributeArgs(ParsedAttributes &Attrs) {
4865 assert(Tok.is(tok::identifier) &&
4866 "Expected an identifier to denote which MS attribute to consider");
4867 IdentifierInfo *RootSignatureIdent = Tok.getIdentifierInfo();
4868 assert(RootSignatureIdent->getName() == "RootSignature" &&
4869 "Expected RootSignature identifier for root signature attribute");
4870
4871 SourceLocation RootSignatureLoc = Tok.getLocation();
4872 ConsumeToken();
4873
4874 // Ignore the left paren location for now.
4875 BalancedDelimiterTracker T(*this, tok::l_paren);
4876 if (T.consumeOpen()) {
4877 Diag(Tok, diag::err_expected) << tok::l_paren;
4878 return;
4879 }
4880
4881 auto ProcessStringLiteral = [this]() -> std::optional<StringLiteral *> {
4882 if (!isTokenStringLiteral())
4883 return std::nullopt;
4884
4886 if (StringResult.isInvalid())
4887 return std::nullopt;
4888
4889 if (auto Lit = dyn_cast<StringLiteral>(StringResult.get()))
4890 return Lit;
4891
4892 return std::nullopt;
4893 };
4894
4895 auto Signature = ProcessStringLiteral();
4896 if (!Signature.has_value()) {
4897 Diag(Tok, diag::err_expected_string_literal)
4898 << /*in attributes...*/ 4 << "RootSignature";
4899 return;
4900 }
4901
4902 // Construct our identifier
4903 IdentifierInfo *DeclIdent = hlsl::ParseHLSLRootSignature(
4904 Actions, getLangOpts().HLSLRootSigVer, *Signature);
4905 if (!DeclIdent) {
4906 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
4907 T.consumeClose();
4908 return;
4909 }
4910
4911 // Create the arg for the ParsedAttr
4912 IdentifierLoc *ILoc = ::new (Actions.getASTContext())
4913 IdentifierLoc(RootSignatureLoc, DeclIdent);
4914
4915 ArgsVector Args = {ILoc};
4916
4917 if (!T.consumeClose())
4918 Attrs.addNew(RootSignatureIdent,
4919 SourceRange(RootSignatureLoc, T.getCloseLocation()),
4920 AttributeScopeInfo(), Args.data(), Args.size(),
4921 ParsedAttr::Form::Microsoft());
4922}
4923
4924void Parser::ParseMicrosoftAttributes(ParsedAttributes &Attrs) {
4925 assert(Tok.is(tok::l_square) && "Not a Microsoft attribute list");
4926
4927 SourceLocation StartLoc = Tok.getLocation();
4928 SourceLocation EndLoc = StartLoc;
4929 do {
4930 // FIXME: If this is actually a C++11 attribute, parse it as one.
4931 BalancedDelimiterTracker T(*this, tok::l_square);
4932 T.consumeOpen();
4933
4934 // Skip most ms attributes except for a specific list.
4935 while (true) {
4936 SkipUntil(tok::r_square, tok::identifier,
4938 if (Tok.is(tok::code_completion)) {
4939 cutOffParsing();
4940 Actions.CodeCompletion().CodeCompleteAttribute(
4943 /*Scope=*/nullptr);
4944 break;
4945 }
4946 if (Tok.isNot(tok::identifier)) // ']', but also eof
4947 break;
4948 if (Tok.getIdentifierInfo()->getName() == "uuid")
4949 ParseMicrosoftUuidAttributeArgs(Attrs);
4950 else if (Tok.getIdentifierInfo()->getName() == "RootSignature")
4951 ParseHLSLRootSignatureAttributeArgs(Attrs);
4952 else {
4953 IdentifierInfo *II = Tok.getIdentifierInfo();
4954 SourceLocation NameLoc = Tok.getLocation();
4955 ConsumeToken();
4956 ParsedAttr::Kind AttrKind =
4958 // For HLSL we want to handle all attributes, but for MSVC compat, we
4959 // silently ignore unknown Microsoft attributes.
4960 if (getLangOpts().HLSL || AttrKind != ParsedAttr::UnknownAttribute) {
4961 bool AttrParsed = false;
4962 if (Tok.is(tok::l_paren)) {
4963 CachedTokens OpenMPTokens;
4964 AttrParsed =
4965 ParseCXX11AttributeArgs(II, NameLoc, Attrs, &EndLoc, nullptr,
4966 SourceLocation(), OpenMPTokens);
4967 ReplayOpenMPAttributeTokens(OpenMPTokens);
4968 }
4969 if (!AttrParsed) {
4970 Attrs.addNew(II, NameLoc, AttributeScopeInfo(), nullptr, 0,
4971 ParsedAttr::Form::Microsoft());
4972 }
4973 }
4974 }
4975 }
4976
4977 T.consumeClose();
4978 EndLoc = T.getCloseLocation();
4979 } while (Tok.is(tok::l_square));
4980
4981 Attrs.Range = SourceRange(StartLoc, EndLoc);
4982}
4983
4984void Parser::ParseMicrosoftIfExistsClassDeclaration(
4985 DeclSpec::TST TagType, ParsedAttributes &AccessAttrs,
4986 AccessSpecifier &CurAS) {
4987 IfExistsCondition Result;
4988 if (ParseMicrosoftIfExistsCondition(Result))
4989 return;
4990
4991 BalancedDelimiterTracker Braces(*this, tok::l_brace);
4992 if (Braces.consumeOpen()) {
4993 Diag(Tok, diag::err_expected) << tok::l_brace;
4994 return;
4995 }
4996
4997 switch (Result.Behavior) {
4999 // Parse the declarations below.
5000 break;
5001
5003 Diag(Result.KeywordLoc, diag::warn_microsoft_dependent_exists)
5004 << Result.IsIfExists;
5005 // Fall through to skip.
5006 [[fallthrough]];
5007
5009 Braces.skipToEnd();
5010 return;
5011 }
5012
5013 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
5014 // __if_exists, __if_not_exists can nest.
5015 if (Tok.isOneOf(tok::kw___if_exists, tok::kw___if_not_exists)) {
5016 ParseMicrosoftIfExistsClassDeclaration(TagType, AccessAttrs, CurAS);
5017 continue;
5018 }
5019
5020 // Check for extraneous top-level semicolon.
5021 if (Tok.is(tok::semi)) {
5022 ConsumeExtraSemi(ExtraSemiKind::InsideStruct, TagType);
5023 continue;
5024 }
5025
5026 AccessSpecifier AS = getAccessSpecifierIfPresent();
5027 if (AS != AS_none) {
5028 // Current token is a C++ access specifier.
5029 CurAS = AS;
5030 SourceLocation ASLoc = Tok.getLocation();
5031 ConsumeToken();
5032 if (Tok.is(tok::colon))
5033 Actions.ActOnAccessSpecifier(AS, ASLoc, Tok.getLocation(),
5034 ParsedAttributesView{});
5035 else
5036 Diag(Tok, diag::err_expected) << tok::colon;
5037 ConsumeToken();
5038 continue;
5039 }
5040
5041 ParsedTemplateInfo TemplateInfo;
5042 // Parse all the comma separated declarators.
5043 ParseCXXClassMemberDeclaration(CurAS, AccessAttrs, TemplateInfo);
5044 }
5045
5046 Braces.consumeClose();
5047}
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:182
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition DeclSpec.h:187
SourceRange getRange() const
Definition DeclSpec.h:81
SourceLocation getBeginLoc() const
Definition DeclSpec.h:85
bool isSet() const
Deprecated.
Definition DeclSpec.h:200
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition DeclSpec.h:185
void setTemplateParamLists(ArrayRef< TemplateParameterList * > L)
Definition DeclSpec.h:88
static CharSourceRange getTokenRange(SourceRange R)
Captures information about "declaration specifiers".
Definition DeclSpec.h:219
void setTypeArgumentRange(SourceRange range)
Definition DeclSpec.h:577
static const TST TST_typename
Definition DeclSpec.h:278
bool hasTypeSpecifier() const
Return true if any type-specifier has been found.
Definition DeclSpec.h:697
void ClearStorageClassSpecs()
Definition DeclSpec.h:499
TST getTypeSpecType() const
Definition DeclSpec.h:521
SCS getStorageClassSpec() const
Definition DeclSpec.h:485
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:558
void SetPackIndexingExpr(SourceLocation EllipsisLoc, Expr *Pack)
Definition DeclSpec.cpp:978
void SetRangeEnd(SourceLocation Loc)
Definition DeclSpec.h:715
static const TST TST_interface
Definition DeclSpec.h:276
unsigned getTypeQualifiers() const
getTypeQualifiers - Return a set of TQs.
Definition DeclSpec.h:601
void SetRangeStart(SourceLocation Loc)
Definition DeclSpec.h:714
static const TST TST_union
Definition DeclSpec.h:274
static const TST TST_typename_pack_indexing
Definition DeclSpec.h:285
SourceLocation getFriendSpecLoc() const
Definition DeclSpec.h:833
SourceLocation getModulePrivateSpecLoc() const
Definition DeclSpec.h:836
bool isFriendSpecifiedFirst() const
Definition DeclSpec.h:831
Expr * getRepAsExpr() const
Definition DeclSpec.h:539
static const TST TST_decltype
Definition DeclSpec.h:283
void takeAttributesAppendingingFrom(ParsedAttributes &attrs)
Definition DeclSpec.h:882
static const TST TST_class
Definition DeclSpec.h:277
TypeSpecifierType TST
Definition DeclSpec.h:249
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:535
CXXScopeSpec & getTypeSpecScope()
Definition DeclSpec.h:555
static const TST TST_decltype_auto
Definition DeclSpec.h:284
void setExternInLinkageSpec(bool Value)
Definition DeclSpec.h:490
static const TST TST_error
Definition DeclSpec.h:300
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:827
static const TST TST_struct
Definition DeclSpec.h:275
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:1942
bool isFunctionDeclarator(unsigned &idx) const
isFunctionDeclarator - This method returns true if the declarator is a function declarator (looking t...
Definition DeclSpec.h:2498
bool isPastIdentifier() const
isPastIdentifier - Return true if we have parsed beyond the point where the name would appear.
Definition DeclSpec.h:2356
bool isArrayOfUnknownBound() const
isArrayOfUnknownBound - This method returns true if the declarator is a declarator for an array of un...
Definition DeclSpec.h:2488
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:2765
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition DeclSpec.h:2089
const ParsedAttributes & getAttributes() const
Definition DeclSpec.h:2725
SourceLocation getIdentifierLoc() const
Definition DeclSpec.h:2378
void SetIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Set the name of this declarator to be the given identifier.
Definition DeclSpec.h:2381
void setTrailingRequiresClause(Expr *TRC)
Sets a trailing requires clause for this declarator.
Definition DeclSpec.h:2668
void setTemplateParameterLists(ArrayRef< TemplateParameterList * > TPLs)
Sets the template parameter lists that preceded the declarator.
Definition DeclSpec.h:2686
bool isFirstDeclarator() const
Definition DeclSpec.h:2763
void setFunctionDefinitionKind(FunctionDefinitionKind Val)
Definition DeclSpec.h:2775
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition DeclSpec.h:2104
bool hasName() const
hasName - Whether this declarator has a name, which might be an identifier (accessible via getIdentif...
Definition DeclSpec.h:2362
void clear()
Reset the contents of this Declarator.
Definition DeclSpec.h:2152
void setAsmLabel(Expr *E)
Definition DeclSpec.h:2743
void ExtendWithDeclSpec(const DeclSpec &DS)
ExtendWithDeclSpec - Extend the declarator source range to include the given declspec,...
Definition DeclSpec.h:2143
void SetRangeEnd(SourceLocation Loc)
SetRangeEnd - Set the end of the source range to Loc, unless it's invalid.
Definition DeclSpec.h:2136
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:2529
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:80
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:117
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:141
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:130
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:104
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:980
This represents a decl that may have a name.
Definition Decl.h:274
@ Namespace
A namespace-like entity, stored as a NamespaceBaseDecl*.
static OpaquePtr make(DeclGroupRef P)
Definition Ownership.h:61
ParsedAttr - Represents a syntactic attribute.
Definition ParsedAttr.h:119
static const ParsedAttributesView & none()
Definition ParsedAttr.h:817
void prepend(iterator B, iterator E)
Definition ParsedAttr.h:859
ParsedAttributes - A collection of parsed attributes.
Definition ParsedAttr.h:937
void takeAllPrependingFrom(ParsedAttributes &Other)
Definition ParsedAttr.h:946
void takeAllAppendingFrom(ParsedAttributes &Other)
Definition ParsedAttr.h:954
ParsedAttr * addNew(IdentifierInfo *attrName, SourceRange attrRange, AttributeScopeInfo scope, ArgsUnion *args, unsigned numArgs, ParsedAttr::Form form, SourceLocation ellipsisLoc=SourceLocation())
Add attribute with expression arguments.
Definition ParsedAttr.h:978
ParseScope - Introduces a new scope for parsing.
Definition Parser.h:450
Parser - This implements a parser for the C family of languages.
Definition Parser.h:214
TypeResult ParseTypeName(SourceRange *Range=nullptr, DeclaratorContext Context=DeclaratorContext::TypeName, AccessSpecifier AS=AS_none, Decl **OwnedType=nullptr, ParsedAttributes *Attrs=nullptr)
ParseTypeName.
Definition ParseDecl.cpp:44
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Definition Parser.cpp:88
SourceLocation ConsumeToken()
ConsumeToken - Consume the current 'peek token' and lex the next one.
Definition Parser.h:305
bool ParseTopLevelDecl()
Definition Parser.h:294
static TypeResult getTypeAnnotation(const Token &Tok)
getTypeAnnotation - Read a parsed type out of an annotation token.
Definition Parser.h:370
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:239
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:333
const Token & GetLookAheadToken(unsigned N)
GetLookAheadToken - This peeks ahead N tokens and returns that token without consuming any tokens.
Definition Parser.h:359
ExprResult ParseConstantExpression()
ExprResult ParseConditionalExpression()
Definition ParseExpr.cpp:95
bool TryConsumeToken(tok::TokenKind Expected)
Definition Parser.h:313
OpaquePtr< DeclGroupRef > DeclGroupPtrTy
Definition Parser.h:262
Scope * getCurScope() const
Definition Parser.h:254
const TargetInfo & getTargetInfo() const
Definition Parser.h:248
OpaquePtr< TemplateName > TemplateTy
Definition Parser.h:263
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:549
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:240
const LangOptions & getLangOpts() const
Definition Parser.h:247
friend class ParenBraceBracketBalancer
Definition Parser.h:241
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:530
@ StopAtCodeCompletion
Stop at code completion.
Definition Parser.h:531
@ StopAtSemi
Stop skipping at semicolon.
Definition Parser.h:528
ExprResult ParseUnevaluatedStringLiteralExpression()
const Token & NextToken()
NextToken - This peeks ahead one token and returns it without consuming it.
Definition Parser.h:367
friend class BalancedDelimiterTracker
Definition Parser.h:242
SmallVector< TemplateParameterList *, 4 > TemplateParameterLists
Definition Parser.h:7815
bool TryAnnotateCXXScopeToken(bool EnteringContext=false)
TryAnnotateScopeToken - Like TryAnnotateTypeOrScopeToken but only annotates C++ scope specifiers and ...
Definition Parser.cpp:2105
RAII object used to inform the actions that we're currently parsing a declaration.
A class for parsing a DeclSpec.
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition Scope.h:271
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition Scope.h:287
@ FunctionPrototypeScope
This is a scope that corresponds to the parameters within a function prototype.
Definition Scope.h:85
@ TypeAliasScope
This is a scope of type alias declaration.
Definition Scope.h:166
@ ClassInheritanceScope
We are between inheritance colon and the real class/struct definition scope.
Definition Scope.h:138
@ ClassScope
The scope of a struct/union/class definition.
Definition Scope.h:69
@ FunctionDeclarationScope
This is a scope that corresponds to the parameters within a function prototype for a function declara...
Definition Scope.h:91
@ DeclScope
This is a scope that can contain a declaration.
Definition Scope.h:63
@ PCC_TopLevelOrExpression
Code completion occurs at top-level in a REPL session.
@ PCC_Namespace
Code completion occurs at top-level or namespace context.
ProcessingContextState ParsingClassState
Definition Sema.h:6631
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
Definition Sema.h:6811
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
Definition Sema.h:6821
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6790
@ PotentiallyEvaluatedIfUsed
The current expression is potentially evaluated, but any declarations referenced inside that expressi...
Definition Sema.h:6831
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:3735
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
bool hasUDSuffix() const
Return true if this token is a string or character literal which has a ud-suffix.
Definition Token.h:321
void startToken()
Reset all flags to cleared.
Definition Token.h:187
Represents a C++11 virt-specifier-seq.
Definition DeclSpec.h:2822
Specifier getLastSpecifier() const
Definition DeclSpec.h:2855
SourceLocation getFirstLocation() const
Definition DeclSpec.h:2853
bool isUnset() const
Definition DeclSpec.h:2839
SourceLocation getAbstractLoc() const
Definition DeclSpec.h:2847
static const char * getSpecifierName(Specifier VS)
bool SetSpecifier(Specifier VS, SourceLocation Loc, const char *&PrevSpec)
Defines the clang::TargetInfo interface.
@ After
Like System, but searched after the system directories.
IdentifierInfo * ParseHLSLRootSignature(Sema &Actions, llvm::dxbc::RootSignatureVersion Version, StringLiteral *Signature)
std::variant< struct RequiresDecl, struct HeaderDecl, struct UmbrellaDirDecl, struct ModuleDecl, struct ExcludeDecl, struct ExportDecl, struct ExportAsDecl, struct ExternModuleDecl, struct UseDecl, struct LinkDecl, struct ConfigMacrosDecl, struct ConflictDecl > Decl
All declarations that can appear in a module declaration.
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition TokenKinds.h:25
constexpr bool isRegularKeywordAttribute(TokenKind K)
Definition TokenKinds.h:124
bool isPragmaAnnotation(TokenKind K)
Return true if this is an annotation token representing a pragma.
The JSON file list parser is used to communicate input to InstallAPI.
@ TST_auto
Definition Specifiers.h: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:1885
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:1026
@ IK_Identifier
An identifier.
Definition DeclSpec.h:1012
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:1892
@ Result
The result type of a method or function.
Definition TypeBase.h:905
ActionResult< ParsedType > TypeResult
Definition Ownership.h:251
ActionResult< CXXCtorInitializer * > MemInitResult
Definition Ownership.h:253
@ 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:451
ExprResult ExprError()
Definition Ownership.h:265
@ Keyword
The name has been typo-corrected to a keyword.
Definition Sema.h:562
@ Type
The name was classified as a type.
Definition Sema.h:564
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:1251
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:5972
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Braces
New-expression has a C++11 list-initializer.
Definition ExprCXX.h:2252
ExceptionSpecificationType
The various types of exception specifications that exist in C++11.
@ EST_Unparsed
not parsed yet
@ EST_None
no exception specification
@ EST_MSAny
Microsoft throw(...) extension.
@ EST_BasicNoexcept
noexcept
@ EST_Dynamic
throw(T1, T2)
CachedTokens * ExceptionSpecTokens
Pointer to the cached tokens for an exception-specification that has not yet been parsed.
Definition DeclSpec.h:1482
ParamInfo * Params
Params - This is a pointer to a new[]'d array of ParamInfo objects that describe the parameters speci...
Definition DeclSpec.h:1462
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
Definition DeclSpec.h:1437
unsigned HasTrailingReturnType
HasTrailingReturnType - If this is true, a trailing return type was specified.
Definition DeclSpec.h:1424
ExceptionSpecificationType getExceptionSpecType() const
Get the type of exception specification this function has.
Definition DeclSpec.h:1601
std::unique_ptr< CachedTokens > DefaultArgTokens
DefaultArgTokens - When the parameter's default argument cannot be parsed immediately (because it occ...
Definition DeclSpec.h:1377
bool CheckSameAsPrevious
Definition Sema.h:355
NamedDecl * New
Definition Sema.h:357
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.