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