blob: 9c7d3c5665543fac911561ef8b76cabec15f0d2b [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);
Erich Keane53f391d2018-11-12 17:19:48 +0000158 } else if (getLangOpts().CPlusPlus2a) {
159 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.
Matthias Gehredc01bb42017-03-17 21:41:20 +0000293 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false,
294 /*MayBePseudoDestructor=*/nullptr,
295 /*IsTypename=*/false,
296 /*LastII=*/nullptr,
297 /*OnlyNamespace=*/true);
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000298
Matthias Gehredc01bb42017-03-17 21:41:20 +0000299 if (Tok.isNot(tok::identifier)) {
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000300 Diag(Tok, diag::err_expected_namespace_name);
301 // Skip to end of the definition and eat the ';'.
302 SkipUntil(tok::semi);
Craig Topper161e4db2014-05-21 06:02:52 +0000303 return nullptr;
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000304 }
305
Matthias Gehredc01bb42017-03-17 21:41:20 +0000306 if (SS.isInvalid()) {
307 // Diagnostics have been emitted in ParseOptionalCXXScopeSpecifier.
308 // Skip to end of the definition and eat the ';'.
309 SkipUntil(tok::semi);
310 return nullptr;
311 }
312
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000313 // Parse identifier.
Anders Carlsson47952ae2009-03-28 22:53:22 +0000314 IdentifierInfo *Ident = Tok.getIdentifierInfo();
315 SourceLocation IdentLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000316
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000317 // Eat the ';'.
Chris Lattner49836b42009-04-02 04:16:50 +0000318 DeclEnd = Tok.getLocation();
Alp Toker383d2c42014-01-01 03:08:43 +0000319 if (ExpectAndConsume(tok::semi, diag::err_expected_semi_after_namespace_name))
320 SkipUntil(tok::semi);
Mike Stump11289f42009-09-09 15:08:12 +0000321
Craig Topperff354282015-11-14 18:16:00 +0000322 return Actions.ActOnNamespaceAliasDef(getCurScope(), NamespaceLoc, AliasLoc,
323 Alias, SS, IdentLoc, Ident);
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000324}
325
Chris Lattner38376f12008-01-12 07:05:38 +0000326/// ParseLinkage - We know that the current token is a string_literal
327/// and just before that, that extern was seen.
328///
329/// linkage-specification: [C++ 7.5p2: dcl.link]
330/// 'extern' string-literal '{' declaration-seq[opt] '}'
331/// 'extern' string-literal declaration
332///
Faisal Vali421b2d12017-12-29 05:41:00 +0000333Decl *Parser::ParseLinkage(ParsingDeclSpec &DS, DeclaratorContext Context) {
Richard Smith4ee696d2014-02-17 23:25:27 +0000334 assert(isTokenStringLiteral() && "Not a string literal!");
335 ExprResult Lang = ParseStringLiteralExpression(false);
Chris Lattner38376f12008-01-12 07:05:38 +0000336
Douglas Gregor07665a62009-01-05 19:45:36 +0000337 ParseScope LinkageScope(this, Scope::DeclScope);
Richard Smith4ee696d2014-02-17 23:25:27 +0000338 Decl *LinkageSpec =
339 Lang.isInvalid()
Craig Topper161e4db2014-05-21 06:02:52 +0000340 ? nullptr
Richard Smith4ee696d2014-02-17 23:25:27 +0000341 : Actions.ActOnStartLinkageSpecification(
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000342 getCurScope(), DS.getSourceRange().getBegin(), Lang.get(),
Richard Smith4ee696d2014-02-17 23:25:27 +0000343 Tok.is(tok::l_brace) ? Tok.getLocation() : SourceLocation());
Douglas Gregor07665a62009-01-05 19:45:36 +0000344
John McCall084e83d2011-03-24 11:26:52 +0000345 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +0000346 MaybeParseCXX11Attributes(attrs);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000347
Douglas Gregor07665a62009-01-05 19:45:36 +0000348 if (Tok.isNot(tok::l_brace)) {
Abramo Bagnara4d423992011-05-01 16:25:54 +0000349 // Reset the source range in DS, as the leading "extern"
350 // does not really belong to the inner declaration ...
351 DS.SetRangeStart(SourceLocation());
352 DS.SetRangeEnd(SourceLocation());
353 // ... but anyway remember that such an "extern" was seen.
Abramo Bagnaraed5b6892010-07-30 16:47:02 +0000354 DS.setExternInLinkageSpec(true);
John McCall53fa7142010-12-24 02:08:15 +0000355 ParseExternalDeclaration(attrs, &DS);
Richard Smith4ee696d2014-02-17 23:25:27 +0000356 return LinkageSpec ? Actions.ActOnFinishLinkageSpecification(
357 getCurScope(), LinkageSpec, SourceLocation())
Craig Topper161e4db2014-05-21 06:02:52 +0000358 : nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000359 }
Douglas Gregor29ff7d02008-12-16 22:23:02 +0000360
Douglas Gregorb65a9132010-02-07 08:38:28 +0000361 DS.abort();
362
John McCall53fa7142010-12-24 02:08:15 +0000363 ProhibitAttributes(attrs);
Alexis Hunt96d5c762009-11-21 08:43:09 +0000364
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000365 BalancedDelimiterTracker T(*this, tok::l_brace);
366 T.consumeOpen();
Richard Smith77944862014-03-02 05:58:18 +0000367
368 unsigned NestedModules = 0;
369 while (true) {
370 switch (Tok.getKind()) {
371 case tok::annot_module_begin:
372 ++NestedModules;
373 ParseTopLevelDecl();
374 continue;
375
376 case tok::annot_module_end:
377 if (!NestedModules)
378 break;
379 --NestedModules;
380 ParseTopLevelDecl();
381 continue;
382
383 case tok::annot_module_include:
384 ParseTopLevelDecl();
385 continue;
386
387 case tok::eof:
388 break;
389
390 case tok::r_brace:
391 if (!NestedModules)
392 break;
Reid Kleckner4dc0b1a2018-11-01 19:54:45 +0000393 LLVM_FALLTHROUGH;
Richard Smith77944862014-03-02 05:58:18 +0000394 default:
395 ParsedAttributesWithRange attrs(AttrFactory);
396 MaybeParseCXX11Attributes(attrs);
Richard Smith77944862014-03-02 05:58:18 +0000397 ParseExternalDeclaration(attrs);
398 continue;
399 }
400
401 break;
Chris Lattner38376f12008-01-12 07:05:38 +0000402 }
403
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000404 T.consumeClose();
Richard Smith4ee696d2014-02-17 23:25:27 +0000405 return LinkageSpec ? Actions.ActOnFinishLinkageSpecification(
406 getCurScope(), LinkageSpec, T.getCloseLocation())
Craig Topper161e4db2014-05-21 06:02:52 +0000407 : nullptr;
Chris Lattner38376f12008-01-12 07:05:38 +0000408}
Douglas Gregor556877c2008-04-13 21:30:24 +0000409
Richard Smith8df390f2016-09-08 23:14:54 +0000410/// Parse a C++ Modules TS export-declaration.
411///
412/// export-declaration:
413/// 'export' declaration
414/// 'export' '{' declaration-seq[opt] '}'
415///
416Decl *Parser::ParseExportDeclaration() {
417 assert(Tok.is(tok::kw_export));
418 SourceLocation ExportLoc = ConsumeToken();
419
420 ParseScope ExportScope(this, Scope::DeclScope);
421 Decl *ExportDecl = Actions.ActOnStartExportDecl(
422 getCurScope(), ExportLoc,
423 Tok.is(tok::l_brace) ? Tok.getLocation() : SourceLocation());
424
425 if (Tok.isNot(tok::l_brace)) {
426 // FIXME: Factor out a ParseExternalDeclarationWithAttrs.
427 ParsedAttributesWithRange Attrs(AttrFactory);
428 MaybeParseCXX11Attributes(Attrs);
429 MaybeParseMicrosoftAttributes(Attrs);
430 ParseExternalDeclaration(Attrs);
431 return Actions.ActOnFinishExportDecl(getCurScope(), ExportDecl,
432 SourceLocation());
433 }
434
435 BalancedDelimiterTracker T(*this, tok::l_brace);
436 T.consumeOpen();
437
438 // The Modules TS draft says "An export-declaration shall declare at least one
439 // entity", but the intent is that it shall contain at least one declaration.
Richard Smithe181de72019-04-22 22:50:11 +0000440 if (Tok.is(tok::r_brace) && getLangOpts().ModulesTS) {
Richard Smith8df390f2016-09-08 23:14:54 +0000441 Diag(ExportLoc, diag::err_export_empty)
442 << SourceRange(ExportLoc, Tok.getLocation());
Richard Smithe181de72019-04-22 22:50:11 +0000443 }
Richard Smith8df390f2016-09-08 23:14:54 +0000444
445 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
446 Tok.isNot(tok::eof)) {
447 ParsedAttributesWithRange Attrs(AttrFactory);
448 MaybeParseCXX11Attributes(Attrs);
449 MaybeParseMicrosoftAttributes(Attrs);
450 ParseExternalDeclaration(Attrs);
451 }
452
453 T.consumeClose();
454 return Actions.ActOnFinishExportDecl(getCurScope(), ExportDecl,
455 T.getCloseLocation());
456}
457
Douglas Gregord7c4d982008-12-30 03:27:21 +0000458/// ParseUsingDirectiveOrDeclaration - Parse C++ using using-declaration or
459/// using-directive. Assumes that current token is 'using'.
Richard Smith6f1daa42016-12-16 00:58:48 +0000460Parser::DeclGroupPtrTy
Faisal Vali421b2d12017-12-29 05:41:00 +0000461Parser::ParseUsingDirectiveOrDeclaration(DeclaratorContext Context,
John McCall9b72f892010-11-10 02:40:36 +0000462 const ParsedTemplateInfo &TemplateInfo,
Richard Smith6f1daa42016-12-16 00:58:48 +0000463 SourceLocation &DeclEnd,
464 ParsedAttributesWithRange &attrs) {
Douglas Gregord7c4d982008-12-30 03:27:21 +0000465 assert(Tok.is(tok::kw_using) && "Not using token");
Fariborz Jahanian4bf82622011-08-22 17:59:19 +0000466 ObjCDeclContextSwitch ObjCDC(*this);
Fangrui Song6907ce22018-07-30 19:24:48 +0000467
Douglas Gregord7c4d982008-12-30 03:27:21 +0000468 // Eat 'using'.
469 SourceLocation UsingLoc = ConsumeToken();
470
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000471 if (Tok.is(tok::code_completion)) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000472 Actions.CodeCompleteUsing(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000473 cutOffParsing();
Craig Topper161e4db2014-05-21 06:02:52 +0000474 return nullptr;
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000475 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000476
Richard Trieu2efd3052019-05-01 23:33:49 +0000477 // Consume unexpected 'template' keywords.
478 while (Tok.is(tok::kw_template)) {
479 SourceLocation TemplateLoc = ConsumeToken();
480 Diag(TemplateLoc, diag::err_unexpected_template_after_using)
481 << FixItHint::CreateRemoval(TemplateLoc);
482 }
483
John McCall9b72f892010-11-10 02:40:36 +0000484 // 'using namespace' means this is a using-directive.
485 if (Tok.is(tok::kw_namespace)) {
486 // Template parameters are always an error here.
487 if (TemplateInfo.Kind) {
488 SourceRange R = TemplateInfo.getSourceRange();
Craig Topper54a6a682015-11-14 18:16:08 +0000489 Diag(UsingLoc, diag::err_templated_using_directive_declaration)
490 << 0 /* directive */ << R << FixItHint::CreateRemoval(R);
John McCall9b72f892010-11-10 02:40:36 +0000491 }
Alexis Hunt96d5c762009-11-21 08:43:09 +0000492
Richard Smith6f1daa42016-12-16 00:58:48 +0000493 Decl *UsingDir = ParseUsingDirective(Context, UsingLoc, DeclEnd, attrs);
494 return Actions.ConvertDeclToDeclGroup(UsingDir);
John McCall9b72f892010-11-10 02:40:36 +0000495 }
496
Richard Smithdda56e42011-04-15 14:24:37 +0000497 // Otherwise, it must be a using-declaration or an alias-declaration.
John McCall9b72f892010-11-10 02:40:36 +0000498
499 // Using declarations can't have attributes.
John McCall53fa7142010-12-24 02:08:15 +0000500 ProhibitAttributes(attrs);
Chris Lattner9b01ca12009-01-06 06:55:51 +0000501
Fariborz Jahanian4bf82622011-08-22 17:59:19 +0000502 return ParseUsingDeclaration(Context, TemplateInfo, UsingLoc, DeclEnd,
Richard Smith6f1daa42016-12-16 00:58:48 +0000503 AS_none);
Douglas Gregord7c4d982008-12-30 03:27:21 +0000504}
505
506/// ParseUsingDirective - Parse C++ using-directive, assumes
507/// that current token is 'namespace' and 'using' was already parsed.
508///
509/// using-directive: [C++ 7.3.p4: namespace.udir]
510/// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
511/// namespace-name ;
512/// [GNU] using-directive:
513/// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
514/// namespace-name attributes[opt] ;
515///
Faisal Vali421b2d12017-12-29 05:41:00 +0000516Decl *Parser::ParseUsingDirective(DeclaratorContext Context,
John McCall9b72f892010-11-10 02:40:36 +0000517 SourceLocation UsingLoc,
518 SourceLocation &DeclEnd,
John McCall53fa7142010-12-24 02:08:15 +0000519 ParsedAttributes &attrs) {
Douglas Gregord7c4d982008-12-30 03:27:21 +0000520 assert(Tok.is(tok::kw_namespace) && "Not 'namespace' token");
521
522 // Eat 'namespace'.
523 SourceLocation NamespcLoc = ConsumeToken();
524
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000525 if (Tok.is(tok::code_completion)) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000526 Actions.CodeCompleteUsingDirective(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000527 cutOffParsing();
Craig Topper161e4db2014-05-21 06:02:52 +0000528 return nullptr;
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000529 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000530
Douglas Gregord7c4d982008-12-30 03:27:21 +0000531 CXXScopeSpec SS;
532 // Parse (optional) nested-name-specifier.
Matthias Gehredc01bb42017-03-17 21:41:20 +0000533 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false,
534 /*MayBePseudoDestructor=*/nullptr,
535 /*IsTypename=*/false,
536 /*LastII=*/nullptr,
537 /*OnlyNamespace=*/true);
Douglas Gregord7c4d982008-12-30 03:27:21 +0000538
Craig Topper161e4db2014-05-21 06:02:52 +0000539 IdentifierInfo *NamespcName = nullptr;
Douglas Gregord7c4d982008-12-30 03:27:21 +0000540 SourceLocation IdentLoc = SourceLocation();
541
542 // Parse namespace-name.
Matthias Gehredc01bb42017-03-17 21:41:20 +0000543 if (Tok.isNot(tok::identifier)) {
Douglas Gregord7c4d982008-12-30 03:27:21 +0000544 Diag(Tok, diag::err_expected_namespace_name);
545 // If there was invalid namespace name, skip to end of decl, and eat ';'.
546 SkipUntil(tok::semi);
547 // FIXME: Are there cases, when we would like to call ActOnUsingDirective?
Craig Topper161e4db2014-05-21 06:02:52 +0000548 return nullptr;
Douglas Gregord7c4d982008-12-30 03:27:21 +0000549 }
Mike Stump11289f42009-09-09 15:08:12 +0000550
Matthias Gehredc01bb42017-03-17 21:41:20 +0000551 if (SS.isInvalid()) {
552 // Diagnostics have been emitted in ParseOptionalCXXScopeSpecifier.
553 // Skip to end of the definition and eat the ';'.
554 SkipUntil(tok::semi);
555 return nullptr;
556 }
557
Chris Lattnerce1da2c2009-01-06 07:27:21 +0000558 // Parse identifier.
559 NamespcName = Tok.getIdentifierInfo();
560 IdentLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000561
Chris Lattnerce1da2c2009-01-06 07:27:21 +0000562 // Parse (optional) attributes (most likely GNU strong-using extension).
Alexis Hunt96d5c762009-11-21 08:43:09 +0000563 bool GNUAttr = false;
564 if (Tok.is(tok::kw___attribute)) {
565 GNUAttr = true;
John McCall53fa7142010-12-24 02:08:15 +0000566 ParseGNUAttributes(attrs);
Alexis Hunt96d5c762009-11-21 08:43:09 +0000567 }
Mike Stump11289f42009-09-09 15:08:12 +0000568
Chris Lattnerce1da2c2009-01-06 07:27:21 +0000569 // Eat ';'.
Chris Lattner49836b42009-04-02 04:16:50 +0000570 DeclEnd = Tok.getLocation();
Alp Toker383d2c42014-01-01 03:08:43 +0000571 if (ExpectAndConsume(tok::semi,
572 GNUAttr ? diag::err_expected_semi_after_attribute_list
573 : diag::err_expected_semi_after_namespace_name))
574 SkipUntil(tok::semi);
Douglas Gregord7c4d982008-12-30 03:27:21 +0000575
Douglas Gregor0be31a22010-07-02 17:43:08 +0000576 return Actions.ActOnUsingDirective(getCurScope(), UsingLoc, NamespcLoc, SS,
Erich Keanec480f302018-07-12 21:09:05 +0000577 IdentLoc, NamespcName, attrs);
Douglas Gregord7c4d982008-12-30 03:27:21 +0000578}
579
Richard Smith6f1daa42016-12-16 00:58:48 +0000580/// Parse a using-declarator (or the identifier in a C++11 alias-declaration).
Douglas Gregord7c4d982008-12-30 03:27:21 +0000581///
Richard Smith6f1daa42016-12-16 00:58:48 +0000582/// using-declarator:
583/// 'typename'[opt] nested-name-specifier unqualified-id
Douglas Gregord7c4d982008-12-30 03:27:21 +0000584///
Faisal Vali421b2d12017-12-29 05:41:00 +0000585bool Parser::ParseUsingDeclarator(DeclaratorContext Context,
586 UsingDeclarator &D) {
Richard Smith6f1daa42016-12-16 00:58:48 +0000587 D.clear();
Douglas Gregorfec52632009-06-20 00:51:54 +0000588
589 // Ignore optional 'typename'.
Douglas Gregor220f4272009-11-04 16:30:06 +0000590 // FIXME: This is wrong; we should parse this as a typename-specifier.
Richard Smith6f1daa42016-12-16 00:58:48 +0000591 TryConsumeToken(tok::kw_typename, D.TypenameLoc);
Douglas Gregorfec52632009-06-20 00:51:54 +0000592
Nikola Smiljanic67860242014-09-26 00:28:20 +0000593 if (Tok.is(tok::kw___super)) {
594 Diag(Tok.getLocation(), diag::err_super_in_using_declaration);
Richard Smith6f1daa42016-12-16 00:58:48 +0000595 return true;
Nikola Smiljanic67860242014-09-26 00:28:20 +0000596 }
597
Douglas Gregorfec52632009-06-20 00:51:54 +0000598 // Parse nested-name-specifier.
Craig Topper161e4db2014-05-21 06:02:52 +0000599 IdentifierInfo *LastII = nullptr;
Richard Smithb23c5e82019-05-09 03:31:27 +0000600 if (ParseOptionalCXXScopeSpecifier(D.SS, nullptr, /*EnteringContext=*/false,
601 /*MayBePseudoDtor=*/nullptr,
602 /*IsTypename=*/false,
Ilya Biryukovd9971d02019-10-28 09:34:21 +0100603 /*LastII=*/&LastII,
604 /*OnlyNamespace=*/false,
605 /*InUsingDeclaration=*/true))
606
Richard Smithb23c5e82019-05-09 03:31:27 +0000607 return true;
Richard Smith6f1daa42016-12-16 00:58:48 +0000608 if (D.SS.isInvalid())
609 return true;
Richard Smith7447af42013-03-26 01:15:19 +0000610
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000611 // Parse the unqualified-id. We allow parsing of both constructor and
Douglas Gregor220f4272009-11-04 16:30:06 +0000612 // destructor names and allow the action module to diagnose any semantic
613 // errors.
Richard Smith7447af42013-03-26 01:15:19 +0000614 //
615 // C++11 [class.qual]p2:
616 // [...] in a using-declaration that is a member-declaration, if the name
617 // specified after the nested-name-specifier is the same as the identifier
618 // or the simple-template-id's template-name in the last component of the
619 // nested-name-specifier, the name is [...] considered to name the
620 // constructor.
Faisal Vali421b2d12017-12-29 05:41:00 +0000621 if (getLangOpts().CPlusPlus11 &&
622 Context == DeclaratorContext::MemberContext &&
Richard Smith151c4562016-12-20 21:35:28 +0000623 Tok.is(tok::identifier) &&
624 (NextToken().is(tok::semi) || NextToken().is(tok::comma) ||
625 NextToken().is(tok::ellipsis)) &&
Richard Smith6f1daa42016-12-16 00:58:48 +0000626 D.SS.isNotEmpty() && LastII == Tok.getIdentifierInfo() &&
627 !D.SS.getScopeRep()->getAsNamespace() &&
628 !D.SS.getScopeRep()->getAsNamespaceAlias()) {
Richard Smith7447af42013-03-26 01:15:19 +0000629 SourceLocation IdLoc = ConsumeToken();
Richard Smith6f1daa42016-12-16 00:58:48 +0000630 ParsedType Type =
631 Actions.getInheritingConstructorName(D.SS, IdLoc, *LastII);
632 D.Name.setConstructorName(Type, IdLoc, IdLoc);
633 } else {
634 if (ParseUnqualifiedId(
635 D.SS, /*EnteringContext=*/false,
636 /*AllowDestructorName=*/true,
637 /*AllowConstructorName=*/!(Tok.is(tok::identifier) &&
638 NextToken().is(tok::equal)),
Richard Smith35845152017-02-07 01:37:30 +0000639 /*AllowDeductionGuide=*/false,
Richard Smithc08b6932018-04-27 02:00:13 +0000640 nullptr, nullptr, D.Name))
Richard Smith6f1daa42016-12-16 00:58:48 +0000641 return true;
Douglas Gregorfec52632009-06-20 00:51:54 +0000642 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000643
Richard Smith151c4562016-12-20 21:35:28 +0000644 if (TryConsumeToken(tok::ellipsis, D.EllipsisLoc))
Aaron Ballmanc351fba2017-12-04 20:27:34 +0000645 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17 ?
Richard Smithb115e5d2017-08-13 23:37:29 +0000646 diag::warn_cxx17_compat_using_declaration_pack :
Richard Smith151c4562016-12-20 21:35:28 +0000647 diag::ext_using_declaration_pack);
Richard Smith6f1daa42016-12-16 00:58:48 +0000648
649 return false;
650}
651
652/// ParseUsingDeclaration - Parse C++ using-declaration or alias-declaration.
653/// Assumes that 'using' was already seen.
654///
655/// using-declaration: [C++ 7.3.p3: namespace.udecl]
656/// 'using' using-declarator-list[opt] ;
657///
658/// using-declarator-list: [C++1z]
659/// using-declarator '...'[opt]
660/// using-declarator-list ',' using-declarator '...'[opt]
661///
662/// using-declarator-list: [C++98-14]
663/// using-declarator
664///
665/// alias-declaration: C++11 [dcl.dcl]p1
666/// 'using' identifier attribute-specifier-seq[opt] = type-id ;
667///
668Parser::DeclGroupPtrTy
Faisal Vali421b2d12017-12-29 05:41:00 +0000669Parser::ParseUsingDeclaration(DeclaratorContext Context,
Richard Smith6f1daa42016-12-16 00:58:48 +0000670 const ParsedTemplateInfo &TemplateInfo,
671 SourceLocation UsingLoc, SourceLocation &DeclEnd,
672 AccessSpecifier AS) {
673 // Check for misplaced attributes before the identifier in an
674 // alias-declaration.
675 ParsedAttributesWithRange MisplacedAttrs(AttrFactory);
676 MaybeParseCXX11Attributes(MisplacedAttrs);
677
678 UsingDeclarator D;
679 bool InvalidDeclarator = ParseUsingDeclarator(Context, D);
680
Richard Smithc2c8bb82013-10-15 01:34:54 +0000681 ParsedAttributesWithRange Attrs(AttrFactory);
Richard Smith37a45dd2013-10-24 01:21:09 +0000682 MaybeParseGNUAttributes(Attrs);
Richard Smith54ecd982013-02-20 19:22:51 +0000683 MaybeParseCXX11Attributes(Attrs);
Richard Smithdda56e42011-04-15 14:24:37 +0000684
685 // Maybe this is an alias-declaration.
Richard Smith6f1daa42016-12-16 00:58:48 +0000686 if (Tok.is(tok::equal)) {
687 if (InvalidDeclarator) {
688 SkipUntil(tok::semi);
689 return nullptr;
690 }
691
Richard Smithc2c8bb82013-10-15 01:34:54 +0000692 // If we had any misplaced attributes from earlier, this is where they
693 // should have been written.
694 if (MisplacedAttrs.Range.isValid()) {
695 Diag(MisplacedAttrs.Range.getBegin(), diag::err_attributes_not_allowed)
696 << FixItHint::CreateInsertionFromRange(
697 Tok.getLocation(),
698 CharSourceRange::getTokenRange(MisplacedAttrs.Range))
699 << FixItHint::CreateRemoval(MisplacedAttrs.Range);
700 Attrs.takeAllFrom(MisplacedAttrs);
701 }
702
Richard Smith6f1daa42016-12-16 00:58:48 +0000703 Decl *DeclFromDeclSpec = nullptr;
704 Decl *AD = ParseAliasDeclarationAfterDeclarator(
705 TemplateInfo, UsingLoc, D, DeclEnd, AS, Attrs, &DeclFromDeclSpec);
706 return Actions.ConvertDeclToDeclGroup(AD, DeclFromDeclSpec);
Alexis Hunt6aa9bee2012-06-23 05:07:58 +0000707 }
Mike Stump11289f42009-09-09 15:08:12 +0000708
Richard Smith6f1daa42016-12-16 00:58:48 +0000709 // C++11 attributes are not allowed on a using-declaration, but GNU ones
710 // are.
711 ProhibitAttributes(MisplacedAttrs);
712 ProhibitAttributes(Attrs);
Douglas Gregorfec52632009-06-20 00:51:54 +0000713
John McCall9b72f892010-11-10 02:40:36 +0000714 // Diagnose an attempt to declare a templated using-declaration.
Richard Smith810ad3e2013-01-29 10:02:16 +0000715 // In C++11, alias-declarations can be templates:
Richard Smithdda56e42011-04-15 14:24:37 +0000716 // template <...> using id = type;
Richard Smith6f1daa42016-12-16 00:58:48 +0000717 if (TemplateInfo.Kind) {
John McCall9b72f892010-11-10 02:40:36 +0000718 SourceRange R = TemplateInfo.getSourceRange();
Craig Topper54a6a682015-11-14 18:16:08 +0000719 Diag(UsingLoc, diag::err_templated_using_directive_declaration)
720 << 1 /* declaration */ << R << FixItHint::CreateRemoval(R);
John McCall9b72f892010-11-10 02:40:36 +0000721
722 // Unfortunately, we have to bail out instead of recovering by
723 // ignoring the parameters, just in case the nested name specifier
724 // depends on the parameters.
Craig Topper161e4db2014-05-21 06:02:52 +0000725 return nullptr;
John McCall9b72f892010-11-10 02:40:36 +0000726 }
727
Richard Smith6f1daa42016-12-16 00:58:48 +0000728 SmallVector<Decl *, 8> DeclsInGroup;
729 while (true) {
730 // Parse (optional) attributes (most likely GNU strong-using extension).
731 MaybeParseGNUAttributes(Attrs);
732
733 if (InvalidDeclarator)
734 SkipUntil(tok::comma, tok::semi, StopBeforeMatch);
735 else {
736 // "typename" keyword is allowed for identifiers only,
737 // because it may be a type definition.
738 if (D.TypenameLoc.isValid() &&
Faisal Vali2ab8c152017-12-30 04:15:27 +0000739 D.Name.getKind() != UnqualifiedIdKind::IK_Identifier) {
Richard Smith6f1daa42016-12-16 00:58:48 +0000740 Diag(D.Name.getSourceRange().getBegin(),
741 diag::err_typename_identifiers_only)
742 << FixItHint::CreateRemoval(SourceRange(D.TypenameLoc));
743 // Proceed parsing, but discard the typename keyword.
744 D.TypenameLoc = SourceLocation();
745 }
746
Richard Smith151c4562016-12-20 21:35:28 +0000747 Decl *UD = Actions.ActOnUsingDeclaration(getCurScope(), AS, UsingLoc,
748 D.TypenameLoc, D.SS, D.Name,
Erich Keanec480f302018-07-12 21:09:05 +0000749 D.EllipsisLoc, Attrs);
Richard Smith6f1daa42016-12-16 00:58:48 +0000750 if (UD)
751 DeclsInGroup.push_back(UD);
752 }
753
754 if (!TryConsumeToken(tok::comma))
755 break;
756
757 // Parse another using-declarator.
758 Attrs.clear();
759 InvalidDeclarator = ParseUsingDeclarator(Context, D);
Douglas Gregor882a61a2011-09-26 14:30:28 +0000760 }
761
Richard Smith6f1daa42016-12-16 00:58:48 +0000762 if (DeclsInGroup.size() > 1)
Aaron Ballmanc351fba2017-12-04 20:27:34 +0000763 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17 ?
Richard Smithb115e5d2017-08-13 23:37:29 +0000764 diag::warn_cxx17_compat_multi_using_declaration :
Richard Smith6f1daa42016-12-16 00:58:48 +0000765 diag::ext_multi_using_declaration);
766
767 // Eat ';'.
768 DeclEnd = Tok.getLocation();
769 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
770 !Attrs.empty() ? "attributes list"
771 : "using declaration"))
772 SkipUntil(tok::semi);
773
Richard Smith3beb7c62017-01-12 02:27:38 +0000774 return Actions.BuildDeclaratorGroup(DeclsInGroup);
Richard Smith6f1daa42016-12-16 00:58:48 +0000775}
776
Richard Smith6f1daa42016-12-16 00:58:48 +0000777Decl *Parser::ParseAliasDeclarationAfterDeclarator(
778 const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc,
779 UsingDeclarator &D, SourceLocation &DeclEnd, AccessSpecifier AS,
780 ParsedAttributes &Attrs, Decl **OwnedType) {
781 if (ExpectAndConsume(tok::equal)) {
782 SkipUntil(tok::semi);
783 return nullptr;
784 }
785
786 Diag(Tok.getLocation(), getLangOpts().CPlusPlus11 ?
787 diag::warn_cxx98_compat_alias_declaration :
788 diag::ext_alias_declaration);
789
790 // Type alias templates cannot be specialized.
791 int SpecKind = -1;
792 if (TemplateInfo.Kind == ParsedTemplateInfo::Template &&
Faisal Vali2ab8c152017-12-30 04:15:27 +0000793 D.Name.getKind() == UnqualifiedIdKind::IK_TemplateId)
Richard Smith6f1daa42016-12-16 00:58:48 +0000794 SpecKind = 0;
795 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization)
796 SpecKind = 1;
797 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
798 SpecKind = 2;
799 if (SpecKind != -1) {
800 SourceRange Range;
801 if (SpecKind == 0)
802 Range = SourceRange(D.Name.TemplateId->LAngleLoc,
803 D.Name.TemplateId->RAngleLoc);
804 else
805 Range = TemplateInfo.getSourceRange();
806 Diag(Range.getBegin(), diag::err_alias_declaration_specialization)
807 << SpecKind << Range;
808 SkipUntil(tok::semi);
809 return nullptr;
810 }
811
812 // Name must be an identifier.
Faisal Vali2ab8c152017-12-30 04:15:27 +0000813 if (D.Name.getKind() != UnqualifiedIdKind::IK_Identifier) {
Richard Smith6f1daa42016-12-16 00:58:48 +0000814 Diag(D.Name.StartLocation, diag::err_alias_declaration_not_identifier);
815 // No removal fixit: can't recover from this.
816 SkipUntil(tok::semi);
817 return nullptr;
818 } else if (D.TypenameLoc.isValid())
819 Diag(D.TypenameLoc, diag::err_alias_declaration_not_identifier)
820 << FixItHint::CreateRemoval(SourceRange(
821 D.TypenameLoc,
822 D.SS.isNotEmpty() ? D.SS.getEndLoc() : D.TypenameLoc));
823 else if (D.SS.isNotEmpty())
824 Diag(D.SS.getBeginLoc(), diag::err_alias_declaration_not_identifier)
825 << FixItHint::CreateRemoval(D.SS.getRange());
Richard Smith151c4562016-12-20 21:35:28 +0000826 if (D.EllipsisLoc.isValid())
827 Diag(D.EllipsisLoc, diag::err_alias_declaration_pack_expansion)
828 << FixItHint::CreateRemoval(SourceRange(D.EllipsisLoc));
Richard Smith6f1daa42016-12-16 00:58:48 +0000829
830 Decl *DeclFromDeclSpec = nullptr;
Faisal Vali421b2d12017-12-29 05:41:00 +0000831 TypeResult TypeAlias = ParseTypeName(
832 nullptr,
833 TemplateInfo.Kind ? DeclaratorContext::AliasTemplateContext
834 : DeclaratorContext::AliasDeclContext,
835 AS, &DeclFromDeclSpec, &Attrs);
Richard Smith6f1daa42016-12-16 00:58:48 +0000836 if (OwnedType)
837 *OwnedType = DeclFromDeclSpec;
838
839 // Eat ';'.
840 DeclEnd = Tok.getLocation();
841 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
842 !Attrs.empty() ? "attributes list"
843 : "alias declaration"))
844 SkipUntil(tok::semi);
845
846 TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
847 MultiTemplateParamsArg TemplateParamsArg(
848 TemplateParams ? TemplateParams->data() : nullptr,
849 TemplateParams ? TemplateParams->size() : 0);
850 return Actions.ActOnAliasDeclaration(getCurScope(), AS, TemplateParamsArg,
Erich Keanec480f302018-07-12 21:09:05 +0000851 UsingLoc, D.Name, Attrs, TypeAlias,
852 DeclFromDeclSpec);
Douglas Gregord7c4d982008-12-30 03:27:21 +0000853}
854
Benjamin Kramere56f3932011-12-23 17:00:35 +0000855/// ParseStaticAssertDeclaration - Parse C++0x or C11 static_assert-declaration.
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000856///
Peter Collingbourne3d9cbdc2011-04-15 00:35:57 +0000857/// [C++0x] static_assert-declaration:
858/// static_assert ( constant-expression , string-literal ) ;
859///
Benjamin Kramere56f3932011-12-23 17:00:35 +0000860/// [C11] static_assert-declaration:
Peter Collingbourne3d9cbdc2011-04-15 00:35:57 +0000861/// _Static_assert ( constant-expression , string-literal ) ;
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000862///
John McCall48871652010-08-21 09:40:31 +0000863Decl *Parser::ParseStaticAssertDeclaration(SourceLocation &DeclEnd){
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000864 assert(Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert) &&
Peter Collingbourne3d9cbdc2011-04-15 00:35:57 +0000865 "Not a static_assert declaration");
866
David Blaikiebbafb8a2012-03-11 07:00:24 +0000867 if (Tok.is(tok::kw__Static_assert) && !getLangOpts().C11)
Aaron Ballman1d935222019-08-27 14:41:39 +0000868 Diag(Tok, diag::ext_c11_feature) << Tok.getName();
Richard Smithb15c11c2011-10-17 23:06:20 +0000869 if (Tok.is(tok::kw_static_assert))
870 Diag(Tok, diag::warn_cxx98_compat_static_assert);
Peter Collingbourne3d9cbdc2011-04-15 00:35:57 +0000871
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000872 SourceLocation StaticAssertLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000873
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000874 BalancedDelimiterTracker T(*this, tok::l_paren);
875 if (T.consumeOpen()) {
Alp Tokerec543272013-12-24 09:48:30 +0000876 Diag(Tok, diag::err_expected) << tok::l_paren;
Richard Smith76965712012-09-13 19:12:50 +0000877 SkipMalformedDecl();
Craig Topper161e4db2014-05-21 06:02:52 +0000878 return nullptr;
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000879 }
Mike Stump11289f42009-09-09 15:08:12 +0000880
Richard Smithb3018062017-06-06 01:34:24 +0000881 EnterExpressionEvaluationContext ConstantEvaluated(
882 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
883 ExprResult AssertExpr(ParseConstantExpressionInExprEvalContext());
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000884 if (AssertExpr.isInvalid()) {
Richard Smith76965712012-09-13 19:12:50 +0000885 SkipMalformedDecl();
Craig Topper161e4db2014-05-21 06:02:52 +0000886 return nullptr;
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000887 }
Mike Stump11289f42009-09-09 15:08:12 +0000888
Richard Smith085a64f2014-06-20 19:57:12 +0000889 ExprResult AssertMessage;
890 if (Tok.is(tok::r_paren)) {
Aaron Ballmanc351fba2017-12-04 20:27:34 +0000891 Diag(Tok, getLangOpts().CPlusPlus17
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000892 ? diag::warn_cxx14_compat_static_assert_no_message
Richard Smith085a64f2014-06-20 19:57:12 +0000893 : diag::ext_static_assert_no_message)
Aaron Ballmanc351fba2017-12-04 20:27:34 +0000894 << (getLangOpts().CPlusPlus17
Richard Smith085a64f2014-06-20 19:57:12 +0000895 ? FixItHint()
896 : FixItHint::CreateInsertion(Tok.getLocation(), ", \"\""));
897 } else {
898 if (ExpectAndConsume(tok::comma)) {
899 SkipUntil(tok::semi);
900 return nullptr;
901 }
Anders Carlssonb4cf3ad2009-03-13 23:29:20 +0000902
Richard Smith085a64f2014-06-20 19:57:12 +0000903 if (!isTokenStringLiteral()) {
904 Diag(Tok, diag::err_expected_string_literal)
905 << /*Source='static_assert'*/1;
906 SkipMalformedDecl();
907 return nullptr;
908 }
Mike Stump11289f42009-09-09 15:08:12 +0000909
Richard Smith085a64f2014-06-20 19:57:12 +0000910 AssertMessage = ParseStringLiteralExpression();
911 if (AssertMessage.isInvalid()) {
912 SkipMalformedDecl();
913 return nullptr;
914 }
Richard Smithd67aea22012-03-06 03:21:47 +0000915 }
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000916
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000917 T.consumeClose();
Mike Stump11289f42009-09-09 15:08:12 +0000918
Chris Lattner49836b42009-04-02 04:16:50 +0000919 DeclEnd = Tok.getLocation();
Douglas Gregor45d6bdf2010-09-07 15:23:11 +0000920 ExpectAndConsumeSemi(diag::err_expected_semi_after_static_assert);
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000921
John McCallb268a282010-08-23 23:25:46 +0000922 return Actions.ActOnStaticAssertDeclaration(StaticAssertLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000923 AssertExpr.get(),
924 AssertMessage.get(),
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000925 T.getCloseLocation());
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000926}
927
Richard Smith74aeef52013-04-26 16:15:35 +0000928/// ParseDecltypeSpecifier - Parse a C++11 decltype specifier.
Anders Carlsson74948d02009-06-24 17:47:40 +0000929///
930/// 'decltype' ( expression )
Richard Smith74aeef52013-04-26 16:15:35 +0000931/// 'decltype' ( 'auto' ) [C++1y]
Anders Carlsson74948d02009-06-24 17:47:40 +0000932///
David Blaikie15a430a2011-12-04 05:04:18 +0000933SourceLocation Parser::ParseDecltypeSpecifier(DeclSpec &DS) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000934 assert(Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)
David Blaikie15a430a2011-12-04 05:04:18 +0000935 && "Not a decltype specifier");
Fangrui Song6907ce22018-07-30 19:24:48 +0000936
David Blaikie15a430a2011-12-04 05:04:18 +0000937 ExprResult Result;
938 SourceLocation StartLoc = Tok.getLocation();
939 SourceLocation EndLoc;
940
941 if (Tok.is(tok::annot_decltype)) {
942 Result = getExprAnnotation(Tok);
943 EndLoc = Tok.getAnnotationEndLoc();
Richard Smithaf3b3252017-05-18 19:21:48 +0000944 ConsumeAnnotationToken();
David Blaikie15a430a2011-12-04 05:04:18 +0000945 if (Result.isInvalid()) {
946 DS.SetTypeSpecError();
947 return EndLoc;
948 }
949 } else {
Richard Smith324df552012-02-24 22:30:04 +0000950 if (Tok.getIdentifierInfo()->isStr("decltype"))
951 Diag(Tok, diag::warn_cxx98_compat_decltype);
Richard Smithfd3da932012-02-24 18:10:23 +0000952
David Blaikie15a430a2011-12-04 05:04:18 +0000953 ConsumeToken();
954
955 BalancedDelimiterTracker T(*this, tok::l_paren);
956 if (T.expectAndConsume(diag::err_expected_lparen_after,
957 "decltype", tok::r_paren)) {
958 DS.SetTypeSpecError();
959 return T.getOpenLocation() == Tok.getLocation() ?
960 StartLoc : T.getOpenLocation();
961 }
962
Richard Smith74aeef52013-04-26 16:15:35 +0000963 // Check for C++1y 'decltype(auto)'.
964 if (Tok.is(tok::kw_auto)) {
965 // No need to disambiguate here: an expression can't start with 'auto',
966 // because the typename-specifier in a function-style cast operation can't
967 // be 'auto'.
968 Diag(Tok.getLocation(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000969 getLangOpts().CPlusPlus14
Richard Smith74aeef52013-04-26 16:15:35 +0000970 ? diag::warn_cxx11_compat_decltype_auto_type_specifier
971 : diag::ext_decltype_auto_type_specifier);
972 ConsumeToken();
973 } else {
974 // Parse the expression
David Blaikie15a430a2011-12-04 05:04:18 +0000975
Richard Smith74aeef52013-04-26 16:15:35 +0000976 // C++11 [dcl.type.simple]p4:
977 // The operand of the decltype specifier is an unevaluated operand.
Faisal Valid143a0c2017-04-01 21:30:49 +0000978 EnterExpressionEvaluationContext Unevaluated(
979 Actions, Sema::ExpressionEvaluationContext::Unevaluated, nullptr,
Nicolas Lesserb6d5c582018-07-12 18:45:41 +0000980 Sema::ExpressionEvaluationContextRecord::EK_Decltype);
Kaelyn Takata5cc85352015-04-10 19:16:46 +0000981 Result =
982 Actions.CorrectDelayedTyposInExpr(ParseExpression(), [](Expr *E) {
983 return E->hasPlaceholderType() ? ExprError() : E;
984 });
Richard Smith74aeef52013-04-26 16:15:35 +0000985 if (Result.isInvalid()) {
986 DS.SetTypeSpecError();
Alexey Bataevee6507d2013-11-18 08:17:37 +0000987 if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch)) {
Richard Smith74aeef52013-04-26 16:15:35 +0000988 EndLoc = ConsumeParen();
Argyrios Kyrtzidisc38395a2012-10-26 22:53:44 +0000989 } else {
Richard Smith74aeef52013-04-26 16:15:35 +0000990 if (PP.isBacktrackEnabled() && Tok.is(tok::semi)) {
991 // Backtrack to get the location of the last token before the semi.
992 PP.RevertCachedTokens(2);
993 ConsumeToken(); // the semi.
994 EndLoc = ConsumeAnyToken();
995 assert(Tok.is(tok::semi));
996 } else {
997 EndLoc = Tok.getLocation();
998 }
Argyrios Kyrtzidisc38395a2012-10-26 22:53:44 +0000999 }
Richard Smith74aeef52013-04-26 16:15:35 +00001000 return EndLoc;
Argyrios Kyrtzidisc38395a2012-10-26 22:53:44 +00001001 }
Richard Smith74aeef52013-04-26 16:15:35 +00001002
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001003 Result = Actions.ActOnDecltypeExpression(Result.get());
David Blaikie15a430a2011-12-04 05:04:18 +00001004 }
1005
1006 // Match the ')'
1007 T.consumeClose();
1008 if (T.getCloseLocation().isInvalid()) {
1009 DS.SetTypeSpecError();
1010 // FIXME: this should return the location of the last token
1011 // that was consumed (by "consumeClose()")
1012 return T.getCloseLocation();
1013 }
1014
Richard Smithfd555f62012-02-22 02:04:18 +00001015 if (Result.isInvalid()) {
1016 DS.SetTypeSpecError();
1017 return T.getCloseLocation();
1018 }
1019
David Blaikie15a430a2011-12-04 05:04:18 +00001020 EndLoc = T.getCloseLocation();
Anders Carlsson74948d02009-06-24 17:47:40 +00001021 }
Richard Smith74aeef52013-04-26 16:15:35 +00001022 assert(!Result.isInvalid());
Mike Stump11289f42009-09-09 15:08:12 +00001023
Craig Topper161e4db2014-05-21 06:02:52 +00001024 const char *PrevSpec = nullptr;
John McCall49bfce42009-08-03 20:12:06 +00001025 unsigned DiagID;
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001026 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
Anders Carlsson74948d02009-06-24 17:47:40 +00001027 // Check for duplicate type specifiers (e.g. "int decltype(a)").
Richard Smith74aeef52013-04-26 16:15:35 +00001028 if (Result.get()
1029 ? DS.SetTypeSpecType(DeclSpec::TST_decltype, StartLoc, PrevSpec,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001030 DiagID, Result.get(), Policy)
Richard Smith74aeef52013-04-26 16:15:35 +00001031 : DS.SetTypeSpecType(DeclSpec::TST_decltype_auto, StartLoc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001032 DiagID, Policy)) {
John McCall49bfce42009-08-03 20:12:06 +00001033 Diag(StartLoc, DiagID) << PrevSpec;
David Blaikie15a430a2011-12-04 05:04:18 +00001034 DS.SetTypeSpecError();
1035 }
1036 return EndLoc;
1037}
1038
Fangrui Song6907ce22018-07-30 19:24:48 +00001039void Parser::AnnotateExistingDecltypeSpecifier(const DeclSpec& DS,
David Blaikie15a430a2011-12-04 05:04:18 +00001040 SourceLocation StartLoc,
1041 SourceLocation EndLoc) {
1042 // make sure we have a token we can turn into an annotation token
1043 if (PP.isBacktrackEnabled())
1044 PP.RevertCachedTokens(1);
1045 else
Ilya Biryukov929af672019-05-17 09:32:05 +00001046 PP.EnterToken(Tok, /*IsReinject*/true);
David Blaikie15a430a2011-12-04 05:04:18 +00001047
1048 Tok.setKind(tok::annot_decltype);
Faisal Vali090da2d2018-01-01 18:23:28 +00001049 setExprAnnotation(Tok,
1050 DS.getTypeSpecType() == TST_decltype ? DS.getRepAsExpr() :
1051 DS.getTypeSpecType() == TST_decltype_auto ? ExprResult() :
1052 ExprError());
David Blaikie15a430a2011-12-04 05:04:18 +00001053 Tok.setAnnotationEndLoc(EndLoc);
1054 Tok.setLocation(StartLoc);
1055 PP.AnnotateCachedTokens(Tok);
Anders Carlsson74948d02009-06-24 17:47:40 +00001056}
1057
Alexis Hunt4a257072011-05-19 05:37:45 +00001058void Parser::ParseUnderlyingTypeSpecifier(DeclSpec &DS) {
1059 assert(Tok.is(tok::kw___underlying_type) &&
1060 "Not an underlying type specifier");
1061
1062 SourceLocation StartLoc = ConsumeToken();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001063 BalancedDelimiterTracker T(*this, tok::l_paren);
1064 if (T.expectAndConsume(diag::err_expected_lparen_after,
1065 "__underlying_type", tok::r_paren)) {
Alexis Hunt4a257072011-05-19 05:37:45 +00001066 return;
1067 }
1068
1069 TypeResult Result = ParseTypeName();
1070 if (Result.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00001071 SkipUntil(tok::r_paren, StopAtSemi);
Alexis Hunt4a257072011-05-19 05:37:45 +00001072 return;
1073 }
1074
1075 // Match the ')'
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001076 T.consumeClose();
1077 if (T.getCloseLocation().isInvalid())
Alexis Hunt4a257072011-05-19 05:37:45 +00001078 return;
1079
Craig Topper161e4db2014-05-21 06:02:52 +00001080 const char *PrevSpec = nullptr;
Alexis Hunt4a257072011-05-19 05:37:45 +00001081 unsigned DiagID;
Alexis Hunte852b102011-05-24 22:41:36 +00001082 if (DS.SetTypeSpecType(DeclSpec::TST_underlyingType, StartLoc, PrevSpec,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001083 DiagID, Result.get(),
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001084 Actions.getASTContext().getPrintingPolicy()))
Alexis Hunt4a257072011-05-19 05:37:45 +00001085 Diag(StartLoc, DiagID) << PrevSpec;
Enea Zaffanellaa90af722013-07-06 18:54:58 +00001086 DS.setTypeofParensRange(T.getRange());
Alexis Hunt4a257072011-05-19 05:37:45 +00001087}
1088
David Blaikie00ee7a082011-10-25 15:01:20 +00001089/// ParseBaseTypeSpecifier - Parse a C++ base-type-specifier which is either a
Fangrui Song6907ce22018-07-30 19:24:48 +00001090/// class name or decltype-specifier. Note that we only check that the result
1091/// names a type; semantic analysis will need to verify that the type names a
1092/// class. The result is either a type or null, depending on whether a type
David Blaikie00ee7a082011-10-25 15:01:20 +00001093/// name was found.
Douglas Gregor831c93f2008-11-05 20:51:48 +00001094///
Richard Smith4c96e992013-02-19 23:47:15 +00001095/// base-type-specifier: [C++11 class.derived]
David Blaikie00ee7a082011-10-25 15:01:20 +00001096/// class-or-decltype
Richard Smith4c96e992013-02-19 23:47:15 +00001097/// class-or-decltype: [C++11 class.derived]
David Blaikie00ee7a082011-10-25 15:01:20 +00001098/// nested-name-specifier[opt] class-name
1099/// decltype-specifier
Richard Smith4c96e992013-02-19 23:47:15 +00001100/// class-name: [C++ class.name]
Douglas Gregor831c93f2008-11-05 20:51:48 +00001101/// identifier
Douglas Gregord54dfb82009-02-25 23:52:28 +00001102/// simple-template-id
Mike Stump11289f42009-09-09 15:08:12 +00001103///
Richard Smith4c96e992013-02-19 23:47:15 +00001104/// In C++98, instead of base-type-specifier, we have:
1105///
1106/// ::[opt] nested-name-specifier[opt] class-name
Craig Topper9ad7e262014-10-31 06:57:07 +00001107TypeResult Parser::ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
1108 SourceLocation &EndLocation) {
David Blaikiedd58d4c2011-10-25 18:46:41 +00001109 // Ignore attempts to use typename
1110 if (Tok.is(tok::kw_typename)) {
1111 Diag(Tok, diag::err_expected_class_name_not_template)
1112 << FixItHint::CreateRemoval(Tok.getLocation());
1113 ConsumeToken();
1114 }
1115
David Blaikieafa155f2011-10-25 18:17:58 +00001116 // Parse optional nested-name-specifier
1117 CXXScopeSpec SS;
Richard Smithb23c5e82019-05-09 03:31:27 +00001118 if (ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false))
1119 return true;
David Blaikieafa155f2011-10-25 18:17:58 +00001120
1121 BaseLoc = Tok.getLocation();
1122
David Blaikie1cd50022011-10-25 17:10:12 +00001123 // Parse decltype-specifier
Fangrui Song6907ce22018-07-30 19:24:48 +00001124 // tok == kw_decltype is just error recovery, it can only happen when SS
David Blaikie15a430a2011-12-04 05:04:18 +00001125 // isn't empty
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001126 if (Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)) {
David Blaikieafa155f2011-10-25 18:17:58 +00001127 if (SS.isNotEmpty())
1128 Diag(SS.getBeginLoc(), diag::err_unexpected_scope_on_base_decltype)
1129 << FixItHint::CreateRemoval(SS.getRange());
David Blaikie1cd50022011-10-25 17:10:12 +00001130 // Fake up a Declarator to use with ActOnTypeName.
1131 DeclSpec DS(AttrFactory);
1132
David Blaikie7491e732011-12-08 04:53:15 +00001133 EndLocation = ParseDecltypeSpecifier(DS);
David Blaikie1cd50022011-10-25 17:10:12 +00001134
Faisal Vali421b2d12017-12-29 05:41:00 +00001135 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
David Blaikie1cd50022011-10-25 17:10:12 +00001136 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
1137 }
1138
Douglas Gregord54dfb82009-02-25 23:52:28 +00001139 // Check whether we have a template-id that names a type.
1140 if (Tok.is(tok::annot_template_id)) {
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00001141 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregor46c59612010-01-12 17:52:59 +00001142 if (TemplateId->Kind == TNK_Type_template ||
Richard Smithb23c5e82019-05-09 03:31:27 +00001143 TemplateId->Kind == TNK_Dependent_template_name ||
1144 TemplateId->Kind == TNK_Undeclared_template) {
Richard Smitha42fd842020-01-17 15:42:11 -08001145 AnnotateTemplateIdTokenAsType(SS, /*IsClassName*/true);
Douglas Gregord54dfb82009-02-25 23:52:28 +00001146
1147 assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
John McCallba7bf592010-08-24 05:47:05 +00001148 ParsedType Type = getTypeAnnotation(Tok);
Douglas Gregord54dfb82009-02-25 23:52:28 +00001149 EndLocation = Tok.getAnnotationEndLoc();
Richard Smithaf3b3252017-05-18 19:21:48 +00001150 ConsumeAnnotationToken();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001151
1152 if (Type)
1153 return Type;
1154 return true;
Douglas Gregord54dfb82009-02-25 23:52:28 +00001155 }
1156
1157 // Fall through to produce an error below.
1158 }
1159
Douglas Gregor831c93f2008-11-05 20:51:48 +00001160 if (Tok.isNot(tok::identifier)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00001161 Diag(Tok, diag::err_expected_class_name);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001162 return true;
Douglas Gregor831c93f2008-11-05 20:51:48 +00001163 }
1164
Douglas Gregor18473f32010-01-12 21:28:44 +00001165 IdentifierInfo *Id = Tok.getIdentifierInfo();
1166 SourceLocation IdLoc = ConsumeToken();
1167
1168 if (Tok.is(tok::less)) {
1169 // It looks the user intended to write a template-id here, but the
1170 // template-name was wrong. Try to fix that.
1171 TemplateNameKind TNK = TNK_Type_template;
1172 TemplateTy Template;
Douglas Gregor0be31a22010-07-02 17:43:08 +00001173 if (!Actions.DiagnoseUnknownTemplateName(*Id, IdLoc, getCurScope(),
Douglas Gregore7c20652011-03-02 00:47:37 +00001174 &SS, Template, TNK)) {
Douglas Gregor18473f32010-01-12 21:28:44 +00001175 Diag(IdLoc, diag::err_unknown_template_name)
1176 << Id;
1177 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001178
Serge Pavlovb716b3c2013-08-10 05:54:47 +00001179 if (!Template) {
1180 TemplateArgList TemplateArgs;
1181 SourceLocation LAngleLoc, RAngleLoc;
Richard Smith9a420f92017-05-10 21:47:30 +00001182 ParseTemplateIdAfterTemplateName(true, LAngleLoc, TemplateArgs,
1183 RAngleLoc);
Douglas Gregor18473f32010-01-12 21:28:44 +00001184 return true;
Serge Pavlovb716b3c2013-08-10 05:54:47 +00001185 }
Douglas Gregor18473f32010-01-12 21:28:44 +00001186
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001187 // Form the template name
Douglas Gregor18473f32010-01-12 21:28:44 +00001188 UnqualifiedId TemplateName;
1189 TemplateName.setIdentifier(Id, IdLoc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001190
Douglas Gregor18473f32010-01-12 21:28:44 +00001191 // Parse the full template-id, then turn it into a type.
Abramo Bagnara7945c982012-01-27 09:46:47 +00001192 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
Richard Smith62559bd2017-02-01 21:36:38 +00001193 TemplateName))
Douglas Gregor18473f32010-01-12 21:28:44 +00001194 return true;
Richard Smith62559bd2017-02-01 21:36:38 +00001195 if (TNK == TNK_Type_template || TNK == TNK_Dependent_template_name)
Richard Smitha42fd842020-01-17 15:42:11 -08001196 AnnotateTemplateIdTokenAsType(SS, /*IsClassName*/true);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001197
Douglas Gregor18473f32010-01-12 21:28:44 +00001198 // If we didn't end up with a typename token, there's nothing more we
1199 // can do.
1200 if (Tok.isNot(tok::annot_typename))
1201 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001202
Douglas Gregor18473f32010-01-12 21:28:44 +00001203 // Retrieve the type from the annotation token, consume that token, and
1204 // return.
1205 EndLocation = Tok.getAnnotationEndLoc();
John McCallba7bf592010-08-24 05:47:05 +00001206 ParsedType Type = getTypeAnnotation(Tok);
Richard Smithaf3b3252017-05-18 19:21:48 +00001207 ConsumeAnnotationToken();
Douglas Gregor18473f32010-01-12 21:28:44 +00001208 return Type;
1209 }
1210
Douglas Gregor831c93f2008-11-05 20:51:48 +00001211 // We have an identifier; check whether it is actually a type.
Craig Topper161e4db2014-05-21 06:02:52 +00001212 IdentifierInfo *CorrectedII = nullptr;
Richard Smith600b5262017-01-26 20:40:47 +00001213 ParsedType Type = Actions.getTypeName(
Rui Ueyama49a3ad22019-07-16 04:46:31 +00001214 *Id, IdLoc, getCurScope(), &SS, /*isClassName=*/true, false, nullptr,
Richard Smith600b5262017-01-26 20:40:47 +00001215 /*IsCtorOrDtorName=*/false,
Rui Ueyama49a3ad22019-07-16 04:46:31 +00001216 /*WantNontrivialTypeSourceInfo=*/true,
Richard Smith600b5262017-01-26 20:40:47 +00001217 /*IsClassTemplateDeductionContext*/ false, &CorrectedII);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001218 if (!Type) {
Douglas Gregorfe17d252010-02-16 19:09:40 +00001219 Diag(IdLoc, diag::err_expected_class_name);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001220 return true;
Douglas Gregor831c93f2008-11-05 20:51:48 +00001221 }
1222
1223 // Consume the identifier.
Douglas Gregor18473f32010-01-12 21:28:44 +00001224 EndLocation = IdLoc;
Nick Lewycky19b9f952010-07-26 16:56:01 +00001225
1226 // Fake up a Declarator to use with ActOnTypeName.
John McCall084e83d2011-03-24 11:26:52 +00001227 DeclSpec DS(AttrFactory);
Nick Lewycky19b9f952010-07-26 16:56:01 +00001228 DS.SetRangeStart(IdLoc);
1229 DS.SetRangeEnd(EndLocation);
Douglas Gregore7c20652011-03-02 00:47:37 +00001230 DS.getTypeSpecScope() = SS;
Nick Lewycky19b9f952010-07-26 16:56:01 +00001231
Craig Topper161e4db2014-05-21 06:02:52 +00001232 const char *PrevSpec = nullptr;
Nick Lewycky19b9f952010-07-26 16:56:01 +00001233 unsigned DiagID;
Faisal Vali090da2d2018-01-01 18:23:28 +00001234 DS.SetTypeSpecType(TST_typename, IdLoc, PrevSpec, DiagID, Type,
1235 Actions.getASTContext().getPrintingPolicy());
Nick Lewycky19b9f952010-07-26 16:56:01 +00001236
Faisal Vali421b2d12017-12-29 05:41:00 +00001237 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
Nick Lewycky19b9f952010-07-26 16:56:01 +00001238 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
Douglas Gregor831c93f2008-11-05 20:51:48 +00001239}
1240
John McCall8d32c052012-05-22 21:28:12 +00001241void Parser::ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001242 while (Tok.isOneOf(tok::kw___single_inheritance,
1243 tok::kw___multiple_inheritance,
1244 tok::kw___virtual_inheritance)) {
John McCall8d32c052012-05-22 21:28:12 +00001245 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
1246 SourceLocation AttrNameLoc = ConsumeToken();
Craig Topper161e4db2014-05-21 06:02:52 +00001247 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
Erich Keanee891aa92018-07-13 15:07:47 +00001248 ParsedAttr::AS_Keyword);
John McCall8d32c052012-05-22 21:28:12 +00001249 }
1250}
1251
Richard Smith369b9f92012-06-25 21:37:02 +00001252/// Determine whether the following tokens are valid after a type-specifier
1253/// which could be a standalone declaration. This will conservatively return
1254/// true if there's any doubt, and is appropriate for insert-';' fixits.
Richard Smith200f47c2012-07-02 19:14:01 +00001255bool Parser::isValidAfterTypeSpecifier(bool CouldBeBitfield) {
Richard Smith369b9f92012-06-25 21:37:02 +00001256 // This switch enumerates the valid "follow" set for type-specifiers.
1257 switch (Tok.getKind()) {
1258 default: break;
1259 case tok::semi: // struct foo {...} ;
1260 case tok::star: // struct foo {...} * P;
1261 case tok::amp: // struct foo {...} & R = ...
Richard Smith1ac67d12013-01-19 03:48:05 +00001262 case tok::ampamp: // struct foo {...} && R = ...
Richard Smith369b9f92012-06-25 21:37:02 +00001263 case tok::identifier: // struct foo {...} V ;
1264 case tok::r_paren: //(struct foo {...} ) {4}
Richard Smith1600e242019-04-16 00:47:45 +00001265 case tok::coloncolon: // struct foo {...} :: a::b;
Richard Smith369b9f92012-06-25 21:37:02 +00001266 case tok::annot_cxxscope: // struct foo {...} a:: b;
1267 case tok::annot_typename: // struct foo {...} a ::b;
1268 case tok::annot_template_id: // struct foo {...} a<int> ::b;
Richard Smith1600e242019-04-16 00:47:45 +00001269 case tok::kw_decltype: // struct foo {...} decltype (a)::b;
Richard Smith369b9f92012-06-25 21:37:02 +00001270 case tok::l_paren: // struct foo {...} ( x);
1271 case tok::comma: // __builtin_offsetof(struct foo{...} ,
Richard Smith1ac67d12013-01-19 03:48:05 +00001272 case tok::kw_operator: // struct foo operator ++() {...}
Alp Tokerd3f79c52013-11-24 20:24:54 +00001273 case tok::kw___declspec: // struct foo {...} __declspec(...)
Richard Smith843f18f2014-08-13 02:13:15 +00001274 case tok::l_square: // void f(struct f [ 3])
1275 case tok::ellipsis: // void f(struct f ... [Ns])
Abramo Bagnara152eb392014-08-16 08:29:27 +00001276 // FIXME: we should emit semantic diagnostic when declaration
1277 // attribute is in type attribute position.
1278 case tok::kw___attribute: // struct foo __attribute__((used)) x;
David Majnemer15b311c2016-06-14 03:20:28 +00001279 case tok::annot_pragma_pack: // struct foo {...} _Pragma(pack(pop));
1280 // struct foo {...} _Pragma(section(...));
1281 case tok::annot_pragma_ms_pragma:
1282 // struct foo {...} _Pragma(vtordisp(pop));
1283 case tok::annot_pragma_ms_vtordisp:
1284 // struct foo {...} _Pragma(pointers_to_members(...));
1285 case tok::annot_pragma_ms_pointers_to_members:
Richard Smith369b9f92012-06-25 21:37:02 +00001286 return true;
Richard Smith200f47c2012-07-02 19:14:01 +00001287 case tok::colon:
1288 return CouldBeBitfield; // enum E { ... } : 2;
Reid Klecknercfa91552016-03-21 16:08:49 +00001289 // Microsoft compatibility
1290 case tok::kw___cdecl: // struct foo {...} __cdecl x;
1291 case tok::kw___fastcall: // struct foo {...} __fastcall x;
1292 case tok::kw___stdcall: // struct foo {...} __stdcall x;
1293 case tok::kw___thiscall: // struct foo {...} __thiscall x;
1294 case tok::kw___vectorcall: // struct foo {...} __vectorcall x;
1295 // We will diagnose these calling-convention specifiers on non-function
1296 // declarations later, so claim they are valid after a type specifier.
1297 return getLangOpts().MicrosoftExt;
Richard Smith369b9f92012-06-25 21:37:02 +00001298 // Type qualifiers
1299 case tok::kw_const: // struct foo {...} const x;
1300 case tok::kw_volatile: // struct foo {...} volatile x;
1301 case tok::kw_restrict: // struct foo {...} restrict x;
Richard Smith843f18f2014-08-13 02:13:15 +00001302 case tok::kw__Atomic: // struct foo {...} _Atomic x;
Nico Rieck3e1ee832014-12-04 23:30:25 +00001303 case tok::kw___unaligned: // struct foo {...} __unaligned *x;
Richard Smith1ac67d12013-01-19 03:48:05 +00001304 // Function specifiers
1305 // Note, no 'explicit'. An explicit function must be either a conversion
1306 // operator or a constructor. Either way, it can't have a return type.
1307 case tok::kw_inline: // struct foo inline f();
1308 case tok::kw_virtual: // struct foo virtual f();
1309 case tok::kw_friend: // struct foo friend f();
Richard Smith369b9f92012-06-25 21:37:02 +00001310 // Storage-class specifiers
1311 case tok::kw_static: // struct foo {...} static x;
1312 case tok::kw_extern: // struct foo {...} extern x;
1313 case tok::kw_typedef: // struct foo {...} typedef x;
1314 case tok::kw_register: // struct foo {...} register x;
1315 case tok::kw_auto: // struct foo {...} auto x;
1316 case tok::kw_mutable: // struct foo {...} mutable x;
Richard Smith1ac67d12013-01-19 03:48:05 +00001317 case tok::kw_thread_local: // struct foo {...} thread_local x;
Richard Smith369b9f92012-06-25 21:37:02 +00001318 case tok::kw_constexpr: // struct foo {...} constexpr x;
Richard Smitha6e8b682019-09-04 20:30:37 +00001319 case tok::kw_consteval: // struct foo {...} consteval x;
1320 case tok::kw_constinit: // struct foo {...} constinit x;
Richard Smith369b9f92012-06-25 21:37:02 +00001321 // As shown above, type qualifiers and storage class specifiers absolutely
1322 // can occur after class specifiers according to the grammar. However,
1323 // almost no one actually writes code like this. If we see one of these,
1324 // it is much more likely that someone missed a semi colon and the
1325 // type/storage class specifier we're seeing is part of the *next*
1326 // intended declaration, as in:
1327 //
1328 // struct foo { ... }
1329 // typedef int X;
1330 //
1331 // We'd really like to emit a missing semicolon error instead of emitting
1332 // an error on the 'int' saying that you can't have two type specifiers in
1333 // the same declaration of X. Because of this, we look ahead past this
1334 // token to see if it's a type specifier. If so, we know the code is
1335 // otherwise invalid, so we can produce the expected semi error.
1336 if (!isKnownToBeTypeSpecifier(NextToken()))
1337 return true;
1338 break;
1339 case tok::r_brace: // struct bar { struct foo {...} }
1340 // Missing ';' at end of struct is accepted as an extension in C mode.
1341 if (!getLangOpts().CPlusPlus)
1342 return true;
1343 break;
Richard Smith52c5b872013-01-29 04:13:32 +00001344 case tok::greater:
1345 // template<class T = class X>
1346 return getLangOpts().CPlusPlus;
Richard Smith369b9f92012-06-25 21:37:02 +00001347 }
1348 return false;
1349}
1350
Douglas Gregor556877c2008-04-13 21:30:24 +00001351/// ParseClassSpecifier - Parse a C++ class-specifier [C++ class] or
1352/// elaborated-type-specifier [C++ dcl.type.elab]; we can't tell which
1353/// until we reach the start of a definition or see a token that
Richard Smithc5b05522012-03-12 07:56:15 +00001354/// cannot start a definition.
Douglas Gregor556877c2008-04-13 21:30:24 +00001355///
1356/// class-specifier: [C++ class]
1357/// class-head '{' member-specification[opt] '}'
1358/// class-head '{' member-specification[opt] '}' attributes[opt]
1359/// class-head:
1360/// class-key identifier[opt] base-clause[opt]
1361/// class-key nested-name-specifier identifier base-clause[opt]
1362/// class-key nested-name-specifier[opt] simple-template-id
1363/// base-clause[opt]
1364/// [GNU] class-key attributes[opt] identifier[opt] base-clause[opt]
Mike Stump11289f42009-09-09 15:08:12 +00001365/// [GNU] class-key attributes[opt] nested-name-specifier
Douglas Gregor556877c2008-04-13 21:30:24 +00001366/// identifier base-clause[opt]
Mike Stump11289f42009-09-09 15:08:12 +00001367/// [GNU] class-key attributes[opt] nested-name-specifier[opt]
Douglas Gregor556877c2008-04-13 21:30:24 +00001368/// simple-template-id base-clause[opt]
1369/// class-key:
1370/// 'class'
1371/// 'struct'
1372/// 'union'
1373///
1374/// elaborated-type-specifier: [C++ dcl.type.elab]
Mike Stump11289f42009-09-09 15:08:12 +00001375/// class-key ::[opt] nested-name-specifier[opt] identifier
1376/// class-key ::[opt] nested-name-specifier[opt] 'template'[opt]
1377/// simple-template-id
Douglas Gregor556877c2008-04-13 21:30:24 +00001378///
1379/// Note that the C++ class-specifier and elaborated-type-specifier,
1380/// together, subsume the C99 struct-or-union-specifier:
1381///
1382/// struct-or-union-specifier: [C99 6.7.2.1]
1383/// struct-or-union identifier[opt] '{' struct-contents '}'
1384/// struct-or-union identifier
1385/// [GNU] struct-or-union attributes[opt] identifier[opt] '{' struct-contents
1386/// '}' attributes[opt]
1387/// [GNU] struct-or-union attributes[opt] identifier
1388/// struct-or-union:
1389/// 'struct'
1390/// 'union'
Chris Lattnerffaa0e62009-04-12 21:49:30 +00001391void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind,
1392 SourceLocation StartLoc, DeclSpec &DS,
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001393 const ParsedTemplateInfo &TemplateInfo,
Fangrui Song6907ce22018-07-30 19:24:48 +00001394 AccessSpecifier AS,
1395 bool EnteringContext, DeclSpecContext DSC,
Bill Wendling44426052012-12-20 19:22:21 +00001396 ParsedAttributesWithRange &Attributes) {
Joao Matose9a3ed42012-08-31 22:18:20 +00001397 DeclSpec::TST TagType;
1398 if (TagTokKind == tok::kw_struct)
1399 TagType = DeclSpec::TST_struct;
1400 else if (TagTokKind == tok::kw___interface)
1401 TagType = DeclSpec::TST_interface;
1402 else if (TagTokKind == tok::kw_class)
1403 TagType = DeclSpec::TST_class;
1404 else {
Chris Lattnerffaa0e62009-04-12 21:49:30 +00001405 assert(TagTokKind == tok::kw_union && "Not a class specifier");
1406 TagType = DeclSpec::TST_union;
1407 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001408
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00001409 if (Tok.is(tok::code_completion)) {
1410 // Code completion for a struct, class, or union name.
Douglas Gregor0be31a22010-07-02 17:43:08 +00001411 Actions.CodeCompleteTag(getCurScope(), TagType);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001412 return cutOffParsing();
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00001413 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001414
Chandler Carruth2d69ec72010-06-28 08:39:25 +00001415 // C++03 [temp.explicit] 14.7.2/8:
1416 // The usual access checking rules do not apply to names used to specify
1417 // explicit instantiations.
1418 //
1419 // As an extension we do not perform access checking on the names used to
1420 // specify explicit specializations either. This is important to allow
1421 // specializing traits classes for private types.
John McCall6347b682012-05-07 06:16:58 +00001422 //
1423 // Note that we don't suppress if this turns out to be an elaborated
1424 // type specifier.
1425 bool shouldDelayDiagsInTag =
1426 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
1427 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
1428 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
Chandler Carruth2d69ec72010-06-28 08:39:25 +00001429
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001430 ParsedAttributesWithRange attrs(AttrFactory);
Douglas Gregor556877c2008-04-13 21:30:24 +00001431 // If attributes exist after tag, parse them.
Richard Smith37a45dd2013-10-24 01:21:09 +00001432 MaybeParseGNUAttributes(attrs);
Aaron Ballman068aa512015-05-20 20:58:33 +00001433 MaybeParseMicrosoftDeclSpecs(attrs);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001434
John McCall8d32c052012-05-22 21:28:12 +00001435 // Parse inheritance specifiers.
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001436 if (Tok.isOneOf(tok::kw___single_inheritance,
1437 tok::kw___multiple_inheritance,
1438 tok::kw___virtual_inheritance))
Richard Smith37a45dd2013-10-24 01:21:09 +00001439 ParseMicrosoftInheritanceClassAttributes(attrs);
John McCall8d32c052012-05-22 21:28:12 +00001440
Alexis Hunt96d5c762009-11-21 08:43:09 +00001441 // If C++0x attributes exist here, parse them.
1442 // FIXME: Are we consistent with the ordering of parsing of different
1443 // styles of attributes?
Richard Smith89645bc2013-01-02 12:01:23 +00001444 MaybeParseCXX11Attributes(attrs);
Mike Stump11289f42009-09-09 15:08:12 +00001445
Michael Han309af292013-01-07 16:57:11 +00001446 // Source location used by FIXIT to insert misplaced
1447 // C++11 attributes
1448 SourceLocation AttrFixitLoc = Tok.getLocation();
1449
Nico Weber7c3c5be2014-09-23 04:09:56 +00001450 if (TagType == DeclSpec::TST_struct &&
David Majnemer86330af2014-12-29 02:14:26 +00001451 Tok.isNot(tok::identifier) &&
1452 !Tok.isAnnotation() &&
Nico Weber7c3c5be2014-09-23 04:09:56 +00001453 Tok.getIdentifierInfo() &&
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001454 Tok.isOneOf(tok::kw___is_abstract,
Eric Fiselier07360662017-04-12 22:12:15 +00001455 tok::kw___is_aggregate,
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001456 tok::kw___is_arithmetic,
1457 tok::kw___is_array,
David Majnemerb3d96882016-05-23 17:21:55 +00001458 tok::kw___is_assignable,
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001459 tok::kw___is_base_of,
1460 tok::kw___is_class,
1461 tok::kw___is_complete_type,
1462 tok::kw___is_compound,
1463 tok::kw___is_const,
1464 tok::kw___is_constructible,
1465 tok::kw___is_convertible,
1466 tok::kw___is_convertible_to,
1467 tok::kw___is_destructible,
1468 tok::kw___is_empty,
1469 tok::kw___is_enum,
1470 tok::kw___is_floating_point,
1471 tok::kw___is_final,
1472 tok::kw___is_function,
1473 tok::kw___is_fundamental,
1474 tok::kw___is_integral,
1475 tok::kw___is_interface_class,
1476 tok::kw___is_literal,
1477 tok::kw___is_lvalue_expr,
1478 tok::kw___is_lvalue_reference,
1479 tok::kw___is_member_function_pointer,
1480 tok::kw___is_member_object_pointer,
1481 tok::kw___is_member_pointer,
1482 tok::kw___is_nothrow_assignable,
1483 tok::kw___is_nothrow_constructible,
1484 tok::kw___is_nothrow_destructible,
1485 tok::kw___is_object,
1486 tok::kw___is_pod,
1487 tok::kw___is_pointer,
1488 tok::kw___is_polymorphic,
1489 tok::kw___is_reference,
1490 tok::kw___is_rvalue_expr,
1491 tok::kw___is_rvalue_reference,
1492 tok::kw___is_same,
1493 tok::kw___is_scalar,
1494 tok::kw___is_sealed,
1495 tok::kw___is_signed,
1496 tok::kw___is_standard_layout,
1497 tok::kw___is_trivial,
1498 tok::kw___is_trivially_assignable,
1499 tok::kw___is_trivially_constructible,
1500 tok::kw___is_trivially_copyable,
1501 tok::kw___is_union,
1502 tok::kw___is_unsigned,
1503 tok::kw___is_void,
1504 tok::kw___is_volatile))
Nico Weber7c3c5be2014-09-23 04:09:56 +00001505 // GNU libstdc++ 4.2 and libc++ use certain intrinsic names as the
1506 // name of struct templates, but some are keywords in GCC >= 4.3
1507 // and Clang. Therefore, when we see the token sequence "struct
1508 // X", make X into a normal identifier rather than a keyword, to
1509 // allow libstdc++ 4.2 and libc++ to work properly.
1510 TryKeywordIdentFallback(true);
Mike Stump11289f42009-09-09 15:08:12 +00001511
David Majnemer51fd8a02015-07-22 23:46:18 +00001512 struct PreserveAtomicIdentifierInfoRAII {
1513 PreserveAtomicIdentifierInfoRAII(Token &Tok, bool Enabled)
1514 : AtomicII(nullptr) {
1515 if (!Enabled)
1516 return;
1517 assert(Tok.is(tok::kw__Atomic));
1518 AtomicII = Tok.getIdentifierInfo();
1519 AtomicII->revertTokenIDToIdentifier();
1520 Tok.setKind(tok::identifier);
1521 }
1522 ~PreserveAtomicIdentifierInfoRAII() {
1523 if (!AtomicII)
1524 return;
1525 AtomicII->revertIdentifierToTokenID(tok::kw__Atomic);
1526 }
1527 IdentifierInfo *AtomicII;
1528 };
1529
1530 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
1531 // implementation for VS2013 uses _Atomic as an identifier for one of the
1532 // classes in <atomic>. When we are parsing 'struct _Atomic', don't consider
1533 // '_Atomic' to be a keyword. We are careful to undo this so that clang can
1534 // use '_Atomic' in its own header files.
1535 bool ShouldChangeAtomicToIdentifier = getLangOpts().MSVCCompat &&
1536 Tok.is(tok::kw__Atomic) &&
1537 TagType == DeclSpec::TST_struct;
1538 PreserveAtomicIdentifierInfoRAII AtomicTokenGuard(
1539 Tok, ShouldChangeAtomicToIdentifier);
1540
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001541 // Parse the (optional) nested-name-specifier.
John McCall9dab4e62009-12-12 11:40:51 +00001542 CXXScopeSpec &SS = DS.getTypeSpecScope();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001543 if (getLangOpts().CPlusPlus) {
Serge Pavlov458ea762014-07-16 05:16:52 +00001544 // "FOO : BAR" is not a potential typo for "FOO::BAR". In this context it
1545 // is a base-specifier-list.
Chris Lattnerd5c1c9d2009-12-10 00:32:41 +00001546 ColonProtectionRAIIObject X(*this);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001547
Nico Webercfaa4cd2015-02-15 07:26:13 +00001548 CXXScopeSpec Spec;
1549 bool HasValidSpec = true;
David Blaikieefdccaa2016-01-15 23:43:34 +00001550 if (ParseOptionalCXXScopeSpecifier(Spec, nullptr, 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) {
1623 // Try to resolve the template name to a type template.
1624 Actions.ActOnUndeclaredTypeTemplateName(getCurScope(), TemplateId->Template,
1625 TemplateId->Kind, NameLoc, Name);
1626 if (TemplateId->Kind == TNK_Undeclared_template) {
1627 RecoverFromUndeclaredTemplateName(
1628 Name, NameLoc,
1629 SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc), true);
1630 TemplateId = nullptr;
1631 }
1632 }
1633
1634 if (TemplateId && TemplateId->Kind != TNK_Type_template &&
Douglas Gregore7c20652011-03-02 00:47:37 +00001635 TemplateId->Kind != TNK_Dependent_template_name) {
Douglas Gregor7f741122009-02-25 19:37:18 +00001636 // The template-name in the simple-template-id refers to
1637 // something other than a class template. Give an appropriate
1638 // error message and skip to the ';'.
1639 SourceRange Range(NameLoc);
1640 if (SS.isNotEmpty())
1641 Range.setBegin(SS.getBeginLoc());
Douglas Gregor67a65642009-02-17 23:15:12 +00001642
Richard Smith72bfbd82013-12-04 00:28:23 +00001643 // FIXME: Name may be null here.
Douglas Gregor7f741122009-02-25 19:37:18 +00001644 Diag(TemplateId->LAngleLoc, diag::err_template_spec_syntax_non_template)
Richard Smithb23c5e82019-05-09 03:31:27 +00001645 << TemplateId->Name << static_cast<int>(TemplateId->Kind) << Range;
Mike Stump11289f42009-09-09 15:08:12 +00001646
Douglas Gregor7f741122009-02-25 19:37:18 +00001647 DS.SetTypeSpecError();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001648 SkipUntil(tok::semi, StopBeforeMatch);
Douglas Gregor7f741122009-02-25 19:37:18 +00001649 return;
Douglas Gregor67a65642009-02-17 23:15:12 +00001650 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001651 }
1652
Richard Smithbfdb1082012-03-12 08:56:40 +00001653 // There are four options here.
1654 // - If we are in a trailing return type, this is always just a reference,
1655 // and we must not try to parse a definition. For instance,
1656 // [] () -> struct S { };
1657 // does not define a type.
1658 // - If we have 'struct foo {...', 'struct foo :...',
1659 // 'struct foo final :' or 'struct foo final {', then this is a definition.
1660 // - If we have 'struct foo;', then this is either a forward declaration
1661 // or a friend declaration, which have to be treated differently.
1662 // - Otherwise we have something like 'struct foo xyz', a reference.
Michael Han9407e502012-11-26 22:54:45 +00001663 //
1664 // We also detect these erroneous cases to provide better diagnostic for
1665 // C++11 attributes parsing.
1666 // - attributes follow class name:
1667 // struct foo [[]] {};
1668 // - attributes appear before or after 'final':
1669 // struct foo [[]] final [[]] {};
1670 //
Richard Smithc5b05522012-03-12 07:56:15 +00001671 // However, in type-specifier-seq's, things look like declarations but are
1672 // just references, e.g.
1673 // new struct s;
Sebastian Redl2b372722010-02-03 21:21:43 +00001674 // or
Richard Smithc5b05522012-03-12 07:56:15 +00001675 // &T::operator struct s;
Faisal Vali7db85c52017-12-31 00:06:40 +00001676 // For these, DSC is DeclSpecContext::DSC_type_specifier or
1677 // DeclSpecContext::DSC_alias_declaration.
Michael Han9407e502012-11-26 22:54:45 +00001678
1679 // If there are attributes after class name, parse them.
Richard Smith89645bc2013-01-02 12:01:23 +00001680 MaybeParseCXX11Attributes(Attributes);
Michael Han9407e502012-11-26 22:54:45 +00001681
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001682 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
John McCallfaf5fb42010-08-26 23:41:50 +00001683 Sema::TagUseKind TUK;
Faisal Vali7db85c52017-12-31 00:06:40 +00001684 if (DSC == DeclSpecContext::DSC_trailing)
Richard Smithbfdb1082012-03-12 08:56:40 +00001685 TUK = Sema::TUK_Reference;
1686 else if (Tok.is(tok::l_brace) ||
1687 (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
Richard Smith89645bc2013-01-02 12:01:23 +00001688 (isCXX11FinalKeyword() &&
David Blaikie9933a5a2012-03-12 15:39:49 +00001689 (NextToken().is(tok::l_brace) || NextToken().is(tok::colon)))) {
Douglas Gregor3dad8422009-09-26 06:47:28 +00001690 if (DS.isFriendSpecified()) {
1691 // C++ [class.friend]p2:
1692 // A class shall not be defined in a friend declaration.
Richard Smith0f8ee222012-01-10 01:33:14 +00001693 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
Douglas Gregor3dad8422009-09-26 06:47:28 +00001694 << SourceRange(DS.getFriendSpecLoc());
1695
1696 // Skip everything up to the semicolon, so that this looks like a proper
1697 // friend class (or template thereof) declaration.
Alexey Bataevee6507d2013-11-18 08:17:37 +00001698 SkipUntil(tok::semi, StopBeforeMatch);
John McCallfaf5fb42010-08-26 23:41:50 +00001699 TUK = Sema::TUK_Friend;
Douglas Gregor3dad8422009-09-26 06:47:28 +00001700 } else {
1701 // Okay, this is a class definition.
John McCallfaf5fb42010-08-26 23:41:50 +00001702 TUK = Sema::TUK_Definition;
Douglas Gregor3dad8422009-09-26 06:47:28 +00001703 }
Richard Smith434516c2013-02-22 06:46:23 +00001704 } else if (isCXX11FinalKeyword() && (NextToken().is(tok::l_square) ||
1705 NextToken().is(tok::kw_alignas))) {
Michael Han9407e502012-11-26 22:54:45 +00001706 // We can't tell if this is a definition or reference
1707 // until we skipped the 'final' and C++11 attribute specifiers.
1708 TentativeParsingAction PA(*this);
1709
1710 // Skip the 'final' keyword.
1711 ConsumeToken();
1712
1713 // Skip C++11 attribute specifiers.
1714 while (true) {
1715 if (Tok.is(tok::l_square) && NextToken().is(tok::l_square)) {
1716 ConsumeBracket();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001717 if (!SkipUntil(tok::r_square, StopAtSemi))
Michael Han9407e502012-11-26 22:54:45 +00001718 break;
Richard Smith434516c2013-02-22 06:46:23 +00001719 } else if (Tok.is(tok::kw_alignas) && NextToken().is(tok::l_paren)) {
Michael Han9407e502012-11-26 22:54:45 +00001720 ConsumeToken();
1721 ConsumeParen();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001722 if (!SkipUntil(tok::r_paren, StopAtSemi))
Michael Han9407e502012-11-26 22:54:45 +00001723 break;
1724 } else {
1725 break;
1726 }
1727 }
1728
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001729 if (Tok.isOneOf(tok::l_brace, tok::colon))
Michael Han9407e502012-11-26 22:54:45 +00001730 TUK = Sema::TUK_Definition;
1731 else
1732 TUK = Sema::TUK_Reference;
1733
1734 PA.Revert();
Richard Smith649c7b062014-01-08 00:56:48 +00001735 } else if (!isTypeSpecifier(DSC) &&
Richard Smith369b9f92012-06-25 21:37:02 +00001736 (Tok.is(tok::semi) ||
Richard Smith200f47c2012-07-02 19:14:01 +00001737 (Tok.isAtStartOfLine() && !isValidAfterTypeSpecifier(false)))) {
John McCallfaf5fb42010-08-26 23:41:50 +00001738 TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
Joao Matose9a3ed42012-08-31 22:18:20 +00001739 if (Tok.isNot(tok::semi)) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001740 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
Joao Matose9a3ed42012-08-31 22:18:20 +00001741 // A semicolon was missing after this declaration. Diagnose and recover.
Alp Toker383d2c42014-01-01 03:08:43 +00001742 ExpectAndConsume(tok::semi, diag::err_expected_after,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001743 DeclSpec::getSpecifierName(TagType, PPol));
Ilya Biryukov929af672019-05-17 09:32:05 +00001744 PP.EnterToken(Tok, /*IsReinject*/true);
Joao Matose9a3ed42012-08-31 22:18:20 +00001745 Tok.setKind(tok::semi);
1746 }
Richard Smith369b9f92012-06-25 21:37:02 +00001747 } else
John McCallfaf5fb42010-08-26 23:41:50 +00001748 TUK = Sema::TUK_Reference;
Douglas Gregor556877c2008-04-13 21:30:24 +00001749
Michael Han9407e502012-11-26 22:54:45 +00001750 // Forbid misplaced attributes. In cases of a reference, we pass attributes
1751 // to caller to handle.
Michael Han309af292013-01-07 16:57:11 +00001752 if (TUK != Sema::TUK_Reference) {
1753 // If this is not a reference, then the only possible
1754 // valid place for C++11 attributes to appear here
1755 // is between class-key and class-name. If there are
1756 // any attributes after class-name, we try a fixit to move
1757 // them to the right place.
1758 SourceRange AttrRange = Attributes.Range;
1759 if (AttrRange.isValid()) {
1760 Diag(AttrRange.getBegin(), diag::err_attributes_not_allowed)
1761 << AttrRange
1762 << FixItHint::CreateInsertionFromRange(AttrFixitLoc,
1763 CharSourceRange(AttrRange, true))
1764 << FixItHint::CreateRemoval(AttrRange);
1765
1766 // Recover by adding misplaced attributes to the attribute list
1767 // of the class so they can be applied on the class later.
1768 attrs.takeAllFrom(Attributes);
1769 }
1770 }
Michael Han9407e502012-11-26 22:54:45 +00001771
John McCall6347b682012-05-07 06:16:58 +00001772 // If this is an elaborated type specifier, and we delayed
1773 // diagnostics before, just merge them into the current pool.
1774 if (shouldDelayDiagsInTag) {
1775 diagsFromTag.done();
1776 if (TUK == Sema::TUK_Reference)
1777 diagsFromTag.redelay();
1778 }
1779
John McCall413021a2010-07-30 06:26:29 +00001780 if (!Name && !TemplateId && (DS.getTypeSpecType() == DeclSpec::TST_error ||
John McCallfaf5fb42010-08-26 23:41:50 +00001781 TUK != Sema::TUK_Definition)) {
John McCall413021a2010-07-30 06:26:29 +00001782 if (DS.getTypeSpecType() != DeclSpec::TST_error) {
1783 // We have a declaration or reference to an anonymous class.
1784 Diag(StartLoc, diag::err_anon_type_definition)
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001785 << DeclSpec::getSpecifierName(TagType, Policy);
John McCall413021a2010-07-30 06:26:29 +00001786 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001787
David Majnemer3252fd02013-12-05 01:36:53 +00001788 // If we are parsing a definition and stop at a base-clause, continue on
1789 // until the semicolon. Continuing from the comma will just trick us into
1790 // thinking we are seeing a variable declaration.
1791 if (TUK == Sema::TUK_Definition && Tok.is(tok::colon))
1792 SkipUntil(tok::semi, StopBeforeMatch);
1793 else
1794 SkipUntil(tok::comma, StopAtSemi);
Douglas Gregor556877c2008-04-13 21:30:24 +00001795 return;
1796 }
1797
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001798 // Create the tag portion of the class or class template.
John McCall48871652010-08-21 09:40:31 +00001799 DeclResult TagOrTempResult = true; // invalid
1800 TypeResult TypeResult = true; // invalid
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001801
Douglas Gregord6ab8742009-05-28 23:31:59 +00001802 bool Owned = false;
Richard Smithd9ba2242015-05-07 03:54:19 +00001803 Sema::SkipBodyInfo SkipBody;
John McCall06f6fe8d2009-09-04 01:14:41 +00001804 if (TemplateId) {
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001805 // Explicit specialization, class template partial specialization,
1806 // or explicit instantiation.
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00001807 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregor7f741122009-02-25 19:37:18 +00001808 TemplateId->NumArgs);
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001809 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
John McCallfaf5fb42010-08-26 23:41:50 +00001810 TUK == Sema::TUK_Declaration) {
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001811 // This is an explicit instantiation of a class template.
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001812 ProhibitAttributes(attrs);
1813
Erich Keanec480f302018-07-12 21:09:05 +00001814 TagOrTempResult = Actions.ActOnExplicitInstantiation(
1815 getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc,
1816 TagType, StartLoc, SS, TemplateId->Template,
1817 TemplateId->TemplateNameLoc, TemplateId->LAngleLoc, TemplateArgsPtr,
1818 TemplateId->RAngleLoc, attrs);
John McCallb7c5c272010-04-14 00:24:33 +00001819
Erich Keanec480f302018-07-12 21:09:05 +00001820 // Friend template-ids are treated as references unless
1821 // they have template headers, in which case they're ill-formed
1822 // (FIXME: "template <class T> friend class A<T>::B<int>;").
1823 // We diagnose this error in ActOnClassTemplateSpecialization.
John McCallfaf5fb42010-08-26 23:41:50 +00001824 } else if (TUK == Sema::TUK_Reference ||
1825 (TUK == Sema::TUK_Friend &&
John McCallb7c5c272010-04-14 00:24:33 +00001826 TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate)) {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001827 ProhibitAttributes(attrs);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00001828 TypeResult = Actions.ActOnTagTemplateIdType(TUK, TagType, StartLoc,
Richard Smitha42fd842020-01-17 15:42:11 -08001829 SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00001830 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00001831 TemplateId->Template,
1832 TemplateId->TemplateNameLoc,
1833 TemplateId->LAngleLoc,
1834 TemplateArgsPtr,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00001835 TemplateId->RAngleLoc);
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001836 } else {
1837 // This is an explicit specialization or a class template
1838 // partial specialization.
1839 TemplateParameterLists FakedParamLists;
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001840 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1841 // This looks like an explicit instantiation, because we have
1842 // something like
1843 //
1844 // template class Foo<X>
1845 //
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001846 // but it actually has a definition. Most likely, this was
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001847 // meant to be an explicit specialization, but the user forgot
1848 // the '<>' after 'template'.
Richard Smith003c5e12013-11-08 19:03:29 +00001849 // It this is friend declaration however, since it cannot have a
1850 // template header, it is most likely that the user meant to
1851 // remove the 'template' keyword.
Larisse Voufob9bbaba2013-06-22 13:56:11 +00001852 assert((TUK == Sema::TUK_Definition || TUK == Sema::TUK_Friend) &&
Richard Smith003c5e12013-11-08 19:03:29 +00001853 "Expected a definition here");
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001854
Richard Smith003c5e12013-11-08 19:03:29 +00001855 if (TUK == Sema::TUK_Friend) {
1856 Diag(DS.getFriendSpecLoc(), diag::err_friend_explicit_instantiation);
Craig Topper161e4db2014-05-21 06:02:52 +00001857 TemplateParams = nullptr;
Richard Smith003c5e12013-11-08 19:03:29 +00001858 } else {
1859 SourceLocation LAngleLoc =
1860 PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
1861 Diag(TemplateId->TemplateNameLoc,
1862 diag::err_explicit_instantiation_with_definition)
1863 << SourceRange(TemplateInfo.TemplateLoc)
1864 << FixItHint::CreateInsertion(LAngleLoc, "<>");
1865
1866 // Create a fake template parameter list that contains only
1867 // "template<>", so that we treat this construct as a class
1868 // template specialization.
1869 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
Craig Topper96225a52015-12-24 23:58:25 +00001870 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
Hubert Tongf608c052016-04-29 18:05:37 +00001871 LAngleLoc, nullptr));
Richard Smith003c5e12013-11-08 19:03:29 +00001872 TemplateParams = &FakedParamLists;
1873 }
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001874 }
1875
1876 // Build the class template specialization.
Richard Smith4b55a9c2014-04-17 03:29:33 +00001877 TagOrTempResult = Actions.ActOnClassTemplateSpecialization(
1878 getCurScope(), TagType, TUK, StartLoc, DS.getModulePrivateSpecLoc(),
Richard Smitha42fd842020-01-17 15:42:11 -08001879 SS, *TemplateId, attrs,
Craig Topper161e4db2014-05-21 06:02:52 +00001880 MultiTemplateParamsArg(TemplateParams ? &(*TemplateParams)[0]
1881 : nullptr,
Richard Smithc7e6ff02015-05-18 20:36:47 +00001882 TemplateParams ? TemplateParams->size() : 0),
1883 &SkipBody);
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001884 }
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001885 } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
John McCallfaf5fb42010-08-26 23:41:50 +00001886 TUK == Sema::TUK_Declaration) {
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001887 // Explicit instantiation of a member of a class template
1888 // specialization, e.g.,
1889 //
1890 // template struct Outer<int>::Inner;
1891 //
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001892 ProhibitAttributes(attrs);
1893
Erich Keanec480f302018-07-12 21:09:05 +00001894 TagOrTempResult = Actions.ActOnExplicitInstantiation(
1895 getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc,
1896 TagType, StartLoc, SS, Name, NameLoc, attrs);
John McCallace48cd2010-10-19 01:40:49 +00001897 } else if (TUK == Sema::TUK_Friend &&
1898 TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate) {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001899 ProhibitAttributes(attrs);
1900
Erich Keanec480f302018-07-12 21:09:05 +00001901 TagOrTempResult = Actions.ActOnTemplatedFriendTag(
1902 getCurScope(), DS.getFriendSpecLoc(), TagType, StartLoc, SS, Name,
1903 NameLoc, attrs,
1904 MultiTemplateParamsArg(TemplateParams ? &(*TemplateParams)[0] : nullptr,
1905 TemplateParams ? TemplateParams->size() : 0));
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001906 } else {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001907 if (TUK != Sema::TUK_Declaration && TUK != Sema::TUK_Definition)
1908 ProhibitAttributes(attrs);
Richard Smith003c5e12013-11-08 19:03:29 +00001909
Larisse Voufo725de3e2013-06-21 00:08:46 +00001910 if (TUK == Sema::TUK_Definition &&
1911 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1912 // If the declarator-id is not a template-id, issue a diagnostic and
1913 // recover by ignoring the 'template' keyword.
1914 Diag(Tok, diag::err_template_defn_explicit_instantiation)
1915 << 1 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
Craig Topper161e4db2014-05-21 06:02:52 +00001916 TemplateParams = nullptr;
Larisse Voufo725de3e2013-06-21 00:08:46 +00001917 }
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001918
John McCall7f41d982009-09-11 04:59:25 +00001919 bool IsDependent = false;
1920
John McCall32723e92010-10-19 18:40:57 +00001921 // Don't pass down template parameter lists if this is just a tag
1922 // reference. For example, we don't need the template parameters here:
1923 // template <class T> class A *makeA(T t);
1924 MultiTemplateParamsArg TParams;
1925 if (TUK != Sema::TUK_Reference && TemplateParams)
1926 TParams =
1927 MultiTemplateParamsArg(&(*TemplateParams)[0], TemplateParams->size());
1928
Nico Weber32a0fc72016-09-03 03:01:32 +00001929 stripTypeAttributesOffDeclSpec(attrs, DS, TUK);
David Majnemer936b4112015-04-19 07:53:29 +00001930
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001931 // Declaration or definition of a class type
Faisal Vali7db85c52017-12-31 00:06:40 +00001932 TagOrTempResult = Actions.ActOnTag(
Erich Keanec480f302018-07-12 21:09:05 +00001933 getCurScope(), TagType, TUK, StartLoc, SS, Name, NameLoc, attrs, AS,
1934 DS.getModulePrivateSpecLoc(), TParams, Owned, IsDependent,
1935 SourceLocation(), false, clang::TypeResult(),
Faisal Vali7db85c52017-12-31 00:06:40 +00001936 DSC == DeclSpecContext::DSC_type_specifier,
1937 DSC == DeclSpecContext::DSC_template_param ||
1938 DSC == DeclSpecContext::DSC_template_type_arg,
1939 &SkipBody);
John McCall7f41d982009-09-11 04:59:25 +00001940
1941 // If ActOnTag said the type was dependent, try again with the
1942 // less common call.
John McCallace48cd2010-10-19 01:40:49 +00001943 if (IsDependent) {
1944 assert(TUK == Sema::TUK_Reference || TUK == Sema::TUK_Friend);
Douglas Gregor0be31a22010-07-02 17:43:08 +00001945 TypeResult = Actions.ActOnDependentTag(getCurScope(), TagType, TUK,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001946 SS, Name, StartLoc, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +00001947 }
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001948 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001949
Douglas Gregor556877c2008-04-13 21:30:24 +00001950 // If there is a body, parse it and inform the actions module.
John McCallfaf5fb42010-08-26 23:41:50 +00001951 if (TUK == Sema::TUK_Definition) {
John McCall2d814c32009-12-19 21:48:58 +00001952 assert(Tok.is(tok::l_brace) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00001953 (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
Richard Smith89645bc2013-01-02 12:01:23 +00001954 isCXX11FinalKeyword());
Richard Smithd9ba2242015-05-07 03:54:19 +00001955 if (SkipBody.ShouldSkip)
Richard Smith65ebb4a2015-03-26 04:09:53 +00001956 SkipCXXMemberSpecification(StartLoc, AttrFixitLoc, TagType,
1957 TagOrTempResult.get());
1958 else if (getLangOpts().CPlusPlus)
Michael Han309af292013-01-07 16:57:11 +00001959 ParseCXXMemberSpecification(StartLoc, AttrFixitLoc, attrs, TagType,
1960 TagOrTempResult.get());
Bruno Cardoso Lopesdf0ee342017-07-01 00:06:47 +00001961 else {
1962 Decl *D =
1963 SkipBody.CheckSameAsPrevious ? SkipBody.New : TagOrTempResult.get();
1964 // Parse the definition body.
1965 ParseStructUnionBody(StartLoc, TagType, D);
1966 if (SkipBody.CheckSameAsPrevious &&
1967 !Actions.ActOnDuplicateDefinition(DS, TagOrTempResult.get(),
1968 SkipBody)) {
1969 DS.SetTypeSpecError();
1970 return;
1971 }
1972 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001973 }
1974
Erich Keane2fe684b2017-02-28 20:44:39 +00001975 if (!TagOrTempResult.isInvalid())
Hiroshi Inoue939d9322017-06-30 05:40:31 +00001976 // Delayed processing of attributes.
Erich Keanec480f302018-07-12 21:09:05 +00001977 Actions.ProcessDeclAttributeDelayed(TagOrTempResult.get(), attrs);
Erich Keane2fe684b2017-02-28 20:44:39 +00001978
Craig Topper161e4db2014-05-21 06:02:52 +00001979 const char *PrevSpec = nullptr;
John McCallba7bf592010-08-24 05:47:05 +00001980 unsigned DiagID;
1981 bool Result;
John McCall7f41d982009-09-11 04:59:25 +00001982 if (!TypeResult.isInvalid()) {
Abramo Bagnara9875a3c2011-03-16 20:16:18 +00001983 Result = DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
1984 NameLoc.isValid() ? NameLoc : StartLoc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001985 PrevSpec, DiagID, TypeResult.get(), Policy);
John McCall7f41d982009-09-11 04:59:25 +00001986 } else if (!TagOrTempResult.isInvalid()) {
Abramo Bagnara9875a3c2011-03-16 20:16:18 +00001987 Result = DS.SetTypeSpecType(TagType, StartLoc,
1988 NameLoc.isValid() ? NameLoc : StartLoc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001989 PrevSpec, DiagID, TagOrTempResult.get(), Owned,
1990 Policy);
John McCall7f41d982009-09-11 04:59:25 +00001991 } else {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001992 DS.SetTypeSpecError();
Anders Carlssonf83c9fa2009-05-11 22:27:47 +00001993 return;
1994 }
Mike Stump11289f42009-09-09 15:08:12 +00001995
John McCallba7bf592010-08-24 05:47:05 +00001996 if (Result)
John McCall49bfce42009-08-03 20:12:06 +00001997 Diag(StartLoc, DiagID) << PrevSpec;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001998
Chris Lattnercf251412010-02-02 01:23:29 +00001999 // At this point, we've successfully parsed a class-specifier in 'definition'
2000 // form (e.g. "struct foo { int x; }". While we could just return here, we're
2001 // going to look at what comes after it to improve error recovery. If an
2002 // impossible token occurs next, we assume that the programmer forgot a ; at
2003 // the end of the declaration and recover that way.
2004 //
Richard Smith369b9f92012-06-25 21:37:02 +00002005 // Also enforce C++ [temp]p3:
2006 // In a template-declaration which defines a class, no declarator
2007 // is permitted.
Richard Smith843f18f2014-08-13 02:13:15 +00002008 //
2009 // After a type-specifier, we don't expect a semicolon. This only happens in
2010 // C, since definitions are not permitted in this context in C++.
Joao Matose9a3ed42012-08-31 22:18:20 +00002011 if (TUK == Sema::TUK_Definition &&
Richard Smith843f18f2014-08-13 02:13:15 +00002012 (getLangOpts().CPlusPlus || !isTypeSpecifier(DSC)) &&
Joao Matose9a3ed42012-08-31 22:18:20 +00002013 (TemplateInfo.Kind || !isValidAfterTypeSpecifier(false))) {
Argyrios Kyrtzidise6f69132012-12-17 20:10:43 +00002014 if (Tok.isNot(tok::semi)) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002015 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
Alp Toker383d2c42014-01-01 03:08:43 +00002016 ExpectAndConsume(tok::semi, diag::err_expected_after,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002017 DeclSpec::getSpecifierName(TagType, PPol));
Argyrios Kyrtzidise6f69132012-12-17 20:10:43 +00002018 // Push this token back into the preprocessor and change our current token
2019 // to ';' so that the rest of the code recovers as though there were an
2020 // ';' after the definition.
Ilya Biryukov929af672019-05-17 09:32:05 +00002021 PP.EnterToken(Tok, /*IsReinject=*/true);
Argyrios Kyrtzidise6f69132012-12-17 20:10:43 +00002022 Tok.setKind(tok::semi);
2023 }
Chris Lattnercf251412010-02-02 01:23:29 +00002024 }
Douglas Gregor556877c2008-04-13 21:30:24 +00002025}
2026
Mike Stump11289f42009-09-09 15:08:12 +00002027/// ParseBaseClause - Parse the base-clause of a C++ class [C++ class.derived].
Douglas Gregor556877c2008-04-13 21:30:24 +00002028///
2029/// base-clause : [C++ class.derived]
2030/// ':' base-specifier-list
2031/// base-specifier-list:
2032/// base-specifier '...'[opt]
2033/// base-specifier-list ',' base-specifier '...'[opt]
John McCall48871652010-08-21 09:40:31 +00002034void Parser::ParseBaseClause(Decl *ClassDecl) {
Douglas Gregor556877c2008-04-13 21:30:24 +00002035 assert(Tok.is(tok::colon) && "Not a base clause");
2036 ConsumeToken();
2037
Douglas Gregor29a92472008-10-22 17:49:05 +00002038 // Build up an array of parsed base specifiers.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002039 SmallVector<CXXBaseSpecifier *, 8> BaseInfo;
Douglas Gregor29a92472008-10-22 17:49:05 +00002040
Douglas Gregor556877c2008-04-13 21:30:24 +00002041 while (true) {
2042 // Parse a base-specifier.
Douglas Gregor29a92472008-10-22 17:49:05 +00002043 BaseResult Result = ParseBaseSpecifier(ClassDecl);
Douglas Gregorf8298252009-01-26 22:44:13 +00002044 if (Result.isInvalid()) {
Douglas Gregor556877c2008-04-13 21:30:24 +00002045 // Skip the rest of this base specifier, up until the comma or
2046 // opening brace.
Alexey Bataevee6507d2013-11-18 08:17:37 +00002047 SkipUntil(tok::comma, tok::l_brace, StopAtSemi | StopBeforeMatch);
Douglas Gregor29a92472008-10-22 17:49:05 +00002048 } else {
2049 // Add this to our array of base specifiers.
Douglas Gregorf8298252009-01-26 22:44:13 +00002050 BaseInfo.push_back(Result.get());
Douglas Gregor556877c2008-04-13 21:30:24 +00002051 }
2052
2053 // If the next token is a comma, consume it and keep reading
2054 // base-specifiers.
Alp Toker97650562014-01-10 11:19:30 +00002055 if (!TryConsumeToken(tok::comma))
2056 break;
Douglas Gregor556877c2008-04-13 21:30:24 +00002057 }
Douglas Gregor29a92472008-10-22 17:49:05 +00002058
2059 // Attach the base specifiers
Craig Topperaa700cb2015-12-27 21:55:19 +00002060 Actions.ActOnBaseSpecifiers(ClassDecl, BaseInfo);
Douglas Gregor556877c2008-04-13 21:30:24 +00002061}
2062
2063/// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is
2064/// one entry in the base class list of a class specifier, for example:
2065/// class foo : public bar, virtual private baz {
2066/// 'public bar' and 'virtual private baz' are each base-specifiers.
2067///
2068/// base-specifier: [C++ class.derived]
Richard Smith4c96e992013-02-19 23:47:15 +00002069/// attribute-specifier-seq[opt] base-type-specifier
2070/// attribute-specifier-seq[opt] 'virtual' access-specifier[opt]
2071/// base-type-specifier
2072/// attribute-specifier-seq[opt] access-specifier 'virtual'[opt]
2073/// base-type-specifier
Craig Topper9ad7e262014-10-31 06:57:07 +00002074BaseResult Parser::ParseBaseSpecifier(Decl *ClassDecl) {
Douglas Gregor556877c2008-04-13 21:30:24 +00002075 bool IsVirtual = false;
2076 SourceLocation StartLoc = Tok.getLocation();
2077
Richard Smith4c96e992013-02-19 23:47:15 +00002078 ParsedAttributesWithRange Attributes(AttrFactory);
2079 MaybeParseCXX11Attributes(Attributes);
2080
Douglas Gregor556877c2008-04-13 21:30:24 +00002081 // Parse the 'virtual' keyword.
Alp Toker97650562014-01-10 11:19:30 +00002082 if (TryConsumeToken(tok::kw_virtual))
Douglas Gregor556877c2008-04-13 21:30:24 +00002083 IsVirtual = true;
Douglas Gregor556877c2008-04-13 21:30:24 +00002084
Richard Smith4c96e992013-02-19 23:47:15 +00002085 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2086
Douglas Gregor556877c2008-04-13 21:30:24 +00002087 // Parse an (optional) access specifier.
2088 AccessSpecifier Access = getAccessSpecifierIfPresent();
John McCall553c0792010-01-23 00:46:32 +00002089 if (Access != AS_none)
Douglas Gregor556877c2008-04-13 21:30:24 +00002090 ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +00002091
Richard Smith4c96e992013-02-19 23:47:15 +00002092 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2093
Douglas Gregor556877c2008-04-13 21:30:24 +00002094 // Parse the 'virtual' keyword (again!), in case it came after the
2095 // access specifier.
2096 if (Tok.is(tok::kw_virtual)) {
2097 SourceLocation VirtualLoc = ConsumeToken();
2098 if (IsVirtual) {
2099 // Complain about duplicate 'virtual'
Chris Lattner6d29c102008-11-18 07:48:38 +00002100 Diag(VirtualLoc, diag::err_dup_virtual)
Douglas Gregora771f462010-03-31 17:46:05 +00002101 << FixItHint::CreateRemoval(VirtualLoc);
Douglas Gregor556877c2008-04-13 21:30:24 +00002102 }
2103
2104 IsVirtual = true;
2105 }
2106
Richard Smith4c96e992013-02-19 23:47:15 +00002107 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2108
Douglas Gregor831c93f2008-11-05 20:51:48 +00002109 // Parse the class-name.
David Majnemer51fd8a02015-07-22 23:46:18 +00002110
2111 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
2112 // implementation for VS2013 uses _Atomic as an identifier for one of the
2113 // classes in <atomic>. Treat '_Atomic' to be an identifier when we are
2114 // parsing the class-name for a base specifier.
2115 if (getLangOpts().MSVCCompat && Tok.is(tok::kw__Atomic) &&
2116 NextToken().is(tok::less))
2117 Tok.setKind(tok::identifier);
2118
Douglas Gregord54dfb82009-02-25 23:52:28 +00002119 SourceLocation EndLocation;
David Blaikie1cd50022011-10-25 17:10:12 +00002120 SourceLocation BaseLoc;
2121 TypeResult BaseType = ParseBaseTypeSpecifier(BaseLoc, EndLocation);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00002122 if (BaseType.isInvalid())
Douglas Gregor831c93f2008-11-05 20:51:48 +00002123 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002124
Fangrui Song6907ce22018-07-30 19:24:48 +00002125 // Parse the optional ellipsis (for a pack expansion). The ellipsis is
Douglas Gregor752a5952011-01-03 22:36:02 +00002126 // actually part of the base-specifier-list grammar productions, but we
2127 // parse it here for convenience.
2128 SourceLocation EllipsisLoc;
Alp Toker97650562014-01-10 11:19:30 +00002129 TryConsumeToken(tok::ellipsis, EllipsisLoc);
2130
Mike Stump11289f42009-09-09 15:08:12 +00002131 // Find the complete source range for the base-specifier.
Douglas Gregord54dfb82009-02-25 23:52:28 +00002132 SourceRange Range(StartLoc, EndLocation);
Mike Stump11289f42009-09-09 15:08:12 +00002133
Douglas Gregor556877c2008-04-13 21:30:24 +00002134 // Notify semantic analysis that we have parsed a complete
2135 // base-specifier.
Richard Smith4c96e992013-02-19 23:47:15 +00002136 return Actions.ActOnBaseSpecifier(ClassDecl, Range, Attributes, IsVirtual,
2137 Access, BaseType.get(), BaseLoc,
2138 EllipsisLoc);
Douglas Gregor556877c2008-04-13 21:30:24 +00002139}
2140
2141/// getAccessSpecifierIfPresent - Determine whether the next token is
2142/// a C++ access-specifier.
2143///
2144/// access-specifier: [C++ class.derived]
2145/// 'private'
2146/// 'protected'
2147/// 'public'
Mike Stump11289f42009-09-09 15:08:12 +00002148AccessSpecifier Parser::getAccessSpecifierIfPresent() const {
Douglas Gregor556877c2008-04-13 21:30:24 +00002149 switch (Tok.getKind()) {
2150 default: return AS_none;
2151 case tok::kw_private: return AS_private;
2152 case tok::kw_protected: return AS_protected;
2153 case tok::kw_public: return AS_public;
2154 }
2155}
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002156
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002157/// If the given declarator has any parts for which parsing has to be
Richard Smith0b3a4622014-11-13 20:01:57 +00002158/// delayed, e.g., default arguments or an exception-specification, create a
2159/// late-parsed method declaration record to handle the parsing at the end of
2160/// the class definition.
Douglas Gregor433e0532012-04-16 18:27:27 +00002161void Parser::HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
2162 Decl *ThisDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00002163 DeclaratorChunk::FunctionTypeInfo &FTI
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002164 = DeclaratorInfo.getFunctionTypeInfo();
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002165 // If there was a late-parsed exception-specification, we'll need a
2166 // late parse
2167 bool NeedLateParse = FTI.getExceptionSpecType() == EST_Unparsed;
Douglas Gregor433e0532012-04-16 18:27:27 +00002168
Nathan Sidwell5bb231c2015-02-19 14:03:22 +00002169 if (!NeedLateParse) {
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002170 // Look ahead to see if there are any default args
Nathan Sidwell5bb231c2015-02-19 14:03:22 +00002171 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx) {
2172 auto Param = cast<ParmVarDecl>(FTI.Params[ParamIdx].Param);
2173 if (Param->hasUnparsedDefaultArg()) {
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002174 NeedLateParse = true;
2175 break;
2176 }
Nathan Sidwell5bb231c2015-02-19 14:03:22 +00002177 }
2178 }
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002179
2180 if (NeedLateParse) {
Richard Smith0b3a4622014-11-13 20:01:57 +00002181 // Push this method onto the stack of late-parsed method
2182 // declarations.
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002183 auto LateMethod = new LateParsedMethodDeclaration(this, ThisDecl);
Richard Smith0b3a4622014-11-13 20:01:57 +00002184 getCurrentClass().LateParsedDeclarations.push_back(LateMethod);
2185 LateMethod->TemplateScope = getCurScope()->isTemplateParamScope();
2186
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002187 // Stash the exception-specification tokens in the late-pased method.
Richard Smith0b3a4622014-11-13 20:01:57 +00002188 LateMethod->ExceptionSpecTokens = FTI.ExceptionSpecTokens;
Hans Wennborgdcfba332015-10-06 23:40:43 +00002189 FTI.ExceptionSpecTokens = nullptr;
Richard Smith0b3a4622014-11-13 20:01:57 +00002190
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002191 // Push tokens for each parameter. Those that do not have
2192 // defaults will be NULL.
Richard Smith0b3a4622014-11-13 20:01:57 +00002193 LateMethod->DefaultArgs.reserve(FTI.NumParams);
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002194 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx)
Alp Tokerc5350722014-02-26 22:27:52 +00002195 LateMethod->DefaultArgs.push_back(LateParsedDefaultArgument(
Malcolm Parsonsca9d8342016-11-17 21:00:09 +00002196 FTI.Params[ParamIdx].Param,
2197 std::move(FTI.Params[ParamIdx].DefaultArgTokens)));
Eli Friedman3af2a772009-07-22 21:45:50 +00002198 }
2199}
2200
Richard Smith89645bc2013-01-02 12:01:23 +00002201/// isCXX11VirtSpecifier - Determine whether the given token is a C++11
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002202/// virt-specifier.
2203///
2204/// virt-specifier:
2205/// override
2206/// final
Andrey Bokhanko276055b2016-07-29 10:42:48 +00002207/// __final
Richard Smith89645bc2013-01-02 12:01:23 +00002208VirtSpecifiers::Specifier Parser::isCXX11VirtSpecifier(const Token &Tok) const {
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002209 if (!getLangOpts().CPlusPlus || Tok.isNot(tok::identifier))
Anders Carlsson4b63d0e2011-01-22 16:56:46 +00002210 return VirtSpecifiers::VS_None;
2211
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002212 IdentifierInfo *II = Tok.getIdentifierInfo();
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002213
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002214 // Initialize the contextual keywords.
2215 if (!Ident_final) {
2216 Ident_final = &PP.getIdentifierTable().get("final");
Andrey Bokhanko276055b2016-07-29 10:42:48 +00002217 if (getLangOpts().GNUKeywords)
2218 Ident_GNU_final = &PP.getIdentifierTable().get("__final");
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002219 if (getLangOpts().MicrosoftExt)
2220 Ident_sealed = &PP.getIdentifierTable().get("sealed");
2221 Ident_override = &PP.getIdentifierTable().get("override");
Anders Carlsson56104902011-01-17 03:05:47 +00002222 }
2223
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002224 if (II == Ident_override)
2225 return VirtSpecifiers::VS_Override;
2226
2227 if (II == Ident_sealed)
2228 return VirtSpecifiers::VS_Sealed;
2229
2230 if (II == Ident_final)
2231 return VirtSpecifiers::VS_Final;
2232
Andrey Bokhanko276055b2016-07-29 10:42:48 +00002233 if (II == Ident_GNU_final)
2234 return VirtSpecifiers::VS_GNU_Final;
2235
Anders Carlsson56104902011-01-17 03:05:47 +00002236 return VirtSpecifiers::VS_None;
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002237}
2238
Richard Smith89645bc2013-01-02 12:01:23 +00002239/// ParseOptionalCXX11VirtSpecifierSeq - Parse a virt-specifier-seq.
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002240///
2241/// virt-specifier-seq:
2242/// virt-specifier
2243/// virt-specifier-seq virt-specifier
Richard Smith89645bc2013-01-02 12:01:23 +00002244void Parser::ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS,
Richard Smith3d1a94c2014-08-12 00:22:39 +00002245 bool IsInterface,
2246 SourceLocation FriendLoc) {
Anders Carlsson56104902011-01-17 03:05:47 +00002247 while (true) {
Richard Smith89645bc2013-01-02 12:01:23 +00002248 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
Anders Carlsson56104902011-01-17 03:05:47 +00002249 if (Specifier == VirtSpecifiers::VS_None)
2250 return;
2251
Richard Smith3d1a94c2014-08-12 00:22:39 +00002252 if (FriendLoc.isValid()) {
2253 Diag(Tok.getLocation(), diag::err_friend_decl_spec)
2254 << VirtSpecifiers::getSpecifierName(Specifier)
2255 << FixItHint::CreateRemoval(Tok.getLocation())
2256 << SourceRange(FriendLoc, FriendLoc);
2257 ConsumeToken();
2258 continue;
2259 }
2260
Anders Carlsson56104902011-01-17 03:05:47 +00002261 // C++ [class.mem]p8:
2262 // A virt-specifier-seq shall contain at most one of each virt-specifier.
Craig Topper161e4db2014-05-21 06:02:52 +00002263 const char *PrevSpec = nullptr;
Anders Carlssonf2ca3892011-01-22 15:58:16 +00002264 if (VS.SetSpecifier(Specifier, Tok.getLocation(), PrevSpec))
Anders Carlsson56104902011-01-17 03:05:47 +00002265 Diag(Tok.getLocation(), diag::err_duplicate_virt_specifier)
2266 << PrevSpec
2267 << FixItHint::CreateRemoval(Tok.getLocation());
2268
David Majnemera5433082013-10-18 00:33:31 +00002269 if (IsInterface && (Specifier == VirtSpecifiers::VS_Final ||
2270 Specifier == VirtSpecifiers::VS_Sealed)) {
John McCalldb632ac2012-09-25 07:32:39 +00002271 Diag(Tok.getLocation(), diag::err_override_control_interface)
2272 << VirtSpecifiers::getSpecifierName(Specifier);
David Majnemera5433082013-10-18 00:33:31 +00002273 } else if (Specifier == VirtSpecifiers::VS_Sealed) {
2274 Diag(Tok.getLocation(), diag::ext_ms_sealed_keyword);
Andrey Bokhanko276055b2016-07-29 10:42:48 +00002275 } else if (Specifier == VirtSpecifiers::VS_GNU_Final) {
2276 Diag(Tok.getLocation(), diag::ext_warn_gnu_final);
John McCalldb632ac2012-09-25 07:32:39 +00002277 } else {
David Majnemera5433082013-10-18 00:33:31 +00002278 Diag(Tok.getLocation(),
2279 getLangOpts().CPlusPlus11
2280 ? diag::warn_cxx98_compat_override_control_keyword
2281 : diag::ext_override_control_keyword)
2282 << VirtSpecifiers::getSpecifierName(Specifier);
John McCalldb632ac2012-09-25 07:32:39 +00002283 }
Anders Carlsson56104902011-01-17 03:05:47 +00002284 ConsumeToken();
2285 }
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002286}
2287
Richard Smith89645bc2013-01-02 12:01:23 +00002288/// isCXX11FinalKeyword - Determine whether the next token is a C++11
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002289/// 'final' or Microsoft 'sealed' contextual keyword.
Richard Smith89645bc2013-01-02 12:01:23 +00002290bool Parser::isCXX11FinalKeyword() const {
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002291 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
2292 return Specifier == VirtSpecifiers::VS_Final ||
Fangrui Song6907ce22018-07-30 19:24:48 +00002293 Specifier == VirtSpecifiers::VS_GNU_Final ||
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002294 Specifier == VirtSpecifiers::VS_Sealed;
Anders Carlsson4b63d0e2011-01-22 16:56:46 +00002295}
2296
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002297/// Parse a C++ member-declarator up to, but not including, the optional
Richard Smith72553fc2014-01-23 23:53:27 +00002298/// brace-or-equal-initializer or pure-specifier.
Nico Weberd89e6f72015-01-16 19:34:13 +00002299bool Parser::ParseCXXMemberDeclaratorBeforeInitializer(
Richard Smith72553fc2014-01-23 23:53:27 +00002300 Declarator &DeclaratorInfo, VirtSpecifiers &VS, ExprResult &BitfieldSize,
2301 LateParsedAttrList &LateParsedAttrs) {
2302 // member-declarator:
2303 // declarator pure-specifier[opt]
Saar Razb65b1f32020-01-09 15:07:51 +02002304 // declarator requires-clause
Richard Smith72553fc2014-01-23 23:53:27 +00002305 // declarator brace-or-equal-initializer[opt]
2306 // identifier[opt] ':' constant-expression
Serge Pavlov458ea762014-07-16 05:16:52 +00002307 if (Tok.isNot(tok::colon))
Richard Smith72553fc2014-01-23 23:53:27 +00002308 ParseDeclarator(DeclaratorInfo);
Richard Smith3d1a94c2014-08-12 00:22:39 +00002309 else
2310 DeclaratorInfo.SetIdentifier(nullptr, Tok.getLocation());
Richard Smith72553fc2014-01-23 23:53:27 +00002311
2312 if (!DeclaratorInfo.isFunctionDeclarator() && TryConsumeToken(tok::colon)) {
Richard Smith3d1a94c2014-08-12 00:22:39 +00002313 assert(DeclaratorInfo.isPastIdentifier() &&
2314 "don't know where identifier would go yet?");
Richard Smith72553fc2014-01-23 23:53:27 +00002315 BitfieldSize = ParseConstantExpression();
2316 if (BitfieldSize.isInvalid())
2317 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
Saar Razb65b1f32020-01-09 15:07:51 +02002318 } else if (Tok.is(tok::kw_requires)) {
2319 ParseTrailingRequiresClause(DeclaratorInfo);
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002320 } else {
Richard Smith3d1a94c2014-08-12 00:22:39 +00002321 ParseOptionalCXX11VirtSpecifierSeq(
2322 VS, getCurrentClass().IsInterface,
2323 DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002324 if (!VS.isUnset())
2325 MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo, VS);
2326 }
Richard Smith72553fc2014-01-23 23:53:27 +00002327
2328 // If a simple-asm-expr is present, parse it.
2329 if (Tok.is(tok::kw_asm)) {
2330 SourceLocation Loc;
Aaron Ballman55a51e12020-01-08 08:38:02 -05002331 ExprResult AsmLabel(ParseSimpleAsm(/*ForAsmLabel*/ true, &Loc));
Richard Smith72553fc2014-01-23 23:53:27 +00002332 if (AsmLabel.isInvalid())
2333 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2334
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002335 DeclaratorInfo.setAsmLabel(AsmLabel.get());
Richard Smith72553fc2014-01-23 23:53:27 +00002336 DeclaratorInfo.SetRangeEnd(Loc);
2337 }
2338
2339 // If attributes exist after the declarator, but before an '{', parse them.
2340 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
Richard Smith4b5a9492014-01-24 22:34:35 +00002341
2342 // For compatibility with code written to older Clang, also accept a
2343 // virt-specifier *after* the GNU attributes.
Aaron Ballman5d153e32014-08-04 17:03:51 +00002344 if (BitfieldSize.isUnset() && VS.isUnset()) {
Richard Smith3d1a94c2014-08-12 00:22:39 +00002345 ParseOptionalCXX11VirtSpecifierSeq(
2346 VS, getCurrentClass().IsInterface,
2347 DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
Aaron Ballman5d153e32014-08-04 17:03:51 +00002348 if (!VS.isUnset()) {
2349 // If we saw any GNU-style attributes that are known to GCC followed by a
2350 // virt-specifier, issue a GCC-compat warning.
Erich Keanee891aa92018-07-13 15:07:47 +00002351 for (const ParsedAttr &AL : DeclaratorInfo.getAttributes())
Erich Keanec480f302018-07-12 21:09:05 +00002352 if (AL.isKnownToGCC() && !AL.isCXX11Attribute())
2353 Diag(AL.getLoc(), diag::warn_gcc_attribute_location);
2354
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002355 MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo, VS);
Aaron Ballman5d153e32014-08-04 17:03:51 +00002356 }
2357 }
Nico Weberd89e6f72015-01-16 19:34:13 +00002358
2359 // If this has neither a name nor a bit width, something has gone seriously
2360 // wrong. Skip until the semi-colon or }.
2361 if (!DeclaratorInfo.hasName() && BitfieldSize.isUnset()) {
2362 // If so, skip until the semi-colon or a }.
2363 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2364 return true;
2365 }
2366 return false;
Richard Smith72553fc2014-01-23 23:53:27 +00002367}
2368
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002369/// Look for declaration specifiers possibly occurring after C++11
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002370/// virt-specifier-seq and diagnose them.
2371void Parser::MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(
2372 Declarator &D,
2373 VirtSpecifiers &VS) {
2374 DeclSpec DS(AttrFactory);
2375
2376 // GNU-style and C++11 attributes are not allowed here, but they will be
2377 // handled by the caller. Diagnose everything else.
Alex Lorenz8f4d3992017-02-13 23:19:40 +00002378 ParseTypeQualifierListOpt(
2379 DS, AR_NoAttributesParsed, false,
2380 /*IdentifierRequired=*/false, llvm::function_ref<void()>([&]() {
2381 Actions.CodeCompleteFunctionQualifiers(DS, D, &VS);
2382 }));
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002383 D.ExtendWithDeclSpec(DS);
2384
2385 if (D.isFunctionDeclarator()) {
Ehsan Akhgaric07d1e22015-03-25 00:53:33 +00002386 auto &Function = D.getFunctionTypeInfo();
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002387 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
Anastasia Stulovaa9bc4bd2019-01-09 11:25:09 +00002388 auto DeclSpecCheck = [&](DeclSpec::TQ TypeQual, StringRef FixItName,
2389 SourceLocation SpecLoc) {
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002390 FixItHint Insertion;
Anastasia Stulovaa9bc4bd2019-01-09 11:25:09 +00002391 auto &MQ = Function.getOrCreateMethodQualifiers();
2392 if (!(MQ.getTypeQualifiers() & TypeQual)) {
2393 std::string Name(FixItName.data());
2394 Name += " ";
2395 Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), Name);
2396 MQ.SetTypeQual(TypeQual, SpecLoc);
2397 }
2398 Diag(SpecLoc, diag::err_declspec_after_virtspec)
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002399 << FixItName
2400 << VirtSpecifiers::getSpecifierName(VS.getLastSpecifier())
Anastasia Stulovaa9bc4bd2019-01-09 11:25:09 +00002401 << FixItHint::CreateRemoval(SpecLoc) << Insertion;
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002402 };
Anastasia Stulovaa9bc4bd2019-01-09 11:25:09 +00002403 DS.forEachQualifier(DeclSpecCheck);
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002404 }
Ehsan Akhgaric07d1e22015-03-25 00:53:33 +00002405
2406 // Parse ref-qualifiers.
2407 bool RefQualifierIsLValueRef = true;
2408 SourceLocation RefQualifierLoc;
2409 if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc)) {
2410 const char *Name = (RefQualifierIsLValueRef ? "& " : "&& ");
2411 FixItHint Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), Name);
2412 Function.RefQualifierIsLValueRef = RefQualifierIsLValueRef;
2413 Function.RefQualifierLoc = RefQualifierLoc.getRawEncoding();
2414
2415 Diag(RefQualifierLoc, diag::err_declspec_after_virtspec)
2416 << (RefQualifierIsLValueRef ? "&" : "&&")
2417 << VirtSpecifiers::getSpecifierName(VS.getLastSpecifier())
2418 << FixItHint::CreateRemoval(RefQualifierLoc)
2419 << Insertion;
2420 D.SetRangeEnd(RefQualifierLoc);
2421 }
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002422 }
2423}
2424
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002425/// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration.
2426///
2427/// member-declaration:
2428/// decl-specifier-seq[opt] member-declarator-list[opt] ';'
2429/// function-definition ';'[opt]
2430/// ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO]
2431/// using-declaration [TODO]
Anders Carlssonf24fcff62009-03-11 16:27:10 +00002432/// [C++0x] static_assert-declaration
Anders Carlssondfbbdf62009-03-26 00:52:18 +00002433/// template-declaration
Chris Lattnerd19c1c02008-12-18 01:12:00 +00002434/// [GNU] '__extension__' member-declaration
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002435///
2436/// member-declarator-list:
2437/// member-declarator
2438/// member-declarator-list ',' member-declarator
2439///
2440/// member-declarator:
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002441/// declarator virt-specifier-seq[opt] pure-specifier[opt]
Saar Razb65b1f32020-01-09 15:07:51 +02002442/// [C++2a] declarator requires-clause
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002443/// declarator constant-initializer[opt]
Richard Smith938f40b2011-06-11 17:19:42 +00002444/// [C++11] declarator brace-or-equal-initializer[opt]
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002445/// identifier[opt] ':' constant-expression
2446///
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002447/// virt-specifier-seq:
2448/// virt-specifier
2449/// virt-specifier-seq virt-specifier
2450///
2451/// virt-specifier:
2452/// override
2453/// final
David Majnemera5433082013-10-18 00:33:31 +00002454/// [MS] sealed
Fangrui Song6907ce22018-07-30 19:24:48 +00002455///
Sebastian Redl42e92c42009-04-12 17:16:29 +00002456/// pure-specifier:
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002457/// '= 0'
2458///
2459/// constant-initializer:
2460/// '=' constant-expression
2461///
Alexey Bataev05c25d62015-07-31 08:42:25 +00002462Parser::DeclGroupPtrTy
2463Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS,
Erich Keanec480f302018-07-12 21:09:05 +00002464 ParsedAttributes &AccessAttrs,
John McCall796c2a52010-07-16 08:13:16 +00002465 const ParsedTemplateInfo &TemplateInfo,
2466 ParsingDeclRAIIObject *TemplateDiags) {
Douglas Gregor23c84762011-04-14 17:21:19 +00002467 if (Tok.is(tok::at)) {
Erik Pilkingtonfa983902018-10-30 20:31:30 +00002468 if (getLangOpts().ObjC && NextToken().isObjCAtKeyword(tok::objc_defs))
Douglas Gregor23c84762011-04-14 17:21:19 +00002469 Diag(Tok, diag::err_at_defs_cxx);
2470 else
2471 Diag(Tok, diag::err_at_in_class);
Richard Smithda35e962013-11-09 04:52:51 +00002472
Douglas Gregor23c84762011-04-14 17:21:19 +00002473 ConsumeToken();
Alexey Bataevee6507d2013-11-18 08:17:37 +00002474 SkipUntil(tok::r_brace, StopAtSemi);
David Blaikie0403cb12016-01-15 23:43:25 +00002475 return nullptr;
Douglas Gregor23c84762011-04-14 17:21:19 +00002476 }
Richard Smithda35e962013-11-09 04:52:51 +00002477
Serge Pavlov458ea762014-07-16 05:16:52 +00002478 // Turn on colon protection early, while parsing declspec, although there is
2479 // nothing to protect there. It prevents from false errors if error recovery
2480 // incorrectly determines where the declspec ends, as in the example:
2481 // struct A { enum class B { C }; };
2482 // const int C = 4;
2483 // struct D { A::B : C; };
2484 ColonProtectionRAIIObject X(*this);
2485
John McCalla0097262009-12-11 02:10:03 +00002486 // Access declarations.
Richard Smith45855df2012-05-09 08:23:23 +00002487 bool MalformedTypeSpec = false;
John McCalla0097262009-12-11 02:10:03 +00002488 if (!TemplateInfo.Kind &&
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002489 Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw___super)) {
Richard Smith45855df2012-05-09 08:23:23 +00002490 if (TryAnnotateCXXScopeToken())
2491 MalformedTypeSpec = true;
2492
2493 bool isAccessDecl;
2494 if (Tok.isNot(tok::annot_cxxscope))
2495 isAccessDecl = false;
2496 else if (NextToken().is(tok::identifier))
John McCalla0097262009-12-11 02:10:03 +00002497 isAccessDecl = GetLookAheadToken(2).is(tok::semi);
2498 else
2499 isAccessDecl = NextToken().is(tok::kw_operator);
2500
2501 if (isAccessDecl) {
2502 // Collect the scope specifier token we annotated earlier.
2503 CXXScopeSpec SS;
David Blaikieefdccaa2016-01-15 23:43:34 +00002504 ParseOptionalCXXScopeSpecifier(SS, nullptr,
Douglas Gregordf593fb2011-11-07 17:33:42 +00002505 /*EnteringContext=*/false);
John McCalla0097262009-12-11 02:10:03 +00002506
Nico Weberef03e702014-09-10 00:59:37 +00002507 if (SS.isInvalid()) {
2508 SkipUntil(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002509 return nullptr;
Nico Weberef03e702014-09-10 00:59:37 +00002510 }
2511
John McCalla0097262009-12-11 02:10:03 +00002512 // Try to parse an unqualified-id.
Abramo Bagnara7945c982012-01-27 09:46:47 +00002513 SourceLocation TemplateKWLoc;
John McCalla0097262009-12-11 02:10:03 +00002514 UnqualifiedId Name;
Richard Smith35845152017-02-07 01:37:30 +00002515 if (ParseUnqualifiedId(SS, false, true, true, false, nullptr,
Richard Smithc08b6932018-04-27 02:00:13 +00002516 &TemplateKWLoc, Name)) {
John McCalla0097262009-12-11 02:10:03 +00002517 SkipUntil(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002518 return nullptr;
John McCalla0097262009-12-11 02:10:03 +00002519 }
2520
2521 // TODO: recover from mistakenly-qualified operator declarations.
Alp Toker383d2c42014-01-01 03:08:43 +00002522 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
2523 "access declaration")) {
2524 SkipUntil(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002525 return nullptr;
Alp Toker383d2c42014-01-01 03:08:43 +00002526 }
John McCalla0097262009-12-11 02:10:03 +00002527
Richard Smithc08b6932018-04-27 02:00:13 +00002528 // FIXME: We should do something with the 'template' keyword here.
Alexey Bataev05c25d62015-07-31 08:42:25 +00002529 return DeclGroupPtrTy::make(DeclGroupRef(Actions.ActOnUsingDeclaration(
Richard Smith151c4562016-12-20 21:35:28 +00002530 getCurScope(), AS, /*UsingLoc*/ SourceLocation(),
2531 /*TypenameLoc*/ SourceLocation(), SS, Name,
Erich Keanec480f302018-07-12 21:09:05 +00002532 /*EllipsisLoc*/ SourceLocation(),
2533 /*AttrList*/ ParsedAttributesView())));
John McCalla0097262009-12-11 02:10:03 +00002534 }
2535 }
2536
Aaron Ballmane7c544d2014-08-04 20:28:35 +00002537 // static_assert-declaration. A templated static_assert declaration is
2538 // diagnosed in Parser::ParseSingleDeclarationAfterTemplate.
2539 if (!TemplateInfo.Kind &&
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002540 Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert)) {
Chris Lattner49836b42009-04-02 04:16:50 +00002541 SourceLocation DeclEnd;
Alexey Bataev05c25d62015-07-31 08:42:25 +00002542 return DeclGroupPtrTy::make(
2543 DeclGroupRef(ParseStaticAssertDeclaration(DeclEnd)));
Chris Lattner5bbb3c82009-03-29 16:50:03 +00002544 }
Mike Stump11289f42009-09-09 15:08:12 +00002545
Chris Lattner5bbb3c82009-03-29 16:50:03 +00002546 if (Tok.is(tok::kw_template)) {
Mike Stump11289f42009-09-09 15:08:12 +00002547 assert(!TemplateInfo.TemplateParams &&
Douglas Gregor3447e762009-08-20 22:52:58 +00002548 "Nested template improperly parsed?");
Richard Smith3af70092017-02-09 22:14:25 +00002549 ObjCDeclContextSwitch ObjCDC(*this);
Chris Lattner49836b42009-04-02 04:16:50 +00002550 SourceLocation DeclEnd;
Alexey Bataev05c25d62015-07-31 08:42:25 +00002551 return DeclGroupPtrTy::make(
Richard Smith3af70092017-02-09 22:14:25 +00002552 DeclGroupRef(ParseTemplateDeclarationOrSpecialization(
Erich Keanec480f302018-07-12 21:09:05 +00002553 DeclaratorContext::MemberContext, DeclEnd, AccessAttrs, AS)));
Chris Lattner5bbb3c82009-03-29 16:50:03 +00002554 }
Anders Carlssondfbbdf62009-03-26 00:52:18 +00002555
Chris Lattnerd19c1c02008-12-18 01:12:00 +00002556 // Handle: member-declaration ::= '__extension__' member-declaration
2557 if (Tok.is(tok::kw___extension__)) {
2558 // __extension__ silences extension warnings in the subexpression.
2559 ExtensionRAIIObject O(Diags); // Use RAII to do this.
2560 ConsumeToken();
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00002561 return ParseCXXClassMemberDeclaration(AS, AccessAttrs,
2562 TemplateInfo, TemplateDiags);
Chris Lattnerd19c1c02008-12-18 01:12:00 +00002563 }
Douglas Gregorfec52632009-06-20 00:51:54 +00002564
John McCall084e83d2011-03-24 11:26:52 +00002565 ParsedAttributesWithRange attrs(AttrFactory);
Erich Keanec480f302018-07-12 21:09:05 +00002566 ParsedAttributesViewWithRange FnAttrs;
Richard Smith89645bc2013-01-02 12:01:23 +00002567 // Optional C++11 attribute-specifier
2568 MaybeParseCXX11Attributes(attrs);
Michael Handdc016d2012-11-28 23:17:40 +00002569 // We need to keep these attributes for future diagnostic
2570 // before they are taken over by declaration specifier.
Erich Keanec480f302018-07-12 21:09:05 +00002571 FnAttrs.addAll(attrs.begin(), attrs.end());
Michael Handdc016d2012-11-28 23:17:40 +00002572 FnAttrs.Range = attrs.Range;
2573
John McCall53fa7142010-12-24 02:08:15 +00002574 MaybeParseMicrosoftAttributes(attrs);
Alexis Hunt96d5c762009-11-21 08:43:09 +00002575
Douglas Gregorfec52632009-06-20 00:51:54 +00002576 if (Tok.is(tok::kw_using)) {
John McCall53fa7142010-12-24 02:08:15 +00002577 ProhibitAttributes(attrs);
Mike Stump11289f42009-09-09 15:08:12 +00002578
Douglas Gregorfec52632009-06-20 00:51:54 +00002579 // Eat 'using'.
2580 SourceLocation UsingLoc = ConsumeToken();
2581
Richard Trieu2efd3052019-05-01 23:33:49 +00002582 // Consume unexpected 'template' keywords.
2583 while (Tok.is(tok::kw_template)) {
2584 SourceLocation TemplateLoc = ConsumeToken();
2585 Diag(TemplateLoc, diag::err_unexpected_template_after_using)
2586 << FixItHint::CreateRemoval(TemplateLoc);
2587 }
2588
Douglas Gregorfec52632009-06-20 00:51:54 +00002589 if (Tok.is(tok::kw_namespace)) {
2590 Diag(UsingLoc, diag::err_using_namespace_in_class);
Alexey Bataevee6507d2013-11-18 08:17:37 +00002591 SkipUntil(tok::semi, StopBeforeMatch);
David Blaikie0403cb12016-01-15 23:43:25 +00002592 return nullptr;
Douglas Gregorfec52632009-06-20 00:51:54 +00002593 }
Alexey Bataev05c25d62015-07-31 08:42:25 +00002594 SourceLocation DeclEnd;
2595 // Otherwise, it must be a using-declaration or an alias-declaration.
Faisal Vali421b2d12017-12-29 05:41:00 +00002596 return ParseUsingDeclaration(DeclaratorContext::MemberContext, TemplateInfo,
Richard Smith6f1daa42016-12-16 00:58:48 +00002597 UsingLoc, DeclEnd, AS);
Douglas Gregorfec52632009-06-20 00:51:54 +00002598 }
2599
DeLesley Hutchinsbd2ee132012-03-02 22:12:59 +00002600 // Hold late-parsed attributes so we can attach a Decl to them later.
2601 LateParsedAttrList CommonLateParsedAttrs;
2602
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002603 // decl-specifier-seq:
2604 // Parse the common declaration-specifiers piece.
John McCall796c2a52010-07-16 08:13:16 +00002605 ParsingDeclSpec DS(*this, TemplateDiags);
John McCall53fa7142010-12-24 02:08:15 +00002606 DS.takeAttributesFrom(attrs);
Richard Smith45855df2012-05-09 08:23:23 +00002607 if (MalformedTypeSpec)
2608 DS.SetTypeSpecError();
Richard Smith72553fc2014-01-23 23:53:27 +00002609
Faisal Valia534f072018-04-26 00:42:40 +00002610 ParseDeclarationSpecifiers(DS, TemplateInfo, AS, DeclSpecContext::DSC_class,
2611 &CommonLateParsedAttrs);
Serge Pavlov458ea762014-07-16 05:16:52 +00002612
2613 // Turn off colon protection that was set for declspec.
2614 X.restore();
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002615
Richard Smith404dfb42013-11-19 22:47:36 +00002616 // If we had a free-standing type definition with a missing semicolon, we
2617 // may get this far before the problem becomes obvious.
2618 if (DS.hasTagDefinition() &&
2619 TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate &&
Faisal Vali7db85c52017-12-31 00:06:40 +00002620 DiagnoseMissingSemiAfterTagDefinition(DS, AS, DeclSpecContext::DSC_class,
Richard Smith404dfb42013-11-19 22:47:36 +00002621 &CommonLateParsedAttrs))
David Blaikie0403cb12016-01-15 23:43:25 +00002622 return nullptr;
Richard Smith404dfb42013-11-19 22:47:36 +00002623
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002624 MultiTemplateParamsArg TemplateParams(
Craig Topper161e4db2014-05-21 06:02:52 +00002625 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->data()
2626 : nullptr,
John McCall11083da2009-09-16 22:47:08 +00002627 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->size() : 0);
2628
Alp Toker35d87032013-12-30 23:29:50 +00002629 if (TryConsumeToken(tok::semi)) {
Michael Handdc016d2012-11-28 23:17:40 +00002630 if (DS.isFriendSpecified())
2631 ProhibitAttributes(FnAttrs);
2632
Nico Weber7b837f52016-01-28 19:25:00 +00002633 RecordDecl *AnonRecord = nullptr;
2634 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(
2635 getCurScope(), AS, DS, TemplateParams, false, AnonRecord);
John McCall796c2a52010-07-16 08:13:16 +00002636 DS.complete(TheDecl);
Nico Weber7b837f52016-01-28 19:25:00 +00002637 if (AnonRecord) {
2638 Decl* decls[] = {AnonRecord, TheDecl};
Richard Smith3beb7c62017-01-12 02:27:38 +00002639 return Actions.BuildDeclaratorGroup(decls);
Nico Weber7b837f52016-01-28 19:25:00 +00002640 }
2641 return Actions.ConvertDeclToDeclGroup(TheDecl);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002642 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002643
Faisal Vali421b2d12017-12-29 05:41:00 +00002644 ParsingDeclarator DeclaratorInfo(*this, DS, DeclaratorContext::MemberContext);
Nico Weber24b2a822011-01-28 06:07:34 +00002645 VirtSpecifiers VS;
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002646
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002647 // Hold late-parsed attributes so we can attach a Decl to them later.
2648 LateParsedAttrList LateParsedAttrs;
2649
Douglas Gregor50cefbf2011-10-17 17:09:53 +00002650 SourceLocation EqualLoc;
Richard Smith9ba0fec2015-06-30 01:28:56 +00002651 SourceLocation PureSpecLoc;
2652
Yaron Keren180c1672015-06-30 07:35:19 +00002653 auto TryConsumePureSpecifier = [&] (bool AllowDefinition) {
Richard Smith9ba0fec2015-06-30 01:28:56 +00002654 if (Tok.isNot(tok::equal))
2655 return false;
2656
2657 auto &Zero = NextToken();
2658 SmallString<8> Buffer;
2659 if (Zero.isNot(tok::numeric_constant) || Zero.getLength() != 1 ||
2660 PP.getSpelling(Zero, Buffer) != "0")
2661 return false;
2662
2663 auto &After = GetLookAheadToken(2);
2664 if (!After.isOneOf(tok::semi, tok::comma) &&
2665 !(AllowDefinition &&
2666 After.isOneOf(tok::l_brace, tok::colon, tok::kw_try)))
2667 return false;
2668
2669 EqualLoc = ConsumeToken();
2670 PureSpecLoc = ConsumeToken();
2671 return true;
2672 };
Chris Lattner17c3b1f2009-12-10 01:59:24 +00002673
Richard Smith72553fc2014-01-23 23:53:27 +00002674 SmallVector<Decl *, 8> DeclsInGroup;
2675 ExprResult BitfieldSize;
Saar Razb65b1f32020-01-09 15:07:51 +02002676 ExprResult TrailingRequiresClause;
Richard Smith72553fc2014-01-23 23:53:27 +00002677 bool ExpectSemi = true;
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002678
Richard Smith72553fc2014-01-23 23:53:27 +00002679 // Parse the first declarator.
Nico Weberd89e6f72015-01-16 19:34:13 +00002680 if (ParseCXXMemberDeclaratorBeforeInitializer(
2681 DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs)) {
Richard Smith72553fc2014-01-23 23:53:27 +00002682 TryConsumeToken(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002683 return nullptr;
Richard Smith72553fc2014-01-23 23:53:27 +00002684 }
John Thompson5bc5cbe2009-11-25 22:58:06 +00002685
Richard Smith72553fc2014-01-23 23:53:27 +00002686 // Check for a member function definition.
Richard Smith4b5a9492014-01-24 22:34:35 +00002687 if (BitfieldSize.isUnset()) {
Richard Smith72553fc2014-01-23 23:53:27 +00002688 // MSVC permits pure specifier on inline functions defined at class scope.
Francois Pichet3abc9b82011-05-11 02:14:46 +00002689 // Hence check for =0 before checking for function definition.
Richard Smith9ba0fec2015-06-30 01:28:56 +00002690 if (getLangOpts().MicrosoftExt && DeclaratorInfo.isDeclarationOfFunction())
2691 TryConsumePureSpecifier(/*AllowDefinition*/ true);
Francois Pichet3abc9b82011-05-11 02:14:46 +00002692
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00002693 FunctionDefinitionKind DefinitionKind = FDK_Declaration;
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002694 // function-definition:
Richard Smith938f40b2011-06-11 17:19:42 +00002695 //
2696 // In C++11, a non-function declarator followed by an open brace is a
2697 // braced-init-list for an in-class member initialization, not an
2698 // erroneous function definition.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002699 if (Tok.is(tok::l_brace) && !getLangOpts().CPlusPlus11) {
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00002700 DefinitionKind = FDK_Definition;
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002701 } else if (DeclaratorInfo.isFunctionDeclarator()) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002702 if (Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try)) {
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00002703 DefinitionKind = FDK_Definition;
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002704 } else if (Tok.is(tok::equal)) {
2705 const Token &KW = NextToken();
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00002706 if (KW.is(tok::kw_default))
2707 DefinitionKind = FDK_Defaulted;
2708 else if (KW.is(tok::kw_delete))
2709 DefinitionKind = FDK_Deleted;
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002710 }
2711 }
Eli Bendersky41842222015-03-23 23:49:41 +00002712 DeclaratorInfo.setFunctionDefinitionKind(DefinitionKind);
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002713
Fangrui Song6907ce22018-07-30 19:24:48 +00002714 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
Michael Handdc016d2012-11-28 23:17:40 +00002715 // to a friend declaration, that declaration shall be a definition.
Fangrui Song6907ce22018-07-30 19:24:48 +00002716 if (DeclaratorInfo.isFunctionDeclarator() &&
Michael Handdc016d2012-11-28 23:17:40 +00002717 DefinitionKind != FDK_Definition && DS.isFriendSpecified()) {
2718 // Diagnose attributes that appear before decl specifier:
2719 // [[]] friend int foo();
2720 ProhibitAttributes(FnAttrs);
2721 }
2722
Nico Webera7f137d2015-01-16 19:35:01 +00002723 if (DefinitionKind != FDK_Declaration) {
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002724 if (!DeclaratorInfo.isFunctionDeclarator()) {
Richard Trieu0d730542012-01-21 02:59:18 +00002725 Diag(DeclaratorInfo.getIdentifierLoc(), diag::err_func_def_no_params);
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002726 ConsumeBrace();
Alexey Bataevee6507d2013-11-18 08:17:37 +00002727 SkipUntil(tok::r_brace);
Michael Handdc016d2012-11-28 23:17:40 +00002728
Douglas Gregor8a4db832011-01-19 16:41:58 +00002729 // Consume the optional ';'
Alp Toker35d87032013-12-30 23:29:50 +00002730 TryConsumeToken(tok::semi);
2731
David Blaikie0403cb12016-01-15 23:43:25 +00002732 return nullptr;
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002733 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002734
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002735 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
Richard Trieu0d730542012-01-21 02:59:18 +00002736 Diag(DeclaratorInfo.getIdentifierLoc(),
2737 diag::err_function_declared_typedef);
Douglas Gregor8a4db832011-01-19 16:41:58 +00002738
Richard Smith2603b092012-11-15 22:54:20 +00002739 // Recover by treating the 'typedef' as spurious.
2740 DS.ClearStorageClassSpecs();
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002741 }
2742
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002743 Decl *FunDecl =
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00002744 ParseCXXInlineMethodDef(AS, AccessAttrs, DeclaratorInfo, TemplateInfo,
Richard Smith9ba0fec2015-06-30 01:28:56 +00002745 VS, PureSpecLoc);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002746
David Majnemer23252a32013-08-01 04:22:55 +00002747 if (FunDecl) {
2748 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i) {
2749 CommonLateParsedAttrs[i]->addDecl(FunDecl);
2750 }
2751 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i) {
2752 LateParsedAttrs[i]->addDecl(FunDecl);
2753 }
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002754 }
2755 LateParsedAttrs.clear();
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002756
2757 // Consume the ';' - it's optional unless we have a delete or default
Richard Trieu2f7dc462012-05-16 19:04:59 +00002758 if (Tok.is(tok::semi))
Richard Smith87f5dc52012-07-23 05:45:25 +00002759 ConsumeExtraSemi(AfterMemberFunctionDefinition);
Douglas Gregor8a4db832011-01-19 16:41:58 +00002760
Alexey Bataev05c25d62015-07-31 08:42:25 +00002761 return DeclGroupPtrTy::make(DeclGroupRef(FunDecl));
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002762 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002763 }
2764
2765 // member-declarator-list:
2766 // member-declarator
2767 // member-declarator-list ',' member-declarator
2768
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002769 while (1) {
Richard Smith2b013182012-06-10 03:12:00 +00002770 InClassInitStyle HasInClassInit = ICIS_NoInit;
Richard Smith9ba0fec2015-06-30 01:28:56 +00002771 bool HasStaticInitializer = false;
2772 if (Tok.isOneOf(tok::equal, tok::l_brace) && PureSpecLoc.isInvalid()) {
Richard Smith6b8e3c02017-08-28 00:28:14 +00002773 if (DeclaratorInfo.isDeclarationOfFunction()) {
Richard Smith9ba0fec2015-06-30 01:28:56 +00002774 // It's a pure-specifier.
2775 if (!TryConsumePureSpecifier(/*AllowFunctionDefinition*/ false))
2776 // Parse it as an expression so that Sema can diagnose it.
2777 HasStaticInitializer = true;
2778 } else if (DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2779 DeclSpec::SCS_static &&
2780 DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2781 DeclSpec::SCS_typedef &&
2782 !DS.isFriendSpecified()) {
2783 // It's a default member initializer.
Richard Smith6b8e3c02017-08-28 00:28:14 +00002784 if (BitfieldSize.get())
2785 Diag(Tok, getLangOpts().CPlusPlus2a
2786 ? diag::warn_cxx17_compat_bitfield_member_init
2787 : diag::ext_bitfield_member_init);
Richard Smith9ba0fec2015-06-30 01:28:56 +00002788 HasInClassInit = Tok.is(tok::equal) ? ICIS_CopyInit : ICIS_ListInit;
Richard Smith938f40b2011-06-11 17:19:42 +00002789 } else {
Richard Smith9ba0fec2015-06-30 01:28:56 +00002790 HasStaticInitializer = true;
Richard Smith938f40b2011-06-11 17:19:42 +00002791 }
2792 }
2793
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002794 // NOTE: If Sema is the Action module and declarator is an instance field,
Chris Lattner5bbb3c82009-03-29 16:50:03 +00002795 // this call will *not* return the created decl; It will return null.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002796 // See Sema::ActOnCXXMemberDeclarator for details.
John McCall07e91c02009-08-06 02:15:43 +00002797
Craig Topper161e4db2014-05-21 06:02:52 +00002798 NamedDecl *ThisDecl = nullptr;
John McCall07e91c02009-08-06 02:15:43 +00002799 if (DS.isFriendSpecified()) {
Richard Smith72553fc2014-01-23 23:53:27 +00002800 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
Michael Handdc016d2012-11-28 23:17:40 +00002801 // to a friend declaration, that declaration shall be a definition.
2802 //
Richard Smith72553fc2014-01-23 23:53:27 +00002803 // Diagnose attributes that appear in a friend member function declarator:
2804 // friend int foo [[]] ();
Michael Handdc016d2012-11-28 23:17:40 +00002805 SmallVector<SourceRange, 4> Ranges;
2806 DeclaratorInfo.getCXX11AttributeRanges(Ranges);
Richard Smith72553fc2014-01-23 23:53:27 +00002807 for (SmallVectorImpl<SourceRange>::iterator I = Ranges.begin(),
2808 E = Ranges.end(); I != E; ++I)
2809 Diag((*I).getBegin(), diag::err_attributes_not_allowed) << *I;
Michael Handdc016d2012-11-28 23:17:40 +00002810
Douglas Gregor0be31a22010-07-02 17:43:08 +00002811 ThisDecl = Actions.ActOnFriendFunctionDecl(getCurScope(), DeclaratorInfo,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002812 TemplateParams);
Douglas Gregor3447e762009-08-20 22:52:58 +00002813 } else {
Douglas Gregor0be31a22010-07-02 17:43:08 +00002814 ThisDecl = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS,
John McCall07e91c02009-08-06 02:15:43 +00002815 DeclaratorInfo,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002816 TemplateParams,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002817 BitfieldSize.get(),
Richard Smith2b013182012-06-10 03:12:00 +00002818 VS, HasInClassInit);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002819
2820 if (VarTemplateDecl *VT =
Craig Topper161e4db2014-05-21 06:02:52 +00002821 ThisDecl ? dyn_cast<VarTemplateDecl>(ThisDecl) : nullptr)
Larisse Voufo39a1e502013-08-06 01:03:05 +00002822 // Re-direct this decl to refer to the templated decl so that we can
2823 // initialize it.
2824 ThisDecl = VT->getTemplatedDecl();
2825
Erich Keanec480f302018-07-12 21:09:05 +00002826 if (ThisDecl)
Richard Smithf8a75c32013-08-29 00:47:48 +00002827 Actions.ProcessDeclAttributeList(getCurScope(), ThisDecl, AccessAttrs);
Douglas Gregor3447e762009-08-20 22:52:58 +00002828 }
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002829
Richard Smith9ba0fec2015-06-30 01:28:56 +00002830 // Error recovery might have converted a non-static member into a static
2831 // member.
David Blaikie35506f82013-01-30 01:22:18 +00002832 if (HasInClassInit != ICIS_NoInit &&
Richard Smith9ba0fec2015-06-30 01:28:56 +00002833 DeclaratorInfo.getDeclSpec().getStorageClassSpec() ==
2834 DeclSpec::SCS_static) {
2835 HasInClassInit = ICIS_NoInit;
2836 HasStaticInitializer = true;
2837 }
2838
2839 if (ThisDecl && PureSpecLoc.isValid())
2840 Actions.ActOnPureSpecifier(ThisDecl, PureSpecLoc);
2841
2842 // Handle the initializer.
2843 if (HasInClassInit != ICIS_NoInit) {
Douglas Gregor728d00b2011-10-10 14:49:18 +00002844 // The initializer was deferred; parse it and cache the tokens.
David Majnemer23252a32013-08-01 04:22:55 +00002845 Diag(Tok, getLangOpts().CPlusPlus11
2846 ? diag::warn_cxx98_compat_nonstatic_member_init
2847 : diag::ext_nonstatic_member_init);
Richard Smith5d164bc2011-10-15 05:09:34 +00002848
Richard Smith938f40b2011-06-11 17:19:42 +00002849 if (DeclaratorInfo.isArrayOfUnknownBound()) {
Richard Smith2b013182012-06-10 03:12:00 +00002850 // C++11 [dcl.array]p3: An array bound may also be omitted when the
2851 // declarator is followed by an initializer.
Richard Smith938f40b2011-06-11 17:19:42 +00002852 //
2853 // A brace-or-equal-initializer for a member-declarator is not an
David Blaikiecdd91db2012-02-14 09:00:46 +00002854 // initializer in the grammar, so this is ill-formed.
Richard Smith938f40b2011-06-11 17:19:42 +00002855 Diag(Tok, diag::err_incomplete_array_member_init);
Alexey Bataevee6507d2013-11-18 08:17:37 +00002856 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
David Majnemer23252a32013-08-01 04:22:55 +00002857
2858 // Avoid later warnings about a class member of incomplete type.
David Blaikiecdd91db2012-02-14 09:00:46 +00002859 if (ThisDecl)
David Blaikiecdd91db2012-02-14 09:00:46 +00002860 ThisDecl->setInvalidDecl();
Richard Smith938f40b2011-06-11 17:19:42 +00002861 } else
2862 ParseCXXNonStaticMemberInitializer(ThisDecl);
Richard Smith9ba0fec2015-06-30 01:28:56 +00002863 } else if (HasStaticInitializer) {
Douglas Gregor728d00b2011-10-10 14:49:18 +00002864 // Normal initializer.
Richard Smith9ba0fec2015-06-30 01:28:56 +00002865 ExprResult Init = ParseCXXMemberInitializer(
2866 ThisDecl, DeclaratorInfo.isDeclarationOfFunction(), EqualLoc);
David Majnemer23252a32013-08-01 04:22:55 +00002867
Douglas Gregor728d00b2011-10-10 14:49:18 +00002868 if (Init.isInvalid())
Alexey Bataevee6507d2013-11-18 08:17:37 +00002869 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
Douglas Gregor728d00b2011-10-10 14:49:18 +00002870 else if (ThisDecl)
Richard Smith3beb7c62017-01-12 02:27:38 +00002871 Actions.AddInitializerToDecl(ThisDecl, Init.get(), EqualLoc.isInvalid());
David Majnemer23252a32013-08-01 04:22:55 +00002872 } else if (ThisDecl && DS.getStorageClassSpec() == DeclSpec::SCS_static)
Douglas Gregor728d00b2011-10-10 14:49:18 +00002873 // No initializer.
Richard Smith3beb7c62017-01-12 02:27:38 +00002874 Actions.ActOnUninitializedDecl(ThisDecl);
David Majnemer23252a32013-08-01 04:22:55 +00002875
Douglas Gregor728d00b2011-10-10 14:49:18 +00002876 if (ThisDecl) {
David Majnemer23252a32013-08-01 04:22:55 +00002877 if (!ThisDecl->isInvalidDecl()) {
2878 // Set the Decl for any late parsed attributes
2879 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i)
2880 CommonLateParsedAttrs[i]->addDecl(ThisDecl);
2881
2882 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i)
2883 LateParsedAttrs[i]->addDecl(ThisDecl);
2884 }
Douglas Gregor728d00b2011-10-10 14:49:18 +00002885 Actions.FinalizeDeclaration(ThisDecl);
2886 DeclsInGroup.push_back(ThisDecl);
David Majnemer23252a32013-08-01 04:22:55 +00002887
2888 if (DeclaratorInfo.isFunctionDeclarator() &&
2889 DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2890 DeclSpec::SCS_typedef)
2891 HandleMemberFunctionDeclDelays(DeclaratorInfo, ThisDecl);
Douglas Gregor728d00b2011-10-10 14:49:18 +00002892 }
David Majnemer23252a32013-08-01 04:22:55 +00002893 LateParsedAttrs.clear();
Douglas Gregor728d00b2011-10-10 14:49:18 +00002894
2895 DeclaratorInfo.complete(ThisDecl);
Richard Smith938f40b2011-06-11 17:19:42 +00002896
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002897 // If we don't have a comma, it is either the end of the list (a ';')
2898 // or an error, bail out.
Alp Toker094e5212014-01-05 03:27:11 +00002899 SourceLocation CommaLoc;
2900 if (!TryConsumeToken(tok::comma, CommaLoc))
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002901 break;
Mike Stump11289f42009-09-09 15:08:12 +00002902
Richard Smithc8a79032012-01-09 22:31:44 +00002903 if (Tok.isAtStartOfLine() &&
Faisal Vali421b2d12017-12-29 05:41:00 +00002904 !MightBeDeclarator(DeclaratorContext::MemberContext)) {
Richard Smithc8a79032012-01-09 22:31:44 +00002905 // This comma was followed by a line-break and something which can't be
2906 // the start of a declarator. The comma was probably a typo for a
2907 // semicolon.
2908 Diag(CommaLoc, diag::err_expected_semi_declaration)
2909 << FixItHint::CreateReplacement(CommaLoc, ";");
2910 ExpectSemi = false;
2911 break;
2912 }
Mike Stump11289f42009-09-09 15:08:12 +00002913
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002914 // Parse the next declarator.
2915 DeclaratorInfo.clear();
Nico Weber24b2a822011-01-28 06:07:34 +00002916 VS.clear();
Nico Weberf56c85b2015-01-17 02:26:40 +00002917 BitfieldSize = ExprResult(/*Invalid=*/false);
Richard Smith9ba0fec2015-06-30 01:28:56 +00002918 EqualLoc = PureSpecLoc = SourceLocation();
Richard Smith8d06f422012-01-12 23:53:29 +00002919 DeclaratorInfo.setCommaLoc(CommaLoc);
Mike Stump11289f42009-09-09 15:08:12 +00002920
Richard Smith72553fc2014-01-23 23:53:27 +00002921 // GNU attributes are allowed before the second and subsequent declarator.
John McCall53fa7142010-12-24 02:08:15 +00002922 MaybeParseGNUAttributes(DeclaratorInfo);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002923
Nico Weberd89e6f72015-01-16 19:34:13 +00002924 if (ParseCXXMemberDeclaratorBeforeInitializer(
2925 DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs))
2926 break;
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002927 }
2928
Richard Smithc8a79032012-01-09 22:31:44 +00002929 if (ExpectSemi &&
2930 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list)) {
Chris Lattner916dbf12010-02-02 00:43:15 +00002931 // Skip to end of block or statement.
Alexey Bataevee6507d2013-11-18 08:17:37 +00002932 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Chris Lattner916dbf12010-02-02 00:43:15 +00002933 // If we stopped at a ';', eat it.
Alp Toker35d87032013-12-30 23:29:50 +00002934 TryConsumeToken(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002935 return nullptr;
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002936 }
2937
Alexey Bataev05c25d62015-07-31 08:42:25 +00002938 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002939}
2940
Richard Smith9ba0fec2015-06-30 01:28:56 +00002941/// ParseCXXMemberInitializer - Parse the brace-or-equal-initializer.
2942/// Also detect and reject any attempted defaulted/deleted function definition.
2943/// The location of the '=', if any, will be placed in EqualLoc.
Richard Smith938f40b2011-06-11 17:19:42 +00002944///
Richard Smith9ba0fec2015-06-30 01:28:56 +00002945/// This does not check for a pure-specifier; that's handled elsewhere.
Sebastian Redleef474c2012-02-22 10:50:08 +00002946///
Richard Smith938f40b2011-06-11 17:19:42 +00002947/// brace-or-equal-initializer:
2948/// '=' initializer-expression
Sebastian Redleef474c2012-02-22 10:50:08 +00002949/// braced-init-list
2950///
Richard Smith938f40b2011-06-11 17:19:42 +00002951/// initializer-clause:
2952/// assignment-expression
Sebastian Redleef474c2012-02-22 10:50:08 +00002953/// braced-init-list
2954///
Richard Smithda35e962013-11-09 04:52:51 +00002955/// defaulted/deleted function-definition:
Richard Smith938f40b2011-06-11 17:19:42 +00002956/// '=' 'default'
2957/// '=' 'delete'
2958///
2959/// Prior to C++0x, the assignment-expression in an initializer-clause must
2960/// be a constant-expression.
Douglas Gregor926410d2012-02-21 02:22:07 +00002961ExprResult Parser::ParseCXXMemberInitializer(Decl *D, bool IsFunction,
Richard Smith938f40b2011-06-11 17:19:42 +00002962 SourceLocation &EqualLoc) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002963 assert(Tok.isOneOf(tok::equal, tok::l_brace)
Richard Smith938f40b2011-06-11 17:19:42 +00002964 && "Data member initializer not starting with '=' or '{'");
2965
Faisal Valid143a0c2017-04-01 21:30:49 +00002966 EnterExpressionEvaluationContext Context(
2967 Actions, Sema::ExpressionEvaluationContext::PotentiallyEvaluated, D);
Alp Toker094e5212014-01-05 03:27:11 +00002968 if (TryConsumeToken(tok::equal, EqualLoc)) {
Richard Smith938f40b2011-06-11 17:19:42 +00002969 if (Tok.is(tok::kw_delete)) {
2970 // In principle, an initializer of '= delete p;' is legal, but it will
2971 // never type-check. It's better to diagnose it as an ill-formed expression
2972 // than as an ill-formed deleted non-function member.
2973 // An initializer of '= delete p, foo' will never be parsed, because
2974 // a top-level comma always ends the initializer expression.
2975 const Token &Next = NextToken();
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002976 if (IsFunction || Next.isOneOf(tok::semi, tok::comma, tok::eof)) {
Richard Smith938f40b2011-06-11 17:19:42 +00002977 if (IsFunction)
2978 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2979 << 1 /* delete */;
2980 else
2981 Diag(ConsumeToken(), diag::err_deleted_non_function);
Richard Smithedcb26e2014-06-11 00:49:52 +00002982 return ExprError();
Richard Smith938f40b2011-06-11 17:19:42 +00002983 }
2984 } else if (Tok.is(tok::kw_default)) {
Richard Smith938f40b2011-06-11 17:19:42 +00002985 if (IsFunction)
2986 Diag(Tok, diag::err_default_delete_in_multiple_declaration)
2987 << 0 /* default */;
2988 else
Richard Smithd052a5782019-10-22 17:44:08 -07002989 Diag(ConsumeToken(), diag::err_default_special_members)
2990 << getLangOpts().CPlusPlus2a;
Richard Smithedcb26e2014-06-11 00:49:52 +00002991 return ExprError();
Richard Smith938f40b2011-06-11 17:19:42 +00002992 }
David Majnemer87ff66c2014-12-13 11:34:16 +00002993 }
2994 if (const auto *PD = dyn_cast_or_null<MSPropertyDecl>(D)) {
2995 Diag(Tok, diag::err_ms_property_initializer) << PD;
2996 return ExprError();
Sebastian Redleef474c2012-02-22 10:50:08 +00002997 }
2998 return ParseInitializer();
Richard Smith938f40b2011-06-11 17:19:42 +00002999}
3000
Richard Smith65ebb4a2015-03-26 04:09:53 +00003001void Parser::SkipCXXMemberSpecification(SourceLocation RecordLoc,
3002 SourceLocation AttrFixitLoc,
Faisal Vali090da2d2018-01-01 18:23:28 +00003003 unsigned TagType, Decl *TagDecl) {
Richard Smith65ebb4a2015-03-26 04:09:53 +00003004 // Skip the optional 'final' keyword.
3005 if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
3006 assert(isCXX11FinalKeyword() && "not a class definition");
3007 ConsumeToken();
3008
3009 // Diagnose any C++11 attributes after 'final' keyword.
3010 // We deliberately discard these attributes.
3011 ParsedAttributesWithRange Attrs(AttrFactory);
3012 CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
3013
3014 // This can only happen if we had malformed misplaced attributes;
3015 // we only get called if there is a colon or left-brace after the
3016 // attributes.
3017 if (Tok.isNot(tok::colon) && Tok.isNot(tok::l_brace))
3018 return;
3019 }
3020
3021 // Skip the base clauses. This requires actually parsing them, because
3022 // otherwise we can't be sure where they end (a left brace may appear
3023 // within a template argument).
3024 if (Tok.is(tok::colon)) {
3025 // Enter the scope of the class so that we can correctly parse its bases.
3026 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
3027 ParsingClassDefinition ParsingDef(*this, TagDecl, /*NonNestedClass*/ true,
3028 TagType == DeclSpec::TST_interface);
Richard Smith0f192e82015-06-11 22:48:25 +00003029 auto OldContext =
3030 Actions.ActOnTagStartSkippedDefinition(getCurScope(), TagDecl);
Richard Smith65ebb4a2015-03-26 04:09:53 +00003031
3032 // Parse the bases but don't attach them to the class.
3033 ParseBaseClause(nullptr);
3034
Richard Smith0f192e82015-06-11 22:48:25 +00003035 Actions.ActOnTagFinishSkippedDefinition(OldContext);
Richard Smith65ebb4a2015-03-26 04:09:53 +00003036
3037 if (!Tok.is(tok::l_brace)) {
3038 Diag(PP.getLocForEndOfToken(PrevTokLocation),
3039 diag::err_expected_lbrace_after_base_specifiers);
3040 return;
3041 }
3042 }
3043
3044 // Skip the body.
3045 assert(Tok.is(tok::l_brace));
3046 BalancedDelimiterTracker T(*this, tok::l_brace);
3047 T.consumeOpen();
3048 T.skipToEnd();
Richard Smith04c6c1f2015-07-01 18:56:50 +00003049
3050 // Parse and discard any trailing attributes.
3051 ParsedAttributes Attrs(AttrFactory);
3052 if (Tok.is(tok::kw___attribute))
3053 MaybeParseGNUAttributes(Attrs);
Richard Smith65ebb4a2015-03-26 04:09:53 +00003054}
3055
Alexey Bataev05c25d62015-07-31 08:42:25 +00003056Parser::DeclGroupPtrTy Parser::ParseCXXClassMemberDeclarationWithPragmas(
3057 AccessSpecifier &AS, ParsedAttributesWithRange &AccessAttrs,
3058 DeclSpec::TST TagType, Decl *TagDecl) {
Richard Smithbf5bcf22018-06-26 23:20:26 +00003059 ParenBraceBracketBalancer BalancerRAIIObj(*this);
3060
Richard Smithb55f7582017-01-28 01:12:10 +00003061 switch (Tok.getKind()) {
3062 case tok::kw___if_exists:
3063 case tok::kw___if_not_exists:
Erich Keanec480f302018-07-12 21:09:05 +00003064 ParseMicrosoftIfExistsClassDeclaration(TagType, AccessAttrs, AS);
David Blaikie0403cb12016-01-15 23:43:25 +00003065 return nullptr;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003066
Richard Smithb55f7582017-01-28 01:12:10 +00003067 case tok::semi:
3068 // Check for extraneous top-level semicolon.
Alexey Bataev05c25d62015-07-31 08:42:25 +00003069 ConsumeExtraSemi(InsideStruct, TagType);
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 // Handle pragmas that can appear as member declarations.
3073 case tok::annot_pragma_vis:
Alexey Bataev05c25d62015-07-31 08:42:25 +00003074 HandlePragmaVisibility();
David Blaikie0403cb12016-01-15 23:43:25 +00003075 return nullptr;
Richard Smithb55f7582017-01-28 01:12:10 +00003076 case tok::annot_pragma_pack:
Alexey Bataev05c25d62015-07-31 08:42:25 +00003077 HandlePragmaPack();
David Blaikie0403cb12016-01-15 23:43:25 +00003078 return nullptr;
Richard Smithb55f7582017-01-28 01:12:10 +00003079 case tok::annot_pragma_align:
Alexey Bataev05c25d62015-07-31 08:42:25 +00003080 HandlePragmaAlign();
David Blaikie0403cb12016-01-15 23:43:25 +00003081 return nullptr;
Richard Smithb55f7582017-01-28 01:12:10 +00003082 case tok::annot_pragma_ms_pointers_to_members:
Alexey Bataev05c25d62015-07-31 08:42:25 +00003083 HandlePragmaMSPointersToMembers();
David Blaikie0403cb12016-01-15 23:43:25 +00003084 return nullptr;
Richard Smithb55f7582017-01-28 01:12:10 +00003085 case tok::annot_pragma_ms_pragma:
Alexey Bataev05c25d62015-07-31 08:42:25 +00003086 HandlePragmaMSPragma();
David Blaikie0403cb12016-01-15 23:43:25 +00003087 return nullptr;
Richard Smithb55f7582017-01-28 01:12:10 +00003088 case tok::annot_pragma_ms_vtordisp:
Alexey Bataev3d42f342015-11-20 07:02:57 +00003089 HandlePragmaMSVtorDisp();
David Blaikie0403cb12016-01-15 23:43:25 +00003090 return nullptr;
Richard Smithb256d302017-01-28 01:20:57 +00003091 case tok::annot_pragma_dump:
3092 HandlePragmaDump();
3093 return nullptr;
Alexey Bataev3d42f342015-11-20 07:02:57 +00003094
Richard Smithb55f7582017-01-28 01:12:10 +00003095 case tok::kw_namespace:
3096 // If we see a namespace here, a close brace was missing somewhere.
Alexey Bataev05c25d62015-07-31 08:42:25 +00003097 DiagnoseUnexpectedNamespace(cast<NamedDecl>(TagDecl));
David Blaikie0403cb12016-01-15 23:43:25 +00003098 return nullptr;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003099
Anastasia Stulova948e37c2019-03-25 11:54:02 +00003100 case tok::kw_private:
3101 // FIXME: We don't accept GNU attributes on access specifiers in OpenCL mode
3102 // yet.
3103 if (getLangOpts().OpenCL && !NextToken().is(tok::colon))
3104 return ParseCXXClassMemberDeclaration(AS, AccessAttrs);
3105 LLVM_FALLTHROUGH;
Richard Smithb55f7582017-01-28 01:12:10 +00003106 case tok::kw_public:
Anastasia Stulova948e37c2019-03-25 11:54:02 +00003107 case tok::kw_protected: {
Richard Smithb55f7582017-01-28 01:12:10 +00003108 AccessSpecifier NewAS = getAccessSpecifierIfPresent();
3109 assert(NewAS != AS_none);
Alexey Bataev05c25d62015-07-31 08:42:25 +00003110 // Current token is a C++ access specifier.
3111 AS = NewAS;
3112 SourceLocation ASLoc = Tok.getLocation();
3113 unsigned TokLength = Tok.getLength();
3114 ConsumeToken();
3115 AccessAttrs.clear();
3116 MaybeParseGNUAttributes(AccessAttrs);
3117
3118 SourceLocation EndLoc;
3119 if (TryConsumeToken(tok::colon, EndLoc)) {
3120 } else if (TryConsumeToken(tok::semi, EndLoc)) {
3121 Diag(EndLoc, diag::err_expected)
3122 << tok::colon << FixItHint::CreateReplacement(EndLoc, ":");
3123 } else {
3124 EndLoc = ASLoc.getLocWithOffset(TokLength);
3125 Diag(EndLoc, diag::err_expected)
3126 << tok::colon << FixItHint::CreateInsertion(EndLoc, ":");
3127 }
3128
3129 // The Microsoft extension __interface does not permit non-public
3130 // access specifiers.
3131 if (TagType == DeclSpec::TST_interface && AS != AS_public) {
3132 Diag(ASLoc, diag::err_access_specifier_interface) << (AS == AS_protected);
3133 }
3134
Erich Keanec480f302018-07-12 21:09:05 +00003135 if (Actions.ActOnAccessSpecifier(NewAS, ASLoc, EndLoc, AccessAttrs)) {
Alexey Bataev05c25d62015-07-31 08:42:25 +00003136 // found another attribute than only annotations
3137 AccessAttrs.clear();
3138 }
3139
David Blaikie0403cb12016-01-15 23:43:25 +00003140 return nullptr;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003141 }
3142
Richard Smithb55f7582017-01-28 01:12:10 +00003143 case tok::annot_pragma_openmp:
Alexey Bataevc972f6f2020-01-07 13:39:18 -05003144 return ParseOpenMPDeclarativeDirectiveWithExtDecl(
3145 AS, AccessAttrs, /*Delayed=*/true, TagType, TagDecl);
Alexey Bataev05c25d62015-07-31 08:42:25 +00003146
Richard Smithb55f7582017-01-28 01:12:10 +00003147 default:
Serge Pavlov037861b2019-08-04 10:08:51 +00003148 if (tok::isPragmaAnnotation(Tok.getKind())) {
3149 Diag(Tok.getLocation(), diag::err_pragma_misplaced_in_decl)
3150 << DeclSpec::getSpecifierName(TagType,
3151 Actions.getASTContext().getPrintingPolicy());
3152 ConsumeAnnotationToken();
3153 return nullptr;
3154 }
Erich Keanec480f302018-07-12 21:09:05 +00003155 return ParseCXXClassMemberDeclaration(AS, AccessAttrs);
Richard Smithb55f7582017-01-28 01:12:10 +00003156 }
Alexey Bataev05c25d62015-07-31 08:42:25 +00003157}
3158
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003159/// ParseCXXMemberSpecification - Parse the class definition.
3160///
3161/// member-specification:
3162/// member-declaration member-specification[opt]
3163/// access-specifier ':' member-specification[opt]
3164///
Joao Matose9a3ed42012-08-31 22:18:20 +00003165void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc,
Michael Han309af292013-01-07 16:57:11 +00003166 SourceLocation AttrFixitLoc,
Richard Smith4c96e992013-02-19 23:47:15 +00003167 ParsedAttributesWithRange &Attrs,
Faisal Vali090da2d2018-01-01 18:23:28 +00003168 unsigned TagType, Decl *TagDecl) {
Joao Matose9a3ed42012-08-31 22:18:20 +00003169 assert((TagType == DeclSpec::TST_struct ||
Faisal Vali090da2d2018-01-01 18:23:28 +00003170 TagType == DeclSpec::TST_interface ||
3171 TagType == DeclSpec::TST_union ||
3172 TagType == DeclSpec::TST_class) && "Invalid TagType!");
Joao Matose9a3ed42012-08-31 22:18:20 +00003173
Anton Afanasyevd880de22019-03-30 08:42:48 +00003174 llvm::TimeTraceScope TimeScope("ParseClass", [&]() {
3175 if (auto *TD = dyn_cast_or_null<NamedDecl>(TagDecl))
3176 return TD->getQualifiedNameAsString();
3177 return std::string("<anonymous>");
3178 });
3179
Jordan Rose1e879d82018-03-23 00:07:18 +00003180 PrettyDeclStackTraceEntry CrashInfo(Actions.Context, TagDecl, RecordLoc,
John McCallfaf5fb42010-08-26 23:41:50 +00003181 "parsing struct/union/class body");
Mike Stump11289f42009-09-09 15:08:12 +00003182
Douglas Gregoredf8f392010-01-16 20:52:59 +00003183 // Determine whether this is a non-nested class. Note that local
3184 // classes are *not* considered to be nested classes.
3185 bool NonNestedClass = true;
3186 if (!ClassStack.empty()) {
Douglas Gregor0be31a22010-07-02 17:43:08 +00003187 for (const Scope *S = getCurScope(); S; S = S->getParent()) {
Douglas Gregoredf8f392010-01-16 20:52:59 +00003188 if (S->isClassScope()) {
3189 // We're inside a class scope, so this is a nested class.
3190 NonNestedClass = false;
John McCalldb632ac2012-09-25 07:32:39 +00003191
3192 // The Microsoft extension __interface does not permit nested classes.
3193 if (getCurrentClass().IsInterface) {
3194 Diag(RecordLoc, diag::err_invalid_member_in_interface)
3195 << /*ErrorType=*/6
3196 << (isa<NamedDecl>(TagDecl)
3197 ? cast<NamedDecl>(TagDecl)->getQualifiedNameAsString()
David Blaikieabe1a392014-04-02 05:58:29 +00003198 : "(anonymous)");
John McCalldb632ac2012-09-25 07:32:39 +00003199 }
Douglas Gregoredf8f392010-01-16 20:52:59 +00003200 break;
3201 }
3202
Serge Pavlovd9c0bcf2015-07-14 10:02:10 +00003203 if ((S->getFlags() & Scope::FnScope))
3204 // If we're in a function or function template then this is a local
3205 // class rather than a nested class.
3206 break;
Douglas Gregoredf8f392010-01-16 20:52:59 +00003207 }
3208 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003209
3210 // Enter a scope for the class.
Douglas Gregor658b9552009-01-09 22:42:13 +00003211 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003212
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003213 // Note that we are parsing a new (potentially-nested) class definition.
John McCalldb632ac2012-09-25 07:32:39 +00003214 ParsingClassDefinition ParsingDef(*this, TagDecl, NonNestedClass,
3215 TagType == DeclSpec::TST_interface);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003216
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003217 if (TagDecl)
Douglas Gregor0be31a22010-07-02 17:43:08 +00003218 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
John McCall2d814c32009-12-19 21:48:58 +00003219
Anders Carlssonf9eb63b2011-03-25 14:46:08 +00003220 SourceLocation FinalLoc;
David Majnemera5433082013-10-18 00:33:31 +00003221 bool IsFinalSpelledSealed = false;
Anders Carlssonf9eb63b2011-03-25 14:46:08 +00003222
3223 // Parse the optional 'final' keyword.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003224 if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
David Majnemera5433082013-10-18 00:33:31 +00003225 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier(Tok);
3226 assert((Specifier == VirtSpecifiers::VS_Final ||
Fangrui Song6907ce22018-07-30 19:24:48 +00003227 Specifier == VirtSpecifiers::VS_GNU_Final ||
David Majnemera5433082013-10-18 00:33:31 +00003228 Specifier == VirtSpecifiers::VS_Sealed) &&
3229 "not a class definition");
Richard Smithda261112011-10-15 04:21:46 +00003230 FinalLoc = ConsumeToken();
David Majnemera5433082013-10-18 00:33:31 +00003231 IsFinalSpelledSealed = Specifier == VirtSpecifiers::VS_Sealed;
Anders Carlssonf9eb63b2011-03-25 14:46:08 +00003232
David Majnemera5433082013-10-18 00:33:31 +00003233 if (TagType == DeclSpec::TST_interface)
John McCalldb632ac2012-09-25 07:32:39 +00003234 Diag(FinalLoc, diag::err_override_control_interface)
David Majnemera5433082013-10-18 00:33:31 +00003235 << VirtSpecifiers::getSpecifierName(Specifier);
3236 else if (Specifier == VirtSpecifiers::VS_Final)
3237 Diag(FinalLoc, getLangOpts().CPlusPlus11
3238 ? diag::warn_cxx98_compat_override_control_keyword
3239 : diag::ext_override_control_keyword)
3240 << VirtSpecifiers::getSpecifierName(Specifier);
3241 else if (Specifier == VirtSpecifiers::VS_Sealed)
3242 Diag(FinalLoc, diag::ext_ms_sealed_keyword);
Andrey Bokhanko276055b2016-07-29 10:42:48 +00003243 else if (Specifier == VirtSpecifiers::VS_GNU_Final)
3244 Diag(FinalLoc, diag::ext_warn_gnu_final);
Michael Han9407e502012-11-26 22:54:45 +00003245
Michael Han309af292013-01-07 16:57:11 +00003246 // Parse any C++11 attributes after 'final' keyword.
3247 // These attributes are not allowed to appear here,
3248 // and the only possible place for them to appertain
3249 // to the class would be between class-key and class-name.
Richard Smith4c96e992013-02-19 23:47:15 +00003250 CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
Nico Weber4b4be842014-12-29 06:56:50 +00003251
3252 // ParseClassSpecifier() does only a superficial check for attributes before
3253 // deciding to call this method. For example, for
3254 // `class C final alignas ([l) {` it will decide that this looks like a
3255 // misplaced attribute since it sees `alignas '(' ')'`. But the actual
3256 // attribute parsing code will try to parse the '[' as a constexpr lambda
3257 // and consume enough tokens that the alignas parsing code will eat the
3258 // opening '{'. So bail out if the next token isn't one we expect.
Nico Weber36de3a22014-12-29 21:56:22 +00003259 if (!Tok.is(tok::colon) && !Tok.is(tok::l_brace)) {
3260 if (TagDecl)
3261 Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
Nico Weber4b4be842014-12-29 06:56:50 +00003262 return;
Nico Weber36de3a22014-12-29 21:56:22 +00003263 }
Anders Carlssonf9eb63b2011-03-25 14:46:08 +00003264 }
Anders Carlsson4b63d0e2011-01-22 16:56:46 +00003265
John McCall2d814c32009-12-19 21:48:58 +00003266 if (Tok.is(tok::colon)) {
Erik Verbruggen6524c052017-10-24 13:46:58 +00003267 ParseScope InheritanceScope(this, getCurScope()->getFlags() |
3268 Scope::ClassInheritanceScope);
3269
John McCall2d814c32009-12-19 21:48:58 +00003270 ParseBaseClause(TagDecl);
John McCall2d814c32009-12-19 21:48:58 +00003271 if (!Tok.is(tok::l_brace)) {
Ismail Pazarbasi129c44c2014-09-25 21:13:02 +00003272 bool SuggestFixIt = false;
3273 SourceLocation BraceLoc = PP.getLocForEndOfToken(PrevTokLocation);
3274 if (Tok.isAtStartOfLine()) {
3275 switch (Tok.getKind()) {
3276 case tok::kw_private:
3277 case tok::kw_protected:
3278 case tok::kw_public:
3279 SuggestFixIt = NextToken().getKind() == tok::colon;
3280 break;
3281 case tok::kw_static_assert:
3282 case tok::r_brace:
3283 case tok::kw_using:
3284 // base-clause can have simple-template-id; 'template' can't be there
3285 case tok::kw_template:
3286 SuggestFixIt = true;
3287 break;
3288 case tok::identifier:
3289 SuggestFixIt = isConstructorDeclarator(true);
3290 break;
3291 default:
3292 SuggestFixIt = isCXXSimpleDeclaration(/*AllowForRangeDecl=*/false);
3293 break;
3294 }
3295 }
3296 DiagnosticBuilder LBraceDiag =
3297 Diag(BraceLoc, diag::err_expected_lbrace_after_base_specifiers);
3298 if (SuggestFixIt) {
3299 LBraceDiag << FixItHint::CreateInsertion(BraceLoc, " {");
3300 // Try recovering from missing { after base-clause.
Ilya Biryukov929af672019-05-17 09:32:05 +00003301 PP.EnterToken(Tok, /*IsReinject*/true);
Ismail Pazarbasi129c44c2014-09-25 21:13:02 +00003302 Tok.setKind(tok::l_brace);
3303 } else {
3304 if (TagDecl)
3305 Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
3306 return;
3307 }
John McCall2d814c32009-12-19 21:48:58 +00003308 }
3309 }
3310
3311 assert(Tok.is(tok::l_brace));
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003312 BalancedDelimiterTracker T(*this, tok::l_brace);
3313 T.consumeOpen();
John McCall2d814c32009-12-19 21:48:58 +00003314
John McCall08bede42010-05-28 08:11:17 +00003315 if (TagDecl)
Anders Carlsson30f29442011-03-25 14:31:08 +00003316 Actions.ActOnStartCXXMemberDeclarations(getCurScope(), TagDecl, FinalLoc,
David Majnemera5433082013-10-18 00:33:31 +00003317 IsFinalSpelledSealed,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003318 T.getOpenLocation());
John McCall1c7e6ec2009-12-20 07:58:13 +00003319
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003320 // C++ 11p3: Members of a class defined with the keyword class are private
3321 // by default. Members of a class defined with the keywords struct or union
3322 // are public by default.
3323 AccessSpecifier CurAS;
3324 if (TagType == DeclSpec::TST_class)
3325 CurAS = AS_private;
3326 else
3327 CurAS = AS_public;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003328 ParsedAttributesWithRange AccessAttrs(AttrFactory);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003329
Douglas Gregor9377c822010-06-21 22:31:09 +00003330 if (TagDecl) {
3331 // While we still have something to read, read the member-declarations.
Richard Smith752ada82015-11-17 23:32:01 +00003332 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
3333 Tok.isNot(tok::eof)) {
Douglas Gregor9377c822010-06-21 22:31:09 +00003334 // Each iteration of this loop reads one member-declaration.
Alexey Bataev05c25d62015-07-31 08:42:25 +00003335 ParseCXXClassMemberDeclarationWithPragmas(
3336 CurAS, AccessAttrs, static_cast<DeclSpec::TST>(TagType), TagDecl);
Serge Pavlovc4e04a22015-09-19 05:32:57 +00003337 }
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003338 T.consumeClose();
Douglas Gregor9377c822010-06-21 22:31:09 +00003339 } else {
Alexey Bataevee6507d2013-11-18 08:17:37 +00003340 SkipUntil(tok::r_brace);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003341 }
Mike Stump11289f42009-09-09 15:08:12 +00003342
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003343 // If attributes exist after class contents, parse them.
John McCall084e83d2011-03-24 11:26:52 +00003344 ParsedAttributes attrs(AttrFactory);
John McCall53fa7142010-12-24 02:08:15 +00003345 MaybeParseGNUAttributes(attrs);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003346
John McCall08bede42010-05-28 08:11:17 +00003347 if (TagDecl)
Douglas Gregor0be31a22010-07-02 17:43:08 +00003348 Actions.ActOnFinishCXXMemberSpecification(getCurScope(), RecordLoc, TagDecl,
Erich Keanec480f302018-07-12 21:09:05 +00003349 T.getOpenLocation(),
3350 T.getCloseLocation(), attrs);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003351
Douglas Gregor433e0532012-04-16 18:27:27 +00003352 // C++11 [class.mem]p2:
3353 // Within the class member-specification, the class is regarded as complete
Richard Smith0b3a4622014-11-13 20:01:57 +00003354 // within function bodies, default arguments, exception-specifications, and
Douglas Gregor433e0532012-04-16 18:27:27 +00003355 // brace-or-equal-initializers for non-static data members (including such
3356 // things in nested classes).
Douglas Gregor9377c822010-06-21 22:31:09 +00003357 if (TagDecl && NonNestedClass) {
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003358 // We are not inside a nested class. This class and its nested classes
Douglas Gregor4d87df52008-12-16 21:30:33 +00003359 // are complete and we can parse the delayed portions of method
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00003360 // declarations and the lexed inline method definitions, along with any
3361 // delayed attributes.
Douglas Gregor428119e2010-06-16 23:45:56 +00003362 SourceLocation SavedPrevTokLocation = PrevTokLocation;
Alexey Bataevc972f6f2020-01-07 13:39:18 -05003363 ParseLexedPragmas(getCurrentClass());
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00003364 ParseLexedAttributes(getCurrentClass());
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003365 ParseLexedMethodDeclarations(getCurrentClass());
Richard Smith84973e52012-04-21 18:42:51 +00003366
3367 // We've finished with all pending member declarations.
3368 Actions.ActOnFinishCXXMemberDecls();
3369
Richard Smith938f40b2011-06-11 17:19:42 +00003370 ParseLexedMemberInitializers(getCurrentClass());
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003371 ParseLexedMethodDefs(getCurrentClass());
Douglas Gregor428119e2010-06-16 23:45:56 +00003372 PrevTokLocation = SavedPrevTokLocation;
Reid Klecknerbba3cb92015-03-17 19:00:50 +00003373
3374 // We've finished parsing everything, including default argument
3375 // initializers.
Hans Wennborg92ce2af2019-12-02 16:25:23 +01003376 Actions.ActOnFinishCXXNonNestedClass();
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003377 }
3378
John McCall08bede42010-05-28 08:11:17 +00003379 if (TagDecl)
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00003380 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getRange());
John McCall2ff380a2010-03-17 00:38:33 +00003381
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003382 // Leave the class scope.
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003383 ParsingDef.Pop();
Douglas Gregor7307d6c2008-12-10 06:34:36 +00003384 ClassScope.Exit();
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003385}
Douglas Gregore8381c02008-11-05 04:29:56 +00003386
Richard Smith2ac43ad2013-11-15 23:00:02 +00003387void Parser::DiagnoseUnexpectedNamespace(NamedDecl *D) {
Richard Smithda35e962013-11-09 04:52:51 +00003388 assert(Tok.is(tok::kw_namespace));
3389
3390 // FIXME: Suggest where the close brace should have gone by looking
3391 // at indentation changes within the definition body.
Richard Smith2ac43ad2013-11-15 23:00:02 +00003392 Diag(D->getLocation(),
3393 diag::err_missing_end_of_definition) << D;
Richard Smithda35e962013-11-09 04:52:51 +00003394 Diag(Tok.getLocation(),
Richard Smith2ac43ad2013-11-15 23:00:02 +00003395 diag::note_missing_end_of_definition_before) << D;
Richard Smithda35e962013-11-09 04:52:51 +00003396
3397 // Push '};' onto the token stream to recover.
Ilya Biryukov929af672019-05-17 09:32:05 +00003398 PP.EnterToken(Tok, /*IsReinject*/ true);
Richard Smithda35e962013-11-09 04:52:51 +00003399
3400 Tok.startToken();
3401 Tok.setLocation(PP.getLocForEndOfToken(PrevTokLocation));
3402 Tok.setKind(tok::semi);
Ilya Biryukov929af672019-05-17 09:32:05 +00003403 PP.EnterToken(Tok, /*IsReinject*/ true);
Richard Smithda35e962013-11-09 04:52:51 +00003404
3405 Tok.setKind(tok::r_brace);
3406}
3407
Douglas Gregore8381c02008-11-05 04:29:56 +00003408/// ParseConstructorInitializer - Parse a C++ constructor initializer,
3409/// which explicitly initializes the members or base classes of a
3410/// class (C++ [class.base.init]). For example, the three initializers
3411/// after the ':' in the Derived constructor below:
3412///
3413/// @code
3414/// class Base { };
3415/// class Derived : Base {
3416/// int x;
3417/// float f;
3418/// public:
3419/// Derived(float f) : Base(), x(17), f(f) { }
3420/// };
3421/// @endcode
3422///
Mike Stump11289f42009-09-09 15:08:12 +00003423/// [C++] ctor-initializer:
3424/// ':' mem-initializer-list
Douglas Gregore8381c02008-11-05 04:29:56 +00003425///
Mike Stump11289f42009-09-09 15:08:12 +00003426/// [C++] mem-initializer-list:
Douglas Gregor44e7df62011-01-04 00:32:56 +00003427/// mem-initializer ...[opt]
3428/// mem-initializer ...[opt] , mem-initializer-list
John McCall48871652010-08-21 09:40:31 +00003429void Parser::ParseConstructorInitializer(Decl *ConstructorDecl) {
Nico Weber3b00fdc2015-03-07 19:52:39 +00003430 assert(Tok.is(tok::colon) &&
3431 "Constructor initializer always starts with ':'");
Douglas Gregore8381c02008-11-05 04:29:56 +00003432
Nico Weber3b00fdc2015-03-07 19:52:39 +00003433 // Poison the SEH identifiers so they are flagged as illegal in constructor
3434 // initializers.
John Wiegley1c0675e2011-04-28 01:08:34 +00003435 PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
Douglas Gregore8381c02008-11-05 04:29:56 +00003436 SourceLocation ColonLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +00003437
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003438 SmallVector<CXXCtorInitializer*, 4> MemInitializers;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003439 bool AnyErrors = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003440
Douglas Gregore8381c02008-11-05 04:29:56 +00003441 do {
Douglas Gregoreaeeca92010-08-28 00:00:50 +00003442 if (Tok.is(tok::code_completion)) {
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00003443 Actions.CodeCompleteConstructorInitializer(ConstructorDecl,
3444 MemInitializers);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00003445 return cutOffParsing();
Douglas Gregoreaeeca92010-08-28 00:00:50 +00003446 }
Alexey Bataev79de17d2016-01-20 05:25:51 +00003447
3448 MemInitResult MemInit = ParseMemInitializer(ConstructorDecl);
3449 if (!MemInit.isInvalid())
3450 MemInitializers.push_back(MemInit.get());
3451 else
3452 AnyErrors = true;
3453
Douglas Gregore8381c02008-11-05 04:29:56 +00003454 if (Tok.is(tok::comma))
3455 ConsumeToken();
3456 else if (Tok.is(tok::l_brace))
3457 break;
Alexey Bataev79de17d2016-01-20 05:25:51 +00003458 // If the previous initializer was valid and the next token looks like a
3459 // base or member initializer, assume that we're just missing a comma.
3460 else if (!MemInit.isInvalid() &&
3461 Tok.isOneOf(tok::identifier, tok::coloncolon)) {
Douglas Gregorce66d022010-09-07 14:51:08 +00003462 SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation);
3463 Diag(Loc, diag::err_ctor_init_missing_comma)
3464 << FixItHint::CreateInsertion(Loc, ", ");
3465 } else {
Douglas Gregore8381c02008-11-05 04:29:56 +00003466 // Skip over garbage, until we get to '{'. Don't eat the '{'.
Alexey Bataev79de17d2016-01-20 05:25:51 +00003467 if (!MemInit.isInvalid())
3468 Diag(Tok.getLocation(), diag::err_expected_either) << tok::l_brace
3469 << tok::comma;
Alexey Bataevee6507d2013-11-18 08:17:37 +00003470 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
Douglas Gregore8381c02008-11-05 04:29:56 +00003471 break;
3472 }
3473 } while (true);
3474
David Blaikie3fc2f912013-01-17 05:26:25 +00003475 Actions.ActOnMemInitializers(ConstructorDecl, ColonLoc, MemInitializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003476 AnyErrors);
Douglas Gregore8381c02008-11-05 04:29:56 +00003477}
3478
3479/// ParseMemInitializer - Parse a C++ member initializer, which is
3480/// part of a constructor initializer that explicitly initializes one
3481/// member or base class (C++ [class.base.init]). See
3482/// ParseConstructorInitializer for an example.
3483///
3484/// [C++] mem-initializer:
3485/// mem-initializer-id '(' expression-list[opt] ')'
Sebastian Redl3da34892011-06-05 12:23:16 +00003486/// [C++0x] mem-initializer-id braced-init-list
Mike Stump11289f42009-09-09 15:08:12 +00003487///
Douglas Gregore8381c02008-11-05 04:29:56 +00003488/// [C++] mem-initializer-id:
3489/// '::'[opt] nested-name-specifier[opt] class-name
3490/// identifier
Craig Topper9ad7e262014-10-31 06:57:07 +00003491MemInitResult Parser::ParseMemInitializer(Decl *ConstructorDecl) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00003492 // parse '::'[opt] nested-name-specifier[opt]
3493 CXXScopeSpec SS;
Richard Smithb23c5e82019-05-09 03:31:27 +00003494 if (ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false))
3495 return true;
Richard Smithaf3b3252017-05-18 19:21:48 +00003496
3497 // : identifier
3498 IdentifierInfo *II = nullptr;
3499 SourceLocation IdLoc = Tok.getLocation();
3500 // : declype(...)
3501 DeclSpec DS(AttrFactory);
3502 // : template_name<...>
John McCallba7bf592010-08-24 05:47:05 +00003503 ParsedType TemplateTypeTy;
Richard Smithaf3b3252017-05-18 19:21:48 +00003504
3505 if (Tok.is(tok::identifier)) {
3506 // Get the identifier. This may be a member name or a class name,
3507 // but we'll let the semantic analysis determine which it is.
3508 II = Tok.getIdentifierInfo();
3509 ConsumeToken();
3510 } else if (Tok.is(tok::annot_decltype)) {
3511 // Get the decltype expression, if there is one.
3512 // Uses of decltype will already have been converted to annot_decltype by
3513 // ParseOptionalCXXScopeSpecifier at this point.
3514 // FIXME: Can we get here with a scope specifier?
3515 ParseDecltypeSpecifier(DS);
3516 } else {
3517 TemplateIdAnnotation *TemplateId = Tok.is(tok::annot_template_id)
3518 ? takeTemplateIdAnnotation(Tok)
3519 : nullptr;
3520 if (TemplateId && (TemplateId->Kind == TNK_Type_template ||
Richard Smithb23c5e82019-05-09 03:31:27 +00003521 TemplateId->Kind == TNK_Dependent_template_name ||
3522 TemplateId->Kind == TNK_Undeclared_template)) {
Richard Smitha42fd842020-01-17 15:42:11 -08003523 AnnotateTemplateIdTokenAsType(SS, /*IsClassName*/true);
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00003524 assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
John McCallba7bf592010-08-24 05:47:05 +00003525 TemplateTypeTy = getTypeAnnotation(Tok);
Richard Smithaf3b3252017-05-18 19:21:48 +00003526 ConsumeAnnotationToken();
Richard Smithb23c5e82019-05-09 03:31:27 +00003527 if (!TemplateTypeTy)
3528 return true;
Richard Smithaf3b3252017-05-18 19:21:48 +00003529 } else {
3530 Diag(Tok, diag::err_expected_member_or_base_name);
3531 return true;
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00003532 }
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00003533 }
Douglas Gregore8381c02008-11-05 04:29:56 +00003534
3535 // Parse the '('.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003536 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
Richard Smith5d164bc2011-10-15 05:09:34 +00003537 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
3538
Kadir Cetinkaya84774c32018-09-11 15:02:18 +00003539 // FIXME: Add support for signature help inside initializer lists.
Sebastian Redla74948d2011-09-24 17:48:25 +00003540 ExprResult InitList = ParseBraceInitializer();
3541 if (InitList.isInvalid())
3542 return true;
3543
3544 SourceLocation EllipsisLoc;
Alp Toker094e5212014-01-05 03:27:11 +00003545 TryConsumeToken(tok::ellipsis, EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00003546
3547 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
Fangrui Song6907ce22018-07-30 19:24:48 +00003548 TemplateTypeTy, DS, IdLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003549 InitList.get(), EllipsisLoc);
Sebastian Redl3da34892011-06-05 12:23:16 +00003550 } else if(Tok.is(tok::l_paren)) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003551 BalancedDelimiterTracker T(*this, tok::l_paren);
3552 T.consumeOpen();
Douglas Gregore8381c02008-11-05 04:29:56 +00003553
Sebastian Redl3da34892011-06-05 12:23:16 +00003554 // Parse the optional expression-list.
Benjamin Kramerf0623432012-08-23 22:51:59 +00003555 ExprVector ArgExprs;
Sebastian Redl3da34892011-06-05 12:23:16 +00003556 CommaLocsTy CommaLocs;
Ilya Biryukovff2a9972019-02-26 11:01:50 +00003557 auto RunSignatureHelp = [&] {
3558 QualType PreferredType = Actions.ProduceCtorInitMemberSignatureHelp(
3559 getCurScope(), ConstructorDecl, SS, TemplateTypeTy, ArgExprs, II,
3560 T.getOpenLocation());
3561 CalledSignatureHelp = true;
3562 return PreferredType;
3563 };
Kadir Cetinkaya84774c32018-09-11 15:02:18 +00003564 if (Tok.isNot(tok::r_paren) &&
3565 ParseExpressionList(ArgExprs, CommaLocs, [&] {
Ilya Biryukovff2a9972019-02-26 11:01:50 +00003566 PreferredType.enterFunctionArgument(Tok.getLocation(),
3567 RunSignatureHelp);
Kadir Cetinkaya84774c32018-09-11 15:02:18 +00003568 })) {
Ilya Biryukovff2a9972019-02-26 11:01:50 +00003569 if (PP.isCodeCompletionReached() && !CalledSignatureHelp)
3570 RunSignatureHelp();
Alexey Bataevee6507d2013-11-18 08:17:37 +00003571 SkipUntil(tok::r_paren, StopAtSemi);
Sebastian Redl3da34892011-06-05 12:23:16 +00003572 return true;
3573 }
3574
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003575 T.consumeClose();
Sebastian Redl3da34892011-06-05 12:23:16 +00003576
3577 SourceLocation EllipsisLoc;
Alp Toker97650562014-01-10 11:19:30 +00003578 TryConsumeToken(tok::ellipsis, EllipsisLoc);
Sebastian Redl3da34892011-06-05 12:23:16 +00003579
3580 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
David Blaikie186a8892012-01-24 06:03:59 +00003581 TemplateTypeTy, DS, IdLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00003582 T.getOpenLocation(), ArgExprs,
3583 T.getCloseLocation(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00003584 }
3585
Alp Tokerec543272013-12-24 09:48:30 +00003586 if (getLangOpts().CPlusPlus11)
3587 return Diag(Tok, diag::err_expected_either) << tok::l_paren << tok::l_brace;
3588 else
3589 return Diag(Tok, diag::err_expected) << tok::l_paren;
Douglas Gregore8381c02008-11-05 04:29:56 +00003590}
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003591
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003592/// Parse a C++ exception-specification if present (C++0x [except.spec]).
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003593///
Douglas Gregor356513d2008-12-01 18:00:20 +00003594/// exception-specification:
Sebastian Redl965b0e32011-03-05 14:45:16 +00003595/// dynamic-exception-specification
3596/// noexcept-specification
3597///
3598/// noexcept-specification:
3599/// 'noexcept'
3600/// 'noexcept' '(' constant-expression ')'
3601ExceptionSpecificationType
Richard Smith0b3a4622014-11-13 20:01:57 +00003602Parser::tryParseExceptionSpecification(bool Delayed,
Douglas Gregor433e0532012-04-16 18:27:27 +00003603 SourceRange &SpecificationRange,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003604 SmallVectorImpl<ParsedType> &DynamicExceptions,
3605 SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
Richard Smith0b3a4622014-11-13 20:01:57 +00003606 ExprResult &NoexceptExpr,
3607 CachedTokens *&ExceptionSpecTokens) {
Sebastian Redl965b0e32011-03-05 14:45:16 +00003608 ExceptionSpecificationType Result = EST_None;
Hans Wennborgdcfba332015-10-06 23:40:43 +00003609 ExceptionSpecTokens = nullptr;
Fangrui Song6907ce22018-07-30 19:24:48 +00003610
Richard Smith0b3a4622014-11-13 20:01:57 +00003611 // Handle delayed parsing of exception-specifications.
3612 if (Delayed) {
3613 if (Tok.isNot(tok::kw_throw) && Tok.isNot(tok::kw_noexcept))
3614 return EST_None;
Sebastian Redl965b0e32011-03-05 14:45:16 +00003615
Richard Smith0b3a4622014-11-13 20:01:57 +00003616 // Consume and cache the starting token.
3617 bool IsNoexcept = Tok.is(tok::kw_noexcept);
3618 Token StartTok = Tok;
3619 SpecificationRange = SourceRange(ConsumeToken());
3620
3621 // Check for a '('.
3622 if (!Tok.is(tok::l_paren)) {
3623 // If this is a bare 'noexcept', we're done.
3624 if (IsNoexcept) {
3625 Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
Hans Wennborgdcfba332015-10-06 23:40:43 +00003626 NoexceptExpr = nullptr;
Richard Smith0b3a4622014-11-13 20:01:57 +00003627 return EST_BasicNoexcept;
3628 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003629
Richard Smith0b3a4622014-11-13 20:01:57 +00003630 Diag(Tok, diag::err_expected_lparen_after) << "throw";
3631 return EST_DynamicNone;
3632 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003633
Richard Smith0b3a4622014-11-13 20:01:57 +00003634 // Cache the tokens for the exception-specification.
3635 ExceptionSpecTokens = new CachedTokens;
3636 ExceptionSpecTokens->push_back(StartTok); // 'throw' or 'noexcept'
3637 ExceptionSpecTokens->push_back(Tok); // '('
3638 SpecificationRange.setEnd(ConsumeParen()); // '('
Richard Smithb1c217e2015-01-13 02:24:58 +00003639
3640 ConsumeAndStoreUntil(tok::r_paren, *ExceptionSpecTokens,
3641 /*StopAtSemi=*/true,
3642 /*ConsumeFinalToken=*/true);
Aaron Ballman580ccaf2016-01-12 21:04:22 +00003643 SpecificationRange.setEnd(ExceptionSpecTokens->back().getLocation());
3644
Richard Smith0b3a4622014-11-13 20:01:57 +00003645 return EST_Unparsed;
3646 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003647
Sebastian Redl965b0e32011-03-05 14:45:16 +00003648 // See if there's a dynamic specification.
3649 if (Tok.is(tok::kw_throw)) {
3650 Result = ParseDynamicExceptionSpecification(SpecificationRange,
3651 DynamicExceptions,
3652 DynamicExceptionRanges);
3653 assert(DynamicExceptions.size() == DynamicExceptionRanges.size() &&
3654 "Produced different number of exception types and ranges.");
3655 }
3656
3657 // If there's no noexcept specification, we're done.
3658 if (Tok.isNot(tok::kw_noexcept))
3659 return Result;
3660
Richard Smithb15c11c2011-10-17 23:06:20 +00003661 Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
3662
Sebastian Redl965b0e32011-03-05 14:45:16 +00003663 // If we already had a dynamic specification, parse the noexcept for,
3664 // recovery, but emit a diagnostic and don't store the results.
3665 SourceRange NoexceptRange;
3666 ExceptionSpecificationType NoexceptType = EST_None;
3667
3668 SourceLocation KeywordLoc = ConsumeToken();
3669 if (Tok.is(tok::l_paren)) {
3670 // There is an argument.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003671 BalancedDelimiterTracker T(*this, tok::l_paren);
3672 T.consumeOpen();
Sebastian Redl965b0e32011-03-05 14:45:16 +00003673 NoexceptExpr = ParseConstantExpression();
Serge Pavlov3739f5e72015-06-29 17:50:19 +00003674 T.consumeClose();
Serge Pavlov3739f5e72015-06-29 17:50:19 +00003675 if (!NoexceptExpr.isInvalid()) {
Richard Smitheaf11ad2018-05-03 03:58:32 +00003676 NoexceptExpr = Actions.ActOnNoexceptSpec(KeywordLoc, NoexceptExpr.get(),
3677 NoexceptType);
Serge Pavlov3739f5e72015-06-29 17:50:19 +00003678 NoexceptRange = SourceRange(KeywordLoc, T.getCloseLocation());
3679 } else {
Malcolm Parsonsa3220ce2017-01-12 16:11:28 +00003680 NoexceptType = EST_BasicNoexcept;
Serge Pavlov3739f5e72015-06-29 17:50:19 +00003681 }
Sebastian Redl965b0e32011-03-05 14:45:16 +00003682 } else {
3683 // There is no argument.
3684 NoexceptType = EST_BasicNoexcept;
3685 NoexceptRange = SourceRange(KeywordLoc, KeywordLoc);
3686 }
3687
3688 if (Result == EST_None) {
3689 SpecificationRange = NoexceptRange;
3690 Result = NoexceptType;
3691
3692 // If there's a dynamic specification after a noexcept specification,
3693 // parse that and ignore the results.
3694 if (Tok.is(tok::kw_throw)) {
3695 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
3696 ParseDynamicExceptionSpecification(NoexceptRange, DynamicExceptions,
3697 DynamicExceptionRanges);
3698 }
3699 } else {
3700 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
3701 }
3702
3703 return Result;
3704}
3705
Richard Smith8ca78a12013-06-13 02:02:51 +00003706static void diagnoseDynamicExceptionSpecification(
Craig Toppere335f252015-10-04 04:53:55 +00003707 Parser &P, SourceRange Range, bool IsNoexcept) {
Richard Smith8ca78a12013-06-13 02:02:51 +00003708 if (P.getLangOpts().CPlusPlus11) {
3709 const char *Replacement = IsNoexcept ? "noexcept" : "noexcept(false)";
Richard Smith82da19d2016-12-08 02:49:07 +00003710 P.Diag(Range.getBegin(),
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003711 P.getLangOpts().CPlusPlus17 && !IsNoexcept
Richard Smith82da19d2016-12-08 02:49:07 +00003712 ? diag::ext_dynamic_exception_spec
3713 : diag::warn_exception_spec_deprecated)
3714 << Range;
Richard Smith8ca78a12013-06-13 02:02:51 +00003715 P.Diag(Range.getBegin(), diag::note_exception_spec_deprecated)
3716 << Replacement << FixItHint::CreateReplacement(Range, Replacement);
3717 }
3718}
3719
Sebastian Redl965b0e32011-03-05 14:45:16 +00003720/// ParseDynamicExceptionSpecification - Parse a C++
3721/// dynamic-exception-specification (C++ [except.spec]).
3722///
3723/// dynamic-exception-specification:
Douglas Gregor356513d2008-12-01 18:00:20 +00003724/// 'throw' '(' type-id-list [opt] ')'
3725/// [MS] 'throw' '(' '...' ')'
Mike Stump11289f42009-09-09 15:08:12 +00003726///
Douglas Gregor356513d2008-12-01 18:00:20 +00003727/// type-id-list:
Douglas Gregor830837d2010-12-20 23:57:46 +00003728/// type-id ... [opt]
3729/// type-id-list ',' type-id ... [opt]
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003730///
Sebastian Redl965b0e32011-03-05 14:45:16 +00003731ExceptionSpecificationType Parser::ParseDynamicExceptionSpecification(
3732 SourceRange &SpecificationRange,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003733 SmallVectorImpl<ParsedType> &Exceptions,
3734 SmallVectorImpl<SourceRange> &Ranges) {
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003735 assert(Tok.is(tok::kw_throw) && "expected throw");
Mike Stump11289f42009-09-09 15:08:12 +00003736
Sebastian Redl965b0e32011-03-05 14:45:16 +00003737 SpecificationRange.setBegin(ConsumeToken());
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003738 BalancedDelimiterTracker T(*this, tok::l_paren);
3739 if (T.consumeOpen()) {
Sebastian Redl965b0e32011-03-05 14:45:16 +00003740 Diag(Tok, diag::err_expected_lparen_after) << "throw";
3741 SpecificationRange.setEnd(SpecificationRange.getBegin());
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003742 return EST_DynamicNone;
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003743 }
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003744
Douglas Gregor356513d2008-12-01 18:00:20 +00003745 // Parse throw(...), a Microsoft extension that means "this function
3746 // can throw anything".
3747 if (Tok.is(tok::ellipsis)) {
3748 SourceLocation EllipsisLoc = ConsumeToken();
David Blaikiebbafb8a2012-03-11 07:00:24 +00003749 if (!getLangOpts().MicrosoftExt)
Douglas Gregor356513d2008-12-01 18:00:20 +00003750 Diag(EllipsisLoc, diag::ext_ellipsis_exception_spec);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003751 T.consumeClose();
3752 SpecificationRange.setEnd(T.getCloseLocation());
Richard Smith8ca78a12013-06-13 02:02:51 +00003753 diagnoseDynamicExceptionSpecification(*this, SpecificationRange, false);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003754 return EST_MSAny;
Douglas Gregor356513d2008-12-01 18:00:20 +00003755 }
3756
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003757 // Parse the sequence of type-ids.
Sebastian Redld6434562009-05-29 18:02:33 +00003758 SourceRange Range;
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003759 while (Tok.isNot(tok::r_paren)) {
Sebastian Redld6434562009-05-29 18:02:33 +00003760 TypeResult Res(ParseTypeName(&Range));
Sebastian Redl965b0e32011-03-05 14:45:16 +00003761
Douglas Gregor830837d2010-12-20 23:57:46 +00003762 if (Tok.is(tok::ellipsis)) {
3763 // C++0x [temp.variadic]p5:
Fangrui Song6907ce22018-07-30 19:24:48 +00003764 // - In a dynamic-exception-specification (15.4); the pattern is a
Douglas Gregor830837d2010-12-20 23:57:46 +00003765 // type-id.
3766 SourceLocation Ellipsis = ConsumeToken();
Sebastian Redl965b0e32011-03-05 14:45:16 +00003767 Range.setEnd(Ellipsis);
Douglas Gregor830837d2010-12-20 23:57:46 +00003768 if (!Res.isInvalid())
3769 Res = Actions.ActOnPackExpansion(Res.get(), Ellipsis);
3770 }
Sebastian Redl965b0e32011-03-05 14:45:16 +00003771
Sebastian Redld6434562009-05-29 18:02:33 +00003772 if (!Res.isInvalid()) {
Sebastian Redl2b9cacb2009-04-29 17:30:04 +00003773 Exceptions.push_back(Res.get());
Sebastian Redld6434562009-05-29 18:02:33 +00003774 Ranges.push_back(Range);
3775 }
Alp Toker97650562014-01-10 11:19:30 +00003776
3777 if (!TryConsumeToken(tok::comma))
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003778 break;
3779 }
3780
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003781 T.consumeClose();
3782 SpecificationRange.setEnd(T.getCloseLocation());
Richard Smith8ca78a12013-06-13 02:02:51 +00003783 diagnoseDynamicExceptionSpecification(*this, SpecificationRange,
3784 Exceptions.empty());
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003785 return Exceptions.empty() ? EST_DynamicNone : EST_Dynamic;
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003786}
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003787
Douglas Gregor7fb25412010-10-01 18:44:50 +00003788/// ParseTrailingReturnType - Parse a trailing return type on a new-style
3789/// function declaration.
Richard Smithe303e352018-02-02 22:24:54 +00003790TypeResult Parser::ParseTrailingReturnType(SourceRange &Range,
3791 bool MayBeFollowedByDirectInit) {
Douglas Gregor7fb25412010-10-01 18:44:50 +00003792 assert(Tok.is(tok::arrow) && "expected arrow");
3793
3794 ConsumeToken();
3795
Richard Smithe303e352018-02-02 22:24:54 +00003796 return ParseTypeName(&Range, MayBeFollowedByDirectInit
3797 ? DeclaratorContext::TrailingReturnVarContext
3798 : DeclaratorContext::TrailingReturnContext);
Douglas Gregor7fb25412010-10-01 18:44:50 +00003799}
3800
Saar Razb65b1f32020-01-09 15:07:51 +02003801/// Parse a requires-clause as part of a function declaration.
3802void Parser::ParseTrailingRequiresClause(Declarator &D) {
3803 assert(Tok.is(tok::kw_requires) && "expected requires");
3804
3805 SourceLocation RequiresKWLoc = ConsumeToken();
3806
3807 ExprResult TrailingRequiresClause;
3808 ParseScope ParamScope(this,
3809 Scope::DeclScope |
3810 Scope::FunctionDeclarationScope |
3811 Scope::FunctionPrototypeScope);
3812
3813 Actions.ActOnStartTrailingRequiresClause(getCurScope(), D);
3814
3815 llvm::Optional<Sema::CXXThisScopeRAII> ThisScope;
3816 InitCXXThisScopeForDeclaratorIfRelevant(D, D.getDeclSpec(), ThisScope);
3817
3818 TrailingRequiresClause =
3819 ParseConstraintLogicalOrExpression(/*IsTrailingRequiresClause=*/true);
3820
3821 TrailingRequiresClause =
3822 Actions.ActOnFinishTrailingRequiresClause(TrailingRequiresClause);
3823
3824 if (!D.isDeclarationOfFunction()) {
3825 Diag(RequiresKWLoc,
3826 diag::err_requires_clause_on_declarator_not_declaring_a_function);
3827 return;
3828 }
3829
3830 if (TrailingRequiresClause.isInvalid())
3831 SkipUntil({tok::l_brace, tok::arrow, tok::kw_try, tok::comma, tok::colon},
3832 StopAtSemi | StopBeforeMatch);
3833 else
3834 D.setTrailingRequiresClause(TrailingRequiresClause.get());
3835
3836 // Did the user swap the trailing return type and requires clause?
3837 if (D.isFunctionDeclarator() && Tok.is(tok::arrow) &&
3838 D.getDeclSpec().getTypeSpecType() == TST_auto) {
3839 SourceLocation ArrowLoc = Tok.getLocation();
3840 SourceRange Range;
3841 TypeResult TrailingReturnType =
3842 ParseTrailingReturnType(Range, /*MayBeFollowedByDirectInit=*/false);
3843
3844 if (!TrailingReturnType.isInvalid()) {
3845 Diag(ArrowLoc,
3846 diag::err_requires_clause_must_appear_after_trailing_return)
3847 << Range;
3848 auto &FunctionChunk = D.getFunctionTypeInfo();
3849 FunctionChunk.HasTrailingReturnType = TrailingReturnType.isUsable();
3850 FunctionChunk.TrailingReturnType = TrailingReturnType.get();
3851 } else
3852 SkipUntil({tok::equal, tok::l_brace, tok::arrow, tok::kw_try, tok::comma},
3853 StopAtSemi | StopBeforeMatch);
3854 }
3855}
3856
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003857/// We have just started parsing the definition of a new class,
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003858/// so push that class onto our stack of classes that is currently
3859/// being parsed.
John McCallc1465822011-02-14 07:13:47 +00003860Sema::ParsingClassState
John McCalldb632ac2012-09-25 07:32:39 +00003861Parser::PushParsingClass(Decl *ClassDecl, bool NonNestedClass,
3862 bool IsInterface) {
Douglas Gregoredf8f392010-01-16 20:52:59 +00003863 assert((NonNestedClass || !ClassStack.empty()) &&
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003864 "Nested class without outer class");
John McCalldb632ac2012-09-25 07:32:39 +00003865 ClassStack.push(new ParsingClass(ClassDecl, NonNestedClass, IsInterface));
John McCallc1465822011-02-14 07:13:47 +00003866 return Actions.PushParsingClass();
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003867}
3868
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003869/// Deallocate the given parsed class and all of its nested
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003870/// classes.
3871void Parser::DeallocateParsedClasses(Parser::ParsingClass *Class) {
Douglas Gregorefc46952010-10-12 16:25:54 +00003872 for (unsigned I = 0, N = Class->LateParsedDeclarations.size(); I != N; ++I)
3873 delete Class->LateParsedDeclarations[I];
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003874 delete Class;
3875}
3876
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003877/// Pop the top class of the stack of classes that are
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003878/// currently being parsed.
3879///
3880/// This routine should be called when we have finished parsing the
3881/// definition of a class, but have not yet popped the Scope
3882/// associated with the class's definition.
John McCallc1465822011-02-14 07:13:47 +00003883void Parser::PopParsingClass(Sema::ParsingClassState state) {
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003884 assert(!ClassStack.empty() && "Mismatched push/pop for class parsing");
Mike Stump11289f42009-09-09 15:08:12 +00003885
John McCallc1465822011-02-14 07:13:47 +00003886 Actions.PopParsingClass(state);
3887
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003888 ParsingClass *Victim = ClassStack.top();
3889 ClassStack.pop();
3890 if (Victim->TopLevelClass) {
3891 // Deallocate all of the nested classes of this class,
3892 // recursively: we don't need to keep any of this information.
3893 DeallocateParsedClasses(Victim);
3894 return;
Mike Stump11289f42009-09-09 15:08:12 +00003895 }
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003896 assert(!ClassStack.empty() && "Missing top-level class?");
3897
Douglas Gregorefc46952010-10-12 16:25:54 +00003898 if (Victim->LateParsedDeclarations.empty()) {
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003899 // The victim is a nested class, but we will not need to perform
3900 // any processing after the definition of this class since it has
3901 // no members whose handling was delayed. Therefore, we can just
3902 // remove this nested class.
Douglas Gregorefc46952010-10-12 16:25:54 +00003903 DeallocateParsedClasses(Victim);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003904 return;
3905 }
3906
3907 // This nested class has some members that will need to be processed
3908 // after the top-level class is completely defined. Therefore, add
3909 // it to the list of nested classes within its parent.
Douglas Gregor0be31a22010-07-02 17:43:08 +00003910 assert(getCurScope()->isClassScope() && "Nested class outside of class scope?");
Douglas Gregorefc46952010-10-12 16:25:54 +00003911 ClassStack.top()->LateParsedDeclarations.push_back(new LateParsedClass(this, Victim));
Douglas Gregor0be31a22010-07-02 17:43:08 +00003912 Victim->TemplateScope = getCurScope()->getParent()->isTemplateParamScope();
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003913}
Alexis Hunt96d5c762009-11-21 08:43:09 +00003914
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003915/// Try to parse an 'identifier' which appears within an attribute-token.
Richard Smith3dff2512012-04-10 03:25:07 +00003916///
3917/// \return the parsed identifier on success, and 0 if the next token is not an
3918/// attribute-token.
3919///
3920/// C++11 [dcl.attr.grammar]p3:
3921/// If a keyword or an alternative token that satisfies the syntactic
3922/// requirements of an identifier is contained in an attribute-token,
3923/// it is considered an identifier.
3924IdentifierInfo *Parser::TryParseCXX11AttributeIdentifier(SourceLocation &Loc) {
3925 switch (Tok.getKind()) {
3926 default:
3927 // Identifiers and keywords have identifier info attached.
David Majnemerd5271992015-01-09 18:09:39 +00003928 if (!Tok.isAnnotation()) {
3929 if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
3930 Loc = ConsumeToken();
3931 return II;
3932 }
Richard Smith3dff2512012-04-10 03:25:07 +00003933 }
Craig Topper161e4db2014-05-21 06:02:52 +00003934 return nullptr;
Richard Smith3dff2512012-04-10 03:25:07 +00003935
Aaron Ballmanc44c17422018-11-09 17:19:45 +00003936 case tok::numeric_constant: {
3937 // If we got a numeric constant, check to see if it comes from a macro that
3938 // corresponds to the predefined __clang__ macro. If it does, warn the user
3939 // and recover by pretending they said _Clang instead.
3940 if (Tok.getLocation().isMacroID()) {
3941 SmallString<8> ExpansionBuf;
3942 SourceLocation ExpansionLoc =
3943 PP.getSourceManager().getExpansionLoc(Tok.getLocation());
3944 StringRef Spelling = PP.getSpelling(ExpansionLoc, ExpansionBuf);
3945 if (Spelling == "__clang__") {
3946 SourceRange TokRange(
3947 ExpansionLoc,
3948 PP.getSourceManager().getExpansionLoc(Tok.getEndLoc()));
3949 Diag(Tok, diag::warn_wrong_clang_attr_namespace)
3950 << FixItHint::CreateReplacement(TokRange, "_Clang");
3951 Loc = ConsumeToken();
3952 return &PP.getIdentifierTable().get("_Clang");
3953 }
3954 }
3955 return nullptr;
3956 }
3957
Richard Smith3dff2512012-04-10 03:25:07 +00003958 case tok::ampamp: // 'and'
3959 case tok::pipe: // 'bitor'
3960 case tok::pipepipe: // 'or'
3961 case tok::caret: // 'xor'
3962 case tok::tilde: // 'compl'
3963 case tok::amp: // 'bitand'
3964 case tok::ampequal: // 'and_eq'
3965 case tok::pipeequal: // 'or_eq'
3966 case tok::caretequal: // 'xor_eq'
3967 case tok::exclaim: // 'not'
3968 case tok::exclaimequal: // 'not_eq'
3969 // Alternative tokens do not have identifier info, but their spelling
3970 // starts with an alphabetical character.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003971 SmallString<8> SpellingBuf;
Benjamin Kramer60be5632015-03-29 19:25:07 +00003972 SourceLocation SpellingLoc =
3973 PP.getSourceManager().getSpellingLoc(Tok.getLocation());
3974 StringRef Spelling = PP.getSpelling(SpellingLoc, SpellingBuf);
Jordan Rosea7d03842013-02-08 22:30:41 +00003975 if (isLetter(Spelling[0])) {
Richard Smith3dff2512012-04-10 03:25:07 +00003976 Loc = ConsumeToken();
Benjamin Kramer5c17f9c2012-04-22 20:43:30 +00003977 return &PP.getIdentifierTable().get(Spelling);
Richard Smith3dff2512012-04-10 03:25:07 +00003978 }
Craig Topper161e4db2014-05-21 06:02:52 +00003979 return nullptr;
Richard Smith3dff2512012-04-10 03:25:07 +00003980 }
3981}
3982
Michael Han23214e52012-10-03 01:56:22 +00003983static bool IsBuiltInOrStandardCXX11Attribute(IdentifierInfo *AttrName,
Aaron Ballman606093a2017-10-15 15:01:42 +00003984 IdentifierInfo *ScopeName) {
Erich Keane6a24e802019-09-13 17:39:31 +00003985 switch (
3986 ParsedAttr::getParsedKind(AttrName, ScopeName, ParsedAttr::AS_CXX11)) {
Erich Keanee891aa92018-07-13 15:07:47 +00003987 case ParsedAttr::AT_CarriesDependency:
3988 case ParsedAttr::AT_Deprecated:
3989 case ParsedAttr::AT_FallThrough:
3990 case ParsedAttr::AT_CXX11NoReturn:
Richard Smith78b239e2019-06-20 20:44:45 +00003991 case ParsedAttr::AT_NoUniqueAddress:
Michael Han23214e52012-10-03 01:56:22 +00003992 return true;
Erich Keanee891aa92018-07-13 15:07:47 +00003993 case ParsedAttr::AT_WarnUnusedResult:
Aaron Ballmane7964782016-03-07 22:44:55 +00003994 return !ScopeName && AttrName->getName().equals("nodiscard");
Erich Keanee891aa92018-07-13 15:07:47 +00003995 case ParsedAttr::AT_Unused:
Nico Weberac03bce2016-08-23 19:59:55 +00003996 return !ScopeName && AttrName->getName().equals("maybe_unused");
Michael Han23214e52012-10-03 01:56:22 +00003997 default:
3998 return false;
3999 }
4000}
4001
Aaron Ballmanb8e20392014-03-31 17:32:39 +00004002/// ParseCXX11AttributeArgs -- Parse a C++11 attribute-argument-clause.
4003///
4004/// [C++11] attribute-argument-clause:
4005/// '(' balanced-token-seq ')'
4006///
4007/// [C++11] balanced-token-seq:
4008/// balanced-token
4009/// balanced-token-seq balanced-token
4010///
4011/// [C++11] balanced-token:
4012/// '(' balanced-token-seq ')'
4013/// '[' balanced-token-seq ']'
4014/// '{' balanced-token-seq '}'
4015/// any token but '(', ')', '[', ']', '{', or '}'
4016bool Parser::ParseCXX11AttributeArgs(IdentifierInfo *AttrName,
4017 SourceLocation AttrNameLoc,
4018 ParsedAttributes &Attrs,
4019 SourceLocation *EndLoc,
4020 IdentifierInfo *ScopeName,
4021 SourceLocation ScopeLoc) {
4022 assert(Tok.is(tok::l_paren) && "Not a C++11 attribute argument list");
Aaron Ballman35f94212014-04-14 16:03:22 +00004023 SourceLocation LParenLoc = Tok.getLocation();
Aaron Ballman606093a2017-10-15 15:01:42 +00004024 const LangOptions &LO = getLangOpts();
Erich Keanee891aa92018-07-13 15:07:47 +00004025 ParsedAttr::Syntax Syntax =
4026 LO.CPlusPlus ? ParsedAttr::AS_CXX11 : ParsedAttr::AS_C2x;
Aaron Ballmanb8e20392014-03-31 17:32:39 +00004027
4028 // If the attribute isn't known, we will not attempt to parse any
4029 // arguments.
Aaron Ballman606093a2017-10-15 15:01:42 +00004030 if (!hasAttribute(LO.CPlusPlus ? AttrSyntax::CXX : AttrSyntax::C, ScopeName,
4031 AttrName, getTargetInfo(), getLangOpts())) {
Aaron Ballmanb8e20392014-03-31 17:32:39 +00004032 // Eat the left paren, then skip to the ending right paren.
4033 ConsumeParen();
4034 SkipUntil(tok::r_paren);
Aaron Ballmanc44c17422018-11-09 17:19:45 +00004035 return false;
4036 }
4037
4038 if (ScopeName && (ScopeName->isStr("gnu") || ScopeName->isStr("__gnu__"))) {
4039 // GNU-scoped attributes have some special cases to handle GNU-specific
4040 // behaviors.
4041 ParseGNUAttributeArgs(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
Aaron Ballman606093a2017-10-15 15:01:42 +00004042 ScopeLoc, Syntax, nullptr);
Alex Lorenzd5d27e12017-03-01 18:06:25 +00004043 return true;
4044 }
4045
4046 unsigned NumArgs;
4047 // Some Clang-scoped attributes have some special parsing behavior.
Aaron Ballmanc44c17422018-11-09 17:19:45 +00004048 if (ScopeName && (ScopeName->isStr("clang") || ScopeName->isStr("_Clang")))
4049 NumArgs = ParseClangAttributeArgs(AttrName, AttrNameLoc, Attrs, EndLoc,
4050 ScopeName, ScopeLoc, Syntax);
Alex Lorenzd5d27e12017-03-01 18:06:25 +00004051 else
4052 NumArgs =
Aaron Ballman35f94212014-04-14 16:03:22 +00004053 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc,
Aaron Ballman606093a2017-10-15 15:01:42 +00004054 ScopeName, ScopeLoc, Syntax);
Alex Lorenzd5d27e12017-03-01 18:06:25 +00004055
Erich Keanec480f302018-07-12 21:09:05 +00004056 if (!Attrs.empty() &&
4057 IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName)) {
Michael Krusedc5ce722018-08-03 01:21:16 +00004058 ParsedAttr &Attr = Attrs.back();
Alex Lorenzd5d27e12017-03-01 18:06:25 +00004059 // If the attribute is a standard or built-in attribute and we are
4060 // parsing an argument list, we need to determine whether this attribute
4061 // was allowed to have an argument list (such as [[deprecated]]), and how
4062 // many arguments were parsed (so we can diagnose on [[deprecated()]]).
Erich Keanec480f302018-07-12 21:09:05 +00004063 if (Attr.getMaxArgs() && !NumArgs) {
Alex Lorenzd5d27e12017-03-01 18:06:25 +00004064 // The attribute was allowed to have arguments, but none were provided
4065 // even though the attribute parsed successfully. This is an error.
4066 Diag(LParenLoc, diag::err_attribute_requires_arguments) << AttrName;
Erich Keanec480f302018-07-12 21:09:05 +00004067 Attr.setInvalid(true);
4068 } else if (!Attr.getMaxArgs()) {
Alex Lorenzd5d27e12017-03-01 18:06:25 +00004069 // The attribute parsed successfully, but was not allowed to have any
4070 // arguments. It doesn't matter whether any were provided -- the
4071 // presence of the argument list (even if empty) is diagnosed.
4072 Diag(LParenLoc, diag::err_cxx11_attribute_forbids_arguments)
4073 << AttrName
4074 << FixItHint::CreateRemoval(SourceRange(LParenLoc, *EndLoc));
Erich Keanec480f302018-07-12 21:09:05 +00004075 Attr.setInvalid(true);
Aaron Ballman35f94212014-04-14 16:03:22 +00004076 }
4077 }
Aaron Ballmanb8e20392014-03-31 17:32:39 +00004078 return true;
4079}
4080
Aaron Ballman606093a2017-10-15 15:01:42 +00004081/// ParseCXX11AttributeSpecifier - Parse a C++11 or C2x attribute-specifier.
Alexis Hunt96d5c762009-11-21 08:43:09 +00004082///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004083/// [C++11] attribute-specifier:
Alexis Hunt96d5c762009-11-21 08:43:09 +00004084/// '[' '[' attribute-list ']' ']'
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00004085/// alignment-specifier
Alexis Hunt96d5c762009-11-21 08:43:09 +00004086///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004087/// [C++11] attribute-list:
Alexis Hunt96d5c762009-11-21 08:43:09 +00004088/// attribute[opt]
4089/// attribute-list ',' attribute[opt]
Richard Smith3dff2512012-04-10 03:25:07 +00004090/// attribute '...'
4091/// attribute-list ',' attribute '...'
Alexis Hunt96d5c762009-11-21 08:43:09 +00004092///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004093/// [C++11] attribute:
Alexis Hunt96d5c762009-11-21 08:43:09 +00004094/// attribute-token attribute-argument-clause[opt]
4095///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004096/// [C++11] attribute-token:
Alexis Hunt96d5c762009-11-21 08:43:09 +00004097/// identifier
4098/// attribute-scoped-token
4099///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004100/// [C++11] attribute-scoped-token:
Alexis Hunt96d5c762009-11-21 08:43:09 +00004101/// attribute-namespace '::' identifier
4102///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004103/// [C++11] attribute-namespace:
Alexis Hunt96d5c762009-11-21 08:43:09 +00004104/// identifier
Richard Smith3dff2512012-04-10 03:25:07 +00004105void Parser::ParseCXX11AttributeSpecifier(ParsedAttributes &attrs,
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004106 SourceLocation *endLoc) {
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00004107 if (Tok.is(tok::kw_alignas)) {
Richard Smithf679b5b2011-10-14 20:48:27 +00004108 Diag(Tok.getLocation(), diag::warn_cxx98_compat_alignas);
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00004109 ParseAlignmentSpecifier(attrs, endLoc);
4110 return;
4111 }
4112
Aaron Ballman606093a2017-10-15 15:01:42 +00004113 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square) &&
4114 "Not a double square bracket attribute list");
Alexis Hunt96d5c762009-11-21 08:43:09 +00004115
Richard Smithf679b5b2011-10-14 20:48:27 +00004116 Diag(Tok.getLocation(), diag::warn_cxx98_compat_attribute);
4117
Alexis Hunt96d5c762009-11-21 08:43:09 +00004118 ConsumeBracket();
4119 ConsumeBracket();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004120
Richard Smithb7d7a042016-06-24 12:15:12 +00004121 SourceLocation CommonScopeLoc;
4122 IdentifierInfo *CommonScopeName = nullptr;
4123 if (Tok.is(tok::kw_using)) {
Aaron Ballmanc351fba2017-12-04 20:27:34 +00004124 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
Richard Smithb7d7a042016-06-24 12:15:12 +00004125 ? diag::warn_cxx14_compat_using_attribute_ns
4126 : diag::ext_using_attribute_ns);
4127 ConsumeToken();
4128
4129 CommonScopeName = TryParseCXX11AttributeIdentifier(CommonScopeLoc);
4130 if (!CommonScopeName) {
4131 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
4132 SkipUntil(tok::r_square, tok::colon, StopBeforeMatch);
4133 }
4134 if (!TryConsumeToken(tok::colon) && CommonScopeName)
4135 Diag(Tok.getLocation(), diag::err_expected) << tok::colon;
4136 }
4137
Richard Smith10876ef2013-01-17 01:30:42 +00004138 llvm::SmallDenseMap<IdentifierInfo*, SourceLocation, 4> SeenAttrs;
4139
Richard Smith3dff2512012-04-10 03:25:07 +00004140 while (Tok.isNot(tok::r_square)) {
Alexis Hunt96d5c762009-11-21 08:43:09 +00004141 // attribute not present
Alp Toker97650562014-01-10 11:19:30 +00004142 if (TryConsumeToken(tok::comma))
Alexis Hunt96d5c762009-11-21 08:43:09 +00004143 continue;
Alexis Hunt96d5c762009-11-21 08:43:09 +00004144
Richard Smith3dff2512012-04-10 03:25:07 +00004145 SourceLocation ScopeLoc, AttrLoc;
Craig Topper161e4db2014-05-21 06:02:52 +00004146 IdentifierInfo *ScopeName = nullptr, *AttrName = nullptr;
Richard Smith3dff2512012-04-10 03:25:07 +00004147
4148 AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
4149 if (!AttrName)
4150 // Break out to the "expected ']'" diagnostic.
4151 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004152
Alexis Hunt96d5c762009-11-21 08:43:09 +00004153 // scoped attribute
Alp Toker97650562014-01-10 11:19:30 +00004154 if (TryConsumeToken(tok::coloncolon)) {
Richard Smith3dff2512012-04-10 03:25:07 +00004155 ScopeName = AttrName;
4156 ScopeLoc = AttrLoc;
4157
4158 AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
4159 if (!AttrName) {
Alp Tokerec543272013-12-24 09:48:30 +00004160 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
Alexey Bataevee6507d2013-11-18 08:17:37 +00004161 SkipUntil(tok::r_square, tok::comma, StopAtSemi | StopBeforeMatch);
Alexis Hunt96d5c762009-11-21 08:43:09 +00004162 continue;
4163 }
Alexis Hunt96d5c762009-11-21 08:43:09 +00004164 }
4165
Richard Smithb7d7a042016-06-24 12:15:12 +00004166 if (CommonScopeName) {
4167 if (ScopeName) {
4168 Diag(ScopeLoc, diag::err_using_attribute_ns_conflict)
4169 << SourceRange(CommonScopeLoc);
4170 } else {
4171 ScopeName = CommonScopeName;
4172 ScopeLoc = CommonScopeLoc;
4173 }
4174 }
4175
Aaron Ballmanb8e20392014-03-31 17:32:39 +00004176 bool StandardAttr = IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName);
Alexis Hunt96d5c762009-11-21 08:43:09 +00004177 bool AttrParsed = false;
Alexis Hunt96d5c762009-11-21 08:43:09 +00004178
Richard Smith10876ef2013-01-17 01:30:42 +00004179 if (StandardAttr &&
4180 !SeenAttrs.insert(std::make_pair(AttrName, AttrLoc)).second)
4181 Diag(AttrLoc, diag::err_cxx11_attribute_repeated)
Aaron Ballmanb8e20392014-03-31 17:32:39 +00004182 << AttrName << SourceRange(SeenAttrs[AttrName]);
Richard Smith10876ef2013-01-17 01:30:42 +00004183
Michael Han23214e52012-10-03 01:56:22 +00004184 // Parse attribute arguments
Aaron Ballman35f94212014-04-14 16:03:22 +00004185 if (Tok.is(tok::l_paren))
Aaron Ballmanb8e20392014-03-31 17:32:39 +00004186 AttrParsed = ParseCXX11AttributeArgs(AttrName, AttrLoc, attrs, endLoc,
4187 ScopeName, ScopeLoc);
Michael Han23214e52012-10-03 01:56:22 +00004188
4189 if (!AttrParsed)
Aaron Ballman606093a2017-10-15 15:01:42 +00004190 attrs.addNew(
4191 AttrName,
4192 SourceRange(ScopeLoc.isValid() ? ScopeLoc : AttrLoc, AttrLoc),
4193 ScopeName, ScopeLoc, nullptr, 0,
Erich Keanee891aa92018-07-13 15:07:47 +00004194 getLangOpts().CPlusPlus ? ParsedAttr::AS_CXX11 : ParsedAttr::AS_C2x);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004195
Alp Toker97650562014-01-10 11:19:30 +00004196 if (TryConsumeToken(tok::ellipsis))
Michael Han23214e52012-10-03 01:56:22 +00004197 Diag(Tok, diag::err_cxx11_attribute_forbids_ellipsis)
Richard Trieub4025802018-03-28 04:16:13 +00004198 << AttrName;
Alexis Hunt96d5c762009-11-21 08:43:09 +00004199 }
4200
Alp Toker383d2c42014-01-01 03:08:43 +00004201 if (ExpectAndConsume(tok::r_square))
Alexey Bataevee6507d2013-11-18 08:17:37 +00004202 SkipUntil(tok::r_square);
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004203 if (endLoc)
4204 *endLoc = Tok.getLocation();
Alp Toker383d2c42014-01-01 03:08:43 +00004205 if (ExpectAndConsume(tok::r_square))
Alexey Bataevee6507d2013-11-18 08:17:37 +00004206 SkipUntil(tok::r_square);
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004207}
Alexis Hunt96d5c762009-11-21 08:43:09 +00004208
Aaron Ballman606093a2017-10-15 15:01:42 +00004209/// ParseCXX11Attributes - Parse a C++11 or C2x attribute-specifier-seq.
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004210///
4211/// attribute-specifier-seq:
4212/// attribute-specifier-seq[opt] attribute-specifier
Richard Smith3dff2512012-04-10 03:25:07 +00004213void Parser::ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004214 SourceLocation *endLoc) {
Aaron Ballman606093a2017-10-15 15:01:42 +00004215 assert(standardAttributesAllowed());
Richard Smith4cabd042013-02-22 09:15:49 +00004216
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004217 SourceLocation StartLoc = Tok.getLocation(), Loc;
4218 if (!endLoc)
4219 endLoc = &Loc;
4220
Douglas Gregor6f981002011-10-07 20:35:25 +00004221 do {
Richard Smith3dff2512012-04-10 03:25:07 +00004222 ParseCXX11AttributeSpecifier(attrs, endLoc);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004223 } while (isCXX11AttributeSpecifier());
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004224
4225 attrs.Range = SourceRange(StartLoc, *endLoc);
Alexis Hunt96d5c762009-11-21 08:43:09 +00004226}
4227
Richard Smithc2c8bb82013-10-15 01:34:54 +00004228void Parser::DiagnoseAndSkipCXX11Attributes() {
Richard Smithc2c8bb82013-10-15 01:34:54 +00004229 // Start and end location of an attribute or an attribute list.
4230 SourceLocation StartLoc = Tok.getLocation();
Richard Smith955bf012014-06-19 11:42:00 +00004231 SourceLocation EndLoc = SkipCXX11Attributes();
4232
4233 if (EndLoc.isValid()) {
4234 SourceRange Range(StartLoc, EndLoc);
4235 Diag(StartLoc, diag::err_attributes_not_allowed)
4236 << Range;
4237 }
4238}
4239
4240SourceLocation Parser::SkipCXX11Attributes() {
Richard Smithc2c8bb82013-10-15 01:34:54 +00004241 SourceLocation EndLoc;
4242
Richard Smith955bf012014-06-19 11:42:00 +00004243 if (!isCXX11AttributeSpecifier())
4244 return EndLoc;
4245
Richard Smithc2c8bb82013-10-15 01:34:54 +00004246 do {
4247 if (Tok.is(tok::l_square)) {
4248 BalancedDelimiterTracker T(*this, tok::l_square);
4249 T.consumeOpen();
4250 T.skipToEnd();
4251 EndLoc = T.getCloseLocation();
4252 } else {
4253 assert(Tok.is(tok::kw_alignas) && "not an attribute specifier");
4254 ConsumeToken();
4255 BalancedDelimiterTracker T(*this, tok::l_paren);
4256 if (!T.consumeOpen())
4257 T.skipToEnd();
4258 EndLoc = T.getCloseLocation();
4259 }
4260 } while (isCXX11AttributeSpecifier());
4261
Richard Smith955bf012014-06-19 11:42:00 +00004262 return EndLoc;
Richard Smithc2c8bb82013-10-15 01:34:54 +00004263}
4264
Nico Weber05e1dad2016-09-03 03:25:22 +00004265/// Parse uuid() attribute when it appears in a [] Microsoft attribute.
4266void Parser::ParseMicrosoftUuidAttributeArgs(ParsedAttributes &Attrs) {
4267 assert(Tok.is(tok::identifier) && "Not a Microsoft attribute list");
4268 IdentifierInfo *UuidIdent = Tok.getIdentifierInfo();
4269 assert(UuidIdent->getName() == "uuid" && "Not a Microsoft attribute list");
4270
4271 SourceLocation UuidLoc = Tok.getLocation();
4272 ConsumeToken();
4273
4274 // Ignore the left paren location for now.
4275 BalancedDelimiterTracker T(*this, tok::l_paren);
4276 if (T.consumeOpen()) {
4277 Diag(Tok, diag::err_expected) << tok::l_paren;
4278 return;
4279 }
4280
4281 ArgsVector ArgExprs;
4282 if (Tok.is(tok::string_literal)) {
4283 // Easy case: uuid("...") -- quoted string.
4284 ExprResult StringResult = ParseStringLiteralExpression();
4285 if (StringResult.isInvalid())
4286 return;
4287 ArgExprs.push_back(StringResult.get());
4288 } else {
4289 // something like uuid({000000A0-0000-0000-C000-000000000049}) -- no
4290 // quotes in the parens. Just append the spelling of all tokens encountered
4291 // until the closing paren.
4292
4293 SmallString<42> StrBuffer; // 2 "", 36 bytes UUID, 2 optional {}, 1 nul
4294 StrBuffer += "\"";
4295
4296 // Since none of C++'s keywords match [a-f]+, accepting just tok::l_brace,
4297 // tok::r_brace, tok::minus, tok::identifier (think C000) and
4298 // tok::numeric_constant (0000) should be enough. But the spelling of the
4299 // uuid argument is checked later anyways, so there's no harm in accepting
4300 // almost anything here.
4301 // cl is very strict about whitespace in this form and errors out if any
4302 // is present, so check the space flags on the tokens.
4303 SourceLocation StartLoc = Tok.getLocation();
4304 while (Tok.isNot(tok::r_paren)) {
4305 if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
4306 Diag(Tok, diag::err_attribute_uuid_malformed_guid);
4307 SkipUntil(tok::r_paren, StopAtSemi);
4308 return;
4309 }
4310 SmallString<16> SpellingBuffer;
4311 SpellingBuffer.resize(Tok.getLength() + 1);
4312 bool Invalid = false;
4313 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
4314 if (Invalid) {
4315 SkipUntil(tok::r_paren, StopAtSemi);
4316 return;
4317 }
4318 StrBuffer += TokSpelling;
4319 ConsumeAnyToken();
4320 }
4321 StrBuffer += "\"";
4322
4323 if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
4324 Diag(Tok, diag::err_attribute_uuid_malformed_guid);
4325 ConsumeParen();
4326 return;
4327 }
4328
4329 // Pretend the user wrote the appropriate string literal here.
4330 // ActOnStringLiteral() copies the string data into the literal, so it's
4331 // ok that the Token points to StrBuffer.
4332 Token Toks[1];
4333 Toks[0].startToken();
4334 Toks[0].setKind(tok::string_literal);
4335 Toks[0].setLocation(StartLoc);
4336 Toks[0].setLiteralData(StrBuffer.data());
4337 Toks[0].setLength(StrBuffer.size());
4338 StringLiteral *UuidString =
4339 cast<StringLiteral>(Actions.ActOnStringLiteral(Toks, nullptr).get());
4340 ArgExprs.push_back(UuidString);
4341 }
4342
4343 if (!T.consumeClose()) {
Nico Weber05e1dad2016-09-03 03:25:22 +00004344 Attrs.addNew(UuidIdent, SourceRange(UuidLoc, T.getCloseLocation()), nullptr,
4345 SourceLocation(), ArgExprs.data(), ArgExprs.size(),
Erich Keanee891aa92018-07-13 15:07:47 +00004346 ParsedAttr::AS_Microsoft);
Nico Weber05e1dad2016-09-03 03:25:22 +00004347 }
4348}
4349
David Majnemere4752e752015-07-08 05:55:00 +00004350/// ParseMicrosoftAttributes - Parse Microsoft attributes [Attr]
Francois Pichetc2bc5ac2010-10-11 12:59:39 +00004351///
4352/// [MS] ms-attribute:
4353/// '[' token-seq ']'
4354///
4355/// [MS] ms-attribute-seq:
4356/// ms-attribute[opt]
4357/// ms-attribute ms-attribute-seq
John McCall53fa7142010-12-24 02:08:15 +00004358void Parser::ParseMicrosoftAttributes(ParsedAttributes &attrs,
4359 SourceLocation *endLoc) {
Francois Pichetc2bc5ac2010-10-11 12:59:39 +00004360 assert(Tok.is(tok::l_square) && "Not a Microsoft attribute list");
4361
Saleem Abdulrasool425efcf2015-06-15 20:57:04 +00004362 do {
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004363 // FIXME: If this is actually a C++11 attribute, parse it as one.
Saleem Abdulrasool425efcf2015-06-15 20:57:04 +00004364 BalancedDelimiterTracker T(*this, tok::l_square);
4365 T.consumeOpen();
Nico Weber05e1dad2016-09-03 03:25:22 +00004366
4367 // Skip most ms attributes except for a whitelist.
4368 while (true) {
4369 SkipUntil(tok::r_square, tok::identifier, StopAtSemi | StopBeforeMatch);
4370 if (Tok.isNot(tok::identifier)) // ']', but also eof
4371 break;
4372 if (Tok.getIdentifierInfo()->getName() == "uuid")
4373 ParseMicrosoftUuidAttributeArgs(attrs);
4374 else
4375 ConsumeToken();
4376 }
4377
Saleem Abdulrasool425efcf2015-06-15 20:57:04 +00004378 T.consumeClose();
4379 if (endLoc)
4380 *endLoc = T.getCloseLocation();
4381 } while (Tok.is(tok::l_square));
Francois Pichetc2bc5ac2010-10-11 12:59:39 +00004382}
Francois Pichet8f981d52011-05-25 10:19:49 +00004383
Erich Keanec480f302018-07-12 21:09:05 +00004384void Parser::ParseMicrosoftIfExistsClassDeclaration(
4385 DeclSpec::TST TagType, ParsedAttributes &AccessAttrs,
4386 AccessSpecifier &CurAS) {
Douglas Gregor43edb322011-10-24 22:31:10 +00004387 IfExistsCondition Result;
Francois Pichet8f981d52011-05-25 10:19:49 +00004388 if (ParseMicrosoftIfExistsCondition(Result))
4389 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00004390
Douglas Gregor43edb322011-10-24 22:31:10 +00004391 BalancedDelimiterTracker Braces(*this, tok::l_brace);
4392 if (Braces.consumeOpen()) {
Alp Tokerec543272013-12-24 09:48:30 +00004393 Diag(Tok, diag::err_expected) << tok::l_brace;
Francois Pichet8f981d52011-05-25 10:19:49 +00004394 return;
4395 }
Francois Pichet8f981d52011-05-25 10:19:49 +00004396
Douglas Gregor43edb322011-10-24 22:31:10 +00004397 switch (Result.Behavior) {
4398 case IEB_Parse:
4399 // Parse the declarations below.
4400 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00004401
Douglas Gregor43edb322011-10-24 22:31:10 +00004402 case IEB_Dependent:
4403 Diag(Result.KeywordLoc, diag::warn_microsoft_dependent_exists)
4404 << Result.IsIfExists;
4405 // Fall through to skip.
Galina Kistanovad819d5b2017-06-01 21:19:06 +00004406 LLVM_FALLTHROUGH;
Fangrui Song6907ce22018-07-30 19:24:48 +00004407
Douglas Gregor43edb322011-10-24 22:31:10 +00004408 case IEB_Skip:
4409 Braces.skipToEnd();
Francois Pichet8f981d52011-05-25 10:19:49 +00004410 return;
4411 }
4412
Richard Smith34f30512013-11-23 04:06:09 +00004413 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
Francois Pichet8f981d52011-05-25 10:19:49 +00004414 // __if_exists, __if_not_exists can nest.
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00004415 if (Tok.isOneOf(tok::kw___if_exists, tok::kw___if_not_exists)) {
Serge Pavlov0c503192019-08-01 11:46:28 +00004416 ParseMicrosoftIfExistsClassDeclaration(TagType,
Erich Keanec480f302018-07-12 21:09:05 +00004417 AccessAttrs, CurAS);
Francois Pichet8f981d52011-05-25 10:19:49 +00004418 continue;
4419 }
4420
4421 // Check for extraneous top-level semicolon.
4422 if (Tok.is(tok::semi)) {
Richard Smith87f5dc52012-07-23 05:45:25 +00004423 ConsumeExtraSemi(InsideStruct, TagType);
Francois Pichet8f981d52011-05-25 10:19:49 +00004424 continue;
4425 }
4426
4427 AccessSpecifier AS = getAccessSpecifierIfPresent();
4428 if (AS != AS_none) {
4429 // Current token is a C++ access specifier.
4430 CurAS = AS;
4431 SourceLocation ASLoc = Tok.getLocation();
4432 ConsumeToken();
4433 if (Tok.is(tok::colon))
Erich Keanec480f302018-07-12 21:09:05 +00004434 Actions.ActOnAccessSpecifier(AS, ASLoc, Tok.getLocation(),
4435 ParsedAttributesView{});
Francois Pichet8f981d52011-05-25 10:19:49 +00004436 else
Alp Toker35d87032013-12-30 23:29:50 +00004437 Diag(Tok, diag::err_expected) << tok::colon;
Francois Pichet8f981d52011-05-25 10:19:49 +00004438 ConsumeToken();
4439 continue;
4440 }
4441
4442 // Parse all the comma separated declarators.
Erich Keanec480f302018-07-12 21:09:05 +00004443 ParseCXXClassMemberDeclaration(CurAS, AccessAttrs);
Francois Pichet8f981d52011-05-25 10:19:49 +00004444 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004445
Douglas Gregor43edb322011-10-24 22:31:10 +00004446 Braces.consumeClose();
Francois Pichet8f981d52011-05-25 10:19:49 +00004447}