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