1 //===--- ParseDeclCXX.cpp - C++ Declaration Parsing -------------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 // This file implements the C++ Declaration portions of the Parser interfaces.
11 //===----------------------------------------------------------------------===//
13 #include "clang/AST/ASTContext.h"
14 #include "clang/AST/DeclTemplate.h"
15 #include "clang/AST/PrettyDeclStackTrace.h"
16 #include "clang/Basic/AttributeCommonInfo.h"
17 #include "clang/Basic/Attributes.h"
18 #include "clang/Basic/CharInfo.h"
19 #include "clang/Basic/OperatorKinds.h"
20 #include "clang/Basic/TargetInfo.h"
21 #include "clang/Basic/TokenKinds.h"
22 #include "clang/Lex/LiteralSupport.h"
23 #include "clang/Parse/ParseDiagnostic.h"
24 #include "clang/Parse/Parser.h"
25 #include "clang/Parse/RAIIObjectsForParser.h"
26 #include "clang/Sema/DeclSpec.h"
27 #include "clang/Sema/EnterExpressionEvaluationContext.h"
28 #include "clang/Sema/ParsedTemplate.h"
29 #include "clang/Sema/Scope.h"
30 #include "llvm/ADT/SmallString.h"
31 #include "llvm/Support/TimeProfiler.h"
34 using namespace clang
;
36 /// ParseNamespace - We know that the current token is a namespace keyword. This
37 /// may either be a top level namespace or a block-level namespace alias. If
38 /// there was an inline keyword, it has already been parsed.
40 /// namespace-definition: [C++: namespace.def]
41 /// named-namespace-definition
42 /// unnamed-namespace-definition
43 /// nested-namespace-definition
45 /// named-namespace-definition:
46 /// 'inline'[opt] 'namespace' attributes[opt] identifier '{'
47 /// namespace-body '}'
49 /// unnamed-namespace-definition:
50 /// 'inline'[opt] 'namespace' attributes[opt] '{' namespace-body '}'
52 /// nested-namespace-definition:
53 /// 'namespace' enclosing-namespace-specifier '::' 'inline'[opt]
54 /// identifier '{' namespace-body '}'
56 /// enclosing-namespace-specifier:
58 /// enclosing-namespace-specifier '::' 'inline'[opt] identifier
60 /// namespace-alias-definition: [C++ 7.3.2: namespace.alias]
61 /// 'namespace' identifier '=' qualified-namespace-specifier ';'
63 Parser::DeclGroupPtrTy
Parser::ParseNamespace(DeclaratorContext Context
,
64 SourceLocation
&DeclEnd
,
65 SourceLocation InlineLoc
) {
66 assert(Tok
.is(tok::kw_namespace
) && "Not a namespace!");
67 SourceLocation NamespaceLoc
= ConsumeToken(); // eat the 'namespace'.
68 ObjCDeclContextSwitch
ObjCDC(*this);
70 if (Tok
.is(tok::code_completion
)) {
72 Actions
.CodeCompleteNamespaceDecl(getCurScope());
76 SourceLocation IdentLoc
;
77 IdentifierInfo
*Ident
= nullptr;
78 InnerNamespaceInfoList ExtraNSs
;
79 SourceLocation FirstNestedInlineLoc
;
81 ParsedAttributes
attrs(AttrFactory
);
83 auto ReadAttributes
= [&] {
87 if (Tok
.is(tok::kw___attribute
)) {
88 ParseGNUAttributes(attrs
);
91 if (getLangOpts().CPlusPlus11
&& isCXX11AttributeSpecifier()) {
92 Diag(Tok
.getLocation(), getLangOpts().CPlusPlus17
93 ? diag::warn_cxx14_compat_ns_enum_attribute
94 : diag::ext_ns_enum_attribute
)
96 ParseCXX11Attributes(attrs
);
99 } while (MoreToParse
);
104 if (Tok
.is(tok::identifier
)) {
105 Ident
= Tok
.getIdentifierInfo();
106 IdentLoc
= ConsumeToken(); // eat the identifier.
107 while (Tok
.is(tok::coloncolon
) &&
108 (NextToken().is(tok::identifier
) ||
109 (NextToken().is(tok::kw_inline
) &&
110 GetLookAheadToken(2).is(tok::identifier
)))) {
112 InnerNamespaceInfo Info
;
113 Info
.NamespaceLoc
= ConsumeToken();
115 if (Tok
.is(tok::kw_inline
)) {
116 Info
.InlineLoc
= ConsumeToken();
117 if (FirstNestedInlineLoc
.isInvalid())
118 FirstNestedInlineLoc
= Info
.InlineLoc
;
121 Info
.Ident
= Tok
.getIdentifierInfo();
122 Info
.IdentLoc
= ConsumeToken();
124 ExtraNSs
.push_back(Info
);
130 SourceLocation attrLoc
= attrs
.Range
.getBegin();
132 // A nested namespace definition cannot have attributes.
133 if (!ExtraNSs
.empty() && attrLoc
.isValid())
134 Diag(attrLoc
, diag::err_unexpected_nested_namespace_attribute
);
136 if (Tok
.is(tok::equal
)) {
138 Diag(Tok
, diag::err_expected
) << tok::identifier
;
139 // Skip to end of the definition and eat the ';'.
140 SkipUntil(tok::semi
);
143 if (attrLoc
.isValid())
144 Diag(attrLoc
, diag::err_unexpected_namespace_attributes_alias
);
145 if (InlineLoc
.isValid())
146 Diag(InlineLoc
, diag::err_inline_namespace_alias
)
147 << FixItHint::CreateRemoval(InlineLoc
);
148 Decl
*NSAlias
= ParseNamespaceAlias(NamespaceLoc
, IdentLoc
, Ident
, DeclEnd
);
149 return Actions
.ConvertDeclToDeclGroup(NSAlias
);
152 BalancedDelimiterTracker
T(*this, tok::l_brace
);
153 if (T
.consumeOpen()) {
155 Diag(Tok
, diag::err_expected
) << tok::l_brace
;
157 Diag(Tok
, diag::err_expected_either
) << tok::identifier
<< tok::l_brace
;
161 if (getCurScope()->isClassScope() || getCurScope()->isTemplateParamScope() ||
162 getCurScope()->isInObjcMethodScope() || getCurScope()->getBlockParent() ||
163 getCurScope()->getFnParent()) {
164 Diag(T
.getOpenLocation(), diag::err_namespace_nonnamespace_scope
);
165 SkipUntil(tok::r_brace
);
169 if (ExtraNSs
.empty()) {
170 // Normal namespace definition, not a nested-namespace-definition.
171 } else if (InlineLoc
.isValid()) {
172 Diag(InlineLoc
, diag::err_inline_nested_namespace_definition
);
173 } else if (getLangOpts().CPlusPlus20
) {
174 Diag(ExtraNSs
[0].NamespaceLoc
,
175 diag::warn_cxx14_compat_nested_namespace_definition
);
176 if (FirstNestedInlineLoc
.isValid())
177 Diag(FirstNestedInlineLoc
,
178 diag::warn_cxx17_compat_inline_nested_namespace_definition
);
179 } else if (getLangOpts().CPlusPlus17
) {
180 Diag(ExtraNSs
[0].NamespaceLoc
,
181 diag::warn_cxx14_compat_nested_namespace_definition
);
182 if (FirstNestedInlineLoc
.isValid())
183 Diag(FirstNestedInlineLoc
, diag::ext_inline_nested_namespace_definition
);
185 TentativeParsingAction
TPA(*this);
186 SkipUntil(tok::r_brace
, StopBeforeMatch
);
187 Token rBraceToken
= Tok
;
190 if (!rBraceToken
.is(tok::r_brace
)) {
191 Diag(ExtraNSs
[0].NamespaceLoc
, diag::ext_nested_namespace_definition
)
192 << SourceRange(ExtraNSs
.front().NamespaceLoc
,
193 ExtraNSs
.back().IdentLoc
);
195 std::string NamespaceFix
;
196 for (const auto &ExtraNS
: ExtraNSs
) {
197 NamespaceFix
+= " { ";
198 if (ExtraNS
.InlineLoc
.isValid())
199 NamespaceFix
+= "inline ";
200 NamespaceFix
+= "namespace ";
201 NamespaceFix
+= ExtraNS
.Ident
->getName();
205 for (unsigned i
= 0, e
= ExtraNSs
.size(); i
!= e
; ++i
)
208 Diag(ExtraNSs
[0].NamespaceLoc
, diag::ext_nested_namespace_definition
)
209 << FixItHint::CreateReplacement(
210 SourceRange(ExtraNSs
.front().NamespaceLoc
,
211 ExtraNSs
.back().IdentLoc
),
213 << FixItHint::CreateInsertion(rBraceToken
.getLocation(), RBraces
);
216 // Warn about nested inline namespaces.
217 if (FirstNestedInlineLoc
.isValid())
218 Diag(FirstNestedInlineLoc
, diag::ext_inline_nested_namespace_definition
);
221 // If we're still good, complain about inline namespaces in non-C++0x now.
222 if (InlineLoc
.isValid())
223 Diag(InlineLoc
, getLangOpts().CPlusPlus11
224 ? diag::warn_cxx98_compat_inline_namespace
225 : diag::ext_inline_namespace
);
227 // Enter a scope for the namespace.
228 ParseScope
NamespaceScope(this, Scope::DeclScope
);
230 UsingDirectiveDecl
*ImplicitUsingDirectiveDecl
= nullptr;
231 Decl
*NamespcDecl
= Actions
.ActOnStartNamespaceDef(
232 getCurScope(), InlineLoc
, NamespaceLoc
, IdentLoc
, Ident
,
233 T
.getOpenLocation(), attrs
, ImplicitUsingDirectiveDecl
, false);
235 PrettyDeclStackTraceEntry
CrashInfo(Actions
.Context
, NamespcDecl
,
236 NamespaceLoc
, "parsing namespace");
238 // Parse the contents of the namespace. This includes parsing recovery on
239 // any improperly nested namespaces.
240 ParseInnerNamespace(ExtraNSs
, 0, InlineLoc
, attrs
, T
);
242 // Leave the namespace scope.
243 NamespaceScope
.Exit();
245 DeclEnd
= T
.getCloseLocation();
246 Actions
.ActOnFinishNamespaceDef(NamespcDecl
, DeclEnd
);
248 return Actions
.ConvertDeclToDeclGroup(NamespcDecl
,
249 ImplicitUsingDirectiveDecl
);
252 /// ParseInnerNamespace - Parse the contents of a namespace.
253 void Parser::ParseInnerNamespace(const InnerNamespaceInfoList
&InnerNSs
,
254 unsigned int index
, SourceLocation
&InlineLoc
,
255 ParsedAttributes
&attrs
,
256 BalancedDelimiterTracker
&Tracker
) {
257 if (index
== InnerNSs
.size()) {
258 while (!tryParseMisplacedModuleImport() && Tok
.isNot(tok::r_brace
) &&
259 Tok
.isNot(tok::eof
)) {
260 ParsedAttributes
DeclAttrs(AttrFactory
);
261 MaybeParseCXX11Attributes(DeclAttrs
);
262 ParsedAttributes
EmptyDeclSpecAttrs(AttrFactory
);
263 ParseExternalDeclaration(DeclAttrs
, EmptyDeclSpecAttrs
);
266 // The caller is what called check -- we are simply calling
268 Tracker
.consumeClose();
273 // Handle a nested namespace definition.
274 // FIXME: Preserve the source information through to the AST rather than
275 // desugaring it here.
276 ParseScope
NamespaceScope(this, Scope::DeclScope
);
277 UsingDirectiveDecl
*ImplicitUsingDirectiveDecl
= nullptr;
278 Decl
*NamespcDecl
= Actions
.ActOnStartNamespaceDef(
279 getCurScope(), InnerNSs
[index
].InlineLoc
, InnerNSs
[index
].NamespaceLoc
,
280 InnerNSs
[index
].IdentLoc
, InnerNSs
[index
].Ident
,
281 Tracker
.getOpenLocation(), attrs
, ImplicitUsingDirectiveDecl
, true);
282 assert(!ImplicitUsingDirectiveDecl
&&
283 "nested namespace definition cannot define anonymous namespace");
285 ParseInnerNamespace(InnerNSs
, ++index
, InlineLoc
, attrs
, Tracker
);
287 NamespaceScope
.Exit();
288 Actions
.ActOnFinishNamespaceDef(NamespcDecl
, Tracker
.getCloseLocation());
291 /// ParseNamespaceAlias - Parse the part after the '=' in a namespace
292 /// alias definition.
294 Decl
*Parser::ParseNamespaceAlias(SourceLocation NamespaceLoc
,
295 SourceLocation AliasLoc
,
296 IdentifierInfo
*Alias
,
297 SourceLocation
&DeclEnd
) {
298 assert(Tok
.is(tok::equal
) && "Not equal token");
300 ConsumeToken(); // eat the '='.
302 if (Tok
.is(tok::code_completion
)) {
304 Actions
.CodeCompleteNamespaceAliasDecl(getCurScope());
309 // Parse (optional) nested-name-specifier.
310 ParseOptionalCXXScopeSpecifier(SS
, /*ObjectType=*/nullptr,
311 /*ObjectHasErrors=*/false,
312 /*EnteringContext=*/false,
313 /*MayBePseudoDestructor=*/nullptr,
314 /*IsTypename=*/false,
316 /*OnlyNamespace=*/true);
318 if (Tok
.isNot(tok::identifier
)) {
319 Diag(Tok
, diag::err_expected_namespace_name
);
320 // Skip to end of the definition and eat the ';'.
321 SkipUntil(tok::semi
);
325 if (SS
.isInvalid()) {
326 // Diagnostics have been emitted in ParseOptionalCXXScopeSpecifier.
327 // Skip to end of the definition and eat the ';'.
328 SkipUntil(tok::semi
);
333 IdentifierInfo
*Ident
= Tok
.getIdentifierInfo();
334 SourceLocation IdentLoc
= ConsumeToken();
337 DeclEnd
= Tok
.getLocation();
338 if (ExpectAndConsume(tok::semi
, diag::err_expected_semi_after_namespace_name
))
339 SkipUntil(tok::semi
);
341 return Actions
.ActOnNamespaceAliasDef(getCurScope(), NamespaceLoc
, AliasLoc
,
342 Alias
, SS
, IdentLoc
, Ident
);
345 /// ParseLinkage - We know that the current token is a string_literal
346 /// and just before that, that extern was seen.
348 /// linkage-specification: [C++ 7.5p2: dcl.link]
349 /// 'extern' string-literal '{' declaration-seq[opt] '}'
350 /// 'extern' string-literal declaration
352 Decl
*Parser::ParseLinkage(ParsingDeclSpec
&DS
, DeclaratorContext Context
) {
353 assert(isTokenStringLiteral() && "Not a string literal!");
354 ExprResult Lang
= ParseUnevaluatedStringLiteralExpression();
356 ParseScope
LinkageScope(this, Scope::DeclScope
);
360 : Actions
.ActOnStartLinkageSpecification(
361 getCurScope(), DS
.getSourceRange().getBegin(), Lang
.get(),
362 Tok
.is(tok::l_brace
) ? Tok
.getLocation() : SourceLocation());
364 ParsedAttributes
DeclAttrs(AttrFactory
);
365 ParsedAttributes
DeclSpecAttrs(AttrFactory
);
367 while (MaybeParseCXX11Attributes(DeclAttrs
) ||
368 MaybeParseGNUAttributes(DeclSpecAttrs
))
371 if (Tok
.isNot(tok::l_brace
)) {
372 // Reset the source range in DS, as the leading "extern"
373 // does not really belong to the inner declaration ...
374 DS
.SetRangeStart(SourceLocation());
375 DS
.SetRangeEnd(SourceLocation());
376 // ... but anyway remember that such an "extern" was seen.
377 DS
.setExternInLinkageSpec(true);
378 ParseExternalDeclaration(DeclAttrs
, DeclSpecAttrs
, &DS
);
379 return LinkageSpec
? Actions
.ActOnFinishLinkageSpecification(
380 getCurScope(), LinkageSpec
, SourceLocation())
386 ProhibitAttributes(DeclAttrs
);
388 BalancedDelimiterTracker
T(*this, tok::l_brace
);
391 unsigned NestedModules
= 0;
393 switch (Tok
.getKind()) {
394 case tok::annot_module_begin
:
399 case tok::annot_module_end
:
406 case tok::annot_module_include
:
418 ParsedAttributes
DeclAttrs(AttrFactory
);
419 MaybeParseCXX11Attributes(DeclAttrs
);
420 ParseExternalDeclaration(DeclAttrs
, DeclSpecAttrs
);
428 return LinkageSpec
? Actions
.ActOnFinishLinkageSpecification(
429 getCurScope(), LinkageSpec
, T
.getCloseLocation())
433 /// Parse a standard C++ Modules export-declaration.
435 /// export-declaration:
436 /// 'export' declaration
437 /// 'export' '{' declaration-seq[opt] '}'
439 Decl
*Parser::ParseExportDeclaration() {
440 assert(Tok
.is(tok::kw_export
));
441 SourceLocation ExportLoc
= ConsumeToken();
443 ParseScope
ExportScope(this, Scope::DeclScope
);
444 Decl
*ExportDecl
= Actions
.ActOnStartExportDecl(
445 getCurScope(), ExportLoc
,
446 Tok
.is(tok::l_brace
) ? Tok
.getLocation() : SourceLocation());
448 if (Tok
.isNot(tok::l_brace
)) {
449 // FIXME: Factor out a ParseExternalDeclarationWithAttrs.
450 ParsedAttributes
DeclAttrs(AttrFactory
);
451 MaybeParseCXX11Attributes(DeclAttrs
);
452 ParsedAttributes
EmptyDeclSpecAttrs(AttrFactory
);
453 ParseExternalDeclaration(DeclAttrs
, EmptyDeclSpecAttrs
);
454 return Actions
.ActOnFinishExportDecl(getCurScope(), ExportDecl
,
458 BalancedDelimiterTracker
T(*this, tok::l_brace
);
461 while (!tryParseMisplacedModuleImport() && Tok
.isNot(tok::r_brace
) &&
462 Tok
.isNot(tok::eof
)) {
463 ParsedAttributes
DeclAttrs(AttrFactory
);
464 MaybeParseCXX11Attributes(DeclAttrs
);
465 ParsedAttributes
EmptyDeclSpecAttrs(AttrFactory
);
466 ParseExternalDeclaration(DeclAttrs
, EmptyDeclSpecAttrs
);
470 return Actions
.ActOnFinishExportDecl(getCurScope(), ExportDecl
,
471 T
.getCloseLocation());
474 /// ParseUsingDirectiveOrDeclaration - Parse C++ using using-declaration or
475 /// using-directive. Assumes that current token is 'using'.
476 Parser::DeclGroupPtrTy
Parser::ParseUsingDirectiveOrDeclaration(
477 DeclaratorContext Context
, const ParsedTemplateInfo
&TemplateInfo
,
478 SourceLocation
&DeclEnd
, ParsedAttributes
&Attrs
) {
479 assert(Tok
.is(tok::kw_using
) && "Not using token");
480 ObjCDeclContextSwitch
ObjCDC(*this);
483 SourceLocation UsingLoc
= ConsumeToken();
485 if (Tok
.is(tok::code_completion
)) {
487 Actions
.CodeCompleteUsing(getCurScope());
491 // Consume unexpected 'template' keywords.
492 while (Tok
.is(tok::kw_template
)) {
493 SourceLocation TemplateLoc
= ConsumeToken();
494 Diag(TemplateLoc
, diag::err_unexpected_template_after_using
)
495 << FixItHint::CreateRemoval(TemplateLoc
);
498 // 'using namespace' means this is a using-directive.
499 if (Tok
.is(tok::kw_namespace
)) {
500 // Template parameters are always an error here.
501 if (TemplateInfo
.Kind
) {
502 SourceRange R
= TemplateInfo
.getSourceRange();
503 Diag(UsingLoc
, diag::err_templated_using_directive_declaration
)
504 << 0 /* directive */ << R
<< FixItHint::CreateRemoval(R
);
507 Decl
*UsingDir
= ParseUsingDirective(Context
, UsingLoc
, DeclEnd
, Attrs
);
508 return Actions
.ConvertDeclToDeclGroup(UsingDir
);
511 // Otherwise, it must be a using-declaration or an alias-declaration.
512 return ParseUsingDeclaration(Context
, TemplateInfo
, UsingLoc
, DeclEnd
, Attrs
,
516 /// ParseUsingDirective - Parse C++ using-directive, assumes
517 /// that current token is 'namespace' and 'using' was already parsed.
519 /// using-directive: [C++ 7.3.p4: namespace.udir]
520 /// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
522 /// [GNU] using-directive:
523 /// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
524 /// namespace-name attributes[opt] ;
526 Decl
*Parser::ParseUsingDirective(DeclaratorContext Context
,
527 SourceLocation UsingLoc
,
528 SourceLocation
&DeclEnd
,
529 ParsedAttributes
&attrs
) {
530 assert(Tok
.is(tok::kw_namespace
) && "Not 'namespace' token");
533 SourceLocation NamespcLoc
= ConsumeToken();
535 if (Tok
.is(tok::code_completion
)) {
537 Actions
.CodeCompleteUsingDirective(getCurScope());
542 // Parse (optional) nested-name-specifier.
543 ParseOptionalCXXScopeSpecifier(SS
, /*ObjectType=*/nullptr,
544 /*ObjectHasErrors=*/false,
545 /*EnteringContext=*/false,
546 /*MayBePseudoDestructor=*/nullptr,
547 /*IsTypename=*/false,
549 /*OnlyNamespace=*/true);
551 IdentifierInfo
*NamespcName
= nullptr;
552 SourceLocation IdentLoc
= SourceLocation();
554 // Parse namespace-name.
555 if (Tok
.isNot(tok::identifier
)) {
556 Diag(Tok
, diag::err_expected_namespace_name
);
557 // If there was invalid namespace name, skip to end of decl, and eat ';'.
558 SkipUntil(tok::semi
);
559 // FIXME: Are there cases, when we would like to call ActOnUsingDirective?
563 if (SS
.isInvalid()) {
564 // Diagnostics have been emitted in ParseOptionalCXXScopeSpecifier.
565 // Skip to end of the definition and eat the ';'.
566 SkipUntil(tok::semi
);
571 NamespcName
= Tok
.getIdentifierInfo();
572 IdentLoc
= ConsumeToken();
574 // Parse (optional) attributes (most likely GNU strong-using extension).
575 bool GNUAttr
= false;
576 if (Tok
.is(tok::kw___attribute
)) {
578 ParseGNUAttributes(attrs
);
582 DeclEnd
= Tok
.getLocation();
583 if (ExpectAndConsume(tok::semi
,
584 GNUAttr
? diag::err_expected_semi_after_attribute_list
585 : diag::err_expected_semi_after_namespace_name
))
586 SkipUntil(tok::semi
);
588 return Actions
.ActOnUsingDirective(getCurScope(), UsingLoc
, NamespcLoc
, SS
,
589 IdentLoc
, NamespcName
, attrs
);
592 /// Parse a using-declarator (or the identifier in a C++11 alias-declaration).
594 /// using-declarator:
595 /// 'typename'[opt] nested-name-specifier unqualified-id
597 bool Parser::ParseUsingDeclarator(DeclaratorContext Context
,
598 UsingDeclarator
&D
) {
601 // Ignore optional 'typename'.
602 // FIXME: This is wrong; we should parse this as a typename-specifier.
603 TryConsumeToken(tok::kw_typename
, D
.TypenameLoc
);
605 if (Tok
.is(tok::kw___super
)) {
606 Diag(Tok
.getLocation(), diag::err_super_in_using_declaration
);
610 // Parse nested-name-specifier.
611 IdentifierInfo
*LastII
= nullptr;
612 if (ParseOptionalCXXScopeSpecifier(D
.SS
, /*ObjectType=*/nullptr,
613 /*ObjectHasErrors=*/false,
614 /*EnteringContext=*/false,
615 /*MayBePseudoDtor=*/nullptr,
616 /*IsTypename=*/false,
618 /*OnlyNamespace=*/false,
619 /*InUsingDeclaration=*/true))
622 if (D
.SS
.isInvalid())
625 // Parse the unqualified-id. We allow parsing of both constructor and
626 // destructor names and allow the action module to diagnose any semantic
629 // C++11 [class.qual]p2:
630 // [...] in a using-declaration that is a member-declaration, if the name
631 // specified after the nested-name-specifier is the same as the identifier
632 // or the simple-template-id's template-name in the last component of the
633 // nested-name-specifier, the name is [...] considered to name the
635 if (getLangOpts().CPlusPlus11
&& Context
== DeclaratorContext::Member
&&
636 Tok
.is(tok::identifier
) &&
637 (NextToken().is(tok::semi
) || NextToken().is(tok::comma
) ||
638 NextToken().is(tok::ellipsis
) || NextToken().is(tok::l_square
) ||
639 NextToken().isRegularKeywordAttribute() ||
640 NextToken().is(tok::kw___attribute
)) &&
641 D
.SS
.isNotEmpty() && LastII
== Tok
.getIdentifierInfo() &&
642 !D
.SS
.getScopeRep()->getAsNamespace() &&
643 !D
.SS
.getScopeRep()->getAsNamespaceAlias()) {
644 SourceLocation IdLoc
= ConsumeToken();
646 Actions
.getInheritingConstructorName(D
.SS
, IdLoc
, *LastII
);
647 D
.Name
.setConstructorName(Type
, IdLoc
, IdLoc
);
649 if (ParseUnqualifiedId(
650 D
.SS
, /*ObjectType=*/nullptr,
651 /*ObjectHadErrors=*/false, /*EnteringContext=*/false,
652 /*AllowDestructorName=*/true,
653 /*AllowConstructorName=*/
654 !(Tok
.is(tok::identifier
) && NextToken().is(tok::equal
)),
655 /*AllowDeductionGuide=*/false, nullptr, D
.Name
))
659 if (TryConsumeToken(tok::ellipsis
, D
.EllipsisLoc
))
660 Diag(Tok
.getLocation(), getLangOpts().CPlusPlus17
661 ? diag::warn_cxx17_compat_using_declaration_pack
662 : diag::ext_using_declaration_pack
);
667 /// ParseUsingDeclaration - Parse C++ using-declaration or alias-declaration.
668 /// Assumes that 'using' was already seen.
670 /// using-declaration: [C++ 7.3.p3: namespace.udecl]
671 /// 'using' using-declarator-list[opt] ;
673 /// using-declarator-list: [C++1z]
674 /// using-declarator '...'[opt]
675 /// using-declarator-list ',' using-declarator '...'[opt]
677 /// using-declarator-list: [C++98-14]
680 /// alias-declaration: C++11 [dcl.dcl]p1
681 /// 'using' identifier attribute-specifier-seq[opt] = type-id ;
683 /// using-enum-declaration: [C++20, dcl.enum]
684 /// 'using' elaborated-enum-specifier ;
685 /// The terminal name of the elaborated-enum-specifier undergoes
688 /// elaborated-enum-specifier:
689 /// 'enum' nested-name-specifier[opt] identifier
690 Parser::DeclGroupPtrTy
Parser::ParseUsingDeclaration(
691 DeclaratorContext Context
, const ParsedTemplateInfo
&TemplateInfo
,
692 SourceLocation UsingLoc
, SourceLocation
&DeclEnd
,
693 ParsedAttributes
&PrefixAttrs
, AccessSpecifier AS
) {
694 SourceLocation UELoc
;
695 bool InInitStatement
= Context
== DeclaratorContext::SelectionInit
||
696 Context
== DeclaratorContext::ForInit
;
698 if (TryConsumeToken(tok::kw_enum
, UELoc
) && !InInitStatement
) {
700 Diag(UELoc
, getLangOpts().CPlusPlus20
701 ? diag::warn_cxx17_compat_using_enum_declaration
702 : diag::ext_using_enum_declaration
);
704 DiagnoseCXX11AttributeExtension(PrefixAttrs
);
706 if (TemplateInfo
.Kind
) {
707 SourceRange R
= TemplateInfo
.getSourceRange();
708 Diag(UsingLoc
, diag::err_templated_using_directive_declaration
)
709 << 1 /* declaration */ << R
<< FixItHint::CreateRemoval(R
);
710 SkipUntil(tok::semi
);
714 if (ParseOptionalCXXScopeSpecifier(SS
, /*ParsedType=*/nullptr,
715 /*ObectHasErrors=*/false,
716 /*EnteringConttext=*/false,
717 /*MayBePseudoDestructor=*/nullptr,
718 /*IsTypename=*/false,
719 /*IdentifierInfo=*/nullptr,
720 /*OnlyNamespace=*/false,
721 /*InUsingDeclaration=*/true)) {
722 SkipUntil(tok::semi
);
726 if (Tok
.is(tok::code_completion
)) {
728 Actions
.CodeCompleteUsing(getCurScope());
732 if (!Tok
.is(tok::identifier
)) {
733 Diag(Tok
.getLocation(), diag::err_using_enum_expect_identifier
)
734 << Tok
.is(tok::kw_enum
);
735 SkipUntil(tok::semi
);
738 IdentifierInfo
*IdentInfo
= Tok
.getIdentifierInfo();
739 SourceLocation IdentLoc
= ConsumeToken();
740 Decl
*UED
= Actions
.ActOnUsingEnumDeclaration(
741 getCurScope(), AS
, UsingLoc
, UELoc
, IdentLoc
, *IdentInfo
, &SS
);
743 SkipUntil(tok::semi
);
747 DeclEnd
= Tok
.getLocation();
748 if (ExpectAndConsume(tok::semi
, diag::err_expected_after
,
749 "using-enum declaration"))
750 SkipUntil(tok::semi
);
752 return Actions
.ConvertDeclToDeclGroup(UED
);
755 // Check for misplaced attributes before the identifier in an
756 // alias-declaration.
757 ParsedAttributes
MisplacedAttrs(AttrFactory
);
758 MaybeParseCXX11Attributes(MisplacedAttrs
);
760 if (InInitStatement
&& Tok
.isNot(tok::identifier
))
764 bool InvalidDeclarator
= ParseUsingDeclarator(Context
, D
);
766 ParsedAttributes
Attrs(AttrFactory
);
767 MaybeParseAttributes(PAKM_GNU
| PAKM_CXX11
, Attrs
);
769 // If we had any misplaced attributes from earlier, this is where they
770 // should have been written.
771 if (MisplacedAttrs
.Range
.isValid()) {
773 MisplacedAttrs
.empty() ? nullptr : &MisplacedAttrs
.front();
774 auto &Range
= MisplacedAttrs
.Range
;
775 (FirstAttr
&& FirstAttr
->isRegularKeywordAttribute()
776 ? Diag(Range
.getBegin(), diag::err_keyword_not_allowed
) << FirstAttr
777 : Diag(Range
.getBegin(), diag::err_attributes_not_allowed
))
778 << FixItHint::CreateInsertionFromRange(
779 Tok
.getLocation(), CharSourceRange::getTokenRange(Range
))
780 << FixItHint::CreateRemoval(Range
);
781 Attrs
.takeAllFrom(MisplacedAttrs
);
784 // Maybe this is an alias-declaration.
785 if (Tok
.is(tok::equal
) || InInitStatement
) {
786 if (InvalidDeclarator
) {
787 SkipUntil(tok::semi
);
791 ProhibitAttributes(PrefixAttrs
);
793 Decl
*DeclFromDeclSpec
= nullptr;
794 Decl
*AD
= ParseAliasDeclarationAfterDeclarator(
795 TemplateInfo
, UsingLoc
, D
, DeclEnd
, AS
, Attrs
, &DeclFromDeclSpec
);
796 return Actions
.ConvertDeclToDeclGroup(AD
, DeclFromDeclSpec
);
799 DiagnoseCXX11AttributeExtension(PrefixAttrs
);
801 // Diagnose an attempt to declare a templated using-declaration.
802 // In C++11, alias-declarations can be templates:
803 // template <...> using id = type;
804 if (TemplateInfo
.Kind
) {
805 SourceRange R
= TemplateInfo
.getSourceRange();
806 Diag(UsingLoc
, diag::err_templated_using_directive_declaration
)
807 << 1 /* declaration */ << R
<< FixItHint::CreateRemoval(R
);
809 // Unfortunately, we have to bail out instead of recovering by
810 // ignoring the parameters, just in case the nested name specifier
811 // depends on the parameters.
815 SmallVector
<Decl
*, 8> DeclsInGroup
;
817 // Parse (optional) attributes.
818 MaybeParseAttributes(PAKM_GNU
| PAKM_CXX11
, Attrs
);
819 DiagnoseCXX11AttributeExtension(Attrs
);
820 Attrs
.addAll(PrefixAttrs
.begin(), PrefixAttrs
.end());
822 if (InvalidDeclarator
)
823 SkipUntil(tok::comma
, tok::semi
, StopBeforeMatch
);
825 // "typename" keyword is allowed for identifiers only,
826 // because it may be a type definition.
827 if (D
.TypenameLoc
.isValid() &&
828 D
.Name
.getKind() != UnqualifiedIdKind::IK_Identifier
) {
829 Diag(D
.Name
.getSourceRange().getBegin(),
830 diag::err_typename_identifiers_only
)
831 << FixItHint::CreateRemoval(SourceRange(D
.TypenameLoc
));
832 // Proceed parsing, but discard the typename keyword.
833 D
.TypenameLoc
= SourceLocation();
836 Decl
*UD
= Actions
.ActOnUsingDeclaration(getCurScope(), AS
, UsingLoc
,
837 D
.TypenameLoc
, D
.SS
, D
.Name
,
838 D
.EllipsisLoc
, Attrs
);
840 DeclsInGroup
.push_back(UD
);
843 if (!TryConsumeToken(tok::comma
))
846 // Parse another using-declarator.
848 InvalidDeclarator
= ParseUsingDeclarator(Context
, D
);
851 if (DeclsInGroup
.size() > 1)
852 Diag(Tok
.getLocation(),
853 getLangOpts().CPlusPlus17
854 ? diag::warn_cxx17_compat_multi_using_declaration
855 : diag::ext_multi_using_declaration
);
858 DeclEnd
= Tok
.getLocation();
859 if (ExpectAndConsume(tok::semi
, diag::err_expected_after
,
860 !Attrs
.empty() ? "attributes list"
861 : UELoc
.isValid() ? "using-enum declaration"
862 : "using declaration"))
863 SkipUntil(tok::semi
);
865 return Actions
.BuildDeclaratorGroup(DeclsInGroup
);
868 Decl
*Parser::ParseAliasDeclarationAfterDeclarator(
869 const ParsedTemplateInfo
&TemplateInfo
, SourceLocation UsingLoc
,
870 UsingDeclarator
&D
, SourceLocation
&DeclEnd
, AccessSpecifier AS
,
871 ParsedAttributes
&Attrs
, Decl
**OwnedType
) {
872 if (ExpectAndConsume(tok::equal
)) {
873 SkipUntil(tok::semi
);
877 Diag(Tok
.getLocation(), getLangOpts().CPlusPlus11
878 ? diag::warn_cxx98_compat_alias_declaration
879 : diag::ext_alias_declaration
);
881 // Type alias templates cannot be specialized.
883 if (TemplateInfo
.Kind
== ParsedTemplateInfo::Template
&&
884 D
.Name
.getKind() == UnqualifiedIdKind::IK_TemplateId
)
886 if (TemplateInfo
.Kind
== ParsedTemplateInfo::ExplicitSpecialization
)
888 if (TemplateInfo
.Kind
== ParsedTemplateInfo::ExplicitInstantiation
)
890 if (SpecKind
!= -1) {
893 Range
= SourceRange(D
.Name
.TemplateId
->LAngleLoc
,
894 D
.Name
.TemplateId
->RAngleLoc
);
896 Range
= TemplateInfo
.getSourceRange();
897 Diag(Range
.getBegin(), diag::err_alias_declaration_specialization
)
898 << SpecKind
<< Range
;
899 SkipUntil(tok::semi
);
903 // Name must be an identifier.
904 if (D
.Name
.getKind() != UnqualifiedIdKind::IK_Identifier
) {
905 Diag(D
.Name
.StartLocation
, diag::err_alias_declaration_not_identifier
);
906 // No removal fixit: can't recover from this.
907 SkipUntil(tok::semi
);
909 } else if (D
.TypenameLoc
.isValid())
910 Diag(D
.TypenameLoc
, diag::err_alias_declaration_not_identifier
)
911 << FixItHint::CreateRemoval(
912 SourceRange(D
.TypenameLoc
, D
.SS
.isNotEmpty() ? D
.SS
.getEndLoc()
914 else if (D
.SS
.isNotEmpty())
915 Diag(D
.SS
.getBeginLoc(), diag::err_alias_declaration_not_identifier
)
916 << FixItHint::CreateRemoval(D
.SS
.getRange());
917 if (D
.EllipsisLoc
.isValid())
918 Diag(D
.EllipsisLoc
, diag::err_alias_declaration_pack_expansion
)
919 << FixItHint::CreateRemoval(SourceRange(D
.EllipsisLoc
));
921 Decl
*DeclFromDeclSpec
= nullptr;
922 TypeResult TypeAlias
=
923 ParseTypeName(nullptr,
924 TemplateInfo
.Kind
? DeclaratorContext::AliasTemplate
925 : DeclaratorContext::AliasDecl
,
926 AS
, &DeclFromDeclSpec
, &Attrs
);
928 *OwnedType
= DeclFromDeclSpec
;
931 DeclEnd
= Tok
.getLocation();
932 if (ExpectAndConsume(tok::semi
, diag::err_expected_after
,
933 !Attrs
.empty() ? "attributes list"
934 : "alias declaration"))
935 SkipUntil(tok::semi
);
937 TemplateParameterLists
*TemplateParams
= TemplateInfo
.TemplateParams
;
938 MultiTemplateParamsArg
TemplateParamsArg(
939 TemplateParams
? TemplateParams
->data() : nullptr,
940 TemplateParams
? TemplateParams
->size() : 0);
941 return Actions
.ActOnAliasDeclaration(getCurScope(), AS
, TemplateParamsArg
,
942 UsingLoc
, D
.Name
, Attrs
, TypeAlias
,
946 static FixItHint
getStaticAssertNoMessageFixIt(const Expr
*AssertExpr
,
947 SourceLocation EndExprLoc
) {
948 if (const auto *BO
= dyn_cast_or_null
<BinaryOperator
>(AssertExpr
)) {
949 if (BO
->getOpcode() == BO_LAnd
&&
950 isa
<StringLiteral
>(BO
->getRHS()->IgnoreImpCasts()))
951 return FixItHint::CreateReplacement(BO
->getOperatorLoc(), ",");
953 return FixItHint::CreateInsertion(EndExprLoc
, ", \"\"");
956 /// ParseStaticAssertDeclaration - Parse C++0x or C11 static_assert-declaration.
958 /// [C++0x] static_assert-declaration:
959 /// static_assert ( constant-expression , string-literal ) ;
961 /// [C11] static_assert-declaration:
962 /// _Static_assert ( constant-expression , string-literal ) ;
964 Decl
*Parser::ParseStaticAssertDeclaration(SourceLocation
&DeclEnd
) {
965 assert(Tok
.isOneOf(tok::kw_static_assert
, tok::kw__Static_assert
) &&
966 "Not a static_assert declaration");
968 // Save the token name used for static assertion.
969 const char *TokName
= Tok
.getName();
971 if (Tok
.is(tok::kw__Static_assert
) && !getLangOpts().C11
)
972 Diag(Tok
, diag::ext_c11_feature
) << Tok
.getName();
973 if (Tok
.is(tok::kw_static_assert
)) {
974 if (!getLangOpts().CPlusPlus
) {
975 if (getLangOpts().C23
)
976 Diag(Tok
, diag::warn_c23_compat_keyword
) << Tok
.getName();
978 Diag(Tok
, diag::ext_ms_static_assert
) << FixItHint::CreateReplacement(
979 Tok
.getLocation(), "_Static_assert");
981 Diag(Tok
, diag::warn_cxx98_compat_static_assert
);
984 SourceLocation StaticAssertLoc
= ConsumeToken();
986 BalancedDelimiterTracker
T(*this, tok::l_paren
);
987 if (T
.consumeOpen()) {
988 Diag(Tok
, diag::err_expected
) << tok::l_paren
;
993 EnterExpressionEvaluationContext
ConstantEvaluated(
994 Actions
, Sema::ExpressionEvaluationContext::ConstantEvaluated
);
995 ExprResult
AssertExpr(ParseConstantExpressionInExprEvalContext());
996 if (AssertExpr
.isInvalid()) {
1001 ExprResult AssertMessage
;
1002 if (Tok
.is(tok::r_paren
)) {
1004 if (getLangOpts().CPlusPlus17
)
1005 DiagVal
= diag::warn_cxx14_compat_static_assert_no_message
;
1006 else if (getLangOpts().CPlusPlus
)
1007 DiagVal
= diag::ext_cxx_static_assert_no_message
;
1008 else if (getLangOpts().C23
)
1009 DiagVal
= diag::warn_c17_compat_static_assert_no_message
;
1011 DiagVal
= diag::ext_c_static_assert_no_message
;
1012 Diag(Tok
, DiagVal
) << getStaticAssertNoMessageFixIt(AssertExpr
.get(),
1015 if (ExpectAndConsume(tok::comma
)) {
1016 SkipUntil(tok::semi
);
1020 bool ParseAsExpression
= false;
1021 if (getLangOpts().CPlusPlus26
) {
1022 for (unsigned I
= 0;; ++I
) {
1023 const Token
&T
= GetLookAheadToken(I
);
1024 if (T
.is(tok::r_paren
))
1026 if (!tokenIsLikeStringLiteral(T
, getLangOpts())) {
1027 ParseAsExpression
= true;
1033 if (ParseAsExpression
)
1034 AssertMessage
= ParseConstantExpressionInExprEvalContext();
1035 else if (tokenIsLikeStringLiteral(Tok
, getLangOpts()))
1036 AssertMessage
= ParseUnevaluatedStringLiteralExpression();
1038 Diag(Tok
, diag::err_expected_string_literal
)
1039 << /*Source='static_assert'*/ 1;
1040 SkipMalformedDecl();
1044 if (AssertMessage
.isInvalid()) {
1045 SkipMalformedDecl();
1052 DeclEnd
= Tok
.getLocation();
1053 ExpectAndConsumeSemi(diag::err_expected_semi_after_static_assert
, TokName
);
1055 return Actions
.ActOnStaticAssertDeclaration(StaticAssertLoc
, AssertExpr
.get(),
1056 AssertMessage
.get(),
1057 T
.getCloseLocation());
1060 /// ParseDecltypeSpecifier - Parse a C++11 decltype specifier.
1062 /// 'decltype' ( expression )
1063 /// 'decltype' ( 'auto' ) [C++1y]
1065 SourceLocation
Parser::ParseDecltypeSpecifier(DeclSpec
&DS
) {
1066 assert(Tok
.isOneOf(tok::kw_decltype
, tok::annot_decltype
) &&
1067 "Not a decltype specifier");
1070 SourceLocation StartLoc
= Tok
.getLocation();
1071 SourceLocation EndLoc
;
1073 if (Tok
.is(tok::annot_decltype
)) {
1074 Result
= getExprAnnotation(Tok
);
1075 EndLoc
= Tok
.getAnnotationEndLoc();
1076 // Unfortunately, we don't know the LParen source location as the annotated
1077 // token doesn't have it.
1078 DS
.setTypeArgumentRange(SourceRange(SourceLocation(), EndLoc
));
1079 ConsumeAnnotationToken();
1080 if (Result
.isInvalid()) {
1081 DS
.SetTypeSpecError();
1085 if (Tok
.getIdentifierInfo()->isStr("decltype"))
1086 Diag(Tok
, diag::warn_cxx98_compat_decltype
);
1090 BalancedDelimiterTracker
T(*this, tok::l_paren
);
1091 if (T
.expectAndConsume(diag::err_expected_lparen_after
, "decltype",
1093 DS
.SetTypeSpecError();
1094 return T
.getOpenLocation() == Tok
.getLocation() ? StartLoc
1095 : T
.getOpenLocation();
1098 // Check for C++1y 'decltype(auto)'.
1099 if (Tok
.is(tok::kw_auto
) && NextToken().is(tok::r_paren
)) {
1100 // the typename-specifier in a function-style cast expression may
1101 // be 'auto' since C++23.
1102 Diag(Tok
.getLocation(),
1103 getLangOpts().CPlusPlus14
1104 ? diag::warn_cxx11_compat_decltype_auto_type_specifier
1105 : diag::ext_decltype_auto_type_specifier
);
1108 // Parse the expression
1110 // C++11 [dcl.type.simple]p4:
1111 // The operand of the decltype specifier is an unevaluated operand.
1112 EnterExpressionEvaluationContext
Unevaluated(
1113 Actions
, Sema::ExpressionEvaluationContext::Unevaluated
, nullptr,
1114 Sema::ExpressionEvaluationContextRecord::EK_Decltype
);
1115 Result
= Actions
.CorrectDelayedTyposInExpr(
1116 ParseExpression(), /*InitDecl=*/nullptr,
1117 /*RecoverUncorrectedTypos=*/false,
1118 [](Expr
*E
) { return E
->hasPlaceholderType() ? ExprError() : E
; });
1119 if (Result
.isInvalid()) {
1120 DS
.SetTypeSpecError();
1121 if (SkipUntil(tok::r_paren
, StopAtSemi
| StopBeforeMatch
)) {
1122 EndLoc
= ConsumeParen();
1124 if (PP
.isBacktrackEnabled() && Tok
.is(tok::semi
)) {
1125 // Backtrack to get the location of the last token before the semi.
1126 PP
.RevertCachedTokens(2);
1127 ConsumeToken(); // the semi.
1128 EndLoc
= ConsumeAnyToken();
1129 assert(Tok
.is(tok::semi
));
1131 EndLoc
= Tok
.getLocation();
1137 Result
= Actions
.ActOnDecltypeExpression(Result
.get());
1142 DS
.setTypeArgumentRange(T
.getRange());
1143 if (T
.getCloseLocation().isInvalid()) {
1144 DS
.SetTypeSpecError();
1145 // FIXME: this should return the location of the last token
1146 // that was consumed (by "consumeClose()")
1147 return T
.getCloseLocation();
1150 if (Result
.isInvalid()) {
1151 DS
.SetTypeSpecError();
1152 return T
.getCloseLocation();
1155 EndLoc
= T
.getCloseLocation();
1157 assert(!Result
.isInvalid());
1159 const char *PrevSpec
= nullptr;
1161 const PrintingPolicy
&Policy
= Actions
.getASTContext().getPrintingPolicy();
1162 // Check for duplicate type specifiers (e.g. "int decltype(a)").
1163 if (Result
.get() ? DS
.SetTypeSpecType(DeclSpec::TST_decltype
, StartLoc
,
1164 PrevSpec
, DiagID
, Result
.get(), Policy
)
1165 : DS
.SetTypeSpecType(DeclSpec::TST_decltype_auto
, StartLoc
,
1166 PrevSpec
, DiagID
, Policy
)) {
1167 Diag(StartLoc
, DiagID
) << PrevSpec
;
1168 DS
.SetTypeSpecError();
1173 void Parser::AnnotateExistingDecltypeSpecifier(const DeclSpec
&DS
,
1174 SourceLocation StartLoc
,
1175 SourceLocation EndLoc
) {
1176 // make sure we have a token we can turn into an annotation token
1177 if (PP
.isBacktrackEnabled()) {
1178 PP
.RevertCachedTokens(1);
1179 if (DS
.getTypeSpecType() == TST_error
) {
1180 // We encountered an error in parsing 'decltype(...)' so lets annotate all
1181 // the tokens in the backtracking cache - that we likely had to skip over
1182 // to get to a token that allows us to resume parsing, such as a
1184 EndLoc
= PP
.getLastCachedTokenLocation();
1187 PP
.EnterToken(Tok
, /*IsReinject*/ true);
1189 Tok
.setKind(tok::annot_decltype
);
1190 setExprAnnotation(Tok
,
1191 DS
.getTypeSpecType() == TST_decltype
? DS
.getRepAsExpr()
1192 : DS
.getTypeSpecType() == TST_decltype_auto
? ExprResult()
1194 Tok
.setAnnotationEndLoc(EndLoc
);
1195 Tok
.setLocation(StartLoc
);
1196 PP
.AnnotateCachedTokens(Tok
);
1199 DeclSpec::TST
Parser::TypeTransformTokToDeclSpec() {
1200 switch (Tok
.getKind()) {
1201 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) \
1202 case tok::kw___##Trait: \
1203 return DeclSpec::TST_##Trait;
1204 #include "clang/Basic/TransformTypeTraits.def"
1206 llvm_unreachable("passed in an unhandled type transformation built-in");
1210 bool Parser::MaybeParseTypeTransformTypeSpecifier(DeclSpec
&DS
) {
1211 if (!NextToken().is(tok::l_paren
)) {
1212 Tok
.setKind(tok::identifier
);
1215 DeclSpec::TST TypeTransformTST
= TypeTransformTokToDeclSpec();
1216 SourceLocation StartLoc
= ConsumeToken();
1218 BalancedDelimiterTracker
T(*this, tok::l_paren
);
1219 if (T
.expectAndConsume(diag::err_expected_lparen_after
, Tok
.getName(),
1223 TypeResult Result
= ParseTypeName();
1224 if (Result
.isInvalid()) {
1225 SkipUntil(tok::r_paren
, StopAtSemi
);
1230 if (T
.getCloseLocation().isInvalid())
1233 const char *PrevSpec
= nullptr;
1235 if (DS
.SetTypeSpecType(TypeTransformTST
, StartLoc
, PrevSpec
, DiagID
,
1237 Actions
.getASTContext().getPrintingPolicy()))
1238 Diag(StartLoc
, DiagID
) << PrevSpec
;
1239 DS
.setTypeArgumentRange(T
.getRange());
1243 /// ParseBaseTypeSpecifier - Parse a C++ base-type-specifier which is either a
1244 /// class name or decltype-specifier. Note that we only check that the result
1245 /// names a type; semantic analysis will need to verify that the type names a
1246 /// class. The result is either a type or null, depending on whether a type
1249 /// base-type-specifier: [C++11 class.derived]
1250 /// class-or-decltype
1251 /// class-or-decltype: [C++11 class.derived]
1252 /// nested-name-specifier[opt] class-name
1253 /// decltype-specifier
1254 /// class-name: [C++ class.name]
1256 /// simple-template-id
1258 /// In C++98, instead of base-type-specifier, we have:
1260 /// ::[opt] nested-name-specifier[opt] class-name
1261 TypeResult
Parser::ParseBaseTypeSpecifier(SourceLocation
&BaseLoc
,
1262 SourceLocation
&EndLocation
) {
1263 // Ignore attempts to use typename
1264 if (Tok
.is(tok::kw_typename
)) {
1265 Diag(Tok
, diag::err_expected_class_name_not_template
)
1266 << FixItHint::CreateRemoval(Tok
.getLocation());
1270 // Parse optional nested-name-specifier
1272 if (ParseOptionalCXXScopeSpecifier(SS
, /*ObjectType=*/nullptr,
1273 /*ObjectHasErrors=*/false,
1274 /*EnteringContext=*/false))
1277 BaseLoc
= Tok
.getLocation();
1279 // Parse decltype-specifier
1280 // tok == kw_decltype is just error recovery, it can only happen when SS
1282 if (Tok
.isOneOf(tok::kw_decltype
, tok::annot_decltype
)) {
1283 if (SS
.isNotEmpty())
1284 Diag(SS
.getBeginLoc(), diag::err_unexpected_scope_on_base_decltype
)
1285 << FixItHint::CreateRemoval(SS
.getRange());
1286 // Fake up a Declarator to use with ActOnTypeName.
1287 DeclSpec
DS(AttrFactory
);
1289 EndLocation
= ParseDecltypeSpecifier(DS
);
1291 Declarator
DeclaratorInfo(DS
, ParsedAttributesView::none(),
1292 DeclaratorContext::TypeName
);
1293 return Actions
.ActOnTypeName(getCurScope(), DeclaratorInfo
);
1296 // Check whether we have a template-id that names a type.
1297 if (Tok
.is(tok::annot_template_id
)) {
1298 TemplateIdAnnotation
*TemplateId
= takeTemplateIdAnnotation(Tok
);
1299 if (TemplateId
->mightBeType()) {
1300 AnnotateTemplateIdTokenAsType(SS
, ImplicitTypenameContext::No
,
1301 /*IsClassName=*/true);
1303 assert(Tok
.is(tok::annot_typename
) && "template-id -> type failed");
1304 TypeResult Type
= getTypeAnnotation(Tok
);
1305 EndLocation
= Tok
.getAnnotationEndLoc();
1306 ConsumeAnnotationToken();
1310 // Fall through to produce an error below.
1313 if (Tok
.isNot(tok::identifier
)) {
1314 Diag(Tok
, diag::err_expected_class_name
);
1318 IdentifierInfo
*Id
= Tok
.getIdentifierInfo();
1319 SourceLocation IdLoc
= ConsumeToken();
1321 if (Tok
.is(tok::less
)) {
1322 // It looks the user intended to write a template-id here, but the
1323 // template-name was wrong. Try to fix that.
1324 // FIXME: Invoke ParseOptionalCXXScopeSpecifier in a "'template' is neither
1325 // required nor permitted" mode, and do this there.
1326 TemplateNameKind TNK
= TNK_Non_template
;
1327 TemplateTy Template
;
1328 if (!Actions
.DiagnoseUnknownTemplateName(*Id
, IdLoc
, getCurScope(), &SS
,
1330 Diag(IdLoc
, diag::err_unknown_template_name
) << Id
;
1333 // Form the template name
1334 UnqualifiedId TemplateName
;
1335 TemplateName
.setIdentifier(Id
, IdLoc
);
1337 // Parse the full template-id, then turn it into a type.
1338 if (AnnotateTemplateIdToken(Template
, TNK
, SS
, SourceLocation(),
1341 if (Tok
.is(tok::annot_template_id
) &&
1342 takeTemplateIdAnnotation(Tok
)->mightBeType())
1343 AnnotateTemplateIdTokenAsType(SS
, ImplicitTypenameContext::No
,
1344 /*IsClassName=*/true);
1346 // If we didn't end up with a typename token, there's nothing more we
1348 if (Tok
.isNot(tok::annot_typename
))
1351 // Retrieve the type from the annotation token, consume that token, and
1353 EndLocation
= Tok
.getAnnotationEndLoc();
1354 TypeResult Type
= getTypeAnnotation(Tok
);
1355 ConsumeAnnotationToken();
1359 // We have an identifier; check whether it is actually a type.
1360 IdentifierInfo
*CorrectedII
= nullptr;
1361 ParsedType Type
= Actions
.getTypeName(
1362 *Id
, IdLoc
, getCurScope(), &SS
, /*isClassName=*/true, false, nullptr,
1363 /*IsCtorOrDtorName=*/false,
1364 /*WantNontrivialTypeSourceInfo=*/true,
1365 /*IsClassTemplateDeductionContext=*/false, ImplicitTypenameContext::No
,
1368 Diag(IdLoc
, diag::err_expected_class_name
);
1372 // Consume the identifier.
1373 EndLocation
= IdLoc
;
1375 // Fake up a Declarator to use with ActOnTypeName.
1376 DeclSpec
DS(AttrFactory
);
1377 DS
.SetRangeStart(IdLoc
);
1378 DS
.SetRangeEnd(EndLocation
);
1379 DS
.getTypeSpecScope() = SS
;
1381 const char *PrevSpec
= nullptr;
1383 DS
.SetTypeSpecType(TST_typename
, IdLoc
, PrevSpec
, DiagID
, Type
,
1384 Actions
.getASTContext().getPrintingPolicy());
1386 Declarator
DeclaratorInfo(DS
, ParsedAttributesView::none(),
1387 DeclaratorContext::TypeName
);
1388 return Actions
.ActOnTypeName(getCurScope(), DeclaratorInfo
);
1391 void Parser::ParseMicrosoftInheritanceClassAttributes(ParsedAttributes
&attrs
) {
1392 while (Tok
.isOneOf(tok::kw___single_inheritance
,
1393 tok::kw___multiple_inheritance
,
1394 tok::kw___virtual_inheritance
)) {
1395 IdentifierInfo
*AttrName
= Tok
.getIdentifierInfo();
1396 auto Kind
= Tok
.getKind();
1397 SourceLocation AttrNameLoc
= ConsumeToken();
1398 attrs
.addNew(AttrName
, AttrNameLoc
, nullptr, AttrNameLoc
, nullptr, 0, Kind
);
1402 /// Determine whether the following tokens are valid after a type-specifier
1403 /// which could be a standalone declaration. This will conservatively return
1404 /// true if there's any doubt, and is appropriate for insert-';' fixits.
1405 bool Parser::isValidAfterTypeSpecifier(bool CouldBeBitfield
) {
1406 // This switch enumerates the valid "follow" set for type-specifiers.
1407 switch (Tok
.getKind()) {
1409 if (Tok
.isRegularKeywordAttribute())
1412 case tok::semi
: // struct foo {...} ;
1413 case tok::star
: // struct foo {...} * P;
1414 case tok::amp
: // struct foo {...} & R = ...
1415 case tok::ampamp
: // struct foo {...} && R = ...
1416 case tok::identifier
: // struct foo {...} V ;
1417 case tok::r_paren
: //(struct foo {...} ) {4}
1418 case tok::coloncolon
: // struct foo {...} :: a::b;
1419 case tok::annot_cxxscope
: // struct foo {...} a:: b;
1420 case tok::annot_typename
: // struct foo {...} a ::b;
1421 case tok::annot_template_id
: // struct foo {...} a<int> ::b;
1422 case tok::kw_decltype
: // struct foo {...} decltype (a)::b;
1423 case tok::l_paren
: // struct foo {...} ( x);
1424 case tok::comma
: // __builtin_offsetof(struct foo{...} ,
1425 case tok::kw_operator
: // struct foo operator ++() {...}
1426 case tok::kw___declspec
: // struct foo {...} __declspec(...)
1427 case tok::l_square
: // void f(struct f [ 3])
1428 case tok::ellipsis
: // void f(struct f ... [Ns])
1429 // FIXME: we should emit semantic diagnostic when declaration
1430 // attribute is in type attribute position.
1431 case tok::kw___attribute
: // struct foo __attribute__((used)) x;
1432 case tok::annot_pragma_pack
: // struct foo {...} _Pragma(pack(pop));
1433 // struct foo {...} _Pragma(section(...));
1434 case tok::annot_pragma_ms_pragma
:
1435 // struct foo {...} _Pragma(vtordisp(pop));
1436 case tok::annot_pragma_ms_vtordisp
:
1437 // struct foo {...} _Pragma(pointers_to_members(...));
1438 case tok::annot_pragma_ms_pointers_to_members
:
1441 return CouldBeBitfield
|| // enum E { ... } : 2;
1442 ColonIsSacred
; // _Generic(..., enum E : 2);
1443 // Microsoft compatibility
1444 case tok::kw___cdecl
: // struct foo {...} __cdecl x;
1445 case tok::kw___fastcall
: // struct foo {...} __fastcall x;
1446 case tok::kw___stdcall
: // struct foo {...} __stdcall x;
1447 case tok::kw___thiscall
: // struct foo {...} __thiscall x;
1448 case tok::kw___vectorcall
: // struct foo {...} __vectorcall x;
1449 // We will diagnose these calling-convention specifiers on non-function
1450 // declarations later, so claim they are valid after a type specifier.
1451 return getLangOpts().MicrosoftExt
;
1453 case tok::kw_const
: // struct foo {...} const x;
1454 case tok::kw_volatile
: // struct foo {...} volatile x;
1455 case tok::kw_restrict
: // struct foo {...} restrict x;
1456 case tok::kw__Atomic
: // struct foo {...} _Atomic x;
1457 case tok::kw___unaligned
: // struct foo {...} __unaligned *x;
1458 // Function specifiers
1459 // Note, no 'explicit'. An explicit function must be either a conversion
1460 // operator or a constructor. Either way, it can't have a return type.
1461 case tok::kw_inline
: // struct foo inline f();
1462 case tok::kw_virtual
: // struct foo virtual f();
1463 case tok::kw_friend
: // struct foo friend f();
1464 // Storage-class specifiers
1465 case tok::kw_static
: // struct foo {...} static x;
1466 case tok::kw_extern
: // struct foo {...} extern x;
1467 case tok::kw_typedef
: // struct foo {...} typedef x;
1468 case tok::kw_register
: // struct foo {...} register x;
1469 case tok::kw_auto
: // struct foo {...} auto x;
1470 case tok::kw_mutable
: // struct foo {...} mutable x;
1471 case tok::kw_thread_local
: // struct foo {...} thread_local x;
1472 case tok::kw_constexpr
: // struct foo {...} constexpr x;
1473 case tok::kw_consteval
: // struct foo {...} consteval x;
1474 case tok::kw_constinit
: // struct foo {...} constinit x;
1475 // As shown above, type qualifiers and storage class specifiers absolutely
1476 // can occur after class specifiers according to the grammar. However,
1477 // almost no one actually writes code like this. If we see one of these,
1478 // it is much more likely that someone missed a semi colon and the
1479 // type/storage class specifier we're seeing is part of the *next*
1480 // intended declaration, as in:
1482 // struct foo { ... }
1485 // We'd really like to emit a missing semicolon error instead of emitting
1486 // an error on the 'int' saying that you can't have two type specifiers in
1487 // the same declaration of X. Because of this, we look ahead past this
1488 // token to see if it's a type specifier. If so, we know the code is
1489 // otherwise invalid, so we can produce the expected semi error.
1490 if (!isKnownToBeTypeSpecifier(NextToken()))
1493 case tok::r_brace
: // struct bar { struct foo {...} }
1494 // Missing ';' at end of struct is accepted as an extension in C mode.
1495 if (!getLangOpts().CPlusPlus
)
1499 // template<class T = class X>
1500 return getLangOpts().CPlusPlus
;
1505 /// ParseClassSpecifier - Parse a C++ class-specifier [C++ class] or
1506 /// elaborated-type-specifier [C++ dcl.type.elab]; we can't tell which
1507 /// until we reach the start of a definition or see a token that
1508 /// cannot start a definition.
1510 /// class-specifier: [C++ class]
1511 /// class-head '{' member-specification[opt] '}'
1512 /// class-head '{' member-specification[opt] '}' attributes[opt]
1514 /// class-key identifier[opt] base-clause[opt]
1515 /// class-key nested-name-specifier identifier base-clause[opt]
1516 /// class-key nested-name-specifier[opt] simple-template-id
1517 /// base-clause[opt]
1518 /// [GNU] class-key attributes[opt] identifier[opt] base-clause[opt]
1519 /// [GNU] class-key attributes[opt] nested-name-specifier
1520 /// identifier base-clause[opt]
1521 /// [GNU] class-key attributes[opt] nested-name-specifier[opt]
1522 /// simple-template-id base-clause[opt]
1528 /// elaborated-type-specifier: [C++ dcl.type.elab]
1529 /// class-key ::[opt] nested-name-specifier[opt] identifier
1530 /// class-key ::[opt] nested-name-specifier[opt] 'template'[opt]
1531 /// simple-template-id
1533 /// Note that the C++ class-specifier and elaborated-type-specifier,
1534 /// together, subsume the C99 struct-or-union-specifier:
1536 /// struct-or-union-specifier: [C99 6.7.2.1]
1537 /// struct-or-union identifier[opt] '{' struct-contents '}'
1538 /// struct-or-union identifier
1539 /// [GNU] struct-or-union attributes[opt] identifier[opt] '{' struct-contents
1540 /// '}' attributes[opt]
1541 /// [GNU] struct-or-union attributes[opt] identifier
1542 /// struct-or-union:
1545 void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind
,
1546 SourceLocation StartLoc
, DeclSpec
&DS
,
1547 const ParsedTemplateInfo
&TemplateInfo
,
1548 AccessSpecifier AS
, bool EnteringContext
,
1549 DeclSpecContext DSC
,
1550 ParsedAttributes
&Attributes
) {
1551 DeclSpec::TST TagType
;
1552 if (TagTokKind
== tok::kw_struct
)
1553 TagType
= DeclSpec::TST_struct
;
1554 else if (TagTokKind
== tok::kw___interface
)
1555 TagType
= DeclSpec::TST_interface
;
1556 else if (TagTokKind
== tok::kw_class
)
1557 TagType
= DeclSpec::TST_class
;
1559 assert(TagTokKind
== tok::kw_union
&& "Not a class specifier");
1560 TagType
= DeclSpec::TST_union
;
1563 if (Tok
.is(tok::code_completion
)) {
1564 // Code completion for a struct, class, or union name.
1566 Actions
.CodeCompleteTag(getCurScope(), TagType
);
1570 // C++20 [temp.class.spec] 13.7.5/10
1571 // The usual access checking rules do not apply to non-dependent names
1572 // used to specify template arguments of the simple-template-id of the
1573 // partial specialization.
1574 // C++20 [temp.spec] 13.9/6:
1575 // The usual access checking rules do not apply to names in a declaration
1576 // of an explicit instantiation or explicit specialization...
1577 const bool shouldDelayDiagsInTag
=
1578 (TemplateInfo
.Kind
!= ParsedTemplateInfo::NonTemplate
);
1579 SuppressAccessChecks
diagsFromTag(*this, shouldDelayDiagsInTag
);
1581 ParsedAttributes
attrs(AttrFactory
);
1582 // If attributes exist after tag, parse them.
1583 MaybeParseAttributes(PAKM_CXX11
| PAKM_Declspec
| PAKM_GNU
, attrs
);
1585 // Parse inheritance specifiers.
1586 if (Tok
.isOneOf(tok::kw___single_inheritance
, tok::kw___multiple_inheritance
,
1587 tok::kw___virtual_inheritance
))
1588 ParseMicrosoftInheritanceClassAttributes(attrs
);
1590 // Allow attributes to precede or succeed the inheritance specifiers.
1591 MaybeParseAttributes(PAKM_CXX11
| PAKM_Declspec
| PAKM_GNU
, attrs
);
1593 // Source location used by FIXIT to insert misplaced
1595 SourceLocation AttrFixitLoc
= Tok
.getLocation();
1597 if (TagType
== DeclSpec::TST_struct
&& Tok
.isNot(tok::identifier
) &&
1598 !Tok
.isAnnotation() && Tok
.getIdentifierInfo() &&
1600 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) tok::kw___##Trait,
1601 #include "clang/Basic/TransformTypeTraits.def"
1602 tok::kw___is_abstract
,
1603 tok::kw___is_aggregate
,
1604 tok::kw___is_arithmetic
,
1606 tok::kw___is_assignable
,
1607 tok::kw___is_base_of
,
1608 tok::kw___is_bounded_array
,
1610 tok::kw___is_complete_type
,
1611 tok::kw___is_compound
,
1613 tok::kw___is_constructible
,
1614 tok::kw___is_convertible
,
1615 tok::kw___is_convertible_to
,
1616 tok::kw___is_destructible
,
1619 tok::kw___is_floating_point
,
1621 tok::kw___is_function
,
1622 tok::kw___is_fundamental
,
1623 tok::kw___is_integral
,
1624 tok::kw___is_interface_class
,
1625 tok::kw___is_literal
,
1626 tok::kw___is_lvalue_expr
,
1627 tok::kw___is_lvalue_reference
,
1628 tok::kw___is_member_function_pointer
,
1629 tok::kw___is_member_object_pointer
,
1630 tok::kw___is_member_pointer
,
1631 tok::kw___is_nothrow_assignable
,
1632 tok::kw___is_nothrow_constructible
,
1633 tok::kw___is_nothrow_destructible
,
1634 tok::kw___is_nullptr
,
1635 tok::kw___is_object
,
1637 tok::kw___is_pointer
,
1638 tok::kw___is_polymorphic
,
1639 tok::kw___is_reference
,
1640 tok::kw___is_referenceable
,
1641 tok::kw___is_rvalue_expr
,
1642 tok::kw___is_rvalue_reference
,
1644 tok::kw___is_scalar
,
1645 tok::kw___is_scoped_enum
,
1646 tok::kw___is_sealed
,
1647 tok::kw___is_signed
,
1648 tok::kw___is_standard_layout
,
1649 tok::kw___is_trivial
,
1650 tok::kw___is_trivially_equality_comparable
,
1651 tok::kw___is_trivially_assignable
,
1652 tok::kw___is_trivially_constructible
,
1653 tok::kw___is_trivially_copyable
,
1654 tok::kw___is_unbounded_array
,
1656 tok::kw___is_unsigned
,
1658 tok::kw___is_volatile
,
1659 tok::kw___reference_binds_to_temporary
,
1660 tok::kw___reference_constructs_from_temporary
))
1661 // GNU libstdc++ 4.2 and libc++ use certain intrinsic names as the
1662 // name of struct templates, but some are keywords in GCC >= 4.3
1663 // and Clang. Therefore, when we see the token sequence "struct
1664 // X", make X into a normal identifier rather than a keyword, to
1665 // allow libstdc++ 4.2 and libc++ to work properly.
1666 TryKeywordIdentFallback(true);
1668 struct PreserveAtomicIdentifierInfoRAII
{
1669 PreserveAtomicIdentifierInfoRAII(Token
&Tok
, bool Enabled
)
1670 : AtomicII(nullptr) {
1673 assert(Tok
.is(tok::kw__Atomic
));
1674 AtomicII
= Tok
.getIdentifierInfo();
1675 AtomicII
->revertTokenIDToIdentifier();
1676 Tok
.setKind(tok::identifier
);
1678 ~PreserveAtomicIdentifierInfoRAII() {
1681 AtomicII
->revertIdentifierToTokenID(tok::kw__Atomic
);
1683 IdentifierInfo
*AtomicII
;
1686 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
1687 // implementation for VS2013 uses _Atomic as an identifier for one of the
1688 // classes in <atomic>. When we are parsing 'struct _Atomic', don't consider
1689 // '_Atomic' to be a keyword. We are careful to undo this so that clang can
1690 // use '_Atomic' in its own header files.
1691 bool ShouldChangeAtomicToIdentifier
= getLangOpts().MSVCCompat
&&
1692 Tok
.is(tok::kw__Atomic
) &&
1693 TagType
== DeclSpec::TST_struct
;
1694 PreserveAtomicIdentifierInfoRAII
AtomicTokenGuard(
1695 Tok
, ShouldChangeAtomicToIdentifier
);
1697 // Parse the (optional) nested-name-specifier.
1698 CXXScopeSpec
&SS
= DS
.getTypeSpecScope();
1699 if (getLangOpts().CPlusPlus
) {
1700 // "FOO : BAR" is not a potential typo for "FOO::BAR". In this context it
1701 // is a base-specifier-list.
1702 ColonProtectionRAIIObject
X(*this);
1705 if (TemplateInfo
.TemplateParams
)
1706 Spec
.setTemplateParamLists(*TemplateInfo
.TemplateParams
);
1708 bool HasValidSpec
= true;
1709 if (ParseOptionalCXXScopeSpecifier(Spec
, /*ObjectType=*/nullptr,
1710 /*ObjectHasErrors=*/false,
1712 DS
.SetTypeSpecError();
1713 HasValidSpec
= false;
1716 if (Tok
.isNot(tok::identifier
) && Tok
.isNot(tok::annot_template_id
)) {
1717 Diag(Tok
, diag::err_expected
) << tok::identifier
;
1718 HasValidSpec
= false;
1724 TemplateParameterLists
*TemplateParams
= TemplateInfo
.TemplateParams
;
1726 auto RecoverFromUndeclaredTemplateName
= [&](IdentifierInfo
*Name
,
1727 SourceLocation NameLoc
,
1728 SourceRange TemplateArgRange
,
1729 bool KnownUndeclared
) {
1730 Diag(NameLoc
, diag::err_explicit_spec_non_template
)
1731 << (TemplateInfo
.Kind
== ParsedTemplateInfo::ExplicitInstantiation
)
1732 << TagTokKind
<< Name
<< TemplateArgRange
<< KnownUndeclared
;
1734 // Strip off the last template parameter list if it was empty, since
1735 // we've removed its template argument list.
1736 if (TemplateParams
&& TemplateInfo
.LastParameterListWasEmpty
) {
1737 if (TemplateParams
->size() > 1) {
1738 TemplateParams
->pop_back();
1740 TemplateParams
= nullptr;
1741 const_cast<ParsedTemplateInfo
&>(TemplateInfo
).Kind
=
1742 ParsedTemplateInfo::NonTemplate
;
1744 } else if (TemplateInfo
.Kind
== ParsedTemplateInfo::ExplicitInstantiation
) {
1745 // Pretend this is just a forward declaration.
1746 TemplateParams
= nullptr;
1747 const_cast<ParsedTemplateInfo
&>(TemplateInfo
).Kind
=
1748 ParsedTemplateInfo::NonTemplate
;
1749 const_cast<ParsedTemplateInfo
&>(TemplateInfo
).TemplateLoc
=
1751 const_cast<ParsedTemplateInfo
&>(TemplateInfo
).ExternLoc
=
1756 // Parse the (optional) class name or simple-template-id.
1757 IdentifierInfo
*Name
= nullptr;
1758 SourceLocation NameLoc
;
1759 TemplateIdAnnotation
*TemplateId
= nullptr;
1760 if (Tok
.is(tok::identifier
)) {
1761 Name
= Tok
.getIdentifierInfo();
1762 NameLoc
= ConsumeToken();
1764 if (Tok
.is(tok::less
) && getLangOpts().CPlusPlus
) {
1765 // The name was supposed to refer to a template, but didn't.
1766 // Eat the template argument list and try to continue parsing this as
1767 // a class (or template thereof).
1768 TemplateArgList TemplateArgs
;
1769 SourceLocation LAngleLoc
, RAngleLoc
;
1770 if (ParseTemplateIdAfterTemplateName(true, LAngleLoc
, TemplateArgs
,
1772 // We couldn't parse the template argument list at all, so don't
1773 // try to give any location information for the list.
1774 LAngleLoc
= RAngleLoc
= SourceLocation();
1776 RecoverFromUndeclaredTemplateName(
1777 Name
, NameLoc
, SourceRange(LAngleLoc
, RAngleLoc
), false);
1779 } else if (Tok
.is(tok::annot_template_id
)) {
1780 TemplateId
= takeTemplateIdAnnotation(Tok
);
1781 NameLoc
= ConsumeAnnotationToken();
1783 if (TemplateId
->Kind
== TNK_Undeclared_template
) {
1784 // Try to resolve the template name to a type template. May update Kind.
1785 Actions
.ActOnUndeclaredTypeTemplateName(
1786 getCurScope(), TemplateId
->Template
, TemplateId
->Kind
, NameLoc
, Name
);
1787 if (TemplateId
->Kind
== TNK_Undeclared_template
) {
1788 RecoverFromUndeclaredTemplateName(
1790 SourceRange(TemplateId
->LAngleLoc
, TemplateId
->RAngleLoc
), true);
1791 TemplateId
= nullptr;
1795 if (TemplateId
&& !TemplateId
->mightBeType()) {
1796 // The template-name in the simple-template-id refers to
1797 // something other than a type template. Give an appropriate
1798 // error message and skip to the ';'.
1799 SourceRange
Range(NameLoc
);
1800 if (SS
.isNotEmpty())
1801 Range
.setBegin(SS
.getBeginLoc());
1803 // FIXME: Name may be null here.
1804 Diag(TemplateId
->LAngleLoc
, diag::err_template_spec_syntax_non_template
)
1805 << TemplateId
->Name
<< static_cast<int>(TemplateId
->Kind
) << Range
;
1807 DS
.SetTypeSpecError();
1808 SkipUntil(tok::semi
, StopBeforeMatch
);
1813 // There are four options here.
1814 // - If we are in a trailing return type, this is always just a reference,
1815 // and we must not try to parse a definition. For instance,
1816 // [] () -> struct S { };
1817 // does not define a type.
1818 // - If we have 'struct foo {...', 'struct foo :...',
1819 // 'struct foo final :' or 'struct foo final {', then this is a definition.
1820 // - If we have 'struct foo;', then this is either a forward declaration
1821 // or a friend declaration, which have to be treated differently.
1822 // - Otherwise we have something like 'struct foo xyz', a reference.
1824 // We also detect these erroneous cases to provide better diagnostic for
1825 // C++11 attributes parsing.
1826 // - attributes follow class name:
1827 // struct foo [[]] {};
1828 // - attributes appear before or after 'final':
1829 // struct foo [[]] final [[]] {};
1831 // However, in type-specifier-seq's, things look like declarations but are
1832 // just references, e.g.
1835 // &T::operator struct s;
1836 // For these, DSC is DeclSpecContext::DSC_type_specifier or
1837 // DeclSpecContext::DSC_alias_declaration.
1839 // If there are attributes after class name, parse them.
1840 MaybeParseCXX11Attributes(Attributes
);
1842 const PrintingPolicy
&Policy
= Actions
.getASTContext().getPrintingPolicy();
1843 Sema::TagUseKind TUK
;
1844 if (isDefiningTypeSpecifierContext(DSC
, getLangOpts().CPlusPlus
) ==
1845 AllowDefiningTypeSpec::No
||
1846 (getLangOpts().OpenMP
&& OpenMPDirectiveParsing
))
1847 TUK
= Sema::TUK_Reference
;
1848 else if (Tok
.is(tok::l_brace
) ||
1849 (DSC
!= DeclSpecContext::DSC_association
&&
1850 getLangOpts().CPlusPlus
&& Tok
.is(tok::colon
)) ||
1851 (isClassCompatibleKeyword() &&
1852 (NextToken().is(tok::l_brace
) || NextToken().is(tok::colon
)))) {
1853 if (DS
.isFriendSpecified()) {
1854 // C++ [class.friend]p2:
1855 // A class shall not be defined in a friend declaration.
1856 Diag(Tok
.getLocation(), diag::err_friend_decl_defines_type
)
1857 << SourceRange(DS
.getFriendSpecLoc());
1859 // Skip everything up to the semicolon, so that this looks like a proper
1860 // friend class (or template thereof) declaration.
1861 SkipUntil(tok::semi
, StopBeforeMatch
);
1862 TUK
= Sema::TUK_Friend
;
1864 // Okay, this is a class definition.
1865 TUK
= Sema::TUK_Definition
;
1867 } else if (isClassCompatibleKeyword() &&
1868 (NextToken().is(tok::l_square
) ||
1869 NextToken().is(tok::kw_alignas
) ||
1870 NextToken().isRegularKeywordAttribute() ||
1871 isCXX11VirtSpecifier(NextToken()) != VirtSpecifiers::VS_None
)) {
1872 // We can't tell if this is a definition or reference
1873 // until we skipped the 'final' and C++11 attribute specifiers.
1874 TentativeParsingAction
PA(*this);
1876 // Skip the 'final', abstract'... keywords.
1877 while (isClassCompatibleKeyword()) {
1881 // Skip C++11 attribute specifiers.
1883 if (Tok
.is(tok::l_square
) && NextToken().is(tok::l_square
)) {
1885 if (!SkipUntil(tok::r_square
, StopAtSemi
))
1887 } else if (Tok
.is(tok::kw_alignas
) && NextToken().is(tok::l_paren
)) {
1890 if (!SkipUntil(tok::r_paren
, StopAtSemi
))
1892 } else if (Tok
.isRegularKeywordAttribute()) {
1899 if (Tok
.isOneOf(tok::l_brace
, tok::colon
))
1900 TUK
= Sema::TUK_Definition
;
1902 TUK
= Sema::TUK_Reference
;
1905 } else if (!isTypeSpecifier(DSC
) &&
1906 (Tok
.is(tok::semi
) ||
1907 (Tok
.isAtStartOfLine() && !isValidAfterTypeSpecifier(false)))) {
1908 TUK
= DS
.isFriendSpecified() ? Sema::TUK_Friend
: Sema::TUK_Declaration
;
1909 if (Tok
.isNot(tok::semi
)) {
1910 const PrintingPolicy
&PPol
= Actions
.getASTContext().getPrintingPolicy();
1911 // A semicolon was missing after this declaration. Diagnose and recover.
1912 ExpectAndConsume(tok::semi
, diag::err_expected_after
,
1913 DeclSpec::getSpecifierName(TagType
, PPol
));
1914 PP
.EnterToken(Tok
, /*IsReinject*/ true);
1915 Tok
.setKind(tok::semi
);
1918 TUK
= Sema::TUK_Reference
;
1920 // Forbid misplaced attributes. In cases of a reference, we pass attributes
1921 // to caller to handle.
1922 if (TUK
!= Sema::TUK_Reference
) {
1923 // If this is not a reference, then the only possible
1924 // valid place for C++11 attributes to appear here
1925 // is between class-key and class-name. If there are
1926 // any attributes after class-name, we try a fixit to move
1927 // them to the right place.
1928 SourceRange AttrRange
= Attributes
.Range
;
1929 if (AttrRange
.isValid()) {
1930 auto *FirstAttr
= Attributes
.empty() ? nullptr : &Attributes
.front();
1931 auto Loc
= AttrRange
.getBegin();
1932 (FirstAttr
&& FirstAttr
->isRegularKeywordAttribute()
1933 ? Diag(Loc
, diag::err_keyword_not_allowed
) << FirstAttr
1934 : Diag(Loc
, diag::err_attributes_not_allowed
))
1936 << FixItHint::CreateInsertionFromRange(
1937 AttrFixitLoc
, CharSourceRange(AttrRange
, true))
1938 << FixItHint::CreateRemoval(AttrRange
);
1940 // Recover by adding misplaced attributes to the attribute list
1941 // of the class so they can be applied on the class later.
1942 attrs
.takeAllFrom(Attributes
);
1946 if (!Name
&& !TemplateId
&&
1947 (DS
.getTypeSpecType() == DeclSpec::TST_error
||
1948 TUK
!= Sema::TUK_Definition
)) {
1949 if (DS
.getTypeSpecType() != DeclSpec::TST_error
) {
1950 // We have a declaration or reference to an anonymous class.
1951 Diag(StartLoc
, diag::err_anon_type_definition
)
1952 << DeclSpec::getSpecifierName(TagType
, Policy
);
1955 // If we are parsing a definition and stop at a base-clause, continue on
1956 // until the semicolon. Continuing from the comma will just trick us into
1957 // thinking we are seeing a variable declaration.
1958 if (TUK
== Sema::TUK_Definition
&& Tok
.is(tok::colon
))
1959 SkipUntil(tok::semi
, StopBeforeMatch
);
1961 SkipUntil(tok::comma
, StopAtSemi
);
1965 // Create the tag portion of the class or class template.
1966 DeclResult TagOrTempResult
= true; // invalid
1967 TypeResult TypeResult
= true; // invalid
1970 Sema::SkipBodyInfo SkipBody
;
1972 // Explicit specialization, class template partial specialization,
1973 // or explicit instantiation.
1974 ASTTemplateArgsPtr
TemplateArgsPtr(TemplateId
->getTemplateArgs(),
1975 TemplateId
->NumArgs
);
1976 if (TemplateId
->isInvalid()) {
1977 // Can't build the declaration.
1978 } else if (TemplateInfo
.Kind
== ParsedTemplateInfo::ExplicitInstantiation
&&
1979 TUK
== Sema::TUK_Declaration
) {
1980 // This is an explicit instantiation of a class template.
1981 ProhibitCXX11Attributes(attrs
, diag::err_attributes_not_allowed
,
1982 diag::err_keyword_not_allowed
,
1983 /*DiagnoseEmptyAttrs=*/true);
1985 TagOrTempResult
= Actions
.ActOnExplicitInstantiation(
1986 getCurScope(), TemplateInfo
.ExternLoc
, TemplateInfo
.TemplateLoc
,
1987 TagType
, StartLoc
, SS
, TemplateId
->Template
,
1988 TemplateId
->TemplateNameLoc
, TemplateId
->LAngleLoc
, TemplateArgsPtr
,
1989 TemplateId
->RAngleLoc
, attrs
);
1991 // Friend template-ids are treated as references unless
1992 // they have template headers, in which case they're ill-formed
1993 // (FIXME: "template <class T> friend class A<T>::B<int>;").
1994 // We diagnose this error in ActOnClassTemplateSpecialization.
1995 } else if (TUK
== Sema::TUK_Reference
||
1996 (TUK
== Sema::TUK_Friend
&&
1997 TemplateInfo
.Kind
== ParsedTemplateInfo::NonTemplate
)) {
1998 ProhibitCXX11Attributes(attrs
, diag::err_attributes_not_allowed
,
1999 diag::err_keyword_not_allowed
,
2000 /*DiagnoseEmptyAttrs=*/true);
2001 TypeResult
= Actions
.ActOnTagTemplateIdType(
2002 TUK
, TagType
, StartLoc
, SS
, TemplateId
->TemplateKWLoc
,
2003 TemplateId
->Template
, TemplateId
->TemplateNameLoc
,
2004 TemplateId
->LAngleLoc
, TemplateArgsPtr
, TemplateId
->RAngleLoc
);
2006 // This is an explicit specialization or a class template
2007 // partial specialization.
2008 TemplateParameterLists FakedParamLists
;
2009 if (TemplateInfo
.Kind
== ParsedTemplateInfo::ExplicitInstantiation
) {
2010 // This looks like an explicit instantiation, because we have
2013 // template class Foo<X>
2015 // but it actually has a definition. Most likely, this was
2016 // meant to be an explicit specialization, but the user forgot
2017 // the '<>' after 'template'.
2018 // It this is friend declaration however, since it cannot have a
2019 // template header, it is most likely that the user meant to
2020 // remove the 'template' keyword.
2021 assert((TUK
== Sema::TUK_Definition
|| TUK
== Sema::TUK_Friend
) &&
2022 "Expected a definition here");
2024 if (TUK
== Sema::TUK_Friend
) {
2025 Diag(DS
.getFriendSpecLoc(), diag::err_friend_explicit_instantiation
);
2026 TemplateParams
= nullptr;
2028 SourceLocation LAngleLoc
=
2029 PP
.getLocForEndOfToken(TemplateInfo
.TemplateLoc
);
2030 Diag(TemplateId
->TemplateNameLoc
,
2031 diag::err_explicit_instantiation_with_definition
)
2032 << SourceRange(TemplateInfo
.TemplateLoc
)
2033 << FixItHint::CreateInsertion(LAngleLoc
, "<>");
2035 // Create a fake template parameter list that contains only
2036 // "template<>", so that we treat this construct as a class
2037 // template specialization.
2038 FakedParamLists
.push_back(Actions
.ActOnTemplateParameterList(
2039 0, SourceLocation(), TemplateInfo
.TemplateLoc
, LAngleLoc
,
2040 std::nullopt
, LAngleLoc
, nullptr));
2041 TemplateParams
= &FakedParamLists
;
2045 // Build the class template specialization.
2046 TagOrTempResult
= Actions
.ActOnClassTemplateSpecialization(
2047 getCurScope(), TagType
, TUK
, StartLoc
, DS
.getModulePrivateSpecLoc(),
2048 SS
, *TemplateId
, attrs
,
2049 MultiTemplateParamsArg(TemplateParams
? &(*TemplateParams
)[0]
2051 TemplateParams
? TemplateParams
->size() : 0),
2054 } else if (TemplateInfo
.Kind
== ParsedTemplateInfo::ExplicitInstantiation
&&
2055 TUK
== Sema::TUK_Declaration
) {
2056 // Explicit instantiation of a member of a class template
2057 // specialization, e.g.,
2059 // template struct Outer<int>::Inner;
2061 ProhibitAttributes(attrs
);
2063 TagOrTempResult
= Actions
.ActOnExplicitInstantiation(
2064 getCurScope(), TemplateInfo
.ExternLoc
, TemplateInfo
.TemplateLoc
,
2065 TagType
, StartLoc
, SS
, Name
, NameLoc
, attrs
);
2066 } else if (TUK
== Sema::TUK_Friend
&&
2067 TemplateInfo
.Kind
!= ParsedTemplateInfo::NonTemplate
) {
2068 ProhibitCXX11Attributes(attrs
, diag::err_attributes_not_allowed
,
2069 diag::err_keyword_not_allowed
,
2070 /*DiagnoseEmptyAttrs=*/true);
2072 TagOrTempResult
= Actions
.ActOnTemplatedFriendTag(
2073 getCurScope(), DS
.getFriendSpecLoc(), TagType
, StartLoc
, SS
, Name
,
2075 MultiTemplateParamsArg(TemplateParams
? &(*TemplateParams
)[0] : nullptr,
2076 TemplateParams
? TemplateParams
->size() : 0));
2078 if (TUK
!= Sema::TUK_Declaration
&& TUK
!= Sema::TUK_Definition
)
2079 ProhibitCXX11Attributes(attrs
, diag::err_attributes_not_allowed
,
2080 diag::err_keyword_not_allowed
,
2081 /* DiagnoseEmptyAttrs=*/true);
2083 if (TUK
== Sema::TUK_Definition
&&
2084 TemplateInfo
.Kind
== ParsedTemplateInfo::ExplicitInstantiation
) {
2085 // If the declarator-id is not a template-id, issue a diagnostic and
2086 // recover by ignoring the 'template' keyword.
2087 Diag(Tok
, diag::err_template_defn_explicit_instantiation
)
2088 << 1 << FixItHint::CreateRemoval(TemplateInfo
.TemplateLoc
);
2089 TemplateParams
= nullptr;
2092 bool IsDependent
= false;
2094 // Don't pass down template parameter lists if this is just a tag
2095 // reference. For example, we don't need the template parameters here:
2096 // template <class T> class A *makeA(T t);
2097 MultiTemplateParamsArg TParams
;
2098 if (TUK
!= Sema::TUK_Reference
&& TemplateParams
)
2100 MultiTemplateParamsArg(&(*TemplateParams
)[0], TemplateParams
->size());
2102 stripTypeAttributesOffDeclSpec(attrs
, DS
, TUK
);
2104 // Declaration or definition of a class type
2105 TagOrTempResult
= Actions
.ActOnTag(
2106 getCurScope(), TagType
, TUK
, StartLoc
, SS
, Name
, NameLoc
, attrs
, AS
,
2107 DS
.getModulePrivateSpecLoc(), TParams
, Owned
, IsDependent
,
2108 SourceLocation(), false, clang::TypeResult(),
2109 DSC
== DeclSpecContext::DSC_type_specifier
,
2110 DSC
== DeclSpecContext::DSC_template_param
||
2111 DSC
== DeclSpecContext::DSC_template_type_arg
,
2112 OffsetOfState
, &SkipBody
);
2114 // If ActOnTag said the type was dependent, try again with the
2115 // less common call.
2117 assert(TUK
== Sema::TUK_Reference
|| TUK
== Sema::TUK_Friend
);
2118 TypeResult
= Actions
.ActOnDependentTag(getCurScope(), TagType
, TUK
, SS
,
2119 Name
, StartLoc
, NameLoc
);
2123 // If this is an elaborated type specifier in function template,
2124 // and we delayed diagnostics before,
2125 // just merge them into the current pool.
2126 if (shouldDelayDiagsInTag
) {
2127 diagsFromTag
.done();
2128 if (TUK
== Sema::TUK_Reference
&&
2129 TemplateInfo
.Kind
== ParsedTemplateInfo::Template
)
2130 diagsFromTag
.redelay();
2133 // If there is a body, parse it and inform the actions module.
2134 if (TUK
== Sema::TUK_Definition
) {
2135 assert(Tok
.is(tok::l_brace
) ||
2136 (getLangOpts().CPlusPlus
&& Tok
.is(tok::colon
)) ||
2137 isClassCompatibleKeyword());
2138 if (SkipBody
.ShouldSkip
)
2139 SkipCXXMemberSpecification(StartLoc
, AttrFixitLoc
, TagType
,
2140 TagOrTempResult
.get());
2141 else if (getLangOpts().CPlusPlus
)
2142 ParseCXXMemberSpecification(StartLoc
, AttrFixitLoc
, attrs
, TagType
,
2143 TagOrTempResult
.get());
2146 SkipBody
.CheckSameAsPrevious
? SkipBody
.New
: TagOrTempResult
.get();
2147 // Parse the definition body.
2148 ParseStructUnionBody(StartLoc
, TagType
, cast
<RecordDecl
>(D
));
2149 if (SkipBody
.CheckSameAsPrevious
&&
2150 !Actions
.ActOnDuplicateDefinition(TagOrTempResult
.get(), SkipBody
)) {
2151 DS
.SetTypeSpecError();
2157 if (!TagOrTempResult
.isInvalid())
2158 // Delayed processing of attributes.
2159 Actions
.ProcessDeclAttributeDelayed(TagOrTempResult
.get(), attrs
);
2161 const char *PrevSpec
= nullptr;
2164 if (!TypeResult
.isInvalid()) {
2165 Result
= DS
.SetTypeSpecType(DeclSpec::TST_typename
, StartLoc
,
2166 NameLoc
.isValid() ? NameLoc
: StartLoc
,
2167 PrevSpec
, DiagID
, TypeResult
.get(), Policy
);
2168 } else if (!TagOrTempResult
.isInvalid()) {
2169 Result
= DS
.SetTypeSpecType(
2170 TagType
, StartLoc
, NameLoc
.isValid() ? NameLoc
: StartLoc
, PrevSpec
,
2171 DiagID
, TagOrTempResult
.get(), Owned
, Policy
);
2173 DS
.SetTypeSpecError();
2178 Diag(StartLoc
, DiagID
) << PrevSpec
;
2180 // At this point, we've successfully parsed a class-specifier in 'definition'
2181 // form (e.g. "struct foo { int x; }". While we could just return here, we're
2182 // going to look at what comes after it to improve error recovery. If an
2183 // impossible token occurs next, we assume that the programmer forgot a ; at
2184 // the end of the declaration and recover that way.
2186 // Also enforce C++ [temp]p3:
2187 // In a template-declaration which defines a class, no declarator
2190 // After a type-specifier, we don't expect a semicolon. This only happens in
2191 // C, since definitions are not permitted in this context in C++.
2192 if (TUK
== Sema::TUK_Definition
&&
2193 (getLangOpts().CPlusPlus
|| !isTypeSpecifier(DSC
)) &&
2194 (TemplateInfo
.Kind
|| !isValidAfterTypeSpecifier(false))) {
2195 if (Tok
.isNot(tok::semi
)) {
2196 const PrintingPolicy
&PPol
= Actions
.getASTContext().getPrintingPolicy();
2197 ExpectAndConsume(tok::semi
, diag::err_expected_after
,
2198 DeclSpec::getSpecifierName(TagType
, PPol
));
2199 // Push this token back into the preprocessor and change our current token
2200 // to ';' so that the rest of the code recovers as though there were an
2201 // ';' after the definition.
2202 PP
.EnterToken(Tok
, /*IsReinject=*/true);
2203 Tok
.setKind(tok::semi
);
2208 /// ParseBaseClause - Parse the base-clause of a C++ class [C++ class.derived].
2210 /// base-clause : [C++ class.derived]
2211 /// ':' base-specifier-list
2212 /// base-specifier-list:
2213 /// base-specifier '...'[opt]
2214 /// base-specifier-list ',' base-specifier '...'[opt]
2215 void Parser::ParseBaseClause(Decl
*ClassDecl
) {
2216 assert(Tok
.is(tok::colon
) && "Not a base clause");
2219 // Build up an array of parsed base specifiers.
2220 SmallVector
<CXXBaseSpecifier
*, 8> BaseInfo
;
2223 // Parse a base-specifier.
2224 BaseResult Result
= ParseBaseSpecifier(ClassDecl
);
2225 if (Result
.isInvalid()) {
2226 // Skip the rest of this base specifier, up until the comma or
2228 SkipUntil(tok::comma
, tok::l_brace
, StopAtSemi
| StopBeforeMatch
);
2230 // Add this to our array of base specifiers.
2231 BaseInfo
.push_back(Result
.get());
2234 // If the next token is a comma, consume it and keep reading
2236 if (!TryConsumeToken(tok::comma
))
2240 // Attach the base specifiers
2241 Actions
.ActOnBaseSpecifiers(ClassDecl
, BaseInfo
);
2244 /// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is
2245 /// one entry in the base class list of a class specifier, for example:
2246 /// class foo : public bar, virtual private baz {
2247 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2249 /// base-specifier: [C++ class.derived]
2250 /// attribute-specifier-seq[opt] base-type-specifier
2251 /// attribute-specifier-seq[opt] 'virtual' access-specifier[opt]
2252 /// base-type-specifier
2253 /// attribute-specifier-seq[opt] access-specifier 'virtual'[opt]
2254 /// base-type-specifier
2255 BaseResult
Parser::ParseBaseSpecifier(Decl
*ClassDecl
) {
2256 bool IsVirtual
= false;
2257 SourceLocation StartLoc
= Tok
.getLocation();
2259 ParsedAttributes
Attributes(AttrFactory
);
2260 MaybeParseCXX11Attributes(Attributes
);
2262 // Parse the 'virtual' keyword.
2263 if (TryConsumeToken(tok::kw_virtual
))
2266 CheckMisplacedCXX11Attribute(Attributes
, StartLoc
);
2268 // Parse an (optional) access specifier.
2269 AccessSpecifier Access
= getAccessSpecifierIfPresent();
2270 if (Access
!= AS_none
) {
2272 if (getLangOpts().HLSL
)
2273 Diag(Tok
.getLocation(), diag::ext_hlsl_access_specifiers
);
2276 CheckMisplacedCXX11Attribute(Attributes
, StartLoc
);
2278 // Parse the 'virtual' keyword (again!), in case it came after the
2279 // access specifier.
2280 if (Tok
.is(tok::kw_virtual
)) {
2281 SourceLocation VirtualLoc
= ConsumeToken();
2283 // Complain about duplicate 'virtual'
2284 Diag(VirtualLoc
, diag::err_dup_virtual
)
2285 << FixItHint::CreateRemoval(VirtualLoc
);
2291 CheckMisplacedCXX11Attribute(Attributes
, StartLoc
);
2293 // Parse the class-name.
2295 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
2296 // implementation for VS2013 uses _Atomic as an identifier for one of the
2297 // classes in <atomic>. Treat '_Atomic' to be an identifier when we are
2298 // parsing the class-name for a base specifier.
2299 if (getLangOpts().MSVCCompat
&& Tok
.is(tok::kw__Atomic
) &&
2300 NextToken().is(tok::less
))
2301 Tok
.setKind(tok::identifier
);
2303 SourceLocation EndLocation
;
2304 SourceLocation BaseLoc
;
2305 TypeResult BaseType
= ParseBaseTypeSpecifier(BaseLoc
, EndLocation
);
2306 if (BaseType
.isInvalid())
2309 // Parse the optional ellipsis (for a pack expansion). The ellipsis is
2310 // actually part of the base-specifier-list grammar productions, but we
2311 // parse it here for convenience.
2312 SourceLocation EllipsisLoc
;
2313 TryConsumeToken(tok::ellipsis
, EllipsisLoc
);
2315 // Find the complete source range for the base-specifier.
2316 SourceRange
Range(StartLoc
, EndLocation
);
2318 // Notify semantic analysis that we have parsed a complete
2320 return Actions
.ActOnBaseSpecifier(ClassDecl
, Range
, Attributes
, IsVirtual
,
2321 Access
, BaseType
.get(), BaseLoc
,
2325 /// getAccessSpecifierIfPresent - Determine whether the next token is
2326 /// a C++ access-specifier.
2328 /// access-specifier: [C++ class.derived]
2332 AccessSpecifier
Parser::getAccessSpecifierIfPresent() const {
2333 switch (Tok
.getKind()) {
2336 case tok::kw_private
:
2338 case tok::kw_protected
:
2339 return AS_protected
;
2340 case tok::kw_public
:
2345 /// If the given declarator has any parts for which parsing has to be
2346 /// delayed, e.g., default arguments or an exception-specification, create a
2347 /// late-parsed method declaration record to handle the parsing at the end of
2348 /// the class definition.
2349 void Parser::HandleMemberFunctionDeclDelays(Declarator
&DeclaratorInfo
,
2351 DeclaratorChunk::FunctionTypeInfo
&FTI
= DeclaratorInfo
.getFunctionTypeInfo();
2352 // If there was a late-parsed exception-specification, we'll need a
2354 bool NeedLateParse
= FTI
.getExceptionSpecType() == EST_Unparsed
;
2356 if (!NeedLateParse
) {
2357 // Look ahead to see if there are any default args
2358 for (unsigned ParamIdx
= 0; ParamIdx
< FTI
.NumParams
; ++ParamIdx
) {
2359 auto Param
= cast
<ParmVarDecl
>(FTI
.Params
[ParamIdx
].Param
);
2360 if (Param
->hasUnparsedDefaultArg()) {
2361 NeedLateParse
= true;
2367 if (NeedLateParse
) {
2368 // Push this method onto the stack of late-parsed method
2370 auto LateMethod
= new LateParsedMethodDeclaration(this, ThisDecl
);
2371 getCurrentClass().LateParsedDeclarations
.push_back(LateMethod
);
2373 // Push tokens for each parameter. Those that do not have defaults will be
2374 // NULL. We need to track all the parameters so that we can push them into
2375 // scope for later parameters and perhaps for the exception specification.
2376 LateMethod
->DefaultArgs
.reserve(FTI
.NumParams
);
2377 for (unsigned ParamIdx
= 0; ParamIdx
< FTI
.NumParams
; ++ParamIdx
)
2378 LateMethod
->DefaultArgs
.push_back(LateParsedDefaultArgument(
2379 FTI
.Params
[ParamIdx
].Param
,
2380 std::move(FTI
.Params
[ParamIdx
].DefaultArgTokens
)));
2382 // Stash the exception-specification tokens in the late-pased method.
2383 if (FTI
.getExceptionSpecType() == EST_Unparsed
) {
2384 LateMethod
->ExceptionSpecTokens
= FTI
.ExceptionSpecTokens
;
2385 FTI
.ExceptionSpecTokens
= nullptr;
2390 /// isCXX11VirtSpecifier - Determine whether the given token is a C++11
2397 VirtSpecifiers::Specifier
Parser::isCXX11VirtSpecifier(const Token
&Tok
) const {
2398 if (!getLangOpts().CPlusPlus
|| Tok
.isNot(tok::identifier
))
2399 return VirtSpecifiers::VS_None
;
2401 IdentifierInfo
*II
= Tok
.getIdentifierInfo();
2403 // Initialize the contextual keywords.
2405 Ident_final
= &PP
.getIdentifierTable().get("final");
2406 if (getLangOpts().GNUKeywords
)
2407 Ident_GNU_final
= &PP
.getIdentifierTable().get("__final");
2408 if (getLangOpts().MicrosoftExt
) {
2409 Ident_sealed
= &PP
.getIdentifierTable().get("sealed");
2410 Ident_abstract
= &PP
.getIdentifierTable().get("abstract");
2412 Ident_override
= &PP
.getIdentifierTable().get("override");
2415 if (II
== Ident_override
)
2416 return VirtSpecifiers::VS_Override
;
2418 if (II
== Ident_sealed
)
2419 return VirtSpecifiers::VS_Sealed
;
2421 if (II
== Ident_abstract
)
2422 return VirtSpecifiers::VS_Abstract
;
2424 if (II
== Ident_final
)
2425 return VirtSpecifiers::VS_Final
;
2427 if (II
== Ident_GNU_final
)
2428 return VirtSpecifiers::VS_GNU_Final
;
2430 return VirtSpecifiers::VS_None
;
2433 /// ParseOptionalCXX11VirtSpecifierSeq - Parse a virt-specifier-seq.
2435 /// virt-specifier-seq:
2437 /// virt-specifier-seq virt-specifier
2438 void Parser::ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers
&VS
,
2440 SourceLocation FriendLoc
) {
2442 VirtSpecifiers::Specifier Specifier
= isCXX11VirtSpecifier();
2443 if (Specifier
== VirtSpecifiers::VS_None
)
2446 if (FriendLoc
.isValid()) {
2447 Diag(Tok
.getLocation(), diag::err_friend_decl_spec
)
2448 << VirtSpecifiers::getSpecifierName(Specifier
)
2449 << FixItHint::CreateRemoval(Tok
.getLocation())
2450 << SourceRange(FriendLoc
, FriendLoc
);
2455 // C++ [class.mem]p8:
2456 // A virt-specifier-seq shall contain at most one of each virt-specifier.
2457 const char *PrevSpec
= nullptr;
2458 if (VS
.SetSpecifier(Specifier
, Tok
.getLocation(), PrevSpec
))
2459 Diag(Tok
.getLocation(), diag::err_duplicate_virt_specifier
)
2460 << PrevSpec
<< FixItHint::CreateRemoval(Tok
.getLocation());
2462 if (IsInterface
&& (Specifier
== VirtSpecifiers::VS_Final
||
2463 Specifier
== VirtSpecifiers::VS_Sealed
)) {
2464 Diag(Tok
.getLocation(), diag::err_override_control_interface
)
2465 << VirtSpecifiers::getSpecifierName(Specifier
);
2466 } else if (Specifier
== VirtSpecifiers::VS_Sealed
) {
2467 Diag(Tok
.getLocation(), diag::ext_ms_sealed_keyword
);
2468 } else if (Specifier
== VirtSpecifiers::VS_Abstract
) {
2469 Diag(Tok
.getLocation(), diag::ext_ms_abstract_keyword
);
2470 } else if (Specifier
== VirtSpecifiers::VS_GNU_Final
) {
2471 Diag(Tok
.getLocation(), diag::ext_warn_gnu_final
);
2473 Diag(Tok
.getLocation(),
2474 getLangOpts().CPlusPlus11
2475 ? diag::warn_cxx98_compat_override_control_keyword
2476 : diag::ext_override_control_keyword
)
2477 << VirtSpecifiers::getSpecifierName(Specifier
);
2483 /// isCXX11FinalKeyword - Determine whether the next token is a C++11
2484 /// 'final' or Microsoft 'sealed' contextual keyword.
2485 bool Parser::isCXX11FinalKeyword() const {
2486 VirtSpecifiers::Specifier Specifier
= isCXX11VirtSpecifier();
2487 return Specifier
== VirtSpecifiers::VS_Final
||
2488 Specifier
== VirtSpecifiers::VS_GNU_Final
||
2489 Specifier
== VirtSpecifiers::VS_Sealed
;
2492 /// isClassCompatibleKeyword - Determine whether the next token is a C++11
2493 /// 'final' or Microsoft 'sealed' or 'abstract' contextual keywords.
2494 bool Parser::isClassCompatibleKeyword() const {
2495 VirtSpecifiers::Specifier Specifier
= isCXX11VirtSpecifier();
2496 return Specifier
== VirtSpecifiers::VS_Final
||
2497 Specifier
== VirtSpecifiers::VS_GNU_Final
||
2498 Specifier
== VirtSpecifiers::VS_Sealed
||
2499 Specifier
== VirtSpecifiers::VS_Abstract
;
2502 /// Parse a C++ member-declarator up to, but not including, the optional
2503 /// brace-or-equal-initializer or pure-specifier.
2504 bool Parser::ParseCXXMemberDeclaratorBeforeInitializer(
2505 Declarator
&DeclaratorInfo
, VirtSpecifiers
&VS
, ExprResult
&BitfieldSize
,
2506 LateParsedAttrList
&LateParsedAttrs
) {
2507 // member-declarator:
2508 // declarator virt-specifier-seq[opt] pure-specifier[opt]
2509 // declarator requires-clause
2510 // declarator brace-or-equal-initializer[opt]
2511 // identifier attribute-specifier-seq[opt] ':' constant-expression
2512 // brace-or-equal-initializer[opt]
2513 // ':' constant-expression
2515 // NOTE: the latter two productions are a proposed bugfix rather than the
2516 // current grammar rules as of C++20.
2517 if (Tok
.isNot(tok::colon
))
2518 ParseDeclarator(DeclaratorInfo
);
2520 DeclaratorInfo
.SetIdentifier(nullptr, Tok
.getLocation());
2522 if (!DeclaratorInfo
.isFunctionDeclarator() && TryConsumeToken(tok::colon
)) {
2523 assert(DeclaratorInfo
.isPastIdentifier() &&
2524 "don't know where identifier would go yet?");
2525 BitfieldSize
= ParseConstantExpression();
2526 if (BitfieldSize
.isInvalid())
2527 SkipUntil(tok::comma
, StopAtSemi
| StopBeforeMatch
);
2528 } else if (Tok
.is(tok::kw_requires
)) {
2529 ParseTrailingRequiresClause(DeclaratorInfo
);
2531 ParseOptionalCXX11VirtSpecifierSeq(
2532 VS
, getCurrentClass().IsInterface
,
2533 DeclaratorInfo
.getDeclSpec().getFriendSpecLoc());
2535 MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo
,
2539 // If a simple-asm-expr is present, parse it.
2540 if (Tok
.is(tok::kw_asm
)) {
2542 ExprResult
AsmLabel(ParseSimpleAsm(/*ForAsmLabel*/ true, &Loc
));
2543 if (AsmLabel
.isInvalid())
2544 SkipUntil(tok::comma
, StopAtSemi
| StopBeforeMatch
);
2546 DeclaratorInfo
.setAsmLabel(AsmLabel
.get());
2547 DeclaratorInfo
.SetRangeEnd(Loc
);
2550 // If attributes exist after the declarator, but before an '{', parse them.
2551 // However, this does not apply for [[]] attributes (which could show up
2552 // before or after the __attribute__ attributes).
2553 DiagnoseAndSkipCXX11Attributes();
2554 MaybeParseGNUAttributes(DeclaratorInfo
, &LateParsedAttrs
);
2555 DiagnoseAndSkipCXX11Attributes();
2557 // For compatibility with code written to older Clang, also accept a
2558 // virt-specifier *after* the GNU attributes.
2559 if (BitfieldSize
.isUnset() && VS
.isUnset()) {
2560 ParseOptionalCXX11VirtSpecifierSeq(
2561 VS
, getCurrentClass().IsInterface
,
2562 DeclaratorInfo
.getDeclSpec().getFriendSpecLoc());
2563 if (!VS
.isUnset()) {
2564 // If we saw any GNU-style attributes that are known to GCC followed by a
2565 // virt-specifier, issue a GCC-compat warning.
2566 for (const ParsedAttr
&AL
: DeclaratorInfo
.getAttributes())
2567 if (AL
.isKnownToGCC() && !AL
.isCXX11Attribute())
2568 Diag(AL
.getLoc(), diag::warn_gcc_attribute_location
);
2570 MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo
,
2575 // If this has neither a name nor a bit width, something has gone seriously
2576 // wrong. Skip until the semi-colon or }.
2577 if (!DeclaratorInfo
.hasName() && BitfieldSize
.isUnset()) {
2578 // If so, skip until the semi-colon or a }.
2579 SkipUntil(tok::r_brace
, StopAtSemi
| StopBeforeMatch
);
2585 /// Look for declaration specifiers possibly occurring after C++11
2586 /// virt-specifier-seq and diagnose them.
2587 void Parser::MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(
2588 Declarator
&D
, VirtSpecifiers
&VS
) {
2589 DeclSpec
DS(AttrFactory
);
2591 // GNU-style and C++11 attributes are not allowed here, but they will be
2592 // handled by the caller. Diagnose everything else.
2593 ParseTypeQualifierListOpt(
2594 DS
, AR_NoAttributesParsed
, false,
2595 /*IdentifierRequired=*/false, llvm::function_ref
<void()>([&]() {
2596 Actions
.CodeCompleteFunctionQualifiers(DS
, D
, &VS
);
2598 D
.ExtendWithDeclSpec(DS
);
2600 if (D
.isFunctionDeclarator()) {
2601 auto &Function
= D
.getFunctionTypeInfo();
2602 if (DS
.getTypeQualifiers() != DeclSpec::TQ_unspecified
) {
2603 auto DeclSpecCheck
= [&](DeclSpec::TQ TypeQual
, StringRef FixItName
,
2604 SourceLocation SpecLoc
) {
2605 FixItHint Insertion
;
2606 auto &MQ
= Function
.getOrCreateMethodQualifiers();
2607 if (!(MQ
.getTypeQualifiers() & TypeQual
)) {
2608 std::string
Name(FixItName
.data());
2610 Insertion
= FixItHint::CreateInsertion(VS
.getFirstLocation(), Name
);
2611 MQ
.SetTypeQual(TypeQual
, SpecLoc
);
2613 Diag(SpecLoc
, diag::err_declspec_after_virtspec
)
2615 << VirtSpecifiers::getSpecifierName(VS
.getLastSpecifier())
2616 << FixItHint::CreateRemoval(SpecLoc
) << Insertion
;
2618 DS
.forEachQualifier(DeclSpecCheck
);
2621 // Parse ref-qualifiers.
2622 bool RefQualifierIsLValueRef
= true;
2623 SourceLocation RefQualifierLoc
;
2624 if (ParseRefQualifier(RefQualifierIsLValueRef
, RefQualifierLoc
)) {
2625 const char *Name
= (RefQualifierIsLValueRef
? "& " : "&& ");
2626 FixItHint Insertion
=
2627 FixItHint::CreateInsertion(VS
.getFirstLocation(), Name
);
2628 Function
.RefQualifierIsLValueRef
= RefQualifierIsLValueRef
;
2629 Function
.RefQualifierLoc
= RefQualifierLoc
;
2631 Diag(RefQualifierLoc
, diag::err_declspec_after_virtspec
)
2632 << (RefQualifierIsLValueRef
? "&" : "&&")
2633 << VirtSpecifiers::getSpecifierName(VS
.getLastSpecifier())
2634 << FixItHint::CreateRemoval(RefQualifierLoc
) << Insertion
;
2635 D
.SetRangeEnd(RefQualifierLoc
);
2640 /// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration.
2642 /// member-declaration:
2643 /// decl-specifier-seq[opt] member-declarator-list[opt] ';'
2644 /// function-definition ';'[opt]
2645 /// ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO]
2646 /// using-declaration [TODO]
2647 /// [C++0x] static_assert-declaration
2648 /// template-declaration
2649 /// [GNU] '__extension__' member-declaration
2651 /// member-declarator-list:
2652 /// member-declarator
2653 /// member-declarator-list ',' member-declarator
2655 /// member-declarator:
2656 /// declarator virt-specifier-seq[opt] pure-specifier[opt]
2657 /// [C++2a] declarator requires-clause
2658 /// declarator constant-initializer[opt]
2659 /// [C++11] declarator brace-or-equal-initializer[opt]
2660 /// identifier[opt] ':' constant-expression
2662 /// virt-specifier-seq:
2664 /// virt-specifier-seq virt-specifier
2674 /// constant-initializer:
2675 /// '=' constant-expression
2677 Parser::DeclGroupPtrTy
2678 Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS
,
2679 ParsedAttributes
&AccessAttrs
,
2680 const ParsedTemplateInfo
&TemplateInfo
,
2681 ParsingDeclRAIIObject
*TemplateDiags
) {
2682 if (Tok
.is(tok::at
)) {
2683 if (getLangOpts().ObjC
&& NextToken().isObjCAtKeyword(tok::objc_defs
))
2684 Diag(Tok
, diag::err_at_defs_cxx
);
2686 Diag(Tok
, diag::err_at_in_class
);
2689 SkipUntil(tok::r_brace
, StopAtSemi
);
2693 // Turn on colon protection early, while parsing declspec, although there is
2694 // nothing to protect there. It prevents from false errors if error recovery
2695 // incorrectly determines where the declspec ends, as in the example:
2696 // struct A { enum class B { C }; };
2698 // struct D { A::B : C; };
2699 ColonProtectionRAIIObject
X(*this);
2701 // Access declarations.
2702 bool MalformedTypeSpec
= false;
2703 if (!TemplateInfo
.Kind
&&
2704 Tok
.isOneOf(tok::identifier
, tok::coloncolon
, tok::kw___super
)) {
2705 if (TryAnnotateCXXScopeToken())
2706 MalformedTypeSpec
= true;
2709 if (Tok
.isNot(tok::annot_cxxscope
))
2710 isAccessDecl
= false;
2711 else if (NextToken().is(tok::identifier
))
2712 isAccessDecl
= GetLookAheadToken(2).is(tok::semi
);
2714 isAccessDecl
= NextToken().is(tok::kw_operator
);
2717 // Collect the scope specifier token we annotated earlier.
2719 ParseOptionalCXXScopeSpecifier(SS
, /*ObjectType=*/nullptr,
2720 /*ObjectHasErrors=*/false,
2721 /*EnteringContext=*/false);
2723 if (SS
.isInvalid()) {
2724 SkipUntil(tok::semi
);
2728 // Try to parse an unqualified-id.
2729 SourceLocation TemplateKWLoc
;
2731 if (ParseUnqualifiedId(SS
, /*ObjectType=*/nullptr,
2732 /*ObjectHadErrors=*/false, false, true, true,
2733 false, &TemplateKWLoc
, Name
)) {
2734 SkipUntil(tok::semi
);
2738 // TODO: recover from mistakenly-qualified operator declarations.
2739 if (ExpectAndConsume(tok::semi
, diag::err_expected_after
,
2740 "access declaration")) {
2741 SkipUntil(tok::semi
);
2745 // FIXME: We should do something with the 'template' keyword here.
2746 return DeclGroupPtrTy::make(DeclGroupRef(Actions
.ActOnUsingDeclaration(
2747 getCurScope(), AS
, /*UsingLoc*/ SourceLocation(),
2748 /*TypenameLoc*/ SourceLocation(), SS
, Name
,
2749 /*EllipsisLoc*/ SourceLocation(),
2750 /*AttrList*/ ParsedAttributesView())));
2754 // static_assert-declaration. A templated static_assert declaration is
2755 // diagnosed in Parser::ParseSingleDeclarationAfterTemplate.
2756 if (!TemplateInfo
.Kind
&&
2757 Tok
.isOneOf(tok::kw_static_assert
, tok::kw__Static_assert
)) {
2758 SourceLocation DeclEnd
;
2759 return DeclGroupPtrTy::make(
2760 DeclGroupRef(ParseStaticAssertDeclaration(DeclEnd
)));
2763 if (Tok
.is(tok::kw_template
)) {
2764 assert(!TemplateInfo
.TemplateParams
&&
2765 "Nested template improperly parsed?");
2766 ObjCDeclContextSwitch
ObjCDC(*this);
2767 SourceLocation DeclEnd
;
2768 return DeclGroupPtrTy::make(
2769 DeclGroupRef(ParseTemplateDeclarationOrSpecialization(
2770 DeclaratorContext::Member
, DeclEnd
, AccessAttrs
, AS
)));
2773 // Handle: member-declaration ::= '__extension__' member-declaration
2774 if (Tok
.is(tok::kw___extension__
)) {
2775 // __extension__ silences extension warnings in the subexpression.
2776 ExtensionRAIIObject
O(Diags
); // Use RAII to do this.
2778 return ParseCXXClassMemberDeclaration(AS
, AccessAttrs
, TemplateInfo
,
2782 ParsedAttributes
DeclAttrs(AttrFactory
);
2783 // Optional C++11 attribute-specifier
2784 MaybeParseCXX11Attributes(DeclAttrs
);
2786 // The next token may be an OpenMP pragma annotation token. That would
2787 // normally be handled from ParseCXXClassMemberDeclarationWithPragmas, but in
2788 // this case, it came from an *attribute* rather than a pragma. Handle it now.
2789 if (Tok
.is(tok::annot_attr_openmp
))
2790 return ParseOpenMPDeclarativeDirectiveWithExtDecl(AS
, DeclAttrs
);
2792 if (Tok
.is(tok::kw_using
)) {
2794 SourceLocation UsingLoc
= ConsumeToken();
2796 // Consume unexpected 'template' keywords.
2797 while (Tok
.is(tok::kw_template
)) {
2798 SourceLocation TemplateLoc
= ConsumeToken();
2799 Diag(TemplateLoc
, diag::err_unexpected_template_after_using
)
2800 << FixItHint::CreateRemoval(TemplateLoc
);
2803 if (Tok
.is(tok::kw_namespace
)) {
2804 Diag(UsingLoc
, diag::err_using_namespace_in_class
);
2805 SkipUntil(tok::semi
, StopBeforeMatch
);
2808 SourceLocation DeclEnd
;
2809 // Otherwise, it must be a using-declaration or an alias-declaration.
2810 return ParseUsingDeclaration(DeclaratorContext::Member
, TemplateInfo
,
2811 UsingLoc
, DeclEnd
, DeclAttrs
, AS
);
2814 ParsedAttributes
DeclSpecAttrs(AttrFactory
);
2815 MaybeParseMicrosoftAttributes(DeclSpecAttrs
);
2817 // Hold late-parsed attributes so we can attach a Decl to them later.
2818 LateParsedAttrList CommonLateParsedAttrs
;
2820 // decl-specifier-seq:
2821 // Parse the common declaration-specifiers piece.
2822 ParsingDeclSpec
DS(*this, TemplateDiags
);
2823 DS
.takeAttributesFrom(DeclSpecAttrs
);
2825 if (MalformedTypeSpec
)
2826 DS
.SetTypeSpecError();
2828 // Turn off usual access checking for templates explicit specialization
2829 // and instantiation.
2830 // C++20 [temp.spec] 13.9/6.
2831 // This disables the access checking rules for member function template
2832 // explicit instantiation and explicit specialization.
2833 bool IsTemplateSpecOrInst
=
2834 (TemplateInfo
.Kind
== ParsedTemplateInfo::ExplicitInstantiation
||
2835 TemplateInfo
.Kind
== ParsedTemplateInfo::ExplicitSpecialization
);
2836 SuppressAccessChecks
diagsFromTag(*this, IsTemplateSpecOrInst
);
2838 ParseDeclarationSpecifiers(DS
, TemplateInfo
, AS
, DeclSpecContext::DSC_class
,
2839 &CommonLateParsedAttrs
);
2841 if (IsTemplateSpecOrInst
)
2842 diagsFromTag
.done();
2844 // Turn off colon protection that was set for declspec.
2847 // If we had a free-standing type definition with a missing semicolon, we
2848 // may get this far before the problem becomes obvious.
2849 if (DS
.hasTagDefinition() &&
2850 TemplateInfo
.Kind
== ParsedTemplateInfo::NonTemplate
&&
2851 DiagnoseMissingSemiAfterTagDefinition(DS
, AS
, DeclSpecContext::DSC_class
,
2852 &CommonLateParsedAttrs
))
2855 MultiTemplateParamsArg
TemplateParams(
2856 TemplateInfo
.TemplateParams
? TemplateInfo
.TemplateParams
->data()
2858 TemplateInfo
.TemplateParams
? TemplateInfo
.TemplateParams
->size() : 0);
2860 if (TryConsumeToken(tok::semi
)) {
2861 if (DS
.isFriendSpecified())
2862 ProhibitAttributes(DeclAttrs
);
2864 RecordDecl
*AnonRecord
= nullptr;
2865 Decl
*TheDecl
= Actions
.ParsedFreeStandingDeclSpec(
2866 getCurScope(), AS
, DS
, DeclAttrs
, TemplateParams
, false, AnonRecord
);
2867 Actions
.ActOnDefinedDeclarationSpecifier(TheDecl
);
2868 DS
.complete(TheDecl
);
2870 Decl
*decls
[] = {AnonRecord
, TheDecl
};
2871 return Actions
.BuildDeclaratorGroup(decls
);
2873 return Actions
.ConvertDeclToDeclGroup(TheDecl
);
2876 if (DS
.hasTagDefinition())
2877 Actions
.ActOnDefinedDeclarationSpecifier(DS
.getRepAsDecl());
2879 ParsingDeclarator
DeclaratorInfo(*this, DS
, DeclAttrs
,
2880 DeclaratorContext::Member
);
2881 if (TemplateInfo
.TemplateParams
)
2882 DeclaratorInfo
.setTemplateParameterLists(TemplateParams
);
2885 // Hold late-parsed attributes so we can attach a Decl to them later.
2886 LateParsedAttrList LateParsedAttrs
;
2888 SourceLocation EqualLoc
;
2889 SourceLocation PureSpecLoc
;
2891 auto TryConsumePureSpecifier
= [&](bool AllowDefinition
) {
2892 if (Tok
.isNot(tok::equal
))
2895 auto &Zero
= NextToken();
2896 SmallString
<8> Buffer
;
2897 if (Zero
.isNot(tok::numeric_constant
) ||
2898 PP
.getSpelling(Zero
, Buffer
) != "0")
2901 auto &After
= GetLookAheadToken(2);
2902 if (!After
.isOneOf(tok::semi
, tok::comma
) &&
2903 !(AllowDefinition
&&
2904 After
.isOneOf(tok::l_brace
, tok::colon
, tok::kw_try
)))
2907 EqualLoc
= ConsumeToken();
2908 PureSpecLoc
= ConsumeToken();
2912 SmallVector
<Decl
*, 8> DeclsInGroup
;
2913 ExprResult BitfieldSize
;
2914 ExprResult TrailingRequiresClause
;
2915 bool ExpectSemi
= true;
2917 // C++20 [temp.spec] 13.9/6.
2918 // This disables the access checking rules for member function template
2919 // explicit instantiation and explicit specialization.
2920 SuppressAccessChecks
SAC(*this, IsTemplateSpecOrInst
);
2922 // Parse the first declarator.
2923 if (ParseCXXMemberDeclaratorBeforeInitializer(
2924 DeclaratorInfo
, VS
, BitfieldSize
, LateParsedAttrs
)) {
2925 TryConsumeToken(tok::semi
);
2929 if (IsTemplateSpecOrInst
)
2932 // Check for a member function definition.
2933 if (BitfieldSize
.isUnset()) {
2934 // MSVC permits pure specifier on inline functions defined at class scope.
2935 // Hence check for =0 before checking for function definition.
2936 if (getLangOpts().MicrosoftExt
&& DeclaratorInfo
.isDeclarationOfFunction())
2937 TryConsumePureSpecifier(/*AllowDefinition*/ true);
2939 FunctionDefinitionKind DefinitionKind
= FunctionDefinitionKind::Declaration
;
2940 // function-definition:
2942 // In C++11, a non-function declarator followed by an open brace is a
2943 // braced-init-list for an in-class member initialization, not an
2944 // erroneous function definition.
2945 if (Tok
.is(tok::l_brace
) && !getLangOpts().CPlusPlus11
) {
2946 DefinitionKind
= FunctionDefinitionKind::Definition
;
2947 } else if (DeclaratorInfo
.isFunctionDeclarator()) {
2948 if (Tok
.isOneOf(tok::l_brace
, tok::colon
, tok::kw_try
)) {
2949 DefinitionKind
= FunctionDefinitionKind::Definition
;
2950 } else if (Tok
.is(tok::equal
)) {
2951 const Token
&KW
= NextToken();
2952 if (KW
.is(tok::kw_default
))
2953 DefinitionKind
= FunctionDefinitionKind::Defaulted
;
2954 else if (KW
.is(tok::kw_delete
))
2955 DefinitionKind
= FunctionDefinitionKind::Deleted
;
2956 else if (KW
.is(tok::code_completion
)) {
2958 Actions
.CodeCompleteAfterFunctionEquals(DeclaratorInfo
);
2963 DeclaratorInfo
.setFunctionDefinitionKind(DefinitionKind
);
2965 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
2966 // to a friend declaration, that declaration shall be a definition.
2967 if (DeclaratorInfo
.isFunctionDeclarator() &&
2968 DefinitionKind
== FunctionDefinitionKind::Declaration
&&
2969 DS
.isFriendSpecified()) {
2970 // Diagnose attributes that appear before decl specifier:
2971 // [[]] friend int foo();
2972 ProhibitAttributes(DeclAttrs
);
2975 if (DefinitionKind
!= FunctionDefinitionKind::Declaration
) {
2976 if (!DeclaratorInfo
.isFunctionDeclarator()) {
2977 Diag(DeclaratorInfo
.getIdentifierLoc(), diag::err_func_def_no_params
);
2979 SkipUntil(tok::r_brace
);
2981 // Consume the optional ';'
2982 TryConsumeToken(tok::semi
);
2987 if (DS
.getStorageClassSpec() == DeclSpec::SCS_typedef
) {
2988 Diag(DeclaratorInfo
.getIdentifierLoc(),
2989 diag::err_function_declared_typedef
);
2991 // Recover by treating the 'typedef' as spurious.
2992 DS
.ClearStorageClassSpecs();
2995 Decl
*FunDecl
= ParseCXXInlineMethodDef(AS
, AccessAttrs
, DeclaratorInfo
,
2996 TemplateInfo
, VS
, PureSpecLoc
);
2999 for (unsigned i
= 0, ni
= CommonLateParsedAttrs
.size(); i
< ni
; ++i
) {
3000 CommonLateParsedAttrs
[i
]->addDecl(FunDecl
);
3002 for (unsigned i
= 0, ni
= LateParsedAttrs
.size(); i
< ni
; ++i
) {
3003 LateParsedAttrs
[i
]->addDecl(FunDecl
);
3006 LateParsedAttrs
.clear();
3008 // Consume the ';' - it's optional unless we have a delete or default
3009 if (Tok
.is(tok::semi
))
3010 ConsumeExtraSemi(AfterMemberFunctionDefinition
);
3012 return DeclGroupPtrTy::make(DeclGroupRef(FunDecl
));
3016 // member-declarator-list:
3017 // member-declarator
3018 // member-declarator-list ',' member-declarator
3021 InClassInitStyle HasInClassInit
= ICIS_NoInit
;
3022 bool HasStaticInitializer
= false;
3023 if (Tok
.isOneOf(tok::equal
, tok::l_brace
) && PureSpecLoc
.isInvalid()) {
3024 // DRXXXX: Anonymous bit-fields cannot have a brace-or-equal-initializer.
3025 if (BitfieldSize
.isUsable() && !DeclaratorInfo
.hasName()) {
3026 // Diagnose the error and pretend there is no in-class initializer.
3027 Diag(Tok
, diag::err_anon_bitfield_member_init
);
3028 SkipUntil(tok::comma
, StopAtSemi
| StopBeforeMatch
);
3029 } else if (DeclaratorInfo
.isDeclarationOfFunction()) {
3030 // It's a pure-specifier.
3031 if (!TryConsumePureSpecifier(/*AllowFunctionDefinition*/ false))
3032 // Parse it as an expression so that Sema can diagnose it.
3033 HasStaticInitializer
= true;
3034 } else if (DeclaratorInfo
.getDeclSpec().getStorageClassSpec() !=
3035 DeclSpec::SCS_static
&&
3036 DeclaratorInfo
.getDeclSpec().getStorageClassSpec() !=
3037 DeclSpec::SCS_typedef
&&
3038 !DS
.isFriendSpecified()) {
3039 // It's a default member initializer.
3040 if (BitfieldSize
.get())
3041 Diag(Tok
, getLangOpts().CPlusPlus20
3042 ? diag::warn_cxx17_compat_bitfield_member_init
3043 : diag::ext_bitfield_member_init
);
3044 HasInClassInit
= Tok
.is(tok::equal
) ? ICIS_CopyInit
: ICIS_ListInit
;
3046 HasStaticInitializer
= true;
3050 // NOTE: If Sema is the Action module and declarator is an instance field,
3051 // this call will *not* return the created decl; It will return null.
3052 // See Sema::ActOnCXXMemberDeclarator for details.
3054 NamedDecl
*ThisDecl
= nullptr;
3055 if (DS
.isFriendSpecified()) {
3056 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
3057 // to a friend declaration, that declaration shall be a definition.
3059 // Diagnose attributes that appear in a friend member function declarator:
3060 // friend int foo [[]] ();
3061 for (const ParsedAttr
&AL
: DeclaratorInfo
.getAttributes())
3062 if (AL
.isCXX11Attribute() || AL
.isRegularKeywordAttribute()) {
3063 auto Loc
= AL
.getRange().getBegin();
3064 (AL
.isRegularKeywordAttribute()
3065 ? Diag(Loc
, diag::err_keyword_not_allowed
) << AL
3066 : Diag(Loc
, diag::err_attributes_not_allowed
))
3070 ThisDecl
= Actions
.ActOnFriendFunctionDecl(getCurScope(), DeclaratorInfo
,
3073 ThisDecl
= Actions
.ActOnCXXMemberDeclarator(
3074 getCurScope(), AS
, DeclaratorInfo
, TemplateParams
, BitfieldSize
.get(),
3075 VS
, HasInClassInit
);
3077 if (VarTemplateDecl
*VT
=
3078 ThisDecl
? dyn_cast
<VarTemplateDecl
>(ThisDecl
) : nullptr)
3079 // Re-direct this decl to refer to the templated decl so that we can
3081 ThisDecl
= VT
->getTemplatedDecl();
3084 Actions
.ProcessDeclAttributeList(getCurScope(), ThisDecl
, AccessAttrs
);
3087 // Error recovery might have converted a non-static member into a static
3089 if (HasInClassInit
!= ICIS_NoInit
&&
3090 DeclaratorInfo
.getDeclSpec().getStorageClassSpec() ==
3091 DeclSpec::SCS_static
) {
3092 HasInClassInit
= ICIS_NoInit
;
3093 HasStaticInitializer
= true;
3096 if (PureSpecLoc
.isValid() && VS
.getAbstractLoc().isValid()) {
3097 Diag(PureSpecLoc
, diag::err_duplicate_virt_specifier
) << "abstract";
3099 if (ThisDecl
&& PureSpecLoc
.isValid())
3100 Actions
.ActOnPureSpecifier(ThisDecl
, PureSpecLoc
);
3101 else if (ThisDecl
&& VS
.getAbstractLoc().isValid())
3102 Actions
.ActOnPureSpecifier(ThisDecl
, VS
.getAbstractLoc());
3104 // Handle the initializer.
3105 if (HasInClassInit
!= ICIS_NoInit
) {
3106 // The initializer was deferred; parse it and cache the tokens.
3107 Diag(Tok
, getLangOpts().CPlusPlus11
3108 ? diag::warn_cxx98_compat_nonstatic_member_init
3109 : diag::ext_nonstatic_member_init
);
3111 if (DeclaratorInfo
.isArrayOfUnknownBound()) {
3112 // C++11 [dcl.array]p3: An array bound may also be omitted when the
3113 // declarator is followed by an initializer.
3115 // A brace-or-equal-initializer for a member-declarator is not an
3116 // initializer in the grammar, so this is ill-formed.
3117 Diag(Tok
, diag::err_incomplete_array_member_init
);
3118 SkipUntil(tok::comma
, StopAtSemi
| StopBeforeMatch
);
3120 // Avoid later warnings about a class member of incomplete type.
3122 ThisDecl
->setInvalidDecl();
3124 ParseCXXNonStaticMemberInitializer(ThisDecl
);
3125 } else if (HasStaticInitializer
) {
3126 // Normal initializer.
3127 ExprResult Init
= ParseCXXMemberInitializer(
3128 ThisDecl
, DeclaratorInfo
.isDeclarationOfFunction(), EqualLoc
);
3130 if (Init
.isInvalid()) {
3132 Actions
.ActOnUninitializedDecl(ThisDecl
);
3133 SkipUntil(tok::comma
, StopAtSemi
| StopBeforeMatch
);
3134 } else if (ThisDecl
)
3135 Actions
.AddInitializerToDecl(ThisDecl
, Init
.get(),
3136 EqualLoc
.isInvalid());
3137 } else if (ThisDecl
&& DS
.getStorageClassSpec() == DeclSpec::SCS_static
)
3139 Actions
.ActOnUninitializedDecl(ThisDecl
);
3142 if (!ThisDecl
->isInvalidDecl()) {
3143 // Set the Decl for any late parsed attributes
3144 for (unsigned i
= 0, ni
= CommonLateParsedAttrs
.size(); i
< ni
; ++i
)
3145 CommonLateParsedAttrs
[i
]->addDecl(ThisDecl
);
3147 for (unsigned i
= 0, ni
= LateParsedAttrs
.size(); i
< ni
; ++i
)
3148 LateParsedAttrs
[i
]->addDecl(ThisDecl
);
3150 Actions
.FinalizeDeclaration(ThisDecl
);
3151 DeclsInGroup
.push_back(ThisDecl
);
3153 if (DeclaratorInfo
.isFunctionDeclarator() &&
3154 DeclaratorInfo
.getDeclSpec().getStorageClassSpec() !=
3155 DeclSpec::SCS_typedef
)
3156 HandleMemberFunctionDeclDelays(DeclaratorInfo
, ThisDecl
);
3158 LateParsedAttrs
.clear();
3160 DeclaratorInfo
.complete(ThisDecl
);
3162 // If we don't have a comma, it is either the end of the list (a ';')
3163 // or an error, bail out.
3164 SourceLocation CommaLoc
;
3165 if (!TryConsumeToken(tok::comma
, CommaLoc
))
3168 if (Tok
.isAtStartOfLine() &&
3169 !MightBeDeclarator(DeclaratorContext::Member
)) {
3170 // This comma was followed by a line-break and something which can't be
3171 // the start of a declarator. The comma was probably a typo for a
3173 Diag(CommaLoc
, diag::err_expected_semi_declaration
)
3174 << FixItHint::CreateReplacement(CommaLoc
, ";");
3179 // Parse the next declarator.
3180 DeclaratorInfo
.clear();
3182 BitfieldSize
= ExprResult(/*Invalid=*/false);
3183 EqualLoc
= PureSpecLoc
= SourceLocation();
3184 DeclaratorInfo
.setCommaLoc(CommaLoc
);
3186 // GNU attributes are allowed before the second and subsequent declarator.
3187 // However, this does not apply for [[]] attributes (which could show up
3188 // before or after the __attribute__ attributes).
3189 DiagnoseAndSkipCXX11Attributes();
3190 MaybeParseGNUAttributes(DeclaratorInfo
);
3191 DiagnoseAndSkipCXX11Attributes();
3193 if (ParseCXXMemberDeclaratorBeforeInitializer(
3194 DeclaratorInfo
, VS
, BitfieldSize
, LateParsedAttrs
))
3199 ExpectAndConsume(tok::semi
, diag::err_expected_semi_decl_list
)) {
3200 // Skip to end of block or statement.
3201 SkipUntil(tok::r_brace
, StopAtSemi
| StopBeforeMatch
);
3202 // If we stopped at a ';', eat it.
3203 TryConsumeToken(tok::semi
);
3207 return Actions
.FinalizeDeclaratorGroup(getCurScope(), DS
, DeclsInGroup
);
3210 /// ParseCXXMemberInitializer - Parse the brace-or-equal-initializer.
3211 /// Also detect and reject any attempted defaulted/deleted function definition.
3212 /// The location of the '=', if any, will be placed in EqualLoc.
3214 /// This does not check for a pure-specifier; that's handled elsewhere.
3216 /// brace-or-equal-initializer:
3217 /// '=' initializer-expression
3218 /// braced-init-list
3220 /// initializer-clause:
3221 /// assignment-expression
3222 /// braced-init-list
3224 /// defaulted/deleted function-definition:
3228 /// Prior to C++0x, the assignment-expression in an initializer-clause must
3229 /// be a constant-expression.
3230 ExprResult
Parser::ParseCXXMemberInitializer(Decl
*D
, bool IsFunction
,
3231 SourceLocation
&EqualLoc
) {
3232 assert(Tok
.isOneOf(tok::equal
, tok::l_brace
) &&
3233 "Data member initializer not starting with '=' or '{'");
3235 bool IsFieldInitialization
= isa_and_present
<FieldDecl
>(D
);
3237 EnterExpressionEvaluationContext
Context(
3239 IsFieldInitialization
3240 ? Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed
3241 : Sema::ExpressionEvaluationContext::PotentiallyEvaluated
,
3245 // Default member initializers used to initialize a base or member subobject
3246 // [...] are considered to be part of the function body
3247 Actions
.ExprEvalContexts
.back().InImmediateEscalatingFunctionContext
=
3248 IsFieldInitialization
;
3250 if (TryConsumeToken(tok::equal
, EqualLoc
)) {
3251 if (Tok
.is(tok::kw_delete
)) {
3252 // In principle, an initializer of '= delete p;' is legal, but it will
3253 // never type-check. It's better to diagnose it as an ill-formed
3254 // expression than as an ill-formed deleted non-function member. An
3255 // initializer of '= delete p, foo' will never be parsed, because a
3256 // top-level comma always ends the initializer expression.
3257 const Token
&Next
= NextToken();
3258 if (IsFunction
|| Next
.isOneOf(tok::semi
, tok::comma
, tok::eof
)) {
3260 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration
)
3263 Diag(ConsumeToken(), diag::err_deleted_non_function
);
3266 } else if (Tok
.is(tok::kw_default
)) {
3268 Diag(Tok
, diag::err_default_delete_in_multiple_declaration
)
3271 Diag(ConsumeToken(), diag::err_default_special_members
)
3272 << getLangOpts().CPlusPlus20
;
3276 if (const auto *PD
= dyn_cast_or_null
<MSPropertyDecl
>(D
)) {
3277 Diag(Tok
, diag::err_ms_property_initializer
) << PD
;
3280 return ParseInitializer();
3283 void Parser::SkipCXXMemberSpecification(SourceLocation RecordLoc
,
3284 SourceLocation AttrFixitLoc
,
3285 unsigned TagType
, Decl
*TagDecl
) {
3286 // Skip the optional 'final' keyword.
3287 if (getLangOpts().CPlusPlus
&& Tok
.is(tok::identifier
)) {
3288 assert(isCXX11FinalKeyword() && "not a class definition");
3291 // Diagnose any C++11 attributes after 'final' keyword.
3292 // We deliberately discard these attributes.
3293 ParsedAttributes
Attrs(AttrFactory
);
3294 CheckMisplacedCXX11Attribute(Attrs
, AttrFixitLoc
);
3296 // This can only happen if we had malformed misplaced attributes;
3297 // we only get called if there is a colon or left-brace after the
3299 if (Tok
.isNot(tok::colon
) && Tok
.isNot(tok::l_brace
))
3303 // Skip the base clauses. This requires actually parsing them, because
3304 // otherwise we can't be sure where they end (a left brace may appear
3305 // within a template argument).
3306 if (Tok
.is(tok::colon
)) {
3307 // Enter the scope of the class so that we can correctly parse its bases.
3308 ParseScope
ClassScope(this, Scope::ClassScope
| Scope::DeclScope
);
3309 ParsingClassDefinition
ParsingDef(*this, TagDecl
, /*NonNestedClass*/ true,
3310 TagType
== DeclSpec::TST_interface
);
3312 Actions
.ActOnTagStartSkippedDefinition(getCurScope(), TagDecl
);
3314 // Parse the bases but don't attach them to the class.
3315 ParseBaseClause(nullptr);
3317 Actions
.ActOnTagFinishSkippedDefinition(OldContext
);
3319 if (!Tok
.is(tok::l_brace
)) {
3320 Diag(PP
.getLocForEndOfToken(PrevTokLocation
),
3321 diag::err_expected_lbrace_after_base_specifiers
);
3327 assert(Tok
.is(tok::l_brace
));
3328 BalancedDelimiterTracker
T(*this, tok::l_brace
);
3332 // Parse and discard any trailing attributes.
3333 if (Tok
.is(tok::kw___attribute
)) {
3334 ParsedAttributes
Attrs(AttrFactory
);
3335 MaybeParseGNUAttributes(Attrs
);
3339 Parser::DeclGroupPtrTy
Parser::ParseCXXClassMemberDeclarationWithPragmas(
3340 AccessSpecifier
&AS
, ParsedAttributes
&AccessAttrs
, DeclSpec::TST TagType
,
3342 ParenBraceBracketBalancer
BalancerRAIIObj(*this);
3344 switch (Tok
.getKind()) {
3345 case tok::kw___if_exists
:
3346 case tok::kw___if_not_exists
:
3347 ParseMicrosoftIfExistsClassDeclaration(TagType
, AccessAttrs
, AS
);
3351 // Check for extraneous top-level semicolon.
3352 ConsumeExtraSemi(InsideStruct
, TagType
);
3355 // Handle pragmas that can appear as member declarations.
3356 case tok::annot_pragma_vis
:
3357 HandlePragmaVisibility();
3359 case tok::annot_pragma_pack
:
3362 case tok::annot_pragma_align
:
3363 HandlePragmaAlign();
3365 case tok::annot_pragma_ms_pointers_to_members
:
3366 HandlePragmaMSPointersToMembers();
3368 case tok::annot_pragma_ms_pragma
:
3369 HandlePragmaMSPragma();
3371 case tok::annot_pragma_ms_vtordisp
:
3372 HandlePragmaMSVtorDisp();
3374 case tok::annot_pragma_dump
:
3378 case tok::kw_namespace
:
3379 // If we see a namespace here, a close brace was missing somewhere.
3380 DiagnoseUnexpectedNamespace(cast
<NamedDecl
>(TagDecl
));
3383 case tok::kw_private
:
3384 // FIXME: We don't accept GNU attributes on access specifiers in OpenCL mode
3386 if (getLangOpts().OpenCL
&& !NextToken().is(tok::colon
))
3387 return ParseCXXClassMemberDeclaration(AS
, AccessAttrs
);
3389 case tok::kw_public
:
3390 case tok::kw_protected
: {
3391 if (getLangOpts().HLSL
)
3392 Diag(Tok
.getLocation(), diag::ext_hlsl_access_specifiers
);
3393 AccessSpecifier NewAS
= getAccessSpecifierIfPresent();
3394 assert(NewAS
!= AS_none
);
3395 // Current token is a C++ access specifier.
3397 SourceLocation ASLoc
= Tok
.getLocation();
3398 unsigned TokLength
= Tok
.getLength();
3400 AccessAttrs
.clear();
3401 MaybeParseGNUAttributes(AccessAttrs
);
3403 SourceLocation EndLoc
;
3404 if (TryConsumeToken(tok::colon
, EndLoc
)) {
3405 } else if (TryConsumeToken(tok::semi
, EndLoc
)) {
3406 Diag(EndLoc
, diag::err_expected
)
3407 << tok::colon
<< FixItHint::CreateReplacement(EndLoc
, ":");
3409 EndLoc
= ASLoc
.getLocWithOffset(TokLength
);
3410 Diag(EndLoc
, diag::err_expected
)
3411 << tok::colon
<< FixItHint::CreateInsertion(EndLoc
, ":");
3414 // The Microsoft extension __interface does not permit non-public
3415 // access specifiers.
3416 if (TagType
== DeclSpec::TST_interface
&& AS
!= AS_public
) {
3417 Diag(ASLoc
, diag::err_access_specifier_interface
) << (AS
== AS_protected
);
3420 if (Actions
.ActOnAccessSpecifier(NewAS
, ASLoc
, EndLoc
, AccessAttrs
)) {
3421 // found another attribute than only annotations
3422 AccessAttrs
.clear();
3428 case tok::annot_attr_openmp
:
3429 case tok::annot_pragma_openmp
:
3430 return ParseOpenMPDeclarativeDirectiveWithExtDecl(
3431 AS
, AccessAttrs
, /*Delayed=*/true, TagType
, TagDecl
);
3434 if (tok::isPragmaAnnotation(Tok
.getKind())) {
3435 Diag(Tok
.getLocation(), diag::err_pragma_misplaced_in_decl
)
3436 << DeclSpec::getSpecifierName(
3437 TagType
, Actions
.getASTContext().getPrintingPolicy());
3438 ConsumeAnnotationToken();
3441 return ParseCXXClassMemberDeclaration(AS
, AccessAttrs
);
3445 /// ParseCXXMemberSpecification - Parse the class definition.
3447 /// member-specification:
3448 /// member-declaration member-specification[opt]
3449 /// access-specifier ':' member-specification[opt]
3451 void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc
,
3452 SourceLocation AttrFixitLoc
,
3453 ParsedAttributes
&Attrs
,
3454 unsigned TagType
, Decl
*TagDecl
) {
3455 assert((TagType
== DeclSpec::TST_struct
||
3456 TagType
== DeclSpec::TST_interface
||
3457 TagType
== DeclSpec::TST_union
|| TagType
== DeclSpec::TST_class
) &&
3458 "Invalid TagType!");
3460 llvm::TimeTraceScope
TimeScope("ParseClass", [&]() {
3461 if (auto *TD
= dyn_cast_or_null
<NamedDecl
>(TagDecl
))
3462 return TD
->getQualifiedNameAsString();
3463 return std::string("<anonymous>");
3466 PrettyDeclStackTraceEntry
CrashInfo(Actions
.Context
, TagDecl
, RecordLoc
,
3467 "parsing struct/union/class body");
3469 // Determine whether this is a non-nested class. Note that local
3470 // classes are *not* considered to be nested classes.
3471 bool NonNestedClass
= true;
3472 if (!ClassStack
.empty()) {
3473 for (const Scope
*S
= getCurScope(); S
; S
= S
->getParent()) {
3474 if (S
->isClassScope()) {
3475 // We're inside a class scope, so this is a nested class.
3476 NonNestedClass
= false;
3478 // The Microsoft extension __interface does not permit nested classes.
3479 if (getCurrentClass().IsInterface
) {
3480 Diag(RecordLoc
, diag::err_invalid_member_in_interface
)
3482 << (isa
<NamedDecl
>(TagDecl
)
3483 ? cast
<NamedDecl
>(TagDecl
)->getQualifiedNameAsString()
3489 if (S
->isFunctionScope())
3490 // If we're in a function or function template then this is a local
3491 // class rather than a nested class.
3496 // Enter a scope for the class.
3497 ParseScope
ClassScope(this, Scope::ClassScope
| Scope::DeclScope
);
3499 // Note that we are parsing a new (potentially-nested) class definition.
3500 ParsingClassDefinition
ParsingDef(*this, TagDecl
, NonNestedClass
,
3501 TagType
== DeclSpec::TST_interface
);
3504 Actions
.ActOnTagStartDefinition(getCurScope(), TagDecl
);
3506 SourceLocation FinalLoc
;
3507 SourceLocation AbstractLoc
;
3508 bool IsFinalSpelledSealed
= false;
3509 bool IsAbstract
= false;
3511 // Parse the optional 'final' keyword.
3512 if (getLangOpts().CPlusPlus
&& Tok
.is(tok::identifier
)) {
3514 VirtSpecifiers::Specifier Specifier
= isCXX11VirtSpecifier(Tok
);
3515 if (Specifier
== VirtSpecifiers::VS_None
)
3517 if (isCXX11FinalKeyword()) {
3518 if (FinalLoc
.isValid()) {
3519 auto Skipped
= ConsumeToken();
3520 Diag(Skipped
, diag::err_duplicate_class_virt_specifier
)
3521 << VirtSpecifiers::getSpecifierName(Specifier
);
3523 FinalLoc
= ConsumeToken();
3524 if (Specifier
== VirtSpecifiers::VS_Sealed
)
3525 IsFinalSpelledSealed
= true;
3528 if (AbstractLoc
.isValid()) {
3529 auto Skipped
= ConsumeToken();
3530 Diag(Skipped
, diag::err_duplicate_class_virt_specifier
)
3531 << VirtSpecifiers::getSpecifierName(Specifier
);
3533 AbstractLoc
= ConsumeToken();
3537 if (TagType
== DeclSpec::TST_interface
)
3538 Diag(FinalLoc
, diag::err_override_control_interface
)
3539 << VirtSpecifiers::getSpecifierName(Specifier
);
3540 else if (Specifier
== VirtSpecifiers::VS_Final
)
3541 Diag(FinalLoc
, getLangOpts().CPlusPlus11
3542 ? diag::warn_cxx98_compat_override_control_keyword
3543 : diag::ext_override_control_keyword
)
3544 << VirtSpecifiers::getSpecifierName(Specifier
);
3545 else if (Specifier
== VirtSpecifiers::VS_Sealed
)
3546 Diag(FinalLoc
, diag::ext_ms_sealed_keyword
);
3547 else if (Specifier
== VirtSpecifiers::VS_Abstract
)
3548 Diag(AbstractLoc
, diag::ext_ms_abstract_keyword
);
3549 else if (Specifier
== VirtSpecifiers::VS_GNU_Final
)
3550 Diag(FinalLoc
, diag::ext_warn_gnu_final
);
3552 assert((FinalLoc
.isValid() || AbstractLoc
.isValid()) &&
3553 "not a class definition");
3555 // Parse any C++11 attributes after 'final' keyword.
3556 // These attributes are not allowed to appear here,
3557 // and the only possible place for them to appertain
3558 // to the class would be between class-key and class-name.
3559 CheckMisplacedCXX11Attribute(Attrs
, AttrFixitLoc
);
3561 // ParseClassSpecifier() does only a superficial check for attributes before
3562 // deciding to call this method. For example, for
3563 // `class C final alignas ([l) {` it will decide that this looks like a
3564 // misplaced attribute since it sees `alignas '(' ')'`. But the actual
3565 // attribute parsing code will try to parse the '[' as a constexpr lambda
3566 // and consume enough tokens that the alignas parsing code will eat the
3567 // opening '{'. So bail out if the next token isn't one we expect.
3568 if (!Tok
.is(tok::colon
) && !Tok
.is(tok::l_brace
)) {
3570 Actions
.ActOnTagDefinitionError(getCurScope(), TagDecl
);
3575 if (Tok
.is(tok::colon
)) {
3576 ParseScope
InheritanceScope(this, getCurScope()->getFlags() |
3577 Scope::ClassInheritanceScope
);
3579 ParseBaseClause(TagDecl
);
3580 if (!Tok
.is(tok::l_brace
)) {
3581 bool SuggestFixIt
= false;
3582 SourceLocation BraceLoc
= PP
.getLocForEndOfToken(PrevTokLocation
);
3583 if (Tok
.isAtStartOfLine()) {
3584 switch (Tok
.getKind()) {
3585 case tok::kw_private
:
3586 case tok::kw_protected
:
3587 case tok::kw_public
:
3588 SuggestFixIt
= NextToken().getKind() == tok::colon
;
3590 case tok::kw_static_assert
:
3593 // base-clause can have simple-template-id; 'template' can't be there
3594 case tok::kw_template
:
3595 SuggestFixIt
= true;
3597 case tok::identifier
:
3598 SuggestFixIt
= isConstructorDeclarator(true);
3601 SuggestFixIt
= isCXXSimpleDeclaration(/*AllowForRangeDecl=*/false);
3605 DiagnosticBuilder LBraceDiag
=
3606 Diag(BraceLoc
, diag::err_expected_lbrace_after_base_specifiers
);
3608 LBraceDiag
<< FixItHint::CreateInsertion(BraceLoc
, " {");
3609 // Try recovering from missing { after base-clause.
3610 PP
.EnterToken(Tok
, /*IsReinject*/ true);
3611 Tok
.setKind(tok::l_brace
);
3614 Actions
.ActOnTagDefinitionError(getCurScope(), TagDecl
);
3620 assert(Tok
.is(tok::l_brace
));
3621 BalancedDelimiterTracker
T(*this, tok::l_brace
);
3625 Actions
.ActOnStartCXXMemberDeclarations(getCurScope(), TagDecl
, FinalLoc
,
3626 IsFinalSpelledSealed
, IsAbstract
,
3627 T
.getOpenLocation());
3629 // C++ 11p3: Members of a class defined with the keyword class are private
3630 // by default. Members of a class defined with the keywords struct or union
3631 // are public by default.
3632 // HLSL: In HLSL members of a class are public by default.
3633 AccessSpecifier CurAS
;
3634 if (TagType
== DeclSpec::TST_class
&& !getLangOpts().HLSL
)
3638 ParsedAttributes
AccessAttrs(AttrFactory
);
3641 // While we still have something to read, read the member-declarations.
3642 while (!tryParseMisplacedModuleImport() && Tok
.isNot(tok::r_brace
) &&
3643 Tok
.isNot(tok::eof
)) {
3644 // Each iteration of this loop reads one member-declaration.
3645 ParseCXXClassMemberDeclarationWithPragmas(
3646 CurAS
, AccessAttrs
, static_cast<DeclSpec::TST
>(TagType
), TagDecl
);
3647 MaybeDestroyTemplateIds();
3651 SkipUntil(tok::r_brace
);
3654 // If attributes exist after class contents, parse them.
3655 ParsedAttributes
attrs(AttrFactory
);
3656 MaybeParseGNUAttributes(attrs
);
3659 Actions
.ActOnFinishCXXMemberSpecification(getCurScope(), RecordLoc
, TagDecl
,
3660 T
.getOpenLocation(),
3661 T
.getCloseLocation(), attrs
);
3663 // C++11 [class.mem]p2:
3664 // Within the class member-specification, the class is regarded as complete
3665 // within function bodies, default arguments, exception-specifications, and
3666 // brace-or-equal-initializers for non-static data members (including such
3667 // things in nested classes).
3668 if (TagDecl
&& NonNestedClass
) {
3669 // We are not inside a nested class. This class and its nested classes
3670 // are complete and we can parse the delayed portions of method
3671 // declarations and the lexed inline method definitions, along with any
3672 // delayed attributes.
3674 SourceLocation SavedPrevTokLocation
= PrevTokLocation
;
3675 ParseLexedPragmas(getCurrentClass());
3676 ParseLexedAttributes(getCurrentClass());
3677 ParseLexedMethodDeclarations(getCurrentClass());
3679 // We've finished with all pending member declarations.
3680 Actions
.ActOnFinishCXXMemberDecls();
3682 ParseLexedMemberInitializers(getCurrentClass());
3683 ParseLexedMethodDefs(getCurrentClass());
3684 PrevTokLocation
= SavedPrevTokLocation
;
3686 // We've finished parsing everything, including default argument
3688 Actions
.ActOnFinishCXXNonNestedClass();
3692 Actions
.ActOnTagFinishDefinition(getCurScope(), TagDecl
, T
.getRange());
3694 // Leave the class scope.
3699 void Parser::DiagnoseUnexpectedNamespace(NamedDecl
*D
) {
3700 assert(Tok
.is(tok::kw_namespace
));
3702 // FIXME: Suggest where the close brace should have gone by looking
3703 // at indentation changes within the definition body.
3704 Diag(D
->getLocation(), diag::err_missing_end_of_definition
) << D
;
3705 Diag(Tok
.getLocation(), diag::note_missing_end_of_definition_before
) << D
;
3707 // Push '};' onto the token stream to recover.
3708 PP
.EnterToken(Tok
, /*IsReinject*/ true);
3711 Tok
.setLocation(PP
.getLocForEndOfToken(PrevTokLocation
));
3712 Tok
.setKind(tok::semi
);
3713 PP
.EnterToken(Tok
, /*IsReinject*/ true);
3715 Tok
.setKind(tok::r_brace
);
3718 /// ParseConstructorInitializer - Parse a C++ constructor initializer,
3719 /// which explicitly initializes the members or base classes of a
3720 /// class (C++ [class.base.init]). For example, the three initializers
3721 /// after the ':' in the Derived constructor below:
3725 /// class Derived : Base {
3729 /// Derived(float f) : Base(), x(17), f(f) { }
3733 /// [C++] ctor-initializer:
3734 /// ':' mem-initializer-list
3736 /// [C++] mem-initializer-list:
3737 /// mem-initializer ...[opt]
3738 /// mem-initializer ...[opt] , mem-initializer-list
3739 void Parser::ParseConstructorInitializer(Decl
*ConstructorDecl
) {
3740 assert(Tok
.is(tok::colon
) &&
3741 "Constructor initializer always starts with ':'");
3743 // Poison the SEH identifiers so they are flagged as illegal in constructor
3745 PoisonSEHIdentifiersRAIIObject
PoisonSEHIdentifiers(*this, true);
3746 SourceLocation ColonLoc
= ConsumeToken();
3748 SmallVector
<CXXCtorInitializer
*, 4> MemInitializers
;
3749 bool AnyErrors
= false;
3752 if (Tok
.is(tok::code_completion
)) {
3754 Actions
.CodeCompleteConstructorInitializer(ConstructorDecl
,
3759 MemInitResult MemInit
= ParseMemInitializer(ConstructorDecl
);
3760 if (!MemInit
.isInvalid())
3761 MemInitializers
.push_back(MemInit
.get());
3765 if (Tok
.is(tok::comma
))
3767 else if (Tok
.is(tok::l_brace
))
3769 // If the previous initializer was valid and the next token looks like a
3770 // base or member initializer, assume that we're just missing a comma.
3771 else if (!MemInit
.isInvalid() &&
3772 Tok
.isOneOf(tok::identifier
, tok::coloncolon
)) {
3773 SourceLocation Loc
= PP
.getLocForEndOfToken(PrevTokLocation
);
3774 Diag(Loc
, diag::err_ctor_init_missing_comma
)
3775 << FixItHint::CreateInsertion(Loc
, ", ");
3777 // Skip over garbage, until we get to '{'. Don't eat the '{'.
3778 if (!MemInit
.isInvalid())
3779 Diag(Tok
.getLocation(), diag::err_expected_either
)
3780 << tok::l_brace
<< tok::comma
;
3781 SkipUntil(tok::l_brace
, StopAtSemi
| StopBeforeMatch
);
3786 Actions
.ActOnMemInitializers(ConstructorDecl
, ColonLoc
, MemInitializers
,
3790 /// ParseMemInitializer - Parse a C++ member initializer, which is
3791 /// part of a constructor initializer that explicitly initializes one
3792 /// member or base class (C++ [class.base.init]). See
3793 /// ParseConstructorInitializer for an example.
3795 /// [C++] mem-initializer:
3796 /// mem-initializer-id '(' expression-list[opt] ')'
3797 /// [C++0x] mem-initializer-id braced-init-list
3799 /// [C++] mem-initializer-id:
3800 /// '::'[opt] nested-name-specifier[opt] class-name
3802 MemInitResult
Parser::ParseMemInitializer(Decl
*ConstructorDecl
) {
3803 // parse '::'[opt] nested-name-specifier[opt]
3805 if (ParseOptionalCXXScopeSpecifier(SS
, /*ObjectType=*/nullptr,
3806 /*ObjectHasErrors=*/false,
3807 /*EnteringContext=*/false))
3811 IdentifierInfo
*II
= nullptr;
3812 SourceLocation IdLoc
= Tok
.getLocation();
3814 DeclSpec
DS(AttrFactory
);
3815 // : template_name<...>
3816 TypeResult TemplateTypeTy
;
3818 if (Tok
.is(tok::identifier
)) {
3819 // Get the identifier. This may be a member name or a class name,
3820 // but we'll let the semantic analysis determine which it is.
3821 II
= Tok
.getIdentifierInfo();
3823 } else if (Tok
.is(tok::annot_decltype
)) {
3824 // Get the decltype expression, if there is one.
3825 // Uses of decltype will already have been converted to annot_decltype by
3826 // ParseOptionalCXXScopeSpecifier at this point.
3827 // FIXME: Can we get here with a scope specifier?
3828 ParseDecltypeSpecifier(DS
);
3830 TemplateIdAnnotation
*TemplateId
= Tok
.is(tok::annot_template_id
)
3831 ? takeTemplateIdAnnotation(Tok
)
3833 if (TemplateId
&& TemplateId
->mightBeType()) {
3834 AnnotateTemplateIdTokenAsType(SS
, ImplicitTypenameContext::No
,
3835 /*IsClassName=*/true);
3836 assert(Tok
.is(tok::annot_typename
) && "template-id -> type failed");
3837 TemplateTypeTy
= getTypeAnnotation(Tok
);
3838 ConsumeAnnotationToken();
3840 Diag(Tok
, diag::err_expected_member_or_base_name
);
3846 if (getLangOpts().CPlusPlus11
&& Tok
.is(tok::l_brace
)) {
3847 Diag(Tok
, diag::warn_cxx98_compat_generalized_initializer_lists
);
3849 // FIXME: Add support for signature help inside initializer lists.
3850 ExprResult InitList
= ParseBraceInitializer();
3851 if (InitList
.isInvalid())
3854 SourceLocation EllipsisLoc
;
3855 TryConsumeToken(tok::ellipsis
, EllipsisLoc
);
3857 if (TemplateTypeTy
.isInvalid())
3859 return Actions
.ActOnMemInitializer(ConstructorDecl
, getCurScope(), SS
, II
,
3860 TemplateTypeTy
.get(), DS
, IdLoc
,
3861 InitList
.get(), EllipsisLoc
);
3862 } else if (Tok
.is(tok::l_paren
)) {
3863 BalancedDelimiterTracker
T(*this, tok::l_paren
);
3866 // Parse the optional expression-list.
3867 ExprVector ArgExprs
;
3868 auto RunSignatureHelp
= [&] {
3869 if (TemplateTypeTy
.isInvalid())
3871 QualType PreferredType
= Actions
.ProduceCtorInitMemberSignatureHelp(
3872 ConstructorDecl
, SS
, TemplateTypeTy
.get(), ArgExprs
, II
,
3873 T
.getOpenLocation(), /*Braced=*/false);
3874 CalledSignatureHelp
= true;
3875 return PreferredType
;
3877 if (Tok
.isNot(tok::r_paren
) && ParseExpressionList(ArgExprs
, [&] {
3878 PreferredType
.enterFunctionArgument(Tok
.getLocation(),
3881 if (PP
.isCodeCompletionReached() && !CalledSignatureHelp
)
3883 SkipUntil(tok::r_paren
, StopAtSemi
);
3889 SourceLocation EllipsisLoc
;
3890 TryConsumeToken(tok::ellipsis
, EllipsisLoc
);
3892 if (TemplateTypeTy
.isInvalid())
3894 return Actions
.ActOnMemInitializer(
3895 ConstructorDecl
, getCurScope(), SS
, II
, TemplateTypeTy
.get(), DS
, IdLoc
,
3896 T
.getOpenLocation(), ArgExprs
, T
.getCloseLocation(), EllipsisLoc
);
3899 if (TemplateTypeTy
.isInvalid())
3902 if (getLangOpts().CPlusPlus11
)
3903 return Diag(Tok
, diag::err_expected_either
) << tok::l_paren
<< tok::l_brace
;
3905 return Diag(Tok
, diag::err_expected
) << tok::l_paren
;
3908 /// Parse a C++ exception-specification if present (C++0x [except.spec]).
3910 /// exception-specification:
3911 /// dynamic-exception-specification
3912 /// noexcept-specification
3914 /// noexcept-specification:
3916 /// 'noexcept' '(' constant-expression ')'
3917 ExceptionSpecificationType
Parser::tryParseExceptionSpecification(
3918 bool Delayed
, SourceRange
&SpecificationRange
,
3919 SmallVectorImpl
<ParsedType
> &DynamicExceptions
,
3920 SmallVectorImpl
<SourceRange
> &DynamicExceptionRanges
,
3921 ExprResult
&NoexceptExpr
, CachedTokens
*&ExceptionSpecTokens
) {
3922 ExceptionSpecificationType Result
= EST_None
;
3923 ExceptionSpecTokens
= nullptr;
3925 // Handle delayed parsing of exception-specifications.
3927 if (Tok
.isNot(tok::kw_throw
) && Tok
.isNot(tok::kw_noexcept
))
3930 // Consume and cache the starting token.
3931 bool IsNoexcept
= Tok
.is(tok::kw_noexcept
);
3932 Token StartTok
= Tok
;
3933 SpecificationRange
= SourceRange(ConsumeToken());
3936 if (!Tok
.is(tok::l_paren
)) {
3937 // If this is a bare 'noexcept', we're done.
3939 Diag(Tok
, diag::warn_cxx98_compat_noexcept_decl
);
3940 NoexceptExpr
= nullptr;
3941 return EST_BasicNoexcept
;
3944 Diag(Tok
, diag::err_expected_lparen_after
) << "throw";
3945 return EST_DynamicNone
;
3948 // Cache the tokens for the exception-specification.
3949 ExceptionSpecTokens
= new CachedTokens
;
3950 ExceptionSpecTokens
->push_back(StartTok
); // 'throw' or 'noexcept'
3951 ExceptionSpecTokens
->push_back(Tok
); // '('
3952 SpecificationRange
.setEnd(ConsumeParen()); // '('
3954 ConsumeAndStoreUntil(tok::r_paren
, *ExceptionSpecTokens
,
3955 /*StopAtSemi=*/true,
3956 /*ConsumeFinalToken=*/true);
3957 SpecificationRange
.setEnd(ExceptionSpecTokens
->back().getLocation());
3959 return EST_Unparsed
;
3962 // See if there's a dynamic specification.
3963 if (Tok
.is(tok::kw_throw
)) {
3964 Result
= ParseDynamicExceptionSpecification(
3965 SpecificationRange
, DynamicExceptions
, DynamicExceptionRanges
);
3966 assert(DynamicExceptions
.size() == DynamicExceptionRanges
.size() &&
3967 "Produced different number of exception types and ranges.");
3970 // If there's no noexcept specification, we're done.
3971 if (Tok
.isNot(tok::kw_noexcept
))
3974 Diag(Tok
, diag::warn_cxx98_compat_noexcept_decl
);
3976 // If we already had a dynamic specification, parse the noexcept for,
3977 // recovery, but emit a diagnostic and don't store the results.
3978 SourceRange NoexceptRange
;
3979 ExceptionSpecificationType NoexceptType
= EST_None
;
3981 SourceLocation KeywordLoc
= ConsumeToken();
3982 if (Tok
.is(tok::l_paren
)) {
3983 // There is an argument.
3984 BalancedDelimiterTracker
T(*this, tok::l_paren
);
3987 EnterExpressionEvaluationContext
ConstantEvaluated(
3988 Actions
, Sema::ExpressionEvaluationContext::ConstantEvaluated
);
3989 NoexceptExpr
= ParseConstantExpressionInExprEvalContext();
3992 if (!NoexceptExpr
.isInvalid()) {
3994 Actions
.ActOnNoexceptSpec(NoexceptExpr
.get(), NoexceptType
);
3995 NoexceptRange
= SourceRange(KeywordLoc
, T
.getCloseLocation());
3997 NoexceptType
= EST_BasicNoexcept
;
4000 // There is no argument.
4001 NoexceptType
= EST_BasicNoexcept
;
4002 NoexceptRange
= SourceRange(KeywordLoc
, KeywordLoc
);
4005 if (Result
== EST_None
) {
4006 SpecificationRange
= NoexceptRange
;
4007 Result
= NoexceptType
;
4009 // If there's a dynamic specification after a noexcept specification,
4010 // parse that and ignore the results.
4011 if (Tok
.is(tok::kw_throw
)) {
4012 Diag(Tok
.getLocation(), diag::err_dynamic_and_noexcept_specification
);
4013 ParseDynamicExceptionSpecification(NoexceptRange
, DynamicExceptions
,
4014 DynamicExceptionRanges
);
4017 Diag(Tok
.getLocation(), diag::err_dynamic_and_noexcept_specification
);
4023 static void diagnoseDynamicExceptionSpecification(Parser
&P
, SourceRange Range
,
4025 if (P
.getLangOpts().CPlusPlus11
) {
4026 const char *Replacement
= IsNoexcept
? "noexcept" : "noexcept(false)";
4027 P
.Diag(Range
.getBegin(), P
.getLangOpts().CPlusPlus17
&& !IsNoexcept
4028 ? diag::ext_dynamic_exception_spec
4029 : diag::warn_exception_spec_deprecated
)
4031 P
.Diag(Range
.getBegin(), diag::note_exception_spec_deprecated
)
4032 << Replacement
<< FixItHint::CreateReplacement(Range
, Replacement
);
4036 /// ParseDynamicExceptionSpecification - Parse a C++
4037 /// dynamic-exception-specification (C++ [except.spec]).
4039 /// dynamic-exception-specification:
4040 /// 'throw' '(' type-id-list [opt] ')'
4041 /// [MS] 'throw' '(' '...' ')'
4044 /// type-id ... [opt]
4045 /// type-id-list ',' type-id ... [opt]
4047 ExceptionSpecificationType
Parser::ParseDynamicExceptionSpecification(
4048 SourceRange
&SpecificationRange
, SmallVectorImpl
<ParsedType
> &Exceptions
,
4049 SmallVectorImpl
<SourceRange
> &Ranges
) {
4050 assert(Tok
.is(tok::kw_throw
) && "expected throw");
4052 SpecificationRange
.setBegin(ConsumeToken());
4053 BalancedDelimiterTracker
T(*this, tok::l_paren
);
4054 if (T
.consumeOpen()) {
4055 Diag(Tok
, diag::err_expected_lparen_after
) << "throw";
4056 SpecificationRange
.setEnd(SpecificationRange
.getBegin());
4057 return EST_DynamicNone
;
4060 // Parse throw(...), a Microsoft extension that means "this function
4061 // can throw anything".
4062 if (Tok
.is(tok::ellipsis
)) {
4063 SourceLocation EllipsisLoc
= ConsumeToken();
4064 if (!getLangOpts().MicrosoftExt
)
4065 Diag(EllipsisLoc
, diag::ext_ellipsis_exception_spec
);
4067 SpecificationRange
.setEnd(T
.getCloseLocation());
4068 diagnoseDynamicExceptionSpecification(*this, SpecificationRange
, false);
4072 // Parse the sequence of type-ids.
4074 while (Tok
.isNot(tok::r_paren
)) {
4075 TypeResult
Res(ParseTypeName(&Range
));
4077 if (Tok
.is(tok::ellipsis
)) {
4078 // C++0x [temp.variadic]p5:
4079 // - In a dynamic-exception-specification (15.4); the pattern is a
4081 SourceLocation Ellipsis
= ConsumeToken();
4082 Range
.setEnd(Ellipsis
);
4083 if (!Res
.isInvalid())
4084 Res
= Actions
.ActOnPackExpansion(Res
.get(), Ellipsis
);
4087 if (!Res
.isInvalid()) {
4088 Exceptions
.push_back(Res
.get());
4089 Ranges
.push_back(Range
);
4092 if (!TryConsumeToken(tok::comma
))
4097 SpecificationRange
.setEnd(T
.getCloseLocation());
4098 diagnoseDynamicExceptionSpecification(*this, SpecificationRange
,
4099 Exceptions
.empty());
4100 return Exceptions
.empty() ? EST_DynamicNone
: EST_Dynamic
;
4103 /// ParseTrailingReturnType - Parse a trailing return type on a new-style
4104 /// function declaration.
4105 TypeResult
Parser::ParseTrailingReturnType(SourceRange
&Range
,
4106 bool MayBeFollowedByDirectInit
) {
4107 assert(Tok
.is(tok::arrow
) && "expected arrow");
4111 return ParseTypeName(&Range
, MayBeFollowedByDirectInit
4112 ? DeclaratorContext::TrailingReturnVar
4113 : DeclaratorContext::TrailingReturn
);
4116 /// Parse a requires-clause as part of a function declaration.
4117 void Parser::ParseTrailingRequiresClause(Declarator
&D
) {
4118 assert(Tok
.is(tok::kw_requires
) && "expected requires");
4120 SourceLocation RequiresKWLoc
= ConsumeToken();
4122 ExprResult TrailingRequiresClause
;
4123 ParseScope
ParamScope(this, Scope::DeclScope
|
4124 Scope::FunctionDeclarationScope
|
4125 Scope::FunctionPrototypeScope
);
4127 Actions
.ActOnStartTrailingRequiresClause(getCurScope(), D
);
4129 std::optional
<Sema::CXXThisScopeRAII
> ThisScope
;
4130 InitCXXThisScopeForDeclaratorIfRelevant(D
, D
.getDeclSpec(), ThisScope
);
4132 TrailingRequiresClause
=
4133 ParseConstraintLogicalOrExpression(/*IsTrailingRequiresClause=*/true);
4135 TrailingRequiresClause
=
4136 Actions
.ActOnFinishTrailingRequiresClause(TrailingRequiresClause
);
4138 if (!D
.isDeclarationOfFunction()) {
4140 diag::err_requires_clause_on_declarator_not_declaring_a_function
);
4144 if (TrailingRequiresClause
.isInvalid())
4145 SkipUntil({tok::l_brace
, tok::arrow
, tok::kw_try
, tok::comma
, tok::colon
},
4146 StopAtSemi
| StopBeforeMatch
);
4148 D
.setTrailingRequiresClause(TrailingRequiresClause
.get());
4150 // Did the user swap the trailing return type and requires clause?
4151 if (D
.isFunctionDeclarator() && Tok
.is(tok::arrow
) &&
4152 D
.getDeclSpec().getTypeSpecType() == TST_auto
) {
4153 SourceLocation ArrowLoc
= Tok
.getLocation();
4155 TypeResult TrailingReturnType
=
4156 ParseTrailingReturnType(Range
, /*MayBeFollowedByDirectInit=*/false);
4158 if (!TrailingReturnType
.isInvalid()) {
4160 diag::err_requires_clause_must_appear_after_trailing_return
)
4162 auto &FunctionChunk
= D
.getFunctionTypeInfo();
4163 FunctionChunk
.HasTrailingReturnType
= TrailingReturnType
.isUsable();
4164 FunctionChunk
.TrailingReturnType
= TrailingReturnType
.get();
4165 FunctionChunk
.TrailingReturnTypeLoc
= Range
.getBegin();
4167 SkipUntil({tok::equal
, tok::l_brace
, tok::arrow
, tok::kw_try
, tok::comma
},
4168 StopAtSemi
| StopBeforeMatch
);
4172 /// We have just started parsing the definition of a new class,
4173 /// so push that class onto our stack of classes that is currently
4175 Sema::ParsingClassState
Parser::PushParsingClass(Decl
*ClassDecl
,
4176 bool NonNestedClass
,
4178 assert((NonNestedClass
|| !ClassStack
.empty()) &&
4179 "Nested class without outer class");
4180 ClassStack
.push(new ParsingClass(ClassDecl
, NonNestedClass
, IsInterface
));
4181 return Actions
.PushParsingClass();
4184 /// Deallocate the given parsed class and all of its nested
4186 void Parser::DeallocateParsedClasses(Parser::ParsingClass
*Class
) {
4187 for (unsigned I
= 0, N
= Class
->LateParsedDeclarations
.size(); I
!= N
; ++I
)
4188 delete Class
->LateParsedDeclarations
[I
];
4192 /// Pop the top class of the stack of classes that are
4193 /// currently being parsed.
4195 /// This routine should be called when we have finished parsing the
4196 /// definition of a class, but have not yet popped the Scope
4197 /// associated with the class's definition.
4198 void Parser::PopParsingClass(Sema::ParsingClassState state
) {
4199 assert(!ClassStack
.empty() && "Mismatched push/pop for class parsing");
4201 Actions
.PopParsingClass(state
);
4203 ParsingClass
*Victim
= ClassStack
.top();
4205 if (Victim
->TopLevelClass
) {
4206 // Deallocate all of the nested classes of this class,
4207 // recursively: we don't need to keep any of this information.
4208 DeallocateParsedClasses(Victim
);
4211 assert(!ClassStack
.empty() && "Missing top-level class?");
4213 if (Victim
->LateParsedDeclarations
.empty()) {
4214 // The victim is a nested class, but we will not need to perform
4215 // any processing after the definition of this class since it has
4216 // no members whose handling was delayed. Therefore, we can just
4217 // remove this nested class.
4218 DeallocateParsedClasses(Victim
);
4222 // This nested class has some members that will need to be processed
4223 // after the top-level class is completely defined. Therefore, add
4224 // it to the list of nested classes within its parent.
4225 assert(getCurScope()->isClassScope() &&
4226 "Nested class outside of class scope?");
4227 ClassStack
.top()->LateParsedDeclarations
.push_back(
4228 new LateParsedClass(this, Victim
));
4231 /// Try to parse an 'identifier' which appears within an attribute-token.
4233 /// \return the parsed identifier on success, and 0 if the next token is not an
4234 /// attribute-token.
4236 /// C++11 [dcl.attr.grammar]p3:
4237 /// If a keyword or an alternative token that satisfies the syntactic
4238 /// requirements of an identifier is contained in an attribute-token,
4239 /// it is considered an identifier.
4241 Parser::TryParseCXX11AttributeIdentifier(SourceLocation
&Loc
,
4242 Sema::AttributeCompletion Completion
,
4243 const IdentifierInfo
*Scope
) {
4244 switch (Tok
.getKind()) {
4246 // Identifiers and keywords have identifier info attached.
4247 if (!Tok
.isAnnotation()) {
4248 if (IdentifierInfo
*II
= Tok
.getIdentifierInfo()) {
4249 Loc
= ConsumeToken();
4255 case tok::code_completion
:
4257 Actions
.CodeCompleteAttribute(getLangOpts().CPlusPlus
? ParsedAttr::AS_CXX11
4258 : ParsedAttr::AS_C23
,
4262 case tok::numeric_constant
: {
4263 // If we got a numeric constant, check to see if it comes from a macro that
4264 // corresponds to the predefined __clang__ macro. If it does, warn the user
4265 // and recover by pretending they said _Clang instead.
4266 if (Tok
.getLocation().isMacroID()) {
4267 SmallString
<8> ExpansionBuf
;
4268 SourceLocation ExpansionLoc
=
4269 PP
.getSourceManager().getExpansionLoc(Tok
.getLocation());
4270 StringRef Spelling
= PP
.getSpelling(ExpansionLoc
, ExpansionBuf
);
4271 if (Spelling
== "__clang__") {
4272 SourceRange
TokRange(
4274 PP
.getSourceManager().getExpansionLoc(Tok
.getEndLoc()));
4275 Diag(Tok
, diag::warn_wrong_clang_attr_namespace
)
4276 << FixItHint::CreateReplacement(TokRange
, "_Clang");
4277 Loc
= ConsumeToken();
4278 return &PP
.getIdentifierTable().get("_Clang");
4284 case tok::ampamp
: // 'and'
4285 case tok::pipe
: // 'bitor'
4286 case tok::pipepipe
: // 'or'
4287 case tok::caret
: // 'xor'
4288 case tok::tilde
: // 'compl'
4289 case tok::amp
: // 'bitand'
4290 case tok::ampequal
: // 'and_eq'
4291 case tok::pipeequal
: // 'or_eq'
4292 case tok::caretequal
: // 'xor_eq'
4293 case tok::exclaim
: // 'not'
4294 case tok::exclaimequal
: // 'not_eq'
4295 // Alternative tokens do not have identifier info, but their spelling
4296 // starts with an alphabetical character.
4297 SmallString
<8> SpellingBuf
;
4298 SourceLocation SpellingLoc
=
4299 PP
.getSourceManager().getSpellingLoc(Tok
.getLocation());
4300 StringRef Spelling
= PP
.getSpelling(SpellingLoc
, SpellingBuf
);
4301 if (isLetter(Spelling
[0])) {
4302 Loc
= ConsumeToken();
4303 return &PP
.getIdentifierTable().get(Spelling
);
4309 void Parser::ParseOpenMPAttributeArgs(const IdentifierInfo
*AttrName
,
4310 CachedTokens
&OpenMPTokens
) {
4311 // Both 'sequence' and 'directive' attributes require arguments, so parse the
4312 // open paren for the argument list.
4313 BalancedDelimiterTracker
T(*this, tok::l_paren
);
4314 if (T
.consumeOpen()) {
4315 Diag(Tok
, diag::err_expected
) << tok::l_paren
;
4319 if (AttrName
->isStr("directive")) {
4320 // If the attribute is named `directive`, we can consume its argument list
4321 // and push the tokens from it into the cached token stream for a new OpenMP
4322 // pragma directive.
4324 OMPBeginTok
.startToken();
4325 OMPBeginTok
.setKind(tok::annot_attr_openmp
);
4326 OMPBeginTok
.setLocation(Tok
.getLocation());
4327 OpenMPTokens
.push_back(OMPBeginTok
);
4329 ConsumeAndStoreUntil(tok::r_paren
, OpenMPTokens
, /*StopAtSemi=*/false,
4330 /*ConsumeFinalToken*/ false);
4332 OMPEndTok
.startToken();
4333 OMPEndTok
.setKind(tok::annot_pragma_openmp_end
);
4334 OMPEndTok
.setLocation(Tok
.getLocation());
4335 OpenMPTokens
.push_back(OMPEndTok
);
4337 assert(AttrName
->isStr("sequence") &&
4338 "Expected either 'directive' or 'sequence'");
4339 // If the attribute is named 'sequence', its argument is a list of one or
4340 // more OpenMP attributes (either 'omp::directive' or 'omp::sequence',
4341 // where the 'omp::' is optional).
4343 // We expect to see one of the following:
4344 // * An identifier (omp) for the attribute namespace followed by ::
4345 // * An identifier (directive) or an identifier (sequence).
4346 SourceLocation IdentLoc
;
4347 const IdentifierInfo
*Ident
= TryParseCXX11AttributeIdentifier(IdentLoc
);
4349 // If there is an identifier and it is 'omp', a double colon is required
4350 // followed by the actual identifier we're after.
4351 if (Ident
&& Ident
->isStr("omp") && !ExpectAndConsume(tok::coloncolon
))
4352 Ident
= TryParseCXX11AttributeIdentifier(IdentLoc
);
4354 // If we failed to find an identifier (scoped or otherwise), or we found
4355 // an unexpected identifier, diagnose.
4356 if (!Ident
|| (!Ident
->isStr("directive") && !Ident
->isStr("sequence"))) {
4357 Diag(Tok
.getLocation(), diag::err_expected_sequence_or_directive
);
4358 SkipUntil(tok::r_paren
, StopBeforeMatch
);
4361 // We read an identifier. If the identifier is one of the ones we
4362 // expected, we can recurse to parse the args.
4363 ParseOpenMPAttributeArgs(Ident
, OpenMPTokens
);
4365 // There may be a comma to signal that we expect another directive in the
4367 } while (TryConsumeToken(tok::comma
));
4369 // Parse the closing paren for the argument list.
4373 static bool IsBuiltInOrStandardCXX11Attribute(IdentifierInfo
*AttrName
,
4374 IdentifierInfo
*ScopeName
) {
4376 ParsedAttr::getParsedKind(AttrName
, ScopeName
, ParsedAttr::AS_CXX11
)) {
4377 case ParsedAttr::AT_CarriesDependency
:
4378 case ParsedAttr::AT_Deprecated
:
4379 case ParsedAttr::AT_FallThrough
:
4380 case ParsedAttr::AT_CXX11NoReturn
:
4381 case ParsedAttr::AT_NoUniqueAddress
:
4382 case ParsedAttr::AT_Likely
:
4383 case ParsedAttr::AT_Unlikely
:
4385 case ParsedAttr::AT_WarnUnusedResult
:
4386 return !ScopeName
&& AttrName
->getName().equals("nodiscard");
4387 case ParsedAttr::AT_Unused
:
4388 return !ScopeName
&& AttrName
->getName().equals("maybe_unused");
4394 /// ParseCXX11AttributeArgs -- Parse a C++11 attribute-argument-clause.
4396 /// [C++11] attribute-argument-clause:
4397 /// '(' balanced-token-seq ')'
4399 /// [C++11] balanced-token-seq:
4401 /// balanced-token-seq balanced-token
4403 /// [C++11] balanced-token:
4404 /// '(' balanced-token-seq ')'
4405 /// '[' balanced-token-seq ']'
4406 /// '{' balanced-token-seq '}'
4407 /// any token but '(', ')', '[', ']', '{', or '}'
4408 bool Parser::ParseCXX11AttributeArgs(
4409 IdentifierInfo
*AttrName
, SourceLocation AttrNameLoc
,
4410 ParsedAttributes
&Attrs
, SourceLocation
*EndLoc
, IdentifierInfo
*ScopeName
,
4411 SourceLocation ScopeLoc
, CachedTokens
&OpenMPTokens
) {
4412 assert(Tok
.is(tok::l_paren
) && "Not a C++11 attribute argument list");
4413 SourceLocation LParenLoc
= Tok
.getLocation();
4414 const LangOptions
&LO
= getLangOpts();
4415 ParsedAttr::Form Form
=
4416 LO
.CPlusPlus
? ParsedAttr::Form::CXX11() : ParsedAttr::Form::C23();
4418 // Try parsing microsoft attributes
4419 if (getLangOpts().MicrosoftExt
|| getLangOpts().HLSL
) {
4420 if (hasAttribute(AttributeCommonInfo::Syntax::AS_Microsoft
, ScopeName
,
4421 AttrName
, getTargetInfo(), getLangOpts()))
4422 Form
= ParsedAttr::Form::Microsoft();
4425 // If the attribute isn't known, we will not attempt to parse any
4427 if (Form
.getSyntax() != ParsedAttr::AS_Microsoft
&&
4428 !hasAttribute(LO
.CPlusPlus
? AttributeCommonInfo::Syntax::AS_CXX11
4429 : AttributeCommonInfo::Syntax::AS_C23
,
4430 ScopeName
, AttrName
, getTargetInfo(), getLangOpts())) {
4431 // Eat the left paren, then skip to the ending right paren.
4433 SkipUntil(tok::r_paren
);
4437 if (ScopeName
&& (ScopeName
->isStr("gnu") || ScopeName
->isStr("__gnu__"))) {
4438 // GNU-scoped attributes have some special cases to handle GNU-specific
4440 ParseGNUAttributeArgs(AttrName
, AttrNameLoc
, Attrs
, EndLoc
, ScopeName
,
4441 ScopeLoc
, Form
, nullptr);
4445 if (ScopeName
&& ScopeName
->isStr("omp")) {
4446 Diag(AttrNameLoc
, getLangOpts().OpenMP
>= 51
4447 ? diag::warn_omp51_compat_attributes
4448 : diag::ext_omp_attributes
);
4450 ParseOpenMPAttributeArgs(AttrName
, OpenMPTokens
);
4452 // We claim that an attribute was parsed and added so that one is not
4453 // created for us by the caller.
4458 // Some Clang-scoped attributes have some special parsing behavior.
4459 if (ScopeName
&& (ScopeName
->isStr("clang") || ScopeName
->isStr("_Clang")))
4460 NumArgs
= ParseClangAttributeArgs(AttrName
, AttrNameLoc
, Attrs
, EndLoc
,
4461 ScopeName
, ScopeLoc
, Form
);
4463 NumArgs
= ParseAttributeArgsCommon(AttrName
, AttrNameLoc
, Attrs
, EndLoc
,
4464 ScopeName
, ScopeLoc
, Form
);
4466 if (!Attrs
.empty() &&
4467 IsBuiltInOrStandardCXX11Attribute(AttrName
, ScopeName
)) {
4468 ParsedAttr
&Attr
= Attrs
.back();
4470 // Ignore attributes that don't exist for the target.
4471 if (!Attr
.existsInTarget(getTargetInfo())) {
4472 Diag(LParenLoc
, diag::warn_unknown_attribute_ignored
) << AttrName
;
4473 Attr
.setInvalid(true);
4477 // If the attribute is a standard or built-in attribute and we are
4478 // parsing an argument list, we need to determine whether this attribute
4479 // was allowed to have an argument list (such as [[deprecated]]), and how
4480 // many arguments were parsed (so we can diagnose on [[deprecated()]]).
4481 if (Attr
.getMaxArgs() && !NumArgs
) {
4482 // The attribute was allowed to have arguments, but none were provided
4483 // even though the attribute parsed successfully. This is an error.
4484 Diag(LParenLoc
, diag::err_attribute_requires_arguments
) << AttrName
;
4485 Attr
.setInvalid(true);
4486 } else if (!Attr
.getMaxArgs()) {
4487 // The attribute parsed successfully, but was not allowed to have any
4488 // arguments. It doesn't matter whether any were provided -- the
4489 // presence of the argument list (even if empty) is diagnosed.
4490 Diag(LParenLoc
, diag::err_cxx11_attribute_forbids_arguments
)
4492 << FixItHint::CreateRemoval(SourceRange(LParenLoc
, *EndLoc
));
4493 Attr
.setInvalid(true);
4499 /// Parse a C++11 or C23 attribute-specifier.
4501 /// [C++11] attribute-specifier:
4502 /// '[' '[' attribute-list ']' ']'
4503 /// alignment-specifier
4505 /// [C++11] attribute-list:
4507 /// attribute-list ',' attribute[opt]
4509 /// attribute-list ',' attribute '...'
4511 /// [C++11] attribute:
4512 /// attribute-token attribute-argument-clause[opt]
4514 /// [C++11] attribute-token:
4516 /// attribute-scoped-token
4518 /// [C++11] attribute-scoped-token:
4519 /// attribute-namespace '::' identifier
4521 /// [C++11] attribute-namespace:
4523 void Parser::ParseCXX11AttributeSpecifierInternal(ParsedAttributes
&Attrs
,
4524 CachedTokens
&OpenMPTokens
,
4525 SourceLocation
*EndLoc
) {
4526 if (Tok
.is(tok::kw_alignas
)) {
4527 if (getLangOpts().C23
)
4528 Diag(Tok
, diag::warn_c23_compat_keyword
) << Tok
.getName();
4530 Diag(Tok
.getLocation(), diag::warn_cxx98_compat_alignas
);
4531 ParseAlignmentSpecifier(Attrs
, EndLoc
);
4535 if (Tok
.isRegularKeywordAttribute()) {
4536 SourceLocation Loc
= Tok
.getLocation();
4537 IdentifierInfo
*AttrName
= Tok
.getIdentifierInfo();
4538 Attrs
.addNew(AttrName
, Loc
, nullptr, Loc
, nullptr, 0, Tok
.getKind());
4543 assert(Tok
.is(tok::l_square
) && NextToken().is(tok::l_square
) &&
4544 "Not a double square bracket attribute list");
4546 SourceLocation OpenLoc
= Tok
.getLocation();
4547 if (getLangOpts().CPlusPlus
) {
4548 Diag(OpenLoc
, getLangOpts().CPlusPlus11
? diag::warn_cxx98_compat_attribute
4549 : diag::warn_ext_cxx11_attributes
);
4551 Diag(OpenLoc
, getLangOpts().C23
? diag::warn_pre_c23_compat_attributes
4552 : diag::warn_ext_c23_attributes
);
4556 checkCompoundToken(OpenLoc
, tok::l_square
, CompoundToken::AttrBegin
);
4559 SourceLocation CommonScopeLoc
;
4560 IdentifierInfo
*CommonScopeName
= nullptr;
4561 if (Tok
.is(tok::kw_using
)) {
4562 Diag(Tok
.getLocation(), getLangOpts().CPlusPlus17
4563 ? diag::warn_cxx14_compat_using_attribute_ns
4564 : diag::ext_using_attribute_ns
);
4567 CommonScopeName
= TryParseCXX11AttributeIdentifier(
4568 CommonScopeLoc
, Sema::AttributeCompletion::Scope
);
4569 if (!CommonScopeName
) {
4570 Diag(Tok
.getLocation(), diag::err_expected
) << tok::identifier
;
4571 SkipUntil(tok::r_square
, tok::colon
, StopBeforeMatch
);
4573 if (!TryConsumeToken(tok::colon
) && CommonScopeName
)
4574 Diag(Tok
.getLocation(), diag::err_expected
) << tok::colon
;
4577 bool AttrParsed
= false;
4578 while (!Tok
.isOneOf(tok::r_square
, tok::semi
, tok::eof
)) {
4580 // If we parsed an attribute, a comma is required before parsing any
4581 // additional attributes.
4582 if (ExpectAndConsume(tok::comma
)) {
4583 SkipUntil(tok::r_square
, StopAtSemi
| StopBeforeMatch
);
4589 // Eat all remaining superfluous commas before parsing the next attribute.
4590 while (TryConsumeToken(tok::comma
))
4593 SourceLocation ScopeLoc
, AttrLoc
;
4594 IdentifierInfo
*ScopeName
= nullptr, *AttrName
= nullptr;
4596 AttrName
= TryParseCXX11AttributeIdentifier(
4597 AttrLoc
, Sema::AttributeCompletion::Attribute
, CommonScopeName
);
4599 // Break out to the "expected ']'" diagnostic.
4603 if (TryConsumeToken(tok::coloncolon
)) {
4604 ScopeName
= AttrName
;
4607 AttrName
= TryParseCXX11AttributeIdentifier(
4608 AttrLoc
, Sema::AttributeCompletion::Attribute
, ScopeName
);
4610 Diag(Tok
.getLocation(), diag::err_expected
) << tok::identifier
;
4611 SkipUntil(tok::r_square
, tok::comma
, StopAtSemi
| StopBeforeMatch
);
4616 if (CommonScopeName
) {
4618 Diag(ScopeLoc
, diag::err_using_attribute_ns_conflict
)
4619 << SourceRange(CommonScopeLoc
);
4621 ScopeName
= CommonScopeName
;
4622 ScopeLoc
= CommonScopeLoc
;
4626 // Parse attribute arguments
4627 if (Tok
.is(tok::l_paren
))
4628 AttrParsed
= ParseCXX11AttributeArgs(AttrName
, AttrLoc
, Attrs
, EndLoc
,
4629 ScopeName
, ScopeLoc
, OpenMPTokens
);
4634 SourceRange(ScopeLoc
.isValid() ? ScopeLoc
: AttrLoc
, AttrLoc
),
4635 ScopeName
, ScopeLoc
, nullptr, 0,
4636 getLangOpts().CPlusPlus
? ParsedAttr::Form::CXX11()
4637 : ParsedAttr::Form::C23());
4641 if (TryConsumeToken(tok::ellipsis
))
4642 Diag(Tok
, diag::err_cxx11_attribute_forbids_ellipsis
) << AttrName
;
4645 // If we hit an error and recovered by parsing up to a semicolon, eat the
4646 // semicolon and don't issue further diagnostics about missing brackets.
4647 if (Tok
.is(tok::semi
)) {
4652 SourceLocation CloseLoc
= Tok
.getLocation();
4653 if (ExpectAndConsume(tok::r_square
))
4654 SkipUntil(tok::r_square
);
4655 else if (Tok
.is(tok::r_square
))
4656 checkCompoundToken(CloseLoc
, tok::r_square
, CompoundToken::AttrEnd
);
4658 *EndLoc
= Tok
.getLocation();
4659 if (ExpectAndConsume(tok::r_square
))
4660 SkipUntil(tok::r_square
);
4663 /// ParseCXX11Attributes - Parse a C++11 or C23 attribute-specifier-seq.
4665 /// attribute-specifier-seq:
4666 /// attribute-specifier-seq[opt] attribute-specifier
4667 void Parser::ParseCXX11Attributes(ParsedAttributes
&Attrs
) {
4668 SourceLocation StartLoc
= Tok
.getLocation();
4669 SourceLocation EndLoc
= StartLoc
;
4672 ParseCXX11AttributeSpecifier(Attrs
, &EndLoc
);
4673 } while (isAllowedCXX11AttributeSpecifier());
4675 Attrs
.Range
= SourceRange(StartLoc
, EndLoc
);
4678 void Parser::DiagnoseAndSkipCXX11Attributes() {
4680 Tok
.isRegularKeywordAttribute() ? Tok
.getIdentifierInfo() : nullptr;
4681 // Start and end location of an attribute or an attribute list.
4682 SourceLocation StartLoc
= Tok
.getLocation();
4683 SourceLocation EndLoc
= SkipCXX11Attributes();
4685 if (EndLoc
.isValid()) {
4686 SourceRange
Range(StartLoc
, EndLoc
);
4687 (Keyword
? Diag(StartLoc
, diag::err_keyword_not_allowed
) << Keyword
4688 : Diag(StartLoc
, diag::err_attributes_not_allowed
))
4693 SourceLocation
Parser::SkipCXX11Attributes() {
4694 SourceLocation EndLoc
;
4696 if (!isCXX11AttributeSpecifier())
4700 if (Tok
.is(tok::l_square
)) {
4701 BalancedDelimiterTracker
T(*this, tok::l_square
);
4704 EndLoc
= T
.getCloseLocation();
4705 } else if (Tok
.isRegularKeywordAttribute()) {
4706 EndLoc
= Tok
.getLocation();
4709 assert(Tok
.is(tok::kw_alignas
) && "not an attribute specifier");
4711 BalancedDelimiterTracker
T(*this, tok::l_paren
);
4712 if (!T
.consumeOpen())
4714 EndLoc
= T
.getCloseLocation();
4716 } while (isCXX11AttributeSpecifier());
4721 /// Parse uuid() attribute when it appears in a [] Microsoft attribute.
4722 void Parser::ParseMicrosoftUuidAttributeArgs(ParsedAttributes
&Attrs
) {
4723 assert(Tok
.is(tok::identifier
) && "Not a Microsoft attribute list");
4724 IdentifierInfo
*UuidIdent
= Tok
.getIdentifierInfo();
4725 assert(UuidIdent
->getName() == "uuid" && "Not a Microsoft attribute list");
4727 SourceLocation UuidLoc
= Tok
.getLocation();
4730 // Ignore the left paren location for now.
4731 BalancedDelimiterTracker
T(*this, tok::l_paren
);
4732 if (T
.consumeOpen()) {
4733 Diag(Tok
, diag::err_expected
) << tok::l_paren
;
4737 ArgsVector ArgExprs
;
4738 if (isTokenStringLiteral()) {
4739 // Easy case: uuid("...") -- quoted string.
4740 ExprResult StringResult
= ParseUnevaluatedStringLiteralExpression();
4741 if (StringResult
.isInvalid())
4743 ArgExprs
.push_back(StringResult
.get());
4745 // something like uuid({000000A0-0000-0000-C000-000000000049}) -- no
4746 // quotes in the parens. Just append the spelling of all tokens encountered
4747 // until the closing paren.
4749 SmallString
<42> StrBuffer
; // 2 "", 36 bytes UUID, 2 optional {}, 1 nul
4752 // Since none of C++'s keywords match [a-f]+, accepting just tok::l_brace,
4753 // tok::r_brace, tok::minus, tok::identifier (think C000) and
4754 // tok::numeric_constant (0000) should be enough. But the spelling of the
4755 // uuid argument is checked later anyways, so there's no harm in accepting
4756 // almost anything here.
4757 // cl is very strict about whitespace in this form and errors out if any
4758 // is present, so check the space flags on the tokens.
4759 SourceLocation StartLoc
= Tok
.getLocation();
4760 while (Tok
.isNot(tok::r_paren
)) {
4761 if (Tok
.hasLeadingSpace() || Tok
.isAtStartOfLine()) {
4762 Diag(Tok
, diag::err_attribute_uuid_malformed_guid
);
4763 SkipUntil(tok::r_paren
, StopAtSemi
);
4766 SmallString
<16> SpellingBuffer
;
4767 SpellingBuffer
.resize(Tok
.getLength() + 1);
4768 bool Invalid
= false;
4769 StringRef TokSpelling
= PP
.getSpelling(Tok
, SpellingBuffer
, &Invalid
);
4771 SkipUntil(tok::r_paren
, StopAtSemi
);
4774 StrBuffer
+= TokSpelling
;
4779 if (Tok
.hasLeadingSpace() || Tok
.isAtStartOfLine()) {
4780 Diag(Tok
, diag::err_attribute_uuid_malformed_guid
);
4785 // Pretend the user wrote the appropriate string literal here.
4786 // ActOnStringLiteral() copies the string data into the literal, so it's
4787 // ok that the Token points to StrBuffer.
4789 Toks
[0].startToken();
4790 Toks
[0].setKind(tok::string_literal
);
4791 Toks
[0].setLocation(StartLoc
);
4792 Toks
[0].setLiteralData(StrBuffer
.data());
4793 Toks
[0].setLength(StrBuffer
.size());
4794 StringLiteral
*UuidString
=
4795 cast
<StringLiteral
>(Actions
.ActOnUnevaluatedStringLiteral(Toks
).get());
4796 ArgExprs
.push_back(UuidString
);
4799 if (!T
.consumeClose()) {
4800 Attrs
.addNew(UuidIdent
, SourceRange(UuidLoc
, T
.getCloseLocation()), nullptr,
4801 SourceLocation(), ArgExprs
.data(), ArgExprs
.size(),
4802 ParsedAttr::Form::Microsoft());
4806 /// ParseMicrosoftAttributes - Parse Microsoft attributes [Attr]
4808 /// [MS] ms-attribute:
4809 /// '[' token-seq ']'
4811 /// [MS] ms-attribute-seq:
4812 /// ms-attribute[opt]
4813 /// ms-attribute ms-attribute-seq
4814 void Parser::ParseMicrosoftAttributes(ParsedAttributes
&Attrs
) {
4815 assert(Tok
.is(tok::l_square
) && "Not a Microsoft attribute list");
4817 SourceLocation StartLoc
= Tok
.getLocation();
4818 SourceLocation EndLoc
= StartLoc
;
4820 // FIXME: If this is actually a C++11 attribute, parse it as one.
4821 BalancedDelimiterTracker
T(*this, tok::l_square
);
4824 // Skip most ms attributes except for a specific list.
4826 SkipUntil(tok::r_square
, tok::identifier
,
4827 StopAtSemi
| StopBeforeMatch
| StopAtCodeCompletion
);
4828 if (Tok
.is(tok::code_completion
)) {
4830 Actions
.CodeCompleteAttribute(AttributeCommonInfo::AS_Microsoft
,
4831 Sema::AttributeCompletion::Attribute
,
4835 if (Tok
.isNot(tok::identifier
)) // ']', but also eof
4837 if (Tok
.getIdentifierInfo()->getName() == "uuid")
4838 ParseMicrosoftUuidAttributeArgs(Attrs
);
4840 IdentifierInfo
*II
= Tok
.getIdentifierInfo();
4841 SourceLocation NameLoc
= Tok
.getLocation();
4843 ParsedAttr::Kind AttrKind
=
4844 ParsedAttr::getParsedKind(II
, nullptr, ParsedAttr::AS_Microsoft
);
4845 // For HLSL we want to handle all attributes, but for MSVC compat, we
4846 // silently ignore unknown Microsoft attributes.
4847 if (getLangOpts().HLSL
|| AttrKind
!= ParsedAttr::UnknownAttribute
) {
4848 bool AttrParsed
= false;
4849 if (Tok
.is(tok::l_paren
)) {
4850 CachedTokens OpenMPTokens
;
4852 ParseCXX11AttributeArgs(II
, NameLoc
, Attrs
, &EndLoc
, nullptr,
4853 SourceLocation(), OpenMPTokens
);
4854 ReplayOpenMPAttributeTokens(OpenMPTokens
);
4857 Attrs
.addNew(II
, NameLoc
, nullptr, SourceLocation(), nullptr, 0,
4858 ParsedAttr::Form::Microsoft());
4865 EndLoc
= T
.getCloseLocation();
4866 } while (Tok
.is(tok::l_square
));
4868 Attrs
.Range
= SourceRange(StartLoc
, EndLoc
);
4871 void Parser::ParseMicrosoftIfExistsClassDeclaration(
4872 DeclSpec::TST TagType
, ParsedAttributes
&AccessAttrs
,
4873 AccessSpecifier
&CurAS
) {
4874 IfExistsCondition Result
;
4875 if (ParseMicrosoftIfExistsCondition(Result
))
4878 BalancedDelimiterTracker
Braces(*this, tok::l_brace
);
4879 if (Braces
.consumeOpen()) {
4880 Diag(Tok
, diag::err_expected
) << tok::l_brace
;
4884 switch (Result
.Behavior
) {
4886 // Parse the declarations below.
4890 Diag(Result
.KeywordLoc
, diag::warn_microsoft_dependent_exists
)
4891 << Result
.IsIfExists
;
4892 // Fall through to skip.
4900 while (Tok
.isNot(tok::r_brace
) && !isEofOrEom()) {
4901 // __if_exists, __if_not_exists can nest.
4902 if (Tok
.isOneOf(tok::kw___if_exists
, tok::kw___if_not_exists
)) {
4903 ParseMicrosoftIfExistsClassDeclaration(TagType
, AccessAttrs
, CurAS
);
4907 // Check for extraneous top-level semicolon.
4908 if (Tok
.is(tok::semi
)) {
4909 ConsumeExtraSemi(InsideStruct
, TagType
);
4913 AccessSpecifier AS
= getAccessSpecifierIfPresent();
4914 if (AS
!= AS_none
) {
4915 // Current token is a C++ access specifier.
4917 SourceLocation ASLoc
= Tok
.getLocation();
4919 if (Tok
.is(tok::colon
))
4920 Actions
.ActOnAccessSpecifier(AS
, ASLoc
, Tok
.getLocation(),
4921 ParsedAttributesView
{});
4923 Diag(Tok
, diag::err_expected
) << tok::colon
;
4928 // Parse all the comma separated declarators.
4929 ParseCXXClassMemberDeclaration(CurAS
, AccessAttrs
);
4932 Braces
.consumeClose();