blob: f8c6379eee913d98acbbd6d42fd1f4120832470a [file] [log] [blame]
Hans Wennborgdcfba332015-10-06 23:40:43 +00001//===--- ParseDeclCXX.cpp - C++ Declaration Parsing -------------*- C++ -*-===//
Chris Lattnera5235172007-08-25 06:57:03 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Chris Lattnera5235172007-08-25 06:57:03 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the C++ Declaration portions of the Parser interfaces.
10//
11//===----------------------------------------------------------------------===//
12
Douglas Gregor423984d2008-04-14 00:13:42 +000013#include "clang/Parse/Parser.h"
Erik Verbruggen888d52a2014-01-15 09:15:43 +000014#include "clang/AST/ASTContext.h"
Chandler Carruth757fcd62014-03-04 10:05:20 +000015#include "clang/AST/DeclTemplate.h"
Jordan Rose1e879d82018-03-23 00:07:18 +000016#include "clang/AST/PrettyDeclStackTrace.h"
Aaron Ballmanb8e20392014-03-31 17:32:39 +000017#include "clang/Basic/Attributes.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000018#include "clang/Basic/CharInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "clang/Basic/OperatorKinds.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000020#include "clang/Basic/TargetInfo.h"
Chris Lattner60f36222009-01-29 05:15:15 +000021#include "clang/Parse/ParseDiagnostic.h"
Vassil Vassilev11ad3392017-03-23 15:11:07 +000022#include "clang/Parse/RAIIObjectsForParser.h"
John McCall8b0666c2010-08-20 18:27:03 +000023#include "clang/Sema/DeclSpec.h"
John McCall8b0666c2010-08-20 18:27:03 +000024#include "clang/Sema/ParsedTemplate.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/Sema/Scope.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000026#include "llvm/ADT/SmallString.h"
Anton Afanasyevd880de22019-03-30 08:42:48 +000027#include "llvm/Support/TimeProfiler.h"
Hans Wennborgdcfba332015-10-06 23:40:43 +000028
Chris Lattnera5235172007-08-25 06:57:03 +000029using namespace clang;
30
31/// ParseNamespace - We know that the current token is a namespace keyword. This
Sebastian Redl67667942010-08-27 23:12:46 +000032/// may either be a top level namespace or a block-level namespace alias. If
33/// there was an inline keyword, it has already been parsed.
Chris Lattnera5235172007-08-25 06:57:03 +000034///
Erich Keane53f391d2018-11-12 17:19:48 +000035/// namespace-definition: [C++: namespace.def]
Chris Lattnera5235172007-08-25 06:57:03 +000036/// named-namespace-definition
37/// unnamed-namespace-definition
Erich Keane53f391d2018-11-12 17:19:48 +000038/// nested-namespace-definition
39///
40/// named-namespace-definition:
Erich Keanede6480a32018-11-13 15:48:08 +000041/// 'inline'[opt] 'namespace' attributes[opt] identifier '{'
42/// namespace-body '}'
Chris Lattnera5235172007-08-25 06:57:03 +000043///
44/// unnamed-namespace-definition:
Sebastian Redl67667942010-08-27 23:12:46 +000045/// 'inline'[opt] 'namespace' attributes[opt] '{' namespace-body '}'
Chris Lattnera5235172007-08-25 06:57:03 +000046///
Erich Keane53f391d2018-11-12 17:19:48 +000047/// nested-namespace-definition:
Erich Keanede6480a32018-11-13 15:48:08 +000048/// 'namespace' enclosing-namespace-specifier '::' 'inline'[opt]
49/// identifier '{' namespace-body '}'
Chris Lattnera5235172007-08-25 06:57:03 +000050///
Erich Keane53f391d2018-11-12 17:19:48 +000051/// enclosing-namespace-specifier:
52/// identifier
53/// enclosing-namespace-specifier '::' 'inline'[opt] identifier
Mike Stump11289f42009-09-09 15:08:12 +000054///
Chris Lattnera5235172007-08-25 06:57:03 +000055/// namespace-alias-definition: [C++ 7.3.2: namespace.alias]
56/// 'namespace' identifier '=' qualified-namespace-specifier ';'
57///
Faisal Vali421b2d12017-12-29 05:41:00 +000058Parser::DeclGroupPtrTy Parser::ParseNamespace(DeclaratorContext Context,
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +000059 SourceLocation &DeclEnd,
60 SourceLocation InlineLoc) {
Chris Lattner76c72282007-10-09 17:33:22 +000061 assert(Tok.is(tok::kw_namespace) && "Not a namespace!");
Chris Lattnera5235172007-08-25 06:57:03 +000062 SourceLocation NamespaceLoc = ConsumeToken(); // eat the 'namespace'.
Fariborz Jahanian4bf82622011-08-22 17:59:19 +000063 ObjCDeclContextSwitch ObjCDC(*this);
Fangrui Song6907ce22018-07-30 19:24:48 +000064
Douglas Gregor7e90c6d2009-09-18 19:03:04 +000065 if (Tok.is(tok::code_completion)) {
Douglas Gregor0be31a22010-07-02 17:43:08 +000066 Actions.CodeCompleteNamespaceDecl(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +000067 cutOffParsing();
David Blaikie0403cb12016-01-15 23:43:25 +000068 return nullptr;
Douglas Gregor7e90c6d2009-09-18 19:03:04 +000069 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000070
Chris Lattnera5235172007-08-25 06:57:03 +000071 SourceLocation IdentLoc;
Craig Topper161e4db2014-05-21 06:02:52 +000072 IdentifierInfo *Ident = nullptr;
Erich Keane53f391d2018-11-12 17:19:48 +000073 InnerNamespaceInfoList ExtraNSs;
74 SourceLocation FirstNestedInlineLoc;
Douglas Gregor6b6bba42009-06-17 19:49:00 +000075
Aaron Ballman730476b2014-11-08 15:33:35 +000076 ParsedAttributesWithRange attrs(AttrFactory);
77 SourceLocation attrLoc;
78 if (getLangOpts().CPlusPlus11 && isCXX11AttributeSpecifier()) {
Aaron Ballmanc351fba2017-12-04 20:27:34 +000079 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
Richard Smith40e202f2017-10-14 00:56:24 +000080 ? diag::warn_cxx14_compat_ns_enum_attribute
81 : diag::ext_ns_enum_attribute)
82 << 0 /*namespace*/;
Aaron Ballman730476b2014-11-08 15:33:35 +000083 attrLoc = Tok.getLocation();
84 ParseCXX11Attributes(attrs);
85 }
Mike Stump11289f42009-09-09 15:08:12 +000086
Chris Lattner76c72282007-10-09 17:33:22 +000087 if (Tok.is(tok::identifier)) {
Chris Lattnera5235172007-08-25 06:57:03 +000088 Ident = Tok.getIdentifierInfo();
89 IdentLoc = ConsumeToken(); // eat the identifier.
Erich Keane53f391d2018-11-12 17:19:48 +000090 while (Tok.is(tok::coloncolon) &&
91 (NextToken().is(tok::identifier) ||
92 (NextToken().is(tok::kw_inline) &&
93 GetLookAheadToken(2).is(tok::identifier)))) {
94
95 InnerNamespaceInfo Info;
96 Info.NamespaceLoc = ConsumeToken();
97
98 if (Tok.is(tok::kw_inline)) {
99 Info.InlineLoc = ConsumeToken();
100 if (FirstNestedInlineLoc.isInvalid())
101 FirstNestedInlineLoc = Info.InlineLoc;
102 }
103
104 Info.Ident = Tok.getIdentifierInfo();
105 Info.IdentLoc = ConsumeToken();
106
107 ExtraNSs.push_back(Info);
Richard Trieu61384cb2011-05-26 20:11:09 +0000108 }
Chris Lattnera5235172007-08-25 06:57:03 +0000109 }
Mike Stump11289f42009-09-09 15:08:12 +0000110
Aaron Ballmanc0ae7df2014-11-08 17:07:15 +0000111 // A nested namespace definition cannot have attributes.
Erich Keane53f391d2018-11-12 17:19:48 +0000112 if (!ExtraNSs.empty() && attrLoc.isValid())
Aaron Ballmanc0ae7df2014-11-08 17:07:15 +0000113 Diag(attrLoc, diag::err_unexpected_nested_namespace_attribute);
114
Chris Lattnera5235172007-08-25 06:57:03 +0000115 // Read label attributes, if present.
Douglas Gregor6b6bba42009-06-17 19:49:00 +0000116 if (Tok.is(tok::kw___attribute)) {
Aaron Ballman730476b2014-11-08 15:33:35 +0000117 attrLoc = Tok.getLocation();
John McCall53fa7142010-12-24 02:08:15 +0000118 ParseGNUAttributes(attrs);
Douglas Gregor6b6bba42009-06-17 19:49:00 +0000119 }
Mike Stump11289f42009-09-09 15:08:12 +0000120
Douglas Gregor6b6bba42009-06-17 19:49:00 +0000121 if (Tok.is(tok::equal)) {
Craig Topper161e4db2014-05-21 06:02:52 +0000122 if (!Ident) {
Alp Tokerec543272013-12-24 09:48:30 +0000123 Diag(Tok, diag::err_expected) << tok::identifier;
Nico Weber729f1e22012-10-27 23:44:27 +0000124 // Skip to end of the definition and eat the ';'.
125 SkipUntil(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +0000126 return nullptr;
Nico Weber729f1e22012-10-27 23:44:27 +0000127 }
Aaron Ballman730476b2014-11-08 15:33:35 +0000128 if (attrLoc.isValid())
129 Diag(attrLoc, diag::err_unexpected_namespace_attributes_alias);
Sebastian Redl67667942010-08-27 23:12:46 +0000130 if (InlineLoc.isValid())
131 Diag(InlineLoc, diag::err_inline_namespace_alias)
132 << FixItHint::CreateRemoval(InlineLoc);
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +0000133 Decl *NSAlias = ParseNamespaceAlias(NamespaceLoc, IdentLoc, Ident, DeclEnd);
134 return Actions.ConvertDeclToDeclGroup(NSAlias);
135}
Mike Stump11289f42009-09-09 15:08:12 +0000136
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000137 BalancedDelimiterTracker T(*this, tok::l_brace);
138 if (T.consumeOpen()) {
Alp Tokerec543272013-12-24 09:48:30 +0000139 if (Ident)
140 Diag(Tok, diag::err_expected) << tok::l_brace;
141 else
142 Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace;
David Blaikie0403cb12016-01-15 23:43:25 +0000143 return nullptr;
Chris Lattnera5235172007-08-25 06:57:03 +0000144 }
Mike Stump11289f42009-09-09 15:08:12 +0000145
Fangrui Song6907ce22018-07-30 19:24:48 +0000146 if (getCurScope()->isClassScope() || getCurScope()->isTemplateParamScope() ||
147 getCurScope()->isInObjcMethodScope() || getCurScope()->getBlockParent() ||
Douglas Gregor0be31a22010-07-02 17:43:08 +0000148 getCurScope()->getFnParent()) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000149 Diag(T.getOpenLocation(), diag::err_namespace_nonnamespace_scope);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000150 SkipUntil(tok::r_brace);
David Blaikie0403cb12016-01-15 23:43:25 +0000151 return nullptr;
Douglas Gregor05cfc292010-05-14 05:08:22 +0000152 }
153
Erich Keane53f391d2018-11-12 17:19:48 +0000154 if (ExtraNSs.empty()) {
Richard Smith13307f52014-11-08 05:37:34 +0000155 // Normal namespace definition, not a nested-namespace-definition.
156 } else if (InlineLoc.isValid()) {
157 Diag(InlineLoc, diag::err_inline_nested_namespace_definition);
Aaron Ballman6a308942020-04-21 15:37:19 -0400158 } else if (getLangOpts().CPlusPlus20) {
Erich Keane53f391d2018-11-12 17:19:48 +0000159 Diag(ExtraNSs[0].NamespaceLoc,
Richard Smith13307f52014-11-08 05:37:34 +0000160 diag::warn_cxx14_compat_nested_namespace_definition);
Erich Keane53f391d2018-11-12 17:19:48 +0000161 if (FirstNestedInlineLoc.isValid())
162 Diag(FirstNestedInlineLoc,
163 diag::warn_cxx17_compat_inline_nested_namespace_definition);
164 } else if (getLangOpts().CPlusPlus17) {
165 Diag(ExtraNSs[0].NamespaceLoc,
166 diag::warn_cxx14_compat_nested_namespace_definition);
167 if (FirstNestedInlineLoc.isValid())
168 Diag(FirstNestedInlineLoc, diag::ext_inline_nested_namespace_definition);
Richard Smith13307f52014-11-08 05:37:34 +0000169 } else {
Richard Trieu61384cb2011-05-26 20:11:09 +0000170 TentativeParsingAction TPA(*this);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000171 SkipUntil(tok::r_brace, StopBeforeMatch);
Richard Trieu61384cb2011-05-26 20:11:09 +0000172 Token rBraceToken = Tok;
173 TPA.Revert();
174
175 if (!rBraceToken.is(tok::r_brace)) {
Erich Keane53f391d2018-11-12 17:19:48 +0000176 Diag(ExtraNSs[0].NamespaceLoc, diag::ext_nested_namespace_definition)
177 << SourceRange(ExtraNSs.front().NamespaceLoc,
178 ExtraNSs.back().IdentLoc);
Richard Trieu61384cb2011-05-26 20:11:09 +0000179 } else {
Benjamin Kramerf546f412011-05-26 21:32:30 +0000180 std::string NamespaceFix;
Erich Keane53f391d2018-11-12 17:19:48 +0000181 for (const auto &ExtraNS : ExtraNSs) {
Erich Keanea946acd2018-11-12 21:08:41 +0000182 NamespaceFix += " { ";
183 if (ExtraNS.InlineLoc.isValid())
184 NamespaceFix += "inline ";
185 NamespaceFix += "namespace ";
Erich Keane53f391d2018-11-12 17:19:48 +0000186 NamespaceFix += ExtraNS.Ident->getName();
Richard Trieu61384cb2011-05-26 20:11:09 +0000187 }
Benjamin Kramerf546f412011-05-26 21:32:30 +0000188
Richard Trieu61384cb2011-05-26 20:11:09 +0000189 std::string RBraces;
Erich Keane53f391d2018-11-12 17:19:48 +0000190 for (unsigned i = 0, e = ExtraNSs.size(); i != e; ++i)
Richard Trieu61384cb2011-05-26 20:11:09 +0000191 RBraces += "} ";
Benjamin Kramerf546f412011-05-26 21:32:30 +0000192
Erich Keane53f391d2018-11-12 17:19:48 +0000193 Diag(ExtraNSs[0].NamespaceLoc, diag::ext_nested_namespace_definition)
194 << FixItHint::CreateReplacement(
195 SourceRange(ExtraNSs.front().NamespaceLoc,
196 ExtraNSs.back().IdentLoc),
197 NamespaceFix)
Richard Trieu61384cb2011-05-26 20:11:09 +0000198 << FixItHint::CreateInsertion(rBraceToken.getLocation(), RBraces);
199 }
Erich Keane53f391d2018-11-12 17:19:48 +0000200
201 // Warn about nested inline namespaces.
202 if (FirstNestedInlineLoc.isValid())
203 Diag(FirstNestedInlineLoc, diag::ext_inline_nested_namespace_definition);
Richard Trieu61384cb2011-05-26 20:11:09 +0000204 }
205
Sebastian Redl5a5f2c72010-08-31 00:36:45 +0000206 // If we're still good, complain about inline namespaces in non-C++0x now.
Richard Smith5d164bc2011-10-15 05:09:34 +0000207 if (InlineLoc.isValid())
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000208 Diag(InlineLoc, getLangOpts().CPlusPlus11 ?
Richard Smith5d164bc2011-10-15 05:09:34 +0000209 diag::warn_cxx98_compat_inline_namespace : diag::ext_inline_namespace);
Sebastian Redl5a5f2c72010-08-31 00:36:45 +0000210
Chris Lattner4de55aa2009-03-29 14:02:43 +0000211 // Enter a scope for the namespace.
212 ParseScope NamespaceScope(this, Scope::DeclScope);
213
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +0000214 UsingDirectiveDecl *ImplicitUsingDirectiveDecl = nullptr;
Erich Keanec480f302018-07-12 21:09:05 +0000215 Decl *NamespcDecl = Actions.ActOnStartNamespaceDef(
216 getCurScope(), InlineLoc, NamespaceLoc, IdentLoc, Ident,
217 T.getOpenLocation(), attrs, ImplicitUsingDirectiveDecl);
Chris Lattner4de55aa2009-03-29 14:02:43 +0000218
Jordan Rose1e879d82018-03-23 00:07:18 +0000219 PrettyDeclStackTraceEntry CrashInfo(Actions.Context, NamespcDecl,
220 NamespaceLoc, "parsing namespace");
Mike Stump11289f42009-09-09 15:08:12 +0000221
Fangrui Song6907ce22018-07-30 19:24:48 +0000222 // Parse the contents of the namespace. This includes parsing recovery on
Richard Trieu61384cb2011-05-26 20:11:09 +0000223 // any improperly nested namespaces.
Erich Keane53f391d2018-11-12 17:19:48 +0000224 ParseInnerNamespace(ExtraNSs, 0, InlineLoc, attrs, T);
Mike Stump11289f42009-09-09 15:08:12 +0000225
Chris Lattner4de55aa2009-03-29 14:02:43 +0000226 // Leave the namespace scope.
227 NamespaceScope.Exit();
228
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000229 DeclEnd = T.getCloseLocation();
230 Actions.ActOnFinishNamespaceDef(NamespcDecl, DeclEnd);
Fangrui Song6907ce22018-07-30 19:24:48 +0000231
232 return Actions.ConvertDeclToDeclGroup(NamespcDecl,
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +0000233 ImplicitUsingDirectiveDecl);
Chris Lattnera5235172007-08-25 06:57:03 +0000234}
Chris Lattner38376f12008-01-12 07:05:38 +0000235
Richard Trieu61384cb2011-05-26 20:11:09 +0000236/// ParseInnerNamespace - Parse the contents of a namespace.
Erich Keane53f391d2018-11-12 17:19:48 +0000237void Parser::ParseInnerNamespace(const InnerNamespaceInfoList &InnerNSs,
Richard Smith13307f52014-11-08 05:37:34 +0000238 unsigned int index, SourceLocation &InlineLoc,
239 ParsedAttributes &attrs,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000240 BalancedDelimiterTracker &Tracker) {
Erich Keane53f391d2018-11-12 17:19:48 +0000241 if (index == InnerNSs.size()) {
Richard Smith752ada82015-11-17 23:32:01 +0000242 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
243 Tok.isNot(tok::eof)) {
Richard Trieu61384cb2011-05-26 20:11:09 +0000244 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +0000245 MaybeParseCXX11Attributes(attrs);
Richard Trieu61384cb2011-05-26 20:11:09 +0000246 ParseExternalDeclaration(attrs);
247 }
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000248
249 // The caller is what called check -- we are simply calling
250 // the close for it.
251 Tracker.consumeClose();
Richard Trieu61384cb2011-05-26 20:11:09 +0000252
253 return;
254 }
255
Richard Smith13307f52014-11-08 05:37:34 +0000256 // Handle a nested namespace definition.
257 // FIXME: Preserve the source information through to the AST rather than
258 // desugaring it here.
Richard Trieu61384cb2011-05-26 20:11:09 +0000259 ParseScope NamespaceScope(this, Scope::DeclScope);
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +0000260 UsingDirectiveDecl *ImplicitUsingDirectiveDecl = nullptr;
Erich Keanec480f302018-07-12 21:09:05 +0000261 Decl *NamespcDecl = Actions.ActOnStartNamespaceDef(
Erich Keane53f391d2018-11-12 17:19:48 +0000262 getCurScope(), InnerNSs[index].InlineLoc, InnerNSs[index].NamespaceLoc,
263 InnerNSs[index].IdentLoc, InnerNSs[index].Ident,
264 Tracker.getOpenLocation(), attrs, ImplicitUsingDirectiveDecl);
Fangrui Song6907ce22018-07-30 19:24:48 +0000265 assert(!ImplicitUsingDirectiveDecl &&
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +0000266 "nested namespace definition cannot define anonymous namespace");
Richard Trieu61384cb2011-05-26 20:11:09 +0000267
Erich Keanede6480a32018-11-13 15:48:08 +0000268 ParseInnerNamespace(InnerNSs, ++index, InlineLoc, attrs, Tracker);
Richard Trieu61384cb2011-05-26 20:11:09 +0000269
270 NamespaceScope.Exit();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000271 Actions.ActOnFinishNamespaceDef(NamespcDecl, Tracker.getCloseLocation());
Richard Trieu61384cb2011-05-26 20:11:09 +0000272}
273
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000274/// ParseNamespaceAlias - Parse the part after the '=' in a namespace
275/// alias definition.
276///
John McCall48871652010-08-21 09:40:31 +0000277Decl *Parser::ParseNamespaceAlias(SourceLocation NamespaceLoc,
John McCall084e83d2011-03-24 11:26:52 +0000278 SourceLocation AliasLoc,
279 IdentifierInfo *Alias,
280 SourceLocation &DeclEnd) {
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000281 assert(Tok.is(tok::equal) && "Not equal token");
Mike Stump11289f42009-09-09 15:08:12 +0000282
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000283 ConsumeToken(); // eat the '='.
Mike Stump11289f42009-09-09 15:08:12 +0000284
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000285 if (Tok.is(tok::code_completion)) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000286 Actions.CodeCompleteNamespaceAliasDecl(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000287 cutOffParsing();
Craig Topper161e4db2014-05-21 06:02:52 +0000288 return nullptr;
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000289 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000290
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000291 CXXScopeSpec SS;
292 // Parse (optional) nested-name-specifier.
Haojian Wu0dd0b102020-03-19 09:12:29 +0100293 ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
294 /*ObjectHadErrors=*/false,
295 /*EnteringContext=*/false,
Matthias Gehredc01bb42017-03-17 21:41:20 +0000296 /*MayBePseudoDestructor=*/nullptr,
297 /*IsTypename=*/false,
298 /*LastII=*/nullptr,
299 /*OnlyNamespace=*/true);
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000300
Matthias Gehredc01bb42017-03-17 21:41:20 +0000301 if (Tok.isNot(tok::identifier)) {
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000302 Diag(Tok, diag::err_expected_namespace_name);
303 // Skip to end of the definition and eat the ';'.
304 SkipUntil(tok::semi);
Craig Topper161e4db2014-05-21 06:02:52 +0000305 return nullptr;
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000306 }
307
Matthias Gehredc01bb42017-03-17 21:41:20 +0000308 if (SS.isInvalid()) {
309 // Diagnostics have been emitted in ParseOptionalCXXScopeSpecifier.
310 // Skip to end of the definition and eat the ';'.
311 SkipUntil(tok::semi);
312 return nullptr;
313 }
314
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000315 // Parse identifier.
Anders Carlsson47952ae2009-03-28 22:53:22 +0000316 IdentifierInfo *Ident = Tok.getIdentifierInfo();
317 SourceLocation IdentLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000318
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000319 // Eat the ';'.
Chris Lattner49836b42009-04-02 04:16:50 +0000320 DeclEnd = Tok.getLocation();
Alp Toker383d2c42014-01-01 03:08:43 +0000321 if (ExpectAndConsume(tok::semi, diag::err_expected_semi_after_namespace_name))
322 SkipUntil(tok::semi);
Mike Stump11289f42009-09-09 15:08:12 +0000323
Craig Topperff354282015-11-14 18:16:00 +0000324 return Actions.ActOnNamespaceAliasDef(getCurScope(), NamespaceLoc, AliasLoc,
325 Alias, SS, IdentLoc, Ident);
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000326}
327
Chris Lattner38376f12008-01-12 07:05:38 +0000328/// ParseLinkage - We know that the current token is a string_literal
329/// and just before that, that extern was seen.
330///
331/// linkage-specification: [C++ 7.5p2: dcl.link]
332/// 'extern' string-literal '{' declaration-seq[opt] '}'
333/// 'extern' string-literal declaration
334///
Faisal Vali421b2d12017-12-29 05:41:00 +0000335Decl *Parser::ParseLinkage(ParsingDeclSpec &DS, DeclaratorContext Context) {
Richard Smith4ee696d2014-02-17 23:25:27 +0000336 assert(isTokenStringLiteral() && "Not a string literal!");
337 ExprResult Lang = ParseStringLiteralExpression(false);
Chris Lattner38376f12008-01-12 07:05:38 +0000338
Douglas Gregor07665a62009-01-05 19:45:36 +0000339 ParseScope LinkageScope(this, Scope::DeclScope);
Richard Smith4ee696d2014-02-17 23:25:27 +0000340 Decl *LinkageSpec =
341 Lang.isInvalid()
Craig Topper161e4db2014-05-21 06:02:52 +0000342 ? nullptr
Richard Smith4ee696d2014-02-17 23:25:27 +0000343 : Actions.ActOnStartLinkageSpecification(
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000344 getCurScope(), DS.getSourceRange().getBegin(), Lang.get(),
Richard Smith4ee696d2014-02-17 23:25:27 +0000345 Tok.is(tok::l_brace) ? Tok.getLocation() : SourceLocation());
Douglas Gregor07665a62009-01-05 19:45:36 +0000346
John McCall084e83d2011-03-24 11:26:52 +0000347 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +0000348 MaybeParseCXX11Attributes(attrs);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000349
Douglas Gregor07665a62009-01-05 19:45:36 +0000350 if (Tok.isNot(tok::l_brace)) {
Abramo Bagnara4d423992011-05-01 16:25:54 +0000351 // Reset the source range in DS, as the leading "extern"
352 // does not really belong to the inner declaration ...
353 DS.SetRangeStart(SourceLocation());
354 DS.SetRangeEnd(SourceLocation());
355 // ... but anyway remember that such an "extern" was seen.
Abramo Bagnaraed5b6892010-07-30 16:47:02 +0000356 DS.setExternInLinkageSpec(true);
John McCall53fa7142010-12-24 02:08:15 +0000357 ParseExternalDeclaration(attrs, &DS);
Richard Smith4ee696d2014-02-17 23:25:27 +0000358 return LinkageSpec ? Actions.ActOnFinishLinkageSpecification(
359 getCurScope(), LinkageSpec, SourceLocation())
Craig Topper161e4db2014-05-21 06:02:52 +0000360 : nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000361 }
Douglas Gregor29ff7d02008-12-16 22:23:02 +0000362
Douglas Gregorb65a9132010-02-07 08:38:28 +0000363 DS.abort();
364
John McCall53fa7142010-12-24 02:08:15 +0000365 ProhibitAttributes(attrs);
Alexis Hunt96d5c762009-11-21 08:43:09 +0000366
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000367 BalancedDelimiterTracker T(*this, tok::l_brace);
368 T.consumeOpen();
Richard Smith77944862014-03-02 05:58:18 +0000369
370 unsigned NestedModules = 0;
371 while (true) {
372 switch (Tok.getKind()) {
373 case tok::annot_module_begin:
374 ++NestedModules;
375 ParseTopLevelDecl();
376 continue;
377
378 case tok::annot_module_end:
379 if (!NestedModules)
380 break;
381 --NestedModules;
382 ParseTopLevelDecl();
383 continue;
384
385 case tok::annot_module_include:
386 ParseTopLevelDecl();
387 continue;
388
389 case tok::eof:
390 break;
391
392 case tok::r_brace:
393 if (!NestedModules)
394 break;
Reid Kleckner4dc0b1a2018-11-01 19:54:45 +0000395 LLVM_FALLTHROUGH;
Richard Smith77944862014-03-02 05:58:18 +0000396 default:
397 ParsedAttributesWithRange attrs(AttrFactory);
398 MaybeParseCXX11Attributes(attrs);
Richard Smith77944862014-03-02 05:58:18 +0000399 ParseExternalDeclaration(attrs);
400 continue;
401 }
402
403 break;
Chris Lattner38376f12008-01-12 07:05:38 +0000404 }
405
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000406 T.consumeClose();
Richard Smith4ee696d2014-02-17 23:25:27 +0000407 return LinkageSpec ? Actions.ActOnFinishLinkageSpecification(
408 getCurScope(), LinkageSpec, T.getCloseLocation())
Craig Topper161e4db2014-05-21 06:02:52 +0000409 : nullptr;
Chris Lattner38376f12008-01-12 07:05:38 +0000410}
Douglas Gregor556877c2008-04-13 21:30:24 +0000411
Richard Smith8df390f2016-09-08 23:14:54 +0000412/// Parse a C++ Modules TS export-declaration.
413///
414/// export-declaration:
415/// 'export' declaration
416/// 'export' '{' declaration-seq[opt] '}'
417///
418Decl *Parser::ParseExportDeclaration() {
419 assert(Tok.is(tok::kw_export));
420 SourceLocation ExportLoc = ConsumeToken();
421
422 ParseScope ExportScope(this, Scope::DeclScope);
423 Decl *ExportDecl = Actions.ActOnStartExportDecl(
424 getCurScope(), ExportLoc,
425 Tok.is(tok::l_brace) ? Tok.getLocation() : SourceLocation());
426
427 if (Tok.isNot(tok::l_brace)) {
428 // FIXME: Factor out a ParseExternalDeclarationWithAttrs.
429 ParsedAttributesWithRange Attrs(AttrFactory);
430 MaybeParseCXX11Attributes(Attrs);
431 MaybeParseMicrosoftAttributes(Attrs);
432 ParseExternalDeclaration(Attrs);
433 return Actions.ActOnFinishExportDecl(getCurScope(), ExportDecl,
434 SourceLocation());
435 }
436
437 BalancedDelimiterTracker T(*this, tok::l_brace);
438 T.consumeOpen();
439
440 // The Modules TS draft says "An export-declaration shall declare at least one
441 // entity", but the intent is that it shall contain at least one declaration.
Richard Smithe181de72019-04-22 22:50:11 +0000442 if (Tok.is(tok::r_brace) && getLangOpts().ModulesTS) {
Richard Smith8df390f2016-09-08 23:14:54 +0000443 Diag(ExportLoc, diag::err_export_empty)
444 << SourceRange(ExportLoc, Tok.getLocation());
Richard Smithe181de72019-04-22 22:50:11 +0000445 }
Richard Smith8df390f2016-09-08 23:14:54 +0000446
447 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
448 Tok.isNot(tok::eof)) {
449 ParsedAttributesWithRange Attrs(AttrFactory);
450 MaybeParseCXX11Attributes(Attrs);
451 MaybeParseMicrosoftAttributes(Attrs);
452 ParseExternalDeclaration(Attrs);
453 }
454
455 T.consumeClose();
456 return Actions.ActOnFinishExportDecl(getCurScope(), ExportDecl,
457 T.getCloseLocation());
458}
459
Douglas Gregord7c4d982008-12-30 03:27:21 +0000460/// ParseUsingDirectiveOrDeclaration - Parse C++ using using-declaration or
461/// using-directive. Assumes that current token is 'using'.
Richard Smith6f1daa42016-12-16 00:58:48 +0000462Parser::DeclGroupPtrTy
Faisal Vali421b2d12017-12-29 05:41:00 +0000463Parser::ParseUsingDirectiveOrDeclaration(DeclaratorContext Context,
John McCall9b72f892010-11-10 02:40:36 +0000464 const ParsedTemplateInfo &TemplateInfo,
Richard Smith6f1daa42016-12-16 00:58:48 +0000465 SourceLocation &DeclEnd,
466 ParsedAttributesWithRange &attrs) {
Douglas Gregord7c4d982008-12-30 03:27:21 +0000467 assert(Tok.is(tok::kw_using) && "Not using token");
Fariborz Jahanian4bf82622011-08-22 17:59:19 +0000468 ObjCDeclContextSwitch ObjCDC(*this);
Fangrui Song6907ce22018-07-30 19:24:48 +0000469
Douglas Gregord7c4d982008-12-30 03:27:21 +0000470 // Eat 'using'.
471 SourceLocation UsingLoc = ConsumeToken();
472
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000473 if (Tok.is(tok::code_completion)) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000474 Actions.CodeCompleteUsing(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000475 cutOffParsing();
Craig Topper161e4db2014-05-21 06:02:52 +0000476 return nullptr;
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000477 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000478
Richard Trieu2efd3052019-05-01 23:33:49 +0000479 // Consume unexpected 'template' keywords.
480 while (Tok.is(tok::kw_template)) {
481 SourceLocation TemplateLoc = ConsumeToken();
482 Diag(TemplateLoc, diag::err_unexpected_template_after_using)
483 << FixItHint::CreateRemoval(TemplateLoc);
484 }
485
John McCall9b72f892010-11-10 02:40:36 +0000486 // 'using namespace' means this is a using-directive.
487 if (Tok.is(tok::kw_namespace)) {
488 // Template parameters are always an error here.
489 if (TemplateInfo.Kind) {
490 SourceRange R = TemplateInfo.getSourceRange();
Craig Topper54a6a682015-11-14 18:16:08 +0000491 Diag(UsingLoc, diag::err_templated_using_directive_declaration)
492 << 0 /* directive */ << R << FixItHint::CreateRemoval(R);
John McCall9b72f892010-11-10 02:40:36 +0000493 }
Alexis Hunt96d5c762009-11-21 08:43:09 +0000494
Richard Smith6f1daa42016-12-16 00:58:48 +0000495 Decl *UsingDir = ParseUsingDirective(Context, UsingLoc, DeclEnd, attrs);
496 return Actions.ConvertDeclToDeclGroup(UsingDir);
John McCall9b72f892010-11-10 02:40:36 +0000497 }
498
Richard Smithdda56e42011-04-15 14:24:37 +0000499 // Otherwise, it must be a using-declaration or an alias-declaration.
John McCall9b72f892010-11-10 02:40:36 +0000500
501 // Using declarations can't have attributes.
John McCall53fa7142010-12-24 02:08:15 +0000502 ProhibitAttributes(attrs);
Chris Lattner9b01ca12009-01-06 06:55:51 +0000503
Fariborz Jahanian4bf82622011-08-22 17:59:19 +0000504 return ParseUsingDeclaration(Context, TemplateInfo, UsingLoc, DeclEnd,
Richard Smith6f1daa42016-12-16 00:58:48 +0000505 AS_none);
Douglas Gregord7c4d982008-12-30 03:27:21 +0000506}
507
508/// ParseUsingDirective - Parse C++ using-directive, assumes
509/// that current token is 'namespace' and 'using' was already parsed.
510///
511/// using-directive: [C++ 7.3.p4: namespace.udir]
512/// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
513/// namespace-name ;
514/// [GNU] using-directive:
515/// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
516/// namespace-name attributes[opt] ;
517///
Faisal Vali421b2d12017-12-29 05:41:00 +0000518Decl *Parser::ParseUsingDirective(DeclaratorContext Context,
John McCall9b72f892010-11-10 02:40:36 +0000519 SourceLocation UsingLoc,
520 SourceLocation &DeclEnd,
John McCall53fa7142010-12-24 02:08:15 +0000521 ParsedAttributes &attrs) {
Douglas Gregord7c4d982008-12-30 03:27:21 +0000522 assert(Tok.is(tok::kw_namespace) && "Not 'namespace' token");
523
524 // Eat 'namespace'.
525 SourceLocation NamespcLoc = ConsumeToken();
526
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000527 if (Tok.is(tok::code_completion)) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000528 Actions.CodeCompleteUsingDirective(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000529 cutOffParsing();
Craig Topper161e4db2014-05-21 06:02:52 +0000530 return nullptr;
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000531 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000532
Douglas Gregord7c4d982008-12-30 03:27:21 +0000533 CXXScopeSpec SS;
534 // Parse (optional) nested-name-specifier.
Haojian Wu0dd0b102020-03-19 09:12:29 +0100535 ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
536 /*ObjectHadErrors=*/false,
537 /*EnteringContext=*/false,
Matthias Gehredc01bb42017-03-17 21:41:20 +0000538 /*MayBePseudoDestructor=*/nullptr,
539 /*IsTypename=*/false,
540 /*LastII=*/nullptr,
541 /*OnlyNamespace=*/true);
Douglas Gregord7c4d982008-12-30 03:27:21 +0000542
Craig Topper161e4db2014-05-21 06:02:52 +0000543 IdentifierInfo *NamespcName = nullptr;
Douglas Gregord7c4d982008-12-30 03:27:21 +0000544 SourceLocation IdentLoc = SourceLocation();
545
546 // Parse namespace-name.
Matthias Gehredc01bb42017-03-17 21:41:20 +0000547 if (Tok.isNot(tok::identifier)) {
Douglas Gregord7c4d982008-12-30 03:27:21 +0000548 Diag(Tok, diag::err_expected_namespace_name);
549 // If there was invalid namespace name, skip to end of decl, and eat ';'.
550 SkipUntil(tok::semi);
551 // FIXME: Are there cases, when we would like to call ActOnUsingDirective?
Craig Topper161e4db2014-05-21 06:02:52 +0000552 return nullptr;
Douglas Gregord7c4d982008-12-30 03:27:21 +0000553 }
Mike Stump11289f42009-09-09 15:08:12 +0000554
Matthias Gehredc01bb42017-03-17 21:41:20 +0000555 if (SS.isInvalid()) {
556 // Diagnostics have been emitted in ParseOptionalCXXScopeSpecifier.
557 // Skip to end of the definition and eat the ';'.
558 SkipUntil(tok::semi);
559 return nullptr;
560 }
561
Chris Lattnerce1da2c2009-01-06 07:27:21 +0000562 // Parse identifier.
563 NamespcName = Tok.getIdentifierInfo();
564 IdentLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000565
Chris Lattnerce1da2c2009-01-06 07:27:21 +0000566 // Parse (optional) attributes (most likely GNU strong-using extension).
Alexis Hunt96d5c762009-11-21 08:43:09 +0000567 bool GNUAttr = false;
568 if (Tok.is(tok::kw___attribute)) {
569 GNUAttr = true;
John McCall53fa7142010-12-24 02:08:15 +0000570 ParseGNUAttributes(attrs);
Alexis Hunt96d5c762009-11-21 08:43:09 +0000571 }
Mike Stump11289f42009-09-09 15:08:12 +0000572
Chris Lattnerce1da2c2009-01-06 07:27:21 +0000573 // Eat ';'.
Chris Lattner49836b42009-04-02 04:16:50 +0000574 DeclEnd = Tok.getLocation();
Alp Toker383d2c42014-01-01 03:08:43 +0000575 if (ExpectAndConsume(tok::semi,
576 GNUAttr ? diag::err_expected_semi_after_attribute_list
577 : diag::err_expected_semi_after_namespace_name))
578 SkipUntil(tok::semi);
Douglas Gregord7c4d982008-12-30 03:27:21 +0000579
Douglas Gregor0be31a22010-07-02 17:43:08 +0000580 return Actions.ActOnUsingDirective(getCurScope(), UsingLoc, NamespcLoc, SS,
Erich Keanec480f302018-07-12 21:09:05 +0000581 IdentLoc, NamespcName, attrs);
Douglas Gregord7c4d982008-12-30 03:27:21 +0000582}
583
Richard Smith6f1daa42016-12-16 00:58:48 +0000584/// Parse a using-declarator (or the identifier in a C++11 alias-declaration).
Douglas Gregord7c4d982008-12-30 03:27:21 +0000585///
Richard Smith6f1daa42016-12-16 00:58:48 +0000586/// using-declarator:
587/// 'typename'[opt] nested-name-specifier unqualified-id
Douglas Gregord7c4d982008-12-30 03:27:21 +0000588///
Faisal Vali421b2d12017-12-29 05:41:00 +0000589bool Parser::ParseUsingDeclarator(DeclaratorContext Context,
590 UsingDeclarator &D) {
Richard Smith6f1daa42016-12-16 00:58:48 +0000591 D.clear();
Douglas Gregorfec52632009-06-20 00:51:54 +0000592
593 // Ignore optional 'typename'.
Douglas Gregor220f4272009-11-04 16:30:06 +0000594 // FIXME: This is wrong; we should parse this as a typename-specifier.
Richard Smith6f1daa42016-12-16 00:58:48 +0000595 TryConsumeToken(tok::kw_typename, D.TypenameLoc);
Douglas Gregorfec52632009-06-20 00:51:54 +0000596
Nikola Smiljanic67860242014-09-26 00:28:20 +0000597 if (Tok.is(tok::kw___super)) {
598 Diag(Tok.getLocation(), diag::err_super_in_using_declaration);
Richard Smith6f1daa42016-12-16 00:58:48 +0000599 return true;
Nikola Smiljanic67860242014-09-26 00:28:20 +0000600 }
601
Douglas Gregorfec52632009-06-20 00:51:54 +0000602 // Parse nested-name-specifier.
Craig Topper161e4db2014-05-21 06:02:52 +0000603 IdentifierInfo *LastII = nullptr;
Haojian Wu0dd0b102020-03-19 09:12:29 +0100604 if (ParseOptionalCXXScopeSpecifier(D.SS, /*ObjectType=*/nullptr,
605 /*ObjectHadErrors=*/false,
606 /*EnteringContext=*/false,
Richard Smithb23c5e82019-05-09 03:31:27 +0000607 /*MayBePseudoDtor=*/nullptr,
608 /*IsTypename=*/false,
Ilya Biryukovd9971d02019-10-28 09:34:21 +0100609 /*LastII=*/&LastII,
610 /*OnlyNamespace=*/false,
611 /*InUsingDeclaration=*/true))
612
Richard Smithb23c5e82019-05-09 03:31:27 +0000613 return true;
Richard Smith6f1daa42016-12-16 00:58:48 +0000614 if (D.SS.isInvalid())
615 return true;
Richard Smith7447af42013-03-26 01:15:19 +0000616
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000617 // Parse the unqualified-id. We allow parsing of both constructor and
Douglas Gregor220f4272009-11-04 16:30:06 +0000618 // destructor names and allow the action module to diagnose any semantic
619 // errors.
Richard Smith7447af42013-03-26 01:15:19 +0000620 //
621 // C++11 [class.qual]p2:
622 // [...] in a using-declaration that is a member-declaration, if the name
623 // specified after the nested-name-specifier is the same as the identifier
624 // or the simple-template-id's template-name in the last component of the
625 // nested-name-specifier, the name is [...] considered to name the
626 // constructor.
Faisal Vali421b2d12017-12-29 05:41:00 +0000627 if (getLangOpts().CPlusPlus11 &&
628 Context == DeclaratorContext::MemberContext &&
Richard Smith151c4562016-12-20 21:35:28 +0000629 Tok.is(tok::identifier) &&
630 (NextToken().is(tok::semi) || NextToken().is(tok::comma) ||
631 NextToken().is(tok::ellipsis)) &&
Richard Smith6f1daa42016-12-16 00:58:48 +0000632 D.SS.isNotEmpty() && LastII == Tok.getIdentifierInfo() &&
633 !D.SS.getScopeRep()->getAsNamespace() &&
634 !D.SS.getScopeRep()->getAsNamespaceAlias()) {
Richard Smith7447af42013-03-26 01:15:19 +0000635 SourceLocation IdLoc = ConsumeToken();
Richard Smith6f1daa42016-12-16 00:58:48 +0000636 ParsedType Type =
637 Actions.getInheritingConstructorName(D.SS, IdLoc, *LastII);
638 D.Name.setConstructorName(Type, IdLoc, IdLoc);
639 } else {
640 if (ParseUnqualifiedId(
Haojian Wu0dd0b102020-03-19 09:12:29 +0100641 D.SS, /*ObjectType=*/nullptr,
642 /*ObjectHadErrors=*/false, /*EnteringContext=*/false,
Richard Smith6f1daa42016-12-16 00:58:48 +0000643 /*AllowDestructorName=*/true,
Haojian Wu0dd0b102020-03-19 09:12:29 +0100644 /*AllowConstructorName=*/
645 !(Tok.is(tok::identifier) && NextToken().is(tok::equal)),
646 /*AllowDeductionGuide=*/false, nullptr, D.Name))
Richard Smith6f1daa42016-12-16 00:58:48 +0000647 return true;
Douglas Gregorfec52632009-06-20 00:51:54 +0000648 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000649
Richard Smith151c4562016-12-20 21:35:28 +0000650 if (TryConsumeToken(tok::ellipsis, D.EllipsisLoc))
Aaron Ballmanc351fba2017-12-04 20:27:34 +0000651 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17 ?
Richard Smithb115e5d2017-08-13 23:37:29 +0000652 diag::warn_cxx17_compat_using_declaration_pack :
Richard Smith151c4562016-12-20 21:35:28 +0000653 diag::ext_using_declaration_pack);
Richard Smith6f1daa42016-12-16 00:58:48 +0000654
655 return false;
656}
657
658/// ParseUsingDeclaration - Parse C++ using-declaration or alias-declaration.
659/// Assumes that 'using' was already seen.
660///
661/// using-declaration: [C++ 7.3.p3: namespace.udecl]
662/// 'using' using-declarator-list[opt] ;
663///
664/// using-declarator-list: [C++1z]
665/// using-declarator '...'[opt]
666/// using-declarator-list ',' using-declarator '...'[opt]
667///
668/// using-declarator-list: [C++98-14]
669/// using-declarator
670///
671/// alias-declaration: C++11 [dcl.dcl]p1
672/// 'using' identifier attribute-specifier-seq[opt] = type-id ;
673///
674Parser::DeclGroupPtrTy
Faisal Vali421b2d12017-12-29 05:41:00 +0000675Parser::ParseUsingDeclaration(DeclaratorContext Context,
Richard Smith6f1daa42016-12-16 00:58:48 +0000676 const ParsedTemplateInfo &TemplateInfo,
677 SourceLocation UsingLoc, SourceLocation &DeclEnd,
678 AccessSpecifier AS) {
679 // Check for misplaced attributes before the identifier in an
680 // alias-declaration.
681 ParsedAttributesWithRange MisplacedAttrs(AttrFactory);
682 MaybeParseCXX11Attributes(MisplacedAttrs);
683
684 UsingDeclarator D;
685 bool InvalidDeclarator = ParseUsingDeclarator(Context, D);
686
Richard Smithc2c8bb82013-10-15 01:34:54 +0000687 ParsedAttributesWithRange Attrs(AttrFactory);
Richard Smith37a45dd2013-10-24 01:21:09 +0000688 MaybeParseGNUAttributes(Attrs);
Richard Smith54ecd982013-02-20 19:22:51 +0000689 MaybeParseCXX11Attributes(Attrs);
Richard Smithdda56e42011-04-15 14:24:37 +0000690
691 // Maybe this is an alias-declaration.
Richard Smith6f1daa42016-12-16 00:58:48 +0000692 if (Tok.is(tok::equal)) {
693 if (InvalidDeclarator) {
694 SkipUntil(tok::semi);
695 return nullptr;
696 }
697
Richard Smithc2c8bb82013-10-15 01:34:54 +0000698 // If we had any misplaced attributes from earlier, this is where they
699 // should have been written.
700 if (MisplacedAttrs.Range.isValid()) {
701 Diag(MisplacedAttrs.Range.getBegin(), diag::err_attributes_not_allowed)
702 << FixItHint::CreateInsertionFromRange(
703 Tok.getLocation(),
704 CharSourceRange::getTokenRange(MisplacedAttrs.Range))
705 << FixItHint::CreateRemoval(MisplacedAttrs.Range);
706 Attrs.takeAllFrom(MisplacedAttrs);
707 }
708
Richard Smith6f1daa42016-12-16 00:58:48 +0000709 Decl *DeclFromDeclSpec = nullptr;
710 Decl *AD = ParseAliasDeclarationAfterDeclarator(
711 TemplateInfo, UsingLoc, D, DeclEnd, AS, Attrs, &DeclFromDeclSpec);
712 return Actions.ConvertDeclToDeclGroup(AD, DeclFromDeclSpec);
Alexis Hunt6aa9bee2012-06-23 05:07:58 +0000713 }
Mike Stump11289f42009-09-09 15:08:12 +0000714
Richard Smith6f1daa42016-12-16 00:58:48 +0000715 // C++11 attributes are not allowed on a using-declaration, but GNU ones
716 // are.
717 ProhibitAttributes(MisplacedAttrs);
718 ProhibitAttributes(Attrs);
Douglas Gregorfec52632009-06-20 00:51:54 +0000719
John McCall9b72f892010-11-10 02:40:36 +0000720 // Diagnose an attempt to declare a templated using-declaration.
Richard Smith810ad3e2013-01-29 10:02:16 +0000721 // In C++11, alias-declarations can be templates:
Richard Smithdda56e42011-04-15 14:24:37 +0000722 // template <...> using id = type;
Richard Smith6f1daa42016-12-16 00:58:48 +0000723 if (TemplateInfo.Kind) {
John McCall9b72f892010-11-10 02:40:36 +0000724 SourceRange R = TemplateInfo.getSourceRange();
Craig Topper54a6a682015-11-14 18:16:08 +0000725 Diag(UsingLoc, diag::err_templated_using_directive_declaration)
726 << 1 /* declaration */ << R << FixItHint::CreateRemoval(R);
John McCall9b72f892010-11-10 02:40:36 +0000727
728 // Unfortunately, we have to bail out instead of recovering by
729 // ignoring the parameters, just in case the nested name specifier
730 // depends on the parameters.
Craig Topper161e4db2014-05-21 06:02:52 +0000731 return nullptr;
John McCall9b72f892010-11-10 02:40:36 +0000732 }
733
Richard Smith6f1daa42016-12-16 00:58:48 +0000734 SmallVector<Decl *, 8> DeclsInGroup;
735 while (true) {
736 // Parse (optional) attributes (most likely GNU strong-using extension).
737 MaybeParseGNUAttributes(Attrs);
738
739 if (InvalidDeclarator)
740 SkipUntil(tok::comma, tok::semi, StopBeforeMatch);
741 else {
742 // "typename" keyword is allowed for identifiers only,
743 // because it may be a type definition.
744 if (D.TypenameLoc.isValid() &&
Faisal Vali2ab8c152017-12-30 04:15:27 +0000745 D.Name.getKind() != UnqualifiedIdKind::IK_Identifier) {
Richard Smith6f1daa42016-12-16 00:58:48 +0000746 Diag(D.Name.getSourceRange().getBegin(),
747 diag::err_typename_identifiers_only)
748 << FixItHint::CreateRemoval(SourceRange(D.TypenameLoc));
749 // Proceed parsing, but discard the typename keyword.
750 D.TypenameLoc = SourceLocation();
751 }
752
Richard Smith151c4562016-12-20 21:35:28 +0000753 Decl *UD = Actions.ActOnUsingDeclaration(getCurScope(), AS, UsingLoc,
754 D.TypenameLoc, D.SS, D.Name,
Erich Keanec480f302018-07-12 21:09:05 +0000755 D.EllipsisLoc, Attrs);
Richard Smith6f1daa42016-12-16 00:58:48 +0000756 if (UD)
757 DeclsInGroup.push_back(UD);
758 }
759
760 if (!TryConsumeToken(tok::comma))
761 break;
762
763 // Parse another using-declarator.
764 Attrs.clear();
765 InvalidDeclarator = ParseUsingDeclarator(Context, D);
Douglas Gregor882a61a2011-09-26 14:30:28 +0000766 }
767
Richard Smith6f1daa42016-12-16 00:58:48 +0000768 if (DeclsInGroup.size() > 1)
Aaron Ballmanc351fba2017-12-04 20:27:34 +0000769 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17 ?
Richard Smithb115e5d2017-08-13 23:37:29 +0000770 diag::warn_cxx17_compat_multi_using_declaration :
Richard Smith6f1daa42016-12-16 00:58:48 +0000771 diag::ext_multi_using_declaration);
772
773 // Eat ';'.
774 DeclEnd = Tok.getLocation();
775 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
776 !Attrs.empty() ? "attributes list"
777 : "using declaration"))
778 SkipUntil(tok::semi);
779
Richard Smith3beb7c62017-01-12 02:27:38 +0000780 return Actions.BuildDeclaratorGroup(DeclsInGroup);
Richard Smith6f1daa42016-12-16 00:58:48 +0000781}
782
Richard Smith6f1daa42016-12-16 00:58:48 +0000783Decl *Parser::ParseAliasDeclarationAfterDeclarator(
784 const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc,
785 UsingDeclarator &D, SourceLocation &DeclEnd, AccessSpecifier AS,
786 ParsedAttributes &Attrs, Decl **OwnedType) {
787 if (ExpectAndConsume(tok::equal)) {
788 SkipUntil(tok::semi);
789 return nullptr;
790 }
791
792 Diag(Tok.getLocation(), getLangOpts().CPlusPlus11 ?
793 diag::warn_cxx98_compat_alias_declaration :
794 diag::ext_alias_declaration);
795
796 // Type alias templates cannot be specialized.
797 int SpecKind = -1;
798 if (TemplateInfo.Kind == ParsedTemplateInfo::Template &&
Faisal Vali2ab8c152017-12-30 04:15:27 +0000799 D.Name.getKind() == UnqualifiedIdKind::IK_TemplateId)
Richard Smith6f1daa42016-12-16 00:58:48 +0000800 SpecKind = 0;
801 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization)
802 SpecKind = 1;
803 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
804 SpecKind = 2;
805 if (SpecKind != -1) {
806 SourceRange Range;
807 if (SpecKind == 0)
808 Range = SourceRange(D.Name.TemplateId->LAngleLoc,
809 D.Name.TemplateId->RAngleLoc);
810 else
811 Range = TemplateInfo.getSourceRange();
812 Diag(Range.getBegin(), diag::err_alias_declaration_specialization)
813 << SpecKind << Range;
814 SkipUntil(tok::semi);
815 return nullptr;
816 }
817
818 // Name must be an identifier.
Faisal Vali2ab8c152017-12-30 04:15:27 +0000819 if (D.Name.getKind() != UnqualifiedIdKind::IK_Identifier) {
Richard Smith6f1daa42016-12-16 00:58:48 +0000820 Diag(D.Name.StartLocation, diag::err_alias_declaration_not_identifier);
821 // No removal fixit: can't recover from this.
822 SkipUntil(tok::semi);
823 return nullptr;
824 } else if (D.TypenameLoc.isValid())
825 Diag(D.TypenameLoc, diag::err_alias_declaration_not_identifier)
826 << FixItHint::CreateRemoval(SourceRange(
827 D.TypenameLoc,
828 D.SS.isNotEmpty() ? D.SS.getEndLoc() : D.TypenameLoc));
829 else if (D.SS.isNotEmpty())
830 Diag(D.SS.getBeginLoc(), diag::err_alias_declaration_not_identifier)
831 << FixItHint::CreateRemoval(D.SS.getRange());
Richard Smith151c4562016-12-20 21:35:28 +0000832 if (D.EllipsisLoc.isValid())
833 Diag(D.EllipsisLoc, diag::err_alias_declaration_pack_expansion)
834 << FixItHint::CreateRemoval(SourceRange(D.EllipsisLoc));
Richard Smith6f1daa42016-12-16 00:58:48 +0000835
836 Decl *DeclFromDeclSpec = nullptr;
Faisal Vali421b2d12017-12-29 05:41:00 +0000837 TypeResult TypeAlias = ParseTypeName(
838 nullptr,
839 TemplateInfo.Kind ? DeclaratorContext::AliasTemplateContext
840 : DeclaratorContext::AliasDeclContext,
841 AS, &DeclFromDeclSpec, &Attrs);
Richard Smith6f1daa42016-12-16 00:58:48 +0000842 if (OwnedType)
843 *OwnedType = DeclFromDeclSpec;
844
845 // Eat ';'.
846 DeclEnd = Tok.getLocation();
847 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
848 !Attrs.empty() ? "attributes list"
849 : "alias declaration"))
850 SkipUntil(tok::semi);
851
852 TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
853 MultiTemplateParamsArg TemplateParamsArg(
854 TemplateParams ? TemplateParams->data() : nullptr,
855 TemplateParams ? TemplateParams->size() : 0);
856 return Actions.ActOnAliasDeclaration(getCurScope(), AS, TemplateParamsArg,
Erich Keanec480f302018-07-12 21:09:05 +0000857 UsingLoc, D.Name, Attrs, TypeAlias,
858 DeclFromDeclSpec);
Douglas Gregord7c4d982008-12-30 03:27:21 +0000859}
860
Benjamin Kramere56f3932011-12-23 17:00:35 +0000861/// ParseStaticAssertDeclaration - Parse C++0x or C11 static_assert-declaration.
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000862///
Peter Collingbourne3d9cbdc2011-04-15 00:35:57 +0000863/// [C++0x] static_assert-declaration:
864/// static_assert ( constant-expression , string-literal ) ;
865///
Benjamin Kramere56f3932011-12-23 17:00:35 +0000866/// [C11] static_assert-declaration:
Peter Collingbourne3d9cbdc2011-04-15 00:35:57 +0000867/// _Static_assert ( constant-expression , string-literal ) ;
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000868///
John McCall48871652010-08-21 09:40:31 +0000869Decl *Parser::ParseStaticAssertDeclaration(SourceLocation &DeclEnd){
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000870 assert(Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert) &&
Peter Collingbourne3d9cbdc2011-04-15 00:35:57 +0000871 "Not a static_assert declaration");
872
David Blaikiebbafb8a2012-03-11 07:00:24 +0000873 if (Tok.is(tok::kw__Static_assert) && !getLangOpts().C11)
Aaron Ballman1d935222019-08-27 14:41:39 +0000874 Diag(Tok, diag::ext_c11_feature) << Tok.getName();
Richard Smithb15c11c2011-10-17 23:06:20 +0000875 if (Tok.is(tok::kw_static_assert))
876 Diag(Tok, diag::warn_cxx98_compat_static_assert);
Peter Collingbourne3d9cbdc2011-04-15 00:35:57 +0000877
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000878 SourceLocation StaticAssertLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000879
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000880 BalancedDelimiterTracker T(*this, tok::l_paren);
881 if (T.consumeOpen()) {
Alp Tokerec543272013-12-24 09:48:30 +0000882 Diag(Tok, diag::err_expected) << tok::l_paren;
Richard Smith76965712012-09-13 19:12:50 +0000883 SkipMalformedDecl();
Craig Topper161e4db2014-05-21 06:02:52 +0000884 return nullptr;
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000885 }
Mike Stump11289f42009-09-09 15:08:12 +0000886
Richard Smithb3018062017-06-06 01:34:24 +0000887 EnterExpressionEvaluationContext ConstantEvaluated(
888 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
889 ExprResult AssertExpr(ParseConstantExpressionInExprEvalContext());
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000890 if (AssertExpr.isInvalid()) {
Richard Smith76965712012-09-13 19:12:50 +0000891 SkipMalformedDecl();
Craig Topper161e4db2014-05-21 06:02:52 +0000892 return nullptr;
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000893 }
Mike Stump11289f42009-09-09 15:08:12 +0000894
Richard Smith085a64f2014-06-20 19:57:12 +0000895 ExprResult AssertMessage;
896 if (Tok.is(tok::r_paren)) {
Aaron Ballmanc351fba2017-12-04 20:27:34 +0000897 Diag(Tok, getLangOpts().CPlusPlus17
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000898 ? diag::warn_cxx14_compat_static_assert_no_message
Richard Smith085a64f2014-06-20 19:57:12 +0000899 : diag::ext_static_assert_no_message)
Aaron Ballmanc351fba2017-12-04 20:27:34 +0000900 << (getLangOpts().CPlusPlus17
Richard Smith085a64f2014-06-20 19:57:12 +0000901 ? FixItHint()
902 : FixItHint::CreateInsertion(Tok.getLocation(), ", \"\""));
903 } else {
904 if (ExpectAndConsume(tok::comma)) {
905 SkipUntil(tok::semi);
906 return nullptr;
907 }
Anders Carlssonb4cf3ad2009-03-13 23:29:20 +0000908
Richard Smith085a64f2014-06-20 19:57:12 +0000909 if (!isTokenStringLiteral()) {
910 Diag(Tok, diag::err_expected_string_literal)
911 << /*Source='static_assert'*/1;
912 SkipMalformedDecl();
913 return nullptr;
914 }
Mike Stump11289f42009-09-09 15:08:12 +0000915
Richard Smith085a64f2014-06-20 19:57:12 +0000916 AssertMessage = ParseStringLiteralExpression();
917 if (AssertMessage.isInvalid()) {
918 SkipMalformedDecl();
919 return nullptr;
920 }
Richard Smithd67aea22012-03-06 03:21:47 +0000921 }
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000922
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000923 T.consumeClose();
Mike Stump11289f42009-09-09 15:08:12 +0000924
Chris Lattner49836b42009-04-02 04:16:50 +0000925 DeclEnd = Tok.getLocation();
Douglas Gregor45d6bdf2010-09-07 15:23:11 +0000926 ExpectAndConsumeSemi(diag::err_expected_semi_after_static_assert);
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000927
John McCallb268a282010-08-23 23:25:46 +0000928 return Actions.ActOnStaticAssertDeclaration(StaticAssertLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000929 AssertExpr.get(),
930 AssertMessage.get(),
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000931 T.getCloseLocation());
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000932}
933
Richard Smith74aeef52013-04-26 16:15:35 +0000934/// ParseDecltypeSpecifier - Parse a C++11 decltype specifier.
Anders Carlsson74948d02009-06-24 17:47:40 +0000935///
936/// 'decltype' ( expression )
Richard Smith74aeef52013-04-26 16:15:35 +0000937/// 'decltype' ( 'auto' ) [C++1y]
Anders Carlsson74948d02009-06-24 17:47:40 +0000938///
David Blaikie15a430a2011-12-04 05:04:18 +0000939SourceLocation Parser::ParseDecltypeSpecifier(DeclSpec &DS) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000940 assert(Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)
David Blaikie15a430a2011-12-04 05:04:18 +0000941 && "Not a decltype specifier");
Fangrui Song6907ce22018-07-30 19:24:48 +0000942
David Blaikie15a430a2011-12-04 05:04:18 +0000943 ExprResult Result;
944 SourceLocation StartLoc = Tok.getLocation();
945 SourceLocation EndLoc;
946
947 if (Tok.is(tok::annot_decltype)) {
948 Result = getExprAnnotation(Tok);
949 EndLoc = Tok.getAnnotationEndLoc();
Richard Smithaf3b3252017-05-18 19:21:48 +0000950 ConsumeAnnotationToken();
David Blaikie15a430a2011-12-04 05:04:18 +0000951 if (Result.isInvalid()) {
952 DS.SetTypeSpecError();
953 return EndLoc;
954 }
955 } else {
Richard Smith324df552012-02-24 22:30:04 +0000956 if (Tok.getIdentifierInfo()->isStr("decltype"))
957 Diag(Tok, diag::warn_cxx98_compat_decltype);
Richard Smithfd3da932012-02-24 18:10:23 +0000958
David Blaikie15a430a2011-12-04 05:04:18 +0000959 ConsumeToken();
960
961 BalancedDelimiterTracker T(*this, tok::l_paren);
962 if (T.expectAndConsume(diag::err_expected_lparen_after,
963 "decltype", tok::r_paren)) {
964 DS.SetTypeSpecError();
965 return T.getOpenLocation() == Tok.getLocation() ?
966 StartLoc : T.getOpenLocation();
967 }
968
Richard Smith74aeef52013-04-26 16:15:35 +0000969 // Check for C++1y 'decltype(auto)'.
970 if (Tok.is(tok::kw_auto)) {
971 // No need to disambiguate here: an expression can't start with 'auto',
972 // because the typename-specifier in a function-style cast operation can't
973 // be 'auto'.
974 Diag(Tok.getLocation(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000975 getLangOpts().CPlusPlus14
Richard Smith74aeef52013-04-26 16:15:35 +0000976 ? diag::warn_cxx11_compat_decltype_auto_type_specifier
977 : diag::ext_decltype_auto_type_specifier);
978 ConsumeToken();
979 } else {
980 // Parse the expression
David Blaikie15a430a2011-12-04 05:04:18 +0000981
Richard Smith74aeef52013-04-26 16:15:35 +0000982 // C++11 [dcl.type.simple]p4:
983 // The operand of the decltype specifier is an unevaluated operand.
Faisal Valid143a0c2017-04-01 21:30:49 +0000984 EnterExpressionEvaluationContext Unevaluated(
985 Actions, Sema::ExpressionEvaluationContext::Unevaluated, nullptr,
Nicolas Lesserb6d5c582018-07-12 18:45:41 +0000986 Sema::ExpressionEvaluationContextRecord::EK_Decltype);
Kaelyn Takata5cc85352015-04-10 19:16:46 +0000987 Result =
988 Actions.CorrectDelayedTyposInExpr(ParseExpression(), [](Expr *E) {
989 return E->hasPlaceholderType() ? ExprError() : E;
990 });
Richard Smith74aeef52013-04-26 16:15:35 +0000991 if (Result.isInvalid()) {
992 DS.SetTypeSpecError();
Alexey Bataevee6507d2013-11-18 08:17:37 +0000993 if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch)) {
Richard Smith74aeef52013-04-26 16:15:35 +0000994 EndLoc = ConsumeParen();
Argyrios Kyrtzidisc38395a2012-10-26 22:53:44 +0000995 } else {
Richard Smith74aeef52013-04-26 16:15:35 +0000996 if (PP.isBacktrackEnabled() && Tok.is(tok::semi)) {
997 // Backtrack to get the location of the last token before the semi.
998 PP.RevertCachedTokens(2);
999 ConsumeToken(); // the semi.
1000 EndLoc = ConsumeAnyToken();
1001 assert(Tok.is(tok::semi));
1002 } else {
1003 EndLoc = Tok.getLocation();
1004 }
Argyrios Kyrtzidisc38395a2012-10-26 22:53:44 +00001005 }
Richard Smith74aeef52013-04-26 16:15:35 +00001006 return EndLoc;
Argyrios Kyrtzidisc38395a2012-10-26 22:53:44 +00001007 }
Richard Smith74aeef52013-04-26 16:15:35 +00001008
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001009 Result = Actions.ActOnDecltypeExpression(Result.get());
David Blaikie15a430a2011-12-04 05:04:18 +00001010 }
1011
1012 // Match the ')'
1013 T.consumeClose();
1014 if (T.getCloseLocation().isInvalid()) {
1015 DS.SetTypeSpecError();
1016 // FIXME: this should return the location of the last token
1017 // that was consumed (by "consumeClose()")
1018 return T.getCloseLocation();
1019 }
1020
Richard Smithfd555f62012-02-22 02:04:18 +00001021 if (Result.isInvalid()) {
1022 DS.SetTypeSpecError();
1023 return T.getCloseLocation();
1024 }
1025
David Blaikie15a430a2011-12-04 05:04:18 +00001026 EndLoc = T.getCloseLocation();
Anders Carlsson74948d02009-06-24 17:47:40 +00001027 }
Richard Smith74aeef52013-04-26 16:15:35 +00001028 assert(!Result.isInvalid());
Mike Stump11289f42009-09-09 15:08:12 +00001029
Craig Topper161e4db2014-05-21 06:02:52 +00001030 const char *PrevSpec = nullptr;
John McCall49bfce42009-08-03 20:12:06 +00001031 unsigned DiagID;
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001032 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
Anders Carlsson74948d02009-06-24 17:47:40 +00001033 // Check for duplicate type specifiers (e.g. "int decltype(a)").
Richard Smith74aeef52013-04-26 16:15:35 +00001034 if (Result.get()
1035 ? DS.SetTypeSpecType(DeclSpec::TST_decltype, StartLoc, PrevSpec,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001036 DiagID, Result.get(), Policy)
Richard Smith74aeef52013-04-26 16:15:35 +00001037 : DS.SetTypeSpecType(DeclSpec::TST_decltype_auto, StartLoc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001038 DiagID, Policy)) {
John McCall49bfce42009-08-03 20:12:06 +00001039 Diag(StartLoc, DiagID) << PrevSpec;
David Blaikie15a430a2011-12-04 05:04:18 +00001040 DS.SetTypeSpecError();
1041 }
1042 return EndLoc;
1043}
1044
Fangrui Song6907ce22018-07-30 19:24:48 +00001045void Parser::AnnotateExistingDecltypeSpecifier(const DeclSpec& DS,
David Blaikie15a430a2011-12-04 05:04:18 +00001046 SourceLocation StartLoc,
1047 SourceLocation EndLoc) {
1048 // make sure we have a token we can turn into an annotation token
1049 if (PP.isBacktrackEnabled())
1050 PP.RevertCachedTokens(1);
1051 else
Ilya Biryukov929af672019-05-17 09:32:05 +00001052 PP.EnterToken(Tok, /*IsReinject*/true);
David Blaikie15a430a2011-12-04 05:04:18 +00001053
1054 Tok.setKind(tok::annot_decltype);
Faisal Vali090da2d2018-01-01 18:23:28 +00001055 setExprAnnotation(Tok,
1056 DS.getTypeSpecType() == TST_decltype ? DS.getRepAsExpr() :
1057 DS.getTypeSpecType() == TST_decltype_auto ? ExprResult() :
1058 ExprError());
David Blaikie15a430a2011-12-04 05:04:18 +00001059 Tok.setAnnotationEndLoc(EndLoc);
1060 Tok.setLocation(StartLoc);
1061 PP.AnnotateCachedTokens(Tok);
Anders Carlsson74948d02009-06-24 17:47:40 +00001062}
1063
Alexis Hunt4a257072011-05-19 05:37:45 +00001064void Parser::ParseUnderlyingTypeSpecifier(DeclSpec &DS) {
1065 assert(Tok.is(tok::kw___underlying_type) &&
1066 "Not an underlying type specifier");
1067
1068 SourceLocation StartLoc = ConsumeToken();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001069 BalancedDelimiterTracker T(*this, tok::l_paren);
1070 if (T.expectAndConsume(diag::err_expected_lparen_after,
1071 "__underlying_type", tok::r_paren)) {
Alexis Hunt4a257072011-05-19 05:37:45 +00001072 return;
1073 }
1074
1075 TypeResult Result = ParseTypeName();
1076 if (Result.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00001077 SkipUntil(tok::r_paren, StopAtSemi);
Alexis Hunt4a257072011-05-19 05:37:45 +00001078 return;
1079 }
1080
1081 // Match the ')'
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001082 T.consumeClose();
1083 if (T.getCloseLocation().isInvalid())
Alexis Hunt4a257072011-05-19 05:37:45 +00001084 return;
1085
Craig Topper161e4db2014-05-21 06:02:52 +00001086 const char *PrevSpec = nullptr;
Alexis Hunt4a257072011-05-19 05:37:45 +00001087 unsigned DiagID;
Alexis Hunte852b102011-05-24 22:41:36 +00001088 if (DS.SetTypeSpecType(DeclSpec::TST_underlyingType, StartLoc, PrevSpec,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001089 DiagID, Result.get(),
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001090 Actions.getASTContext().getPrintingPolicy()))
Alexis Hunt4a257072011-05-19 05:37:45 +00001091 Diag(StartLoc, DiagID) << PrevSpec;
Enea Zaffanellaa90af722013-07-06 18:54:58 +00001092 DS.setTypeofParensRange(T.getRange());
Alexis Hunt4a257072011-05-19 05:37:45 +00001093}
1094
David Blaikie00ee7a082011-10-25 15:01:20 +00001095/// ParseBaseTypeSpecifier - Parse a C++ base-type-specifier which is either a
Fangrui Song6907ce22018-07-30 19:24:48 +00001096/// class name or decltype-specifier. Note that we only check that the result
1097/// names a type; semantic analysis will need to verify that the type names a
1098/// class. The result is either a type or null, depending on whether a type
David Blaikie00ee7a082011-10-25 15:01:20 +00001099/// name was found.
Douglas Gregor831c93f2008-11-05 20:51:48 +00001100///
Richard Smith4c96e992013-02-19 23:47:15 +00001101/// base-type-specifier: [C++11 class.derived]
David Blaikie00ee7a082011-10-25 15:01:20 +00001102/// class-or-decltype
Richard Smith4c96e992013-02-19 23:47:15 +00001103/// class-or-decltype: [C++11 class.derived]
David Blaikie00ee7a082011-10-25 15:01:20 +00001104/// nested-name-specifier[opt] class-name
1105/// decltype-specifier
Richard Smith4c96e992013-02-19 23:47:15 +00001106/// class-name: [C++ class.name]
Douglas Gregor831c93f2008-11-05 20:51:48 +00001107/// identifier
Douglas Gregord54dfb82009-02-25 23:52:28 +00001108/// simple-template-id
Mike Stump11289f42009-09-09 15:08:12 +00001109///
Richard Smith4c96e992013-02-19 23:47:15 +00001110/// In C++98, instead of base-type-specifier, we have:
1111///
1112/// ::[opt] nested-name-specifier[opt] class-name
Craig Topper9ad7e262014-10-31 06:57:07 +00001113TypeResult Parser::ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
1114 SourceLocation &EndLocation) {
David Blaikiedd58d4c2011-10-25 18:46:41 +00001115 // Ignore attempts to use typename
1116 if (Tok.is(tok::kw_typename)) {
1117 Diag(Tok, diag::err_expected_class_name_not_template)
1118 << FixItHint::CreateRemoval(Tok.getLocation());
1119 ConsumeToken();
1120 }
1121
David Blaikieafa155f2011-10-25 18:17:58 +00001122 // Parse optional nested-name-specifier
1123 CXXScopeSpec SS;
Haojian Wu0dd0b102020-03-19 09:12:29 +01001124 if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
1125 /*ObjectHadErrors=*/false,
1126 /*EnteringContext=*/false))
Richard Smithb23c5e82019-05-09 03:31:27 +00001127 return true;
David Blaikieafa155f2011-10-25 18:17:58 +00001128
1129 BaseLoc = Tok.getLocation();
1130
David Blaikie1cd50022011-10-25 17:10:12 +00001131 // Parse decltype-specifier
Fangrui Song6907ce22018-07-30 19:24:48 +00001132 // tok == kw_decltype is just error recovery, it can only happen when SS
David Blaikie15a430a2011-12-04 05:04:18 +00001133 // isn't empty
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001134 if (Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)) {
David Blaikieafa155f2011-10-25 18:17:58 +00001135 if (SS.isNotEmpty())
1136 Diag(SS.getBeginLoc(), diag::err_unexpected_scope_on_base_decltype)
1137 << FixItHint::CreateRemoval(SS.getRange());
David Blaikie1cd50022011-10-25 17:10:12 +00001138 // Fake up a Declarator to use with ActOnTypeName.
1139 DeclSpec DS(AttrFactory);
1140
David Blaikie7491e732011-12-08 04:53:15 +00001141 EndLocation = ParseDecltypeSpecifier(DS);
David Blaikie1cd50022011-10-25 17:10:12 +00001142
Faisal Vali421b2d12017-12-29 05:41:00 +00001143 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
David Blaikie1cd50022011-10-25 17:10:12 +00001144 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
1145 }
1146
Douglas Gregord54dfb82009-02-25 23:52:28 +00001147 // Check whether we have a template-id that names a type.
1148 if (Tok.is(tok::annot_template_id)) {
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00001149 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Richard Smithb3f6e3d2020-03-27 17:08:26 -07001150 if (TemplateId->mightBeType()) {
Richard Smitha42fd842020-01-17 15:42:11 -08001151 AnnotateTemplateIdTokenAsType(SS, /*IsClassName*/true);
Douglas Gregord54dfb82009-02-25 23:52:28 +00001152
1153 assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
Richard Smith33087322020-03-30 17:19:30 -07001154 TypeResult Type = getTypeAnnotation(Tok);
Douglas Gregord54dfb82009-02-25 23:52:28 +00001155 EndLocation = Tok.getAnnotationEndLoc();
Richard Smithaf3b3252017-05-18 19:21:48 +00001156 ConsumeAnnotationToken();
Richard Smith33087322020-03-30 17:19:30 -07001157 return Type;
Douglas Gregord54dfb82009-02-25 23:52:28 +00001158 }
1159
1160 // Fall through to produce an error below.
1161 }
1162
Douglas Gregor831c93f2008-11-05 20:51:48 +00001163 if (Tok.isNot(tok::identifier)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00001164 Diag(Tok, diag::err_expected_class_name);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001165 return true;
Douglas Gregor831c93f2008-11-05 20:51:48 +00001166 }
1167
Douglas Gregor18473f32010-01-12 21:28:44 +00001168 IdentifierInfo *Id = Tok.getIdentifierInfo();
1169 SourceLocation IdLoc = ConsumeToken();
1170
1171 if (Tok.is(tok::less)) {
1172 // It looks the user intended to write a template-id here, but the
1173 // template-name was wrong. Try to fix that.
Richard Smithb3f6e3d2020-03-27 17:08:26 -07001174 // FIXME: Invoke ParseOptionalCXXScopeSpecifier in a "'template' is neither
1175 // required nor permitted" mode, and do this there.
1176 TemplateNameKind TNK = TNK_Non_template;
Douglas Gregor18473f32010-01-12 21:28:44 +00001177 TemplateTy Template;
Douglas Gregor0be31a22010-07-02 17:43:08 +00001178 if (!Actions.DiagnoseUnknownTemplateName(*Id, IdLoc, getCurScope(),
Douglas Gregore7c20652011-03-02 00:47:37 +00001179 &SS, Template, TNK)) {
Douglas Gregor18473f32010-01-12 21:28:44 +00001180 Diag(IdLoc, diag::err_unknown_template_name)
1181 << Id;
1182 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001183
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001184 // Form the template name
Douglas Gregor18473f32010-01-12 21:28:44 +00001185 UnqualifiedId TemplateName;
1186 TemplateName.setIdentifier(Id, IdLoc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001187
Douglas Gregor18473f32010-01-12 21:28:44 +00001188 // Parse the full template-id, then turn it into a type.
Abramo Bagnara7945c982012-01-27 09:46:47 +00001189 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
Richard Smith62559bd2017-02-01 21:36:38 +00001190 TemplateName))
Douglas Gregor18473f32010-01-12 21:28:44 +00001191 return true;
Richard Smithb3f6e3d2020-03-27 17:08:26 -07001192 if (Tok.is(tok::annot_template_id) &&
1193 takeTemplateIdAnnotation(Tok)->mightBeType())
Richard Smitha42fd842020-01-17 15:42:11 -08001194 AnnotateTemplateIdTokenAsType(SS, /*IsClassName*/true);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001195
Douglas Gregor18473f32010-01-12 21:28:44 +00001196 // If we didn't end up with a typename token, there's nothing more we
1197 // can do.
1198 if (Tok.isNot(tok::annot_typename))
1199 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001200
Douglas Gregor18473f32010-01-12 21:28:44 +00001201 // Retrieve the type from the annotation token, consume that token, and
1202 // return.
1203 EndLocation = Tok.getAnnotationEndLoc();
Richard Smith33087322020-03-30 17:19:30 -07001204 TypeResult Type = getTypeAnnotation(Tok);
Richard Smithaf3b3252017-05-18 19:21:48 +00001205 ConsumeAnnotationToken();
Douglas Gregor18473f32010-01-12 21:28:44 +00001206 return Type;
1207 }
1208
Douglas Gregor831c93f2008-11-05 20:51:48 +00001209 // We have an identifier; check whether it is actually a type.
Craig Topper161e4db2014-05-21 06:02:52 +00001210 IdentifierInfo *CorrectedII = nullptr;
Richard Smith600b5262017-01-26 20:40:47 +00001211 ParsedType Type = Actions.getTypeName(
Rui Ueyama49a3ad22019-07-16 04:46:31 +00001212 *Id, IdLoc, getCurScope(), &SS, /*isClassName=*/true, false, nullptr,
Richard Smith600b5262017-01-26 20:40:47 +00001213 /*IsCtorOrDtorName=*/false,
Rui Ueyama49a3ad22019-07-16 04:46:31 +00001214 /*WantNontrivialTypeSourceInfo=*/true,
Richard Smith600b5262017-01-26 20:40:47 +00001215 /*IsClassTemplateDeductionContext*/ false, &CorrectedII);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001216 if (!Type) {
Douglas Gregorfe17d252010-02-16 19:09:40 +00001217 Diag(IdLoc, diag::err_expected_class_name);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001218 return true;
Douglas Gregor831c93f2008-11-05 20:51:48 +00001219 }
1220
1221 // Consume the identifier.
Douglas Gregor18473f32010-01-12 21:28:44 +00001222 EndLocation = IdLoc;
Nick Lewycky19b9f952010-07-26 16:56:01 +00001223
1224 // Fake up a Declarator to use with ActOnTypeName.
John McCall084e83d2011-03-24 11:26:52 +00001225 DeclSpec DS(AttrFactory);
Nick Lewycky19b9f952010-07-26 16:56:01 +00001226 DS.SetRangeStart(IdLoc);
1227 DS.SetRangeEnd(EndLocation);
Douglas Gregore7c20652011-03-02 00:47:37 +00001228 DS.getTypeSpecScope() = SS;
Nick Lewycky19b9f952010-07-26 16:56:01 +00001229
Craig Topper161e4db2014-05-21 06:02:52 +00001230 const char *PrevSpec = nullptr;
Nick Lewycky19b9f952010-07-26 16:56:01 +00001231 unsigned DiagID;
Faisal Vali090da2d2018-01-01 18:23:28 +00001232 DS.SetTypeSpecType(TST_typename, IdLoc, PrevSpec, DiagID, Type,
1233 Actions.getASTContext().getPrintingPolicy());
Nick Lewycky19b9f952010-07-26 16:56:01 +00001234
Faisal Vali421b2d12017-12-29 05:41:00 +00001235 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
Nick Lewycky19b9f952010-07-26 16:56:01 +00001236 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
Douglas Gregor831c93f2008-11-05 20:51:48 +00001237}
1238
John McCall8d32c052012-05-22 21:28:12 +00001239void Parser::ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001240 while (Tok.isOneOf(tok::kw___single_inheritance,
1241 tok::kw___multiple_inheritance,
1242 tok::kw___virtual_inheritance)) {
John McCall8d32c052012-05-22 21:28:12 +00001243 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
1244 SourceLocation AttrNameLoc = ConsumeToken();
Craig Topper161e4db2014-05-21 06:02:52 +00001245 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
Erich Keanee891aa92018-07-13 15:07:47 +00001246 ParsedAttr::AS_Keyword);
John McCall8d32c052012-05-22 21:28:12 +00001247 }
1248}
1249
Richard Smith369b9f92012-06-25 21:37:02 +00001250/// Determine whether the following tokens are valid after a type-specifier
1251/// which could be a standalone declaration. This will conservatively return
1252/// true if there's any doubt, and is appropriate for insert-';' fixits.
Richard Smith200f47c2012-07-02 19:14:01 +00001253bool Parser::isValidAfterTypeSpecifier(bool CouldBeBitfield) {
Richard Smith369b9f92012-06-25 21:37:02 +00001254 // This switch enumerates the valid "follow" set for type-specifiers.
1255 switch (Tok.getKind()) {
1256 default: break;
1257 case tok::semi: // struct foo {...} ;
1258 case tok::star: // struct foo {...} * P;
1259 case tok::amp: // struct foo {...} & R = ...
Richard Smith1ac67d12013-01-19 03:48:05 +00001260 case tok::ampamp: // struct foo {...} && R = ...
Richard Smith369b9f92012-06-25 21:37:02 +00001261 case tok::identifier: // struct foo {...} V ;
1262 case tok::r_paren: //(struct foo {...} ) {4}
Richard Smith1600e242019-04-16 00:47:45 +00001263 case tok::coloncolon: // struct foo {...} :: a::b;
Richard Smith369b9f92012-06-25 21:37:02 +00001264 case tok::annot_cxxscope: // struct foo {...} a:: b;
1265 case tok::annot_typename: // struct foo {...} a ::b;
1266 case tok::annot_template_id: // struct foo {...} a<int> ::b;
Richard Smith1600e242019-04-16 00:47:45 +00001267 case tok::kw_decltype: // struct foo {...} decltype (a)::b;
Richard Smith369b9f92012-06-25 21:37:02 +00001268 case tok::l_paren: // struct foo {...} ( x);
1269 case tok::comma: // __builtin_offsetof(struct foo{...} ,
Richard Smith1ac67d12013-01-19 03:48:05 +00001270 case tok::kw_operator: // struct foo operator ++() {...}
Alp Tokerd3f79c52013-11-24 20:24:54 +00001271 case tok::kw___declspec: // struct foo {...} __declspec(...)
Richard Smith843f18f2014-08-13 02:13:15 +00001272 case tok::l_square: // void f(struct f [ 3])
1273 case tok::ellipsis: // void f(struct f ... [Ns])
Abramo Bagnara152eb392014-08-16 08:29:27 +00001274 // FIXME: we should emit semantic diagnostic when declaration
1275 // attribute is in type attribute position.
1276 case tok::kw___attribute: // struct foo __attribute__((used)) x;
David Majnemer15b311c2016-06-14 03:20:28 +00001277 case tok::annot_pragma_pack: // struct foo {...} _Pragma(pack(pop));
1278 // struct foo {...} _Pragma(section(...));
1279 case tok::annot_pragma_ms_pragma:
1280 // struct foo {...} _Pragma(vtordisp(pop));
1281 case tok::annot_pragma_ms_vtordisp:
1282 // struct foo {...} _Pragma(pointers_to_members(...));
1283 case tok::annot_pragma_ms_pointers_to_members:
Richard Smith369b9f92012-06-25 21:37:02 +00001284 return true;
Richard Smith200f47c2012-07-02 19:14:01 +00001285 case tok::colon:
1286 return CouldBeBitfield; // enum E { ... } : 2;
Reid Klecknercfa91552016-03-21 16:08:49 +00001287 // Microsoft compatibility
1288 case tok::kw___cdecl: // struct foo {...} __cdecl x;
1289 case tok::kw___fastcall: // struct foo {...} __fastcall x;
1290 case tok::kw___stdcall: // struct foo {...} __stdcall x;
1291 case tok::kw___thiscall: // struct foo {...} __thiscall x;
1292 case tok::kw___vectorcall: // struct foo {...} __vectorcall x;
1293 // We will diagnose these calling-convention specifiers on non-function
1294 // declarations later, so claim they are valid after a type specifier.
1295 return getLangOpts().MicrosoftExt;
Richard Smith369b9f92012-06-25 21:37:02 +00001296 // Type qualifiers
1297 case tok::kw_const: // struct foo {...} const x;
1298 case tok::kw_volatile: // struct foo {...} volatile x;
1299 case tok::kw_restrict: // struct foo {...} restrict x;
Richard Smith843f18f2014-08-13 02:13:15 +00001300 case tok::kw__Atomic: // struct foo {...} _Atomic x;
Nico Rieck3e1ee832014-12-04 23:30:25 +00001301 case tok::kw___unaligned: // struct foo {...} __unaligned *x;
Richard Smith1ac67d12013-01-19 03:48:05 +00001302 // Function specifiers
1303 // Note, no 'explicit'. An explicit function must be either a conversion
1304 // operator or a constructor. Either way, it can't have a return type.
1305 case tok::kw_inline: // struct foo inline f();
1306 case tok::kw_virtual: // struct foo virtual f();
1307 case tok::kw_friend: // struct foo friend f();
Richard Smith369b9f92012-06-25 21:37:02 +00001308 // Storage-class specifiers
1309 case tok::kw_static: // struct foo {...} static x;
1310 case tok::kw_extern: // struct foo {...} extern x;
1311 case tok::kw_typedef: // struct foo {...} typedef x;
1312 case tok::kw_register: // struct foo {...} register x;
1313 case tok::kw_auto: // struct foo {...} auto x;
1314 case tok::kw_mutable: // struct foo {...} mutable x;
Richard Smith1ac67d12013-01-19 03:48:05 +00001315 case tok::kw_thread_local: // struct foo {...} thread_local x;
Richard Smith369b9f92012-06-25 21:37:02 +00001316 case tok::kw_constexpr: // struct foo {...} constexpr x;
Richard Smitha6e8b682019-09-04 20:30:37 +00001317 case tok::kw_consteval: // struct foo {...} consteval x;
1318 case tok::kw_constinit: // struct foo {...} constinit x;
Richard Smith369b9f92012-06-25 21:37:02 +00001319 // As shown above, type qualifiers and storage class specifiers absolutely
1320 // can occur after class specifiers according to the grammar. However,
1321 // almost no one actually writes code like this. If we see one of these,
1322 // it is much more likely that someone missed a semi colon and the
1323 // type/storage class specifier we're seeing is part of the *next*
1324 // intended declaration, as in:
1325 //
1326 // struct foo { ... }
1327 // typedef int X;
1328 //
1329 // We'd really like to emit a missing semicolon error instead of emitting
1330 // an error on the 'int' saying that you can't have two type specifiers in
1331 // the same declaration of X. Because of this, we look ahead past this
1332 // token to see if it's a type specifier. If so, we know the code is
1333 // otherwise invalid, so we can produce the expected semi error.
1334 if (!isKnownToBeTypeSpecifier(NextToken()))
1335 return true;
1336 break;
1337 case tok::r_brace: // struct bar { struct foo {...} }
1338 // Missing ';' at end of struct is accepted as an extension in C mode.
1339 if (!getLangOpts().CPlusPlus)
1340 return true;
1341 break;
Richard Smith52c5b872013-01-29 04:13:32 +00001342 case tok::greater:
1343 // template<class T = class X>
1344 return getLangOpts().CPlusPlus;
Richard Smith369b9f92012-06-25 21:37:02 +00001345 }
1346 return false;
1347}
1348
Douglas Gregor556877c2008-04-13 21:30:24 +00001349/// ParseClassSpecifier - Parse a C++ class-specifier [C++ class] or
1350/// elaborated-type-specifier [C++ dcl.type.elab]; we can't tell which
1351/// until we reach the start of a definition or see a token that
Richard Smithc5b05522012-03-12 07:56:15 +00001352/// cannot start a definition.
Douglas Gregor556877c2008-04-13 21:30:24 +00001353///
1354/// class-specifier: [C++ class]
1355/// class-head '{' member-specification[opt] '}'
1356/// class-head '{' member-specification[opt] '}' attributes[opt]
1357/// class-head:
1358/// class-key identifier[opt] base-clause[opt]
1359/// class-key nested-name-specifier identifier base-clause[opt]
1360/// class-key nested-name-specifier[opt] simple-template-id
1361/// base-clause[opt]
1362/// [GNU] class-key attributes[opt] identifier[opt] base-clause[opt]
Mike Stump11289f42009-09-09 15:08:12 +00001363/// [GNU] class-key attributes[opt] nested-name-specifier
Douglas Gregor556877c2008-04-13 21:30:24 +00001364/// identifier base-clause[opt]
Mike Stump11289f42009-09-09 15:08:12 +00001365/// [GNU] class-key attributes[opt] nested-name-specifier[opt]
Douglas Gregor556877c2008-04-13 21:30:24 +00001366/// simple-template-id base-clause[opt]
1367/// class-key:
1368/// 'class'
1369/// 'struct'
1370/// 'union'
1371///
1372/// elaborated-type-specifier: [C++ dcl.type.elab]
Mike Stump11289f42009-09-09 15:08:12 +00001373/// class-key ::[opt] nested-name-specifier[opt] identifier
1374/// class-key ::[opt] nested-name-specifier[opt] 'template'[opt]
1375/// simple-template-id
Douglas Gregor556877c2008-04-13 21:30:24 +00001376///
1377/// Note that the C++ class-specifier and elaborated-type-specifier,
1378/// together, subsume the C99 struct-or-union-specifier:
1379///
1380/// struct-or-union-specifier: [C99 6.7.2.1]
1381/// struct-or-union identifier[opt] '{' struct-contents '}'
1382/// struct-or-union identifier
1383/// [GNU] struct-or-union attributes[opt] identifier[opt] '{' struct-contents
1384/// '}' attributes[opt]
1385/// [GNU] struct-or-union attributes[opt] identifier
1386/// struct-or-union:
1387/// 'struct'
1388/// 'union'
Chris Lattnerffaa0e62009-04-12 21:49:30 +00001389void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind,
1390 SourceLocation StartLoc, DeclSpec &DS,
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001391 const ParsedTemplateInfo &TemplateInfo,
Fangrui Song6907ce22018-07-30 19:24:48 +00001392 AccessSpecifier AS,
1393 bool EnteringContext, DeclSpecContext DSC,
Bill Wendling44426052012-12-20 19:22:21 +00001394 ParsedAttributesWithRange &Attributes) {
Joao Matose9a3ed42012-08-31 22:18:20 +00001395 DeclSpec::TST TagType;
1396 if (TagTokKind == tok::kw_struct)
1397 TagType = DeclSpec::TST_struct;
1398 else if (TagTokKind == tok::kw___interface)
1399 TagType = DeclSpec::TST_interface;
1400 else if (TagTokKind == tok::kw_class)
1401 TagType = DeclSpec::TST_class;
1402 else {
Chris Lattnerffaa0e62009-04-12 21:49:30 +00001403 assert(TagTokKind == tok::kw_union && "Not a class specifier");
1404 TagType = DeclSpec::TST_union;
1405 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001406
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00001407 if (Tok.is(tok::code_completion)) {
1408 // Code completion for a struct, class, or union name.
Douglas Gregor0be31a22010-07-02 17:43:08 +00001409 Actions.CodeCompleteTag(getCurScope(), TagType);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001410 return cutOffParsing();
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00001411 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001412
Chandler Carruth2d69ec72010-06-28 08:39:25 +00001413 // C++03 [temp.explicit] 14.7.2/8:
1414 // The usual access checking rules do not apply to names used to specify
1415 // explicit instantiations.
1416 //
1417 // As an extension we do not perform access checking on the names used to
1418 // specify explicit specializations either. This is important to allow
1419 // specializing traits classes for private types.
John McCall6347b682012-05-07 06:16:58 +00001420 //
1421 // Note that we don't suppress if this turns out to be an elaborated
1422 // type specifier.
1423 bool shouldDelayDiagsInTag =
1424 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
1425 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
1426 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
Chandler Carruth2d69ec72010-06-28 08:39:25 +00001427
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001428 ParsedAttributesWithRange attrs(AttrFactory);
Douglas Gregor556877c2008-04-13 21:30:24 +00001429 // If attributes exist after tag, parse them.
Richard Smith37a45dd2013-10-24 01:21:09 +00001430 MaybeParseGNUAttributes(attrs);
Aaron Ballman068aa512015-05-20 20:58:33 +00001431 MaybeParseMicrosoftDeclSpecs(attrs);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001432
John McCall8d32c052012-05-22 21:28:12 +00001433 // Parse inheritance specifiers.
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001434 if (Tok.isOneOf(tok::kw___single_inheritance,
1435 tok::kw___multiple_inheritance,
1436 tok::kw___virtual_inheritance))
Richard Smith37a45dd2013-10-24 01:21:09 +00001437 ParseMicrosoftInheritanceClassAttributes(attrs);
John McCall8d32c052012-05-22 21:28:12 +00001438
Alexis Hunt96d5c762009-11-21 08:43:09 +00001439 // If C++0x attributes exist here, parse them.
1440 // FIXME: Are we consistent with the ordering of parsing of different
1441 // styles of attributes?
Richard Smith89645bc2013-01-02 12:01:23 +00001442 MaybeParseCXX11Attributes(attrs);
Mike Stump11289f42009-09-09 15:08:12 +00001443
Michael Han309af292013-01-07 16:57:11 +00001444 // Source location used by FIXIT to insert misplaced
1445 // C++11 attributes
1446 SourceLocation AttrFixitLoc = Tok.getLocation();
1447
Nico Weber7c3c5be2014-09-23 04:09:56 +00001448 if (TagType == DeclSpec::TST_struct &&
David Majnemer86330af2014-12-29 02:14:26 +00001449 Tok.isNot(tok::identifier) &&
1450 !Tok.isAnnotation() &&
Nico Weber7c3c5be2014-09-23 04:09:56 +00001451 Tok.getIdentifierInfo() &&
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001452 Tok.isOneOf(tok::kw___is_abstract,
Eric Fiselier07360662017-04-12 22:12:15 +00001453 tok::kw___is_aggregate,
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001454 tok::kw___is_arithmetic,
1455 tok::kw___is_array,
David Majnemerb3d96882016-05-23 17:21:55 +00001456 tok::kw___is_assignable,
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001457 tok::kw___is_base_of,
1458 tok::kw___is_class,
1459 tok::kw___is_complete_type,
1460 tok::kw___is_compound,
1461 tok::kw___is_const,
1462 tok::kw___is_constructible,
1463 tok::kw___is_convertible,
1464 tok::kw___is_convertible_to,
1465 tok::kw___is_destructible,
1466 tok::kw___is_empty,
1467 tok::kw___is_enum,
1468 tok::kw___is_floating_point,
1469 tok::kw___is_final,
1470 tok::kw___is_function,
1471 tok::kw___is_fundamental,
1472 tok::kw___is_integral,
1473 tok::kw___is_interface_class,
1474 tok::kw___is_literal,
1475 tok::kw___is_lvalue_expr,
1476 tok::kw___is_lvalue_reference,
1477 tok::kw___is_member_function_pointer,
1478 tok::kw___is_member_object_pointer,
1479 tok::kw___is_member_pointer,
1480 tok::kw___is_nothrow_assignable,
1481 tok::kw___is_nothrow_constructible,
1482 tok::kw___is_nothrow_destructible,
1483 tok::kw___is_object,
1484 tok::kw___is_pod,
1485 tok::kw___is_pointer,
1486 tok::kw___is_polymorphic,
1487 tok::kw___is_reference,
1488 tok::kw___is_rvalue_expr,
1489 tok::kw___is_rvalue_reference,
1490 tok::kw___is_same,
1491 tok::kw___is_scalar,
1492 tok::kw___is_sealed,
1493 tok::kw___is_signed,
1494 tok::kw___is_standard_layout,
1495 tok::kw___is_trivial,
1496 tok::kw___is_trivially_assignable,
1497 tok::kw___is_trivially_constructible,
1498 tok::kw___is_trivially_copyable,
1499 tok::kw___is_union,
1500 tok::kw___is_unsigned,
1501 tok::kw___is_void,
1502 tok::kw___is_volatile))
Nico Weber7c3c5be2014-09-23 04:09:56 +00001503 // GNU libstdc++ 4.2 and libc++ use certain intrinsic names as the
1504 // name of struct templates, but some are keywords in GCC >= 4.3
1505 // and Clang. Therefore, when we see the token sequence "struct
1506 // X", make X into a normal identifier rather than a keyword, to
1507 // allow libstdc++ 4.2 and libc++ to work properly.
1508 TryKeywordIdentFallback(true);
Mike Stump11289f42009-09-09 15:08:12 +00001509
David Majnemer51fd8a02015-07-22 23:46:18 +00001510 struct PreserveAtomicIdentifierInfoRAII {
1511 PreserveAtomicIdentifierInfoRAII(Token &Tok, bool Enabled)
1512 : AtomicII(nullptr) {
1513 if (!Enabled)
1514 return;
1515 assert(Tok.is(tok::kw__Atomic));
1516 AtomicII = Tok.getIdentifierInfo();
1517 AtomicII->revertTokenIDToIdentifier();
1518 Tok.setKind(tok::identifier);
1519 }
1520 ~PreserveAtomicIdentifierInfoRAII() {
1521 if (!AtomicII)
1522 return;
1523 AtomicII->revertIdentifierToTokenID(tok::kw__Atomic);
1524 }
1525 IdentifierInfo *AtomicII;
1526 };
1527
1528 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
1529 // implementation for VS2013 uses _Atomic as an identifier for one of the
1530 // classes in <atomic>. When we are parsing 'struct _Atomic', don't consider
1531 // '_Atomic' to be a keyword. We are careful to undo this so that clang can
1532 // use '_Atomic' in its own header files.
1533 bool ShouldChangeAtomicToIdentifier = getLangOpts().MSVCCompat &&
1534 Tok.is(tok::kw__Atomic) &&
1535 TagType == DeclSpec::TST_struct;
1536 PreserveAtomicIdentifierInfoRAII AtomicTokenGuard(
1537 Tok, ShouldChangeAtomicToIdentifier);
1538
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001539 // Parse the (optional) nested-name-specifier.
John McCall9dab4e62009-12-12 11:40:51 +00001540 CXXScopeSpec &SS = DS.getTypeSpecScope();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001541 if (getLangOpts().CPlusPlus) {
Serge Pavlov458ea762014-07-16 05:16:52 +00001542 // "FOO : BAR" is not a potential typo for "FOO::BAR". In this context it
1543 // is a base-specifier-list.
Chris Lattnerd5c1c9d2009-12-10 00:32:41 +00001544 ColonProtectionRAIIObject X(*this);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001545
Nico Webercfaa4cd2015-02-15 07:26:13 +00001546 CXXScopeSpec Spec;
1547 bool HasValidSpec = true;
Haojian Wu0dd0b102020-03-19 09:12:29 +01001548 if (ParseOptionalCXXScopeSpecifier(Spec, /*ObjectType=*/nullptr,
1549 /*ObjectHadErrors=*/false,
1550 EnteringContext)) {
John McCall413021a2010-07-30 06:26:29 +00001551 DS.SetTypeSpecError();
Nico Webercfaa4cd2015-02-15 07:26:13 +00001552 HasValidSpec = false;
1553 }
1554 if (Spec.isSet())
1555 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::annot_template_id)) {
Alp Tokerec543272013-12-24 09:48:30 +00001556 Diag(Tok, diag::err_expected) << tok::identifier;
Nico Webercfaa4cd2015-02-15 07:26:13 +00001557 HasValidSpec = false;
1558 }
1559 if (HasValidSpec)
1560 SS = Spec;
Chris Lattnerd5c1c9d2009-12-10 00:32:41 +00001561 }
Douglas Gregor67a65642009-02-17 23:15:12 +00001562
Douglas Gregor916462b2009-10-30 21:46:58 +00001563 TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
1564
Richard Smithb23c5e82019-05-09 03:31:27 +00001565 auto RecoverFromUndeclaredTemplateName = [&](IdentifierInfo *Name,
1566 SourceLocation NameLoc,
1567 SourceRange TemplateArgRange,
1568 bool KnownUndeclared) {
1569 Diag(NameLoc, diag::err_explicit_spec_non_template)
1570 << (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
1571 << TagTokKind << Name << TemplateArgRange << KnownUndeclared;
1572
1573 // Strip off the last template parameter list if it was empty, since
1574 // we've removed its template argument list.
1575 if (TemplateParams && TemplateInfo.LastParameterListWasEmpty) {
1576 if (TemplateParams->size() > 1) {
1577 TemplateParams->pop_back();
1578 } else {
1579 TemplateParams = nullptr;
1580 const_cast<ParsedTemplateInfo &>(TemplateInfo).Kind =
1581 ParsedTemplateInfo::NonTemplate;
1582 }
1583 } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1584 // Pretend this is just a forward declaration.
1585 TemplateParams = nullptr;
1586 const_cast<ParsedTemplateInfo &>(TemplateInfo).Kind =
1587 ParsedTemplateInfo::NonTemplate;
1588 const_cast<ParsedTemplateInfo &>(TemplateInfo).TemplateLoc =
1589 SourceLocation();
1590 const_cast<ParsedTemplateInfo &>(TemplateInfo).ExternLoc =
1591 SourceLocation();
1592 }
1593 };
1594
Douglas Gregor67a65642009-02-17 23:15:12 +00001595 // Parse the (optional) class name or simple-template-id.
Craig Topper161e4db2014-05-21 06:02:52 +00001596 IdentifierInfo *Name = nullptr;
Douglas Gregor556877c2008-04-13 21:30:24 +00001597 SourceLocation NameLoc;
Craig Topper161e4db2014-05-21 06:02:52 +00001598 TemplateIdAnnotation *TemplateId = nullptr;
Douglas Gregor556877c2008-04-13 21:30:24 +00001599 if (Tok.is(tok::identifier)) {
1600 Name = Tok.getIdentifierInfo();
1601 NameLoc = ConsumeToken();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001602
David Blaikiebbafb8a2012-03-11 07:00:24 +00001603 if (Tok.is(tok::less) && getLangOpts().CPlusPlus) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001604 // The name was supposed to refer to a template, but didn't.
Douglas Gregor916462b2009-10-30 21:46:58 +00001605 // Eat the template argument list and try to continue parsing this as
1606 // a class (or template thereof).
1607 TemplateArgList TemplateArgs;
Douglas Gregor916462b2009-10-30 21:46:58 +00001608 SourceLocation LAngleLoc, RAngleLoc;
Richard Smith9a420f92017-05-10 21:47:30 +00001609 if (ParseTemplateIdAfterTemplateName(true, LAngleLoc, TemplateArgs,
1610 RAngleLoc)) {
Douglas Gregor916462b2009-10-30 21:46:58 +00001611 // We couldn't parse the template argument list at all, so don't
1612 // try to give any location information for the list.
1613 LAngleLoc = RAngleLoc = SourceLocation();
1614 }
Richard Smithb23c5e82019-05-09 03:31:27 +00001615 RecoverFromUndeclaredTemplateName(
1616 Name, NameLoc, SourceRange(LAngleLoc, RAngleLoc), false);
Douglas Gregor916462b2009-10-30 21:46:58 +00001617 }
Douglas Gregor7f741122009-02-25 19:37:18 +00001618 } else if (Tok.is(tok::annot_template_id)) {
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00001619 TemplateId = takeTemplateIdAnnotation(Tok);
Richard Smithaf3b3252017-05-18 19:21:48 +00001620 NameLoc = ConsumeAnnotationToken();
Douglas Gregor67a65642009-02-17 23:15:12 +00001621
Richard Smithb23c5e82019-05-09 03:31:27 +00001622 if (TemplateId->Kind == TNK_Undeclared_template) {
Richard Smithb3f6e3d2020-03-27 17:08:26 -07001623 // Try to resolve the template name to a type template. May update Kind.
1624 Actions.ActOnUndeclaredTypeTemplateName(
1625 getCurScope(), TemplateId->Template, TemplateId->Kind, NameLoc, Name);
Richard Smithb23c5e82019-05-09 03:31:27 +00001626 if (TemplateId->Kind == TNK_Undeclared_template) {
1627 RecoverFromUndeclaredTemplateName(
1628 Name, NameLoc,
1629 SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc), true);
1630 TemplateId = nullptr;
1631 }
1632 }
1633
Richard Smithb3f6e3d2020-03-27 17:08:26 -07001634 if (TemplateId && !TemplateId->mightBeType()) {
Douglas Gregor7f741122009-02-25 19:37:18 +00001635 // The template-name in the simple-template-id refers to
Richard Smithb3f6e3d2020-03-27 17:08:26 -07001636 // something other than a type template. Give an appropriate
Douglas Gregor7f741122009-02-25 19:37:18 +00001637 // error message and skip to the ';'.
1638 SourceRange Range(NameLoc);
1639 if (SS.isNotEmpty())
1640 Range.setBegin(SS.getBeginLoc());
Douglas Gregor67a65642009-02-17 23:15:12 +00001641
Richard Smith72bfbd82013-12-04 00:28:23 +00001642 // FIXME: Name may be null here.
Douglas Gregor7f741122009-02-25 19:37:18 +00001643 Diag(TemplateId->LAngleLoc, diag::err_template_spec_syntax_non_template)
Richard Smithb23c5e82019-05-09 03:31:27 +00001644 << TemplateId->Name << static_cast<int>(TemplateId->Kind) << Range;
Mike Stump11289f42009-09-09 15:08:12 +00001645
Douglas Gregor7f741122009-02-25 19:37:18 +00001646 DS.SetTypeSpecError();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001647 SkipUntil(tok::semi, StopBeforeMatch);
Douglas Gregor7f741122009-02-25 19:37:18 +00001648 return;
Douglas Gregor67a65642009-02-17 23:15:12 +00001649 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001650 }
1651
Richard Smithbfdb1082012-03-12 08:56:40 +00001652 // There are four options here.
1653 // - If we are in a trailing return type, this is always just a reference,
1654 // and we must not try to parse a definition. For instance,
1655 // [] () -> struct S { };
1656 // does not define a type.
1657 // - If we have 'struct foo {...', 'struct foo :...',
1658 // 'struct foo final :' or 'struct foo final {', then this is a definition.
1659 // - If we have 'struct foo;', then this is either a forward declaration
1660 // or a friend declaration, which have to be treated differently.
1661 // - Otherwise we have something like 'struct foo xyz', a reference.
Michael Han9407e502012-11-26 22:54:45 +00001662 //
1663 // We also detect these erroneous cases to provide better diagnostic for
1664 // C++11 attributes parsing.
1665 // - attributes follow class name:
1666 // struct foo [[]] {};
1667 // - attributes appear before or after 'final':
1668 // struct foo [[]] final [[]] {};
1669 //
Richard Smithc5b05522012-03-12 07:56:15 +00001670 // However, in type-specifier-seq's, things look like declarations but are
1671 // just references, e.g.
1672 // new struct s;
Sebastian Redl2b372722010-02-03 21:21:43 +00001673 // or
Richard Smithc5b05522012-03-12 07:56:15 +00001674 // &T::operator struct s;
Faisal Vali7db85c52017-12-31 00:06:40 +00001675 // For these, DSC is DeclSpecContext::DSC_type_specifier or
1676 // DeclSpecContext::DSC_alias_declaration.
Michael Han9407e502012-11-26 22:54:45 +00001677
1678 // If there are attributes after class name, parse them.
Richard Smith89645bc2013-01-02 12:01:23 +00001679 MaybeParseCXX11Attributes(Attributes);
Michael Han9407e502012-11-26 22:54:45 +00001680
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001681 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
John McCallfaf5fb42010-08-26 23:41:50 +00001682 Sema::TagUseKind TUK;
Faisal Vali7db85c52017-12-31 00:06:40 +00001683 if (DSC == DeclSpecContext::DSC_trailing)
Richard Smithbfdb1082012-03-12 08:56:40 +00001684 TUK = Sema::TUK_Reference;
1685 else if (Tok.is(tok::l_brace) ||
1686 (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
Richard Smith89645bc2013-01-02 12:01:23 +00001687 (isCXX11FinalKeyword() &&
David Blaikie9933a5a2012-03-12 15:39:49 +00001688 (NextToken().is(tok::l_brace) || NextToken().is(tok::colon)))) {
Douglas Gregor3dad8422009-09-26 06:47:28 +00001689 if (DS.isFriendSpecified()) {
1690 // C++ [class.friend]p2:
1691 // A class shall not be defined in a friend declaration.
Richard Smith0f8ee222012-01-10 01:33:14 +00001692 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
Douglas Gregor3dad8422009-09-26 06:47:28 +00001693 << SourceRange(DS.getFriendSpecLoc());
1694
1695 // Skip everything up to the semicolon, so that this looks like a proper
1696 // friend class (or template thereof) declaration.
Alexey Bataevee6507d2013-11-18 08:17:37 +00001697 SkipUntil(tok::semi, StopBeforeMatch);
John McCallfaf5fb42010-08-26 23:41:50 +00001698 TUK = Sema::TUK_Friend;
Douglas Gregor3dad8422009-09-26 06:47:28 +00001699 } else {
1700 // Okay, this is a class definition.
John McCallfaf5fb42010-08-26 23:41:50 +00001701 TUK = Sema::TUK_Definition;
Douglas Gregor3dad8422009-09-26 06:47:28 +00001702 }
Richard Smith434516c2013-02-22 06:46:23 +00001703 } else if (isCXX11FinalKeyword() && (NextToken().is(tok::l_square) ||
1704 NextToken().is(tok::kw_alignas))) {
Michael Han9407e502012-11-26 22:54:45 +00001705 // We can't tell if this is a definition or reference
1706 // until we skipped the 'final' and C++11 attribute specifiers.
1707 TentativeParsingAction PA(*this);
1708
1709 // Skip the 'final' keyword.
1710 ConsumeToken();
1711
1712 // Skip C++11 attribute specifiers.
1713 while (true) {
1714 if (Tok.is(tok::l_square) && NextToken().is(tok::l_square)) {
1715 ConsumeBracket();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001716 if (!SkipUntil(tok::r_square, StopAtSemi))
Michael Han9407e502012-11-26 22:54:45 +00001717 break;
Richard Smith434516c2013-02-22 06:46:23 +00001718 } else if (Tok.is(tok::kw_alignas) && NextToken().is(tok::l_paren)) {
Michael Han9407e502012-11-26 22:54:45 +00001719 ConsumeToken();
1720 ConsumeParen();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001721 if (!SkipUntil(tok::r_paren, StopAtSemi))
Michael Han9407e502012-11-26 22:54:45 +00001722 break;
1723 } else {
1724 break;
1725 }
1726 }
1727
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001728 if (Tok.isOneOf(tok::l_brace, tok::colon))
Michael Han9407e502012-11-26 22:54:45 +00001729 TUK = Sema::TUK_Definition;
1730 else
1731 TUK = Sema::TUK_Reference;
1732
1733 PA.Revert();
Richard Smith649c7b062014-01-08 00:56:48 +00001734 } else if (!isTypeSpecifier(DSC) &&
Richard Smith369b9f92012-06-25 21:37:02 +00001735 (Tok.is(tok::semi) ||
Richard Smith200f47c2012-07-02 19:14:01 +00001736 (Tok.isAtStartOfLine() && !isValidAfterTypeSpecifier(false)))) {
John McCallfaf5fb42010-08-26 23:41:50 +00001737 TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
Joao Matose9a3ed42012-08-31 22:18:20 +00001738 if (Tok.isNot(tok::semi)) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001739 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
Joao Matose9a3ed42012-08-31 22:18:20 +00001740 // A semicolon was missing after this declaration. Diagnose and recover.
Alp Toker383d2c42014-01-01 03:08:43 +00001741 ExpectAndConsume(tok::semi, diag::err_expected_after,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001742 DeclSpec::getSpecifierName(TagType, PPol));
Ilya Biryukov929af672019-05-17 09:32:05 +00001743 PP.EnterToken(Tok, /*IsReinject*/true);
Joao Matose9a3ed42012-08-31 22:18:20 +00001744 Tok.setKind(tok::semi);
1745 }
Richard Smith369b9f92012-06-25 21:37:02 +00001746 } else
John McCallfaf5fb42010-08-26 23:41:50 +00001747 TUK = Sema::TUK_Reference;
Douglas Gregor556877c2008-04-13 21:30:24 +00001748
Michael Han9407e502012-11-26 22:54:45 +00001749 // Forbid misplaced attributes. In cases of a reference, we pass attributes
1750 // to caller to handle.
Michael Han309af292013-01-07 16:57:11 +00001751 if (TUK != Sema::TUK_Reference) {
1752 // If this is not a reference, then the only possible
1753 // valid place for C++11 attributes to appear here
1754 // is between class-key and class-name. If there are
1755 // any attributes after class-name, we try a fixit to move
1756 // them to the right place.
1757 SourceRange AttrRange = Attributes.Range;
1758 if (AttrRange.isValid()) {
1759 Diag(AttrRange.getBegin(), diag::err_attributes_not_allowed)
1760 << AttrRange
1761 << FixItHint::CreateInsertionFromRange(AttrFixitLoc,
1762 CharSourceRange(AttrRange, true))
1763 << FixItHint::CreateRemoval(AttrRange);
1764
1765 // Recover by adding misplaced attributes to the attribute list
1766 // of the class so they can be applied on the class later.
1767 attrs.takeAllFrom(Attributes);
1768 }
1769 }
Michael Han9407e502012-11-26 22:54:45 +00001770
John McCall6347b682012-05-07 06:16:58 +00001771 // If this is an elaborated type specifier, and we delayed
1772 // diagnostics before, just merge them into the current pool.
1773 if (shouldDelayDiagsInTag) {
1774 diagsFromTag.done();
1775 if (TUK == Sema::TUK_Reference)
1776 diagsFromTag.redelay();
1777 }
1778
John McCall413021a2010-07-30 06:26:29 +00001779 if (!Name && !TemplateId && (DS.getTypeSpecType() == DeclSpec::TST_error ||
John McCallfaf5fb42010-08-26 23:41:50 +00001780 TUK != Sema::TUK_Definition)) {
John McCall413021a2010-07-30 06:26:29 +00001781 if (DS.getTypeSpecType() != DeclSpec::TST_error) {
1782 // We have a declaration or reference to an anonymous class.
1783 Diag(StartLoc, diag::err_anon_type_definition)
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001784 << DeclSpec::getSpecifierName(TagType, Policy);
John McCall413021a2010-07-30 06:26:29 +00001785 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001786
David Majnemer3252fd02013-12-05 01:36:53 +00001787 // If we are parsing a definition and stop at a base-clause, continue on
1788 // until the semicolon. Continuing from the comma will just trick us into
1789 // thinking we are seeing a variable declaration.
1790 if (TUK == Sema::TUK_Definition && Tok.is(tok::colon))
1791 SkipUntil(tok::semi, StopBeforeMatch);
1792 else
1793 SkipUntil(tok::comma, StopAtSemi);
Douglas Gregor556877c2008-04-13 21:30:24 +00001794 return;
1795 }
1796
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001797 // Create the tag portion of the class or class template.
John McCall48871652010-08-21 09:40:31 +00001798 DeclResult TagOrTempResult = true; // invalid
1799 TypeResult TypeResult = true; // invalid
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001800
Douglas Gregord6ab8742009-05-28 23:31:59 +00001801 bool Owned = false;
Richard Smithd9ba2242015-05-07 03:54:19 +00001802 Sema::SkipBodyInfo SkipBody;
John McCall06f6fe8d2009-09-04 01:14:41 +00001803 if (TemplateId) {
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001804 // Explicit specialization, class template partial specialization,
1805 // or explicit instantiation.
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00001806 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregor7f741122009-02-25 19:37:18 +00001807 TemplateId->NumArgs);
Richard Smithb3f6e3d2020-03-27 17:08:26 -07001808 if (TemplateId->isInvalid()) {
1809 // Can't build the declaration.
1810 } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
John McCallfaf5fb42010-08-26 23:41:50 +00001811 TUK == Sema::TUK_Declaration) {
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001812 // This is an explicit instantiation of a class template.
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001813 ProhibitAttributes(attrs);
1814
Erich Keanec480f302018-07-12 21:09:05 +00001815 TagOrTempResult = Actions.ActOnExplicitInstantiation(
1816 getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc,
1817 TagType, StartLoc, SS, TemplateId->Template,
1818 TemplateId->TemplateNameLoc, TemplateId->LAngleLoc, TemplateArgsPtr,
1819 TemplateId->RAngleLoc, attrs);
John McCallb7c5c272010-04-14 00:24:33 +00001820
Erich Keanec480f302018-07-12 21:09:05 +00001821 // Friend template-ids are treated as references unless
1822 // they have template headers, in which case they're ill-formed
1823 // (FIXME: "template <class T> friend class A<T>::B<int>;").
1824 // We diagnose this error in ActOnClassTemplateSpecialization.
John McCallfaf5fb42010-08-26 23:41:50 +00001825 } else if (TUK == Sema::TUK_Reference ||
1826 (TUK == Sema::TUK_Friend &&
John McCallb7c5c272010-04-14 00:24:33 +00001827 TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate)) {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001828 ProhibitAttributes(attrs);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00001829 TypeResult = Actions.ActOnTagTemplateIdType(TUK, TagType, StartLoc,
Richard Smitha42fd842020-01-17 15:42:11 -08001830 SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00001831 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00001832 TemplateId->Template,
1833 TemplateId->TemplateNameLoc,
1834 TemplateId->LAngleLoc,
1835 TemplateArgsPtr,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00001836 TemplateId->RAngleLoc);
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001837 } else {
1838 // This is an explicit specialization or a class template
1839 // partial specialization.
1840 TemplateParameterLists FakedParamLists;
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001841 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1842 // This looks like an explicit instantiation, because we have
1843 // something like
1844 //
1845 // template class Foo<X>
1846 //
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001847 // but it actually has a definition. Most likely, this was
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001848 // meant to be an explicit specialization, but the user forgot
1849 // the '<>' after 'template'.
Richard Smith003c5e12013-11-08 19:03:29 +00001850 // It this is friend declaration however, since it cannot have a
1851 // template header, it is most likely that the user meant to
1852 // remove the 'template' keyword.
Larisse Voufob9bbaba2013-06-22 13:56:11 +00001853 assert((TUK == Sema::TUK_Definition || TUK == Sema::TUK_Friend) &&
Richard Smith003c5e12013-11-08 19:03:29 +00001854 "Expected a definition here");
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001855
Richard Smith003c5e12013-11-08 19:03:29 +00001856 if (TUK == Sema::TUK_Friend) {
1857 Diag(DS.getFriendSpecLoc(), diag::err_friend_explicit_instantiation);
Craig Topper161e4db2014-05-21 06:02:52 +00001858 TemplateParams = nullptr;
Richard Smith003c5e12013-11-08 19:03:29 +00001859 } else {
1860 SourceLocation LAngleLoc =
1861 PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
1862 Diag(TemplateId->TemplateNameLoc,
1863 diag::err_explicit_instantiation_with_definition)
1864 << SourceRange(TemplateInfo.TemplateLoc)
1865 << FixItHint::CreateInsertion(LAngleLoc, "<>");
1866
1867 // Create a fake template parameter list that contains only
1868 // "template<>", so that we treat this construct as a class
1869 // template specialization.
1870 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
Craig Topper96225a52015-12-24 23:58:25 +00001871 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
Hubert Tongf608c052016-04-29 18:05:37 +00001872 LAngleLoc, nullptr));
Richard Smith003c5e12013-11-08 19:03:29 +00001873 TemplateParams = &FakedParamLists;
1874 }
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001875 }
1876
1877 // Build the class template specialization.
Richard Smith4b55a9c2014-04-17 03:29:33 +00001878 TagOrTempResult = Actions.ActOnClassTemplateSpecialization(
1879 getCurScope(), TagType, TUK, StartLoc, DS.getModulePrivateSpecLoc(),
Richard Smitha42fd842020-01-17 15:42:11 -08001880 SS, *TemplateId, attrs,
Craig Topper161e4db2014-05-21 06:02:52 +00001881 MultiTemplateParamsArg(TemplateParams ? &(*TemplateParams)[0]
1882 : nullptr,
Richard Smithc7e6ff02015-05-18 20:36:47 +00001883 TemplateParams ? TemplateParams->size() : 0),
1884 &SkipBody);
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001885 }
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001886 } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
John McCallfaf5fb42010-08-26 23:41:50 +00001887 TUK == Sema::TUK_Declaration) {
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001888 // Explicit instantiation of a member of a class template
1889 // specialization, e.g.,
1890 //
1891 // template struct Outer<int>::Inner;
1892 //
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001893 ProhibitAttributes(attrs);
1894
Erich Keanec480f302018-07-12 21:09:05 +00001895 TagOrTempResult = Actions.ActOnExplicitInstantiation(
1896 getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc,
1897 TagType, StartLoc, SS, Name, NameLoc, attrs);
John McCallace48cd2010-10-19 01:40:49 +00001898 } else if (TUK == Sema::TUK_Friend &&
1899 TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate) {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001900 ProhibitAttributes(attrs);
1901
Erich Keanec480f302018-07-12 21:09:05 +00001902 TagOrTempResult = Actions.ActOnTemplatedFriendTag(
1903 getCurScope(), DS.getFriendSpecLoc(), TagType, StartLoc, SS, Name,
1904 NameLoc, attrs,
1905 MultiTemplateParamsArg(TemplateParams ? &(*TemplateParams)[0] : nullptr,
1906 TemplateParams ? TemplateParams->size() : 0));
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001907 } else {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001908 if (TUK != Sema::TUK_Declaration && TUK != Sema::TUK_Definition)
1909 ProhibitAttributes(attrs);
Richard Smith003c5e12013-11-08 19:03:29 +00001910
Larisse Voufo725de3e2013-06-21 00:08:46 +00001911 if (TUK == Sema::TUK_Definition &&
1912 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1913 // If the declarator-id is not a template-id, issue a diagnostic and
1914 // recover by ignoring the 'template' keyword.
1915 Diag(Tok, diag::err_template_defn_explicit_instantiation)
1916 << 1 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
Craig Topper161e4db2014-05-21 06:02:52 +00001917 TemplateParams = nullptr;
Larisse Voufo725de3e2013-06-21 00:08:46 +00001918 }
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001919
John McCall7f41d982009-09-11 04:59:25 +00001920 bool IsDependent = false;
1921
John McCall32723e92010-10-19 18:40:57 +00001922 // Don't pass down template parameter lists if this is just a tag
1923 // reference. For example, we don't need the template parameters here:
1924 // template <class T> class A *makeA(T t);
1925 MultiTemplateParamsArg TParams;
1926 if (TUK != Sema::TUK_Reference && TemplateParams)
1927 TParams =
1928 MultiTemplateParamsArg(&(*TemplateParams)[0], TemplateParams->size());
1929
Nico Weber32a0fc72016-09-03 03:01:32 +00001930 stripTypeAttributesOffDeclSpec(attrs, DS, TUK);
David Majnemer936b4112015-04-19 07:53:29 +00001931
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001932 // Declaration or definition of a class type
Faisal Vali7db85c52017-12-31 00:06:40 +00001933 TagOrTempResult = Actions.ActOnTag(
Erich Keanec480f302018-07-12 21:09:05 +00001934 getCurScope(), TagType, TUK, StartLoc, SS, Name, NameLoc, attrs, AS,
1935 DS.getModulePrivateSpecLoc(), TParams, Owned, IsDependent,
1936 SourceLocation(), false, clang::TypeResult(),
Faisal Vali7db85c52017-12-31 00:06:40 +00001937 DSC == DeclSpecContext::DSC_type_specifier,
1938 DSC == DeclSpecContext::DSC_template_param ||
1939 DSC == DeclSpecContext::DSC_template_type_arg,
1940 &SkipBody);
John McCall7f41d982009-09-11 04:59:25 +00001941
1942 // If ActOnTag said the type was dependent, try again with the
1943 // less common call.
John McCallace48cd2010-10-19 01:40:49 +00001944 if (IsDependent) {
1945 assert(TUK == Sema::TUK_Reference || TUK == Sema::TUK_Friend);
Douglas Gregor0be31a22010-07-02 17:43:08 +00001946 TypeResult = Actions.ActOnDependentTag(getCurScope(), TagType, TUK,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001947 SS, Name, StartLoc, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +00001948 }
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001949 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001950
Douglas Gregor556877c2008-04-13 21:30:24 +00001951 // If there is a body, parse it and inform the actions module.
John McCallfaf5fb42010-08-26 23:41:50 +00001952 if (TUK == Sema::TUK_Definition) {
John McCall2d814c32009-12-19 21:48:58 +00001953 assert(Tok.is(tok::l_brace) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00001954 (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
Richard Smith89645bc2013-01-02 12:01:23 +00001955 isCXX11FinalKeyword());
Richard Smithd9ba2242015-05-07 03:54:19 +00001956 if (SkipBody.ShouldSkip)
Richard Smith65ebb4a2015-03-26 04:09:53 +00001957 SkipCXXMemberSpecification(StartLoc, AttrFixitLoc, TagType,
1958 TagOrTempResult.get());
1959 else if (getLangOpts().CPlusPlus)
Michael Han309af292013-01-07 16:57:11 +00001960 ParseCXXMemberSpecification(StartLoc, AttrFixitLoc, attrs, TagType,
1961 TagOrTempResult.get());
Bruno Cardoso Lopesdf0ee342017-07-01 00:06:47 +00001962 else {
1963 Decl *D =
1964 SkipBody.CheckSameAsPrevious ? SkipBody.New : TagOrTempResult.get();
1965 // Parse the definition body.
1966 ParseStructUnionBody(StartLoc, TagType, D);
1967 if (SkipBody.CheckSameAsPrevious &&
1968 !Actions.ActOnDuplicateDefinition(DS, TagOrTempResult.get(),
1969 SkipBody)) {
1970 DS.SetTypeSpecError();
1971 return;
1972 }
1973 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001974 }
1975
Erich Keane2fe684b2017-02-28 20:44:39 +00001976 if (!TagOrTempResult.isInvalid())
Hiroshi Inoue939d9322017-06-30 05:40:31 +00001977 // Delayed processing of attributes.
Erich Keanec480f302018-07-12 21:09:05 +00001978 Actions.ProcessDeclAttributeDelayed(TagOrTempResult.get(), attrs);
Erich Keane2fe684b2017-02-28 20:44:39 +00001979
Craig Topper161e4db2014-05-21 06:02:52 +00001980 const char *PrevSpec = nullptr;
John McCallba7bf592010-08-24 05:47:05 +00001981 unsigned DiagID;
1982 bool Result;
John McCall7f41d982009-09-11 04:59:25 +00001983 if (!TypeResult.isInvalid()) {
Abramo Bagnara9875a3c2011-03-16 20:16:18 +00001984 Result = DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
1985 NameLoc.isValid() ? NameLoc : StartLoc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001986 PrevSpec, DiagID, TypeResult.get(), Policy);
John McCall7f41d982009-09-11 04:59:25 +00001987 } else if (!TagOrTempResult.isInvalid()) {
Abramo Bagnara9875a3c2011-03-16 20:16:18 +00001988 Result = DS.SetTypeSpecType(TagType, StartLoc,
1989 NameLoc.isValid() ? NameLoc : StartLoc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001990 PrevSpec, DiagID, TagOrTempResult.get(), Owned,
1991 Policy);
John McCall7f41d982009-09-11 04:59:25 +00001992 } else {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001993 DS.SetTypeSpecError();
Anders Carlssonf83c9fa2009-05-11 22:27:47 +00001994 return;
1995 }
Mike Stump11289f42009-09-09 15:08:12 +00001996
John McCallba7bf592010-08-24 05:47:05 +00001997 if (Result)
John McCall49bfce42009-08-03 20:12:06 +00001998 Diag(StartLoc, DiagID) << PrevSpec;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001999
Chris Lattnercf251412010-02-02 01:23:29 +00002000 // At this point, we've successfully parsed a class-specifier in 'definition'
2001 // form (e.g. "struct foo { int x; }". While we could just return here, we're
2002 // going to look at what comes after it to improve error recovery. If an
2003 // impossible token occurs next, we assume that the programmer forgot a ; at
2004 // the end of the declaration and recover that way.
2005 //
Richard Smith369b9f92012-06-25 21:37:02 +00002006 // Also enforce C++ [temp]p3:
2007 // In a template-declaration which defines a class, no declarator
2008 // is permitted.
Richard Smith843f18f2014-08-13 02:13:15 +00002009 //
2010 // After a type-specifier, we don't expect a semicolon. This only happens in
2011 // C, since definitions are not permitted in this context in C++.
Joao Matose9a3ed42012-08-31 22:18:20 +00002012 if (TUK == Sema::TUK_Definition &&
Richard Smith843f18f2014-08-13 02:13:15 +00002013 (getLangOpts().CPlusPlus || !isTypeSpecifier(DSC)) &&
Joao Matose9a3ed42012-08-31 22:18:20 +00002014 (TemplateInfo.Kind || !isValidAfterTypeSpecifier(false))) {
Argyrios Kyrtzidise6f69132012-12-17 20:10:43 +00002015 if (Tok.isNot(tok::semi)) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002016 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
Alp Toker383d2c42014-01-01 03:08:43 +00002017 ExpectAndConsume(tok::semi, diag::err_expected_after,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002018 DeclSpec::getSpecifierName(TagType, PPol));
Argyrios Kyrtzidise6f69132012-12-17 20:10:43 +00002019 // Push this token back into the preprocessor and change our current token
2020 // to ';' so that the rest of the code recovers as though there were an
2021 // ';' after the definition.
Ilya Biryukov929af672019-05-17 09:32:05 +00002022 PP.EnterToken(Tok, /*IsReinject=*/true);
Argyrios Kyrtzidise6f69132012-12-17 20:10:43 +00002023 Tok.setKind(tok::semi);
2024 }
Chris Lattnercf251412010-02-02 01:23:29 +00002025 }
Douglas Gregor556877c2008-04-13 21:30:24 +00002026}
2027
Mike Stump11289f42009-09-09 15:08:12 +00002028/// ParseBaseClause - Parse the base-clause of a C++ class [C++ class.derived].
Douglas Gregor556877c2008-04-13 21:30:24 +00002029///
2030/// base-clause : [C++ class.derived]
2031/// ':' base-specifier-list
2032/// base-specifier-list:
2033/// base-specifier '...'[opt]
2034/// base-specifier-list ',' base-specifier '...'[opt]
John McCall48871652010-08-21 09:40:31 +00002035void Parser::ParseBaseClause(Decl *ClassDecl) {
Douglas Gregor556877c2008-04-13 21:30:24 +00002036 assert(Tok.is(tok::colon) && "Not a base clause");
2037 ConsumeToken();
2038
Douglas Gregor29a92472008-10-22 17:49:05 +00002039 // Build up an array of parsed base specifiers.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002040 SmallVector<CXXBaseSpecifier *, 8> BaseInfo;
Douglas Gregor29a92472008-10-22 17:49:05 +00002041
Douglas Gregor556877c2008-04-13 21:30:24 +00002042 while (true) {
2043 // Parse a base-specifier.
Douglas Gregor29a92472008-10-22 17:49:05 +00002044 BaseResult Result = ParseBaseSpecifier(ClassDecl);
Douglas Gregorf8298252009-01-26 22:44:13 +00002045 if (Result.isInvalid()) {
Douglas Gregor556877c2008-04-13 21:30:24 +00002046 // Skip the rest of this base specifier, up until the comma or
2047 // opening brace.
Alexey Bataevee6507d2013-11-18 08:17:37 +00002048 SkipUntil(tok::comma, tok::l_brace, StopAtSemi | StopBeforeMatch);
Douglas Gregor29a92472008-10-22 17:49:05 +00002049 } else {
2050 // Add this to our array of base specifiers.
Douglas Gregorf8298252009-01-26 22:44:13 +00002051 BaseInfo.push_back(Result.get());
Douglas Gregor556877c2008-04-13 21:30:24 +00002052 }
2053
2054 // If the next token is a comma, consume it and keep reading
2055 // base-specifiers.
Alp Toker97650562014-01-10 11:19:30 +00002056 if (!TryConsumeToken(tok::comma))
2057 break;
Douglas Gregor556877c2008-04-13 21:30:24 +00002058 }
Douglas Gregor29a92472008-10-22 17:49:05 +00002059
2060 // Attach the base specifiers
Craig Topperaa700cb2015-12-27 21:55:19 +00002061 Actions.ActOnBaseSpecifiers(ClassDecl, BaseInfo);
Douglas Gregor556877c2008-04-13 21:30:24 +00002062}
2063
2064/// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is
2065/// one entry in the base class list of a class specifier, for example:
2066/// class foo : public bar, virtual private baz {
2067/// 'public bar' and 'virtual private baz' are each base-specifiers.
2068///
2069/// base-specifier: [C++ class.derived]
Richard Smith4c96e992013-02-19 23:47:15 +00002070/// attribute-specifier-seq[opt] base-type-specifier
2071/// attribute-specifier-seq[opt] 'virtual' access-specifier[opt]
2072/// base-type-specifier
2073/// attribute-specifier-seq[opt] access-specifier 'virtual'[opt]
2074/// base-type-specifier
Craig Topper9ad7e262014-10-31 06:57:07 +00002075BaseResult Parser::ParseBaseSpecifier(Decl *ClassDecl) {
Douglas Gregor556877c2008-04-13 21:30:24 +00002076 bool IsVirtual = false;
2077 SourceLocation StartLoc = Tok.getLocation();
2078
Richard Smith4c96e992013-02-19 23:47:15 +00002079 ParsedAttributesWithRange Attributes(AttrFactory);
2080 MaybeParseCXX11Attributes(Attributes);
2081
Douglas Gregor556877c2008-04-13 21:30:24 +00002082 // Parse the 'virtual' keyword.
Alp Toker97650562014-01-10 11:19:30 +00002083 if (TryConsumeToken(tok::kw_virtual))
Douglas Gregor556877c2008-04-13 21:30:24 +00002084 IsVirtual = true;
Douglas Gregor556877c2008-04-13 21:30:24 +00002085
Richard Smith4c96e992013-02-19 23:47:15 +00002086 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2087
Douglas Gregor556877c2008-04-13 21:30:24 +00002088 // Parse an (optional) access specifier.
2089 AccessSpecifier Access = getAccessSpecifierIfPresent();
John McCall553c0792010-01-23 00:46:32 +00002090 if (Access != AS_none)
Douglas Gregor556877c2008-04-13 21:30:24 +00002091 ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +00002092
Richard Smith4c96e992013-02-19 23:47:15 +00002093 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2094
Douglas Gregor556877c2008-04-13 21:30:24 +00002095 // Parse the 'virtual' keyword (again!), in case it came after the
2096 // access specifier.
2097 if (Tok.is(tok::kw_virtual)) {
2098 SourceLocation VirtualLoc = ConsumeToken();
2099 if (IsVirtual) {
2100 // Complain about duplicate 'virtual'
Chris Lattner6d29c102008-11-18 07:48:38 +00002101 Diag(VirtualLoc, diag::err_dup_virtual)
Douglas Gregora771f462010-03-31 17:46:05 +00002102 << FixItHint::CreateRemoval(VirtualLoc);
Douglas Gregor556877c2008-04-13 21:30:24 +00002103 }
2104
2105 IsVirtual = true;
2106 }
2107
Richard Smith4c96e992013-02-19 23:47:15 +00002108 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2109
Douglas Gregor831c93f2008-11-05 20:51:48 +00002110 // Parse the class-name.
David Majnemer51fd8a02015-07-22 23:46:18 +00002111
2112 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
2113 // implementation for VS2013 uses _Atomic as an identifier for one of the
2114 // classes in <atomic>. Treat '_Atomic' to be an identifier when we are
2115 // parsing the class-name for a base specifier.
2116 if (getLangOpts().MSVCCompat && Tok.is(tok::kw__Atomic) &&
2117 NextToken().is(tok::less))
2118 Tok.setKind(tok::identifier);
2119
Douglas Gregord54dfb82009-02-25 23:52:28 +00002120 SourceLocation EndLocation;
David Blaikie1cd50022011-10-25 17:10:12 +00002121 SourceLocation BaseLoc;
2122 TypeResult BaseType = ParseBaseTypeSpecifier(BaseLoc, EndLocation);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00002123 if (BaseType.isInvalid())
Douglas Gregor831c93f2008-11-05 20:51:48 +00002124 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002125
Fangrui Song6907ce22018-07-30 19:24:48 +00002126 // Parse the optional ellipsis (for a pack expansion). The ellipsis is
Douglas Gregor752a5952011-01-03 22:36:02 +00002127 // actually part of the base-specifier-list grammar productions, but we
2128 // parse it here for convenience.
2129 SourceLocation EllipsisLoc;
Alp Toker97650562014-01-10 11:19:30 +00002130 TryConsumeToken(tok::ellipsis, EllipsisLoc);
2131
Mike Stump11289f42009-09-09 15:08:12 +00002132 // Find the complete source range for the base-specifier.
Douglas Gregord54dfb82009-02-25 23:52:28 +00002133 SourceRange Range(StartLoc, EndLocation);
Mike Stump11289f42009-09-09 15:08:12 +00002134
Douglas Gregor556877c2008-04-13 21:30:24 +00002135 // Notify semantic analysis that we have parsed a complete
2136 // base-specifier.
Richard Smith4c96e992013-02-19 23:47:15 +00002137 return Actions.ActOnBaseSpecifier(ClassDecl, Range, Attributes, IsVirtual,
2138 Access, BaseType.get(), BaseLoc,
2139 EllipsisLoc);
Douglas Gregor556877c2008-04-13 21:30:24 +00002140}
2141
2142/// getAccessSpecifierIfPresent - Determine whether the next token is
2143/// a C++ access-specifier.
2144///
2145/// access-specifier: [C++ class.derived]
2146/// 'private'
2147/// 'protected'
2148/// 'public'
Mike Stump11289f42009-09-09 15:08:12 +00002149AccessSpecifier Parser::getAccessSpecifierIfPresent() const {
Douglas Gregor556877c2008-04-13 21:30:24 +00002150 switch (Tok.getKind()) {
2151 default: return AS_none;
2152 case tok::kw_private: return AS_private;
2153 case tok::kw_protected: return AS_protected;
2154 case tok::kw_public: return AS_public;
2155 }
2156}
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002157
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002158/// If the given declarator has any parts for which parsing has to be
Richard Smith0b3a4622014-11-13 20:01:57 +00002159/// delayed, e.g., default arguments or an exception-specification, create a
2160/// late-parsed method declaration record to handle the parsing at the end of
2161/// the class definition.
Douglas Gregor433e0532012-04-16 18:27:27 +00002162void Parser::HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
2163 Decl *ThisDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00002164 DeclaratorChunk::FunctionTypeInfo &FTI
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002165 = DeclaratorInfo.getFunctionTypeInfo();
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002166 // If there was a late-parsed exception-specification, we'll need a
2167 // late parse
2168 bool NeedLateParse = FTI.getExceptionSpecType() == EST_Unparsed;
Douglas Gregor433e0532012-04-16 18:27:27 +00002169
Nathan Sidwell5bb231c2015-02-19 14:03:22 +00002170 if (!NeedLateParse) {
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002171 // Look ahead to see if there are any default args
Nathan Sidwell5bb231c2015-02-19 14:03:22 +00002172 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx) {
2173 auto Param = cast<ParmVarDecl>(FTI.Params[ParamIdx].Param);
2174 if (Param->hasUnparsedDefaultArg()) {
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002175 NeedLateParse = true;
2176 break;
2177 }
Nathan Sidwell5bb231c2015-02-19 14:03:22 +00002178 }
2179 }
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002180
2181 if (NeedLateParse) {
Richard Smith0b3a4622014-11-13 20:01:57 +00002182 // Push this method onto the stack of late-parsed method
2183 // declarations.
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002184 auto LateMethod = new LateParsedMethodDeclaration(this, ThisDecl);
Richard Smith0b3a4622014-11-13 20:01:57 +00002185 getCurrentClass().LateParsedDeclarations.push_back(LateMethod);
2186 LateMethod->TemplateScope = getCurScope()->isTemplateParamScope();
2187
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002188 // Stash the exception-specification tokens in the late-pased method.
Richard Smith0b3a4622014-11-13 20:01:57 +00002189 LateMethod->ExceptionSpecTokens = FTI.ExceptionSpecTokens;
Hans Wennborgdcfba332015-10-06 23:40:43 +00002190 FTI.ExceptionSpecTokens = nullptr;
Richard Smith0b3a4622014-11-13 20:01:57 +00002191
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002192 // Push tokens for each parameter. Those that do not have
2193 // defaults will be NULL.
Richard Smith0b3a4622014-11-13 20:01:57 +00002194 LateMethod->DefaultArgs.reserve(FTI.NumParams);
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002195 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx)
Alp Tokerc5350722014-02-26 22:27:52 +00002196 LateMethod->DefaultArgs.push_back(LateParsedDefaultArgument(
Malcolm Parsonsca9d8342016-11-17 21:00:09 +00002197 FTI.Params[ParamIdx].Param,
2198 std::move(FTI.Params[ParamIdx].DefaultArgTokens)));
Eli Friedman3af2a772009-07-22 21:45:50 +00002199 }
2200}
2201
Richard Smith89645bc2013-01-02 12:01:23 +00002202/// isCXX11VirtSpecifier - Determine whether the given token is a C++11
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002203/// virt-specifier.
2204///
2205/// virt-specifier:
2206/// override
2207/// final
Andrey Bokhanko276055b2016-07-29 10:42:48 +00002208/// __final
Richard Smith89645bc2013-01-02 12:01:23 +00002209VirtSpecifiers::Specifier Parser::isCXX11VirtSpecifier(const Token &Tok) const {
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002210 if (!getLangOpts().CPlusPlus || Tok.isNot(tok::identifier))
Anders Carlsson4b63d0e2011-01-22 16:56:46 +00002211 return VirtSpecifiers::VS_None;
2212
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002213 IdentifierInfo *II = Tok.getIdentifierInfo();
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002214
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002215 // Initialize the contextual keywords.
2216 if (!Ident_final) {
2217 Ident_final = &PP.getIdentifierTable().get("final");
Andrey Bokhanko276055b2016-07-29 10:42:48 +00002218 if (getLangOpts().GNUKeywords)
2219 Ident_GNU_final = &PP.getIdentifierTable().get("__final");
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002220 if (getLangOpts().MicrosoftExt)
2221 Ident_sealed = &PP.getIdentifierTable().get("sealed");
2222 Ident_override = &PP.getIdentifierTable().get("override");
Anders Carlsson56104902011-01-17 03:05:47 +00002223 }
2224
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002225 if (II == Ident_override)
2226 return VirtSpecifiers::VS_Override;
2227
2228 if (II == Ident_sealed)
2229 return VirtSpecifiers::VS_Sealed;
2230
2231 if (II == Ident_final)
2232 return VirtSpecifiers::VS_Final;
2233
Andrey Bokhanko276055b2016-07-29 10:42:48 +00002234 if (II == Ident_GNU_final)
2235 return VirtSpecifiers::VS_GNU_Final;
2236
Anders Carlsson56104902011-01-17 03:05:47 +00002237 return VirtSpecifiers::VS_None;
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002238}
2239
Richard Smith89645bc2013-01-02 12:01:23 +00002240/// ParseOptionalCXX11VirtSpecifierSeq - Parse a virt-specifier-seq.
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002241///
2242/// virt-specifier-seq:
2243/// virt-specifier
2244/// virt-specifier-seq virt-specifier
Richard Smith89645bc2013-01-02 12:01:23 +00002245void Parser::ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS,
Richard Smith3d1a94c2014-08-12 00:22:39 +00002246 bool IsInterface,
2247 SourceLocation FriendLoc) {
Anders Carlsson56104902011-01-17 03:05:47 +00002248 while (true) {
Richard Smith89645bc2013-01-02 12:01:23 +00002249 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
Anders Carlsson56104902011-01-17 03:05:47 +00002250 if (Specifier == VirtSpecifiers::VS_None)
2251 return;
2252
Richard Smith3d1a94c2014-08-12 00:22:39 +00002253 if (FriendLoc.isValid()) {
2254 Diag(Tok.getLocation(), diag::err_friend_decl_spec)
2255 << VirtSpecifiers::getSpecifierName(Specifier)
2256 << FixItHint::CreateRemoval(Tok.getLocation())
2257 << SourceRange(FriendLoc, FriendLoc);
2258 ConsumeToken();
2259 continue;
2260 }
2261
Anders Carlsson56104902011-01-17 03:05:47 +00002262 // C++ [class.mem]p8:
2263 // A virt-specifier-seq shall contain at most one of each virt-specifier.
Craig Topper161e4db2014-05-21 06:02:52 +00002264 const char *PrevSpec = nullptr;
Anders Carlssonf2ca3892011-01-22 15:58:16 +00002265 if (VS.SetSpecifier(Specifier, Tok.getLocation(), PrevSpec))
Anders Carlsson56104902011-01-17 03:05:47 +00002266 Diag(Tok.getLocation(), diag::err_duplicate_virt_specifier)
2267 << PrevSpec
2268 << FixItHint::CreateRemoval(Tok.getLocation());
2269
David Majnemera5433082013-10-18 00:33:31 +00002270 if (IsInterface && (Specifier == VirtSpecifiers::VS_Final ||
2271 Specifier == VirtSpecifiers::VS_Sealed)) {
John McCalldb632ac2012-09-25 07:32:39 +00002272 Diag(Tok.getLocation(), diag::err_override_control_interface)
2273 << VirtSpecifiers::getSpecifierName(Specifier);
David Majnemera5433082013-10-18 00:33:31 +00002274 } else if (Specifier == VirtSpecifiers::VS_Sealed) {
2275 Diag(Tok.getLocation(), diag::ext_ms_sealed_keyword);
Andrey Bokhanko276055b2016-07-29 10:42:48 +00002276 } else if (Specifier == VirtSpecifiers::VS_GNU_Final) {
2277 Diag(Tok.getLocation(), diag::ext_warn_gnu_final);
John McCalldb632ac2012-09-25 07:32:39 +00002278 } else {
David Majnemera5433082013-10-18 00:33:31 +00002279 Diag(Tok.getLocation(),
2280 getLangOpts().CPlusPlus11
2281 ? diag::warn_cxx98_compat_override_control_keyword
2282 : diag::ext_override_control_keyword)
2283 << VirtSpecifiers::getSpecifierName(Specifier);
John McCalldb632ac2012-09-25 07:32:39 +00002284 }
Anders Carlsson56104902011-01-17 03:05:47 +00002285 ConsumeToken();
2286 }
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002287}
2288
Richard Smith89645bc2013-01-02 12:01:23 +00002289/// isCXX11FinalKeyword - Determine whether the next token is a C++11
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002290/// 'final' or Microsoft 'sealed' contextual keyword.
Richard Smith89645bc2013-01-02 12:01:23 +00002291bool Parser::isCXX11FinalKeyword() const {
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002292 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
2293 return Specifier == VirtSpecifiers::VS_Final ||
Fangrui Song6907ce22018-07-30 19:24:48 +00002294 Specifier == VirtSpecifiers::VS_GNU_Final ||
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002295 Specifier == VirtSpecifiers::VS_Sealed;
Anders Carlsson4b63d0e2011-01-22 16:56:46 +00002296}
2297
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002298/// Parse a C++ member-declarator up to, but not including, the optional
Richard Smith72553fc2014-01-23 23:53:27 +00002299/// brace-or-equal-initializer or pure-specifier.
Nico Weberd89e6f72015-01-16 19:34:13 +00002300bool Parser::ParseCXXMemberDeclaratorBeforeInitializer(
Richard Smith72553fc2014-01-23 23:53:27 +00002301 Declarator &DeclaratorInfo, VirtSpecifiers &VS, ExprResult &BitfieldSize,
2302 LateParsedAttrList &LateParsedAttrs) {
2303 // member-declarator:
2304 // declarator pure-specifier[opt]
Saar Razb65b1f32020-01-09 15:07:51 +02002305 // declarator requires-clause
Richard Smith72553fc2014-01-23 23:53:27 +00002306 // declarator brace-or-equal-initializer[opt]
2307 // identifier[opt] ':' constant-expression
Serge Pavlov458ea762014-07-16 05:16:52 +00002308 if (Tok.isNot(tok::colon))
Richard Smith72553fc2014-01-23 23:53:27 +00002309 ParseDeclarator(DeclaratorInfo);
Richard Smith3d1a94c2014-08-12 00:22:39 +00002310 else
2311 DeclaratorInfo.SetIdentifier(nullptr, Tok.getLocation());
Richard Smith72553fc2014-01-23 23:53:27 +00002312
2313 if (!DeclaratorInfo.isFunctionDeclarator() && TryConsumeToken(tok::colon)) {
Richard Smith3d1a94c2014-08-12 00:22:39 +00002314 assert(DeclaratorInfo.isPastIdentifier() &&
2315 "don't know where identifier would go yet?");
Richard Smith72553fc2014-01-23 23:53:27 +00002316 BitfieldSize = ParseConstantExpression();
2317 if (BitfieldSize.isInvalid())
2318 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
Saar Razb65b1f32020-01-09 15:07:51 +02002319 } else if (Tok.is(tok::kw_requires)) {
2320 ParseTrailingRequiresClause(DeclaratorInfo);
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002321 } else {
Richard Smith3d1a94c2014-08-12 00:22:39 +00002322 ParseOptionalCXX11VirtSpecifierSeq(
2323 VS, getCurrentClass().IsInterface,
2324 DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002325 if (!VS.isUnset())
2326 MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo, VS);
2327 }
Richard Smith72553fc2014-01-23 23:53:27 +00002328
2329 // If a simple-asm-expr is present, parse it.
2330 if (Tok.is(tok::kw_asm)) {
2331 SourceLocation Loc;
Aaron Ballman55a51e12020-01-08 08:38:02 -05002332 ExprResult AsmLabel(ParseSimpleAsm(/*ForAsmLabel*/ true, &Loc));
Richard Smith72553fc2014-01-23 23:53:27 +00002333 if (AsmLabel.isInvalid())
2334 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2335
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002336 DeclaratorInfo.setAsmLabel(AsmLabel.get());
Richard Smith72553fc2014-01-23 23:53:27 +00002337 DeclaratorInfo.SetRangeEnd(Loc);
2338 }
2339
2340 // If attributes exist after the declarator, but before an '{', parse them.
2341 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
Richard Smith4b5a9492014-01-24 22:34:35 +00002342
2343 // For compatibility with code written to older Clang, also accept a
2344 // virt-specifier *after* the GNU attributes.
Aaron Ballman5d153e32014-08-04 17:03:51 +00002345 if (BitfieldSize.isUnset() && VS.isUnset()) {
Richard Smith3d1a94c2014-08-12 00:22:39 +00002346 ParseOptionalCXX11VirtSpecifierSeq(
2347 VS, getCurrentClass().IsInterface,
2348 DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
Aaron Ballman5d153e32014-08-04 17:03:51 +00002349 if (!VS.isUnset()) {
2350 // If we saw any GNU-style attributes that are known to GCC followed by a
2351 // virt-specifier, issue a GCC-compat warning.
Erich Keanee891aa92018-07-13 15:07:47 +00002352 for (const ParsedAttr &AL : DeclaratorInfo.getAttributes())
Erich Keanec480f302018-07-12 21:09:05 +00002353 if (AL.isKnownToGCC() && !AL.isCXX11Attribute())
2354 Diag(AL.getLoc(), diag::warn_gcc_attribute_location);
2355
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002356 MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo, VS);
Aaron Ballman5d153e32014-08-04 17:03:51 +00002357 }
2358 }
Nico Weberd89e6f72015-01-16 19:34:13 +00002359
2360 // If this has neither a name nor a bit width, something has gone seriously
2361 // wrong. Skip until the semi-colon or }.
2362 if (!DeclaratorInfo.hasName() && BitfieldSize.isUnset()) {
2363 // If so, skip until the semi-colon or a }.
2364 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2365 return true;
2366 }
2367 return false;
Richard Smith72553fc2014-01-23 23:53:27 +00002368}
2369
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002370/// Look for declaration specifiers possibly occurring after C++11
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002371/// virt-specifier-seq and diagnose them.
2372void Parser::MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(
2373 Declarator &D,
2374 VirtSpecifiers &VS) {
2375 DeclSpec DS(AttrFactory);
2376
2377 // GNU-style and C++11 attributes are not allowed here, but they will be
2378 // handled by the caller. Diagnose everything else.
Alex Lorenz8f4d3992017-02-13 23:19:40 +00002379 ParseTypeQualifierListOpt(
2380 DS, AR_NoAttributesParsed, false,
2381 /*IdentifierRequired=*/false, llvm::function_ref<void()>([&]() {
2382 Actions.CodeCompleteFunctionQualifiers(DS, D, &VS);
2383 }));
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002384 D.ExtendWithDeclSpec(DS);
2385
2386 if (D.isFunctionDeclarator()) {
Ehsan Akhgaric07d1e22015-03-25 00:53:33 +00002387 auto &Function = D.getFunctionTypeInfo();
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002388 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
Anastasia Stulovaa9bc4bd2019-01-09 11:25:09 +00002389 auto DeclSpecCheck = [&](DeclSpec::TQ TypeQual, StringRef FixItName,
2390 SourceLocation SpecLoc) {
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002391 FixItHint Insertion;
Anastasia Stulovaa9bc4bd2019-01-09 11:25:09 +00002392 auto &MQ = Function.getOrCreateMethodQualifiers();
2393 if (!(MQ.getTypeQualifiers() & TypeQual)) {
2394 std::string Name(FixItName.data());
2395 Name += " ";
2396 Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), Name);
2397 MQ.SetTypeQual(TypeQual, SpecLoc);
2398 }
2399 Diag(SpecLoc, diag::err_declspec_after_virtspec)
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002400 << FixItName
2401 << VirtSpecifiers::getSpecifierName(VS.getLastSpecifier())
Anastasia Stulovaa9bc4bd2019-01-09 11:25:09 +00002402 << FixItHint::CreateRemoval(SpecLoc) << Insertion;
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002403 };
Anastasia Stulovaa9bc4bd2019-01-09 11:25:09 +00002404 DS.forEachQualifier(DeclSpecCheck);
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002405 }
Ehsan Akhgaric07d1e22015-03-25 00:53:33 +00002406
2407 // Parse ref-qualifiers.
2408 bool RefQualifierIsLValueRef = true;
2409 SourceLocation RefQualifierLoc;
2410 if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc)) {
2411 const char *Name = (RefQualifierIsLValueRef ? "& " : "&& ");
2412 FixItHint Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), Name);
2413 Function.RefQualifierIsLValueRef = RefQualifierIsLValueRef;
2414 Function.RefQualifierLoc = RefQualifierLoc.getRawEncoding();
2415
2416 Diag(RefQualifierLoc, diag::err_declspec_after_virtspec)
2417 << (RefQualifierIsLValueRef ? "&" : "&&")
2418 << VirtSpecifiers::getSpecifierName(VS.getLastSpecifier())
2419 << FixItHint::CreateRemoval(RefQualifierLoc)
2420 << Insertion;
2421 D.SetRangeEnd(RefQualifierLoc);
2422 }
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002423 }
2424}
2425
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002426/// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration.
2427///
2428/// member-declaration:
2429/// decl-specifier-seq[opt] member-declarator-list[opt] ';'
2430/// function-definition ';'[opt]
2431/// ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO]
2432/// using-declaration [TODO]
Anders Carlssonf24fcff62009-03-11 16:27:10 +00002433/// [C++0x] static_assert-declaration
Anders Carlssondfbbdf62009-03-26 00:52:18 +00002434/// template-declaration
Chris Lattnerd19c1c02008-12-18 01:12:00 +00002435/// [GNU] '__extension__' member-declaration
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002436///
2437/// member-declarator-list:
2438/// member-declarator
2439/// member-declarator-list ',' member-declarator
2440///
2441/// member-declarator:
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002442/// declarator virt-specifier-seq[opt] pure-specifier[opt]
Saar Razb65b1f32020-01-09 15:07:51 +02002443/// [C++2a] declarator requires-clause
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002444/// declarator constant-initializer[opt]
Richard Smith938f40b2011-06-11 17:19:42 +00002445/// [C++11] declarator brace-or-equal-initializer[opt]
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002446/// identifier[opt] ':' constant-expression
2447///
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002448/// virt-specifier-seq:
2449/// virt-specifier
2450/// virt-specifier-seq virt-specifier
2451///
2452/// virt-specifier:
2453/// override
2454/// final
David Majnemera5433082013-10-18 00:33:31 +00002455/// [MS] sealed
Fangrui Song6907ce22018-07-30 19:24:48 +00002456///
Sebastian Redl42e92c42009-04-12 17:16:29 +00002457/// pure-specifier:
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002458/// '= 0'
2459///
2460/// constant-initializer:
2461/// '=' constant-expression
2462///
Alexey Bataev05c25d62015-07-31 08:42:25 +00002463Parser::DeclGroupPtrTy
2464Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS,
Erich Keanec480f302018-07-12 21:09:05 +00002465 ParsedAttributes &AccessAttrs,
John McCall796c2a52010-07-16 08:13:16 +00002466 const ParsedTemplateInfo &TemplateInfo,
2467 ParsingDeclRAIIObject *TemplateDiags) {
Douglas Gregor23c84762011-04-14 17:21:19 +00002468 if (Tok.is(tok::at)) {
Erik Pilkingtonfa983902018-10-30 20:31:30 +00002469 if (getLangOpts().ObjC && NextToken().isObjCAtKeyword(tok::objc_defs))
Douglas Gregor23c84762011-04-14 17:21:19 +00002470 Diag(Tok, diag::err_at_defs_cxx);
2471 else
2472 Diag(Tok, diag::err_at_in_class);
Richard Smithda35e962013-11-09 04:52:51 +00002473
Douglas Gregor23c84762011-04-14 17:21:19 +00002474 ConsumeToken();
Alexey Bataevee6507d2013-11-18 08:17:37 +00002475 SkipUntil(tok::r_brace, StopAtSemi);
David Blaikie0403cb12016-01-15 23:43:25 +00002476 return nullptr;
Douglas Gregor23c84762011-04-14 17:21:19 +00002477 }
Richard Smithda35e962013-11-09 04:52:51 +00002478
Serge Pavlov458ea762014-07-16 05:16:52 +00002479 // Turn on colon protection early, while parsing declspec, although there is
2480 // nothing to protect there. It prevents from false errors if error recovery
2481 // incorrectly determines where the declspec ends, as in the example:
2482 // struct A { enum class B { C }; };
2483 // const int C = 4;
2484 // struct D { A::B : C; };
2485 ColonProtectionRAIIObject X(*this);
2486
John McCalla0097262009-12-11 02:10:03 +00002487 // Access declarations.
Richard Smith45855df2012-05-09 08:23:23 +00002488 bool MalformedTypeSpec = false;
John McCalla0097262009-12-11 02:10:03 +00002489 if (!TemplateInfo.Kind &&
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002490 Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw___super)) {
Richard Smith45855df2012-05-09 08:23:23 +00002491 if (TryAnnotateCXXScopeToken())
2492 MalformedTypeSpec = true;
2493
2494 bool isAccessDecl;
2495 if (Tok.isNot(tok::annot_cxxscope))
2496 isAccessDecl = false;
2497 else if (NextToken().is(tok::identifier))
John McCalla0097262009-12-11 02:10:03 +00002498 isAccessDecl = GetLookAheadToken(2).is(tok::semi);
2499 else
2500 isAccessDecl = NextToken().is(tok::kw_operator);
2501
2502 if (isAccessDecl) {
2503 // Collect the scope specifier token we annotated earlier.
2504 CXXScopeSpec SS;
Haojian Wu0dd0b102020-03-19 09:12:29 +01002505 ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
2506 /*ObjectHadErrors=*/false,
Douglas Gregordf593fb2011-11-07 17:33:42 +00002507 /*EnteringContext=*/false);
John McCalla0097262009-12-11 02:10:03 +00002508
Nico Weberef03e702014-09-10 00:59:37 +00002509 if (SS.isInvalid()) {
2510 SkipUntil(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002511 return nullptr;
Nico Weberef03e702014-09-10 00:59:37 +00002512 }
2513
John McCalla0097262009-12-11 02:10:03 +00002514 // Try to parse an unqualified-id.
Abramo Bagnara7945c982012-01-27 09:46:47 +00002515 SourceLocation TemplateKWLoc;
John McCalla0097262009-12-11 02:10:03 +00002516 UnqualifiedId Name;
Haojian Wu0dd0b102020-03-19 09:12:29 +01002517 if (ParseUnqualifiedId(SS, /*ObjectType=*/nullptr,
2518 /*ObjectHadErrors=*/false, false, true, true,
2519 false, &TemplateKWLoc, Name)) {
John McCalla0097262009-12-11 02:10:03 +00002520 SkipUntil(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002521 return nullptr;
John McCalla0097262009-12-11 02:10:03 +00002522 }
2523
2524 // TODO: recover from mistakenly-qualified operator declarations.
Alp Toker383d2c42014-01-01 03:08:43 +00002525 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
2526 "access declaration")) {
2527 SkipUntil(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002528 return nullptr;
Alp Toker383d2c42014-01-01 03:08:43 +00002529 }
John McCalla0097262009-12-11 02:10:03 +00002530
Richard Smithc08b6932018-04-27 02:00:13 +00002531 // FIXME: We should do something with the 'template' keyword here.
Alexey Bataev05c25d62015-07-31 08:42:25 +00002532 return DeclGroupPtrTy::make(DeclGroupRef(Actions.ActOnUsingDeclaration(
Richard Smith151c4562016-12-20 21:35:28 +00002533 getCurScope(), AS, /*UsingLoc*/ SourceLocation(),
2534 /*TypenameLoc*/ SourceLocation(), SS, Name,
Erich Keanec480f302018-07-12 21:09:05 +00002535 /*EllipsisLoc*/ SourceLocation(),
2536 /*AttrList*/ ParsedAttributesView())));
John McCalla0097262009-12-11 02:10:03 +00002537 }
2538 }
2539
Aaron Ballmane7c544d2014-08-04 20:28:35 +00002540 // static_assert-declaration. A templated static_assert declaration is
2541 // diagnosed in Parser::ParseSingleDeclarationAfterTemplate.
2542 if (!TemplateInfo.Kind &&
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002543 Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert)) {
Chris Lattner49836b42009-04-02 04:16:50 +00002544 SourceLocation DeclEnd;
Alexey Bataev05c25d62015-07-31 08:42:25 +00002545 return DeclGroupPtrTy::make(
2546 DeclGroupRef(ParseStaticAssertDeclaration(DeclEnd)));
Chris Lattner5bbb3c82009-03-29 16:50:03 +00002547 }
Mike Stump11289f42009-09-09 15:08:12 +00002548
Chris Lattner5bbb3c82009-03-29 16:50:03 +00002549 if (Tok.is(tok::kw_template)) {
Mike Stump11289f42009-09-09 15:08:12 +00002550 assert(!TemplateInfo.TemplateParams &&
Douglas Gregor3447e762009-08-20 22:52:58 +00002551 "Nested template improperly parsed?");
Richard Smith3af70092017-02-09 22:14:25 +00002552 ObjCDeclContextSwitch ObjCDC(*this);
Chris Lattner49836b42009-04-02 04:16:50 +00002553 SourceLocation DeclEnd;
Alexey Bataev05c25d62015-07-31 08:42:25 +00002554 return DeclGroupPtrTy::make(
Richard Smith3af70092017-02-09 22:14:25 +00002555 DeclGroupRef(ParseTemplateDeclarationOrSpecialization(
Erich Keanec480f302018-07-12 21:09:05 +00002556 DeclaratorContext::MemberContext, DeclEnd, AccessAttrs, AS)));
Chris Lattner5bbb3c82009-03-29 16:50:03 +00002557 }
Anders Carlssondfbbdf62009-03-26 00:52:18 +00002558
Chris Lattnerd19c1c02008-12-18 01:12:00 +00002559 // Handle: member-declaration ::= '__extension__' member-declaration
2560 if (Tok.is(tok::kw___extension__)) {
2561 // __extension__ silences extension warnings in the subexpression.
2562 ExtensionRAIIObject O(Diags); // Use RAII to do this.
2563 ConsumeToken();
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00002564 return ParseCXXClassMemberDeclaration(AS, AccessAttrs,
2565 TemplateInfo, TemplateDiags);
Chris Lattnerd19c1c02008-12-18 01:12:00 +00002566 }
Douglas Gregorfec52632009-06-20 00:51:54 +00002567
John McCall084e83d2011-03-24 11:26:52 +00002568 ParsedAttributesWithRange attrs(AttrFactory);
Erich Keanec480f302018-07-12 21:09:05 +00002569 ParsedAttributesViewWithRange FnAttrs;
Richard Smith89645bc2013-01-02 12:01:23 +00002570 // Optional C++11 attribute-specifier
2571 MaybeParseCXX11Attributes(attrs);
Michael Handdc016d2012-11-28 23:17:40 +00002572 // We need to keep these attributes for future diagnostic
2573 // before they are taken over by declaration specifier.
Erich Keanec480f302018-07-12 21:09:05 +00002574 FnAttrs.addAll(attrs.begin(), attrs.end());
Michael Handdc016d2012-11-28 23:17:40 +00002575 FnAttrs.Range = attrs.Range;
2576
John McCall53fa7142010-12-24 02:08:15 +00002577 MaybeParseMicrosoftAttributes(attrs);
Alexis Hunt96d5c762009-11-21 08:43:09 +00002578
Douglas Gregorfec52632009-06-20 00:51:54 +00002579 if (Tok.is(tok::kw_using)) {
John McCall53fa7142010-12-24 02:08:15 +00002580 ProhibitAttributes(attrs);
Mike Stump11289f42009-09-09 15:08:12 +00002581
Douglas Gregorfec52632009-06-20 00:51:54 +00002582 // Eat 'using'.
2583 SourceLocation UsingLoc = ConsumeToken();
2584
Richard Trieu2efd3052019-05-01 23:33:49 +00002585 // Consume unexpected 'template' keywords.
2586 while (Tok.is(tok::kw_template)) {
2587 SourceLocation TemplateLoc = ConsumeToken();
2588 Diag(TemplateLoc, diag::err_unexpected_template_after_using)
2589 << FixItHint::CreateRemoval(TemplateLoc);
2590 }
2591
Douglas Gregorfec52632009-06-20 00:51:54 +00002592 if (Tok.is(tok::kw_namespace)) {
2593 Diag(UsingLoc, diag::err_using_namespace_in_class);
Alexey Bataevee6507d2013-11-18 08:17:37 +00002594 SkipUntil(tok::semi, StopBeforeMatch);
David Blaikie0403cb12016-01-15 23:43:25 +00002595 return nullptr;
Douglas Gregorfec52632009-06-20 00:51:54 +00002596 }
Alexey Bataev05c25d62015-07-31 08:42:25 +00002597 SourceLocation DeclEnd;
2598 // Otherwise, it must be a using-declaration or an alias-declaration.
Faisal Vali421b2d12017-12-29 05:41:00 +00002599 return ParseUsingDeclaration(DeclaratorContext::MemberContext, TemplateInfo,
Richard Smith6f1daa42016-12-16 00:58:48 +00002600 UsingLoc, DeclEnd, AS);
Douglas Gregorfec52632009-06-20 00:51:54 +00002601 }
2602
DeLesley Hutchinsbd2ee132012-03-02 22:12:59 +00002603 // Hold late-parsed attributes so we can attach a Decl to them later.
2604 LateParsedAttrList CommonLateParsedAttrs;
2605
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002606 // decl-specifier-seq:
2607 // Parse the common declaration-specifiers piece.
John McCall796c2a52010-07-16 08:13:16 +00002608 ParsingDeclSpec DS(*this, TemplateDiags);
John McCall53fa7142010-12-24 02:08:15 +00002609 DS.takeAttributesFrom(attrs);
Richard Smith45855df2012-05-09 08:23:23 +00002610 if (MalformedTypeSpec)
2611 DS.SetTypeSpecError();
Richard Smith72553fc2014-01-23 23:53:27 +00002612
Faisal Valia534f072018-04-26 00:42:40 +00002613 ParseDeclarationSpecifiers(DS, TemplateInfo, AS, DeclSpecContext::DSC_class,
2614 &CommonLateParsedAttrs);
Serge Pavlov458ea762014-07-16 05:16:52 +00002615
2616 // Turn off colon protection that was set for declspec.
2617 X.restore();
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002618
Richard Smith404dfb42013-11-19 22:47:36 +00002619 // If we had a free-standing type definition with a missing semicolon, we
2620 // may get this far before the problem becomes obvious.
2621 if (DS.hasTagDefinition() &&
2622 TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate &&
Faisal Vali7db85c52017-12-31 00:06:40 +00002623 DiagnoseMissingSemiAfterTagDefinition(DS, AS, DeclSpecContext::DSC_class,
Richard Smith404dfb42013-11-19 22:47:36 +00002624 &CommonLateParsedAttrs))
David Blaikie0403cb12016-01-15 23:43:25 +00002625 return nullptr;
Richard Smith404dfb42013-11-19 22:47:36 +00002626
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002627 MultiTemplateParamsArg TemplateParams(
Craig Topper161e4db2014-05-21 06:02:52 +00002628 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->data()
2629 : nullptr,
John McCall11083da2009-09-16 22:47:08 +00002630 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->size() : 0);
2631
Alp Toker35d87032013-12-30 23:29:50 +00002632 if (TryConsumeToken(tok::semi)) {
Michael Handdc016d2012-11-28 23:17:40 +00002633 if (DS.isFriendSpecified())
2634 ProhibitAttributes(FnAttrs);
2635
Nico Weber7b837f52016-01-28 19:25:00 +00002636 RecordDecl *AnonRecord = nullptr;
2637 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(
2638 getCurScope(), AS, DS, TemplateParams, false, AnonRecord);
John McCall796c2a52010-07-16 08:13:16 +00002639 DS.complete(TheDecl);
Nico Weber7b837f52016-01-28 19:25:00 +00002640 if (AnonRecord) {
2641 Decl* decls[] = {AnonRecord, TheDecl};
Richard Smith3beb7c62017-01-12 02:27:38 +00002642 return Actions.BuildDeclaratorGroup(decls);
Nico Weber7b837f52016-01-28 19:25:00 +00002643 }
2644 return Actions.ConvertDeclToDeclGroup(TheDecl);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002645 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002646
Faisal Vali421b2d12017-12-29 05:41:00 +00002647 ParsingDeclarator DeclaratorInfo(*this, DS, DeclaratorContext::MemberContext);
Saar Razb481f022020-01-22 02:03:05 +02002648 if (TemplateInfo.TemplateParams)
2649 DeclaratorInfo.setTemplateParameterLists(TemplateParams);
Nico Weber24b2a822011-01-28 06:07:34 +00002650 VirtSpecifiers VS;
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002651
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002652 // Hold late-parsed attributes so we can attach a Decl to them later.
2653 LateParsedAttrList LateParsedAttrs;
2654
Douglas Gregor50cefbf2011-10-17 17:09:53 +00002655 SourceLocation EqualLoc;
Richard Smith9ba0fec2015-06-30 01:28:56 +00002656 SourceLocation PureSpecLoc;
2657
Yaron Keren180c1672015-06-30 07:35:19 +00002658 auto TryConsumePureSpecifier = [&] (bool AllowDefinition) {
Richard Smith9ba0fec2015-06-30 01:28:56 +00002659 if (Tok.isNot(tok::equal))
2660 return false;
2661
2662 auto &Zero = NextToken();
2663 SmallString<8> Buffer;
Richard Smithced76172020-03-20 18:44:13 -07002664 if (Zero.isNot(tok::numeric_constant) ||
Richard Smith9ba0fec2015-06-30 01:28:56 +00002665 PP.getSpelling(Zero, Buffer) != "0")
2666 return false;
2667
2668 auto &After = GetLookAheadToken(2);
2669 if (!After.isOneOf(tok::semi, tok::comma) &&
2670 !(AllowDefinition &&
2671 After.isOneOf(tok::l_brace, tok::colon, tok::kw_try)))
2672 return false;
2673
2674 EqualLoc = ConsumeToken();
2675 PureSpecLoc = ConsumeToken();
2676 return true;
2677 };
Chris Lattner17c3b1f2009-12-10 01:59:24 +00002678
Richard Smith72553fc2014-01-23 23:53:27 +00002679 SmallVector<Decl *, 8> DeclsInGroup;
2680 ExprResult BitfieldSize;
Saar Razb65b1f32020-01-09 15:07:51 +02002681 ExprResult TrailingRequiresClause;
Richard Smith72553fc2014-01-23 23:53:27 +00002682 bool ExpectSemi = true;
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002683
Richard Smith72553fc2014-01-23 23:53:27 +00002684 // Parse the first declarator.
Nico Weberd89e6f72015-01-16 19:34:13 +00002685 if (ParseCXXMemberDeclaratorBeforeInitializer(
2686 DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs)) {
Richard Smith72553fc2014-01-23 23:53:27 +00002687 TryConsumeToken(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002688 return nullptr;
Richard Smith72553fc2014-01-23 23:53:27 +00002689 }
John Thompson5bc5cbe2009-11-25 22:58:06 +00002690
Richard Smith72553fc2014-01-23 23:53:27 +00002691 // Check for a member function definition.
Richard Smith4b5a9492014-01-24 22:34:35 +00002692 if (BitfieldSize.isUnset()) {
Richard Smith72553fc2014-01-23 23:53:27 +00002693 // MSVC permits pure specifier on inline functions defined at class scope.
Francois Pichet3abc9b82011-05-11 02:14:46 +00002694 // Hence check for =0 before checking for function definition.
Richard Smith9ba0fec2015-06-30 01:28:56 +00002695 if (getLangOpts().MicrosoftExt && DeclaratorInfo.isDeclarationOfFunction())
2696 TryConsumePureSpecifier(/*AllowDefinition*/ true);
Francois Pichet3abc9b82011-05-11 02:14:46 +00002697
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00002698 FunctionDefinitionKind DefinitionKind = FDK_Declaration;
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002699 // function-definition:
Richard Smith938f40b2011-06-11 17:19:42 +00002700 //
2701 // In C++11, a non-function declarator followed by an open brace is a
2702 // braced-init-list for an in-class member initialization, not an
2703 // erroneous function definition.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002704 if (Tok.is(tok::l_brace) && !getLangOpts().CPlusPlus11) {
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00002705 DefinitionKind = FDK_Definition;
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002706 } else if (DeclaratorInfo.isFunctionDeclarator()) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002707 if (Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try)) {
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00002708 DefinitionKind = FDK_Definition;
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002709 } else if (Tok.is(tok::equal)) {
2710 const Token &KW = NextToken();
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00002711 if (KW.is(tok::kw_default))
2712 DefinitionKind = FDK_Defaulted;
2713 else if (KW.is(tok::kw_delete))
2714 DefinitionKind = FDK_Deleted;
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002715 }
2716 }
Eli Bendersky41842222015-03-23 23:49:41 +00002717 DeclaratorInfo.setFunctionDefinitionKind(DefinitionKind);
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002718
Fangrui Song6907ce22018-07-30 19:24:48 +00002719 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
Michael Handdc016d2012-11-28 23:17:40 +00002720 // to a friend declaration, that declaration shall be a definition.
Fangrui Song6907ce22018-07-30 19:24:48 +00002721 if (DeclaratorInfo.isFunctionDeclarator() &&
Richard Smith5ae65542020-01-30 17:42:17 -08002722 DefinitionKind == FDK_Declaration && DS.isFriendSpecified()) {
Michael Handdc016d2012-11-28 23:17:40 +00002723 // Diagnose attributes that appear before decl specifier:
2724 // [[]] friend int foo();
2725 ProhibitAttributes(FnAttrs);
2726 }
2727
Nico Webera7f137d2015-01-16 19:35:01 +00002728 if (DefinitionKind != FDK_Declaration) {
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002729 if (!DeclaratorInfo.isFunctionDeclarator()) {
Richard Trieu0d730542012-01-21 02:59:18 +00002730 Diag(DeclaratorInfo.getIdentifierLoc(), diag::err_func_def_no_params);
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002731 ConsumeBrace();
Alexey Bataevee6507d2013-11-18 08:17:37 +00002732 SkipUntil(tok::r_brace);
Michael Handdc016d2012-11-28 23:17:40 +00002733
Douglas Gregor8a4db832011-01-19 16:41:58 +00002734 // Consume the optional ';'
Alp Toker35d87032013-12-30 23:29:50 +00002735 TryConsumeToken(tok::semi);
2736
David Blaikie0403cb12016-01-15 23:43:25 +00002737 return nullptr;
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002738 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002739
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002740 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
Richard Trieu0d730542012-01-21 02:59:18 +00002741 Diag(DeclaratorInfo.getIdentifierLoc(),
2742 diag::err_function_declared_typedef);
Douglas Gregor8a4db832011-01-19 16:41:58 +00002743
Richard Smith2603b092012-11-15 22:54:20 +00002744 // Recover by treating the 'typedef' as spurious.
2745 DS.ClearStorageClassSpecs();
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002746 }
2747
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002748 Decl *FunDecl =
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00002749 ParseCXXInlineMethodDef(AS, AccessAttrs, DeclaratorInfo, TemplateInfo,
Richard Smith9ba0fec2015-06-30 01:28:56 +00002750 VS, PureSpecLoc);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002751
David Majnemer23252a32013-08-01 04:22:55 +00002752 if (FunDecl) {
2753 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i) {
2754 CommonLateParsedAttrs[i]->addDecl(FunDecl);
2755 }
2756 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i) {
2757 LateParsedAttrs[i]->addDecl(FunDecl);
2758 }
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002759 }
2760 LateParsedAttrs.clear();
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002761
2762 // Consume the ';' - it's optional unless we have a delete or default
Richard Trieu2f7dc462012-05-16 19:04:59 +00002763 if (Tok.is(tok::semi))
Richard Smith87f5dc52012-07-23 05:45:25 +00002764 ConsumeExtraSemi(AfterMemberFunctionDefinition);
Douglas Gregor8a4db832011-01-19 16:41:58 +00002765
Alexey Bataev05c25d62015-07-31 08:42:25 +00002766 return DeclGroupPtrTy::make(DeclGroupRef(FunDecl));
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002767 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002768 }
2769
2770 // member-declarator-list:
2771 // member-declarator
2772 // member-declarator-list ',' member-declarator
2773
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002774 while (1) {
Richard Smith2b013182012-06-10 03:12:00 +00002775 InClassInitStyle HasInClassInit = ICIS_NoInit;
Richard Smith9ba0fec2015-06-30 01:28:56 +00002776 bool HasStaticInitializer = false;
2777 if (Tok.isOneOf(tok::equal, tok::l_brace) && PureSpecLoc.isInvalid()) {
Richard Smith6b8e3c02017-08-28 00:28:14 +00002778 if (DeclaratorInfo.isDeclarationOfFunction()) {
Richard Smith9ba0fec2015-06-30 01:28:56 +00002779 // It's a pure-specifier.
2780 if (!TryConsumePureSpecifier(/*AllowFunctionDefinition*/ false))
2781 // Parse it as an expression so that Sema can diagnose it.
2782 HasStaticInitializer = true;
2783 } else if (DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2784 DeclSpec::SCS_static &&
2785 DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2786 DeclSpec::SCS_typedef &&
2787 !DS.isFriendSpecified()) {
2788 // It's a default member initializer.
Richard Smith6b8e3c02017-08-28 00:28:14 +00002789 if (BitfieldSize.get())
Aaron Ballman6a308942020-04-21 15:37:19 -04002790 Diag(Tok, getLangOpts().CPlusPlus20
Richard Smith6b8e3c02017-08-28 00:28:14 +00002791 ? diag::warn_cxx17_compat_bitfield_member_init
2792 : diag::ext_bitfield_member_init);
Richard Smith9ba0fec2015-06-30 01:28:56 +00002793 HasInClassInit = Tok.is(tok::equal) ? ICIS_CopyInit : ICIS_ListInit;
Richard Smith938f40b2011-06-11 17:19:42 +00002794 } else {
Richard Smith9ba0fec2015-06-30 01:28:56 +00002795 HasStaticInitializer = true;
Richard Smith938f40b2011-06-11 17:19:42 +00002796 }
2797 }
2798
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002799 // NOTE: If Sema is the Action module and declarator is an instance field,
Chris Lattner5bbb3c82009-03-29 16:50:03 +00002800 // this call will *not* return the created decl; It will return null.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002801 // See Sema::ActOnCXXMemberDeclarator for details.
John McCall07e91c02009-08-06 02:15:43 +00002802
Craig Topper161e4db2014-05-21 06:02:52 +00002803 NamedDecl *ThisDecl = nullptr;
John McCall07e91c02009-08-06 02:15:43 +00002804 if (DS.isFriendSpecified()) {
Richard Smith72553fc2014-01-23 23:53:27 +00002805 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
Michael Handdc016d2012-11-28 23:17:40 +00002806 // to a friend declaration, that declaration shall be a definition.
2807 //
Richard Smith72553fc2014-01-23 23:53:27 +00002808 // Diagnose attributes that appear in a friend member function declarator:
2809 // friend int foo [[]] ();
Michael Handdc016d2012-11-28 23:17:40 +00002810 SmallVector<SourceRange, 4> Ranges;
2811 DeclaratorInfo.getCXX11AttributeRanges(Ranges);
Richard Smith72553fc2014-01-23 23:53:27 +00002812 for (SmallVectorImpl<SourceRange>::iterator I = Ranges.begin(),
2813 E = Ranges.end(); I != E; ++I)
2814 Diag((*I).getBegin(), diag::err_attributes_not_allowed) << *I;
Michael Handdc016d2012-11-28 23:17:40 +00002815
Douglas Gregor0be31a22010-07-02 17:43:08 +00002816 ThisDecl = Actions.ActOnFriendFunctionDecl(getCurScope(), DeclaratorInfo,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002817 TemplateParams);
Douglas Gregor3447e762009-08-20 22:52:58 +00002818 } else {
Douglas Gregor0be31a22010-07-02 17:43:08 +00002819 ThisDecl = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS,
John McCall07e91c02009-08-06 02:15:43 +00002820 DeclaratorInfo,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002821 TemplateParams,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002822 BitfieldSize.get(),
Richard Smith2b013182012-06-10 03:12:00 +00002823 VS, HasInClassInit);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002824
2825 if (VarTemplateDecl *VT =
Craig Topper161e4db2014-05-21 06:02:52 +00002826 ThisDecl ? dyn_cast<VarTemplateDecl>(ThisDecl) : nullptr)
Larisse Voufo39a1e502013-08-06 01:03:05 +00002827 // Re-direct this decl to refer to the templated decl so that we can
2828 // initialize it.
2829 ThisDecl = VT->getTemplatedDecl();
2830
Erich Keanec480f302018-07-12 21:09:05 +00002831 if (ThisDecl)
Richard Smithf8a75c32013-08-29 00:47:48 +00002832 Actions.ProcessDeclAttributeList(getCurScope(), ThisDecl, AccessAttrs);
Douglas Gregor3447e762009-08-20 22:52:58 +00002833 }
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002834
Richard Smith9ba0fec2015-06-30 01:28:56 +00002835 // Error recovery might have converted a non-static member into a static
2836 // member.
David Blaikie35506f82013-01-30 01:22:18 +00002837 if (HasInClassInit != ICIS_NoInit &&
Richard Smith9ba0fec2015-06-30 01:28:56 +00002838 DeclaratorInfo.getDeclSpec().getStorageClassSpec() ==
2839 DeclSpec::SCS_static) {
2840 HasInClassInit = ICIS_NoInit;
2841 HasStaticInitializer = true;
2842 }
2843
2844 if (ThisDecl && PureSpecLoc.isValid())
2845 Actions.ActOnPureSpecifier(ThisDecl, PureSpecLoc);
2846
2847 // Handle the initializer.
2848 if (HasInClassInit != ICIS_NoInit) {
Douglas Gregor728d00b2011-10-10 14:49:18 +00002849 // The initializer was deferred; parse it and cache the tokens.
David Majnemer23252a32013-08-01 04:22:55 +00002850 Diag(Tok, getLangOpts().CPlusPlus11
2851 ? diag::warn_cxx98_compat_nonstatic_member_init
2852 : diag::ext_nonstatic_member_init);
Richard Smith5d164bc2011-10-15 05:09:34 +00002853
Richard Smith938f40b2011-06-11 17:19:42 +00002854 if (DeclaratorInfo.isArrayOfUnknownBound()) {
Richard Smith2b013182012-06-10 03:12:00 +00002855 // C++11 [dcl.array]p3: An array bound may also be omitted when the
2856 // declarator is followed by an initializer.
Richard Smith938f40b2011-06-11 17:19:42 +00002857 //
2858 // A brace-or-equal-initializer for a member-declarator is not an
David Blaikiecdd91db2012-02-14 09:00:46 +00002859 // initializer in the grammar, so this is ill-formed.
Richard Smith938f40b2011-06-11 17:19:42 +00002860 Diag(Tok, diag::err_incomplete_array_member_init);
Alexey Bataevee6507d2013-11-18 08:17:37 +00002861 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
David Majnemer23252a32013-08-01 04:22:55 +00002862
2863 // Avoid later warnings about a class member of incomplete type.
David Blaikiecdd91db2012-02-14 09:00:46 +00002864 if (ThisDecl)
David Blaikiecdd91db2012-02-14 09:00:46 +00002865 ThisDecl->setInvalidDecl();
Richard Smith938f40b2011-06-11 17:19:42 +00002866 } else
2867 ParseCXXNonStaticMemberInitializer(ThisDecl);
Richard Smith9ba0fec2015-06-30 01:28:56 +00002868 } else if (HasStaticInitializer) {
Douglas Gregor728d00b2011-10-10 14:49:18 +00002869 // Normal initializer.
Richard Smith9ba0fec2015-06-30 01:28:56 +00002870 ExprResult Init = ParseCXXMemberInitializer(
2871 ThisDecl, DeclaratorInfo.isDeclarationOfFunction(), EqualLoc);
David Majnemer23252a32013-08-01 04:22:55 +00002872
Douglas Gregor728d00b2011-10-10 14:49:18 +00002873 if (Init.isInvalid())
Alexey Bataevee6507d2013-11-18 08:17:37 +00002874 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
Douglas Gregor728d00b2011-10-10 14:49:18 +00002875 else if (ThisDecl)
Richard Smith3beb7c62017-01-12 02:27:38 +00002876 Actions.AddInitializerToDecl(ThisDecl, Init.get(), EqualLoc.isInvalid());
David Majnemer23252a32013-08-01 04:22:55 +00002877 } else if (ThisDecl && DS.getStorageClassSpec() == DeclSpec::SCS_static)
Douglas Gregor728d00b2011-10-10 14:49:18 +00002878 // No initializer.
Richard Smith3beb7c62017-01-12 02:27:38 +00002879 Actions.ActOnUninitializedDecl(ThisDecl);
David Majnemer23252a32013-08-01 04:22:55 +00002880
Douglas Gregor728d00b2011-10-10 14:49:18 +00002881 if (ThisDecl) {
David Majnemer23252a32013-08-01 04:22:55 +00002882 if (!ThisDecl->isInvalidDecl()) {
2883 // Set the Decl for any late parsed attributes
2884 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i)
2885 CommonLateParsedAttrs[i]->addDecl(ThisDecl);
2886
2887 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i)
2888 LateParsedAttrs[i]->addDecl(ThisDecl);
2889 }
Douglas Gregor728d00b2011-10-10 14:49:18 +00002890 Actions.FinalizeDeclaration(ThisDecl);
2891 DeclsInGroup.push_back(ThisDecl);
David Majnemer23252a32013-08-01 04:22:55 +00002892
2893 if (DeclaratorInfo.isFunctionDeclarator() &&
2894 DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2895 DeclSpec::SCS_typedef)
2896 HandleMemberFunctionDeclDelays(DeclaratorInfo, ThisDecl);
Douglas Gregor728d00b2011-10-10 14:49:18 +00002897 }
David Majnemer23252a32013-08-01 04:22:55 +00002898 LateParsedAttrs.clear();
Douglas Gregor728d00b2011-10-10 14:49:18 +00002899
2900 DeclaratorInfo.complete(ThisDecl);
Richard Smith938f40b2011-06-11 17:19:42 +00002901
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002902 // If we don't have a comma, it is either the end of the list (a ';')
2903 // or an error, bail out.
Alp Toker094e5212014-01-05 03:27:11 +00002904 SourceLocation CommaLoc;
2905 if (!TryConsumeToken(tok::comma, CommaLoc))
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002906 break;
Mike Stump11289f42009-09-09 15:08:12 +00002907
Richard Smithc8a79032012-01-09 22:31:44 +00002908 if (Tok.isAtStartOfLine() &&
Faisal Vali421b2d12017-12-29 05:41:00 +00002909 !MightBeDeclarator(DeclaratorContext::MemberContext)) {
Richard Smithc8a79032012-01-09 22:31:44 +00002910 // This comma was followed by a line-break and something which can't be
2911 // the start of a declarator. The comma was probably a typo for a
2912 // semicolon.
2913 Diag(CommaLoc, diag::err_expected_semi_declaration)
2914 << FixItHint::CreateReplacement(CommaLoc, ";");
2915 ExpectSemi = false;
2916 break;
2917 }
Mike Stump11289f42009-09-09 15:08:12 +00002918
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002919 // Parse the next declarator.
2920 DeclaratorInfo.clear();
Nico Weber24b2a822011-01-28 06:07:34 +00002921 VS.clear();
Nico Weberf56c85b2015-01-17 02:26:40 +00002922 BitfieldSize = ExprResult(/*Invalid=*/false);
Richard Smith9ba0fec2015-06-30 01:28:56 +00002923 EqualLoc = PureSpecLoc = SourceLocation();
Richard Smith8d06f422012-01-12 23:53:29 +00002924 DeclaratorInfo.setCommaLoc(CommaLoc);
Mike Stump11289f42009-09-09 15:08:12 +00002925
Richard Smith72553fc2014-01-23 23:53:27 +00002926 // GNU attributes are allowed before the second and subsequent declarator.
John McCall53fa7142010-12-24 02:08:15 +00002927 MaybeParseGNUAttributes(DeclaratorInfo);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002928
Nico Weberd89e6f72015-01-16 19:34:13 +00002929 if (ParseCXXMemberDeclaratorBeforeInitializer(
2930 DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs))
2931 break;
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002932 }
2933
Richard Smithc8a79032012-01-09 22:31:44 +00002934 if (ExpectSemi &&
2935 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list)) {
Chris Lattner916dbf12010-02-02 00:43:15 +00002936 // Skip to end of block or statement.
Alexey Bataevee6507d2013-11-18 08:17:37 +00002937 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Chris Lattner916dbf12010-02-02 00:43:15 +00002938 // If we stopped at a ';', eat it.
Alp Toker35d87032013-12-30 23:29:50 +00002939 TryConsumeToken(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002940 return nullptr;
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002941 }
2942
Alexey Bataev05c25d62015-07-31 08:42:25 +00002943 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002944}
2945
Richard Smith9ba0fec2015-06-30 01:28:56 +00002946/// ParseCXXMemberInitializer - Parse the brace-or-equal-initializer.
2947/// Also detect and reject any attempted defaulted/deleted function definition.
2948/// The location of the '=', if any, will be placed in EqualLoc.
Richard Smith938f40b2011-06-11 17:19:42 +00002949///
Richard Smith9ba0fec2015-06-30 01:28:56 +00002950/// This does not check for a pure-specifier; that's handled elsewhere.
Sebastian Redleef474c2012-02-22 10:50:08 +00002951///
Richard Smith938f40b2011-06-11 17:19:42 +00002952/// brace-or-equal-initializer:
2953/// '=' initializer-expression
Sebastian Redleef474c2012-02-22 10:50:08 +00002954/// braced-init-list
2955///
Richard Smith938f40b2011-06-11 17:19:42 +00002956/// initializer-clause:
2957/// assignment-expression
Sebastian Redleef474c2012-02-22 10:50:08 +00002958/// braced-init-list
2959///
Richard Smithda35e962013-11-09 04:52:51 +00002960/// defaulted/deleted function-definition:
Richard Smith938f40b2011-06-11 17:19:42 +00002961/// '=' 'default'
2962/// '=' 'delete'
2963///
2964/// Prior to C++0x, the assignment-expression in an initializer-clause must
2965/// be a constant-expression.
Douglas Gregor926410d2012-02-21 02:22:07 +00002966ExprResult Parser::ParseCXXMemberInitializer(Decl *D, bool IsFunction,
Richard Smith938f40b2011-06-11 17:19:42 +00002967 SourceLocation &EqualLoc) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002968 assert(Tok.isOneOf(tok::equal, tok::l_brace)
Richard Smith938f40b2011-06-11 17:19:42 +00002969 && "Data member initializer not starting with '=' or '{'");
2970
Faisal Valid143a0c2017-04-01 21:30:49 +00002971 EnterExpressionEvaluationContext Context(
2972 Actions, Sema::ExpressionEvaluationContext::PotentiallyEvaluated, D);
Alp Toker094e5212014-01-05 03:27:11 +00002973 if (TryConsumeToken(tok::equal, EqualLoc)) {
Richard Smith938f40b2011-06-11 17:19:42 +00002974 if (Tok.is(tok::kw_delete)) {
2975 // In principle, an initializer of '= delete p;' is legal, but it will
2976 // never type-check. It's better to diagnose it as an ill-formed expression
2977 // than as an ill-formed deleted non-function member.
2978 // An initializer of '= delete p, foo' will never be parsed, because
2979 // a top-level comma always ends the initializer expression.
2980 const Token &Next = NextToken();
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002981 if (IsFunction || Next.isOneOf(tok::semi, tok::comma, tok::eof)) {
Richard Smith938f40b2011-06-11 17:19:42 +00002982 if (IsFunction)
2983 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2984 << 1 /* delete */;
2985 else
2986 Diag(ConsumeToken(), diag::err_deleted_non_function);
Richard Smithedcb26e2014-06-11 00:49:52 +00002987 return ExprError();
Richard Smith938f40b2011-06-11 17:19:42 +00002988 }
2989 } else if (Tok.is(tok::kw_default)) {
Richard Smith938f40b2011-06-11 17:19:42 +00002990 if (IsFunction)
2991 Diag(Tok, diag::err_default_delete_in_multiple_declaration)
2992 << 0 /* default */;
2993 else
Richard Smithd052a5782019-10-22 17:44:08 -07002994 Diag(ConsumeToken(), diag::err_default_special_members)
Aaron Ballman6a308942020-04-21 15:37:19 -04002995 << getLangOpts().CPlusPlus20;
Richard Smithedcb26e2014-06-11 00:49:52 +00002996 return ExprError();
Richard Smith938f40b2011-06-11 17:19:42 +00002997 }
David Majnemer87ff66c2014-12-13 11:34:16 +00002998 }
2999 if (const auto *PD = dyn_cast_or_null<MSPropertyDecl>(D)) {
3000 Diag(Tok, diag::err_ms_property_initializer) << PD;
3001 return ExprError();
Sebastian Redleef474c2012-02-22 10:50:08 +00003002 }
3003 return ParseInitializer();
Richard Smith938f40b2011-06-11 17:19:42 +00003004}
3005
Richard Smith65ebb4a2015-03-26 04:09:53 +00003006void Parser::SkipCXXMemberSpecification(SourceLocation RecordLoc,
3007 SourceLocation AttrFixitLoc,
Faisal Vali090da2d2018-01-01 18:23:28 +00003008 unsigned TagType, Decl *TagDecl) {
Richard Smith65ebb4a2015-03-26 04:09:53 +00003009 // Skip the optional 'final' keyword.
3010 if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
3011 assert(isCXX11FinalKeyword() && "not a class definition");
3012 ConsumeToken();
3013
3014 // Diagnose any C++11 attributes after 'final' keyword.
3015 // We deliberately discard these attributes.
3016 ParsedAttributesWithRange Attrs(AttrFactory);
3017 CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
3018
3019 // This can only happen if we had malformed misplaced attributes;
3020 // we only get called if there is a colon or left-brace after the
3021 // attributes.
3022 if (Tok.isNot(tok::colon) && Tok.isNot(tok::l_brace))
3023 return;
3024 }
3025
3026 // Skip the base clauses. This requires actually parsing them, because
3027 // otherwise we can't be sure where they end (a left brace may appear
3028 // within a template argument).
3029 if (Tok.is(tok::colon)) {
3030 // Enter the scope of the class so that we can correctly parse its bases.
3031 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
3032 ParsingClassDefinition ParsingDef(*this, TagDecl, /*NonNestedClass*/ true,
3033 TagType == DeclSpec::TST_interface);
Richard Smith0f192e82015-06-11 22:48:25 +00003034 auto OldContext =
3035 Actions.ActOnTagStartSkippedDefinition(getCurScope(), TagDecl);
Richard Smith65ebb4a2015-03-26 04:09:53 +00003036
3037 // Parse the bases but don't attach them to the class.
3038 ParseBaseClause(nullptr);
3039
Richard Smith0f192e82015-06-11 22:48:25 +00003040 Actions.ActOnTagFinishSkippedDefinition(OldContext);
Richard Smith65ebb4a2015-03-26 04:09:53 +00003041
3042 if (!Tok.is(tok::l_brace)) {
3043 Diag(PP.getLocForEndOfToken(PrevTokLocation),
3044 diag::err_expected_lbrace_after_base_specifiers);
3045 return;
3046 }
3047 }
3048
3049 // Skip the body.
3050 assert(Tok.is(tok::l_brace));
3051 BalancedDelimiterTracker T(*this, tok::l_brace);
3052 T.consumeOpen();
3053 T.skipToEnd();
Richard Smith04c6c1f2015-07-01 18:56:50 +00003054
3055 // Parse and discard any trailing attributes.
3056 ParsedAttributes Attrs(AttrFactory);
3057 if (Tok.is(tok::kw___attribute))
3058 MaybeParseGNUAttributes(Attrs);
Richard Smith65ebb4a2015-03-26 04:09:53 +00003059}
3060
Alexey Bataev05c25d62015-07-31 08:42:25 +00003061Parser::DeclGroupPtrTy Parser::ParseCXXClassMemberDeclarationWithPragmas(
3062 AccessSpecifier &AS, ParsedAttributesWithRange &AccessAttrs,
3063 DeclSpec::TST TagType, Decl *TagDecl) {
Richard Smithbf5bcf22018-06-26 23:20:26 +00003064 ParenBraceBracketBalancer BalancerRAIIObj(*this);
3065
Richard Smithb55f7582017-01-28 01:12:10 +00003066 switch (Tok.getKind()) {
3067 case tok::kw___if_exists:
3068 case tok::kw___if_not_exists:
Erich Keanec480f302018-07-12 21:09:05 +00003069 ParseMicrosoftIfExistsClassDeclaration(TagType, AccessAttrs, AS);
David Blaikie0403cb12016-01-15 23:43:25 +00003070 return nullptr;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003071
Richard Smithb55f7582017-01-28 01:12:10 +00003072 case tok::semi:
3073 // Check for extraneous top-level semicolon.
Alexey Bataev05c25d62015-07-31 08:42:25 +00003074 ConsumeExtraSemi(InsideStruct, TagType);
David Blaikie0403cb12016-01-15 23:43:25 +00003075 return nullptr;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003076
Richard Smithb55f7582017-01-28 01:12:10 +00003077 // Handle pragmas that can appear as member declarations.
3078 case tok::annot_pragma_vis:
Alexey Bataev05c25d62015-07-31 08:42:25 +00003079 HandlePragmaVisibility();
David Blaikie0403cb12016-01-15 23:43:25 +00003080 return nullptr;
Richard Smithb55f7582017-01-28 01:12:10 +00003081 case tok::annot_pragma_pack:
Alexey Bataev05c25d62015-07-31 08:42:25 +00003082 HandlePragmaPack();
David Blaikie0403cb12016-01-15 23:43:25 +00003083 return nullptr;
Richard Smithb55f7582017-01-28 01:12:10 +00003084 case tok::annot_pragma_align:
Alexey Bataev05c25d62015-07-31 08:42:25 +00003085 HandlePragmaAlign();
David Blaikie0403cb12016-01-15 23:43:25 +00003086 return nullptr;
Richard Smithb55f7582017-01-28 01:12:10 +00003087 case tok::annot_pragma_ms_pointers_to_members:
Alexey Bataev05c25d62015-07-31 08:42:25 +00003088 HandlePragmaMSPointersToMembers();
David Blaikie0403cb12016-01-15 23:43:25 +00003089 return nullptr;
Richard Smithb55f7582017-01-28 01:12:10 +00003090 case tok::annot_pragma_ms_pragma:
Alexey Bataev05c25d62015-07-31 08:42:25 +00003091 HandlePragmaMSPragma();
David Blaikie0403cb12016-01-15 23:43:25 +00003092 return nullptr;
Richard Smithb55f7582017-01-28 01:12:10 +00003093 case tok::annot_pragma_ms_vtordisp:
Alexey Bataev3d42f342015-11-20 07:02:57 +00003094 HandlePragmaMSVtorDisp();
David Blaikie0403cb12016-01-15 23:43:25 +00003095 return nullptr;
Richard Smithb256d302017-01-28 01:20:57 +00003096 case tok::annot_pragma_dump:
3097 HandlePragmaDump();
3098 return nullptr;
Alexey Bataev3d42f342015-11-20 07:02:57 +00003099
Richard Smithb55f7582017-01-28 01:12:10 +00003100 case tok::kw_namespace:
3101 // If we see a namespace here, a close brace was missing somewhere.
Alexey Bataev05c25d62015-07-31 08:42:25 +00003102 DiagnoseUnexpectedNamespace(cast<NamedDecl>(TagDecl));
David Blaikie0403cb12016-01-15 23:43:25 +00003103 return nullptr;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003104
Anastasia Stulova948e37c2019-03-25 11:54:02 +00003105 case tok::kw_private:
3106 // FIXME: We don't accept GNU attributes on access specifiers in OpenCL mode
3107 // yet.
3108 if (getLangOpts().OpenCL && !NextToken().is(tok::colon))
3109 return ParseCXXClassMemberDeclaration(AS, AccessAttrs);
3110 LLVM_FALLTHROUGH;
Richard Smithb55f7582017-01-28 01:12:10 +00003111 case tok::kw_public:
Anastasia Stulova948e37c2019-03-25 11:54:02 +00003112 case tok::kw_protected: {
Richard Smithb55f7582017-01-28 01:12:10 +00003113 AccessSpecifier NewAS = getAccessSpecifierIfPresent();
3114 assert(NewAS != AS_none);
Alexey Bataev05c25d62015-07-31 08:42:25 +00003115 // Current token is a C++ access specifier.
3116 AS = NewAS;
3117 SourceLocation ASLoc = Tok.getLocation();
3118 unsigned TokLength = Tok.getLength();
3119 ConsumeToken();
3120 AccessAttrs.clear();
3121 MaybeParseGNUAttributes(AccessAttrs);
3122
3123 SourceLocation EndLoc;
3124 if (TryConsumeToken(tok::colon, EndLoc)) {
3125 } else if (TryConsumeToken(tok::semi, EndLoc)) {
3126 Diag(EndLoc, diag::err_expected)
3127 << tok::colon << FixItHint::CreateReplacement(EndLoc, ":");
3128 } else {
3129 EndLoc = ASLoc.getLocWithOffset(TokLength);
3130 Diag(EndLoc, diag::err_expected)
3131 << tok::colon << FixItHint::CreateInsertion(EndLoc, ":");
3132 }
3133
3134 // The Microsoft extension __interface does not permit non-public
3135 // access specifiers.
3136 if (TagType == DeclSpec::TST_interface && AS != AS_public) {
3137 Diag(ASLoc, diag::err_access_specifier_interface) << (AS == AS_protected);
3138 }
3139
Erich Keanec480f302018-07-12 21:09:05 +00003140 if (Actions.ActOnAccessSpecifier(NewAS, ASLoc, EndLoc, AccessAttrs)) {
Alexey Bataev05c25d62015-07-31 08:42:25 +00003141 // found another attribute than only annotations
3142 AccessAttrs.clear();
3143 }
3144
David Blaikie0403cb12016-01-15 23:43:25 +00003145 return nullptr;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003146 }
3147
Richard Smithb55f7582017-01-28 01:12:10 +00003148 case tok::annot_pragma_openmp:
Alexey Bataevc972f6f2020-01-07 13:39:18 -05003149 return ParseOpenMPDeclarativeDirectiveWithExtDecl(
3150 AS, AccessAttrs, /*Delayed=*/true, TagType, TagDecl);
Alexey Bataev05c25d62015-07-31 08:42:25 +00003151
Richard Smithb55f7582017-01-28 01:12:10 +00003152 default:
Serge Pavlov037861b2019-08-04 10:08:51 +00003153 if (tok::isPragmaAnnotation(Tok.getKind())) {
3154 Diag(Tok.getLocation(), diag::err_pragma_misplaced_in_decl)
3155 << DeclSpec::getSpecifierName(TagType,
3156 Actions.getASTContext().getPrintingPolicy());
3157 ConsumeAnnotationToken();
3158 return nullptr;
3159 }
Erich Keanec480f302018-07-12 21:09:05 +00003160 return ParseCXXClassMemberDeclaration(AS, AccessAttrs);
Richard Smithb55f7582017-01-28 01:12:10 +00003161 }
Alexey Bataev05c25d62015-07-31 08:42:25 +00003162}
3163
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003164/// ParseCXXMemberSpecification - Parse the class definition.
3165///
3166/// member-specification:
3167/// member-declaration member-specification[opt]
3168/// access-specifier ':' member-specification[opt]
3169///
Joao Matose9a3ed42012-08-31 22:18:20 +00003170void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc,
Michael Han309af292013-01-07 16:57:11 +00003171 SourceLocation AttrFixitLoc,
Richard Smith4c96e992013-02-19 23:47:15 +00003172 ParsedAttributesWithRange &Attrs,
Faisal Vali090da2d2018-01-01 18:23:28 +00003173 unsigned TagType, Decl *TagDecl) {
Joao Matose9a3ed42012-08-31 22:18:20 +00003174 assert((TagType == DeclSpec::TST_struct ||
Faisal Vali090da2d2018-01-01 18:23:28 +00003175 TagType == DeclSpec::TST_interface ||
3176 TagType == DeclSpec::TST_union ||
3177 TagType == DeclSpec::TST_class) && "Invalid TagType!");
Joao Matose9a3ed42012-08-31 22:18:20 +00003178
Anton Afanasyevd880de22019-03-30 08:42:48 +00003179 llvm::TimeTraceScope TimeScope("ParseClass", [&]() {
3180 if (auto *TD = dyn_cast_or_null<NamedDecl>(TagDecl))
3181 return TD->getQualifiedNameAsString();
3182 return std::string("<anonymous>");
3183 });
3184
Jordan Rose1e879d82018-03-23 00:07:18 +00003185 PrettyDeclStackTraceEntry CrashInfo(Actions.Context, TagDecl, RecordLoc,
John McCallfaf5fb42010-08-26 23:41:50 +00003186 "parsing struct/union/class body");
Mike Stump11289f42009-09-09 15:08:12 +00003187
Douglas Gregoredf8f392010-01-16 20:52:59 +00003188 // Determine whether this is a non-nested class. Note that local
3189 // classes are *not* considered to be nested classes.
3190 bool NonNestedClass = true;
3191 if (!ClassStack.empty()) {
Douglas Gregor0be31a22010-07-02 17:43:08 +00003192 for (const Scope *S = getCurScope(); S; S = S->getParent()) {
Douglas Gregoredf8f392010-01-16 20:52:59 +00003193 if (S->isClassScope()) {
3194 // We're inside a class scope, so this is a nested class.
3195 NonNestedClass = false;
John McCalldb632ac2012-09-25 07:32:39 +00003196
3197 // The Microsoft extension __interface does not permit nested classes.
3198 if (getCurrentClass().IsInterface) {
3199 Diag(RecordLoc, diag::err_invalid_member_in_interface)
3200 << /*ErrorType=*/6
3201 << (isa<NamedDecl>(TagDecl)
3202 ? cast<NamedDecl>(TagDecl)->getQualifiedNameAsString()
David Blaikieabe1a392014-04-02 05:58:29 +00003203 : "(anonymous)");
John McCalldb632ac2012-09-25 07:32:39 +00003204 }
Douglas Gregoredf8f392010-01-16 20:52:59 +00003205 break;
3206 }
3207
Serge Pavlovd9c0bcf2015-07-14 10:02:10 +00003208 if ((S->getFlags() & Scope::FnScope))
3209 // If we're in a function or function template then this is a local
3210 // class rather than a nested class.
3211 break;
Douglas Gregoredf8f392010-01-16 20:52:59 +00003212 }
3213 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003214
3215 // Enter a scope for the class.
Douglas Gregor658b9552009-01-09 22:42:13 +00003216 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003217
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003218 // Note that we are parsing a new (potentially-nested) class definition.
John McCalldb632ac2012-09-25 07:32:39 +00003219 ParsingClassDefinition ParsingDef(*this, TagDecl, NonNestedClass,
3220 TagType == DeclSpec::TST_interface);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003221
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003222 if (TagDecl)
Douglas Gregor0be31a22010-07-02 17:43:08 +00003223 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
John McCall2d814c32009-12-19 21:48:58 +00003224
Anders Carlssonf9eb63b2011-03-25 14:46:08 +00003225 SourceLocation FinalLoc;
David Majnemera5433082013-10-18 00:33:31 +00003226 bool IsFinalSpelledSealed = false;
Anders Carlssonf9eb63b2011-03-25 14:46:08 +00003227
3228 // Parse the optional 'final' keyword.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003229 if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
David Majnemera5433082013-10-18 00:33:31 +00003230 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier(Tok);
3231 assert((Specifier == VirtSpecifiers::VS_Final ||
Fangrui Song6907ce22018-07-30 19:24:48 +00003232 Specifier == VirtSpecifiers::VS_GNU_Final ||
David Majnemera5433082013-10-18 00:33:31 +00003233 Specifier == VirtSpecifiers::VS_Sealed) &&
3234 "not a class definition");
Richard Smithda261112011-10-15 04:21:46 +00003235 FinalLoc = ConsumeToken();
David Majnemera5433082013-10-18 00:33:31 +00003236 IsFinalSpelledSealed = Specifier == VirtSpecifiers::VS_Sealed;
Anders Carlssonf9eb63b2011-03-25 14:46:08 +00003237
David Majnemera5433082013-10-18 00:33:31 +00003238 if (TagType == DeclSpec::TST_interface)
John McCalldb632ac2012-09-25 07:32:39 +00003239 Diag(FinalLoc, diag::err_override_control_interface)
David Majnemera5433082013-10-18 00:33:31 +00003240 << VirtSpecifiers::getSpecifierName(Specifier);
3241 else if (Specifier == VirtSpecifiers::VS_Final)
3242 Diag(FinalLoc, getLangOpts().CPlusPlus11
3243 ? diag::warn_cxx98_compat_override_control_keyword
3244 : diag::ext_override_control_keyword)
3245 << VirtSpecifiers::getSpecifierName(Specifier);
3246 else if (Specifier == VirtSpecifiers::VS_Sealed)
3247 Diag(FinalLoc, diag::ext_ms_sealed_keyword);
Andrey Bokhanko276055b2016-07-29 10:42:48 +00003248 else if (Specifier == VirtSpecifiers::VS_GNU_Final)
3249 Diag(FinalLoc, diag::ext_warn_gnu_final);
Michael Han9407e502012-11-26 22:54:45 +00003250
Michael Han309af292013-01-07 16:57:11 +00003251 // Parse any C++11 attributes after 'final' keyword.
3252 // These attributes are not allowed to appear here,
3253 // and the only possible place for them to appertain
3254 // to the class would be between class-key and class-name.
Richard Smith4c96e992013-02-19 23:47:15 +00003255 CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
Nico Weber4b4be842014-12-29 06:56:50 +00003256
3257 // ParseClassSpecifier() does only a superficial check for attributes before
3258 // deciding to call this method. For example, for
3259 // `class C final alignas ([l) {` it will decide that this looks like a
3260 // misplaced attribute since it sees `alignas '(' ')'`. But the actual
3261 // attribute parsing code will try to parse the '[' as a constexpr lambda
3262 // and consume enough tokens that the alignas parsing code will eat the
3263 // opening '{'. So bail out if the next token isn't one we expect.
Nico Weber36de3a22014-12-29 21:56:22 +00003264 if (!Tok.is(tok::colon) && !Tok.is(tok::l_brace)) {
3265 if (TagDecl)
3266 Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
Nico Weber4b4be842014-12-29 06:56:50 +00003267 return;
Nico Weber36de3a22014-12-29 21:56:22 +00003268 }
Anders Carlssonf9eb63b2011-03-25 14:46:08 +00003269 }
Anders Carlsson4b63d0e2011-01-22 16:56:46 +00003270
John McCall2d814c32009-12-19 21:48:58 +00003271 if (Tok.is(tok::colon)) {
Erik Verbruggen6524c052017-10-24 13:46:58 +00003272 ParseScope InheritanceScope(this, getCurScope()->getFlags() |
3273 Scope::ClassInheritanceScope);
3274
John McCall2d814c32009-12-19 21:48:58 +00003275 ParseBaseClause(TagDecl);
John McCall2d814c32009-12-19 21:48:58 +00003276 if (!Tok.is(tok::l_brace)) {
Ismail Pazarbasi129c44c2014-09-25 21:13:02 +00003277 bool SuggestFixIt = false;
3278 SourceLocation BraceLoc = PP.getLocForEndOfToken(PrevTokLocation);
3279 if (Tok.isAtStartOfLine()) {
3280 switch (Tok.getKind()) {
3281 case tok::kw_private:
3282 case tok::kw_protected:
3283 case tok::kw_public:
3284 SuggestFixIt = NextToken().getKind() == tok::colon;
3285 break;
3286 case tok::kw_static_assert:
3287 case tok::r_brace:
3288 case tok::kw_using:
3289 // base-clause can have simple-template-id; 'template' can't be there
3290 case tok::kw_template:
3291 SuggestFixIt = true;
3292 break;
3293 case tok::identifier:
3294 SuggestFixIt = isConstructorDeclarator(true);
3295 break;
3296 default:
3297 SuggestFixIt = isCXXSimpleDeclaration(/*AllowForRangeDecl=*/false);
3298 break;
3299 }
3300 }
3301 DiagnosticBuilder LBraceDiag =
3302 Diag(BraceLoc, diag::err_expected_lbrace_after_base_specifiers);
3303 if (SuggestFixIt) {
3304 LBraceDiag << FixItHint::CreateInsertion(BraceLoc, " {");
3305 // Try recovering from missing { after base-clause.
Ilya Biryukov929af672019-05-17 09:32:05 +00003306 PP.EnterToken(Tok, /*IsReinject*/true);
Ismail Pazarbasi129c44c2014-09-25 21:13:02 +00003307 Tok.setKind(tok::l_brace);
3308 } else {
3309 if (TagDecl)
3310 Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
3311 return;
3312 }
John McCall2d814c32009-12-19 21:48:58 +00003313 }
3314 }
3315
3316 assert(Tok.is(tok::l_brace));
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003317 BalancedDelimiterTracker T(*this, tok::l_brace);
3318 T.consumeOpen();
John McCall2d814c32009-12-19 21:48:58 +00003319
John McCall08bede42010-05-28 08:11:17 +00003320 if (TagDecl)
Anders Carlsson30f29442011-03-25 14:31:08 +00003321 Actions.ActOnStartCXXMemberDeclarations(getCurScope(), TagDecl, FinalLoc,
David Majnemera5433082013-10-18 00:33:31 +00003322 IsFinalSpelledSealed,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003323 T.getOpenLocation());
John McCall1c7e6ec2009-12-20 07:58:13 +00003324
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003325 // C++ 11p3: Members of a class defined with the keyword class are private
3326 // by default. Members of a class defined with the keywords struct or union
3327 // are public by default.
3328 AccessSpecifier CurAS;
3329 if (TagType == DeclSpec::TST_class)
3330 CurAS = AS_private;
3331 else
3332 CurAS = AS_public;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003333 ParsedAttributesWithRange AccessAttrs(AttrFactory);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003334
Douglas Gregor9377c822010-06-21 22:31:09 +00003335 if (TagDecl) {
3336 // While we still have something to read, read the member-declarations.
Richard Smith752ada82015-11-17 23:32:01 +00003337 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
3338 Tok.isNot(tok::eof)) {
Douglas Gregor9377c822010-06-21 22:31:09 +00003339 // Each iteration of this loop reads one member-declaration.
Alexey Bataev05c25d62015-07-31 08:42:25 +00003340 ParseCXXClassMemberDeclarationWithPragmas(
3341 CurAS, AccessAttrs, static_cast<DeclSpec::TST>(TagType), TagDecl);
Richard Smith6163aa92020-04-05 23:10:08 -07003342 MaybeDestroyTemplateIds();
Serge Pavlovc4e04a22015-09-19 05:32:57 +00003343 }
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003344 T.consumeClose();
Douglas Gregor9377c822010-06-21 22:31:09 +00003345 } else {
Alexey Bataevee6507d2013-11-18 08:17:37 +00003346 SkipUntil(tok::r_brace);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003347 }
Mike Stump11289f42009-09-09 15:08:12 +00003348
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003349 // If attributes exist after class contents, parse them.
John McCall084e83d2011-03-24 11:26:52 +00003350 ParsedAttributes attrs(AttrFactory);
John McCall53fa7142010-12-24 02:08:15 +00003351 MaybeParseGNUAttributes(attrs);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003352
John McCall08bede42010-05-28 08:11:17 +00003353 if (TagDecl)
Douglas Gregor0be31a22010-07-02 17:43:08 +00003354 Actions.ActOnFinishCXXMemberSpecification(getCurScope(), RecordLoc, TagDecl,
Erich Keanec480f302018-07-12 21:09:05 +00003355 T.getOpenLocation(),
3356 T.getCloseLocation(), attrs);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003357
Douglas Gregor433e0532012-04-16 18:27:27 +00003358 // C++11 [class.mem]p2:
3359 // Within the class member-specification, the class is regarded as complete
Richard Smith0b3a4622014-11-13 20:01:57 +00003360 // within function bodies, default arguments, exception-specifications, and
Douglas Gregor433e0532012-04-16 18:27:27 +00003361 // brace-or-equal-initializers for non-static data members (including such
3362 // things in nested classes).
Douglas Gregor9377c822010-06-21 22:31:09 +00003363 if (TagDecl && NonNestedClass) {
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003364 // We are not inside a nested class. This class and its nested classes
Douglas Gregor4d87df52008-12-16 21:30:33 +00003365 // are complete and we can parse the delayed portions of method
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00003366 // declarations and the lexed inline method definitions, along with any
3367 // delayed attributes.
Melanie Blowerf5360d42020-05-01 10:32:06 -07003368
3369 // Save the state of Sema.FPFeatures, and change the setting
3370 // to the levels specified on the command line. Previous level
3371 // will be restored when the RAII object is destroyed.
3372 Sema::FPFeaturesStateRAII SaveFPFeaturesState(Actions);
3373 FPOptions fpOptions(getLangOpts());
3374 Actions.CurFPFeatures.getFromOpaqueInt(fpOptions.getAsOpaqueInt());
3375
Douglas Gregor428119e2010-06-16 23:45:56 +00003376 SourceLocation SavedPrevTokLocation = PrevTokLocation;
Alexey Bataevc972f6f2020-01-07 13:39:18 -05003377 ParseLexedPragmas(getCurrentClass());
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00003378 ParseLexedAttributes(getCurrentClass());
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003379 ParseLexedMethodDeclarations(getCurrentClass());
Richard Smith84973e52012-04-21 18:42:51 +00003380
3381 // We've finished with all pending member declarations.
3382 Actions.ActOnFinishCXXMemberDecls();
3383
Richard Smith938f40b2011-06-11 17:19:42 +00003384 ParseLexedMemberInitializers(getCurrentClass());
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003385 ParseLexedMethodDefs(getCurrentClass());
Douglas Gregor428119e2010-06-16 23:45:56 +00003386 PrevTokLocation = SavedPrevTokLocation;
Reid Klecknerbba3cb92015-03-17 19:00:50 +00003387
3388 // We've finished parsing everything, including default argument
3389 // initializers.
Hans Wennborg92ce2af2019-12-02 16:25:23 +01003390 Actions.ActOnFinishCXXNonNestedClass();
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003391 }
3392
John McCall08bede42010-05-28 08:11:17 +00003393 if (TagDecl)
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00003394 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getRange());
John McCall2ff380a2010-03-17 00:38:33 +00003395
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003396 // Leave the class scope.
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003397 ParsingDef.Pop();
Douglas Gregor7307d6c2008-12-10 06:34:36 +00003398 ClassScope.Exit();
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003399}
Douglas Gregore8381c02008-11-05 04:29:56 +00003400
Richard Smith2ac43ad2013-11-15 23:00:02 +00003401void Parser::DiagnoseUnexpectedNamespace(NamedDecl *D) {
Richard Smithda35e962013-11-09 04:52:51 +00003402 assert(Tok.is(tok::kw_namespace));
3403
3404 // FIXME: Suggest where the close brace should have gone by looking
3405 // at indentation changes within the definition body.
Richard Smith2ac43ad2013-11-15 23:00:02 +00003406 Diag(D->getLocation(),
3407 diag::err_missing_end_of_definition) << D;
Richard Smithda35e962013-11-09 04:52:51 +00003408 Diag(Tok.getLocation(),
Richard Smith2ac43ad2013-11-15 23:00:02 +00003409 diag::note_missing_end_of_definition_before) << D;
Richard Smithda35e962013-11-09 04:52:51 +00003410
3411 // Push '};' onto the token stream to recover.
Ilya Biryukov929af672019-05-17 09:32:05 +00003412 PP.EnterToken(Tok, /*IsReinject*/ true);
Richard Smithda35e962013-11-09 04:52:51 +00003413
3414 Tok.startToken();
3415 Tok.setLocation(PP.getLocForEndOfToken(PrevTokLocation));
3416 Tok.setKind(tok::semi);
Ilya Biryukov929af672019-05-17 09:32:05 +00003417 PP.EnterToken(Tok, /*IsReinject*/ true);
Richard Smithda35e962013-11-09 04:52:51 +00003418
3419 Tok.setKind(tok::r_brace);
3420}
3421
Douglas Gregore8381c02008-11-05 04:29:56 +00003422/// ParseConstructorInitializer - Parse a C++ constructor initializer,
3423/// which explicitly initializes the members or base classes of a
3424/// class (C++ [class.base.init]). For example, the three initializers
3425/// after the ':' in the Derived constructor below:
3426///
3427/// @code
3428/// class Base { };
3429/// class Derived : Base {
3430/// int x;
3431/// float f;
3432/// public:
3433/// Derived(float f) : Base(), x(17), f(f) { }
3434/// };
3435/// @endcode
3436///
Mike Stump11289f42009-09-09 15:08:12 +00003437/// [C++] ctor-initializer:
3438/// ':' mem-initializer-list
Douglas Gregore8381c02008-11-05 04:29:56 +00003439///
Mike Stump11289f42009-09-09 15:08:12 +00003440/// [C++] mem-initializer-list:
Douglas Gregor44e7df62011-01-04 00:32:56 +00003441/// mem-initializer ...[opt]
3442/// mem-initializer ...[opt] , mem-initializer-list
John McCall48871652010-08-21 09:40:31 +00003443void Parser::ParseConstructorInitializer(Decl *ConstructorDecl) {
Nico Weber3b00fdc2015-03-07 19:52:39 +00003444 assert(Tok.is(tok::colon) &&
3445 "Constructor initializer always starts with ':'");
Douglas Gregore8381c02008-11-05 04:29:56 +00003446
Nico Weber3b00fdc2015-03-07 19:52:39 +00003447 // Poison the SEH identifiers so they are flagged as illegal in constructor
3448 // initializers.
John Wiegley1c0675e2011-04-28 01:08:34 +00003449 PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
Douglas Gregore8381c02008-11-05 04:29:56 +00003450 SourceLocation ColonLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +00003451
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003452 SmallVector<CXXCtorInitializer*, 4> MemInitializers;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003453 bool AnyErrors = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003454
Douglas Gregore8381c02008-11-05 04:29:56 +00003455 do {
Douglas Gregoreaeeca92010-08-28 00:00:50 +00003456 if (Tok.is(tok::code_completion)) {
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00003457 Actions.CodeCompleteConstructorInitializer(ConstructorDecl,
3458 MemInitializers);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00003459 return cutOffParsing();
Douglas Gregoreaeeca92010-08-28 00:00:50 +00003460 }
Alexey Bataev79de17d2016-01-20 05:25:51 +00003461
3462 MemInitResult MemInit = ParseMemInitializer(ConstructorDecl);
3463 if (!MemInit.isInvalid())
3464 MemInitializers.push_back(MemInit.get());
3465 else
3466 AnyErrors = true;
3467
Douglas Gregore8381c02008-11-05 04:29:56 +00003468 if (Tok.is(tok::comma))
3469 ConsumeToken();
3470 else if (Tok.is(tok::l_brace))
3471 break;
Alexey Bataev79de17d2016-01-20 05:25:51 +00003472 // If the previous initializer was valid and the next token looks like a
3473 // base or member initializer, assume that we're just missing a comma.
3474 else if (!MemInit.isInvalid() &&
3475 Tok.isOneOf(tok::identifier, tok::coloncolon)) {
Douglas Gregorce66d022010-09-07 14:51:08 +00003476 SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation);
3477 Diag(Loc, diag::err_ctor_init_missing_comma)
3478 << FixItHint::CreateInsertion(Loc, ", ");
3479 } else {
Douglas Gregore8381c02008-11-05 04:29:56 +00003480 // Skip over garbage, until we get to '{'. Don't eat the '{'.
Alexey Bataev79de17d2016-01-20 05:25:51 +00003481 if (!MemInit.isInvalid())
3482 Diag(Tok.getLocation(), diag::err_expected_either) << tok::l_brace
3483 << tok::comma;
Alexey Bataevee6507d2013-11-18 08:17:37 +00003484 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
Douglas Gregore8381c02008-11-05 04:29:56 +00003485 break;
3486 }
3487 } while (true);
3488
David Blaikie3fc2f912013-01-17 05:26:25 +00003489 Actions.ActOnMemInitializers(ConstructorDecl, ColonLoc, MemInitializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003490 AnyErrors);
Douglas Gregore8381c02008-11-05 04:29:56 +00003491}
3492
3493/// ParseMemInitializer - Parse a C++ member initializer, which is
3494/// part of a constructor initializer that explicitly initializes one
3495/// member or base class (C++ [class.base.init]). See
3496/// ParseConstructorInitializer for an example.
3497///
3498/// [C++] mem-initializer:
3499/// mem-initializer-id '(' expression-list[opt] ')'
Sebastian Redl3da34892011-06-05 12:23:16 +00003500/// [C++0x] mem-initializer-id braced-init-list
Mike Stump11289f42009-09-09 15:08:12 +00003501///
Douglas Gregore8381c02008-11-05 04:29:56 +00003502/// [C++] mem-initializer-id:
3503/// '::'[opt] nested-name-specifier[opt] class-name
3504/// identifier
Craig Topper9ad7e262014-10-31 06:57:07 +00003505MemInitResult Parser::ParseMemInitializer(Decl *ConstructorDecl) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00003506 // parse '::'[opt] nested-name-specifier[opt]
3507 CXXScopeSpec SS;
Haojian Wu0dd0b102020-03-19 09:12:29 +01003508 if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
3509 /*ObjectHadErrors=*/false,
3510 /*EnteringContext=*/false))
Richard Smithb23c5e82019-05-09 03:31:27 +00003511 return true;
Richard Smithaf3b3252017-05-18 19:21:48 +00003512
3513 // : identifier
3514 IdentifierInfo *II = nullptr;
3515 SourceLocation IdLoc = Tok.getLocation();
3516 // : declype(...)
3517 DeclSpec DS(AttrFactory);
3518 // : template_name<...>
Richard Smith33087322020-03-30 17:19:30 -07003519 TypeResult TemplateTypeTy;
Richard Smithaf3b3252017-05-18 19:21:48 +00003520
3521 if (Tok.is(tok::identifier)) {
3522 // Get the identifier. This may be a member name or a class name,
3523 // but we'll let the semantic analysis determine which it is.
3524 II = Tok.getIdentifierInfo();
3525 ConsumeToken();
3526 } else if (Tok.is(tok::annot_decltype)) {
3527 // Get the decltype expression, if there is one.
3528 // Uses of decltype will already have been converted to annot_decltype by
3529 // ParseOptionalCXXScopeSpecifier at this point.
3530 // FIXME: Can we get here with a scope specifier?
3531 ParseDecltypeSpecifier(DS);
3532 } else {
3533 TemplateIdAnnotation *TemplateId = Tok.is(tok::annot_template_id)
3534 ? takeTemplateIdAnnotation(Tok)
3535 : nullptr;
Richard Smithb3f6e3d2020-03-27 17:08:26 -07003536 if (TemplateId && TemplateId->mightBeType()) {
Richard Smitha42fd842020-01-17 15:42:11 -08003537 AnnotateTemplateIdTokenAsType(SS, /*IsClassName*/true);
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00003538 assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
John McCallba7bf592010-08-24 05:47:05 +00003539 TemplateTypeTy = getTypeAnnotation(Tok);
Richard Smithaf3b3252017-05-18 19:21:48 +00003540 ConsumeAnnotationToken();
3541 } else {
3542 Diag(Tok, diag::err_expected_member_or_base_name);
3543 return true;
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00003544 }
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00003545 }
Douglas Gregore8381c02008-11-05 04:29:56 +00003546
3547 // Parse the '('.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003548 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
Richard Smith5d164bc2011-10-15 05:09:34 +00003549 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
3550
Kadir Cetinkaya84774c32018-09-11 15:02:18 +00003551 // FIXME: Add support for signature help inside initializer lists.
Sebastian Redla74948d2011-09-24 17:48:25 +00003552 ExprResult InitList = ParseBraceInitializer();
3553 if (InitList.isInvalid())
3554 return true;
3555
3556 SourceLocation EllipsisLoc;
Alp Toker094e5212014-01-05 03:27:11 +00003557 TryConsumeToken(tok::ellipsis, EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00003558
Richard Smith33087322020-03-30 17:19:30 -07003559 if (TemplateTypeTy.isInvalid())
3560 return true;
Sebastian Redla74948d2011-09-24 17:48:25 +00003561 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
Richard Smith33087322020-03-30 17:19:30 -07003562 TemplateTypeTy.get(), DS, IdLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003563 InitList.get(), EllipsisLoc);
Sebastian Redl3da34892011-06-05 12:23:16 +00003564 } else if(Tok.is(tok::l_paren)) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003565 BalancedDelimiterTracker T(*this, tok::l_paren);
3566 T.consumeOpen();
Douglas Gregore8381c02008-11-05 04:29:56 +00003567
Sebastian Redl3da34892011-06-05 12:23:16 +00003568 // Parse the optional expression-list.
Benjamin Kramerf0623432012-08-23 22:51:59 +00003569 ExprVector ArgExprs;
Sebastian Redl3da34892011-06-05 12:23:16 +00003570 CommaLocsTy CommaLocs;
Ilya Biryukovff2a9972019-02-26 11:01:50 +00003571 auto RunSignatureHelp = [&] {
Richard Smith33087322020-03-30 17:19:30 -07003572 if (TemplateTypeTy.isInvalid())
3573 return QualType();
Ilya Biryukovff2a9972019-02-26 11:01:50 +00003574 QualType PreferredType = Actions.ProduceCtorInitMemberSignatureHelp(
Richard Smith33087322020-03-30 17:19:30 -07003575 getCurScope(), ConstructorDecl, SS, TemplateTypeTy.get(), ArgExprs, II,
Ilya Biryukovff2a9972019-02-26 11:01:50 +00003576 T.getOpenLocation());
3577 CalledSignatureHelp = true;
3578 return PreferredType;
3579 };
Kadir Cetinkaya84774c32018-09-11 15:02:18 +00003580 if (Tok.isNot(tok::r_paren) &&
3581 ParseExpressionList(ArgExprs, CommaLocs, [&] {
Ilya Biryukovff2a9972019-02-26 11:01:50 +00003582 PreferredType.enterFunctionArgument(Tok.getLocation(),
3583 RunSignatureHelp);
Kadir Cetinkaya84774c32018-09-11 15:02:18 +00003584 })) {
Ilya Biryukovff2a9972019-02-26 11:01:50 +00003585 if (PP.isCodeCompletionReached() && !CalledSignatureHelp)
3586 RunSignatureHelp();
Alexey Bataevee6507d2013-11-18 08:17:37 +00003587 SkipUntil(tok::r_paren, StopAtSemi);
Sebastian Redl3da34892011-06-05 12:23:16 +00003588 return true;
3589 }
3590
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003591 T.consumeClose();
Sebastian Redl3da34892011-06-05 12:23:16 +00003592
3593 SourceLocation EllipsisLoc;
Alp Toker97650562014-01-10 11:19:30 +00003594 TryConsumeToken(tok::ellipsis, EllipsisLoc);
Sebastian Redl3da34892011-06-05 12:23:16 +00003595
Richard Smith33087322020-03-30 17:19:30 -07003596 if (TemplateTypeTy.isInvalid())
3597 return true;
Sebastian Redl3da34892011-06-05 12:23:16 +00003598 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
Richard Smith33087322020-03-30 17:19:30 -07003599 TemplateTypeTy.get(), DS, IdLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00003600 T.getOpenLocation(), ArgExprs,
3601 T.getCloseLocation(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00003602 }
3603
Richard Smith33087322020-03-30 17:19:30 -07003604 if (TemplateTypeTy.isInvalid())
3605 return true;
3606
Alp Tokerec543272013-12-24 09:48:30 +00003607 if (getLangOpts().CPlusPlus11)
3608 return Diag(Tok, diag::err_expected_either) << tok::l_paren << tok::l_brace;
3609 else
3610 return Diag(Tok, diag::err_expected) << tok::l_paren;
Douglas Gregore8381c02008-11-05 04:29:56 +00003611}
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003612
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003613/// Parse a C++ exception-specification if present (C++0x [except.spec]).
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003614///
Douglas Gregor356513d2008-12-01 18:00:20 +00003615/// exception-specification:
Sebastian Redl965b0e32011-03-05 14:45:16 +00003616/// dynamic-exception-specification
3617/// noexcept-specification
3618///
3619/// noexcept-specification:
3620/// 'noexcept'
3621/// 'noexcept' '(' constant-expression ')'
3622ExceptionSpecificationType
Richard Smith0b3a4622014-11-13 20:01:57 +00003623Parser::tryParseExceptionSpecification(bool Delayed,
Douglas Gregor433e0532012-04-16 18:27:27 +00003624 SourceRange &SpecificationRange,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003625 SmallVectorImpl<ParsedType> &DynamicExceptions,
3626 SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
Richard Smith0b3a4622014-11-13 20:01:57 +00003627 ExprResult &NoexceptExpr,
3628 CachedTokens *&ExceptionSpecTokens) {
Sebastian Redl965b0e32011-03-05 14:45:16 +00003629 ExceptionSpecificationType Result = EST_None;
Hans Wennborgdcfba332015-10-06 23:40:43 +00003630 ExceptionSpecTokens = nullptr;
Fangrui Song6907ce22018-07-30 19:24:48 +00003631
Richard Smith0b3a4622014-11-13 20:01:57 +00003632 // Handle delayed parsing of exception-specifications.
3633 if (Delayed) {
3634 if (Tok.isNot(tok::kw_throw) && Tok.isNot(tok::kw_noexcept))
3635 return EST_None;
Sebastian Redl965b0e32011-03-05 14:45:16 +00003636
Richard Smith0b3a4622014-11-13 20:01:57 +00003637 // Consume and cache the starting token.
3638 bool IsNoexcept = Tok.is(tok::kw_noexcept);
3639 Token StartTok = Tok;
3640 SpecificationRange = SourceRange(ConsumeToken());
3641
3642 // Check for a '('.
3643 if (!Tok.is(tok::l_paren)) {
3644 // If this is a bare 'noexcept', we're done.
3645 if (IsNoexcept) {
3646 Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
Hans Wennborgdcfba332015-10-06 23:40:43 +00003647 NoexceptExpr = nullptr;
Richard Smith0b3a4622014-11-13 20:01:57 +00003648 return EST_BasicNoexcept;
3649 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003650
Richard Smith0b3a4622014-11-13 20:01:57 +00003651 Diag(Tok, diag::err_expected_lparen_after) << "throw";
3652 return EST_DynamicNone;
3653 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003654
Richard Smith0b3a4622014-11-13 20:01:57 +00003655 // Cache the tokens for the exception-specification.
3656 ExceptionSpecTokens = new CachedTokens;
3657 ExceptionSpecTokens->push_back(StartTok); // 'throw' or 'noexcept'
3658 ExceptionSpecTokens->push_back(Tok); // '('
3659 SpecificationRange.setEnd(ConsumeParen()); // '('
Richard Smithb1c217e2015-01-13 02:24:58 +00003660
3661 ConsumeAndStoreUntil(tok::r_paren, *ExceptionSpecTokens,
3662 /*StopAtSemi=*/true,
3663 /*ConsumeFinalToken=*/true);
Aaron Ballman580ccaf2016-01-12 21:04:22 +00003664 SpecificationRange.setEnd(ExceptionSpecTokens->back().getLocation());
3665
Richard Smith0b3a4622014-11-13 20:01:57 +00003666 return EST_Unparsed;
3667 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003668
Sebastian Redl965b0e32011-03-05 14:45:16 +00003669 // See if there's a dynamic specification.
3670 if (Tok.is(tok::kw_throw)) {
3671 Result = ParseDynamicExceptionSpecification(SpecificationRange,
3672 DynamicExceptions,
3673 DynamicExceptionRanges);
3674 assert(DynamicExceptions.size() == DynamicExceptionRanges.size() &&
3675 "Produced different number of exception types and ranges.");
3676 }
3677
3678 // If there's no noexcept specification, we're done.
3679 if (Tok.isNot(tok::kw_noexcept))
3680 return Result;
3681
Richard Smithb15c11c2011-10-17 23:06:20 +00003682 Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
3683
Sebastian Redl965b0e32011-03-05 14:45:16 +00003684 // If we already had a dynamic specification, parse the noexcept for,
3685 // recovery, but emit a diagnostic and don't store the results.
3686 SourceRange NoexceptRange;
3687 ExceptionSpecificationType NoexceptType = EST_None;
3688
3689 SourceLocation KeywordLoc = ConsumeToken();
3690 if (Tok.is(tok::l_paren)) {
3691 // There is an argument.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003692 BalancedDelimiterTracker T(*this, tok::l_paren);
3693 T.consumeOpen();
Sebastian Redl965b0e32011-03-05 14:45:16 +00003694 NoexceptExpr = ParseConstantExpression();
Serge Pavlov3739f5e72015-06-29 17:50:19 +00003695 T.consumeClose();
Serge Pavlov3739f5e72015-06-29 17:50:19 +00003696 if (!NoexceptExpr.isInvalid()) {
Richard Smitheaf11ad2018-05-03 03:58:32 +00003697 NoexceptExpr = Actions.ActOnNoexceptSpec(KeywordLoc, NoexceptExpr.get(),
3698 NoexceptType);
Serge Pavlov3739f5e72015-06-29 17:50:19 +00003699 NoexceptRange = SourceRange(KeywordLoc, T.getCloseLocation());
3700 } else {
Malcolm Parsonsa3220ce2017-01-12 16:11:28 +00003701 NoexceptType = EST_BasicNoexcept;
Serge Pavlov3739f5e72015-06-29 17:50:19 +00003702 }
Sebastian Redl965b0e32011-03-05 14:45:16 +00003703 } else {
3704 // There is no argument.
3705 NoexceptType = EST_BasicNoexcept;
3706 NoexceptRange = SourceRange(KeywordLoc, KeywordLoc);
3707 }
3708
3709 if (Result == EST_None) {
3710 SpecificationRange = NoexceptRange;
3711 Result = NoexceptType;
3712
3713 // If there's a dynamic specification after a noexcept specification,
3714 // parse that and ignore the results.
3715 if (Tok.is(tok::kw_throw)) {
3716 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
3717 ParseDynamicExceptionSpecification(NoexceptRange, DynamicExceptions,
3718 DynamicExceptionRanges);
3719 }
3720 } else {
3721 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
3722 }
3723
3724 return Result;
3725}
3726
Richard Smith8ca78a12013-06-13 02:02:51 +00003727static void diagnoseDynamicExceptionSpecification(
Craig Toppere335f252015-10-04 04:53:55 +00003728 Parser &P, SourceRange Range, bool IsNoexcept) {
Richard Smith8ca78a12013-06-13 02:02:51 +00003729 if (P.getLangOpts().CPlusPlus11) {
3730 const char *Replacement = IsNoexcept ? "noexcept" : "noexcept(false)";
Richard Smith82da19d2016-12-08 02:49:07 +00003731 P.Diag(Range.getBegin(),
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003732 P.getLangOpts().CPlusPlus17 && !IsNoexcept
Richard Smith82da19d2016-12-08 02:49:07 +00003733 ? diag::ext_dynamic_exception_spec
3734 : diag::warn_exception_spec_deprecated)
3735 << Range;
Richard Smith8ca78a12013-06-13 02:02:51 +00003736 P.Diag(Range.getBegin(), diag::note_exception_spec_deprecated)
3737 << Replacement << FixItHint::CreateReplacement(Range, Replacement);
3738 }
3739}
3740
Sebastian Redl965b0e32011-03-05 14:45:16 +00003741/// ParseDynamicExceptionSpecification - Parse a C++
3742/// dynamic-exception-specification (C++ [except.spec]).
3743///
3744/// dynamic-exception-specification:
Douglas Gregor356513d2008-12-01 18:00:20 +00003745/// 'throw' '(' type-id-list [opt] ')'
3746/// [MS] 'throw' '(' '...' ')'
Mike Stump11289f42009-09-09 15:08:12 +00003747///
Douglas Gregor356513d2008-12-01 18:00:20 +00003748/// type-id-list:
Douglas Gregor830837d2010-12-20 23:57:46 +00003749/// type-id ... [opt]
3750/// type-id-list ',' type-id ... [opt]
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003751///
Sebastian Redl965b0e32011-03-05 14:45:16 +00003752ExceptionSpecificationType Parser::ParseDynamicExceptionSpecification(
3753 SourceRange &SpecificationRange,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003754 SmallVectorImpl<ParsedType> &Exceptions,
3755 SmallVectorImpl<SourceRange> &Ranges) {
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003756 assert(Tok.is(tok::kw_throw) && "expected throw");
Mike Stump11289f42009-09-09 15:08:12 +00003757
Sebastian Redl965b0e32011-03-05 14:45:16 +00003758 SpecificationRange.setBegin(ConsumeToken());
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003759 BalancedDelimiterTracker T(*this, tok::l_paren);
3760 if (T.consumeOpen()) {
Sebastian Redl965b0e32011-03-05 14:45:16 +00003761 Diag(Tok, diag::err_expected_lparen_after) << "throw";
3762 SpecificationRange.setEnd(SpecificationRange.getBegin());
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003763 return EST_DynamicNone;
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003764 }
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003765
Douglas Gregor356513d2008-12-01 18:00:20 +00003766 // Parse throw(...), a Microsoft extension that means "this function
3767 // can throw anything".
3768 if (Tok.is(tok::ellipsis)) {
3769 SourceLocation EllipsisLoc = ConsumeToken();
David Blaikiebbafb8a2012-03-11 07:00:24 +00003770 if (!getLangOpts().MicrosoftExt)
Douglas Gregor356513d2008-12-01 18:00:20 +00003771 Diag(EllipsisLoc, diag::ext_ellipsis_exception_spec);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003772 T.consumeClose();
3773 SpecificationRange.setEnd(T.getCloseLocation());
Richard Smith8ca78a12013-06-13 02:02:51 +00003774 diagnoseDynamicExceptionSpecification(*this, SpecificationRange, false);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003775 return EST_MSAny;
Douglas Gregor356513d2008-12-01 18:00:20 +00003776 }
3777
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003778 // Parse the sequence of type-ids.
Sebastian Redld6434562009-05-29 18:02:33 +00003779 SourceRange Range;
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003780 while (Tok.isNot(tok::r_paren)) {
Sebastian Redld6434562009-05-29 18:02:33 +00003781 TypeResult Res(ParseTypeName(&Range));
Sebastian Redl965b0e32011-03-05 14:45:16 +00003782
Douglas Gregor830837d2010-12-20 23:57:46 +00003783 if (Tok.is(tok::ellipsis)) {
3784 // C++0x [temp.variadic]p5:
Fangrui Song6907ce22018-07-30 19:24:48 +00003785 // - In a dynamic-exception-specification (15.4); the pattern is a
Douglas Gregor830837d2010-12-20 23:57:46 +00003786 // type-id.
3787 SourceLocation Ellipsis = ConsumeToken();
Sebastian Redl965b0e32011-03-05 14:45:16 +00003788 Range.setEnd(Ellipsis);
Douglas Gregor830837d2010-12-20 23:57:46 +00003789 if (!Res.isInvalid())
3790 Res = Actions.ActOnPackExpansion(Res.get(), Ellipsis);
3791 }
Sebastian Redl965b0e32011-03-05 14:45:16 +00003792
Sebastian Redld6434562009-05-29 18:02:33 +00003793 if (!Res.isInvalid()) {
Sebastian Redl2b9cacb2009-04-29 17:30:04 +00003794 Exceptions.push_back(Res.get());
Sebastian Redld6434562009-05-29 18:02:33 +00003795 Ranges.push_back(Range);
3796 }
Alp Toker97650562014-01-10 11:19:30 +00003797
3798 if (!TryConsumeToken(tok::comma))
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003799 break;
3800 }
3801
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003802 T.consumeClose();
3803 SpecificationRange.setEnd(T.getCloseLocation());
Richard Smith8ca78a12013-06-13 02:02:51 +00003804 diagnoseDynamicExceptionSpecification(*this, SpecificationRange,
3805 Exceptions.empty());
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003806 return Exceptions.empty() ? EST_DynamicNone : EST_Dynamic;
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003807}
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003808
Douglas Gregor7fb25412010-10-01 18:44:50 +00003809/// ParseTrailingReturnType - Parse a trailing return type on a new-style
3810/// function declaration.
Richard Smithe303e352018-02-02 22:24:54 +00003811TypeResult Parser::ParseTrailingReturnType(SourceRange &Range,
3812 bool MayBeFollowedByDirectInit) {
Douglas Gregor7fb25412010-10-01 18:44:50 +00003813 assert(Tok.is(tok::arrow) && "expected arrow");
3814
3815 ConsumeToken();
3816
Richard Smithe303e352018-02-02 22:24:54 +00003817 return ParseTypeName(&Range, MayBeFollowedByDirectInit
3818 ? DeclaratorContext::TrailingReturnVarContext
3819 : DeclaratorContext::TrailingReturnContext);
Douglas Gregor7fb25412010-10-01 18:44:50 +00003820}
3821
Saar Razb65b1f32020-01-09 15:07:51 +02003822/// Parse a requires-clause as part of a function declaration.
3823void Parser::ParseTrailingRequiresClause(Declarator &D) {
3824 assert(Tok.is(tok::kw_requires) && "expected requires");
3825
3826 SourceLocation RequiresKWLoc = ConsumeToken();
3827
3828 ExprResult TrailingRequiresClause;
3829 ParseScope ParamScope(this,
3830 Scope::DeclScope |
3831 Scope::FunctionDeclarationScope |
3832 Scope::FunctionPrototypeScope);
3833
3834 Actions.ActOnStartTrailingRequiresClause(getCurScope(), D);
3835
3836 llvm::Optional<Sema::CXXThisScopeRAII> ThisScope;
3837 InitCXXThisScopeForDeclaratorIfRelevant(D, D.getDeclSpec(), ThisScope);
3838
3839 TrailingRequiresClause =
3840 ParseConstraintLogicalOrExpression(/*IsTrailingRequiresClause=*/true);
3841
3842 TrailingRequiresClause =
3843 Actions.ActOnFinishTrailingRequiresClause(TrailingRequiresClause);
3844
3845 if (!D.isDeclarationOfFunction()) {
3846 Diag(RequiresKWLoc,
3847 diag::err_requires_clause_on_declarator_not_declaring_a_function);
3848 return;
3849 }
3850
3851 if (TrailingRequiresClause.isInvalid())
3852 SkipUntil({tok::l_brace, tok::arrow, tok::kw_try, tok::comma, tok::colon},
3853 StopAtSemi | StopBeforeMatch);
3854 else
3855 D.setTrailingRequiresClause(TrailingRequiresClause.get());
3856
3857 // Did the user swap the trailing return type and requires clause?
3858 if (D.isFunctionDeclarator() && Tok.is(tok::arrow) &&
3859 D.getDeclSpec().getTypeSpecType() == TST_auto) {
3860 SourceLocation ArrowLoc = Tok.getLocation();
3861 SourceRange Range;
3862 TypeResult TrailingReturnType =
3863 ParseTrailingReturnType(Range, /*MayBeFollowedByDirectInit=*/false);
3864
3865 if (!TrailingReturnType.isInvalid()) {
3866 Diag(ArrowLoc,
3867 diag::err_requires_clause_must_appear_after_trailing_return)
3868 << Range;
3869 auto &FunctionChunk = D.getFunctionTypeInfo();
3870 FunctionChunk.HasTrailingReturnType = TrailingReturnType.isUsable();
3871 FunctionChunk.TrailingReturnType = TrailingReturnType.get();
3872 } else
3873 SkipUntil({tok::equal, tok::l_brace, tok::arrow, tok::kw_try, tok::comma},
3874 StopAtSemi | StopBeforeMatch);
3875 }
3876}
3877
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003878/// We have just started parsing the definition of a new class,
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003879/// so push that class onto our stack of classes that is currently
3880/// being parsed.
John McCallc1465822011-02-14 07:13:47 +00003881Sema::ParsingClassState
John McCalldb632ac2012-09-25 07:32:39 +00003882Parser::PushParsingClass(Decl *ClassDecl, bool NonNestedClass,
3883 bool IsInterface) {
Douglas Gregoredf8f392010-01-16 20:52:59 +00003884 assert((NonNestedClass || !ClassStack.empty()) &&
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003885 "Nested class without outer class");
John McCalldb632ac2012-09-25 07:32:39 +00003886 ClassStack.push(new ParsingClass(ClassDecl, NonNestedClass, IsInterface));
John McCallc1465822011-02-14 07:13:47 +00003887 return Actions.PushParsingClass();
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003888}
3889
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003890/// Deallocate the given parsed class and all of its nested
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003891/// classes.
3892void Parser::DeallocateParsedClasses(Parser::ParsingClass *Class) {
Douglas Gregorefc46952010-10-12 16:25:54 +00003893 for (unsigned I = 0, N = Class->LateParsedDeclarations.size(); I != N; ++I)
3894 delete Class->LateParsedDeclarations[I];
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003895 delete Class;
3896}
3897
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003898/// Pop the top class of the stack of classes that are
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003899/// currently being parsed.
3900///
3901/// This routine should be called when we have finished parsing the
3902/// definition of a class, but have not yet popped the Scope
3903/// associated with the class's definition.
John McCallc1465822011-02-14 07:13:47 +00003904void Parser::PopParsingClass(Sema::ParsingClassState state) {
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003905 assert(!ClassStack.empty() && "Mismatched push/pop for class parsing");
Mike Stump11289f42009-09-09 15:08:12 +00003906
John McCallc1465822011-02-14 07:13:47 +00003907 Actions.PopParsingClass(state);
3908
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003909 ParsingClass *Victim = ClassStack.top();
3910 ClassStack.pop();
3911 if (Victim->TopLevelClass) {
3912 // Deallocate all of the nested classes of this class,
3913 // recursively: we don't need to keep any of this information.
3914 DeallocateParsedClasses(Victim);
3915 return;
Mike Stump11289f42009-09-09 15:08:12 +00003916 }
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003917 assert(!ClassStack.empty() && "Missing top-level class?");
3918
Douglas Gregorefc46952010-10-12 16:25:54 +00003919 if (Victim->LateParsedDeclarations.empty()) {
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003920 // The victim is a nested class, but we will not need to perform
3921 // any processing after the definition of this class since it has
3922 // no members whose handling was delayed. Therefore, we can just
3923 // remove this nested class.
Douglas Gregorefc46952010-10-12 16:25:54 +00003924 DeallocateParsedClasses(Victim);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003925 return;
3926 }
3927
3928 // This nested class has some members that will need to be processed
3929 // after the top-level class is completely defined. Therefore, add
3930 // it to the list of nested classes within its parent.
Douglas Gregor0be31a22010-07-02 17:43:08 +00003931 assert(getCurScope()->isClassScope() && "Nested class outside of class scope?");
Douglas Gregorefc46952010-10-12 16:25:54 +00003932 ClassStack.top()->LateParsedDeclarations.push_back(new LateParsedClass(this, Victim));
Douglas Gregor0be31a22010-07-02 17:43:08 +00003933 Victim->TemplateScope = getCurScope()->getParent()->isTemplateParamScope();
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003934}
Alexis Hunt96d5c762009-11-21 08:43:09 +00003935
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003936/// Try to parse an 'identifier' which appears within an attribute-token.
Richard Smith3dff2512012-04-10 03:25:07 +00003937///
3938/// \return the parsed identifier on success, and 0 if the next token is not an
3939/// attribute-token.
3940///
3941/// C++11 [dcl.attr.grammar]p3:
3942/// If a keyword or an alternative token that satisfies the syntactic
3943/// requirements of an identifier is contained in an attribute-token,
3944/// it is considered an identifier.
3945IdentifierInfo *Parser::TryParseCXX11AttributeIdentifier(SourceLocation &Loc) {
3946 switch (Tok.getKind()) {
3947 default:
3948 // Identifiers and keywords have identifier info attached.
David Majnemerd5271992015-01-09 18:09:39 +00003949 if (!Tok.isAnnotation()) {
3950 if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
3951 Loc = ConsumeToken();
3952 return II;
3953 }
Richard Smith3dff2512012-04-10 03:25:07 +00003954 }
Craig Topper161e4db2014-05-21 06:02:52 +00003955 return nullptr;
Richard Smith3dff2512012-04-10 03:25:07 +00003956
Aaron Ballmanc44c17422018-11-09 17:19:45 +00003957 case tok::numeric_constant: {
3958 // If we got a numeric constant, check to see if it comes from a macro that
3959 // corresponds to the predefined __clang__ macro. If it does, warn the user
3960 // and recover by pretending they said _Clang instead.
3961 if (Tok.getLocation().isMacroID()) {
3962 SmallString<8> ExpansionBuf;
3963 SourceLocation ExpansionLoc =
3964 PP.getSourceManager().getExpansionLoc(Tok.getLocation());
3965 StringRef Spelling = PP.getSpelling(ExpansionLoc, ExpansionBuf);
3966 if (Spelling == "__clang__") {
3967 SourceRange TokRange(
3968 ExpansionLoc,
3969 PP.getSourceManager().getExpansionLoc(Tok.getEndLoc()));
3970 Diag(Tok, diag::warn_wrong_clang_attr_namespace)
3971 << FixItHint::CreateReplacement(TokRange, "_Clang");
3972 Loc = ConsumeToken();
3973 return &PP.getIdentifierTable().get("_Clang");
3974 }
3975 }
3976 return nullptr;
3977 }
3978
Richard Smith3dff2512012-04-10 03:25:07 +00003979 case tok::ampamp: // 'and'
3980 case tok::pipe: // 'bitor'
3981 case tok::pipepipe: // 'or'
3982 case tok::caret: // 'xor'
3983 case tok::tilde: // 'compl'
3984 case tok::amp: // 'bitand'
3985 case tok::ampequal: // 'and_eq'
3986 case tok::pipeequal: // 'or_eq'
3987 case tok::caretequal: // 'xor_eq'
3988 case tok::exclaim: // 'not'
3989 case tok::exclaimequal: // 'not_eq'
3990 // Alternative tokens do not have identifier info, but their spelling
3991 // starts with an alphabetical character.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003992 SmallString<8> SpellingBuf;
Benjamin Kramer60be5632015-03-29 19:25:07 +00003993 SourceLocation SpellingLoc =
3994 PP.getSourceManager().getSpellingLoc(Tok.getLocation());
3995 StringRef Spelling = PP.getSpelling(SpellingLoc, SpellingBuf);
Jordan Rosea7d03842013-02-08 22:30:41 +00003996 if (isLetter(Spelling[0])) {
Richard Smith3dff2512012-04-10 03:25:07 +00003997 Loc = ConsumeToken();
Benjamin Kramer5c17f9c2012-04-22 20:43:30 +00003998 return &PP.getIdentifierTable().get(Spelling);
Richard Smith3dff2512012-04-10 03:25:07 +00003999 }
Craig Topper161e4db2014-05-21 06:02:52 +00004000 return nullptr;
Richard Smith3dff2512012-04-10 03:25:07 +00004001 }
4002}
4003
Michael Han23214e52012-10-03 01:56:22 +00004004static bool IsBuiltInOrStandardCXX11Attribute(IdentifierInfo *AttrName,
Aaron Ballman606093a2017-10-15 15:01:42 +00004005 IdentifierInfo *ScopeName) {
Erich Keane6a24e802019-09-13 17:39:31 +00004006 switch (
4007 ParsedAttr::getParsedKind(AttrName, ScopeName, ParsedAttr::AS_CXX11)) {
Erich Keanee891aa92018-07-13 15:07:47 +00004008 case ParsedAttr::AT_CarriesDependency:
4009 case ParsedAttr::AT_Deprecated:
4010 case ParsedAttr::AT_FallThrough:
4011 case ParsedAttr::AT_CXX11NoReturn:
Richard Smith78b239e2019-06-20 20:44:45 +00004012 case ParsedAttr::AT_NoUniqueAddress:
Michael Han23214e52012-10-03 01:56:22 +00004013 return true;
Erich Keanee891aa92018-07-13 15:07:47 +00004014 case ParsedAttr::AT_WarnUnusedResult:
Aaron Ballmane7964782016-03-07 22:44:55 +00004015 return !ScopeName && AttrName->getName().equals("nodiscard");
Erich Keanee891aa92018-07-13 15:07:47 +00004016 case ParsedAttr::AT_Unused:
Nico Weberac03bce2016-08-23 19:59:55 +00004017 return !ScopeName && AttrName->getName().equals("maybe_unused");
Michael Han23214e52012-10-03 01:56:22 +00004018 default:
4019 return false;
4020 }
4021}
4022
Aaron Ballmanb8e20392014-03-31 17:32:39 +00004023/// ParseCXX11AttributeArgs -- Parse a C++11 attribute-argument-clause.
4024///
4025/// [C++11] attribute-argument-clause:
4026/// '(' balanced-token-seq ')'
4027///
4028/// [C++11] balanced-token-seq:
4029/// balanced-token
4030/// balanced-token-seq balanced-token
4031///
4032/// [C++11] balanced-token:
4033/// '(' balanced-token-seq ')'
4034/// '[' balanced-token-seq ']'
4035/// '{' balanced-token-seq '}'
4036/// any token but '(', ')', '[', ']', '{', or '}'
4037bool Parser::ParseCXX11AttributeArgs(IdentifierInfo *AttrName,
4038 SourceLocation AttrNameLoc,
4039 ParsedAttributes &Attrs,
4040 SourceLocation *EndLoc,
4041 IdentifierInfo *ScopeName,
4042 SourceLocation ScopeLoc) {
4043 assert(Tok.is(tok::l_paren) && "Not a C++11 attribute argument list");
Aaron Ballman35f94212014-04-14 16:03:22 +00004044 SourceLocation LParenLoc = Tok.getLocation();
Aaron Ballman606093a2017-10-15 15:01:42 +00004045 const LangOptions &LO = getLangOpts();
Erich Keanee891aa92018-07-13 15:07:47 +00004046 ParsedAttr::Syntax Syntax =
4047 LO.CPlusPlus ? ParsedAttr::AS_CXX11 : ParsedAttr::AS_C2x;
Aaron Ballmanb8e20392014-03-31 17:32:39 +00004048
4049 // If the attribute isn't known, we will not attempt to parse any
4050 // arguments.
Aaron Ballman606093a2017-10-15 15:01:42 +00004051 if (!hasAttribute(LO.CPlusPlus ? AttrSyntax::CXX : AttrSyntax::C, ScopeName,
4052 AttrName, getTargetInfo(), getLangOpts())) {
Aaron Ballmanb8e20392014-03-31 17:32:39 +00004053 // Eat the left paren, then skip to the ending right paren.
4054 ConsumeParen();
4055 SkipUntil(tok::r_paren);
Aaron Ballmanc44c17422018-11-09 17:19:45 +00004056 return false;
4057 }
4058
4059 if (ScopeName && (ScopeName->isStr("gnu") || ScopeName->isStr("__gnu__"))) {
4060 // GNU-scoped attributes have some special cases to handle GNU-specific
4061 // behaviors.
4062 ParseGNUAttributeArgs(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
Aaron Ballman606093a2017-10-15 15:01:42 +00004063 ScopeLoc, Syntax, nullptr);
Alex Lorenzd5d27e12017-03-01 18:06:25 +00004064 return true;
4065 }
4066
4067 unsigned NumArgs;
4068 // Some Clang-scoped attributes have some special parsing behavior.
Aaron Ballmanc44c17422018-11-09 17:19:45 +00004069 if (ScopeName && (ScopeName->isStr("clang") || ScopeName->isStr("_Clang")))
4070 NumArgs = ParseClangAttributeArgs(AttrName, AttrNameLoc, Attrs, EndLoc,
4071 ScopeName, ScopeLoc, Syntax);
Alex Lorenzd5d27e12017-03-01 18:06:25 +00004072 else
4073 NumArgs =
Aaron Ballman35f94212014-04-14 16:03:22 +00004074 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc,
Aaron Ballman606093a2017-10-15 15:01:42 +00004075 ScopeName, ScopeLoc, Syntax);
Alex Lorenzd5d27e12017-03-01 18:06:25 +00004076
Erich Keanec480f302018-07-12 21:09:05 +00004077 if (!Attrs.empty() &&
4078 IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName)) {
Michael Krusedc5ce722018-08-03 01:21:16 +00004079 ParsedAttr &Attr = Attrs.back();
Alex Lorenzd5d27e12017-03-01 18:06:25 +00004080 // If the attribute is a standard or built-in attribute and we are
4081 // parsing an argument list, we need to determine whether this attribute
4082 // was allowed to have an argument list (such as [[deprecated]]), and how
4083 // many arguments were parsed (so we can diagnose on [[deprecated()]]).
Erich Keanec480f302018-07-12 21:09:05 +00004084 if (Attr.getMaxArgs() && !NumArgs) {
Alex Lorenzd5d27e12017-03-01 18:06:25 +00004085 // The attribute was allowed to have arguments, but none were provided
4086 // even though the attribute parsed successfully. This is an error.
4087 Diag(LParenLoc, diag::err_attribute_requires_arguments) << AttrName;
Erich Keanec480f302018-07-12 21:09:05 +00004088 Attr.setInvalid(true);
4089 } else if (!Attr.getMaxArgs()) {
Alex Lorenzd5d27e12017-03-01 18:06:25 +00004090 // The attribute parsed successfully, but was not allowed to have any
4091 // arguments. It doesn't matter whether any were provided -- the
4092 // presence of the argument list (even if empty) is diagnosed.
4093 Diag(LParenLoc, diag::err_cxx11_attribute_forbids_arguments)
4094 << AttrName
4095 << FixItHint::CreateRemoval(SourceRange(LParenLoc, *EndLoc));
Erich Keanec480f302018-07-12 21:09:05 +00004096 Attr.setInvalid(true);
Aaron Ballman35f94212014-04-14 16:03:22 +00004097 }
4098 }
Aaron Ballmanb8e20392014-03-31 17:32:39 +00004099 return true;
4100}
4101
Aaron Ballman606093a2017-10-15 15:01:42 +00004102/// ParseCXX11AttributeSpecifier - Parse a C++11 or C2x attribute-specifier.
Alexis Hunt96d5c762009-11-21 08:43:09 +00004103///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004104/// [C++11] attribute-specifier:
Alexis Hunt96d5c762009-11-21 08:43:09 +00004105/// '[' '[' attribute-list ']' ']'
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00004106/// alignment-specifier
Alexis Hunt96d5c762009-11-21 08:43:09 +00004107///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004108/// [C++11] attribute-list:
Alexis Hunt96d5c762009-11-21 08:43:09 +00004109/// attribute[opt]
4110/// attribute-list ',' attribute[opt]
Richard Smith3dff2512012-04-10 03:25:07 +00004111/// attribute '...'
4112/// attribute-list ',' attribute '...'
Alexis Hunt96d5c762009-11-21 08:43:09 +00004113///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004114/// [C++11] attribute:
Alexis Hunt96d5c762009-11-21 08:43:09 +00004115/// attribute-token attribute-argument-clause[opt]
4116///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004117/// [C++11] attribute-token:
Alexis Hunt96d5c762009-11-21 08:43:09 +00004118/// identifier
4119/// attribute-scoped-token
4120///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004121/// [C++11] attribute-scoped-token:
Alexis Hunt96d5c762009-11-21 08:43:09 +00004122/// attribute-namespace '::' identifier
4123///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004124/// [C++11] attribute-namespace:
Alexis Hunt96d5c762009-11-21 08:43:09 +00004125/// identifier
Richard Smith3dff2512012-04-10 03:25:07 +00004126void Parser::ParseCXX11AttributeSpecifier(ParsedAttributes &attrs,
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004127 SourceLocation *endLoc) {
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00004128 if (Tok.is(tok::kw_alignas)) {
Richard Smithf679b5b2011-10-14 20:48:27 +00004129 Diag(Tok.getLocation(), diag::warn_cxx98_compat_alignas);
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00004130 ParseAlignmentSpecifier(attrs, endLoc);
4131 return;
4132 }
4133
Aaron Ballman606093a2017-10-15 15:01:42 +00004134 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square) &&
4135 "Not a double square bracket attribute list");
Alexis Hunt96d5c762009-11-21 08:43:09 +00004136
Richard Smithf679b5b2011-10-14 20:48:27 +00004137 Diag(Tok.getLocation(), diag::warn_cxx98_compat_attribute);
4138
Alexis Hunt96d5c762009-11-21 08:43:09 +00004139 ConsumeBracket();
4140 ConsumeBracket();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004141
Richard Smithb7d7a042016-06-24 12:15:12 +00004142 SourceLocation CommonScopeLoc;
4143 IdentifierInfo *CommonScopeName = nullptr;
4144 if (Tok.is(tok::kw_using)) {
Aaron Ballmanc351fba2017-12-04 20:27:34 +00004145 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
Richard Smithb7d7a042016-06-24 12:15:12 +00004146 ? diag::warn_cxx14_compat_using_attribute_ns
4147 : diag::ext_using_attribute_ns);
4148 ConsumeToken();
4149
4150 CommonScopeName = TryParseCXX11AttributeIdentifier(CommonScopeLoc);
4151 if (!CommonScopeName) {
4152 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
4153 SkipUntil(tok::r_square, tok::colon, StopBeforeMatch);
4154 }
4155 if (!TryConsumeToken(tok::colon) && CommonScopeName)
4156 Diag(Tok.getLocation(), diag::err_expected) << tok::colon;
4157 }
4158
Richard Smith10876ef2013-01-17 01:30:42 +00004159 llvm::SmallDenseMap<IdentifierInfo*, SourceLocation, 4> SeenAttrs;
4160
Richard Smith3dff2512012-04-10 03:25:07 +00004161 while (Tok.isNot(tok::r_square)) {
Alexis Hunt96d5c762009-11-21 08:43:09 +00004162 // attribute not present
Alp Toker97650562014-01-10 11:19:30 +00004163 if (TryConsumeToken(tok::comma))
Alexis Hunt96d5c762009-11-21 08:43:09 +00004164 continue;
Alexis Hunt96d5c762009-11-21 08:43:09 +00004165
Richard Smith3dff2512012-04-10 03:25:07 +00004166 SourceLocation ScopeLoc, AttrLoc;
Craig Topper161e4db2014-05-21 06:02:52 +00004167 IdentifierInfo *ScopeName = nullptr, *AttrName = nullptr;
Richard Smith3dff2512012-04-10 03:25:07 +00004168
4169 AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
4170 if (!AttrName)
4171 // Break out to the "expected ']'" diagnostic.
4172 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004173
Alexis Hunt96d5c762009-11-21 08:43:09 +00004174 // scoped attribute
Alp Toker97650562014-01-10 11:19:30 +00004175 if (TryConsumeToken(tok::coloncolon)) {
Richard Smith3dff2512012-04-10 03:25:07 +00004176 ScopeName = AttrName;
4177 ScopeLoc = AttrLoc;
4178
4179 AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
4180 if (!AttrName) {
Alp Tokerec543272013-12-24 09:48:30 +00004181 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
Alexey Bataevee6507d2013-11-18 08:17:37 +00004182 SkipUntil(tok::r_square, tok::comma, StopAtSemi | StopBeforeMatch);
Alexis Hunt96d5c762009-11-21 08:43:09 +00004183 continue;
4184 }
Alexis Hunt96d5c762009-11-21 08:43:09 +00004185 }
4186
Richard Smithb7d7a042016-06-24 12:15:12 +00004187 if (CommonScopeName) {
4188 if (ScopeName) {
4189 Diag(ScopeLoc, diag::err_using_attribute_ns_conflict)
4190 << SourceRange(CommonScopeLoc);
4191 } else {
4192 ScopeName = CommonScopeName;
4193 ScopeLoc = CommonScopeLoc;
4194 }
4195 }
4196
Aaron Ballmanb8e20392014-03-31 17:32:39 +00004197 bool StandardAttr = IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName);
Alexis Hunt96d5c762009-11-21 08:43:09 +00004198 bool AttrParsed = false;
Alexis Hunt96d5c762009-11-21 08:43:09 +00004199
Richard Smith10876ef2013-01-17 01:30:42 +00004200 if (StandardAttr &&
4201 !SeenAttrs.insert(std::make_pair(AttrName, AttrLoc)).second)
4202 Diag(AttrLoc, diag::err_cxx11_attribute_repeated)
Aaron Ballmanb8e20392014-03-31 17:32:39 +00004203 << AttrName << SourceRange(SeenAttrs[AttrName]);
Richard Smith10876ef2013-01-17 01:30:42 +00004204
Michael Han23214e52012-10-03 01:56:22 +00004205 // Parse attribute arguments
Aaron Ballman35f94212014-04-14 16:03:22 +00004206 if (Tok.is(tok::l_paren))
Aaron Ballmanb8e20392014-03-31 17:32:39 +00004207 AttrParsed = ParseCXX11AttributeArgs(AttrName, AttrLoc, attrs, endLoc,
4208 ScopeName, ScopeLoc);
Michael Han23214e52012-10-03 01:56:22 +00004209
4210 if (!AttrParsed)
Aaron Ballman606093a2017-10-15 15:01:42 +00004211 attrs.addNew(
4212 AttrName,
4213 SourceRange(ScopeLoc.isValid() ? ScopeLoc : AttrLoc, AttrLoc),
4214 ScopeName, ScopeLoc, nullptr, 0,
Erich Keanee891aa92018-07-13 15:07:47 +00004215 getLangOpts().CPlusPlus ? ParsedAttr::AS_CXX11 : ParsedAttr::AS_C2x);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004216
Alp Toker97650562014-01-10 11:19:30 +00004217 if (TryConsumeToken(tok::ellipsis))
Michael Han23214e52012-10-03 01:56:22 +00004218 Diag(Tok, diag::err_cxx11_attribute_forbids_ellipsis)
Richard Trieub4025802018-03-28 04:16:13 +00004219 << AttrName;
Alexis Hunt96d5c762009-11-21 08:43:09 +00004220 }
4221
Alp Toker383d2c42014-01-01 03:08:43 +00004222 if (ExpectAndConsume(tok::r_square))
Alexey Bataevee6507d2013-11-18 08:17:37 +00004223 SkipUntil(tok::r_square);
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004224 if (endLoc)
4225 *endLoc = Tok.getLocation();
Alp Toker383d2c42014-01-01 03:08:43 +00004226 if (ExpectAndConsume(tok::r_square))
Alexey Bataevee6507d2013-11-18 08:17:37 +00004227 SkipUntil(tok::r_square);
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004228}
Alexis Hunt96d5c762009-11-21 08:43:09 +00004229
Aaron Ballman606093a2017-10-15 15:01:42 +00004230/// ParseCXX11Attributes - Parse a C++11 or C2x attribute-specifier-seq.
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004231///
4232/// attribute-specifier-seq:
4233/// attribute-specifier-seq[opt] attribute-specifier
Richard Smith3dff2512012-04-10 03:25:07 +00004234void Parser::ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004235 SourceLocation *endLoc) {
Aaron Ballman606093a2017-10-15 15:01:42 +00004236 assert(standardAttributesAllowed());
Richard Smith4cabd042013-02-22 09:15:49 +00004237
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004238 SourceLocation StartLoc = Tok.getLocation(), Loc;
4239 if (!endLoc)
4240 endLoc = &Loc;
4241
Douglas Gregor6f981002011-10-07 20:35:25 +00004242 do {
Richard Smith3dff2512012-04-10 03:25:07 +00004243 ParseCXX11AttributeSpecifier(attrs, endLoc);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004244 } while (isCXX11AttributeSpecifier());
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004245
4246 attrs.Range = SourceRange(StartLoc, *endLoc);
Alexis Hunt96d5c762009-11-21 08:43:09 +00004247}
4248
Richard Smithc2c8bb82013-10-15 01:34:54 +00004249void Parser::DiagnoseAndSkipCXX11Attributes() {
Richard Smithc2c8bb82013-10-15 01:34:54 +00004250 // Start and end location of an attribute or an attribute list.
4251 SourceLocation StartLoc = Tok.getLocation();
Richard Smith955bf012014-06-19 11:42:00 +00004252 SourceLocation EndLoc = SkipCXX11Attributes();
4253
4254 if (EndLoc.isValid()) {
4255 SourceRange Range(StartLoc, EndLoc);
4256 Diag(StartLoc, diag::err_attributes_not_allowed)
4257 << Range;
4258 }
4259}
4260
4261SourceLocation Parser::SkipCXX11Attributes() {
Richard Smithc2c8bb82013-10-15 01:34:54 +00004262 SourceLocation EndLoc;
4263
Richard Smith955bf012014-06-19 11:42:00 +00004264 if (!isCXX11AttributeSpecifier())
4265 return EndLoc;
4266
Richard Smithc2c8bb82013-10-15 01:34:54 +00004267 do {
4268 if (Tok.is(tok::l_square)) {
4269 BalancedDelimiterTracker T(*this, tok::l_square);
4270 T.consumeOpen();
4271 T.skipToEnd();
4272 EndLoc = T.getCloseLocation();
4273 } else {
4274 assert(Tok.is(tok::kw_alignas) && "not an attribute specifier");
4275 ConsumeToken();
4276 BalancedDelimiterTracker T(*this, tok::l_paren);
4277 if (!T.consumeOpen())
4278 T.skipToEnd();
4279 EndLoc = T.getCloseLocation();
4280 }
4281 } while (isCXX11AttributeSpecifier());
4282
Richard Smith955bf012014-06-19 11:42:00 +00004283 return EndLoc;
Richard Smithc2c8bb82013-10-15 01:34:54 +00004284}
4285
Nico Weber05e1dad2016-09-03 03:25:22 +00004286/// Parse uuid() attribute when it appears in a [] Microsoft attribute.
4287void Parser::ParseMicrosoftUuidAttributeArgs(ParsedAttributes &Attrs) {
4288 assert(Tok.is(tok::identifier) && "Not a Microsoft attribute list");
4289 IdentifierInfo *UuidIdent = Tok.getIdentifierInfo();
4290 assert(UuidIdent->getName() == "uuid" && "Not a Microsoft attribute list");
4291
4292 SourceLocation UuidLoc = Tok.getLocation();
4293 ConsumeToken();
4294
4295 // Ignore the left paren location for now.
4296 BalancedDelimiterTracker T(*this, tok::l_paren);
4297 if (T.consumeOpen()) {
4298 Diag(Tok, diag::err_expected) << tok::l_paren;
4299 return;
4300 }
4301
4302 ArgsVector ArgExprs;
4303 if (Tok.is(tok::string_literal)) {
4304 // Easy case: uuid("...") -- quoted string.
4305 ExprResult StringResult = ParseStringLiteralExpression();
4306 if (StringResult.isInvalid())
4307 return;
4308 ArgExprs.push_back(StringResult.get());
4309 } else {
4310 // something like uuid({000000A0-0000-0000-C000-000000000049}) -- no
4311 // quotes in the parens. Just append the spelling of all tokens encountered
4312 // until the closing paren.
4313
4314 SmallString<42> StrBuffer; // 2 "", 36 bytes UUID, 2 optional {}, 1 nul
4315 StrBuffer += "\"";
4316
4317 // Since none of C++'s keywords match [a-f]+, accepting just tok::l_brace,
4318 // tok::r_brace, tok::minus, tok::identifier (think C000) and
4319 // tok::numeric_constant (0000) should be enough. But the spelling of the
4320 // uuid argument is checked later anyways, so there's no harm in accepting
4321 // almost anything here.
4322 // cl is very strict about whitespace in this form and errors out if any
4323 // is present, so check the space flags on the tokens.
4324 SourceLocation StartLoc = Tok.getLocation();
4325 while (Tok.isNot(tok::r_paren)) {
4326 if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
4327 Diag(Tok, diag::err_attribute_uuid_malformed_guid);
4328 SkipUntil(tok::r_paren, StopAtSemi);
4329 return;
4330 }
4331 SmallString<16> SpellingBuffer;
4332 SpellingBuffer.resize(Tok.getLength() + 1);
4333 bool Invalid = false;
4334 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
4335 if (Invalid) {
4336 SkipUntil(tok::r_paren, StopAtSemi);
4337 return;
4338 }
4339 StrBuffer += TokSpelling;
4340 ConsumeAnyToken();
4341 }
4342 StrBuffer += "\"";
4343
4344 if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
4345 Diag(Tok, diag::err_attribute_uuid_malformed_guid);
4346 ConsumeParen();
4347 return;
4348 }
4349
4350 // Pretend the user wrote the appropriate string literal here.
4351 // ActOnStringLiteral() copies the string data into the literal, so it's
4352 // ok that the Token points to StrBuffer.
4353 Token Toks[1];
4354 Toks[0].startToken();
4355 Toks[0].setKind(tok::string_literal);
4356 Toks[0].setLocation(StartLoc);
4357 Toks[0].setLiteralData(StrBuffer.data());
4358 Toks[0].setLength(StrBuffer.size());
4359 StringLiteral *UuidString =
4360 cast<StringLiteral>(Actions.ActOnStringLiteral(Toks, nullptr).get());
4361 ArgExprs.push_back(UuidString);
4362 }
4363
4364 if (!T.consumeClose()) {
Nico Weber05e1dad2016-09-03 03:25:22 +00004365 Attrs.addNew(UuidIdent, SourceRange(UuidLoc, T.getCloseLocation()), nullptr,
4366 SourceLocation(), ArgExprs.data(), ArgExprs.size(),
Erich Keanee891aa92018-07-13 15:07:47 +00004367 ParsedAttr::AS_Microsoft);
Nico Weber05e1dad2016-09-03 03:25:22 +00004368 }
4369}
4370
David Majnemere4752e752015-07-08 05:55:00 +00004371/// ParseMicrosoftAttributes - Parse Microsoft attributes [Attr]
Francois Pichetc2bc5ac2010-10-11 12:59:39 +00004372///
4373/// [MS] ms-attribute:
4374/// '[' token-seq ']'
4375///
4376/// [MS] ms-attribute-seq:
4377/// ms-attribute[opt]
4378/// ms-attribute ms-attribute-seq
John McCall53fa7142010-12-24 02:08:15 +00004379void Parser::ParseMicrosoftAttributes(ParsedAttributes &attrs,
4380 SourceLocation *endLoc) {
Francois Pichetc2bc5ac2010-10-11 12:59:39 +00004381 assert(Tok.is(tok::l_square) && "Not a Microsoft attribute list");
4382
Saleem Abdulrasool425efcf2015-06-15 20:57:04 +00004383 do {
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004384 // FIXME: If this is actually a C++11 attribute, parse it as one.
Saleem Abdulrasool425efcf2015-06-15 20:57:04 +00004385 BalancedDelimiterTracker T(*this, tok::l_square);
4386 T.consumeOpen();
Nico Weber05e1dad2016-09-03 03:25:22 +00004387
4388 // Skip most ms attributes except for a whitelist.
4389 while (true) {
4390 SkipUntil(tok::r_square, tok::identifier, StopAtSemi | StopBeforeMatch);
4391 if (Tok.isNot(tok::identifier)) // ']', but also eof
4392 break;
4393 if (Tok.getIdentifierInfo()->getName() == "uuid")
4394 ParseMicrosoftUuidAttributeArgs(attrs);
4395 else
4396 ConsumeToken();
4397 }
4398
Saleem Abdulrasool425efcf2015-06-15 20:57:04 +00004399 T.consumeClose();
4400 if (endLoc)
4401 *endLoc = T.getCloseLocation();
4402 } while (Tok.is(tok::l_square));
Francois Pichetc2bc5ac2010-10-11 12:59:39 +00004403}
Francois Pichet8f981d52011-05-25 10:19:49 +00004404
Erich Keanec480f302018-07-12 21:09:05 +00004405void Parser::ParseMicrosoftIfExistsClassDeclaration(
4406 DeclSpec::TST TagType, ParsedAttributes &AccessAttrs,
4407 AccessSpecifier &CurAS) {
Douglas Gregor43edb322011-10-24 22:31:10 +00004408 IfExistsCondition Result;
Francois Pichet8f981d52011-05-25 10:19:49 +00004409 if (ParseMicrosoftIfExistsCondition(Result))
4410 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00004411
Douglas Gregor43edb322011-10-24 22:31:10 +00004412 BalancedDelimiterTracker Braces(*this, tok::l_brace);
4413 if (Braces.consumeOpen()) {
Alp Tokerec543272013-12-24 09:48:30 +00004414 Diag(Tok, diag::err_expected) << tok::l_brace;
Francois Pichet8f981d52011-05-25 10:19:49 +00004415 return;
4416 }
Francois Pichet8f981d52011-05-25 10:19:49 +00004417
Douglas Gregor43edb322011-10-24 22:31:10 +00004418 switch (Result.Behavior) {
4419 case IEB_Parse:
4420 // Parse the declarations below.
4421 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00004422
Douglas Gregor43edb322011-10-24 22:31:10 +00004423 case IEB_Dependent:
4424 Diag(Result.KeywordLoc, diag::warn_microsoft_dependent_exists)
4425 << Result.IsIfExists;
4426 // Fall through to skip.
Galina Kistanovad819d5b2017-06-01 21:19:06 +00004427 LLVM_FALLTHROUGH;
Fangrui Song6907ce22018-07-30 19:24:48 +00004428
Douglas Gregor43edb322011-10-24 22:31:10 +00004429 case IEB_Skip:
4430 Braces.skipToEnd();
Francois Pichet8f981d52011-05-25 10:19:49 +00004431 return;
4432 }
4433
Richard Smith34f30512013-11-23 04:06:09 +00004434 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
Francois Pichet8f981d52011-05-25 10:19:49 +00004435 // __if_exists, __if_not_exists can nest.
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00004436 if (Tok.isOneOf(tok::kw___if_exists, tok::kw___if_not_exists)) {
Serge Pavlov0c503192019-08-01 11:46:28 +00004437 ParseMicrosoftIfExistsClassDeclaration(TagType,
Erich Keanec480f302018-07-12 21:09:05 +00004438 AccessAttrs, CurAS);
Francois Pichet8f981d52011-05-25 10:19:49 +00004439 continue;
4440 }
4441
4442 // Check for extraneous top-level semicolon.
4443 if (Tok.is(tok::semi)) {
Richard Smith87f5dc52012-07-23 05:45:25 +00004444 ConsumeExtraSemi(InsideStruct, TagType);
Francois Pichet8f981d52011-05-25 10:19:49 +00004445 continue;
4446 }
4447
4448 AccessSpecifier AS = getAccessSpecifierIfPresent();
4449 if (AS != AS_none) {
4450 // Current token is a C++ access specifier.
4451 CurAS = AS;
4452 SourceLocation ASLoc = Tok.getLocation();
4453 ConsumeToken();
4454 if (Tok.is(tok::colon))
Erich Keanec480f302018-07-12 21:09:05 +00004455 Actions.ActOnAccessSpecifier(AS, ASLoc, Tok.getLocation(),
4456 ParsedAttributesView{});
Francois Pichet8f981d52011-05-25 10:19:49 +00004457 else
Alp Toker35d87032013-12-30 23:29:50 +00004458 Diag(Tok, diag::err_expected) << tok::colon;
Francois Pichet8f981d52011-05-25 10:19:49 +00004459 ConsumeToken();
4460 continue;
4461 }
4462
4463 // Parse all the comma separated declarators.
Erich Keanec480f302018-07-12 21:09:05 +00004464 ParseCXXClassMemberDeclaration(CurAS, AccessAttrs);
Francois Pichet8f981d52011-05-25 10:19:49 +00004465 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004466
Douglas Gregor43edb322011-10-24 22:31:10 +00004467 Braces.consumeClose();
Francois Pichet8f981d52011-05-25 10:19:49 +00004468}