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/DiagnosticParse.h"
20 #include "clang/Basic/OperatorKinds.h"
21 #include "clang/Basic/TargetInfo.h"
22 #include "clang/Basic/TokenKinds.h"
23 #include "clang/Lex/LiteralSupport.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 "clang/Sema/SemaCodeCompletion.h"
31 #include "llvm/ADT/SmallString.h"
32 #include "llvm/Support/TimeProfiler.h"
35 using namespace clang
;
37 /// ParseNamespace - We know that the current token is a namespace keyword. This
38 /// may either be a top level namespace or a block-level namespace alias. If
39 /// there was an inline keyword, it has already been parsed.
41 /// namespace-definition: [C++: namespace.def]
42 /// named-namespace-definition
43 /// unnamed-namespace-definition
44 /// nested-namespace-definition
46 /// named-namespace-definition:
47 /// 'inline'[opt] 'namespace' attributes[opt] identifier '{'
48 /// namespace-body '}'
50 /// unnamed-namespace-definition:
51 /// 'inline'[opt] 'namespace' attributes[opt] '{' namespace-body '}'
53 /// nested-namespace-definition:
54 /// 'namespace' enclosing-namespace-specifier '::' 'inline'[opt]
55 /// identifier '{' namespace-body '}'
57 /// enclosing-namespace-specifier:
59 /// enclosing-namespace-specifier '::' 'inline'[opt] identifier
61 /// namespace-alias-definition: [C++ 7.3.2: namespace.alias]
62 /// 'namespace' identifier '=' qualified-namespace-specifier ';'
64 Parser::DeclGroupPtrTy
Parser::ParseNamespace(DeclaratorContext Context
,
65 SourceLocation
&DeclEnd
,
66 SourceLocation InlineLoc
) {
67 assert(Tok
.is(tok::kw_namespace
) && "Not a namespace!");
68 SourceLocation NamespaceLoc
= ConsumeToken(); // eat the 'namespace'.
69 ObjCDeclContextSwitch
ObjCDC(*this);
71 if (Tok
.is(tok::code_completion
)) {
73 Actions
.CodeCompletion().CodeCompleteNamespaceDecl(getCurScope());
77 SourceLocation IdentLoc
;
78 IdentifierInfo
*Ident
= nullptr;
79 InnerNamespaceInfoList ExtraNSs
;
80 SourceLocation FirstNestedInlineLoc
;
82 ParsedAttributes
attrs(AttrFactory
);
84 auto ReadAttributes
= [&] {
88 if (Tok
.is(tok::kw___attribute
)) {
89 ParseGNUAttributes(attrs
);
92 if (getLangOpts().CPlusPlus11
&& isCXX11AttributeSpecifier()) {
93 Diag(Tok
.getLocation(), getLangOpts().CPlusPlus17
94 ? diag::warn_cxx14_compat_ns_enum_attribute
95 : diag::ext_ns_enum_attribute
)
97 ParseCXX11Attributes(attrs
);
100 } while (MoreToParse
);
105 if (Tok
.is(tok::identifier
)) {
106 Ident
= Tok
.getIdentifierInfo();
107 IdentLoc
= ConsumeToken(); // eat the identifier.
108 while (Tok
.is(tok::coloncolon
) &&
109 (NextToken().is(tok::identifier
) ||
110 (NextToken().is(tok::kw_inline
) &&
111 GetLookAheadToken(2).is(tok::identifier
)))) {
113 InnerNamespaceInfo Info
;
114 Info
.NamespaceLoc
= ConsumeToken();
116 if (Tok
.is(tok::kw_inline
)) {
117 Info
.InlineLoc
= ConsumeToken();
118 if (FirstNestedInlineLoc
.isInvalid())
119 FirstNestedInlineLoc
= Info
.InlineLoc
;
122 Info
.Ident
= Tok
.getIdentifierInfo();
123 Info
.IdentLoc
= ConsumeToken();
125 ExtraNSs
.push_back(Info
);
131 SourceLocation attrLoc
= attrs
.Range
.getBegin();
133 // A nested namespace definition cannot have attributes.
134 if (!ExtraNSs
.empty() && attrLoc
.isValid())
135 Diag(attrLoc
, diag::err_unexpected_nested_namespace_attribute
);
137 if (Tok
.is(tok::equal
)) {
139 Diag(Tok
, diag::err_expected
) << tok::identifier
;
140 // Skip to end of the definition and eat the ';'.
141 SkipUntil(tok::semi
);
144 if (!ExtraNSs
.empty()) {
145 Diag(ExtraNSs
.front().NamespaceLoc
,
146 diag::err_unexpected_qualified_namespace_alias
)
147 << SourceRange(ExtraNSs
.front().NamespaceLoc
,
148 ExtraNSs
.back().IdentLoc
);
149 SkipUntil(tok::semi
);
152 if (attrLoc
.isValid())
153 Diag(attrLoc
, diag::err_unexpected_namespace_attributes_alias
);
154 if (InlineLoc
.isValid())
155 Diag(InlineLoc
, diag::err_inline_namespace_alias
)
156 << FixItHint::CreateRemoval(InlineLoc
);
157 Decl
*NSAlias
= ParseNamespaceAlias(NamespaceLoc
, IdentLoc
, Ident
, DeclEnd
);
158 return Actions
.ConvertDeclToDeclGroup(NSAlias
);
161 BalancedDelimiterTracker
T(*this, tok::l_brace
);
162 if (T
.consumeOpen()) {
164 Diag(Tok
, diag::err_expected
) << tok::l_brace
;
166 Diag(Tok
, diag::err_expected_either
) << tok::identifier
<< tok::l_brace
;
170 if (getCurScope()->isClassScope() || getCurScope()->isTemplateParamScope() ||
171 getCurScope()->isInObjcMethodScope() || getCurScope()->getBlockParent() ||
172 getCurScope()->getFnParent()) {
173 Diag(T
.getOpenLocation(), diag::err_namespace_nonnamespace_scope
);
174 SkipUntil(tok::r_brace
);
178 if (ExtraNSs
.empty()) {
179 // Normal namespace definition, not a nested-namespace-definition.
180 } else if (InlineLoc
.isValid()) {
181 Diag(InlineLoc
, diag::err_inline_nested_namespace_definition
);
182 } else if (getLangOpts().CPlusPlus20
) {
183 Diag(ExtraNSs
[0].NamespaceLoc
,
184 diag::warn_cxx14_compat_nested_namespace_definition
);
185 if (FirstNestedInlineLoc
.isValid())
186 Diag(FirstNestedInlineLoc
,
187 diag::warn_cxx17_compat_inline_nested_namespace_definition
);
188 } else if (getLangOpts().CPlusPlus17
) {
189 Diag(ExtraNSs
[0].NamespaceLoc
,
190 diag::warn_cxx14_compat_nested_namespace_definition
);
191 if (FirstNestedInlineLoc
.isValid())
192 Diag(FirstNestedInlineLoc
, diag::ext_inline_nested_namespace_definition
);
194 TentativeParsingAction
TPA(*this);
195 SkipUntil(tok::r_brace
, StopBeforeMatch
);
196 Token rBraceToken
= Tok
;
199 if (!rBraceToken
.is(tok::r_brace
)) {
200 Diag(ExtraNSs
[0].NamespaceLoc
, diag::ext_nested_namespace_definition
)
201 << SourceRange(ExtraNSs
.front().NamespaceLoc
,
202 ExtraNSs
.back().IdentLoc
);
204 std::string NamespaceFix
;
205 for (const auto &ExtraNS
: ExtraNSs
) {
206 NamespaceFix
+= " { ";
207 if (ExtraNS
.InlineLoc
.isValid())
208 NamespaceFix
+= "inline ";
209 NamespaceFix
+= "namespace ";
210 NamespaceFix
+= ExtraNS
.Ident
->getName();
214 for (unsigned i
= 0, e
= ExtraNSs
.size(); i
!= e
; ++i
)
217 Diag(ExtraNSs
[0].NamespaceLoc
, diag::ext_nested_namespace_definition
)
218 << FixItHint::CreateReplacement(
219 SourceRange(ExtraNSs
.front().NamespaceLoc
,
220 ExtraNSs
.back().IdentLoc
),
222 << FixItHint::CreateInsertion(rBraceToken
.getLocation(), RBraces
);
225 // Warn about nested inline namespaces.
226 if (FirstNestedInlineLoc
.isValid())
227 Diag(FirstNestedInlineLoc
, diag::ext_inline_nested_namespace_definition
);
230 // If we're still good, complain about inline namespaces in non-C++0x now.
231 if (InlineLoc
.isValid())
232 Diag(InlineLoc
, getLangOpts().CPlusPlus11
233 ? diag::warn_cxx98_compat_inline_namespace
234 : diag::ext_inline_namespace
);
236 // Enter a scope for the namespace.
237 ParseScope
NamespaceScope(this, Scope::DeclScope
);
239 UsingDirectiveDecl
*ImplicitUsingDirectiveDecl
= nullptr;
240 Decl
*NamespcDecl
= Actions
.ActOnStartNamespaceDef(
241 getCurScope(), InlineLoc
, NamespaceLoc
, IdentLoc
, Ident
,
242 T
.getOpenLocation(), attrs
, ImplicitUsingDirectiveDecl
, false);
244 PrettyDeclStackTraceEntry
CrashInfo(Actions
.Context
, NamespcDecl
,
245 NamespaceLoc
, "parsing namespace");
247 // Parse the contents of the namespace. This includes parsing recovery on
248 // any improperly nested namespaces.
249 ParseInnerNamespace(ExtraNSs
, 0, InlineLoc
, attrs
, T
);
251 // Leave the namespace scope.
252 NamespaceScope
.Exit();
254 DeclEnd
= T
.getCloseLocation();
255 Actions
.ActOnFinishNamespaceDef(NamespcDecl
, DeclEnd
);
257 return Actions
.ConvertDeclToDeclGroup(NamespcDecl
,
258 ImplicitUsingDirectiveDecl
);
261 /// ParseInnerNamespace - Parse the contents of a namespace.
262 void Parser::ParseInnerNamespace(const InnerNamespaceInfoList
&InnerNSs
,
263 unsigned int index
, SourceLocation
&InlineLoc
,
264 ParsedAttributes
&attrs
,
265 BalancedDelimiterTracker
&Tracker
) {
266 if (index
== InnerNSs
.size()) {
267 while (!tryParseMisplacedModuleImport() && Tok
.isNot(tok::r_brace
) &&
268 Tok
.isNot(tok::eof
)) {
269 ParsedAttributes
DeclAttrs(AttrFactory
);
270 MaybeParseCXX11Attributes(DeclAttrs
);
271 ParsedAttributes
EmptyDeclSpecAttrs(AttrFactory
);
272 ParseExternalDeclaration(DeclAttrs
, EmptyDeclSpecAttrs
);
275 // The caller is what called check -- we are simply calling
277 Tracker
.consumeClose();
282 // Handle a nested namespace definition.
283 // FIXME: Preserve the source information through to the AST rather than
284 // desugaring it here.
285 ParseScope
NamespaceScope(this, Scope::DeclScope
);
286 UsingDirectiveDecl
*ImplicitUsingDirectiveDecl
= nullptr;
287 Decl
*NamespcDecl
= Actions
.ActOnStartNamespaceDef(
288 getCurScope(), InnerNSs
[index
].InlineLoc
, InnerNSs
[index
].NamespaceLoc
,
289 InnerNSs
[index
].IdentLoc
, InnerNSs
[index
].Ident
,
290 Tracker
.getOpenLocation(), attrs
, ImplicitUsingDirectiveDecl
, true);
291 assert(!ImplicitUsingDirectiveDecl
&&
292 "nested namespace definition cannot define anonymous namespace");
294 ParseInnerNamespace(InnerNSs
, ++index
, InlineLoc
, attrs
, Tracker
);
296 NamespaceScope
.Exit();
297 Actions
.ActOnFinishNamespaceDef(NamespcDecl
, Tracker
.getCloseLocation());
300 /// ParseNamespaceAlias - Parse the part after the '=' in a namespace
301 /// alias definition.
303 Decl
*Parser::ParseNamespaceAlias(SourceLocation NamespaceLoc
,
304 SourceLocation AliasLoc
,
305 IdentifierInfo
*Alias
,
306 SourceLocation
&DeclEnd
) {
307 assert(Tok
.is(tok::equal
) && "Not equal token");
309 ConsumeToken(); // eat the '='.
311 if (Tok
.is(tok::code_completion
)) {
313 Actions
.CodeCompletion().CodeCompleteNamespaceAliasDecl(getCurScope());
318 // Parse (optional) nested-name-specifier.
319 ParseOptionalCXXScopeSpecifier(SS
, /*ObjectType=*/nullptr,
320 /*ObjectHasErrors=*/false,
321 /*EnteringContext=*/false,
322 /*MayBePseudoDestructor=*/nullptr,
323 /*IsTypename=*/false,
325 /*OnlyNamespace=*/true);
327 if (Tok
.isNot(tok::identifier
)) {
328 Diag(Tok
, diag::err_expected_namespace_name
);
329 // Skip to end of the definition and eat the ';'.
330 SkipUntil(tok::semi
);
334 if (SS
.isInvalid()) {
335 // Diagnostics have been emitted in ParseOptionalCXXScopeSpecifier.
336 // Skip to end of the definition and eat the ';'.
337 SkipUntil(tok::semi
);
342 IdentifierInfo
*Ident
= Tok
.getIdentifierInfo();
343 SourceLocation IdentLoc
= ConsumeToken();
346 DeclEnd
= Tok
.getLocation();
347 if (ExpectAndConsume(tok::semi
, diag::err_expected_semi_after_namespace_name
))
348 SkipUntil(tok::semi
);
350 return Actions
.ActOnNamespaceAliasDef(getCurScope(), NamespaceLoc
, AliasLoc
,
351 Alias
, SS
, IdentLoc
, Ident
);
354 /// ParseLinkage - We know that the current token is a string_literal
355 /// and just before that, that extern was seen.
357 /// linkage-specification: [C++ 7.5p2: dcl.link]
358 /// 'extern' string-literal '{' declaration-seq[opt] '}'
359 /// 'extern' string-literal declaration
361 Decl
*Parser::ParseLinkage(ParsingDeclSpec
&DS
, DeclaratorContext Context
) {
362 assert(isTokenStringLiteral() && "Not a string literal!");
363 ExprResult Lang
= ParseUnevaluatedStringLiteralExpression();
365 ParseScope
LinkageScope(this, Scope::DeclScope
);
369 : Actions
.ActOnStartLinkageSpecification(
370 getCurScope(), DS
.getSourceRange().getBegin(), Lang
.get(),
371 Tok
.is(tok::l_brace
) ? Tok
.getLocation() : SourceLocation());
373 ParsedAttributes
DeclAttrs(AttrFactory
);
374 ParsedAttributes
DeclSpecAttrs(AttrFactory
);
376 while (MaybeParseCXX11Attributes(DeclAttrs
) ||
377 MaybeParseGNUAttributes(DeclSpecAttrs
))
380 if (Tok
.isNot(tok::l_brace
)) {
381 // Reset the source range in DS, as the leading "extern"
382 // does not really belong to the inner declaration ...
383 DS
.SetRangeStart(SourceLocation());
384 DS
.SetRangeEnd(SourceLocation());
385 // ... but anyway remember that such an "extern" was seen.
386 DS
.setExternInLinkageSpec(true);
387 ParseExternalDeclaration(DeclAttrs
, DeclSpecAttrs
, &DS
);
388 return LinkageSpec
? Actions
.ActOnFinishLinkageSpecification(
389 getCurScope(), LinkageSpec
, SourceLocation())
395 ProhibitAttributes(DeclAttrs
);
397 BalancedDelimiterTracker
T(*this, tok::l_brace
);
400 unsigned NestedModules
= 0;
402 switch (Tok
.getKind()) {
403 case tok::annot_module_begin
:
408 case tok::annot_module_end
:
415 case tok::annot_module_include
:
427 ParsedAttributes
DeclAttrs(AttrFactory
);
428 ParsedAttributes
DeclSpecAttrs(AttrFactory
);
429 while (MaybeParseCXX11Attributes(DeclAttrs
) ||
430 MaybeParseGNUAttributes(DeclSpecAttrs
))
432 ParseExternalDeclaration(DeclAttrs
, DeclSpecAttrs
);
440 return LinkageSpec
? Actions
.ActOnFinishLinkageSpecification(
441 getCurScope(), LinkageSpec
, T
.getCloseLocation())
445 /// Parse a standard C++ Modules export-declaration.
447 /// export-declaration:
448 /// 'export' declaration
449 /// 'export' '{' declaration-seq[opt] '}'
451 /// HLSL: Parse export function declaration.
453 /// export-function-declaration:
454 /// 'export' function-declaration
456 /// export-declaration-group:
457 /// 'export' '{' function-declaration-seq[opt] '}'
459 Decl
*Parser::ParseExportDeclaration() {
460 assert(Tok
.is(tok::kw_export
));
461 SourceLocation ExportLoc
= ConsumeToken();
463 if (Tok
.is(tok::code_completion
)) {
465 Actions
.CodeCompletion().CodeCompleteOrdinaryName(
466 getCurScope(), PP
.isIncrementalProcessingEnabled()
467 ? SemaCodeCompletion::PCC_TopLevelOrExpression
468 : SemaCodeCompletion::PCC_Namespace
);
472 ParseScope
ExportScope(this, Scope::DeclScope
);
473 Decl
*ExportDecl
= Actions
.ActOnStartExportDecl(
474 getCurScope(), ExportLoc
,
475 Tok
.is(tok::l_brace
) ? Tok
.getLocation() : SourceLocation());
477 if (Tok
.isNot(tok::l_brace
)) {
478 // FIXME: Factor out a ParseExternalDeclarationWithAttrs.
479 ParsedAttributes
DeclAttrs(AttrFactory
);
480 MaybeParseCXX11Attributes(DeclAttrs
);
481 ParsedAttributes
EmptyDeclSpecAttrs(AttrFactory
);
482 ParseExternalDeclaration(DeclAttrs
, EmptyDeclSpecAttrs
);
483 return Actions
.ActOnFinishExportDecl(getCurScope(), ExportDecl
,
487 BalancedDelimiterTracker
T(*this, tok::l_brace
);
490 while (!tryParseMisplacedModuleImport() && Tok
.isNot(tok::r_brace
) &&
491 Tok
.isNot(tok::eof
)) {
492 ParsedAttributes
DeclAttrs(AttrFactory
);
493 MaybeParseCXX11Attributes(DeclAttrs
);
494 ParsedAttributes
EmptyDeclSpecAttrs(AttrFactory
);
495 ParseExternalDeclaration(DeclAttrs
, EmptyDeclSpecAttrs
);
499 return Actions
.ActOnFinishExportDecl(getCurScope(), ExportDecl
,
500 T
.getCloseLocation());
503 /// ParseUsingDirectiveOrDeclaration - Parse C++ using using-declaration or
504 /// using-directive. Assumes that current token is 'using'.
505 Parser::DeclGroupPtrTy
Parser::ParseUsingDirectiveOrDeclaration(
506 DeclaratorContext Context
, const ParsedTemplateInfo
&TemplateInfo
,
507 SourceLocation
&DeclEnd
, ParsedAttributes
&Attrs
) {
508 assert(Tok
.is(tok::kw_using
) && "Not using token");
509 ObjCDeclContextSwitch
ObjCDC(*this);
512 SourceLocation UsingLoc
= ConsumeToken();
514 if (Tok
.is(tok::code_completion
)) {
516 Actions
.CodeCompletion().CodeCompleteUsing(getCurScope());
520 // Consume unexpected 'template' keywords.
521 while (Tok
.is(tok::kw_template
)) {
522 SourceLocation TemplateLoc
= ConsumeToken();
523 Diag(TemplateLoc
, diag::err_unexpected_template_after_using
)
524 << FixItHint::CreateRemoval(TemplateLoc
);
527 // 'using namespace' means this is a using-directive.
528 if (Tok
.is(tok::kw_namespace
)) {
529 // Template parameters are always an error here.
530 if (TemplateInfo
.Kind
) {
531 SourceRange R
= TemplateInfo
.getSourceRange();
532 Diag(UsingLoc
, diag::err_templated_using_directive_declaration
)
533 << 0 /* directive */ << R
<< FixItHint::CreateRemoval(R
);
536 Decl
*UsingDir
= ParseUsingDirective(Context
, UsingLoc
, DeclEnd
, Attrs
);
537 return Actions
.ConvertDeclToDeclGroup(UsingDir
);
540 // Otherwise, it must be a using-declaration or an alias-declaration.
541 return ParseUsingDeclaration(Context
, TemplateInfo
, UsingLoc
, DeclEnd
, Attrs
,
545 /// ParseUsingDirective - Parse C++ using-directive, assumes
546 /// that current token is 'namespace' and 'using' was already parsed.
548 /// using-directive: [C++ 7.3.p4: namespace.udir]
549 /// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
551 /// [GNU] using-directive:
552 /// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
553 /// namespace-name attributes[opt] ;
555 Decl
*Parser::ParseUsingDirective(DeclaratorContext Context
,
556 SourceLocation UsingLoc
,
557 SourceLocation
&DeclEnd
,
558 ParsedAttributes
&attrs
) {
559 assert(Tok
.is(tok::kw_namespace
) && "Not 'namespace' token");
562 SourceLocation NamespcLoc
= ConsumeToken();
564 if (Tok
.is(tok::code_completion
)) {
566 Actions
.CodeCompletion().CodeCompleteUsingDirective(getCurScope());
571 // Parse (optional) nested-name-specifier.
572 ParseOptionalCXXScopeSpecifier(SS
, /*ObjectType=*/nullptr,
573 /*ObjectHasErrors=*/false,
574 /*EnteringContext=*/false,
575 /*MayBePseudoDestructor=*/nullptr,
576 /*IsTypename=*/false,
578 /*OnlyNamespace=*/true);
580 IdentifierInfo
*NamespcName
= nullptr;
581 SourceLocation IdentLoc
= SourceLocation();
583 // Parse namespace-name.
584 if (Tok
.isNot(tok::identifier
)) {
585 Diag(Tok
, diag::err_expected_namespace_name
);
586 // If there was invalid namespace name, skip to end of decl, and eat ';'.
587 SkipUntil(tok::semi
);
588 // FIXME: Are there cases, when we would like to call ActOnUsingDirective?
592 if (SS
.isInvalid()) {
593 // Diagnostics have been emitted in ParseOptionalCXXScopeSpecifier.
594 // Skip to end of the definition and eat the ';'.
595 SkipUntil(tok::semi
);
600 NamespcName
= Tok
.getIdentifierInfo();
601 IdentLoc
= ConsumeToken();
603 // Parse (optional) attributes (most likely GNU strong-using extension).
604 bool GNUAttr
= false;
605 if (Tok
.is(tok::kw___attribute
)) {
607 ParseGNUAttributes(attrs
);
611 DeclEnd
= Tok
.getLocation();
612 if (ExpectAndConsume(tok::semi
,
613 GNUAttr
? diag::err_expected_semi_after_attribute_list
614 : diag::err_expected_semi_after_namespace_name
))
615 SkipUntil(tok::semi
);
617 return Actions
.ActOnUsingDirective(getCurScope(), UsingLoc
, NamespcLoc
, SS
,
618 IdentLoc
, NamespcName
, attrs
);
621 /// Parse a using-declarator (or the identifier in a C++11 alias-declaration).
623 /// using-declarator:
624 /// 'typename'[opt] nested-name-specifier unqualified-id
626 bool Parser::ParseUsingDeclarator(DeclaratorContext Context
,
627 UsingDeclarator
&D
) {
630 // Ignore optional 'typename'.
631 // FIXME: This is wrong; we should parse this as a typename-specifier.
632 TryConsumeToken(tok::kw_typename
, D
.TypenameLoc
);
634 if (Tok
.is(tok::kw___super
)) {
635 Diag(Tok
.getLocation(), diag::err_super_in_using_declaration
);
639 // Parse nested-name-specifier.
640 const IdentifierInfo
*LastII
= nullptr;
641 if (ParseOptionalCXXScopeSpecifier(D
.SS
, /*ObjectType=*/nullptr,
642 /*ObjectHasErrors=*/false,
643 /*EnteringContext=*/false,
644 /*MayBePseudoDtor=*/nullptr,
645 /*IsTypename=*/false,
647 /*OnlyNamespace=*/false,
648 /*InUsingDeclaration=*/true))
651 if (D
.SS
.isInvalid())
654 // Parse the unqualified-id. We allow parsing of both constructor and
655 // destructor names and allow the action module to diagnose any semantic
658 // C++11 [class.qual]p2:
659 // [...] in a using-declaration that is a member-declaration, if the name
660 // specified after the nested-name-specifier is the same as the identifier
661 // or the simple-template-id's template-name in the last component of the
662 // nested-name-specifier, the name is [...] considered to name the
664 if (getLangOpts().CPlusPlus11
&& Context
== DeclaratorContext::Member
&&
665 Tok
.is(tok::identifier
) &&
666 (NextToken().is(tok::semi
) || NextToken().is(tok::comma
) ||
667 NextToken().is(tok::ellipsis
) || NextToken().is(tok::l_square
) ||
668 NextToken().isRegularKeywordAttribute() ||
669 NextToken().is(tok::kw___attribute
)) &&
670 D
.SS
.isNotEmpty() && LastII
== Tok
.getIdentifierInfo() &&
671 !D
.SS
.getScopeRep()->getAsNamespace() &&
672 !D
.SS
.getScopeRep()->getAsNamespaceAlias()) {
673 SourceLocation IdLoc
= ConsumeToken();
675 Actions
.getInheritingConstructorName(D
.SS
, IdLoc
, *LastII
);
676 D
.Name
.setConstructorName(Type
, IdLoc
, IdLoc
);
678 if (ParseUnqualifiedId(
679 D
.SS
, /*ObjectType=*/nullptr,
680 /*ObjectHadErrors=*/false, /*EnteringContext=*/false,
681 /*AllowDestructorName=*/true,
682 /*AllowConstructorName=*/
683 !(Tok
.is(tok::identifier
) && NextToken().is(tok::equal
)),
684 /*AllowDeductionGuide=*/false, nullptr, D
.Name
))
688 if (TryConsumeToken(tok::ellipsis
, D
.EllipsisLoc
))
689 Diag(Tok
.getLocation(), getLangOpts().CPlusPlus17
690 ? diag::warn_cxx17_compat_using_declaration_pack
691 : diag::ext_using_declaration_pack
);
696 /// ParseUsingDeclaration - Parse C++ using-declaration or alias-declaration.
697 /// Assumes that 'using' was already seen.
699 /// using-declaration: [C++ 7.3.p3: namespace.udecl]
700 /// 'using' using-declarator-list[opt] ;
702 /// using-declarator-list: [C++1z]
703 /// using-declarator '...'[opt]
704 /// using-declarator-list ',' using-declarator '...'[opt]
706 /// using-declarator-list: [C++98-14]
709 /// alias-declaration: C++11 [dcl.dcl]p1
710 /// 'using' identifier attribute-specifier-seq[opt] = type-id ;
712 /// using-enum-declaration: [C++20, dcl.enum]
713 /// 'using' elaborated-enum-specifier ;
714 /// The terminal name of the elaborated-enum-specifier undergoes
717 /// elaborated-enum-specifier:
718 /// 'enum' nested-name-specifier[opt] identifier
719 Parser::DeclGroupPtrTy
Parser::ParseUsingDeclaration(
720 DeclaratorContext Context
, const ParsedTemplateInfo
&TemplateInfo
,
721 SourceLocation UsingLoc
, SourceLocation
&DeclEnd
,
722 ParsedAttributes
&PrefixAttrs
, AccessSpecifier AS
) {
723 SourceLocation UELoc
;
724 bool InInitStatement
= Context
== DeclaratorContext::SelectionInit
||
725 Context
== DeclaratorContext::ForInit
;
727 if (TryConsumeToken(tok::kw_enum
, UELoc
) && !InInitStatement
) {
729 Diag(UELoc
, getLangOpts().CPlusPlus20
730 ? diag::warn_cxx17_compat_using_enum_declaration
731 : diag::ext_using_enum_declaration
);
733 DiagnoseCXX11AttributeExtension(PrefixAttrs
);
735 if (TemplateInfo
.Kind
) {
736 SourceRange R
= TemplateInfo
.getSourceRange();
737 Diag(UsingLoc
, diag::err_templated_using_directive_declaration
)
738 << 1 /* declaration */ << R
<< FixItHint::CreateRemoval(R
);
739 SkipUntil(tok::semi
);
743 if (ParseOptionalCXXScopeSpecifier(SS
, /*ParsedType=*/nullptr,
744 /*ObectHasErrors=*/false,
745 /*EnteringConttext=*/false,
746 /*MayBePseudoDestructor=*/nullptr,
748 /*IdentifierInfo=*/nullptr,
749 /*OnlyNamespace=*/false,
750 /*InUsingDeclaration=*/true)) {
751 SkipUntil(tok::semi
);
755 if (Tok
.is(tok::code_completion
)) {
757 Actions
.CodeCompletion().CodeCompleteUsing(getCurScope());
763 // FIXME: identifier and annot_template_id handling is very similar to
764 // ParseBaseTypeSpecifier. It should be factored out into a function.
765 if (Tok
.is(tok::identifier
)) {
766 IdentifierInfo
*IdentInfo
= Tok
.getIdentifierInfo();
767 SourceLocation IdentLoc
= ConsumeToken();
769 ParsedType Type
= Actions
.getTypeName(
770 *IdentInfo
, IdentLoc
, getCurScope(), &SS
, /*isClassName=*/true,
771 /*HasTrailingDot=*/false,
772 /*ObjectType=*/nullptr, /*IsCtorOrDtorName=*/false,
773 /*WantNontrivialTypeSourceInfo=*/true);
775 UED
= Actions
.ActOnUsingEnumDeclaration(
776 getCurScope(), AS
, UsingLoc
, UELoc
, IdentLoc
, *IdentInfo
, Type
, &SS
);
777 } else if (Tok
.is(tok::annot_template_id
)) {
778 TemplateIdAnnotation
*TemplateId
= takeTemplateIdAnnotation(Tok
);
780 if (TemplateId
->mightBeType()) {
781 AnnotateTemplateIdTokenAsType(SS
, ImplicitTypenameContext::No
,
782 /*IsClassName=*/true);
784 assert(Tok
.is(tok::annot_typename
) && "template-id -> type failed");
785 TypeResult Type
= getTypeAnnotation(Tok
);
786 SourceRange Loc
= Tok
.getAnnotationRange();
787 ConsumeAnnotationToken();
789 UED
= Actions
.ActOnUsingEnumDeclaration(getCurScope(), AS
, UsingLoc
,
790 UELoc
, Loc
, *TemplateId
->Name
,
793 Diag(Tok
.getLocation(), diag::err_using_enum_not_enum
)
794 << TemplateId
->Name
->getName()
795 << SourceRange(TemplateId
->TemplateNameLoc
, TemplateId
->RAngleLoc
);
798 Diag(Tok
.getLocation(), diag::err_using_enum_expect_identifier
)
799 << Tok
.is(tok::kw_enum
);
800 SkipUntil(tok::semi
);
805 SkipUntil(tok::semi
);
809 DeclEnd
= Tok
.getLocation();
810 if (ExpectAndConsume(tok::semi
, diag::err_expected_after
,
811 "using-enum declaration"))
812 SkipUntil(tok::semi
);
814 return Actions
.ConvertDeclToDeclGroup(UED
);
817 // Check for misplaced attributes before the identifier in an
818 // alias-declaration.
819 ParsedAttributes
MisplacedAttrs(AttrFactory
);
820 MaybeParseCXX11Attributes(MisplacedAttrs
);
822 if (InInitStatement
&& Tok
.isNot(tok::identifier
))
826 bool InvalidDeclarator
= ParseUsingDeclarator(Context
, D
);
828 ParsedAttributes
Attrs(AttrFactory
);
829 MaybeParseAttributes(PAKM_GNU
| PAKM_CXX11
, Attrs
);
831 // If we had any misplaced attributes from earlier, this is where they
832 // should have been written.
833 if (MisplacedAttrs
.Range
.isValid()) {
835 MisplacedAttrs
.empty() ? nullptr : &MisplacedAttrs
.front();
836 auto &Range
= MisplacedAttrs
.Range
;
837 (FirstAttr
&& FirstAttr
->isRegularKeywordAttribute()
838 ? Diag(Range
.getBegin(), diag::err_keyword_not_allowed
) << FirstAttr
839 : Diag(Range
.getBegin(), diag::err_attributes_not_allowed
))
840 << FixItHint::CreateInsertionFromRange(
841 Tok
.getLocation(), CharSourceRange::getTokenRange(Range
))
842 << FixItHint::CreateRemoval(Range
);
843 Attrs
.takeAllFrom(MisplacedAttrs
);
846 // Maybe this is an alias-declaration.
847 if (Tok
.is(tok::equal
) || InInitStatement
) {
848 if (InvalidDeclarator
) {
849 SkipUntil(tok::semi
);
853 ProhibitAttributes(PrefixAttrs
);
855 Decl
*DeclFromDeclSpec
= nullptr;
856 Scope
*CurScope
= getCurScope();
858 CurScope
->setFlags(Scope::ScopeFlags::TypeAliasScope
|
859 CurScope
->getFlags());
861 Decl
*AD
= ParseAliasDeclarationAfterDeclarator(
862 TemplateInfo
, UsingLoc
, D
, DeclEnd
, AS
, Attrs
, &DeclFromDeclSpec
);
863 return Actions
.ConvertDeclToDeclGroup(AD
, DeclFromDeclSpec
);
866 DiagnoseCXX11AttributeExtension(PrefixAttrs
);
868 // Diagnose an attempt to declare a templated using-declaration.
869 // In C++11, alias-declarations can be templates:
870 // template <...> using id = type;
871 if (TemplateInfo
.Kind
) {
872 SourceRange R
= TemplateInfo
.getSourceRange();
873 Diag(UsingLoc
, diag::err_templated_using_directive_declaration
)
874 << 1 /* declaration */ << R
<< FixItHint::CreateRemoval(R
);
876 // Unfortunately, we have to bail out instead of recovering by
877 // ignoring the parameters, just in case the nested name specifier
878 // depends on the parameters.
882 SmallVector
<Decl
*, 8> DeclsInGroup
;
884 // Parse (optional) attributes.
885 MaybeParseAttributes(PAKM_GNU
| PAKM_CXX11
, Attrs
);
886 DiagnoseCXX11AttributeExtension(Attrs
);
887 Attrs
.addAll(PrefixAttrs
.begin(), PrefixAttrs
.end());
889 if (InvalidDeclarator
)
890 SkipUntil(tok::comma
, tok::semi
, StopBeforeMatch
);
892 // "typename" keyword is allowed for identifiers only,
893 // because it may be a type definition.
894 if (D
.TypenameLoc
.isValid() &&
895 D
.Name
.getKind() != UnqualifiedIdKind::IK_Identifier
) {
896 Diag(D
.Name
.getSourceRange().getBegin(),
897 diag::err_typename_identifiers_only
)
898 << FixItHint::CreateRemoval(SourceRange(D
.TypenameLoc
));
899 // Proceed parsing, but discard the typename keyword.
900 D
.TypenameLoc
= SourceLocation();
903 Decl
*UD
= Actions
.ActOnUsingDeclaration(getCurScope(), AS
, UsingLoc
,
904 D
.TypenameLoc
, D
.SS
, D
.Name
,
905 D
.EllipsisLoc
, Attrs
);
907 DeclsInGroup
.push_back(UD
);
910 if (!TryConsumeToken(tok::comma
))
913 // Parse another using-declarator.
915 InvalidDeclarator
= ParseUsingDeclarator(Context
, D
);
918 if (DeclsInGroup
.size() > 1)
919 Diag(Tok
.getLocation(),
920 getLangOpts().CPlusPlus17
921 ? diag::warn_cxx17_compat_multi_using_declaration
922 : diag::ext_multi_using_declaration
);
925 DeclEnd
= Tok
.getLocation();
926 if (ExpectAndConsume(tok::semi
, diag::err_expected_after
,
927 !Attrs
.empty() ? "attributes list"
928 : UELoc
.isValid() ? "using-enum declaration"
929 : "using declaration"))
930 SkipUntil(tok::semi
);
932 return Actions
.BuildDeclaratorGroup(DeclsInGroup
);
935 Decl
*Parser::ParseAliasDeclarationAfterDeclarator(
936 const ParsedTemplateInfo
&TemplateInfo
, SourceLocation UsingLoc
,
937 UsingDeclarator
&D
, SourceLocation
&DeclEnd
, AccessSpecifier AS
,
938 ParsedAttributes
&Attrs
, Decl
**OwnedType
) {
939 if (ExpectAndConsume(tok::equal
)) {
940 SkipUntil(tok::semi
);
944 Diag(Tok
.getLocation(), getLangOpts().CPlusPlus11
945 ? diag::warn_cxx98_compat_alias_declaration
946 : diag::ext_alias_declaration
);
948 // Type alias templates cannot be specialized.
950 if (TemplateInfo
.Kind
== ParsedTemplateInfo::Template
&&
951 D
.Name
.getKind() == UnqualifiedIdKind::IK_TemplateId
)
953 if (TemplateInfo
.Kind
== ParsedTemplateInfo::ExplicitSpecialization
)
955 if (TemplateInfo
.Kind
== ParsedTemplateInfo::ExplicitInstantiation
)
957 if (SpecKind
!= -1) {
960 Range
= SourceRange(D
.Name
.TemplateId
->LAngleLoc
,
961 D
.Name
.TemplateId
->RAngleLoc
);
963 Range
= TemplateInfo
.getSourceRange();
964 Diag(Range
.getBegin(), diag::err_alias_declaration_specialization
)
965 << SpecKind
<< Range
;
966 SkipUntil(tok::semi
);
970 // Name must be an identifier.
971 if (D
.Name
.getKind() != UnqualifiedIdKind::IK_Identifier
) {
972 Diag(D
.Name
.StartLocation
, diag::err_alias_declaration_not_identifier
);
973 // No removal fixit: can't recover from this.
974 SkipUntil(tok::semi
);
976 } else if (D
.TypenameLoc
.isValid())
977 Diag(D
.TypenameLoc
, diag::err_alias_declaration_not_identifier
)
978 << FixItHint::CreateRemoval(
979 SourceRange(D
.TypenameLoc
, D
.SS
.isNotEmpty() ? D
.SS
.getEndLoc()
981 else if (D
.SS
.isNotEmpty())
982 Diag(D
.SS
.getBeginLoc(), diag::err_alias_declaration_not_identifier
)
983 << FixItHint::CreateRemoval(D
.SS
.getRange());
984 if (D
.EllipsisLoc
.isValid())
985 Diag(D
.EllipsisLoc
, diag::err_alias_declaration_pack_expansion
)
986 << FixItHint::CreateRemoval(SourceRange(D
.EllipsisLoc
));
988 Decl
*DeclFromDeclSpec
= nullptr;
989 TypeResult TypeAlias
=
990 ParseTypeName(nullptr,
991 TemplateInfo
.Kind
? DeclaratorContext::AliasTemplate
992 : DeclaratorContext::AliasDecl
,
993 AS
, &DeclFromDeclSpec
, &Attrs
);
995 *OwnedType
= DeclFromDeclSpec
;
998 DeclEnd
= Tok
.getLocation();
999 if (ExpectAndConsume(tok::semi
, diag::err_expected_after
,
1000 !Attrs
.empty() ? "attributes list"
1001 : "alias declaration"))
1002 SkipUntil(tok::semi
);
1004 TemplateParameterLists
*TemplateParams
= TemplateInfo
.TemplateParams
;
1005 MultiTemplateParamsArg
TemplateParamsArg(
1006 TemplateParams
? TemplateParams
->data() : nullptr,
1007 TemplateParams
? TemplateParams
->size() : 0);
1008 return Actions
.ActOnAliasDeclaration(getCurScope(), AS
, TemplateParamsArg
,
1009 UsingLoc
, D
.Name
, Attrs
, TypeAlias
,
1013 static FixItHint
getStaticAssertNoMessageFixIt(const Expr
*AssertExpr
,
1014 SourceLocation EndExprLoc
) {
1015 if (const auto *BO
= dyn_cast_or_null
<BinaryOperator
>(AssertExpr
)) {
1016 if (BO
->getOpcode() == BO_LAnd
&&
1017 isa
<StringLiteral
>(BO
->getRHS()->IgnoreImpCasts()))
1018 return FixItHint::CreateReplacement(BO
->getOperatorLoc(), ",");
1020 return FixItHint::CreateInsertion(EndExprLoc
, ", \"\"");
1023 /// ParseStaticAssertDeclaration - Parse C++0x or C11 static_assert-declaration.
1025 /// [C++0x] static_assert-declaration:
1026 /// static_assert ( constant-expression , string-literal ) ;
1028 /// [C11] static_assert-declaration:
1029 /// _Static_assert ( constant-expression , string-literal ) ;
1031 Decl
*Parser::ParseStaticAssertDeclaration(SourceLocation
&DeclEnd
) {
1032 assert(Tok
.isOneOf(tok::kw_static_assert
, tok::kw__Static_assert
) &&
1033 "Not a static_assert declaration");
1035 // Save the token name used for static assertion.
1036 const char *TokName
= Tok
.getName();
1038 if (Tok
.is(tok::kw__Static_assert
))
1039 diagnoseUseOfC11Keyword(Tok
);
1040 else if (Tok
.is(tok::kw_static_assert
)) {
1041 if (!getLangOpts().CPlusPlus
) {
1042 if (getLangOpts().C23
)
1043 Diag(Tok
, diag::warn_c23_compat_keyword
) << Tok
.getName();
1045 Diag(Tok
, diag::ext_ms_static_assert
) << FixItHint::CreateReplacement(
1046 Tok
.getLocation(), "_Static_assert");
1048 Diag(Tok
, diag::warn_cxx98_compat_static_assert
);
1051 SourceLocation StaticAssertLoc
= ConsumeToken();
1053 BalancedDelimiterTracker
T(*this, tok::l_paren
);
1054 if (T
.consumeOpen()) {
1055 Diag(Tok
, diag::err_expected
) << tok::l_paren
;
1056 SkipMalformedDecl();
1060 EnterExpressionEvaluationContext
ConstantEvaluated(
1061 Actions
, Sema::ExpressionEvaluationContext::ConstantEvaluated
);
1062 ExprResult
AssertExpr(ParseConstantExpressionInExprEvalContext());
1063 if (AssertExpr
.isInvalid()) {
1064 SkipMalformedDecl();
1068 ExprResult AssertMessage
;
1069 if (Tok
.is(tok::r_paren
)) {
1071 if (getLangOpts().CPlusPlus17
)
1072 DiagVal
= diag::warn_cxx14_compat_static_assert_no_message
;
1073 else if (getLangOpts().CPlusPlus
)
1074 DiagVal
= diag::ext_cxx_static_assert_no_message
;
1075 else if (getLangOpts().C23
)
1076 DiagVal
= diag::warn_c17_compat_static_assert_no_message
;
1078 DiagVal
= diag::ext_c_static_assert_no_message
;
1079 Diag(Tok
, DiagVal
) << getStaticAssertNoMessageFixIt(AssertExpr
.get(),
1082 if (ExpectAndConsume(tok::comma
)) {
1083 SkipUntil(tok::semi
);
1087 bool ParseAsExpression
= false;
1088 if (getLangOpts().CPlusPlus11
) {
1089 for (unsigned I
= 0;; ++I
) {
1090 const Token
&T
= GetLookAheadToken(I
);
1091 if (T
.is(tok::r_paren
))
1093 if (!tokenIsLikeStringLiteral(T
, getLangOpts()) || T
.hasUDSuffix()) {
1094 ParseAsExpression
= true;
1100 if (ParseAsExpression
) {
1102 getLangOpts().CPlusPlus26
1103 ? diag::warn_cxx20_compat_static_assert_user_generated_message
1104 : diag::ext_cxx_static_assert_user_generated_message
);
1105 AssertMessage
= ParseConstantExpressionInExprEvalContext();
1106 } else if (tokenIsLikeStringLiteral(Tok
, getLangOpts()))
1107 AssertMessage
= ParseUnevaluatedStringLiteralExpression();
1109 Diag(Tok
, diag::err_expected_string_literal
)
1110 << /*Source='static_assert'*/ 1;
1111 SkipMalformedDecl();
1115 if (AssertMessage
.isInvalid()) {
1116 SkipMalformedDecl();
1121 if (T
.consumeClose())
1124 DeclEnd
= Tok
.getLocation();
1125 ExpectAndConsumeSemi(diag::err_expected_semi_after_static_assert
, TokName
);
1127 return Actions
.ActOnStaticAssertDeclaration(StaticAssertLoc
, AssertExpr
.get(),
1128 AssertMessage
.get(),
1129 T
.getCloseLocation());
1132 /// ParseDecltypeSpecifier - Parse a C++11 decltype specifier.
1134 /// 'decltype' ( expression )
1135 /// 'decltype' ( 'auto' ) [C++1y]
1137 SourceLocation
Parser::ParseDecltypeSpecifier(DeclSpec
&DS
) {
1138 assert(Tok
.isOneOf(tok::kw_decltype
, tok::annot_decltype
) &&
1139 "Not a decltype specifier");
1142 SourceLocation StartLoc
= Tok
.getLocation();
1143 SourceLocation EndLoc
;
1145 if (Tok
.is(tok::annot_decltype
)) {
1146 Result
= getExprAnnotation(Tok
);
1147 EndLoc
= Tok
.getAnnotationEndLoc();
1148 // Unfortunately, we don't know the LParen source location as the annotated
1149 // token doesn't have it.
1150 DS
.setTypeArgumentRange(SourceRange(SourceLocation(), EndLoc
));
1151 ConsumeAnnotationToken();
1152 if (Result
.isInvalid()) {
1153 DS
.SetTypeSpecError();
1157 if (Tok
.getIdentifierInfo()->isStr("decltype"))
1158 Diag(Tok
, diag::warn_cxx98_compat_decltype
);
1162 BalancedDelimiterTracker
T(*this, tok::l_paren
);
1163 if (T
.expectAndConsume(diag::err_expected_lparen_after
, "decltype",
1165 DS
.SetTypeSpecError();
1166 return T
.getOpenLocation() == Tok
.getLocation() ? StartLoc
1167 : T
.getOpenLocation();
1170 // Check for C++1y 'decltype(auto)'.
1171 if (Tok
.is(tok::kw_auto
) && NextToken().is(tok::r_paren
)) {
1172 // the typename-specifier in a function-style cast expression may
1173 // be 'auto' since C++23.
1174 Diag(Tok
.getLocation(),
1175 getLangOpts().CPlusPlus14
1176 ? diag::warn_cxx11_compat_decltype_auto_type_specifier
1177 : diag::ext_decltype_auto_type_specifier
);
1180 // Parse the expression
1182 // C++11 [dcl.type.simple]p4:
1183 // The operand of the decltype specifier is an unevaluated operand.
1184 EnterExpressionEvaluationContext
Unevaluated(
1185 Actions
, Sema::ExpressionEvaluationContext::Unevaluated
, nullptr,
1186 Sema::ExpressionEvaluationContextRecord::EK_Decltype
);
1187 Result
= Actions
.CorrectDelayedTyposInExpr(
1188 ParseExpression(), /*InitDecl=*/nullptr,
1189 /*RecoverUncorrectedTypos=*/false,
1190 [](Expr
*E
) { return E
->hasPlaceholderType() ? ExprError() : E
; });
1191 if (Result
.isInvalid()) {
1192 DS
.SetTypeSpecError();
1193 if (SkipUntil(tok::r_paren
, StopAtSemi
| StopBeforeMatch
)) {
1194 EndLoc
= ConsumeParen();
1196 if (PP
.isBacktrackEnabled() && Tok
.is(tok::semi
)) {
1197 // Backtrack to get the location of the last token before the semi.
1198 PP
.RevertCachedTokens(2);
1199 ConsumeToken(); // the semi.
1200 EndLoc
= ConsumeAnyToken();
1201 assert(Tok
.is(tok::semi
));
1203 EndLoc
= Tok
.getLocation();
1209 Result
= Actions
.ActOnDecltypeExpression(Result
.get());
1214 DS
.setTypeArgumentRange(T
.getRange());
1215 if (T
.getCloseLocation().isInvalid()) {
1216 DS
.SetTypeSpecError();
1217 // FIXME: this should return the location of the last token
1218 // that was consumed (by "consumeClose()")
1219 return T
.getCloseLocation();
1222 if (Result
.isInvalid()) {
1223 DS
.SetTypeSpecError();
1224 return T
.getCloseLocation();
1227 EndLoc
= T
.getCloseLocation();
1229 assert(!Result
.isInvalid());
1231 const char *PrevSpec
= nullptr;
1233 const PrintingPolicy
&Policy
= Actions
.getASTContext().getPrintingPolicy();
1234 // Check for duplicate type specifiers (e.g. "int decltype(a)").
1235 if (Result
.get() ? DS
.SetTypeSpecType(DeclSpec::TST_decltype
, StartLoc
,
1236 PrevSpec
, DiagID
, Result
.get(), Policy
)
1237 : DS
.SetTypeSpecType(DeclSpec::TST_decltype_auto
, StartLoc
,
1238 PrevSpec
, DiagID
, Policy
)) {
1239 Diag(StartLoc
, DiagID
) << PrevSpec
;
1240 DS
.SetTypeSpecError();
1245 void Parser::AnnotateExistingDecltypeSpecifier(const DeclSpec
&DS
,
1246 SourceLocation StartLoc
,
1247 SourceLocation EndLoc
) {
1248 // make sure we have a token we can turn into an annotation token
1249 if (PP
.isBacktrackEnabled()) {
1250 PP
.RevertCachedTokens(1);
1251 if (DS
.getTypeSpecType() == TST_error
) {
1252 // We encountered an error in parsing 'decltype(...)' so lets annotate all
1253 // the tokens in the backtracking cache - that we likely had to skip over
1254 // to get to a token that allows us to resume parsing, such as a
1256 EndLoc
= PP
.getLastCachedTokenLocation();
1259 PP
.EnterToken(Tok
, /*IsReinject*/ true);
1261 Tok
.setKind(tok::annot_decltype
);
1262 setExprAnnotation(Tok
,
1263 DS
.getTypeSpecType() == TST_decltype
? DS
.getRepAsExpr()
1264 : DS
.getTypeSpecType() == TST_decltype_auto
? ExprResult()
1266 Tok
.setAnnotationEndLoc(EndLoc
);
1267 Tok
.setLocation(StartLoc
);
1268 PP
.AnnotateCachedTokens(Tok
);
1271 SourceLocation
Parser::ParsePackIndexingType(DeclSpec
&DS
) {
1272 assert(Tok
.isOneOf(tok::annot_pack_indexing_type
, tok::identifier
) &&
1273 "Expected an identifier");
1276 SourceLocation StartLoc
;
1277 SourceLocation EllipsisLoc
;
1278 const char *PrevSpec
;
1280 const PrintingPolicy
&Policy
= Actions
.getASTContext().getPrintingPolicy();
1282 if (Tok
.is(tok::annot_pack_indexing_type
)) {
1283 StartLoc
= Tok
.getLocation();
1284 SourceLocation EndLoc
;
1285 Type
= getTypeAnnotation(Tok
);
1286 EndLoc
= Tok
.getAnnotationEndLoc();
1287 // Unfortunately, we don't know the LParen source location as the annotated
1288 // token doesn't have it.
1289 DS
.setTypeArgumentRange(SourceRange(SourceLocation(), EndLoc
));
1290 ConsumeAnnotationToken();
1291 if (Type
.isInvalid()) {
1292 DS
.SetTypeSpecError();
1295 DS
.SetTypeSpecType(DeclSpec::TST_typename_pack_indexing
, StartLoc
, PrevSpec
,
1296 DiagID
, Type
, Policy
);
1299 if (!NextToken().is(tok::ellipsis
) ||
1300 !GetLookAheadToken(2).is(tok::l_square
)) {
1301 DS
.SetTypeSpecError();
1302 return Tok
.getEndLoc();
1305 ParsedType Ty
= Actions
.getTypeName(*Tok
.getIdentifierInfo(),
1306 Tok
.getLocation(), getCurScope());
1308 DS
.SetTypeSpecError();
1309 return Tok
.getEndLoc();
1313 StartLoc
= ConsumeToken();
1314 EllipsisLoc
= ConsumeToken();
1315 BalancedDelimiterTracker
T(*this, tok::l_square
);
1317 ExprResult IndexExpr
= ParseConstantExpression();
1320 DS
.SetRangeStart(StartLoc
);
1321 DS
.SetRangeEnd(T
.getCloseLocation());
1323 if (!IndexExpr
.isUsable()) {
1324 ASTContext
&C
= Actions
.getASTContext();
1325 IndexExpr
= IntegerLiteral::Create(C
, C
.MakeIntValue(0, C
.getSizeType()),
1326 C
.getSizeType(), SourceLocation());
1329 DS
.SetTypeSpecType(DeclSpec::TST_typename
, StartLoc
, PrevSpec
, DiagID
, Type
,
1331 DS
.SetPackIndexingExpr(EllipsisLoc
, IndexExpr
.get());
1332 return T
.getCloseLocation();
1335 void Parser::AnnotateExistingIndexedTypeNamePack(ParsedType T
,
1336 SourceLocation StartLoc
,
1337 SourceLocation EndLoc
) {
1338 // make sure we have a token we can turn into an annotation token
1339 if (PP
.isBacktrackEnabled()) {
1340 PP
.RevertCachedTokens(1);
1342 // We encountered an error in parsing 'decltype(...)' so lets annotate all
1343 // the tokens in the backtracking cache - that we likely had to skip over
1344 // to get to a token that allows us to resume parsing, such as a
1346 EndLoc
= PP
.getLastCachedTokenLocation();
1349 PP
.EnterToken(Tok
, /*IsReinject*/ true);
1351 Tok
.setKind(tok::annot_pack_indexing_type
);
1352 setTypeAnnotation(Tok
, T
);
1353 Tok
.setAnnotationEndLoc(EndLoc
);
1354 Tok
.setLocation(StartLoc
);
1355 PP
.AnnotateCachedTokens(Tok
);
1358 DeclSpec::TST
Parser::TypeTransformTokToDeclSpec() {
1359 switch (Tok
.getKind()) {
1360 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) \
1361 case tok::kw___##Trait: \
1362 return DeclSpec::TST_##Trait;
1363 #include "clang/Basic/TransformTypeTraits.def"
1365 llvm_unreachable("passed in an unhandled type transformation built-in");
1369 bool Parser::MaybeParseTypeTransformTypeSpecifier(DeclSpec
&DS
) {
1370 if (!NextToken().is(tok::l_paren
)) {
1371 Tok
.setKind(tok::identifier
);
1374 DeclSpec::TST TypeTransformTST
= TypeTransformTokToDeclSpec();
1375 SourceLocation StartLoc
= ConsumeToken();
1377 BalancedDelimiterTracker
T(*this, tok::l_paren
);
1378 if (T
.expectAndConsume(diag::err_expected_lparen_after
, Tok
.getName(),
1382 TypeResult Result
= ParseTypeName();
1383 if (Result
.isInvalid()) {
1384 SkipUntil(tok::r_paren
, StopAtSemi
);
1389 if (T
.getCloseLocation().isInvalid())
1392 const char *PrevSpec
= nullptr;
1394 if (DS
.SetTypeSpecType(TypeTransformTST
, StartLoc
, PrevSpec
, DiagID
,
1396 Actions
.getASTContext().getPrintingPolicy()))
1397 Diag(StartLoc
, DiagID
) << PrevSpec
;
1398 DS
.setTypeArgumentRange(T
.getRange());
1402 /// ParseBaseTypeSpecifier - Parse a C++ base-type-specifier which is either a
1403 /// class name or decltype-specifier. Note that we only check that the result
1404 /// names a type; semantic analysis will need to verify that the type names a
1405 /// class. The result is either a type or null, depending on whether a type
1408 /// base-type-specifier: [C++11 class.derived]
1409 /// class-or-decltype
1410 /// class-or-decltype: [C++11 class.derived]
1411 /// nested-name-specifier[opt] class-name
1412 /// decltype-specifier
1413 /// class-name: [C++ class.name]
1415 /// simple-template-id
1417 /// In C++98, instead of base-type-specifier, we have:
1419 /// ::[opt] nested-name-specifier[opt] class-name
1420 TypeResult
Parser::ParseBaseTypeSpecifier(SourceLocation
&BaseLoc
,
1421 SourceLocation
&EndLocation
) {
1422 // Ignore attempts to use typename
1423 if (Tok
.is(tok::kw_typename
)) {
1424 Diag(Tok
, diag::err_expected_class_name_not_template
)
1425 << FixItHint::CreateRemoval(Tok
.getLocation());
1429 // Parse optional nested-name-specifier
1431 if (ParseOptionalCXXScopeSpecifier(SS
, /*ObjectType=*/nullptr,
1432 /*ObjectHasErrors=*/false,
1433 /*EnteringContext=*/false))
1436 BaseLoc
= Tok
.getLocation();
1438 // Parse decltype-specifier
1439 // tok == kw_decltype is just error recovery, it can only happen when SS
1441 if (Tok
.isOneOf(tok::kw_decltype
, tok::annot_decltype
)) {
1442 if (SS
.isNotEmpty())
1443 Diag(SS
.getBeginLoc(), diag::err_unexpected_scope_on_base_decltype
)
1444 << FixItHint::CreateRemoval(SS
.getRange());
1445 // Fake up a Declarator to use with ActOnTypeName.
1446 DeclSpec
DS(AttrFactory
);
1448 EndLocation
= ParseDecltypeSpecifier(DS
);
1450 Declarator
DeclaratorInfo(DS
, ParsedAttributesView::none(),
1451 DeclaratorContext::TypeName
);
1452 return Actions
.ActOnTypeName(DeclaratorInfo
);
1455 if (Tok
.is(tok::annot_pack_indexing_type
)) {
1456 DeclSpec
DS(AttrFactory
);
1457 ParsePackIndexingType(DS
);
1458 Declarator
DeclaratorInfo(DS
, ParsedAttributesView::none(),
1459 DeclaratorContext::TypeName
);
1460 return Actions
.ActOnTypeName(DeclaratorInfo
);
1463 // Check whether we have a template-id that names a type.
1464 // FIXME: identifier and annot_template_id handling in ParseUsingDeclaration
1465 // work very similarly. It should be refactored into a separate function.
1466 if (Tok
.is(tok::annot_template_id
)) {
1467 TemplateIdAnnotation
*TemplateId
= takeTemplateIdAnnotation(Tok
);
1468 if (TemplateId
->mightBeType()) {
1469 AnnotateTemplateIdTokenAsType(SS
, ImplicitTypenameContext::No
,
1470 /*IsClassName=*/true);
1472 assert(Tok
.is(tok::annot_typename
) && "template-id -> type failed");
1473 TypeResult Type
= getTypeAnnotation(Tok
);
1474 EndLocation
= Tok
.getAnnotationEndLoc();
1475 ConsumeAnnotationToken();
1479 // Fall through to produce an error below.
1482 if (Tok
.isNot(tok::identifier
)) {
1483 Diag(Tok
, diag::err_expected_class_name
);
1487 IdentifierInfo
*Id
= Tok
.getIdentifierInfo();
1488 SourceLocation IdLoc
= ConsumeToken();
1490 if (Tok
.is(tok::less
)) {
1491 // It looks the user intended to write a template-id here, but the
1492 // template-name was wrong. Try to fix that.
1493 // FIXME: Invoke ParseOptionalCXXScopeSpecifier in a "'template' is neither
1494 // required nor permitted" mode, and do this there.
1495 TemplateNameKind TNK
= TNK_Non_template
;
1496 TemplateTy Template
;
1497 if (!Actions
.DiagnoseUnknownTemplateName(*Id
, IdLoc
, getCurScope(), &SS
,
1499 Diag(IdLoc
, diag::err_unknown_template_name
) << Id
;
1502 // Form the template name
1503 UnqualifiedId TemplateName
;
1504 TemplateName
.setIdentifier(Id
, IdLoc
);
1506 // Parse the full template-id, then turn it into a type.
1507 if (AnnotateTemplateIdToken(Template
, TNK
, SS
, SourceLocation(),
1510 if (Tok
.is(tok::annot_template_id
) &&
1511 takeTemplateIdAnnotation(Tok
)->mightBeType())
1512 AnnotateTemplateIdTokenAsType(SS
, ImplicitTypenameContext::No
,
1513 /*IsClassName=*/true);
1515 // If we didn't end up with a typename token, there's nothing more we
1517 if (Tok
.isNot(tok::annot_typename
))
1520 // Retrieve the type from the annotation token, consume that token, and
1522 EndLocation
= Tok
.getAnnotationEndLoc();
1523 TypeResult Type
= getTypeAnnotation(Tok
);
1524 ConsumeAnnotationToken();
1528 // We have an identifier; check whether it is actually a type.
1529 IdentifierInfo
*CorrectedII
= nullptr;
1530 ParsedType Type
= Actions
.getTypeName(
1531 *Id
, IdLoc
, getCurScope(), &SS
, /*isClassName=*/true, false, nullptr,
1532 /*IsCtorOrDtorName=*/false,
1533 /*WantNontrivialTypeSourceInfo=*/true,
1534 /*IsClassTemplateDeductionContext=*/false, ImplicitTypenameContext::No
,
1537 Diag(IdLoc
, diag::err_expected_class_name
);
1541 // Consume the identifier.
1542 EndLocation
= IdLoc
;
1544 // Fake up a Declarator to use with ActOnTypeName.
1545 DeclSpec
DS(AttrFactory
);
1546 DS
.SetRangeStart(IdLoc
);
1547 DS
.SetRangeEnd(EndLocation
);
1548 DS
.getTypeSpecScope() = SS
;
1550 const char *PrevSpec
= nullptr;
1552 DS
.SetTypeSpecType(TST_typename
, IdLoc
, PrevSpec
, DiagID
, Type
,
1553 Actions
.getASTContext().getPrintingPolicy());
1555 Declarator
DeclaratorInfo(DS
, ParsedAttributesView::none(),
1556 DeclaratorContext::TypeName
);
1557 return Actions
.ActOnTypeName(DeclaratorInfo
);
1560 void Parser::ParseMicrosoftInheritanceClassAttributes(ParsedAttributes
&attrs
) {
1561 while (Tok
.isOneOf(tok::kw___single_inheritance
,
1562 tok::kw___multiple_inheritance
,
1563 tok::kw___virtual_inheritance
)) {
1564 IdentifierInfo
*AttrName
= Tok
.getIdentifierInfo();
1565 auto Kind
= Tok
.getKind();
1566 SourceLocation AttrNameLoc
= ConsumeToken();
1567 attrs
.addNew(AttrName
, AttrNameLoc
, nullptr, AttrNameLoc
, nullptr, 0, Kind
);
1571 void Parser::ParseNullabilityClassAttributes(ParsedAttributes
&attrs
) {
1572 while (Tok
.is(tok::kw__Nullable
)) {
1573 IdentifierInfo
*AttrName
= Tok
.getIdentifierInfo();
1574 auto Kind
= Tok
.getKind();
1575 SourceLocation AttrNameLoc
= ConsumeToken();
1576 attrs
.addNew(AttrName
, AttrNameLoc
, nullptr, AttrNameLoc
, nullptr, 0, Kind
);
1580 /// Determine whether the following tokens are valid after a type-specifier
1581 /// which could be a standalone declaration. This will conservatively return
1582 /// true if there's any doubt, and is appropriate for insert-';' fixits.
1583 bool Parser::isValidAfterTypeSpecifier(bool CouldBeBitfield
) {
1584 // This switch enumerates the valid "follow" set for type-specifiers.
1585 switch (Tok
.getKind()) {
1587 if (Tok
.isRegularKeywordAttribute())
1590 case tok::semi
: // struct foo {...} ;
1591 case tok::star
: // struct foo {...} * P;
1592 case tok::amp
: // struct foo {...} & R = ...
1593 case tok::ampamp
: // struct foo {...} && R = ...
1594 case tok::identifier
: // struct foo {...} V ;
1595 case tok::r_paren
: //(struct foo {...} ) {4}
1596 case tok::coloncolon
: // struct foo {...} :: a::b;
1597 case tok::annot_cxxscope
: // struct foo {...} a:: b;
1598 case tok::annot_typename
: // struct foo {...} a ::b;
1599 case tok::annot_template_id
: // struct foo {...} a<int> ::b;
1600 case tok::kw_decltype
: // struct foo {...} decltype (a)::b;
1601 case tok::l_paren
: // struct foo {...} ( x);
1602 case tok::comma
: // __builtin_offsetof(struct foo{...} ,
1603 case tok::kw_operator
: // struct foo operator ++() {...}
1604 case tok::kw___declspec
: // struct foo {...} __declspec(...)
1605 case tok::l_square
: // void f(struct f [ 3])
1606 case tok::ellipsis
: // void f(struct f ... [Ns])
1607 // FIXME: we should emit semantic diagnostic when declaration
1608 // attribute is in type attribute position.
1609 case tok::kw___attribute
: // struct foo __attribute__((used)) x;
1610 case tok::annot_pragma_pack
: // struct foo {...} _Pragma(pack(pop));
1611 // struct foo {...} _Pragma(section(...));
1612 case tok::annot_pragma_ms_pragma
:
1613 // struct foo {...} _Pragma(vtordisp(pop));
1614 case tok::annot_pragma_ms_vtordisp
:
1615 // struct foo {...} _Pragma(pointers_to_members(...));
1616 case tok::annot_pragma_ms_pointers_to_members
:
1619 return CouldBeBitfield
|| // enum E { ... } : 2;
1620 ColonIsSacred
; // _Generic(..., enum E : 2);
1621 // Microsoft compatibility
1622 case tok::kw___cdecl
: // struct foo {...} __cdecl x;
1623 case tok::kw___fastcall
: // struct foo {...} __fastcall x;
1624 case tok::kw___stdcall
: // struct foo {...} __stdcall x;
1625 case tok::kw___thiscall
: // struct foo {...} __thiscall x;
1626 case tok::kw___vectorcall
: // struct foo {...} __vectorcall x;
1627 // We will diagnose these calling-convention specifiers on non-function
1628 // declarations later, so claim they are valid after a type specifier.
1629 return getLangOpts().MicrosoftExt
;
1631 case tok::kw_const
: // struct foo {...} const x;
1632 case tok::kw_volatile
: // struct foo {...} volatile x;
1633 case tok::kw_restrict
: // struct foo {...} restrict x;
1634 case tok::kw__Atomic
: // struct foo {...} _Atomic x;
1635 case tok::kw___unaligned
: // struct foo {...} __unaligned *x;
1636 // Function specifiers
1637 // Note, no 'explicit'. An explicit function must be either a conversion
1638 // operator or a constructor. Either way, it can't have a return type.
1639 case tok::kw_inline
: // struct foo inline f();
1640 case tok::kw_virtual
: // struct foo virtual f();
1641 case tok::kw_friend
: // struct foo friend f();
1642 // Storage-class specifiers
1643 case tok::kw_static
: // struct foo {...} static x;
1644 case tok::kw_extern
: // struct foo {...} extern x;
1645 case tok::kw_typedef
: // struct foo {...} typedef x;
1646 case tok::kw_register
: // struct foo {...} register x;
1647 case tok::kw_auto
: // struct foo {...} auto x;
1648 case tok::kw_mutable
: // struct foo {...} mutable x;
1649 case tok::kw_thread_local
: // struct foo {...} thread_local x;
1650 case tok::kw_constexpr
: // struct foo {...} constexpr x;
1651 case tok::kw_consteval
: // struct foo {...} consteval x;
1652 case tok::kw_constinit
: // struct foo {...} constinit x;
1653 // As shown above, type qualifiers and storage class specifiers absolutely
1654 // can occur after class specifiers according to the grammar. However,
1655 // almost no one actually writes code like this. If we see one of these,
1656 // it is much more likely that someone missed a semi colon and the
1657 // type/storage class specifier we're seeing is part of the *next*
1658 // intended declaration, as in:
1660 // struct foo { ... }
1663 // We'd really like to emit a missing semicolon error instead of emitting
1664 // an error on the 'int' saying that you can't have two type specifiers in
1665 // the same declaration of X. Because of this, we look ahead past this
1666 // token to see if it's a type specifier. If so, we know the code is
1667 // otherwise invalid, so we can produce the expected semi error.
1668 if (!isKnownToBeTypeSpecifier(NextToken()))
1671 case tok::r_brace
: // struct bar { struct foo {...} }
1672 // Missing ';' at end of struct is accepted as an extension in C mode.
1673 if (!getLangOpts().CPlusPlus
)
1677 // template<class T = class X>
1678 return getLangOpts().CPlusPlus
;
1683 /// ParseClassSpecifier - Parse a C++ class-specifier [C++ class] or
1684 /// elaborated-type-specifier [C++ dcl.type.elab]; we can't tell which
1685 /// until we reach the start of a definition or see a token that
1686 /// cannot start a definition.
1688 /// class-specifier: [C++ class]
1689 /// class-head '{' member-specification[opt] '}'
1690 /// class-head '{' member-specification[opt] '}' attributes[opt]
1692 /// class-key identifier[opt] base-clause[opt]
1693 /// class-key nested-name-specifier identifier base-clause[opt]
1694 /// class-key nested-name-specifier[opt] simple-template-id
1695 /// base-clause[opt]
1696 /// [GNU] class-key attributes[opt] identifier[opt] base-clause[opt]
1697 /// [GNU] class-key attributes[opt] nested-name-specifier
1698 /// identifier base-clause[opt]
1699 /// [GNU] class-key attributes[opt] nested-name-specifier[opt]
1700 /// simple-template-id base-clause[opt]
1706 /// elaborated-type-specifier: [C++ dcl.type.elab]
1707 /// class-key ::[opt] nested-name-specifier[opt] identifier
1708 /// class-key ::[opt] nested-name-specifier[opt] 'template'[opt]
1709 /// simple-template-id
1711 /// Note that the C++ class-specifier and elaborated-type-specifier,
1712 /// together, subsume the C99 struct-or-union-specifier:
1714 /// struct-or-union-specifier: [C99 6.7.2.1]
1715 /// struct-or-union identifier[opt] '{' struct-contents '}'
1716 /// struct-or-union identifier
1717 /// [GNU] struct-or-union attributes[opt] identifier[opt] '{' struct-contents
1718 /// '}' attributes[opt]
1719 /// [GNU] struct-or-union attributes[opt] identifier
1720 /// struct-or-union:
1723 void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind
,
1724 SourceLocation StartLoc
, DeclSpec
&DS
,
1725 ParsedTemplateInfo
&TemplateInfo
,
1726 AccessSpecifier AS
, bool EnteringContext
,
1727 DeclSpecContext DSC
,
1728 ParsedAttributes
&Attributes
) {
1729 DeclSpec::TST TagType
;
1730 if (TagTokKind
== tok::kw_struct
)
1731 TagType
= DeclSpec::TST_struct
;
1732 else if (TagTokKind
== tok::kw___interface
)
1733 TagType
= DeclSpec::TST_interface
;
1734 else if (TagTokKind
== tok::kw_class
)
1735 TagType
= DeclSpec::TST_class
;
1737 assert(TagTokKind
== tok::kw_union
&& "Not a class specifier");
1738 TagType
= DeclSpec::TST_union
;
1741 if (Tok
.is(tok::code_completion
)) {
1742 // Code completion for a struct, class, or union name.
1744 Actions
.CodeCompletion().CodeCompleteTag(getCurScope(), TagType
);
1748 // C++20 [temp.class.spec] 13.7.5/10
1749 // The usual access checking rules do not apply to non-dependent names
1750 // used to specify template arguments of the simple-template-id of the
1751 // partial specialization.
1752 // C++20 [temp.spec] 13.9/6:
1753 // The usual access checking rules do not apply to names in a declaration
1754 // of an explicit instantiation or explicit specialization...
1755 const bool shouldDelayDiagsInTag
=
1756 (TemplateInfo
.Kind
!= ParsedTemplateInfo::NonTemplate
);
1757 SuppressAccessChecks
diagsFromTag(*this, shouldDelayDiagsInTag
);
1759 ParsedAttributes
attrs(AttrFactory
);
1760 // If attributes exist after tag, parse them.
1762 MaybeParseAttributes(PAKM_CXX11
| PAKM_Declspec
| PAKM_GNU
, attrs
);
1763 // Parse inheritance specifiers.
1764 if (Tok
.isOneOf(tok::kw___single_inheritance
,
1765 tok::kw___multiple_inheritance
,
1766 tok::kw___virtual_inheritance
)) {
1767 ParseMicrosoftInheritanceClassAttributes(attrs
);
1770 if (Tok
.is(tok::kw__Nullable
)) {
1771 ParseNullabilityClassAttributes(attrs
);
1777 // Source location used by FIXIT to insert misplaced
1779 SourceLocation AttrFixitLoc
= Tok
.getLocation();
1781 if (TagType
== DeclSpec::TST_struct
&& Tok
.isNot(tok::identifier
) &&
1782 !Tok
.isAnnotation() && Tok
.getIdentifierInfo() &&
1784 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) tok::kw___##Trait,
1785 #include "clang/Basic/TransformTypeTraits.def"
1786 tok::kw___is_abstract
,
1787 tok::kw___is_aggregate
,
1788 tok::kw___is_arithmetic
,
1790 tok::kw___is_assignable
,
1791 tok::kw___is_base_of
,
1792 tok::kw___is_bounded_array
,
1794 tok::kw___is_complete_type
,
1795 tok::kw___is_compound
,
1797 tok::kw___is_constructible
,
1798 tok::kw___is_convertible
,
1799 tok::kw___is_convertible_to
,
1800 tok::kw___is_destructible
,
1803 tok::kw___is_floating_point
,
1805 tok::kw___is_function
,
1806 tok::kw___is_fundamental
,
1807 tok::kw___is_integral
,
1808 tok::kw___is_interface_class
,
1809 tok::kw___is_literal
,
1810 tok::kw___is_lvalue_expr
,
1811 tok::kw___is_lvalue_reference
,
1812 tok::kw___is_member_function_pointer
,
1813 tok::kw___is_member_object_pointer
,
1814 tok::kw___is_member_pointer
,
1815 tok::kw___is_nothrow_assignable
,
1816 tok::kw___is_nothrow_constructible
,
1817 tok::kw___is_nothrow_convertible
,
1818 tok::kw___is_nothrow_destructible
,
1819 tok::kw___is_object
,
1821 tok::kw___is_pointer
,
1822 tok::kw___is_polymorphic
,
1823 tok::kw___is_reference
,
1824 tok::kw___is_referenceable
,
1825 tok::kw___is_rvalue_expr
,
1826 tok::kw___is_rvalue_reference
,
1828 tok::kw___is_scalar
,
1829 tok::kw___is_scoped_enum
,
1830 tok::kw___is_sealed
,
1831 tok::kw___is_signed
,
1832 tok::kw___is_standard_layout
,
1833 tok::kw___is_trivial
,
1834 tok::kw___is_trivially_equality_comparable
,
1835 tok::kw___is_trivially_assignable
,
1836 tok::kw___is_trivially_constructible
,
1837 tok::kw___is_trivially_copyable
,
1838 tok::kw___is_unbounded_array
,
1840 tok::kw___is_unsigned
,
1842 tok::kw___is_volatile
1844 // GNU libstdc++ 4.2 and libc++ use certain intrinsic names as the
1845 // name of struct templates, but some are keywords in GCC >= 4.3
1846 // and Clang. Therefore, when we see the token sequence "struct
1847 // X", make X into a normal identifier rather than a keyword, to
1848 // allow libstdc++ 4.2 and libc++ to work properly.
1849 TryKeywordIdentFallback(true);
1851 struct PreserveAtomicIdentifierInfoRAII
{
1852 PreserveAtomicIdentifierInfoRAII(Token
&Tok
, bool Enabled
)
1853 : AtomicII(nullptr) {
1856 assert(Tok
.is(tok::kw__Atomic
));
1857 AtomicII
= Tok
.getIdentifierInfo();
1858 AtomicII
->revertTokenIDToIdentifier();
1859 Tok
.setKind(tok::identifier
);
1861 ~PreserveAtomicIdentifierInfoRAII() {
1864 AtomicII
->revertIdentifierToTokenID(tok::kw__Atomic
);
1866 IdentifierInfo
*AtomicII
;
1869 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
1870 // implementation for VS2013 uses _Atomic as an identifier for one of the
1871 // classes in <atomic>. When we are parsing 'struct _Atomic', don't consider
1872 // '_Atomic' to be a keyword. We are careful to undo this so that clang can
1873 // use '_Atomic' in its own header files.
1874 bool ShouldChangeAtomicToIdentifier
= getLangOpts().MSVCCompat
&&
1875 Tok
.is(tok::kw__Atomic
) &&
1876 TagType
== DeclSpec::TST_struct
;
1877 PreserveAtomicIdentifierInfoRAII
AtomicTokenGuard(
1878 Tok
, ShouldChangeAtomicToIdentifier
);
1880 // Parse the (optional) nested-name-specifier.
1881 CXXScopeSpec
&SS
= DS
.getTypeSpecScope();
1882 if (getLangOpts().CPlusPlus
) {
1883 // "FOO : BAR" is not a potential typo for "FOO::BAR". In this context it
1884 // is a base-specifier-list.
1885 ColonProtectionRAIIObject
X(*this);
1888 if (TemplateInfo
.TemplateParams
)
1889 Spec
.setTemplateParamLists(*TemplateInfo
.TemplateParams
);
1891 bool HasValidSpec
= true;
1892 if (ParseOptionalCXXScopeSpecifier(Spec
, /*ObjectType=*/nullptr,
1893 /*ObjectHasErrors=*/false,
1895 DS
.SetTypeSpecError();
1896 HasValidSpec
= false;
1899 if (Tok
.isNot(tok::identifier
) && Tok
.isNot(tok::annot_template_id
)) {
1900 Diag(Tok
, diag::err_expected
) << tok::identifier
;
1901 HasValidSpec
= false;
1907 TemplateParameterLists
*TemplateParams
= TemplateInfo
.TemplateParams
;
1909 auto RecoverFromUndeclaredTemplateName
= [&](IdentifierInfo
*Name
,
1910 SourceLocation NameLoc
,
1911 SourceRange TemplateArgRange
,
1912 bool KnownUndeclared
) {
1913 Diag(NameLoc
, diag::err_explicit_spec_non_template
)
1914 << (TemplateInfo
.Kind
== ParsedTemplateInfo::ExplicitInstantiation
)
1915 << TagTokKind
<< Name
<< TemplateArgRange
<< KnownUndeclared
;
1917 // Strip off the last template parameter list if it was empty, since
1918 // we've removed its template argument list.
1919 if (TemplateParams
&& TemplateInfo
.LastParameterListWasEmpty
) {
1920 if (TemplateParams
->size() > 1) {
1921 TemplateParams
->pop_back();
1923 TemplateParams
= nullptr;
1924 TemplateInfo
.Kind
= ParsedTemplateInfo::NonTemplate
;
1926 } else if (TemplateInfo
.Kind
== ParsedTemplateInfo::ExplicitInstantiation
) {
1927 // Pretend this is just a forward declaration.
1928 TemplateParams
= nullptr;
1929 TemplateInfo
.Kind
= ParsedTemplateInfo::NonTemplate
;
1930 TemplateInfo
.TemplateLoc
= SourceLocation();
1931 TemplateInfo
.ExternLoc
= SourceLocation();
1935 // Parse the (optional) class name or simple-template-id.
1936 IdentifierInfo
*Name
= nullptr;
1937 SourceLocation NameLoc
;
1938 TemplateIdAnnotation
*TemplateId
= nullptr;
1939 if (Tok
.is(tok::identifier
)) {
1940 Name
= Tok
.getIdentifierInfo();
1941 NameLoc
= ConsumeToken();
1942 DS
.SetRangeEnd(NameLoc
);
1944 if (Tok
.is(tok::less
) && getLangOpts().CPlusPlus
) {
1945 // The name was supposed to refer to a template, but didn't.
1946 // Eat the template argument list and try to continue parsing this as
1947 // a class (or template thereof).
1948 TemplateArgList TemplateArgs
;
1949 SourceLocation LAngleLoc
, RAngleLoc
;
1950 if (ParseTemplateIdAfterTemplateName(true, LAngleLoc
, TemplateArgs
,
1952 // We couldn't parse the template argument list at all, so don't
1953 // try to give any location information for the list.
1954 LAngleLoc
= RAngleLoc
= SourceLocation();
1956 RecoverFromUndeclaredTemplateName(
1957 Name
, NameLoc
, SourceRange(LAngleLoc
, RAngleLoc
), false);
1959 } else if (Tok
.is(tok::annot_template_id
)) {
1960 TemplateId
= takeTemplateIdAnnotation(Tok
);
1961 NameLoc
= ConsumeAnnotationToken();
1963 if (TemplateId
->Kind
== TNK_Undeclared_template
) {
1964 // Try to resolve the template name to a type template. May update Kind.
1965 Actions
.ActOnUndeclaredTypeTemplateName(
1966 getCurScope(), TemplateId
->Template
, TemplateId
->Kind
, NameLoc
, Name
);
1967 if (TemplateId
->Kind
== TNK_Undeclared_template
) {
1968 RecoverFromUndeclaredTemplateName(
1970 SourceRange(TemplateId
->LAngleLoc
, TemplateId
->RAngleLoc
), true);
1971 TemplateId
= nullptr;
1975 if (TemplateId
&& !TemplateId
->mightBeType()) {
1976 // The template-name in the simple-template-id refers to
1977 // something other than a type template. Give an appropriate
1978 // error message and skip to the ';'.
1979 SourceRange
Range(NameLoc
);
1980 if (SS
.isNotEmpty())
1981 Range
.setBegin(SS
.getBeginLoc());
1983 // FIXME: Name may be null here.
1984 Diag(TemplateId
->LAngleLoc
, diag::err_template_spec_syntax_non_template
)
1985 << TemplateId
->Name
<< static_cast<int>(TemplateId
->Kind
) << Range
;
1987 DS
.SetTypeSpecError();
1988 SkipUntil(tok::semi
, StopBeforeMatch
);
1993 // There are four options here.
1994 // - If we are in a trailing return type, this is always just a reference,
1995 // and we must not try to parse a definition. For instance,
1996 // [] () -> struct S { };
1997 // does not define a type.
1998 // - If we have 'struct foo {...', 'struct foo :...',
1999 // 'struct foo final :' or 'struct foo final {', then this is a definition.
2000 // - If we have 'struct foo;', then this is either a forward declaration
2001 // or a friend declaration, which have to be treated differently.
2002 // - Otherwise we have something like 'struct foo xyz', a reference.
2004 // We also detect these erroneous cases to provide better diagnostic for
2005 // C++11 attributes parsing.
2006 // - attributes follow class name:
2007 // struct foo [[]] {};
2008 // - attributes appear before or after 'final':
2009 // struct foo [[]] final [[]] {};
2011 // However, in type-specifier-seq's, things look like declarations but are
2012 // just references, e.g.
2015 // &T::operator struct s;
2016 // For these, DSC is DeclSpecContext::DSC_type_specifier or
2017 // DeclSpecContext::DSC_alias_declaration.
2019 // If there are attributes after class name, parse them.
2020 MaybeParseCXX11Attributes(Attributes
);
2022 const PrintingPolicy
&Policy
= Actions
.getASTContext().getPrintingPolicy();
2025 // C++26 [class.mem.general]p10: If a name-declaration matches the
2026 // syntactic requirements of friend-type-declaration, it is a
2027 // friend-type-declaration.
2028 if (getLangOpts().CPlusPlus
&& DS
.isFriendSpecifiedFirst() &&
2029 Tok
.isOneOf(tok::comma
, tok::ellipsis
))
2030 TUK
= TagUseKind::Friend
;
2031 else if (isDefiningTypeSpecifierContext(DSC
, getLangOpts().CPlusPlus
) ==
2032 AllowDefiningTypeSpec::No
||
2033 (getLangOpts().OpenMP
&& OpenMPDirectiveParsing
))
2034 TUK
= TagUseKind::Reference
;
2035 else if (Tok
.is(tok::l_brace
) ||
2036 (DSC
!= DeclSpecContext::DSC_association
&&
2037 getLangOpts().CPlusPlus
&& Tok
.is(tok::colon
)) ||
2038 (isClassCompatibleKeyword() &&
2039 (NextToken().is(tok::l_brace
) || NextToken().is(tok::colon
)))) {
2040 if (DS
.isFriendSpecified()) {
2041 // C++ [class.friend]p2:
2042 // A class shall not be defined in a friend declaration.
2043 Diag(Tok
.getLocation(), diag::err_friend_decl_defines_type
)
2044 << SourceRange(DS
.getFriendSpecLoc());
2046 // Skip everything up to the semicolon, so that this looks like a proper
2047 // friend class (or template thereof) declaration.
2048 SkipUntil(tok::semi
, StopBeforeMatch
);
2049 TUK
= TagUseKind::Friend
;
2051 // Okay, this is a class definition.
2052 TUK
= TagUseKind::Definition
;
2054 } else if (isClassCompatibleKeyword() &&
2055 (NextToken().is(tok::l_square
) ||
2056 NextToken().is(tok::kw_alignas
) ||
2057 NextToken().isRegularKeywordAttribute() ||
2058 isCXX11VirtSpecifier(NextToken()) != VirtSpecifiers::VS_None
)) {
2059 // We can't tell if this is a definition or reference
2060 // until we skipped the 'final' and C++11 attribute specifiers.
2061 TentativeParsingAction
PA(*this);
2063 // Skip the 'final', abstract'... keywords.
2064 while (isClassCompatibleKeyword()) {
2068 // Skip C++11 attribute specifiers.
2070 if (Tok
.is(tok::l_square
) && NextToken().is(tok::l_square
)) {
2072 if (!SkipUntil(tok::r_square
, StopAtSemi
))
2074 } else if (Tok
.is(tok::kw_alignas
) && NextToken().is(tok::l_paren
)) {
2077 if (!SkipUntil(tok::r_paren
, StopAtSemi
))
2079 } else if (Tok
.isRegularKeywordAttribute()) {
2080 bool TakesArgs
= doesKeywordAttributeTakeArgs(Tok
.getKind());
2083 BalancedDelimiterTracker
T(*this, tok::l_paren
);
2084 if (!T
.consumeOpen())
2092 if (Tok
.isOneOf(tok::l_brace
, tok::colon
))
2093 TUK
= TagUseKind::Definition
;
2095 TUK
= TagUseKind::Reference
;
2098 } else if (!isTypeSpecifier(DSC
) &&
2099 (Tok
.is(tok::semi
) ||
2100 (Tok
.isAtStartOfLine() && !isValidAfterTypeSpecifier(false)))) {
2101 TUK
= DS
.isFriendSpecified() ? TagUseKind::Friend
: TagUseKind::Declaration
;
2102 if (Tok
.isNot(tok::semi
)) {
2103 const PrintingPolicy
&PPol
= Actions
.getASTContext().getPrintingPolicy();
2104 // A semicolon was missing after this declaration. Diagnose and recover.
2105 ExpectAndConsume(tok::semi
, diag::err_expected_after
,
2106 DeclSpec::getSpecifierName(TagType
, PPol
));
2107 PP
.EnterToken(Tok
, /*IsReinject*/ true);
2108 Tok
.setKind(tok::semi
);
2111 TUK
= TagUseKind::Reference
;
2113 // Forbid misplaced attributes. In cases of a reference, we pass attributes
2114 // to caller to handle.
2115 if (TUK
!= TagUseKind::Reference
) {
2116 // If this is not a reference, then the only possible
2117 // valid place for C++11 attributes to appear here
2118 // is between class-key and class-name. If there are
2119 // any attributes after class-name, we try a fixit to move
2120 // them to the right place.
2121 SourceRange AttrRange
= Attributes
.Range
;
2122 if (AttrRange
.isValid()) {
2123 auto *FirstAttr
= Attributes
.empty() ? nullptr : &Attributes
.front();
2124 auto Loc
= AttrRange
.getBegin();
2125 (FirstAttr
&& FirstAttr
->isRegularKeywordAttribute()
2126 ? Diag(Loc
, diag::err_keyword_not_allowed
) << FirstAttr
2127 : Diag(Loc
, diag::err_attributes_not_allowed
))
2129 << FixItHint::CreateInsertionFromRange(
2130 AttrFixitLoc
, CharSourceRange(AttrRange
, true))
2131 << FixItHint::CreateRemoval(AttrRange
);
2133 // Recover by adding misplaced attributes to the attribute list
2134 // of the class so they can be applied on the class later.
2135 attrs
.takeAllFrom(Attributes
);
2139 if (!Name
&& !TemplateId
&&
2140 (DS
.getTypeSpecType() == DeclSpec::TST_error
||
2141 TUK
!= TagUseKind::Definition
)) {
2142 if (DS
.getTypeSpecType() != DeclSpec::TST_error
) {
2143 // We have a declaration or reference to an anonymous class.
2144 Diag(StartLoc
, diag::err_anon_type_definition
)
2145 << DeclSpec::getSpecifierName(TagType
, Policy
);
2148 // If we are parsing a definition and stop at a base-clause, continue on
2149 // until the semicolon. Continuing from the comma will just trick us into
2150 // thinking we are seeing a variable declaration.
2151 if (TUK
== TagUseKind::Definition
&& Tok
.is(tok::colon
))
2152 SkipUntil(tok::semi
, StopBeforeMatch
);
2154 SkipUntil(tok::comma
, StopAtSemi
);
2158 // Create the tag portion of the class or class template.
2159 DeclResult TagOrTempResult
= true; // invalid
2160 TypeResult TypeResult
= true; // invalid
2163 SkipBodyInfo SkipBody
;
2165 // Explicit specialization, class template partial specialization,
2166 // or explicit instantiation.
2167 ASTTemplateArgsPtr
TemplateArgsPtr(TemplateId
->getTemplateArgs(),
2168 TemplateId
->NumArgs
);
2169 if (TemplateId
->isInvalid()) {
2170 // Can't build the declaration.
2171 } else if (TemplateInfo
.Kind
== ParsedTemplateInfo::ExplicitInstantiation
&&
2172 TUK
== TagUseKind::Declaration
) {
2173 // This is an explicit instantiation of a class template.
2174 ProhibitCXX11Attributes(attrs
, diag::err_attributes_not_allowed
,
2175 diag::err_keyword_not_allowed
,
2176 /*DiagnoseEmptyAttrs=*/true);
2178 TagOrTempResult
= Actions
.ActOnExplicitInstantiation(
2179 getCurScope(), TemplateInfo
.ExternLoc
, TemplateInfo
.TemplateLoc
,
2180 TagType
, StartLoc
, SS
, TemplateId
->Template
,
2181 TemplateId
->TemplateNameLoc
, TemplateId
->LAngleLoc
, TemplateArgsPtr
,
2182 TemplateId
->RAngleLoc
, attrs
);
2184 // Friend template-ids are treated as references unless
2185 // they have template headers, in which case they're ill-formed
2186 // (FIXME: "template <class T> friend class A<T>::B<int>;").
2187 // We diagnose this error in ActOnClassTemplateSpecialization.
2188 } else if (TUK
== TagUseKind::Reference
||
2189 (TUK
== TagUseKind::Friend
&&
2190 TemplateInfo
.Kind
== ParsedTemplateInfo::NonTemplate
)) {
2191 ProhibitCXX11Attributes(attrs
, diag::err_attributes_not_allowed
,
2192 diag::err_keyword_not_allowed
,
2193 /*DiagnoseEmptyAttrs=*/true);
2194 TypeResult
= Actions
.ActOnTagTemplateIdType(
2195 TUK
, TagType
, StartLoc
, SS
, TemplateId
->TemplateKWLoc
,
2196 TemplateId
->Template
, TemplateId
->TemplateNameLoc
,
2197 TemplateId
->LAngleLoc
, TemplateArgsPtr
, TemplateId
->RAngleLoc
);
2199 // This is an explicit specialization or a class template
2200 // partial specialization.
2201 TemplateParameterLists FakedParamLists
;
2202 if (TemplateInfo
.Kind
== ParsedTemplateInfo::ExplicitInstantiation
) {
2203 // This looks like an explicit instantiation, because we have
2206 // template class Foo<X>
2208 // but it actually has a definition. Most likely, this was
2209 // meant to be an explicit specialization, but the user forgot
2210 // the '<>' after 'template'.
2211 // It this is friend declaration however, since it cannot have a
2212 // template header, it is most likely that the user meant to
2213 // remove the 'template' keyword.
2214 assert((TUK
== TagUseKind::Definition
|| TUK
== TagUseKind::Friend
) &&
2215 "Expected a definition here");
2217 if (TUK
== TagUseKind::Friend
) {
2218 Diag(DS
.getFriendSpecLoc(), diag::err_friend_explicit_instantiation
);
2219 TemplateParams
= nullptr;
2221 SourceLocation LAngleLoc
=
2222 PP
.getLocForEndOfToken(TemplateInfo
.TemplateLoc
);
2223 Diag(TemplateId
->TemplateNameLoc
,
2224 diag::err_explicit_instantiation_with_definition
)
2225 << SourceRange(TemplateInfo
.TemplateLoc
)
2226 << FixItHint::CreateInsertion(LAngleLoc
, "<>");
2228 // Create a fake template parameter list that contains only
2229 // "template<>", so that we treat this construct as a class
2230 // template specialization.
2231 FakedParamLists
.push_back(Actions
.ActOnTemplateParameterList(
2232 0, SourceLocation(), TemplateInfo
.TemplateLoc
, LAngleLoc
, {},
2233 LAngleLoc
, nullptr));
2234 TemplateParams
= &FakedParamLists
;
2238 // Build the class template specialization.
2239 TagOrTempResult
= Actions
.ActOnClassTemplateSpecialization(
2240 getCurScope(), TagType
, TUK
, StartLoc
, DS
.getModulePrivateSpecLoc(),
2241 SS
, *TemplateId
, attrs
,
2242 MultiTemplateParamsArg(TemplateParams
? &(*TemplateParams
)[0]
2244 TemplateParams
? TemplateParams
->size() : 0),
2247 } else if (TemplateInfo
.Kind
== ParsedTemplateInfo::ExplicitInstantiation
&&
2248 TUK
== TagUseKind::Declaration
) {
2249 // Explicit instantiation of a member of a class template
2250 // specialization, e.g.,
2252 // template struct Outer<int>::Inner;
2254 ProhibitAttributes(attrs
);
2256 TagOrTempResult
= Actions
.ActOnExplicitInstantiation(
2257 getCurScope(), TemplateInfo
.ExternLoc
, TemplateInfo
.TemplateLoc
,
2258 TagType
, StartLoc
, SS
, Name
, NameLoc
, attrs
);
2259 } else if (TUK
== TagUseKind::Friend
&&
2260 TemplateInfo
.Kind
!= ParsedTemplateInfo::NonTemplate
) {
2261 ProhibitCXX11Attributes(attrs
, diag::err_attributes_not_allowed
,
2262 diag::err_keyword_not_allowed
,
2263 /*DiagnoseEmptyAttrs=*/true);
2265 // Consume '...' first so we error on the ',' after it if there is one.
2266 SourceLocation EllipsisLoc
;
2267 TryConsumeToken(tok::ellipsis
, EllipsisLoc
);
2269 // CWG 2917: In a template-declaration whose declaration is a
2270 // friend-type-declaration, the friend-type-specifier-list shall
2271 // consist of exactly one friend-type-specifier.
2273 // Essentially, the following is obviously nonsense, so disallow it:
2275 // template <typename>
2276 // friend class S, int;
2278 if (Tok
.is(tok::comma
)) {
2279 Diag(Tok
.getLocation(),
2280 diag::err_friend_template_decl_multiple_specifiers
);
2281 SkipUntil(tok::semi
, StopBeforeMatch
);
2284 TagOrTempResult
= Actions
.ActOnTemplatedFriendTag(
2285 getCurScope(), DS
.getFriendSpecLoc(), TagType
, StartLoc
, SS
, Name
,
2286 NameLoc
, EllipsisLoc
, attrs
,
2287 MultiTemplateParamsArg(TemplateParams
? &(*TemplateParams
)[0] : nullptr,
2288 TemplateParams
? TemplateParams
->size() : 0));
2290 if (TUK
!= TagUseKind::Declaration
&& TUK
!= TagUseKind::Definition
)
2291 ProhibitCXX11Attributes(attrs
, diag::err_attributes_not_allowed
,
2292 diag::err_keyword_not_allowed
,
2293 /* DiagnoseEmptyAttrs=*/true);
2295 if (TUK
== TagUseKind::Definition
&&
2296 TemplateInfo
.Kind
== ParsedTemplateInfo::ExplicitInstantiation
) {
2297 // If the declarator-id is not a template-id, issue a diagnostic and
2298 // recover by ignoring the 'template' keyword.
2299 Diag(Tok
, diag::err_template_defn_explicit_instantiation
)
2300 << 1 << FixItHint::CreateRemoval(TemplateInfo
.TemplateLoc
);
2301 TemplateParams
= nullptr;
2304 bool IsDependent
= false;
2306 // Don't pass down template parameter lists if this is just a tag
2307 // reference. For example, we don't need the template parameters here:
2308 // template <class T> class A *makeA(T t);
2309 MultiTemplateParamsArg TParams
;
2310 if (TUK
!= TagUseKind::Reference
&& TemplateParams
)
2312 MultiTemplateParamsArg(&(*TemplateParams
)[0], TemplateParams
->size());
2314 stripTypeAttributesOffDeclSpec(attrs
, DS
, TUK
);
2316 // Declaration or definition of a class type
2317 TagOrTempResult
= Actions
.ActOnTag(
2318 getCurScope(), TagType
, TUK
, StartLoc
, SS
, Name
, NameLoc
, attrs
, AS
,
2319 DS
.getModulePrivateSpecLoc(), TParams
, Owned
, IsDependent
,
2320 SourceLocation(), false, clang::TypeResult(),
2321 DSC
== DeclSpecContext::DSC_type_specifier
,
2322 DSC
== DeclSpecContext::DSC_template_param
||
2323 DSC
== DeclSpecContext::DSC_template_type_arg
,
2324 OffsetOfState
, &SkipBody
);
2326 // If ActOnTag said the type was dependent, try again with the
2327 // less common call.
2329 assert(TUK
== TagUseKind::Reference
|| TUK
== TagUseKind::Friend
);
2330 TypeResult
= Actions
.ActOnDependentTag(getCurScope(), TagType
, TUK
, SS
,
2331 Name
, StartLoc
, NameLoc
);
2335 // If this is an elaborated type specifier in function template,
2336 // and we delayed diagnostics before,
2337 // just merge them into the current pool.
2338 if (shouldDelayDiagsInTag
) {
2339 diagsFromTag
.done();
2340 if (TUK
== TagUseKind::Reference
&&
2341 TemplateInfo
.Kind
== ParsedTemplateInfo::Template
)
2342 diagsFromTag
.redelay();
2345 // If there is a body, parse it and inform the actions module.
2346 if (TUK
== TagUseKind::Definition
) {
2347 assert(Tok
.is(tok::l_brace
) ||
2348 (getLangOpts().CPlusPlus
&& Tok
.is(tok::colon
)) ||
2349 isClassCompatibleKeyword());
2350 if (SkipBody
.ShouldSkip
)
2351 SkipCXXMemberSpecification(StartLoc
, AttrFixitLoc
, TagType
,
2352 TagOrTempResult
.get());
2353 else if (getLangOpts().CPlusPlus
)
2354 ParseCXXMemberSpecification(StartLoc
, AttrFixitLoc
, attrs
, TagType
,
2355 TagOrTempResult
.get());
2358 SkipBody
.CheckSameAsPrevious
? SkipBody
.New
: TagOrTempResult
.get();
2359 // Parse the definition body.
2360 ParseStructUnionBody(StartLoc
, TagType
, cast
<RecordDecl
>(D
));
2361 if (SkipBody
.CheckSameAsPrevious
&&
2362 !Actions
.ActOnDuplicateDefinition(TagOrTempResult
.get(), SkipBody
)) {
2363 DS
.SetTypeSpecError();
2369 if (!TagOrTempResult
.isInvalid())
2370 // Delayed processing of attributes.
2371 Actions
.ProcessDeclAttributeDelayed(TagOrTempResult
.get(), attrs
);
2373 const char *PrevSpec
= nullptr;
2376 if (!TypeResult
.isInvalid()) {
2377 Result
= DS
.SetTypeSpecType(DeclSpec::TST_typename
, StartLoc
,
2378 NameLoc
.isValid() ? NameLoc
: StartLoc
,
2379 PrevSpec
, DiagID
, TypeResult
.get(), Policy
);
2380 } else if (!TagOrTempResult
.isInvalid()) {
2381 Result
= DS
.SetTypeSpecType(
2382 TagType
, StartLoc
, NameLoc
.isValid() ? NameLoc
: StartLoc
, PrevSpec
,
2383 DiagID
, TagOrTempResult
.get(), Owned
, Policy
);
2385 DS
.SetTypeSpecError();
2390 Diag(StartLoc
, DiagID
) << PrevSpec
;
2392 // At this point, we've successfully parsed a class-specifier in 'definition'
2393 // form (e.g. "struct foo { int x; }". While we could just return here, we're
2394 // going to look at what comes after it to improve error recovery. If an
2395 // impossible token occurs next, we assume that the programmer forgot a ; at
2396 // the end of the declaration and recover that way.
2398 // Also enforce C++ [temp]p3:
2399 // In a template-declaration which defines a class, no declarator
2402 // After a type-specifier, we don't expect a semicolon. This only happens in
2403 // C, since definitions are not permitted in this context in C++.
2404 if (TUK
== TagUseKind::Definition
&&
2405 (getLangOpts().CPlusPlus
|| !isTypeSpecifier(DSC
)) &&
2406 (TemplateInfo
.Kind
|| !isValidAfterTypeSpecifier(false))) {
2407 if (Tok
.isNot(tok::semi
)) {
2408 const PrintingPolicy
&PPol
= Actions
.getASTContext().getPrintingPolicy();
2409 ExpectAndConsume(tok::semi
, diag::err_expected_after
,
2410 DeclSpec::getSpecifierName(TagType
, PPol
));
2411 // Push this token back into the preprocessor and change our current token
2412 // to ';' so that the rest of the code recovers as though there were an
2413 // ';' after the definition.
2414 PP
.EnterToken(Tok
, /*IsReinject=*/true);
2415 Tok
.setKind(tok::semi
);
2420 /// ParseBaseClause - Parse the base-clause of a C++ class [C++ class.derived].
2422 /// base-clause : [C++ class.derived]
2423 /// ':' base-specifier-list
2424 /// base-specifier-list:
2425 /// base-specifier '...'[opt]
2426 /// base-specifier-list ',' base-specifier '...'[opt]
2427 void Parser::ParseBaseClause(Decl
*ClassDecl
) {
2428 assert(Tok
.is(tok::colon
) && "Not a base clause");
2431 // Build up an array of parsed base specifiers.
2432 SmallVector
<CXXBaseSpecifier
*, 8> BaseInfo
;
2435 // Parse a base-specifier.
2436 BaseResult Result
= ParseBaseSpecifier(ClassDecl
);
2437 if (Result
.isInvalid()) {
2438 // Skip the rest of this base specifier, up until the comma or
2440 SkipUntil(tok::comma
, tok::l_brace
, StopAtSemi
| StopBeforeMatch
);
2442 // Add this to our array of base specifiers.
2443 BaseInfo
.push_back(Result
.get());
2446 // If the next token is a comma, consume it and keep reading
2448 if (!TryConsumeToken(tok::comma
))
2452 // Attach the base specifiers
2453 Actions
.ActOnBaseSpecifiers(ClassDecl
, BaseInfo
);
2456 /// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is
2457 /// one entry in the base class list of a class specifier, for example:
2458 /// class foo : public bar, virtual private baz {
2459 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2461 /// base-specifier: [C++ class.derived]
2462 /// attribute-specifier-seq[opt] base-type-specifier
2463 /// attribute-specifier-seq[opt] 'virtual' access-specifier[opt]
2464 /// base-type-specifier
2465 /// attribute-specifier-seq[opt] access-specifier 'virtual'[opt]
2466 /// base-type-specifier
2467 BaseResult
Parser::ParseBaseSpecifier(Decl
*ClassDecl
) {
2468 bool IsVirtual
= false;
2469 SourceLocation StartLoc
= Tok
.getLocation();
2471 ParsedAttributes
Attributes(AttrFactory
);
2472 MaybeParseCXX11Attributes(Attributes
);
2474 // Parse the 'virtual' keyword.
2475 if (TryConsumeToken(tok::kw_virtual
))
2478 CheckMisplacedCXX11Attribute(Attributes
, StartLoc
);
2480 // Parse an (optional) access specifier.
2481 AccessSpecifier Access
= getAccessSpecifierIfPresent();
2482 if (Access
!= AS_none
) {
2484 if (getLangOpts().HLSL
)
2485 Diag(Tok
.getLocation(), diag::ext_hlsl_access_specifiers
);
2488 CheckMisplacedCXX11Attribute(Attributes
, StartLoc
);
2490 // Parse the 'virtual' keyword (again!), in case it came after the
2491 // access specifier.
2492 if (Tok
.is(tok::kw_virtual
)) {
2493 SourceLocation VirtualLoc
= ConsumeToken();
2495 // Complain about duplicate 'virtual'
2496 Diag(VirtualLoc
, diag::err_dup_virtual
)
2497 << FixItHint::CreateRemoval(VirtualLoc
);
2503 CheckMisplacedCXX11Attribute(Attributes
, StartLoc
);
2505 // Parse the class-name.
2507 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
2508 // implementation for VS2013 uses _Atomic as an identifier for one of the
2509 // classes in <atomic>. Treat '_Atomic' to be an identifier when we are
2510 // parsing the class-name for a base specifier.
2511 if (getLangOpts().MSVCCompat
&& Tok
.is(tok::kw__Atomic
) &&
2512 NextToken().is(tok::less
))
2513 Tok
.setKind(tok::identifier
);
2515 SourceLocation EndLocation
;
2516 SourceLocation BaseLoc
;
2517 TypeResult BaseType
= ParseBaseTypeSpecifier(BaseLoc
, EndLocation
);
2518 if (BaseType
.isInvalid())
2521 // Parse the optional ellipsis (for a pack expansion). The ellipsis is
2522 // actually part of the base-specifier-list grammar productions, but we
2523 // parse it here for convenience.
2524 SourceLocation EllipsisLoc
;
2525 TryConsumeToken(tok::ellipsis
, EllipsisLoc
);
2527 // Find the complete source range for the base-specifier.
2528 SourceRange
Range(StartLoc
, EndLocation
);
2530 // Notify semantic analysis that we have parsed a complete
2532 return Actions
.ActOnBaseSpecifier(ClassDecl
, Range
, Attributes
, IsVirtual
,
2533 Access
, BaseType
.get(), BaseLoc
,
2537 /// getAccessSpecifierIfPresent - Determine whether the next token is
2538 /// a C++ access-specifier.
2540 /// access-specifier: [C++ class.derived]
2544 AccessSpecifier
Parser::getAccessSpecifierIfPresent() const {
2545 switch (Tok
.getKind()) {
2548 case tok::kw_private
:
2550 case tok::kw_protected
:
2551 return AS_protected
;
2552 case tok::kw_public
:
2557 /// If the given declarator has any parts for which parsing has to be
2558 /// delayed, e.g., default arguments or an exception-specification, create a
2559 /// late-parsed method declaration record to handle the parsing at the end of
2560 /// the class definition.
2561 void Parser::HandleMemberFunctionDeclDelays(Declarator
&DeclaratorInfo
,
2563 DeclaratorChunk::FunctionTypeInfo
&FTI
= DeclaratorInfo
.getFunctionTypeInfo();
2564 // If there was a late-parsed exception-specification, we'll need a
2566 bool NeedLateParse
= FTI
.getExceptionSpecType() == EST_Unparsed
;
2568 if (!NeedLateParse
) {
2569 // Look ahead to see if there are any default args
2570 for (unsigned ParamIdx
= 0; ParamIdx
< FTI
.NumParams
; ++ParamIdx
) {
2571 const auto *Param
= cast
<ParmVarDecl
>(FTI
.Params
[ParamIdx
].Param
);
2572 if (Param
->hasUnparsedDefaultArg()) {
2573 NeedLateParse
= true;
2579 if (NeedLateParse
) {
2580 // Push this method onto the stack of late-parsed method
2582 auto LateMethod
= new LateParsedMethodDeclaration(this, ThisDecl
);
2583 getCurrentClass().LateParsedDeclarations
.push_back(LateMethod
);
2585 // Push tokens for each parameter. Those that do not have defaults will be
2586 // NULL. We need to track all the parameters so that we can push them into
2587 // scope for later parameters and perhaps for the exception specification.
2588 LateMethod
->DefaultArgs
.reserve(FTI
.NumParams
);
2589 for (unsigned ParamIdx
= 0; ParamIdx
< FTI
.NumParams
; ++ParamIdx
)
2590 LateMethod
->DefaultArgs
.push_back(LateParsedDefaultArgument(
2591 FTI
.Params
[ParamIdx
].Param
,
2592 std::move(FTI
.Params
[ParamIdx
].DefaultArgTokens
)));
2594 // Stash the exception-specification tokens in the late-pased method.
2595 if (FTI
.getExceptionSpecType() == EST_Unparsed
) {
2596 LateMethod
->ExceptionSpecTokens
= FTI
.ExceptionSpecTokens
;
2597 FTI
.ExceptionSpecTokens
= nullptr;
2602 /// isCXX11VirtSpecifier - Determine whether the given token is a C++11
2609 VirtSpecifiers::Specifier
Parser::isCXX11VirtSpecifier(const Token
&Tok
) const {
2610 if (!getLangOpts().CPlusPlus
|| Tok
.isNot(tok::identifier
))
2611 return VirtSpecifiers::VS_None
;
2613 const IdentifierInfo
*II
= Tok
.getIdentifierInfo();
2615 // Initialize the contextual keywords.
2617 Ident_final
= &PP
.getIdentifierTable().get("final");
2618 if (getLangOpts().GNUKeywords
)
2619 Ident_GNU_final
= &PP
.getIdentifierTable().get("__final");
2620 if (getLangOpts().MicrosoftExt
) {
2621 Ident_sealed
= &PP
.getIdentifierTable().get("sealed");
2622 Ident_abstract
= &PP
.getIdentifierTable().get("abstract");
2624 Ident_override
= &PP
.getIdentifierTable().get("override");
2627 if (II
== Ident_override
)
2628 return VirtSpecifiers::VS_Override
;
2630 if (II
== Ident_sealed
)
2631 return VirtSpecifiers::VS_Sealed
;
2633 if (II
== Ident_abstract
)
2634 return VirtSpecifiers::VS_Abstract
;
2636 if (II
== Ident_final
)
2637 return VirtSpecifiers::VS_Final
;
2639 if (II
== Ident_GNU_final
)
2640 return VirtSpecifiers::VS_GNU_Final
;
2642 return VirtSpecifiers::VS_None
;
2645 /// ParseOptionalCXX11VirtSpecifierSeq - Parse a virt-specifier-seq.
2647 /// virt-specifier-seq:
2649 /// virt-specifier-seq virt-specifier
2650 void Parser::ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers
&VS
,
2652 SourceLocation FriendLoc
) {
2654 VirtSpecifiers::Specifier Specifier
= isCXX11VirtSpecifier();
2655 if (Specifier
== VirtSpecifiers::VS_None
)
2658 if (FriendLoc
.isValid()) {
2659 Diag(Tok
.getLocation(), diag::err_friend_decl_spec
)
2660 << VirtSpecifiers::getSpecifierName(Specifier
)
2661 << FixItHint::CreateRemoval(Tok
.getLocation())
2662 << SourceRange(FriendLoc
, FriendLoc
);
2667 // C++ [class.mem]p8:
2668 // A virt-specifier-seq shall contain at most one of each virt-specifier.
2669 const char *PrevSpec
= nullptr;
2670 if (VS
.SetSpecifier(Specifier
, Tok
.getLocation(), PrevSpec
))
2671 Diag(Tok
.getLocation(), diag::err_duplicate_virt_specifier
)
2672 << PrevSpec
<< FixItHint::CreateRemoval(Tok
.getLocation());
2674 if (IsInterface
&& (Specifier
== VirtSpecifiers::VS_Final
||
2675 Specifier
== VirtSpecifiers::VS_Sealed
)) {
2676 Diag(Tok
.getLocation(), diag::err_override_control_interface
)
2677 << VirtSpecifiers::getSpecifierName(Specifier
);
2678 } else if (Specifier
== VirtSpecifiers::VS_Sealed
) {
2679 Diag(Tok
.getLocation(), diag::ext_ms_sealed_keyword
);
2680 } else if (Specifier
== VirtSpecifiers::VS_Abstract
) {
2681 Diag(Tok
.getLocation(), diag::ext_ms_abstract_keyword
);
2682 } else if (Specifier
== VirtSpecifiers::VS_GNU_Final
) {
2683 Diag(Tok
.getLocation(), diag::ext_warn_gnu_final
);
2685 Diag(Tok
.getLocation(),
2686 getLangOpts().CPlusPlus11
2687 ? diag::warn_cxx98_compat_override_control_keyword
2688 : diag::ext_override_control_keyword
)
2689 << VirtSpecifiers::getSpecifierName(Specifier
);
2695 /// isCXX11FinalKeyword - Determine whether the next token is a C++11
2696 /// 'final' or Microsoft 'sealed' contextual keyword.
2697 bool Parser::isCXX11FinalKeyword() const {
2698 VirtSpecifiers::Specifier Specifier
= isCXX11VirtSpecifier();
2699 return Specifier
== VirtSpecifiers::VS_Final
||
2700 Specifier
== VirtSpecifiers::VS_GNU_Final
||
2701 Specifier
== VirtSpecifiers::VS_Sealed
;
2704 /// isClassCompatibleKeyword - Determine whether the next token is a C++11
2705 /// 'final' or Microsoft 'sealed' or 'abstract' contextual keywords.
2706 bool Parser::isClassCompatibleKeyword() const {
2707 VirtSpecifiers::Specifier Specifier
= isCXX11VirtSpecifier();
2708 return Specifier
== VirtSpecifiers::VS_Final
||
2709 Specifier
== VirtSpecifiers::VS_GNU_Final
||
2710 Specifier
== VirtSpecifiers::VS_Sealed
||
2711 Specifier
== VirtSpecifiers::VS_Abstract
;
2714 /// Parse a C++ member-declarator up to, but not including, the optional
2715 /// brace-or-equal-initializer or pure-specifier.
2716 bool Parser::ParseCXXMemberDeclaratorBeforeInitializer(
2717 Declarator
&DeclaratorInfo
, VirtSpecifiers
&VS
, ExprResult
&BitfieldSize
,
2718 LateParsedAttrList
&LateParsedAttrs
) {
2719 // member-declarator:
2720 // declarator virt-specifier-seq[opt] pure-specifier[opt]
2721 // declarator requires-clause
2722 // declarator brace-or-equal-initializer[opt]
2723 // identifier attribute-specifier-seq[opt] ':' constant-expression
2724 // brace-or-equal-initializer[opt]
2725 // ':' constant-expression
2727 // NOTE: the latter two productions are a proposed bugfix rather than the
2728 // current grammar rules as of C++20.
2729 if (Tok
.isNot(tok::colon
))
2730 ParseDeclarator(DeclaratorInfo
);
2732 DeclaratorInfo
.SetIdentifier(nullptr, Tok
.getLocation());
2734 if (getLangOpts().HLSL
)
2735 MaybeParseHLSLAnnotations(DeclaratorInfo
, nullptr,
2736 /*CouldBeBitField*/ true);
2738 if (!DeclaratorInfo
.isFunctionDeclarator() && TryConsumeToken(tok::colon
)) {
2739 assert(DeclaratorInfo
.isPastIdentifier() &&
2740 "don't know where identifier would go yet?");
2741 BitfieldSize
= ParseConstantExpression();
2742 if (BitfieldSize
.isInvalid())
2743 SkipUntil(tok::comma
, StopAtSemi
| StopBeforeMatch
);
2744 } else if (Tok
.is(tok::kw_requires
)) {
2745 ParseTrailingRequiresClause(DeclaratorInfo
);
2747 ParseOptionalCXX11VirtSpecifierSeq(
2748 VS
, getCurrentClass().IsInterface
,
2749 DeclaratorInfo
.getDeclSpec().getFriendSpecLoc());
2751 MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo
,
2755 // If a simple-asm-expr is present, parse it.
2756 if (Tok
.is(tok::kw_asm
)) {
2758 ExprResult
AsmLabel(ParseSimpleAsm(/*ForAsmLabel*/ true, &Loc
));
2759 if (AsmLabel
.isInvalid())
2760 SkipUntil(tok::comma
, StopAtSemi
| StopBeforeMatch
);
2762 DeclaratorInfo
.setAsmLabel(AsmLabel
.get());
2763 DeclaratorInfo
.SetRangeEnd(Loc
);
2766 // If attributes exist after the declarator, but before an '{', parse them.
2767 // However, this does not apply for [[]] attributes (which could show up
2768 // before or after the __attribute__ attributes).
2769 DiagnoseAndSkipCXX11Attributes();
2770 MaybeParseGNUAttributes(DeclaratorInfo
, &LateParsedAttrs
);
2771 DiagnoseAndSkipCXX11Attributes();
2773 // For compatibility with code written to older Clang, also accept a
2774 // virt-specifier *after* the GNU attributes.
2775 if (BitfieldSize
.isUnset() && VS
.isUnset()) {
2776 ParseOptionalCXX11VirtSpecifierSeq(
2777 VS
, getCurrentClass().IsInterface
,
2778 DeclaratorInfo
.getDeclSpec().getFriendSpecLoc());
2779 if (!VS
.isUnset()) {
2780 // If we saw any GNU-style attributes that are known to GCC followed by a
2781 // virt-specifier, issue a GCC-compat warning.
2782 for (const ParsedAttr
&AL
: DeclaratorInfo
.getAttributes())
2783 if (AL
.isKnownToGCC() && !AL
.isCXX11Attribute())
2784 Diag(AL
.getLoc(), diag::warn_gcc_attribute_location
);
2786 MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo
,
2791 // If this has neither a name nor a bit width, something has gone seriously
2792 // wrong. Skip until the semi-colon or }.
2793 if (!DeclaratorInfo
.hasName() && BitfieldSize
.isUnset()) {
2794 // If so, skip until the semi-colon or a }.
2795 SkipUntil(tok::r_brace
, StopAtSemi
| StopBeforeMatch
);
2801 /// Look for declaration specifiers possibly occurring after C++11
2802 /// virt-specifier-seq and diagnose them.
2803 void Parser::MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(
2804 Declarator
&D
, VirtSpecifiers
&VS
) {
2805 DeclSpec
DS(AttrFactory
);
2807 // GNU-style and C++11 attributes are not allowed here, but they will be
2808 // handled by the caller. Diagnose everything else.
2809 ParseTypeQualifierListOpt(
2810 DS
, AR_NoAttributesParsed
, false,
2811 /*IdentifierRequired=*/false, llvm::function_ref
<void()>([&]() {
2812 Actions
.CodeCompletion().CodeCompleteFunctionQualifiers(DS
, D
, &VS
);
2814 D
.ExtendWithDeclSpec(DS
);
2816 if (D
.isFunctionDeclarator()) {
2817 auto &Function
= D
.getFunctionTypeInfo();
2818 if (DS
.getTypeQualifiers() != DeclSpec::TQ_unspecified
) {
2819 auto DeclSpecCheck
= [&](DeclSpec::TQ TypeQual
, StringRef FixItName
,
2820 SourceLocation SpecLoc
) {
2821 FixItHint Insertion
;
2822 auto &MQ
= Function
.getOrCreateMethodQualifiers();
2823 if (!(MQ
.getTypeQualifiers() & TypeQual
)) {
2824 std::string
Name(FixItName
.data());
2826 Insertion
= FixItHint::CreateInsertion(VS
.getFirstLocation(), Name
);
2827 MQ
.SetTypeQual(TypeQual
, SpecLoc
);
2829 Diag(SpecLoc
, diag::err_declspec_after_virtspec
)
2831 << VirtSpecifiers::getSpecifierName(VS
.getLastSpecifier())
2832 << FixItHint::CreateRemoval(SpecLoc
) << Insertion
;
2834 DS
.forEachQualifier(DeclSpecCheck
);
2837 // Parse ref-qualifiers.
2838 bool RefQualifierIsLValueRef
= true;
2839 SourceLocation RefQualifierLoc
;
2840 if (ParseRefQualifier(RefQualifierIsLValueRef
, RefQualifierLoc
)) {
2841 const char *Name
= (RefQualifierIsLValueRef
? "& " : "&& ");
2842 FixItHint Insertion
=
2843 FixItHint::CreateInsertion(VS
.getFirstLocation(), Name
);
2844 Function
.RefQualifierIsLValueRef
= RefQualifierIsLValueRef
;
2845 Function
.RefQualifierLoc
= RefQualifierLoc
;
2847 Diag(RefQualifierLoc
, diag::err_declspec_after_virtspec
)
2848 << (RefQualifierIsLValueRef
? "&" : "&&")
2849 << VirtSpecifiers::getSpecifierName(VS
.getLastSpecifier())
2850 << FixItHint::CreateRemoval(RefQualifierLoc
) << Insertion
;
2851 D
.SetRangeEnd(RefQualifierLoc
);
2856 /// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration.
2858 /// member-declaration:
2859 /// decl-specifier-seq[opt] member-declarator-list[opt] ';'
2860 /// function-definition ';'[opt]
2861 /// [C++26] friend-type-declaration
2862 /// ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO]
2863 /// using-declaration [TODO]
2864 /// [C++0x] static_assert-declaration
2865 /// template-declaration
2866 /// [GNU] '__extension__' member-declaration
2868 /// member-declarator-list:
2869 /// member-declarator
2870 /// member-declarator-list ',' member-declarator
2872 /// member-declarator:
2873 /// declarator virt-specifier-seq[opt] pure-specifier[opt]
2874 /// [C++2a] declarator requires-clause
2875 /// declarator constant-initializer[opt]
2876 /// [C++11] declarator brace-or-equal-initializer[opt]
2877 /// identifier[opt] ':' constant-expression
2879 /// virt-specifier-seq:
2881 /// virt-specifier-seq virt-specifier
2891 /// constant-initializer:
2892 /// '=' constant-expression
2894 /// friend-type-declaration:
2895 /// 'friend' friend-type-specifier-list ;
2897 /// friend-type-specifier-list:
2898 /// friend-type-specifier ...[opt]
2899 /// friend-type-specifier-list , friend-type-specifier ...[opt]
2901 /// friend-type-specifier:
2902 /// simple-type-specifier
2903 /// elaborated-type-specifier
2904 /// typename-specifier
2906 Parser::DeclGroupPtrTy
Parser::ParseCXXClassMemberDeclaration(
2907 AccessSpecifier AS
, ParsedAttributes
&AccessAttrs
,
2908 ParsedTemplateInfo
&TemplateInfo
, ParsingDeclRAIIObject
*TemplateDiags
) {
2909 assert(getLangOpts().CPlusPlus
&&
2910 "ParseCXXClassMemberDeclaration should only be called in C++ mode");
2911 if (Tok
.is(tok::at
)) {
2912 if (getLangOpts().ObjC
&& NextToken().isObjCAtKeyword(tok::objc_defs
))
2913 Diag(Tok
, diag::err_at_defs_cxx
);
2915 Diag(Tok
, diag::err_at_in_class
);
2918 SkipUntil(tok::r_brace
, StopAtSemi
);
2922 // Turn on colon protection early, while parsing declspec, although there is
2923 // nothing to protect there. It prevents from false errors if error recovery
2924 // incorrectly determines where the declspec ends, as in the example:
2925 // struct A { enum class B { C }; };
2927 // struct D { A::B : C; };
2928 ColonProtectionRAIIObject
X(*this);
2930 // Access declarations.
2931 bool MalformedTypeSpec
= false;
2932 if (!TemplateInfo
.Kind
&&
2933 Tok
.isOneOf(tok::identifier
, tok::coloncolon
, tok::kw___super
)) {
2934 if (TryAnnotateCXXScopeToken())
2935 MalformedTypeSpec
= true;
2938 if (Tok
.isNot(tok::annot_cxxscope
))
2939 isAccessDecl
= false;
2940 else if (NextToken().is(tok::identifier
))
2941 isAccessDecl
= GetLookAheadToken(2).is(tok::semi
);
2943 isAccessDecl
= NextToken().is(tok::kw_operator
);
2946 // Collect the scope specifier token we annotated earlier.
2948 ParseOptionalCXXScopeSpecifier(SS
, /*ObjectType=*/nullptr,
2949 /*ObjectHasErrors=*/false,
2950 /*EnteringContext=*/false);
2952 if (SS
.isInvalid()) {
2953 SkipUntil(tok::semi
);
2957 // Try to parse an unqualified-id.
2958 SourceLocation TemplateKWLoc
;
2960 if (ParseUnqualifiedId(SS
, /*ObjectType=*/nullptr,
2961 /*ObjectHadErrors=*/false, false, true, true,
2962 false, &TemplateKWLoc
, Name
)) {
2963 SkipUntil(tok::semi
);
2967 // TODO: recover from mistakenly-qualified operator declarations.
2968 if (ExpectAndConsume(tok::semi
, diag::err_expected_after
,
2969 "access declaration")) {
2970 SkipUntil(tok::semi
);
2974 // FIXME: We should do something with the 'template' keyword here.
2975 return DeclGroupPtrTy::make(DeclGroupRef(Actions
.ActOnUsingDeclaration(
2976 getCurScope(), AS
, /*UsingLoc*/ SourceLocation(),
2977 /*TypenameLoc*/ SourceLocation(), SS
, Name
,
2978 /*EllipsisLoc*/ SourceLocation(),
2979 /*AttrList*/ ParsedAttributesView())));
2983 // static_assert-declaration. A templated static_assert declaration is
2984 // diagnosed in Parser::ParseDeclarationAfterTemplate.
2985 if (!TemplateInfo
.Kind
&&
2986 Tok
.isOneOf(tok::kw_static_assert
, tok::kw__Static_assert
)) {
2987 SourceLocation DeclEnd
;
2988 return DeclGroupPtrTy::make(
2989 DeclGroupRef(ParseStaticAssertDeclaration(DeclEnd
)));
2992 if (Tok
.is(tok::kw_template
)) {
2993 assert(!TemplateInfo
.TemplateParams
&&
2994 "Nested template improperly parsed?");
2995 ObjCDeclContextSwitch
ObjCDC(*this);
2996 SourceLocation DeclEnd
;
2997 return ParseTemplateDeclarationOrSpecialization(DeclaratorContext::Member
,
2998 DeclEnd
, AccessAttrs
, AS
);
3001 // Handle: member-declaration ::= '__extension__' member-declaration
3002 if (Tok
.is(tok::kw___extension__
)) {
3003 // __extension__ silences extension warnings in the subexpression.
3004 ExtensionRAIIObject
O(Diags
); // Use RAII to do this.
3006 return ParseCXXClassMemberDeclaration(AS
, AccessAttrs
, TemplateInfo
,
3010 ParsedAttributes
DeclAttrs(AttrFactory
);
3011 // Optional C++11 attribute-specifier
3012 MaybeParseCXX11Attributes(DeclAttrs
);
3014 // The next token may be an OpenMP pragma annotation token. That would
3015 // normally be handled from ParseCXXClassMemberDeclarationWithPragmas, but in
3016 // this case, it came from an *attribute* rather than a pragma. Handle it now.
3017 if (Tok
.is(tok::annot_attr_openmp
))
3018 return ParseOpenMPDeclarativeDirectiveWithExtDecl(AS
, DeclAttrs
);
3020 if (Tok
.is(tok::kw_using
)) {
3022 SourceLocation UsingLoc
= ConsumeToken();
3024 // Consume unexpected 'template' keywords.
3025 while (Tok
.is(tok::kw_template
)) {
3026 SourceLocation TemplateLoc
= ConsumeToken();
3027 Diag(TemplateLoc
, diag::err_unexpected_template_after_using
)
3028 << FixItHint::CreateRemoval(TemplateLoc
);
3031 if (Tok
.is(tok::kw_namespace
)) {
3032 Diag(UsingLoc
, diag::err_using_namespace_in_class
);
3033 SkipUntil(tok::semi
, StopBeforeMatch
);
3036 SourceLocation DeclEnd
;
3037 // Otherwise, it must be a using-declaration or an alias-declaration.
3038 return ParseUsingDeclaration(DeclaratorContext::Member
, TemplateInfo
,
3039 UsingLoc
, DeclEnd
, DeclAttrs
, AS
);
3042 ParsedAttributes
DeclSpecAttrs(AttrFactory
);
3043 MaybeParseMicrosoftAttributes(DeclSpecAttrs
);
3045 // Hold late-parsed attributes so we can attach a Decl to them later.
3046 LateParsedAttrList CommonLateParsedAttrs
;
3048 // decl-specifier-seq:
3049 // Parse the common declaration-specifiers piece.
3050 ParsingDeclSpec
DS(*this, TemplateDiags
);
3051 DS
.takeAttributesFrom(DeclSpecAttrs
);
3053 if (MalformedTypeSpec
)
3054 DS
.SetTypeSpecError();
3056 // Turn off usual access checking for templates explicit specialization
3057 // and instantiation.
3058 // C++20 [temp.spec] 13.9/6.
3059 // This disables the access checking rules for member function template
3060 // explicit instantiation and explicit specialization.
3061 bool IsTemplateSpecOrInst
=
3062 (TemplateInfo
.Kind
== ParsedTemplateInfo::ExplicitInstantiation
||
3063 TemplateInfo
.Kind
== ParsedTemplateInfo::ExplicitSpecialization
);
3064 SuppressAccessChecks
diagsFromTag(*this, IsTemplateSpecOrInst
);
3066 ParseDeclarationSpecifiers(DS
, TemplateInfo
, AS
, DeclSpecContext::DSC_class
,
3067 &CommonLateParsedAttrs
);
3069 if (IsTemplateSpecOrInst
)
3070 diagsFromTag
.done();
3072 // Turn off colon protection that was set for declspec.
3075 // If we had a free-standing type definition with a missing semicolon, we
3076 // may get this far before the problem becomes obvious.
3077 if (DS
.hasTagDefinition() &&
3078 TemplateInfo
.Kind
== ParsedTemplateInfo::NonTemplate
&&
3079 DiagnoseMissingSemiAfterTagDefinition(DS
, AS
, DeclSpecContext::DSC_class
,
3080 &CommonLateParsedAttrs
))
3083 MultiTemplateParamsArg
TemplateParams(
3084 TemplateInfo
.TemplateParams
? TemplateInfo
.TemplateParams
->data()
3086 TemplateInfo
.TemplateParams
? TemplateInfo
.TemplateParams
->size() : 0);
3088 if (TryConsumeToken(tok::semi
)) {
3089 if (DS
.isFriendSpecified())
3090 ProhibitAttributes(DeclAttrs
);
3092 RecordDecl
*AnonRecord
= nullptr;
3093 Decl
*TheDecl
= Actions
.ParsedFreeStandingDeclSpec(
3094 getCurScope(), AS
, DS
, DeclAttrs
, TemplateParams
, false, AnonRecord
);
3095 Actions
.ActOnDefinedDeclarationSpecifier(TheDecl
);
3096 DS
.complete(TheDecl
);
3098 Decl
*decls
[] = {AnonRecord
, TheDecl
};
3099 return Actions
.BuildDeclaratorGroup(decls
);
3101 return Actions
.ConvertDeclToDeclGroup(TheDecl
);
3104 if (DS
.hasTagDefinition())
3105 Actions
.ActOnDefinedDeclarationSpecifier(DS
.getRepAsDecl());
3107 // Handle C++26's variadic friend declarations. These don't even have
3108 // declarators, so we get them out of the way early here.
3109 if (DS
.isFriendSpecifiedFirst() && Tok
.isOneOf(tok::comma
, tok::ellipsis
)) {
3110 Diag(Tok
.getLocation(), getLangOpts().CPlusPlus26
3111 ? diag::warn_cxx23_variadic_friends
3112 : diag::ext_variadic_friends
);
3114 SourceLocation FriendLoc
= DS
.getFriendSpecLoc();
3115 SmallVector
<Decl
*> Decls
;
3117 // Handles a single friend-type-specifier.
3118 auto ParsedFriendDecl
= [&](ParsingDeclSpec
&DeclSpec
) {
3119 SourceLocation VariadicLoc
;
3120 TryConsumeToken(tok::ellipsis
, VariadicLoc
);
3122 RecordDecl
*AnonRecord
= nullptr;
3123 Decl
*D
= Actions
.ParsedFreeStandingDeclSpec(
3124 getCurScope(), AS
, DeclSpec
, DeclAttrs
, TemplateParams
, false,
3125 AnonRecord
, VariadicLoc
);
3126 DeclSpec
.complete(D
);
3128 SkipUntil(tok::semi
, tok::r_brace
);
3136 if (ParsedFriendDecl(DS
))
3139 while (TryConsumeToken(tok::comma
)) {
3140 ParsingDeclSpec
DeclSpec(*this, TemplateDiags
);
3141 const char *PrevSpec
= nullptr;
3142 unsigned DiagId
= 0;
3143 DeclSpec
.SetFriendSpec(FriendLoc
, PrevSpec
, DiagId
);
3144 ParseDeclarationSpecifiers(DeclSpec
, TemplateInfo
, AS
,
3145 DeclSpecContext::DSC_class
, nullptr);
3146 if (ParsedFriendDecl(DeclSpec
))
3150 ExpectAndConsume(tok::semi
, diag::err_expected_semi_after_stmt
,
3151 "friend declaration");
3153 return Actions
.BuildDeclaratorGroup(Decls
);
3156 // Befriending a concept is invalid and would already fail if
3157 // we did nothing here, but this allows us to issue a more
3158 // helpful diagnostic.
3159 if (Tok
.is(tok::kw_concept
)) {
3162 DS
.isFriendSpecified() || NextToken().is(tok::kw_friend
)
3163 ? llvm::to_underlying(diag::err_friend_concept
)
3164 : llvm::to_underlying(
3166 err_concept_decls_may_only_appear_in_global_namespace_scope
));
3167 SkipUntil(tok::semi
, tok::r_brace
, StopBeforeMatch
);
3171 ParsingDeclarator
DeclaratorInfo(*this, DS
, DeclAttrs
,
3172 DeclaratorContext::Member
);
3173 if (TemplateInfo
.TemplateParams
)
3174 DeclaratorInfo
.setTemplateParameterLists(TemplateParams
);
3177 // Hold late-parsed attributes so we can attach a Decl to them later.
3178 LateParsedAttrList LateParsedAttrs
;
3180 SourceLocation EqualLoc
;
3181 SourceLocation PureSpecLoc
;
3183 auto TryConsumePureSpecifier
= [&](bool AllowDefinition
) {
3184 if (Tok
.isNot(tok::equal
))
3187 auto &Zero
= NextToken();
3188 SmallString
<8> Buffer
;
3189 if (Zero
.isNot(tok::numeric_constant
) ||
3190 PP
.getSpelling(Zero
, Buffer
) != "0")
3193 auto &After
= GetLookAheadToken(2);
3194 if (!After
.isOneOf(tok::semi
, tok::comma
) &&
3195 !(AllowDefinition
&&
3196 After
.isOneOf(tok::l_brace
, tok::colon
, tok::kw_try
)))
3199 EqualLoc
= ConsumeToken();
3200 PureSpecLoc
= ConsumeToken();
3204 SmallVector
<Decl
*, 8> DeclsInGroup
;
3205 ExprResult BitfieldSize
;
3206 ExprResult TrailingRequiresClause
;
3207 bool ExpectSemi
= true;
3209 // C++20 [temp.spec] 13.9/6.
3210 // This disables the access checking rules for member function template
3211 // explicit instantiation and explicit specialization.
3212 SuppressAccessChecks
SAC(*this, IsTemplateSpecOrInst
);
3214 // Parse the first declarator.
3215 if (ParseCXXMemberDeclaratorBeforeInitializer(
3216 DeclaratorInfo
, VS
, BitfieldSize
, LateParsedAttrs
)) {
3217 TryConsumeToken(tok::semi
);
3221 if (IsTemplateSpecOrInst
)
3224 // Check for a member function definition.
3225 if (BitfieldSize
.isUnset()) {
3226 // MSVC permits pure specifier on inline functions defined at class scope.
3227 // Hence check for =0 before checking for function definition.
3228 if (getLangOpts().MicrosoftExt
&& DeclaratorInfo
.isDeclarationOfFunction())
3229 TryConsumePureSpecifier(/*AllowDefinition*/ true);
3231 FunctionDefinitionKind DefinitionKind
= FunctionDefinitionKind::Declaration
;
3232 // function-definition:
3234 // In C++11, a non-function declarator followed by an open brace is a
3235 // braced-init-list for an in-class member initialization, not an
3236 // erroneous function definition.
3237 if (Tok
.is(tok::l_brace
) && !getLangOpts().CPlusPlus11
) {
3238 DefinitionKind
= FunctionDefinitionKind::Definition
;
3239 } else if (DeclaratorInfo
.isFunctionDeclarator()) {
3240 if (Tok
.isOneOf(tok::l_brace
, tok::colon
, tok::kw_try
)) {
3241 DefinitionKind
= FunctionDefinitionKind::Definition
;
3242 } else if (Tok
.is(tok::equal
)) {
3243 const Token
&KW
= NextToken();
3244 if (KW
.is(tok::kw_default
))
3245 DefinitionKind
= FunctionDefinitionKind::Defaulted
;
3246 else if (KW
.is(tok::kw_delete
))
3247 DefinitionKind
= FunctionDefinitionKind::Deleted
;
3248 else if (KW
.is(tok::code_completion
)) {
3250 Actions
.CodeCompletion().CodeCompleteAfterFunctionEquals(
3256 DeclaratorInfo
.setFunctionDefinitionKind(DefinitionKind
);
3258 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
3259 // to a friend declaration, that declaration shall be a definition.
3260 if (DeclaratorInfo
.isFunctionDeclarator() &&
3261 DefinitionKind
== FunctionDefinitionKind::Declaration
&&
3262 DS
.isFriendSpecified()) {
3263 // Diagnose attributes that appear before decl specifier:
3264 // [[]] friend int foo();
3265 ProhibitAttributes(DeclAttrs
);
3268 if (DefinitionKind
!= FunctionDefinitionKind::Declaration
) {
3269 if (!DeclaratorInfo
.isFunctionDeclarator()) {
3270 Diag(DeclaratorInfo
.getIdentifierLoc(), diag::err_func_def_no_params
);
3272 SkipUntil(tok::r_brace
);
3274 // Consume the optional ';'
3275 TryConsumeToken(tok::semi
);
3280 if (DS
.getStorageClassSpec() == DeclSpec::SCS_typedef
) {
3281 Diag(DeclaratorInfo
.getIdentifierLoc(),
3282 diag::err_function_declared_typedef
);
3284 // Recover by treating the 'typedef' as spurious.
3285 DS
.ClearStorageClassSpecs();
3288 Decl
*FunDecl
= ParseCXXInlineMethodDef(AS
, AccessAttrs
, DeclaratorInfo
,
3289 TemplateInfo
, VS
, PureSpecLoc
);
3292 for (unsigned i
= 0, ni
= CommonLateParsedAttrs
.size(); i
< ni
; ++i
) {
3293 CommonLateParsedAttrs
[i
]->addDecl(FunDecl
);
3295 for (unsigned i
= 0, ni
= LateParsedAttrs
.size(); i
< ni
; ++i
) {
3296 LateParsedAttrs
[i
]->addDecl(FunDecl
);
3299 LateParsedAttrs
.clear();
3301 // Consume the ';' - it's optional unless we have a delete or default
3302 if (Tok
.is(tok::semi
))
3303 ConsumeExtraSemi(AfterMemberFunctionDefinition
);
3305 return DeclGroupPtrTy::make(DeclGroupRef(FunDecl
));
3309 // member-declarator-list:
3310 // member-declarator
3311 // member-declarator-list ',' member-declarator
3314 InClassInitStyle HasInClassInit
= ICIS_NoInit
;
3315 bool HasStaticInitializer
= false;
3316 if (Tok
.isOneOf(tok::equal
, tok::l_brace
) && PureSpecLoc
.isInvalid()) {
3317 // DRXXXX: Anonymous bit-fields cannot have a brace-or-equal-initializer.
3318 if (BitfieldSize
.isUsable() && !DeclaratorInfo
.hasName()) {
3319 // Diagnose the error and pretend there is no in-class initializer.
3320 Diag(Tok
, diag::err_anon_bitfield_member_init
);
3321 SkipUntil(tok::comma
, StopAtSemi
| StopBeforeMatch
);
3322 } else if (DeclaratorInfo
.isDeclarationOfFunction()) {
3323 // It's a pure-specifier.
3324 if (!TryConsumePureSpecifier(/*AllowFunctionDefinition*/ false))
3325 // Parse it as an expression so that Sema can diagnose it.
3326 HasStaticInitializer
= true;
3327 } else if (DeclaratorInfo
.getDeclSpec().getStorageClassSpec() !=
3328 DeclSpec::SCS_static
&&
3329 DeclaratorInfo
.getDeclSpec().getStorageClassSpec() !=
3330 DeclSpec::SCS_typedef
&&
3331 !DS
.isFriendSpecified() &&
3332 TemplateInfo
.Kind
== ParsedTemplateInfo::NonTemplate
) {
3333 // It's a default member initializer.
3334 if (BitfieldSize
.get())
3335 Diag(Tok
, getLangOpts().CPlusPlus20
3336 ? diag::warn_cxx17_compat_bitfield_member_init
3337 : diag::ext_bitfield_member_init
);
3338 HasInClassInit
= Tok
.is(tok::equal
) ? ICIS_CopyInit
: ICIS_ListInit
;
3340 HasStaticInitializer
= true;
3344 // NOTE: If Sema is the Action module and declarator is an instance field,
3345 // this call will *not* return the created decl; It will return null.
3346 // See Sema::ActOnCXXMemberDeclarator for details.
3348 NamedDecl
*ThisDecl
= nullptr;
3349 if (DS
.isFriendSpecified()) {
3350 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
3351 // to a friend declaration, that declaration shall be a definition.
3353 // Diagnose attributes that appear in a friend member function declarator:
3354 // friend int foo [[]] ();
3355 for (const ParsedAttr
&AL
: DeclaratorInfo
.getAttributes())
3356 if (AL
.isCXX11Attribute() || AL
.isRegularKeywordAttribute()) {
3357 auto Loc
= AL
.getRange().getBegin();
3358 (AL
.isRegularKeywordAttribute()
3359 ? Diag(Loc
, diag::err_keyword_not_allowed
) << AL
3360 : Diag(Loc
, diag::err_attributes_not_allowed
))
3364 ThisDecl
= Actions
.ActOnFriendFunctionDecl(getCurScope(), DeclaratorInfo
,
3367 ThisDecl
= Actions
.ActOnCXXMemberDeclarator(
3368 getCurScope(), AS
, DeclaratorInfo
, TemplateParams
, BitfieldSize
.get(),
3369 VS
, HasInClassInit
);
3371 if (VarTemplateDecl
*VT
=
3372 ThisDecl
? dyn_cast
<VarTemplateDecl
>(ThisDecl
) : nullptr)
3373 // Re-direct this decl to refer to the templated decl so that we can
3375 ThisDecl
= VT
->getTemplatedDecl();
3378 Actions
.ProcessDeclAttributeList(getCurScope(), ThisDecl
, AccessAttrs
);
3381 // Error recovery might have converted a non-static member into a static
3383 if (HasInClassInit
!= ICIS_NoInit
&&
3384 DeclaratorInfo
.getDeclSpec().getStorageClassSpec() ==
3385 DeclSpec::SCS_static
) {
3386 HasInClassInit
= ICIS_NoInit
;
3387 HasStaticInitializer
= true;
3390 if (PureSpecLoc
.isValid() && VS
.getAbstractLoc().isValid()) {
3391 Diag(PureSpecLoc
, diag::err_duplicate_virt_specifier
) << "abstract";
3393 if (ThisDecl
&& PureSpecLoc
.isValid())
3394 Actions
.ActOnPureSpecifier(ThisDecl
, PureSpecLoc
);
3395 else if (ThisDecl
&& VS
.getAbstractLoc().isValid())
3396 Actions
.ActOnPureSpecifier(ThisDecl
, VS
.getAbstractLoc());
3398 // Handle the initializer.
3399 if (HasInClassInit
!= ICIS_NoInit
) {
3400 // The initializer was deferred; parse it and cache the tokens.
3401 Diag(Tok
, getLangOpts().CPlusPlus11
3402 ? diag::warn_cxx98_compat_nonstatic_member_init
3403 : diag::ext_nonstatic_member_init
);
3405 if (DeclaratorInfo
.isArrayOfUnknownBound()) {
3406 // C++11 [dcl.array]p3: An array bound may also be omitted when the
3407 // declarator is followed by an initializer.
3409 // A brace-or-equal-initializer for a member-declarator is not an
3410 // initializer in the grammar, so this is ill-formed.
3411 Diag(Tok
, diag::err_incomplete_array_member_init
);
3412 SkipUntil(tok::comma
, StopAtSemi
| StopBeforeMatch
);
3414 // Avoid later warnings about a class member of incomplete type.
3416 ThisDecl
->setInvalidDecl();
3418 ParseCXXNonStaticMemberInitializer(ThisDecl
);
3419 } else if (HasStaticInitializer
) {
3420 // Normal initializer.
3421 ExprResult Init
= ParseCXXMemberInitializer(
3422 ThisDecl
, DeclaratorInfo
.isDeclarationOfFunction(), EqualLoc
);
3424 if (Init
.isInvalid()) {
3426 Actions
.ActOnUninitializedDecl(ThisDecl
);
3427 SkipUntil(tok::comma
, StopAtSemi
| StopBeforeMatch
);
3428 } else if (ThisDecl
)
3429 Actions
.AddInitializerToDecl(ThisDecl
, Init
.get(),
3430 EqualLoc
.isInvalid());
3431 } else if (ThisDecl
&& DeclaratorInfo
.isStaticMember())
3433 Actions
.ActOnUninitializedDecl(ThisDecl
);
3436 if (!ThisDecl
->isInvalidDecl()) {
3437 // Set the Decl for any late parsed attributes
3438 for (unsigned i
= 0, ni
= CommonLateParsedAttrs
.size(); i
< ni
; ++i
)
3439 CommonLateParsedAttrs
[i
]->addDecl(ThisDecl
);
3441 for (unsigned i
= 0, ni
= LateParsedAttrs
.size(); i
< ni
; ++i
)
3442 LateParsedAttrs
[i
]->addDecl(ThisDecl
);
3444 Actions
.FinalizeDeclaration(ThisDecl
);
3445 DeclsInGroup
.push_back(ThisDecl
);
3447 if (DeclaratorInfo
.isFunctionDeclarator() &&
3448 DeclaratorInfo
.getDeclSpec().getStorageClassSpec() !=
3449 DeclSpec::SCS_typedef
)
3450 HandleMemberFunctionDeclDelays(DeclaratorInfo
, ThisDecl
);
3452 LateParsedAttrs
.clear();
3454 DeclaratorInfo
.complete(ThisDecl
);
3456 // If we don't have a comma, it is either the end of the list (a ';')
3457 // or an error, bail out.
3458 SourceLocation CommaLoc
;
3459 if (!TryConsumeToken(tok::comma
, CommaLoc
))
3462 if (Tok
.isAtStartOfLine() &&
3463 !MightBeDeclarator(DeclaratorContext::Member
)) {
3464 // This comma was followed by a line-break and something which can't be
3465 // the start of a declarator. The comma was probably a typo for a
3467 Diag(CommaLoc
, diag::err_expected_semi_declaration
)
3468 << FixItHint::CreateReplacement(CommaLoc
, ";");
3473 // C++23 [temp.pre]p5:
3474 // In a template-declaration, explicit specialization, or explicit
3475 // instantiation the init-declarator-list in the declaration shall
3476 // contain at most one declarator.
3477 if (TemplateInfo
.Kind
!= ParsedTemplateInfo::NonTemplate
&&
3478 DeclaratorInfo
.isFirstDeclarator()) {
3479 Diag(CommaLoc
, diag::err_multiple_template_declarators
)
3480 << TemplateInfo
.Kind
;
3483 // Parse the next declarator.
3484 DeclaratorInfo
.clear();
3486 BitfieldSize
= ExprResult(/*Invalid=*/false);
3487 EqualLoc
= PureSpecLoc
= SourceLocation();
3488 DeclaratorInfo
.setCommaLoc(CommaLoc
);
3490 // GNU attributes are allowed before the second and subsequent declarator.
3491 // However, this does not apply for [[]] attributes (which could show up
3492 // before or after the __attribute__ attributes).
3493 DiagnoseAndSkipCXX11Attributes();
3494 MaybeParseGNUAttributes(DeclaratorInfo
);
3495 DiagnoseAndSkipCXX11Attributes();
3497 if (ParseCXXMemberDeclaratorBeforeInitializer(
3498 DeclaratorInfo
, VS
, BitfieldSize
, LateParsedAttrs
))
3503 ExpectAndConsume(tok::semi
, diag::err_expected_semi_decl_list
)) {
3504 // Skip to end of block or statement.
3505 SkipUntil(tok::r_brace
, StopAtSemi
| StopBeforeMatch
);
3506 // If we stopped at a ';', eat it.
3507 TryConsumeToken(tok::semi
);
3511 return Actions
.FinalizeDeclaratorGroup(getCurScope(), DS
, DeclsInGroup
);
3514 /// ParseCXXMemberInitializer - Parse the brace-or-equal-initializer.
3515 /// Also detect and reject any attempted defaulted/deleted function definition.
3516 /// The location of the '=', if any, will be placed in EqualLoc.
3518 /// This does not check for a pure-specifier; that's handled elsewhere.
3520 /// brace-or-equal-initializer:
3521 /// '=' initializer-expression
3522 /// braced-init-list
3524 /// initializer-clause:
3525 /// assignment-expression
3526 /// braced-init-list
3528 /// defaulted/deleted function-definition:
3532 /// Prior to C++0x, the assignment-expression in an initializer-clause must
3533 /// be a constant-expression.
3534 ExprResult
Parser::ParseCXXMemberInitializer(Decl
*D
, bool IsFunction
,
3535 SourceLocation
&EqualLoc
) {
3536 assert(Tok
.isOneOf(tok::equal
, tok::l_brace
) &&
3537 "Data member initializer not starting with '=' or '{'");
3539 bool IsFieldInitialization
= isa_and_present
<FieldDecl
>(D
);
3541 EnterExpressionEvaluationContext
Context(
3543 IsFieldInitialization
3544 ? Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed
3545 : Sema::ExpressionEvaluationContext::PotentiallyEvaluated
,
3549 // Default member initializers used to initialize a base or member subobject
3550 // [...] are considered to be part of the function body
3551 Actions
.ExprEvalContexts
.back().InImmediateEscalatingFunctionContext
=
3552 IsFieldInitialization
;
3554 if (TryConsumeToken(tok::equal
, EqualLoc
)) {
3555 if (Tok
.is(tok::kw_delete
)) {
3556 // In principle, an initializer of '= delete p;' is legal, but it will
3557 // never type-check. It's better to diagnose it as an ill-formed
3558 // expression than as an ill-formed deleted non-function member. An
3559 // initializer of '= delete p, foo' will never be parsed, because a
3560 // top-level comma always ends the initializer expression.
3561 const Token
&Next
= NextToken();
3562 if (IsFunction
|| Next
.isOneOf(tok::semi
, tok::comma
, tok::eof
)) {
3564 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration
)
3567 Diag(ConsumeToken(), diag::err_deleted_non_function
);
3568 SkipDeletedFunctionBody();
3571 } else if (Tok
.is(tok::kw_default
)) {
3573 Diag(Tok
, diag::err_default_delete_in_multiple_declaration
)
3576 Diag(ConsumeToken(), diag::err_default_special_members
)
3577 << getLangOpts().CPlusPlus20
;
3581 if (const auto *PD
= dyn_cast_or_null
<MSPropertyDecl
>(D
)) {
3582 Diag(Tok
, diag::err_ms_property_initializer
) << PD
;
3585 return ParseInitializer();
3588 void Parser::SkipCXXMemberSpecification(SourceLocation RecordLoc
,
3589 SourceLocation AttrFixitLoc
,
3590 unsigned TagType
, Decl
*TagDecl
) {
3591 // Skip the optional 'final' keyword.
3592 if (getLangOpts().CPlusPlus
&& Tok
.is(tok::identifier
)) {
3593 assert(isCXX11FinalKeyword() && "not a class definition");
3596 // Diagnose any C++11 attributes after 'final' keyword.
3597 // We deliberately discard these attributes.
3598 ParsedAttributes
Attrs(AttrFactory
);
3599 CheckMisplacedCXX11Attribute(Attrs
, AttrFixitLoc
);
3601 // This can only happen if we had malformed misplaced attributes;
3602 // we only get called if there is a colon or left-brace after the
3604 if (Tok
.isNot(tok::colon
) && Tok
.isNot(tok::l_brace
))
3608 // Skip the base clauses. This requires actually parsing them, because
3609 // otherwise we can't be sure where they end (a left brace may appear
3610 // within a template argument).
3611 if (Tok
.is(tok::colon
)) {
3612 // Enter the scope of the class so that we can correctly parse its bases.
3613 ParseScope
ClassScope(this, Scope::ClassScope
| Scope::DeclScope
);
3614 ParsingClassDefinition
ParsingDef(*this, TagDecl
, /*NonNestedClass*/ true,
3615 TagType
== DeclSpec::TST_interface
);
3617 Actions
.ActOnTagStartSkippedDefinition(getCurScope(), TagDecl
);
3619 // Parse the bases but don't attach them to the class.
3620 ParseBaseClause(nullptr);
3622 Actions
.ActOnTagFinishSkippedDefinition(OldContext
);
3624 if (!Tok
.is(tok::l_brace
)) {
3625 Diag(PP
.getLocForEndOfToken(PrevTokLocation
),
3626 diag::err_expected_lbrace_after_base_specifiers
);
3632 assert(Tok
.is(tok::l_brace
));
3633 BalancedDelimiterTracker
T(*this, tok::l_brace
);
3637 // Parse and discard any trailing attributes.
3638 if (Tok
.is(tok::kw___attribute
)) {
3639 ParsedAttributes
Attrs(AttrFactory
);
3640 MaybeParseGNUAttributes(Attrs
);
3644 Parser::DeclGroupPtrTy
Parser::ParseCXXClassMemberDeclarationWithPragmas(
3645 AccessSpecifier
&AS
, ParsedAttributes
&AccessAttrs
, DeclSpec::TST TagType
,
3647 ParenBraceBracketBalancer
BalancerRAIIObj(*this);
3649 switch (Tok
.getKind()) {
3650 case tok::kw___if_exists
:
3651 case tok::kw___if_not_exists
:
3652 ParseMicrosoftIfExistsClassDeclaration(TagType
, AccessAttrs
, AS
);
3656 // Check for extraneous top-level semicolon.
3657 ConsumeExtraSemi(InsideStruct
, TagType
);
3660 // Handle pragmas that can appear as member declarations.
3661 case tok::annot_pragma_vis
:
3662 HandlePragmaVisibility();
3664 case tok::annot_pragma_pack
:
3667 case tok::annot_pragma_align
:
3668 HandlePragmaAlign();
3670 case tok::annot_pragma_ms_pointers_to_members
:
3671 HandlePragmaMSPointersToMembers();
3673 case tok::annot_pragma_ms_pragma
:
3674 HandlePragmaMSPragma();
3676 case tok::annot_pragma_ms_vtordisp
:
3677 HandlePragmaMSVtorDisp();
3679 case tok::annot_pragma_dump
:
3683 case tok::kw_namespace
:
3684 // If we see a namespace here, a close brace was missing somewhere.
3685 DiagnoseUnexpectedNamespace(cast
<NamedDecl
>(TagDecl
));
3688 case tok::kw_private
:
3689 // FIXME: We don't accept GNU attributes on access specifiers in OpenCL mode
3691 if (getLangOpts().OpenCL
&& !NextToken().is(tok::colon
)) {
3692 ParsedTemplateInfo TemplateInfo
;
3693 return ParseCXXClassMemberDeclaration(AS
, AccessAttrs
, TemplateInfo
);
3696 case tok::kw_public
:
3697 case tok::kw_protected
: {
3698 if (getLangOpts().HLSL
)
3699 Diag(Tok
.getLocation(), diag::ext_hlsl_access_specifiers
);
3700 AccessSpecifier NewAS
= getAccessSpecifierIfPresent();
3701 assert(NewAS
!= AS_none
);
3702 // Current token is a C++ access specifier.
3704 SourceLocation ASLoc
= Tok
.getLocation();
3705 unsigned TokLength
= Tok
.getLength();
3707 AccessAttrs
.clear();
3708 MaybeParseGNUAttributes(AccessAttrs
);
3710 SourceLocation EndLoc
;
3711 if (TryConsumeToken(tok::colon
, EndLoc
)) {
3712 } else if (TryConsumeToken(tok::semi
, EndLoc
)) {
3713 Diag(EndLoc
, diag::err_expected
)
3714 << tok::colon
<< FixItHint::CreateReplacement(EndLoc
, ":");
3716 EndLoc
= ASLoc
.getLocWithOffset(TokLength
);
3717 Diag(EndLoc
, diag::err_expected
)
3718 << tok::colon
<< FixItHint::CreateInsertion(EndLoc
, ":");
3721 // The Microsoft extension __interface does not permit non-public
3722 // access specifiers.
3723 if (TagType
== DeclSpec::TST_interface
&& AS
!= AS_public
) {
3724 Diag(ASLoc
, diag::err_access_specifier_interface
) << (AS
== AS_protected
);
3727 if (Actions
.ActOnAccessSpecifier(NewAS
, ASLoc
, EndLoc
, AccessAttrs
)) {
3728 // found another attribute than only annotations
3729 AccessAttrs
.clear();
3735 case tok::annot_attr_openmp
:
3736 case tok::annot_pragma_openmp
:
3737 return ParseOpenMPDeclarativeDirectiveWithExtDecl(
3738 AS
, AccessAttrs
, /*Delayed=*/true, TagType
, TagDecl
);
3739 case tok::annot_pragma_openacc
:
3740 return ParseOpenACCDirectiveDecl();
3743 if (tok::isPragmaAnnotation(Tok
.getKind())) {
3744 Diag(Tok
.getLocation(), diag::err_pragma_misplaced_in_decl
)
3745 << DeclSpec::getSpecifierName(
3746 TagType
, Actions
.getASTContext().getPrintingPolicy());
3747 ConsumeAnnotationToken();
3750 ParsedTemplateInfo TemplateInfo
;
3751 return ParseCXXClassMemberDeclaration(AS
, AccessAttrs
, TemplateInfo
);
3755 /// ParseCXXMemberSpecification - Parse the class definition.
3757 /// member-specification:
3758 /// member-declaration member-specification[opt]
3759 /// access-specifier ':' member-specification[opt]
3761 void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc
,
3762 SourceLocation AttrFixitLoc
,
3763 ParsedAttributes
&Attrs
,
3764 unsigned TagType
, Decl
*TagDecl
) {
3765 assert((TagType
== DeclSpec::TST_struct
||
3766 TagType
== DeclSpec::TST_interface
||
3767 TagType
== DeclSpec::TST_union
|| TagType
== DeclSpec::TST_class
) &&
3768 "Invalid TagType!");
3770 llvm::TimeTraceScope
TimeScope("ParseClass", [&]() {
3771 if (auto *TD
= dyn_cast_or_null
<NamedDecl
>(TagDecl
))
3772 return TD
->getQualifiedNameAsString();
3773 return std::string("<anonymous>");
3776 PrettyDeclStackTraceEntry
CrashInfo(Actions
.Context
, TagDecl
, RecordLoc
,
3777 "parsing struct/union/class body");
3779 // Determine whether this is a non-nested class. Note that local
3780 // classes are *not* considered to be nested classes.
3781 bool NonNestedClass
= true;
3782 if (!ClassStack
.empty()) {
3783 for (const Scope
*S
= getCurScope(); S
; S
= S
->getParent()) {
3784 if (S
->isClassScope()) {
3785 // We're inside a class scope, so this is a nested class.
3786 NonNestedClass
= false;
3788 // The Microsoft extension __interface does not permit nested classes.
3789 if (getCurrentClass().IsInterface
) {
3790 Diag(RecordLoc
, diag::err_invalid_member_in_interface
)
3792 << (isa
<NamedDecl
>(TagDecl
)
3793 ? cast
<NamedDecl
>(TagDecl
)->getQualifiedNameAsString()
3799 if (S
->isFunctionScope())
3800 // If we're in a function or function template then this is a local
3801 // class rather than a nested class.
3806 // Enter a scope for the class.
3807 ParseScope
ClassScope(this, Scope::ClassScope
| Scope::DeclScope
);
3809 // Note that we are parsing a new (potentially-nested) class definition.
3810 ParsingClassDefinition
ParsingDef(*this, TagDecl
, NonNestedClass
,
3811 TagType
== DeclSpec::TST_interface
);
3814 Actions
.ActOnTagStartDefinition(getCurScope(), TagDecl
);
3816 SourceLocation FinalLoc
;
3817 SourceLocation AbstractLoc
;
3818 bool IsFinalSpelledSealed
= false;
3819 bool IsAbstract
= false;
3821 // Parse the optional 'final' keyword.
3822 if (getLangOpts().CPlusPlus
&& Tok
.is(tok::identifier
)) {
3824 VirtSpecifiers::Specifier Specifier
= isCXX11VirtSpecifier(Tok
);
3825 if (Specifier
== VirtSpecifiers::VS_None
)
3827 if (isCXX11FinalKeyword()) {
3828 if (FinalLoc
.isValid()) {
3829 auto Skipped
= ConsumeToken();
3830 Diag(Skipped
, diag::err_duplicate_class_virt_specifier
)
3831 << VirtSpecifiers::getSpecifierName(Specifier
);
3833 FinalLoc
= ConsumeToken();
3834 if (Specifier
== VirtSpecifiers::VS_Sealed
)
3835 IsFinalSpelledSealed
= true;
3838 if (AbstractLoc
.isValid()) {
3839 auto Skipped
= ConsumeToken();
3840 Diag(Skipped
, diag::err_duplicate_class_virt_specifier
)
3841 << VirtSpecifiers::getSpecifierName(Specifier
);
3843 AbstractLoc
= ConsumeToken();
3847 if (TagType
== DeclSpec::TST_interface
)
3848 Diag(FinalLoc
, diag::err_override_control_interface
)
3849 << VirtSpecifiers::getSpecifierName(Specifier
);
3850 else if (Specifier
== VirtSpecifiers::VS_Final
)
3851 Diag(FinalLoc
, getLangOpts().CPlusPlus11
3852 ? diag::warn_cxx98_compat_override_control_keyword
3853 : diag::ext_override_control_keyword
)
3854 << VirtSpecifiers::getSpecifierName(Specifier
);
3855 else if (Specifier
== VirtSpecifiers::VS_Sealed
)
3856 Diag(FinalLoc
, diag::ext_ms_sealed_keyword
);
3857 else if (Specifier
== VirtSpecifiers::VS_Abstract
)
3858 Diag(AbstractLoc
, diag::ext_ms_abstract_keyword
);
3859 else if (Specifier
== VirtSpecifiers::VS_GNU_Final
)
3860 Diag(FinalLoc
, diag::ext_warn_gnu_final
);
3862 assert((FinalLoc
.isValid() || AbstractLoc
.isValid()) &&
3863 "not a class definition");
3865 // Parse any C++11 attributes after 'final' keyword.
3866 // These attributes are not allowed to appear here,
3867 // and the only possible place for them to appertain
3868 // to the class would be between class-key and class-name.
3869 CheckMisplacedCXX11Attribute(Attrs
, AttrFixitLoc
);
3871 // ParseClassSpecifier() does only a superficial check for attributes before
3872 // deciding to call this method. For example, for
3873 // `class C final alignas ([l) {` it will decide that this looks like a
3874 // misplaced attribute since it sees `alignas '(' ')'`. But the actual
3875 // attribute parsing code will try to parse the '[' as a constexpr lambda
3876 // and consume enough tokens that the alignas parsing code will eat the
3877 // opening '{'. So bail out if the next token isn't one we expect.
3878 if (!Tok
.is(tok::colon
) && !Tok
.is(tok::l_brace
)) {
3880 Actions
.ActOnTagDefinitionError(getCurScope(), TagDecl
);
3885 if (Tok
.is(tok::colon
)) {
3886 ParseScope
InheritanceScope(this, getCurScope()->getFlags() |
3887 Scope::ClassInheritanceScope
);
3889 ParseBaseClause(TagDecl
);
3890 if (!Tok
.is(tok::l_brace
)) {
3891 bool SuggestFixIt
= false;
3892 SourceLocation BraceLoc
= PP
.getLocForEndOfToken(PrevTokLocation
);
3893 if (Tok
.isAtStartOfLine()) {
3894 switch (Tok
.getKind()) {
3895 case tok::kw_private
:
3896 case tok::kw_protected
:
3897 case tok::kw_public
:
3898 SuggestFixIt
= NextToken().getKind() == tok::colon
;
3900 case tok::kw_static_assert
:
3903 // base-clause can have simple-template-id; 'template' can't be there
3904 case tok::kw_template
:
3905 SuggestFixIt
= true;
3907 case tok::identifier
:
3908 SuggestFixIt
= isConstructorDeclarator(true);
3911 SuggestFixIt
= isCXXSimpleDeclaration(/*AllowForRangeDecl=*/false);
3915 DiagnosticBuilder LBraceDiag
=
3916 Diag(BraceLoc
, diag::err_expected_lbrace_after_base_specifiers
);
3918 LBraceDiag
<< FixItHint::CreateInsertion(BraceLoc
, " {");
3919 // Try recovering from missing { after base-clause.
3920 PP
.EnterToken(Tok
, /*IsReinject*/ true);
3921 Tok
.setKind(tok::l_brace
);
3924 Actions
.ActOnTagDefinitionError(getCurScope(), TagDecl
);
3930 assert(Tok
.is(tok::l_brace
));
3931 BalancedDelimiterTracker
T(*this, tok::l_brace
);
3935 Actions
.ActOnStartCXXMemberDeclarations(getCurScope(), TagDecl
, FinalLoc
,
3936 IsFinalSpelledSealed
, IsAbstract
,
3937 T
.getOpenLocation());
3939 // C++ 11p3: Members of a class defined with the keyword class are private
3940 // by default. Members of a class defined with the keywords struct or union
3941 // are public by default.
3942 // HLSL: In HLSL members of a class are public by default.
3943 AccessSpecifier CurAS
;
3944 if (TagType
== DeclSpec::TST_class
&& !getLangOpts().HLSL
)
3948 ParsedAttributes
AccessAttrs(AttrFactory
);
3951 // While we still have something to read, read the member-declarations.
3952 while (!tryParseMisplacedModuleImport() && Tok
.isNot(tok::r_brace
) &&
3953 Tok
.isNot(tok::eof
)) {
3954 // Each iteration of this loop reads one member-declaration.
3955 ParseCXXClassMemberDeclarationWithPragmas(
3956 CurAS
, AccessAttrs
, static_cast<DeclSpec::TST
>(TagType
), TagDecl
);
3957 MaybeDestroyTemplateIds();
3961 SkipUntil(tok::r_brace
);
3964 // If attributes exist after class contents, parse them.
3965 ParsedAttributes
attrs(AttrFactory
);
3966 MaybeParseGNUAttributes(attrs
);
3969 Actions
.ActOnFinishCXXMemberSpecification(getCurScope(), RecordLoc
, TagDecl
,
3970 T
.getOpenLocation(),
3971 T
.getCloseLocation(), attrs
);
3973 // C++11 [class.mem]p2:
3974 // Within the class member-specification, the class is regarded as complete
3975 // within function bodies, default arguments, exception-specifications, and
3976 // brace-or-equal-initializers for non-static data members (including such
3977 // things in nested classes).
3978 if (TagDecl
&& NonNestedClass
) {
3979 // We are not inside a nested class. This class and its nested classes
3980 // are complete and we can parse the delayed portions of method
3981 // declarations and the lexed inline method definitions, along with any
3982 // delayed attributes.
3984 SourceLocation SavedPrevTokLocation
= PrevTokLocation
;
3985 ParseLexedPragmas(getCurrentClass());
3986 ParseLexedAttributes(getCurrentClass());
3987 ParseLexedMethodDeclarations(getCurrentClass());
3989 // We've finished with all pending member declarations.
3990 Actions
.ActOnFinishCXXMemberDecls();
3992 ParseLexedMemberInitializers(getCurrentClass());
3993 ParseLexedMethodDefs(getCurrentClass());
3994 PrevTokLocation
= SavedPrevTokLocation
;
3996 // We've finished parsing everything, including default argument
3998 Actions
.ActOnFinishCXXNonNestedClass();
4002 Actions
.ActOnTagFinishDefinition(getCurScope(), TagDecl
, T
.getRange());
4004 // Leave the class scope.
4009 void Parser::DiagnoseUnexpectedNamespace(NamedDecl
*D
) {
4010 assert(Tok
.is(tok::kw_namespace
));
4012 // FIXME: Suggest where the close brace should have gone by looking
4013 // at indentation changes within the definition body.
4014 Diag(D
->getLocation(), diag::err_missing_end_of_definition
) << D
;
4015 Diag(Tok
.getLocation(), diag::note_missing_end_of_definition_before
) << D
;
4017 // Push '};' onto the token stream to recover.
4018 PP
.EnterToken(Tok
, /*IsReinject*/ true);
4021 Tok
.setLocation(PP
.getLocForEndOfToken(PrevTokLocation
));
4022 Tok
.setKind(tok::semi
);
4023 PP
.EnterToken(Tok
, /*IsReinject*/ true);
4025 Tok
.setKind(tok::r_brace
);
4028 /// ParseConstructorInitializer - Parse a C++ constructor initializer,
4029 /// which explicitly initializes the members or base classes of a
4030 /// class (C++ [class.base.init]). For example, the three initializers
4031 /// after the ':' in the Derived constructor below:
4035 /// class Derived : Base {
4039 /// Derived(float f) : Base(), x(17), f(f) { }
4043 /// [C++] ctor-initializer:
4044 /// ':' mem-initializer-list
4046 /// [C++] mem-initializer-list:
4047 /// mem-initializer ...[opt]
4048 /// mem-initializer ...[opt] , mem-initializer-list
4049 void Parser::ParseConstructorInitializer(Decl
*ConstructorDecl
) {
4050 assert(Tok
.is(tok::colon
) &&
4051 "Constructor initializer always starts with ':'");
4053 // Poison the SEH identifiers so they are flagged as illegal in constructor
4055 PoisonSEHIdentifiersRAIIObject
PoisonSEHIdentifiers(*this, true);
4056 SourceLocation ColonLoc
= ConsumeToken();
4058 SmallVector
<CXXCtorInitializer
*, 4> MemInitializers
;
4059 bool AnyErrors
= false;
4062 if (Tok
.is(tok::code_completion
)) {
4064 Actions
.CodeCompletion().CodeCompleteConstructorInitializer(
4065 ConstructorDecl
, MemInitializers
);
4069 MemInitResult MemInit
= ParseMemInitializer(ConstructorDecl
);
4070 if (!MemInit
.isInvalid())
4071 MemInitializers
.push_back(MemInit
.get());
4075 if (Tok
.is(tok::comma
))
4077 else if (Tok
.is(tok::l_brace
))
4079 // If the previous initializer was valid and the next token looks like a
4080 // base or member initializer, assume that we're just missing a comma.
4081 else if (!MemInit
.isInvalid() &&
4082 Tok
.isOneOf(tok::identifier
, tok::coloncolon
)) {
4083 SourceLocation Loc
= PP
.getLocForEndOfToken(PrevTokLocation
);
4084 Diag(Loc
, diag::err_ctor_init_missing_comma
)
4085 << FixItHint::CreateInsertion(Loc
, ", ");
4087 // Skip over garbage, until we get to '{'. Don't eat the '{'.
4088 if (!MemInit
.isInvalid())
4089 Diag(Tok
.getLocation(), diag::err_expected_either
)
4090 << tok::l_brace
<< tok::comma
;
4091 SkipUntil(tok::l_brace
, StopAtSemi
| StopBeforeMatch
);
4096 Actions
.ActOnMemInitializers(ConstructorDecl
, ColonLoc
, MemInitializers
,
4100 /// ParseMemInitializer - Parse a C++ member initializer, which is
4101 /// part of a constructor initializer that explicitly initializes one
4102 /// member or base class (C++ [class.base.init]). See
4103 /// ParseConstructorInitializer for an example.
4105 /// [C++] mem-initializer:
4106 /// mem-initializer-id '(' expression-list[opt] ')'
4107 /// [C++0x] mem-initializer-id braced-init-list
4109 /// [C++] mem-initializer-id:
4110 /// '::'[opt] nested-name-specifier[opt] class-name
4112 MemInitResult
Parser::ParseMemInitializer(Decl
*ConstructorDecl
) {
4113 // parse '::'[opt] nested-name-specifier[opt]
4115 if (ParseOptionalCXXScopeSpecifier(SS
, /*ObjectType=*/nullptr,
4116 /*ObjectHasErrors=*/false,
4117 /*EnteringContext=*/false))
4121 IdentifierInfo
*II
= nullptr;
4122 SourceLocation IdLoc
= Tok
.getLocation();
4124 DeclSpec
DS(AttrFactory
);
4125 // : template_name<...>
4126 TypeResult TemplateTypeTy
;
4128 if (Tok
.is(tok::identifier
)) {
4129 // Get the identifier. This may be a member name or a class name,
4130 // but we'll let the semantic analysis determine which it is.
4131 II
= Tok
.getIdentifierInfo();
4133 } else if (Tok
.is(tok::annot_decltype
)) {
4134 // Get the decltype expression, if there is one.
4135 // Uses of decltype will already have been converted to annot_decltype by
4136 // ParseOptionalCXXScopeSpecifier at this point.
4137 // FIXME: Can we get here with a scope specifier?
4138 ParseDecltypeSpecifier(DS
);
4139 } else if (Tok
.is(tok::annot_pack_indexing_type
)) {
4140 // Uses of T...[N] will already have been converted to
4141 // annot_pack_indexing_type by ParseOptionalCXXScopeSpecifier at this point.
4142 ParsePackIndexingType(DS
);
4144 TemplateIdAnnotation
*TemplateId
= Tok
.is(tok::annot_template_id
)
4145 ? takeTemplateIdAnnotation(Tok
)
4147 if (TemplateId
&& TemplateId
->mightBeType()) {
4148 AnnotateTemplateIdTokenAsType(SS
, ImplicitTypenameContext::No
,
4149 /*IsClassName=*/true);
4150 assert(Tok
.is(tok::annot_typename
) && "template-id -> type failed");
4151 TemplateTypeTy
= getTypeAnnotation(Tok
);
4152 ConsumeAnnotationToken();
4154 Diag(Tok
, diag::err_expected_member_or_base_name
);
4160 if (getLangOpts().CPlusPlus11
&& Tok
.is(tok::l_brace
)) {
4161 Diag(Tok
, diag::warn_cxx98_compat_generalized_initializer_lists
);
4163 // FIXME: Add support for signature help inside initializer lists.
4164 ExprResult InitList
= ParseBraceInitializer();
4165 if (InitList
.isInvalid())
4168 SourceLocation EllipsisLoc
;
4169 TryConsumeToken(tok::ellipsis
, EllipsisLoc
);
4171 if (TemplateTypeTy
.isInvalid())
4173 return Actions
.ActOnMemInitializer(ConstructorDecl
, getCurScope(), SS
, II
,
4174 TemplateTypeTy
.get(), DS
, IdLoc
,
4175 InitList
.get(), EllipsisLoc
);
4176 } else if (Tok
.is(tok::l_paren
)) {
4177 BalancedDelimiterTracker
T(*this, tok::l_paren
);
4180 // Parse the optional expression-list.
4181 ExprVector ArgExprs
;
4182 auto RunSignatureHelp
= [&] {
4183 if (TemplateTypeTy
.isInvalid())
4185 QualType PreferredType
=
4186 Actions
.CodeCompletion().ProduceCtorInitMemberSignatureHelp(
4187 ConstructorDecl
, SS
, TemplateTypeTy
.get(), ArgExprs
, II
,
4188 T
.getOpenLocation(), /*Braced=*/false);
4189 CalledSignatureHelp
= true;
4190 return PreferredType
;
4192 if (Tok
.isNot(tok::r_paren
) && ParseExpressionList(ArgExprs
, [&] {
4193 PreferredType
.enterFunctionArgument(Tok
.getLocation(),
4196 if (PP
.isCodeCompletionReached() && !CalledSignatureHelp
)
4198 SkipUntil(tok::r_paren
, StopAtSemi
);
4204 SourceLocation EllipsisLoc
;
4205 TryConsumeToken(tok::ellipsis
, EllipsisLoc
);
4207 if (TemplateTypeTy
.isInvalid())
4209 return Actions
.ActOnMemInitializer(
4210 ConstructorDecl
, getCurScope(), SS
, II
, TemplateTypeTy
.get(), DS
, IdLoc
,
4211 T
.getOpenLocation(), ArgExprs
, T
.getCloseLocation(), EllipsisLoc
);
4214 if (TemplateTypeTy
.isInvalid())
4217 if (getLangOpts().CPlusPlus11
)
4218 return Diag(Tok
, diag::err_expected_either
) << tok::l_paren
<< tok::l_brace
;
4220 return Diag(Tok
, diag::err_expected
) << tok::l_paren
;
4223 /// Parse a C++ exception-specification if present (C++0x [except.spec]).
4225 /// exception-specification:
4226 /// dynamic-exception-specification
4227 /// noexcept-specification
4229 /// noexcept-specification:
4231 /// 'noexcept' '(' constant-expression ')'
4232 ExceptionSpecificationType
Parser::tryParseExceptionSpecification(
4233 bool Delayed
, SourceRange
&SpecificationRange
,
4234 SmallVectorImpl
<ParsedType
> &DynamicExceptions
,
4235 SmallVectorImpl
<SourceRange
> &DynamicExceptionRanges
,
4236 ExprResult
&NoexceptExpr
, CachedTokens
*&ExceptionSpecTokens
) {
4237 ExceptionSpecificationType Result
= EST_None
;
4238 ExceptionSpecTokens
= nullptr;
4240 // Handle delayed parsing of exception-specifications.
4242 if (Tok
.isNot(tok::kw_throw
) && Tok
.isNot(tok::kw_noexcept
))
4245 // Consume and cache the starting token.
4246 bool IsNoexcept
= Tok
.is(tok::kw_noexcept
);
4247 Token StartTok
= Tok
;
4248 SpecificationRange
= SourceRange(ConsumeToken());
4251 if (!Tok
.is(tok::l_paren
)) {
4252 // If this is a bare 'noexcept', we're done.
4254 Diag(Tok
, diag::warn_cxx98_compat_noexcept_decl
);
4255 NoexceptExpr
= nullptr;
4256 return EST_BasicNoexcept
;
4259 Diag(Tok
, diag::err_expected_lparen_after
) << "throw";
4260 return EST_DynamicNone
;
4263 // Cache the tokens for the exception-specification.
4264 ExceptionSpecTokens
= new CachedTokens
;
4265 ExceptionSpecTokens
->push_back(StartTok
); // 'throw' or 'noexcept'
4266 ExceptionSpecTokens
->push_back(Tok
); // '('
4267 SpecificationRange
.setEnd(ConsumeParen()); // '('
4269 ConsumeAndStoreUntil(tok::r_paren
, *ExceptionSpecTokens
,
4270 /*StopAtSemi=*/true,
4271 /*ConsumeFinalToken=*/true);
4272 SpecificationRange
.setEnd(ExceptionSpecTokens
->back().getLocation());
4274 return EST_Unparsed
;
4277 // See if there's a dynamic specification.
4278 if (Tok
.is(tok::kw_throw
)) {
4279 Result
= ParseDynamicExceptionSpecification(
4280 SpecificationRange
, DynamicExceptions
, DynamicExceptionRanges
);
4281 assert(DynamicExceptions
.size() == DynamicExceptionRanges
.size() &&
4282 "Produced different number of exception types and ranges.");
4285 // If there's no noexcept specification, we're done.
4286 if (Tok
.isNot(tok::kw_noexcept
))
4289 Diag(Tok
, diag::warn_cxx98_compat_noexcept_decl
);
4291 // If we already had a dynamic specification, parse the noexcept for,
4292 // recovery, but emit a diagnostic and don't store the results.
4293 SourceRange NoexceptRange
;
4294 ExceptionSpecificationType NoexceptType
= EST_None
;
4296 SourceLocation KeywordLoc
= ConsumeToken();
4297 if (Tok
.is(tok::l_paren
)) {
4298 // There is an argument.
4299 BalancedDelimiterTracker
T(*this, tok::l_paren
);
4302 EnterExpressionEvaluationContext
ConstantEvaluated(
4303 Actions
, Sema::ExpressionEvaluationContext::ConstantEvaluated
);
4304 NoexceptExpr
= ParseConstantExpressionInExprEvalContext();
4307 if (!NoexceptExpr
.isInvalid()) {
4309 Actions
.ActOnNoexceptSpec(NoexceptExpr
.get(), NoexceptType
);
4310 NoexceptRange
= SourceRange(KeywordLoc
, T
.getCloseLocation());
4312 NoexceptType
= EST_BasicNoexcept
;
4315 // There is no argument.
4316 NoexceptType
= EST_BasicNoexcept
;
4317 NoexceptRange
= SourceRange(KeywordLoc
, KeywordLoc
);
4320 if (Result
== EST_None
) {
4321 SpecificationRange
= NoexceptRange
;
4322 Result
= NoexceptType
;
4324 // If there's a dynamic specification after a noexcept specification,
4325 // parse that and ignore the results.
4326 if (Tok
.is(tok::kw_throw
)) {
4327 Diag(Tok
.getLocation(), diag::err_dynamic_and_noexcept_specification
);
4328 ParseDynamicExceptionSpecification(NoexceptRange
, DynamicExceptions
,
4329 DynamicExceptionRanges
);
4332 Diag(Tok
.getLocation(), diag::err_dynamic_and_noexcept_specification
);
4338 static void diagnoseDynamicExceptionSpecification(Parser
&P
, SourceRange Range
,
4340 if (P
.getLangOpts().CPlusPlus11
) {
4341 const char *Replacement
= IsNoexcept
? "noexcept" : "noexcept(false)";
4342 P
.Diag(Range
.getBegin(), P
.getLangOpts().CPlusPlus17
&& !IsNoexcept
4343 ? diag::ext_dynamic_exception_spec
4344 : diag::warn_exception_spec_deprecated
)
4346 P
.Diag(Range
.getBegin(), diag::note_exception_spec_deprecated
)
4347 << Replacement
<< FixItHint::CreateReplacement(Range
, Replacement
);
4351 /// ParseDynamicExceptionSpecification - Parse a C++
4352 /// dynamic-exception-specification (C++ [except.spec]).
4354 /// dynamic-exception-specification:
4355 /// 'throw' '(' type-id-list [opt] ')'
4356 /// [MS] 'throw' '(' '...' ')'
4359 /// type-id ... [opt]
4360 /// type-id-list ',' type-id ... [opt]
4362 ExceptionSpecificationType
Parser::ParseDynamicExceptionSpecification(
4363 SourceRange
&SpecificationRange
, SmallVectorImpl
<ParsedType
> &Exceptions
,
4364 SmallVectorImpl
<SourceRange
> &Ranges
) {
4365 assert(Tok
.is(tok::kw_throw
) && "expected throw");
4367 SpecificationRange
.setBegin(ConsumeToken());
4368 BalancedDelimiterTracker
T(*this, tok::l_paren
);
4369 if (T
.consumeOpen()) {
4370 Diag(Tok
, diag::err_expected_lparen_after
) << "throw";
4371 SpecificationRange
.setEnd(SpecificationRange
.getBegin());
4372 return EST_DynamicNone
;
4375 // Parse throw(...), a Microsoft extension that means "this function
4376 // can throw anything".
4377 if (Tok
.is(tok::ellipsis
)) {
4378 SourceLocation EllipsisLoc
= ConsumeToken();
4379 if (!getLangOpts().MicrosoftExt
)
4380 Diag(EllipsisLoc
, diag::ext_ellipsis_exception_spec
);
4382 SpecificationRange
.setEnd(T
.getCloseLocation());
4383 diagnoseDynamicExceptionSpecification(*this, SpecificationRange
, false);
4387 // Parse the sequence of type-ids.
4389 while (Tok
.isNot(tok::r_paren
)) {
4390 TypeResult
Res(ParseTypeName(&Range
));
4392 if (Tok
.is(tok::ellipsis
)) {
4393 // C++0x [temp.variadic]p5:
4394 // - In a dynamic-exception-specification (15.4); the pattern is a
4396 SourceLocation Ellipsis
= ConsumeToken();
4397 Range
.setEnd(Ellipsis
);
4398 if (!Res
.isInvalid())
4399 Res
= Actions
.ActOnPackExpansion(Res
.get(), Ellipsis
);
4402 if (!Res
.isInvalid()) {
4403 Exceptions
.push_back(Res
.get());
4404 Ranges
.push_back(Range
);
4407 if (!TryConsumeToken(tok::comma
))
4412 SpecificationRange
.setEnd(T
.getCloseLocation());
4413 diagnoseDynamicExceptionSpecification(*this, SpecificationRange
,
4414 Exceptions
.empty());
4415 return Exceptions
.empty() ? EST_DynamicNone
: EST_Dynamic
;
4418 /// ParseTrailingReturnType - Parse a trailing return type on a new-style
4419 /// function declaration.
4420 TypeResult
Parser::ParseTrailingReturnType(SourceRange
&Range
,
4421 bool MayBeFollowedByDirectInit
) {
4422 assert(Tok
.is(tok::arrow
) && "expected arrow");
4426 return ParseTypeName(&Range
, MayBeFollowedByDirectInit
4427 ? DeclaratorContext::TrailingReturnVar
4428 : DeclaratorContext::TrailingReturn
);
4431 /// Parse a requires-clause as part of a function declaration.
4432 void Parser::ParseTrailingRequiresClause(Declarator
&D
) {
4433 assert(Tok
.is(tok::kw_requires
) && "expected requires");
4435 SourceLocation RequiresKWLoc
= ConsumeToken();
4437 // C++23 [basic.scope.namespace]p1:
4438 // For each non-friend redeclaration or specialization whose target scope
4439 // is or is contained by the scope, the portion after the declarator-id,
4440 // class-head-name, or enum-head-name is also included in the scope.
4441 // C++23 [basic.scope.class]p1:
4442 // For each non-friend redeclaration or specialization whose target scope
4443 // is or is contained by the scope, the portion after the declarator-id,
4444 // class-head-name, or enum-head-name is also included in the scope.
4446 // FIXME: We should really be calling ParseTrailingRequiresClause in
4447 // ParseDirectDeclarator, when we are already in the declarator scope.
4448 // This would also correctly suppress access checks for specializations
4449 // and explicit instantiations, which we currently do not do.
4450 CXXScopeSpec
&SS
= D
.getCXXScopeSpec();
4451 DeclaratorScopeObj
DeclScopeObj(*this, SS
);
4452 if (SS
.isValid() && Actions
.ShouldEnterDeclaratorScope(getCurScope(), SS
))
4453 DeclScopeObj
.EnterDeclaratorScope();
4455 ExprResult TrailingRequiresClause
;
4456 ParseScope
ParamScope(this, Scope::DeclScope
|
4457 Scope::FunctionDeclarationScope
|
4458 Scope::FunctionPrototypeScope
);
4460 Actions
.ActOnStartTrailingRequiresClause(getCurScope(), D
);
4462 std::optional
<Sema::CXXThisScopeRAII
> ThisScope
;
4463 InitCXXThisScopeForDeclaratorIfRelevant(D
, D
.getDeclSpec(), ThisScope
);
4465 TrailingRequiresClause
=
4466 ParseConstraintLogicalOrExpression(/*IsTrailingRequiresClause=*/true);
4468 TrailingRequiresClause
=
4469 Actions
.ActOnFinishTrailingRequiresClause(TrailingRequiresClause
);
4471 if (!D
.isDeclarationOfFunction()) {
4473 diag::err_requires_clause_on_declarator_not_declaring_a_function
);
4477 if (TrailingRequiresClause
.isInvalid())
4478 SkipUntil({tok::l_brace
, tok::arrow
, tok::kw_try
, tok::comma
, tok::colon
},
4479 StopAtSemi
| StopBeforeMatch
);
4481 D
.setTrailingRequiresClause(TrailingRequiresClause
.get());
4483 // Did the user swap the trailing return type and requires clause?
4484 if (D
.isFunctionDeclarator() && Tok
.is(tok::arrow
) &&
4485 D
.getDeclSpec().getTypeSpecType() == TST_auto
) {
4486 SourceLocation ArrowLoc
= Tok
.getLocation();
4488 TypeResult TrailingReturnType
=
4489 ParseTrailingReturnType(Range
, /*MayBeFollowedByDirectInit=*/false);
4491 if (!TrailingReturnType
.isInvalid()) {
4493 diag::err_requires_clause_must_appear_after_trailing_return
)
4495 auto &FunctionChunk
= D
.getFunctionTypeInfo();
4496 FunctionChunk
.HasTrailingReturnType
= TrailingReturnType
.isUsable();
4497 FunctionChunk
.TrailingReturnType
= TrailingReturnType
.get();
4498 FunctionChunk
.TrailingReturnTypeLoc
= Range
.getBegin();
4500 SkipUntil({tok::equal
, tok::l_brace
, tok::arrow
, tok::kw_try
, tok::comma
},
4501 StopAtSemi
| StopBeforeMatch
);
4505 /// We have just started parsing the definition of a new class,
4506 /// so push that class onto our stack of classes that is currently
4508 Sema::ParsingClassState
Parser::PushParsingClass(Decl
*ClassDecl
,
4509 bool NonNestedClass
,
4511 assert((NonNestedClass
|| !ClassStack
.empty()) &&
4512 "Nested class without outer class");
4513 ClassStack
.push(new ParsingClass(ClassDecl
, NonNestedClass
, IsInterface
));
4514 return Actions
.PushParsingClass();
4517 /// Deallocate the given parsed class and all of its nested
4519 void Parser::DeallocateParsedClasses(Parser::ParsingClass
*Class
) {
4520 for (unsigned I
= 0, N
= Class
->LateParsedDeclarations
.size(); I
!= N
; ++I
)
4521 delete Class
->LateParsedDeclarations
[I
];
4525 /// Pop the top class of the stack of classes that are
4526 /// currently being parsed.
4528 /// This routine should be called when we have finished parsing the
4529 /// definition of a class, but have not yet popped the Scope
4530 /// associated with the class's definition.
4531 void Parser::PopParsingClass(Sema::ParsingClassState state
) {
4532 assert(!ClassStack
.empty() && "Mismatched push/pop for class parsing");
4534 Actions
.PopParsingClass(state
);
4536 ParsingClass
*Victim
= ClassStack
.top();
4538 if (Victim
->TopLevelClass
) {
4539 // Deallocate all of the nested classes of this class,
4540 // recursively: we don't need to keep any of this information.
4541 DeallocateParsedClasses(Victim
);
4544 assert(!ClassStack
.empty() && "Missing top-level class?");
4546 if (Victim
->LateParsedDeclarations
.empty()) {
4547 // The victim is a nested class, but we will not need to perform
4548 // any processing after the definition of this class since it has
4549 // no members whose handling was delayed. Therefore, we can just
4550 // remove this nested class.
4551 DeallocateParsedClasses(Victim
);
4555 // This nested class has some members that will need to be processed
4556 // after the top-level class is completely defined. Therefore, add
4557 // it to the list of nested classes within its parent.
4558 assert(getCurScope()->isClassScope() &&
4559 "Nested class outside of class scope?");
4560 ClassStack
.top()->LateParsedDeclarations
.push_back(
4561 new LateParsedClass(this, Victim
));
4564 /// Try to parse an 'identifier' which appears within an attribute-token.
4566 /// \return the parsed identifier on success, and 0 if the next token is not an
4567 /// attribute-token.
4569 /// C++11 [dcl.attr.grammar]p3:
4570 /// If a keyword or an alternative token that satisfies the syntactic
4571 /// requirements of an identifier is contained in an attribute-token,
4572 /// it is considered an identifier.
4573 IdentifierInfo
*Parser::TryParseCXX11AttributeIdentifier(
4574 SourceLocation
&Loc
, SemaCodeCompletion::AttributeCompletion Completion
,
4575 const IdentifierInfo
*Scope
) {
4576 switch (Tok
.getKind()) {
4578 // Identifiers and keywords have identifier info attached.
4579 if (!Tok
.isAnnotation()) {
4580 if (IdentifierInfo
*II
= Tok
.getIdentifierInfo()) {
4581 Loc
= ConsumeToken();
4587 case tok::code_completion
:
4589 Actions
.CodeCompletion().CodeCompleteAttribute(
4590 getLangOpts().CPlusPlus
? ParsedAttr::AS_CXX11
: ParsedAttr::AS_C23
,
4594 case tok::numeric_constant
: {
4595 // If we got a numeric constant, check to see if it comes from a macro that
4596 // corresponds to the predefined __clang__ macro. If it does, warn the user
4597 // and recover by pretending they said _Clang instead.
4598 if (Tok
.getLocation().isMacroID()) {
4599 SmallString
<8> ExpansionBuf
;
4600 SourceLocation ExpansionLoc
=
4601 PP
.getSourceManager().getExpansionLoc(Tok
.getLocation());
4602 StringRef Spelling
= PP
.getSpelling(ExpansionLoc
, ExpansionBuf
);
4603 if (Spelling
== "__clang__") {
4604 SourceRange
TokRange(
4606 PP
.getSourceManager().getExpansionLoc(Tok
.getEndLoc()));
4607 Diag(Tok
, diag::warn_wrong_clang_attr_namespace
)
4608 << FixItHint::CreateReplacement(TokRange
, "_Clang");
4609 Loc
= ConsumeToken();
4610 return &PP
.getIdentifierTable().get("_Clang");
4616 case tok::ampamp
: // 'and'
4617 case tok::pipe
: // 'bitor'
4618 case tok::pipepipe
: // 'or'
4619 case tok::caret
: // 'xor'
4620 case tok::tilde
: // 'compl'
4621 case tok::amp
: // 'bitand'
4622 case tok::ampequal
: // 'and_eq'
4623 case tok::pipeequal
: // 'or_eq'
4624 case tok::caretequal
: // 'xor_eq'
4625 case tok::exclaim
: // 'not'
4626 case tok::exclaimequal
: // 'not_eq'
4627 // Alternative tokens do not have identifier info, but their spelling
4628 // starts with an alphabetical character.
4629 SmallString
<8> SpellingBuf
;
4630 SourceLocation SpellingLoc
=
4631 PP
.getSourceManager().getSpellingLoc(Tok
.getLocation());
4632 StringRef Spelling
= PP
.getSpelling(SpellingLoc
, SpellingBuf
);
4633 if (isLetter(Spelling
[0])) {
4634 Loc
= ConsumeToken();
4635 return &PP
.getIdentifierTable().get(Spelling
);
4641 void Parser::ParseOpenMPAttributeArgs(const IdentifierInfo
*AttrName
,
4642 CachedTokens
&OpenMPTokens
) {
4643 // Both 'sequence' and 'directive' attributes require arguments, so parse the
4644 // open paren for the argument list.
4645 BalancedDelimiterTracker
T(*this, tok::l_paren
);
4646 if (T
.consumeOpen()) {
4647 Diag(Tok
, diag::err_expected
) << tok::l_paren
;
4651 if (AttrName
->isStr("directive")) {
4652 // If the attribute is named `directive`, we can consume its argument list
4653 // and push the tokens from it into the cached token stream for a new OpenMP
4654 // pragma directive.
4656 OMPBeginTok
.startToken();
4657 OMPBeginTok
.setKind(tok::annot_attr_openmp
);
4658 OMPBeginTok
.setLocation(Tok
.getLocation());
4659 OpenMPTokens
.push_back(OMPBeginTok
);
4661 ConsumeAndStoreUntil(tok::r_paren
, OpenMPTokens
, /*StopAtSemi=*/false,
4662 /*ConsumeFinalToken*/ false);
4664 OMPEndTok
.startToken();
4665 OMPEndTok
.setKind(tok::annot_pragma_openmp_end
);
4666 OMPEndTok
.setLocation(Tok
.getLocation());
4667 OpenMPTokens
.push_back(OMPEndTok
);
4669 assert(AttrName
->isStr("sequence") &&
4670 "Expected either 'directive' or 'sequence'");
4671 // If the attribute is named 'sequence', its argument is a list of one or
4672 // more OpenMP attributes (either 'omp::directive' or 'omp::sequence',
4673 // where the 'omp::' is optional).
4675 // We expect to see one of the following:
4676 // * An identifier (omp) for the attribute namespace followed by ::
4677 // * An identifier (directive) or an identifier (sequence).
4678 SourceLocation IdentLoc
;
4679 const IdentifierInfo
*Ident
= TryParseCXX11AttributeIdentifier(IdentLoc
);
4681 // If there is an identifier and it is 'omp', a double colon is required
4682 // followed by the actual identifier we're after.
4683 if (Ident
&& Ident
->isStr("omp") && !ExpectAndConsume(tok::coloncolon
))
4684 Ident
= TryParseCXX11AttributeIdentifier(IdentLoc
);
4686 // If we failed to find an identifier (scoped or otherwise), or we found
4687 // an unexpected identifier, diagnose.
4688 if (!Ident
|| (!Ident
->isStr("directive") && !Ident
->isStr("sequence"))) {
4689 Diag(Tok
.getLocation(), diag::err_expected_sequence_or_directive
);
4690 SkipUntil(tok::r_paren
, StopBeforeMatch
);
4693 // We read an identifier. If the identifier is one of the ones we
4694 // expected, we can recurse to parse the args.
4695 ParseOpenMPAttributeArgs(Ident
, OpenMPTokens
);
4697 // There may be a comma to signal that we expect another directive in the
4699 } while (TryConsumeToken(tok::comma
));
4701 // Parse the closing paren for the argument list.
4705 static bool IsBuiltInOrStandardCXX11Attribute(IdentifierInfo
*AttrName
,
4706 IdentifierInfo
*ScopeName
) {
4708 ParsedAttr::getParsedKind(AttrName
, ScopeName
, ParsedAttr::AS_CXX11
)) {
4709 case ParsedAttr::AT_CarriesDependency
:
4710 case ParsedAttr::AT_Deprecated
:
4711 case ParsedAttr::AT_FallThrough
:
4712 case ParsedAttr::AT_CXX11NoReturn
:
4713 case ParsedAttr::AT_NoUniqueAddress
:
4714 case ParsedAttr::AT_Likely
:
4715 case ParsedAttr::AT_Unlikely
:
4717 case ParsedAttr::AT_WarnUnusedResult
:
4718 return !ScopeName
&& AttrName
->getName() == "nodiscard";
4719 case ParsedAttr::AT_Unused
:
4720 return !ScopeName
&& AttrName
->getName() == "maybe_unused";
4726 /// Parse the argument to C++23's [[assume()]] attribute.
4727 bool Parser::ParseCXXAssumeAttributeArg(ParsedAttributes
&Attrs
,
4728 IdentifierInfo
*AttrName
,
4729 SourceLocation AttrNameLoc
,
4730 SourceLocation
*EndLoc
,
4731 ParsedAttr::Form Form
) {
4732 assert(Tok
.is(tok::l_paren
) && "Not a C++11 attribute argument list");
4733 BalancedDelimiterTracker
T(*this, tok::l_paren
);
4736 // [dcl.attr.assume]: The expression is potentially evaluated.
4737 EnterExpressionEvaluationContext
Unevaluated(
4738 Actions
, Sema::ExpressionEvaluationContext::PotentiallyEvaluated
);
4740 TentativeParsingAction
TPA(*this);
4742 Actions
.CorrectDelayedTyposInExpr(ParseConditionalExpression()));
4743 if (Res
.isInvalid()) {
4745 SkipUntil(tok::r_paren
, tok::r_square
, StopAtSemi
| StopBeforeMatch
);
4746 if (Tok
.is(tok::r_paren
))
4751 if (!Tok
.isOneOf(tok::r_paren
, tok::r_square
)) {
4752 // Emit a better diagnostic if this is an otherwise valid expression that
4753 // is not allowed here.
4755 Res
= ParseExpression();
4756 if (!Res
.isInvalid()) {
4757 auto *E
= Res
.get();
4758 Diag(E
->getExprLoc(), diag::err_assume_attr_expects_cond_expr
)
4759 << AttrName
<< FixItHint::CreateInsertion(E
->getBeginLoc(), "(")
4760 << FixItHint::CreateInsertion(PP
.getLocForEndOfToken(E
->getEndLoc()),
4762 << E
->getSourceRange();
4770 ArgsUnion Assumption
= Res
.get();
4771 auto RParen
= Tok
.getLocation();
4773 Attrs
.addNew(AttrName
, SourceRange(AttrNameLoc
, RParen
), nullptr,
4774 SourceLocation(), &Assumption
, 1, Form
);
4782 /// ParseCXX11AttributeArgs -- Parse a C++11 attribute-argument-clause.
4784 /// [C++11] attribute-argument-clause:
4785 /// '(' balanced-token-seq ')'
4787 /// [C++11] balanced-token-seq:
4789 /// balanced-token-seq balanced-token
4791 /// [C++11] balanced-token:
4792 /// '(' balanced-token-seq ')'
4793 /// '[' balanced-token-seq ']'
4794 /// '{' balanced-token-seq '}'
4795 /// any token but '(', ')', '[', ']', '{', or '}'
4796 bool Parser::ParseCXX11AttributeArgs(
4797 IdentifierInfo
*AttrName
, SourceLocation AttrNameLoc
,
4798 ParsedAttributes
&Attrs
, SourceLocation
*EndLoc
, IdentifierInfo
*ScopeName
,
4799 SourceLocation ScopeLoc
, CachedTokens
&OpenMPTokens
) {
4800 assert(Tok
.is(tok::l_paren
) && "Not a C++11 attribute argument list");
4801 SourceLocation LParenLoc
= Tok
.getLocation();
4802 const LangOptions
&LO
= getLangOpts();
4803 ParsedAttr::Form Form
=
4804 LO
.CPlusPlus
? ParsedAttr::Form::CXX11() : ParsedAttr::Form::C23();
4806 // Try parsing microsoft attributes
4807 if (getLangOpts().MicrosoftExt
|| getLangOpts().HLSL
) {
4808 if (hasAttribute(AttributeCommonInfo::Syntax::AS_Microsoft
, ScopeName
,
4809 AttrName
, getTargetInfo(), getLangOpts()))
4810 Form
= ParsedAttr::Form::Microsoft();
4813 // If the attribute isn't known, we will not attempt to parse any
4815 if (Form
.getSyntax() != ParsedAttr::AS_Microsoft
&&
4816 !hasAttribute(LO
.CPlusPlus
? AttributeCommonInfo::Syntax::AS_CXX11
4817 : AttributeCommonInfo::Syntax::AS_C23
,
4818 ScopeName
, AttrName
, getTargetInfo(), getLangOpts())) {
4819 // Eat the left paren, then skip to the ending right paren.
4821 SkipUntil(tok::r_paren
);
4825 if (ScopeName
&& (ScopeName
->isStr("gnu") || ScopeName
->isStr("__gnu__"))) {
4826 // GNU-scoped attributes have some special cases to handle GNU-specific
4828 ParseGNUAttributeArgs(AttrName
, AttrNameLoc
, Attrs
, EndLoc
, ScopeName
,
4829 ScopeLoc
, Form
, nullptr);
4833 // [[omp::directive]] and [[omp::sequence]] need special handling.
4834 if (ScopeName
&& ScopeName
->isStr("omp") &&
4835 (AttrName
->isStr("directive") || AttrName
->isStr("sequence"))) {
4836 Diag(AttrNameLoc
, getLangOpts().OpenMP
>= 51
4837 ? diag::warn_omp51_compat_attributes
4838 : diag::ext_omp_attributes
);
4840 ParseOpenMPAttributeArgs(AttrName
, OpenMPTokens
);
4842 // We claim that an attribute was parsed and added so that one is not
4843 // created for us by the caller.
4848 // Some Clang-scoped attributes have some special parsing behavior.
4849 if (ScopeName
&& (ScopeName
->isStr("clang") || ScopeName
->isStr("_Clang")))
4850 NumArgs
= ParseClangAttributeArgs(AttrName
, AttrNameLoc
, Attrs
, EndLoc
,
4851 ScopeName
, ScopeLoc
, Form
);
4852 // So does C++23's assume() attribute.
4853 else if (!ScopeName
&& AttrName
->isStr("assume")) {
4854 if (ParseCXXAssumeAttributeArg(Attrs
, AttrName
, AttrNameLoc
, EndLoc
, Form
))
4858 NumArgs
= ParseAttributeArgsCommon(AttrName
, AttrNameLoc
, Attrs
, EndLoc
,
4859 ScopeName
, ScopeLoc
, Form
);
4861 if (!Attrs
.empty() &&
4862 IsBuiltInOrStandardCXX11Attribute(AttrName
, ScopeName
)) {
4863 ParsedAttr
&Attr
= Attrs
.back();
4865 // Ignore attributes that don't exist for the target.
4866 if (!Attr
.existsInTarget(getTargetInfo())) {
4867 Diag(LParenLoc
, diag::warn_unknown_attribute_ignored
) << AttrName
;
4868 Attr
.setInvalid(true);
4872 // If the attribute is a standard or built-in attribute and we are
4873 // parsing an argument list, we need to determine whether this attribute
4874 // was allowed to have an argument list (such as [[deprecated]]), and how
4875 // many arguments were parsed (so we can diagnose on [[deprecated()]]).
4876 if (Attr
.getMaxArgs() && !NumArgs
) {
4877 // The attribute was allowed to have arguments, but none were provided
4878 // even though the attribute parsed successfully. This is an error.
4879 Diag(LParenLoc
, diag::err_attribute_requires_arguments
) << AttrName
;
4880 Attr
.setInvalid(true);
4881 } else if (!Attr
.getMaxArgs()) {
4882 // The attribute parsed successfully, but was not allowed to have any
4883 // arguments. It doesn't matter whether any were provided -- the
4884 // presence of the argument list (even if empty) is diagnosed.
4885 Diag(LParenLoc
, diag::err_cxx11_attribute_forbids_arguments
)
4887 << FixItHint::CreateRemoval(SourceRange(LParenLoc
, *EndLoc
));
4888 Attr
.setInvalid(true);
4894 /// Parse a C++11 or C23 attribute-specifier.
4896 /// [C++11] attribute-specifier:
4897 /// '[' '[' attribute-list ']' ']'
4898 /// alignment-specifier
4900 /// [C++11] attribute-list:
4902 /// attribute-list ',' attribute[opt]
4904 /// attribute-list ',' attribute '...'
4906 /// [C++11] attribute:
4907 /// attribute-token attribute-argument-clause[opt]
4909 /// [C++11] attribute-token:
4911 /// attribute-scoped-token
4913 /// [C++11] attribute-scoped-token:
4914 /// attribute-namespace '::' identifier
4916 /// [C++11] attribute-namespace:
4918 void Parser::ParseCXX11AttributeSpecifierInternal(ParsedAttributes
&Attrs
,
4919 CachedTokens
&OpenMPTokens
,
4920 SourceLocation
*EndLoc
) {
4921 if (Tok
.is(tok::kw_alignas
)) {
4922 // alignas is a valid token in C23 but it is not an attribute, it's a type-
4923 // specifier-qualifier, which means it has different parsing behavior. We
4924 // handle this in ParseDeclarationSpecifiers() instead of here in C. We
4925 // should not get here for C any longer.
4926 assert(getLangOpts().CPlusPlus
&& "'alignas' is not an attribute in C");
4927 Diag(Tok
.getLocation(), diag::warn_cxx98_compat_alignas
);
4928 ParseAlignmentSpecifier(Attrs
, EndLoc
);
4932 if (Tok
.isRegularKeywordAttribute()) {
4933 SourceLocation Loc
= Tok
.getLocation();
4934 IdentifierInfo
*AttrName
= Tok
.getIdentifierInfo();
4935 ParsedAttr::Form Form
= ParsedAttr::Form(Tok
.getKind());
4936 bool TakesArgs
= doesKeywordAttributeTakeArgs(Tok
.getKind());
4939 if (!Tok
.is(tok::l_paren
))
4940 Diag(Tok
.getLocation(), diag::err_expected_lparen_after
) << AttrName
;
4942 ParseAttributeArgsCommon(AttrName
, Loc
, Attrs
, EndLoc
,
4943 /*ScopeName*/ nullptr,
4944 /*ScopeLoc*/ Loc
, Form
);
4946 Attrs
.addNew(AttrName
, Loc
, nullptr, Loc
, nullptr, 0, Form
);
4950 assert(Tok
.is(tok::l_square
) && NextToken().is(tok::l_square
) &&
4951 "Not a double square bracket attribute list");
4953 SourceLocation OpenLoc
= Tok
.getLocation();
4954 if (getLangOpts().CPlusPlus
) {
4955 Diag(OpenLoc
, getLangOpts().CPlusPlus11
? diag::warn_cxx98_compat_attribute
4956 : diag::warn_ext_cxx11_attributes
);
4958 Diag(OpenLoc
, getLangOpts().C23
? diag::warn_pre_c23_compat_attributes
4959 : diag::warn_ext_c23_attributes
);
4963 checkCompoundToken(OpenLoc
, tok::l_square
, CompoundToken::AttrBegin
);
4966 SourceLocation CommonScopeLoc
;
4967 IdentifierInfo
*CommonScopeName
= nullptr;
4968 if (Tok
.is(tok::kw_using
)) {
4969 Diag(Tok
.getLocation(), getLangOpts().CPlusPlus17
4970 ? diag::warn_cxx14_compat_using_attribute_ns
4971 : diag::ext_using_attribute_ns
);
4974 CommonScopeName
= TryParseCXX11AttributeIdentifier(
4975 CommonScopeLoc
, SemaCodeCompletion::AttributeCompletion::Scope
);
4976 if (!CommonScopeName
) {
4977 Diag(Tok
.getLocation(), diag::err_expected
) << tok::identifier
;
4978 SkipUntil(tok::r_square
, tok::colon
, StopBeforeMatch
);
4980 if (!TryConsumeToken(tok::colon
) && CommonScopeName
)
4981 Diag(Tok
.getLocation(), diag::err_expected
) << tok::colon
;
4984 bool AttrParsed
= false;
4985 while (!Tok
.isOneOf(tok::r_square
, tok::semi
, tok::eof
)) {
4987 // If we parsed an attribute, a comma is required before parsing any
4988 // additional attributes.
4989 if (ExpectAndConsume(tok::comma
)) {
4990 SkipUntil(tok::r_square
, StopAtSemi
| StopBeforeMatch
);
4996 // Eat all remaining superfluous commas before parsing the next attribute.
4997 while (TryConsumeToken(tok::comma
))
5000 SourceLocation ScopeLoc
, AttrLoc
;
5001 IdentifierInfo
*ScopeName
= nullptr, *AttrName
= nullptr;
5003 AttrName
= TryParseCXX11AttributeIdentifier(
5004 AttrLoc
, SemaCodeCompletion::AttributeCompletion::Attribute
,
5007 // Break out to the "expected ']'" diagnostic.
5011 if (TryConsumeToken(tok::coloncolon
)) {
5012 ScopeName
= AttrName
;
5015 AttrName
= TryParseCXX11AttributeIdentifier(
5016 AttrLoc
, SemaCodeCompletion::AttributeCompletion::Attribute
,
5019 Diag(Tok
.getLocation(), diag::err_expected
) << tok::identifier
;
5020 SkipUntil(tok::r_square
, tok::comma
, StopAtSemi
| StopBeforeMatch
);
5025 if (CommonScopeName
) {
5027 Diag(ScopeLoc
, diag::err_using_attribute_ns_conflict
)
5028 << SourceRange(CommonScopeLoc
);
5030 ScopeName
= CommonScopeName
;
5031 ScopeLoc
= CommonScopeLoc
;
5035 // Parse attribute arguments
5036 if (Tok
.is(tok::l_paren
))
5037 AttrParsed
= ParseCXX11AttributeArgs(AttrName
, AttrLoc
, Attrs
, EndLoc
,
5038 ScopeName
, ScopeLoc
, OpenMPTokens
);
5043 SourceRange(ScopeLoc
.isValid() ? ScopeLoc
: AttrLoc
, AttrLoc
),
5044 ScopeName
, ScopeLoc
, nullptr, 0,
5045 getLangOpts().CPlusPlus
? ParsedAttr::Form::CXX11()
5046 : ParsedAttr::Form::C23());
5050 if (TryConsumeToken(tok::ellipsis
))
5051 Diag(Tok
, diag::err_cxx11_attribute_forbids_ellipsis
) << AttrName
;
5054 // If we hit an error and recovered by parsing up to a semicolon, eat the
5055 // semicolon and don't issue further diagnostics about missing brackets.
5056 if (Tok
.is(tok::semi
)) {
5061 SourceLocation CloseLoc
= Tok
.getLocation();
5062 if (ExpectAndConsume(tok::r_square
))
5063 SkipUntil(tok::r_square
);
5064 else if (Tok
.is(tok::r_square
))
5065 checkCompoundToken(CloseLoc
, tok::r_square
, CompoundToken::AttrEnd
);
5067 *EndLoc
= Tok
.getLocation();
5068 if (ExpectAndConsume(tok::r_square
))
5069 SkipUntil(tok::r_square
);
5072 /// ParseCXX11Attributes - Parse a C++11 or C23 attribute-specifier-seq.
5074 /// attribute-specifier-seq:
5075 /// attribute-specifier-seq[opt] attribute-specifier
5076 void Parser::ParseCXX11Attributes(ParsedAttributes
&Attrs
) {
5077 SourceLocation StartLoc
= Tok
.getLocation();
5078 SourceLocation EndLoc
= StartLoc
;
5081 ParseCXX11AttributeSpecifier(Attrs
, &EndLoc
);
5082 } while (isAllowedCXX11AttributeSpecifier());
5084 Attrs
.Range
= SourceRange(StartLoc
, EndLoc
);
5087 void Parser::DiagnoseAndSkipCXX11Attributes() {
5089 Tok
.isRegularKeywordAttribute() ? Tok
.getIdentifierInfo() : nullptr;
5090 // Start and end location of an attribute or an attribute list.
5091 SourceLocation StartLoc
= Tok
.getLocation();
5092 SourceLocation EndLoc
= SkipCXX11Attributes();
5094 if (EndLoc
.isValid()) {
5095 SourceRange
Range(StartLoc
, EndLoc
);
5096 (Keyword
? Diag(StartLoc
, diag::err_keyword_not_allowed
) << Keyword
5097 : Diag(StartLoc
, diag::err_attributes_not_allowed
))
5102 SourceLocation
Parser::SkipCXX11Attributes() {
5103 SourceLocation EndLoc
;
5105 if (!isCXX11AttributeSpecifier())
5109 if (Tok
.is(tok::l_square
)) {
5110 BalancedDelimiterTracker
T(*this, tok::l_square
);
5113 EndLoc
= T
.getCloseLocation();
5114 } else if (Tok
.isRegularKeywordAttribute() &&
5115 !doesKeywordAttributeTakeArgs(Tok
.getKind())) {
5116 EndLoc
= Tok
.getLocation();
5119 assert((Tok
.is(tok::kw_alignas
) || Tok
.isRegularKeywordAttribute()) &&
5120 "not an attribute specifier");
5122 BalancedDelimiterTracker
T(*this, tok::l_paren
);
5123 if (!T
.consumeOpen())
5125 EndLoc
= T
.getCloseLocation();
5127 } while (isCXX11AttributeSpecifier());
5132 /// Parse uuid() attribute when it appears in a [] Microsoft attribute.
5133 void Parser::ParseMicrosoftUuidAttributeArgs(ParsedAttributes
&Attrs
) {
5134 assert(Tok
.is(tok::identifier
) && "Not a Microsoft attribute list");
5135 IdentifierInfo
*UuidIdent
= Tok
.getIdentifierInfo();
5136 assert(UuidIdent
->getName() == "uuid" && "Not a Microsoft attribute list");
5138 SourceLocation UuidLoc
= Tok
.getLocation();
5141 // Ignore the left paren location for now.
5142 BalancedDelimiterTracker
T(*this, tok::l_paren
);
5143 if (T
.consumeOpen()) {
5144 Diag(Tok
, diag::err_expected
) << tok::l_paren
;
5148 ArgsVector ArgExprs
;
5149 if (isTokenStringLiteral()) {
5150 // Easy case: uuid("...") -- quoted string.
5151 ExprResult StringResult
= ParseUnevaluatedStringLiteralExpression();
5152 if (StringResult
.isInvalid())
5154 ArgExprs
.push_back(StringResult
.get());
5156 // something like uuid({000000A0-0000-0000-C000-000000000049}) -- no
5157 // quotes in the parens. Just append the spelling of all tokens encountered
5158 // until the closing paren.
5160 SmallString
<42> StrBuffer
; // 2 "", 36 bytes UUID, 2 optional {}, 1 nul
5163 // Since none of C++'s keywords match [a-f]+, accepting just tok::l_brace,
5164 // tok::r_brace, tok::minus, tok::identifier (think C000) and
5165 // tok::numeric_constant (0000) should be enough. But the spelling of the
5166 // uuid argument is checked later anyways, so there's no harm in accepting
5167 // almost anything here.
5168 // cl is very strict about whitespace in this form and errors out if any
5169 // is present, so check the space flags on the tokens.
5170 SourceLocation StartLoc
= Tok
.getLocation();
5171 while (Tok
.isNot(tok::r_paren
)) {
5172 if (Tok
.hasLeadingSpace() || Tok
.isAtStartOfLine()) {
5173 Diag(Tok
, diag::err_attribute_uuid_malformed_guid
);
5174 SkipUntil(tok::r_paren
, StopAtSemi
);
5177 SmallString
<16> SpellingBuffer
;
5178 SpellingBuffer
.resize(Tok
.getLength() + 1);
5179 bool Invalid
= false;
5180 StringRef TokSpelling
= PP
.getSpelling(Tok
, SpellingBuffer
, &Invalid
);
5182 SkipUntil(tok::r_paren
, StopAtSemi
);
5185 StrBuffer
+= TokSpelling
;
5190 if (Tok
.hasLeadingSpace() || Tok
.isAtStartOfLine()) {
5191 Diag(Tok
, diag::err_attribute_uuid_malformed_guid
);
5196 // Pretend the user wrote the appropriate string literal here.
5197 // ActOnStringLiteral() copies the string data into the literal, so it's
5198 // ok that the Token points to StrBuffer.
5200 Toks
[0].startToken();
5201 Toks
[0].setKind(tok::string_literal
);
5202 Toks
[0].setLocation(StartLoc
);
5203 Toks
[0].setLiteralData(StrBuffer
.data());
5204 Toks
[0].setLength(StrBuffer
.size());
5205 StringLiteral
*UuidString
=
5206 cast
<StringLiteral
>(Actions
.ActOnUnevaluatedStringLiteral(Toks
).get());
5207 ArgExprs
.push_back(UuidString
);
5210 if (!T
.consumeClose()) {
5211 Attrs
.addNew(UuidIdent
, SourceRange(UuidLoc
, T
.getCloseLocation()), nullptr,
5212 SourceLocation(), ArgExprs
.data(), ArgExprs
.size(),
5213 ParsedAttr::Form::Microsoft());
5217 /// ParseMicrosoftAttributes - Parse Microsoft attributes [Attr]
5219 /// [MS] ms-attribute:
5220 /// '[' token-seq ']'
5222 /// [MS] ms-attribute-seq:
5223 /// ms-attribute[opt]
5224 /// ms-attribute ms-attribute-seq
5225 void Parser::ParseMicrosoftAttributes(ParsedAttributes
&Attrs
) {
5226 assert(Tok
.is(tok::l_square
) && "Not a Microsoft attribute list");
5228 SourceLocation StartLoc
= Tok
.getLocation();
5229 SourceLocation EndLoc
= StartLoc
;
5231 // FIXME: If this is actually a C++11 attribute, parse it as one.
5232 BalancedDelimiterTracker
T(*this, tok::l_square
);
5235 // Skip most ms attributes except for a specific list.
5237 SkipUntil(tok::r_square
, tok::identifier
,
5238 StopAtSemi
| StopBeforeMatch
| StopAtCodeCompletion
);
5239 if (Tok
.is(tok::code_completion
)) {
5241 Actions
.CodeCompletion().CodeCompleteAttribute(
5242 AttributeCommonInfo::AS_Microsoft
,
5243 SemaCodeCompletion::AttributeCompletion::Attribute
,
5247 if (Tok
.isNot(tok::identifier
)) // ']', but also eof
5249 if (Tok
.getIdentifierInfo()->getName() == "uuid")
5250 ParseMicrosoftUuidAttributeArgs(Attrs
);
5252 IdentifierInfo
*II
= Tok
.getIdentifierInfo();
5253 SourceLocation NameLoc
= Tok
.getLocation();
5255 ParsedAttr::Kind AttrKind
=
5256 ParsedAttr::getParsedKind(II
, nullptr, ParsedAttr::AS_Microsoft
);
5257 // For HLSL we want to handle all attributes, but for MSVC compat, we
5258 // silently ignore unknown Microsoft attributes.
5259 if (getLangOpts().HLSL
|| AttrKind
!= ParsedAttr::UnknownAttribute
) {
5260 bool AttrParsed
= false;
5261 if (Tok
.is(tok::l_paren
)) {
5262 CachedTokens OpenMPTokens
;
5264 ParseCXX11AttributeArgs(II
, NameLoc
, Attrs
, &EndLoc
, nullptr,
5265 SourceLocation(), OpenMPTokens
);
5266 ReplayOpenMPAttributeTokens(OpenMPTokens
);
5269 Attrs
.addNew(II
, NameLoc
, nullptr, SourceLocation(), nullptr, 0,
5270 ParsedAttr::Form::Microsoft());
5277 EndLoc
= T
.getCloseLocation();
5278 } while (Tok
.is(tok::l_square
));
5280 Attrs
.Range
= SourceRange(StartLoc
, EndLoc
);
5283 void Parser::ParseMicrosoftIfExistsClassDeclaration(
5284 DeclSpec::TST TagType
, ParsedAttributes
&AccessAttrs
,
5285 AccessSpecifier
&CurAS
) {
5286 IfExistsCondition Result
;
5287 if (ParseMicrosoftIfExistsCondition(Result
))
5290 BalancedDelimiterTracker
Braces(*this, tok::l_brace
);
5291 if (Braces
.consumeOpen()) {
5292 Diag(Tok
, diag::err_expected
) << tok::l_brace
;
5296 switch (Result
.Behavior
) {
5298 // Parse the declarations below.
5302 Diag(Result
.KeywordLoc
, diag::warn_microsoft_dependent_exists
)
5303 << Result
.IsIfExists
;
5304 // Fall through to skip.
5312 while (Tok
.isNot(tok::r_brace
) && !isEofOrEom()) {
5313 // __if_exists, __if_not_exists can nest.
5314 if (Tok
.isOneOf(tok::kw___if_exists
, tok::kw___if_not_exists
)) {
5315 ParseMicrosoftIfExistsClassDeclaration(TagType
, AccessAttrs
, CurAS
);
5319 // Check for extraneous top-level semicolon.
5320 if (Tok
.is(tok::semi
)) {
5321 ConsumeExtraSemi(InsideStruct
, TagType
);
5325 AccessSpecifier AS
= getAccessSpecifierIfPresent();
5326 if (AS
!= AS_none
) {
5327 // Current token is a C++ access specifier.
5329 SourceLocation ASLoc
= Tok
.getLocation();
5331 if (Tok
.is(tok::colon
))
5332 Actions
.ActOnAccessSpecifier(AS
, ASLoc
, Tok
.getLocation(),
5333 ParsedAttributesView
{});
5335 Diag(Tok
, diag::err_expected
) << tok::colon
;
5340 ParsedTemplateInfo TemplateInfo
;
5341 // Parse all the comma separated declarators.
5342 ParseCXXClassMemberDeclaration(CurAS
, AccessAttrs
, TemplateInfo
);
5345 Braces
.consumeClose();