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