[docs] Fix build-docs.sh
[llvm-project.git] / clang / lib / Parse / ParseDeclCXX.cpp
blobd0bf89799c258f2d83f432f6dbef138b8a41b3aa
1 //===--- ParseDeclCXX.cpp - C++ Declaration Parsing -------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the C++ Declaration portions of the Parser interfaces.
11 //===----------------------------------------------------------------------===//
13 #include "clang/AST/ASTContext.h"
14 #include "clang/AST/DeclTemplate.h"
15 #include "clang/AST/PrettyDeclStackTrace.h"
16 #include "clang/Basic/AttributeCommonInfo.h"
17 #include "clang/Basic/Attributes.h"
18 #include "clang/Basic/CharInfo.h"
19 #include "clang/Basic/OperatorKinds.h"
20 #include "clang/Basic/TargetInfo.h"
21 #include "clang/Basic/TokenKinds.h"
22 #include "clang/Parse/ParseDiagnostic.h"
23 #include "clang/Parse/Parser.h"
24 #include "clang/Parse/RAIIObjectsForParser.h"
25 #include "clang/Sema/DeclSpec.h"
26 #include "clang/Sema/ParsedTemplate.h"
27 #include "clang/Sema/Scope.h"
28 #include "llvm/ADT/SmallString.h"
29 #include "llvm/Support/TimeProfiler.h"
31 using namespace clang;
33 /// ParseNamespace - We know that the current token is a namespace keyword. This
34 /// may either be a top level namespace or a block-level namespace alias. If
35 /// there was an inline keyword, it has already been parsed.
36 ///
37 /// namespace-definition: [C++: namespace.def]
38 /// named-namespace-definition
39 /// unnamed-namespace-definition
40 /// nested-namespace-definition
41 ///
42 /// named-namespace-definition:
43 /// 'inline'[opt] 'namespace' attributes[opt] identifier '{'
44 /// namespace-body '}'
45 ///
46 /// unnamed-namespace-definition:
47 /// 'inline'[opt] 'namespace' attributes[opt] '{' namespace-body '}'
48 ///
49 /// nested-namespace-definition:
50 /// 'namespace' enclosing-namespace-specifier '::' 'inline'[opt]
51 /// identifier '{' namespace-body '}'
52 ///
53 /// enclosing-namespace-specifier:
54 /// identifier
55 /// enclosing-namespace-specifier '::' 'inline'[opt] identifier
56 ///
57 /// namespace-alias-definition: [C++ 7.3.2: namespace.alias]
58 /// 'namespace' identifier '=' qualified-namespace-specifier ';'
59 ///
60 Parser::DeclGroupPtrTy Parser::ParseNamespace(DeclaratorContext Context,
61 SourceLocation &DeclEnd,
62 SourceLocation InlineLoc) {
63 assert(Tok.is(tok::kw_namespace) && "Not a namespace!");
64 SourceLocation NamespaceLoc = ConsumeToken(); // eat the 'namespace'.
65 ObjCDeclContextSwitch ObjCDC(*this);
67 if (Tok.is(tok::code_completion)) {
68 cutOffParsing();
69 Actions.CodeCompleteNamespaceDecl(getCurScope());
70 return nullptr;
73 SourceLocation IdentLoc;
74 IdentifierInfo *Ident = nullptr;
75 InnerNamespaceInfoList ExtraNSs;
76 SourceLocation FirstNestedInlineLoc;
78 ParsedAttributes attrs(AttrFactory);
80 auto ReadAttributes = [&] {
81 bool MoreToParse;
82 do {
83 MoreToParse = false;
84 if (Tok.is(tok::kw___attribute)) {
85 ParseGNUAttributes(attrs);
86 MoreToParse = true;
88 if (getLangOpts().CPlusPlus11 && isCXX11AttributeSpecifier()) {
89 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
90 ? diag::warn_cxx14_compat_ns_enum_attribute
91 : diag::ext_ns_enum_attribute)
92 << 0 /*namespace*/;
93 ParseCXX11Attributes(attrs);
94 MoreToParse = true;
96 } while (MoreToParse);
99 ReadAttributes();
101 if (Tok.is(tok::identifier)) {
102 Ident = Tok.getIdentifierInfo();
103 IdentLoc = ConsumeToken(); // eat the identifier.
104 while (Tok.is(tok::coloncolon) &&
105 (NextToken().is(tok::identifier) ||
106 (NextToken().is(tok::kw_inline) &&
107 GetLookAheadToken(2).is(tok::identifier)))) {
109 InnerNamespaceInfo Info;
110 Info.NamespaceLoc = ConsumeToken();
112 if (Tok.is(tok::kw_inline)) {
113 Info.InlineLoc = ConsumeToken();
114 if (FirstNestedInlineLoc.isInvalid())
115 FirstNestedInlineLoc = Info.InlineLoc;
118 Info.Ident = Tok.getIdentifierInfo();
119 Info.IdentLoc = ConsumeToken();
121 ExtraNSs.push_back(Info);
125 ReadAttributes();
127 SourceLocation attrLoc = attrs.Range.getBegin();
129 // A nested namespace definition cannot have attributes.
130 if (!ExtraNSs.empty() && attrLoc.isValid())
131 Diag(attrLoc, diag::err_unexpected_nested_namespace_attribute);
133 if (Tok.is(tok::equal)) {
134 if (!Ident) {
135 Diag(Tok, diag::err_expected) << tok::identifier;
136 // Skip to end of the definition and eat the ';'.
137 SkipUntil(tok::semi);
138 return nullptr;
140 if (attrLoc.isValid())
141 Diag(attrLoc, diag::err_unexpected_namespace_attributes_alias);
142 if (InlineLoc.isValid())
143 Diag(InlineLoc, diag::err_inline_namespace_alias)
144 << FixItHint::CreateRemoval(InlineLoc);
145 Decl *NSAlias = ParseNamespaceAlias(NamespaceLoc, IdentLoc, Ident, DeclEnd);
146 return Actions.ConvertDeclToDeclGroup(NSAlias);
149 BalancedDelimiterTracker T(*this, tok::l_brace);
150 if (T.consumeOpen()) {
151 if (Ident)
152 Diag(Tok, diag::err_expected) << tok::l_brace;
153 else
154 Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace;
155 return nullptr;
158 if (getCurScope()->isClassScope() || getCurScope()->isTemplateParamScope() ||
159 getCurScope()->isInObjcMethodScope() || getCurScope()->getBlockParent() ||
160 getCurScope()->getFnParent()) {
161 Diag(T.getOpenLocation(), diag::err_namespace_nonnamespace_scope);
162 SkipUntil(tok::r_brace);
163 return nullptr;
166 if (ExtraNSs.empty()) {
167 // Normal namespace definition, not a nested-namespace-definition.
168 } else if (InlineLoc.isValid()) {
169 Diag(InlineLoc, diag::err_inline_nested_namespace_definition);
170 } else if (getLangOpts().CPlusPlus20) {
171 Diag(ExtraNSs[0].NamespaceLoc,
172 diag::warn_cxx14_compat_nested_namespace_definition);
173 if (FirstNestedInlineLoc.isValid())
174 Diag(FirstNestedInlineLoc,
175 diag::warn_cxx17_compat_inline_nested_namespace_definition);
176 } else if (getLangOpts().CPlusPlus17) {
177 Diag(ExtraNSs[0].NamespaceLoc,
178 diag::warn_cxx14_compat_nested_namespace_definition);
179 if (FirstNestedInlineLoc.isValid())
180 Diag(FirstNestedInlineLoc, diag::ext_inline_nested_namespace_definition);
181 } else {
182 TentativeParsingAction TPA(*this);
183 SkipUntil(tok::r_brace, StopBeforeMatch);
184 Token rBraceToken = Tok;
185 TPA.Revert();
187 if (!rBraceToken.is(tok::r_brace)) {
188 Diag(ExtraNSs[0].NamespaceLoc, diag::ext_nested_namespace_definition)
189 << SourceRange(ExtraNSs.front().NamespaceLoc,
190 ExtraNSs.back().IdentLoc);
191 } else {
192 std::string NamespaceFix;
193 for (const auto &ExtraNS : ExtraNSs) {
194 NamespaceFix += " { ";
195 if (ExtraNS.InlineLoc.isValid())
196 NamespaceFix += "inline ";
197 NamespaceFix += "namespace ";
198 NamespaceFix += ExtraNS.Ident->getName();
201 std::string RBraces;
202 for (unsigned i = 0, e = ExtraNSs.size(); i != e; ++i)
203 RBraces += "} ";
205 Diag(ExtraNSs[0].NamespaceLoc, diag::ext_nested_namespace_definition)
206 << FixItHint::CreateReplacement(
207 SourceRange(ExtraNSs.front().NamespaceLoc,
208 ExtraNSs.back().IdentLoc),
209 NamespaceFix)
210 << FixItHint::CreateInsertion(rBraceToken.getLocation(), RBraces);
213 // Warn about nested inline namespaces.
214 if (FirstNestedInlineLoc.isValid())
215 Diag(FirstNestedInlineLoc, diag::ext_inline_nested_namespace_definition);
218 // If we're still good, complain about inline namespaces in non-C++0x now.
219 if (InlineLoc.isValid())
220 Diag(InlineLoc, getLangOpts().CPlusPlus11
221 ? diag::warn_cxx98_compat_inline_namespace
222 : diag::ext_inline_namespace);
224 // Enter a scope for the namespace.
225 ParseScope NamespaceScope(this, Scope::DeclScope);
227 UsingDirectiveDecl *ImplicitUsingDirectiveDecl = nullptr;
228 Decl *NamespcDecl = Actions.ActOnStartNamespaceDef(
229 getCurScope(), InlineLoc, NamespaceLoc, IdentLoc, Ident,
230 T.getOpenLocation(), attrs, ImplicitUsingDirectiveDecl);
232 PrettyDeclStackTraceEntry CrashInfo(Actions.Context, NamespcDecl,
233 NamespaceLoc, "parsing namespace");
235 // Parse the contents of the namespace. This includes parsing recovery on
236 // any improperly nested namespaces.
237 ParseInnerNamespace(ExtraNSs, 0, InlineLoc, attrs, T);
239 // Leave the namespace scope.
240 NamespaceScope.Exit();
242 DeclEnd = T.getCloseLocation();
243 Actions.ActOnFinishNamespaceDef(NamespcDecl, DeclEnd);
245 return Actions.ConvertDeclToDeclGroup(NamespcDecl,
246 ImplicitUsingDirectiveDecl);
249 /// ParseInnerNamespace - Parse the contents of a namespace.
250 void Parser::ParseInnerNamespace(const InnerNamespaceInfoList &InnerNSs,
251 unsigned int index, SourceLocation &InlineLoc,
252 ParsedAttributes &attrs,
253 BalancedDelimiterTracker &Tracker) {
254 if (index == InnerNSs.size()) {
255 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
256 Tok.isNot(tok::eof)) {
257 ParsedAttributes Attrs(AttrFactory);
258 MaybeParseCXX11Attributes(Attrs);
259 ParseExternalDeclaration(Attrs);
262 // The caller is what called check -- we are simply calling
263 // the close for it.
264 Tracker.consumeClose();
266 return;
269 // Handle a nested namespace definition.
270 // FIXME: Preserve the source information through to the AST rather than
271 // desugaring it here.
272 ParseScope NamespaceScope(this, Scope::DeclScope);
273 UsingDirectiveDecl *ImplicitUsingDirectiveDecl = nullptr;
274 Decl *NamespcDecl = Actions.ActOnStartNamespaceDef(
275 getCurScope(), InnerNSs[index].InlineLoc, InnerNSs[index].NamespaceLoc,
276 InnerNSs[index].IdentLoc, InnerNSs[index].Ident,
277 Tracker.getOpenLocation(), attrs, ImplicitUsingDirectiveDecl);
278 assert(!ImplicitUsingDirectiveDecl &&
279 "nested namespace definition cannot define anonymous namespace");
281 ParseInnerNamespace(InnerNSs, ++index, InlineLoc, attrs, Tracker);
283 NamespaceScope.Exit();
284 Actions.ActOnFinishNamespaceDef(NamespcDecl, Tracker.getCloseLocation());
287 /// ParseNamespaceAlias - Parse the part after the '=' in a namespace
288 /// alias definition.
290 Decl *Parser::ParseNamespaceAlias(SourceLocation NamespaceLoc,
291 SourceLocation AliasLoc,
292 IdentifierInfo *Alias,
293 SourceLocation &DeclEnd) {
294 assert(Tok.is(tok::equal) && "Not equal token");
296 ConsumeToken(); // eat the '='.
298 if (Tok.is(tok::code_completion)) {
299 cutOffParsing();
300 Actions.CodeCompleteNamespaceAliasDecl(getCurScope());
301 return nullptr;
304 CXXScopeSpec SS;
305 // Parse (optional) nested-name-specifier.
306 ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
307 /*ObjectHasErrors=*/false,
308 /*EnteringContext=*/false,
309 /*MayBePseudoDestructor=*/nullptr,
310 /*IsTypename=*/false,
311 /*LastII=*/nullptr,
312 /*OnlyNamespace=*/true);
314 if (Tok.isNot(tok::identifier)) {
315 Diag(Tok, diag::err_expected_namespace_name);
316 // Skip to end of the definition and eat the ';'.
317 SkipUntil(tok::semi);
318 return nullptr;
321 if (SS.isInvalid()) {
322 // Diagnostics have been emitted in ParseOptionalCXXScopeSpecifier.
323 // Skip to end of the definition and eat the ';'.
324 SkipUntil(tok::semi);
325 return nullptr;
328 // Parse identifier.
329 IdentifierInfo *Ident = Tok.getIdentifierInfo();
330 SourceLocation IdentLoc = ConsumeToken();
332 // Eat the ';'.
333 DeclEnd = Tok.getLocation();
334 if (ExpectAndConsume(tok::semi, diag::err_expected_semi_after_namespace_name))
335 SkipUntil(tok::semi);
337 return Actions.ActOnNamespaceAliasDef(getCurScope(), NamespaceLoc, AliasLoc,
338 Alias, SS, IdentLoc, Ident);
341 /// ParseLinkage - We know that the current token is a string_literal
342 /// and just before that, that extern was seen.
344 /// linkage-specification: [C++ 7.5p2: dcl.link]
345 /// 'extern' string-literal '{' declaration-seq[opt] '}'
346 /// 'extern' string-literal declaration
348 Decl *Parser::ParseLinkage(ParsingDeclSpec &DS, DeclaratorContext Context) {
349 assert(isTokenStringLiteral() && "Not a string literal!");
350 ExprResult Lang = ParseStringLiteralExpression(false);
352 ParseScope LinkageScope(this, Scope::DeclScope);
353 Decl *LinkageSpec =
354 Lang.isInvalid()
355 ? nullptr
356 : Actions.ActOnStartLinkageSpecification(
357 getCurScope(), DS.getSourceRange().getBegin(), Lang.get(),
358 Tok.is(tok::l_brace) ? Tok.getLocation() : SourceLocation());
360 ParsedAttributes DeclAttrs(AttrFactory);
361 MaybeParseCXX11Attributes(DeclAttrs);
363 if (Tok.isNot(tok::l_brace)) {
364 // Reset the source range in DS, as the leading "extern"
365 // does not really belong to the inner declaration ...
366 DS.SetRangeStart(SourceLocation());
367 DS.SetRangeEnd(SourceLocation());
368 // ... but anyway remember that such an "extern" was seen.
369 DS.setExternInLinkageSpec(true);
370 ParseExternalDeclaration(DeclAttrs, &DS);
371 return LinkageSpec ? Actions.ActOnFinishLinkageSpecification(
372 getCurScope(), LinkageSpec, SourceLocation())
373 : nullptr;
376 DS.abort();
378 ProhibitAttributes(DeclAttrs);
380 BalancedDelimiterTracker T(*this, tok::l_brace);
381 T.consumeOpen();
383 unsigned NestedModules = 0;
384 while (true) {
385 switch (Tok.getKind()) {
386 case tok::annot_module_begin:
387 ++NestedModules;
388 ParseTopLevelDecl();
389 continue;
391 case tok::annot_module_end:
392 if (!NestedModules)
393 break;
394 --NestedModules;
395 ParseTopLevelDecl();
396 continue;
398 case tok::annot_module_include:
399 ParseTopLevelDecl();
400 continue;
402 case tok::eof:
403 break;
405 case tok::r_brace:
406 if (!NestedModules)
407 break;
408 [[fallthrough]];
409 default:
410 ParsedAttributes Attrs(AttrFactory);
411 MaybeParseCXX11Attributes(Attrs);
412 ParseExternalDeclaration(Attrs);
413 continue;
416 break;
419 T.consumeClose();
420 return LinkageSpec ? Actions.ActOnFinishLinkageSpecification(
421 getCurScope(), LinkageSpec, T.getCloseLocation())
422 : nullptr;
425 /// Parse a C++ Modules TS export-declaration.
427 /// export-declaration:
428 /// 'export' declaration
429 /// 'export' '{' declaration-seq[opt] '}'
431 Decl *Parser::ParseExportDeclaration() {
432 assert(Tok.is(tok::kw_export));
433 SourceLocation ExportLoc = ConsumeToken();
435 ParseScope ExportScope(this, Scope::DeclScope);
436 Decl *ExportDecl = Actions.ActOnStartExportDecl(
437 getCurScope(), ExportLoc,
438 Tok.is(tok::l_brace) ? Tok.getLocation() : SourceLocation());
440 if (Tok.isNot(tok::l_brace)) {
441 // FIXME: Factor out a ParseExternalDeclarationWithAttrs.
442 ParsedAttributes Attrs(AttrFactory);
443 MaybeParseCXX11Attributes(Attrs);
444 ParseExternalDeclaration(Attrs);
445 return Actions.ActOnFinishExportDecl(getCurScope(), ExportDecl,
446 SourceLocation());
449 BalancedDelimiterTracker T(*this, tok::l_brace);
450 T.consumeOpen();
452 // The Modules TS draft says "An export-declaration shall declare at least one
453 // entity", but the intent is that it shall contain at least one declaration.
454 if (Tok.is(tok::r_brace) && getLangOpts().ModulesTS) {
455 Diag(ExportLoc, diag::err_export_empty)
456 << SourceRange(ExportLoc, Tok.getLocation());
459 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
460 Tok.isNot(tok::eof)) {
461 ParsedAttributes Attrs(AttrFactory);
462 MaybeParseCXX11Attributes(Attrs);
463 ParseExternalDeclaration(Attrs);
466 T.consumeClose();
467 return Actions.ActOnFinishExportDecl(getCurScope(), ExportDecl,
468 T.getCloseLocation());
471 /// ParseUsingDirectiveOrDeclaration - Parse C++ using using-declaration or
472 /// using-directive. Assumes that current token is 'using'.
473 Parser::DeclGroupPtrTy Parser::ParseUsingDirectiveOrDeclaration(
474 DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo,
475 SourceLocation &DeclEnd, ParsedAttributes &Attrs) {
476 assert(Tok.is(tok::kw_using) && "Not using token");
477 ObjCDeclContextSwitch ObjCDC(*this);
479 // Eat 'using'.
480 SourceLocation UsingLoc = ConsumeToken();
482 if (Tok.is(tok::code_completion)) {
483 cutOffParsing();
484 Actions.CodeCompleteUsing(getCurScope());
485 return nullptr;
488 // Consume unexpected 'template' keywords.
489 while (Tok.is(tok::kw_template)) {
490 SourceLocation TemplateLoc = ConsumeToken();
491 Diag(TemplateLoc, diag::err_unexpected_template_after_using)
492 << FixItHint::CreateRemoval(TemplateLoc);
495 // 'using namespace' means this is a using-directive.
496 if (Tok.is(tok::kw_namespace)) {
497 // Template parameters are always an error here.
498 if (TemplateInfo.Kind) {
499 SourceRange R = TemplateInfo.getSourceRange();
500 Diag(UsingLoc, diag::err_templated_using_directive_declaration)
501 << 0 /* directive */ << R << FixItHint::CreateRemoval(R);
504 Decl *UsingDir = ParseUsingDirective(Context, UsingLoc, DeclEnd, Attrs);
505 return Actions.ConvertDeclToDeclGroup(UsingDir);
508 // Otherwise, it must be a using-declaration or an alias-declaration.
509 return ParseUsingDeclaration(Context, TemplateInfo, UsingLoc, DeclEnd, Attrs,
510 AS_none);
513 /// ParseUsingDirective - Parse C++ using-directive, assumes
514 /// that current token is 'namespace' and 'using' was already parsed.
516 /// using-directive: [C++ 7.3.p4: namespace.udir]
517 /// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
518 /// namespace-name ;
519 /// [GNU] using-directive:
520 /// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
521 /// namespace-name attributes[opt] ;
523 Decl *Parser::ParseUsingDirective(DeclaratorContext Context,
524 SourceLocation UsingLoc,
525 SourceLocation &DeclEnd,
526 ParsedAttributes &attrs) {
527 assert(Tok.is(tok::kw_namespace) && "Not 'namespace' token");
529 // Eat 'namespace'.
530 SourceLocation NamespcLoc = ConsumeToken();
532 if (Tok.is(tok::code_completion)) {
533 cutOffParsing();
534 Actions.CodeCompleteUsingDirective(getCurScope());
535 return nullptr;
538 CXXScopeSpec SS;
539 // Parse (optional) nested-name-specifier.
540 ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
541 /*ObjectHasErrors=*/false,
542 /*EnteringContext=*/false,
543 /*MayBePseudoDestructor=*/nullptr,
544 /*IsTypename=*/false,
545 /*LastII=*/nullptr,
546 /*OnlyNamespace=*/true);
548 IdentifierInfo *NamespcName = nullptr;
549 SourceLocation IdentLoc = SourceLocation();
551 // Parse namespace-name.
552 if (Tok.isNot(tok::identifier)) {
553 Diag(Tok, diag::err_expected_namespace_name);
554 // If there was invalid namespace name, skip to end of decl, and eat ';'.
555 SkipUntil(tok::semi);
556 // FIXME: Are there cases, when we would like to call ActOnUsingDirective?
557 return nullptr;
560 if (SS.isInvalid()) {
561 // Diagnostics have been emitted in ParseOptionalCXXScopeSpecifier.
562 // Skip to end of the definition and eat the ';'.
563 SkipUntil(tok::semi);
564 return nullptr;
567 // Parse identifier.
568 NamespcName = Tok.getIdentifierInfo();
569 IdentLoc = ConsumeToken();
571 // Parse (optional) attributes (most likely GNU strong-using extension).
572 bool GNUAttr = false;
573 if (Tok.is(tok::kw___attribute)) {
574 GNUAttr = true;
575 ParseGNUAttributes(attrs);
578 // Eat ';'.
579 DeclEnd = Tok.getLocation();
580 if (ExpectAndConsume(tok::semi,
581 GNUAttr ? diag::err_expected_semi_after_attribute_list
582 : diag::err_expected_semi_after_namespace_name))
583 SkipUntil(tok::semi);
585 return Actions.ActOnUsingDirective(getCurScope(), UsingLoc, NamespcLoc, SS,
586 IdentLoc, NamespcName, attrs);
589 /// Parse a using-declarator (or the identifier in a C++11 alias-declaration).
591 /// using-declarator:
592 /// 'typename'[opt] nested-name-specifier unqualified-id
594 bool Parser::ParseUsingDeclarator(DeclaratorContext Context,
595 UsingDeclarator &D) {
596 D.clear();
598 // Ignore optional 'typename'.
599 // FIXME: This is wrong; we should parse this as a typename-specifier.
600 TryConsumeToken(tok::kw_typename, D.TypenameLoc);
602 if (Tok.is(tok::kw___super)) {
603 Diag(Tok.getLocation(), diag::err_super_in_using_declaration);
604 return true;
607 // Parse nested-name-specifier.
608 IdentifierInfo *LastII = nullptr;
609 if (ParseOptionalCXXScopeSpecifier(D.SS, /*ObjectType=*/nullptr,
610 /*ObjectHasErrors=*/false,
611 /*EnteringContext=*/false,
612 /*MayBePseudoDtor=*/nullptr,
613 /*IsTypename=*/false,
614 /*LastII=*/&LastII,
615 /*OnlyNamespace=*/false,
616 /*InUsingDeclaration=*/true))
618 return true;
619 if (D.SS.isInvalid())
620 return true;
622 // Parse the unqualified-id. We allow parsing of both constructor and
623 // destructor names and allow the action module to diagnose any semantic
624 // errors.
626 // C++11 [class.qual]p2:
627 // [...] in a using-declaration that is a member-declaration, if the name
628 // specified after the nested-name-specifier is the same as the identifier
629 // or the simple-template-id's template-name in the last component of the
630 // nested-name-specifier, the name is [...] considered to name the
631 // constructor.
632 if (getLangOpts().CPlusPlus11 && Context == DeclaratorContext::Member &&
633 Tok.is(tok::identifier) &&
634 (NextToken().is(tok::semi) || NextToken().is(tok::comma) ||
635 NextToken().is(tok::ellipsis) || NextToken().is(tok::l_square) ||
636 NextToken().is(tok::kw___attribute)) &&
637 D.SS.isNotEmpty() && LastII == Tok.getIdentifierInfo() &&
638 !D.SS.getScopeRep()->getAsNamespace() &&
639 !D.SS.getScopeRep()->getAsNamespaceAlias()) {
640 SourceLocation IdLoc = ConsumeToken();
641 ParsedType Type =
642 Actions.getInheritingConstructorName(D.SS, IdLoc, *LastII);
643 D.Name.setConstructorName(Type, IdLoc, IdLoc);
644 } else {
645 if (ParseUnqualifiedId(
646 D.SS, /*ObjectType=*/nullptr,
647 /*ObjectHadErrors=*/false, /*EnteringContext=*/false,
648 /*AllowDestructorName=*/true,
649 /*AllowConstructorName=*/
650 !(Tok.is(tok::identifier) && NextToken().is(tok::equal)),
651 /*AllowDeductionGuide=*/false, nullptr, D.Name))
652 return true;
655 if (TryConsumeToken(tok::ellipsis, D.EllipsisLoc))
656 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
657 ? diag::warn_cxx17_compat_using_declaration_pack
658 : diag::ext_using_declaration_pack);
660 return false;
663 /// ParseUsingDeclaration - Parse C++ using-declaration or alias-declaration.
664 /// Assumes that 'using' was already seen.
666 /// using-declaration: [C++ 7.3.p3: namespace.udecl]
667 /// 'using' using-declarator-list[opt] ;
669 /// using-declarator-list: [C++1z]
670 /// using-declarator '...'[opt]
671 /// using-declarator-list ',' using-declarator '...'[opt]
673 /// using-declarator-list: [C++98-14]
674 /// using-declarator
676 /// alias-declaration: C++11 [dcl.dcl]p1
677 /// 'using' identifier attribute-specifier-seq[opt] = type-id ;
679 /// using-enum-declaration: [C++20, dcl.enum]
680 /// 'using' elaborated-enum-specifier ;
682 /// elaborated-enum-specifier:
683 /// 'enum' nested-name-specifier[opt] identifier
684 Parser::DeclGroupPtrTy Parser::ParseUsingDeclaration(
685 DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo,
686 SourceLocation UsingLoc, SourceLocation &DeclEnd,
687 ParsedAttributes &PrefixAttrs, AccessSpecifier AS) {
688 SourceLocation UELoc;
689 bool InInitStatement = Context == DeclaratorContext::SelectionInit ||
690 Context == DeclaratorContext::ForInit;
692 if (TryConsumeToken(tok::kw_enum, UELoc) && !InInitStatement) {
693 // C++20 using-enum
694 Diag(UELoc, getLangOpts().CPlusPlus20
695 ? diag::warn_cxx17_compat_using_enum_declaration
696 : diag::ext_using_enum_declaration);
698 DiagnoseCXX11AttributeExtension(PrefixAttrs);
700 DeclSpec DS(AttrFactory);
701 ParseEnumSpecifier(UELoc, DS, TemplateInfo, AS,
702 // DSC_trailing has the semantics we desire
703 DeclSpecContext::DSC_trailing);
705 if (TemplateInfo.Kind) {
706 SourceRange R = TemplateInfo.getSourceRange();
707 Diag(UsingLoc, diag::err_templated_using_directive_declaration)
708 << 1 /* declaration */ << R << FixItHint::CreateRemoval(R);
710 return nullptr;
713 Decl *UED = Actions.ActOnUsingEnumDeclaration(getCurScope(), AS, UsingLoc,
714 UELoc, DS);
715 DeclEnd = Tok.getLocation();
716 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
717 "using-enum declaration"))
718 SkipUntil(tok::semi);
720 return Actions.ConvertDeclToDeclGroup(UED);
723 // Check for misplaced attributes before the identifier in an
724 // alias-declaration.
725 ParsedAttributes MisplacedAttrs(AttrFactory);
726 MaybeParseCXX11Attributes(MisplacedAttrs);
728 if (InInitStatement && Tok.isNot(tok::identifier))
729 return nullptr;
731 UsingDeclarator D;
732 bool InvalidDeclarator = ParseUsingDeclarator(Context, D);
734 ParsedAttributes Attrs(AttrFactory);
735 MaybeParseAttributes(PAKM_GNU | PAKM_CXX11, Attrs);
737 // If we had any misplaced attributes from earlier, this is where they
738 // should have been written.
739 if (MisplacedAttrs.Range.isValid()) {
740 Diag(MisplacedAttrs.Range.getBegin(), diag::err_attributes_not_allowed)
741 << FixItHint::CreateInsertionFromRange(
742 Tok.getLocation(),
743 CharSourceRange::getTokenRange(MisplacedAttrs.Range))
744 << FixItHint::CreateRemoval(MisplacedAttrs.Range);
745 Attrs.takeAllFrom(MisplacedAttrs);
748 // Maybe this is an alias-declaration.
749 if (Tok.is(tok::equal) || InInitStatement) {
750 if (InvalidDeclarator) {
751 SkipUntil(tok::semi);
752 return nullptr;
755 ProhibitAttributes(PrefixAttrs);
757 Decl *DeclFromDeclSpec = nullptr;
758 Decl *AD = ParseAliasDeclarationAfterDeclarator(
759 TemplateInfo, UsingLoc, D, DeclEnd, AS, Attrs, &DeclFromDeclSpec);
760 return Actions.ConvertDeclToDeclGroup(AD, DeclFromDeclSpec);
763 DiagnoseCXX11AttributeExtension(PrefixAttrs);
765 // Diagnose an attempt to declare a templated using-declaration.
766 // In C++11, alias-declarations can be templates:
767 // template <...> using id = type;
768 if (TemplateInfo.Kind) {
769 SourceRange R = TemplateInfo.getSourceRange();
770 Diag(UsingLoc, diag::err_templated_using_directive_declaration)
771 << 1 /* declaration */ << R << FixItHint::CreateRemoval(R);
773 // Unfortunately, we have to bail out instead of recovering by
774 // ignoring the parameters, just in case the nested name specifier
775 // depends on the parameters.
776 return nullptr;
779 SmallVector<Decl *, 8> DeclsInGroup;
780 while (true) {
781 // Parse (optional) attributes.
782 MaybeParseAttributes(PAKM_GNU | PAKM_CXX11, Attrs);
783 DiagnoseCXX11AttributeExtension(Attrs);
784 Attrs.addAll(PrefixAttrs.begin(), PrefixAttrs.end());
786 if (InvalidDeclarator)
787 SkipUntil(tok::comma, tok::semi, StopBeforeMatch);
788 else {
789 // "typename" keyword is allowed for identifiers only,
790 // because it may be a type definition.
791 if (D.TypenameLoc.isValid() &&
792 D.Name.getKind() != UnqualifiedIdKind::IK_Identifier) {
793 Diag(D.Name.getSourceRange().getBegin(),
794 diag::err_typename_identifiers_only)
795 << FixItHint::CreateRemoval(SourceRange(D.TypenameLoc));
796 // Proceed parsing, but discard the typename keyword.
797 D.TypenameLoc = SourceLocation();
800 Decl *UD = Actions.ActOnUsingDeclaration(getCurScope(), AS, UsingLoc,
801 D.TypenameLoc, D.SS, D.Name,
802 D.EllipsisLoc, Attrs);
803 if (UD)
804 DeclsInGroup.push_back(UD);
807 if (!TryConsumeToken(tok::comma))
808 break;
810 // Parse another using-declarator.
811 Attrs.clear();
812 InvalidDeclarator = ParseUsingDeclarator(Context, D);
815 if (DeclsInGroup.size() > 1)
816 Diag(Tok.getLocation(),
817 getLangOpts().CPlusPlus17
818 ? diag::warn_cxx17_compat_multi_using_declaration
819 : diag::ext_multi_using_declaration);
821 // Eat ';'.
822 DeclEnd = Tok.getLocation();
823 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
824 !Attrs.empty() ? "attributes list"
825 : UELoc.isValid() ? "using-enum declaration"
826 : "using declaration"))
827 SkipUntil(tok::semi);
829 return Actions.BuildDeclaratorGroup(DeclsInGroup);
832 Decl *Parser::ParseAliasDeclarationAfterDeclarator(
833 const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc,
834 UsingDeclarator &D, SourceLocation &DeclEnd, AccessSpecifier AS,
835 ParsedAttributes &Attrs, Decl **OwnedType) {
836 if (ExpectAndConsume(tok::equal)) {
837 SkipUntil(tok::semi);
838 return nullptr;
841 Diag(Tok.getLocation(), getLangOpts().CPlusPlus11
842 ? diag::warn_cxx98_compat_alias_declaration
843 : diag::ext_alias_declaration);
845 // Type alias templates cannot be specialized.
846 int SpecKind = -1;
847 if (TemplateInfo.Kind == ParsedTemplateInfo::Template &&
848 D.Name.getKind() == UnqualifiedIdKind::IK_TemplateId)
849 SpecKind = 0;
850 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization)
851 SpecKind = 1;
852 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
853 SpecKind = 2;
854 if (SpecKind != -1) {
855 SourceRange Range;
856 if (SpecKind == 0)
857 Range = SourceRange(D.Name.TemplateId->LAngleLoc,
858 D.Name.TemplateId->RAngleLoc);
859 else
860 Range = TemplateInfo.getSourceRange();
861 Diag(Range.getBegin(), diag::err_alias_declaration_specialization)
862 << SpecKind << Range;
863 SkipUntil(tok::semi);
864 return nullptr;
867 // Name must be an identifier.
868 if (D.Name.getKind() != UnqualifiedIdKind::IK_Identifier) {
869 Diag(D.Name.StartLocation, diag::err_alias_declaration_not_identifier);
870 // No removal fixit: can't recover from this.
871 SkipUntil(tok::semi);
872 return nullptr;
873 } else if (D.TypenameLoc.isValid())
874 Diag(D.TypenameLoc, diag::err_alias_declaration_not_identifier)
875 << FixItHint::CreateRemoval(
876 SourceRange(D.TypenameLoc, D.SS.isNotEmpty() ? D.SS.getEndLoc()
877 : D.TypenameLoc));
878 else if (D.SS.isNotEmpty())
879 Diag(D.SS.getBeginLoc(), diag::err_alias_declaration_not_identifier)
880 << FixItHint::CreateRemoval(D.SS.getRange());
881 if (D.EllipsisLoc.isValid())
882 Diag(D.EllipsisLoc, diag::err_alias_declaration_pack_expansion)
883 << FixItHint::CreateRemoval(SourceRange(D.EllipsisLoc));
885 Decl *DeclFromDeclSpec = nullptr;
886 TypeResult TypeAlias =
887 ParseTypeName(nullptr,
888 TemplateInfo.Kind ? DeclaratorContext::AliasTemplate
889 : DeclaratorContext::AliasDecl,
890 AS, &DeclFromDeclSpec, &Attrs);
891 if (OwnedType)
892 *OwnedType = DeclFromDeclSpec;
894 // Eat ';'.
895 DeclEnd = Tok.getLocation();
896 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
897 !Attrs.empty() ? "attributes list"
898 : "alias declaration"))
899 SkipUntil(tok::semi);
901 TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
902 MultiTemplateParamsArg TemplateParamsArg(
903 TemplateParams ? TemplateParams->data() : nullptr,
904 TemplateParams ? TemplateParams->size() : 0);
905 return Actions.ActOnAliasDeclaration(getCurScope(), AS, TemplateParamsArg,
906 UsingLoc, D.Name, Attrs, TypeAlias,
907 DeclFromDeclSpec);
910 static FixItHint getStaticAssertNoMessageFixIt(const Expr *AssertExpr,
911 SourceLocation EndExprLoc) {
912 if (const auto *BO = dyn_cast_or_null<BinaryOperator>(AssertExpr)) {
913 if (BO->getOpcode() == BO_LAnd &&
914 isa<StringLiteral>(BO->getRHS()->IgnoreImpCasts()))
915 return FixItHint::CreateReplacement(BO->getOperatorLoc(), ",");
917 return FixItHint::CreateInsertion(EndExprLoc, ", \"\"");
920 /// ParseStaticAssertDeclaration - Parse C++0x or C11 static_assert-declaration.
922 /// [C++0x] static_assert-declaration:
923 /// static_assert ( constant-expression , string-literal ) ;
925 /// [C11] static_assert-declaration:
926 /// _Static_assert ( constant-expression , string-literal ) ;
928 Decl *Parser::ParseStaticAssertDeclaration(SourceLocation &DeclEnd) {
929 assert(Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert) &&
930 "Not a static_assert declaration");
932 // Save the token used for static assertion.
933 Token SavedTok = Tok;
935 if (Tok.is(tok::kw__Static_assert) && !getLangOpts().C11)
936 Diag(Tok, diag::ext_c11_feature) << Tok.getName();
937 if (Tok.is(tok::kw_static_assert)) {
938 if (!getLangOpts().CPlusPlus) {
939 if (!getLangOpts().C2x)
940 Diag(Tok, diag::ext_ms_static_assert) << FixItHint::CreateReplacement(
941 Tok.getLocation(), "_Static_assert");
942 } else
943 Diag(Tok, diag::warn_cxx98_compat_static_assert);
946 SourceLocation StaticAssertLoc = ConsumeToken();
948 BalancedDelimiterTracker T(*this, tok::l_paren);
949 if (T.consumeOpen()) {
950 Diag(Tok, diag::err_expected) << tok::l_paren;
951 SkipMalformedDecl();
952 return nullptr;
955 EnterExpressionEvaluationContext ConstantEvaluated(
956 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
957 ExprResult AssertExpr(ParseConstantExpressionInExprEvalContext());
958 if (AssertExpr.isInvalid()) {
959 SkipMalformedDecl();
960 return nullptr;
963 ExprResult AssertMessage;
964 if (Tok.is(tok::r_paren)) {
965 unsigned DiagVal;
966 if (getLangOpts().CPlusPlus17)
967 DiagVal = diag::warn_cxx14_compat_static_assert_no_message;
968 else if (getLangOpts().CPlusPlus)
969 DiagVal = diag::ext_cxx_static_assert_no_message;
970 else if (getLangOpts().C2x)
971 DiagVal = diag::warn_c17_compat_static_assert_no_message;
972 else
973 DiagVal = diag::ext_c_static_assert_no_message;
974 Diag(Tok, DiagVal) << getStaticAssertNoMessageFixIt(AssertExpr.get(),
975 Tok.getLocation());
976 } else {
977 if (ExpectAndConsume(tok::comma)) {
978 SkipUntil(tok::semi);
979 return nullptr;
982 if (!isTokenStringLiteral()) {
983 Diag(Tok, diag::err_expected_string_literal)
984 << /*Source='static_assert'*/ 1;
985 SkipMalformedDecl();
986 return nullptr;
989 AssertMessage = ParseStringLiteralExpression();
990 if (AssertMessage.isInvalid()) {
991 SkipMalformedDecl();
992 return nullptr;
996 T.consumeClose();
998 DeclEnd = Tok.getLocation();
999 // Passing the token used to the error message.
1000 ExpectAndConsumeSemi(diag::err_expected_semi_after_static_assert,
1001 SavedTok.getName());
1003 return Actions.ActOnStaticAssertDeclaration(StaticAssertLoc, AssertExpr.get(),
1004 AssertMessage.get(),
1005 T.getCloseLocation());
1008 /// ParseDecltypeSpecifier - Parse a C++11 decltype specifier.
1010 /// 'decltype' ( expression )
1011 /// 'decltype' ( 'auto' ) [C++1y]
1013 SourceLocation Parser::ParseDecltypeSpecifier(DeclSpec &DS) {
1014 assert(Tok.isOneOf(tok::kw_decltype, tok::annot_decltype) &&
1015 "Not a decltype specifier");
1017 ExprResult Result;
1018 SourceLocation StartLoc = Tok.getLocation();
1019 SourceLocation EndLoc;
1021 if (Tok.is(tok::annot_decltype)) {
1022 Result = getExprAnnotation(Tok);
1023 EndLoc = Tok.getAnnotationEndLoc();
1024 // Unfortunately, we don't know the LParen source location as the annotated
1025 // token doesn't have it.
1026 DS.setTypeArgumentRange(SourceRange(SourceLocation(), EndLoc));
1027 ConsumeAnnotationToken();
1028 if (Result.isInvalid()) {
1029 DS.SetTypeSpecError();
1030 return EndLoc;
1032 } else {
1033 if (Tok.getIdentifierInfo()->isStr("decltype"))
1034 Diag(Tok, diag::warn_cxx98_compat_decltype);
1036 ConsumeToken();
1038 BalancedDelimiterTracker T(*this, tok::l_paren);
1039 if (T.expectAndConsume(diag::err_expected_lparen_after, "decltype",
1040 tok::r_paren)) {
1041 DS.SetTypeSpecError();
1042 return T.getOpenLocation() == Tok.getLocation() ? StartLoc
1043 : T.getOpenLocation();
1046 // Check for C++1y 'decltype(auto)'.
1047 if (Tok.is(tok::kw_auto) && NextToken().is(tok::r_paren)) {
1048 // the typename-specifier in a function-style cast expression may
1049 // be 'auto' since C++2b.
1050 Diag(Tok.getLocation(),
1051 getLangOpts().CPlusPlus14
1052 ? diag::warn_cxx11_compat_decltype_auto_type_specifier
1053 : diag::ext_decltype_auto_type_specifier);
1054 ConsumeToken();
1055 } else {
1056 // Parse the expression
1058 // C++11 [dcl.type.simple]p4:
1059 // The operand of the decltype specifier is an unevaluated operand.
1060 EnterExpressionEvaluationContext Unevaluated(
1061 Actions, Sema::ExpressionEvaluationContext::Unevaluated, nullptr,
1062 Sema::ExpressionEvaluationContextRecord::EK_Decltype);
1063 Result = Actions.CorrectDelayedTyposInExpr(
1064 ParseExpression(), /*InitDecl=*/nullptr,
1065 /*RecoverUncorrectedTypos=*/false,
1066 [](Expr *E) { return E->hasPlaceholderType() ? ExprError() : E; });
1067 if (Result.isInvalid()) {
1068 DS.SetTypeSpecError();
1069 if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch)) {
1070 EndLoc = ConsumeParen();
1071 } else {
1072 if (PP.isBacktrackEnabled() && Tok.is(tok::semi)) {
1073 // Backtrack to get the location of the last token before the semi.
1074 PP.RevertCachedTokens(2);
1075 ConsumeToken(); // the semi.
1076 EndLoc = ConsumeAnyToken();
1077 assert(Tok.is(tok::semi));
1078 } else {
1079 EndLoc = Tok.getLocation();
1082 return EndLoc;
1085 Result = Actions.ActOnDecltypeExpression(Result.get());
1088 // Match the ')'
1089 T.consumeClose();
1090 DS.setTypeArgumentRange(T.getRange());
1091 if (T.getCloseLocation().isInvalid()) {
1092 DS.SetTypeSpecError();
1093 // FIXME: this should return the location of the last token
1094 // that was consumed (by "consumeClose()")
1095 return T.getCloseLocation();
1098 if (Result.isInvalid()) {
1099 DS.SetTypeSpecError();
1100 return T.getCloseLocation();
1103 EndLoc = T.getCloseLocation();
1105 assert(!Result.isInvalid());
1107 const char *PrevSpec = nullptr;
1108 unsigned DiagID;
1109 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
1110 // Check for duplicate type specifiers (e.g. "int decltype(a)").
1111 if (Result.get() ? DS.SetTypeSpecType(DeclSpec::TST_decltype, StartLoc,
1112 PrevSpec, DiagID, Result.get(), Policy)
1113 : DS.SetTypeSpecType(DeclSpec::TST_decltype_auto, StartLoc,
1114 PrevSpec, DiagID, Policy)) {
1115 Diag(StartLoc, DiagID) << PrevSpec;
1116 DS.SetTypeSpecError();
1118 return EndLoc;
1121 void Parser::AnnotateExistingDecltypeSpecifier(const DeclSpec &DS,
1122 SourceLocation StartLoc,
1123 SourceLocation EndLoc) {
1124 // make sure we have a token we can turn into an annotation token
1125 if (PP.isBacktrackEnabled()) {
1126 PP.RevertCachedTokens(1);
1127 if (DS.getTypeSpecType() == TST_error) {
1128 // We encountered an error in parsing 'decltype(...)' so lets annotate all
1129 // the tokens in the backtracking cache - that we likely had to skip over
1130 // to get to a token that allows us to resume parsing, such as a
1131 // semi-colon.
1132 EndLoc = PP.getLastCachedTokenLocation();
1134 } else
1135 PP.EnterToken(Tok, /*IsReinject*/ true);
1137 Tok.setKind(tok::annot_decltype);
1138 setExprAnnotation(Tok,
1139 DS.getTypeSpecType() == TST_decltype ? DS.getRepAsExpr()
1140 : DS.getTypeSpecType() == TST_decltype_auto ? ExprResult()
1141 : ExprError());
1142 Tok.setAnnotationEndLoc(EndLoc);
1143 Tok.setLocation(StartLoc);
1144 PP.AnnotateCachedTokens(Tok);
1147 DeclSpec::TST Parser::TypeTransformTokToDeclSpec() {
1148 switch (Tok.getKind()) {
1149 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) \
1150 case tok::kw___##Trait: \
1151 return DeclSpec::TST_##Trait;
1152 #include "clang/Basic/TransformTypeTraits.def"
1153 default:
1154 llvm_unreachable("passed in an unhandled type transformation built-in");
1158 bool Parser::MaybeParseTypeTransformTypeSpecifier(DeclSpec &DS) {
1159 if (!NextToken().is(tok::l_paren)) {
1160 Tok.setKind(tok::identifier);
1161 return false;
1163 DeclSpec::TST TypeTransformTST = TypeTransformTokToDeclSpec();
1164 SourceLocation StartLoc = ConsumeToken();
1166 BalancedDelimiterTracker T(*this, tok::l_paren);
1167 if (T.expectAndConsume(diag::err_expected_lparen_after, Tok.getName(),
1168 tok::r_paren))
1169 return true;
1171 TypeResult Result = ParseTypeName();
1172 if (Result.isInvalid()) {
1173 SkipUntil(tok::r_paren, StopAtSemi);
1174 return true;
1177 T.consumeClose();
1178 if (T.getCloseLocation().isInvalid())
1179 return true;
1181 const char *PrevSpec = nullptr;
1182 unsigned DiagID;
1183 if (DS.SetTypeSpecType(TypeTransformTST, StartLoc, PrevSpec, DiagID,
1184 Result.get(),
1185 Actions.getASTContext().getPrintingPolicy()))
1186 Diag(StartLoc, DiagID) << PrevSpec;
1187 DS.setTypeArgumentRange(T.getRange());
1188 return true;
1191 /// ParseBaseTypeSpecifier - Parse a C++ base-type-specifier which is either a
1192 /// class name or decltype-specifier. Note that we only check that the result
1193 /// names a type; semantic analysis will need to verify that the type names a
1194 /// class. The result is either a type or null, depending on whether a type
1195 /// name was found.
1197 /// base-type-specifier: [C++11 class.derived]
1198 /// class-or-decltype
1199 /// class-or-decltype: [C++11 class.derived]
1200 /// nested-name-specifier[opt] class-name
1201 /// decltype-specifier
1202 /// class-name: [C++ class.name]
1203 /// identifier
1204 /// simple-template-id
1206 /// In C++98, instead of base-type-specifier, we have:
1208 /// ::[opt] nested-name-specifier[opt] class-name
1209 TypeResult Parser::ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
1210 SourceLocation &EndLocation) {
1211 // Ignore attempts to use typename
1212 if (Tok.is(tok::kw_typename)) {
1213 Diag(Tok, diag::err_expected_class_name_not_template)
1214 << FixItHint::CreateRemoval(Tok.getLocation());
1215 ConsumeToken();
1218 // Parse optional nested-name-specifier
1219 CXXScopeSpec SS;
1220 if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
1221 /*ObjectHasErrors=*/false,
1222 /*EnteringContext=*/false))
1223 return true;
1225 BaseLoc = Tok.getLocation();
1227 // Parse decltype-specifier
1228 // tok == kw_decltype is just error recovery, it can only happen when SS
1229 // isn't empty
1230 if (Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)) {
1231 if (SS.isNotEmpty())
1232 Diag(SS.getBeginLoc(), diag::err_unexpected_scope_on_base_decltype)
1233 << FixItHint::CreateRemoval(SS.getRange());
1234 // Fake up a Declarator to use with ActOnTypeName.
1235 DeclSpec DS(AttrFactory);
1237 EndLocation = ParseDecltypeSpecifier(DS);
1239 Declarator DeclaratorInfo(DS, ParsedAttributesView::none(),
1240 DeclaratorContext::TypeName);
1241 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
1244 // Check whether we have a template-id that names a type.
1245 if (Tok.is(tok::annot_template_id)) {
1246 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1247 if (TemplateId->mightBeType()) {
1248 AnnotateTemplateIdTokenAsType(SS, /*IsClassName*/ true);
1250 assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
1251 TypeResult Type = getTypeAnnotation(Tok);
1252 EndLocation = Tok.getAnnotationEndLoc();
1253 ConsumeAnnotationToken();
1254 return Type;
1257 // Fall through to produce an error below.
1260 if (Tok.isNot(tok::identifier)) {
1261 Diag(Tok, diag::err_expected_class_name);
1262 return true;
1265 IdentifierInfo *Id = Tok.getIdentifierInfo();
1266 SourceLocation IdLoc = ConsumeToken();
1268 if (Tok.is(tok::less)) {
1269 // It looks the user intended to write a template-id here, but the
1270 // template-name was wrong. Try to fix that.
1271 // FIXME: Invoke ParseOptionalCXXScopeSpecifier in a "'template' is neither
1272 // required nor permitted" mode, and do this there.
1273 TemplateNameKind TNK = TNK_Non_template;
1274 TemplateTy Template;
1275 if (!Actions.DiagnoseUnknownTemplateName(*Id, IdLoc, getCurScope(), &SS,
1276 Template, TNK)) {
1277 Diag(IdLoc, diag::err_unknown_template_name) << Id;
1280 // Form the template name
1281 UnqualifiedId TemplateName;
1282 TemplateName.setIdentifier(Id, IdLoc);
1284 // Parse the full template-id, then turn it into a type.
1285 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
1286 TemplateName))
1287 return true;
1288 if (Tok.is(tok::annot_template_id) &&
1289 takeTemplateIdAnnotation(Tok)->mightBeType())
1290 AnnotateTemplateIdTokenAsType(SS, /*IsClassName*/ true);
1292 // If we didn't end up with a typename token, there's nothing more we
1293 // can do.
1294 if (Tok.isNot(tok::annot_typename))
1295 return true;
1297 // Retrieve the type from the annotation token, consume that token, and
1298 // return.
1299 EndLocation = Tok.getAnnotationEndLoc();
1300 TypeResult Type = getTypeAnnotation(Tok);
1301 ConsumeAnnotationToken();
1302 return Type;
1305 // We have an identifier; check whether it is actually a type.
1306 IdentifierInfo *CorrectedII = nullptr;
1307 ParsedType Type = Actions.getTypeName(
1308 *Id, IdLoc, getCurScope(), &SS, /*isClassName=*/true, false, nullptr,
1309 /*IsCtorOrDtorName=*/false,
1310 /*WantNontrivialTypeSourceInfo=*/true,
1311 /*IsClassTemplateDeductionContext*/ false, &CorrectedII);
1312 if (!Type) {
1313 Diag(IdLoc, diag::err_expected_class_name);
1314 return true;
1317 // Consume the identifier.
1318 EndLocation = IdLoc;
1320 // Fake up a Declarator to use with ActOnTypeName.
1321 DeclSpec DS(AttrFactory);
1322 DS.SetRangeStart(IdLoc);
1323 DS.SetRangeEnd(EndLocation);
1324 DS.getTypeSpecScope() = SS;
1326 const char *PrevSpec = nullptr;
1327 unsigned DiagID;
1328 DS.SetTypeSpecType(TST_typename, IdLoc, PrevSpec, DiagID, Type,
1329 Actions.getASTContext().getPrintingPolicy());
1331 Declarator DeclaratorInfo(DS, ParsedAttributesView::none(),
1332 DeclaratorContext::TypeName);
1333 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
1336 void Parser::ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs) {
1337 while (Tok.isOneOf(tok::kw___single_inheritance,
1338 tok::kw___multiple_inheritance,
1339 tok::kw___virtual_inheritance)) {
1340 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
1341 SourceLocation AttrNameLoc = ConsumeToken();
1342 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
1343 ParsedAttr::AS_Keyword);
1347 /// Determine whether the following tokens are valid after a type-specifier
1348 /// which could be a standalone declaration. This will conservatively return
1349 /// true if there's any doubt, and is appropriate for insert-';' fixits.
1350 bool Parser::isValidAfterTypeSpecifier(bool CouldBeBitfield) {
1351 // This switch enumerates the valid "follow" set for type-specifiers.
1352 switch (Tok.getKind()) {
1353 default:
1354 break;
1355 case tok::semi: // struct foo {...} ;
1356 case tok::star: // struct foo {...} * P;
1357 case tok::amp: // struct foo {...} & R = ...
1358 case tok::ampamp: // struct foo {...} && R = ...
1359 case tok::identifier: // struct foo {...} V ;
1360 case tok::r_paren: //(struct foo {...} ) {4}
1361 case tok::coloncolon: // struct foo {...} :: a::b;
1362 case tok::annot_cxxscope: // struct foo {...} a:: b;
1363 case tok::annot_typename: // struct foo {...} a ::b;
1364 case tok::annot_template_id: // struct foo {...} a<int> ::b;
1365 case tok::kw_decltype: // struct foo {...} decltype (a)::b;
1366 case tok::l_paren: // struct foo {...} ( x);
1367 case tok::comma: // __builtin_offsetof(struct foo{...} ,
1368 case tok::kw_operator: // struct foo operator ++() {...}
1369 case tok::kw___declspec: // struct foo {...} __declspec(...)
1370 case tok::l_square: // void f(struct f [ 3])
1371 case tok::ellipsis: // void f(struct f ... [Ns])
1372 // FIXME: we should emit semantic diagnostic when declaration
1373 // attribute is in type attribute position.
1374 case tok::kw___attribute: // struct foo __attribute__((used)) x;
1375 case tok::annot_pragma_pack: // struct foo {...} _Pragma(pack(pop));
1376 // struct foo {...} _Pragma(section(...));
1377 case tok::annot_pragma_ms_pragma:
1378 // struct foo {...} _Pragma(vtordisp(pop));
1379 case tok::annot_pragma_ms_vtordisp:
1380 // struct foo {...} _Pragma(pointers_to_members(...));
1381 case tok::annot_pragma_ms_pointers_to_members:
1382 return true;
1383 case tok::colon:
1384 return CouldBeBitfield || // enum E { ... } : 2;
1385 ColonIsSacred; // _Generic(..., enum E : 2);
1386 // Microsoft compatibility
1387 case tok::kw___cdecl: // struct foo {...} __cdecl x;
1388 case tok::kw___fastcall: // struct foo {...} __fastcall x;
1389 case tok::kw___stdcall: // struct foo {...} __stdcall x;
1390 case tok::kw___thiscall: // struct foo {...} __thiscall x;
1391 case tok::kw___vectorcall: // struct foo {...} __vectorcall x;
1392 // We will diagnose these calling-convention specifiers on non-function
1393 // declarations later, so claim they are valid after a type specifier.
1394 return getLangOpts().MicrosoftExt;
1395 // Type qualifiers
1396 case tok::kw_const: // struct foo {...} const x;
1397 case tok::kw_volatile: // struct foo {...} volatile x;
1398 case tok::kw_restrict: // struct foo {...} restrict x;
1399 case tok::kw__Atomic: // struct foo {...} _Atomic x;
1400 case tok::kw___unaligned: // struct foo {...} __unaligned *x;
1401 // Function specifiers
1402 // Note, no 'explicit'. An explicit function must be either a conversion
1403 // operator or a constructor. Either way, it can't have a return type.
1404 case tok::kw_inline: // struct foo inline f();
1405 case tok::kw_virtual: // struct foo virtual f();
1406 case tok::kw_friend: // struct foo friend f();
1407 // Storage-class specifiers
1408 case tok::kw_static: // struct foo {...} static x;
1409 case tok::kw_extern: // struct foo {...} extern x;
1410 case tok::kw_typedef: // struct foo {...} typedef x;
1411 case tok::kw_register: // struct foo {...} register x;
1412 case tok::kw_auto: // struct foo {...} auto x;
1413 case tok::kw_mutable: // struct foo {...} mutable x;
1414 case tok::kw_thread_local: // struct foo {...} thread_local x;
1415 case tok::kw_constexpr: // struct foo {...} constexpr x;
1416 case tok::kw_consteval: // struct foo {...} consteval x;
1417 case tok::kw_constinit: // struct foo {...} constinit x;
1418 // As shown above, type qualifiers and storage class specifiers absolutely
1419 // can occur after class specifiers according to the grammar. However,
1420 // almost no one actually writes code like this. If we see one of these,
1421 // it is much more likely that someone missed a semi colon and the
1422 // type/storage class specifier we're seeing is part of the *next*
1423 // intended declaration, as in:
1425 // struct foo { ... }
1426 // typedef int X;
1428 // We'd really like to emit a missing semicolon error instead of emitting
1429 // an error on the 'int' saying that you can't have two type specifiers in
1430 // the same declaration of X. Because of this, we look ahead past this
1431 // token to see if it's a type specifier. If so, we know the code is
1432 // otherwise invalid, so we can produce the expected semi error.
1433 if (!isKnownToBeTypeSpecifier(NextToken()))
1434 return true;
1435 break;
1436 case tok::r_brace: // struct bar { struct foo {...} }
1437 // Missing ';' at end of struct is accepted as an extension in C mode.
1438 if (!getLangOpts().CPlusPlus)
1439 return true;
1440 break;
1441 case tok::greater:
1442 // template<class T = class X>
1443 return getLangOpts().CPlusPlus;
1445 return false;
1448 /// ParseClassSpecifier - Parse a C++ class-specifier [C++ class] or
1449 /// elaborated-type-specifier [C++ dcl.type.elab]; we can't tell which
1450 /// until we reach the start of a definition or see a token that
1451 /// cannot start a definition.
1453 /// class-specifier: [C++ class]
1454 /// class-head '{' member-specification[opt] '}'
1455 /// class-head '{' member-specification[opt] '}' attributes[opt]
1456 /// class-head:
1457 /// class-key identifier[opt] base-clause[opt]
1458 /// class-key nested-name-specifier identifier base-clause[opt]
1459 /// class-key nested-name-specifier[opt] simple-template-id
1460 /// base-clause[opt]
1461 /// [GNU] class-key attributes[opt] identifier[opt] base-clause[opt]
1462 /// [GNU] class-key attributes[opt] nested-name-specifier
1463 /// identifier base-clause[opt]
1464 /// [GNU] class-key attributes[opt] nested-name-specifier[opt]
1465 /// simple-template-id base-clause[opt]
1466 /// class-key:
1467 /// 'class'
1468 /// 'struct'
1469 /// 'union'
1471 /// elaborated-type-specifier: [C++ dcl.type.elab]
1472 /// class-key ::[opt] nested-name-specifier[opt] identifier
1473 /// class-key ::[opt] nested-name-specifier[opt] 'template'[opt]
1474 /// simple-template-id
1476 /// Note that the C++ class-specifier and elaborated-type-specifier,
1477 /// together, subsume the C99 struct-or-union-specifier:
1479 /// struct-or-union-specifier: [C99 6.7.2.1]
1480 /// struct-or-union identifier[opt] '{' struct-contents '}'
1481 /// struct-or-union identifier
1482 /// [GNU] struct-or-union attributes[opt] identifier[opt] '{' struct-contents
1483 /// '}' attributes[opt]
1484 /// [GNU] struct-or-union attributes[opt] identifier
1485 /// struct-or-union:
1486 /// 'struct'
1487 /// 'union'
1488 void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind,
1489 SourceLocation StartLoc, DeclSpec &DS,
1490 const ParsedTemplateInfo &TemplateInfo,
1491 AccessSpecifier AS, bool EnteringContext,
1492 DeclSpecContext DSC,
1493 ParsedAttributes &Attributes) {
1494 DeclSpec::TST TagType;
1495 if (TagTokKind == tok::kw_struct)
1496 TagType = DeclSpec::TST_struct;
1497 else if (TagTokKind == tok::kw___interface)
1498 TagType = DeclSpec::TST_interface;
1499 else if (TagTokKind == tok::kw_class)
1500 TagType = DeclSpec::TST_class;
1501 else {
1502 assert(TagTokKind == tok::kw_union && "Not a class specifier");
1503 TagType = DeclSpec::TST_union;
1506 if (Tok.is(tok::code_completion)) {
1507 // Code completion for a struct, class, or union name.
1508 cutOffParsing();
1509 Actions.CodeCompleteTag(getCurScope(), TagType);
1510 return;
1513 // C++20 [temp.class.spec] 13.7.5/10
1514 // The usual access checking rules do not apply to non-dependent names
1515 // used to specify template arguments of the simple-template-id of the
1516 // partial specialization.
1517 // C++20 [temp.spec] 13.9/6:
1518 // The usual access checking rules do not apply to names in a declaration
1519 // of an explicit instantiation or explicit specialization...
1520 const bool shouldDelayDiagsInTag =
1521 (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate);
1522 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
1524 ParsedAttributes attrs(AttrFactory);
1525 // If attributes exist after tag, parse them.
1526 MaybeParseAttributes(PAKM_CXX11 | PAKM_Declspec | PAKM_GNU, attrs);
1528 // Parse inheritance specifiers.
1529 if (Tok.isOneOf(tok::kw___single_inheritance, tok::kw___multiple_inheritance,
1530 tok::kw___virtual_inheritance))
1531 ParseMicrosoftInheritanceClassAttributes(attrs);
1533 // Allow attributes to precede or succeed the inheritance specifiers.
1534 MaybeParseAttributes(PAKM_CXX11 | PAKM_Declspec | PAKM_GNU, attrs);
1536 // Source location used by FIXIT to insert misplaced
1537 // C++11 attributes
1538 SourceLocation AttrFixitLoc = Tok.getLocation();
1540 if (TagType == DeclSpec::TST_struct && Tok.isNot(tok::identifier) &&
1541 !Tok.isAnnotation() && Tok.getIdentifierInfo() &&
1542 Tok.isOneOf(
1543 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) tok::kw___##Trait,
1544 #include "clang/Basic/TransformTypeTraits.def"
1545 tok::kw___is_abstract,
1546 tok::kw___is_aggregate,
1547 tok::kw___is_arithmetic,
1548 tok::kw___is_array,
1549 tok::kw___is_assignable,
1550 tok::kw___is_base_of,
1551 tok::kw___is_class,
1552 tok::kw___is_complete_type,
1553 tok::kw___is_compound,
1554 tok::kw___is_const,
1555 tok::kw___is_constructible,
1556 tok::kw___is_convertible,
1557 tok::kw___is_convertible_to,
1558 tok::kw___is_destructible,
1559 tok::kw___is_empty,
1560 tok::kw___is_enum,
1561 tok::kw___is_floating_point,
1562 tok::kw___is_final,
1563 tok::kw___is_function,
1564 tok::kw___is_fundamental,
1565 tok::kw___is_integral,
1566 tok::kw___is_interface_class,
1567 tok::kw___is_literal,
1568 tok::kw___is_lvalue_expr,
1569 tok::kw___is_lvalue_reference,
1570 tok::kw___is_member_function_pointer,
1571 tok::kw___is_member_object_pointer,
1572 tok::kw___is_member_pointer,
1573 tok::kw___is_nothrow_assignable,
1574 tok::kw___is_nothrow_constructible,
1575 tok::kw___is_nothrow_destructible,
1576 tok::kw___is_object,
1577 tok::kw___is_pod,
1578 tok::kw___is_pointer,
1579 tok::kw___is_polymorphic,
1580 tok::kw___is_reference,
1581 tok::kw___is_rvalue_expr,
1582 tok::kw___is_rvalue_reference,
1583 tok::kw___is_same,
1584 tok::kw___is_scalar,
1585 tok::kw___is_sealed,
1586 tok::kw___is_signed,
1587 tok::kw___is_standard_layout,
1588 tok::kw___is_trivial,
1589 tok::kw___is_trivially_assignable,
1590 tok::kw___is_trivially_constructible,
1591 tok::kw___is_trivially_copyable,
1592 tok::kw___is_union,
1593 tok::kw___is_unsigned,
1594 tok::kw___is_void,
1595 tok::kw___is_volatile))
1596 // GNU libstdc++ 4.2 and libc++ use certain intrinsic names as the
1597 // name of struct templates, but some are keywords in GCC >= 4.3
1598 // and Clang. Therefore, when we see the token sequence "struct
1599 // X", make X into a normal identifier rather than a keyword, to
1600 // allow libstdc++ 4.2 and libc++ to work properly.
1601 TryKeywordIdentFallback(true);
1603 struct PreserveAtomicIdentifierInfoRAII {
1604 PreserveAtomicIdentifierInfoRAII(Token &Tok, bool Enabled)
1605 : AtomicII(nullptr) {
1606 if (!Enabled)
1607 return;
1608 assert(Tok.is(tok::kw__Atomic));
1609 AtomicII = Tok.getIdentifierInfo();
1610 AtomicII->revertTokenIDToIdentifier();
1611 Tok.setKind(tok::identifier);
1613 ~PreserveAtomicIdentifierInfoRAII() {
1614 if (!AtomicII)
1615 return;
1616 AtomicII->revertIdentifierToTokenID(tok::kw__Atomic);
1618 IdentifierInfo *AtomicII;
1621 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
1622 // implementation for VS2013 uses _Atomic as an identifier for one of the
1623 // classes in <atomic>. When we are parsing 'struct _Atomic', don't consider
1624 // '_Atomic' to be a keyword. We are careful to undo this so that clang can
1625 // use '_Atomic' in its own header files.
1626 bool ShouldChangeAtomicToIdentifier = getLangOpts().MSVCCompat &&
1627 Tok.is(tok::kw__Atomic) &&
1628 TagType == DeclSpec::TST_struct;
1629 PreserveAtomicIdentifierInfoRAII AtomicTokenGuard(
1630 Tok, ShouldChangeAtomicToIdentifier);
1632 // Parse the (optional) nested-name-specifier.
1633 CXXScopeSpec &SS = DS.getTypeSpecScope();
1634 if (getLangOpts().CPlusPlus) {
1635 // "FOO : BAR" is not a potential typo for "FOO::BAR". In this context it
1636 // is a base-specifier-list.
1637 ColonProtectionRAIIObject X(*this);
1639 CXXScopeSpec Spec;
1640 bool HasValidSpec = true;
1641 if (ParseOptionalCXXScopeSpecifier(Spec, /*ObjectType=*/nullptr,
1642 /*ObjectHasErrors=*/false,
1643 EnteringContext)) {
1644 DS.SetTypeSpecError();
1645 HasValidSpec = false;
1647 if (Spec.isSet())
1648 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::annot_template_id)) {
1649 Diag(Tok, diag::err_expected) << tok::identifier;
1650 HasValidSpec = false;
1652 if (HasValidSpec)
1653 SS = Spec;
1656 TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
1658 auto RecoverFromUndeclaredTemplateName = [&](IdentifierInfo *Name,
1659 SourceLocation NameLoc,
1660 SourceRange TemplateArgRange,
1661 bool KnownUndeclared) {
1662 Diag(NameLoc, diag::err_explicit_spec_non_template)
1663 << (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
1664 << TagTokKind << Name << TemplateArgRange << KnownUndeclared;
1666 // Strip off the last template parameter list if it was empty, since
1667 // we've removed its template argument list.
1668 if (TemplateParams && TemplateInfo.LastParameterListWasEmpty) {
1669 if (TemplateParams->size() > 1) {
1670 TemplateParams->pop_back();
1671 } else {
1672 TemplateParams = nullptr;
1673 const_cast<ParsedTemplateInfo &>(TemplateInfo).Kind =
1674 ParsedTemplateInfo::NonTemplate;
1676 } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1677 // Pretend this is just a forward declaration.
1678 TemplateParams = nullptr;
1679 const_cast<ParsedTemplateInfo &>(TemplateInfo).Kind =
1680 ParsedTemplateInfo::NonTemplate;
1681 const_cast<ParsedTemplateInfo &>(TemplateInfo).TemplateLoc =
1682 SourceLocation();
1683 const_cast<ParsedTemplateInfo &>(TemplateInfo).ExternLoc =
1684 SourceLocation();
1688 // Parse the (optional) class name or simple-template-id.
1689 IdentifierInfo *Name = nullptr;
1690 SourceLocation NameLoc;
1691 TemplateIdAnnotation *TemplateId = nullptr;
1692 if (Tok.is(tok::identifier)) {
1693 Name = Tok.getIdentifierInfo();
1694 NameLoc = ConsumeToken();
1696 if (Tok.is(tok::less) && getLangOpts().CPlusPlus) {
1697 // The name was supposed to refer to a template, but didn't.
1698 // Eat the template argument list and try to continue parsing this as
1699 // a class (or template thereof).
1700 TemplateArgList TemplateArgs;
1701 SourceLocation LAngleLoc, RAngleLoc;
1702 if (ParseTemplateIdAfterTemplateName(true, LAngleLoc, TemplateArgs,
1703 RAngleLoc)) {
1704 // We couldn't parse the template argument list at all, so don't
1705 // try to give any location information for the list.
1706 LAngleLoc = RAngleLoc = SourceLocation();
1708 RecoverFromUndeclaredTemplateName(
1709 Name, NameLoc, SourceRange(LAngleLoc, RAngleLoc), false);
1711 } else if (Tok.is(tok::annot_template_id)) {
1712 TemplateId = takeTemplateIdAnnotation(Tok);
1713 NameLoc = ConsumeAnnotationToken();
1715 if (TemplateId->Kind == TNK_Undeclared_template) {
1716 // Try to resolve the template name to a type template. May update Kind.
1717 Actions.ActOnUndeclaredTypeTemplateName(
1718 getCurScope(), TemplateId->Template, TemplateId->Kind, NameLoc, Name);
1719 if (TemplateId->Kind == TNK_Undeclared_template) {
1720 RecoverFromUndeclaredTemplateName(
1721 Name, NameLoc,
1722 SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc), true);
1723 TemplateId = nullptr;
1727 if (TemplateId && !TemplateId->mightBeType()) {
1728 // The template-name in the simple-template-id refers to
1729 // something other than a type template. Give an appropriate
1730 // error message and skip to the ';'.
1731 SourceRange Range(NameLoc);
1732 if (SS.isNotEmpty())
1733 Range.setBegin(SS.getBeginLoc());
1735 // FIXME: Name may be null here.
1736 Diag(TemplateId->LAngleLoc, diag::err_template_spec_syntax_non_template)
1737 << TemplateId->Name << static_cast<int>(TemplateId->Kind) << Range;
1739 DS.SetTypeSpecError();
1740 SkipUntil(tok::semi, StopBeforeMatch);
1741 return;
1745 // There are four options here.
1746 // - If we are in a trailing return type, this is always just a reference,
1747 // and we must not try to parse a definition. For instance,
1748 // [] () -> struct S { };
1749 // does not define a type.
1750 // - If we have 'struct foo {...', 'struct foo :...',
1751 // 'struct foo final :' or 'struct foo final {', then this is a definition.
1752 // - If we have 'struct foo;', then this is either a forward declaration
1753 // or a friend declaration, which have to be treated differently.
1754 // - Otherwise we have something like 'struct foo xyz', a reference.
1756 // We also detect these erroneous cases to provide better diagnostic for
1757 // C++11 attributes parsing.
1758 // - attributes follow class name:
1759 // struct foo [[]] {};
1760 // - attributes appear before or after 'final':
1761 // struct foo [[]] final [[]] {};
1763 // However, in type-specifier-seq's, things look like declarations but are
1764 // just references, e.g.
1765 // new struct s;
1766 // or
1767 // &T::operator struct s;
1768 // For these, DSC is DeclSpecContext::DSC_type_specifier or
1769 // DeclSpecContext::DSC_alias_declaration.
1771 // If there are attributes after class name, parse them.
1772 MaybeParseCXX11Attributes(Attributes);
1774 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
1775 Sema::TagUseKind TUK;
1776 if (isDefiningTypeSpecifierContext(DSC, getLangOpts().CPlusPlus) ==
1777 AllowDefiningTypeSpec::No ||
1778 (getLangOpts().OpenMP && OpenMPDirectiveParsing))
1779 TUK = Sema::TUK_Reference;
1780 else if (Tok.is(tok::l_brace) ||
1781 (DSC != DeclSpecContext::DSC_association &&
1782 getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
1783 (isClassCompatibleKeyword() &&
1784 (NextToken().is(tok::l_brace) || NextToken().is(tok::colon)))) {
1785 if (DS.isFriendSpecified()) {
1786 // C++ [class.friend]p2:
1787 // A class shall not be defined in a friend declaration.
1788 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
1789 << SourceRange(DS.getFriendSpecLoc());
1791 // Skip everything up to the semicolon, so that this looks like a proper
1792 // friend class (or template thereof) declaration.
1793 SkipUntil(tok::semi, StopBeforeMatch);
1794 TUK = Sema::TUK_Friend;
1795 } else {
1796 // Okay, this is a class definition.
1797 TUK = Sema::TUK_Definition;
1799 } else if (isClassCompatibleKeyword() &&
1800 (NextToken().is(tok::l_square) ||
1801 NextToken().is(tok::kw_alignas) ||
1802 isCXX11VirtSpecifier(NextToken()) != VirtSpecifiers::VS_None)) {
1803 // We can't tell if this is a definition or reference
1804 // until we skipped the 'final' and C++11 attribute specifiers.
1805 TentativeParsingAction PA(*this);
1807 // Skip the 'final', abstract'... keywords.
1808 while (isClassCompatibleKeyword()) {
1809 ConsumeToken();
1812 // Skip C++11 attribute specifiers.
1813 while (true) {
1814 if (Tok.is(tok::l_square) && NextToken().is(tok::l_square)) {
1815 ConsumeBracket();
1816 if (!SkipUntil(tok::r_square, StopAtSemi))
1817 break;
1818 } else if (Tok.is(tok::kw_alignas) && NextToken().is(tok::l_paren)) {
1819 ConsumeToken();
1820 ConsumeParen();
1821 if (!SkipUntil(tok::r_paren, StopAtSemi))
1822 break;
1823 } else {
1824 break;
1828 if (Tok.isOneOf(tok::l_brace, tok::colon))
1829 TUK = Sema::TUK_Definition;
1830 else
1831 TUK = Sema::TUK_Reference;
1833 PA.Revert();
1834 } else if (!isTypeSpecifier(DSC) &&
1835 (Tok.is(tok::semi) ||
1836 (Tok.isAtStartOfLine() && !isValidAfterTypeSpecifier(false)))) {
1837 TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
1838 if (Tok.isNot(tok::semi)) {
1839 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
1840 // A semicolon was missing after this declaration. Diagnose and recover.
1841 ExpectAndConsume(tok::semi, diag::err_expected_after,
1842 DeclSpec::getSpecifierName(TagType, PPol));
1843 PP.EnterToken(Tok, /*IsReinject*/ true);
1844 Tok.setKind(tok::semi);
1846 } else
1847 TUK = Sema::TUK_Reference;
1849 // Forbid misplaced attributes. In cases of a reference, we pass attributes
1850 // to caller to handle.
1851 if (TUK != Sema::TUK_Reference) {
1852 // If this is not a reference, then the only possible
1853 // valid place for C++11 attributes to appear here
1854 // is between class-key and class-name. If there are
1855 // any attributes after class-name, we try a fixit to move
1856 // them to the right place.
1857 SourceRange AttrRange = Attributes.Range;
1858 if (AttrRange.isValid()) {
1859 Diag(AttrRange.getBegin(), diag::err_attributes_not_allowed)
1860 << AttrRange
1861 << FixItHint::CreateInsertionFromRange(
1862 AttrFixitLoc, CharSourceRange(AttrRange, true))
1863 << FixItHint::CreateRemoval(AttrRange);
1865 // Recover by adding misplaced attributes to the attribute list
1866 // of the class so they can be applied on the class later.
1867 attrs.takeAllFrom(Attributes);
1871 if (!Name && !TemplateId &&
1872 (DS.getTypeSpecType() == DeclSpec::TST_error ||
1873 TUK != Sema::TUK_Definition)) {
1874 if (DS.getTypeSpecType() != DeclSpec::TST_error) {
1875 // We have a declaration or reference to an anonymous class.
1876 Diag(StartLoc, diag::err_anon_type_definition)
1877 << DeclSpec::getSpecifierName(TagType, Policy);
1880 // If we are parsing a definition and stop at a base-clause, continue on
1881 // until the semicolon. Continuing from the comma will just trick us into
1882 // thinking we are seeing a variable declaration.
1883 if (TUK == Sema::TUK_Definition && Tok.is(tok::colon))
1884 SkipUntil(tok::semi, StopBeforeMatch);
1885 else
1886 SkipUntil(tok::comma, StopAtSemi);
1887 return;
1890 // Create the tag portion of the class or class template.
1891 DeclResult TagOrTempResult = true; // invalid
1892 TypeResult TypeResult = true; // invalid
1894 bool Owned = false;
1895 Sema::SkipBodyInfo SkipBody;
1896 if (TemplateId) {
1897 // Explicit specialization, class template partial specialization,
1898 // or explicit instantiation.
1899 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1900 TemplateId->NumArgs);
1901 if (TemplateId->isInvalid()) {
1902 // Can't build the declaration.
1903 } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
1904 TUK == Sema::TUK_Declaration) {
1905 // This is an explicit instantiation of a class template.
1906 ProhibitCXX11Attributes(attrs, diag::err_attributes_not_allowed,
1907 /*DiagnoseEmptyAttrs=*/true);
1909 TagOrTempResult = Actions.ActOnExplicitInstantiation(
1910 getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc,
1911 TagType, StartLoc, SS, TemplateId->Template,
1912 TemplateId->TemplateNameLoc, TemplateId->LAngleLoc, TemplateArgsPtr,
1913 TemplateId->RAngleLoc, attrs);
1915 // Friend template-ids are treated as references unless
1916 // they have template headers, in which case they're ill-formed
1917 // (FIXME: "template <class T> friend class A<T>::B<int>;").
1918 // We diagnose this error in ActOnClassTemplateSpecialization.
1919 } else if (TUK == Sema::TUK_Reference ||
1920 (TUK == Sema::TUK_Friend &&
1921 TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate)) {
1922 ProhibitCXX11Attributes(attrs, diag::err_attributes_not_allowed,
1923 /*DiagnoseEmptyAttrs=*/true);
1924 TypeResult = Actions.ActOnTagTemplateIdType(
1925 TUK, TagType, StartLoc, SS, TemplateId->TemplateKWLoc,
1926 TemplateId->Template, TemplateId->TemplateNameLoc,
1927 TemplateId->LAngleLoc, TemplateArgsPtr, TemplateId->RAngleLoc);
1928 } else {
1929 // This is an explicit specialization or a class template
1930 // partial specialization.
1931 TemplateParameterLists FakedParamLists;
1932 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1933 // This looks like an explicit instantiation, because we have
1934 // something like
1936 // template class Foo<X>
1938 // but it actually has a definition. Most likely, this was
1939 // meant to be an explicit specialization, but the user forgot
1940 // the '<>' after 'template'.
1941 // It this is friend declaration however, since it cannot have a
1942 // template header, it is most likely that the user meant to
1943 // remove the 'template' keyword.
1944 assert((TUK == Sema::TUK_Definition || TUK == Sema::TUK_Friend) &&
1945 "Expected a definition here");
1947 if (TUK == Sema::TUK_Friend) {
1948 Diag(DS.getFriendSpecLoc(), diag::err_friend_explicit_instantiation);
1949 TemplateParams = nullptr;
1950 } else {
1951 SourceLocation LAngleLoc =
1952 PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
1953 Diag(TemplateId->TemplateNameLoc,
1954 diag::err_explicit_instantiation_with_definition)
1955 << SourceRange(TemplateInfo.TemplateLoc)
1956 << FixItHint::CreateInsertion(LAngleLoc, "<>");
1958 // Create a fake template parameter list that contains only
1959 // "template<>", so that we treat this construct as a class
1960 // template specialization.
1961 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
1962 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
1963 LAngleLoc, nullptr));
1964 TemplateParams = &FakedParamLists;
1968 // Build the class template specialization.
1969 TagOrTempResult = Actions.ActOnClassTemplateSpecialization(
1970 getCurScope(), TagType, TUK, StartLoc, DS.getModulePrivateSpecLoc(),
1971 SS, *TemplateId, attrs,
1972 MultiTemplateParamsArg(TemplateParams ? &(*TemplateParams)[0]
1973 : nullptr,
1974 TemplateParams ? TemplateParams->size() : 0),
1975 &SkipBody);
1977 } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
1978 TUK == Sema::TUK_Declaration) {
1979 // Explicit instantiation of a member of a class template
1980 // specialization, e.g.,
1982 // template struct Outer<int>::Inner;
1984 ProhibitAttributes(attrs);
1986 TagOrTempResult = Actions.ActOnExplicitInstantiation(
1987 getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc,
1988 TagType, StartLoc, SS, Name, NameLoc, attrs);
1989 } else if (TUK == Sema::TUK_Friend &&
1990 TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate) {
1991 ProhibitCXX11Attributes(attrs, diag::err_attributes_not_allowed,
1992 /*DiagnoseEmptyAttrs=*/true);
1994 TagOrTempResult = Actions.ActOnTemplatedFriendTag(
1995 getCurScope(), DS.getFriendSpecLoc(), TagType, StartLoc, SS, Name,
1996 NameLoc, attrs,
1997 MultiTemplateParamsArg(TemplateParams ? &(*TemplateParams)[0] : nullptr,
1998 TemplateParams ? TemplateParams->size() : 0));
1999 } else {
2000 if (TUK != Sema::TUK_Declaration && TUK != Sema::TUK_Definition)
2001 ProhibitCXX11Attributes(attrs, diag::err_attributes_not_allowed,
2002 /* DiagnoseEmptyAttrs=*/true);
2004 if (TUK == Sema::TUK_Definition &&
2005 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
2006 // If the declarator-id is not a template-id, issue a diagnostic and
2007 // recover by ignoring the 'template' keyword.
2008 Diag(Tok, diag::err_template_defn_explicit_instantiation)
2009 << 1 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
2010 TemplateParams = nullptr;
2013 bool IsDependent = false;
2015 // Don't pass down template parameter lists if this is just a tag
2016 // reference. For example, we don't need the template parameters here:
2017 // template <class T> class A *makeA(T t);
2018 MultiTemplateParamsArg TParams;
2019 if (TUK != Sema::TUK_Reference && TemplateParams)
2020 TParams =
2021 MultiTemplateParamsArg(&(*TemplateParams)[0], TemplateParams->size());
2023 stripTypeAttributesOffDeclSpec(attrs, DS, TUK);
2025 // Declaration or definition of a class type
2026 TagOrTempResult = Actions.ActOnTag(
2027 getCurScope(), TagType, TUK, StartLoc, SS, Name, NameLoc, attrs, AS,
2028 DS.getModulePrivateSpecLoc(), TParams, Owned, IsDependent,
2029 SourceLocation(), false, clang::TypeResult(),
2030 DSC == DeclSpecContext::DSC_type_specifier,
2031 DSC == DeclSpecContext::DSC_template_param ||
2032 DSC == DeclSpecContext::DSC_template_type_arg,
2033 &SkipBody);
2035 // If ActOnTag said the type was dependent, try again with the
2036 // less common call.
2037 if (IsDependent) {
2038 assert(TUK == Sema::TUK_Reference || TUK == Sema::TUK_Friend);
2039 TypeResult = Actions.ActOnDependentTag(getCurScope(), TagType, TUK, SS,
2040 Name, StartLoc, NameLoc);
2044 // If this is an elaborated type specifier in function template,
2045 // and we delayed diagnostics before,
2046 // just merge them into the current pool.
2047 if (shouldDelayDiagsInTag) {
2048 diagsFromTag.done();
2049 if (TUK == Sema::TUK_Reference &&
2050 TemplateInfo.Kind == ParsedTemplateInfo::Template)
2051 diagsFromTag.redelay();
2054 // If there is a body, parse it and inform the actions module.
2055 if (TUK == Sema::TUK_Definition) {
2056 assert(Tok.is(tok::l_brace) ||
2057 (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
2058 isClassCompatibleKeyword());
2059 if (SkipBody.ShouldSkip)
2060 SkipCXXMemberSpecification(StartLoc, AttrFixitLoc, TagType,
2061 TagOrTempResult.get());
2062 else if (getLangOpts().CPlusPlus)
2063 ParseCXXMemberSpecification(StartLoc, AttrFixitLoc, attrs, TagType,
2064 TagOrTempResult.get());
2065 else {
2066 Decl *D =
2067 SkipBody.CheckSameAsPrevious ? SkipBody.New : TagOrTempResult.get();
2068 // Parse the definition body.
2069 ParseStructUnionBody(StartLoc, TagType, cast<RecordDecl>(D));
2070 if (SkipBody.CheckSameAsPrevious &&
2071 !Actions.ActOnDuplicateDefinition(TagOrTempResult.get(), SkipBody)) {
2072 DS.SetTypeSpecError();
2073 return;
2078 if (!TagOrTempResult.isInvalid())
2079 // Delayed processing of attributes.
2080 Actions.ProcessDeclAttributeDelayed(TagOrTempResult.get(), attrs);
2082 const char *PrevSpec = nullptr;
2083 unsigned DiagID;
2084 bool Result;
2085 if (!TypeResult.isInvalid()) {
2086 Result = DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
2087 NameLoc.isValid() ? NameLoc : StartLoc,
2088 PrevSpec, DiagID, TypeResult.get(), Policy);
2089 } else if (!TagOrTempResult.isInvalid()) {
2090 Result = DS.SetTypeSpecType(
2091 TagType, StartLoc, NameLoc.isValid() ? NameLoc : StartLoc, PrevSpec,
2092 DiagID, TagOrTempResult.get(), Owned, Policy);
2093 } else {
2094 DS.SetTypeSpecError();
2095 return;
2098 if (Result)
2099 Diag(StartLoc, DiagID) << PrevSpec;
2101 // At this point, we've successfully parsed a class-specifier in 'definition'
2102 // form (e.g. "struct foo { int x; }". While we could just return here, we're
2103 // going to look at what comes after it to improve error recovery. If an
2104 // impossible token occurs next, we assume that the programmer forgot a ; at
2105 // the end of the declaration and recover that way.
2107 // Also enforce C++ [temp]p3:
2108 // In a template-declaration which defines a class, no declarator
2109 // is permitted.
2111 // After a type-specifier, we don't expect a semicolon. This only happens in
2112 // C, since definitions are not permitted in this context in C++.
2113 if (TUK == Sema::TUK_Definition &&
2114 (getLangOpts().CPlusPlus || !isTypeSpecifier(DSC)) &&
2115 (TemplateInfo.Kind || !isValidAfterTypeSpecifier(false))) {
2116 if (Tok.isNot(tok::semi)) {
2117 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
2118 ExpectAndConsume(tok::semi, diag::err_expected_after,
2119 DeclSpec::getSpecifierName(TagType, PPol));
2120 // Push this token back into the preprocessor and change our current token
2121 // to ';' so that the rest of the code recovers as though there were an
2122 // ';' after the definition.
2123 PP.EnterToken(Tok, /*IsReinject=*/true);
2124 Tok.setKind(tok::semi);
2129 /// ParseBaseClause - Parse the base-clause of a C++ class [C++ class.derived].
2131 /// base-clause : [C++ class.derived]
2132 /// ':' base-specifier-list
2133 /// base-specifier-list:
2134 /// base-specifier '...'[opt]
2135 /// base-specifier-list ',' base-specifier '...'[opt]
2136 void Parser::ParseBaseClause(Decl *ClassDecl) {
2137 assert(Tok.is(tok::colon) && "Not a base clause");
2138 ConsumeToken();
2140 // Build up an array of parsed base specifiers.
2141 SmallVector<CXXBaseSpecifier *, 8> BaseInfo;
2143 while (true) {
2144 // Parse a base-specifier.
2145 BaseResult Result = ParseBaseSpecifier(ClassDecl);
2146 if (Result.isInvalid()) {
2147 // Skip the rest of this base specifier, up until the comma or
2148 // opening brace.
2149 SkipUntil(tok::comma, tok::l_brace, StopAtSemi | StopBeforeMatch);
2150 } else {
2151 // Add this to our array of base specifiers.
2152 BaseInfo.push_back(Result.get());
2155 // If the next token is a comma, consume it and keep reading
2156 // base-specifiers.
2157 if (!TryConsumeToken(tok::comma))
2158 break;
2161 // Attach the base specifiers
2162 Actions.ActOnBaseSpecifiers(ClassDecl, BaseInfo);
2165 /// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is
2166 /// one entry in the base class list of a class specifier, for example:
2167 /// class foo : public bar, virtual private baz {
2168 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2170 /// base-specifier: [C++ class.derived]
2171 /// attribute-specifier-seq[opt] base-type-specifier
2172 /// attribute-specifier-seq[opt] 'virtual' access-specifier[opt]
2173 /// base-type-specifier
2174 /// attribute-specifier-seq[opt] access-specifier 'virtual'[opt]
2175 /// base-type-specifier
2176 BaseResult Parser::ParseBaseSpecifier(Decl *ClassDecl) {
2177 bool IsVirtual = false;
2178 SourceLocation StartLoc = Tok.getLocation();
2180 ParsedAttributes Attributes(AttrFactory);
2181 MaybeParseCXX11Attributes(Attributes);
2183 // Parse the 'virtual' keyword.
2184 if (TryConsumeToken(tok::kw_virtual))
2185 IsVirtual = true;
2187 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2189 // Parse an (optional) access specifier.
2190 AccessSpecifier Access = getAccessSpecifierIfPresent();
2191 if (Access != AS_none) {
2192 ConsumeToken();
2193 if (getLangOpts().HLSL)
2194 Diag(Tok.getLocation(), diag::ext_hlsl_access_specifiers);
2197 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2199 // Parse the 'virtual' keyword (again!), in case it came after the
2200 // access specifier.
2201 if (Tok.is(tok::kw_virtual)) {
2202 SourceLocation VirtualLoc = ConsumeToken();
2203 if (IsVirtual) {
2204 // Complain about duplicate 'virtual'
2205 Diag(VirtualLoc, diag::err_dup_virtual)
2206 << FixItHint::CreateRemoval(VirtualLoc);
2209 IsVirtual = true;
2212 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2214 // Parse the class-name.
2216 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
2217 // implementation for VS2013 uses _Atomic as an identifier for one of the
2218 // classes in <atomic>. Treat '_Atomic' to be an identifier when we are
2219 // parsing the class-name for a base specifier.
2220 if (getLangOpts().MSVCCompat && Tok.is(tok::kw__Atomic) &&
2221 NextToken().is(tok::less))
2222 Tok.setKind(tok::identifier);
2224 SourceLocation EndLocation;
2225 SourceLocation BaseLoc;
2226 TypeResult BaseType = ParseBaseTypeSpecifier(BaseLoc, EndLocation);
2227 if (BaseType.isInvalid())
2228 return true;
2230 // Parse the optional ellipsis (for a pack expansion). The ellipsis is
2231 // actually part of the base-specifier-list grammar productions, but we
2232 // parse it here for convenience.
2233 SourceLocation EllipsisLoc;
2234 TryConsumeToken(tok::ellipsis, EllipsisLoc);
2236 // Find the complete source range for the base-specifier.
2237 SourceRange Range(StartLoc, EndLocation);
2239 // Notify semantic analysis that we have parsed a complete
2240 // base-specifier.
2241 return Actions.ActOnBaseSpecifier(ClassDecl, Range, Attributes, IsVirtual,
2242 Access, BaseType.get(), BaseLoc,
2243 EllipsisLoc);
2246 /// getAccessSpecifierIfPresent - Determine whether the next token is
2247 /// a C++ access-specifier.
2249 /// access-specifier: [C++ class.derived]
2250 /// 'private'
2251 /// 'protected'
2252 /// 'public'
2253 AccessSpecifier Parser::getAccessSpecifierIfPresent() const {
2254 switch (Tok.getKind()) {
2255 default:
2256 return AS_none;
2257 case tok::kw_private:
2258 return AS_private;
2259 case tok::kw_protected:
2260 return AS_protected;
2261 case tok::kw_public:
2262 return AS_public;
2266 /// If the given declarator has any parts for which parsing has to be
2267 /// delayed, e.g., default arguments or an exception-specification, create a
2268 /// late-parsed method declaration record to handle the parsing at the end of
2269 /// the class definition.
2270 void Parser::HandleMemberFunctionDeclDelays(Declarator &DeclaratorInfo,
2271 Decl *ThisDecl) {
2272 DeclaratorChunk::FunctionTypeInfo &FTI = DeclaratorInfo.getFunctionTypeInfo();
2273 // If there was a late-parsed exception-specification, we'll need a
2274 // late parse
2275 bool NeedLateParse = FTI.getExceptionSpecType() == EST_Unparsed;
2277 if (!NeedLateParse) {
2278 // Look ahead to see if there are any default args
2279 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx) {
2280 auto Param = cast<ParmVarDecl>(FTI.Params[ParamIdx].Param);
2281 if (Param->hasUnparsedDefaultArg()) {
2282 NeedLateParse = true;
2283 break;
2288 if (NeedLateParse) {
2289 // Push this method onto the stack of late-parsed method
2290 // declarations.
2291 auto LateMethod = new LateParsedMethodDeclaration(this, ThisDecl);
2292 getCurrentClass().LateParsedDeclarations.push_back(LateMethod);
2294 // Push tokens for each parameter. Those that do not have defaults will be
2295 // NULL. We need to track all the parameters so that we can push them into
2296 // scope for later parameters and perhaps for the exception specification.
2297 LateMethod->DefaultArgs.reserve(FTI.NumParams);
2298 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx)
2299 LateMethod->DefaultArgs.push_back(LateParsedDefaultArgument(
2300 FTI.Params[ParamIdx].Param,
2301 std::move(FTI.Params[ParamIdx].DefaultArgTokens)));
2303 // Stash the exception-specification tokens in the late-pased method.
2304 if (FTI.getExceptionSpecType() == EST_Unparsed) {
2305 LateMethod->ExceptionSpecTokens = FTI.ExceptionSpecTokens;
2306 FTI.ExceptionSpecTokens = nullptr;
2311 /// isCXX11VirtSpecifier - Determine whether the given token is a C++11
2312 /// virt-specifier.
2314 /// virt-specifier:
2315 /// override
2316 /// final
2317 /// __final
2318 VirtSpecifiers::Specifier Parser::isCXX11VirtSpecifier(const Token &Tok) const {
2319 if (!getLangOpts().CPlusPlus || Tok.isNot(tok::identifier))
2320 return VirtSpecifiers::VS_None;
2322 IdentifierInfo *II = Tok.getIdentifierInfo();
2324 // Initialize the contextual keywords.
2325 if (!Ident_final) {
2326 Ident_final = &PP.getIdentifierTable().get("final");
2327 if (getLangOpts().GNUKeywords)
2328 Ident_GNU_final = &PP.getIdentifierTable().get("__final");
2329 if (getLangOpts().MicrosoftExt) {
2330 Ident_sealed = &PP.getIdentifierTable().get("sealed");
2331 Ident_abstract = &PP.getIdentifierTable().get("abstract");
2333 Ident_override = &PP.getIdentifierTable().get("override");
2336 if (II == Ident_override)
2337 return VirtSpecifiers::VS_Override;
2339 if (II == Ident_sealed)
2340 return VirtSpecifiers::VS_Sealed;
2342 if (II == Ident_abstract)
2343 return VirtSpecifiers::VS_Abstract;
2345 if (II == Ident_final)
2346 return VirtSpecifiers::VS_Final;
2348 if (II == Ident_GNU_final)
2349 return VirtSpecifiers::VS_GNU_Final;
2351 return VirtSpecifiers::VS_None;
2354 /// ParseOptionalCXX11VirtSpecifierSeq - Parse a virt-specifier-seq.
2356 /// virt-specifier-seq:
2357 /// virt-specifier
2358 /// virt-specifier-seq virt-specifier
2359 void Parser::ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS,
2360 bool IsInterface,
2361 SourceLocation FriendLoc) {
2362 while (true) {
2363 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
2364 if (Specifier == VirtSpecifiers::VS_None)
2365 return;
2367 if (FriendLoc.isValid()) {
2368 Diag(Tok.getLocation(), diag::err_friend_decl_spec)
2369 << VirtSpecifiers::getSpecifierName(Specifier)
2370 << FixItHint::CreateRemoval(Tok.getLocation())
2371 << SourceRange(FriendLoc, FriendLoc);
2372 ConsumeToken();
2373 continue;
2376 // C++ [class.mem]p8:
2377 // A virt-specifier-seq shall contain at most one of each virt-specifier.
2378 const char *PrevSpec = nullptr;
2379 if (VS.SetSpecifier(Specifier, Tok.getLocation(), PrevSpec))
2380 Diag(Tok.getLocation(), diag::err_duplicate_virt_specifier)
2381 << PrevSpec << FixItHint::CreateRemoval(Tok.getLocation());
2383 if (IsInterface && (Specifier == VirtSpecifiers::VS_Final ||
2384 Specifier == VirtSpecifiers::VS_Sealed)) {
2385 Diag(Tok.getLocation(), diag::err_override_control_interface)
2386 << VirtSpecifiers::getSpecifierName(Specifier);
2387 } else if (Specifier == VirtSpecifiers::VS_Sealed) {
2388 Diag(Tok.getLocation(), diag::ext_ms_sealed_keyword);
2389 } else if (Specifier == VirtSpecifiers::VS_Abstract) {
2390 Diag(Tok.getLocation(), diag::ext_ms_abstract_keyword);
2391 } else if (Specifier == VirtSpecifiers::VS_GNU_Final) {
2392 Diag(Tok.getLocation(), diag::ext_warn_gnu_final);
2393 } else {
2394 Diag(Tok.getLocation(),
2395 getLangOpts().CPlusPlus11
2396 ? diag::warn_cxx98_compat_override_control_keyword
2397 : diag::ext_override_control_keyword)
2398 << VirtSpecifiers::getSpecifierName(Specifier);
2400 ConsumeToken();
2404 /// isCXX11FinalKeyword - Determine whether the next token is a C++11
2405 /// 'final' or Microsoft 'sealed' contextual keyword.
2406 bool Parser::isCXX11FinalKeyword() const {
2407 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
2408 return Specifier == VirtSpecifiers::VS_Final ||
2409 Specifier == VirtSpecifiers::VS_GNU_Final ||
2410 Specifier == VirtSpecifiers::VS_Sealed;
2413 /// isClassCompatibleKeyword - Determine whether the next token is a C++11
2414 /// 'final' or Microsoft 'sealed' or 'abstract' contextual keywords.
2415 bool Parser::isClassCompatibleKeyword() const {
2416 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
2417 return Specifier == VirtSpecifiers::VS_Final ||
2418 Specifier == VirtSpecifiers::VS_GNU_Final ||
2419 Specifier == VirtSpecifiers::VS_Sealed ||
2420 Specifier == VirtSpecifiers::VS_Abstract;
2423 /// Parse a C++ member-declarator up to, but not including, the optional
2424 /// brace-or-equal-initializer or pure-specifier.
2425 bool Parser::ParseCXXMemberDeclaratorBeforeInitializer(
2426 Declarator &DeclaratorInfo, VirtSpecifiers &VS, ExprResult &BitfieldSize,
2427 LateParsedAttrList &LateParsedAttrs) {
2428 // member-declarator:
2429 // declarator virt-specifier-seq[opt] pure-specifier[opt]
2430 // declarator requires-clause
2431 // declarator brace-or-equal-initializer[opt]
2432 // identifier attribute-specifier-seq[opt] ':' constant-expression
2433 // brace-or-equal-initializer[opt]
2434 // ':' constant-expression
2436 // NOTE: the latter two productions are a proposed bugfix rather than the
2437 // current grammar rules as of C++20.
2438 if (Tok.isNot(tok::colon))
2439 ParseDeclarator(DeclaratorInfo);
2440 else
2441 DeclaratorInfo.SetIdentifier(nullptr, Tok.getLocation());
2443 if (!DeclaratorInfo.isFunctionDeclarator() && TryConsumeToken(tok::colon)) {
2444 assert(DeclaratorInfo.isPastIdentifier() &&
2445 "don't know where identifier would go yet?");
2446 BitfieldSize = ParseConstantExpression();
2447 if (BitfieldSize.isInvalid())
2448 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2449 } else if (Tok.is(tok::kw_requires)) {
2450 ParseTrailingRequiresClause(DeclaratorInfo);
2451 } else {
2452 ParseOptionalCXX11VirtSpecifierSeq(
2453 VS, getCurrentClass().IsInterface,
2454 DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
2455 if (!VS.isUnset())
2456 MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo,
2457 VS);
2460 // If a simple-asm-expr is present, parse it.
2461 if (Tok.is(tok::kw_asm)) {
2462 SourceLocation Loc;
2463 ExprResult AsmLabel(ParseSimpleAsm(/*ForAsmLabel*/ true, &Loc));
2464 if (AsmLabel.isInvalid())
2465 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2467 DeclaratorInfo.setAsmLabel(AsmLabel.get());
2468 DeclaratorInfo.SetRangeEnd(Loc);
2471 // If attributes exist after the declarator, but before an '{', parse them.
2472 // However, this does not apply for [[]] attributes (which could show up
2473 // before or after the __attribute__ attributes).
2474 DiagnoseAndSkipCXX11Attributes();
2475 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
2476 DiagnoseAndSkipCXX11Attributes();
2478 // For compatibility with code written to older Clang, also accept a
2479 // virt-specifier *after* the GNU attributes.
2480 if (BitfieldSize.isUnset() && VS.isUnset()) {
2481 ParseOptionalCXX11VirtSpecifierSeq(
2482 VS, getCurrentClass().IsInterface,
2483 DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
2484 if (!VS.isUnset()) {
2485 // If we saw any GNU-style attributes that are known to GCC followed by a
2486 // virt-specifier, issue a GCC-compat warning.
2487 for (const ParsedAttr &AL : DeclaratorInfo.getAttributes())
2488 if (AL.isKnownToGCC() && !AL.isCXX11Attribute())
2489 Diag(AL.getLoc(), diag::warn_gcc_attribute_location);
2491 MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo,
2492 VS);
2496 // If this has neither a name nor a bit width, something has gone seriously
2497 // wrong. Skip until the semi-colon or }.
2498 if (!DeclaratorInfo.hasName() && BitfieldSize.isUnset()) {
2499 // If so, skip until the semi-colon or a }.
2500 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2501 return true;
2503 return false;
2506 /// Look for declaration specifiers possibly occurring after C++11
2507 /// virt-specifier-seq and diagnose them.
2508 void Parser::MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(
2509 Declarator &D, VirtSpecifiers &VS) {
2510 DeclSpec DS(AttrFactory);
2512 // GNU-style and C++11 attributes are not allowed here, but they will be
2513 // handled by the caller. Diagnose everything else.
2514 ParseTypeQualifierListOpt(
2515 DS, AR_NoAttributesParsed, false,
2516 /*IdentifierRequired=*/false, llvm::function_ref<void()>([&]() {
2517 Actions.CodeCompleteFunctionQualifiers(DS, D, &VS);
2518 }));
2519 D.ExtendWithDeclSpec(DS);
2521 if (D.isFunctionDeclarator()) {
2522 auto &Function = D.getFunctionTypeInfo();
2523 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
2524 auto DeclSpecCheck = [&](DeclSpec::TQ TypeQual, StringRef FixItName,
2525 SourceLocation SpecLoc) {
2526 FixItHint Insertion;
2527 auto &MQ = Function.getOrCreateMethodQualifiers();
2528 if (!(MQ.getTypeQualifiers() & TypeQual)) {
2529 std::string Name(FixItName.data());
2530 Name += " ";
2531 Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), Name);
2532 MQ.SetTypeQual(TypeQual, SpecLoc);
2534 Diag(SpecLoc, diag::err_declspec_after_virtspec)
2535 << FixItName
2536 << VirtSpecifiers::getSpecifierName(VS.getLastSpecifier())
2537 << FixItHint::CreateRemoval(SpecLoc) << Insertion;
2539 DS.forEachQualifier(DeclSpecCheck);
2542 // Parse ref-qualifiers.
2543 bool RefQualifierIsLValueRef = true;
2544 SourceLocation RefQualifierLoc;
2545 if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc)) {
2546 const char *Name = (RefQualifierIsLValueRef ? "& " : "&& ");
2547 FixItHint Insertion =
2548 FixItHint::CreateInsertion(VS.getFirstLocation(), Name);
2549 Function.RefQualifierIsLValueRef = RefQualifierIsLValueRef;
2550 Function.RefQualifierLoc = RefQualifierLoc;
2552 Diag(RefQualifierLoc, diag::err_declspec_after_virtspec)
2553 << (RefQualifierIsLValueRef ? "&" : "&&")
2554 << VirtSpecifiers::getSpecifierName(VS.getLastSpecifier())
2555 << FixItHint::CreateRemoval(RefQualifierLoc) << Insertion;
2556 D.SetRangeEnd(RefQualifierLoc);
2561 /// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration.
2563 /// member-declaration:
2564 /// decl-specifier-seq[opt] member-declarator-list[opt] ';'
2565 /// function-definition ';'[opt]
2566 /// ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO]
2567 /// using-declaration [TODO]
2568 /// [C++0x] static_assert-declaration
2569 /// template-declaration
2570 /// [GNU] '__extension__' member-declaration
2572 /// member-declarator-list:
2573 /// member-declarator
2574 /// member-declarator-list ',' member-declarator
2576 /// member-declarator:
2577 /// declarator virt-specifier-seq[opt] pure-specifier[opt]
2578 /// [C++2a] declarator requires-clause
2579 /// declarator constant-initializer[opt]
2580 /// [C++11] declarator brace-or-equal-initializer[opt]
2581 /// identifier[opt] ':' constant-expression
2583 /// virt-specifier-seq:
2584 /// virt-specifier
2585 /// virt-specifier-seq virt-specifier
2587 /// virt-specifier:
2588 /// override
2589 /// final
2590 /// [MS] sealed
2592 /// pure-specifier:
2593 /// '= 0'
2595 /// constant-initializer:
2596 /// '=' constant-expression
2598 Parser::DeclGroupPtrTy
2599 Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS,
2600 ParsedAttributes &AccessAttrs,
2601 const ParsedTemplateInfo &TemplateInfo,
2602 ParsingDeclRAIIObject *TemplateDiags) {
2603 if (Tok.is(tok::at)) {
2604 if (getLangOpts().ObjC && NextToken().isObjCAtKeyword(tok::objc_defs))
2605 Diag(Tok, diag::err_at_defs_cxx);
2606 else
2607 Diag(Tok, diag::err_at_in_class);
2609 ConsumeToken();
2610 SkipUntil(tok::r_brace, StopAtSemi);
2611 return nullptr;
2614 // Turn on colon protection early, while parsing declspec, although there is
2615 // nothing to protect there. It prevents from false errors if error recovery
2616 // incorrectly determines where the declspec ends, as in the example:
2617 // struct A { enum class B { C }; };
2618 // const int C = 4;
2619 // struct D { A::B : C; };
2620 ColonProtectionRAIIObject X(*this);
2622 // Access declarations.
2623 bool MalformedTypeSpec = false;
2624 if (!TemplateInfo.Kind &&
2625 Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw___super)) {
2626 if (TryAnnotateCXXScopeToken())
2627 MalformedTypeSpec = true;
2629 bool isAccessDecl;
2630 if (Tok.isNot(tok::annot_cxxscope))
2631 isAccessDecl = false;
2632 else if (NextToken().is(tok::identifier))
2633 isAccessDecl = GetLookAheadToken(2).is(tok::semi);
2634 else
2635 isAccessDecl = NextToken().is(tok::kw_operator);
2637 if (isAccessDecl) {
2638 // Collect the scope specifier token we annotated earlier.
2639 CXXScopeSpec SS;
2640 ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
2641 /*ObjectHasErrors=*/false,
2642 /*EnteringContext=*/false);
2644 if (SS.isInvalid()) {
2645 SkipUntil(tok::semi);
2646 return nullptr;
2649 // Try to parse an unqualified-id.
2650 SourceLocation TemplateKWLoc;
2651 UnqualifiedId Name;
2652 if (ParseUnqualifiedId(SS, /*ObjectType=*/nullptr,
2653 /*ObjectHadErrors=*/false, false, true, true,
2654 false, &TemplateKWLoc, Name)) {
2655 SkipUntil(tok::semi);
2656 return nullptr;
2659 // TODO: recover from mistakenly-qualified operator declarations.
2660 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
2661 "access declaration")) {
2662 SkipUntil(tok::semi);
2663 return nullptr;
2666 // FIXME: We should do something with the 'template' keyword here.
2667 return DeclGroupPtrTy::make(DeclGroupRef(Actions.ActOnUsingDeclaration(
2668 getCurScope(), AS, /*UsingLoc*/ SourceLocation(),
2669 /*TypenameLoc*/ SourceLocation(), SS, Name,
2670 /*EllipsisLoc*/ SourceLocation(),
2671 /*AttrList*/ ParsedAttributesView())));
2675 // static_assert-declaration. A templated static_assert declaration is
2676 // diagnosed in Parser::ParseSingleDeclarationAfterTemplate.
2677 if (!TemplateInfo.Kind &&
2678 Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert)) {
2679 SourceLocation DeclEnd;
2680 return DeclGroupPtrTy::make(
2681 DeclGroupRef(ParseStaticAssertDeclaration(DeclEnd)));
2684 if (Tok.is(tok::kw_template)) {
2685 assert(!TemplateInfo.TemplateParams &&
2686 "Nested template improperly parsed?");
2687 ObjCDeclContextSwitch ObjCDC(*this);
2688 SourceLocation DeclEnd;
2689 return DeclGroupPtrTy::make(
2690 DeclGroupRef(ParseTemplateDeclarationOrSpecialization(
2691 DeclaratorContext::Member, DeclEnd, AccessAttrs, AS)));
2694 // Handle: member-declaration ::= '__extension__' member-declaration
2695 if (Tok.is(tok::kw___extension__)) {
2696 // __extension__ silences extension warnings in the subexpression.
2697 ExtensionRAIIObject O(Diags); // Use RAII to do this.
2698 ConsumeToken();
2699 return ParseCXXClassMemberDeclaration(AS, AccessAttrs, TemplateInfo,
2700 TemplateDiags);
2703 ParsedAttributes DeclAttrs(AttrFactory);
2704 // Optional C++11 attribute-specifier
2705 MaybeParseCXX11Attributes(DeclAttrs);
2707 // The next token may be an OpenMP pragma annotation token. That would
2708 // normally be handled from ParseCXXClassMemberDeclarationWithPragmas, but in
2709 // this case, it came from an *attribute* rather than a pragma. Handle it now.
2710 if (Tok.is(tok::annot_attr_openmp))
2711 return ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, DeclAttrs);
2713 if (Tok.is(tok::kw_using)) {
2714 // Eat 'using'.
2715 SourceLocation UsingLoc = ConsumeToken();
2717 // Consume unexpected 'template' keywords.
2718 while (Tok.is(tok::kw_template)) {
2719 SourceLocation TemplateLoc = ConsumeToken();
2720 Diag(TemplateLoc, diag::err_unexpected_template_after_using)
2721 << FixItHint::CreateRemoval(TemplateLoc);
2724 if (Tok.is(tok::kw_namespace)) {
2725 Diag(UsingLoc, diag::err_using_namespace_in_class);
2726 SkipUntil(tok::semi, StopBeforeMatch);
2727 return nullptr;
2729 SourceLocation DeclEnd;
2730 // Otherwise, it must be a using-declaration or an alias-declaration.
2731 return ParseUsingDeclaration(DeclaratorContext::Member, TemplateInfo,
2732 UsingLoc, DeclEnd, DeclAttrs, AS);
2735 ParsedAttributes DeclSpecAttrs(AttrFactory);
2736 MaybeParseMicrosoftAttributes(DeclSpecAttrs);
2738 // Hold late-parsed attributes so we can attach a Decl to them later.
2739 LateParsedAttrList CommonLateParsedAttrs;
2741 // decl-specifier-seq:
2742 // Parse the common declaration-specifiers piece.
2743 ParsingDeclSpec DS(*this, TemplateDiags);
2744 DS.takeAttributesFrom(DeclSpecAttrs);
2746 if (MalformedTypeSpec)
2747 DS.SetTypeSpecError();
2749 // Turn off usual access checking for templates explicit specialization
2750 // and instantiation.
2751 // C++20 [temp.spec] 13.9/6.
2752 // This disables the access checking rules for member function template
2753 // explicit instantiation and explicit specialization.
2754 bool IsTemplateSpecOrInst =
2755 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
2756 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
2757 SuppressAccessChecks diagsFromTag(*this, IsTemplateSpecOrInst);
2759 ParseDeclarationSpecifiers(DS, TemplateInfo, AS, DeclSpecContext::DSC_class,
2760 &CommonLateParsedAttrs);
2762 if (IsTemplateSpecOrInst)
2763 diagsFromTag.done();
2765 // Turn off colon protection that was set for declspec.
2766 X.restore();
2768 // If we had a free-standing type definition with a missing semicolon, we
2769 // may get this far before the problem becomes obvious.
2770 if (DS.hasTagDefinition() &&
2771 TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate &&
2772 DiagnoseMissingSemiAfterTagDefinition(DS, AS, DeclSpecContext::DSC_class,
2773 &CommonLateParsedAttrs))
2774 return nullptr;
2776 MultiTemplateParamsArg TemplateParams(
2777 TemplateInfo.TemplateParams ? TemplateInfo.TemplateParams->data()
2778 : nullptr,
2779 TemplateInfo.TemplateParams ? TemplateInfo.TemplateParams->size() : 0);
2781 if (TryConsumeToken(tok::semi)) {
2782 if (DS.isFriendSpecified())
2783 ProhibitAttributes(DeclAttrs);
2785 RecordDecl *AnonRecord = nullptr;
2786 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(
2787 getCurScope(), AS, DS, DeclAttrs, TemplateParams, false, AnonRecord);
2788 DS.complete(TheDecl);
2789 if (AnonRecord) {
2790 Decl *decls[] = {AnonRecord, TheDecl};
2791 return Actions.BuildDeclaratorGroup(decls);
2793 return Actions.ConvertDeclToDeclGroup(TheDecl);
2796 ParsingDeclarator DeclaratorInfo(*this, DS, DeclAttrs,
2797 DeclaratorContext::Member);
2798 if (TemplateInfo.TemplateParams)
2799 DeclaratorInfo.setTemplateParameterLists(TemplateParams);
2800 VirtSpecifiers VS;
2802 // Hold late-parsed attributes so we can attach a Decl to them later.
2803 LateParsedAttrList LateParsedAttrs;
2805 SourceLocation EqualLoc;
2806 SourceLocation PureSpecLoc;
2808 auto TryConsumePureSpecifier = [&](bool AllowDefinition) {
2809 if (Tok.isNot(tok::equal))
2810 return false;
2812 auto &Zero = NextToken();
2813 SmallString<8> Buffer;
2814 if (Zero.isNot(tok::numeric_constant) ||
2815 PP.getSpelling(Zero, Buffer) != "0")
2816 return false;
2818 auto &After = GetLookAheadToken(2);
2819 if (!After.isOneOf(tok::semi, tok::comma) &&
2820 !(AllowDefinition &&
2821 After.isOneOf(tok::l_brace, tok::colon, tok::kw_try)))
2822 return false;
2824 EqualLoc = ConsumeToken();
2825 PureSpecLoc = ConsumeToken();
2826 return true;
2829 SmallVector<Decl *, 8> DeclsInGroup;
2830 ExprResult BitfieldSize;
2831 ExprResult TrailingRequiresClause;
2832 bool ExpectSemi = true;
2834 // C++20 [temp.spec] 13.9/6.
2835 // This disables the access checking rules for member function template
2836 // explicit instantiation and explicit specialization.
2837 SuppressAccessChecks SAC(*this, IsTemplateSpecOrInst);
2839 // Parse the first declarator.
2840 if (ParseCXXMemberDeclaratorBeforeInitializer(
2841 DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs)) {
2842 TryConsumeToken(tok::semi);
2843 return nullptr;
2846 if (IsTemplateSpecOrInst)
2847 SAC.done();
2849 // Check for a member function definition.
2850 if (BitfieldSize.isUnset()) {
2851 // MSVC permits pure specifier on inline functions defined at class scope.
2852 // Hence check for =0 before checking for function definition.
2853 if (getLangOpts().MicrosoftExt && DeclaratorInfo.isDeclarationOfFunction())
2854 TryConsumePureSpecifier(/*AllowDefinition*/ true);
2856 FunctionDefinitionKind DefinitionKind = FunctionDefinitionKind::Declaration;
2857 // function-definition:
2859 // In C++11, a non-function declarator followed by an open brace is a
2860 // braced-init-list for an in-class member initialization, not an
2861 // erroneous function definition.
2862 if (Tok.is(tok::l_brace) && !getLangOpts().CPlusPlus11) {
2863 DefinitionKind = FunctionDefinitionKind::Definition;
2864 } else if (DeclaratorInfo.isFunctionDeclarator()) {
2865 if (Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try)) {
2866 DefinitionKind = FunctionDefinitionKind::Definition;
2867 } else if (Tok.is(tok::equal)) {
2868 const Token &KW = NextToken();
2869 if (KW.is(tok::kw_default))
2870 DefinitionKind = FunctionDefinitionKind::Defaulted;
2871 else if (KW.is(tok::kw_delete))
2872 DefinitionKind = FunctionDefinitionKind::Deleted;
2873 else if (KW.is(tok::code_completion)) {
2874 cutOffParsing();
2875 Actions.CodeCompleteAfterFunctionEquals(DeclaratorInfo);
2876 return nullptr;
2880 DeclaratorInfo.setFunctionDefinitionKind(DefinitionKind);
2882 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
2883 // to a friend declaration, that declaration shall be a definition.
2884 if (DeclaratorInfo.isFunctionDeclarator() &&
2885 DefinitionKind == FunctionDefinitionKind::Declaration &&
2886 DS.isFriendSpecified()) {
2887 // Diagnose attributes that appear before decl specifier:
2888 // [[]] friend int foo();
2889 ProhibitAttributes(DeclAttrs);
2892 if (DefinitionKind != FunctionDefinitionKind::Declaration) {
2893 if (!DeclaratorInfo.isFunctionDeclarator()) {
2894 Diag(DeclaratorInfo.getIdentifierLoc(), diag::err_func_def_no_params);
2895 ConsumeBrace();
2896 SkipUntil(tok::r_brace);
2898 // Consume the optional ';'
2899 TryConsumeToken(tok::semi);
2901 return nullptr;
2904 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
2905 Diag(DeclaratorInfo.getIdentifierLoc(),
2906 diag::err_function_declared_typedef);
2908 // Recover by treating the 'typedef' as spurious.
2909 DS.ClearStorageClassSpecs();
2912 Decl *FunDecl = ParseCXXInlineMethodDef(AS, AccessAttrs, DeclaratorInfo,
2913 TemplateInfo, VS, PureSpecLoc);
2915 if (FunDecl) {
2916 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i) {
2917 CommonLateParsedAttrs[i]->addDecl(FunDecl);
2919 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i) {
2920 LateParsedAttrs[i]->addDecl(FunDecl);
2923 LateParsedAttrs.clear();
2925 // Consume the ';' - it's optional unless we have a delete or default
2926 if (Tok.is(tok::semi))
2927 ConsumeExtraSemi(AfterMemberFunctionDefinition);
2929 return DeclGroupPtrTy::make(DeclGroupRef(FunDecl));
2933 // member-declarator-list:
2934 // member-declarator
2935 // member-declarator-list ',' member-declarator
2937 while (true) {
2938 InClassInitStyle HasInClassInit = ICIS_NoInit;
2939 bool HasStaticInitializer = false;
2940 if (Tok.isOneOf(tok::equal, tok::l_brace) && PureSpecLoc.isInvalid()) {
2941 // DRXXXX: Anonymous bit-fields cannot have a brace-or-equal-initializer.
2942 if (BitfieldSize.isUsable() && !DeclaratorInfo.hasName()) {
2943 // Diagnose the error and pretend there is no in-class initializer.
2944 Diag(Tok, diag::err_anon_bitfield_member_init);
2945 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2946 } else if (DeclaratorInfo.isDeclarationOfFunction()) {
2947 // It's a pure-specifier.
2948 if (!TryConsumePureSpecifier(/*AllowFunctionDefinition*/ false))
2949 // Parse it as an expression so that Sema can diagnose it.
2950 HasStaticInitializer = true;
2951 } else if (DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2952 DeclSpec::SCS_static &&
2953 DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2954 DeclSpec::SCS_typedef &&
2955 !DS.isFriendSpecified()) {
2956 // It's a default member initializer.
2957 if (BitfieldSize.get())
2958 Diag(Tok, getLangOpts().CPlusPlus20
2959 ? diag::warn_cxx17_compat_bitfield_member_init
2960 : diag::ext_bitfield_member_init);
2961 HasInClassInit = Tok.is(tok::equal) ? ICIS_CopyInit : ICIS_ListInit;
2962 } else {
2963 HasStaticInitializer = true;
2967 // NOTE: If Sema is the Action module and declarator is an instance field,
2968 // this call will *not* return the created decl; It will return null.
2969 // See Sema::ActOnCXXMemberDeclarator for details.
2971 NamedDecl *ThisDecl = nullptr;
2972 if (DS.isFriendSpecified()) {
2973 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
2974 // to a friend declaration, that declaration shall be a definition.
2976 // Diagnose attributes that appear in a friend member function declarator:
2977 // friend int foo [[]] ();
2978 SmallVector<SourceRange, 4> Ranges;
2979 DeclaratorInfo.getCXX11AttributeRanges(Ranges);
2980 for (SmallVectorImpl<SourceRange>::iterator I = Ranges.begin(),
2981 E = Ranges.end();
2982 I != E; ++I)
2983 Diag((*I).getBegin(), diag::err_attributes_not_allowed) << *I;
2985 ThisDecl = Actions.ActOnFriendFunctionDecl(getCurScope(), DeclaratorInfo,
2986 TemplateParams);
2987 } else {
2988 ThisDecl = Actions.ActOnCXXMemberDeclarator(
2989 getCurScope(), AS, DeclaratorInfo, TemplateParams, BitfieldSize.get(),
2990 VS, HasInClassInit);
2992 if (VarTemplateDecl *VT =
2993 ThisDecl ? dyn_cast<VarTemplateDecl>(ThisDecl) : nullptr)
2994 // Re-direct this decl to refer to the templated decl so that we can
2995 // initialize it.
2996 ThisDecl = VT->getTemplatedDecl();
2998 if (ThisDecl)
2999 Actions.ProcessDeclAttributeList(getCurScope(), ThisDecl, AccessAttrs);
3002 // Error recovery might have converted a non-static member into a static
3003 // member.
3004 if (HasInClassInit != ICIS_NoInit &&
3005 DeclaratorInfo.getDeclSpec().getStorageClassSpec() ==
3006 DeclSpec::SCS_static) {
3007 HasInClassInit = ICIS_NoInit;
3008 HasStaticInitializer = true;
3011 if (PureSpecLoc.isValid() && VS.getAbstractLoc().isValid()) {
3012 Diag(PureSpecLoc, diag::err_duplicate_virt_specifier) << "abstract";
3014 if (ThisDecl && PureSpecLoc.isValid())
3015 Actions.ActOnPureSpecifier(ThisDecl, PureSpecLoc);
3016 else if (ThisDecl && VS.getAbstractLoc().isValid())
3017 Actions.ActOnPureSpecifier(ThisDecl, VS.getAbstractLoc());
3019 // Handle the initializer.
3020 if (HasInClassInit != ICIS_NoInit) {
3021 // The initializer was deferred; parse it and cache the tokens.
3022 Diag(Tok, getLangOpts().CPlusPlus11
3023 ? diag::warn_cxx98_compat_nonstatic_member_init
3024 : diag::ext_nonstatic_member_init);
3026 if (DeclaratorInfo.isArrayOfUnknownBound()) {
3027 // C++11 [dcl.array]p3: An array bound may also be omitted when the
3028 // declarator is followed by an initializer.
3030 // A brace-or-equal-initializer for a member-declarator is not an
3031 // initializer in the grammar, so this is ill-formed.
3032 Diag(Tok, diag::err_incomplete_array_member_init);
3033 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
3035 // Avoid later warnings about a class member of incomplete type.
3036 if (ThisDecl)
3037 ThisDecl->setInvalidDecl();
3038 } else
3039 ParseCXXNonStaticMemberInitializer(ThisDecl);
3040 } else if (HasStaticInitializer) {
3041 // Normal initializer.
3042 ExprResult Init = ParseCXXMemberInitializer(
3043 ThisDecl, DeclaratorInfo.isDeclarationOfFunction(), EqualLoc);
3045 if (Init.isInvalid()) {
3046 if (ThisDecl)
3047 Actions.ActOnUninitializedDecl(ThisDecl);
3048 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
3049 } else if (ThisDecl)
3050 Actions.AddInitializerToDecl(ThisDecl, Init.get(),
3051 EqualLoc.isInvalid());
3052 } else if (ThisDecl && DS.getStorageClassSpec() == DeclSpec::SCS_static)
3053 // No initializer.
3054 Actions.ActOnUninitializedDecl(ThisDecl);
3056 if (ThisDecl) {
3057 if (!ThisDecl->isInvalidDecl()) {
3058 // Set the Decl for any late parsed attributes
3059 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i)
3060 CommonLateParsedAttrs[i]->addDecl(ThisDecl);
3062 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i)
3063 LateParsedAttrs[i]->addDecl(ThisDecl);
3065 Actions.FinalizeDeclaration(ThisDecl);
3066 DeclsInGroup.push_back(ThisDecl);
3068 if (DeclaratorInfo.isFunctionDeclarator() &&
3069 DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
3070 DeclSpec::SCS_typedef)
3071 HandleMemberFunctionDeclDelays(DeclaratorInfo, ThisDecl);
3073 LateParsedAttrs.clear();
3075 DeclaratorInfo.complete(ThisDecl);
3077 // If we don't have a comma, it is either the end of the list (a ';')
3078 // or an error, bail out.
3079 SourceLocation CommaLoc;
3080 if (!TryConsumeToken(tok::comma, CommaLoc))
3081 break;
3083 if (Tok.isAtStartOfLine() &&
3084 !MightBeDeclarator(DeclaratorContext::Member)) {
3085 // This comma was followed by a line-break and something which can't be
3086 // the start of a declarator. The comma was probably a typo for a
3087 // semicolon.
3088 Diag(CommaLoc, diag::err_expected_semi_declaration)
3089 << FixItHint::CreateReplacement(CommaLoc, ";");
3090 ExpectSemi = false;
3091 break;
3094 // Parse the next declarator.
3095 DeclaratorInfo.clear();
3096 VS.clear();
3097 BitfieldSize = ExprResult(/*Invalid=*/false);
3098 EqualLoc = PureSpecLoc = SourceLocation();
3099 DeclaratorInfo.setCommaLoc(CommaLoc);
3101 // GNU attributes are allowed before the second and subsequent declarator.
3102 // However, this does not apply for [[]] attributes (which could show up
3103 // before or after the __attribute__ attributes).
3104 DiagnoseAndSkipCXX11Attributes();
3105 MaybeParseGNUAttributes(DeclaratorInfo);
3106 DiagnoseAndSkipCXX11Attributes();
3108 if (ParseCXXMemberDeclaratorBeforeInitializer(
3109 DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs))
3110 break;
3113 if (ExpectSemi &&
3114 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list)) {
3115 // Skip to end of block or statement.
3116 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
3117 // If we stopped at a ';', eat it.
3118 TryConsumeToken(tok::semi);
3119 return nullptr;
3122 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
3125 /// ParseCXXMemberInitializer - Parse the brace-or-equal-initializer.
3126 /// Also detect and reject any attempted defaulted/deleted function definition.
3127 /// The location of the '=', if any, will be placed in EqualLoc.
3129 /// This does not check for a pure-specifier; that's handled elsewhere.
3131 /// brace-or-equal-initializer:
3132 /// '=' initializer-expression
3133 /// braced-init-list
3135 /// initializer-clause:
3136 /// assignment-expression
3137 /// braced-init-list
3139 /// defaulted/deleted function-definition:
3140 /// '=' 'default'
3141 /// '=' 'delete'
3143 /// Prior to C++0x, the assignment-expression in an initializer-clause must
3144 /// be a constant-expression.
3145 ExprResult Parser::ParseCXXMemberInitializer(Decl *D, bool IsFunction,
3146 SourceLocation &EqualLoc) {
3147 assert(Tok.isOneOf(tok::equal, tok::l_brace) &&
3148 "Data member initializer not starting with '=' or '{'");
3150 EnterExpressionEvaluationContext Context(
3151 Actions, Sema::ExpressionEvaluationContext::PotentiallyEvaluated, D);
3152 if (TryConsumeToken(tok::equal, EqualLoc)) {
3153 if (Tok.is(tok::kw_delete)) {
3154 // In principle, an initializer of '= delete p;' is legal, but it will
3155 // never type-check. It's better to diagnose it as an ill-formed
3156 // expression than as an ill-formed deleted non-function member. An
3157 // initializer of '= delete p, foo' will never be parsed, because a
3158 // top-level comma always ends the initializer expression.
3159 const Token &Next = NextToken();
3160 if (IsFunction || Next.isOneOf(tok::semi, tok::comma, tok::eof)) {
3161 if (IsFunction)
3162 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
3163 << 1 /* delete */;
3164 else
3165 Diag(ConsumeToken(), diag::err_deleted_non_function);
3166 return ExprError();
3168 } else if (Tok.is(tok::kw_default)) {
3169 if (IsFunction)
3170 Diag(Tok, diag::err_default_delete_in_multiple_declaration)
3171 << 0 /* default */;
3172 else
3173 Diag(ConsumeToken(), diag::err_default_special_members)
3174 << getLangOpts().CPlusPlus20;
3175 return ExprError();
3178 if (const auto *PD = dyn_cast_or_null<MSPropertyDecl>(D)) {
3179 Diag(Tok, diag::err_ms_property_initializer) << PD;
3180 return ExprError();
3182 return ParseInitializer();
3185 void Parser::SkipCXXMemberSpecification(SourceLocation RecordLoc,
3186 SourceLocation AttrFixitLoc,
3187 unsigned TagType, Decl *TagDecl) {
3188 // Skip the optional 'final' keyword.
3189 if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
3190 assert(isCXX11FinalKeyword() && "not a class definition");
3191 ConsumeToken();
3193 // Diagnose any C++11 attributes after 'final' keyword.
3194 // We deliberately discard these attributes.
3195 ParsedAttributes Attrs(AttrFactory);
3196 CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
3198 // This can only happen if we had malformed misplaced attributes;
3199 // we only get called if there is a colon or left-brace after the
3200 // attributes.
3201 if (Tok.isNot(tok::colon) && Tok.isNot(tok::l_brace))
3202 return;
3205 // Skip the base clauses. This requires actually parsing them, because
3206 // otherwise we can't be sure where they end (a left brace may appear
3207 // within a template argument).
3208 if (Tok.is(tok::colon)) {
3209 // Enter the scope of the class so that we can correctly parse its bases.
3210 ParseScope ClassScope(this, Scope::ClassScope | Scope::DeclScope);
3211 ParsingClassDefinition ParsingDef(*this, TagDecl, /*NonNestedClass*/ true,
3212 TagType == DeclSpec::TST_interface);
3213 auto OldContext =
3214 Actions.ActOnTagStartSkippedDefinition(getCurScope(), TagDecl);
3216 // Parse the bases but don't attach them to the class.
3217 ParseBaseClause(nullptr);
3219 Actions.ActOnTagFinishSkippedDefinition(OldContext);
3221 if (!Tok.is(tok::l_brace)) {
3222 Diag(PP.getLocForEndOfToken(PrevTokLocation),
3223 diag::err_expected_lbrace_after_base_specifiers);
3224 return;
3228 // Skip the body.
3229 assert(Tok.is(tok::l_brace));
3230 BalancedDelimiterTracker T(*this, tok::l_brace);
3231 T.consumeOpen();
3232 T.skipToEnd();
3234 // Parse and discard any trailing attributes.
3235 if (Tok.is(tok::kw___attribute)) {
3236 ParsedAttributes Attrs(AttrFactory);
3237 MaybeParseGNUAttributes(Attrs);
3241 Parser::DeclGroupPtrTy Parser::ParseCXXClassMemberDeclarationWithPragmas(
3242 AccessSpecifier &AS, ParsedAttributes &AccessAttrs, DeclSpec::TST TagType,
3243 Decl *TagDecl) {
3244 ParenBraceBracketBalancer BalancerRAIIObj(*this);
3246 switch (Tok.getKind()) {
3247 case tok::kw___if_exists:
3248 case tok::kw___if_not_exists:
3249 ParseMicrosoftIfExistsClassDeclaration(TagType, AccessAttrs, AS);
3250 return nullptr;
3252 case tok::semi:
3253 // Check for extraneous top-level semicolon.
3254 ConsumeExtraSemi(InsideStruct, TagType);
3255 return nullptr;
3257 // Handle pragmas that can appear as member declarations.
3258 case tok::annot_pragma_vis:
3259 HandlePragmaVisibility();
3260 return nullptr;
3261 case tok::annot_pragma_pack:
3262 HandlePragmaPack();
3263 return nullptr;
3264 case tok::annot_pragma_align:
3265 HandlePragmaAlign();
3266 return nullptr;
3267 case tok::annot_pragma_ms_pointers_to_members:
3268 HandlePragmaMSPointersToMembers();
3269 return nullptr;
3270 case tok::annot_pragma_ms_pragma:
3271 HandlePragmaMSPragma();
3272 return nullptr;
3273 case tok::annot_pragma_ms_vtordisp:
3274 HandlePragmaMSVtorDisp();
3275 return nullptr;
3276 case tok::annot_pragma_dump:
3277 HandlePragmaDump();
3278 return nullptr;
3280 case tok::kw_namespace:
3281 // If we see a namespace here, a close brace was missing somewhere.
3282 DiagnoseUnexpectedNamespace(cast<NamedDecl>(TagDecl));
3283 return nullptr;
3285 case tok::kw_private:
3286 // FIXME: We don't accept GNU attributes on access specifiers in OpenCL mode
3287 // yet.
3288 if (getLangOpts().OpenCL && !NextToken().is(tok::colon))
3289 return ParseCXXClassMemberDeclaration(AS, AccessAttrs);
3290 [[fallthrough]];
3291 case tok::kw_public:
3292 case tok::kw_protected: {
3293 if (getLangOpts().HLSL)
3294 Diag(Tok.getLocation(), diag::ext_hlsl_access_specifiers);
3295 AccessSpecifier NewAS = getAccessSpecifierIfPresent();
3296 assert(NewAS != AS_none);
3297 // Current token is a C++ access specifier.
3298 AS = NewAS;
3299 SourceLocation ASLoc = Tok.getLocation();
3300 unsigned TokLength = Tok.getLength();
3301 ConsumeToken();
3302 AccessAttrs.clear();
3303 MaybeParseGNUAttributes(AccessAttrs);
3305 SourceLocation EndLoc;
3306 if (TryConsumeToken(tok::colon, EndLoc)) {
3307 } else if (TryConsumeToken(tok::semi, EndLoc)) {
3308 Diag(EndLoc, diag::err_expected)
3309 << tok::colon << FixItHint::CreateReplacement(EndLoc, ":");
3310 } else {
3311 EndLoc = ASLoc.getLocWithOffset(TokLength);
3312 Diag(EndLoc, diag::err_expected)
3313 << tok::colon << FixItHint::CreateInsertion(EndLoc, ":");
3316 // The Microsoft extension __interface does not permit non-public
3317 // access specifiers.
3318 if (TagType == DeclSpec::TST_interface && AS != AS_public) {
3319 Diag(ASLoc, diag::err_access_specifier_interface) << (AS == AS_protected);
3322 if (Actions.ActOnAccessSpecifier(NewAS, ASLoc, EndLoc, AccessAttrs)) {
3323 // found another attribute than only annotations
3324 AccessAttrs.clear();
3327 return nullptr;
3330 case tok::annot_attr_openmp:
3331 case tok::annot_pragma_openmp:
3332 return ParseOpenMPDeclarativeDirectiveWithExtDecl(
3333 AS, AccessAttrs, /*Delayed=*/true, TagType, TagDecl);
3335 default:
3336 if (tok::isPragmaAnnotation(Tok.getKind())) {
3337 Diag(Tok.getLocation(), diag::err_pragma_misplaced_in_decl)
3338 << DeclSpec::getSpecifierName(
3339 TagType, Actions.getASTContext().getPrintingPolicy());
3340 ConsumeAnnotationToken();
3341 return nullptr;
3343 return ParseCXXClassMemberDeclaration(AS, AccessAttrs);
3347 /// ParseCXXMemberSpecification - Parse the class definition.
3349 /// member-specification:
3350 /// member-declaration member-specification[opt]
3351 /// access-specifier ':' member-specification[opt]
3353 void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc,
3354 SourceLocation AttrFixitLoc,
3355 ParsedAttributes &Attrs,
3356 unsigned TagType, Decl *TagDecl) {
3357 assert((TagType == DeclSpec::TST_struct ||
3358 TagType == DeclSpec::TST_interface ||
3359 TagType == DeclSpec::TST_union || TagType == DeclSpec::TST_class) &&
3360 "Invalid TagType!");
3362 llvm::TimeTraceScope TimeScope("ParseClass", [&]() {
3363 if (auto *TD = dyn_cast_or_null<NamedDecl>(TagDecl))
3364 return TD->getQualifiedNameAsString();
3365 return std::string("<anonymous>");
3368 PrettyDeclStackTraceEntry CrashInfo(Actions.Context, TagDecl, RecordLoc,
3369 "parsing struct/union/class body");
3371 // Determine whether this is a non-nested class. Note that local
3372 // classes are *not* considered to be nested classes.
3373 bool NonNestedClass = true;
3374 if (!ClassStack.empty()) {
3375 for (const Scope *S = getCurScope(); S; S = S->getParent()) {
3376 if (S->isClassScope()) {
3377 // We're inside a class scope, so this is a nested class.
3378 NonNestedClass = false;
3380 // The Microsoft extension __interface does not permit nested classes.
3381 if (getCurrentClass().IsInterface) {
3382 Diag(RecordLoc, diag::err_invalid_member_in_interface)
3383 << /*ErrorType=*/6
3384 << (isa<NamedDecl>(TagDecl)
3385 ? cast<NamedDecl>(TagDecl)->getQualifiedNameAsString()
3386 : "(anonymous)");
3388 break;
3391 if (S->isFunctionScope())
3392 // If we're in a function or function template then this is a local
3393 // class rather than a nested class.
3394 break;
3398 // Enter a scope for the class.
3399 ParseScope ClassScope(this, Scope::ClassScope | Scope::DeclScope);
3401 // Note that we are parsing a new (potentially-nested) class definition.
3402 ParsingClassDefinition ParsingDef(*this, TagDecl, NonNestedClass,
3403 TagType == DeclSpec::TST_interface);
3405 if (TagDecl)
3406 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
3408 SourceLocation FinalLoc;
3409 SourceLocation AbstractLoc;
3410 bool IsFinalSpelledSealed = false;
3411 bool IsAbstract = false;
3413 // Parse the optional 'final' keyword.
3414 if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
3415 while (true) {
3416 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier(Tok);
3417 if (Specifier == VirtSpecifiers::VS_None)
3418 break;
3419 if (isCXX11FinalKeyword()) {
3420 if (FinalLoc.isValid()) {
3421 auto Skipped = ConsumeToken();
3422 Diag(Skipped, diag::err_duplicate_class_virt_specifier)
3423 << VirtSpecifiers::getSpecifierName(Specifier);
3424 } else {
3425 FinalLoc = ConsumeToken();
3426 if (Specifier == VirtSpecifiers::VS_Sealed)
3427 IsFinalSpelledSealed = true;
3429 } else {
3430 if (AbstractLoc.isValid()) {
3431 auto Skipped = ConsumeToken();
3432 Diag(Skipped, diag::err_duplicate_class_virt_specifier)
3433 << VirtSpecifiers::getSpecifierName(Specifier);
3434 } else {
3435 AbstractLoc = ConsumeToken();
3436 IsAbstract = true;
3439 if (TagType == DeclSpec::TST_interface)
3440 Diag(FinalLoc, diag::err_override_control_interface)
3441 << VirtSpecifiers::getSpecifierName(Specifier);
3442 else if (Specifier == VirtSpecifiers::VS_Final)
3443 Diag(FinalLoc, getLangOpts().CPlusPlus11
3444 ? diag::warn_cxx98_compat_override_control_keyword
3445 : diag::ext_override_control_keyword)
3446 << VirtSpecifiers::getSpecifierName(Specifier);
3447 else if (Specifier == VirtSpecifiers::VS_Sealed)
3448 Diag(FinalLoc, diag::ext_ms_sealed_keyword);
3449 else if (Specifier == VirtSpecifiers::VS_Abstract)
3450 Diag(AbstractLoc, diag::ext_ms_abstract_keyword);
3451 else if (Specifier == VirtSpecifiers::VS_GNU_Final)
3452 Diag(FinalLoc, diag::ext_warn_gnu_final);
3454 assert((FinalLoc.isValid() || AbstractLoc.isValid()) &&
3455 "not a class definition");
3457 // Parse any C++11 attributes after 'final' keyword.
3458 // These attributes are not allowed to appear here,
3459 // and the only possible place for them to appertain
3460 // to the class would be between class-key and class-name.
3461 CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
3463 // ParseClassSpecifier() does only a superficial check for attributes before
3464 // deciding to call this method. For example, for
3465 // `class C final alignas ([l) {` it will decide that this looks like a
3466 // misplaced attribute since it sees `alignas '(' ')'`. But the actual
3467 // attribute parsing code will try to parse the '[' as a constexpr lambda
3468 // and consume enough tokens that the alignas parsing code will eat the
3469 // opening '{'. So bail out if the next token isn't one we expect.
3470 if (!Tok.is(tok::colon) && !Tok.is(tok::l_brace)) {
3471 if (TagDecl)
3472 Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
3473 return;
3477 if (Tok.is(tok::colon)) {
3478 ParseScope InheritanceScope(this, getCurScope()->getFlags() |
3479 Scope::ClassInheritanceScope);
3481 ParseBaseClause(TagDecl);
3482 if (!Tok.is(tok::l_brace)) {
3483 bool SuggestFixIt = false;
3484 SourceLocation BraceLoc = PP.getLocForEndOfToken(PrevTokLocation);
3485 if (Tok.isAtStartOfLine()) {
3486 switch (Tok.getKind()) {
3487 case tok::kw_private:
3488 case tok::kw_protected:
3489 case tok::kw_public:
3490 SuggestFixIt = NextToken().getKind() == tok::colon;
3491 break;
3492 case tok::kw_static_assert:
3493 case tok::r_brace:
3494 case tok::kw_using:
3495 // base-clause can have simple-template-id; 'template' can't be there
3496 case tok::kw_template:
3497 SuggestFixIt = true;
3498 break;
3499 case tok::identifier:
3500 SuggestFixIt = isConstructorDeclarator(true);
3501 break;
3502 default:
3503 SuggestFixIt = isCXXSimpleDeclaration(/*AllowForRangeDecl=*/false);
3504 break;
3507 DiagnosticBuilder LBraceDiag =
3508 Diag(BraceLoc, diag::err_expected_lbrace_after_base_specifiers);
3509 if (SuggestFixIt) {
3510 LBraceDiag << FixItHint::CreateInsertion(BraceLoc, " {");
3511 // Try recovering from missing { after base-clause.
3512 PP.EnterToken(Tok, /*IsReinject*/ true);
3513 Tok.setKind(tok::l_brace);
3514 } else {
3515 if (TagDecl)
3516 Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
3517 return;
3522 assert(Tok.is(tok::l_brace));
3523 BalancedDelimiterTracker T(*this, tok::l_brace);
3524 T.consumeOpen();
3526 if (TagDecl)
3527 Actions.ActOnStartCXXMemberDeclarations(getCurScope(), TagDecl, FinalLoc,
3528 IsFinalSpelledSealed, IsAbstract,
3529 T.getOpenLocation());
3531 // C++ 11p3: Members of a class defined with the keyword class are private
3532 // by default. Members of a class defined with the keywords struct or union
3533 // are public by default.
3534 // HLSL: In HLSL members of a class are public by default.
3535 AccessSpecifier CurAS;
3536 if (TagType == DeclSpec::TST_class && !getLangOpts().HLSL)
3537 CurAS = AS_private;
3538 else
3539 CurAS = AS_public;
3540 ParsedAttributes AccessAttrs(AttrFactory);
3542 if (TagDecl) {
3543 // While we still have something to read, read the member-declarations.
3544 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
3545 Tok.isNot(tok::eof)) {
3546 // Each iteration of this loop reads one member-declaration.
3547 ParseCXXClassMemberDeclarationWithPragmas(
3548 CurAS, AccessAttrs, static_cast<DeclSpec::TST>(TagType), TagDecl);
3549 MaybeDestroyTemplateIds();
3551 T.consumeClose();
3552 } else {
3553 SkipUntil(tok::r_brace);
3556 // If attributes exist after class contents, parse them.
3557 ParsedAttributes attrs(AttrFactory);
3558 MaybeParseGNUAttributes(attrs);
3560 if (TagDecl)
3561 Actions.ActOnFinishCXXMemberSpecification(getCurScope(), RecordLoc, TagDecl,
3562 T.getOpenLocation(),
3563 T.getCloseLocation(), attrs);
3565 // C++11 [class.mem]p2:
3566 // Within the class member-specification, the class is regarded as complete
3567 // within function bodies, default arguments, exception-specifications, and
3568 // brace-or-equal-initializers for non-static data members (including such
3569 // things in nested classes).
3570 if (TagDecl && NonNestedClass) {
3571 // We are not inside a nested class. This class and its nested classes
3572 // are complete and we can parse the delayed portions of method
3573 // declarations and the lexed inline method definitions, along with any
3574 // delayed attributes.
3576 SourceLocation SavedPrevTokLocation = PrevTokLocation;
3577 ParseLexedPragmas(getCurrentClass());
3578 ParseLexedAttributes(getCurrentClass());
3579 ParseLexedMethodDeclarations(getCurrentClass());
3581 // We've finished with all pending member declarations.
3582 Actions.ActOnFinishCXXMemberDecls();
3584 ParseLexedMemberInitializers(getCurrentClass());
3585 ParseLexedMethodDefs(getCurrentClass());
3586 PrevTokLocation = SavedPrevTokLocation;
3588 // We've finished parsing everything, including default argument
3589 // initializers.
3590 Actions.ActOnFinishCXXNonNestedClass();
3593 if (TagDecl)
3594 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getRange());
3596 // Leave the class scope.
3597 ParsingDef.Pop();
3598 ClassScope.Exit();
3601 void Parser::DiagnoseUnexpectedNamespace(NamedDecl *D) {
3602 assert(Tok.is(tok::kw_namespace));
3604 // FIXME: Suggest where the close brace should have gone by looking
3605 // at indentation changes within the definition body.
3606 Diag(D->getLocation(), diag::err_missing_end_of_definition) << D;
3607 Diag(Tok.getLocation(), diag::note_missing_end_of_definition_before) << D;
3609 // Push '};' onto the token stream to recover.
3610 PP.EnterToken(Tok, /*IsReinject*/ true);
3612 Tok.startToken();
3613 Tok.setLocation(PP.getLocForEndOfToken(PrevTokLocation));
3614 Tok.setKind(tok::semi);
3615 PP.EnterToken(Tok, /*IsReinject*/ true);
3617 Tok.setKind(tok::r_brace);
3620 /// ParseConstructorInitializer - Parse a C++ constructor initializer,
3621 /// which explicitly initializes the members or base classes of a
3622 /// class (C++ [class.base.init]). For example, the three initializers
3623 /// after the ':' in the Derived constructor below:
3625 /// @code
3626 /// class Base { };
3627 /// class Derived : Base {
3628 /// int x;
3629 /// float f;
3630 /// public:
3631 /// Derived(float f) : Base(), x(17), f(f) { }
3632 /// };
3633 /// @endcode
3635 /// [C++] ctor-initializer:
3636 /// ':' mem-initializer-list
3638 /// [C++] mem-initializer-list:
3639 /// mem-initializer ...[opt]
3640 /// mem-initializer ...[opt] , mem-initializer-list
3641 void Parser::ParseConstructorInitializer(Decl *ConstructorDecl) {
3642 assert(Tok.is(tok::colon) &&
3643 "Constructor initializer always starts with ':'");
3645 // Poison the SEH identifiers so they are flagged as illegal in constructor
3646 // initializers.
3647 PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
3648 SourceLocation ColonLoc = ConsumeToken();
3650 SmallVector<CXXCtorInitializer *, 4> MemInitializers;
3651 bool AnyErrors = false;
3653 do {
3654 if (Tok.is(tok::code_completion)) {
3655 cutOffParsing();
3656 Actions.CodeCompleteConstructorInitializer(ConstructorDecl,
3657 MemInitializers);
3658 return;
3661 MemInitResult MemInit = ParseMemInitializer(ConstructorDecl);
3662 if (!MemInit.isInvalid())
3663 MemInitializers.push_back(MemInit.get());
3664 else
3665 AnyErrors = true;
3667 if (Tok.is(tok::comma))
3668 ConsumeToken();
3669 else if (Tok.is(tok::l_brace))
3670 break;
3671 // If the previous initializer was valid and the next token looks like a
3672 // base or member initializer, assume that we're just missing a comma.
3673 else if (!MemInit.isInvalid() &&
3674 Tok.isOneOf(tok::identifier, tok::coloncolon)) {
3675 SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation);
3676 Diag(Loc, diag::err_ctor_init_missing_comma)
3677 << FixItHint::CreateInsertion(Loc, ", ");
3678 } else {
3679 // Skip over garbage, until we get to '{'. Don't eat the '{'.
3680 if (!MemInit.isInvalid())
3681 Diag(Tok.getLocation(), diag::err_expected_either)
3682 << tok::l_brace << tok::comma;
3683 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
3684 break;
3686 } while (true);
3688 Actions.ActOnMemInitializers(ConstructorDecl, ColonLoc, MemInitializers,
3689 AnyErrors);
3692 /// ParseMemInitializer - Parse a C++ member initializer, which is
3693 /// part of a constructor initializer that explicitly initializes one
3694 /// member or base class (C++ [class.base.init]). See
3695 /// ParseConstructorInitializer for an example.
3697 /// [C++] mem-initializer:
3698 /// mem-initializer-id '(' expression-list[opt] ')'
3699 /// [C++0x] mem-initializer-id braced-init-list
3701 /// [C++] mem-initializer-id:
3702 /// '::'[opt] nested-name-specifier[opt] class-name
3703 /// identifier
3704 MemInitResult Parser::ParseMemInitializer(Decl *ConstructorDecl) {
3705 // parse '::'[opt] nested-name-specifier[opt]
3706 CXXScopeSpec SS;
3707 if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
3708 /*ObjectHasErrors=*/false,
3709 /*EnteringContext=*/false))
3710 return true;
3712 // : identifier
3713 IdentifierInfo *II = nullptr;
3714 SourceLocation IdLoc = Tok.getLocation();
3715 // : declype(...)
3716 DeclSpec DS(AttrFactory);
3717 // : template_name<...>
3718 TypeResult TemplateTypeTy;
3720 if (Tok.is(tok::identifier)) {
3721 // Get the identifier. This may be a member name or a class name,
3722 // but we'll let the semantic analysis determine which it is.
3723 II = Tok.getIdentifierInfo();
3724 ConsumeToken();
3725 } else if (Tok.is(tok::annot_decltype)) {
3726 // Get the decltype expression, if there is one.
3727 // Uses of decltype will already have been converted to annot_decltype by
3728 // ParseOptionalCXXScopeSpecifier at this point.
3729 // FIXME: Can we get here with a scope specifier?
3730 ParseDecltypeSpecifier(DS);
3731 } else {
3732 TemplateIdAnnotation *TemplateId = Tok.is(tok::annot_template_id)
3733 ? takeTemplateIdAnnotation(Tok)
3734 : nullptr;
3735 if (TemplateId && TemplateId->mightBeType()) {
3736 AnnotateTemplateIdTokenAsType(SS, /*IsClassName*/ true);
3737 assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
3738 TemplateTypeTy = getTypeAnnotation(Tok);
3739 ConsumeAnnotationToken();
3740 } else {
3741 Diag(Tok, diag::err_expected_member_or_base_name);
3742 return true;
3746 // Parse the '('.
3747 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
3748 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
3750 // FIXME: Add support for signature help inside initializer lists.
3751 ExprResult InitList = ParseBraceInitializer();
3752 if (InitList.isInvalid())
3753 return true;
3755 SourceLocation EllipsisLoc;
3756 TryConsumeToken(tok::ellipsis, EllipsisLoc);
3758 if (TemplateTypeTy.isInvalid())
3759 return true;
3760 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
3761 TemplateTypeTy.get(), DS, IdLoc,
3762 InitList.get(), EllipsisLoc);
3763 } else if (Tok.is(tok::l_paren)) {
3764 BalancedDelimiterTracker T(*this, tok::l_paren);
3765 T.consumeOpen();
3767 // Parse the optional expression-list.
3768 ExprVector ArgExprs;
3769 CommaLocsTy CommaLocs;
3770 auto RunSignatureHelp = [&] {
3771 if (TemplateTypeTy.isInvalid())
3772 return QualType();
3773 QualType PreferredType = Actions.ProduceCtorInitMemberSignatureHelp(
3774 ConstructorDecl, SS, TemplateTypeTy.get(), ArgExprs, II,
3775 T.getOpenLocation(), /*Braced=*/false);
3776 CalledSignatureHelp = true;
3777 return PreferredType;
3779 if (Tok.isNot(tok::r_paren) &&
3780 ParseExpressionList(ArgExprs, CommaLocs, [&] {
3781 PreferredType.enterFunctionArgument(Tok.getLocation(),
3782 RunSignatureHelp);
3783 })) {
3784 if (PP.isCodeCompletionReached() && !CalledSignatureHelp)
3785 RunSignatureHelp();
3786 SkipUntil(tok::r_paren, StopAtSemi);
3787 return true;
3790 T.consumeClose();
3792 SourceLocation EllipsisLoc;
3793 TryConsumeToken(tok::ellipsis, EllipsisLoc);
3795 if (TemplateTypeTy.isInvalid())
3796 return true;
3797 return Actions.ActOnMemInitializer(
3798 ConstructorDecl, getCurScope(), SS, II, TemplateTypeTy.get(), DS, IdLoc,
3799 T.getOpenLocation(), ArgExprs, T.getCloseLocation(), EllipsisLoc);
3802 if (TemplateTypeTy.isInvalid())
3803 return true;
3805 if (getLangOpts().CPlusPlus11)
3806 return Diag(Tok, diag::err_expected_either) << tok::l_paren << tok::l_brace;
3807 else
3808 return Diag(Tok, diag::err_expected) << tok::l_paren;
3811 /// Parse a C++ exception-specification if present (C++0x [except.spec]).
3813 /// exception-specification:
3814 /// dynamic-exception-specification
3815 /// noexcept-specification
3817 /// noexcept-specification:
3818 /// 'noexcept'
3819 /// 'noexcept' '(' constant-expression ')'
3820 ExceptionSpecificationType Parser::tryParseExceptionSpecification(
3821 bool Delayed, SourceRange &SpecificationRange,
3822 SmallVectorImpl<ParsedType> &DynamicExceptions,
3823 SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
3824 ExprResult &NoexceptExpr, CachedTokens *&ExceptionSpecTokens) {
3825 ExceptionSpecificationType Result = EST_None;
3826 ExceptionSpecTokens = nullptr;
3828 // Handle delayed parsing of exception-specifications.
3829 if (Delayed) {
3830 if (Tok.isNot(tok::kw_throw) && Tok.isNot(tok::kw_noexcept))
3831 return EST_None;
3833 // Consume and cache the starting token.
3834 bool IsNoexcept = Tok.is(tok::kw_noexcept);
3835 Token StartTok = Tok;
3836 SpecificationRange = SourceRange(ConsumeToken());
3838 // Check for a '('.
3839 if (!Tok.is(tok::l_paren)) {
3840 // If this is a bare 'noexcept', we're done.
3841 if (IsNoexcept) {
3842 Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
3843 NoexceptExpr = nullptr;
3844 return EST_BasicNoexcept;
3847 Diag(Tok, diag::err_expected_lparen_after) << "throw";
3848 return EST_DynamicNone;
3851 // Cache the tokens for the exception-specification.
3852 ExceptionSpecTokens = new CachedTokens;
3853 ExceptionSpecTokens->push_back(StartTok); // 'throw' or 'noexcept'
3854 ExceptionSpecTokens->push_back(Tok); // '('
3855 SpecificationRange.setEnd(ConsumeParen()); // '('
3857 ConsumeAndStoreUntil(tok::r_paren, *ExceptionSpecTokens,
3858 /*StopAtSemi=*/true,
3859 /*ConsumeFinalToken=*/true);
3860 SpecificationRange.setEnd(ExceptionSpecTokens->back().getLocation());
3862 return EST_Unparsed;
3865 // See if there's a dynamic specification.
3866 if (Tok.is(tok::kw_throw)) {
3867 Result = ParseDynamicExceptionSpecification(
3868 SpecificationRange, DynamicExceptions, DynamicExceptionRanges);
3869 assert(DynamicExceptions.size() == DynamicExceptionRanges.size() &&
3870 "Produced different number of exception types and ranges.");
3873 // If there's no noexcept specification, we're done.
3874 if (Tok.isNot(tok::kw_noexcept))
3875 return Result;
3877 Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
3879 // If we already had a dynamic specification, parse the noexcept for,
3880 // recovery, but emit a diagnostic and don't store the results.
3881 SourceRange NoexceptRange;
3882 ExceptionSpecificationType NoexceptType = EST_None;
3884 SourceLocation KeywordLoc = ConsumeToken();
3885 if (Tok.is(tok::l_paren)) {
3886 // There is an argument.
3887 BalancedDelimiterTracker T(*this, tok::l_paren);
3888 T.consumeOpen();
3889 NoexceptExpr = ParseConstantExpression();
3890 T.consumeClose();
3891 if (!NoexceptExpr.isInvalid()) {
3892 NoexceptExpr =
3893 Actions.ActOnNoexceptSpec(NoexceptExpr.get(), NoexceptType);
3894 NoexceptRange = SourceRange(KeywordLoc, T.getCloseLocation());
3895 } else {
3896 NoexceptType = EST_BasicNoexcept;
3898 } else {
3899 // There is no argument.
3900 NoexceptType = EST_BasicNoexcept;
3901 NoexceptRange = SourceRange(KeywordLoc, KeywordLoc);
3904 if (Result == EST_None) {
3905 SpecificationRange = NoexceptRange;
3906 Result = NoexceptType;
3908 // If there's a dynamic specification after a noexcept specification,
3909 // parse that and ignore the results.
3910 if (Tok.is(tok::kw_throw)) {
3911 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
3912 ParseDynamicExceptionSpecification(NoexceptRange, DynamicExceptions,
3913 DynamicExceptionRanges);
3915 } else {
3916 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
3919 return Result;
3922 static void diagnoseDynamicExceptionSpecification(Parser &P, SourceRange Range,
3923 bool IsNoexcept) {
3924 if (P.getLangOpts().CPlusPlus11) {
3925 const char *Replacement = IsNoexcept ? "noexcept" : "noexcept(false)";
3926 P.Diag(Range.getBegin(), P.getLangOpts().CPlusPlus17 && !IsNoexcept
3927 ? diag::ext_dynamic_exception_spec
3928 : diag::warn_exception_spec_deprecated)
3929 << Range;
3930 P.Diag(Range.getBegin(), diag::note_exception_spec_deprecated)
3931 << Replacement << FixItHint::CreateReplacement(Range, Replacement);
3935 /// ParseDynamicExceptionSpecification - Parse a C++
3936 /// dynamic-exception-specification (C++ [except.spec]).
3938 /// dynamic-exception-specification:
3939 /// 'throw' '(' type-id-list [opt] ')'
3940 /// [MS] 'throw' '(' '...' ')'
3942 /// type-id-list:
3943 /// type-id ... [opt]
3944 /// type-id-list ',' type-id ... [opt]
3946 ExceptionSpecificationType Parser::ParseDynamicExceptionSpecification(
3947 SourceRange &SpecificationRange, SmallVectorImpl<ParsedType> &Exceptions,
3948 SmallVectorImpl<SourceRange> &Ranges) {
3949 assert(Tok.is(tok::kw_throw) && "expected throw");
3951 SpecificationRange.setBegin(ConsumeToken());
3952 BalancedDelimiterTracker T(*this, tok::l_paren);
3953 if (T.consumeOpen()) {
3954 Diag(Tok, diag::err_expected_lparen_after) << "throw";
3955 SpecificationRange.setEnd(SpecificationRange.getBegin());
3956 return EST_DynamicNone;
3959 // Parse throw(...), a Microsoft extension that means "this function
3960 // can throw anything".
3961 if (Tok.is(tok::ellipsis)) {
3962 SourceLocation EllipsisLoc = ConsumeToken();
3963 if (!getLangOpts().MicrosoftExt)
3964 Diag(EllipsisLoc, diag::ext_ellipsis_exception_spec);
3965 T.consumeClose();
3966 SpecificationRange.setEnd(T.getCloseLocation());
3967 diagnoseDynamicExceptionSpecification(*this, SpecificationRange, false);
3968 return EST_MSAny;
3971 // Parse the sequence of type-ids.
3972 SourceRange Range;
3973 while (Tok.isNot(tok::r_paren)) {
3974 TypeResult Res(ParseTypeName(&Range));
3976 if (Tok.is(tok::ellipsis)) {
3977 // C++0x [temp.variadic]p5:
3978 // - In a dynamic-exception-specification (15.4); the pattern is a
3979 // type-id.
3980 SourceLocation Ellipsis = ConsumeToken();
3981 Range.setEnd(Ellipsis);
3982 if (!Res.isInvalid())
3983 Res = Actions.ActOnPackExpansion(Res.get(), Ellipsis);
3986 if (!Res.isInvalid()) {
3987 Exceptions.push_back(Res.get());
3988 Ranges.push_back(Range);
3991 if (!TryConsumeToken(tok::comma))
3992 break;
3995 T.consumeClose();
3996 SpecificationRange.setEnd(T.getCloseLocation());
3997 diagnoseDynamicExceptionSpecification(*this, SpecificationRange,
3998 Exceptions.empty());
3999 return Exceptions.empty() ? EST_DynamicNone : EST_Dynamic;
4002 /// ParseTrailingReturnType - Parse a trailing return type on a new-style
4003 /// function declaration.
4004 TypeResult Parser::ParseTrailingReturnType(SourceRange &Range,
4005 bool MayBeFollowedByDirectInit) {
4006 assert(Tok.is(tok::arrow) && "expected arrow");
4008 ConsumeToken();
4010 return ParseTypeName(&Range, MayBeFollowedByDirectInit
4011 ? DeclaratorContext::TrailingReturnVar
4012 : DeclaratorContext::TrailingReturn);
4015 /// Parse a requires-clause as part of a function declaration.
4016 void Parser::ParseTrailingRequiresClause(Declarator &D) {
4017 assert(Tok.is(tok::kw_requires) && "expected requires");
4019 SourceLocation RequiresKWLoc = ConsumeToken();
4021 ExprResult TrailingRequiresClause;
4022 ParseScope ParamScope(this, Scope::DeclScope |
4023 Scope::FunctionDeclarationScope |
4024 Scope::FunctionPrototypeScope);
4026 Actions.ActOnStartTrailingRequiresClause(getCurScope(), D);
4028 llvm::Optional<Sema::CXXThisScopeRAII> ThisScope;
4029 InitCXXThisScopeForDeclaratorIfRelevant(D, D.getDeclSpec(), ThisScope);
4031 TrailingRequiresClause =
4032 ParseConstraintLogicalOrExpression(/*IsTrailingRequiresClause=*/true);
4034 TrailingRequiresClause =
4035 Actions.ActOnFinishTrailingRequiresClause(TrailingRequiresClause);
4037 if (!D.isDeclarationOfFunction()) {
4038 Diag(RequiresKWLoc,
4039 diag::err_requires_clause_on_declarator_not_declaring_a_function);
4040 return;
4043 if (TrailingRequiresClause.isInvalid())
4044 SkipUntil({tok::l_brace, tok::arrow, tok::kw_try, tok::comma, tok::colon},
4045 StopAtSemi | StopBeforeMatch);
4046 else
4047 D.setTrailingRequiresClause(TrailingRequiresClause.get());
4049 // Did the user swap the trailing return type and requires clause?
4050 if (D.isFunctionDeclarator() && Tok.is(tok::arrow) &&
4051 D.getDeclSpec().getTypeSpecType() == TST_auto) {
4052 SourceLocation ArrowLoc = Tok.getLocation();
4053 SourceRange Range;
4054 TypeResult TrailingReturnType =
4055 ParseTrailingReturnType(Range, /*MayBeFollowedByDirectInit=*/false);
4057 if (!TrailingReturnType.isInvalid()) {
4058 Diag(ArrowLoc,
4059 diag::err_requires_clause_must_appear_after_trailing_return)
4060 << Range;
4061 auto &FunctionChunk = D.getFunctionTypeInfo();
4062 FunctionChunk.HasTrailingReturnType = TrailingReturnType.isUsable();
4063 FunctionChunk.TrailingReturnType = TrailingReturnType.get();
4064 FunctionChunk.TrailingReturnTypeLoc = Range.getBegin();
4065 } else
4066 SkipUntil({tok::equal, tok::l_brace, tok::arrow, tok::kw_try, tok::comma},
4067 StopAtSemi | StopBeforeMatch);
4071 /// We have just started parsing the definition of a new class,
4072 /// so push that class onto our stack of classes that is currently
4073 /// being parsed.
4074 Sema::ParsingClassState Parser::PushParsingClass(Decl *ClassDecl,
4075 bool NonNestedClass,
4076 bool IsInterface) {
4077 assert((NonNestedClass || !ClassStack.empty()) &&
4078 "Nested class without outer class");
4079 ClassStack.push(new ParsingClass(ClassDecl, NonNestedClass, IsInterface));
4080 return Actions.PushParsingClass();
4083 /// Deallocate the given parsed class and all of its nested
4084 /// classes.
4085 void Parser::DeallocateParsedClasses(Parser::ParsingClass *Class) {
4086 for (unsigned I = 0, N = Class->LateParsedDeclarations.size(); I != N; ++I)
4087 delete Class->LateParsedDeclarations[I];
4088 delete Class;
4091 /// Pop the top class of the stack of classes that are
4092 /// currently being parsed.
4094 /// This routine should be called when we have finished parsing the
4095 /// definition of a class, but have not yet popped the Scope
4096 /// associated with the class's definition.
4097 void Parser::PopParsingClass(Sema::ParsingClassState state) {
4098 assert(!ClassStack.empty() && "Mismatched push/pop for class parsing");
4100 Actions.PopParsingClass(state);
4102 ParsingClass *Victim = ClassStack.top();
4103 ClassStack.pop();
4104 if (Victim->TopLevelClass) {
4105 // Deallocate all of the nested classes of this class,
4106 // recursively: we don't need to keep any of this information.
4107 DeallocateParsedClasses(Victim);
4108 return;
4110 assert(!ClassStack.empty() && "Missing top-level class?");
4112 if (Victim->LateParsedDeclarations.empty()) {
4113 // The victim is a nested class, but we will not need to perform
4114 // any processing after the definition of this class since it has
4115 // no members whose handling was delayed. Therefore, we can just
4116 // remove this nested class.
4117 DeallocateParsedClasses(Victim);
4118 return;
4121 // This nested class has some members that will need to be processed
4122 // after the top-level class is completely defined. Therefore, add
4123 // it to the list of nested classes within its parent.
4124 assert(getCurScope()->isClassScope() &&
4125 "Nested class outside of class scope?");
4126 ClassStack.top()->LateParsedDeclarations.push_back(
4127 new LateParsedClass(this, Victim));
4130 /// Try to parse an 'identifier' which appears within an attribute-token.
4132 /// \return the parsed identifier on success, and 0 if the next token is not an
4133 /// attribute-token.
4135 /// C++11 [dcl.attr.grammar]p3:
4136 /// If a keyword or an alternative token that satisfies the syntactic
4137 /// requirements of an identifier is contained in an attribute-token,
4138 /// it is considered an identifier.
4139 IdentifierInfo *
4140 Parser::TryParseCXX11AttributeIdentifier(SourceLocation &Loc,
4141 Sema::AttributeCompletion Completion,
4142 const IdentifierInfo *Scope) {
4143 switch (Tok.getKind()) {
4144 default:
4145 // Identifiers and keywords have identifier info attached.
4146 if (!Tok.isAnnotation()) {
4147 if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
4148 Loc = ConsumeToken();
4149 return II;
4152 return nullptr;
4154 case tok::code_completion:
4155 cutOffParsing();
4156 Actions.CodeCompleteAttribute(getLangOpts().CPlusPlus ? ParsedAttr::AS_CXX11
4157 : ParsedAttr::AS_C2x,
4158 Completion, Scope);
4159 return nullptr;
4161 case tok::numeric_constant: {
4162 // If we got a numeric constant, check to see if it comes from a macro that
4163 // corresponds to the predefined __clang__ macro. If it does, warn the user
4164 // and recover by pretending they said _Clang instead.
4165 if (Tok.getLocation().isMacroID()) {
4166 SmallString<8> ExpansionBuf;
4167 SourceLocation ExpansionLoc =
4168 PP.getSourceManager().getExpansionLoc(Tok.getLocation());
4169 StringRef Spelling = PP.getSpelling(ExpansionLoc, ExpansionBuf);
4170 if (Spelling == "__clang__") {
4171 SourceRange TokRange(
4172 ExpansionLoc,
4173 PP.getSourceManager().getExpansionLoc(Tok.getEndLoc()));
4174 Diag(Tok, diag::warn_wrong_clang_attr_namespace)
4175 << FixItHint::CreateReplacement(TokRange, "_Clang");
4176 Loc = ConsumeToken();
4177 return &PP.getIdentifierTable().get("_Clang");
4180 return nullptr;
4183 case tok::ampamp: // 'and'
4184 case tok::pipe: // 'bitor'
4185 case tok::pipepipe: // 'or'
4186 case tok::caret: // 'xor'
4187 case tok::tilde: // 'compl'
4188 case tok::amp: // 'bitand'
4189 case tok::ampequal: // 'and_eq'
4190 case tok::pipeequal: // 'or_eq'
4191 case tok::caretequal: // 'xor_eq'
4192 case tok::exclaim: // 'not'
4193 case tok::exclaimequal: // 'not_eq'
4194 // Alternative tokens do not have identifier info, but their spelling
4195 // starts with an alphabetical character.
4196 SmallString<8> SpellingBuf;
4197 SourceLocation SpellingLoc =
4198 PP.getSourceManager().getSpellingLoc(Tok.getLocation());
4199 StringRef Spelling = PP.getSpelling(SpellingLoc, SpellingBuf);
4200 if (isLetter(Spelling[0])) {
4201 Loc = ConsumeToken();
4202 return &PP.getIdentifierTable().get(Spelling);
4204 return nullptr;
4208 void Parser::ParseOpenMPAttributeArgs(IdentifierInfo *AttrName,
4209 CachedTokens &OpenMPTokens) {
4210 // Both 'sequence' and 'directive' attributes require arguments, so parse the
4211 // open paren for the argument list.
4212 BalancedDelimiterTracker T(*this, tok::l_paren);
4213 if (T.consumeOpen()) {
4214 Diag(Tok, diag::err_expected) << tok::l_paren;
4215 return;
4218 if (AttrName->isStr("directive")) {
4219 // If the attribute is named `directive`, we can consume its argument list
4220 // and push the tokens from it into the cached token stream for a new OpenMP
4221 // pragma directive.
4222 Token OMPBeginTok;
4223 OMPBeginTok.startToken();
4224 OMPBeginTok.setKind(tok::annot_attr_openmp);
4225 OMPBeginTok.setLocation(Tok.getLocation());
4226 OpenMPTokens.push_back(OMPBeginTok);
4228 ConsumeAndStoreUntil(tok::r_paren, OpenMPTokens, /*StopAtSemi=*/false,
4229 /*ConsumeFinalToken*/ false);
4230 Token OMPEndTok;
4231 OMPEndTok.startToken();
4232 OMPEndTok.setKind(tok::annot_pragma_openmp_end);
4233 OMPEndTok.setLocation(Tok.getLocation());
4234 OpenMPTokens.push_back(OMPEndTok);
4235 } else {
4236 assert(AttrName->isStr("sequence") &&
4237 "Expected either 'directive' or 'sequence'");
4238 // If the attribute is named 'sequence', its argument is a list of one or
4239 // more OpenMP attributes (either 'omp::directive' or 'omp::sequence',
4240 // where the 'omp::' is optional).
4241 do {
4242 // We expect to see one of the following:
4243 // * An identifier (omp) for the attribute namespace followed by ::
4244 // * An identifier (directive) or an identifier (sequence).
4245 SourceLocation IdentLoc;
4246 IdentifierInfo *Ident = TryParseCXX11AttributeIdentifier(IdentLoc);
4248 // If there is an identifier and it is 'omp', a double colon is required
4249 // followed by the actual identifier we're after.
4250 if (Ident && Ident->isStr("omp") && !ExpectAndConsume(tok::coloncolon))
4251 Ident = TryParseCXX11AttributeIdentifier(IdentLoc);
4253 // If we failed to find an identifier (scoped or otherwise), or we found
4254 // an unexpected identifier, diagnose.
4255 if (!Ident || (!Ident->isStr("directive") && !Ident->isStr("sequence"))) {
4256 Diag(Tok.getLocation(), diag::err_expected_sequence_or_directive);
4257 SkipUntil(tok::r_paren, StopBeforeMatch);
4258 continue;
4260 // We read an identifier. If the identifier is one of the ones we
4261 // expected, we can recurse to parse the args.
4262 ParseOpenMPAttributeArgs(Ident, OpenMPTokens);
4264 // There may be a comma to signal that we expect another directive in the
4265 // sequence.
4266 } while (TryConsumeToken(tok::comma));
4268 // Parse the closing paren for the argument list.
4269 T.consumeClose();
4272 static bool IsBuiltInOrStandardCXX11Attribute(IdentifierInfo *AttrName,
4273 IdentifierInfo *ScopeName) {
4274 switch (
4275 ParsedAttr::getParsedKind(AttrName, ScopeName, ParsedAttr::AS_CXX11)) {
4276 case ParsedAttr::AT_CarriesDependency:
4277 case ParsedAttr::AT_Deprecated:
4278 case ParsedAttr::AT_FallThrough:
4279 case ParsedAttr::AT_CXX11NoReturn:
4280 case ParsedAttr::AT_NoUniqueAddress:
4281 case ParsedAttr::AT_Likely:
4282 case ParsedAttr::AT_Unlikely:
4283 return true;
4284 case ParsedAttr::AT_WarnUnusedResult:
4285 return !ScopeName && AttrName->getName().equals("nodiscard");
4286 case ParsedAttr::AT_Unused:
4287 return !ScopeName && AttrName->getName().equals("maybe_unused");
4288 default:
4289 return false;
4293 /// ParseCXX11AttributeArgs -- Parse a C++11 attribute-argument-clause.
4295 /// [C++11] attribute-argument-clause:
4296 /// '(' balanced-token-seq ')'
4298 /// [C++11] balanced-token-seq:
4299 /// balanced-token
4300 /// balanced-token-seq balanced-token
4302 /// [C++11] balanced-token:
4303 /// '(' balanced-token-seq ')'
4304 /// '[' balanced-token-seq ']'
4305 /// '{' balanced-token-seq '}'
4306 /// any token but '(', ')', '[', ']', '{', or '}'
4307 bool Parser::ParseCXX11AttributeArgs(
4308 IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
4309 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
4310 SourceLocation ScopeLoc, CachedTokens &OpenMPTokens) {
4311 assert(Tok.is(tok::l_paren) && "Not a C++11 attribute argument list");
4312 SourceLocation LParenLoc = Tok.getLocation();
4313 const LangOptions &LO = getLangOpts();
4314 ParsedAttr::Syntax Syntax =
4315 LO.CPlusPlus ? ParsedAttr::AS_CXX11 : ParsedAttr::AS_C2x;
4317 // Try parsing microsoft attributes
4318 if (getLangOpts().MicrosoftExt || getLangOpts().HLSL) {
4319 if (hasAttribute(AttributeCommonInfo::Syntax::AS_Microsoft, ScopeName,
4320 AttrName, getTargetInfo(), getLangOpts()))
4321 Syntax = ParsedAttr::AS_Microsoft;
4324 // If the attribute isn't known, we will not attempt to parse any
4325 // arguments.
4326 if (Syntax != ParsedAttr::AS_Microsoft &&
4327 !hasAttribute(LO.CPlusPlus ? AttributeCommonInfo::Syntax::AS_CXX11
4328 : AttributeCommonInfo::Syntax::AS_C2x,
4329 ScopeName, AttrName, getTargetInfo(), getLangOpts())) {
4330 if (getLangOpts().MicrosoftExt || getLangOpts().HLSL) {
4332 // Eat the left paren, then skip to the ending right paren.
4333 ConsumeParen();
4334 SkipUntil(tok::r_paren);
4335 return false;
4338 if (ScopeName && (ScopeName->isStr("gnu") || ScopeName->isStr("__gnu__"))) {
4339 // GNU-scoped attributes have some special cases to handle GNU-specific
4340 // behaviors.
4341 ParseGNUAttributeArgs(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
4342 ScopeLoc, Syntax, nullptr);
4343 return true;
4346 if (ScopeName && ScopeName->isStr("omp")) {
4347 Diag(AttrNameLoc, getLangOpts().OpenMP >= 51
4348 ? diag::warn_omp51_compat_attributes
4349 : diag::ext_omp_attributes);
4351 ParseOpenMPAttributeArgs(AttrName, OpenMPTokens);
4353 // We claim that an attribute was parsed and added so that one is not
4354 // created for us by the caller.
4355 return true;
4358 unsigned NumArgs;
4359 // Some Clang-scoped attributes have some special parsing behavior.
4360 if (ScopeName && (ScopeName->isStr("clang") || ScopeName->isStr("_Clang")))
4361 NumArgs = ParseClangAttributeArgs(AttrName, AttrNameLoc, Attrs, EndLoc,
4362 ScopeName, ScopeLoc, Syntax);
4363 else
4364 NumArgs = ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc,
4365 ScopeName, ScopeLoc, Syntax);
4367 if (!Attrs.empty() &&
4368 IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName)) {
4369 ParsedAttr &Attr = Attrs.back();
4370 // If the attribute is a standard or built-in attribute and we are
4371 // parsing an argument list, we need to determine whether this attribute
4372 // was allowed to have an argument list (such as [[deprecated]]), and how
4373 // many arguments were parsed (so we can diagnose on [[deprecated()]]).
4374 if (Attr.getMaxArgs() && !NumArgs) {
4375 // The attribute was allowed to have arguments, but none were provided
4376 // even though the attribute parsed successfully. This is an error.
4377 Diag(LParenLoc, diag::err_attribute_requires_arguments) << AttrName;
4378 Attr.setInvalid(true);
4379 } else if (!Attr.getMaxArgs()) {
4380 // The attribute parsed successfully, but was not allowed to have any
4381 // arguments. It doesn't matter whether any were provided -- the
4382 // presence of the argument list (even if empty) is diagnosed.
4383 Diag(LParenLoc, diag::err_cxx11_attribute_forbids_arguments)
4384 << AttrName
4385 << FixItHint::CreateRemoval(SourceRange(LParenLoc, *EndLoc));
4386 Attr.setInvalid(true);
4389 return true;
4392 /// Parse a C++11 or C2x attribute-specifier.
4394 /// [C++11] attribute-specifier:
4395 /// '[' '[' attribute-list ']' ']'
4396 /// alignment-specifier
4398 /// [C++11] attribute-list:
4399 /// attribute[opt]
4400 /// attribute-list ',' attribute[opt]
4401 /// attribute '...'
4402 /// attribute-list ',' attribute '...'
4404 /// [C++11] attribute:
4405 /// attribute-token attribute-argument-clause[opt]
4407 /// [C++11] attribute-token:
4408 /// identifier
4409 /// attribute-scoped-token
4411 /// [C++11] attribute-scoped-token:
4412 /// attribute-namespace '::' identifier
4414 /// [C++11] attribute-namespace:
4415 /// identifier
4416 void Parser::ParseCXX11AttributeSpecifierInternal(ParsedAttributes &Attrs,
4417 CachedTokens &OpenMPTokens,
4418 SourceLocation *EndLoc) {
4419 if (Tok.is(tok::kw_alignas)) {
4420 Diag(Tok.getLocation(), diag::warn_cxx98_compat_alignas);
4421 ParseAlignmentSpecifier(Attrs, EndLoc);
4422 return;
4425 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square) &&
4426 "Not a double square bracket attribute list");
4428 SourceLocation OpenLoc = Tok.getLocation();
4429 Diag(OpenLoc, diag::warn_cxx98_compat_attribute);
4431 ConsumeBracket();
4432 checkCompoundToken(OpenLoc, tok::l_square, CompoundToken::AttrBegin);
4433 ConsumeBracket();
4435 SourceLocation CommonScopeLoc;
4436 IdentifierInfo *CommonScopeName = nullptr;
4437 if (Tok.is(tok::kw_using)) {
4438 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
4439 ? diag::warn_cxx14_compat_using_attribute_ns
4440 : diag::ext_using_attribute_ns);
4441 ConsumeToken();
4443 CommonScopeName = TryParseCXX11AttributeIdentifier(
4444 CommonScopeLoc, Sema::AttributeCompletion::Scope);
4445 if (!CommonScopeName) {
4446 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
4447 SkipUntil(tok::r_square, tok::colon, StopBeforeMatch);
4449 if (!TryConsumeToken(tok::colon) && CommonScopeName)
4450 Diag(Tok.getLocation(), diag::err_expected) << tok::colon;
4453 llvm::SmallDenseMap<IdentifierInfo *, SourceLocation, 4> SeenAttrs;
4455 bool AttrParsed = false;
4456 while (!Tok.isOneOf(tok::r_square, tok::semi, tok::eof)) {
4457 if (AttrParsed) {
4458 // If we parsed an attribute, a comma is required before parsing any
4459 // additional attributes.
4460 if (ExpectAndConsume(tok::comma)) {
4461 SkipUntil(tok::r_square, StopAtSemi | StopBeforeMatch);
4462 continue;
4464 AttrParsed = false;
4467 // Eat all remaining superfluous commas before parsing the next attribute.
4468 while (TryConsumeToken(tok::comma))
4471 SourceLocation ScopeLoc, AttrLoc;
4472 IdentifierInfo *ScopeName = nullptr, *AttrName = nullptr;
4474 AttrName = TryParseCXX11AttributeIdentifier(
4475 AttrLoc, Sema::AttributeCompletion::Attribute, CommonScopeName);
4476 if (!AttrName)
4477 // Break out to the "expected ']'" diagnostic.
4478 break;
4480 // scoped attribute
4481 if (TryConsumeToken(tok::coloncolon)) {
4482 ScopeName = AttrName;
4483 ScopeLoc = AttrLoc;
4485 AttrName = TryParseCXX11AttributeIdentifier(
4486 AttrLoc, Sema::AttributeCompletion::Attribute, ScopeName);
4487 if (!AttrName) {
4488 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
4489 SkipUntil(tok::r_square, tok::comma, StopAtSemi | StopBeforeMatch);
4490 continue;
4494 if (CommonScopeName) {
4495 if (ScopeName) {
4496 Diag(ScopeLoc, diag::err_using_attribute_ns_conflict)
4497 << SourceRange(CommonScopeLoc);
4498 } else {
4499 ScopeName = CommonScopeName;
4500 ScopeLoc = CommonScopeLoc;
4504 // Parse attribute arguments
4505 if (Tok.is(tok::l_paren))
4506 AttrParsed = ParseCXX11AttributeArgs(AttrName, AttrLoc, Attrs, EndLoc,
4507 ScopeName, ScopeLoc, OpenMPTokens);
4509 if (!AttrParsed) {
4510 Attrs.addNew(
4511 AttrName,
4512 SourceRange(ScopeLoc.isValid() ? ScopeLoc : AttrLoc, AttrLoc),
4513 ScopeName, ScopeLoc, nullptr, 0,
4514 getLangOpts().CPlusPlus ? ParsedAttr::AS_CXX11 : ParsedAttr::AS_C2x);
4515 AttrParsed = true;
4518 if (TryConsumeToken(tok::ellipsis))
4519 Diag(Tok, diag::err_cxx11_attribute_forbids_ellipsis) << AttrName;
4522 // If we hit an error and recovered by parsing up to a semicolon, eat the
4523 // semicolon and don't issue further diagnostics about missing brackets.
4524 if (Tok.is(tok::semi)) {
4525 ConsumeToken();
4526 return;
4529 SourceLocation CloseLoc = Tok.getLocation();
4530 if (ExpectAndConsume(tok::r_square))
4531 SkipUntil(tok::r_square);
4532 else if (Tok.is(tok::r_square))
4533 checkCompoundToken(CloseLoc, tok::r_square, CompoundToken::AttrEnd);
4534 if (EndLoc)
4535 *EndLoc = Tok.getLocation();
4536 if (ExpectAndConsume(tok::r_square))
4537 SkipUntil(tok::r_square);
4540 /// ParseCXX11Attributes - Parse a C++11 or C2x attribute-specifier-seq.
4542 /// attribute-specifier-seq:
4543 /// attribute-specifier-seq[opt] attribute-specifier
4544 void Parser::ParseCXX11Attributes(ParsedAttributes &Attrs) {
4545 assert(standardAttributesAllowed());
4547 SourceLocation StartLoc = Tok.getLocation();
4548 SourceLocation EndLoc = StartLoc;
4550 do {
4551 ParseCXX11AttributeSpecifier(Attrs, &EndLoc);
4552 } while (isCXX11AttributeSpecifier());
4554 Attrs.Range = SourceRange(StartLoc, EndLoc);
4557 void Parser::DiagnoseAndSkipCXX11Attributes() {
4558 // Start and end location of an attribute or an attribute list.
4559 SourceLocation StartLoc = Tok.getLocation();
4560 SourceLocation EndLoc = SkipCXX11Attributes();
4562 if (EndLoc.isValid()) {
4563 SourceRange Range(StartLoc, EndLoc);
4564 Diag(StartLoc, diag::err_attributes_not_allowed) << Range;
4568 SourceLocation Parser::SkipCXX11Attributes() {
4569 SourceLocation EndLoc;
4571 if (!isCXX11AttributeSpecifier())
4572 return EndLoc;
4574 do {
4575 if (Tok.is(tok::l_square)) {
4576 BalancedDelimiterTracker T(*this, tok::l_square);
4577 T.consumeOpen();
4578 T.skipToEnd();
4579 EndLoc = T.getCloseLocation();
4580 } else {
4581 assert(Tok.is(tok::kw_alignas) && "not an attribute specifier");
4582 ConsumeToken();
4583 BalancedDelimiterTracker T(*this, tok::l_paren);
4584 if (!T.consumeOpen())
4585 T.skipToEnd();
4586 EndLoc = T.getCloseLocation();
4588 } while (isCXX11AttributeSpecifier());
4590 return EndLoc;
4593 /// Parse uuid() attribute when it appears in a [] Microsoft attribute.
4594 void Parser::ParseMicrosoftUuidAttributeArgs(ParsedAttributes &Attrs) {
4595 assert(Tok.is(tok::identifier) && "Not a Microsoft attribute list");
4596 IdentifierInfo *UuidIdent = Tok.getIdentifierInfo();
4597 assert(UuidIdent->getName() == "uuid" && "Not a Microsoft attribute list");
4599 SourceLocation UuidLoc = Tok.getLocation();
4600 ConsumeToken();
4602 // Ignore the left paren location for now.
4603 BalancedDelimiterTracker T(*this, tok::l_paren);
4604 if (T.consumeOpen()) {
4605 Diag(Tok, diag::err_expected) << tok::l_paren;
4606 return;
4609 ArgsVector ArgExprs;
4610 if (Tok.is(tok::string_literal)) {
4611 // Easy case: uuid("...") -- quoted string.
4612 ExprResult StringResult = ParseStringLiteralExpression();
4613 if (StringResult.isInvalid())
4614 return;
4615 ArgExprs.push_back(StringResult.get());
4616 } else {
4617 // something like uuid({000000A0-0000-0000-C000-000000000049}) -- no
4618 // quotes in the parens. Just append the spelling of all tokens encountered
4619 // until the closing paren.
4621 SmallString<42> StrBuffer; // 2 "", 36 bytes UUID, 2 optional {}, 1 nul
4622 StrBuffer += "\"";
4624 // Since none of C++'s keywords match [a-f]+, accepting just tok::l_brace,
4625 // tok::r_brace, tok::minus, tok::identifier (think C000) and
4626 // tok::numeric_constant (0000) should be enough. But the spelling of the
4627 // uuid argument is checked later anyways, so there's no harm in accepting
4628 // almost anything here.
4629 // cl is very strict about whitespace in this form and errors out if any
4630 // is present, so check the space flags on the tokens.
4631 SourceLocation StartLoc = Tok.getLocation();
4632 while (Tok.isNot(tok::r_paren)) {
4633 if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
4634 Diag(Tok, diag::err_attribute_uuid_malformed_guid);
4635 SkipUntil(tok::r_paren, StopAtSemi);
4636 return;
4638 SmallString<16> SpellingBuffer;
4639 SpellingBuffer.resize(Tok.getLength() + 1);
4640 bool Invalid = false;
4641 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
4642 if (Invalid) {
4643 SkipUntil(tok::r_paren, StopAtSemi);
4644 return;
4646 StrBuffer += TokSpelling;
4647 ConsumeAnyToken();
4649 StrBuffer += "\"";
4651 if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
4652 Diag(Tok, diag::err_attribute_uuid_malformed_guid);
4653 ConsumeParen();
4654 return;
4657 // Pretend the user wrote the appropriate string literal here.
4658 // ActOnStringLiteral() copies the string data into the literal, so it's
4659 // ok that the Token points to StrBuffer.
4660 Token Toks[1];
4661 Toks[0].startToken();
4662 Toks[0].setKind(tok::string_literal);
4663 Toks[0].setLocation(StartLoc);
4664 Toks[0].setLiteralData(StrBuffer.data());
4665 Toks[0].setLength(StrBuffer.size());
4666 StringLiteral *UuidString =
4667 cast<StringLiteral>(Actions.ActOnStringLiteral(Toks, nullptr).get());
4668 ArgExprs.push_back(UuidString);
4671 if (!T.consumeClose()) {
4672 Attrs.addNew(UuidIdent, SourceRange(UuidLoc, T.getCloseLocation()), nullptr,
4673 SourceLocation(), ArgExprs.data(), ArgExprs.size(),
4674 ParsedAttr::AS_Microsoft);
4678 /// ParseMicrosoftAttributes - Parse Microsoft attributes [Attr]
4680 /// [MS] ms-attribute:
4681 /// '[' token-seq ']'
4683 /// [MS] ms-attribute-seq:
4684 /// ms-attribute[opt]
4685 /// ms-attribute ms-attribute-seq
4686 void Parser::ParseMicrosoftAttributes(ParsedAttributes &Attrs) {
4687 assert(Tok.is(tok::l_square) && "Not a Microsoft attribute list");
4689 SourceLocation StartLoc = Tok.getLocation();
4690 SourceLocation EndLoc = StartLoc;
4691 do {
4692 // FIXME: If this is actually a C++11 attribute, parse it as one.
4693 BalancedDelimiterTracker T(*this, tok::l_square);
4694 T.consumeOpen();
4696 // Skip most ms attributes except for a specific list.
4697 while (true) {
4698 SkipUntil(tok::r_square, tok::identifier,
4699 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
4700 if (Tok.is(tok::code_completion)) {
4701 cutOffParsing();
4702 Actions.CodeCompleteAttribute(AttributeCommonInfo::AS_Microsoft,
4703 Sema::AttributeCompletion::Attribute,
4704 /*Scope=*/nullptr);
4705 break;
4707 if (Tok.isNot(tok::identifier)) // ']', but also eof
4708 break;
4709 if (Tok.getIdentifierInfo()->getName() == "uuid")
4710 ParseMicrosoftUuidAttributeArgs(Attrs);
4711 else {
4712 IdentifierInfo *II = Tok.getIdentifierInfo();
4713 SourceLocation NameLoc = Tok.getLocation();
4714 ConsumeToken();
4715 ParsedAttr::Kind AttrKind =
4716 ParsedAttr::getParsedKind(II, nullptr, ParsedAttr::AS_Microsoft);
4717 // For HLSL we want to handle all attributes, but for MSVC compat, we
4718 // silently ignore unknown Microsoft attributes.
4719 if (getLangOpts().HLSL || AttrKind != ParsedAttr::UnknownAttribute) {
4720 bool AttrParsed = false;
4721 if (Tok.is(tok::l_paren)) {
4722 CachedTokens OpenMPTokens;
4723 AttrParsed =
4724 ParseCXX11AttributeArgs(II, NameLoc, Attrs, &EndLoc, nullptr,
4725 SourceLocation(), OpenMPTokens);
4726 ReplayOpenMPAttributeTokens(OpenMPTokens);
4728 if (!AttrParsed) {
4729 Attrs.addNew(II, NameLoc, nullptr, SourceLocation(), nullptr, 0,
4730 ParsedAttr::AS_Microsoft);
4736 T.consumeClose();
4737 EndLoc = T.getCloseLocation();
4738 } while (Tok.is(tok::l_square));
4740 Attrs.Range = SourceRange(StartLoc, EndLoc);
4743 void Parser::ParseMicrosoftIfExistsClassDeclaration(
4744 DeclSpec::TST TagType, ParsedAttributes &AccessAttrs,
4745 AccessSpecifier &CurAS) {
4746 IfExistsCondition Result;
4747 if (ParseMicrosoftIfExistsCondition(Result))
4748 return;
4750 BalancedDelimiterTracker Braces(*this, tok::l_brace);
4751 if (Braces.consumeOpen()) {
4752 Diag(Tok, diag::err_expected) << tok::l_brace;
4753 return;
4756 switch (Result.Behavior) {
4757 case IEB_Parse:
4758 // Parse the declarations below.
4759 break;
4761 case IEB_Dependent:
4762 Diag(Result.KeywordLoc, diag::warn_microsoft_dependent_exists)
4763 << Result.IsIfExists;
4764 // Fall through to skip.
4765 [[fallthrough]];
4767 case IEB_Skip:
4768 Braces.skipToEnd();
4769 return;
4772 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
4773 // __if_exists, __if_not_exists can nest.
4774 if (Tok.isOneOf(tok::kw___if_exists, tok::kw___if_not_exists)) {
4775 ParseMicrosoftIfExistsClassDeclaration(TagType, AccessAttrs, CurAS);
4776 continue;
4779 // Check for extraneous top-level semicolon.
4780 if (Tok.is(tok::semi)) {
4781 ConsumeExtraSemi(InsideStruct, TagType);
4782 continue;
4785 AccessSpecifier AS = getAccessSpecifierIfPresent();
4786 if (AS != AS_none) {
4787 // Current token is a C++ access specifier.
4788 CurAS = AS;
4789 SourceLocation ASLoc = Tok.getLocation();
4790 ConsumeToken();
4791 if (Tok.is(tok::colon))
4792 Actions.ActOnAccessSpecifier(AS, ASLoc, Tok.getLocation(),
4793 ParsedAttributesView{});
4794 else
4795 Diag(Tok, diag::err_expected) << tok::colon;
4796 ConsumeToken();
4797 continue;
4800 // Parse all the comma separated declarators.
4801 ParseCXXClassMemberDeclaration(CurAS, AccessAttrs);
4804 Braces.consumeClose();