blob: 85c972f4107912da7e117b12b64a5cc795992eb3 [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//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnera5235172007-08-25 06:57:03 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the C++ Declaration portions of the Parser interfaces.
11//
12//===----------------------------------------------------------------------===//
13
Douglas Gregor423984d2008-04-14 00:13:42 +000014#include "clang/Parse/Parser.h"
Erik Verbruggen888d52a2014-01-15 09:15:43 +000015#include "clang/AST/ASTContext.h"
Chandler Carruth757fcd62014-03-04 10:05:20 +000016#include "clang/AST/DeclTemplate.h"
Jordan Rose1e879d82018-03-23 00:07:18 +000017#include "clang/AST/PrettyDeclStackTrace.h"
Aaron Ballmanb8e20392014-03-31 17:32:39 +000018#include "clang/Basic/Attributes.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000019#include "clang/Basic/CharInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/Basic/OperatorKinds.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000021#include "clang/Basic/TargetInfo.h"
Chris Lattner60f36222009-01-29 05:15:15 +000022#include "clang/Parse/ParseDiagnostic.h"
Vassil Vassilev11ad3392017-03-23 15:11:07 +000023#include "clang/Parse/RAIIObjectsForParser.h"
John McCall8b0666c2010-08-20 18:27:03 +000024#include "clang/Sema/DeclSpec.h"
John McCall8b0666c2010-08-20 18:27:03 +000025#include "clang/Sema/ParsedTemplate.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "clang/Sema/Scope.h"
John McCalldb632ac2012-09-25 07:32:39 +000027#include "clang/Sema/SemaDiagnostic.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000028#include "llvm/ADT/SmallString.h"
Hans Wennborgdcfba332015-10-06 23:40:43 +000029
Chris Lattnera5235172007-08-25 06:57:03 +000030using namespace clang;
31
32/// ParseNamespace - We know that the current token is a namespace keyword. This
Sebastian Redl67667942010-08-27 23:12:46 +000033/// may either be a top level namespace or a block-level namespace alias. If
34/// there was an inline keyword, it has already been parsed.
Chris Lattnera5235172007-08-25 06:57:03 +000035///
Erich Keane53f391d2018-11-12 17:19:48 +000036/// namespace-definition: [C++: namespace.def]
Chris Lattnera5235172007-08-25 06:57:03 +000037/// named-namespace-definition
38/// unnamed-namespace-definition
Erich Keane53f391d2018-11-12 17:19:48 +000039/// nested-namespace-definition
40///
41/// named-namespace-definition:
42/// 'inline'[opt] 'namespace' attributes[opt] identifier '{' 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:
48/// 'namespace' enclosing-namespace-specifier '::' 'inline'[opt] identifier '{' namespace-body '}'
Chris Lattnera5235172007-08-25 06:57:03 +000049///
Erich Keane53f391d2018-11-12 17:19:48 +000050/// enclosing-namespace-specifier:
51/// identifier
52/// enclosing-namespace-specifier '::' 'inline'[opt] identifier
Mike Stump11289f42009-09-09 15:08:12 +000053///
Chris Lattnera5235172007-08-25 06:57:03 +000054/// namespace-alias-definition: [C++ 7.3.2: namespace.alias]
55/// 'namespace' identifier '=' qualified-namespace-specifier ';'
56///
Faisal Vali421b2d12017-12-29 05:41:00 +000057Parser::DeclGroupPtrTy Parser::ParseNamespace(DeclaratorContext Context,
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +000058 SourceLocation &DeclEnd,
59 SourceLocation InlineLoc) {
Chris Lattner76c72282007-10-09 17:33:22 +000060 assert(Tok.is(tok::kw_namespace) && "Not a namespace!");
Chris Lattnera5235172007-08-25 06:57:03 +000061 SourceLocation NamespaceLoc = ConsumeToken(); // eat the 'namespace'.
Fariborz Jahanian4bf82622011-08-22 17:59:19 +000062 ObjCDeclContextSwitch ObjCDC(*this);
Fangrui Song6907ce22018-07-30 19:24:48 +000063
Douglas Gregor7e90c6d2009-09-18 19:03:04 +000064 if (Tok.is(tok::code_completion)) {
Douglas Gregor0be31a22010-07-02 17:43:08 +000065 Actions.CodeCompleteNamespaceDecl(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +000066 cutOffParsing();
David Blaikie0403cb12016-01-15 23:43:25 +000067 return nullptr;
Douglas Gregor7e90c6d2009-09-18 19:03:04 +000068 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000069
Chris Lattnera5235172007-08-25 06:57:03 +000070 SourceLocation IdentLoc;
Craig Topper161e4db2014-05-21 06:02:52 +000071 IdentifierInfo *Ident = nullptr;
Erich Keane53f391d2018-11-12 17:19:48 +000072 InnerNamespaceInfoList ExtraNSs;
73 SourceLocation FirstNestedInlineLoc;
Douglas Gregor6b6bba42009-06-17 19:49:00 +000074
Aaron Ballman730476b2014-11-08 15:33:35 +000075 ParsedAttributesWithRange attrs(AttrFactory);
76 SourceLocation attrLoc;
77 if (getLangOpts().CPlusPlus11 && isCXX11AttributeSpecifier()) {
Aaron Ballmanc351fba2017-12-04 20:27:34 +000078 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
Richard Smith40e202f2017-10-14 00:56:24 +000079 ? diag::warn_cxx14_compat_ns_enum_attribute
80 : diag::ext_ns_enum_attribute)
81 << 0 /*namespace*/;
Aaron Ballman730476b2014-11-08 15:33:35 +000082 attrLoc = Tok.getLocation();
83 ParseCXX11Attributes(attrs);
84 }
Mike Stump11289f42009-09-09 15:08:12 +000085
Chris Lattner76c72282007-10-09 17:33:22 +000086 if (Tok.is(tok::identifier)) {
Chris Lattnera5235172007-08-25 06:57:03 +000087 Ident = Tok.getIdentifierInfo();
88 IdentLoc = ConsumeToken(); // eat the identifier.
Erich Keane53f391d2018-11-12 17:19:48 +000089 while (Tok.is(tok::coloncolon) &&
90 (NextToken().is(tok::identifier) ||
91 (NextToken().is(tok::kw_inline) &&
92 GetLookAheadToken(2).is(tok::identifier)))) {
93
94 InnerNamespaceInfo Info;
95 Info.NamespaceLoc = ConsumeToken();
96
97 if (Tok.is(tok::kw_inline)) {
98 Info.InlineLoc = ConsumeToken();
99 if (FirstNestedInlineLoc.isInvalid())
100 FirstNestedInlineLoc = Info.InlineLoc;
101 }
102
103 Info.Ident = Tok.getIdentifierInfo();
104 Info.IdentLoc = ConsumeToken();
105
106 ExtraNSs.push_back(Info);
Richard Trieu61384cb2011-05-26 20:11:09 +0000107 }
Chris Lattnera5235172007-08-25 06:57:03 +0000108 }
Mike Stump11289f42009-09-09 15:08:12 +0000109
Aaron Ballmanc0ae7df2014-11-08 17:07:15 +0000110 // A nested namespace definition cannot have attributes.
Erich Keane53f391d2018-11-12 17:19:48 +0000111 if (!ExtraNSs.empty() && attrLoc.isValid())
Aaron Ballmanc0ae7df2014-11-08 17:07:15 +0000112 Diag(attrLoc, diag::err_unexpected_nested_namespace_attribute);
113
Chris Lattnera5235172007-08-25 06:57:03 +0000114 // Read label attributes, if present.
Douglas Gregor6b6bba42009-06-17 19:49:00 +0000115 if (Tok.is(tok::kw___attribute)) {
Aaron Ballman730476b2014-11-08 15:33:35 +0000116 attrLoc = Tok.getLocation();
John McCall53fa7142010-12-24 02:08:15 +0000117 ParseGNUAttributes(attrs);
Douglas Gregor6b6bba42009-06-17 19:49:00 +0000118 }
Mike Stump11289f42009-09-09 15:08:12 +0000119
Douglas Gregor6b6bba42009-06-17 19:49:00 +0000120 if (Tok.is(tok::equal)) {
Craig Topper161e4db2014-05-21 06:02:52 +0000121 if (!Ident) {
Alp Tokerec543272013-12-24 09:48:30 +0000122 Diag(Tok, diag::err_expected) << tok::identifier;
Nico Weber729f1e22012-10-27 23:44:27 +0000123 // Skip to end of the definition and eat the ';'.
124 SkipUntil(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +0000125 return nullptr;
Nico Weber729f1e22012-10-27 23:44:27 +0000126 }
Aaron Ballman730476b2014-11-08 15:33:35 +0000127 if (attrLoc.isValid())
128 Diag(attrLoc, diag::err_unexpected_namespace_attributes_alias);
Sebastian Redl67667942010-08-27 23:12:46 +0000129 if (InlineLoc.isValid())
130 Diag(InlineLoc, diag::err_inline_namespace_alias)
131 << FixItHint::CreateRemoval(InlineLoc);
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +0000132 Decl *NSAlias = ParseNamespaceAlias(NamespaceLoc, IdentLoc, Ident, DeclEnd);
133 return Actions.ConvertDeclToDeclGroup(NSAlias);
134}
Mike Stump11289f42009-09-09 15:08:12 +0000135
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000136 BalancedDelimiterTracker T(*this, tok::l_brace);
137 if (T.consumeOpen()) {
Alp Tokerec543272013-12-24 09:48:30 +0000138 if (Ident)
139 Diag(Tok, diag::err_expected) << tok::l_brace;
140 else
141 Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace;
David Blaikie0403cb12016-01-15 23:43:25 +0000142 return nullptr;
Chris Lattnera5235172007-08-25 06:57:03 +0000143 }
Mike Stump11289f42009-09-09 15:08:12 +0000144
Fangrui Song6907ce22018-07-30 19:24:48 +0000145 if (getCurScope()->isClassScope() || getCurScope()->isTemplateParamScope() ||
146 getCurScope()->isInObjcMethodScope() || getCurScope()->getBlockParent() ||
Douglas Gregor0be31a22010-07-02 17:43:08 +0000147 getCurScope()->getFnParent()) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000148 Diag(T.getOpenLocation(), diag::err_namespace_nonnamespace_scope);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000149 SkipUntil(tok::r_brace);
David Blaikie0403cb12016-01-15 23:43:25 +0000150 return nullptr;
Douglas Gregor05cfc292010-05-14 05:08:22 +0000151 }
152
Erich Keane53f391d2018-11-12 17:19:48 +0000153 if (ExtraNSs.empty()) {
Richard Smith13307f52014-11-08 05:37:34 +0000154 // Normal namespace definition, not a nested-namespace-definition.
155 } else if (InlineLoc.isValid()) {
156 Diag(InlineLoc, diag::err_inline_nested_namespace_definition);
Erich Keane53f391d2018-11-12 17:19:48 +0000157 } else if (getLangOpts().CPlusPlus2a) {
158 Diag(ExtraNSs[0].NamespaceLoc,
Richard Smith13307f52014-11-08 05:37:34 +0000159 diag::warn_cxx14_compat_nested_namespace_definition);
Erich Keane53f391d2018-11-12 17:19:48 +0000160 if (FirstNestedInlineLoc.isValid())
161 Diag(FirstNestedInlineLoc,
162 diag::warn_cxx17_compat_inline_nested_namespace_definition);
163 } else if (getLangOpts().CPlusPlus17) {
164 Diag(ExtraNSs[0].NamespaceLoc,
165 diag::warn_cxx14_compat_nested_namespace_definition);
166 if (FirstNestedInlineLoc.isValid())
167 Diag(FirstNestedInlineLoc, diag::ext_inline_nested_namespace_definition);
Richard Smith13307f52014-11-08 05:37:34 +0000168 } else {
Richard Trieu61384cb2011-05-26 20:11:09 +0000169 TentativeParsingAction TPA(*this);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000170 SkipUntil(tok::r_brace, StopBeforeMatch);
Richard Trieu61384cb2011-05-26 20:11:09 +0000171 Token rBraceToken = Tok;
172 TPA.Revert();
173
174 if (!rBraceToken.is(tok::r_brace)) {
Erich Keane53f391d2018-11-12 17:19:48 +0000175 Diag(ExtraNSs[0].NamespaceLoc, diag::ext_nested_namespace_definition)
176 << SourceRange(ExtraNSs.front().NamespaceLoc,
177 ExtraNSs.back().IdentLoc);
Richard Trieu61384cb2011-05-26 20:11:09 +0000178 } else {
Benjamin Kramerf546f412011-05-26 21:32:30 +0000179 std::string NamespaceFix;
Erich Keane53f391d2018-11-12 17:19:48 +0000180 for (const auto &ExtraNS : ExtraNSs) {
Richard Trieu61384cb2011-05-26 20:11:09 +0000181 NamespaceFix += " { namespace ";
Erich Keane53f391d2018-11-12 17:19:48 +0000182 NamespaceFix += ExtraNS.Ident->getName();
Richard Trieu61384cb2011-05-26 20:11:09 +0000183 }
Benjamin Kramerf546f412011-05-26 21:32:30 +0000184
Richard Trieu61384cb2011-05-26 20:11:09 +0000185 std::string RBraces;
Erich Keane53f391d2018-11-12 17:19:48 +0000186 for (unsigned i = 0, e = ExtraNSs.size(); i != e; ++i)
Richard Trieu61384cb2011-05-26 20:11:09 +0000187 RBraces += "} ";
Benjamin Kramerf546f412011-05-26 21:32:30 +0000188
Erich Keane53f391d2018-11-12 17:19:48 +0000189 Diag(ExtraNSs[0].NamespaceLoc, diag::ext_nested_namespace_definition)
190 << FixItHint::CreateReplacement(
191 SourceRange(ExtraNSs.front().NamespaceLoc,
192 ExtraNSs.back().IdentLoc),
193 NamespaceFix)
Richard Trieu61384cb2011-05-26 20:11:09 +0000194 << FixItHint::CreateInsertion(rBraceToken.getLocation(), RBraces);
195 }
Erich Keane53f391d2018-11-12 17:19:48 +0000196
197 // Warn about nested inline namespaces.
198 if (FirstNestedInlineLoc.isValid())
199 Diag(FirstNestedInlineLoc, diag::ext_inline_nested_namespace_definition);
Richard Trieu61384cb2011-05-26 20:11:09 +0000200 }
201
Sebastian Redl5a5f2c72010-08-31 00:36:45 +0000202 // If we're still good, complain about inline namespaces in non-C++0x now.
Richard Smith5d164bc2011-10-15 05:09:34 +0000203 if (InlineLoc.isValid())
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000204 Diag(InlineLoc, getLangOpts().CPlusPlus11 ?
Richard Smith5d164bc2011-10-15 05:09:34 +0000205 diag::warn_cxx98_compat_inline_namespace : diag::ext_inline_namespace);
Sebastian Redl5a5f2c72010-08-31 00:36:45 +0000206
Chris Lattner4de55aa2009-03-29 14:02:43 +0000207 // Enter a scope for the namespace.
208 ParseScope NamespaceScope(this, Scope::DeclScope);
209
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +0000210 UsingDirectiveDecl *ImplicitUsingDirectiveDecl = nullptr;
Erich Keanec480f302018-07-12 21:09:05 +0000211 Decl *NamespcDecl = Actions.ActOnStartNamespaceDef(
212 getCurScope(), InlineLoc, NamespaceLoc, IdentLoc, Ident,
213 T.getOpenLocation(), attrs, ImplicitUsingDirectiveDecl);
Chris Lattner4de55aa2009-03-29 14:02:43 +0000214
Jordan Rose1e879d82018-03-23 00:07:18 +0000215 PrettyDeclStackTraceEntry CrashInfo(Actions.Context, NamespcDecl,
216 NamespaceLoc, "parsing namespace");
Mike Stump11289f42009-09-09 15:08:12 +0000217
Fangrui Song6907ce22018-07-30 19:24:48 +0000218 // Parse the contents of the namespace. This includes parsing recovery on
Richard Trieu61384cb2011-05-26 20:11:09 +0000219 // any improperly nested namespaces.
Erich Keane53f391d2018-11-12 17:19:48 +0000220 ParseInnerNamespace(ExtraNSs, 0, InlineLoc, attrs, T);
Mike Stump11289f42009-09-09 15:08:12 +0000221
Chris Lattner4de55aa2009-03-29 14:02:43 +0000222 // Leave the namespace scope.
223 NamespaceScope.Exit();
224
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000225 DeclEnd = T.getCloseLocation();
226 Actions.ActOnFinishNamespaceDef(NamespcDecl, DeclEnd);
Fangrui Song6907ce22018-07-30 19:24:48 +0000227
228 return Actions.ConvertDeclToDeclGroup(NamespcDecl,
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +0000229 ImplicitUsingDirectiveDecl);
Chris Lattnera5235172007-08-25 06:57:03 +0000230}
Chris Lattner38376f12008-01-12 07:05:38 +0000231
Richard Trieu61384cb2011-05-26 20:11:09 +0000232/// ParseInnerNamespace - Parse the contents of a namespace.
Erich Keane53f391d2018-11-12 17:19:48 +0000233void Parser::ParseInnerNamespace(const InnerNamespaceInfoList &InnerNSs,
Richard Smith13307f52014-11-08 05:37:34 +0000234 unsigned int index, SourceLocation &InlineLoc,
235 ParsedAttributes &attrs,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000236 BalancedDelimiterTracker &Tracker) {
Erich Keane53f391d2018-11-12 17:19:48 +0000237 if (index == InnerNSs.size()) {
Richard Smith752ada82015-11-17 23:32:01 +0000238 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
239 Tok.isNot(tok::eof)) {
Richard Trieu61384cb2011-05-26 20:11:09 +0000240 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +0000241 MaybeParseCXX11Attributes(attrs);
Richard Trieu61384cb2011-05-26 20:11:09 +0000242 ParseExternalDeclaration(attrs);
243 }
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000244
245 // The caller is what called check -- we are simply calling
246 // the close for it.
247 Tracker.consumeClose();
Richard Trieu61384cb2011-05-26 20:11:09 +0000248
249 return;
250 }
251
Richard Smith13307f52014-11-08 05:37:34 +0000252 // Handle a nested namespace definition.
253 // FIXME: Preserve the source information through to the AST rather than
254 // desugaring it here.
Richard Trieu61384cb2011-05-26 20:11:09 +0000255 ParseScope NamespaceScope(this, Scope::DeclScope);
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +0000256 UsingDirectiveDecl *ImplicitUsingDirectiveDecl = nullptr;
Erich Keanec480f302018-07-12 21:09:05 +0000257 Decl *NamespcDecl = Actions.ActOnStartNamespaceDef(
Erich Keane53f391d2018-11-12 17:19:48 +0000258 getCurScope(), InnerNSs[index].InlineLoc, InnerNSs[index].NamespaceLoc,
259 InnerNSs[index].IdentLoc, InnerNSs[index].Ident,
260 Tracker.getOpenLocation(), attrs, ImplicitUsingDirectiveDecl);
Fangrui Song6907ce22018-07-30 19:24:48 +0000261 assert(!ImplicitUsingDirectiveDecl &&
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +0000262 "nested namespace definition cannot define anonymous namespace");
Richard Trieu61384cb2011-05-26 20:11:09 +0000263
Erich Keane53f391d2018-11-12 17:19:48 +0000264 ParseInnerNamespace(InnerNSs, ++index, InlineLoc,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000265 attrs, Tracker);
Richard Trieu61384cb2011-05-26 20:11:09 +0000266
267 NamespaceScope.Exit();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000268 Actions.ActOnFinishNamespaceDef(NamespcDecl, Tracker.getCloseLocation());
Richard Trieu61384cb2011-05-26 20:11:09 +0000269}
270
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000271/// ParseNamespaceAlias - Parse the part after the '=' in a namespace
272/// alias definition.
273///
John McCall48871652010-08-21 09:40:31 +0000274Decl *Parser::ParseNamespaceAlias(SourceLocation NamespaceLoc,
John McCall084e83d2011-03-24 11:26:52 +0000275 SourceLocation AliasLoc,
276 IdentifierInfo *Alias,
277 SourceLocation &DeclEnd) {
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000278 assert(Tok.is(tok::equal) && "Not equal token");
Mike Stump11289f42009-09-09 15:08:12 +0000279
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000280 ConsumeToken(); // eat the '='.
Mike Stump11289f42009-09-09 15:08:12 +0000281
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000282 if (Tok.is(tok::code_completion)) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000283 Actions.CodeCompleteNamespaceAliasDecl(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000284 cutOffParsing();
Craig Topper161e4db2014-05-21 06:02:52 +0000285 return nullptr;
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000286 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000287
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000288 CXXScopeSpec SS;
289 // Parse (optional) nested-name-specifier.
Matthias Gehredc01bb42017-03-17 21:41:20 +0000290 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false,
291 /*MayBePseudoDestructor=*/nullptr,
292 /*IsTypename=*/false,
293 /*LastII=*/nullptr,
294 /*OnlyNamespace=*/true);
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000295
Matthias Gehredc01bb42017-03-17 21:41:20 +0000296 if (Tok.isNot(tok::identifier)) {
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000297 Diag(Tok, diag::err_expected_namespace_name);
298 // Skip to end of the definition and eat the ';'.
299 SkipUntil(tok::semi);
Craig Topper161e4db2014-05-21 06:02:52 +0000300 return nullptr;
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000301 }
302
Matthias Gehredc01bb42017-03-17 21:41:20 +0000303 if (SS.isInvalid()) {
304 // Diagnostics have been emitted in ParseOptionalCXXScopeSpecifier.
305 // Skip to end of the definition and eat the ';'.
306 SkipUntil(tok::semi);
307 return nullptr;
308 }
309
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000310 // Parse identifier.
Anders Carlsson47952ae2009-03-28 22:53:22 +0000311 IdentifierInfo *Ident = Tok.getIdentifierInfo();
312 SourceLocation IdentLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000313
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000314 // Eat the ';'.
Chris Lattner49836b42009-04-02 04:16:50 +0000315 DeclEnd = Tok.getLocation();
Alp Toker383d2c42014-01-01 03:08:43 +0000316 if (ExpectAndConsume(tok::semi, diag::err_expected_semi_after_namespace_name))
317 SkipUntil(tok::semi);
Mike Stump11289f42009-09-09 15:08:12 +0000318
Craig Topperff354282015-11-14 18:16:00 +0000319 return Actions.ActOnNamespaceAliasDef(getCurScope(), NamespaceLoc, AliasLoc,
320 Alias, SS, IdentLoc, Ident);
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000321}
322
Chris Lattner38376f12008-01-12 07:05:38 +0000323/// ParseLinkage - We know that the current token is a string_literal
324/// and just before that, that extern was seen.
325///
326/// linkage-specification: [C++ 7.5p2: dcl.link]
327/// 'extern' string-literal '{' declaration-seq[opt] '}'
328/// 'extern' string-literal declaration
329///
Faisal Vali421b2d12017-12-29 05:41:00 +0000330Decl *Parser::ParseLinkage(ParsingDeclSpec &DS, DeclaratorContext Context) {
Richard Smith4ee696d2014-02-17 23:25:27 +0000331 assert(isTokenStringLiteral() && "Not a string literal!");
332 ExprResult Lang = ParseStringLiteralExpression(false);
Chris Lattner38376f12008-01-12 07:05:38 +0000333
Douglas Gregor07665a62009-01-05 19:45:36 +0000334 ParseScope LinkageScope(this, Scope::DeclScope);
Richard Smith4ee696d2014-02-17 23:25:27 +0000335 Decl *LinkageSpec =
336 Lang.isInvalid()
Craig Topper161e4db2014-05-21 06:02:52 +0000337 ? nullptr
Richard Smith4ee696d2014-02-17 23:25:27 +0000338 : Actions.ActOnStartLinkageSpecification(
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000339 getCurScope(), DS.getSourceRange().getBegin(), Lang.get(),
Richard Smith4ee696d2014-02-17 23:25:27 +0000340 Tok.is(tok::l_brace) ? Tok.getLocation() : SourceLocation());
Douglas Gregor07665a62009-01-05 19:45:36 +0000341
John McCall084e83d2011-03-24 11:26:52 +0000342 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +0000343 MaybeParseCXX11Attributes(attrs);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000344
Douglas Gregor07665a62009-01-05 19:45:36 +0000345 if (Tok.isNot(tok::l_brace)) {
Abramo Bagnara4d423992011-05-01 16:25:54 +0000346 // Reset the source range in DS, as the leading "extern"
347 // does not really belong to the inner declaration ...
348 DS.SetRangeStart(SourceLocation());
349 DS.SetRangeEnd(SourceLocation());
350 // ... but anyway remember that such an "extern" was seen.
Abramo Bagnaraed5b6892010-07-30 16:47:02 +0000351 DS.setExternInLinkageSpec(true);
John McCall53fa7142010-12-24 02:08:15 +0000352 ParseExternalDeclaration(attrs, &DS);
Richard Smith4ee696d2014-02-17 23:25:27 +0000353 return LinkageSpec ? Actions.ActOnFinishLinkageSpecification(
354 getCurScope(), LinkageSpec, SourceLocation())
Craig Topper161e4db2014-05-21 06:02:52 +0000355 : nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000356 }
Douglas Gregor29ff7d02008-12-16 22:23:02 +0000357
Douglas Gregorb65a9132010-02-07 08:38:28 +0000358 DS.abort();
359
John McCall53fa7142010-12-24 02:08:15 +0000360 ProhibitAttributes(attrs);
Alexis Hunt96d5c762009-11-21 08:43:09 +0000361
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000362 BalancedDelimiterTracker T(*this, tok::l_brace);
363 T.consumeOpen();
Richard Smith77944862014-03-02 05:58:18 +0000364
365 unsigned NestedModules = 0;
366 while (true) {
367 switch (Tok.getKind()) {
368 case tok::annot_module_begin:
369 ++NestedModules;
370 ParseTopLevelDecl();
371 continue;
372
373 case tok::annot_module_end:
374 if (!NestedModules)
375 break;
376 --NestedModules;
377 ParseTopLevelDecl();
378 continue;
379
380 case tok::annot_module_include:
381 ParseTopLevelDecl();
382 continue;
383
384 case tok::eof:
385 break;
386
387 case tok::r_brace:
388 if (!NestedModules)
389 break;
Reid Kleckner4dc0b1a2018-11-01 19:54:45 +0000390 LLVM_FALLTHROUGH;
Richard Smith77944862014-03-02 05:58:18 +0000391 default:
392 ParsedAttributesWithRange attrs(AttrFactory);
393 MaybeParseCXX11Attributes(attrs);
Richard Smith77944862014-03-02 05:58:18 +0000394 ParseExternalDeclaration(attrs);
395 continue;
396 }
397
398 break;
Chris Lattner38376f12008-01-12 07:05:38 +0000399 }
400
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000401 T.consumeClose();
Richard Smith4ee696d2014-02-17 23:25:27 +0000402 return LinkageSpec ? Actions.ActOnFinishLinkageSpecification(
403 getCurScope(), LinkageSpec, T.getCloseLocation())
Craig Topper161e4db2014-05-21 06:02:52 +0000404 : nullptr;
Chris Lattner38376f12008-01-12 07:05:38 +0000405}
Douglas Gregor556877c2008-04-13 21:30:24 +0000406
Richard Smith8df390f2016-09-08 23:14:54 +0000407/// Parse a C++ Modules TS export-declaration.
408///
409/// export-declaration:
410/// 'export' declaration
411/// 'export' '{' declaration-seq[opt] '}'
412///
413Decl *Parser::ParseExportDeclaration() {
414 assert(Tok.is(tok::kw_export));
415 SourceLocation ExportLoc = ConsumeToken();
416
417 ParseScope ExportScope(this, Scope::DeclScope);
418 Decl *ExportDecl = Actions.ActOnStartExportDecl(
419 getCurScope(), ExportLoc,
420 Tok.is(tok::l_brace) ? Tok.getLocation() : SourceLocation());
421
422 if (Tok.isNot(tok::l_brace)) {
423 // FIXME: Factor out a ParseExternalDeclarationWithAttrs.
424 ParsedAttributesWithRange Attrs(AttrFactory);
425 MaybeParseCXX11Attributes(Attrs);
426 MaybeParseMicrosoftAttributes(Attrs);
427 ParseExternalDeclaration(Attrs);
428 return Actions.ActOnFinishExportDecl(getCurScope(), ExportDecl,
429 SourceLocation());
430 }
431
432 BalancedDelimiterTracker T(*this, tok::l_brace);
433 T.consumeOpen();
434
435 // The Modules TS draft says "An export-declaration shall declare at least one
436 // entity", but the intent is that it shall contain at least one declaration.
437 if (Tok.is(tok::r_brace))
438 Diag(ExportLoc, diag::err_export_empty)
439 << SourceRange(ExportLoc, Tok.getLocation());
440
441 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
442 Tok.isNot(tok::eof)) {
443 ParsedAttributesWithRange Attrs(AttrFactory);
444 MaybeParseCXX11Attributes(Attrs);
445 MaybeParseMicrosoftAttributes(Attrs);
446 ParseExternalDeclaration(Attrs);
447 }
448
449 T.consumeClose();
450 return Actions.ActOnFinishExportDecl(getCurScope(), ExportDecl,
451 T.getCloseLocation());
452}
453
Douglas Gregord7c4d982008-12-30 03:27:21 +0000454/// ParseUsingDirectiveOrDeclaration - Parse C++ using using-declaration or
455/// using-directive. Assumes that current token is 'using'.
Richard Smith6f1daa42016-12-16 00:58:48 +0000456Parser::DeclGroupPtrTy
Faisal Vali421b2d12017-12-29 05:41:00 +0000457Parser::ParseUsingDirectiveOrDeclaration(DeclaratorContext Context,
John McCall9b72f892010-11-10 02:40:36 +0000458 const ParsedTemplateInfo &TemplateInfo,
Richard Smith6f1daa42016-12-16 00:58:48 +0000459 SourceLocation &DeclEnd,
460 ParsedAttributesWithRange &attrs) {
Douglas Gregord7c4d982008-12-30 03:27:21 +0000461 assert(Tok.is(tok::kw_using) && "Not using token");
Fariborz Jahanian4bf82622011-08-22 17:59:19 +0000462 ObjCDeclContextSwitch ObjCDC(*this);
Fangrui Song6907ce22018-07-30 19:24:48 +0000463
Douglas Gregord7c4d982008-12-30 03:27:21 +0000464 // Eat 'using'.
465 SourceLocation UsingLoc = ConsumeToken();
466
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000467 if (Tok.is(tok::code_completion)) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000468 Actions.CodeCompleteUsing(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000469 cutOffParsing();
Craig Topper161e4db2014-05-21 06:02:52 +0000470 return nullptr;
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000471 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000472
John McCall9b72f892010-11-10 02:40:36 +0000473 // 'using namespace' means this is a using-directive.
474 if (Tok.is(tok::kw_namespace)) {
475 // Template parameters are always an error here.
476 if (TemplateInfo.Kind) {
477 SourceRange R = TemplateInfo.getSourceRange();
Craig Topper54a6a682015-11-14 18:16:08 +0000478 Diag(UsingLoc, diag::err_templated_using_directive_declaration)
479 << 0 /* directive */ << R << FixItHint::CreateRemoval(R);
John McCall9b72f892010-11-10 02:40:36 +0000480 }
Alexis Hunt96d5c762009-11-21 08:43:09 +0000481
Richard Smith6f1daa42016-12-16 00:58:48 +0000482 Decl *UsingDir = ParseUsingDirective(Context, UsingLoc, DeclEnd, attrs);
483 return Actions.ConvertDeclToDeclGroup(UsingDir);
John McCall9b72f892010-11-10 02:40:36 +0000484 }
485
Richard Smithdda56e42011-04-15 14:24:37 +0000486 // Otherwise, it must be a using-declaration or an alias-declaration.
John McCall9b72f892010-11-10 02:40:36 +0000487
488 // Using declarations can't have attributes.
John McCall53fa7142010-12-24 02:08:15 +0000489 ProhibitAttributes(attrs);
Chris Lattner9b01ca12009-01-06 06:55:51 +0000490
Fariborz Jahanian4bf82622011-08-22 17:59:19 +0000491 return ParseUsingDeclaration(Context, TemplateInfo, UsingLoc, DeclEnd,
Richard Smith6f1daa42016-12-16 00:58:48 +0000492 AS_none);
Douglas Gregord7c4d982008-12-30 03:27:21 +0000493}
494
495/// ParseUsingDirective - Parse C++ using-directive, assumes
496/// that current token is 'namespace' and 'using' was already parsed.
497///
498/// using-directive: [C++ 7.3.p4: namespace.udir]
499/// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
500/// namespace-name ;
501/// [GNU] using-directive:
502/// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
503/// namespace-name attributes[opt] ;
504///
Faisal Vali421b2d12017-12-29 05:41:00 +0000505Decl *Parser::ParseUsingDirective(DeclaratorContext Context,
John McCall9b72f892010-11-10 02:40:36 +0000506 SourceLocation UsingLoc,
507 SourceLocation &DeclEnd,
John McCall53fa7142010-12-24 02:08:15 +0000508 ParsedAttributes &attrs) {
Douglas Gregord7c4d982008-12-30 03:27:21 +0000509 assert(Tok.is(tok::kw_namespace) && "Not 'namespace' token");
510
511 // Eat 'namespace'.
512 SourceLocation NamespcLoc = ConsumeToken();
513
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000514 if (Tok.is(tok::code_completion)) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000515 Actions.CodeCompleteUsingDirective(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000516 cutOffParsing();
Craig Topper161e4db2014-05-21 06:02:52 +0000517 return nullptr;
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000518 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000519
Douglas Gregord7c4d982008-12-30 03:27:21 +0000520 CXXScopeSpec SS;
521 // Parse (optional) nested-name-specifier.
Matthias Gehredc01bb42017-03-17 21:41:20 +0000522 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false,
523 /*MayBePseudoDestructor=*/nullptr,
524 /*IsTypename=*/false,
525 /*LastII=*/nullptr,
526 /*OnlyNamespace=*/true);
Douglas Gregord7c4d982008-12-30 03:27:21 +0000527
Craig Topper161e4db2014-05-21 06:02:52 +0000528 IdentifierInfo *NamespcName = nullptr;
Douglas Gregord7c4d982008-12-30 03:27:21 +0000529 SourceLocation IdentLoc = SourceLocation();
530
531 // Parse namespace-name.
Matthias Gehredc01bb42017-03-17 21:41:20 +0000532 if (Tok.isNot(tok::identifier)) {
Douglas Gregord7c4d982008-12-30 03:27:21 +0000533 Diag(Tok, diag::err_expected_namespace_name);
534 // If there was invalid namespace name, skip to end of decl, and eat ';'.
535 SkipUntil(tok::semi);
536 // FIXME: Are there cases, when we would like to call ActOnUsingDirective?
Craig Topper161e4db2014-05-21 06:02:52 +0000537 return nullptr;
Douglas Gregord7c4d982008-12-30 03:27:21 +0000538 }
Mike Stump11289f42009-09-09 15:08:12 +0000539
Matthias Gehredc01bb42017-03-17 21:41:20 +0000540 if (SS.isInvalid()) {
541 // Diagnostics have been emitted in ParseOptionalCXXScopeSpecifier.
542 // Skip to end of the definition and eat the ';'.
543 SkipUntil(tok::semi);
544 return nullptr;
545 }
546
Chris Lattnerce1da2c2009-01-06 07:27:21 +0000547 // Parse identifier.
548 NamespcName = Tok.getIdentifierInfo();
549 IdentLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000550
Chris Lattnerce1da2c2009-01-06 07:27:21 +0000551 // Parse (optional) attributes (most likely GNU strong-using extension).
Alexis Hunt96d5c762009-11-21 08:43:09 +0000552 bool GNUAttr = false;
553 if (Tok.is(tok::kw___attribute)) {
554 GNUAttr = true;
John McCall53fa7142010-12-24 02:08:15 +0000555 ParseGNUAttributes(attrs);
Alexis Hunt96d5c762009-11-21 08:43:09 +0000556 }
Mike Stump11289f42009-09-09 15:08:12 +0000557
Chris Lattnerce1da2c2009-01-06 07:27:21 +0000558 // Eat ';'.
Chris Lattner49836b42009-04-02 04:16:50 +0000559 DeclEnd = Tok.getLocation();
Alp Toker383d2c42014-01-01 03:08:43 +0000560 if (ExpectAndConsume(tok::semi,
561 GNUAttr ? diag::err_expected_semi_after_attribute_list
562 : diag::err_expected_semi_after_namespace_name))
563 SkipUntil(tok::semi);
Douglas Gregord7c4d982008-12-30 03:27:21 +0000564
Douglas Gregor0be31a22010-07-02 17:43:08 +0000565 return Actions.ActOnUsingDirective(getCurScope(), UsingLoc, NamespcLoc, SS,
Erich Keanec480f302018-07-12 21:09:05 +0000566 IdentLoc, NamespcName, attrs);
Douglas Gregord7c4d982008-12-30 03:27:21 +0000567}
568
Richard Smith6f1daa42016-12-16 00:58:48 +0000569/// Parse a using-declarator (or the identifier in a C++11 alias-declaration).
Douglas Gregord7c4d982008-12-30 03:27:21 +0000570///
Richard Smith6f1daa42016-12-16 00:58:48 +0000571/// using-declarator:
572/// 'typename'[opt] nested-name-specifier unqualified-id
Douglas Gregord7c4d982008-12-30 03:27:21 +0000573///
Faisal Vali421b2d12017-12-29 05:41:00 +0000574bool Parser::ParseUsingDeclarator(DeclaratorContext Context,
575 UsingDeclarator &D) {
Richard Smith6f1daa42016-12-16 00:58:48 +0000576 D.clear();
Douglas Gregorfec52632009-06-20 00:51:54 +0000577
578 // Ignore optional 'typename'.
Douglas Gregor220f4272009-11-04 16:30:06 +0000579 // FIXME: This is wrong; we should parse this as a typename-specifier.
Richard Smith6f1daa42016-12-16 00:58:48 +0000580 TryConsumeToken(tok::kw_typename, D.TypenameLoc);
Douglas Gregorfec52632009-06-20 00:51:54 +0000581
Nikola Smiljanic67860242014-09-26 00:28:20 +0000582 if (Tok.is(tok::kw___super)) {
583 Diag(Tok.getLocation(), diag::err_super_in_using_declaration);
Richard Smith6f1daa42016-12-16 00:58:48 +0000584 return true;
Nikola Smiljanic67860242014-09-26 00:28:20 +0000585 }
586
Douglas Gregorfec52632009-06-20 00:51:54 +0000587 // Parse nested-name-specifier.
Craig Topper161e4db2014-05-21 06:02:52 +0000588 IdentifierInfo *LastII = nullptr;
Richard Smith6f1daa42016-12-16 00:58:48 +0000589 ParseOptionalCXXScopeSpecifier(D.SS, nullptr, /*EnteringContext=*/false,
Craig Topper161e4db2014-05-21 06:02:52 +0000590 /*MayBePseudoDtor=*/nullptr,
591 /*IsTypename=*/false,
Richard Smith7447af42013-03-26 01:15:19 +0000592 /*LastII=*/&LastII);
Richard Smith6f1daa42016-12-16 00:58:48 +0000593 if (D.SS.isInvalid())
594 return true;
Richard Smith7447af42013-03-26 01:15:19 +0000595
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000596 // Parse the unqualified-id. We allow parsing of both constructor and
Douglas Gregor220f4272009-11-04 16:30:06 +0000597 // destructor names and allow the action module to diagnose any semantic
598 // errors.
Richard Smith7447af42013-03-26 01:15:19 +0000599 //
600 // C++11 [class.qual]p2:
601 // [...] in a using-declaration that is a member-declaration, if the name
602 // specified after the nested-name-specifier is the same as the identifier
603 // or the simple-template-id's template-name in the last component of the
604 // nested-name-specifier, the name is [...] considered to name the
605 // constructor.
Faisal Vali421b2d12017-12-29 05:41:00 +0000606 if (getLangOpts().CPlusPlus11 &&
607 Context == DeclaratorContext::MemberContext &&
Richard Smith151c4562016-12-20 21:35:28 +0000608 Tok.is(tok::identifier) &&
609 (NextToken().is(tok::semi) || NextToken().is(tok::comma) ||
610 NextToken().is(tok::ellipsis)) &&
Richard Smith6f1daa42016-12-16 00:58:48 +0000611 D.SS.isNotEmpty() && LastII == Tok.getIdentifierInfo() &&
612 !D.SS.getScopeRep()->getAsNamespace() &&
613 !D.SS.getScopeRep()->getAsNamespaceAlias()) {
Richard Smith7447af42013-03-26 01:15:19 +0000614 SourceLocation IdLoc = ConsumeToken();
Richard Smith6f1daa42016-12-16 00:58:48 +0000615 ParsedType Type =
616 Actions.getInheritingConstructorName(D.SS, IdLoc, *LastII);
617 D.Name.setConstructorName(Type, IdLoc, IdLoc);
618 } else {
619 if (ParseUnqualifiedId(
620 D.SS, /*EnteringContext=*/false,
621 /*AllowDestructorName=*/true,
622 /*AllowConstructorName=*/!(Tok.is(tok::identifier) &&
623 NextToken().is(tok::equal)),
Richard Smith35845152017-02-07 01:37:30 +0000624 /*AllowDeductionGuide=*/false,
Richard Smithc08b6932018-04-27 02:00:13 +0000625 nullptr, nullptr, D.Name))
Richard Smith6f1daa42016-12-16 00:58:48 +0000626 return true;
Douglas Gregorfec52632009-06-20 00:51:54 +0000627 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000628
Richard Smith151c4562016-12-20 21:35:28 +0000629 if (TryConsumeToken(tok::ellipsis, D.EllipsisLoc))
Aaron Ballmanc351fba2017-12-04 20:27:34 +0000630 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17 ?
Richard Smithb115e5d2017-08-13 23:37:29 +0000631 diag::warn_cxx17_compat_using_declaration_pack :
Richard Smith151c4562016-12-20 21:35:28 +0000632 diag::ext_using_declaration_pack);
Richard Smith6f1daa42016-12-16 00:58:48 +0000633
634 return false;
635}
636
637/// ParseUsingDeclaration - Parse C++ using-declaration or alias-declaration.
638/// Assumes that 'using' was already seen.
639///
640/// using-declaration: [C++ 7.3.p3: namespace.udecl]
641/// 'using' using-declarator-list[opt] ;
642///
643/// using-declarator-list: [C++1z]
644/// using-declarator '...'[opt]
645/// using-declarator-list ',' using-declarator '...'[opt]
646///
647/// using-declarator-list: [C++98-14]
648/// using-declarator
649///
650/// alias-declaration: C++11 [dcl.dcl]p1
651/// 'using' identifier attribute-specifier-seq[opt] = type-id ;
652///
653Parser::DeclGroupPtrTy
Faisal Vali421b2d12017-12-29 05:41:00 +0000654Parser::ParseUsingDeclaration(DeclaratorContext Context,
Richard Smith6f1daa42016-12-16 00:58:48 +0000655 const ParsedTemplateInfo &TemplateInfo,
656 SourceLocation UsingLoc, SourceLocation &DeclEnd,
657 AccessSpecifier AS) {
658 // Check for misplaced attributes before the identifier in an
659 // alias-declaration.
660 ParsedAttributesWithRange MisplacedAttrs(AttrFactory);
661 MaybeParseCXX11Attributes(MisplacedAttrs);
662
663 UsingDeclarator D;
664 bool InvalidDeclarator = ParseUsingDeclarator(Context, D);
665
Richard Smithc2c8bb82013-10-15 01:34:54 +0000666 ParsedAttributesWithRange Attrs(AttrFactory);
Richard Smith37a45dd2013-10-24 01:21:09 +0000667 MaybeParseGNUAttributes(Attrs);
Richard Smith54ecd982013-02-20 19:22:51 +0000668 MaybeParseCXX11Attributes(Attrs);
Richard Smithdda56e42011-04-15 14:24:37 +0000669
670 // Maybe this is an alias-declaration.
Richard Smith6f1daa42016-12-16 00:58:48 +0000671 if (Tok.is(tok::equal)) {
672 if (InvalidDeclarator) {
673 SkipUntil(tok::semi);
674 return nullptr;
675 }
676
Richard Smithc2c8bb82013-10-15 01:34:54 +0000677 // If we had any misplaced attributes from earlier, this is where they
678 // should have been written.
679 if (MisplacedAttrs.Range.isValid()) {
680 Diag(MisplacedAttrs.Range.getBegin(), diag::err_attributes_not_allowed)
681 << FixItHint::CreateInsertionFromRange(
682 Tok.getLocation(),
683 CharSourceRange::getTokenRange(MisplacedAttrs.Range))
684 << FixItHint::CreateRemoval(MisplacedAttrs.Range);
685 Attrs.takeAllFrom(MisplacedAttrs);
686 }
687
Richard Smith6f1daa42016-12-16 00:58:48 +0000688 Decl *DeclFromDeclSpec = nullptr;
689 Decl *AD = ParseAliasDeclarationAfterDeclarator(
690 TemplateInfo, UsingLoc, D, DeclEnd, AS, Attrs, &DeclFromDeclSpec);
691 return Actions.ConvertDeclToDeclGroup(AD, DeclFromDeclSpec);
Alexis Hunt6aa9bee2012-06-23 05:07:58 +0000692 }
Mike Stump11289f42009-09-09 15:08:12 +0000693
Richard Smith6f1daa42016-12-16 00:58:48 +0000694 // C++11 attributes are not allowed on a using-declaration, but GNU ones
695 // are.
696 ProhibitAttributes(MisplacedAttrs);
697 ProhibitAttributes(Attrs);
Douglas Gregorfec52632009-06-20 00:51:54 +0000698
John McCall9b72f892010-11-10 02:40:36 +0000699 // Diagnose an attempt to declare a templated using-declaration.
Richard Smith810ad3e2013-01-29 10:02:16 +0000700 // In C++11, alias-declarations can be templates:
Richard Smithdda56e42011-04-15 14:24:37 +0000701 // template <...> using id = type;
Richard Smith6f1daa42016-12-16 00:58:48 +0000702 if (TemplateInfo.Kind) {
John McCall9b72f892010-11-10 02:40:36 +0000703 SourceRange R = TemplateInfo.getSourceRange();
Craig Topper54a6a682015-11-14 18:16:08 +0000704 Diag(UsingLoc, diag::err_templated_using_directive_declaration)
705 << 1 /* declaration */ << R << FixItHint::CreateRemoval(R);
John McCall9b72f892010-11-10 02:40:36 +0000706
707 // Unfortunately, we have to bail out instead of recovering by
708 // ignoring the parameters, just in case the nested name specifier
709 // depends on the parameters.
Craig Topper161e4db2014-05-21 06:02:52 +0000710 return nullptr;
John McCall9b72f892010-11-10 02:40:36 +0000711 }
712
Richard Smith6f1daa42016-12-16 00:58:48 +0000713 SmallVector<Decl *, 8> DeclsInGroup;
714 while (true) {
715 // Parse (optional) attributes (most likely GNU strong-using extension).
716 MaybeParseGNUAttributes(Attrs);
717
718 if (InvalidDeclarator)
719 SkipUntil(tok::comma, tok::semi, StopBeforeMatch);
720 else {
721 // "typename" keyword is allowed for identifiers only,
722 // because it may be a type definition.
723 if (D.TypenameLoc.isValid() &&
Faisal Vali2ab8c152017-12-30 04:15:27 +0000724 D.Name.getKind() != UnqualifiedIdKind::IK_Identifier) {
Richard Smith6f1daa42016-12-16 00:58:48 +0000725 Diag(D.Name.getSourceRange().getBegin(),
726 diag::err_typename_identifiers_only)
727 << FixItHint::CreateRemoval(SourceRange(D.TypenameLoc));
728 // Proceed parsing, but discard the typename keyword.
729 D.TypenameLoc = SourceLocation();
730 }
731
Richard Smith151c4562016-12-20 21:35:28 +0000732 Decl *UD = Actions.ActOnUsingDeclaration(getCurScope(), AS, UsingLoc,
733 D.TypenameLoc, D.SS, D.Name,
Erich Keanec480f302018-07-12 21:09:05 +0000734 D.EllipsisLoc, Attrs);
Richard Smith6f1daa42016-12-16 00:58:48 +0000735 if (UD)
736 DeclsInGroup.push_back(UD);
737 }
738
739 if (!TryConsumeToken(tok::comma))
740 break;
741
742 // Parse another using-declarator.
743 Attrs.clear();
744 InvalidDeclarator = ParseUsingDeclarator(Context, D);
Douglas Gregor882a61a2011-09-26 14:30:28 +0000745 }
746
Richard Smith6f1daa42016-12-16 00:58:48 +0000747 if (DeclsInGroup.size() > 1)
Aaron Ballmanc351fba2017-12-04 20:27:34 +0000748 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17 ?
Richard Smithb115e5d2017-08-13 23:37:29 +0000749 diag::warn_cxx17_compat_multi_using_declaration :
Richard Smith6f1daa42016-12-16 00:58:48 +0000750 diag::ext_multi_using_declaration);
751
752 // Eat ';'.
753 DeclEnd = Tok.getLocation();
754 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
755 !Attrs.empty() ? "attributes list"
756 : "using declaration"))
757 SkipUntil(tok::semi);
758
Richard Smith3beb7c62017-01-12 02:27:38 +0000759 return Actions.BuildDeclaratorGroup(DeclsInGroup);
Richard Smith6f1daa42016-12-16 00:58:48 +0000760}
761
Richard Smith6f1daa42016-12-16 00:58:48 +0000762Decl *Parser::ParseAliasDeclarationAfterDeclarator(
763 const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc,
764 UsingDeclarator &D, SourceLocation &DeclEnd, AccessSpecifier AS,
765 ParsedAttributes &Attrs, Decl **OwnedType) {
766 if (ExpectAndConsume(tok::equal)) {
767 SkipUntil(tok::semi);
768 return nullptr;
769 }
770
771 Diag(Tok.getLocation(), getLangOpts().CPlusPlus11 ?
772 diag::warn_cxx98_compat_alias_declaration :
773 diag::ext_alias_declaration);
774
775 // Type alias templates cannot be specialized.
776 int SpecKind = -1;
777 if (TemplateInfo.Kind == ParsedTemplateInfo::Template &&
Faisal Vali2ab8c152017-12-30 04:15:27 +0000778 D.Name.getKind() == UnqualifiedIdKind::IK_TemplateId)
Richard Smith6f1daa42016-12-16 00:58:48 +0000779 SpecKind = 0;
780 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization)
781 SpecKind = 1;
782 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
783 SpecKind = 2;
784 if (SpecKind != -1) {
785 SourceRange Range;
786 if (SpecKind == 0)
787 Range = SourceRange(D.Name.TemplateId->LAngleLoc,
788 D.Name.TemplateId->RAngleLoc);
789 else
790 Range = TemplateInfo.getSourceRange();
791 Diag(Range.getBegin(), diag::err_alias_declaration_specialization)
792 << SpecKind << Range;
793 SkipUntil(tok::semi);
794 return nullptr;
795 }
796
797 // Name must be an identifier.
Faisal Vali2ab8c152017-12-30 04:15:27 +0000798 if (D.Name.getKind() != UnqualifiedIdKind::IK_Identifier) {
Richard Smith6f1daa42016-12-16 00:58:48 +0000799 Diag(D.Name.StartLocation, diag::err_alias_declaration_not_identifier);
800 // No removal fixit: can't recover from this.
801 SkipUntil(tok::semi);
802 return nullptr;
803 } else if (D.TypenameLoc.isValid())
804 Diag(D.TypenameLoc, diag::err_alias_declaration_not_identifier)
805 << FixItHint::CreateRemoval(SourceRange(
806 D.TypenameLoc,
807 D.SS.isNotEmpty() ? D.SS.getEndLoc() : D.TypenameLoc));
808 else if (D.SS.isNotEmpty())
809 Diag(D.SS.getBeginLoc(), diag::err_alias_declaration_not_identifier)
810 << FixItHint::CreateRemoval(D.SS.getRange());
Richard Smith151c4562016-12-20 21:35:28 +0000811 if (D.EllipsisLoc.isValid())
812 Diag(D.EllipsisLoc, diag::err_alias_declaration_pack_expansion)
813 << FixItHint::CreateRemoval(SourceRange(D.EllipsisLoc));
Richard Smith6f1daa42016-12-16 00:58:48 +0000814
815 Decl *DeclFromDeclSpec = nullptr;
Faisal Vali421b2d12017-12-29 05:41:00 +0000816 TypeResult TypeAlias = ParseTypeName(
817 nullptr,
818 TemplateInfo.Kind ? DeclaratorContext::AliasTemplateContext
819 : DeclaratorContext::AliasDeclContext,
820 AS, &DeclFromDeclSpec, &Attrs);
Richard Smith6f1daa42016-12-16 00:58:48 +0000821 if (OwnedType)
822 *OwnedType = DeclFromDeclSpec;
823
824 // Eat ';'.
825 DeclEnd = Tok.getLocation();
826 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
827 !Attrs.empty() ? "attributes list"
828 : "alias declaration"))
829 SkipUntil(tok::semi);
830
831 TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
832 MultiTemplateParamsArg TemplateParamsArg(
833 TemplateParams ? TemplateParams->data() : nullptr,
834 TemplateParams ? TemplateParams->size() : 0);
835 return Actions.ActOnAliasDeclaration(getCurScope(), AS, TemplateParamsArg,
Erich Keanec480f302018-07-12 21:09:05 +0000836 UsingLoc, D.Name, Attrs, TypeAlias,
837 DeclFromDeclSpec);
Douglas Gregord7c4d982008-12-30 03:27:21 +0000838}
839
Benjamin Kramere56f3932011-12-23 17:00:35 +0000840/// ParseStaticAssertDeclaration - Parse C++0x or C11 static_assert-declaration.
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000841///
Peter Collingbourne3d9cbdc2011-04-15 00:35:57 +0000842/// [C++0x] static_assert-declaration:
843/// static_assert ( constant-expression , string-literal ) ;
844///
Benjamin Kramere56f3932011-12-23 17:00:35 +0000845/// [C11] static_assert-declaration:
Peter Collingbourne3d9cbdc2011-04-15 00:35:57 +0000846/// _Static_assert ( constant-expression , string-literal ) ;
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000847///
John McCall48871652010-08-21 09:40:31 +0000848Decl *Parser::ParseStaticAssertDeclaration(SourceLocation &DeclEnd){
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000849 assert(Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert) &&
Peter Collingbourne3d9cbdc2011-04-15 00:35:57 +0000850 "Not a static_assert declaration");
851
David Blaikiebbafb8a2012-03-11 07:00:24 +0000852 if (Tok.is(tok::kw__Static_assert) && !getLangOpts().C11)
Benjamin Kramere56f3932011-12-23 17:00:35 +0000853 Diag(Tok, diag::ext_c11_static_assert);
Richard Smithb15c11c2011-10-17 23:06:20 +0000854 if (Tok.is(tok::kw_static_assert))
855 Diag(Tok, diag::warn_cxx98_compat_static_assert);
Peter Collingbourne3d9cbdc2011-04-15 00:35:57 +0000856
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000857 SourceLocation StaticAssertLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000858
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000859 BalancedDelimiterTracker T(*this, tok::l_paren);
860 if (T.consumeOpen()) {
Alp Tokerec543272013-12-24 09:48:30 +0000861 Diag(Tok, diag::err_expected) << tok::l_paren;
Richard Smith76965712012-09-13 19:12:50 +0000862 SkipMalformedDecl();
Craig Topper161e4db2014-05-21 06:02:52 +0000863 return nullptr;
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000864 }
Mike Stump11289f42009-09-09 15:08:12 +0000865
Richard Smithb3018062017-06-06 01:34:24 +0000866 EnterExpressionEvaluationContext ConstantEvaluated(
867 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
868 ExprResult AssertExpr(ParseConstantExpressionInExprEvalContext());
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000869 if (AssertExpr.isInvalid()) {
Richard Smith76965712012-09-13 19:12:50 +0000870 SkipMalformedDecl();
Craig Topper161e4db2014-05-21 06:02:52 +0000871 return nullptr;
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000872 }
Mike Stump11289f42009-09-09 15:08:12 +0000873
Richard Smith085a64f2014-06-20 19:57:12 +0000874 ExprResult AssertMessage;
875 if (Tok.is(tok::r_paren)) {
Aaron Ballmanc351fba2017-12-04 20:27:34 +0000876 Diag(Tok, getLangOpts().CPlusPlus17
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000877 ? diag::warn_cxx14_compat_static_assert_no_message
Richard Smith085a64f2014-06-20 19:57:12 +0000878 : diag::ext_static_assert_no_message)
Aaron Ballmanc351fba2017-12-04 20:27:34 +0000879 << (getLangOpts().CPlusPlus17
Richard Smith085a64f2014-06-20 19:57:12 +0000880 ? FixItHint()
881 : FixItHint::CreateInsertion(Tok.getLocation(), ", \"\""));
882 } else {
883 if (ExpectAndConsume(tok::comma)) {
884 SkipUntil(tok::semi);
885 return nullptr;
886 }
Anders Carlssonb4cf3ad2009-03-13 23:29:20 +0000887
Richard Smith085a64f2014-06-20 19:57:12 +0000888 if (!isTokenStringLiteral()) {
889 Diag(Tok, diag::err_expected_string_literal)
890 << /*Source='static_assert'*/1;
891 SkipMalformedDecl();
892 return nullptr;
893 }
Mike Stump11289f42009-09-09 15:08:12 +0000894
Richard Smith085a64f2014-06-20 19:57:12 +0000895 AssertMessage = ParseStringLiteralExpression();
896 if (AssertMessage.isInvalid()) {
897 SkipMalformedDecl();
898 return nullptr;
899 }
Richard Smithd67aea22012-03-06 03:21:47 +0000900 }
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000901
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000902 T.consumeClose();
Mike Stump11289f42009-09-09 15:08:12 +0000903
Chris Lattner49836b42009-04-02 04:16:50 +0000904 DeclEnd = Tok.getLocation();
Douglas Gregor45d6bdf2010-09-07 15:23:11 +0000905 ExpectAndConsumeSemi(diag::err_expected_semi_after_static_assert);
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000906
John McCallb268a282010-08-23 23:25:46 +0000907 return Actions.ActOnStaticAssertDeclaration(StaticAssertLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000908 AssertExpr.get(),
909 AssertMessage.get(),
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000910 T.getCloseLocation());
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000911}
912
Richard Smith74aeef52013-04-26 16:15:35 +0000913/// ParseDecltypeSpecifier - Parse a C++11 decltype specifier.
Anders Carlsson74948d02009-06-24 17:47:40 +0000914///
915/// 'decltype' ( expression )
Richard Smith74aeef52013-04-26 16:15:35 +0000916/// 'decltype' ( 'auto' ) [C++1y]
Anders Carlsson74948d02009-06-24 17:47:40 +0000917///
David Blaikie15a430a2011-12-04 05:04:18 +0000918SourceLocation Parser::ParseDecltypeSpecifier(DeclSpec &DS) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000919 assert(Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)
David Blaikie15a430a2011-12-04 05:04:18 +0000920 && "Not a decltype specifier");
Fangrui Song6907ce22018-07-30 19:24:48 +0000921
David Blaikie15a430a2011-12-04 05:04:18 +0000922 ExprResult Result;
923 SourceLocation StartLoc = Tok.getLocation();
924 SourceLocation EndLoc;
925
926 if (Tok.is(tok::annot_decltype)) {
927 Result = getExprAnnotation(Tok);
928 EndLoc = Tok.getAnnotationEndLoc();
Richard Smithaf3b3252017-05-18 19:21:48 +0000929 ConsumeAnnotationToken();
David Blaikie15a430a2011-12-04 05:04:18 +0000930 if (Result.isInvalid()) {
931 DS.SetTypeSpecError();
932 return EndLoc;
933 }
934 } else {
Richard Smith324df552012-02-24 22:30:04 +0000935 if (Tok.getIdentifierInfo()->isStr("decltype"))
936 Diag(Tok, diag::warn_cxx98_compat_decltype);
Richard Smithfd3da932012-02-24 18:10:23 +0000937
David Blaikie15a430a2011-12-04 05:04:18 +0000938 ConsumeToken();
939
940 BalancedDelimiterTracker T(*this, tok::l_paren);
941 if (T.expectAndConsume(diag::err_expected_lparen_after,
942 "decltype", tok::r_paren)) {
943 DS.SetTypeSpecError();
944 return T.getOpenLocation() == Tok.getLocation() ?
945 StartLoc : T.getOpenLocation();
946 }
947
Richard Smith74aeef52013-04-26 16:15:35 +0000948 // Check for C++1y 'decltype(auto)'.
949 if (Tok.is(tok::kw_auto)) {
950 // No need to disambiguate here: an expression can't start with 'auto',
951 // because the typename-specifier in a function-style cast operation can't
952 // be 'auto'.
953 Diag(Tok.getLocation(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000954 getLangOpts().CPlusPlus14
Richard Smith74aeef52013-04-26 16:15:35 +0000955 ? diag::warn_cxx11_compat_decltype_auto_type_specifier
956 : diag::ext_decltype_auto_type_specifier);
957 ConsumeToken();
958 } else {
959 // Parse the expression
David Blaikie15a430a2011-12-04 05:04:18 +0000960
Richard Smith74aeef52013-04-26 16:15:35 +0000961 // C++11 [dcl.type.simple]p4:
962 // The operand of the decltype specifier is an unevaluated operand.
Faisal Valid143a0c2017-04-01 21:30:49 +0000963 EnterExpressionEvaluationContext Unevaluated(
964 Actions, Sema::ExpressionEvaluationContext::Unevaluated, nullptr,
Nicolas Lesserb6d5c582018-07-12 18:45:41 +0000965 Sema::ExpressionEvaluationContextRecord::EK_Decltype);
Kaelyn Takata5cc85352015-04-10 19:16:46 +0000966 Result =
967 Actions.CorrectDelayedTyposInExpr(ParseExpression(), [](Expr *E) {
968 return E->hasPlaceholderType() ? ExprError() : E;
969 });
Richard Smith74aeef52013-04-26 16:15:35 +0000970 if (Result.isInvalid()) {
971 DS.SetTypeSpecError();
Alexey Bataevee6507d2013-11-18 08:17:37 +0000972 if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch)) {
Richard Smith74aeef52013-04-26 16:15:35 +0000973 EndLoc = ConsumeParen();
Argyrios Kyrtzidisc38395a2012-10-26 22:53:44 +0000974 } else {
Richard Smith74aeef52013-04-26 16:15:35 +0000975 if (PP.isBacktrackEnabled() && Tok.is(tok::semi)) {
976 // Backtrack to get the location of the last token before the semi.
977 PP.RevertCachedTokens(2);
978 ConsumeToken(); // the semi.
979 EndLoc = ConsumeAnyToken();
980 assert(Tok.is(tok::semi));
981 } else {
982 EndLoc = Tok.getLocation();
983 }
Argyrios Kyrtzidisc38395a2012-10-26 22:53:44 +0000984 }
Richard Smith74aeef52013-04-26 16:15:35 +0000985 return EndLoc;
Argyrios Kyrtzidisc38395a2012-10-26 22:53:44 +0000986 }
Richard Smith74aeef52013-04-26 16:15:35 +0000987
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000988 Result = Actions.ActOnDecltypeExpression(Result.get());
David Blaikie15a430a2011-12-04 05:04:18 +0000989 }
990
991 // Match the ')'
992 T.consumeClose();
993 if (T.getCloseLocation().isInvalid()) {
994 DS.SetTypeSpecError();
995 // FIXME: this should return the location of the last token
996 // that was consumed (by "consumeClose()")
997 return T.getCloseLocation();
998 }
999
Richard Smithfd555f62012-02-22 02:04:18 +00001000 if (Result.isInvalid()) {
1001 DS.SetTypeSpecError();
1002 return T.getCloseLocation();
1003 }
1004
David Blaikie15a430a2011-12-04 05:04:18 +00001005 EndLoc = T.getCloseLocation();
Anders Carlsson74948d02009-06-24 17:47:40 +00001006 }
Richard Smith74aeef52013-04-26 16:15:35 +00001007 assert(!Result.isInvalid());
Mike Stump11289f42009-09-09 15:08:12 +00001008
Craig Topper161e4db2014-05-21 06:02:52 +00001009 const char *PrevSpec = nullptr;
John McCall49bfce42009-08-03 20:12:06 +00001010 unsigned DiagID;
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001011 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
Anders Carlsson74948d02009-06-24 17:47:40 +00001012 // Check for duplicate type specifiers (e.g. "int decltype(a)").
Richard Smith74aeef52013-04-26 16:15:35 +00001013 if (Result.get()
1014 ? DS.SetTypeSpecType(DeclSpec::TST_decltype, StartLoc, PrevSpec,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001015 DiagID, Result.get(), Policy)
Richard Smith74aeef52013-04-26 16:15:35 +00001016 : DS.SetTypeSpecType(DeclSpec::TST_decltype_auto, StartLoc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001017 DiagID, Policy)) {
John McCall49bfce42009-08-03 20:12:06 +00001018 Diag(StartLoc, DiagID) << PrevSpec;
David Blaikie15a430a2011-12-04 05:04:18 +00001019 DS.SetTypeSpecError();
1020 }
1021 return EndLoc;
1022}
1023
Fangrui Song6907ce22018-07-30 19:24:48 +00001024void Parser::AnnotateExistingDecltypeSpecifier(const DeclSpec& DS,
David Blaikie15a430a2011-12-04 05:04:18 +00001025 SourceLocation StartLoc,
1026 SourceLocation EndLoc) {
1027 // make sure we have a token we can turn into an annotation token
1028 if (PP.isBacktrackEnabled())
1029 PP.RevertCachedTokens(1);
1030 else
1031 PP.EnterToken(Tok);
1032
1033 Tok.setKind(tok::annot_decltype);
Faisal Vali090da2d2018-01-01 18:23:28 +00001034 setExprAnnotation(Tok,
1035 DS.getTypeSpecType() == TST_decltype ? DS.getRepAsExpr() :
1036 DS.getTypeSpecType() == TST_decltype_auto ? ExprResult() :
1037 ExprError());
David Blaikie15a430a2011-12-04 05:04:18 +00001038 Tok.setAnnotationEndLoc(EndLoc);
1039 Tok.setLocation(StartLoc);
1040 PP.AnnotateCachedTokens(Tok);
Anders Carlsson74948d02009-06-24 17:47:40 +00001041}
1042
Alexis Hunt4a257072011-05-19 05:37:45 +00001043void Parser::ParseUnderlyingTypeSpecifier(DeclSpec &DS) {
1044 assert(Tok.is(tok::kw___underlying_type) &&
1045 "Not an underlying type specifier");
1046
1047 SourceLocation StartLoc = ConsumeToken();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001048 BalancedDelimiterTracker T(*this, tok::l_paren);
1049 if (T.expectAndConsume(diag::err_expected_lparen_after,
1050 "__underlying_type", tok::r_paren)) {
Alexis Hunt4a257072011-05-19 05:37:45 +00001051 return;
1052 }
1053
1054 TypeResult Result = ParseTypeName();
1055 if (Result.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00001056 SkipUntil(tok::r_paren, StopAtSemi);
Alexis Hunt4a257072011-05-19 05:37:45 +00001057 return;
1058 }
1059
1060 // Match the ')'
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001061 T.consumeClose();
1062 if (T.getCloseLocation().isInvalid())
Alexis Hunt4a257072011-05-19 05:37:45 +00001063 return;
1064
Craig Topper161e4db2014-05-21 06:02:52 +00001065 const char *PrevSpec = nullptr;
Alexis Hunt4a257072011-05-19 05:37:45 +00001066 unsigned DiagID;
Alexis Hunte852b102011-05-24 22:41:36 +00001067 if (DS.SetTypeSpecType(DeclSpec::TST_underlyingType, StartLoc, PrevSpec,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001068 DiagID, Result.get(),
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001069 Actions.getASTContext().getPrintingPolicy()))
Alexis Hunt4a257072011-05-19 05:37:45 +00001070 Diag(StartLoc, DiagID) << PrevSpec;
Enea Zaffanellaa90af722013-07-06 18:54:58 +00001071 DS.setTypeofParensRange(T.getRange());
Alexis Hunt4a257072011-05-19 05:37:45 +00001072}
1073
David Blaikie00ee7a082011-10-25 15:01:20 +00001074/// ParseBaseTypeSpecifier - Parse a C++ base-type-specifier which is either a
Fangrui Song6907ce22018-07-30 19:24:48 +00001075/// class name or decltype-specifier. Note that we only check that the result
1076/// names a type; semantic analysis will need to verify that the type names a
1077/// class. The result is either a type or null, depending on whether a type
David Blaikie00ee7a082011-10-25 15:01:20 +00001078/// name was found.
Douglas Gregor831c93f2008-11-05 20:51:48 +00001079///
Richard Smith4c96e992013-02-19 23:47:15 +00001080/// base-type-specifier: [C++11 class.derived]
David Blaikie00ee7a082011-10-25 15:01:20 +00001081/// class-or-decltype
Richard Smith4c96e992013-02-19 23:47:15 +00001082/// class-or-decltype: [C++11 class.derived]
David Blaikie00ee7a082011-10-25 15:01:20 +00001083/// nested-name-specifier[opt] class-name
1084/// decltype-specifier
Richard Smith4c96e992013-02-19 23:47:15 +00001085/// class-name: [C++ class.name]
Douglas Gregor831c93f2008-11-05 20:51:48 +00001086/// identifier
Douglas Gregord54dfb82009-02-25 23:52:28 +00001087/// simple-template-id
Mike Stump11289f42009-09-09 15:08:12 +00001088///
Richard Smith4c96e992013-02-19 23:47:15 +00001089/// In C++98, instead of base-type-specifier, we have:
1090///
1091/// ::[opt] nested-name-specifier[opt] class-name
Craig Topper9ad7e262014-10-31 06:57:07 +00001092TypeResult Parser::ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
1093 SourceLocation &EndLocation) {
David Blaikiedd58d4c2011-10-25 18:46:41 +00001094 // Ignore attempts to use typename
1095 if (Tok.is(tok::kw_typename)) {
1096 Diag(Tok, diag::err_expected_class_name_not_template)
1097 << FixItHint::CreateRemoval(Tok.getLocation());
1098 ConsumeToken();
1099 }
1100
David Blaikieafa155f2011-10-25 18:17:58 +00001101 // Parse optional nested-name-specifier
1102 CXXScopeSpec SS;
David Blaikieefdccaa2016-01-15 23:43:34 +00001103 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false);
David Blaikieafa155f2011-10-25 18:17:58 +00001104
1105 BaseLoc = Tok.getLocation();
1106
David Blaikie1cd50022011-10-25 17:10:12 +00001107 // Parse decltype-specifier
Fangrui Song6907ce22018-07-30 19:24:48 +00001108 // tok == kw_decltype is just error recovery, it can only happen when SS
David Blaikie15a430a2011-12-04 05:04:18 +00001109 // isn't empty
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001110 if (Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)) {
David Blaikieafa155f2011-10-25 18:17:58 +00001111 if (SS.isNotEmpty())
1112 Diag(SS.getBeginLoc(), diag::err_unexpected_scope_on_base_decltype)
1113 << FixItHint::CreateRemoval(SS.getRange());
David Blaikie1cd50022011-10-25 17:10:12 +00001114 // Fake up a Declarator to use with ActOnTypeName.
1115 DeclSpec DS(AttrFactory);
1116
David Blaikie7491e732011-12-08 04:53:15 +00001117 EndLocation = ParseDecltypeSpecifier(DS);
David Blaikie1cd50022011-10-25 17:10:12 +00001118
Faisal Vali421b2d12017-12-29 05:41:00 +00001119 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
David Blaikie1cd50022011-10-25 17:10:12 +00001120 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
1121 }
1122
Douglas Gregord54dfb82009-02-25 23:52:28 +00001123 // Check whether we have a template-id that names a type.
1124 if (Tok.is(tok::annot_template_id)) {
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00001125 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregor46c59612010-01-12 17:52:59 +00001126 if (TemplateId->Kind == TNK_Type_template ||
1127 TemplateId->Kind == TNK_Dependent_template_name) {
Richard Smith62559bd2017-02-01 21:36:38 +00001128 AnnotateTemplateIdTokenAsType(/*IsClassName*/true);
Douglas Gregord54dfb82009-02-25 23:52:28 +00001129
1130 assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
John McCallba7bf592010-08-24 05:47:05 +00001131 ParsedType Type = getTypeAnnotation(Tok);
Douglas Gregord54dfb82009-02-25 23:52:28 +00001132 EndLocation = Tok.getAnnotationEndLoc();
Richard Smithaf3b3252017-05-18 19:21:48 +00001133 ConsumeAnnotationToken();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001134
1135 if (Type)
1136 return Type;
1137 return true;
Douglas Gregord54dfb82009-02-25 23:52:28 +00001138 }
1139
1140 // Fall through to produce an error below.
1141 }
1142
Douglas Gregor831c93f2008-11-05 20:51:48 +00001143 if (Tok.isNot(tok::identifier)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00001144 Diag(Tok, diag::err_expected_class_name);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001145 return true;
Douglas Gregor831c93f2008-11-05 20:51:48 +00001146 }
1147
Douglas Gregor18473f32010-01-12 21:28:44 +00001148 IdentifierInfo *Id = Tok.getIdentifierInfo();
1149 SourceLocation IdLoc = ConsumeToken();
1150
1151 if (Tok.is(tok::less)) {
1152 // It looks the user intended to write a template-id here, but the
1153 // template-name was wrong. Try to fix that.
1154 TemplateNameKind TNK = TNK_Type_template;
1155 TemplateTy Template;
Douglas Gregor0be31a22010-07-02 17:43:08 +00001156 if (!Actions.DiagnoseUnknownTemplateName(*Id, IdLoc, getCurScope(),
Douglas Gregore7c20652011-03-02 00:47:37 +00001157 &SS, Template, TNK)) {
Douglas Gregor18473f32010-01-12 21:28:44 +00001158 Diag(IdLoc, diag::err_unknown_template_name)
1159 << Id;
1160 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001161
Serge Pavlovb716b3c2013-08-10 05:54:47 +00001162 if (!Template) {
1163 TemplateArgList TemplateArgs;
1164 SourceLocation LAngleLoc, RAngleLoc;
Richard Smith9a420f92017-05-10 21:47:30 +00001165 ParseTemplateIdAfterTemplateName(true, LAngleLoc, TemplateArgs,
1166 RAngleLoc);
Douglas Gregor18473f32010-01-12 21:28:44 +00001167 return true;
Serge Pavlovb716b3c2013-08-10 05:54:47 +00001168 }
Douglas Gregor18473f32010-01-12 21:28:44 +00001169
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001170 // Form the template name
Douglas Gregor18473f32010-01-12 21:28:44 +00001171 UnqualifiedId TemplateName;
1172 TemplateName.setIdentifier(Id, IdLoc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001173
Douglas Gregor18473f32010-01-12 21:28:44 +00001174 // Parse the full template-id, then turn it into a type.
Abramo Bagnara7945c982012-01-27 09:46:47 +00001175 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
Richard Smith62559bd2017-02-01 21:36:38 +00001176 TemplateName))
Douglas Gregor18473f32010-01-12 21:28:44 +00001177 return true;
Richard Smith62559bd2017-02-01 21:36:38 +00001178 if (TNK == TNK_Type_template || TNK == TNK_Dependent_template_name)
1179 AnnotateTemplateIdTokenAsType(/*IsClassName*/true);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001180
Douglas Gregor18473f32010-01-12 21:28:44 +00001181 // If we didn't end up with a typename token, there's nothing more we
1182 // can do.
1183 if (Tok.isNot(tok::annot_typename))
1184 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001185
Douglas Gregor18473f32010-01-12 21:28:44 +00001186 // Retrieve the type from the annotation token, consume that token, and
1187 // return.
1188 EndLocation = Tok.getAnnotationEndLoc();
John McCallba7bf592010-08-24 05:47:05 +00001189 ParsedType Type = getTypeAnnotation(Tok);
Richard Smithaf3b3252017-05-18 19:21:48 +00001190 ConsumeAnnotationToken();
Douglas Gregor18473f32010-01-12 21:28:44 +00001191 return Type;
1192 }
1193
Douglas Gregor831c93f2008-11-05 20:51:48 +00001194 // We have an identifier; check whether it is actually a type.
Craig Topper161e4db2014-05-21 06:02:52 +00001195 IdentifierInfo *CorrectedII = nullptr;
Richard Smith600b5262017-01-26 20:40:47 +00001196 ParsedType Type = Actions.getTypeName(
Richard Smith62559bd2017-02-01 21:36:38 +00001197 *Id, IdLoc, getCurScope(), &SS, /*IsClassName=*/true, false, nullptr,
Richard Smith600b5262017-01-26 20:40:47 +00001198 /*IsCtorOrDtorName=*/false,
1199 /*NonTrivialTypeSourceInfo=*/true,
1200 /*IsClassTemplateDeductionContext*/ false, &CorrectedII);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001201 if (!Type) {
Douglas Gregorfe17d252010-02-16 19:09:40 +00001202 Diag(IdLoc, diag::err_expected_class_name);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001203 return true;
Douglas Gregor831c93f2008-11-05 20:51:48 +00001204 }
1205
1206 // Consume the identifier.
Douglas Gregor18473f32010-01-12 21:28:44 +00001207 EndLocation = IdLoc;
Nick Lewycky19b9f952010-07-26 16:56:01 +00001208
1209 // Fake up a Declarator to use with ActOnTypeName.
John McCall084e83d2011-03-24 11:26:52 +00001210 DeclSpec DS(AttrFactory);
Nick Lewycky19b9f952010-07-26 16:56:01 +00001211 DS.SetRangeStart(IdLoc);
1212 DS.SetRangeEnd(EndLocation);
Douglas Gregore7c20652011-03-02 00:47:37 +00001213 DS.getTypeSpecScope() = SS;
Nick Lewycky19b9f952010-07-26 16:56:01 +00001214
Craig Topper161e4db2014-05-21 06:02:52 +00001215 const char *PrevSpec = nullptr;
Nick Lewycky19b9f952010-07-26 16:56:01 +00001216 unsigned DiagID;
Faisal Vali090da2d2018-01-01 18:23:28 +00001217 DS.SetTypeSpecType(TST_typename, IdLoc, PrevSpec, DiagID, Type,
1218 Actions.getASTContext().getPrintingPolicy());
Nick Lewycky19b9f952010-07-26 16:56:01 +00001219
Faisal Vali421b2d12017-12-29 05:41:00 +00001220 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
Nick Lewycky19b9f952010-07-26 16:56:01 +00001221 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
Douglas Gregor831c93f2008-11-05 20:51:48 +00001222}
1223
John McCall8d32c052012-05-22 21:28:12 +00001224void Parser::ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001225 while (Tok.isOneOf(tok::kw___single_inheritance,
1226 tok::kw___multiple_inheritance,
1227 tok::kw___virtual_inheritance)) {
John McCall8d32c052012-05-22 21:28:12 +00001228 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
1229 SourceLocation AttrNameLoc = ConsumeToken();
Craig Topper161e4db2014-05-21 06:02:52 +00001230 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
Erich Keanee891aa92018-07-13 15:07:47 +00001231 ParsedAttr::AS_Keyword);
John McCall8d32c052012-05-22 21:28:12 +00001232 }
1233}
1234
Richard Smith369b9f92012-06-25 21:37:02 +00001235/// Determine whether the following tokens are valid after a type-specifier
1236/// which could be a standalone declaration. This will conservatively return
1237/// true if there's any doubt, and is appropriate for insert-';' fixits.
Richard Smith200f47c2012-07-02 19:14:01 +00001238bool Parser::isValidAfterTypeSpecifier(bool CouldBeBitfield) {
Richard Smith369b9f92012-06-25 21:37:02 +00001239 // This switch enumerates the valid "follow" set for type-specifiers.
1240 switch (Tok.getKind()) {
1241 default: break;
1242 case tok::semi: // struct foo {...} ;
1243 case tok::star: // struct foo {...} * P;
1244 case tok::amp: // struct foo {...} & R = ...
Richard Smith1ac67d12013-01-19 03:48:05 +00001245 case tok::ampamp: // struct foo {...} && R = ...
Richard Smith369b9f92012-06-25 21:37:02 +00001246 case tok::identifier: // struct foo {...} V ;
1247 case tok::r_paren: //(struct foo {...} ) {4}
1248 case tok::annot_cxxscope: // struct foo {...} a:: b;
1249 case tok::annot_typename: // struct foo {...} a ::b;
1250 case tok::annot_template_id: // struct foo {...} a<int> ::b;
1251 case tok::l_paren: // struct foo {...} ( x);
1252 case tok::comma: // __builtin_offsetof(struct foo{...} ,
Richard Smith1ac67d12013-01-19 03:48:05 +00001253 case tok::kw_operator: // struct foo operator ++() {...}
Alp Tokerd3f79c52013-11-24 20:24:54 +00001254 case tok::kw___declspec: // struct foo {...} __declspec(...)
Richard Smith843f18f2014-08-13 02:13:15 +00001255 case tok::l_square: // void f(struct f [ 3])
1256 case tok::ellipsis: // void f(struct f ... [Ns])
Abramo Bagnara152eb392014-08-16 08:29:27 +00001257 // FIXME: we should emit semantic diagnostic when declaration
1258 // attribute is in type attribute position.
1259 case tok::kw___attribute: // struct foo __attribute__((used)) x;
David Majnemer15b311c2016-06-14 03:20:28 +00001260 case tok::annot_pragma_pack: // struct foo {...} _Pragma(pack(pop));
1261 // struct foo {...} _Pragma(section(...));
1262 case tok::annot_pragma_ms_pragma:
1263 // struct foo {...} _Pragma(vtordisp(pop));
1264 case tok::annot_pragma_ms_vtordisp:
1265 // struct foo {...} _Pragma(pointers_to_members(...));
1266 case tok::annot_pragma_ms_pointers_to_members:
Richard Smith369b9f92012-06-25 21:37:02 +00001267 return true;
Richard Smith200f47c2012-07-02 19:14:01 +00001268 case tok::colon:
1269 return CouldBeBitfield; // enum E { ... } : 2;
Reid Klecknercfa91552016-03-21 16:08:49 +00001270 // Microsoft compatibility
1271 case tok::kw___cdecl: // struct foo {...} __cdecl x;
1272 case tok::kw___fastcall: // struct foo {...} __fastcall x;
1273 case tok::kw___stdcall: // struct foo {...} __stdcall x;
1274 case tok::kw___thiscall: // struct foo {...} __thiscall x;
1275 case tok::kw___vectorcall: // struct foo {...} __vectorcall x;
1276 // We will diagnose these calling-convention specifiers on non-function
1277 // declarations later, so claim they are valid after a type specifier.
1278 return getLangOpts().MicrosoftExt;
Richard Smith369b9f92012-06-25 21:37:02 +00001279 // Type qualifiers
1280 case tok::kw_const: // struct foo {...} const x;
1281 case tok::kw_volatile: // struct foo {...} volatile x;
1282 case tok::kw_restrict: // struct foo {...} restrict x;
Richard Smith843f18f2014-08-13 02:13:15 +00001283 case tok::kw__Atomic: // struct foo {...} _Atomic x;
Nico Rieck3e1ee832014-12-04 23:30:25 +00001284 case tok::kw___unaligned: // struct foo {...} __unaligned *x;
Richard Smith1ac67d12013-01-19 03:48:05 +00001285 // Function specifiers
1286 // Note, no 'explicit'. An explicit function must be either a conversion
1287 // operator or a constructor. Either way, it can't have a return type.
1288 case tok::kw_inline: // struct foo inline f();
1289 case tok::kw_virtual: // struct foo virtual f();
1290 case tok::kw_friend: // struct foo friend f();
Richard Smith369b9f92012-06-25 21:37:02 +00001291 // Storage-class specifiers
1292 case tok::kw_static: // struct foo {...} static x;
1293 case tok::kw_extern: // struct foo {...} extern x;
1294 case tok::kw_typedef: // struct foo {...} typedef x;
1295 case tok::kw_register: // struct foo {...} register x;
1296 case tok::kw_auto: // struct foo {...} auto x;
1297 case tok::kw_mutable: // struct foo {...} mutable x;
Richard Smith1ac67d12013-01-19 03:48:05 +00001298 case tok::kw_thread_local: // struct foo {...} thread_local x;
Richard Smith369b9f92012-06-25 21:37:02 +00001299 case tok::kw_constexpr: // struct foo {...} constexpr x;
1300 // As shown above, type qualifiers and storage class specifiers absolutely
1301 // can occur after class specifiers according to the grammar. However,
1302 // almost no one actually writes code like this. If we see one of these,
1303 // it is much more likely that someone missed a semi colon and the
1304 // type/storage class specifier we're seeing is part of the *next*
1305 // intended declaration, as in:
1306 //
1307 // struct foo { ... }
1308 // typedef int X;
1309 //
1310 // We'd really like to emit a missing semicolon error instead of emitting
1311 // an error on the 'int' saying that you can't have two type specifiers in
1312 // the same declaration of X. Because of this, we look ahead past this
1313 // token to see if it's a type specifier. If so, we know the code is
1314 // otherwise invalid, so we can produce the expected semi error.
1315 if (!isKnownToBeTypeSpecifier(NextToken()))
1316 return true;
1317 break;
1318 case tok::r_brace: // struct bar { struct foo {...} }
1319 // Missing ';' at end of struct is accepted as an extension in C mode.
1320 if (!getLangOpts().CPlusPlus)
1321 return true;
1322 break;
Richard Smith52c5b872013-01-29 04:13:32 +00001323 case tok::greater:
1324 // template<class T = class X>
1325 return getLangOpts().CPlusPlus;
Richard Smith369b9f92012-06-25 21:37:02 +00001326 }
1327 return false;
1328}
1329
Douglas Gregor556877c2008-04-13 21:30:24 +00001330/// ParseClassSpecifier - Parse a C++ class-specifier [C++ class] or
1331/// elaborated-type-specifier [C++ dcl.type.elab]; we can't tell which
1332/// until we reach the start of a definition or see a token that
Richard Smithc5b05522012-03-12 07:56:15 +00001333/// cannot start a definition.
Douglas Gregor556877c2008-04-13 21:30:24 +00001334///
1335/// class-specifier: [C++ class]
1336/// class-head '{' member-specification[opt] '}'
1337/// class-head '{' member-specification[opt] '}' attributes[opt]
1338/// class-head:
1339/// class-key identifier[opt] base-clause[opt]
1340/// class-key nested-name-specifier identifier base-clause[opt]
1341/// class-key nested-name-specifier[opt] simple-template-id
1342/// base-clause[opt]
1343/// [GNU] class-key attributes[opt] identifier[opt] base-clause[opt]
Mike Stump11289f42009-09-09 15:08:12 +00001344/// [GNU] class-key attributes[opt] nested-name-specifier
Douglas Gregor556877c2008-04-13 21:30:24 +00001345/// identifier base-clause[opt]
Mike Stump11289f42009-09-09 15:08:12 +00001346/// [GNU] class-key attributes[opt] nested-name-specifier[opt]
Douglas Gregor556877c2008-04-13 21:30:24 +00001347/// simple-template-id base-clause[opt]
1348/// class-key:
1349/// 'class'
1350/// 'struct'
1351/// 'union'
1352///
1353/// elaborated-type-specifier: [C++ dcl.type.elab]
Mike Stump11289f42009-09-09 15:08:12 +00001354/// class-key ::[opt] nested-name-specifier[opt] identifier
1355/// class-key ::[opt] nested-name-specifier[opt] 'template'[opt]
1356/// simple-template-id
Douglas Gregor556877c2008-04-13 21:30:24 +00001357///
1358/// Note that the C++ class-specifier and elaborated-type-specifier,
1359/// together, subsume the C99 struct-or-union-specifier:
1360///
1361/// struct-or-union-specifier: [C99 6.7.2.1]
1362/// struct-or-union identifier[opt] '{' struct-contents '}'
1363/// struct-or-union identifier
1364/// [GNU] struct-or-union attributes[opt] identifier[opt] '{' struct-contents
1365/// '}' attributes[opt]
1366/// [GNU] struct-or-union attributes[opt] identifier
1367/// struct-or-union:
1368/// 'struct'
1369/// 'union'
Chris Lattnerffaa0e62009-04-12 21:49:30 +00001370void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind,
1371 SourceLocation StartLoc, DeclSpec &DS,
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001372 const ParsedTemplateInfo &TemplateInfo,
Fangrui Song6907ce22018-07-30 19:24:48 +00001373 AccessSpecifier AS,
1374 bool EnteringContext, DeclSpecContext DSC,
Bill Wendling44426052012-12-20 19:22:21 +00001375 ParsedAttributesWithRange &Attributes) {
Joao Matose9a3ed42012-08-31 22:18:20 +00001376 DeclSpec::TST TagType;
1377 if (TagTokKind == tok::kw_struct)
1378 TagType = DeclSpec::TST_struct;
1379 else if (TagTokKind == tok::kw___interface)
1380 TagType = DeclSpec::TST_interface;
1381 else if (TagTokKind == tok::kw_class)
1382 TagType = DeclSpec::TST_class;
1383 else {
Chris Lattnerffaa0e62009-04-12 21:49:30 +00001384 assert(TagTokKind == tok::kw_union && "Not a class specifier");
1385 TagType = DeclSpec::TST_union;
1386 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001387
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00001388 if (Tok.is(tok::code_completion)) {
1389 // Code completion for a struct, class, or union name.
Douglas Gregor0be31a22010-07-02 17:43:08 +00001390 Actions.CodeCompleteTag(getCurScope(), TagType);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001391 return cutOffParsing();
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00001392 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001393
Chandler Carruth2d69ec72010-06-28 08:39:25 +00001394 // C++03 [temp.explicit] 14.7.2/8:
1395 // The usual access checking rules do not apply to names used to specify
1396 // explicit instantiations.
1397 //
1398 // As an extension we do not perform access checking on the names used to
1399 // specify explicit specializations either. This is important to allow
1400 // specializing traits classes for private types.
John McCall6347b682012-05-07 06:16:58 +00001401 //
1402 // Note that we don't suppress if this turns out to be an elaborated
1403 // type specifier.
1404 bool shouldDelayDiagsInTag =
1405 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
1406 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
1407 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
Chandler Carruth2d69ec72010-06-28 08:39:25 +00001408
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001409 ParsedAttributesWithRange attrs(AttrFactory);
Douglas Gregor556877c2008-04-13 21:30:24 +00001410 // If attributes exist after tag, parse them.
Richard Smith37a45dd2013-10-24 01:21:09 +00001411 MaybeParseGNUAttributes(attrs);
Aaron Ballman068aa512015-05-20 20:58:33 +00001412 MaybeParseMicrosoftDeclSpecs(attrs);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001413
John McCall8d32c052012-05-22 21:28:12 +00001414 // Parse inheritance specifiers.
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001415 if (Tok.isOneOf(tok::kw___single_inheritance,
1416 tok::kw___multiple_inheritance,
1417 tok::kw___virtual_inheritance))
Richard Smith37a45dd2013-10-24 01:21:09 +00001418 ParseMicrosoftInheritanceClassAttributes(attrs);
John McCall8d32c052012-05-22 21:28:12 +00001419
Alexis Hunt96d5c762009-11-21 08:43:09 +00001420 // If C++0x attributes exist here, parse them.
1421 // FIXME: Are we consistent with the ordering of parsing of different
1422 // styles of attributes?
Richard Smith89645bc2013-01-02 12:01:23 +00001423 MaybeParseCXX11Attributes(attrs);
Mike Stump11289f42009-09-09 15:08:12 +00001424
Michael Han309af292013-01-07 16:57:11 +00001425 // Source location used by FIXIT to insert misplaced
1426 // C++11 attributes
1427 SourceLocation AttrFixitLoc = Tok.getLocation();
1428
Nico Weber7c3c5be2014-09-23 04:09:56 +00001429 if (TagType == DeclSpec::TST_struct &&
David Majnemer86330af2014-12-29 02:14:26 +00001430 Tok.isNot(tok::identifier) &&
1431 !Tok.isAnnotation() &&
Nico Weber7c3c5be2014-09-23 04:09:56 +00001432 Tok.getIdentifierInfo() &&
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001433 Tok.isOneOf(tok::kw___is_abstract,
Eric Fiselier07360662017-04-12 22:12:15 +00001434 tok::kw___is_aggregate,
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001435 tok::kw___is_arithmetic,
1436 tok::kw___is_array,
David Majnemerb3d96882016-05-23 17:21:55 +00001437 tok::kw___is_assignable,
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001438 tok::kw___is_base_of,
1439 tok::kw___is_class,
1440 tok::kw___is_complete_type,
1441 tok::kw___is_compound,
1442 tok::kw___is_const,
1443 tok::kw___is_constructible,
1444 tok::kw___is_convertible,
1445 tok::kw___is_convertible_to,
1446 tok::kw___is_destructible,
1447 tok::kw___is_empty,
1448 tok::kw___is_enum,
1449 tok::kw___is_floating_point,
1450 tok::kw___is_final,
1451 tok::kw___is_function,
1452 tok::kw___is_fundamental,
1453 tok::kw___is_integral,
1454 tok::kw___is_interface_class,
1455 tok::kw___is_literal,
1456 tok::kw___is_lvalue_expr,
1457 tok::kw___is_lvalue_reference,
1458 tok::kw___is_member_function_pointer,
1459 tok::kw___is_member_object_pointer,
1460 tok::kw___is_member_pointer,
1461 tok::kw___is_nothrow_assignable,
1462 tok::kw___is_nothrow_constructible,
1463 tok::kw___is_nothrow_destructible,
1464 tok::kw___is_object,
1465 tok::kw___is_pod,
1466 tok::kw___is_pointer,
1467 tok::kw___is_polymorphic,
1468 tok::kw___is_reference,
1469 tok::kw___is_rvalue_expr,
1470 tok::kw___is_rvalue_reference,
1471 tok::kw___is_same,
1472 tok::kw___is_scalar,
1473 tok::kw___is_sealed,
1474 tok::kw___is_signed,
1475 tok::kw___is_standard_layout,
1476 tok::kw___is_trivial,
1477 tok::kw___is_trivially_assignable,
1478 tok::kw___is_trivially_constructible,
1479 tok::kw___is_trivially_copyable,
1480 tok::kw___is_union,
1481 tok::kw___is_unsigned,
1482 tok::kw___is_void,
1483 tok::kw___is_volatile))
Nico Weber7c3c5be2014-09-23 04:09:56 +00001484 // GNU libstdc++ 4.2 and libc++ use certain intrinsic names as the
1485 // name of struct templates, but some are keywords in GCC >= 4.3
1486 // and Clang. Therefore, when we see the token sequence "struct
1487 // X", make X into a normal identifier rather than a keyword, to
1488 // allow libstdc++ 4.2 and libc++ to work properly.
1489 TryKeywordIdentFallback(true);
Mike Stump11289f42009-09-09 15:08:12 +00001490
David Majnemer51fd8a02015-07-22 23:46:18 +00001491 struct PreserveAtomicIdentifierInfoRAII {
1492 PreserveAtomicIdentifierInfoRAII(Token &Tok, bool Enabled)
1493 : AtomicII(nullptr) {
1494 if (!Enabled)
1495 return;
1496 assert(Tok.is(tok::kw__Atomic));
1497 AtomicII = Tok.getIdentifierInfo();
1498 AtomicII->revertTokenIDToIdentifier();
1499 Tok.setKind(tok::identifier);
1500 }
1501 ~PreserveAtomicIdentifierInfoRAII() {
1502 if (!AtomicII)
1503 return;
1504 AtomicII->revertIdentifierToTokenID(tok::kw__Atomic);
1505 }
1506 IdentifierInfo *AtomicII;
1507 };
1508
1509 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
1510 // implementation for VS2013 uses _Atomic as an identifier for one of the
1511 // classes in <atomic>. When we are parsing 'struct _Atomic', don't consider
1512 // '_Atomic' to be a keyword. We are careful to undo this so that clang can
1513 // use '_Atomic' in its own header files.
1514 bool ShouldChangeAtomicToIdentifier = getLangOpts().MSVCCompat &&
1515 Tok.is(tok::kw__Atomic) &&
1516 TagType == DeclSpec::TST_struct;
1517 PreserveAtomicIdentifierInfoRAII AtomicTokenGuard(
1518 Tok, ShouldChangeAtomicToIdentifier);
1519
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001520 // Parse the (optional) nested-name-specifier.
John McCall9dab4e62009-12-12 11:40:51 +00001521 CXXScopeSpec &SS = DS.getTypeSpecScope();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001522 if (getLangOpts().CPlusPlus) {
Serge Pavlov458ea762014-07-16 05:16:52 +00001523 // "FOO : BAR" is not a potential typo for "FOO::BAR". In this context it
1524 // is a base-specifier-list.
Chris Lattnerd5c1c9d2009-12-10 00:32:41 +00001525 ColonProtectionRAIIObject X(*this);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001526
Nico Webercfaa4cd2015-02-15 07:26:13 +00001527 CXXScopeSpec Spec;
1528 bool HasValidSpec = true;
David Blaikieefdccaa2016-01-15 23:43:34 +00001529 if (ParseOptionalCXXScopeSpecifier(Spec, nullptr, EnteringContext)) {
John McCall413021a2010-07-30 06:26:29 +00001530 DS.SetTypeSpecError();
Nico Webercfaa4cd2015-02-15 07:26:13 +00001531 HasValidSpec = false;
1532 }
1533 if (Spec.isSet())
1534 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::annot_template_id)) {
Alp Tokerec543272013-12-24 09:48:30 +00001535 Diag(Tok, diag::err_expected) << tok::identifier;
Nico Webercfaa4cd2015-02-15 07:26:13 +00001536 HasValidSpec = false;
1537 }
1538 if (HasValidSpec)
1539 SS = Spec;
Chris Lattnerd5c1c9d2009-12-10 00:32:41 +00001540 }
Douglas Gregor67a65642009-02-17 23:15:12 +00001541
Douglas Gregor916462b2009-10-30 21:46:58 +00001542 TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
1543
Douglas Gregor67a65642009-02-17 23:15:12 +00001544 // Parse the (optional) class name or simple-template-id.
Craig Topper161e4db2014-05-21 06:02:52 +00001545 IdentifierInfo *Name = nullptr;
Douglas Gregor556877c2008-04-13 21:30:24 +00001546 SourceLocation NameLoc;
Craig Topper161e4db2014-05-21 06:02:52 +00001547 TemplateIdAnnotation *TemplateId = nullptr;
Douglas Gregor556877c2008-04-13 21:30:24 +00001548 if (Tok.is(tok::identifier)) {
1549 Name = Tok.getIdentifierInfo();
1550 NameLoc = ConsumeToken();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001551
David Blaikiebbafb8a2012-03-11 07:00:24 +00001552 if (Tok.is(tok::less) && getLangOpts().CPlusPlus) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001553 // The name was supposed to refer to a template, but didn't.
Douglas Gregor916462b2009-10-30 21:46:58 +00001554 // Eat the template argument list and try to continue parsing this as
1555 // a class (or template thereof).
1556 TemplateArgList TemplateArgs;
Douglas Gregor916462b2009-10-30 21:46:58 +00001557 SourceLocation LAngleLoc, RAngleLoc;
Richard Smith9a420f92017-05-10 21:47:30 +00001558 if (ParseTemplateIdAfterTemplateName(true, LAngleLoc, TemplateArgs,
1559 RAngleLoc)) {
Douglas Gregor916462b2009-10-30 21:46:58 +00001560 // We couldn't parse the template argument list at all, so don't
1561 // try to give any location information for the list.
1562 LAngleLoc = RAngleLoc = SourceLocation();
1563 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001564
Douglas Gregor916462b2009-10-30 21:46:58 +00001565 Diag(NameLoc, diag::err_explicit_spec_non_template)
Alp Toker01d65e12014-01-06 12:54:41 +00001566 << (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
1567 << TagTokKind << Name << SourceRange(LAngleLoc, RAngleLoc);
Joao Matose9a3ed42012-08-31 22:18:20 +00001568
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001569 // Strip off the last template parameter list if it was empty, since
Douglas Gregor1d0015f2009-10-30 22:09:44 +00001570 // we've removed its template argument list.
1571 if (TemplateParams && TemplateInfo.LastParameterListWasEmpty) {
Hubert Tong97b06632016-04-13 18:41:03 +00001572 if (TemplateParams->size() > 1) {
Douglas Gregor1d0015f2009-10-30 22:09:44 +00001573 TemplateParams->pop_back();
1574 } else {
Craig Topper161e4db2014-05-21 06:02:52 +00001575 TemplateParams = nullptr;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001576 const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind
Douglas Gregor1d0015f2009-10-30 22:09:44 +00001577 = ParsedTemplateInfo::NonTemplate;
1578 }
1579 } else if (TemplateInfo.Kind
1580 == ParsedTemplateInfo::ExplicitInstantiation) {
1581 // Pretend this is just a forward declaration.
Craig Topper161e4db2014-05-21 06:02:52 +00001582 TemplateParams = nullptr;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001583 const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind
Douglas Gregor916462b2009-10-30 21:46:58 +00001584 = ParsedTemplateInfo::NonTemplate;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001585 const_cast<ParsedTemplateInfo&>(TemplateInfo).TemplateLoc
Douglas Gregor1d0015f2009-10-30 22:09:44 +00001586 = SourceLocation();
1587 const_cast<ParsedTemplateInfo&>(TemplateInfo).ExternLoc
1588 = SourceLocation();
Douglas Gregor916462b2009-10-30 21:46:58 +00001589 }
Douglas Gregor916462b2009-10-30 21:46:58 +00001590 }
Douglas Gregor7f741122009-02-25 19:37:18 +00001591 } else if (Tok.is(tok::annot_template_id)) {
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00001592 TemplateId = takeTemplateIdAnnotation(Tok);
Richard Smithaf3b3252017-05-18 19:21:48 +00001593 NameLoc = ConsumeAnnotationToken();
Douglas Gregor67a65642009-02-17 23:15:12 +00001594
Douglas Gregore7c20652011-03-02 00:47:37 +00001595 if (TemplateId->Kind != TNK_Type_template &&
1596 TemplateId->Kind != TNK_Dependent_template_name) {
Douglas Gregor7f741122009-02-25 19:37:18 +00001597 // The template-name in the simple-template-id refers to
1598 // something other than a class template. Give an appropriate
1599 // error message and skip to the ';'.
1600 SourceRange Range(NameLoc);
1601 if (SS.isNotEmpty())
1602 Range.setBegin(SS.getBeginLoc());
Douglas Gregor67a65642009-02-17 23:15:12 +00001603
Richard Smith72bfbd82013-12-04 00:28:23 +00001604 // FIXME: Name may be null here.
Douglas Gregor7f741122009-02-25 19:37:18 +00001605 Diag(TemplateId->LAngleLoc, diag::err_template_spec_syntax_non_template)
Richard Trieu30f93852013-06-19 22:25:01 +00001606 << TemplateId->Name << static_cast<int>(TemplateId->Kind) << Range;
Mike Stump11289f42009-09-09 15:08:12 +00001607
Douglas Gregor7f741122009-02-25 19:37:18 +00001608 DS.SetTypeSpecError();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001609 SkipUntil(tok::semi, StopBeforeMatch);
Douglas Gregor7f741122009-02-25 19:37:18 +00001610 return;
Douglas Gregor67a65642009-02-17 23:15:12 +00001611 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001612 }
1613
Richard Smithbfdb1082012-03-12 08:56:40 +00001614 // There are four options here.
1615 // - If we are in a trailing return type, this is always just a reference,
1616 // and we must not try to parse a definition. For instance,
1617 // [] () -> struct S { };
1618 // does not define a type.
1619 // - If we have 'struct foo {...', 'struct foo :...',
1620 // 'struct foo final :' or 'struct foo final {', then this is a definition.
1621 // - If we have 'struct foo;', then this is either a forward declaration
1622 // or a friend declaration, which have to be treated differently.
1623 // - Otherwise we have something like 'struct foo xyz', a reference.
Michael Han9407e502012-11-26 22:54:45 +00001624 //
1625 // We also detect these erroneous cases to provide better diagnostic for
1626 // C++11 attributes parsing.
1627 // - attributes follow class name:
1628 // struct foo [[]] {};
1629 // - attributes appear before or after 'final':
1630 // struct foo [[]] final [[]] {};
1631 //
Richard Smithc5b05522012-03-12 07:56:15 +00001632 // However, in type-specifier-seq's, things look like declarations but are
1633 // just references, e.g.
1634 // new struct s;
Sebastian Redl2b372722010-02-03 21:21:43 +00001635 // or
Richard Smithc5b05522012-03-12 07:56:15 +00001636 // &T::operator struct s;
Faisal Vali7db85c52017-12-31 00:06:40 +00001637 // For these, DSC is DeclSpecContext::DSC_type_specifier or
1638 // DeclSpecContext::DSC_alias_declaration.
Michael Han9407e502012-11-26 22:54:45 +00001639
1640 // If there are attributes after class name, parse them.
Richard Smith89645bc2013-01-02 12:01:23 +00001641 MaybeParseCXX11Attributes(Attributes);
Michael Han9407e502012-11-26 22:54:45 +00001642
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001643 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
John McCallfaf5fb42010-08-26 23:41:50 +00001644 Sema::TagUseKind TUK;
Faisal Vali7db85c52017-12-31 00:06:40 +00001645 if (DSC == DeclSpecContext::DSC_trailing)
Richard Smithbfdb1082012-03-12 08:56:40 +00001646 TUK = Sema::TUK_Reference;
1647 else if (Tok.is(tok::l_brace) ||
1648 (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
Richard Smith89645bc2013-01-02 12:01:23 +00001649 (isCXX11FinalKeyword() &&
David Blaikie9933a5a2012-03-12 15:39:49 +00001650 (NextToken().is(tok::l_brace) || NextToken().is(tok::colon)))) {
Douglas Gregor3dad8422009-09-26 06:47:28 +00001651 if (DS.isFriendSpecified()) {
1652 // C++ [class.friend]p2:
1653 // A class shall not be defined in a friend declaration.
Richard Smith0f8ee222012-01-10 01:33:14 +00001654 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
Douglas Gregor3dad8422009-09-26 06:47:28 +00001655 << SourceRange(DS.getFriendSpecLoc());
1656
1657 // Skip everything up to the semicolon, so that this looks like a proper
1658 // friend class (or template thereof) declaration.
Alexey Bataevee6507d2013-11-18 08:17:37 +00001659 SkipUntil(tok::semi, StopBeforeMatch);
John McCallfaf5fb42010-08-26 23:41:50 +00001660 TUK = Sema::TUK_Friend;
Douglas Gregor3dad8422009-09-26 06:47:28 +00001661 } else {
1662 // Okay, this is a class definition.
John McCallfaf5fb42010-08-26 23:41:50 +00001663 TUK = Sema::TUK_Definition;
Douglas Gregor3dad8422009-09-26 06:47:28 +00001664 }
Richard Smith434516c2013-02-22 06:46:23 +00001665 } else if (isCXX11FinalKeyword() && (NextToken().is(tok::l_square) ||
1666 NextToken().is(tok::kw_alignas))) {
Michael Han9407e502012-11-26 22:54:45 +00001667 // We can't tell if this is a definition or reference
1668 // until we skipped the 'final' and C++11 attribute specifiers.
1669 TentativeParsingAction PA(*this);
1670
1671 // Skip the 'final' keyword.
1672 ConsumeToken();
1673
1674 // Skip C++11 attribute specifiers.
1675 while (true) {
1676 if (Tok.is(tok::l_square) && NextToken().is(tok::l_square)) {
1677 ConsumeBracket();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001678 if (!SkipUntil(tok::r_square, StopAtSemi))
Michael Han9407e502012-11-26 22:54:45 +00001679 break;
Richard Smith434516c2013-02-22 06:46:23 +00001680 } else if (Tok.is(tok::kw_alignas) && NextToken().is(tok::l_paren)) {
Michael Han9407e502012-11-26 22:54:45 +00001681 ConsumeToken();
1682 ConsumeParen();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001683 if (!SkipUntil(tok::r_paren, StopAtSemi))
Michael Han9407e502012-11-26 22:54:45 +00001684 break;
1685 } else {
1686 break;
1687 }
1688 }
1689
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001690 if (Tok.isOneOf(tok::l_brace, tok::colon))
Michael Han9407e502012-11-26 22:54:45 +00001691 TUK = Sema::TUK_Definition;
1692 else
1693 TUK = Sema::TUK_Reference;
1694
1695 PA.Revert();
Richard Smith649c7b062014-01-08 00:56:48 +00001696 } else if (!isTypeSpecifier(DSC) &&
Richard Smith369b9f92012-06-25 21:37:02 +00001697 (Tok.is(tok::semi) ||
Richard Smith200f47c2012-07-02 19:14:01 +00001698 (Tok.isAtStartOfLine() && !isValidAfterTypeSpecifier(false)))) {
John McCallfaf5fb42010-08-26 23:41:50 +00001699 TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
Joao Matose9a3ed42012-08-31 22:18:20 +00001700 if (Tok.isNot(tok::semi)) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001701 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
Joao Matose9a3ed42012-08-31 22:18:20 +00001702 // A semicolon was missing after this declaration. Diagnose and recover.
Alp Toker383d2c42014-01-01 03:08:43 +00001703 ExpectAndConsume(tok::semi, diag::err_expected_after,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001704 DeclSpec::getSpecifierName(TagType, PPol));
Joao Matose9a3ed42012-08-31 22:18:20 +00001705 PP.EnterToken(Tok);
1706 Tok.setKind(tok::semi);
1707 }
Richard Smith369b9f92012-06-25 21:37:02 +00001708 } else
John McCallfaf5fb42010-08-26 23:41:50 +00001709 TUK = Sema::TUK_Reference;
Douglas Gregor556877c2008-04-13 21:30:24 +00001710
Michael Han9407e502012-11-26 22:54:45 +00001711 // Forbid misplaced attributes. In cases of a reference, we pass attributes
1712 // to caller to handle.
Michael Han309af292013-01-07 16:57:11 +00001713 if (TUK != Sema::TUK_Reference) {
1714 // If this is not a reference, then the only possible
1715 // valid place for C++11 attributes to appear here
1716 // is between class-key and class-name. If there are
1717 // any attributes after class-name, we try a fixit to move
1718 // them to the right place.
1719 SourceRange AttrRange = Attributes.Range;
1720 if (AttrRange.isValid()) {
1721 Diag(AttrRange.getBegin(), diag::err_attributes_not_allowed)
1722 << AttrRange
1723 << FixItHint::CreateInsertionFromRange(AttrFixitLoc,
1724 CharSourceRange(AttrRange, true))
1725 << FixItHint::CreateRemoval(AttrRange);
1726
1727 // Recover by adding misplaced attributes to the attribute list
1728 // of the class so they can be applied on the class later.
1729 attrs.takeAllFrom(Attributes);
1730 }
1731 }
Michael Han9407e502012-11-26 22:54:45 +00001732
John McCall6347b682012-05-07 06:16:58 +00001733 // If this is an elaborated type specifier, and we delayed
1734 // diagnostics before, just merge them into the current pool.
1735 if (shouldDelayDiagsInTag) {
1736 diagsFromTag.done();
1737 if (TUK == Sema::TUK_Reference)
1738 diagsFromTag.redelay();
1739 }
1740
John McCall413021a2010-07-30 06:26:29 +00001741 if (!Name && !TemplateId && (DS.getTypeSpecType() == DeclSpec::TST_error ||
John McCallfaf5fb42010-08-26 23:41:50 +00001742 TUK != Sema::TUK_Definition)) {
John McCall413021a2010-07-30 06:26:29 +00001743 if (DS.getTypeSpecType() != DeclSpec::TST_error) {
1744 // We have a declaration or reference to an anonymous class.
1745 Diag(StartLoc, diag::err_anon_type_definition)
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001746 << DeclSpec::getSpecifierName(TagType, Policy);
John McCall413021a2010-07-30 06:26:29 +00001747 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001748
David Majnemer3252fd02013-12-05 01:36:53 +00001749 // If we are parsing a definition and stop at a base-clause, continue on
1750 // until the semicolon. Continuing from the comma will just trick us into
1751 // thinking we are seeing a variable declaration.
1752 if (TUK == Sema::TUK_Definition && Tok.is(tok::colon))
1753 SkipUntil(tok::semi, StopBeforeMatch);
1754 else
1755 SkipUntil(tok::comma, StopAtSemi);
Douglas Gregor556877c2008-04-13 21:30:24 +00001756 return;
1757 }
1758
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001759 // Create the tag portion of the class or class template.
John McCall48871652010-08-21 09:40:31 +00001760 DeclResult TagOrTempResult = true; // invalid
1761 TypeResult TypeResult = true; // invalid
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001762
Douglas Gregord6ab8742009-05-28 23:31:59 +00001763 bool Owned = false;
Richard Smithd9ba2242015-05-07 03:54:19 +00001764 Sema::SkipBodyInfo SkipBody;
John McCall06f6fe8d2009-09-04 01:14:41 +00001765 if (TemplateId) {
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001766 // Explicit specialization, class template partial specialization,
1767 // or explicit instantiation.
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00001768 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregor7f741122009-02-25 19:37:18 +00001769 TemplateId->NumArgs);
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001770 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
John McCallfaf5fb42010-08-26 23:41:50 +00001771 TUK == Sema::TUK_Declaration) {
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001772 // This is an explicit instantiation of a class template.
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001773 ProhibitAttributes(attrs);
1774
Erich Keanec480f302018-07-12 21:09:05 +00001775 TagOrTempResult = Actions.ActOnExplicitInstantiation(
1776 getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc,
1777 TagType, StartLoc, SS, TemplateId->Template,
1778 TemplateId->TemplateNameLoc, TemplateId->LAngleLoc, TemplateArgsPtr,
1779 TemplateId->RAngleLoc, attrs);
John McCallb7c5c272010-04-14 00:24:33 +00001780
Erich Keanec480f302018-07-12 21:09:05 +00001781 // Friend template-ids are treated as references unless
1782 // they have template headers, in which case they're ill-formed
1783 // (FIXME: "template <class T> friend class A<T>::B<int>;").
1784 // We diagnose this error in ActOnClassTemplateSpecialization.
John McCallfaf5fb42010-08-26 23:41:50 +00001785 } else if (TUK == Sema::TUK_Reference ||
1786 (TUK == Sema::TUK_Friend &&
John McCallb7c5c272010-04-14 00:24:33 +00001787 TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate)) {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001788 ProhibitAttributes(attrs);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00001789 TypeResult = Actions.ActOnTagTemplateIdType(TUK, TagType, StartLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00001790 TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00001791 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00001792 TemplateId->Template,
1793 TemplateId->TemplateNameLoc,
1794 TemplateId->LAngleLoc,
1795 TemplateArgsPtr,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00001796 TemplateId->RAngleLoc);
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001797 } else {
1798 // This is an explicit specialization or a class template
1799 // partial specialization.
1800 TemplateParameterLists FakedParamLists;
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001801 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1802 // This looks like an explicit instantiation, because we have
1803 // something like
1804 //
1805 // template class Foo<X>
1806 //
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001807 // but it actually has a definition. Most likely, this was
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001808 // meant to be an explicit specialization, but the user forgot
1809 // the '<>' after 'template'.
Richard Smith003c5e12013-11-08 19:03:29 +00001810 // It this is friend declaration however, since it cannot have a
1811 // template header, it is most likely that the user meant to
1812 // remove the 'template' keyword.
Larisse Voufob9bbaba2013-06-22 13:56:11 +00001813 assert((TUK == Sema::TUK_Definition || TUK == Sema::TUK_Friend) &&
Richard Smith003c5e12013-11-08 19:03:29 +00001814 "Expected a definition here");
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001815
Richard Smith003c5e12013-11-08 19:03:29 +00001816 if (TUK == Sema::TUK_Friend) {
1817 Diag(DS.getFriendSpecLoc(), diag::err_friend_explicit_instantiation);
Craig Topper161e4db2014-05-21 06:02:52 +00001818 TemplateParams = nullptr;
Richard Smith003c5e12013-11-08 19:03:29 +00001819 } else {
1820 SourceLocation LAngleLoc =
1821 PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
1822 Diag(TemplateId->TemplateNameLoc,
1823 diag::err_explicit_instantiation_with_definition)
1824 << SourceRange(TemplateInfo.TemplateLoc)
1825 << FixItHint::CreateInsertion(LAngleLoc, "<>");
1826
1827 // Create a fake template parameter list that contains only
1828 // "template<>", so that we treat this construct as a class
1829 // template specialization.
1830 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
Craig Topper96225a52015-12-24 23:58:25 +00001831 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
Hubert Tongf608c052016-04-29 18:05:37 +00001832 LAngleLoc, nullptr));
Richard Smith003c5e12013-11-08 19:03:29 +00001833 TemplateParams = &FakedParamLists;
1834 }
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001835 }
1836
1837 // Build the class template specialization.
Richard Smith4b55a9c2014-04-17 03:29:33 +00001838 TagOrTempResult = Actions.ActOnClassTemplateSpecialization(
1839 getCurScope(), TagType, TUK, StartLoc, DS.getModulePrivateSpecLoc(),
Erich Keanec480f302018-07-12 21:09:05 +00001840 *TemplateId, attrs,
Craig Topper161e4db2014-05-21 06:02:52 +00001841 MultiTemplateParamsArg(TemplateParams ? &(*TemplateParams)[0]
1842 : nullptr,
Richard Smithc7e6ff02015-05-18 20:36:47 +00001843 TemplateParams ? TemplateParams->size() : 0),
1844 &SkipBody);
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001845 }
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001846 } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
John McCallfaf5fb42010-08-26 23:41:50 +00001847 TUK == Sema::TUK_Declaration) {
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001848 // Explicit instantiation of a member of a class template
1849 // specialization, e.g.,
1850 //
1851 // template struct Outer<int>::Inner;
1852 //
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001853 ProhibitAttributes(attrs);
1854
Erich Keanec480f302018-07-12 21:09:05 +00001855 TagOrTempResult = Actions.ActOnExplicitInstantiation(
1856 getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc,
1857 TagType, StartLoc, SS, Name, NameLoc, attrs);
John McCallace48cd2010-10-19 01:40:49 +00001858 } else if (TUK == Sema::TUK_Friend &&
1859 TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate) {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001860 ProhibitAttributes(attrs);
1861
Erich Keanec480f302018-07-12 21:09:05 +00001862 TagOrTempResult = Actions.ActOnTemplatedFriendTag(
1863 getCurScope(), DS.getFriendSpecLoc(), TagType, StartLoc, SS, Name,
1864 NameLoc, attrs,
1865 MultiTemplateParamsArg(TemplateParams ? &(*TemplateParams)[0] : nullptr,
1866 TemplateParams ? TemplateParams->size() : 0));
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001867 } else {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001868 if (TUK != Sema::TUK_Declaration && TUK != Sema::TUK_Definition)
1869 ProhibitAttributes(attrs);
Richard Smith003c5e12013-11-08 19:03:29 +00001870
Larisse Voufo725de3e2013-06-21 00:08:46 +00001871 if (TUK == Sema::TUK_Definition &&
1872 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1873 // If the declarator-id is not a template-id, issue a diagnostic and
1874 // recover by ignoring the 'template' keyword.
1875 Diag(Tok, diag::err_template_defn_explicit_instantiation)
1876 << 1 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
Craig Topper161e4db2014-05-21 06:02:52 +00001877 TemplateParams = nullptr;
Larisse Voufo725de3e2013-06-21 00:08:46 +00001878 }
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001879
John McCall7f41d982009-09-11 04:59:25 +00001880 bool IsDependent = false;
1881
John McCall32723e92010-10-19 18:40:57 +00001882 // Don't pass down template parameter lists if this is just a tag
1883 // reference. For example, we don't need the template parameters here:
1884 // template <class T> class A *makeA(T t);
1885 MultiTemplateParamsArg TParams;
1886 if (TUK != Sema::TUK_Reference && TemplateParams)
1887 TParams =
1888 MultiTemplateParamsArg(&(*TemplateParams)[0], TemplateParams->size());
1889
Nico Weber32a0fc72016-09-03 03:01:32 +00001890 stripTypeAttributesOffDeclSpec(attrs, DS, TUK);
David Majnemer936b4112015-04-19 07:53:29 +00001891
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001892 // Declaration or definition of a class type
Faisal Vali7db85c52017-12-31 00:06:40 +00001893 TagOrTempResult = Actions.ActOnTag(
Erich Keanec480f302018-07-12 21:09:05 +00001894 getCurScope(), TagType, TUK, StartLoc, SS, Name, NameLoc, attrs, AS,
1895 DS.getModulePrivateSpecLoc(), TParams, Owned, IsDependent,
1896 SourceLocation(), false, clang::TypeResult(),
Faisal Vali7db85c52017-12-31 00:06:40 +00001897 DSC == DeclSpecContext::DSC_type_specifier,
1898 DSC == DeclSpecContext::DSC_template_param ||
1899 DSC == DeclSpecContext::DSC_template_type_arg,
1900 &SkipBody);
John McCall7f41d982009-09-11 04:59:25 +00001901
1902 // If ActOnTag said the type was dependent, try again with the
1903 // less common call.
John McCallace48cd2010-10-19 01:40:49 +00001904 if (IsDependent) {
1905 assert(TUK == Sema::TUK_Reference || TUK == Sema::TUK_Friend);
Douglas Gregor0be31a22010-07-02 17:43:08 +00001906 TypeResult = Actions.ActOnDependentTag(getCurScope(), TagType, TUK,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001907 SS, Name, StartLoc, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +00001908 }
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001909 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001910
Douglas Gregor556877c2008-04-13 21:30:24 +00001911 // If there is a body, parse it and inform the actions module.
John McCallfaf5fb42010-08-26 23:41:50 +00001912 if (TUK == Sema::TUK_Definition) {
John McCall2d814c32009-12-19 21:48:58 +00001913 assert(Tok.is(tok::l_brace) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00001914 (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
Richard Smith89645bc2013-01-02 12:01:23 +00001915 isCXX11FinalKeyword());
Richard Smithd9ba2242015-05-07 03:54:19 +00001916 if (SkipBody.ShouldSkip)
Richard Smith65ebb4a2015-03-26 04:09:53 +00001917 SkipCXXMemberSpecification(StartLoc, AttrFixitLoc, TagType,
1918 TagOrTempResult.get());
1919 else if (getLangOpts().CPlusPlus)
Michael Han309af292013-01-07 16:57:11 +00001920 ParseCXXMemberSpecification(StartLoc, AttrFixitLoc, attrs, TagType,
1921 TagOrTempResult.get());
Bruno Cardoso Lopesdf0ee342017-07-01 00:06:47 +00001922 else {
1923 Decl *D =
1924 SkipBody.CheckSameAsPrevious ? SkipBody.New : TagOrTempResult.get();
1925 // Parse the definition body.
1926 ParseStructUnionBody(StartLoc, TagType, D);
1927 if (SkipBody.CheckSameAsPrevious &&
1928 !Actions.ActOnDuplicateDefinition(DS, TagOrTempResult.get(),
1929 SkipBody)) {
1930 DS.SetTypeSpecError();
1931 return;
1932 }
1933 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001934 }
1935
Erich Keane2fe684b2017-02-28 20:44:39 +00001936 if (!TagOrTempResult.isInvalid())
Hiroshi Inoue939d9322017-06-30 05:40:31 +00001937 // Delayed processing of attributes.
Erich Keanec480f302018-07-12 21:09:05 +00001938 Actions.ProcessDeclAttributeDelayed(TagOrTempResult.get(), attrs);
Erich Keane2fe684b2017-02-28 20:44:39 +00001939
Craig Topper161e4db2014-05-21 06:02:52 +00001940 const char *PrevSpec = nullptr;
John McCallba7bf592010-08-24 05:47:05 +00001941 unsigned DiagID;
1942 bool Result;
John McCall7f41d982009-09-11 04:59:25 +00001943 if (!TypeResult.isInvalid()) {
Abramo Bagnara9875a3c2011-03-16 20:16:18 +00001944 Result = DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
1945 NameLoc.isValid() ? NameLoc : StartLoc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001946 PrevSpec, DiagID, TypeResult.get(), Policy);
John McCall7f41d982009-09-11 04:59:25 +00001947 } else if (!TagOrTempResult.isInvalid()) {
Abramo Bagnara9875a3c2011-03-16 20:16:18 +00001948 Result = DS.SetTypeSpecType(TagType, StartLoc,
1949 NameLoc.isValid() ? NameLoc : StartLoc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001950 PrevSpec, DiagID, TagOrTempResult.get(), Owned,
1951 Policy);
John McCall7f41d982009-09-11 04:59:25 +00001952 } else {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001953 DS.SetTypeSpecError();
Anders Carlssonf83c9fa2009-05-11 22:27:47 +00001954 return;
1955 }
Mike Stump11289f42009-09-09 15:08:12 +00001956
John McCallba7bf592010-08-24 05:47:05 +00001957 if (Result)
John McCall49bfce42009-08-03 20:12:06 +00001958 Diag(StartLoc, DiagID) << PrevSpec;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001959
Chris Lattnercf251412010-02-02 01:23:29 +00001960 // At this point, we've successfully parsed a class-specifier in 'definition'
1961 // form (e.g. "struct foo { int x; }". While we could just return here, we're
1962 // going to look at what comes after it to improve error recovery. If an
1963 // impossible token occurs next, we assume that the programmer forgot a ; at
1964 // the end of the declaration and recover that way.
1965 //
Richard Smith369b9f92012-06-25 21:37:02 +00001966 // Also enforce C++ [temp]p3:
1967 // In a template-declaration which defines a class, no declarator
1968 // is permitted.
Richard Smith843f18f2014-08-13 02:13:15 +00001969 //
1970 // After a type-specifier, we don't expect a semicolon. This only happens in
1971 // C, since definitions are not permitted in this context in C++.
Joao Matose9a3ed42012-08-31 22:18:20 +00001972 if (TUK == Sema::TUK_Definition &&
Richard Smith843f18f2014-08-13 02:13:15 +00001973 (getLangOpts().CPlusPlus || !isTypeSpecifier(DSC)) &&
Joao Matose9a3ed42012-08-31 22:18:20 +00001974 (TemplateInfo.Kind || !isValidAfterTypeSpecifier(false))) {
Argyrios Kyrtzidise6f69132012-12-17 20:10:43 +00001975 if (Tok.isNot(tok::semi)) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001976 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
Alp Toker383d2c42014-01-01 03:08:43 +00001977 ExpectAndConsume(tok::semi, diag::err_expected_after,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001978 DeclSpec::getSpecifierName(TagType, PPol));
Argyrios Kyrtzidise6f69132012-12-17 20:10:43 +00001979 // Push this token back into the preprocessor and change our current token
1980 // to ';' so that the rest of the code recovers as though there were an
1981 // ';' after the definition.
1982 PP.EnterToken(Tok);
1983 Tok.setKind(tok::semi);
1984 }
Chris Lattnercf251412010-02-02 01:23:29 +00001985 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001986}
1987
Mike Stump11289f42009-09-09 15:08:12 +00001988/// ParseBaseClause - Parse the base-clause of a C++ class [C++ class.derived].
Douglas Gregor556877c2008-04-13 21:30:24 +00001989///
1990/// base-clause : [C++ class.derived]
1991/// ':' base-specifier-list
1992/// base-specifier-list:
1993/// base-specifier '...'[opt]
1994/// base-specifier-list ',' base-specifier '...'[opt]
John McCall48871652010-08-21 09:40:31 +00001995void Parser::ParseBaseClause(Decl *ClassDecl) {
Douglas Gregor556877c2008-04-13 21:30:24 +00001996 assert(Tok.is(tok::colon) && "Not a base clause");
1997 ConsumeToken();
1998
Douglas Gregor29a92472008-10-22 17:49:05 +00001999 // Build up an array of parsed base specifiers.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002000 SmallVector<CXXBaseSpecifier *, 8> BaseInfo;
Douglas Gregor29a92472008-10-22 17:49:05 +00002001
Douglas Gregor556877c2008-04-13 21:30:24 +00002002 while (true) {
2003 // Parse a base-specifier.
Douglas Gregor29a92472008-10-22 17:49:05 +00002004 BaseResult Result = ParseBaseSpecifier(ClassDecl);
Douglas Gregorf8298252009-01-26 22:44:13 +00002005 if (Result.isInvalid()) {
Douglas Gregor556877c2008-04-13 21:30:24 +00002006 // Skip the rest of this base specifier, up until the comma or
2007 // opening brace.
Alexey Bataevee6507d2013-11-18 08:17:37 +00002008 SkipUntil(tok::comma, tok::l_brace, StopAtSemi | StopBeforeMatch);
Douglas Gregor29a92472008-10-22 17:49:05 +00002009 } else {
2010 // Add this to our array of base specifiers.
Douglas Gregorf8298252009-01-26 22:44:13 +00002011 BaseInfo.push_back(Result.get());
Douglas Gregor556877c2008-04-13 21:30:24 +00002012 }
2013
2014 // If the next token is a comma, consume it and keep reading
2015 // base-specifiers.
Alp Toker97650562014-01-10 11:19:30 +00002016 if (!TryConsumeToken(tok::comma))
2017 break;
Douglas Gregor556877c2008-04-13 21:30:24 +00002018 }
Douglas Gregor29a92472008-10-22 17:49:05 +00002019
2020 // Attach the base specifiers
Craig Topperaa700cb2015-12-27 21:55:19 +00002021 Actions.ActOnBaseSpecifiers(ClassDecl, BaseInfo);
Douglas Gregor556877c2008-04-13 21:30:24 +00002022}
2023
2024/// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is
2025/// one entry in the base class list of a class specifier, for example:
2026/// class foo : public bar, virtual private baz {
2027/// 'public bar' and 'virtual private baz' are each base-specifiers.
2028///
2029/// base-specifier: [C++ class.derived]
Richard Smith4c96e992013-02-19 23:47:15 +00002030/// attribute-specifier-seq[opt] base-type-specifier
2031/// attribute-specifier-seq[opt] 'virtual' access-specifier[opt]
2032/// base-type-specifier
2033/// attribute-specifier-seq[opt] access-specifier 'virtual'[opt]
2034/// base-type-specifier
Craig Topper9ad7e262014-10-31 06:57:07 +00002035BaseResult Parser::ParseBaseSpecifier(Decl *ClassDecl) {
Douglas Gregor556877c2008-04-13 21:30:24 +00002036 bool IsVirtual = false;
2037 SourceLocation StartLoc = Tok.getLocation();
2038
Richard Smith4c96e992013-02-19 23:47:15 +00002039 ParsedAttributesWithRange Attributes(AttrFactory);
2040 MaybeParseCXX11Attributes(Attributes);
2041
Douglas Gregor556877c2008-04-13 21:30:24 +00002042 // Parse the 'virtual' keyword.
Alp Toker97650562014-01-10 11:19:30 +00002043 if (TryConsumeToken(tok::kw_virtual))
Douglas Gregor556877c2008-04-13 21:30:24 +00002044 IsVirtual = true;
Douglas Gregor556877c2008-04-13 21:30:24 +00002045
Richard Smith4c96e992013-02-19 23:47:15 +00002046 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2047
Douglas Gregor556877c2008-04-13 21:30:24 +00002048 // Parse an (optional) access specifier.
2049 AccessSpecifier Access = getAccessSpecifierIfPresent();
John McCall553c0792010-01-23 00:46:32 +00002050 if (Access != AS_none)
Douglas Gregor556877c2008-04-13 21:30:24 +00002051 ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +00002052
Richard Smith4c96e992013-02-19 23:47:15 +00002053 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2054
Douglas Gregor556877c2008-04-13 21:30:24 +00002055 // Parse the 'virtual' keyword (again!), in case it came after the
2056 // access specifier.
2057 if (Tok.is(tok::kw_virtual)) {
2058 SourceLocation VirtualLoc = ConsumeToken();
2059 if (IsVirtual) {
2060 // Complain about duplicate 'virtual'
Chris Lattner6d29c102008-11-18 07:48:38 +00002061 Diag(VirtualLoc, diag::err_dup_virtual)
Douglas Gregora771f462010-03-31 17:46:05 +00002062 << FixItHint::CreateRemoval(VirtualLoc);
Douglas Gregor556877c2008-04-13 21:30:24 +00002063 }
2064
2065 IsVirtual = true;
2066 }
2067
Richard Smith4c96e992013-02-19 23:47:15 +00002068 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2069
Douglas Gregor831c93f2008-11-05 20:51:48 +00002070 // Parse the class-name.
David Majnemer51fd8a02015-07-22 23:46:18 +00002071
2072 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
2073 // implementation for VS2013 uses _Atomic as an identifier for one of the
2074 // classes in <atomic>. Treat '_Atomic' to be an identifier when we are
2075 // parsing the class-name for a base specifier.
2076 if (getLangOpts().MSVCCompat && Tok.is(tok::kw__Atomic) &&
2077 NextToken().is(tok::less))
2078 Tok.setKind(tok::identifier);
2079
Douglas Gregord54dfb82009-02-25 23:52:28 +00002080 SourceLocation EndLocation;
David Blaikie1cd50022011-10-25 17:10:12 +00002081 SourceLocation BaseLoc;
2082 TypeResult BaseType = ParseBaseTypeSpecifier(BaseLoc, EndLocation);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00002083 if (BaseType.isInvalid())
Douglas Gregor831c93f2008-11-05 20:51:48 +00002084 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002085
Fangrui Song6907ce22018-07-30 19:24:48 +00002086 // Parse the optional ellipsis (for a pack expansion). The ellipsis is
Douglas Gregor752a5952011-01-03 22:36:02 +00002087 // actually part of the base-specifier-list grammar productions, but we
2088 // parse it here for convenience.
2089 SourceLocation EllipsisLoc;
Alp Toker97650562014-01-10 11:19:30 +00002090 TryConsumeToken(tok::ellipsis, EllipsisLoc);
2091
Mike Stump11289f42009-09-09 15:08:12 +00002092 // Find the complete source range for the base-specifier.
Douglas Gregord54dfb82009-02-25 23:52:28 +00002093 SourceRange Range(StartLoc, EndLocation);
Mike Stump11289f42009-09-09 15:08:12 +00002094
Douglas Gregor556877c2008-04-13 21:30:24 +00002095 // Notify semantic analysis that we have parsed a complete
2096 // base-specifier.
Richard Smith4c96e992013-02-19 23:47:15 +00002097 return Actions.ActOnBaseSpecifier(ClassDecl, Range, Attributes, IsVirtual,
2098 Access, BaseType.get(), BaseLoc,
2099 EllipsisLoc);
Douglas Gregor556877c2008-04-13 21:30:24 +00002100}
2101
2102/// getAccessSpecifierIfPresent - Determine whether the next token is
2103/// a C++ access-specifier.
2104///
2105/// access-specifier: [C++ class.derived]
2106/// 'private'
2107/// 'protected'
2108/// 'public'
Mike Stump11289f42009-09-09 15:08:12 +00002109AccessSpecifier Parser::getAccessSpecifierIfPresent() const {
Douglas Gregor556877c2008-04-13 21:30:24 +00002110 switch (Tok.getKind()) {
2111 default: return AS_none;
2112 case tok::kw_private: return AS_private;
2113 case tok::kw_protected: return AS_protected;
2114 case tok::kw_public: return AS_public;
2115 }
2116}
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002117
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002118/// If the given declarator has any parts for which parsing has to be
Richard Smith0b3a4622014-11-13 20:01:57 +00002119/// delayed, e.g., default arguments or an exception-specification, create a
2120/// late-parsed method declaration record to handle the parsing at the end of
2121/// the class definition.
Douglas Gregor433e0532012-04-16 18:27:27 +00002122void Parser::HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
2123 Decl *ThisDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00002124 DeclaratorChunk::FunctionTypeInfo &FTI
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002125 = DeclaratorInfo.getFunctionTypeInfo();
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002126 // If there was a late-parsed exception-specification, we'll need a
2127 // late parse
2128 bool NeedLateParse = FTI.getExceptionSpecType() == EST_Unparsed;
Douglas Gregor433e0532012-04-16 18:27:27 +00002129
Nathan Sidwell5bb231c2015-02-19 14:03:22 +00002130 if (!NeedLateParse) {
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002131 // Look ahead to see if there are any default args
Nathan Sidwell5bb231c2015-02-19 14:03:22 +00002132 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx) {
2133 auto Param = cast<ParmVarDecl>(FTI.Params[ParamIdx].Param);
2134 if (Param->hasUnparsedDefaultArg()) {
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002135 NeedLateParse = true;
2136 break;
2137 }
Nathan Sidwell5bb231c2015-02-19 14:03:22 +00002138 }
2139 }
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002140
2141 if (NeedLateParse) {
Richard Smith0b3a4622014-11-13 20:01:57 +00002142 // Push this method onto the stack of late-parsed method
2143 // declarations.
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002144 auto LateMethod = new LateParsedMethodDeclaration(this, ThisDecl);
Richard Smith0b3a4622014-11-13 20:01:57 +00002145 getCurrentClass().LateParsedDeclarations.push_back(LateMethod);
2146 LateMethod->TemplateScope = getCurScope()->isTemplateParamScope();
2147
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002148 // Stash the exception-specification tokens in the late-pased method.
Richard Smith0b3a4622014-11-13 20:01:57 +00002149 LateMethod->ExceptionSpecTokens = FTI.ExceptionSpecTokens;
Hans Wennborgdcfba332015-10-06 23:40:43 +00002150 FTI.ExceptionSpecTokens = nullptr;
Richard Smith0b3a4622014-11-13 20:01:57 +00002151
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002152 // Push tokens for each parameter. Those that do not have
2153 // defaults will be NULL.
Richard Smith0b3a4622014-11-13 20:01:57 +00002154 LateMethod->DefaultArgs.reserve(FTI.NumParams);
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002155 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx)
Alp Tokerc5350722014-02-26 22:27:52 +00002156 LateMethod->DefaultArgs.push_back(LateParsedDefaultArgument(
Malcolm Parsonsca9d8342016-11-17 21:00:09 +00002157 FTI.Params[ParamIdx].Param,
2158 std::move(FTI.Params[ParamIdx].DefaultArgTokens)));
Eli Friedman3af2a772009-07-22 21:45:50 +00002159 }
2160}
2161
Richard Smith89645bc2013-01-02 12:01:23 +00002162/// isCXX11VirtSpecifier - Determine whether the given token is a C++11
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002163/// virt-specifier.
2164///
2165/// virt-specifier:
2166/// override
2167/// final
Andrey Bokhanko276055b2016-07-29 10:42:48 +00002168/// __final
Richard Smith89645bc2013-01-02 12:01:23 +00002169VirtSpecifiers::Specifier Parser::isCXX11VirtSpecifier(const Token &Tok) const {
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002170 if (!getLangOpts().CPlusPlus || Tok.isNot(tok::identifier))
Anders Carlsson4b63d0e2011-01-22 16:56:46 +00002171 return VirtSpecifiers::VS_None;
2172
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002173 IdentifierInfo *II = Tok.getIdentifierInfo();
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002174
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002175 // Initialize the contextual keywords.
2176 if (!Ident_final) {
2177 Ident_final = &PP.getIdentifierTable().get("final");
Andrey Bokhanko276055b2016-07-29 10:42:48 +00002178 if (getLangOpts().GNUKeywords)
2179 Ident_GNU_final = &PP.getIdentifierTable().get("__final");
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002180 if (getLangOpts().MicrosoftExt)
2181 Ident_sealed = &PP.getIdentifierTable().get("sealed");
2182 Ident_override = &PP.getIdentifierTable().get("override");
Anders Carlsson56104902011-01-17 03:05:47 +00002183 }
2184
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002185 if (II == Ident_override)
2186 return VirtSpecifiers::VS_Override;
2187
2188 if (II == Ident_sealed)
2189 return VirtSpecifiers::VS_Sealed;
2190
2191 if (II == Ident_final)
2192 return VirtSpecifiers::VS_Final;
2193
Andrey Bokhanko276055b2016-07-29 10:42:48 +00002194 if (II == Ident_GNU_final)
2195 return VirtSpecifiers::VS_GNU_Final;
2196
Anders Carlsson56104902011-01-17 03:05:47 +00002197 return VirtSpecifiers::VS_None;
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002198}
2199
Richard Smith89645bc2013-01-02 12:01:23 +00002200/// ParseOptionalCXX11VirtSpecifierSeq - Parse a virt-specifier-seq.
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002201///
2202/// virt-specifier-seq:
2203/// virt-specifier
2204/// virt-specifier-seq virt-specifier
Richard Smith89645bc2013-01-02 12:01:23 +00002205void Parser::ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS,
Richard Smith3d1a94c2014-08-12 00:22:39 +00002206 bool IsInterface,
2207 SourceLocation FriendLoc) {
Anders Carlsson56104902011-01-17 03:05:47 +00002208 while (true) {
Richard Smith89645bc2013-01-02 12:01:23 +00002209 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
Anders Carlsson56104902011-01-17 03:05:47 +00002210 if (Specifier == VirtSpecifiers::VS_None)
2211 return;
2212
Richard Smith3d1a94c2014-08-12 00:22:39 +00002213 if (FriendLoc.isValid()) {
2214 Diag(Tok.getLocation(), diag::err_friend_decl_spec)
2215 << VirtSpecifiers::getSpecifierName(Specifier)
2216 << FixItHint::CreateRemoval(Tok.getLocation())
2217 << SourceRange(FriendLoc, FriendLoc);
2218 ConsumeToken();
2219 continue;
2220 }
2221
Anders Carlsson56104902011-01-17 03:05:47 +00002222 // C++ [class.mem]p8:
2223 // A virt-specifier-seq shall contain at most one of each virt-specifier.
Craig Topper161e4db2014-05-21 06:02:52 +00002224 const char *PrevSpec = nullptr;
Anders Carlssonf2ca3892011-01-22 15:58:16 +00002225 if (VS.SetSpecifier(Specifier, Tok.getLocation(), PrevSpec))
Anders Carlsson56104902011-01-17 03:05:47 +00002226 Diag(Tok.getLocation(), diag::err_duplicate_virt_specifier)
2227 << PrevSpec
2228 << FixItHint::CreateRemoval(Tok.getLocation());
2229
David Majnemera5433082013-10-18 00:33:31 +00002230 if (IsInterface && (Specifier == VirtSpecifiers::VS_Final ||
2231 Specifier == VirtSpecifiers::VS_Sealed)) {
John McCalldb632ac2012-09-25 07:32:39 +00002232 Diag(Tok.getLocation(), diag::err_override_control_interface)
2233 << VirtSpecifiers::getSpecifierName(Specifier);
David Majnemera5433082013-10-18 00:33:31 +00002234 } else if (Specifier == VirtSpecifiers::VS_Sealed) {
2235 Diag(Tok.getLocation(), diag::ext_ms_sealed_keyword);
Andrey Bokhanko276055b2016-07-29 10:42:48 +00002236 } else if (Specifier == VirtSpecifiers::VS_GNU_Final) {
2237 Diag(Tok.getLocation(), diag::ext_warn_gnu_final);
John McCalldb632ac2012-09-25 07:32:39 +00002238 } else {
David Majnemera5433082013-10-18 00:33:31 +00002239 Diag(Tok.getLocation(),
2240 getLangOpts().CPlusPlus11
2241 ? diag::warn_cxx98_compat_override_control_keyword
2242 : diag::ext_override_control_keyword)
2243 << VirtSpecifiers::getSpecifierName(Specifier);
John McCalldb632ac2012-09-25 07:32:39 +00002244 }
Anders Carlsson56104902011-01-17 03:05:47 +00002245 ConsumeToken();
2246 }
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002247}
2248
Richard Smith89645bc2013-01-02 12:01:23 +00002249/// isCXX11FinalKeyword - Determine whether the next token is a C++11
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002250/// 'final' or Microsoft 'sealed' contextual keyword.
Richard Smith89645bc2013-01-02 12:01:23 +00002251bool Parser::isCXX11FinalKeyword() const {
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002252 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
2253 return Specifier == VirtSpecifiers::VS_Final ||
Fangrui Song6907ce22018-07-30 19:24:48 +00002254 Specifier == VirtSpecifiers::VS_GNU_Final ||
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002255 Specifier == VirtSpecifiers::VS_Sealed;
Anders Carlsson4b63d0e2011-01-22 16:56:46 +00002256}
2257
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002258/// Parse a C++ member-declarator up to, but not including, the optional
Richard Smith72553fc2014-01-23 23:53:27 +00002259/// brace-or-equal-initializer or pure-specifier.
Nico Weberd89e6f72015-01-16 19:34:13 +00002260bool Parser::ParseCXXMemberDeclaratorBeforeInitializer(
Richard Smith72553fc2014-01-23 23:53:27 +00002261 Declarator &DeclaratorInfo, VirtSpecifiers &VS, ExprResult &BitfieldSize,
2262 LateParsedAttrList &LateParsedAttrs) {
2263 // member-declarator:
2264 // declarator pure-specifier[opt]
2265 // declarator brace-or-equal-initializer[opt]
2266 // identifier[opt] ':' constant-expression
Serge Pavlov458ea762014-07-16 05:16:52 +00002267 if (Tok.isNot(tok::colon))
Richard Smith72553fc2014-01-23 23:53:27 +00002268 ParseDeclarator(DeclaratorInfo);
Richard Smith3d1a94c2014-08-12 00:22:39 +00002269 else
2270 DeclaratorInfo.SetIdentifier(nullptr, Tok.getLocation());
Richard Smith72553fc2014-01-23 23:53:27 +00002271
2272 if (!DeclaratorInfo.isFunctionDeclarator() && TryConsumeToken(tok::colon)) {
Richard Smith3d1a94c2014-08-12 00:22:39 +00002273 assert(DeclaratorInfo.isPastIdentifier() &&
2274 "don't know where identifier would go yet?");
Richard Smith72553fc2014-01-23 23:53:27 +00002275 BitfieldSize = ParseConstantExpression();
2276 if (BitfieldSize.isInvalid())
2277 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002278 } else {
Richard Smith3d1a94c2014-08-12 00:22:39 +00002279 ParseOptionalCXX11VirtSpecifierSeq(
2280 VS, getCurrentClass().IsInterface,
2281 DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002282 if (!VS.isUnset())
2283 MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo, VS);
2284 }
Richard Smith72553fc2014-01-23 23:53:27 +00002285
2286 // If a simple-asm-expr is present, parse it.
2287 if (Tok.is(tok::kw_asm)) {
2288 SourceLocation Loc;
2289 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
2290 if (AsmLabel.isInvalid())
2291 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2292
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002293 DeclaratorInfo.setAsmLabel(AsmLabel.get());
Richard Smith72553fc2014-01-23 23:53:27 +00002294 DeclaratorInfo.SetRangeEnd(Loc);
2295 }
2296
2297 // If attributes exist after the declarator, but before an '{', parse them.
2298 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
Richard Smith4b5a9492014-01-24 22:34:35 +00002299
2300 // For compatibility with code written to older Clang, also accept a
2301 // virt-specifier *after* the GNU attributes.
Aaron Ballman5d153e32014-08-04 17:03:51 +00002302 if (BitfieldSize.isUnset() && VS.isUnset()) {
Richard Smith3d1a94c2014-08-12 00:22:39 +00002303 ParseOptionalCXX11VirtSpecifierSeq(
2304 VS, getCurrentClass().IsInterface,
2305 DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
Aaron Ballman5d153e32014-08-04 17:03:51 +00002306 if (!VS.isUnset()) {
2307 // If we saw any GNU-style attributes that are known to GCC followed by a
2308 // virt-specifier, issue a GCC-compat warning.
Erich Keanee891aa92018-07-13 15:07:47 +00002309 for (const ParsedAttr &AL : DeclaratorInfo.getAttributes())
Erich Keanec480f302018-07-12 21:09:05 +00002310 if (AL.isKnownToGCC() && !AL.isCXX11Attribute())
2311 Diag(AL.getLoc(), diag::warn_gcc_attribute_location);
2312
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002313 MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo, VS);
Aaron Ballman5d153e32014-08-04 17:03:51 +00002314 }
2315 }
Nico Weberd89e6f72015-01-16 19:34:13 +00002316
2317 // If this has neither a name nor a bit width, something has gone seriously
2318 // wrong. Skip until the semi-colon or }.
2319 if (!DeclaratorInfo.hasName() && BitfieldSize.isUnset()) {
2320 // If so, skip until the semi-colon or a }.
2321 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2322 return true;
2323 }
2324 return false;
Richard Smith72553fc2014-01-23 23:53:27 +00002325}
2326
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002327/// Look for declaration specifiers possibly occurring after C++11
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002328/// virt-specifier-seq and diagnose them.
2329void Parser::MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(
2330 Declarator &D,
2331 VirtSpecifiers &VS) {
2332 DeclSpec DS(AttrFactory);
2333
2334 // GNU-style and C++11 attributes are not allowed here, but they will be
2335 // handled by the caller. Diagnose everything else.
Alex Lorenz8f4d3992017-02-13 23:19:40 +00002336 ParseTypeQualifierListOpt(
2337 DS, AR_NoAttributesParsed, false,
2338 /*IdentifierRequired=*/false, llvm::function_ref<void()>([&]() {
2339 Actions.CodeCompleteFunctionQualifiers(DS, D, &VS);
2340 }));
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002341 D.ExtendWithDeclSpec(DS);
2342
2343 if (D.isFunctionDeclarator()) {
Ehsan Akhgaric07d1e22015-03-25 00:53:33 +00002344 auto &Function = D.getFunctionTypeInfo();
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002345 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
2346 auto DeclSpecCheck = [&] (DeclSpec::TQ TypeQual,
2347 const char *FixItName,
2348 SourceLocation SpecLoc,
2349 unsigned* QualifierLoc) {
2350 FixItHint Insertion;
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002351 if (DS.getTypeQualifiers() & TypeQual) {
2352 if (!(Function.TypeQuals & TypeQual)) {
2353 std::string Name(FixItName);
2354 Name += " ";
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00002355 Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), Name);
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002356 Function.TypeQuals |= TypeQual;
2357 *QualifierLoc = SpecLoc.getRawEncoding();
2358 }
2359 Diag(SpecLoc, diag::err_declspec_after_virtspec)
2360 << FixItName
2361 << VirtSpecifiers::getSpecifierName(VS.getLastSpecifier())
2362 << FixItHint::CreateRemoval(SpecLoc)
2363 << Insertion;
2364 }
2365 };
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002366 DeclSpecCheck(DeclSpec::TQ_const, "const", DS.getConstSpecLoc(),
2367 &Function.ConstQualifierLoc);
2368 DeclSpecCheck(DeclSpec::TQ_volatile, "volatile", DS.getVolatileSpecLoc(),
2369 &Function.VolatileQualifierLoc);
2370 DeclSpecCheck(DeclSpec::TQ_restrict, "restrict", DS.getRestrictSpecLoc(),
2371 &Function.RestrictQualifierLoc);
2372 }
Ehsan Akhgaric07d1e22015-03-25 00:53:33 +00002373
2374 // Parse ref-qualifiers.
2375 bool RefQualifierIsLValueRef = true;
2376 SourceLocation RefQualifierLoc;
2377 if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc)) {
2378 const char *Name = (RefQualifierIsLValueRef ? "& " : "&& ");
2379 FixItHint Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), Name);
2380 Function.RefQualifierIsLValueRef = RefQualifierIsLValueRef;
2381 Function.RefQualifierLoc = RefQualifierLoc.getRawEncoding();
2382
2383 Diag(RefQualifierLoc, diag::err_declspec_after_virtspec)
2384 << (RefQualifierIsLValueRef ? "&" : "&&")
2385 << VirtSpecifiers::getSpecifierName(VS.getLastSpecifier())
2386 << FixItHint::CreateRemoval(RefQualifierLoc)
2387 << Insertion;
2388 D.SetRangeEnd(RefQualifierLoc);
2389 }
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002390 }
2391}
2392
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002393/// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration.
2394///
2395/// member-declaration:
2396/// decl-specifier-seq[opt] member-declarator-list[opt] ';'
2397/// function-definition ';'[opt]
2398/// ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO]
2399/// using-declaration [TODO]
Anders Carlssonf24fcff62009-03-11 16:27:10 +00002400/// [C++0x] static_assert-declaration
Anders Carlssondfbbdf62009-03-26 00:52:18 +00002401/// template-declaration
Chris Lattnerd19c1c02008-12-18 01:12:00 +00002402/// [GNU] '__extension__' member-declaration
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002403///
2404/// member-declarator-list:
2405/// member-declarator
2406/// member-declarator-list ',' member-declarator
2407///
2408/// member-declarator:
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002409/// declarator virt-specifier-seq[opt] pure-specifier[opt]
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002410/// declarator constant-initializer[opt]
Richard Smith938f40b2011-06-11 17:19:42 +00002411/// [C++11] declarator brace-or-equal-initializer[opt]
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002412/// identifier[opt] ':' constant-expression
2413///
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002414/// virt-specifier-seq:
2415/// virt-specifier
2416/// virt-specifier-seq virt-specifier
2417///
2418/// virt-specifier:
2419/// override
2420/// final
David Majnemera5433082013-10-18 00:33:31 +00002421/// [MS] sealed
Fangrui Song6907ce22018-07-30 19:24:48 +00002422///
Sebastian Redl42e92c42009-04-12 17:16:29 +00002423/// pure-specifier:
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002424/// '= 0'
2425///
2426/// constant-initializer:
2427/// '=' constant-expression
2428///
Alexey Bataev05c25d62015-07-31 08:42:25 +00002429Parser::DeclGroupPtrTy
2430Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS,
Erich Keanec480f302018-07-12 21:09:05 +00002431 ParsedAttributes &AccessAttrs,
John McCall796c2a52010-07-16 08:13:16 +00002432 const ParsedTemplateInfo &TemplateInfo,
2433 ParsingDeclRAIIObject *TemplateDiags) {
Douglas Gregor23c84762011-04-14 17:21:19 +00002434 if (Tok.is(tok::at)) {
Erik Pilkingtonfa983902018-10-30 20:31:30 +00002435 if (getLangOpts().ObjC && NextToken().isObjCAtKeyword(tok::objc_defs))
Douglas Gregor23c84762011-04-14 17:21:19 +00002436 Diag(Tok, diag::err_at_defs_cxx);
2437 else
2438 Diag(Tok, diag::err_at_in_class);
Richard Smithda35e962013-11-09 04:52:51 +00002439
Douglas Gregor23c84762011-04-14 17:21:19 +00002440 ConsumeToken();
Alexey Bataevee6507d2013-11-18 08:17:37 +00002441 SkipUntil(tok::r_brace, StopAtSemi);
David Blaikie0403cb12016-01-15 23:43:25 +00002442 return nullptr;
Douglas Gregor23c84762011-04-14 17:21:19 +00002443 }
Richard Smithda35e962013-11-09 04:52:51 +00002444
Serge Pavlov458ea762014-07-16 05:16:52 +00002445 // Turn on colon protection early, while parsing declspec, although there is
2446 // nothing to protect there. It prevents from false errors if error recovery
2447 // incorrectly determines where the declspec ends, as in the example:
2448 // struct A { enum class B { C }; };
2449 // const int C = 4;
2450 // struct D { A::B : C; };
2451 ColonProtectionRAIIObject X(*this);
2452
John McCalla0097262009-12-11 02:10:03 +00002453 // Access declarations.
Richard Smith45855df2012-05-09 08:23:23 +00002454 bool MalformedTypeSpec = false;
John McCalla0097262009-12-11 02:10:03 +00002455 if (!TemplateInfo.Kind &&
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002456 Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw___super)) {
Richard Smith45855df2012-05-09 08:23:23 +00002457 if (TryAnnotateCXXScopeToken())
2458 MalformedTypeSpec = true;
2459
2460 bool isAccessDecl;
2461 if (Tok.isNot(tok::annot_cxxscope))
2462 isAccessDecl = false;
2463 else if (NextToken().is(tok::identifier))
John McCalla0097262009-12-11 02:10:03 +00002464 isAccessDecl = GetLookAheadToken(2).is(tok::semi);
2465 else
2466 isAccessDecl = NextToken().is(tok::kw_operator);
2467
2468 if (isAccessDecl) {
2469 // Collect the scope specifier token we annotated earlier.
2470 CXXScopeSpec SS;
David Blaikieefdccaa2016-01-15 23:43:34 +00002471 ParseOptionalCXXScopeSpecifier(SS, nullptr,
Douglas Gregordf593fb2011-11-07 17:33:42 +00002472 /*EnteringContext=*/false);
John McCalla0097262009-12-11 02:10:03 +00002473
Nico Weberef03e702014-09-10 00:59:37 +00002474 if (SS.isInvalid()) {
2475 SkipUntil(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002476 return nullptr;
Nico Weberef03e702014-09-10 00:59:37 +00002477 }
2478
John McCalla0097262009-12-11 02:10:03 +00002479 // Try to parse an unqualified-id.
Abramo Bagnara7945c982012-01-27 09:46:47 +00002480 SourceLocation TemplateKWLoc;
John McCalla0097262009-12-11 02:10:03 +00002481 UnqualifiedId Name;
Richard Smith35845152017-02-07 01:37:30 +00002482 if (ParseUnqualifiedId(SS, false, true, true, false, nullptr,
Richard Smithc08b6932018-04-27 02:00:13 +00002483 &TemplateKWLoc, Name)) {
John McCalla0097262009-12-11 02:10:03 +00002484 SkipUntil(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002485 return nullptr;
John McCalla0097262009-12-11 02:10:03 +00002486 }
2487
2488 // TODO: recover from mistakenly-qualified operator declarations.
Alp Toker383d2c42014-01-01 03:08:43 +00002489 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
2490 "access declaration")) {
2491 SkipUntil(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002492 return nullptr;
Alp Toker383d2c42014-01-01 03:08:43 +00002493 }
John McCalla0097262009-12-11 02:10:03 +00002494
Richard Smithc08b6932018-04-27 02:00:13 +00002495 // FIXME: We should do something with the 'template' keyword here.
Alexey Bataev05c25d62015-07-31 08:42:25 +00002496 return DeclGroupPtrTy::make(DeclGroupRef(Actions.ActOnUsingDeclaration(
Richard Smith151c4562016-12-20 21:35:28 +00002497 getCurScope(), AS, /*UsingLoc*/ SourceLocation(),
2498 /*TypenameLoc*/ SourceLocation(), SS, Name,
Erich Keanec480f302018-07-12 21:09:05 +00002499 /*EllipsisLoc*/ SourceLocation(),
2500 /*AttrList*/ ParsedAttributesView())));
John McCalla0097262009-12-11 02:10:03 +00002501 }
2502 }
2503
Aaron Ballmane7c544d2014-08-04 20:28:35 +00002504 // static_assert-declaration. A templated static_assert declaration is
2505 // diagnosed in Parser::ParseSingleDeclarationAfterTemplate.
2506 if (!TemplateInfo.Kind &&
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002507 Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert)) {
Chris Lattner49836b42009-04-02 04:16:50 +00002508 SourceLocation DeclEnd;
Alexey Bataev05c25d62015-07-31 08:42:25 +00002509 return DeclGroupPtrTy::make(
2510 DeclGroupRef(ParseStaticAssertDeclaration(DeclEnd)));
Chris Lattner5bbb3c82009-03-29 16:50:03 +00002511 }
Mike Stump11289f42009-09-09 15:08:12 +00002512
Chris Lattner5bbb3c82009-03-29 16:50:03 +00002513 if (Tok.is(tok::kw_template)) {
Mike Stump11289f42009-09-09 15:08:12 +00002514 assert(!TemplateInfo.TemplateParams &&
Douglas Gregor3447e762009-08-20 22:52:58 +00002515 "Nested template improperly parsed?");
Richard Smith3af70092017-02-09 22:14:25 +00002516 ObjCDeclContextSwitch ObjCDC(*this);
Chris Lattner49836b42009-04-02 04:16:50 +00002517 SourceLocation DeclEnd;
Alexey Bataev05c25d62015-07-31 08:42:25 +00002518 return DeclGroupPtrTy::make(
Richard Smith3af70092017-02-09 22:14:25 +00002519 DeclGroupRef(ParseTemplateDeclarationOrSpecialization(
Erich Keanec480f302018-07-12 21:09:05 +00002520 DeclaratorContext::MemberContext, DeclEnd, AccessAttrs, AS)));
Chris Lattner5bbb3c82009-03-29 16:50:03 +00002521 }
Anders Carlssondfbbdf62009-03-26 00:52:18 +00002522
Chris Lattnerd19c1c02008-12-18 01:12:00 +00002523 // Handle: member-declaration ::= '__extension__' member-declaration
2524 if (Tok.is(tok::kw___extension__)) {
2525 // __extension__ silences extension warnings in the subexpression.
2526 ExtensionRAIIObject O(Diags); // Use RAII to do this.
2527 ConsumeToken();
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00002528 return ParseCXXClassMemberDeclaration(AS, AccessAttrs,
2529 TemplateInfo, TemplateDiags);
Chris Lattnerd19c1c02008-12-18 01:12:00 +00002530 }
Douglas Gregorfec52632009-06-20 00:51:54 +00002531
John McCall084e83d2011-03-24 11:26:52 +00002532 ParsedAttributesWithRange attrs(AttrFactory);
Erich Keanec480f302018-07-12 21:09:05 +00002533 ParsedAttributesViewWithRange FnAttrs;
Richard Smith89645bc2013-01-02 12:01:23 +00002534 // Optional C++11 attribute-specifier
2535 MaybeParseCXX11Attributes(attrs);
Michael Handdc016d2012-11-28 23:17:40 +00002536 // We need to keep these attributes for future diagnostic
2537 // before they are taken over by declaration specifier.
Erich Keanec480f302018-07-12 21:09:05 +00002538 FnAttrs.addAll(attrs.begin(), attrs.end());
Michael Handdc016d2012-11-28 23:17:40 +00002539 FnAttrs.Range = attrs.Range;
2540
John McCall53fa7142010-12-24 02:08:15 +00002541 MaybeParseMicrosoftAttributes(attrs);
Alexis Hunt96d5c762009-11-21 08:43:09 +00002542
Douglas Gregorfec52632009-06-20 00:51:54 +00002543 if (Tok.is(tok::kw_using)) {
John McCall53fa7142010-12-24 02:08:15 +00002544 ProhibitAttributes(attrs);
Mike Stump11289f42009-09-09 15:08:12 +00002545
Douglas Gregorfec52632009-06-20 00:51:54 +00002546 // Eat 'using'.
2547 SourceLocation UsingLoc = ConsumeToken();
2548
2549 if (Tok.is(tok::kw_namespace)) {
2550 Diag(UsingLoc, diag::err_using_namespace_in_class);
Alexey Bataevee6507d2013-11-18 08:17:37 +00002551 SkipUntil(tok::semi, StopBeforeMatch);
David Blaikie0403cb12016-01-15 23:43:25 +00002552 return nullptr;
Douglas Gregorfec52632009-06-20 00:51:54 +00002553 }
Alexey Bataev05c25d62015-07-31 08:42:25 +00002554 SourceLocation DeclEnd;
2555 // Otherwise, it must be a using-declaration or an alias-declaration.
Faisal Vali421b2d12017-12-29 05:41:00 +00002556 return ParseUsingDeclaration(DeclaratorContext::MemberContext, TemplateInfo,
Richard Smith6f1daa42016-12-16 00:58:48 +00002557 UsingLoc, DeclEnd, AS);
Douglas Gregorfec52632009-06-20 00:51:54 +00002558 }
2559
DeLesley Hutchinsbd2ee132012-03-02 22:12:59 +00002560 // Hold late-parsed attributes so we can attach a Decl to them later.
2561 LateParsedAttrList CommonLateParsedAttrs;
2562
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002563 // decl-specifier-seq:
2564 // Parse the common declaration-specifiers piece.
John McCall796c2a52010-07-16 08:13:16 +00002565 ParsingDeclSpec DS(*this, TemplateDiags);
John McCall53fa7142010-12-24 02:08:15 +00002566 DS.takeAttributesFrom(attrs);
Richard Smith45855df2012-05-09 08:23:23 +00002567 if (MalformedTypeSpec)
2568 DS.SetTypeSpecError();
Richard Smith72553fc2014-01-23 23:53:27 +00002569
Faisal Valia534f072018-04-26 00:42:40 +00002570 ParseDeclarationSpecifiers(DS, TemplateInfo, AS, DeclSpecContext::DSC_class,
2571 &CommonLateParsedAttrs);
Serge Pavlov458ea762014-07-16 05:16:52 +00002572
2573 // Turn off colon protection that was set for declspec.
2574 X.restore();
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002575
Richard Smith404dfb42013-11-19 22:47:36 +00002576 // If we had a free-standing type definition with a missing semicolon, we
2577 // may get this far before the problem becomes obvious.
2578 if (DS.hasTagDefinition() &&
2579 TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate &&
Faisal Vali7db85c52017-12-31 00:06:40 +00002580 DiagnoseMissingSemiAfterTagDefinition(DS, AS, DeclSpecContext::DSC_class,
Richard Smith404dfb42013-11-19 22:47:36 +00002581 &CommonLateParsedAttrs))
David Blaikie0403cb12016-01-15 23:43:25 +00002582 return nullptr;
Richard Smith404dfb42013-11-19 22:47:36 +00002583
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002584 MultiTemplateParamsArg TemplateParams(
Craig Topper161e4db2014-05-21 06:02:52 +00002585 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->data()
2586 : nullptr,
John McCall11083da2009-09-16 22:47:08 +00002587 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->size() : 0);
2588
Alp Toker35d87032013-12-30 23:29:50 +00002589 if (TryConsumeToken(tok::semi)) {
Michael Handdc016d2012-11-28 23:17:40 +00002590 if (DS.isFriendSpecified())
2591 ProhibitAttributes(FnAttrs);
2592
Nico Weber7b837f52016-01-28 19:25:00 +00002593 RecordDecl *AnonRecord = nullptr;
2594 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(
2595 getCurScope(), AS, DS, TemplateParams, false, AnonRecord);
John McCall796c2a52010-07-16 08:13:16 +00002596 DS.complete(TheDecl);
Nico Weber7b837f52016-01-28 19:25:00 +00002597 if (AnonRecord) {
2598 Decl* decls[] = {AnonRecord, TheDecl};
Richard Smith3beb7c62017-01-12 02:27:38 +00002599 return Actions.BuildDeclaratorGroup(decls);
Nico Weber7b837f52016-01-28 19:25:00 +00002600 }
2601 return Actions.ConvertDeclToDeclGroup(TheDecl);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002602 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002603
Faisal Vali421b2d12017-12-29 05:41:00 +00002604 ParsingDeclarator DeclaratorInfo(*this, DS, DeclaratorContext::MemberContext);
Nico Weber24b2a822011-01-28 06:07:34 +00002605 VirtSpecifiers VS;
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002606
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002607 // Hold late-parsed attributes so we can attach a Decl to them later.
2608 LateParsedAttrList LateParsedAttrs;
2609
Douglas Gregor50cefbf2011-10-17 17:09:53 +00002610 SourceLocation EqualLoc;
Richard Smith9ba0fec2015-06-30 01:28:56 +00002611 SourceLocation PureSpecLoc;
2612
Yaron Keren180c1672015-06-30 07:35:19 +00002613 auto TryConsumePureSpecifier = [&] (bool AllowDefinition) {
Richard Smith9ba0fec2015-06-30 01:28:56 +00002614 if (Tok.isNot(tok::equal))
2615 return false;
2616
2617 auto &Zero = NextToken();
2618 SmallString<8> Buffer;
2619 if (Zero.isNot(tok::numeric_constant) || Zero.getLength() != 1 ||
2620 PP.getSpelling(Zero, Buffer) != "0")
2621 return false;
2622
2623 auto &After = GetLookAheadToken(2);
2624 if (!After.isOneOf(tok::semi, tok::comma) &&
2625 !(AllowDefinition &&
2626 After.isOneOf(tok::l_brace, tok::colon, tok::kw_try)))
2627 return false;
2628
2629 EqualLoc = ConsumeToken();
2630 PureSpecLoc = ConsumeToken();
2631 return true;
2632 };
Chris Lattner17c3b1f2009-12-10 01:59:24 +00002633
Richard Smith72553fc2014-01-23 23:53:27 +00002634 SmallVector<Decl *, 8> DeclsInGroup;
2635 ExprResult BitfieldSize;
2636 bool ExpectSemi = true;
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002637
Richard Smith72553fc2014-01-23 23:53:27 +00002638 // Parse the first declarator.
Nico Weberd89e6f72015-01-16 19:34:13 +00002639 if (ParseCXXMemberDeclaratorBeforeInitializer(
2640 DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs)) {
Richard Smith72553fc2014-01-23 23:53:27 +00002641 TryConsumeToken(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002642 return nullptr;
Richard Smith72553fc2014-01-23 23:53:27 +00002643 }
John Thompson5bc5cbe2009-11-25 22:58:06 +00002644
Richard Smith72553fc2014-01-23 23:53:27 +00002645 // Check for a member function definition.
Richard Smith4b5a9492014-01-24 22:34:35 +00002646 if (BitfieldSize.isUnset()) {
Richard Smith72553fc2014-01-23 23:53:27 +00002647 // MSVC permits pure specifier on inline functions defined at class scope.
Francois Pichet3abc9b82011-05-11 02:14:46 +00002648 // Hence check for =0 before checking for function definition.
Richard Smith9ba0fec2015-06-30 01:28:56 +00002649 if (getLangOpts().MicrosoftExt && DeclaratorInfo.isDeclarationOfFunction())
2650 TryConsumePureSpecifier(/*AllowDefinition*/ true);
Francois Pichet3abc9b82011-05-11 02:14:46 +00002651
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00002652 FunctionDefinitionKind DefinitionKind = FDK_Declaration;
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002653 // function-definition:
Richard Smith938f40b2011-06-11 17:19:42 +00002654 //
2655 // In C++11, a non-function declarator followed by an open brace is a
2656 // braced-init-list for an in-class member initialization, not an
2657 // erroneous function definition.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002658 if (Tok.is(tok::l_brace) && !getLangOpts().CPlusPlus11) {
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00002659 DefinitionKind = FDK_Definition;
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002660 } else if (DeclaratorInfo.isFunctionDeclarator()) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002661 if (Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try)) {
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00002662 DefinitionKind = FDK_Definition;
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002663 } else if (Tok.is(tok::equal)) {
2664 const Token &KW = NextToken();
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00002665 if (KW.is(tok::kw_default))
2666 DefinitionKind = FDK_Defaulted;
2667 else if (KW.is(tok::kw_delete))
2668 DefinitionKind = FDK_Deleted;
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002669 }
2670 }
Eli Bendersky41842222015-03-23 23:49:41 +00002671 DeclaratorInfo.setFunctionDefinitionKind(DefinitionKind);
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002672
Fangrui Song6907ce22018-07-30 19:24:48 +00002673 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
Michael Handdc016d2012-11-28 23:17:40 +00002674 // to a friend declaration, that declaration shall be a definition.
Fangrui Song6907ce22018-07-30 19:24:48 +00002675 if (DeclaratorInfo.isFunctionDeclarator() &&
Michael Handdc016d2012-11-28 23:17:40 +00002676 DefinitionKind != FDK_Definition && DS.isFriendSpecified()) {
2677 // Diagnose attributes that appear before decl specifier:
2678 // [[]] friend int foo();
2679 ProhibitAttributes(FnAttrs);
2680 }
2681
Nico Webera7f137d2015-01-16 19:35:01 +00002682 if (DefinitionKind != FDK_Declaration) {
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002683 if (!DeclaratorInfo.isFunctionDeclarator()) {
Richard Trieu0d730542012-01-21 02:59:18 +00002684 Diag(DeclaratorInfo.getIdentifierLoc(), diag::err_func_def_no_params);
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002685 ConsumeBrace();
Alexey Bataevee6507d2013-11-18 08:17:37 +00002686 SkipUntil(tok::r_brace);
Michael Handdc016d2012-11-28 23:17:40 +00002687
Douglas Gregor8a4db832011-01-19 16:41:58 +00002688 // Consume the optional ';'
Alp Toker35d87032013-12-30 23:29:50 +00002689 TryConsumeToken(tok::semi);
2690
David Blaikie0403cb12016-01-15 23:43:25 +00002691 return nullptr;
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002692 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002693
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002694 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
Richard Trieu0d730542012-01-21 02:59:18 +00002695 Diag(DeclaratorInfo.getIdentifierLoc(),
2696 diag::err_function_declared_typedef);
Douglas Gregor8a4db832011-01-19 16:41:58 +00002697
Richard Smith2603b092012-11-15 22:54:20 +00002698 // Recover by treating the 'typedef' as spurious.
2699 DS.ClearStorageClassSpecs();
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002700 }
2701
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002702 Decl *FunDecl =
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00002703 ParseCXXInlineMethodDef(AS, AccessAttrs, DeclaratorInfo, TemplateInfo,
Richard Smith9ba0fec2015-06-30 01:28:56 +00002704 VS, PureSpecLoc);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002705
David Majnemer23252a32013-08-01 04:22:55 +00002706 if (FunDecl) {
2707 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i) {
2708 CommonLateParsedAttrs[i]->addDecl(FunDecl);
2709 }
2710 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i) {
2711 LateParsedAttrs[i]->addDecl(FunDecl);
2712 }
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002713 }
2714 LateParsedAttrs.clear();
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002715
2716 // Consume the ';' - it's optional unless we have a delete or default
Richard Trieu2f7dc462012-05-16 19:04:59 +00002717 if (Tok.is(tok::semi))
Richard Smith87f5dc52012-07-23 05:45:25 +00002718 ConsumeExtraSemi(AfterMemberFunctionDefinition);
Douglas Gregor8a4db832011-01-19 16:41:58 +00002719
Alexey Bataev05c25d62015-07-31 08:42:25 +00002720 return DeclGroupPtrTy::make(DeclGroupRef(FunDecl));
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002721 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002722 }
2723
2724 // member-declarator-list:
2725 // member-declarator
2726 // member-declarator-list ',' member-declarator
2727
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002728 while (1) {
Richard Smith2b013182012-06-10 03:12:00 +00002729 InClassInitStyle HasInClassInit = ICIS_NoInit;
Richard Smith9ba0fec2015-06-30 01:28:56 +00002730 bool HasStaticInitializer = false;
2731 if (Tok.isOneOf(tok::equal, tok::l_brace) && PureSpecLoc.isInvalid()) {
Richard Smith6b8e3c02017-08-28 00:28:14 +00002732 if (DeclaratorInfo.isDeclarationOfFunction()) {
Richard Smith9ba0fec2015-06-30 01:28:56 +00002733 // It's a pure-specifier.
2734 if (!TryConsumePureSpecifier(/*AllowFunctionDefinition*/ false))
2735 // Parse it as an expression so that Sema can diagnose it.
2736 HasStaticInitializer = true;
2737 } else if (DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2738 DeclSpec::SCS_static &&
2739 DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2740 DeclSpec::SCS_typedef &&
2741 !DS.isFriendSpecified()) {
2742 // It's a default member initializer.
Richard Smith6b8e3c02017-08-28 00:28:14 +00002743 if (BitfieldSize.get())
2744 Diag(Tok, getLangOpts().CPlusPlus2a
2745 ? diag::warn_cxx17_compat_bitfield_member_init
2746 : diag::ext_bitfield_member_init);
Richard Smith9ba0fec2015-06-30 01:28:56 +00002747 HasInClassInit = Tok.is(tok::equal) ? ICIS_CopyInit : ICIS_ListInit;
Richard Smith938f40b2011-06-11 17:19:42 +00002748 } else {
Richard Smith9ba0fec2015-06-30 01:28:56 +00002749 HasStaticInitializer = true;
Richard Smith938f40b2011-06-11 17:19:42 +00002750 }
2751 }
2752
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002753 // NOTE: If Sema is the Action module and declarator is an instance field,
Chris Lattner5bbb3c82009-03-29 16:50:03 +00002754 // this call will *not* return the created decl; It will return null.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002755 // See Sema::ActOnCXXMemberDeclarator for details.
John McCall07e91c02009-08-06 02:15:43 +00002756
Craig Topper161e4db2014-05-21 06:02:52 +00002757 NamedDecl *ThisDecl = nullptr;
John McCall07e91c02009-08-06 02:15:43 +00002758 if (DS.isFriendSpecified()) {
Richard Smith72553fc2014-01-23 23:53:27 +00002759 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
Michael Handdc016d2012-11-28 23:17:40 +00002760 // to a friend declaration, that declaration shall be a definition.
2761 //
Richard Smith72553fc2014-01-23 23:53:27 +00002762 // Diagnose attributes that appear in a friend member function declarator:
2763 // friend int foo [[]] ();
Michael Handdc016d2012-11-28 23:17:40 +00002764 SmallVector<SourceRange, 4> Ranges;
2765 DeclaratorInfo.getCXX11AttributeRanges(Ranges);
Richard Smith72553fc2014-01-23 23:53:27 +00002766 for (SmallVectorImpl<SourceRange>::iterator I = Ranges.begin(),
2767 E = Ranges.end(); I != E; ++I)
2768 Diag((*I).getBegin(), diag::err_attributes_not_allowed) << *I;
Michael Handdc016d2012-11-28 23:17:40 +00002769
Douglas Gregor0be31a22010-07-02 17:43:08 +00002770 ThisDecl = Actions.ActOnFriendFunctionDecl(getCurScope(), DeclaratorInfo,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002771 TemplateParams);
Douglas Gregor3447e762009-08-20 22:52:58 +00002772 } else {
Douglas Gregor0be31a22010-07-02 17:43:08 +00002773 ThisDecl = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS,
John McCall07e91c02009-08-06 02:15:43 +00002774 DeclaratorInfo,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002775 TemplateParams,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002776 BitfieldSize.get(),
Richard Smith2b013182012-06-10 03:12:00 +00002777 VS, HasInClassInit);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002778
2779 if (VarTemplateDecl *VT =
Craig Topper161e4db2014-05-21 06:02:52 +00002780 ThisDecl ? dyn_cast<VarTemplateDecl>(ThisDecl) : nullptr)
Larisse Voufo39a1e502013-08-06 01:03:05 +00002781 // Re-direct this decl to refer to the templated decl so that we can
2782 // initialize it.
2783 ThisDecl = VT->getTemplatedDecl();
2784
Erich Keanec480f302018-07-12 21:09:05 +00002785 if (ThisDecl)
Richard Smithf8a75c32013-08-29 00:47:48 +00002786 Actions.ProcessDeclAttributeList(getCurScope(), ThisDecl, AccessAttrs);
Douglas Gregor3447e762009-08-20 22:52:58 +00002787 }
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002788
Richard Smith9ba0fec2015-06-30 01:28:56 +00002789 // Error recovery might have converted a non-static member into a static
2790 // member.
David Blaikie35506f82013-01-30 01:22:18 +00002791 if (HasInClassInit != ICIS_NoInit &&
Richard Smith9ba0fec2015-06-30 01:28:56 +00002792 DeclaratorInfo.getDeclSpec().getStorageClassSpec() ==
2793 DeclSpec::SCS_static) {
2794 HasInClassInit = ICIS_NoInit;
2795 HasStaticInitializer = true;
2796 }
2797
2798 if (ThisDecl && PureSpecLoc.isValid())
2799 Actions.ActOnPureSpecifier(ThisDecl, PureSpecLoc);
2800
2801 // Handle the initializer.
2802 if (HasInClassInit != ICIS_NoInit) {
Douglas Gregor728d00b2011-10-10 14:49:18 +00002803 // The initializer was deferred; parse it and cache the tokens.
David Majnemer23252a32013-08-01 04:22:55 +00002804 Diag(Tok, getLangOpts().CPlusPlus11
2805 ? diag::warn_cxx98_compat_nonstatic_member_init
2806 : diag::ext_nonstatic_member_init);
Richard Smith5d164bc2011-10-15 05:09:34 +00002807
Richard Smith938f40b2011-06-11 17:19:42 +00002808 if (DeclaratorInfo.isArrayOfUnknownBound()) {
Richard Smith2b013182012-06-10 03:12:00 +00002809 // C++11 [dcl.array]p3: An array bound may also be omitted when the
2810 // declarator is followed by an initializer.
Richard Smith938f40b2011-06-11 17:19:42 +00002811 //
2812 // A brace-or-equal-initializer for a member-declarator is not an
David Blaikiecdd91db2012-02-14 09:00:46 +00002813 // initializer in the grammar, so this is ill-formed.
Richard Smith938f40b2011-06-11 17:19:42 +00002814 Diag(Tok, diag::err_incomplete_array_member_init);
Alexey Bataevee6507d2013-11-18 08:17:37 +00002815 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
David Majnemer23252a32013-08-01 04:22:55 +00002816
2817 // Avoid later warnings about a class member of incomplete type.
David Blaikiecdd91db2012-02-14 09:00:46 +00002818 if (ThisDecl)
David Blaikiecdd91db2012-02-14 09:00:46 +00002819 ThisDecl->setInvalidDecl();
Richard Smith938f40b2011-06-11 17:19:42 +00002820 } else
2821 ParseCXXNonStaticMemberInitializer(ThisDecl);
Richard Smith9ba0fec2015-06-30 01:28:56 +00002822 } else if (HasStaticInitializer) {
Douglas Gregor728d00b2011-10-10 14:49:18 +00002823 // Normal initializer.
Richard Smith9ba0fec2015-06-30 01:28:56 +00002824 ExprResult Init = ParseCXXMemberInitializer(
2825 ThisDecl, DeclaratorInfo.isDeclarationOfFunction(), EqualLoc);
David Majnemer23252a32013-08-01 04:22:55 +00002826
Douglas Gregor728d00b2011-10-10 14:49:18 +00002827 if (Init.isInvalid())
Alexey Bataevee6507d2013-11-18 08:17:37 +00002828 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
Douglas Gregor728d00b2011-10-10 14:49:18 +00002829 else if (ThisDecl)
Richard Smith3beb7c62017-01-12 02:27:38 +00002830 Actions.AddInitializerToDecl(ThisDecl, Init.get(), EqualLoc.isInvalid());
David Majnemer23252a32013-08-01 04:22:55 +00002831 } else if (ThisDecl && DS.getStorageClassSpec() == DeclSpec::SCS_static)
Douglas Gregor728d00b2011-10-10 14:49:18 +00002832 // No initializer.
Richard Smith3beb7c62017-01-12 02:27:38 +00002833 Actions.ActOnUninitializedDecl(ThisDecl);
David Majnemer23252a32013-08-01 04:22:55 +00002834
Douglas Gregor728d00b2011-10-10 14:49:18 +00002835 if (ThisDecl) {
David Majnemer23252a32013-08-01 04:22:55 +00002836 if (!ThisDecl->isInvalidDecl()) {
2837 // Set the Decl for any late parsed attributes
2838 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i)
2839 CommonLateParsedAttrs[i]->addDecl(ThisDecl);
2840
2841 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i)
2842 LateParsedAttrs[i]->addDecl(ThisDecl);
2843 }
Douglas Gregor728d00b2011-10-10 14:49:18 +00002844 Actions.FinalizeDeclaration(ThisDecl);
2845 DeclsInGroup.push_back(ThisDecl);
David Majnemer23252a32013-08-01 04:22:55 +00002846
2847 if (DeclaratorInfo.isFunctionDeclarator() &&
2848 DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2849 DeclSpec::SCS_typedef)
2850 HandleMemberFunctionDeclDelays(DeclaratorInfo, ThisDecl);
Douglas Gregor728d00b2011-10-10 14:49:18 +00002851 }
David Majnemer23252a32013-08-01 04:22:55 +00002852 LateParsedAttrs.clear();
Douglas Gregor728d00b2011-10-10 14:49:18 +00002853
2854 DeclaratorInfo.complete(ThisDecl);
Richard Smith938f40b2011-06-11 17:19:42 +00002855
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002856 // If we don't have a comma, it is either the end of the list (a ';')
2857 // or an error, bail out.
Alp Toker094e5212014-01-05 03:27:11 +00002858 SourceLocation CommaLoc;
2859 if (!TryConsumeToken(tok::comma, CommaLoc))
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002860 break;
Mike Stump11289f42009-09-09 15:08:12 +00002861
Richard Smithc8a79032012-01-09 22:31:44 +00002862 if (Tok.isAtStartOfLine() &&
Faisal Vali421b2d12017-12-29 05:41:00 +00002863 !MightBeDeclarator(DeclaratorContext::MemberContext)) {
Richard Smithc8a79032012-01-09 22:31:44 +00002864 // This comma was followed by a line-break and something which can't be
2865 // the start of a declarator. The comma was probably a typo for a
2866 // semicolon.
2867 Diag(CommaLoc, diag::err_expected_semi_declaration)
2868 << FixItHint::CreateReplacement(CommaLoc, ";");
2869 ExpectSemi = false;
2870 break;
2871 }
Mike Stump11289f42009-09-09 15:08:12 +00002872
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002873 // Parse the next declarator.
2874 DeclaratorInfo.clear();
Nico Weber24b2a822011-01-28 06:07:34 +00002875 VS.clear();
Nico Weberf56c85b2015-01-17 02:26:40 +00002876 BitfieldSize = ExprResult(/*Invalid=*/false);
Richard Smith9ba0fec2015-06-30 01:28:56 +00002877 EqualLoc = PureSpecLoc = SourceLocation();
Richard Smith8d06f422012-01-12 23:53:29 +00002878 DeclaratorInfo.setCommaLoc(CommaLoc);
Mike Stump11289f42009-09-09 15:08:12 +00002879
Richard Smith72553fc2014-01-23 23:53:27 +00002880 // GNU attributes are allowed before the second and subsequent declarator.
John McCall53fa7142010-12-24 02:08:15 +00002881 MaybeParseGNUAttributes(DeclaratorInfo);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002882
Nico Weberd89e6f72015-01-16 19:34:13 +00002883 if (ParseCXXMemberDeclaratorBeforeInitializer(
2884 DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs))
2885 break;
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002886 }
2887
Richard Smithc8a79032012-01-09 22:31:44 +00002888 if (ExpectSemi &&
2889 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list)) {
Chris Lattner916dbf12010-02-02 00:43:15 +00002890 // Skip to end of block or statement.
Alexey Bataevee6507d2013-11-18 08:17:37 +00002891 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Chris Lattner916dbf12010-02-02 00:43:15 +00002892 // If we stopped at a ';', eat it.
Alp Toker35d87032013-12-30 23:29:50 +00002893 TryConsumeToken(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002894 return nullptr;
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002895 }
2896
Alexey Bataev05c25d62015-07-31 08:42:25 +00002897 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002898}
2899
Richard Smith9ba0fec2015-06-30 01:28:56 +00002900/// ParseCXXMemberInitializer - Parse the brace-or-equal-initializer.
2901/// Also detect and reject any attempted defaulted/deleted function definition.
2902/// The location of the '=', if any, will be placed in EqualLoc.
Richard Smith938f40b2011-06-11 17:19:42 +00002903///
Richard Smith9ba0fec2015-06-30 01:28:56 +00002904/// This does not check for a pure-specifier; that's handled elsewhere.
Sebastian Redleef474c2012-02-22 10:50:08 +00002905///
Richard Smith938f40b2011-06-11 17:19:42 +00002906/// brace-or-equal-initializer:
2907/// '=' initializer-expression
Sebastian Redleef474c2012-02-22 10:50:08 +00002908/// braced-init-list
2909///
Richard Smith938f40b2011-06-11 17:19:42 +00002910/// initializer-clause:
2911/// assignment-expression
Sebastian Redleef474c2012-02-22 10:50:08 +00002912/// braced-init-list
2913///
Richard Smithda35e962013-11-09 04:52:51 +00002914/// defaulted/deleted function-definition:
Richard Smith938f40b2011-06-11 17:19:42 +00002915/// '=' 'default'
2916/// '=' 'delete'
2917///
2918/// Prior to C++0x, the assignment-expression in an initializer-clause must
2919/// be a constant-expression.
Douglas Gregor926410d2012-02-21 02:22:07 +00002920ExprResult Parser::ParseCXXMemberInitializer(Decl *D, bool IsFunction,
Richard Smith938f40b2011-06-11 17:19:42 +00002921 SourceLocation &EqualLoc) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002922 assert(Tok.isOneOf(tok::equal, tok::l_brace)
Richard Smith938f40b2011-06-11 17:19:42 +00002923 && "Data member initializer not starting with '=' or '{'");
2924
Faisal Valid143a0c2017-04-01 21:30:49 +00002925 EnterExpressionEvaluationContext Context(
2926 Actions, Sema::ExpressionEvaluationContext::PotentiallyEvaluated, D);
Alp Toker094e5212014-01-05 03:27:11 +00002927 if (TryConsumeToken(tok::equal, EqualLoc)) {
Richard Smith938f40b2011-06-11 17:19:42 +00002928 if (Tok.is(tok::kw_delete)) {
2929 // In principle, an initializer of '= delete p;' is legal, but it will
2930 // never type-check. It's better to diagnose it as an ill-formed expression
2931 // than as an ill-formed deleted non-function member.
2932 // An initializer of '= delete p, foo' will never be parsed, because
2933 // a top-level comma always ends the initializer expression.
2934 const Token &Next = NextToken();
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002935 if (IsFunction || Next.isOneOf(tok::semi, tok::comma, tok::eof)) {
Richard Smith938f40b2011-06-11 17:19:42 +00002936 if (IsFunction)
2937 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2938 << 1 /* delete */;
2939 else
2940 Diag(ConsumeToken(), diag::err_deleted_non_function);
Richard Smithedcb26e2014-06-11 00:49:52 +00002941 return ExprError();
Richard Smith938f40b2011-06-11 17:19:42 +00002942 }
2943 } else if (Tok.is(tok::kw_default)) {
Richard Smith938f40b2011-06-11 17:19:42 +00002944 if (IsFunction)
2945 Diag(Tok, diag::err_default_delete_in_multiple_declaration)
2946 << 0 /* default */;
2947 else
2948 Diag(ConsumeToken(), diag::err_default_special_members);
Richard Smithedcb26e2014-06-11 00:49:52 +00002949 return ExprError();
Richard Smith938f40b2011-06-11 17:19:42 +00002950 }
David Majnemer87ff66c2014-12-13 11:34:16 +00002951 }
2952 if (const auto *PD = dyn_cast_or_null<MSPropertyDecl>(D)) {
2953 Diag(Tok, diag::err_ms_property_initializer) << PD;
2954 return ExprError();
Sebastian Redleef474c2012-02-22 10:50:08 +00002955 }
2956 return ParseInitializer();
Richard Smith938f40b2011-06-11 17:19:42 +00002957}
2958
Richard Smith65ebb4a2015-03-26 04:09:53 +00002959void Parser::SkipCXXMemberSpecification(SourceLocation RecordLoc,
2960 SourceLocation AttrFixitLoc,
Faisal Vali090da2d2018-01-01 18:23:28 +00002961 unsigned TagType, Decl *TagDecl) {
Richard Smith65ebb4a2015-03-26 04:09:53 +00002962 // Skip the optional 'final' keyword.
2963 if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
2964 assert(isCXX11FinalKeyword() && "not a class definition");
2965 ConsumeToken();
2966
2967 // Diagnose any C++11 attributes after 'final' keyword.
2968 // We deliberately discard these attributes.
2969 ParsedAttributesWithRange Attrs(AttrFactory);
2970 CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
2971
2972 // This can only happen if we had malformed misplaced attributes;
2973 // we only get called if there is a colon or left-brace after the
2974 // attributes.
2975 if (Tok.isNot(tok::colon) && Tok.isNot(tok::l_brace))
2976 return;
2977 }
2978
2979 // Skip the base clauses. This requires actually parsing them, because
2980 // otherwise we can't be sure where they end (a left brace may appear
2981 // within a template argument).
2982 if (Tok.is(tok::colon)) {
2983 // Enter the scope of the class so that we can correctly parse its bases.
2984 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
2985 ParsingClassDefinition ParsingDef(*this, TagDecl, /*NonNestedClass*/ true,
2986 TagType == DeclSpec::TST_interface);
Richard Smith0f192e82015-06-11 22:48:25 +00002987 auto OldContext =
2988 Actions.ActOnTagStartSkippedDefinition(getCurScope(), TagDecl);
Richard Smith65ebb4a2015-03-26 04:09:53 +00002989
2990 // Parse the bases but don't attach them to the class.
2991 ParseBaseClause(nullptr);
2992
Richard Smith0f192e82015-06-11 22:48:25 +00002993 Actions.ActOnTagFinishSkippedDefinition(OldContext);
Richard Smith65ebb4a2015-03-26 04:09:53 +00002994
2995 if (!Tok.is(tok::l_brace)) {
2996 Diag(PP.getLocForEndOfToken(PrevTokLocation),
2997 diag::err_expected_lbrace_after_base_specifiers);
2998 return;
2999 }
3000 }
3001
3002 // Skip the body.
3003 assert(Tok.is(tok::l_brace));
3004 BalancedDelimiterTracker T(*this, tok::l_brace);
3005 T.consumeOpen();
3006 T.skipToEnd();
Richard Smith04c6c1f2015-07-01 18:56:50 +00003007
3008 // Parse and discard any trailing attributes.
3009 ParsedAttributes Attrs(AttrFactory);
3010 if (Tok.is(tok::kw___attribute))
3011 MaybeParseGNUAttributes(Attrs);
Richard Smith65ebb4a2015-03-26 04:09:53 +00003012}
3013
Alexey Bataev05c25d62015-07-31 08:42:25 +00003014Parser::DeclGroupPtrTy Parser::ParseCXXClassMemberDeclarationWithPragmas(
3015 AccessSpecifier &AS, ParsedAttributesWithRange &AccessAttrs,
3016 DeclSpec::TST TagType, Decl *TagDecl) {
Richard Smithbf5bcf22018-06-26 23:20:26 +00003017 ParenBraceBracketBalancer BalancerRAIIObj(*this);
3018
Richard Smithb55f7582017-01-28 01:12:10 +00003019 switch (Tok.getKind()) {
3020 case tok::kw___if_exists:
3021 case tok::kw___if_not_exists:
Erich Keanec480f302018-07-12 21:09:05 +00003022 ParseMicrosoftIfExistsClassDeclaration(TagType, AccessAttrs, AS);
David Blaikie0403cb12016-01-15 23:43:25 +00003023 return nullptr;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003024
Richard Smithb55f7582017-01-28 01:12:10 +00003025 case tok::semi:
3026 // Check for extraneous top-level semicolon.
Alexey Bataev05c25d62015-07-31 08:42:25 +00003027 ConsumeExtraSemi(InsideStruct, TagType);
David Blaikie0403cb12016-01-15 23:43:25 +00003028 return nullptr;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003029
Richard Smithb55f7582017-01-28 01:12:10 +00003030 // Handle pragmas that can appear as member declarations.
3031 case tok::annot_pragma_vis:
Alexey Bataev05c25d62015-07-31 08:42:25 +00003032 HandlePragmaVisibility();
David Blaikie0403cb12016-01-15 23:43:25 +00003033 return nullptr;
Richard Smithb55f7582017-01-28 01:12:10 +00003034 case tok::annot_pragma_pack:
Alexey Bataev05c25d62015-07-31 08:42:25 +00003035 HandlePragmaPack();
David Blaikie0403cb12016-01-15 23:43:25 +00003036 return nullptr;
Richard Smithb55f7582017-01-28 01:12:10 +00003037 case tok::annot_pragma_align:
Alexey Bataev05c25d62015-07-31 08:42:25 +00003038 HandlePragmaAlign();
David Blaikie0403cb12016-01-15 23:43:25 +00003039 return nullptr;
Richard Smithb55f7582017-01-28 01:12:10 +00003040 case tok::annot_pragma_ms_pointers_to_members:
Alexey Bataev05c25d62015-07-31 08:42:25 +00003041 HandlePragmaMSPointersToMembers();
David Blaikie0403cb12016-01-15 23:43:25 +00003042 return nullptr;
Richard Smithb55f7582017-01-28 01:12:10 +00003043 case tok::annot_pragma_ms_pragma:
Alexey Bataev05c25d62015-07-31 08:42:25 +00003044 HandlePragmaMSPragma();
David Blaikie0403cb12016-01-15 23:43:25 +00003045 return nullptr;
Richard Smithb55f7582017-01-28 01:12:10 +00003046 case tok::annot_pragma_ms_vtordisp:
Alexey Bataev3d42f342015-11-20 07:02:57 +00003047 HandlePragmaMSVtorDisp();
David Blaikie0403cb12016-01-15 23:43:25 +00003048 return nullptr;
Richard Smithb256d302017-01-28 01:20:57 +00003049 case tok::annot_pragma_dump:
3050 HandlePragmaDump();
3051 return nullptr;
Alexey Bataev3d42f342015-11-20 07:02:57 +00003052
Richard Smithb55f7582017-01-28 01:12:10 +00003053 case tok::kw_namespace:
3054 // If we see a namespace here, a close brace was missing somewhere.
Alexey Bataev05c25d62015-07-31 08:42:25 +00003055 DiagnoseUnexpectedNamespace(cast<NamedDecl>(TagDecl));
David Blaikie0403cb12016-01-15 23:43:25 +00003056 return nullptr;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003057
Richard Smithb55f7582017-01-28 01:12:10 +00003058 case tok::kw_public:
3059 case tok::kw_protected:
3060 case tok::kw_private: {
3061 AccessSpecifier NewAS = getAccessSpecifierIfPresent();
3062 assert(NewAS != AS_none);
Alexey Bataev05c25d62015-07-31 08:42:25 +00003063 // Current token is a C++ access specifier.
3064 AS = NewAS;
3065 SourceLocation ASLoc = Tok.getLocation();
3066 unsigned TokLength = Tok.getLength();
3067 ConsumeToken();
3068 AccessAttrs.clear();
3069 MaybeParseGNUAttributes(AccessAttrs);
3070
3071 SourceLocation EndLoc;
3072 if (TryConsumeToken(tok::colon, EndLoc)) {
3073 } else if (TryConsumeToken(tok::semi, EndLoc)) {
3074 Diag(EndLoc, diag::err_expected)
3075 << tok::colon << FixItHint::CreateReplacement(EndLoc, ":");
3076 } else {
3077 EndLoc = ASLoc.getLocWithOffset(TokLength);
3078 Diag(EndLoc, diag::err_expected)
3079 << tok::colon << FixItHint::CreateInsertion(EndLoc, ":");
3080 }
3081
3082 // The Microsoft extension __interface does not permit non-public
3083 // access specifiers.
3084 if (TagType == DeclSpec::TST_interface && AS != AS_public) {
3085 Diag(ASLoc, diag::err_access_specifier_interface) << (AS == AS_protected);
3086 }
3087
Erich Keanec480f302018-07-12 21:09:05 +00003088 if (Actions.ActOnAccessSpecifier(NewAS, ASLoc, EndLoc, AccessAttrs)) {
Alexey Bataev05c25d62015-07-31 08:42:25 +00003089 // found another attribute than only annotations
3090 AccessAttrs.clear();
3091 }
3092
David Blaikie0403cb12016-01-15 23:43:25 +00003093 return nullptr;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003094 }
3095
Richard Smithb55f7582017-01-28 01:12:10 +00003096 case tok::annot_pragma_openmp:
Alexey Bataev587e1de2016-03-30 10:43:55 +00003097 return ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, AccessAttrs, TagType,
3098 TagDecl);
Alexey Bataev05c25d62015-07-31 08:42:25 +00003099
Richard Smithb55f7582017-01-28 01:12:10 +00003100 default:
Erich Keanec480f302018-07-12 21:09:05 +00003101 return ParseCXXClassMemberDeclaration(AS, AccessAttrs);
Richard Smithb55f7582017-01-28 01:12:10 +00003102 }
Alexey Bataev05c25d62015-07-31 08:42:25 +00003103}
3104
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003105/// ParseCXXMemberSpecification - Parse the class definition.
3106///
3107/// member-specification:
3108/// member-declaration member-specification[opt]
3109/// access-specifier ':' member-specification[opt]
3110///
Joao Matose9a3ed42012-08-31 22:18:20 +00003111void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc,
Michael Han309af292013-01-07 16:57:11 +00003112 SourceLocation AttrFixitLoc,
Richard Smith4c96e992013-02-19 23:47:15 +00003113 ParsedAttributesWithRange &Attrs,
Faisal Vali090da2d2018-01-01 18:23:28 +00003114 unsigned TagType, Decl *TagDecl) {
Joao Matose9a3ed42012-08-31 22:18:20 +00003115 assert((TagType == DeclSpec::TST_struct ||
Faisal Vali090da2d2018-01-01 18:23:28 +00003116 TagType == DeclSpec::TST_interface ||
3117 TagType == DeclSpec::TST_union ||
3118 TagType == DeclSpec::TST_class) && "Invalid TagType!");
Joao Matose9a3ed42012-08-31 22:18:20 +00003119
Jordan Rose1e879d82018-03-23 00:07:18 +00003120 PrettyDeclStackTraceEntry CrashInfo(Actions.Context, TagDecl, RecordLoc,
John McCallfaf5fb42010-08-26 23:41:50 +00003121 "parsing struct/union/class body");
Mike Stump11289f42009-09-09 15:08:12 +00003122
Douglas Gregoredf8f392010-01-16 20:52:59 +00003123 // Determine whether this is a non-nested class. Note that local
3124 // classes are *not* considered to be nested classes.
3125 bool NonNestedClass = true;
3126 if (!ClassStack.empty()) {
Douglas Gregor0be31a22010-07-02 17:43:08 +00003127 for (const Scope *S = getCurScope(); S; S = S->getParent()) {
Douglas Gregoredf8f392010-01-16 20:52:59 +00003128 if (S->isClassScope()) {
3129 // We're inside a class scope, so this is a nested class.
3130 NonNestedClass = false;
John McCalldb632ac2012-09-25 07:32:39 +00003131
3132 // The Microsoft extension __interface does not permit nested classes.
3133 if (getCurrentClass().IsInterface) {
3134 Diag(RecordLoc, diag::err_invalid_member_in_interface)
3135 << /*ErrorType=*/6
3136 << (isa<NamedDecl>(TagDecl)
3137 ? cast<NamedDecl>(TagDecl)->getQualifiedNameAsString()
David Blaikieabe1a392014-04-02 05:58:29 +00003138 : "(anonymous)");
John McCalldb632ac2012-09-25 07:32:39 +00003139 }
Douglas Gregoredf8f392010-01-16 20:52:59 +00003140 break;
3141 }
3142
Serge Pavlovd9c0bcf2015-07-14 10:02:10 +00003143 if ((S->getFlags() & Scope::FnScope))
3144 // If we're in a function or function template then this is a local
3145 // class rather than a nested class.
3146 break;
Douglas Gregoredf8f392010-01-16 20:52:59 +00003147 }
3148 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003149
3150 // Enter a scope for the class.
Douglas Gregor658b9552009-01-09 22:42:13 +00003151 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003152
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003153 // Note that we are parsing a new (potentially-nested) class definition.
John McCalldb632ac2012-09-25 07:32:39 +00003154 ParsingClassDefinition ParsingDef(*this, TagDecl, NonNestedClass,
3155 TagType == DeclSpec::TST_interface);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003156
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003157 if (TagDecl)
Douglas Gregor0be31a22010-07-02 17:43:08 +00003158 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
John McCall2d814c32009-12-19 21:48:58 +00003159
Anders Carlssonf9eb63b2011-03-25 14:46:08 +00003160 SourceLocation FinalLoc;
David Majnemera5433082013-10-18 00:33:31 +00003161 bool IsFinalSpelledSealed = false;
Anders Carlssonf9eb63b2011-03-25 14:46:08 +00003162
3163 // Parse the optional 'final' keyword.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003164 if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
David Majnemera5433082013-10-18 00:33:31 +00003165 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier(Tok);
3166 assert((Specifier == VirtSpecifiers::VS_Final ||
Fangrui Song6907ce22018-07-30 19:24:48 +00003167 Specifier == VirtSpecifiers::VS_GNU_Final ||
David Majnemera5433082013-10-18 00:33:31 +00003168 Specifier == VirtSpecifiers::VS_Sealed) &&
3169 "not a class definition");
Richard Smithda261112011-10-15 04:21:46 +00003170 FinalLoc = ConsumeToken();
David Majnemera5433082013-10-18 00:33:31 +00003171 IsFinalSpelledSealed = Specifier == VirtSpecifiers::VS_Sealed;
Anders Carlssonf9eb63b2011-03-25 14:46:08 +00003172
David Majnemera5433082013-10-18 00:33:31 +00003173 if (TagType == DeclSpec::TST_interface)
John McCalldb632ac2012-09-25 07:32:39 +00003174 Diag(FinalLoc, diag::err_override_control_interface)
David Majnemera5433082013-10-18 00:33:31 +00003175 << VirtSpecifiers::getSpecifierName(Specifier);
3176 else if (Specifier == VirtSpecifiers::VS_Final)
3177 Diag(FinalLoc, getLangOpts().CPlusPlus11
3178 ? diag::warn_cxx98_compat_override_control_keyword
3179 : diag::ext_override_control_keyword)
3180 << VirtSpecifiers::getSpecifierName(Specifier);
3181 else if (Specifier == VirtSpecifiers::VS_Sealed)
3182 Diag(FinalLoc, diag::ext_ms_sealed_keyword);
Andrey Bokhanko276055b2016-07-29 10:42:48 +00003183 else if (Specifier == VirtSpecifiers::VS_GNU_Final)
3184 Diag(FinalLoc, diag::ext_warn_gnu_final);
Michael Han9407e502012-11-26 22:54:45 +00003185
Michael Han309af292013-01-07 16:57:11 +00003186 // Parse any C++11 attributes after 'final' keyword.
3187 // These attributes are not allowed to appear here,
3188 // and the only possible place for them to appertain
3189 // to the class would be between class-key and class-name.
Richard Smith4c96e992013-02-19 23:47:15 +00003190 CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
Nico Weber4b4be842014-12-29 06:56:50 +00003191
3192 // ParseClassSpecifier() does only a superficial check for attributes before
3193 // deciding to call this method. For example, for
3194 // `class C final alignas ([l) {` it will decide that this looks like a
3195 // misplaced attribute since it sees `alignas '(' ')'`. But the actual
3196 // attribute parsing code will try to parse the '[' as a constexpr lambda
3197 // and consume enough tokens that the alignas parsing code will eat the
3198 // opening '{'. So bail out if the next token isn't one we expect.
Nico Weber36de3a22014-12-29 21:56:22 +00003199 if (!Tok.is(tok::colon) && !Tok.is(tok::l_brace)) {
3200 if (TagDecl)
3201 Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
Nico Weber4b4be842014-12-29 06:56:50 +00003202 return;
Nico Weber36de3a22014-12-29 21:56:22 +00003203 }
Anders Carlssonf9eb63b2011-03-25 14:46:08 +00003204 }
Anders Carlsson4b63d0e2011-01-22 16:56:46 +00003205
John McCall2d814c32009-12-19 21:48:58 +00003206 if (Tok.is(tok::colon)) {
Erik Verbruggen6524c052017-10-24 13:46:58 +00003207 ParseScope InheritanceScope(this, getCurScope()->getFlags() |
3208 Scope::ClassInheritanceScope);
3209
John McCall2d814c32009-12-19 21:48:58 +00003210 ParseBaseClause(TagDecl);
John McCall2d814c32009-12-19 21:48:58 +00003211 if (!Tok.is(tok::l_brace)) {
Ismail Pazarbasi129c44c2014-09-25 21:13:02 +00003212 bool SuggestFixIt = false;
3213 SourceLocation BraceLoc = PP.getLocForEndOfToken(PrevTokLocation);
3214 if (Tok.isAtStartOfLine()) {
3215 switch (Tok.getKind()) {
3216 case tok::kw_private:
3217 case tok::kw_protected:
3218 case tok::kw_public:
3219 SuggestFixIt = NextToken().getKind() == tok::colon;
3220 break;
3221 case tok::kw_static_assert:
3222 case tok::r_brace:
3223 case tok::kw_using:
3224 // base-clause can have simple-template-id; 'template' can't be there
3225 case tok::kw_template:
3226 SuggestFixIt = true;
3227 break;
3228 case tok::identifier:
3229 SuggestFixIt = isConstructorDeclarator(true);
3230 break;
3231 default:
3232 SuggestFixIt = isCXXSimpleDeclaration(/*AllowForRangeDecl=*/false);
3233 break;
3234 }
3235 }
3236 DiagnosticBuilder LBraceDiag =
3237 Diag(BraceLoc, diag::err_expected_lbrace_after_base_specifiers);
3238 if (SuggestFixIt) {
3239 LBraceDiag << FixItHint::CreateInsertion(BraceLoc, " {");
3240 // Try recovering from missing { after base-clause.
3241 PP.EnterToken(Tok);
3242 Tok.setKind(tok::l_brace);
3243 } else {
3244 if (TagDecl)
3245 Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
3246 return;
3247 }
John McCall2d814c32009-12-19 21:48:58 +00003248 }
3249 }
3250
3251 assert(Tok.is(tok::l_brace));
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003252 BalancedDelimiterTracker T(*this, tok::l_brace);
3253 T.consumeOpen();
John McCall2d814c32009-12-19 21:48:58 +00003254
John McCall08bede42010-05-28 08:11:17 +00003255 if (TagDecl)
Anders Carlsson30f29442011-03-25 14:31:08 +00003256 Actions.ActOnStartCXXMemberDeclarations(getCurScope(), TagDecl, FinalLoc,
David Majnemera5433082013-10-18 00:33:31 +00003257 IsFinalSpelledSealed,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003258 T.getOpenLocation());
John McCall1c7e6ec2009-12-20 07:58:13 +00003259
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003260 // C++ 11p3: Members of a class defined with the keyword class are private
3261 // by default. Members of a class defined with the keywords struct or union
3262 // are public by default.
3263 AccessSpecifier CurAS;
3264 if (TagType == DeclSpec::TST_class)
3265 CurAS = AS_private;
3266 else
3267 CurAS = AS_public;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003268 ParsedAttributesWithRange AccessAttrs(AttrFactory);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003269
Douglas Gregor9377c822010-06-21 22:31:09 +00003270 if (TagDecl) {
3271 // While we still have something to read, read the member-declarations.
Richard Smith752ada82015-11-17 23:32:01 +00003272 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
3273 Tok.isNot(tok::eof)) {
Douglas Gregor9377c822010-06-21 22:31:09 +00003274 // Each iteration of this loop reads one member-declaration.
Alexey Bataev05c25d62015-07-31 08:42:25 +00003275 ParseCXXClassMemberDeclarationWithPragmas(
3276 CurAS, AccessAttrs, static_cast<DeclSpec::TST>(TagType), TagDecl);
Serge Pavlovc4e04a22015-09-19 05:32:57 +00003277 }
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003278 T.consumeClose();
Douglas Gregor9377c822010-06-21 22:31:09 +00003279 } else {
Alexey Bataevee6507d2013-11-18 08:17:37 +00003280 SkipUntil(tok::r_brace);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003281 }
Mike Stump11289f42009-09-09 15:08:12 +00003282
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003283 // If attributes exist after class contents, parse them.
John McCall084e83d2011-03-24 11:26:52 +00003284 ParsedAttributes attrs(AttrFactory);
John McCall53fa7142010-12-24 02:08:15 +00003285 MaybeParseGNUAttributes(attrs);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003286
John McCall08bede42010-05-28 08:11:17 +00003287 if (TagDecl)
Douglas Gregor0be31a22010-07-02 17:43:08 +00003288 Actions.ActOnFinishCXXMemberSpecification(getCurScope(), RecordLoc, TagDecl,
Erich Keanec480f302018-07-12 21:09:05 +00003289 T.getOpenLocation(),
3290 T.getCloseLocation(), attrs);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003291
Douglas Gregor433e0532012-04-16 18:27:27 +00003292 // C++11 [class.mem]p2:
3293 // Within the class member-specification, the class is regarded as complete
Richard Smith0b3a4622014-11-13 20:01:57 +00003294 // within function bodies, default arguments, exception-specifications, and
Douglas Gregor433e0532012-04-16 18:27:27 +00003295 // brace-or-equal-initializers for non-static data members (including such
3296 // things in nested classes).
Douglas Gregor9377c822010-06-21 22:31:09 +00003297 if (TagDecl && NonNestedClass) {
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003298 // We are not inside a nested class. This class and its nested classes
Douglas Gregor4d87df52008-12-16 21:30:33 +00003299 // are complete and we can parse the delayed portions of method
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00003300 // declarations and the lexed inline method definitions, along with any
3301 // delayed attributes.
Douglas Gregor428119e2010-06-16 23:45:56 +00003302 SourceLocation SavedPrevTokLocation = PrevTokLocation;
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00003303 ParseLexedAttributes(getCurrentClass());
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003304 ParseLexedMethodDeclarations(getCurrentClass());
Richard Smith84973e52012-04-21 18:42:51 +00003305
3306 // We've finished with all pending member declarations.
3307 Actions.ActOnFinishCXXMemberDecls();
3308
Richard Smith938f40b2011-06-11 17:19:42 +00003309 ParseLexedMemberInitializers(getCurrentClass());
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003310 ParseLexedMethodDefs(getCurrentClass());
Douglas Gregor428119e2010-06-16 23:45:56 +00003311 PrevTokLocation = SavedPrevTokLocation;
Reid Klecknerbba3cb92015-03-17 19:00:50 +00003312
3313 // We've finished parsing everything, including default argument
3314 // initializers.
Hans Wennborg99000c22015-08-15 01:18:16 +00003315 Actions.ActOnFinishCXXNonNestedClass(TagDecl);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003316 }
3317
John McCall08bede42010-05-28 08:11:17 +00003318 if (TagDecl)
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00003319 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getRange());
John McCall2ff380a2010-03-17 00:38:33 +00003320
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003321 // Leave the class scope.
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003322 ParsingDef.Pop();
Douglas Gregor7307d6c2008-12-10 06:34:36 +00003323 ClassScope.Exit();
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003324}
Douglas Gregore8381c02008-11-05 04:29:56 +00003325
Richard Smith2ac43ad2013-11-15 23:00:02 +00003326void Parser::DiagnoseUnexpectedNamespace(NamedDecl *D) {
Richard Smithda35e962013-11-09 04:52:51 +00003327 assert(Tok.is(tok::kw_namespace));
3328
3329 // FIXME: Suggest where the close brace should have gone by looking
3330 // at indentation changes within the definition body.
Richard Smith2ac43ad2013-11-15 23:00:02 +00003331 Diag(D->getLocation(),
3332 diag::err_missing_end_of_definition) << D;
Richard Smithda35e962013-11-09 04:52:51 +00003333 Diag(Tok.getLocation(),
Richard Smith2ac43ad2013-11-15 23:00:02 +00003334 diag::note_missing_end_of_definition_before) << D;
Richard Smithda35e962013-11-09 04:52:51 +00003335
3336 // Push '};' onto the token stream to recover.
3337 PP.EnterToken(Tok);
3338
3339 Tok.startToken();
3340 Tok.setLocation(PP.getLocForEndOfToken(PrevTokLocation));
3341 Tok.setKind(tok::semi);
3342 PP.EnterToken(Tok);
3343
3344 Tok.setKind(tok::r_brace);
3345}
3346
Douglas Gregore8381c02008-11-05 04:29:56 +00003347/// ParseConstructorInitializer - Parse a C++ constructor initializer,
3348/// which explicitly initializes the members or base classes of a
3349/// class (C++ [class.base.init]). For example, the three initializers
3350/// after the ':' in the Derived constructor below:
3351///
3352/// @code
3353/// class Base { };
3354/// class Derived : Base {
3355/// int x;
3356/// float f;
3357/// public:
3358/// Derived(float f) : Base(), x(17), f(f) { }
3359/// };
3360/// @endcode
3361///
Mike Stump11289f42009-09-09 15:08:12 +00003362/// [C++] ctor-initializer:
3363/// ':' mem-initializer-list
Douglas Gregore8381c02008-11-05 04:29:56 +00003364///
Mike Stump11289f42009-09-09 15:08:12 +00003365/// [C++] mem-initializer-list:
Douglas Gregor44e7df62011-01-04 00:32:56 +00003366/// mem-initializer ...[opt]
3367/// mem-initializer ...[opt] , mem-initializer-list
John McCall48871652010-08-21 09:40:31 +00003368void Parser::ParseConstructorInitializer(Decl *ConstructorDecl) {
Nico Weber3b00fdc2015-03-07 19:52:39 +00003369 assert(Tok.is(tok::colon) &&
3370 "Constructor initializer always starts with ':'");
Douglas Gregore8381c02008-11-05 04:29:56 +00003371
Nico Weber3b00fdc2015-03-07 19:52:39 +00003372 // Poison the SEH identifiers so they are flagged as illegal in constructor
3373 // initializers.
John Wiegley1c0675e2011-04-28 01:08:34 +00003374 PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
Douglas Gregore8381c02008-11-05 04:29:56 +00003375 SourceLocation ColonLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +00003376
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003377 SmallVector<CXXCtorInitializer*, 4> MemInitializers;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003378 bool AnyErrors = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003379
Douglas Gregore8381c02008-11-05 04:29:56 +00003380 do {
Douglas Gregoreaeeca92010-08-28 00:00:50 +00003381 if (Tok.is(tok::code_completion)) {
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00003382 Actions.CodeCompleteConstructorInitializer(ConstructorDecl,
3383 MemInitializers);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00003384 return cutOffParsing();
Douglas Gregoreaeeca92010-08-28 00:00:50 +00003385 }
Alexey Bataev79de17d2016-01-20 05:25:51 +00003386
3387 MemInitResult MemInit = ParseMemInitializer(ConstructorDecl);
3388 if (!MemInit.isInvalid())
3389 MemInitializers.push_back(MemInit.get());
3390 else
3391 AnyErrors = true;
3392
Douglas Gregore8381c02008-11-05 04:29:56 +00003393 if (Tok.is(tok::comma))
3394 ConsumeToken();
3395 else if (Tok.is(tok::l_brace))
3396 break;
Alexey Bataev79de17d2016-01-20 05:25:51 +00003397 // If the previous initializer was valid and the next token looks like a
3398 // base or member initializer, assume that we're just missing a comma.
3399 else if (!MemInit.isInvalid() &&
3400 Tok.isOneOf(tok::identifier, tok::coloncolon)) {
Douglas Gregorce66d022010-09-07 14:51:08 +00003401 SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation);
3402 Diag(Loc, diag::err_ctor_init_missing_comma)
3403 << FixItHint::CreateInsertion(Loc, ", ");
3404 } else {
Douglas Gregore8381c02008-11-05 04:29:56 +00003405 // Skip over garbage, until we get to '{'. Don't eat the '{'.
Alexey Bataev79de17d2016-01-20 05:25:51 +00003406 if (!MemInit.isInvalid())
3407 Diag(Tok.getLocation(), diag::err_expected_either) << tok::l_brace
3408 << tok::comma;
Alexey Bataevee6507d2013-11-18 08:17:37 +00003409 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
Douglas Gregore8381c02008-11-05 04:29:56 +00003410 break;
3411 }
3412 } while (true);
3413
David Blaikie3fc2f912013-01-17 05:26:25 +00003414 Actions.ActOnMemInitializers(ConstructorDecl, ColonLoc, MemInitializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003415 AnyErrors);
Douglas Gregore8381c02008-11-05 04:29:56 +00003416}
3417
3418/// ParseMemInitializer - Parse a C++ member initializer, which is
3419/// part of a constructor initializer that explicitly initializes one
3420/// member or base class (C++ [class.base.init]). See
3421/// ParseConstructorInitializer for an example.
3422///
3423/// [C++] mem-initializer:
3424/// mem-initializer-id '(' expression-list[opt] ')'
Sebastian Redl3da34892011-06-05 12:23:16 +00003425/// [C++0x] mem-initializer-id braced-init-list
Mike Stump11289f42009-09-09 15:08:12 +00003426///
Douglas Gregore8381c02008-11-05 04:29:56 +00003427/// [C++] mem-initializer-id:
3428/// '::'[opt] nested-name-specifier[opt] class-name
3429/// identifier
Craig Topper9ad7e262014-10-31 06:57:07 +00003430MemInitResult Parser::ParseMemInitializer(Decl *ConstructorDecl) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00003431 // parse '::'[opt] nested-name-specifier[opt]
3432 CXXScopeSpec SS;
David Blaikieefdccaa2016-01-15 23:43:34 +00003433 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false);
Richard Smithaf3b3252017-05-18 19:21:48 +00003434
3435 // : identifier
3436 IdentifierInfo *II = nullptr;
3437 SourceLocation IdLoc = Tok.getLocation();
3438 // : declype(...)
3439 DeclSpec DS(AttrFactory);
3440 // : template_name<...>
John McCallba7bf592010-08-24 05:47:05 +00003441 ParsedType TemplateTypeTy;
Richard Smithaf3b3252017-05-18 19:21:48 +00003442
3443 if (Tok.is(tok::identifier)) {
3444 // Get the identifier. This may be a member name or a class name,
3445 // but we'll let the semantic analysis determine which it is.
3446 II = Tok.getIdentifierInfo();
3447 ConsumeToken();
3448 } else if (Tok.is(tok::annot_decltype)) {
3449 // Get the decltype expression, if there is one.
3450 // Uses of decltype will already have been converted to annot_decltype by
3451 // ParseOptionalCXXScopeSpecifier at this point.
3452 // FIXME: Can we get here with a scope specifier?
3453 ParseDecltypeSpecifier(DS);
3454 } else {
3455 TemplateIdAnnotation *TemplateId = Tok.is(tok::annot_template_id)
3456 ? takeTemplateIdAnnotation(Tok)
3457 : nullptr;
3458 if (TemplateId && (TemplateId->Kind == TNK_Type_template ||
3459 TemplateId->Kind == TNK_Dependent_template_name)) {
Richard Smith62559bd2017-02-01 21:36:38 +00003460 AnnotateTemplateIdTokenAsType(/*IsClassName*/true);
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00003461 assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
John McCallba7bf592010-08-24 05:47:05 +00003462 TemplateTypeTy = getTypeAnnotation(Tok);
Richard Smithaf3b3252017-05-18 19:21:48 +00003463 ConsumeAnnotationToken();
3464 } else {
3465 Diag(Tok, diag::err_expected_member_or_base_name);
3466 return true;
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00003467 }
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00003468 }
Douglas Gregore8381c02008-11-05 04:29:56 +00003469
3470 // Parse the '('.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003471 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
Richard Smith5d164bc2011-10-15 05:09:34 +00003472 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
3473
Kadir Cetinkaya84774c32018-09-11 15:02:18 +00003474 // FIXME: Add support for signature help inside initializer lists.
Sebastian Redla74948d2011-09-24 17:48:25 +00003475 ExprResult InitList = ParseBraceInitializer();
3476 if (InitList.isInvalid())
3477 return true;
3478
3479 SourceLocation EllipsisLoc;
Alp Toker094e5212014-01-05 03:27:11 +00003480 TryConsumeToken(tok::ellipsis, EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00003481
3482 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
Fangrui Song6907ce22018-07-30 19:24:48 +00003483 TemplateTypeTy, DS, IdLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003484 InitList.get(), EllipsisLoc);
Sebastian Redl3da34892011-06-05 12:23:16 +00003485 } else if(Tok.is(tok::l_paren)) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003486 BalancedDelimiterTracker T(*this, tok::l_paren);
3487 T.consumeOpen();
Douglas Gregore8381c02008-11-05 04:29:56 +00003488
Sebastian Redl3da34892011-06-05 12:23:16 +00003489 // Parse the optional expression-list.
Benjamin Kramerf0623432012-08-23 22:51:59 +00003490 ExprVector ArgExprs;
Sebastian Redl3da34892011-06-05 12:23:16 +00003491 CommaLocsTy CommaLocs;
Kadir Cetinkaya84774c32018-09-11 15:02:18 +00003492 if (Tok.isNot(tok::r_paren) &&
3493 ParseExpressionList(ArgExprs, CommaLocs, [&] {
3494 QualType PreferredType = Actions.ProduceCtorInitMemberSignatureHelp(
3495 getCurScope(), ConstructorDecl, SS, TemplateTypeTy, ArgExprs, II,
3496 T.getOpenLocation());
3497 CalledSignatureHelp = true;
3498 Actions.CodeCompleteExpression(getCurScope(), PreferredType);
3499 })) {
3500 if (PP.isCodeCompletionReached() && !CalledSignatureHelp) {
3501 Actions.ProduceCtorInitMemberSignatureHelp(
3502 getCurScope(), ConstructorDecl, SS, TemplateTypeTy, ArgExprs, II,
3503 T.getOpenLocation());
3504 CalledSignatureHelp = true;
3505 }
Alexey Bataevee6507d2013-11-18 08:17:37 +00003506 SkipUntil(tok::r_paren, StopAtSemi);
Sebastian Redl3da34892011-06-05 12:23:16 +00003507 return true;
3508 }
3509
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003510 T.consumeClose();
Sebastian Redl3da34892011-06-05 12:23:16 +00003511
3512 SourceLocation EllipsisLoc;
Alp Toker97650562014-01-10 11:19:30 +00003513 TryConsumeToken(tok::ellipsis, EllipsisLoc);
Sebastian Redl3da34892011-06-05 12:23:16 +00003514
3515 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
David Blaikie186a8892012-01-24 06:03:59 +00003516 TemplateTypeTy, DS, IdLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00003517 T.getOpenLocation(), ArgExprs,
3518 T.getCloseLocation(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00003519 }
3520
Alp Tokerec543272013-12-24 09:48:30 +00003521 if (getLangOpts().CPlusPlus11)
3522 return Diag(Tok, diag::err_expected_either) << tok::l_paren << tok::l_brace;
3523 else
3524 return Diag(Tok, diag::err_expected) << tok::l_paren;
Douglas Gregore8381c02008-11-05 04:29:56 +00003525}
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003526
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003527/// Parse a C++ exception-specification if present (C++0x [except.spec]).
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003528///
Douglas Gregor356513d2008-12-01 18:00:20 +00003529/// exception-specification:
Sebastian Redl965b0e32011-03-05 14:45:16 +00003530/// dynamic-exception-specification
3531/// noexcept-specification
3532///
3533/// noexcept-specification:
3534/// 'noexcept'
3535/// 'noexcept' '(' constant-expression ')'
3536ExceptionSpecificationType
Richard Smith0b3a4622014-11-13 20:01:57 +00003537Parser::tryParseExceptionSpecification(bool Delayed,
Douglas Gregor433e0532012-04-16 18:27:27 +00003538 SourceRange &SpecificationRange,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003539 SmallVectorImpl<ParsedType> &DynamicExceptions,
3540 SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
Richard Smith0b3a4622014-11-13 20:01:57 +00003541 ExprResult &NoexceptExpr,
3542 CachedTokens *&ExceptionSpecTokens) {
Sebastian Redl965b0e32011-03-05 14:45:16 +00003543 ExceptionSpecificationType Result = EST_None;
Hans Wennborgdcfba332015-10-06 23:40:43 +00003544 ExceptionSpecTokens = nullptr;
Fangrui Song6907ce22018-07-30 19:24:48 +00003545
Richard Smith0b3a4622014-11-13 20:01:57 +00003546 // Handle delayed parsing of exception-specifications.
3547 if (Delayed) {
3548 if (Tok.isNot(tok::kw_throw) && Tok.isNot(tok::kw_noexcept))
3549 return EST_None;
Sebastian Redl965b0e32011-03-05 14:45:16 +00003550
Richard Smith0b3a4622014-11-13 20:01:57 +00003551 // Consume and cache the starting token.
3552 bool IsNoexcept = Tok.is(tok::kw_noexcept);
3553 Token StartTok = Tok;
3554 SpecificationRange = SourceRange(ConsumeToken());
3555
3556 // Check for a '('.
3557 if (!Tok.is(tok::l_paren)) {
3558 // If this is a bare 'noexcept', we're done.
3559 if (IsNoexcept) {
3560 Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
Hans Wennborgdcfba332015-10-06 23:40:43 +00003561 NoexceptExpr = nullptr;
Richard Smith0b3a4622014-11-13 20:01:57 +00003562 return EST_BasicNoexcept;
3563 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003564
Richard Smith0b3a4622014-11-13 20:01:57 +00003565 Diag(Tok, diag::err_expected_lparen_after) << "throw";
3566 return EST_DynamicNone;
3567 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003568
Richard Smith0b3a4622014-11-13 20:01:57 +00003569 // Cache the tokens for the exception-specification.
3570 ExceptionSpecTokens = new CachedTokens;
3571 ExceptionSpecTokens->push_back(StartTok); // 'throw' or 'noexcept'
3572 ExceptionSpecTokens->push_back(Tok); // '('
3573 SpecificationRange.setEnd(ConsumeParen()); // '('
Richard Smithb1c217e2015-01-13 02:24:58 +00003574
3575 ConsumeAndStoreUntil(tok::r_paren, *ExceptionSpecTokens,
3576 /*StopAtSemi=*/true,
3577 /*ConsumeFinalToken=*/true);
Aaron Ballman580ccaf2016-01-12 21:04:22 +00003578 SpecificationRange.setEnd(ExceptionSpecTokens->back().getLocation());
3579
Richard Smith0b3a4622014-11-13 20:01:57 +00003580 return EST_Unparsed;
3581 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003582
Sebastian Redl965b0e32011-03-05 14:45:16 +00003583 // See if there's a dynamic specification.
3584 if (Tok.is(tok::kw_throw)) {
3585 Result = ParseDynamicExceptionSpecification(SpecificationRange,
3586 DynamicExceptions,
3587 DynamicExceptionRanges);
3588 assert(DynamicExceptions.size() == DynamicExceptionRanges.size() &&
3589 "Produced different number of exception types and ranges.");
3590 }
3591
3592 // If there's no noexcept specification, we're done.
3593 if (Tok.isNot(tok::kw_noexcept))
3594 return Result;
3595
Richard Smithb15c11c2011-10-17 23:06:20 +00003596 Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
3597
Sebastian Redl965b0e32011-03-05 14:45:16 +00003598 // If we already had a dynamic specification, parse the noexcept for,
3599 // recovery, but emit a diagnostic and don't store the results.
3600 SourceRange NoexceptRange;
3601 ExceptionSpecificationType NoexceptType = EST_None;
3602
3603 SourceLocation KeywordLoc = ConsumeToken();
3604 if (Tok.is(tok::l_paren)) {
3605 // There is an argument.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003606 BalancedDelimiterTracker T(*this, tok::l_paren);
3607 T.consumeOpen();
Sebastian Redl965b0e32011-03-05 14:45:16 +00003608 NoexceptExpr = ParseConstantExpression();
Serge Pavlov3739f5e72015-06-29 17:50:19 +00003609 T.consumeClose();
Serge Pavlov3739f5e72015-06-29 17:50:19 +00003610 if (!NoexceptExpr.isInvalid()) {
Richard Smitheaf11ad2018-05-03 03:58:32 +00003611 NoexceptExpr = Actions.ActOnNoexceptSpec(KeywordLoc, NoexceptExpr.get(),
3612 NoexceptType);
Serge Pavlov3739f5e72015-06-29 17:50:19 +00003613 NoexceptRange = SourceRange(KeywordLoc, T.getCloseLocation());
3614 } else {
Malcolm Parsonsa3220ce2017-01-12 16:11:28 +00003615 NoexceptType = EST_BasicNoexcept;
Serge Pavlov3739f5e72015-06-29 17:50:19 +00003616 }
Sebastian Redl965b0e32011-03-05 14:45:16 +00003617 } else {
3618 // There is no argument.
3619 NoexceptType = EST_BasicNoexcept;
3620 NoexceptRange = SourceRange(KeywordLoc, KeywordLoc);
3621 }
3622
3623 if (Result == EST_None) {
3624 SpecificationRange = NoexceptRange;
3625 Result = NoexceptType;
3626
3627 // If there's a dynamic specification after a noexcept specification,
3628 // parse that and ignore the results.
3629 if (Tok.is(tok::kw_throw)) {
3630 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
3631 ParseDynamicExceptionSpecification(NoexceptRange, DynamicExceptions,
3632 DynamicExceptionRanges);
3633 }
3634 } else {
3635 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
3636 }
3637
3638 return Result;
3639}
3640
Richard Smith8ca78a12013-06-13 02:02:51 +00003641static void diagnoseDynamicExceptionSpecification(
Craig Toppere335f252015-10-04 04:53:55 +00003642 Parser &P, SourceRange Range, bool IsNoexcept) {
Richard Smith8ca78a12013-06-13 02:02:51 +00003643 if (P.getLangOpts().CPlusPlus11) {
3644 const char *Replacement = IsNoexcept ? "noexcept" : "noexcept(false)";
Richard Smith82da19d2016-12-08 02:49:07 +00003645 P.Diag(Range.getBegin(),
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003646 P.getLangOpts().CPlusPlus17 && !IsNoexcept
Richard Smith82da19d2016-12-08 02:49:07 +00003647 ? diag::ext_dynamic_exception_spec
3648 : diag::warn_exception_spec_deprecated)
3649 << Range;
Richard Smith8ca78a12013-06-13 02:02:51 +00003650 P.Diag(Range.getBegin(), diag::note_exception_spec_deprecated)
3651 << Replacement << FixItHint::CreateReplacement(Range, Replacement);
3652 }
3653}
3654
Sebastian Redl965b0e32011-03-05 14:45:16 +00003655/// ParseDynamicExceptionSpecification - Parse a C++
3656/// dynamic-exception-specification (C++ [except.spec]).
3657///
3658/// dynamic-exception-specification:
Douglas Gregor356513d2008-12-01 18:00:20 +00003659/// 'throw' '(' type-id-list [opt] ')'
3660/// [MS] 'throw' '(' '...' ')'
Mike Stump11289f42009-09-09 15:08:12 +00003661///
Douglas Gregor356513d2008-12-01 18:00:20 +00003662/// type-id-list:
Douglas Gregor830837d2010-12-20 23:57:46 +00003663/// type-id ... [opt]
3664/// type-id-list ',' type-id ... [opt]
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003665///
Sebastian Redl965b0e32011-03-05 14:45:16 +00003666ExceptionSpecificationType Parser::ParseDynamicExceptionSpecification(
3667 SourceRange &SpecificationRange,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003668 SmallVectorImpl<ParsedType> &Exceptions,
3669 SmallVectorImpl<SourceRange> &Ranges) {
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003670 assert(Tok.is(tok::kw_throw) && "expected throw");
Mike Stump11289f42009-09-09 15:08:12 +00003671
Sebastian Redl965b0e32011-03-05 14:45:16 +00003672 SpecificationRange.setBegin(ConsumeToken());
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003673 BalancedDelimiterTracker T(*this, tok::l_paren);
3674 if (T.consumeOpen()) {
Sebastian Redl965b0e32011-03-05 14:45:16 +00003675 Diag(Tok, diag::err_expected_lparen_after) << "throw";
3676 SpecificationRange.setEnd(SpecificationRange.getBegin());
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003677 return EST_DynamicNone;
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003678 }
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003679
Douglas Gregor356513d2008-12-01 18:00:20 +00003680 // Parse throw(...), a Microsoft extension that means "this function
3681 // can throw anything".
3682 if (Tok.is(tok::ellipsis)) {
3683 SourceLocation EllipsisLoc = ConsumeToken();
David Blaikiebbafb8a2012-03-11 07:00:24 +00003684 if (!getLangOpts().MicrosoftExt)
Douglas Gregor356513d2008-12-01 18:00:20 +00003685 Diag(EllipsisLoc, diag::ext_ellipsis_exception_spec);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003686 T.consumeClose();
3687 SpecificationRange.setEnd(T.getCloseLocation());
Richard Smith8ca78a12013-06-13 02:02:51 +00003688 diagnoseDynamicExceptionSpecification(*this, SpecificationRange, false);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003689 return EST_MSAny;
Douglas Gregor356513d2008-12-01 18:00:20 +00003690 }
3691
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003692 // Parse the sequence of type-ids.
Sebastian Redld6434562009-05-29 18:02:33 +00003693 SourceRange Range;
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003694 while (Tok.isNot(tok::r_paren)) {
Sebastian Redld6434562009-05-29 18:02:33 +00003695 TypeResult Res(ParseTypeName(&Range));
Sebastian Redl965b0e32011-03-05 14:45:16 +00003696
Douglas Gregor830837d2010-12-20 23:57:46 +00003697 if (Tok.is(tok::ellipsis)) {
3698 // C++0x [temp.variadic]p5:
Fangrui Song6907ce22018-07-30 19:24:48 +00003699 // - In a dynamic-exception-specification (15.4); the pattern is a
Douglas Gregor830837d2010-12-20 23:57:46 +00003700 // type-id.
3701 SourceLocation Ellipsis = ConsumeToken();
Sebastian Redl965b0e32011-03-05 14:45:16 +00003702 Range.setEnd(Ellipsis);
Douglas Gregor830837d2010-12-20 23:57:46 +00003703 if (!Res.isInvalid())
3704 Res = Actions.ActOnPackExpansion(Res.get(), Ellipsis);
3705 }
Sebastian Redl965b0e32011-03-05 14:45:16 +00003706
Sebastian Redld6434562009-05-29 18:02:33 +00003707 if (!Res.isInvalid()) {
Sebastian Redl2b9cacb2009-04-29 17:30:04 +00003708 Exceptions.push_back(Res.get());
Sebastian Redld6434562009-05-29 18:02:33 +00003709 Ranges.push_back(Range);
3710 }
Alp Toker97650562014-01-10 11:19:30 +00003711
3712 if (!TryConsumeToken(tok::comma))
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003713 break;
3714 }
3715
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003716 T.consumeClose();
3717 SpecificationRange.setEnd(T.getCloseLocation());
Richard Smith8ca78a12013-06-13 02:02:51 +00003718 diagnoseDynamicExceptionSpecification(*this, SpecificationRange,
3719 Exceptions.empty());
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003720 return Exceptions.empty() ? EST_DynamicNone : EST_Dynamic;
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003721}
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003722
Douglas Gregor7fb25412010-10-01 18:44:50 +00003723/// ParseTrailingReturnType - Parse a trailing return type on a new-style
3724/// function declaration.
Richard Smithe303e352018-02-02 22:24:54 +00003725TypeResult Parser::ParseTrailingReturnType(SourceRange &Range,
3726 bool MayBeFollowedByDirectInit) {
Douglas Gregor7fb25412010-10-01 18:44:50 +00003727 assert(Tok.is(tok::arrow) && "expected arrow");
3728
3729 ConsumeToken();
3730
Richard Smithe303e352018-02-02 22:24:54 +00003731 return ParseTypeName(&Range, MayBeFollowedByDirectInit
3732 ? DeclaratorContext::TrailingReturnVarContext
3733 : DeclaratorContext::TrailingReturnContext);
Douglas Gregor7fb25412010-10-01 18:44:50 +00003734}
3735
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003736/// We have just started parsing the definition of a new class,
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003737/// so push that class onto our stack of classes that is currently
3738/// being parsed.
John McCallc1465822011-02-14 07:13:47 +00003739Sema::ParsingClassState
John McCalldb632ac2012-09-25 07:32:39 +00003740Parser::PushParsingClass(Decl *ClassDecl, bool NonNestedClass,
3741 bool IsInterface) {
Douglas Gregoredf8f392010-01-16 20:52:59 +00003742 assert((NonNestedClass || !ClassStack.empty()) &&
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003743 "Nested class without outer class");
John McCalldb632ac2012-09-25 07:32:39 +00003744 ClassStack.push(new ParsingClass(ClassDecl, NonNestedClass, IsInterface));
John McCallc1465822011-02-14 07:13:47 +00003745 return Actions.PushParsingClass();
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003746}
3747
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003748/// Deallocate the given parsed class and all of its nested
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003749/// classes.
3750void Parser::DeallocateParsedClasses(Parser::ParsingClass *Class) {
Douglas Gregorefc46952010-10-12 16:25:54 +00003751 for (unsigned I = 0, N = Class->LateParsedDeclarations.size(); I != N; ++I)
3752 delete Class->LateParsedDeclarations[I];
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003753 delete Class;
3754}
3755
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003756/// Pop the top class of the stack of classes that are
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003757/// currently being parsed.
3758///
3759/// This routine should be called when we have finished parsing the
3760/// definition of a class, but have not yet popped the Scope
3761/// associated with the class's definition.
John McCallc1465822011-02-14 07:13:47 +00003762void Parser::PopParsingClass(Sema::ParsingClassState state) {
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003763 assert(!ClassStack.empty() && "Mismatched push/pop for class parsing");
Mike Stump11289f42009-09-09 15:08:12 +00003764
John McCallc1465822011-02-14 07:13:47 +00003765 Actions.PopParsingClass(state);
3766
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003767 ParsingClass *Victim = ClassStack.top();
3768 ClassStack.pop();
3769 if (Victim->TopLevelClass) {
3770 // Deallocate all of the nested classes of this class,
3771 // recursively: we don't need to keep any of this information.
3772 DeallocateParsedClasses(Victim);
3773 return;
Mike Stump11289f42009-09-09 15:08:12 +00003774 }
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003775 assert(!ClassStack.empty() && "Missing top-level class?");
3776
Douglas Gregorefc46952010-10-12 16:25:54 +00003777 if (Victim->LateParsedDeclarations.empty()) {
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003778 // The victim is a nested class, but we will not need to perform
3779 // any processing after the definition of this class since it has
3780 // no members whose handling was delayed. Therefore, we can just
3781 // remove this nested class.
Douglas Gregorefc46952010-10-12 16:25:54 +00003782 DeallocateParsedClasses(Victim);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003783 return;
3784 }
3785
3786 // This nested class has some members that will need to be processed
3787 // after the top-level class is completely defined. Therefore, add
3788 // it to the list of nested classes within its parent.
Douglas Gregor0be31a22010-07-02 17:43:08 +00003789 assert(getCurScope()->isClassScope() && "Nested class outside of class scope?");
Douglas Gregorefc46952010-10-12 16:25:54 +00003790 ClassStack.top()->LateParsedDeclarations.push_back(new LateParsedClass(this, Victim));
Douglas Gregor0be31a22010-07-02 17:43:08 +00003791 Victim->TemplateScope = getCurScope()->getParent()->isTemplateParamScope();
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003792}
Alexis Hunt96d5c762009-11-21 08:43:09 +00003793
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003794/// Try to parse an 'identifier' which appears within an attribute-token.
Richard Smith3dff2512012-04-10 03:25:07 +00003795///
3796/// \return the parsed identifier on success, and 0 if the next token is not an
3797/// attribute-token.
3798///
3799/// C++11 [dcl.attr.grammar]p3:
3800/// If a keyword or an alternative token that satisfies the syntactic
3801/// requirements of an identifier is contained in an attribute-token,
3802/// it is considered an identifier.
3803IdentifierInfo *Parser::TryParseCXX11AttributeIdentifier(SourceLocation &Loc) {
3804 switch (Tok.getKind()) {
3805 default:
3806 // Identifiers and keywords have identifier info attached.
David Majnemerd5271992015-01-09 18:09:39 +00003807 if (!Tok.isAnnotation()) {
3808 if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
3809 Loc = ConsumeToken();
3810 return II;
3811 }
Richard Smith3dff2512012-04-10 03:25:07 +00003812 }
Craig Topper161e4db2014-05-21 06:02:52 +00003813 return nullptr;
Richard Smith3dff2512012-04-10 03:25:07 +00003814
Aaron Ballmanc44c17422018-11-09 17:19:45 +00003815 case tok::numeric_constant: {
3816 // If we got a numeric constant, check to see if it comes from a macro that
3817 // corresponds to the predefined __clang__ macro. If it does, warn the user
3818 // and recover by pretending they said _Clang instead.
3819 if (Tok.getLocation().isMacroID()) {
3820 SmallString<8> ExpansionBuf;
3821 SourceLocation ExpansionLoc =
3822 PP.getSourceManager().getExpansionLoc(Tok.getLocation());
3823 StringRef Spelling = PP.getSpelling(ExpansionLoc, ExpansionBuf);
3824 if (Spelling == "__clang__") {
3825 SourceRange TokRange(
3826 ExpansionLoc,
3827 PP.getSourceManager().getExpansionLoc(Tok.getEndLoc()));
3828 Diag(Tok, diag::warn_wrong_clang_attr_namespace)
3829 << FixItHint::CreateReplacement(TokRange, "_Clang");
3830 Loc = ConsumeToken();
3831 return &PP.getIdentifierTable().get("_Clang");
3832 }
3833 }
3834 return nullptr;
3835 }
3836
Richard Smith3dff2512012-04-10 03:25:07 +00003837 case tok::ampamp: // 'and'
3838 case tok::pipe: // 'bitor'
3839 case tok::pipepipe: // 'or'
3840 case tok::caret: // 'xor'
3841 case tok::tilde: // 'compl'
3842 case tok::amp: // 'bitand'
3843 case tok::ampequal: // 'and_eq'
3844 case tok::pipeequal: // 'or_eq'
3845 case tok::caretequal: // 'xor_eq'
3846 case tok::exclaim: // 'not'
3847 case tok::exclaimequal: // 'not_eq'
3848 // Alternative tokens do not have identifier info, but their spelling
3849 // starts with an alphabetical character.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003850 SmallString<8> SpellingBuf;
Benjamin Kramer60be5632015-03-29 19:25:07 +00003851 SourceLocation SpellingLoc =
3852 PP.getSourceManager().getSpellingLoc(Tok.getLocation());
3853 StringRef Spelling = PP.getSpelling(SpellingLoc, SpellingBuf);
Jordan Rosea7d03842013-02-08 22:30:41 +00003854 if (isLetter(Spelling[0])) {
Richard Smith3dff2512012-04-10 03:25:07 +00003855 Loc = ConsumeToken();
Benjamin Kramer5c17f9c2012-04-22 20:43:30 +00003856 return &PP.getIdentifierTable().get(Spelling);
Richard Smith3dff2512012-04-10 03:25:07 +00003857 }
Craig Topper161e4db2014-05-21 06:02:52 +00003858 return nullptr;
Richard Smith3dff2512012-04-10 03:25:07 +00003859 }
3860}
3861
Michael Han23214e52012-10-03 01:56:22 +00003862static bool IsBuiltInOrStandardCXX11Attribute(IdentifierInfo *AttrName,
Aaron Ballman606093a2017-10-15 15:01:42 +00003863 IdentifierInfo *ScopeName) {
Erich Keanee891aa92018-07-13 15:07:47 +00003864 switch (ParsedAttr::getKind(AttrName, ScopeName, ParsedAttr::AS_CXX11)) {
3865 case ParsedAttr::AT_CarriesDependency:
3866 case ParsedAttr::AT_Deprecated:
3867 case ParsedAttr::AT_FallThrough:
3868 case ParsedAttr::AT_CXX11NoReturn:
Michael Han23214e52012-10-03 01:56:22 +00003869 return true;
Erich Keanee891aa92018-07-13 15:07:47 +00003870 case ParsedAttr::AT_WarnUnusedResult:
Aaron Ballmane7964782016-03-07 22:44:55 +00003871 return !ScopeName && AttrName->getName().equals("nodiscard");
Erich Keanee891aa92018-07-13 15:07:47 +00003872 case ParsedAttr::AT_Unused:
Nico Weberac03bce2016-08-23 19:59:55 +00003873 return !ScopeName && AttrName->getName().equals("maybe_unused");
Michael Han23214e52012-10-03 01:56:22 +00003874 default:
3875 return false;
3876 }
3877}
3878
Aaron Ballmanb8e20392014-03-31 17:32:39 +00003879/// ParseCXX11AttributeArgs -- Parse a C++11 attribute-argument-clause.
3880///
3881/// [C++11] attribute-argument-clause:
3882/// '(' balanced-token-seq ')'
3883///
3884/// [C++11] balanced-token-seq:
3885/// balanced-token
3886/// balanced-token-seq balanced-token
3887///
3888/// [C++11] balanced-token:
3889/// '(' balanced-token-seq ')'
3890/// '[' balanced-token-seq ']'
3891/// '{' balanced-token-seq '}'
3892/// any token but '(', ')', '[', ']', '{', or '}'
3893bool Parser::ParseCXX11AttributeArgs(IdentifierInfo *AttrName,
3894 SourceLocation AttrNameLoc,
3895 ParsedAttributes &Attrs,
3896 SourceLocation *EndLoc,
3897 IdentifierInfo *ScopeName,
3898 SourceLocation ScopeLoc) {
3899 assert(Tok.is(tok::l_paren) && "Not a C++11 attribute argument list");
Aaron Ballman35f94212014-04-14 16:03:22 +00003900 SourceLocation LParenLoc = Tok.getLocation();
Aaron Ballman606093a2017-10-15 15:01:42 +00003901 const LangOptions &LO = getLangOpts();
Erich Keanee891aa92018-07-13 15:07:47 +00003902 ParsedAttr::Syntax Syntax =
3903 LO.CPlusPlus ? ParsedAttr::AS_CXX11 : ParsedAttr::AS_C2x;
Aaron Ballmanb8e20392014-03-31 17:32:39 +00003904
3905 // If the attribute isn't known, we will not attempt to parse any
3906 // arguments.
Aaron Ballman606093a2017-10-15 15:01:42 +00003907 if (!hasAttribute(LO.CPlusPlus ? AttrSyntax::CXX : AttrSyntax::C, ScopeName,
3908 AttrName, getTargetInfo(), getLangOpts())) {
Aaron Ballmanb8e20392014-03-31 17:32:39 +00003909 // Eat the left paren, then skip to the ending right paren.
3910 ConsumeParen();
3911 SkipUntil(tok::r_paren);
Aaron Ballmanc44c17422018-11-09 17:19:45 +00003912 return false;
3913 }
3914
3915 if (ScopeName && (ScopeName->isStr("gnu") || ScopeName->isStr("__gnu__"))) {
3916 // GNU-scoped attributes have some special cases to handle GNU-specific
3917 // behaviors.
3918 ParseGNUAttributeArgs(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
Aaron Ballman606093a2017-10-15 15:01:42 +00003919 ScopeLoc, Syntax, nullptr);
Alex Lorenzd5d27e12017-03-01 18:06:25 +00003920 return true;
3921 }
3922
3923 unsigned NumArgs;
3924 // Some Clang-scoped attributes have some special parsing behavior.
Aaron Ballmanc44c17422018-11-09 17:19:45 +00003925 if (ScopeName && (ScopeName->isStr("clang") || ScopeName->isStr("_Clang")))
3926 NumArgs = ParseClangAttributeArgs(AttrName, AttrNameLoc, Attrs, EndLoc,
3927 ScopeName, ScopeLoc, Syntax);
Alex Lorenzd5d27e12017-03-01 18:06:25 +00003928 else
3929 NumArgs =
Aaron Ballman35f94212014-04-14 16:03:22 +00003930 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc,
Aaron Ballman606093a2017-10-15 15:01:42 +00003931 ScopeName, ScopeLoc, Syntax);
Alex Lorenzd5d27e12017-03-01 18:06:25 +00003932
Erich Keanec480f302018-07-12 21:09:05 +00003933 if (!Attrs.empty() &&
3934 IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName)) {
Michael Krusedc5ce722018-08-03 01:21:16 +00003935 ParsedAttr &Attr = Attrs.back();
Alex Lorenzd5d27e12017-03-01 18:06:25 +00003936 // If the attribute is a standard or built-in attribute and we are
3937 // parsing an argument list, we need to determine whether this attribute
3938 // was allowed to have an argument list (such as [[deprecated]]), and how
3939 // many arguments were parsed (so we can diagnose on [[deprecated()]]).
Erich Keanec480f302018-07-12 21:09:05 +00003940 if (Attr.getMaxArgs() && !NumArgs) {
Alex Lorenzd5d27e12017-03-01 18:06:25 +00003941 // The attribute was allowed to have arguments, but none were provided
3942 // even though the attribute parsed successfully. This is an error.
3943 Diag(LParenLoc, diag::err_attribute_requires_arguments) << AttrName;
Erich Keanec480f302018-07-12 21:09:05 +00003944 Attr.setInvalid(true);
3945 } else if (!Attr.getMaxArgs()) {
Alex Lorenzd5d27e12017-03-01 18:06:25 +00003946 // The attribute parsed successfully, but was not allowed to have any
3947 // arguments. It doesn't matter whether any were provided -- the
3948 // presence of the argument list (even if empty) is diagnosed.
3949 Diag(LParenLoc, diag::err_cxx11_attribute_forbids_arguments)
3950 << AttrName
3951 << FixItHint::CreateRemoval(SourceRange(LParenLoc, *EndLoc));
Erich Keanec480f302018-07-12 21:09:05 +00003952 Attr.setInvalid(true);
Aaron Ballman35f94212014-04-14 16:03:22 +00003953 }
3954 }
Aaron Ballmanb8e20392014-03-31 17:32:39 +00003955 return true;
3956}
3957
Aaron Ballman606093a2017-10-15 15:01:42 +00003958/// ParseCXX11AttributeSpecifier - Parse a C++11 or C2x attribute-specifier.
Alexis Hunt96d5c762009-11-21 08:43:09 +00003959///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003960/// [C++11] attribute-specifier:
Alexis Hunt96d5c762009-11-21 08:43:09 +00003961/// '[' '[' attribute-list ']' ']'
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00003962/// alignment-specifier
Alexis Hunt96d5c762009-11-21 08:43:09 +00003963///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003964/// [C++11] attribute-list:
Alexis Hunt96d5c762009-11-21 08:43:09 +00003965/// attribute[opt]
3966/// attribute-list ',' attribute[opt]
Richard Smith3dff2512012-04-10 03:25:07 +00003967/// attribute '...'
3968/// attribute-list ',' attribute '...'
Alexis Hunt96d5c762009-11-21 08:43:09 +00003969///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003970/// [C++11] attribute:
Alexis Hunt96d5c762009-11-21 08:43:09 +00003971/// attribute-token attribute-argument-clause[opt]
3972///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003973/// [C++11] attribute-token:
Alexis Hunt96d5c762009-11-21 08:43:09 +00003974/// identifier
3975/// attribute-scoped-token
3976///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003977/// [C++11] attribute-scoped-token:
Alexis Hunt96d5c762009-11-21 08:43:09 +00003978/// attribute-namespace '::' identifier
3979///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003980/// [C++11] attribute-namespace:
Alexis Hunt96d5c762009-11-21 08:43:09 +00003981/// identifier
Richard Smith3dff2512012-04-10 03:25:07 +00003982void Parser::ParseCXX11AttributeSpecifier(ParsedAttributes &attrs,
Peter Collingbourne49eedec2011-09-29 18:04:05 +00003983 SourceLocation *endLoc) {
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00003984 if (Tok.is(tok::kw_alignas)) {
Richard Smithf679b5b2011-10-14 20:48:27 +00003985 Diag(Tok.getLocation(), diag::warn_cxx98_compat_alignas);
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00003986 ParseAlignmentSpecifier(attrs, endLoc);
3987 return;
3988 }
3989
Aaron Ballman606093a2017-10-15 15:01:42 +00003990 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square) &&
3991 "Not a double square bracket attribute list");
Alexis Hunt96d5c762009-11-21 08:43:09 +00003992
Richard Smithf679b5b2011-10-14 20:48:27 +00003993 Diag(Tok.getLocation(), diag::warn_cxx98_compat_attribute);
3994
Alexis Hunt96d5c762009-11-21 08:43:09 +00003995 ConsumeBracket();
3996 ConsumeBracket();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003997
Richard Smithb7d7a042016-06-24 12:15:12 +00003998 SourceLocation CommonScopeLoc;
3999 IdentifierInfo *CommonScopeName = nullptr;
4000 if (Tok.is(tok::kw_using)) {
Aaron Ballmanc351fba2017-12-04 20:27:34 +00004001 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
Richard Smithb7d7a042016-06-24 12:15:12 +00004002 ? diag::warn_cxx14_compat_using_attribute_ns
4003 : diag::ext_using_attribute_ns);
4004 ConsumeToken();
4005
4006 CommonScopeName = TryParseCXX11AttributeIdentifier(CommonScopeLoc);
4007 if (!CommonScopeName) {
4008 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
4009 SkipUntil(tok::r_square, tok::colon, StopBeforeMatch);
4010 }
4011 if (!TryConsumeToken(tok::colon) && CommonScopeName)
4012 Diag(Tok.getLocation(), diag::err_expected) << tok::colon;
4013 }
4014
Richard Smith10876ef2013-01-17 01:30:42 +00004015 llvm::SmallDenseMap<IdentifierInfo*, SourceLocation, 4> SeenAttrs;
4016
Richard Smith3dff2512012-04-10 03:25:07 +00004017 while (Tok.isNot(tok::r_square)) {
Alexis Hunt96d5c762009-11-21 08:43:09 +00004018 // attribute not present
Alp Toker97650562014-01-10 11:19:30 +00004019 if (TryConsumeToken(tok::comma))
Alexis Hunt96d5c762009-11-21 08:43:09 +00004020 continue;
Alexis Hunt96d5c762009-11-21 08:43:09 +00004021
Richard Smith3dff2512012-04-10 03:25:07 +00004022 SourceLocation ScopeLoc, AttrLoc;
Craig Topper161e4db2014-05-21 06:02:52 +00004023 IdentifierInfo *ScopeName = nullptr, *AttrName = nullptr;
Richard Smith3dff2512012-04-10 03:25:07 +00004024
4025 AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
4026 if (!AttrName)
4027 // Break out to the "expected ']'" diagnostic.
4028 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004029
Alexis Hunt96d5c762009-11-21 08:43:09 +00004030 // scoped attribute
Alp Toker97650562014-01-10 11:19:30 +00004031 if (TryConsumeToken(tok::coloncolon)) {
Richard Smith3dff2512012-04-10 03:25:07 +00004032 ScopeName = AttrName;
4033 ScopeLoc = AttrLoc;
4034
4035 AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
4036 if (!AttrName) {
Alp Tokerec543272013-12-24 09:48:30 +00004037 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
Alexey Bataevee6507d2013-11-18 08:17:37 +00004038 SkipUntil(tok::r_square, tok::comma, StopAtSemi | StopBeforeMatch);
Alexis Hunt96d5c762009-11-21 08:43:09 +00004039 continue;
4040 }
Alexis Hunt96d5c762009-11-21 08:43:09 +00004041 }
4042
Richard Smithb7d7a042016-06-24 12:15:12 +00004043 if (CommonScopeName) {
4044 if (ScopeName) {
4045 Diag(ScopeLoc, diag::err_using_attribute_ns_conflict)
4046 << SourceRange(CommonScopeLoc);
4047 } else {
4048 ScopeName = CommonScopeName;
4049 ScopeLoc = CommonScopeLoc;
4050 }
4051 }
4052
Aaron Ballmanb8e20392014-03-31 17:32:39 +00004053 bool StandardAttr = IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName);
Alexis Hunt96d5c762009-11-21 08:43:09 +00004054 bool AttrParsed = false;
Alexis Hunt96d5c762009-11-21 08:43:09 +00004055
Richard Smith10876ef2013-01-17 01:30:42 +00004056 if (StandardAttr &&
4057 !SeenAttrs.insert(std::make_pair(AttrName, AttrLoc)).second)
4058 Diag(AttrLoc, diag::err_cxx11_attribute_repeated)
Aaron Ballmanb8e20392014-03-31 17:32:39 +00004059 << AttrName << SourceRange(SeenAttrs[AttrName]);
Richard Smith10876ef2013-01-17 01:30:42 +00004060
Michael Han23214e52012-10-03 01:56:22 +00004061 // Parse attribute arguments
Aaron Ballman35f94212014-04-14 16:03:22 +00004062 if (Tok.is(tok::l_paren))
Aaron Ballmanb8e20392014-03-31 17:32:39 +00004063 AttrParsed = ParseCXX11AttributeArgs(AttrName, AttrLoc, attrs, endLoc,
4064 ScopeName, ScopeLoc);
Michael Han23214e52012-10-03 01:56:22 +00004065
4066 if (!AttrParsed)
Aaron Ballman606093a2017-10-15 15:01:42 +00004067 attrs.addNew(
4068 AttrName,
4069 SourceRange(ScopeLoc.isValid() ? ScopeLoc : AttrLoc, AttrLoc),
4070 ScopeName, ScopeLoc, nullptr, 0,
Erich Keanee891aa92018-07-13 15:07:47 +00004071 getLangOpts().CPlusPlus ? ParsedAttr::AS_CXX11 : ParsedAttr::AS_C2x);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004072
Alp Toker97650562014-01-10 11:19:30 +00004073 if (TryConsumeToken(tok::ellipsis))
Michael Han23214e52012-10-03 01:56:22 +00004074 Diag(Tok, diag::err_cxx11_attribute_forbids_ellipsis)
Richard Trieub4025802018-03-28 04:16:13 +00004075 << AttrName;
Alexis Hunt96d5c762009-11-21 08:43:09 +00004076 }
4077
Alp Toker383d2c42014-01-01 03:08:43 +00004078 if (ExpectAndConsume(tok::r_square))
Alexey Bataevee6507d2013-11-18 08:17:37 +00004079 SkipUntil(tok::r_square);
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004080 if (endLoc)
4081 *endLoc = Tok.getLocation();
Alp Toker383d2c42014-01-01 03:08:43 +00004082 if (ExpectAndConsume(tok::r_square))
Alexey Bataevee6507d2013-11-18 08:17:37 +00004083 SkipUntil(tok::r_square);
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004084}
Alexis Hunt96d5c762009-11-21 08:43:09 +00004085
Aaron Ballman606093a2017-10-15 15:01:42 +00004086/// ParseCXX11Attributes - Parse a C++11 or C2x attribute-specifier-seq.
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004087///
4088/// attribute-specifier-seq:
4089/// attribute-specifier-seq[opt] attribute-specifier
Richard Smith3dff2512012-04-10 03:25:07 +00004090void Parser::ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004091 SourceLocation *endLoc) {
Aaron Ballman606093a2017-10-15 15:01:42 +00004092 assert(standardAttributesAllowed());
Richard Smith4cabd042013-02-22 09:15:49 +00004093
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004094 SourceLocation StartLoc = Tok.getLocation(), Loc;
4095 if (!endLoc)
4096 endLoc = &Loc;
4097
Douglas Gregor6f981002011-10-07 20:35:25 +00004098 do {
Richard Smith3dff2512012-04-10 03:25:07 +00004099 ParseCXX11AttributeSpecifier(attrs, endLoc);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004100 } while (isCXX11AttributeSpecifier());
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004101
4102 attrs.Range = SourceRange(StartLoc, *endLoc);
Alexis Hunt96d5c762009-11-21 08:43:09 +00004103}
4104
Richard Smithc2c8bb82013-10-15 01:34:54 +00004105void Parser::DiagnoseAndSkipCXX11Attributes() {
Richard Smithc2c8bb82013-10-15 01:34:54 +00004106 // Start and end location of an attribute or an attribute list.
4107 SourceLocation StartLoc = Tok.getLocation();
Richard Smith955bf012014-06-19 11:42:00 +00004108 SourceLocation EndLoc = SkipCXX11Attributes();
4109
4110 if (EndLoc.isValid()) {
4111 SourceRange Range(StartLoc, EndLoc);
4112 Diag(StartLoc, diag::err_attributes_not_allowed)
4113 << Range;
4114 }
4115}
4116
4117SourceLocation Parser::SkipCXX11Attributes() {
Richard Smithc2c8bb82013-10-15 01:34:54 +00004118 SourceLocation EndLoc;
4119
Richard Smith955bf012014-06-19 11:42:00 +00004120 if (!isCXX11AttributeSpecifier())
4121 return EndLoc;
4122
Richard Smithc2c8bb82013-10-15 01:34:54 +00004123 do {
4124 if (Tok.is(tok::l_square)) {
4125 BalancedDelimiterTracker T(*this, tok::l_square);
4126 T.consumeOpen();
4127 T.skipToEnd();
4128 EndLoc = T.getCloseLocation();
4129 } else {
4130 assert(Tok.is(tok::kw_alignas) && "not an attribute specifier");
4131 ConsumeToken();
4132 BalancedDelimiterTracker T(*this, tok::l_paren);
4133 if (!T.consumeOpen())
4134 T.skipToEnd();
4135 EndLoc = T.getCloseLocation();
4136 }
4137 } while (isCXX11AttributeSpecifier());
4138
Richard Smith955bf012014-06-19 11:42:00 +00004139 return EndLoc;
Richard Smithc2c8bb82013-10-15 01:34:54 +00004140}
4141
Nico Weber05e1dad2016-09-03 03:25:22 +00004142/// Parse uuid() attribute when it appears in a [] Microsoft attribute.
4143void Parser::ParseMicrosoftUuidAttributeArgs(ParsedAttributes &Attrs) {
4144 assert(Tok.is(tok::identifier) && "Not a Microsoft attribute list");
4145 IdentifierInfo *UuidIdent = Tok.getIdentifierInfo();
4146 assert(UuidIdent->getName() == "uuid" && "Not a Microsoft attribute list");
4147
4148 SourceLocation UuidLoc = Tok.getLocation();
4149 ConsumeToken();
4150
4151 // Ignore the left paren location for now.
4152 BalancedDelimiterTracker T(*this, tok::l_paren);
4153 if (T.consumeOpen()) {
4154 Diag(Tok, diag::err_expected) << tok::l_paren;
4155 return;
4156 }
4157
4158 ArgsVector ArgExprs;
4159 if (Tok.is(tok::string_literal)) {
4160 // Easy case: uuid("...") -- quoted string.
4161 ExprResult StringResult = ParseStringLiteralExpression();
4162 if (StringResult.isInvalid())
4163 return;
4164 ArgExprs.push_back(StringResult.get());
4165 } else {
4166 // something like uuid({000000A0-0000-0000-C000-000000000049}) -- no
4167 // quotes in the parens. Just append the spelling of all tokens encountered
4168 // until the closing paren.
4169
4170 SmallString<42> StrBuffer; // 2 "", 36 bytes UUID, 2 optional {}, 1 nul
4171 StrBuffer += "\"";
4172
4173 // Since none of C++'s keywords match [a-f]+, accepting just tok::l_brace,
4174 // tok::r_brace, tok::minus, tok::identifier (think C000) and
4175 // tok::numeric_constant (0000) should be enough. But the spelling of the
4176 // uuid argument is checked later anyways, so there's no harm in accepting
4177 // almost anything here.
4178 // cl is very strict about whitespace in this form and errors out if any
4179 // is present, so check the space flags on the tokens.
4180 SourceLocation StartLoc = Tok.getLocation();
4181 while (Tok.isNot(tok::r_paren)) {
4182 if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
4183 Diag(Tok, diag::err_attribute_uuid_malformed_guid);
4184 SkipUntil(tok::r_paren, StopAtSemi);
4185 return;
4186 }
4187 SmallString<16> SpellingBuffer;
4188 SpellingBuffer.resize(Tok.getLength() + 1);
4189 bool Invalid = false;
4190 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
4191 if (Invalid) {
4192 SkipUntil(tok::r_paren, StopAtSemi);
4193 return;
4194 }
4195 StrBuffer += TokSpelling;
4196 ConsumeAnyToken();
4197 }
4198 StrBuffer += "\"";
4199
4200 if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
4201 Diag(Tok, diag::err_attribute_uuid_malformed_guid);
4202 ConsumeParen();
4203 return;
4204 }
4205
4206 // Pretend the user wrote the appropriate string literal here.
4207 // ActOnStringLiteral() copies the string data into the literal, so it's
4208 // ok that the Token points to StrBuffer.
4209 Token Toks[1];
4210 Toks[0].startToken();
4211 Toks[0].setKind(tok::string_literal);
4212 Toks[0].setLocation(StartLoc);
4213 Toks[0].setLiteralData(StrBuffer.data());
4214 Toks[0].setLength(StrBuffer.size());
4215 StringLiteral *UuidString =
4216 cast<StringLiteral>(Actions.ActOnStringLiteral(Toks, nullptr).get());
4217 ArgExprs.push_back(UuidString);
4218 }
4219
4220 if (!T.consumeClose()) {
Nico Weber05e1dad2016-09-03 03:25:22 +00004221 Attrs.addNew(UuidIdent, SourceRange(UuidLoc, T.getCloseLocation()), nullptr,
4222 SourceLocation(), ArgExprs.data(), ArgExprs.size(),
Erich Keanee891aa92018-07-13 15:07:47 +00004223 ParsedAttr::AS_Microsoft);
Nico Weber05e1dad2016-09-03 03:25:22 +00004224 }
4225}
4226
David Majnemere4752e752015-07-08 05:55:00 +00004227/// ParseMicrosoftAttributes - Parse Microsoft attributes [Attr]
Francois Pichetc2bc5ac2010-10-11 12:59:39 +00004228///
4229/// [MS] ms-attribute:
4230/// '[' token-seq ']'
4231///
4232/// [MS] ms-attribute-seq:
4233/// ms-attribute[opt]
4234/// ms-attribute ms-attribute-seq
John McCall53fa7142010-12-24 02:08:15 +00004235void Parser::ParseMicrosoftAttributes(ParsedAttributes &attrs,
4236 SourceLocation *endLoc) {
Francois Pichetc2bc5ac2010-10-11 12:59:39 +00004237 assert(Tok.is(tok::l_square) && "Not a Microsoft attribute list");
4238
Saleem Abdulrasool425efcf2015-06-15 20:57:04 +00004239 do {
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004240 // FIXME: If this is actually a C++11 attribute, parse it as one.
Saleem Abdulrasool425efcf2015-06-15 20:57:04 +00004241 BalancedDelimiterTracker T(*this, tok::l_square);
4242 T.consumeOpen();
Nico Weber05e1dad2016-09-03 03:25:22 +00004243
4244 // Skip most ms attributes except for a whitelist.
4245 while (true) {
4246 SkipUntil(tok::r_square, tok::identifier, StopAtSemi | StopBeforeMatch);
4247 if (Tok.isNot(tok::identifier)) // ']', but also eof
4248 break;
4249 if (Tok.getIdentifierInfo()->getName() == "uuid")
4250 ParseMicrosoftUuidAttributeArgs(attrs);
4251 else
4252 ConsumeToken();
4253 }
4254
Saleem Abdulrasool425efcf2015-06-15 20:57:04 +00004255 T.consumeClose();
4256 if (endLoc)
4257 *endLoc = T.getCloseLocation();
4258 } while (Tok.is(tok::l_square));
Francois Pichetc2bc5ac2010-10-11 12:59:39 +00004259}
Francois Pichet8f981d52011-05-25 10:19:49 +00004260
Erich Keanec480f302018-07-12 21:09:05 +00004261void Parser::ParseMicrosoftIfExistsClassDeclaration(
4262 DeclSpec::TST TagType, ParsedAttributes &AccessAttrs,
4263 AccessSpecifier &CurAS) {
Douglas Gregor43edb322011-10-24 22:31:10 +00004264 IfExistsCondition Result;
Francois Pichet8f981d52011-05-25 10:19:49 +00004265 if (ParseMicrosoftIfExistsCondition(Result))
4266 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00004267
Douglas Gregor43edb322011-10-24 22:31:10 +00004268 BalancedDelimiterTracker Braces(*this, tok::l_brace);
4269 if (Braces.consumeOpen()) {
Alp Tokerec543272013-12-24 09:48:30 +00004270 Diag(Tok, diag::err_expected) << tok::l_brace;
Francois Pichet8f981d52011-05-25 10:19:49 +00004271 return;
4272 }
Francois Pichet8f981d52011-05-25 10:19:49 +00004273
Douglas Gregor43edb322011-10-24 22:31:10 +00004274 switch (Result.Behavior) {
4275 case IEB_Parse:
4276 // Parse the declarations below.
4277 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00004278
Douglas Gregor43edb322011-10-24 22:31:10 +00004279 case IEB_Dependent:
4280 Diag(Result.KeywordLoc, diag::warn_microsoft_dependent_exists)
4281 << Result.IsIfExists;
4282 // Fall through to skip.
Galina Kistanovad819d5b2017-06-01 21:19:06 +00004283 LLVM_FALLTHROUGH;
Fangrui Song6907ce22018-07-30 19:24:48 +00004284
Douglas Gregor43edb322011-10-24 22:31:10 +00004285 case IEB_Skip:
4286 Braces.skipToEnd();
Francois Pichet8f981d52011-05-25 10:19:49 +00004287 return;
4288 }
4289
Richard Smith34f30512013-11-23 04:06:09 +00004290 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
Francois Pichet8f981d52011-05-25 10:19:49 +00004291 // __if_exists, __if_not_exists can nest.
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00004292 if (Tok.isOneOf(tok::kw___if_exists, tok::kw___if_not_exists)) {
Erich Keanec480f302018-07-12 21:09:05 +00004293 ParseMicrosoftIfExistsClassDeclaration((DeclSpec::TST)TagType,
4294 AccessAttrs, CurAS);
Francois Pichet8f981d52011-05-25 10:19:49 +00004295 continue;
4296 }
4297
4298 // Check for extraneous top-level semicolon.
4299 if (Tok.is(tok::semi)) {
Richard Smith87f5dc52012-07-23 05:45:25 +00004300 ConsumeExtraSemi(InsideStruct, TagType);
Francois Pichet8f981d52011-05-25 10:19:49 +00004301 continue;
4302 }
4303
4304 AccessSpecifier AS = getAccessSpecifierIfPresent();
4305 if (AS != AS_none) {
4306 // Current token is a C++ access specifier.
4307 CurAS = AS;
4308 SourceLocation ASLoc = Tok.getLocation();
4309 ConsumeToken();
4310 if (Tok.is(tok::colon))
Erich Keanec480f302018-07-12 21:09:05 +00004311 Actions.ActOnAccessSpecifier(AS, ASLoc, Tok.getLocation(),
4312 ParsedAttributesView{});
Francois Pichet8f981d52011-05-25 10:19:49 +00004313 else
Alp Toker35d87032013-12-30 23:29:50 +00004314 Diag(Tok, diag::err_expected) << tok::colon;
Francois Pichet8f981d52011-05-25 10:19:49 +00004315 ConsumeToken();
4316 continue;
4317 }
4318
4319 // Parse all the comma separated declarators.
Erich Keanec480f302018-07-12 21:09:05 +00004320 ParseCXXClassMemberDeclaration(CurAS, AccessAttrs);
Francois Pichet8f981d52011-05-25 10:19:49 +00004321 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004322
Douglas Gregor43edb322011-10-24 22:31:10 +00004323 Braces.consumeClose();
Francois Pichet8f981d52011-05-25 10:19:49 +00004324}