blob: a86f7ed8642b7226b793583204d3fe82d8d24850 [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///
36/// namespace-definition: [C++ 7.3: basic.namespace]
37/// named-namespace-definition
38/// unnamed-namespace-definition
39///
40/// unnamed-namespace-definition:
Sebastian Redl67667942010-08-27 23:12:46 +000041/// 'inline'[opt] 'namespace' attributes[opt] '{' namespace-body '}'
Chris Lattnera5235172007-08-25 06:57:03 +000042///
43/// named-namespace-definition:
44/// original-namespace-definition
45/// extension-namespace-definition
46///
47/// original-namespace-definition:
Sebastian Redl67667942010-08-27 23:12:46 +000048/// 'inline'[opt] 'namespace' identifier attributes[opt]
49/// '{' namespace-body '}'
Chris Lattnera5235172007-08-25 06:57:03 +000050///
51/// extension-namespace-definition:
Sebastian Redl67667942010-08-27 23:12:46 +000052/// 'inline'[opt] 'namespace' original-namespace-name
53/// '{' namespace-body '}'
Mike Stump11289f42009-09-09 15:08:12 +000054///
Chris Lattnera5235172007-08-25 06:57:03 +000055/// namespace-alias-definition: [C++ 7.3.2: namespace.alias]
56/// 'namespace' identifier '=' qualified-namespace-specifier ';'
57///
Faisal Vali421b2d12017-12-29 05:41:00 +000058Parser::DeclGroupPtrTy Parser::ParseNamespace(DeclaratorContext Context,
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +000059 SourceLocation &DeclEnd,
60 SourceLocation InlineLoc) {
Chris Lattner76c72282007-10-09 17:33:22 +000061 assert(Tok.is(tok::kw_namespace) && "Not a namespace!");
Chris Lattnera5235172007-08-25 06:57:03 +000062 SourceLocation NamespaceLoc = ConsumeToken(); // eat the 'namespace'.
Fariborz Jahanian4bf82622011-08-22 17:59:19 +000063 ObjCDeclContextSwitch ObjCDC(*this);
Fangrui Song6907ce22018-07-30 19:24:48 +000064
Douglas Gregor7e90c6d2009-09-18 19:03:04 +000065 if (Tok.is(tok::code_completion)) {
Douglas Gregor0be31a22010-07-02 17:43:08 +000066 Actions.CodeCompleteNamespaceDecl(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +000067 cutOffParsing();
David Blaikie0403cb12016-01-15 23:43:25 +000068 return nullptr;
Douglas Gregor7e90c6d2009-09-18 19:03:04 +000069 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000070
Chris Lattnera5235172007-08-25 06:57:03 +000071 SourceLocation IdentLoc;
Craig Topper161e4db2014-05-21 06:02:52 +000072 IdentifierInfo *Ident = nullptr;
Richard Trieu61384cb2011-05-26 20:11:09 +000073 std::vector<SourceLocation> ExtraIdentLoc;
74 std::vector<IdentifierInfo*> ExtraIdent;
75 std::vector<SourceLocation> ExtraNamespaceLoc;
Douglas Gregor6b6bba42009-06-17 19:49:00 +000076
Aaron Ballman730476b2014-11-08 15:33:35 +000077 ParsedAttributesWithRange attrs(AttrFactory);
78 SourceLocation attrLoc;
79 if (getLangOpts().CPlusPlus11 && isCXX11AttributeSpecifier()) {
Aaron Ballmanc351fba2017-12-04 20:27:34 +000080 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
Richard Smith40e202f2017-10-14 00:56:24 +000081 ? diag::warn_cxx14_compat_ns_enum_attribute
82 : diag::ext_ns_enum_attribute)
83 << 0 /*namespace*/;
Aaron Ballman730476b2014-11-08 15:33:35 +000084 attrLoc = Tok.getLocation();
85 ParseCXX11Attributes(attrs);
86 }
Mike Stump11289f42009-09-09 15:08:12 +000087
Chris Lattner76c72282007-10-09 17:33:22 +000088 if (Tok.is(tok::identifier)) {
Chris Lattnera5235172007-08-25 06:57:03 +000089 Ident = Tok.getIdentifierInfo();
90 IdentLoc = ConsumeToken(); // eat the identifier.
Richard Trieu61384cb2011-05-26 20:11:09 +000091 while (Tok.is(tok::coloncolon) && NextToken().is(tok::identifier)) {
92 ExtraNamespaceLoc.push_back(ConsumeToken());
93 ExtraIdent.push_back(Tok.getIdentifierInfo());
94 ExtraIdentLoc.push_back(ConsumeToken());
95 }
Chris Lattnera5235172007-08-25 06:57:03 +000096 }
Mike Stump11289f42009-09-09 15:08:12 +000097
Aaron Ballmanc0ae7df2014-11-08 17:07:15 +000098 // A nested namespace definition cannot have attributes.
99 if (!ExtraNamespaceLoc.empty() && attrLoc.isValid())
100 Diag(attrLoc, diag::err_unexpected_nested_namespace_attribute);
101
Chris Lattnera5235172007-08-25 06:57:03 +0000102 // Read label attributes, if present.
Douglas Gregor6b6bba42009-06-17 19:49:00 +0000103 if (Tok.is(tok::kw___attribute)) {
Aaron Ballman730476b2014-11-08 15:33:35 +0000104 attrLoc = Tok.getLocation();
John McCall53fa7142010-12-24 02:08:15 +0000105 ParseGNUAttributes(attrs);
Douglas Gregor6b6bba42009-06-17 19:49:00 +0000106 }
Mike Stump11289f42009-09-09 15:08:12 +0000107
Douglas Gregor6b6bba42009-06-17 19:49:00 +0000108 if (Tok.is(tok::equal)) {
Craig Topper161e4db2014-05-21 06:02:52 +0000109 if (!Ident) {
Alp Tokerec543272013-12-24 09:48:30 +0000110 Diag(Tok, diag::err_expected) << tok::identifier;
Nico Weber729f1e22012-10-27 23:44:27 +0000111 // Skip to end of the definition and eat the ';'.
112 SkipUntil(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +0000113 return nullptr;
Nico Weber729f1e22012-10-27 23:44:27 +0000114 }
Aaron Ballman730476b2014-11-08 15:33:35 +0000115 if (attrLoc.isValid())
116 Diag(attrLoc, diag::err_unexpected_namespace_attributes_alias);
Sebastian Redl67667942010-08-27 23:12:46 +0000117 if (InlineLoc.isValid())
118 Diag(InlineLoc, diag::err_inline_namespace_alias)
119 << FixItHint::CreateRemoval(InlineLoc);
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +0000120 Decl *NSAlias = ParseNamespaceAlias(NamespaceLoc, IdentLoc, Ident, DeclEnd);
121 return Actions.ConvertDeclToDeclGroup(NSAlias);
122}
Mike Stump11289f42009-09-09 15:08:12 +0000123
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000124 BalancedDelimiterTracker T(*this, tok::l_brace);
125 if (T.consumeOpen()) {
Alp Tokerec543272013-12-24 09:48:30 +0000126 if (Ident)
127 Diag(Tok, diag::err_expected) << tok::l_brace;
128 else
129 Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace;
David Blaikie0403cb12016-01-15 23:43:25 +0000130 return nullptr;
Chris Lattnera5235172007-08-25 06:57:03 +0000131 }
Mike Stump11289f42009-09-09 15:08:12 +0000132
Fangrui Song6907ce22018-07-30 19:24:48 +0000133 if (getCurScope()->isClassScope() || getCurScope()->isTemplateParamScope() ||
134 getCurScope()->isInObjcMethodScope() || getCurScope()->getBlockParent() ||
Douglas Gregor0be31a22010-07-02 17:43:08 +0000135 getCurScope()->getFnParent()) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000136 Diag(T.getOpenLocation(), diag::err_namespace_nonnamespace_scope);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000137 SkipUntil(tok::r_brace);
David Blaikie0403cb12016-01-15 23:43:25 +0000138 return nullptr;
Douglas Gregor05cfc292010-05-14 05:08:22 +0000139 }
140
Richard Smith13307f52014-11-08 05:37:34 +0000141 if (ExtraIdent.empty()) {
142 // Normal namespace definition, not a nested-namespace-definition.
143 } else if (InlineLoc.isValid()) {
144 Diag(InlineLoc, diag::err_inline_nested_namespace_definition);
Aaron Ballmanc351fba2017-12-04 20:27:34 +0000145 } else if (getLangOpts().CPlusPlus17) {
Richard Smith13307f52014-11-08 05:37:34 +0000146 Diag(ExtraNamespaceLoc[0],
147 diag::warn_cxx14_compat_nested_namespace_definition);
148 } else {
Richard Trieu61384cb2011-05-26 20:11:09 +0000149 TentativeParsingAction TPA(*this);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000150 SkipUntil(tok::r_brace, StopBeforeMatch);
Richard Trieu61384cb2011-05-26 20:11:09 +0000151 Token rBraceToken = Tok;
152 TPA.Revert();
153
154 if (!rBraceToken.is(tok::r_brace)) {
Richard Smith13307f52014-11-08 05:37:34 +0000155 Diag(ExtraNamespaceLoc[0], diag::ext_nested_namespace_definition)
Richard Trieu61384cb2011-05-26 20:11:09 +0000156 << SourceRange(ExtraNamespaceLoc.front(), ExtraIdentLoc.back());
157 } else {
Benjamin Kramerf546f412011-05-26 21:32:30 +0000158 std::string NamespaceFix;
Richard Trieu61384cb2011-05-26 20:11:09 +0000159 for (std::vector<IdentifierInfo*>::iterator I = ExtraIdent.begin(),
160 E = ExtraIdent.end(); I != E; ++I) {
161 NamespaceFix += " { namespace ";
162 NamespaceFix += (*I)->getName();
163 }
Benjamin Kramerf546f412011-05-26 21:32:30 +0000164
Richard Trieu61384cb2011-05-26 20:11:09 +0000165 std::string RBraces;
Benjamin Kramerf546f412011-05-26 21:32:30 +0000166 for (unsigned i = 0, e = ExtraIdent.size(); i != e; ++i)
Richard Trieu61384cb2011-05-26 20:11:09 +0000167 RBraces += "} ";
Benjamin Kramerf546f412011-05-26 21:32:30 +0000168
Richard Smith13307f52014-11-08 05:37:34 +0000169 Diag(ExtraNamespaceLoc[0], diag::ext_nested_namespace_definition)
Richard Trieu61384cb2011-05-26 20:11:09 +0000170 << FixItHint::CreateReplacement(SourceRange(ExtraNamespaceLoc.front(),
171 ExtraIdentLoc.back()),
172 NamespaceFix)
173 << FixItHint::CreateInsertion(rBraceToken.getLocation(), RBraces);
174 }
175 }
176
Sebastian Redl5a5f2c72010-08-31 00:36:45 +0000177 // If we're still good, complain about inline namespaces in non-C++0x now.
Richard Smith5d164bc2011-10-15 05:09:34 +0000178 if (InlineLoc.isValid())
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000179 Diag(InlineLoc, getLangOpts().CPlusPlus11 ?
Richard Smith5d164bc2011-10-15 05:09:34 +0000180 diag::warn_cxx98_compat_inline_namespace : diag::ext_inline_namespace);
Sebastian Redl5a5f2c72010-08-31 00:36:45 +0000181
Chris Lattner4de55aa2009-03-29 14:02:43 +0000182 // Enter a scope for the namespace.
183 ParseScope NamespaceScope(this, Scope::DeclScope);
184
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +0000185 UsingDirectiveDecl *ImplicitUsingDirectiveDecl = nullptr;
Erich Keanec480f302018-07-12 21:09:05 +0000186 Decl *NamespcDecl = Actions.ActOnStartNamespaceDef(
187 getCurScope(), InlineLoc, NamespaceLoc, IdentLoc, Ident,
188 T.getOpenLocation(), attrs, ImplicitUsingDirectiveDecl);
Chris Lattner4de55aa2009-03-29 14:02:43 +0000189
Jordan Rose1e879d82018-03-23 00:07:18 +0000190 PrettyDeclStackTraceEntry CrashInfo(Actions.Context, NamespcDecl,
191 NamespaceLoc, "parsing namespace");
Mike Stump11289f42009-09-09 15:08:12 +0000192
Fangrui Song6907ce22018-07-30 19:24:48 +0000193 // Parse the contents of the namespace. This includes parsing recovery on
Richard Trieu61384cb2011-05-26 20:11:09 +0000194 // any improperly nested namespaces.
195 ParseInnerNamespace(ExtraIdentLoc, ExtraIdent, ExtraNamespaceLoc, 0,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000196 InlineLoc, attrs, T);
Mike Stump11289f42009-09-09 15:08:12 +0000197
Chris Lattner4de55aa2009-03-29 14:02:43 +0000198 // Leave the namespace scope.
199 NamespaceScope.Exit();
200
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000201 DeclEnd = T.getCloseLocation();
202 Actions.ActOnFinishNamespaceDef(NamespcDecl, DeclEnd);
Fangrui Song6907ce22018-07-30 19:24:48 +0000203
204 return Actions.ConvertDeclToDeclGroup(NamespcDecl,
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +0000205 ImplicitUsingDirectiveDecl);
Chris Lattnera5235172007-08-25 06:57:03 +0000206}
Chris Lattner38376f12008-01-12 07:05:38 +0000207
Richard Trieu61384cb2011-05-26 20:11:09 +0000208/// ParseInnerNamespace - Parse the contents of a namespace.
Richard Smith13307f52014-11-08 05:37:34 +0000209void Parser::ParseInnerNamespace(std::vector<SourceLocation> &IdentLoc,
210 std::vector<IdentifierInfo *> &Ident,
211 std::vector<SourceLocation> &NamespaceLoc,
212 unsigned int index, SourceLocation &InlineLoc,
213 ParsedAttributes &attrs,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000214 BalancedDelimiterTracker &Tracker) {
Richard Trieu61384cb2011-05-26 20:11:09 +0000215 if (index == Ident.size()) {
Richard Smith752ada82015-11-17 23:32:01 +0000216 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
217 Tok.isNot(tok::eof)) {
Richard Trieu61384cb2011-05-26 20:11:09 +0000218 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +0000219 MaybeParseCXX11Attributes(attrs);
Richard Trieu61384cb2011-05-26 20:11:09 +0000220 ParseExternalDeclaration(attrs);
221 }
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000222
223 // The caller is what called check -- we are simply calling
224 // the close for it.
225 Tracker.consumeClose();
Richard Trieu61384cb2011-05-26 20:11:09 +0000226
227 return;
228 }
229
Richard Smith13307f52014-11-08 05:37:34 +0000230 // Handle a nested namespace definition.
231 // FIXME: Preserve the source information through to the AST rather than
232 // desugaring it here.
Richard Trieu61384cb2011-05-26 20:11:09 +0000233 ParseScope NamespaceScope(this, Scope::DeclScope);
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +0000234 UsingDirectiveDecl *ImplicitUsingDirectiveDecl = nullptr;
Erich Keanec480f302018-07-12 21:09:05 +0000235 Decl *NamespcDecl = Actions.ActOnStartNamespaceDef(
236 getCurScope(), SourceLocation(), NamespaceLoc[index], IdentLoc[index],
237 Ident[index], Tracker.getOpenLocation(), attrs,
238 ImplicitUsingDirectiveDecl);
Fangrui Song6907ce22018-07-30 19:24:48 +0000239 assert(!ImplicitUsingDirectiveDecl &&
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +0000240 "nested namespace definition cannot define anonymous namespace");
Richard Trieu61384cb2011-05-26 20:11:09 +0000241
242 ParseInnerNamespace(IdentLoc, Ident, NamespaceLoc, ++index, InlineLoc,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000243 attrs, Tracker);
Richard Trieu61384cb2011-05-26 20:11:09 +0000244
245 NamespaceScope.Exit();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000246 Actions.ActOnFinishNamespaceDef(NamespcDecl, Tracker.getCloseLocation());
Richard Trieu61384cb2011-05-26 20:11:09 +0000247}
248
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000249/// ParseNamespaceAlias - Parse the part after the '=' in a namespace
250/// alias definition.
251///
John McCall48871652010-08-21 09:40:31 +0000252Decl *Parser::ParseNamespaceAlias(SourceLocation NamespaceLoc,
John McCall084e83d2011-03-24 11:26:52 +0000253 SourceLocation AliasLoc,
254 IdentifierInfo *Alias,
255 SourceLocation &DeclEnd) {
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000256 assert(Tok.is(tok::equal) && "Not equal token");
Mike Stump11289f42009-09-09 15:08:12 +0000257
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000258 ConsumeToken(); // eat the '='.
Mike Stump11289f42009-09-09 15:08:12 +0000259
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000260 if (Tok.is(tok::code_completion)) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000261 Actions.CodeCompleteNamespaceAliasDecl(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000262 cutOffParsing();
Craig Topper161e4db2014-05-21 06:02:52 +0000263 return nullptr;
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000264 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000265
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000266 CXXScopeSpec SS;
267 // Parse (optional) nested-name-specifier.
Matthias Gehredc01bb42017-03-17 21:41:20 +0000268 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false,
269 /*MayBePseudoDestructor=*/nullptr,
270 /*IsTypename=*/false,
271 /*LastII=*/nullptr,
272 /*OnlyNamespace=*/true);
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000273
Matthias Gehredc01bb42017-03-17 21:41:20 +0000274 if (Tok.isNot(tok::identifier)) {
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000275 Diag(Tok, diag::err_expected_namespace_name);
276 // Skip to end of the definition and eat the ';'.
277 SkipUntil(tok::semi);
Craig Topper161e4db2014-05-21 06:02:52 +0000278 return nullptr;
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000279 }
280
Matthias Gehredc01bb42017-03-17 21:41:20 +0000281 if (SS.isInvalid()) {
282 // Diagnostics have been emitted in ParseOptionalCXXScopeSpecifier.
283 // Skip to end of the definition and eat the ';'.
284 SkipUntil(tok::semi);
285 return nullptr;
286 }
287
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000288 // Parse identifier.
Anders Carlsson47952ae2009-03-28 22:53:22 +0000289 IdentifierInfo *Ident = Tok.getIdentifierInfo();
290 SourceLocation IdentLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000291
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000292 // Eat the ';'.
Chris Lattner49836b42009-04-02 04:16:50 +0000293 DeclEnd = Tok.getLocation();
Alp Toker383d2c42014-01-01 03:08:43 +0000294 if (ExpectAndConsume(tok::semi, diag::err_expected_semi_after_namespace_name))
295 SkipUntil(tok::semi);
Mike Stump11289f42009-09-09 15:08:12 +0000296
Craig Topperff354282015-11-14 18:16:00 +0000297 return Actions.ActOnNamespaceAliasDef(getCurScope(), NamespaceLoc, AliasLoc,
298 Alias, SS, IdentLoc, Ident);
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000299}
300
Chris Lattner38376f12008-01-12 07:05:38 +0000301/// ParseLinkage - We know that the current token is a string_literal
302/// and just before that, that extern was seen.
303///
304/// linkage-specification: [C++ 7.5p2: dcl.link]
305/// 'extern' string-literal '{' declaration-seq[opt] '}'
306/// 'extern' string-literal declaration
307///
Faisal Vali421b2d12017-12-29 05:41:00 +0000308Decl *Parser::ParseLinkage(ParsingDeclSpec &DS, DeclaratorContext Context) {
Richard Smith4ee696d2014-02-17 23:25:27 +0000309 assert(isTokenStringLiteral() && "Not a string literal!");
310 ExprResult Lang = ParseStringLiteralExpression(false);
Chris Lattner38376f12008-01-12 07:05:38 +0000311
Douglas Gregor07665a62009-01-05 19:45:36 +0000312 ParseScope LinkageScope(this, Scope::DeclScope);
Richard Smith4ee696d2014-02-17 23:25:27 +0000313 Decl *LinkageSpec =
314 Lang.isInvalid()
Craig Topper161e4db2014-05-21 06:02:52 +0000315 ? nullptr
Richard Smith4ee696d2014-02-17 23:25:27 +0000316 : Actions.ActOnStartLinkageSpecification(
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000317 getCurScope(), DS.getSourceRange().getBegin(), Lang.get(),
Richard Smith4ee696d2014-02-17 23:25:27 +0000318 Tok.is(tok::l_brace) ? Tok.getLocation() : SourceLocation());
Douglas Gregor07665a62009-01-05 19:45:36 +0000319
John McCall084e83d2011-03-24 11:26:52 +0000320 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +0000321 MaybeParseCXX11Attributes(attrs);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000322
Douglas Gregor07665a62009-01-05 19:45:36 +0000323 if (Tok.isNot(tok::l_brace)) {
Abramo Bagnara4d423992011-05-01 16:25:54 +0000324 // Reset the source range in DS, as the leading "extern"
325 // does not really belong to the inner declaration ...
326 DS.SetRangeStart(SourceLocation());
327 DS.SetRangeEnd(SourceLocation());
328 // ... but anyway remember that such an "extern" was seen.
Abramo Bagnaraed5b6892010-07-30 16:47:02 +0000329 DS.setExternInLinkageSpec(true);
John McCall53fa7142010-12-24 02:08:15 +0000330 ParseExternalDeclaration(attrs, &DS);
Richard Smith4ee696d2014-02-17 23:25:27 +0000331 return LinkageSpec ? Actions.ActOnFinishLinkageSpecification(
332 getCurScope(), LinkageSpec, SourceLocation())
Craig Topper161e4db2014-05-21 06:02:52 +0000333 : nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000334 }
Douglas Gregor29ff7d02008-12-16 22:23:02 +0000335
Douglas Gregorb65a9132010-02-07 08:38:28 +0000336 DS.abort();
337
John McCall53fa7142010-12-24 02:08:15 +0000338 ProhibitAttributes(attrs);
Alexis Hunt96d5c762009-11-21 08:43:09 +0000339
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000340 BalancedDelimiterTracker T(*this, tok::l_brace);
341 T.consumeOpen();
Richard Smith77944862014-03-02 05:58:18 +0000342
343 unsigned NestedModules = 0;
344 while (true) {
345 switch (Tok.getKind()) {
346 case tok::annot_module_begin:
347 ++NestedModules;
348 ParseTopLevelDecl();
349 continue;
350
351 case tok::annot_module_end:
352 if (!NestedModules)
353 break;
354 --NestedModules;
355 ParseTopLevelDecl();
356 continue;
357
358 case tok::annot_module_include:
359 ParseTopLevelDecl();
360 continue;
361
362 case tok::eof:
363 break;
364
365 case tok::r_brace:
366 if (!NestedModules)
367 break;
368 // Fall through.
369 default:
370 ParsedAttributesWithRange attrs(AttrFactory);
371 MaybeParseCXX11Attributes(attrs);
Richard Smith77944862014-03-02 05:58:18 +0000372 ParseExternalDeclaration(attrs);
373 continue;
374 }
375
376 break;
Chris Lattner38376f12008-01-12 07:05:38 +0000377 }
378
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000379 T.consumeClose();
Richard Smith4ee696d2014-02-17 23:25:27 +0000380 return LinkageSpec ? Actions.ActOnFinishLinkageSpecification(
381 getCurScope(), LinkageSpec, T.getCloseLocation())
Craig Topper161e4db2014-05-21 06:02:52 +0000382 : nullptr;
Chris Lattner38376f12008-01-12 07:05:38 +0000383}
Douglas Gregor556877c2008-04-13 21:30:24 +0000384
Richard Smith8df390f2016-09-08 23:14:54 +0000385/// Parse a C++ Modules TS export-declaration.
386///
387/// export-declaration:
388/// 'export' declaration
389/// 'export' '{' declaration-seq[opt] '}'
390///
391Decl *Parser::ParseExportDeclaration() {
392 assert(Tok.is(tok::kw_export));
393 SourceLocation ExportLoc = ConsumeToken();
394
395 ParseScope ExportScope(this, Scope::DeclScope);
396 Decl *ExportDecl = Actions.ActOnStartExportDecl(
397 getCurScope(), ExportLoc,
398 Tok.is(tok::l_brace) ? Tok.getLocation() : SourceLocation());
399
400 if (Tok.isNot(tok::l_brace)) {
401 // FIXME: Factor out a ParseExternalDeclarationWithAttrs.
402 ParsedAttributesWithRange Attrs(AttrFactory);
403 MaybeParseCXX11Attributes(Attrs);
404 MaybeParseMicrosoftAttributes(Attrs);
405 ParseExternalDeclaration(Attrs);
406 return Actions.ActOnFinishExportDecl(getCurScope(), ExportDecl,
407 SourceLocation());
408 }
409
410 BalancedDelimiterTracker T(*this, tok::l_brace);
411 T.consumeOpen();
412
413 // The Modules TS draft says "An export-declaration shall declare at least one
414 // entity", but the intent is that it shall contain at least one declaration.
415 if (Tok.is(tok::r_brace))
416 Diag(ExportLoc, diag::err_export_empty)
417 << SourceRange(ExportLoc, Tok.getLocation());
418
419 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
420 Tok.isNot(tok::eof)) {
421 ParsedAttributesWithRange Attrs(AttrFactory);
422 MaybeParseCXX11Attributes(Attrs);
423 MaybeParseMicrosoftAttributes(Attrs);
424 ParseExternalDeclaration(Attrs);
425 }
426
427 T.consumeClose();
428 return Actions.ActOnFinishExportDecl(getCurScope(), ExportDecl,
429 T.getCloseLocation());
430}
431
Douglas Gregord7c4d982008-12-30 03:27:21 +0000432/// ParseUsingDirectiveOrDeclaration - Parse C++ using using-declaration or
433/// using-directive. Assumes that current token is 'using'.
Richard Smith6f1daa42016-12-16 00:58:48 +0000434Parser::DeclGroupPtrTy
Faisal Vali421b2d12017-12-29 05:41:00 +0000435Parser::ParseUsingDirectiveOrDeclaration(DeclaratorContext Context,
John McCall9b72f892010-11-10 02:40:36 +0000436 const ParsedTemplateInfo &TemplateInfo,
Richard Smith6f1daa42016-12-16 00:58:48 +0000437 SourceLocation &DeclEnd,
438 ParsedAttributesWithRange &attrs) {
Douglas Gregord7c4d982008-12-30 03:27:21 +0000439 assert(Tok.is(tok::kw_using) && "Not using token");
Fariborz Jahanian4bf82622011-08-22 17:59:19 +0000440 ObjCDeclContextSwitch ObjCDC(*this);
Fangrui Song6907ce22018-07-30 19:24:48 +0000441
Douglas Gregord7c4d982008-12-30 03:27:21 +0000442 // Eat 'using'.
443 SourceLocation UsingLoc = ConsumeToken();
444
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000445 if (Tok.is(tok::code_completion)) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000446 Actions.CodeCompleteUsing(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000447 cutOffParsing();
Craig Topper161e4db2014-05-21 06:02:52 +0000448 return nullptr;
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000449 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000450
John McCall9b72f892010-11-10 02:40:36 +0000451 // 'using namespace' means this is a using-directive.
452 if (Tok.is(tok::kw_namespace)) {
453 // Template parameters are always an error here.
454 if (TemplateInfo.Kind) {
455 SourceRange R = TemplateInfo.getSourceRange();
Craig Topper54a6a682015-11-14 18:16:08 +0000456 Diag(UsingLoc, diag::err_templated_using_directive_declaration)
457 << 0 /* directive */ << R << FixItHint::CreateRemoval(R);
John McCall9b72f892010-11-10 02:40:36 +0000458 }
Alexis Hunt96d5c762009-11-21 08:43:09 +0000459
Richard Smith6f1daa42016-12-16 00:58:48 +0000460 Decl *UsingDir = ParseUsingDirective(Context, UsingLoc, DeclEnd, attrs);
461 return Actions.ConvertDeclToDeclGroup(UsingDir);
John McCall9b72f892010-11-10 02:40:36 +0000462 }
463
Richard Smithdda56e42011-04-15 14:24:37 +0000464 // Otherwise, it must be a using-declaration or an alias-declaration.
John McCall9b72f892010-11-10 02:40:36 +0000465
466 // Using declarations can't have attributes.
John McCall53fa7142010-12-24 02:08:15 +0000467 ProhibitAttributes(attrs);
Chris Lattner9b01ca12009-01-06 06:55:51 +0000468
Fariborz Jahanian4bf82622011-08-22 17:59:19 +0000469 return ParseUsingDeclaration(Context, TemplateInfo, UsingLoc, DeclEnd,
Richard Smith6f1daa42016-12-16 00:58:48 +0000470 AS_none);
Douglas Gregord7c4d982008-12-30 03:27:21 +0000471}
472
473/// ParseUsingDirective - Parse C++ using-directive, assumes
474/// that current token is 'namespace' and 'using' was already parsed.
475///
476/// using-directive: [C++ 7.3.p4: namespace.udir]
477/// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
478/// namespace-name ;
479/// [GNU] using-directive:
480/// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
481/// namespace-name attributes[opt] ;
482///
Faisal Vali421b2d12017-12-29 05:41:00 +0000483Decl *Parser::ParseUsingDirective(DeclaratorContext Context,
John McCall9b72f892010-11-10 02:40:36 +0000484 SourceLocation UsingLoc,
485 SourceLocation &DeclEnd,
John McCall53fa7142010-12-24 02:08:15 +0000486 ParsedAttributes &attrs) {
Douglas Gregord7c4d982008-12-30 03:27:21 +0000487 assert(Tok.is(tok::kw_namespace) && "Not 'namespace' token");
488
489 // Eat 'namespace'.
490 SourceLocation NamespcLoc = ConsumeToken();
491
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000492 if (Tok.is(tok::code_completion)) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000493 Actions.CodeCompleteUsingDirective(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000494 cutOffParsing();
Craig Topper161e4db2014-05-21 06:02:52 +0000495 return nullptr;
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000496 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000497
Douglas Gregord7c4d982008-12-30 03:27:21 +0000498 CXXScopeSpec SS;
499 // Parse (optional) nested-name-specifier.
Matthias Gehredc01bb42017-03-17 21:41:20 +0000500 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false,
501 /*MayBePseudoDestructor=*/nullptr,
502 /*IsTypename=*/false,
503 /*LastII=*/nullptr,
504 /*OnlyNamespace=*/true);
Douglas Gregord7c4d982008-12-30 03:27:21 +0000505
Craig Topper161e4db2014-05-21 06:02:52 +0000506 IdentifierInfo *NamespcName = nullptr;
Douglas Gregord7c4d982008-12-30 03:27:21 +0000507 SourceLocation IdentLoc = SourceLocation();
508
509 // Parse namespace-name.
Matthias Gehredc01bb42017-03-17 21:41:20 +0000510 if (Tok.isNot(tok::identifier)) {
Douglas Gregord7c4d982008-12-30 03:27:21 +0000511 Diag(Tok, diag::err_expected_namespace_name);
512 // If there was invalid namespace name, skip to end of decl, and eat ';'.
513 SkipUntil(tok::semi);
514 // FIXME: Are there cases, when we would like to call ActOnUsingDirective?
Craig Topper161e4db2014-05-21 06:02:52 +0000515 return nullptr;
Douglas Gregord7c4d982008-12-30 03:27:21 +0000516 }
Mike Stump11289f42009-09-09 15:08:12 +0000517
Matthias Gehredc01bb42017-03-17 21:41:20 +0000518 if (SS.isInvalid()) {
519 // Diagnostics have been emitted in ParseOptionalCXXScopeSpecifier.
520 // Skip to end of the definition and eat the ';'.
521 SkipUntil(tok::semi);
522 return nullptr;
523 }
524
Chris Lattnerce1da2c2009-01-06 07:27:21 +0000525 // Parse identifier.
526 NamespcName = Tok.getIdentifierInfo();
527 IdentLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000528
Chris Lattnerce1da2c2009-01-06 07:27:21 +0000529 // Parse (optional) attributes (most likely GNU strong-using extension).
Alexis Hunt96d5c762009-11-21 08:43:09 +0000530 bool GNUAttr = false;
531 if (Tok.is(tok::kw___attribute)) {
532 GNUAttr = true;
John McCall53fa7142010-12-24 02:08:15 +0000533 ParseGNUAttributes(attrs);
Alexis Hunt96d5c762009-11-21 08:43:09 +0000534 }
Mike Stump11289f42009-09-09 15:08:12 +0000535
Chris Lattnerce1da2c2009-01-06 07:27:21 +0000536 // Eat ';'.
Chris Lattner49836b42009-04-02 04:16:50 +0000537 DeclEnd = Tok.getLocation();
Alp Toker383d2c42014-01-01 03:08:43 +0000538 if (ExpectAndConsume(tok::semi,
539 GNUAttr ? diag::err_expected_semi_after_attribute_list
540 : diag::err_expected_semi_after_namespace_name))
541 SkipUntil(tok::semi);
Douglas Gregord7c4d982008-12-30 03:27:21 +0000542
Douglas Gregor0be31a22010-07-02 17:43:08 +0000543 return Actions.ActOnUsingDirective(getCurScope(), UsingLoc, NamespcLoc, SS,
Erich Keanec480f302018-07-12 21:09:05 +0000544 IdentLoc, NamespcName, attrs);
Douglas Gregord7c4d982008-12-30 03:27:21 +0000545}
546
Richard Smith6f1daa42016-12-16 00:58:48 +0000547/// Parse a using-declarator (or the identifier in a C++11 alias-declaration).
Douglas Gregord7c4d982008-12-30 03:27:21 +0000548///
Richard Smith6f1daa42016-12-16 00:58:48 +0000549/// using-declarator:
550/// 'typename'[opt] nested-name-specifier unqualified-id
Douglas Gregord7c4d982008-12-30 03:27:21 +0000551///
Faisal Vali421b2d12017-12-29 05:41:00 +0000552bool Parser::ParseUsingDeclarator(DeclaratorContext Context,
553 UsingDeclarator &D) {
Richard Smith6f1daa42016-12-16 00:58:48 +0000554 D.clear();
Douglas Gregorfec52632009-06-20 00:51:54 +0000555
556 // Ignore optional 'typename'.
Douglas Gregor220f4272009-11-04 16:30:06 +0000557 // FIXME: This is wrong; we should parse this as a typename-specifier.
Richard Smith6f1daa42016-12-16 00:58:48 +0000558 TryConsumeToken(tok::kw_typename, D.TypenameLoc);
Douglas Gregorfec52632009-06-20 00:51:54 +0000559
Nikola Smiljanic67860242014-09-26 00:28:20 +0000560 if (Tok.is(tok::kw___super)) {
561 Diag(Tok.getLocation(), diag::err_super_in_using_declaration);
Richard Smith6f1daa42016-12-16 00:58:48 +0000562 return true;
Nikola Smiljanic67860242014-09-26 00:28:20 +0000563 }
564
Douglas Gregorfec52632009-06-20 00:51:54 +0000565 // Parse nested-name-specifier.
Craig Topper161e4db2014-05-21 06:02:52 +0000566 IdentifierInfo *LastII = nullptr;
Richard Smith6f1daa42016-12-16 00:58:48 +0000567 ParseOptionalCXXScopeSpecifier(D.SS, nullptr, /*EnteringContext=*/false,
Craig Topper161e4db2014-05-21 06:02:52 +0000568 /*MayBePseudoDtor=*/nullptr,
569 /*IsTypename=*/false,
Richard Smith7447af42013-03-26 01:15:19 +0000570 /*LastII=*/&LastII);
Richard Smith6f1daa42016-12-16 00:58:48 +0000571 if (D.SS.isInvalid())
572 return true;
Richard Smith7447af42013-03-26 01:15:19 +0000573
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000574 // Parse the unqualified-id. We allow parsing of both constructor and
Douglas Gregor220f4272009-11-04 16:30:06 +0000575 // destructor names and allow the action module to diagnose any semantic
576 // errors.
Richard Smith7447af42013-03-26 01:15:19 +0000577 //
578 // C++11 [class.qual]p2:
579 // [...] in a using-declaration that is a member-declaration, if the name
580 // specified after the nested-name-specifier is the same as the identifier
581 // or the simple-template-id's template-name in the last component of the
582 // nested-name-specifier, the name is [...] considered to name the
583 // constructor.
Faisal Vali421b2d12017-12-29 05:41:00 +0000584 if (getLangOpts().CPlusPlus11 &&
585 Context == DeclaratorContext::MemberContext &&
Richard Smith151c4562016-12-20 21:35:28 +0000586 Tok.is(tok::identifier) &&
587 (NextToken().is(tok::semi) || NextToken().is(tok::comma) ||
588 NextToken().is(tok::ellipsis)) &&
Richard Smith6f1daa42016-12-16 00:58:48 +0000589 D.SS.isNotEmpty() && LastII == Tok.getIdentifierInfo() &&
590 !D.SS.getScopeRep()->getAsNamespace() &&
591 !D.SS.getScopeRep()->getAsNamespaceAlias()) {
Richard Smith7447af42013-03-26 01:15:19 +0000592 SourceLocation IdLoc = ConsumeToken();
Richard Smith6f1daa42016-12-16 00:58:48 +0000593 ParsedType Type =
594 Actions.getInheritingConstructorName(D.SS, IdLoc, *LastII);
595 D.Name.setConstructorName(Type, IdLoc, IdLoc);
596 } else {
597 if (ParseUnqualifiedId(
598 D.SS, /*EnteringContext=*/false,
599 /*AllowDestructorName=*/true,
600 /*AllowConstructorName=*/!(Tok.is(tok::identifier) &&
601 NextToken().is(tok::equal)),
Richard Smith35845152017-02-07 01:37:30 +0000602 /*AllowDeductionGuide=*/false,
Richard Smithc08b6932018-04-27 02:00:13 +0000603 nullptr, nullptr, D.Name))
Richard Smith6f1daa42016-12-16 00:58:48 +0000604 return true;
Douglas Gregorfec52632009-06-20 00:51:54 +0000605 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000606
Richard Smith151c4562016-12-20 21:35:28 +0000607 if (TryConsumeToken(tok::ellipsis, D.EllipsisLoc))
Aaron Ballmanc351fba2017-12-04 20:27:34 +0000608 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17 ?
Richard Smithb115e5d2017-08-13 23:37:29 +0000609 diag::warn_cxx17_compat_using_declaration_pack :
Richard Smith151c4562016-12-20 21:35:28 +0000610 diag::ext_using_declaration_pack);
Richard Smith6f1daa42016-12-16 00:58:48 +0000611
612 return false;
613}
614
615/// ParseUsingDeclaration - Parse C++ using-declaration or alias-declaration.
616/// Assumes that 'using' was already seen.
617///
618/// using-declaration: [C++ 7.3.p3: namespace.udecl]
619/// 'using' using-declarator-list[opt] ;
620///
621/// using-declarator-list: [C++1z]
622/// using-declarator '...'[opt]
623/// using-declarator-list ',' using-declarator '...'[opt]
624///
625/// using-declarator-list: [C++98-14]
626/// using-declarator
627///
628/// alias-declaration: C++11 [dcl.dcl]p1
629/// 'using' identifier attribute-specifier-seq[opt] = type-id ;
630///
631Parser::DeclGroupPtrTy
Faisal Vali421b2d12017-12-29 05:41:00 +0000632Parser::ParseUsingDeclaration(DeclaratorContext Context,
Richard Smith6f1daa42016-12-16 00:58:48 +0000633 const ParsedTemplateInfo &TemplateInfo,
634 SourceLocation UsingLoc, SourceLocation &DeclEnd,
635 AccessSpecifier AS) {
636 // Check for misplaced attributes before the identifier in an
637 // alias-declaration.
638 ParsedAttributesWithRange MisplacedAttrs(AttrFactory);
639 MaybeParseCXX11Attributes(MisplacedAttrs);
640
641 UsingDeclarator D;
642 bool InvalidDeclarator = ParseUsingDeclarator(Context, D);
643
Richard Smithc2c8bb82013-10-15 01:34:54 +0000644 ParsedAttributesWithRange Attrs(AttrFactory);
Richard Smith37a45dd2013-10-24 01:21:09 +0000645 MaybeParseGNUAttributes(Attrs);
Richard Smith54ecd982013-02-20 19:22:51 +0000646 MaybeParseCXX11Attributes(Attrs);
Richard Smithdda56e42011-04-15 14:24:37 +0000647
648 // Maybe this is an alias-declaration.
Richard Smith6f1daa42016-12-16 00:58:48 +0000649 if (Tok.is(tok::equal)) {
650 if (InvalidDeclarator) {
651 SkipUntil(tok::semi);
652 return nullptr;
653 }
654
Richard Smithc2c8bb82013-10-15 01:34:54 +0000655 // If we had any misplaced attributes from earlier, this is where they
656 // should have been written.
657 if (MisplacedAttrs.Range.isValid()) {
658 Diag(MisplacedAttrs.Range.getBegin(), diag::err_attributes_not_allowed)
659 << FixItHint::CreateInsertionFromRange(
660 Tok.getLocation(),
661 CharSourceRange::getTokenRange(MisplacedAttrs.Range))
662 << FixItHint::CreateRemoval(MisplacedAttrs.Range);
663 Attrs.takeAllFrom(MisplacedAttrs);
664 }
665
Richard Smith6f1daa42016-12-16 00:58:48 +0000666 Decl *DeclFromDeclSpec = nullptr;
667 Decl *AD = ParseAliasDeclarationAfterDeclarator(
668 TemplateInfo, UsingLoc, D, DeclEnd, AS, Attrs, &DeclFromDeclSpec);
669 return Actions.ConvertDeclToDeclGroup(AD, DeclFromDeclSpec);
Alexis Hunt6aa9bee2012-06-23 05:07:58 +0000670 }
Mike Stump11289f42009-09-09 15:08:12 +0000671
Richard Smith6f1daa42016-12-16 00:58:48 +0000672 // C++11 attributes are not allowed on a using-declaration, but GNU ones
673 // are.
674 ProhibitAttributes(MisplacedAttrs);
675 ProhibitAttributes(Attrs);
Douglas Gregorfec52632009-06-20 00:51:54 +0000676
John McCall9b72f892010-11-10 02:40:36 +0000677 // Diagnose an attempt to declare a templated using-declaration.
Richard Smith810ad3e2013-01-29 10:02:16 +0000678 // In C++11, alias-declarations can be templates:
Richard Smithdda56e42011-04-15 14:24:37 +0000679 // template <...> using id = type;
Richard Smith6f1daa42016-12-16 00:58:48 +0000680 if (TemplateInfo.Kind) {
John McCall9b72f892010-11-10 02:40:36 +0000681 SourceRange R = TemplateInfo.getSourceRange();
Craig Topper54a6a682015-11-14 18:16:08 +0000682 Diag(UsingLoc, diag::err_templated_using_directive_declaration)
683 << 1 /* declaration */ << R << FixItHint::CreateRemoval(R);
John McCall9b72f892010-11-10 02:40:36 +0000684
685 // Unfortunately, we have to bail out instead of recovering by
686 // ignoring the parameters, just in case the nested name specifier
687 // depends on the parameters.
Craig Topper161e4db2014-05-21 06:02:52 +0000688 return nullptr;
John McCall9b72f892010-11-10 02:40:36 +0000689 }
690
Richard Smith6f1daa42016-12-16 00:58:48 +0000691 SmallVector<Decl *, 8> DeclsInGroup;
692 while (true) {
693 // Parse (optional) attributes (most likely GNU strong-using extension).
694 MaybeParseGNUAttributes(Attrs);
695
696 if (InvalidDeclarator)
697 SkipUntil(tok::comma, tok::semi, StopBeforeMatch);
698 else {
699 // "typename" keyword is allowed for identifiers only,
700 // because it may be a type definition.
701 if (D.TypenameLoc.isValid() &&
Faisal Vali2ab8c152017-12-30 04:15:27 +0000702 D.Name.getKind() != UnqualifiedIdKind::IK_Identifier) {
Richard Smith6f1daa42016-12-16 00:58:48 +0000703 Diag(D.Name.getSourceRange().getBegin(),
704 diag::err_typename_identifiers_only)
705 << FixItHint::CreateRemoval(SourceRange(D.TypenameLoc));
706 // Proceed parsing, but discard the typename keyword.
707 D.TypenameLoc = SourceLocation();
708 }
709
Richard Smith151c4562016-12-20 21:35:28 +0000710 Decl *UD = Actions.ActOnUsingDeclaration(getCurScope(), AS, UsingLoc,
711 D.TypenameLoc, D.SS, D.Name,
Erich Keanec480f302018-07-12 21:09:05 +0000712 D.EllipsisLoc, Attrs);
Richard Smith6f1daa42016-12-16 00:58:48 +0000713 if (UD)
714 DeclsInGroup.push_back(UD);
715 }
716
717 if (!TryConsumeToken(tok::comma))
718 break;
719
720 // Parse another using-declarator.
721 Attrs.clear();
722 InvalidDeclarator = ParseUsingDeclarator(Context, D);
Douglas Gregor882a61a2011-09-26 14:30:28 +0000723 }
724
Richard Smith6f1daa42016-12-16 00:58:48 +0000725 if (DeclsInGroup.size() > 1)
Aaron Ballmanc351fba2017-12-04 20:27:34 +0000726 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17 ?
Richard Smithb115e5d2017-08-13 23:37:29 +0000727 diag::warn_cxx17_compat_multi_using_declaration :
Richard Smith6f1daa42016-12-16 00:58:48 +0000728 diag::ext_multi_using_declaration);
729
730 // Eat ';'.
731 DeclEnd = Tok.getLocation();
732 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
733 !Attrs.empty() ? "attributes list"
734 : "using declaration"))
735 SkipUntil(tok::semi);
736
Richard Smith3beb7c62017-01-12 02:27:38 +0000737 return Actions.BuildDeclaratorGroup(DeclsInGroup);
Richard Smith6f1daa42016-12-16 00:58:48 +0000738}
739
Richard Smith6f1daa42016-12-16 00:58:48 +0000740Decl *Parser::ParseAliasDeclarationAfterDeclarator(
741 const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc,
742 UsingDeclarator &D, SourceLocation &DeclEnd, AccessSpecifier AS,
743 ParsedAttributes &Attrs, Decl **OwnedType) {
744 if (ExpectAndConsume(tok::equal)) {
745 SkipUntil(tok::semi);
746 return nullptr;
747 }
748
749 Diag(Tok.getLocation(), getLangOpts().CPlusPlus11 ?
750 diag::warn_cxx98_compat_alias_declaration :
751 diag::ext_alias_declaration);
752
753 // Type alias templates cannot be specialized.
754 int SpecKind = -1;
755 if (TemplateInfo.Kind == ParsedTemplateInfo::Template &&
Faisal Vali2ab8c152017-12-30 04:15:27 +0000756 D.Name.getKind() == UnqualifiedIdKind::IK_TemplateId)
Richard Smith6f1daa42016-12-16 00:58:48 +0000757 SpecKind = 0;
758 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization)
759 SpecKind = 1;
760 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
761 SpecKind = 2;
762 if (SpecKind != -1) {
763 SourceRange Range;
764 if (SpecKind == 0)
765 Range = SourceRange(D.Name.TemplateId->LAngleLoc,
766 D.Name.TemplateId->RAngleLoc);
767 else
768 Range = TemplateInfo.getSourceRange();
769 Diag(Range.getBegin(), diag::err_alias_declaration_specialization)
770 << SpecKind << Range;
771 SkipUntil(tok::semi);
772 return nullptr;
773 }
774
775 // Name must be an identifier.
Faisal Vali2ab8c152017-12-30 04:15:27 +0000776 if (D.Name.getKind() != UnqualifiedIdKind::IK_Identifier) {
Richard Smith6f1daa42016-12-16 00:58:48 +0000777 Diag(D.Name.StartLocation, diag::err_alias_declaration_not_identifier);
778 // No removal fixit: can't recover from this.
779 SkipUntil(tok::semi);
780 return nullptr;
781 } else if (D.TypenameLoc.isValid())
782 Diag(D.TypenameLoc, diag::err_alias_declaration_not_identifier)
783 << FixItHint::CreateRemoval(SourceRange(
784 D.TypenameLoc,
785 D.SS.isNotEmpty() ? D.SS.getEndLoc() : D.TypenameLoc));
786 else if (D.SS.isNotEmpty())
787 Diag(D.SS.getBeginLoc(), diag::err_alias_declaration_not_identifier)
788 << FixItHint::CreateRemoval(D.SS.getRange());
Richard Smith151c4562016-12-20 21:35:28 +0000789 if (D.EllipsisLoc.isValid())
790 Diag(D.EllipsisLoc, diag::err_alias_declaration_pack_expansion)
791 << FixItHint::CreateRemoval(SourceRange(D.EllipsisLoc));
Richard Smith6f1daa42016-12-16 00:58:48 +0000792
793 Decl *DeclFromDeclSpec = nullptr;
Faisal Vali421b2d12017-12-29 05:41:00 +0000794 TypeResult TypeAlias = ParseTypeName(
795 nullptr,
796 TemplateInfo.Kind ? DeclaratorContext::AliasTemplateContext
797 : DeclaratorContext::AliasDeclContext,
798 AS, &DeclFromDeclSpec, &Attrs);
Richard Smith6f1daa42016-12-16 00:58:48 +0000799 if (OwnedType)
800 *OwnedType = DeclFromDeclSpec;
801
802 // Eat ';'.
803 DeclEnd = Tok.getLocation();
804 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
805 !Attrs.empty() ? "attributes list"
806 : "alias declaration"))
807 SkipUntil(tok::semi);
808
809 TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
810 MultiTemplateParamsArg TemplateParamsArg(
811 TemplateParams ? TemplateParams->data() : nullptr,
812 TemplateParams ? TemplateParams->size() : 0);
813 return Actions.ActOnAliasDeclaration(getCurScope(), AS, TemplateParamsArg,
Erich Keanec480f302018-07-12 21:09:05 +0000814 UsingLoc, D.Name, Attrs, TypeAlias,
815 DeclFromDeclSpec);
Douglas Gregord7c4d982008-12-30 03:27:21 +0000816}
817
Benjamin Kramere56f3932011-12-23 17:00:35 +0000818/// ParseStaticAssertDeclaration - Parse C++0x or C11 static_assert-declaration.
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000819///
Peter Collingbourne3d9cbdc2011-04-15 00:35:57 +0000820/// [C++0x] static_assert-declaration:
821/// static_assert ( constant-expression , string-literal ) ;
822///
Benjamin Kramere56f3932011-12-23 17:00:35 +0000823/// [C11] static_assert-declaration:
Peter Collingbourne3d9cbdc2011-04-15 00:35:57 +0000824/// _Static_assert ( constant-expression , string-literal ) ;
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000825///
John McCall48871652010-08-21 09:40:31 +0000826Decl *Parser::ParseStaticAssertDeclaration(SourceLocation &DeclEnd){
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000827 assert(Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert) &&
Peter Collingbourne3d9cbdc2011-04-15 00:35:57 +0000828 "Not a static_assert declaration");
829
David Blaikiebbafb8a2012-03-11 07:00:24 +0000830 if (Tok.is(tok::kw__Static_assert) && !getLangOpts().C11)
Benjamin Kramere56f3932011-12-23 17:00:35 +0000831 Diag(Tok, diag::ext_c11_static_assert);
Richard Smithb15c11c2011-10-17 23:06:20 +0000832 if (Tok.is(tok::kw_static_assert))
833 Diag(Tok, diag::warn_cxx98_compat_static_assert);
Peter Collingbourne3d9cbdc2011-04-15 00:35:57 +0000834
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000835 SourceLocation StaticAssertLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000836
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000837 BalancedDelimiterTracker T(*this, tok::l_paren);
838 if (T.consumeOpen()) {
Alp Tokerec543272013-12-24 09:48:30 +0000839 Diag(Tok, diag::err_expected) << tok::l_paren;
Richard Smith76965712012-09-13 19:12:50 +0000840 SkipMalformedDecl();
Craig Topper161e4db2014-05-21 06:02:52 +0000841 return nullptr;
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000842 }
Mike Stump11289f42009-09-09 15:08:12 +0000843
Richard Smithb3018062017-06-06 01:34:24 +0000844 EnterExpressionEvaluationContext ConstantEvaluated(
845 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
846 ExprResult AssertExpr(ParseConstantExpressionInExprEvalContext());
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000847 if (AssertExpr.isInvalid()) {
Richard Smith76965712012-09-13 19:12:50 +0000848 SkipMalformedDecl();
Craig Topper161e4db2014-05-21 06:02:52 +0000849 return nullptr;
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000850 }
Mike Stump11289f42009-09-09 15:08:12 +0000851
Richard Smith085a64f2014-06-20 19:57:12 +0000852 ExprResult AssertMessage;
853 if (Tok.is(tok::r_paren)) {
Aaron Ballmanc351fba2017-12-04 20:27:34 +0000854 Diag(Tok, getLangOpts().CPlusPlus17
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000855 ? diag::warn_cxx14_compat_static_assert_no_message
Richard Smith085a64f2014-06-20 19:57:12 +0000856 : diag::ext_static_assert_no_message)
Aaron Ballmanc351fba2017-12-04 20:27:34 +0000857 << (getLangOpts().CPlusPlus17
Richard Smith085a64f2014-06-20 19:57:12 +0000858 ? FixItHint()
859 : FixItHint::CreateInsertion(Tok.getLocation(), ", \"\""));
860 } else {
861 if (ExpectAndConsume(tok::comma)) {
862 SkipUntil(tok::semi);
863 return nullptr;
864 }
Anders Carlssonb4cf3ad2009-03-13 23:29:20 +0000865
Richard Smith085a64f2014-06-20 19:57:12 +0000866 if (!isTokenStringLiteral()) {
867 Diag(Tok, diag::err_expected_string_literal)
868 << /*Source='static_assert'*/1;
869 SkipMalformedDecl();
870 return nullptr;
871 }
Mike Stump11289f42009-09-09 15:08:12 +0000872
Richard Smith085a64f2014-06-20 19:57:12 +0000873 AssertMessage = ParseStringLiteralExpression();
874 if (AssertMessage.isInvalid()) {
875 SkipMalformedDecl();
876 return nullptr;
877 }
Richard Smithd67aea22012-03-06 03:21:47 +0000878 }
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000879
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000880 T.consumeClose();
Mike Stump11289f42009-09-09 15:08:12 +0000881
Chris Lattner49836b42009-04-02 04:16:50 +0000882 DeclEnd = Tok.getLocation();
Douglas Gregor45d6bdf2010-09-07 15:23:11 +0000883 ExpectAndConsumeSemi(diag::err_expected_semi_after_static_assert);
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000884
John McCallb268a282010-08-23 23:25:46 +0000885 return Actions.ActOnStaticAssertDeclaration(StaticAssertLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000886 AssertExpr.get(),
887 AssertMessage.get(),
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000888 T.getCloseLocation());
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000889}
890
Richard Smith74aeef52013-04-26 16:15:35 +0000891/// ParseDecltypeSpecifier - Parse a C++11 decltype specifier.
Anders Carlsson74948d02009-06-24 17:47:40 +0000892///
893/// 'decltype' ( expression )
Richard Smith74aeef52013-04-26 16:15:35 +0000894/// 'decltype' ( 'auto' ) [C++1y]
Anders Carlsson74948d02009-06-24 17:47:40 +0000895///
David Blaikie15a430a2011-12-04 05:04:18 +0000896SourceLocation Parser::ParseDecltypeSpecifier(DeclSpec &DS) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000897 assert(Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)
David Blaikie15a430a2011-12-04 05:04:18 +0000898 && "Not a decltype specifier");
Fangrui Song6907ce22018-07-30 19:24:48 +0000899
David Blaikie15a430a2011-12-04 05:04:18 +0000900 ExprResult Result;
901 SourceLocation StartLoc = Tok.getLocation();
902 SourceLocation EndLoc;
903
904 if (Tok.is(tok::annot_decltype)) {
905 Result = getExprAnnotation(Tok);
906 EndLoc = Tok.getAnnotationEndLoc();
Richard Smithaf3b3252017-05-18 19:21:48 +0000907 ConsumeAnnotationToken();
David Blaikie15a430a2011-12-04 05:04:18 +0000908 if (Result.isInvalid()) {
909 DS.SetTypeSpecError();
910 return EndLoc;
911 }
912 } else {
Richard Smith324df552012-02-24 22:30:04 +0000913 if (Tok.getIdentifierInfo()->isStr("decltype"))
914 Diag(Tok, diag::warn_cxx98_compat_decltype);
Richard Smithfd3da932012-02-24 18:10:23 +0000915
David Blaikie15a430a2011-12-04 05:04:18 +0000916 ConsumeToken();
917
918 BalancedDelimiterTracker T(*this, tok::l_paren);
919 if (T.expectAndConsume(diag::err_expected_lparen_after,
920 "decltype", tok::r_paren)) {
921 DS.SetTypeSpecError();
922 return T.getOpenLocation() == Tok.getLocation() ?
923 StartLoc : T.getOpenLocation();
924 }
925
Richard Smith74aeef52013-04-26 16:15:35 +0000926 // Check for C++1y 'decltype(auto)'.
927 if (Tok.is(tok::kw_auto)) {
928 // No need to disambiguate here: an expression can't start with 'auto',
929 // because the typename-specifier in a function-style cast operation can't
930 // be 'auto'.
931 Diag(Tok.getLocation(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000932 getLangOpts().CPlusPlus14
Richard Smith74aeef52013-04-26 16:15:35 +0000933 ? diag::warn_cxx11_compat_decltype_auto_type_specifier
934 : diag::ext_decltype_auto_type_specifier);
935 ConsumeToken();
936 } else {
937 // Parse the expression
David Blaikie15a430a2011-12-04 05:04:18 +0000938
Richard Smith74aeef52013-04-26 16:15:35 +0000939 // C++11 [dcl.type.simple]p4:
940 // The operand of the decltype specifier is an unevaluated operand.
Faisal Valid143a0c2017-04-01 21:30:49 +0000941 EnterExpressionEvaluationContext Unevaluated(
942 Actions, Sema::ExpressionEvaluationContext::Unevaluated, nullptr,
Nicolas Lesserb6d5c582018-07-12 18:45:41 +0000943 Sema::ExpressionEvaluationContextRecord::EK_Decltype);
Kaelyn Takata5cc85352015-04-10 19:16:46 +0000944 Result =
945 Actions.CorrectDelayedTyposInExpr(ParseExpression(), [](Expr *E) {
946 return E->hasPlaceholderType() ? ExprError() : E;
947 });
Richard Smith74aeef52013-04-26 16:15:35 +0000948 if (Result.isInvalid()) {
949 DS.SetTypeSpecError();
Alexey Bataevee6507d2013-11-18 08:17:37 +0000950 if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch)) {
Richard Smith74aeef52013-04-26 16:15:35 +0000951 EndLoc = ConsumeParen();
Argyrios Kyrtzidisc38395a2012-10-26 22:53:44 +0000952 } else {
Richard Smith74aeef52013-04-26 16:15:35 +0000953 if (PP.isBacktrackEnabled() && Tok.is(tok::semi)) {
954 // Backtrack to get the location of the last token before the semi.
955 PP.RevertCachedTokens(2);
956 ConsumeToken(); // the semi.
957 EndLoc = ConsumeAnyToken();
958 assert(Tok.is(tok::semi));
959 } else {
960 EndLoc = Tok.getLocation();
961 }
Argyrios Kyrtzidisc38395a2012-10-26 22:53:44 +0000962 }
Richard Smith74aeef52013-04-26 16:15:35 +0000963 return EndLoc;
Argyrios Kyrtzidisc38395a2012-10-26 22:53:44 +0000964 }
Richard Smith74aeef52013-04-26 16:15:35 +0000965
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000966 Result = Actions.ActOnDecltypeExpression(Result.get());
David Blaikie15a430a2011-12-04 05:04:18 +0000967 }
968
969 // Match the ')'
970 T.consumeClose();
971 if (T.getCloseLocation().isInvalid()) {
972 DS.SetTypeSpecError();
973 // FIXME: this should return the location of the last token
974 // that was consumed (by "consumeClose()")
975 return T.getCloseLocation();
976 }
977
Richard Smithfd555f62012-02-22 02:04:18 +0000978 if (Result.isInvalid()) {
979 DS.SetTypeSpecError();
980 return T.getCloseLocation();
981 }
982
David Blaikie15a430a2011-12-04 05:04:18 +0000983 EndLoc = T.getCloseLocation();
Anders Carlsson74948d02009-06-24 17:47:40 +0000984 }
Richard Smith74aeef52013-04-26 16:15:35 +0000985 assert(!Result.isInvalid());
Mike Stump11289f42009-09-09 15:08:12 +0000986
Craig Topper161e4db2014-05-21 06:02:52 +0000987 const char *PrevSpec = nullptr;
John McCall49bfce42009-08-03 20:12:06 +0000988 unsigned DiagID;
Erik Verbruggen888d52a2014-01-15 09:15:43 +0000989 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
Anders Carlsson74948d02009-06-24 17:47:40 +0000990 // Check for duplicate type specifiers (e.g. "int decltype(a)").
Richard Smith74aeef52013-04-26 16:15:35 +0000991 if (Result.get()
992 ? DS.SetTypeSpecType(DeclSpec::TST_decltype, StartLoc, PrevSpec,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000993 DiagID, Result.get(), Policy)
Richard Smith74aeef52013-04-26 16:15:35 +0000994 : DS.SetTypeSpecType(DeclSpec::TST_decltype_auto, StartLoc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +0000995 DiagID, Policy)) {
John McCall49bfce42009-08-03 20:12:06 +0000996 Diag(StartLoc, DiagID) << PrevSpec;
David Blaikie15a430a2011-12-04 05:04:18 +0000997 DS.SetTypeSpecError();
998 }
999 return EndLoc;
1000}
1001
Fangrui Song6907ce22018-07-30 19:24:48 +00001002void Parser::AnnotateExistingDecltypeSpecifier(const DeclSpec& DS,
David Blaikie15a430a2011-12-04 05:04:18 +00001003 SourceLocation StartLoc,
1004 SourceLocation EndLoc) {
1005 // make sure we have a token we can turn into an annotation token
1006 if (PP.isBacktrackEnabled())
1007 PP.RevertCachedTokens(1);
1008 else
1009 PP.EnterToken(Tok);
1010
1011 Tok.setKind(tok::annot_decltype);
Faisal Vali090da2d2018-01-01 18:23:28 +00001012 setExprAnnotation(Tok,
1013 DS.getTypeSpecType() == TST_decltype ? DS.getRepAsExpr() :
1014 DS.getTypeSpecType() == TST_decltype_auto ? ExprResult() :
1015 ExprError());
David Blaikie15a430a2011-12-04 05:04:18 +00001016 Tok.setAnnotationEndLoc(EndLoc);
1017 Tok.setLocation(StartLoc);
1018 PP.AnnotateCachedTokens(Tok);
Anders Carlsson74948d02009-06-24 17:47:40 +00001019}
1020
Alexis Hunt4a257072011-05-19 05:37:45 +00001021void Parser::ParseUnderlyingTypeSpecifier(DeclSpec &DS) {
1022 assert(Tok.is(tok::kw___underlying_type) &&
1023 "Not an underlying type specifier");
1024
1025 SourceLocation StartLoc = ConsumeToken();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001026 BalancedDelimiterTracker T(*this, tok::l_paren);
1027 if (T.expectAndConsume(diag::err_expected_lparen_after,
1028 "__underlying_type", tok::r_paren)) {
Alexis Hunt4a257072011-05-19 05:37:45 +00001029 return;
1030 }
1031
1032 TypeResult Result = ParseTypeName();
1033 if (Result.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00001034 SkipUntil(tok::r_paren, StopAtSemi);
Alexis Hunt4a257072011-05-19 05:37:45 +00001035 return;
1036 }
1037
1038 // Match the ')'
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001039 T.consumeClose();
1040 if (T.getCloseLocation().isInvalid())
Alexis Hunt4a257072011-05-19 05:37:45 +00001041 return;
1042
Craig Topper161e4db2014-05-21 06:02:52 +00001043 const char *PrevSpec = nullptr;
Alexis Hunt4a257072011-05-19 05:37:45 +00001044 unsigned DiagID;
Alexis Hunte852b102011-05-24 22:41:36 +00001045 if (DS.SetTypeSpecType(DeclSpec::TST_underlyingType, StartLoc, PrevSpec,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001046 DiagID, Result.get(),
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001047 Actions.getASTContext().getPrintingPolicy()))
Alexis Hunt4a257072011-05-19 05:37:45 +00001048 Diag(StartLoc, DiagID) << PrevSpec;
Enea Zaffanellaa90af722013-07-06 18:54:58 +00001049 DS.setTypeofParensRange(T.getRange());
Alexis Hunt4a257072011-05-19 05:37:45 +00001050}
1051
David Blaikie00ee7a082011-10-25 15:01:20 +00001052/// ParseBaseTypeSpecifier - Parse a C++ base-type-specifier which is either a
Fangrui Song6907ce22018-07-30 19:24:48 +00001053/// class name or decltype-specifier. Note that we only check that the result
1054/// names a type; semantic analysis will need to verify that the type names a
1055/// class. The result is either a type or null, depending on whether a type
David Blaikie00ee7a082011-10-25 15:01:20 +00001056/// name was found.
Douglas Gregor831c93f2008-11-05 20:51:48 +00001057///
Richard Smith4c96e992013-02-19 23:47:15 +00001058/// base-type-specifier: [C++11 class.derived]
David Blaikie00ee7a082011-10-25 15:01:20 +00001059/// class-or-decltype
Richard Smith4c96e992013-02-19 23:47:15 +00001060/// class-or-decltype: [C++11 class.derived]
David Blaikie00ee7a082011-10-25 15:01:20 +00001061/// nested-name-specifier[opt] class-name
1062/// decltype-specifier
Richard Smith4c96e992013-02-19 23:47:15 +00001063/// class-name: [C++ class.name]
Douglas Gregor831c93f2008-11-05 20:51:48 +00001064/// identifier
Douglas Gregord54dfb82009-02-25 23:52:28 +00001065/// simple-template-id
Mike Stump11289f42009-09-09 15:08:12 +00001066///
Richard Smith4c96e992013-02-19 23:47:15 +00001067/// In C++98, instead of base-type-specifier, we have:
1068///
1069/// ::[opt] nested-name-specifier[opt] class-name
Craig Topper9ad7e262014-10-31 06:57:07 +00001070TypeResult Parser::ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
1071 SourceLocation &EndLocation) {
David Blaikiedd58d4c2011-10-25 18:46:41 +00001072 // Ignore attempts to use typename
1073 if (Tok.is(tok::kw_typename)) {
1074 Diag(Tok, diag::err_expected_class_name_not_template)
1075 << FixItHint::CreateRemoval(Tok.getLocation());
1076 ConsumeToken();
1077 }
1078
David Blaikieafa155f2011-10-25 18:17:58 +00001079 // Parse optional nested-name-specifier
1080 CXXScopeSpec SS;
David Blaikieefdccaa2016-01-15 23:43:34 +00001081 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false);
David Blaikieafa155f2011-10-25 18:17:58 +00001082
1083 BaseLoc = Tok.getLocation();
1084
David Blaikie1cd50022011-10-25 17:10:12 +00001085 // Parse decltype-specifier
Fangrui Song6907ce22018-07-30 19:24:48 +00001086 // tok == kw_decltype is just error recovery, it can only happen when SS
David Blaikie15a430a2011-12-04 05:04:18 +00001087 // isn't empty
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001088 if (Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)) {
David Blaikieafa155f2011-10-25 18:17:58 +00001089 if (SS.isNotEmpty())
1090 Diag(SS.getBeginLoc(), diag::err_unexpected_scope_on_base_decltype)
1091 << FixItHint::CreateRemoval(SS.getRange());
David Blaikie1cd50022011-10-25 17:10:12 +00001092 // Fake up a Declarator to use with ActOnTypeName.
1093 DeclSpec DS(AttrFactory);
1094
David Blaikie7491e732011-12-08 04:53:15 +00001095 EndLocation = ParseDecltypeSpecifier(DS);
David Blaikie1cd50022011-10-25 17:10:12 +00001096
Faisal Vali421b2d12017-12-29 05:41:00 +00001097 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
David Blaikie1cd50022011-10-25 17:10:12 +00001098 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
1099 }
1100
Douglas Gregord54dfb82009-02-25 23:52:28 +00001101 // Check whether we have a template-id that names a type.
1102 if (Tok.is(tok::annot_template_id)) {
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00001103 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregor46c59612010-01-12 17:52:59 +00001104 if (TemplateId->Kind == TNK_Type_template ||
1105 TemplateId->Kind == TNK_Dependent_template_name) {
Richard Smith62559bd2017-02-01 21:36:38 +00001106 AnnotateTemplateIdTokenAsType(/*IsClassName*/true);
Douglas Gregord54dfb82009-02-25 23:52:28 +00001107
1108 assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
John McCallba7bf592010-08-24 05:47:05 +00001109 ParsedType Type = getTypeAnnotation(Tok);
Douglas Gregord54dfb82009-02-25 23:52:28 +00001110 EndLocation = Tok.getAnnotationEndLoc();
Richard Smithaf3b3252017-05-18 19:21:48 +00001111 ConsumeAnnotationToken();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001112
1113 if (Type)
1114 return Type;
1115 return true;
Douglas Gregord54dfb82009-02-25 23:52:28 +00001116 }
1117
1118 // Fall through to produce an error below.
1119 }
1120
Douglas Gregor831c93f2008-11-05 20:51:48 +00001121 if (Tok.isNot(tok::identifier)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00001122 Diag(Tok, diag::err_expected_class_name);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001123 return true;
Douglas Gregor831c93f2008-11-05 20:51:48 +00001124 }
1125
Douglas Gregor18473f32010-01-12 21:28:44 +00001126 IdentifierInfo *Id = Tok.getIdentifierInfo();
1127 SourceLocation IdLoc = ConsumeToken();
1128
1129 if (Tok.is(tok::less)) {
1130 // It looks the user intended to write a template-id here, but the
1131 // template-name was wrong. Try to fix that.
1132 TemplateNameKind TNK = TNK_Type_template;
1133 TemplateTy Template;
Douglas Gregor0be31a22010-07-02 17:43:08 +00001134 if (!Actions.DiagnoseUnknownTemplateName(*Id, IdLoc, getCurScope(),
Douglas Gregore7c20652011-03-02 00:47:37 +00001135 &SS, Template, TNK)) {
Douglas Gregor18473f32010-01-12 21:28:44 +00001136 Diag(IdLoc, diag::err_unknown_template_name)
1137 << Id;
1138 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001139
Serge Pavlovb716b3c2013-08-10 05:54:47 +00001140 if (!Template) {
1141 TemplateArgList TemplateArgs;
1142 SourceLocation LAngleLoc, RAngleLoc;
Richard Smith9a420f92017-05-10 21:47:30 +00001143 ParseTemplateIdAfterTemplateName(true, LAngleLoc, TemplateArgs,
1144 RAngleLoc);
Douglas Gregor18473f32010-01-12 21:28:44 +00001145 return true;
Serge Pavlovb716b3c2013-08-10 05:54:47 +00001146 }
Douglas Gregor18473f32010-01-12 21:28:44 +00001147
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001148 // Form the template name
Douglas Gregor18473f32010-01-12 21:28:44 +00001149 UnqualifiedId TemplateName;
1150 TemplateName.setIdentifier(Id, IdLoc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001151
Douglas Gregor18473f32010-01-12 21:28:44 +00001152 // Parse the full template-id, then turn it into a type.
Abramo Bagnara7945c982012-01-27 09:46:47 +00001153 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
Richard Smith62559bd2017-02-01 21:36:38 +00001154 TemplateName))
Douglas Gregor18473f32010-01-12 21:28:44 +00001155 return true;
Richard Smith62559bd2017-02-01 21:36:38 +00001156 if (TNK == TNK_Type_template || TNK == TNK_Dependent_template_name)
1157 AnnotateTemplateIdTokenAsType(/*IsClassName*/true);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001158
Douglas Gregor18473f32010-01-12 21:28:44 +00001159 // If we didn't end up with a typename token, there's nothing more we
1160 // can do.
1161 if (Tok.isNot(tok::annot_typename))
1162 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001163
Douglas Gregor18473f32010-01-12 21:28:44 +00001164 // Retrieve the type from the annotation token, consume that token, and
1165 // return.
1166 EndLocation = Tok.getAnnotationEndLoc();
John McCallba7bf592010-08-24 05:47:05 +00001167 ParsedType Type = getTypeAnnotation(Tok);
Richard Smithaf3b3252017-05-18 19:21:48 +00001168 ConsumeAnnotationToken();
Douglas Gregor18473f32010-01-12 21:28:44 +00001169 return Type;
1170 }
1171
Douglas Gregor831c93f2008-11-05 20:51:48 +00001172 // We have an identifier; check whether it is actually a type.
Craig Topper161e4db2014-05-21 06:02:52 +00001173 IdentifierInfo *CorrectedII = nullptr;
Richard Smith600b5262017-01-26 20:40:47 +00001174 ParsedType Type = Actions.getTypeName(
Richard Smith62559bd2017-02-01 21:36:38 +00001175 *Id, IdLoc, getCurScope(), &SS, /*IsClassName=*/true, false, nullptr,
Richard Smith600b5262017-01-26 20:40:47 +00001176 /*IsCtorOrDtorName=*/false,
1177 /*NonTrivialTypeSourceInfo=*/true,
1178 /*IsClassTemplateDeductionContext*/ false, &CorrectedII);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001179 if (!Type) {
Douglas Gregorfe17d252010-02-16 19:09:40 +00001180 Diag(IdLoc, diag::err_expected_class_name);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001181 return true;
Douglas Gregor831c93f2008-11-05 20:51:48 +00001182 }
1183
1184 // Consume the identifier.
Douglas Gregor18473f32010-01-12 21:28:44 +00001185 EndLocation = IdLoc;
Nick Lewycky19b9f952010-07-26 16:56:01 +00001186
1187 // Fake up a Declarator to use with ActOnTypeName.
John McCall084e83d2011-03-24 11:26:52 +00001188 DeclSpec DS(AttrFactory);
Nick Lewycky19b9f952010-07-26 16:56:01 +00001189 DS.SetRangeStart(IdLoc);
1190 DS.SetRangeEnd(EndLocation);
Douglas Gregore7c20652011-03-02 00:47:37 +00001191 DS.getTypeSpecScope() = SS;
Nick Lewycky19b9f952010-07-26 16:56:01 +00001192
Craig Topper161e4db2014-05-21 06:02:52 +00001193 const char *PrevSpec = nullptr;
Nick Lewycky19b9f952010-07-26 16:56:01 +00001194 unsigned DiagID;
Faisal Vali090da2d2018-01-01 18:23:28 +00001195 DS.SetTypeSpecType(TST_typename, IdLoc, PrevSpec, DiagID, Type,
1196 Actions.getASTContext().getPrintingPolicy());
Nick Lewycky19b9f952010-07-26 16:56:01 +00001197
Faisal Vali421b2d12017-12-29 05:41:00 +00001198 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
Nick Lewycky19b9f952010-07-26 16:56:01 +00001199 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
Douglas Gregor831c93f2008-11-05 20:51:48 +00001200}
1201
John McCall8d32c052012-05-22 21:28:12 +00001202void Parser::ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001203 while (Tok.isOneOf(tok::kw___single_inheritance,
1204 tok::kw___multiple_inheritance,
1205 tok::kw___virtual_inheritance)) {
John McCall8d32c052012-05-22 21:28:12 +00001206 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
1207 SourceLocation AttrNameLoc = ConsumeToken();
Craig Topper161e4db2014-05-21 06:02:52 +00001208 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
Erich Keanee891aa92018-07-13 15:07:47 +00001209 ParsedAttr::AS_Keyword);
John McCall8d32c052012-05-22 21:28:12 +00001210 }
1211}
1212
Richard Smith369b9f92012-06-25 21:37:02 +00001213/// Determine whether the following tokens are valid after a type-specifier
1214/// which could be a standalone declaration. This will conservatively return
1215/// true if there's any doubt, and is appropriate for insert-';' fixits.
Richard Smith200f47c2012-07-02 19:14:01 +00001216bool Parser::isValidAfterTypeSpecifier(bool CouldBeBitfield) {
Richard Smith369b9f92012-06-25 21:37:02 +00001217 // This switch enumerates the valid "follow" set for type-specifiers.
1218 switch (Tok.getKind()) {
1219 default: break;
1220 case tok::semi: // struct foo {...} ;
1221 case tok::star: // struct foo {...} * P;
1222 case tok::amp: // struct foo {...} & R = ...
Richard Smith1ac67d12013-01-19 03:48:05 +00001223 case tok::ampamp: // struct foo {...} && R = ...
Richard Smith369b9f92012-06-25 21:37:02 +00001224 case tok::identifier: // struct foo {...} V ;
1225 case tok::r_paren: //(struct foo {...} ) {4}
1226 case tok::annot_cxxscope: // struct foo {...} a:: b;
1227 case tok::annot_typename: // struct foo {...} a ::b;
1228 case tok::annot_template_id: // struct foo {...} a<int> ::b;
1229 case tok::l_paren: // struct foo {...} ( x);
1230 case tok::comma: // __builtin_offsetof(struct foo{...} ,
Richard Smith1ac67d12013-01-19 03:48:05 +00001231 case tok::kw_operator: // struct foo operator ++() {...}
Alp Tokerd3f79c52013-11-24 20:24:54 +00001232 case tok::kw___declspec: // struct foo {...} __declspec(...)
Richard Smith843f18f2014-08-13 02:13:15 +00001233 case tok::l_square: // void f(struct f [ 3])
1234 case tok::ellipsis: // void f(struct f ... [Ns])
Abramo Bagnara152eb392014-08-16 08:29:27 +00001235 // FIXME: we should emit semantic diagnostic when declaration
1236 // attribute is in type attribute position.
1237 case tok::kw___attribute: // struct foo __attribute__((used)) x;
David Majnemer15b311c2016-06-14 03:20:28 +00001238 case tok::annot_pragma_pack: // struct foo {...} _Pragma(pack(pop));
1239 // struct foo {...} _Pragma(section(...));
1240 case tok::annot_pragma_ms_pragma:
1241 // struct foo {...} _Pragma(vtordisp(pop));
1242 case tok::annot_pragma_ms_vtordisp:
1243 // struct foo {...} _Pragma(pointers_to_members(...));
1244 case tok::annot_pragma_ms_pointers_to_members:
Richard Smith369b9f92012-06-25 21:37:02 +00001245 return true;
Richard Smith200f47c2012-07-02 19:14:01 +00001246 case tok::colon:
1247 return CouldBeBitfield; // enum E { ... } : 2;
Reid Klecknercfa91552016-03-21 16:08:49 +00001248 // Microsoft compatibility
1249 case tok::kw___cdecl: // struct foo {...} __cdecl x;
1250 case tok::kw___fastcall: // struct foo {...} __fastcall x;
1251 case tok::kw___stdcall: // struct foo {...} __stdcall x;
1252 case tok::kw___thiscall: // struct foo {...} __thiscall x;
1253 case tok::kw___vectorcall: // struct foo {...} __vectorcall x;
1254 // We will diagnose these calling-convention specifiers on non-function
1255 // declarations later, so claim they are valid after a type specifier.
1256 return getLangOpts().MicrosoftExt;
Richard Smith369b9f92012-06-25 21:37:02 +00001257 // Type qualifiers
1258 case tok::kw_const: // struct foo {...} const x;
1259 case tok::kw_volatile: // struct foo {...} volatile x;
1260 case tok::kw_restrict: // struct foo {...} restrict x;
Richard Smith843f18f2014-08-13 02:13:15 +00001261 case tok::kw__Atomic: // struct foo {...} _Atomic x;
Nico Rieck3e1ee832014-12-04 23:30:25 +00001262 case tok::kw___unaligned: // struct foo {...} __unaligned *x;
Richard Smith1ac67d12013-01-19 03:48:05 +00001263 // Function specifiers
1264 // Note, no 'explicit'. An explicit function must be either a conversion
1265 // operator or a constructor. Either way, it can't have a return type.
1266 case tok::kw_inline: // struct foo inline f();
1267 case tok::kw_virtual: // struct foo virtual f();
1268 case tok::kw_friend: // struct foo friend f();
Richard Smith369b9f92012-06-25 21:37:02 +00001269 // Storage-class specifiers
1270 case tok::kw_static: // struct foo {...} static x;
1271 case tok::kw_extern: // struct foo {...} extern x;
1272 case tok::kw_typedef: // struct foo {...} typedef x;
1273 case tok::kw_register: // struct foo {...} register x;
1274 case tok::kw_auto: // struct foo {...} auto x;
1275 case tok::kw_mutable: // struct foo {...} mutable x;
Richard Smith1ac67d12013-01-19 03:48:05 +00001276 case tok::kw_thread_local: // struct foo {...} thread_local x;
Richard Smith369b9f92012-06-25 21:37:02 +00001277 case tok::kw_constexpr: // struct foo {...} constexpr x;
1278 // As shown above, type qualifiers and storage class specifiers absolutely
1279 // can occur after class specifiers according to the grammar. However,
1280 // almost no one actually writes code like this. If we see one of these,
1281 // it is much more likely that someone missed a semi colon and the
1282 // type/storage class specifier we're seeing is part of the *next*
1283 // intended declaration, as in:
1284 //
1285 // struct foo { ... }
1286 // typedef int X;
1287 //
1288 // We'd really like to emit a missing semicolon error instead of emitting
1289 // an error on the 'int' saying that you can't have two type specifiers in
1290 // the same declaration of X. Because of this, we look ahead past this
1291 // token to see if it's a type specifier. If so, we know the code is
1292 // otherwise invalid, so we can produce the expected semi error.
1293 if (!isKnownToBeTypeSpecifier(NextToken()))
1294 return true;
1295 break;
1296 case tok::r_brace: // struct bar { struct foo {...} }
1297 // Missing ';' at end of struct is accepted as an extension in C mode.
1298 if (!getLangOpts().CPlusPlus)
1299 return true;
1300 break;
Richard Smith52c5b872013-01-29 04:13:32 +00001301 case tok::greater:
1302 // template<class T = class X>
1303 return getLangOpts().CPlusPlus;
Richard Smith369b9f92012-06-25 21:37:02 +00001304 }
1305 return false;
1306}
1307
Douglas Gregor556877c2008-04-13 21:30:24 +00001308/// ParseClassSpecifier - Parse a C++ class-specifier [C++ class] or
1309/// elaborated-type-specifier [C++ dcl.type.elab]; we can't tell which
1310/// until we reach the start of a definition or see a token that
Richard Smithc5b05522012-03-12 07:56:15 +00001311/// cannot start a definition.
Douglas Gregor556877c2008-04-13 21:30:24 +00001312///
1313/// class-specifier: [C++ class]
1314/// class-head '{' member-specification[opt] '}'
1315/// class-head '{' member-specification[opt] '}' attributes[opt]
1316/// class-head:
1317/// class-key identifier[opt] base-clause[opt]
1318/// class-key nested-name-specifier identifier base-clause[opt]
1319/// class-key nested-name-specifier[opt] simple-template-id
1320/// base-clause[opt]
1321/// [GNU] class-key attributes[opt] identifier[opt] base-clause[opt]
Mike Stump11289f42009-09-09 15:08:12 +00001322/// [GNU] class-key attributes[opt] nested-name-specifier
Douglas Gregor556877c2008-04-13 21:30:24 +00001323/// identifier base-clause[opt]
Mike Stump11289f42009-09-09 15:08:12 +00001324/// [GNU] class-key attributes[opt] nested-name-specifier[opt]
Douglas Gregor556877c2008-04-13 21:30:24 +00001325/// simple-template-id base-clause[opt]
1326/// class-key:
1327/// 'class'
1328/// 'struct'
1329/// 'union'
1330///
1331/// elaborated-type-specifier: [C++ dcl.type.elab]
Mike Stump11289f42009-09-09 15:08:12 +00001332/// class-key ::[opt] nested-name-specifier[opt] identifier
1333/// class-key ::[opt] nested-name-specifier[opt] 'template'[opt]
1334/// simple-template-id
Douglas Gregor556877c2008-04-13 21:30:24 +00001335///
1336/// Note that the C++ class-specifier and elaborated-type-specifier,
1337/// together, subsume the C99 struct-or-union-specifier:
1338///
1339/// struct-or-union-specifier: [C99 6.7.2.1]
1340/// struct-or-union identifier[opt] '{' struct-contents '}'
1341/// struct-or-union identifier
1342/// [GNU] struct-or-union attributes[opt] identifier[opt] '{' struct-contents
1343/// '}' attributes[opt]
1344/// [GNU] struct-or-union attributes[opt] identifier
1345/// struct-or-union:
1346/// 'struct'
1347/// 'union'
Chris Lattnerffaa0e62009-04-12 21:49:30 +00001348void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind,
1349 SourceLocation StartLoc, DeclSpec &DS,
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001350 const ParsedTemplateInfo &TemplateInfo,
Fangrui Song6907ce22018-07-30 19:24:48 +00001351 AccessSpecifier AS,
1352 bool EnteringContext, DeclSpecContext DSC,
Bill Wendling44426052012-12-20 19:22:21 +00001353 ParsedAttributesWithRange &Attributes) {
Joao Matose9a3ed42012-08-31 22:18:20 +00001354 DeclSpec::TST TagType;
1355 if (TagTokKind == tok::kw_struct)
1356 TagType = DeclSpec::TST_struct;
1357 else if (TagTokKind == tok::kw___interface)
1358 TagType = DeclSpec::TST_interface;
1359 else if (TagTokKind == tok::kw_class)
1360 TagType = DeclSpec::TST_class;
1361 else {
Chris Lattnerffaa0e62009-04-12 21:49:30 +00001362 assert(TagTokKind == tok::kw_union && "Not a class specifier");
1363 TagType = DeclSpec::TST_union;
1364 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001365
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00001366 if (Tok.is(tok::code_completion)) {
1367 // Code completion for a struct, class, or union name.
Douglas Gregor0be31a22010-07-02 17:43:08 +00001368 Actions.CodeCompleteTag(getCurScope(), TagType);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001369 return cutOffParsing();
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00001370 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001371
Chandler Carruth2d69ec72010-06-28 08:39:25 +00001372 // C++03 [temp.explicit] 14.7.2/8:
1373 // The usual access checking rules do not apply to names used to specify
1374 // explicit instantiations.
1375 //
1376 // As an extension we do not perform access checking on the names used to
1377 // specify explicit specializations either. This is important to allow
1378 // specializing traits classes for private types.
John McCall6347b682012-05-07 06:16:58 +00001379 //
1380 // Note that we don't suppress if this turns out to be an elaborated
1381 // type specifier.
1382 bool shouldDelayDiagsInTag =
1383 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
1384 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
1385 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
Chandler Carruth2d69ec72010-06-28 08:39:25 +00001386
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001387 ParsedAttributesWithRange attrs(AttrFactory);
Douglas Gregor556877c2008-04-13 21:30:24 +00001388 // If attributes exist after tag, parse them.
Richard Smith37a45dd2013-10-24 01:21:09 +00001389 MaybeParseGNUAttributes(attrs);
Aaron Ballman068aa512015-05-20 20:58:33 +00001390 MaybeParseMicrosoftDeclSpecs(attrs);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001391
John McCall8d32c052012-05-22 21:28:12 +00001392 // Parse inheritance specifiers.
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001393 if (Tok.isOneOf(tok::kw___single_inheritance,
1394 tok::kw___multiple_inheritance,
1395 tok::kw___virtual_inheritance))
Richard Smith37a45dd2013-10-24 01:21:09 +00001396 ParseMicrosoftInheritanceClassAttributes(attrs);
John McCall8d32c052012-05-22 21:28:12 +00001397
Alexis Hunt96d5c762009-11-21 08:43:09 +00001398 // If C++0x attributes exist here, parse them.
1399 // FIXME: Are we consistent with the ordering of parsing of different
1400 // styles of attributes?
Richard Smith89645bc2013-01-02 12:01:23 +00001401 MaybeParseCXX11Attributes(attrs);
Mike Stump11289f42009-09-09 15:08:12 +00001402
Michael Han309af292013-01-07 16:57:11 +00001403 // Source location used by FIXIT to insert misplaced
1404 // C++11 attributes
1405 SourceLocation AttrFixitLoc = Tok.getLocation();
1406
Nico Weber7c3c5be2014-09-23 04:09:56 +00001407 if (TagType == DeclSpec::TST_struct &&
David Majnemer86330af2014-12-29 02:14:26 +00001408 Tok.isNot(tok::identifier) &&
1409 !Tok.isAnnotation() &&
Nico Weber7c3c5be2014-09-23 04:09:56 +00001410 Tok.getIdentifierInfo() &&
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001411 Tok.isOneOf(tok::kw___is_abstract,
Eric Fiselier07360662017-04-12 22:12:15 +00001412 tok::kw___is_aggregate,
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001413 tok::kw___is_arithmetic,
1414 tok::kw___is_array,
David Majnemerb3d96882016-05-23 17:21:55 +00001415 tok::kw___is_assignable,
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001416 tok::kw___is_base_of,
1417 tok::kw___is_class,
1418 tok::kw___is_complete_type,
1419 tok::kw___is_compound,
1420 tok::kw___is_const,
1421 tok::kw___is_constructible,
1422 tok::kw___is_convertible,
1423 tok::kw___is_convertible_to,
1424 tok::kw___is_destructible,
1425 tok::kw___is_empty,
1426 tok::kw___is_enum,
1427 tok::kw___is_floating_point,
1428 tok::kw___is_final,
1429 tok::kw___is_function,
1430 tok::kw___is_fundamental,
1431 tok::kw___is_integral,
1432 tok::kw___is_interface_class,
1433 tok::kw___is_literal,
1434 tok::kw___is_lvalue_expr,
1435 tok::kw___is_lvalue_reference,
1436 tok::kw___is_member_function_pointer,
1437 tok::kw___is_member_object_pointer,
1438 tok::kw___is_member_pointer,
1439 tok::kw___is_nothrow_assignable,
1440 tok::kw___is_nothrow_constructible,
1441 tok::kw___is_nothrow_destructible,
1442 tok::kw___is_object,
1443 tok::kw___is_pod,
1444 tok::kw___is_pointer,
1445 tok::kw___is_polymorphic,
1446 tok::kw___is_reference,
1447 tok::kw___is_rvalue_expr,
1448 tok::kw___is_rvalue_reference,
1449 tok::kw___is_same,
1450 tok::kw___is_scalar,
1451 tok::kw___is_sealed,
1452 tok::kw___is_signed,
1453 tok::kw___is_standard_layout,
1454 tok::kw___is_trivial,
1455 tok::kw___is_trivially_assignable,
1456 tok::kw___is_trivially_constructible,
1457 tok::kw___is_trivially_copyable,
1458 tok::kw___is_union,
1459 tok::kw___is_unsigned,
1460 tok::kw___is_void,
1461 tok::kw___is_volatile))
Nico Weber7c3c5be2014-09-23 04:09:56 +00001462 // GNU libstdc++ 4.2 and libc++ use certain intrinsic names as the
1463 // name of struct templates, but some are keywords in GCC >= 4.3
1464 // and Clang. Therefore, when we see the token sequence "struct
1465 // X", make X into a normal identifier rather than a keyword, to
1466 // allow libstdc++ 4.2 and libc++ to work properly.
1467 TryKeywordIdentFallback(true);
Mike Stump11289f42009-09-09 15:08:12 +00001468
David Majnemer51fd8a02015-07-22 23:46:18 +00001469 struct PreserveAtomicIdentifierInfoRAII {
1470 PreserveAtomicIdentifierInfoRAII(Token &Tok, bool Enabled)
1471 : AtomicII(nullptr) {
1472 if (!Enabled)
1473 return;
1474 assert(Tok.is(tok::kw__Atomic));
1475 AtomicII = Tok.getIdentifierInfo();
1476 AtomicII->revertTokenIDToIdentifier();
1477 Tok.setKind(tok::identifier);
1478 }
1479 ~PreserveAtomicIdentifierInfoRAII() {
1480 if (!AtomicII)
1481 return;
1482 AtomicII->revertIdentifierToTokenID(tok::kw__Atomic);
1483 }
1484 IdentifierInfo *AtomicII;
1485 };
1486
1487 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
1488 // implementation for VS2013 uses _Atomic as an identifier for one of the
1489 // classes in <atomic>. When we are parsing 'struct _Atomic', don't consider
1490 // '_Atomic' to be a keyword. We are careful to undo this so that clang can
1491 // use '_Atomic' in its own header files.
1492 bool ShouldChangeAtomicToIdentifier = getLangOpts().MSVCCompat &&
1493 Tok.is(tok::kw__Atomic) &&
1494 TagType == DeclSpec::TST_struct;
1495 PreserveAtomicIdentifierInfoRAII AtomicTokenGuard(
1496 Tok, ShouldChangeAtomicToIdentifier);
1497
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001498 // Parse the (optional) nested-name-specifier.
John McCall9dab4e62009-12-12 11:40:51 +00001499 CXXScopeSpec &SS = DS.getTypeSpecScope();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001500 if (getLangOpts().CPlusPlus) {
Serge Pavlov458ea762014-07-16 05:16:52 +00001501 // "FOO : BAR" is not a potential typo for "FOO::BAR". In this context it
1502 // is a base-specifier-list.
Chris Lattnerd5c1c9d2009-12-10 00:32:41 +00001503 ColonProtectionRAIIObject X(*this);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001504
Nico Webercfaa4cd2015-02-15 07:26:13 +00001505 CXXScopeSpec Spec;
1506 bool HasValidSpec = true;
David Blaikieefdccaa2016-01-15 23:43:34 +00001507 if (ParseOptionalCXXScopeSpecifier(Spec, nullptr, EnteringContext)) {
John McCall413021a2010-07-30 06:26:29 +00001508 DS.SetTypeSpecError();
Nico Webercfaa4cd2015-02-15 07:26:13 +00001509 HasValidSpec = false;
1510 }
1511 if (Spec.isSet())
1512 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::annot_template_id)) {
Alp Tokerec543272013-12-24 09:48:30 +00001513 Diag(Tok, diag::err_expected) << tok::identifier;
Nico Webercfaa4cd2015-02-15 07:26:13 +00001514 HasValidSpec = false;
1515 }
1516 if (HasValidSpec)
1517 SS = Spec;
Chris Lattnerd5c1c9d2009-12-10 00:32:41 +00001518 }
Douglas Gregor67a65642009-02-17 23:15:12 +00001519
Douglas Gregor916462b2009-10-30 21:46:58 +00001520 TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
1521
Douglas Gregor67a65642009-02-17 23:15:12 +00001522 // Parse the (optional) class name or simple-template-id.
Craig Topper161e4db2014-05-21 06:02:52 +00001523 IdentifierInfo *Name = nullptr;
Douglas Gregor556877c2008-04-13 21:30:24 +00001524 SourceLocation NameLoc;
Craig Topper161e4db2014-05-21 06:02:52 +00001525 TemplateIdAnnotation *TemplateId = nullptr;
Douglas Gregor556877c2008-04-13 21:30:24 +00001526 if (Tok.is(tok::identifier)) {
1527 Name = Tok.getIdentifierInfo();
1528 NameLoc = ConsumeToken();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001529
David Blaikiebbafb8a2012-03-11 07:00:24 +00001530 if (Tok.is(tok::less) && getLangOpts().CPlusPlus) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001531 // The name was supposed to refer to a template, but didn't.
Douglas Gregor916462b2009-10-30 21:46:58 +00001532 // Eat the template argument list and try to continue parsing this as
1533 // a class (or template thereof).
1534 TemplateArgList TemplateArgs;
Douglas Gregor916462b2009-10-30 21:46:58 +00001535 SourceLocation LAngleLoc, RAngleLoc;
Richard Smith9a420f92017-05-10 21:47:30 +00001536 if (ParseTemplateIdAfterTemplateName(true, LAngleLoc, TemplateArgs,
1537 RAngleLoc)) {
Douglas Gregor916462b2009-10-30 21:46:58 +00001538 // We couldn't parse the template argument list at all, so don't
1539 // try to give any location information for the list.
1540 LAngleLoc = RAngleLoc = SourceLocation();
1541 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001542
Douglas Gregor916462b2009-10-30 21:46:58 +00001543 Diag(NameLoc, diag::err_explicit_spec_non_template)
Alp Toker01d65e12014-01-06 12:54:41 +00001544 << (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
1545 << TagTokKind << Name << SourceRange(LAngleLoc, RAngleLoc);
Joao Matose9a3ed42012-08-31 22:18:20 +00001546
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001547 // Strip off the last template parameter list if it was empty, since
Douglas Gregor1d0015f2009-10-30 22:09:44 +00001548 // we've removed its template argument list.
1549 if (TemplateParams && TemplateInfo.LastParameterListWasEmpty) {
Hubert Tong97b06632016-04-13 18:41:03 +00001550 if (TemplateParams->size() > 1) {
Douglas Gregor1d0015f2009-10-30 22:09:44 +00001551 TemplateParams->pop_back();
1552 } else {
Craig Topper161e4db2014-05-21 06:02:52 +00001553 TemplateParams = nullptr;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001554 const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind
Douglas Gregor1d0015f2009-10-30 22:09:44 +00001555 = ParsedTemplateInfo::NonTemplate;
1556 }
1557 } else if (TemplateInfo.Kind
1558 == ParsedTemplateInfo::ExplicitInstantiation) {
1559 // Pretend this is just a forward declaration.
Craig Topper161e4db2014-05-21 06:02:52 +00001560 TemplateParams = nullptr;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001561 const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind
Douglas Gregor916462b2009-10-30 21:46:58 +00001562 = ParsedTemplateInfo::NonTemplate;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001563 const_cast<ParsedTemplateInfo&>(TemplateInfo).TemplateLoc
Douglas Gregor1d0015f2009-10-30 22:09:44 +00001564 = SourceLocation();
1565 const_cast<ParsedTemplateInfo&>(TemplateInfo).ExternLoc
1566 = SourceLocation();
Douglas Gregor916462b2009-10-30 21:46:58 +00001567 }
Douglas Gregor916462b2009-10-30 21:46:58 +00001568 }
Douglas Gregor7f741122009-02-25 19:37:18 +00001569 } else if (Tok.is(tok::annot_template_id)) {
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00001570 TemplateId = takeTemplateIdAnnotation(Tok);
Richard Smithaf3b3252017-05-18 19:21:48 +00001571 NameLoc = ConsumeAnnotationToken();
Douglas Gregor67a65642009-02-17 23:15:12 +00001572
Douglas Gregore7c20652011-03-02 00:47:37 +00001573 if (TemplateId->Kind != TNK_Type_template &&
1574 TemplateId->Kind != TNK_Dependent_template_name) {
Douglas Gregor7f741122009-02-25 19:37:18 +00001575 // The template-name in the simple-template-id refers to
1576 // something other than a class template. Give an appropriate
1577 // error message and skip to the ';'.
1578 SourceRange Range(NameLoc);
1579 if (SS.isNotEmpty())
1580 Range.setBegin(SS.getBeginLoc());
Douglas Gregor67a65642009-02-17 23:15:12 +00001581
Richard Smith72bfbd82013-12-04 00:28:23 +00001582 // FIXME: Name may be null here.
Douglas Gregor7f741122009-02-25 19:37:18 +00001583 Diag(TemplateId->LAngleLoc, diag::err_template_spec_syntax_non_template)
Richard Trieu30f93852013-06-19 22:25:01 +00001584 << TemplateId->Name << static_cast<int>(TemplateId->Kind) << Range;
Mike Stump11289f42009-09-09 15:08:12 +00001585
Douglas Gregor7f741122009-02-25 19:37:18 +00001586 DS.SetTypeSpecError();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001587 SkipUntil(tok::semi, StopBeforeMatch);
Douglas Gregor7f741122009-02-25 19:37:18 +00001588 return;
Douglas Gregor67a65642009-02-17 23:15:12 +00001589 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001590 }
1591
Richard Smithbfdb1082012-03-12 08:56:40 +00001592 // There are four options here.
1593 // - If we are in a trailing return type, this is always just a reference,
1594 // and we must not try to parse a definition. For instance,
1595 // [] () -> struct S { };
1596 // does not define a type.
1597 // - If we have 'struct foo {...', 'struct foo :...',
1598 // 'struct foo final :' or 'struct foo final {', then this is a definition.
1599 // - If we have 'struct foo;', then this is either a forward declaration
1600 // or a friend declaration, which have to be treated differently.
1601 // - Otherwise we have something like 'struct foo xyz', a reference.
Michael Han9407e502012-11-26 22:54:45 +00001602 //
1603 // We also detect these erroneous cases to provide better diagnostic for
1604 // C++11 attributes parsing.
1605 // - attributes follow class name:
1606 // struct foo [[]] {};
1607 // - attributes appear before or after 'final':
1608 // struct foo [[]] final [[]] {};
1609 //
Richard Smithc5b05522012-03-12 07:56:15 +00001610 // However, in type-specifier-seq's, things look like declarations but are
1611 // just references, e.g.
1612 // new struct s;
Sebastian Redl2b372722010-02-03 21:21:43 +00001613 // or
Richard Smithc5b05522012-03-12 07:56:15 +00001614 // &T::operator struct s;
Faisal Vali7db85c52017-12-31 00:06:40 +00001615 // For these, DSC is DeclSpecContext::DSC_type_specifier or
1616 // DeclSpecContext::DSC_alias_declaration.
Michael Han9407e502012-11-26 22:54:45 +00001617
1618 // If there are attributes after class name, parse them.
Richard Smith89645bc2013-01-02 12:01:23 +00001619 MaybeParseCXX11Attributes(Attributes);
Michael Han9407e502012-11-26 22:54:45 +00001620
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001621 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
John McCallfaf5fb42010-08-26 23:41:50 +00001622 Sema::TagUseKind TUK;
Faisal Vali7db85c52017-12-31 00:06:40 +00001623 if (DSC == DeclSpecContext::DSC_trailing)
Richard Smithbfdb1082012-03-12 08:56:40 +00001624 TUK = Sema::TUK_Reference;
1625 else if (Tok.is(tok::l_brace) ||
1626 (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
Richard Smith89645bc2013-01-02 12:01:23 +00001627 (isCXX11FinalKeyword() &&
David Blaikie9933a5a2012-03-12 15:39:49 +00001628 (NextToken().is(tok::l_brace) || NextToken().is(tok::colon)))) {
Douglas Gregor3dad8422009-09-26 06:47:28 +00001629 if (DS.isFriendSpecified()) {
1630 // C++ [class.friend]p2:
1631 // A class shall not be defined in a friend declaration.
Richard Smith0f8ee222012-01-10 01:33:14 +00001632 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
Douglas Gregor3dad8422009-09-26 06:47:28 +00001633 << SourceRange(DS.getFriendSpecLoc());
1634
1635 // Skip everything up to the semicolon, so that this looks like a proper
1636 // friend class (or template thereof) declaration.
Alexey Bataevee6507d2013-11-18 08:17:37 +00001637 SkipUntil(tok::semi, StopBeforeMatch);
John McCallfaf5fb42010-08-26 23:41:50 +00001638 TUK = Sema::TUK_Friend;
Douglas Gregor3dad8422009-09-26 06:47:28 +00001639 } else {
1640 // Okay, this is a class definition.
John McCallfaf5fb42010-08-26 23:41:50 +00001641 TUK = Sema::TUK_Definition;
Douglas Gregor3dad8422009-09-26 06:47:28 +00001642 }
Richard Smith434516c2013-02-22 06:46:23 +00001643 } else if (isCXX11FinalKeyword() && (NextToken().is(tok::l_square) ||
1644 NextToken().is(tok::kw_alignas))) {
Michael Han9407e502012-11-26 22:54:45 +00001645 // We can't tell if this is a definition or reference
1646 // until we skipped the 'final' and C++11 attribute specifiers.
1647 TentativeParsingAction PA(*this);
1648
1649 // Skip the 'final' keyword.
1650 ConsumeToken();
1651
1652 // Skip C++11 attribute specifiers.
1653 while (true) {
1654 if (Tok.is(tok::l_square) && NextToken().is(tok::l_square)) {
1655 ConsumeBracket();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001656 if (!SkipUntil(tok::r_square, StopAtSemi))
Michael Han9407e502012-11-26 22:54:45 +00001657 break;
Richard Smith434516c2013-02-22 06:46:23 +00001658 } else if (Tok.is(tok::kw_alignas) && NextToken().is(tok::l_paren)) {
Michael Han9407e502012-11-26 22:54:45 +00001659 ConsumeToken();
1660 ConsumeParen();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001661 if (!SkipUntil(tok::r_paren, StopAtSemi))
Michael Han9407e502012-11-26 22:54:45 +00001662 break;
1663 } else {
1664 break;
1665 }
1666 }
1667
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001668 if (Tok.isOneOf(tok::l_brace, tok::colon))
Michael Han9407e502012-11-26 22:54:45 +00001669 TUK = Sema::TUK_Definition;
1670 else
1671 TUK = Sema::TUK_Reference;
1672
1673 PA.Revert();
Richard Smith649c7b062014-01-08 00:56:48 +00001674 } else if (!isTypeSpecifier(DSC) &&
Richard Smith369b9f92012-06-25 21:37:02 +00001675 (Tok.is(tok::semi) ||
Richard Smith200f47c2012-07-02 19:14:01 +00001676 (Tok.isAtStartOfLine() && !isValidAfterTypeSpecifier(false)))) {
John McCallfaf5fb42010-08-26 23:41:50 +00001677 TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
Joao Matose9a3ed42012-08-31 22:18:20 +00001678 if (Tok.isNot(tok::semi)) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001679 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
Joao Matose9a3ed42012-08-31 22:18:20 +00001680 // A semicolon was missing after this declaration. Diagnose and recover.
Alp Toker383d2c42014-01-01 03:08:43 +00001681 ExpectAndConsume(tok::semi, diag::err_expected_after,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001682 DeclSpec::getSpecifierName(TagType, PPol));
Joao Matose9a3ed42012-08-31 22:18:20 +00001683 PP.EnterToken(Tok);
1684 Tok.setKind(tok::semi);
1685 }
Richard Smith369b9f92012-06-25 21:37:02 +00001686 } else
John McCallfaf5fb42010-08-26 23:41:50 +00001687 TUK = Sema::TUK_Reference;
Douglas Gregor556877c2008-04-13 21:30:24 +00001688
Michael Han9407e502012-11-26 22:54:45 +00001689 // Forbid misplaced attributes. In cases of a reference, we pass attributes
1690 // to caller to handle.
Michael Han309af292013-01-07 16:57:11 +00001691 if (TUK != Sema::TUK_Reference) {
1692 // If this is not a reference, then the only possible
1693 // valid place for C++11 attributes to appear here
1694 // is between class-key and class-name. If there are
1695 // any attributes after class-name, we try a fixit to move
1696 // them to the right place.
1697 SourceRange AttrRange = Attributes.Range;
1698 if (AttrRange.isValid()) {
1699 Diag(AttrRange.getBegin(), diag::err_attributes_not_allowed)
1700 << AttrRange
1701 << FixItHint::CreateInsertionFromRange(AttrFixitLoc,
1702 CharSourceRange(AttrRange, true))
1703 << FixItHint::CreateRemoval(AttrRange);
1704
1705 // Recover by adding misplaced attributes to the attribute list
1706 // of the class so they can be applied on the class later.
1707 attrs.takeAllFrom(Attributes);
1708 }
1709 }
Michael Han9407e502012-11-26 22:54:45 +00001710
John McCall6347b682012-05-07 06:16:58 +00001711 // If this is an elaborated type specifier, and we delayed
1712 // diagnostics before, just merge them into the current pool.
1713 if (shouldDelayDiagsInTag) {
1714 diagsFromTag.done();
1715 if (TUK == Sema::TUK_Reference)
1716 diagsFromTag.redelay();
1717 }
1718
John McCall413021a2010-07-30 06:26:29 +00001719 if (!Name && !TemplateId && (DS.getTypeSpecType() == DeclSpec::TST_error ||
John McCallfaf5fb42010-08-26 23:41:50 +00001720 TUK != Sema::TUK_Definition)) {
John McCall413021a2010-07-30 06:26:29 +00001721 if (DS.getTypeSpecType() != DeclSpec::TST_error) {
1722 // We have a declaration or reference to an anonymous class.
1723 Diag(StartLoc, diag::err_anon_type_definition)
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001724 << DeclSpec::getSpecifierName(TagType, Policy);
John McCall413021a2010-07-30 06:26:29 +00001725 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001726
David Majnemer3252fd02013-12-05 01:36:53 +00001727 // If we are parsing a definition and stop at a base-clause, continue on
1728 // until the semicolon. Continuing from the comma will just trick us into
1729 // thinking we are seeing a variable declaration.
1730 if (TUK == Sema::TUK_Definition && Tok.is(tok::colon))
1731 SkipUntil(tok::semi, StopBeforeMatch);
1732 else
1733 SkipUntil(tok::comma, StopAtSemi);
Douglas Gregor556877c2008-04-13 21:30:24 +00001734 return;
1735 }
1736
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001737 // Create the tag portion of the class or class template.
John McCall48871652010-08-21 09:40:31 +00001738 DeclResult TagOrTempResult = true; // invalid
1739 TypeResult TypeResult = true; // invalid
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001740
Douglas Gregord6ab8742009-05-28 23:31:59 +00001741 bool Owned = false;
Richard Smithd9ba2242015-05-07 03:54:19 +00001742 Sema::SkipBodyInfo SkipBody;
John McCall06f6fe8d2009-09-04 01:14:41 +00001743 if (TemplateId) {
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001744 // Explicit specialization, class template partial specialization,
1745 // or explicit instantiation.
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00001746 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregor7f741122009-02-25 19:37:18 +00001747 TemplateId->NumArgs);
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001748 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
John McCallfaf5fb42010-08-26 23:41:50 +00001749 TUK == Sema::TUK_Declaration) {
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001750 // This is an explicit instantiation of a class template.
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001751 ProhibitAttributes(attrs);
1752
Erich Keanec480f302018-07-12 21:09:05 +00001753 TagOrTempResult = Actions.ActOnExplicitInstantiation(
1754 getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc,
1755 TagType, StartLoc, SS, TemplateId->Template,
1756 TemplateId->TemplateNameLoc, TemplateId->LAngleLoc, TemplateArgsPtr,
1757 TemplateId->RAngleLoc, attrs);
John McCallb7c5c272010-04-14 00:24:33 +00001758
Erich Keanec480f302018-07-12 21:09:05 +00001759 // Friend template-ids are treated as references unless
1760 // they have template headers, in which case they're ill-formed
1761 // (FIXME: "template <class T> friend class A<T>::B<int>;").
1762 // We diagnose this error in ActOnClassTemplateSpecialization.
John McCallfaf5fb42010-08-26 23:41:50 +00001763 } else if (TUK == Sema::TUK_Reference ||
1764 (TUK == Sema::TUK_Friend &&
John McCallb7c5c272010-04-14 00:24:33 +00001765 TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate)) {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001766 ProhibitAttributes(attrs);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00001767 TypeResult = Actions.ActOnTagTemplateIdType(TUK, TagType, StartLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00001768 TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00001769 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00001770 TemplateId->Template,
1771 TemplateId->TemplateNameLoc,
1772 TemplateId->LAngleLoc,
1773 TemplateArgsPtr,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00001774 TemplateId->RAngleLoc);
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001775 } else {
1776 // This is an explicit specialization or a class template
1777 // partial specialization.
1778 TemplateParameterLists FakedParamLists;
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001779 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1780 // This looks like an explicit instantiation, because we have
1781 // something like
1782 //
1783 // template class Foo<X>
1784 //
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001785 // but it actually has a definition. Most likely, this was
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001786 // meant to be an explicit specialization, but the user forgot
1787 // the '<>' after 'template'.
Richard Smith003c5e12013-11-08 19:03:29 +00001788 // It this is friend declaration however, since it cannot have a
1789 // template header, it is most likely that the user meant to
1790 // remove the 'template' keyword.
Larisse Voufob9bbaba2013-06-22 13:56:11 +00001791 assert((TUK == Sema::TUK_Definition || TUK == Sema::TUK_Friend) &&
Richard Smith003c5e12013-11-08 19:03:29 +00001792 "Expected a definition here");
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001793
Richard Smith003c5e12013-11-08 19:03:29 +00001794 if (TUK == Sema::TUK_Friend) {
1795 Diag(DS.getFriendSpecLoc(), diag::err_friend_explicit_instantiation);
Craig Topper161e4db2014-05-21 06:02:52 +00001796 TemplateParams = nullptr;
Richard Smith003c5e12013-11-08 19:03:29 +00001797 } else {
1798 SourceLocation LAngleLoc =
1799 PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
1800 Diag(TemplateId->TemplateNameLoc,
1801 diag::err_explicit_instantiation_with_definition)
1802 << SourceRange(TemplateInfo.TemplateLoc)
1803 << FixItHint::CreateInsertion(LAngleLoc, "<>");
1804
1805 // Create a fake template parameter list that contains only
1806 // "template<>", so that we treat this construct as a class
1807 // template specialization.
1808 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
Craig Topper96225a52015-12-24 23:58:25 +00001809 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
Hubert Tongf608c052016-04-29 18:05:37 +00001810 LAngleLoc, nullptr));
Richard Smith003c5e12013-11-08 19:03:29 +00001811 TemplateParams = &FakedParamLists;
1812 }
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001813 }
1814
1815 // Build the class template specialization.
Richard Smith4b55a9c2014-04-17 03:29:33 +00001816 TagOrTempResult = Actions.ActOnClassTemplateSpecialization(
1817 getCurScope(), TagType, TUK, StartLoc, DS.getModulePrivateSpecLoc(),
Erich Keanec480f302018-07-12 21:09:05 +00001818 *TemplateId, attrs,
Craig Topper161e4db2014-05-21 06:02:52 +00001819 MultiTemplateParamsArg(TemplateParams ? &(*TemplateParams)[0]
1820 : nullptr,
Richard Smithc7e6ff02015-05-18 20:36:47 +00001821 TemplateParams ? TemplateParams->size() : 0),
1822 &SkipBody);
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001823 }
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001824 } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
John McCallfaf5fb42010-08-26 23:41:50 +00001825 TUK == Sema::TUK_Declaration) {
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001826 // Explicit instantiation of a member of a class template
1827 // specialization, e.g.,
1828 //
1829 // template struct Outer<int>::Inner;
1830 //
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001831 ProhibitAttributes(attrs);
1832
Erich Keanec480f302018-07-12 21:09:05 +00001833 TagOrTempResult = Actions.ActOnExplicitInstantiation(
1834 getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc,
1835 TagType, StartLoc, SS, Name, NameLoc, attrs);
John McCallace48cd2010-10-19 01:40:49 +00001836 } else if (TUK == Sema::TUK_Friend &&
1837 TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate) {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001838 ProhibitAttributes(attrs);
1839
Erich Keanec480f302018-07-12 21:09:05 +00001840 TagOrTempResult = Actions.ActOnTemplatedFriendTag(
1841 getCurScope(), DS.getFriendSpecLoc(), TagType, StartLoc, SS, Name,
1842 NameLoc, attrs,
1843 MultiTemplateParamsArg(TemplateParams ? &(*TemplateParams)[0] : nullptr,
1844 TemplateParams ? TemplateParams->size() : 0));
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001845 } else {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001846 if (TUK != Sema::TUK_Declaration && TUK != Sema::TUK_Definition)
1847 ProhibitAttributes(attrs);
Richard Smith003c5e12013-11-08 19:03:29 +00001848
Larisse Voufo725de3e2013-06-21 00:08:46 +00001849 if (TUK == Sema::TUK_Definition &&
1850 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1851 // If the declarator-id is not a template-id, issue a diagnostic and
1852 // recover by ignoring the 'template' keyword.
1853 Diag(Tok, diag::err_template_defn_explicit_instantiation)
1854 << 1 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
Craig Topper161e4db2014-05-21 06:02:52 +00001855 TemplateParams = nullptr;
Larisse Voufo725de3e2013-06-21 00:08:46 +00001856 }
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001857
John McCall7f41d982009-09-11 04:59:25 +00001858 bool IsDependent = false;
1859
John McCall32723e92010-10-19 18:40:57 +00001860 // Don't pass down template parameter lists if this is just a tag
1861 // reference. For example, we don't need the template parameters here:
1862 // template <class T> class A *makeA(T t);
1863 MultiTemplateParamsArg TParams;
1864 if (TUK != Sema::TUK_Reference && TemplateParams)
1865 TParams =
1866 MultiTemplateParamsArg(&(*TemplateParams)[0], TemplateParams->size());
1867
Nico Weber32a0fc72016-09-03 03:01:32 +00001868 stripTypeAttributesOffDeclSpec(attrs, DS, TUK);
David Majnemer936b4112015-04-19 07:53:29 +00001869
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001870 // Declaration or definition of a class type
Faisal Vali7db85c52017-12-31 00:06:40 +00001871 TagOrTempResult = Actions.ActOnTag(
Erich Keanec480f302018-07-12 21:09:05 +00001872 getCurScope(), TagType, TUK, StartLoc, SS, Name, NameLoc, attrs, AS,
1873 DS.getModulePrivateSpecLoc(), TParams, Owned, IsDependent,
1874 SourceLocation(), false, clang::TypeResult(),
Faisal Vali7db85c52017-12-31 00:06:40 +00001875 DSC == DeclSpecContext::DSC_type_specifier,
1876 DSC == DeclSpecContext::DSC_template_param ||
1877 DSC == DeclSpecContext::DSC_template_type_arg,
1878 &SkipBody);
John McCall7f41d982009-09-11 04:59:25 +00001879
1880 // If ActOnTag said the type was dependent, try again with the
1881 // less common call.
John McCallace48cd2010-10-19 01:40:49 +00001882 if (IsDependent) {
1883 assert(TUK == Sema::TUK_Reference || TUK == Sema::TUK_Friend);
Douglas Gregor0be31a22010-07-02 17:43:08 +00001884 TypeResult = Actions.ActOnDependentTag(getCurScope(), TagType, TUK,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001885 SS, Name, StartLoc, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +00001886 }
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001887 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001888
Douglas Gregor556877c2008-04-13 21:30:24 +00001889 // If there is a body, parse it and inform the actions module.
John McCallfaf5fb42010-08-26 23:41:50 +00001890 if (TUK == Sema::TUK_Definition) {
John McCall2d814c32009-12-19 21:48:58 +00001891 assert(Tok.is(tok::l_brace) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00001892 (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
Richard Smith89645bc2013-01-02 12:01:23 +00001893 isCXX11FinalKeyword());
Richard Smithd9ba2242015-05-07 03:54:19 +00001894 if (SkipBody.ShouldSkip)
Richard Smith65ebb4a2015-03-26 04:09:53 +00001895 SkipCXXMemberSpecification(StartLoc, AttrFixitLoc, TagType,
1896 TagOrTempResult.get());
1897 else if (getLangOpts().CPlusPlus)
Michael Han309af292013-01-07 16:57:11 +00001898 ParseCXXMemberSpecification(StartLoc, AttrFixitLoc, attrs, TagType,
1899 TagOrTempResult.get());
Bruno Cardoso Lopesdf0ee342017-07-01 00:06:47 +00001900 else {
1901 Decl *D =
1902 SkipBody.CheckSameAsPrevious ? SkipBody.New : TagOrTempResult.get();
1903 // Parse the definition body.
1904 ParseStructUnionBody(StartLoc, TagType, D);
1905 if (SkipBody.CheckSameAsPrevious &&
1906 !Actions.ActOnDuplicateDefinition(DS, TagOrTempResult.get(),
1907 SkipBody)) {
1908 DS.SetTypeSpecError();
1909 return;
1910 }
1911 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001912 }
1913
Erich Keane2fe684b2017-02-28 20:44:39 +00001914 if (!TagOrTempResult.isInvalid())
Hiroshi Inoue939d9322017-06-30 05:40:31 +00001915 // Delayed processing of attributes.
Erich Keanec480f302018-07-12 21:09:05 +00001916 Actions.ProcessDeclAttributeDelayed(TagOrTempResult.get(), attrs);
Erich Keane2fe684b2017-02-28 20:44:39 +00001917
Craig Topper161e4db2014-05-21 06:02:52 +00001918 const char *PrevSpec = nullptr;
John McCallba7bf592010-08-24 05:47:05 +00001919 unsigned DiagID;
1920 bool Result;
John McCall7f41d982009-09-11 04:59:25 +00001921 if (!TypeResult.isInvalid()) {
Abramo Bagnara9875a3c2011-03-16 20:16:18 +00001922 Result = DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
1923 NameLoc.isValid() ? NameLoc : StartLoc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001924 PrevSpec, DiagID, TypeResult.get(), Policy);
John McCall7f41d982009-09-11 04:59:25 +00001925 } else if (!TagOrTempResult.isInvalid()) {
Abramo Bagnara9875a3c2011-03-16 20:16:18 +00001926 Result = DS.SetTypeSpecType(TagType, StartLoc,
1927 NameLoc.isValid() ? NameLoc : StartLoc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001928 PrevSpec, DiagID, TagOrTempResult.get(), Owned,
1929 Policy);
John McCall7f41d982009-09-11 04:59:25 +00001930 } else {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001931 DS.SetTypeSpecError();
Anders Carlssonf83c9fa2009-05-11 22:27:47 +00001932 return;
1933 }
Mike Stump11289f42009-09-09 15:08:12 +00001934
John McCallba7bf592010-08-24 05:47:05 +00001935 if (Result)
John McCall49bfce42009-08-03 20:12:06 +00001936 Diag(StartLoc, DiagID) << PrevSpec;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001937
Chris Lattnercf251412010-02-02 01:23:29 +00001938 // At this point, we've successfully parsed a class-specifier in 'definition'
1939 // form (e.g. "struct foo { int x; }". While we could just return here, we're
1940 // going to look at what comes after it to improve error recovery. If an
1941 // impossible token occurs next, we assume that the programmer forgot a ; at
1942 // the end of the declaration and recover that way.
1943 //
Richard Smith369b9f92012-06-25 21:37:02 +00001944 // Also enforce C++ [temp]p3:
1945 // In a template-declaration which defines a class, no declarator
1946 // is permitted.
Richard Smith843f18f2014-08-13 02:13:15 +00001947 //
1948 // After a type-specifier, we don't expect a semicolon. This only happens in
1949 // C, since definitions are not permitted in this context in C++.
Joao Matose9a3ed42012-08-31 22:18:20 +00001950 if (TUK == Sema::TUK_Definition &&
Richard Smith843f18f2014-08-13 02:13:15 +00001951 (getLangOpts().CPlusPlus || !isTypeSpecifier(DSC)) &&
Joao Matose9a3ed42012-08-31 22:18:20 +00001952 (TemplateInfo.Kind || !isValidAfterTypeSpecifier(false))) {
Argyrios Kyrtzidise6f69132012-12-17 20:10:43 +00001953 if (Tok.isNot(tok::semi)) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001954 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
Alp Toker383d2c42014-01-01 03:08:43 +00001955 ExpectAndConsume(tok::semi, diag::err_expected_after,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001956 DeclSpec::getSpecifierName(TagType, PPol));
Argyrios Kyrtzidise6f69132012-12-17 20:10:43 +00001957 // Push this token back into the preprocessor and change our current token
1958 // to ';' so that the rest of the code recovers as though there were an
1959 // ';' after the definition.
1960 PP.EnterToken(Tok);
1961 Tok.setKind(tok::semi);
1962 }
Chris Lattnercf251412010-02-02 01:23:29 +00001963 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001964}
1965
Mike Stump11289f42009-09-09 15:08:12 +00001966/// ParseBaseClause - Parse the base-clause of a C++ class [C++ class.derived].
Douglas Gregor556877c2008-04-13 21:30:24 +00001967///
1968/// base-clause : [C++ class.derived]
1969/// ':' base-specifier-list
1970/// base-specifier-list:
1971/// base-specifier '...'[opt]
1972/// base-specifier-list ',' base-specifier '...'[opt]
John McCall48871652010-08-21 09:40:31 +00001973void Parser::ParseBaseClause(Decl *ClassDecl) {
Douglas Gregor556877c2008-04-13 21:30:24 +00001974 assert(Tok.is(tok::colon) && "Not a base clause");
1975 ConsumeToken();
1976
Douglas Gregor29a92472008-10-22 17:49:05 +00001977 // Build up an array of parsed base specifiers.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001978 SmallVector<CXXBaseSpecifier *, 8> BaseInfo;
Douglas Gregor29a92472008-10-22 17:49:05 +00001979
Douglas Gregor556877c2008-04-13 21:30:24 +00001980 while (true) {
1981 // Parse a base-specifier.
Douglas Gregor29a92472008-10-22 17:49:05 +00001982 BaseResult Result = ParseBaseSpecifier(ClassDecl);
Douglas Gregorf8298252009-01-26 22:44:13 +00001983 if (Result.isInvalid()) {
Douglas Gregor556877c2008-04-13 21:30:24 +00001984 // Skip the rest of this base specifier, up until the comma or
1985 // opening brace.
Alexey Bataevee6507d2013-11-18 08:17:37 +00001986 SkipUntil(tok::comma, tok::l_brace, StopAtSemi | StopBeforeMatch);
Douglas Gregor29a92472008-10-22 17:49:05 +00001987 } else {
1988 // Add this to our array of base specifiers.
Douglas Gregorf8298252009-01-26 22:44:13 +00001989 BaseInfo.push_back(Result.get());
Douglas Gregor556877c2008-04-13 21:30:24 +00001990 }
1991
1992 // If the next token is a comma, consume it and keep reading
1993 // base-specifiers.
Alp Toker97650562014-01-10 11:19:30 +00001994 if (!TryConsumeToken(tok::comma))
1995 break;
Douglas Gregor556877c2008-04-13 21:30:24 +00001996 }
Douglas Gregor29a92472008-10-22 17:49:05 +00001997
1998 // Attach the base specifiers
Craig Topperaa700cb2015-12-27 21:55:19 +00001999 Actions.ActOnBaseSpecifiers(ClassDecl, BaseInfo);
Douglas Gregor556877c2008-04-13 21:30:24 +00002000}
2001
2002/// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is
2003/// one entry in the base class list of a class specifier, for example:
2004/// class foo : public bar, virtual private baz {
2005/// 'public bar' and 'virtual private baz' are each base-specifiers.
2006///
2007/// base-specifier: [C++ class.derived]
Richard Smith4c96e992013-02-19 23:47:15 +00002008/// attribute-specifier-seq[opt] base-type-specifier
2009/// attribute-specifier-seq[opt] 'virtual' access-specifier[opt]
2010/// base-type-specifier
2011/// attribute-specifier-seq[opt] access-specifier 'virtual'[opt]
2012/// base-type-specifier
Craig Topper9ad7e262014-10-31 06:57:07 +00002013BaseResult Parser::ParseBaseSpecifier(Decl *ClassDecl) {
Douglas Gregor556877c2008-04-13 21:30:24 +00002014 bool IsVirtual = false;
2015 SourceLocation StartLoc = Tok.getLocation();
2016
Richard Smith4c96e992013-02-19 23:47:15 +00002017 ParsedAttributesWithRange Attributes(AttrFactory);
2018 MaybeParseCXX11Attributes(Attributes);
2019
Douglas Gregor556877c2008-04-13 21:30:24 +00002020 // Parse the 'virtual' keyword.
Alp Toker97650562014-01-10 11:19:30 +00002021 if (TryConsumeToken(tok::kw_virtual))
Douglas Gregor556877c2008-04-13 21:30:24 +00002022 IsVirtual = true;
Douglas Gregor556877c2008-04-13 21:30:24 +00002023
Richard Smith4c96e992013-02-19 23:47:15 +00002024 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2025
Douglas Gregor556877c2008-04-13 21:30:24 +00002026 // Parse an (optional) access specifier.
2027 AccessSpecifier Access = getAccessSpecifierIfPresent();
John McCall553c0792010-01-23 00:46:32 +00002028 if (Access != AS_none)
Douglas Gregor556877c2008-04-13 21:30:24 +00002029 ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +00002030
Richard Smith4c96e992013-02-19 23:47:15 +00002031 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2032
Douglas Gregor556877c2008-04-13 21:30:24 +00002033 // Parse the 'virtual' keyword (again!), in case it came after the
2034 // access specifier.
2035 if (Tok.is(tok::kw_virtual)) {
2036 SourceLocation VirtualLoc = ConsumeToken();
2037 if (IsVirtual) {
2038 // Complain about duplicate 'virtual'
Chris Lattner6d29c102008-11-18 07:48:38 +00002039 Diag(VirtualLoc, diag::err_dup_virtual)
Douglas Gregora771f462010-03-31 17:46:05 +00002040 << FixItHint::CreateRemoval(VirtualLoc);
Douglas Gregor556877c2008-04-13 21:30:24 +00002041 }
2042
2043 IsVirtual = true;
2044 }
2045
Richard Smith4c96e992013-02-19 23:47:15 +00002046 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2047
Douglas Gregor831c93f2008-11-05 20:51:48 +00002048 // Parse the class-name.
David Majnemer51fd8a02015-07-22 23:46:18 +00002049
2050 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
2051 // implementation for VS2013 uses _Atomic as an identifier for one of the
2052 // classes in <atomic>. Treat '_Atomic' to be an identifier when we are
2053 // parsing the class-name for a base specifier.
2054 if (getLangOpts().MSVCCompat && Tok.is(tok::kw__Atomic) &&
2055 NextToken().is(tok::less))
2056 Tok.setKind(tok::identifier);
2057
Douglas Gregord54dfb82009-02-25 23:52:28 +00002058 SourceLocation EndLocation;
David Blaikie1cd50022011-10-25 17:10:12 +00002059 SourceLocation BaseLoc;
2060 TypeResult BaseType = ParseBaseTypeSpecifier(BaseLoc, EndLocation);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00002061 if (BaseType.isInvalid())
Douglas Gregor831c93f2008-11-05 20:51:48 +00002062 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002063
Fangrui Song6907ce22018-07-30 19:24:48 +00002064 // Parse the optional ellipsis (for a pack expansion). The ellipsis is
Douglas Gregor752a5952011-01-03 22:36:02 +00002065 // actually part of the base-specifier-list grammar productions, but we
2066 // parse it here for convenience.
2067 SourceLocation EllipsisLoc;
Alp Toker97650562014-01-10 11:19:30 +00002068 TryConsumeToken(tok::ellipsis, EllipsisLoc);
2069
Mike Stump11289f42009-09-09 15:08:12 +00002070 // Find the complete source range for the base-specifier.
Douglas Gregord54dfb82009-02-25 23:52:28 +00002071 SourceRange Range(StartLoc, EndLocation);
Mike Stump11289f42009-09-09 15:08:12 +00002072
Douglas Gregor556877c2008-04-13 21:30:24 +00002073 // Notify semantic analysis that we have parsed a complete
2074 // base-specifier.
Richard Smith4c96e992013-02-19 23:47:15 +00002075 return Actions.ActOnBaseSpecifier(ClassDecl, Range, Attributes, IsVirtual,
2076 Access, BaseType.get(), BaseLoc,
2077 EllipsisLoc);
Douglas Gregor556877c2008-04-13 21:30:24 +00002078}
2079
2080/// getAccessSpecifierIfPresent - Determine whether the next token is
2081/// a C++ access-specifier.
2082///
2083/// access-specifier: [C++ class.derived]
2084/// 'private'
2085/// 'protected'
2086/// 'public'
Mike Stump11289f42009-09-09 15:08:12 +00002087AccessSpecifier Parser::getAccessSpecifierIfPresent() const {
Douglas Gregor556877c2008-04-13 21:30:24 +00002088 switch (Tok.getKind()) {
2089 default: return AS_none;
2090 case tok::kw_private: return AS_private;
2091 case tok::kw_protected: return AS_protected;
2092 case tok::kw_public: return AS_public;
2093 }
2094}
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002095
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002096/// If the given declarator has any parts for which parsing has to be
Richard Smith0b3a4622014-11-13 20:01:57 +00002097/// delayed, e.g., default arguments or an exception-specification, create a
2098/// late-parsed method declaration record to handle the parsing at the end of
2099/// the class definition.
Douglas Gregor433e0532012-04-16 18:27:27 +00002100void Parser::HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
2101 Decl *ThisDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00002102 DeclaratorChunk::FunctionTypeInfo &FTI
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002103 = DeclaratorInfo.getFunctionTypeInfo();
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002104 // If there was a late-parsed exception-specification, we'll need a
2105 // late parse
2106 bool NeedLateParse = FTI.getExceptionSpecType() == EST_Unparsed;
Douglas Gregor433e0532012-04-16 18:27:27 +00002107
Nathan Sidwell5bb231c2015-02-19 14:03:22 +00002108 if (!NeedLateParse) {
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002109 // Look ahead to see if there are any default args
Nathan Sidwell5bb231c2015-02-19 14:03:22 +00002110 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx) {
2111 auto Param = cast<ParmVarDecl>(FTI.Params[ParamIdx].Param);
2112 if (Param->hasUnparsedDefaultArg()) {
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002113 NeedLateParse = true;
2114 break;
2115 }
Nathan Sidwell5bb231c2015-02-19 14:03:22 +00002116 }
2117 }
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002118
2119 if (NeedLateParse) {
Richard Smith0b3a4622014-11-13 20:01:57 +00002120 // Push this method onto the stack of late-parsed method
2121 // declarations.
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002122 auto LateMethod = new LateParsedMethodDeclaration(this, ThisDecl);
Richard Smith0b3a4622014-11-13 20:01:57 +00002123 getCurrentClass().LateParsedDeclarations.push_back(LateMethod);
2124 LateMethod->TemplateScope = getCurScope()->isTemplateParamScope();
2125
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002126 // Stash the exception-specification tokens in the late-pased method.
Richard Smith0b3a4622014-11-13 20:01:57 +00002127 LateMethod->ExceptionSpecTokens = FTI.ExceptionSpecTokens;
Hans Wennborgdcfba332015-10-06 23:40:43 +00002128 FTI.ExceptionSpecTokens = nullptr;
Richard Smith0b3a4622014-11-13 20:01:57 +00002129
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002130 // Push tokens for each parameter. Those that do not have
2131 // defaults will be NULL.
Richard Smith0b3a4622014-11-13 20:01:57 +00002132 LateMethod->DefaultArgs.reserve(FTI.NumParams);
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002133 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx)
Alp Tokerc5350722014-02-26 22:27:52 +00002134 LateMethod->DefaultArgs.push_back(LateParsedDefaultArgument(
Malcolm Parsonsca9d8342016-11-17 21:00:09 +00002135 FTI.Params[ParamIdx].Param,
2136 std::move(FTI.Params[ParamIdx].DefaultArgTokens)));
Eli Friedman3af2a772009-07-22 21:45:50 +00002137 }
2138}
2139
Richard Smith89645bc2013-01-02 12:01:23 +00002140/// isCXX11VirtSpecifier - Determine whether the given token is a C++11
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002141/// virt-specifier.
2142///
2143/// virt-specifier:
2144/// override
2145/// final
Andrey Bokhanko276055b2016-07-29 10:42:48 +00002146/// __final
Richard Smith89645bc2013-01-02 12:01:23 +00002147VirtSpecifiers::Specifier Parser::isCXX11VirtSpecifier(const Token &Tok) const {
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002148 if (!getLangOpts().CPlusPlus || Tok.isNot(tok::identifier))
Anders Carlsson4b63d0e2011-01-22 16:56:46 +00002149 return VirtSpecifiers::VS_None;
2150
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002151 IdentifierInfo *II = Tok.getIdentifierInfo();
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002152
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002153 // Initialize the contextual keywords.
2154 if (!Ident_final) {
2155 Ident_final = &PP.getIdentifierTable().get("final");
Andrey Bokhanko276055b2016-07-29 10:42:48 +00002156 if (getLangOpts().GNUKeywords)
2157 Ident_GNU_final = &PP.getIdentifierTable().get("__final");
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002158 if (getLangOpts().MicrosoftExt)
2159 Ident_sealed = &PP.getIdentifierTable().get("sealed");
2160 Ident_override = &PP.getIdentifierTable().get("override");
Anders Carlsson56104902011-01-17 03:05:47 +00002161 }
2162
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002163 if (II == Ident_override)
2164 return VirtSpecifiers::VS_Override;
2165
2166 if (II == Ident_sealed)
2167 return VirtSpecifiers::VS_Sealed;
2168
2169 if (II == Ident_final)
2170 return VirtSpecifiers::VS_Final;
2171
Andrey Bokhanko276055b2016-07-29 10:42:48 +00002172 if (II == Ident_GNU_final)
2173 return VirtSpecifiers::VS_GNU_Final;
2174
Anders Carlsson56104902011-01-17 03:05:47 +00002175 return VirtSpecifiers::VS_None;
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002176}
2177
Richard Smith89645bc2013-01-02 12:01:23 +00002178/// ParseOptionalCXX11VirtSpecifierSeq - Parse a virt-specifier-seq.
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002179///
2180/// virt-specifier-seq:
2181/// virt-specifier
2182/// virt-specifier-seq virt-specifier
Richard Smith89645bc2013-01-02 12:01:23 +00002183void Parser::ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS,
Richard Smith3d1a94c2014-08-12 00:22:39 +00002184 bool IsInterface,
2185 SourceLocation FriendLoc) {
Anders Carlsson56104902011-01-17 03:05:47 +00002186 while (true) {
Richard Smith89645bc2013-01-02 12:01:23 +00002187 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
Anders Carlsson56104902011-01-17 03:05:47 +00002188 if (Specifier == VirtSpecifiers::VS_None)
2189 return;
2190
Richard Smith3d1a94c2014-08-12 00:22:39 +00002191 if (FriendLoc.isValid()) {
2192 Diag(Tok.getLocation(), diag::err_friend_decl_spec)
2193 << VirtSpecifiers::getSpecifierName(Specifier)
2194 << FixItHint::CreateRemoval(Tok.getLocation())
2195 << SourceRange(FriendLoc, FriendLoc);
2196 ConsumeToken();
2197 continue;
2198 }
2199
Anders Carlsson56104902011-01-17 03:05:47 +00002200 // C++ [class.mem]p8:
2201 // A virt-specifier-seq shall contain at most one of each virt-specifier.
Craig Topper161e4db2014-05-21 06:02:52 +00002202 const char *PrevSpec = nullptr;
Anders Carlssonf2ca3892011-01-22 15:58:16 +00002203 if (VS.SetSpecifier(Specifier, Tok.getLocation(), PrevSpec))
Anders Carlsson56104902011-01-17 03:05:47 +00002204 Diag(Tok.getLocation(), diag::err_duplicate_virt_specifier)
2205 << PrevSpec
2206 << FixItHint::CreateRemoval(Tok.getLocation());
2207
David Majnemera5433082013-10-18 00:33:31 +00002208 if (IsInterface && (Specifier == VirtSpecifiers::VS_Final ||
2209 Specifier == VirtSpecifiers::VS_Sealed)) {
John McCalldb632ac2012-09-25 07:32:39 +00002210 Diag(Tok.getLocation(), diag::err_override_control_interface)
2211 << VirtSpecifiers::getSpecifierName(Specifier);
David Majnemera5433082013-10-18 00:33:31 +00002212 } else if (Specifier == VirtSpecifiers::VS_Sealed) {
2213 Diag(Tok.getLocation(), diag::ext_ms_sealed_keyword);
Andrey Bokhanko276055b2016-07-29 10:42:48 +00002214 } else if (Specifier == VirtSpecifiers::VS_GNU_Final) {
2215 Diag(Tok.getLocation(), diag::ext_warn_gnu_final);
John McCalldb632ac2012-09-25 07:32:39 +00002216 } else {
David Majnemera5433082013-10-18 00:33:31 +00002217 Diag(Tok.getLocation(),
2218 getLangOpts().CPlusPlus11
2219 ? diag::warn_cxx98_compat_override_control_keyword
2220 : diag::ext_override_control_keyword)
2221 << VirtSpecifiers::getSpecifierName(Specifier);
John McCalldb632ac2012-09-25 07:32:39 +00002222 }
Anders Carlsson56104902011-01-17 03:05:47 +00002223 ConsumeToken();
2224 }
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002225}
2226
Richard Smith89645bc2013-01-02 12:01:23 +00002227/// isCXX11FinalKeyword - Determine whether the next token is a C++11
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002228/// 'final' or Microsoft 'sealed' contextual keyword.
Richard Smith89645bc2013-01-02 12:01:23 +00002229bool Parser::isCXX11FinalKeyword() const {
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002230 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
2231 return Specifier == VirtSpecifiers::VS_Final ||
Fangrui Song6907ce22018-07-30 19:24:48 +00002232 Specifier == VirtSpecifiers::VS_GNU_Final ||
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002233 Specifier == VirtSpecifiers::VS_Sealed;
Anders Carlsson4b63d0e2011-01-22 16:56:46 +00002234}
2235
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002236/// Parse a C++ member-declarator up to, but not including, the optional
Richard Smith72553fc2014-01-23 23:53:27 +00002237/// brace-or-equal-initializer or pure-specifier.
Nico Weberd89e6f72015-01-16 19:34:13 +00002238bool Parser::ParseCXXMemberDeclaratorBeforeInitializer(
Richard Smith72553fc2014-01-23 23:53:27 +00002239 Declarator &DeclaratorInfo, VirtSpecifiers &VS, ExprResult &BitfieldSize,
2240 LateParsedAttrList &LateParsedAttrs) {
2241 // member-declarator:
2242 // declarator pure-specifier[opt]
2243 // declarator brace-or-equal-initializer[opt]
2244 // identifier[opt] ':' constant-expression
Serge Pavlov458ea762014-07-16 05:16:52 +00002245 if (Tok.isNot(tok::colon))
Richard Smith72553fc2014-01-23 23:53:27 +00002246 ParseDeclarator(DeclaratorInfo);
Richard Smith3d1a94c2014-08-12 00:22:39 +00002247 else
2248 DeclaratorInfo.SetIdentifier(nullptr, Tok.getLocation());
Richard Smith72553fc2014-01-23 23:53:27 +00002249
2250 if (!DeclaratorInfo.isFunctionDeclarator() && TryConsumeToken(tok::colon)) {
Richard Smith3d1a94c2014-08-12 00:22:39 +00002251 assert(DeclaratorInfo.isPastIdentifier() &&
2252 "don't know where identifier would go yet?");
Richard Smith72553fc2014-01-23 23:53:27 +00002253 BitfieldSize = ParseConstantExpression();
2254 if (BitfieldSize.isInvalid())
2255 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002256 } else {
Richard Smith3d1a94c2014-08-12 00:22:39 +00002257 ParseOptionalCXX11VirtSpecifierSeq(
2258 VS, getCurrentClass().IsInterface,
2259 DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002260 if (!VS.isUnset())
2261 MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo, VS);
2262 }
Richard Smith72553fc2014-01-23 23:53:27 +00002263
2264 // If a simple-asm-expr is present, parse it.
2265 if (Tok.is(tok::kw_asm)) {
2266 SourceLocation Loc;
2267 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
2268 if (AsmLabel.isInvalid())
2269 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2270
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002271 DeclaratorInfo.setAsmLabel(AsmLabel.get());
Richard Smith72553fc2014-01-23 23:53:27 +00002272 DeclaratorInfo.SetRangeEnd(Loc);
2273 }
2274
2275 // If attributes exist after the declarator, but before an '{', parse them.
2276 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
Richard Smith4b5a9492014-01-24 22:34:35 +00002277
2278 // For compatibility with code written to older Clang, also accept a
2279 // virt-specifier *after* the GNU attributes.
Aaron Ballman5d153e32014-08-04 17:03:51 +00002280 if (BitfieldSize.isUnset() && VS.isUnset()) {
Richard Smith3d1a94c2014-08-12 00:22:39 +00002281 ParseOptionalCXX11VirtSpecifierSeq(
2282 VS, getCurrentClass().IsInterface,
2283 DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
Aaron Ballman5d153e32014-08-04 17:03:51 +00002284 if (!VS.isUnset()) {
2285 // If we saw any GNU-style attributes that are known to GCC followed by a
2286 // virt-specifier, issue a GCC-compat warning.
Erich Keanee891aa92018-07-13 15:07:47 +00002287 for (const ParsedAttr &AL : DeclaratorInfo.getAttributes())
Erich Keanec480f302018-07-12 21:09:05 +00002288 if (AL.isKnownToGCC() && !AL.isCXX11Attribute())
2289 Diag(AL.getLoc(), diag::warn_gcc_attribute_location);
2290
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002291 MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo, VS);
Aaron Ballman5d153e32014-08-04 17:03:51 +00002292 }
2293 }
Nico Weberd89e6f72015-01-16 19:34:13 +00002294
2295 // If this has neither a name nor a bit width, something has gone seriously
2296 // wrong. Skip until the semi-colon or }.
2297 if (!DeclaratorInfo.hasName() && BitfieldSize.isUnset()) {
2298 // If so, skip until the semi-colon or a }.
2299 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2300 return true;
2301 }
2302 return false;
Richard Smith72553fc2014-01-23 23:53:27 +00002303}
2304
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002305/// Look for declaration specifiers possibly occurring after C++11
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002306/// virt-specifier-seq and diagnose them.
2307void Parser::MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(
2308 Declarator &D,
2309 VirtSpecifiers &VS) {
2310 DeclSpec DS(AttrFactory);
2311
2312 // GNU-style and C++11 attributes are not allowed here, but they will be
2313 // handled by the caller. Diagnose everything else.
Alex Lorenz8f4d3992017-02-13 23:19:40 +00002314 ParseTypeQualifierListOpt(
2315 DS, AR_NoAttributesParsed, false,
2316 /*IdentifierRequired=*/false, llvm::function_ref<void()>([&]() {
2317 Actions.CodeCompleteFunctionQualifiers(DS, D, &VS);
2318 }));
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002319 D.ExtendWithDeclSpec(DS);
2320
2321 if (D.isFunctionDeclarator()) {
Ehsan Akhgaric07d1e22015-03-25 00:53:33 +00002322 auto &Function = D.getFunctionTypeInfo();
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002323 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
2324 auto DeclSpecCheck = [&] (DeclSpec::TQ TypeQual,
2325 const char *FixItName,
2326 SourceLocation SpecLoc,
2327 unsigned* QualifierLoc) {
2328 FixItHint Insertion;
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002329 if (DS.getTypeQualifiers() & TypeQual) {
2330 if (!(Function.TypeQuals & TypeQual)) {
2331 std::string Name(FixItName);
2332 Name += " ";
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00002333 Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), Name);
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002334 Function.TypeQuals |= TypeQual;
2335 *QualifierLoc = SpecLoc.getRawEncoding();
2336 }
2337 Diag(SpecLoc, diag::err_declspec_after_virtspec)
2338 << FixItName
2339 << VirtSpecifiers::getSpecifierName(VS.getLastSpecifier())
2340 << FixItHint::CreateRemoval(SpecLoc)
2341 << Insertion;
2342 }
2343 };
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002344 DeclSpecCheck(DeclSpec::TQ_const, "const", DS.getConstSpecLoc(),
2345 &Function.ConstQualifierLoc);
2346 DeclSpecCheck(DeclSpec::TQ_volatile, "volatile", DS.getVolatileSpecLoc(),
2347 &Function.VolatileQualifierLoc);
2348 DeclSpecCheck(DeclSpec::TQ_restrict, "restrict", DS.getRestrictSpecLoc(),
2349 &Function.RestrictQualifierLoc);
2350 }
Ehsan Akhgaric07d1e22015-03-25 00:53:33 +00002351
2352 // Parse ref-qualifiers.
2353 bool RefQualifierIsLValueRef = true;
2354 SourceLocation RefQualifierLoc;
2355 if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc)) {
2356 const char *Name = (RefQualifierIsLValueRef ? "& " : "&& ");
2357 FixItHint Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), Name);
2358 Function.RefQualifierIsLValueRef = RefQualifierIsLValueRef;
2359 Function.RefQualifierLoc = RefQualifierLoc.getRawEncoding();
2360
2361 Diag(RefQualifierLoc, diag::err_declspec_after_virtspec)
2362 << (RefQualifierIsLValueRef ? "&" : "&&")
2363 << VirtSpecifiers::getSpecifierName(VS.getLastSpecifier())
2364 << FixItHint::CreateRemoval(RefQualifierLoc)
2365 << Insertion;
2366 D.SetRangeEnd(RefQualifierLoc);
2367 }
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002368 }
2369}
2370
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002371/// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration.
2372///
2373/// member-declaration:
2374/// decl-specifier-seq[opt] member-declarator-list[opt] ';'
2375/// function-definition ';'[opt]
2376/// ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO]
2377/// using-declaration [TODO]
Anders Carlssonf24fcff62009-03-11 16:27:10 +00002378/// [C++0x] static_assert-declaration
Anders Carlssondfbbdf62009-03-26 00:52:18 +00002379/// template-declaration
Chris Lattnerd19c1c02008-12-18 01:12:00 +00002380/// [GNU] '__extension__' member-declaration
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002381///
2382/// member-declarator-list:
2383/// member-declarator
2384/// member-declarator-list ',' member-declarator
2385///
2386/// member-declarator:
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002387/// declarator virt-specifier-seq[opt] pure-specifier[opt]
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002388/// declarator constant-initializer[opt]
Richard Smith938f40b2011-06-11 17:19:42 +00002389/// [C++11] declarator brace-or-equal-initializer[opt]
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002390/// identifier[opt] ':' constant-expression
2391///
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002392/// virt-specifier-seq:
2393/// virt-specifier
2394/// virt-specifier-seq virt-specifier
2395///
2396/// virt-specifier:
2397/// override
2398/// final
David Majnemera5433082013-10-18 00:33:31 +00002399/// [MS] sealed
Fangrui Song6907ce22018-07-30 19:24:48 +00002400///
Sebastian Redl42e92c42009-04-12 17:16:29 +00002401/// pure-specifier:
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002402/// '= 0'
2403///
2404/// constant-initializer:
2405/// '=' constant-expression
2406///
Alexey Bataev05c25d62015-07-31 08:42:25 +00002407Parser::DeclGroupPtrTy
2408Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS,
Erich Keanec480f302018-07-12 21:09:05 +00002409 ParsedAttributes &AccessAttrs,
John McCall796c2a52010-07-16 08:13:16 +00002410 const ParsedTemplateInfo &TemplateInfo,
2411 ParsingDeclRAIIObject *TemplateDiags) {
Douglas Gregor23c84762011-04-14 17:21:19 +00002412 if (Tok.is(tok::at)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002413 if (getLangOpts().ObjC1 && NextToken().isObjCAtKeyword(tok::objc_defs))
Douglas Gregor23c84762011-04-14 17:21:19 +00002414 Diag(Tok, diag::err_at_defs_cxx);
2415 else
2416 Diag(Tok, diag::err_at_in_class);
Richard Smithda35e962013-11-09 04:52:51 +00002417
Douglas Gregor23c84762011-04-14 17:21:19 +00002418 ConsumeToken();
Alexey Bataevee6507d2013-11-18 08:17:37 +00002419 SkipUntil(tok::r_brace, StopAtSemi);
David Blaikie0403cb12016-01-15 23:43:25 +00002420 return nullptr;
Douglas Gregor23c84762011-04-14 17:21:19 +00002421 }
Richard Smithda35e962013-11-09 04:52:51 +00002422
Serge Pavlov458ea762014-07-16 05:16:52 +00002423 // Turn on colon protection early, while parsing declspec, although there is
2424 // nothing to protect there. It prevents from false errors if error recovery
2425 // incorrectly determines where the declspec ends, as in the example:
2426 // struct A { enum class B { C }; };
2427 // const int C = 4;
2428 // struct D { A::B : C; };
2429 ColonProtectionRAIIObject X(*this);
2430
John McCalla0097262009-12-11 02:10:03 +00002431 // Access declarations.
Richard Smith45855df2012-05-09 08:23:23 +00002432 bool MalformedTypeSpec = false;
John McCalla0097262009-12-11 02:10:03 +00002433 if (!TemplateInfo.Kind &&
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002434 Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw___super)) {
Richard Smith45855df2012-05-09 08:23:23 +00002435 if (TryAnnotateCXXScopeToken())
2436 MalformedTypeSpec = true;
2437
2438 bool isAccessDecl;
2439 if (Tok.isNot(tok::annot_cxxscope))
2440 isAccessDecl = false;
2441 else if (NextToken().is(tok::identifier))
John McCalla0097262009-12-11 02:10:03 +00002442 isAccessDecl = GetLookAheadToken(2).is(tok::semi);
2443 else
2444 isAccessDecl = NextToken().is(tok::kw_operator);
2445
2446 if (isAccessDecl) {
2447 // Collect the scope specifier token we annotated earlier.
2448 CXXScopeSpec SS;
David Blaikieefdccaa2016-01-15 23:43:34 +00002449 ParseOptionalCXXScopeSpecifier(SS, nullptr,
Douglas Gregordf593fb2011-11-07 17:33:42 +00002450 /*EnteringContext=*/false);
John McCalla0097262009-12-11 02:10:03 +00002451
Nico Weberef03e702014-09-10 00:59:37 +00002452 if (SS.isInvalid()) {
2453 SkipUntil(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002454 return nullptr;
Nico Weberef03e702014-09-10 00:59:37 +00002455 }
2456
John McCalla0097262009-12-11 02:10:03 +00002457 // Try to parse an unqualified-id.
Abramo Bagnara7945c982012-01-27 09:46:47 +00002458 SourceLocation TemplateKWLoc;
John McCalla0097262009-12-11 02:10:03 +00002459 UnqualifiedId Name;
Richard Smith35845152017-02-07 01:37:30 +00002460 if (ParseUnqualifiedId(SS, false, true, true, false, nullptr,
Richard Smithc08b6932018-04-27 02:00:13 +00002461 &TemplateKWLoc, Name)) {
John McCalla0097262009-12-11 02:10:03 +00002462 SkipUntil(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002463 return nullptr;
John McCalla0097262009-12-11 02:10:03 +00002464 }
2465
2466 // TODO: recover from mistakenly-qualified operator declarations.
Alp Toker383d2c42014-01-01 03:08:43 +00002467 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
2468 "access declaration")) {
2469 SkipUntil(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002470 return nullptr;
Alp Toker383d2c42014-01-01 03:08:43 +00002471 }
John McCalla0097262009-12-11 02:10:03 +00002472
Richard Smithc08b6932018-04-27 02:00:13 +00002473 // FIXME: We should do something with the 'template' keyword here.
Alexey Bataev05c25d62015-07-31 08:42:25 +00002474 return DeclGroupPtrTy::make(DeclGroupRef(Actions.ActOnUsingDeclaration(
Richard Smith151c4562016-12-20 21:35:28 +00002475 getCurScope(), AS, /*UsingLoc*/ SourceLocation(),
2476 /*TypenameLoc*/ SourceLocation(), SS, Name,
Erich Keanec480f302018-07-12 21:09:05 +00002477 /*EllipsisLoc*/ SourceLocation(),
2478 /*AttrList*/ ParsedAttributesView())));
John McCalla0097262009-12-11 02:10:03 +00002479 }
2480 }
2481
Aaron Ballmane7c544d2014-08-04 20:28:35 +00002482 // static_assert-declaration. A templated static_assert declaration is
2483 // diagnosed in Parser::ParseSingleDeclarationAfterTemplate.
2484 if (!TemplateInfo.Kind &&
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002485 Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert)) {
Chris Lattner49836b42009-04-02 04:16:50 +00002486 SourceLocation DeclEnd;
Alexey Bataev05c25d62015-07-31 08:42:25 +00002487 return DeclGroupPtrTy::make(
2488 DeclGroupRef(ParseStaticAssertDeclaration(DeclEnd)));
Chris Lattner5bbb3c82009-03-29 16:50:03 +00002489 }
Mike Stump11289f42009-09-09 15:08:12 +00002490
Chris Lattner5bbb3c82009-03-29 16:50:03 +00002491 if (Tok.is(tok::kw_template)) {
Mike Stump11289f42009-09-09 15:08:12 +00002492 assert(!TemplateInfo.TemplateParams &&
Douglas Gregor3447e762009-08-20 22:52:58 +00002493 "Nested template improperly parsed?");
Richard Smith3af70092017-02-09 22:14:25 +00002494 ObjCDeclContextSwitch ObjCDC(*this);
Chris Lattner49836b42009-04-02 04:16:50 +00002495 SourceLocation DeclEnd;
Alexey Bataev05c25d62015-07-31 08:42:25 +00002496 return DeclGroupPtrTy::make(
Richard Smith3af70092017-02-09 22:14:25 +00002497 DeclGroupRef(ParseTemplateDeclarationOrSpecialization(
Erich Keanec480f302018-07-12 21:09:05 +00002498 DeclaratorContext::MemberContext, DeclEnd, AccessAttrs, AS)));
Chris Lattner5bbb3c82009-03-29 16:50:03 +00002499 }
Anders Carlssondfbbdf62009-03-26 00:52:18 +00002500
Chris Lattnerd19c1c02008-12-18 01:12:00 +00002501 // Handle: member-declaration ::= '__extension__' member-declaration
2502 if (Tok.is(tok::kw___extension__)) {
2503 // __extension__ silences extension warnings in the subexpression.
2504 ExtensionRAIIObject O(Diags); // Use RAII to do this.
2505 ConsumeToken();
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00002506 return ParseCXXClassMemberDeclaration(AS, AccessAttrs,
2507 TemplateInfo, TemplateDiags);
Chris Lattnerd19c1c02008-12-18 01:12:00 +00002508 }
Douglas Gregorfec52632009-06-20 00:51:54 +00002509
John McCall084e83d2011-03-24 11:26:52 +00002510 ParsedAttributesWithRange attrs(AttrFactory);
Erich Keanec480f302018-07-12 21:09:05 +00002511 ParsedAttributesViewWithRange FnAttrs;
Richard Smith89645bc2013-01-02 12:01:23 +00002512 // Optional C++11 attribute-specifier
2513 MaybeParseCXX11Attributes(attrs);
Michael Handdc016d2012-11-28 23:17:40 +00002514 // We need to keep these attributes for future diagnostic
2515 // before they are taken over by declaration specifier.
Erich Keanec480f302018-07-12 21:09:05 +00002516 FnAttrs.addAll(attrs.begin(), attrs.end());
Michael Handdc016d2012-11-28 23:17:40 +00002517 FnAttrs.Range = attrs.Range;
2518
John McCall53fa7142010-12-24 02:08:15 +00002519 MaybeParseMicrosoftAttributes(attrs);
Alexis Hunt96d5c762009-11-21 08:43:09 +00002520
Douglas Gregorfec52632009-06-20 00:51:54 +00002521 if (Tok.is(tok::kw_using)) {
John McCall53fa7142010-12-24 02:08:15 +00002522 ProhibitAttributes(attrs);
Mike Stump11289f42009-09-09 15:08:12 +00002523
Douglas Gregorfec52632009-06-20 00:51:54 +00002524 // Eat 'using'.
2525 SourceLocation UsingLoc = ConsumeToken();
2526
2527 if (Tok.is(tok::kw_namespace)) {
2528 Diag(UsingLoc, diag::err_using_namespace_in_class);
Alexey Bataevee6507d2013-11-18 08:17:37 +00002529 SkipUntil(tok::semi, StopBeforeMatch);
David Blaikie0403cb12016-01-15 23:43:25 +00002530 return nullptr;
Douglas Gregorfec52632009-06-20 00:51:54 +00002531 }
Alexey Bataev05c25d62015-07-31 08:42:25 +00002532 SourceLocation DeclEnd;
2533 // Otherwise, it must be a using-declaration or an alias-declaration.
Faisal Vali421b2d12017-12-29 05:41:00 +00002534 return ParseUsingDeclaration(DeclaratorContext::MemberContext, TemplateInfo,
Richard Smith6f1daa42016-12-16 00:58:48 +00002535 UsingLoc, DeclEnd, AS);
Douglas Gregorfec52632009-06-20 00:51:54 +00002536 }
2537
DeLesley Hutchinsbd2ee132012-03-02 22:12:59 +00002538 // Hold late-parsed attributes so we can attach a Decl to them later.
2539 LateParsedAttrList CommonLateParsedAttrs;
2540
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002541 // decl-specifier-seq:
2542 // Parse the common declaration-specifiers piece.
John McCall796c2a52010-07-16 08:13:16 +00002543 ParsingDeclSpec DS(*this, TemplateDiags);
John McCall53fa7142010-12-24 02:08:15 +00002544 DS.takeAttributesFrom(attrs);
Richard Smith45855df2012-05-09 08:23:23 +00002545 if (MalformedTypeSpec)
2546 DS.SetTypeSpecError();
Richard Smith72553fc2014-01-23 23:53:27 +00002547
Faisal Valia534f072018-04-26 00:42:40 +00002548 ParseDeclarationSpecifiers(DS, TemplateInfo, AS, DeclSpecContext::DSC_class,
2549 &CommonLateParsedAttrs);
Serge Pavlov458ea762014-07-16 05:16:52 +00002550
2551 // Turn off colon protection that was set for declspec.
2552 X.restore();
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002553
Richard Smith404dfb42013-11-19 22:47:36 +00002554 // If we had a free-standing type definition with a missing semicolon, we
2555 // may get this far before the problem becomes obvious.
2556 if (DS.hasTagDefinition() &&
2557 TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate &&
Faisal Vali7db85c52017-12-31 00:06:40 +00002558 DiagnoseMissingSemiAfterTagDefinition(DS, AS, DeclSpecContext::DSC_class,
Richard Smith404dfb42013-11-19 22:47:36 +00002559 &CommonLateParsedAttrs))
David Blaikie0403cb12016-01-15 23:43:25 +00002560 return nullptr;
Richard Smith404dfb42013-11-19 22:47:36 +00002561
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002562 MultiTemplateParamsArg TemplateParams(
Craig Topper161e4db2014-05-21 06:02:52 +00002563 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->data()
2564 : nullptr,
John McCall11083da2009-09-16 22:47:08 +00002565 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->size() : 0);
2566
Alp Toker35d87032013-12-30 23:29:50 +00002567 if (TryConsumeToken(tok::semi)) {
Michael Handdc016d2012-11-28 23:17:40 +00002568 if (DS.isFriendSpecified())
2569 ProhibitAttributes(FnAttrs);
2570
Nico Weber7b837f52016-01-28 19:25:00 +00002571 RecordDecl *AnonRecord = nullptr;
2572 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(
2573 getCurScope(), AS, DS, TemplateParams, false, AnonRecord);
John McCall796c2a52010-07-16 08:13:16 +00002574 DS.complete(TheDecl);
Nico Weber7b837f52016-01-28 19:25:00 +00002575 if (AnonRecord) {
2576 Decl* decls[] = {AnonRecord, TheDecl};
Richard Smith3beb7c62017-01-12 02:27:38 +00002577 return Actions.BuildDeclaratorGroup(decls);
Nico Weber7b837f52016-01-28 19:25:00 +00002578 }
2579 return Actions.ConvertDeclToDeclGroup(TheDecl);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002580 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002581
Faisal Vali421b2d12017-12-29 05:41:00 +00002582 ParsingDeclarator DeclaratorInfo(*this, DS, DeclaratorContext::MemberContext);
Nico Weber24b2a822011-01-28 06:07:34 +00002583 VirtSpecifiers VS;
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002584
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002585 // Hold late-parsed attributes so we can attach a Decl to them later.
2586 LateParsedAttrList LateParsedAttrs;
2587
Douglas Gregor50cefbf2011-10-17 17:09:53 +00002588 SourceLocation EqualLoc;
Richard Smith9ba0fec2015-06-30 01:28:56 +00002589 SourceLocation PureSpecLoc;
2590
Yaron Keren180c1672015-06-30 07:35:19 +00002591 auto TryConsumePureSpecifier = [&] (bool AllowDefinition) {
Richard Smith9ba0fec2015-06-30 01:28:56 +00002592 if (Tok.isNot(tok::equal))
2593 return false;
2594
2595 auto &Zero = NextToken();
2596 SmallString<8> Buffer;
2597 if (Zero.isNot(tok::numeric_constant) || Zero.getLength() != 1 ||
2598 PP.getSpelling(Zero, Buffer) != "0")
2599 return false;
2600
2601 auto &After = GetLookAheadToken(2);
2602 if (!After.isOneOf(tok::semi, tok::comma) &&
2603 !(AllowDefinition &&
2604 After.isOneOf(tok::l_brace, tok::colon, tok::kw_try)))
2605 return false;
2606
2607 EqualLoc = ConsumeToken();
2608 PureSpecLoc = ConsumeToken();
2609 return true;
2610 };
Chris Lattner17c3b1f2009-12-10 01:59:24 +00002611
Richard Smith72553fc2014-01-23 23:53:27 +00002612 SmallVector<Decl *, 8> DeclsInGroup;
2613 ExprResult BitfieldSize;
2614 bool ExpectSemi = true;
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002615
Richard Smith72553fc2014-01-23 23:53:27 +00002616 // Parse the first declarator.
Nico Weberd89e6f72015-01-16 19:34:13 +00002617 if (ParseCXXMemberDeclaratorBeforeInitializer(
2618 DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs)) {
Richard Smith72553fc2014-01-23 23:53:27 +00002619 TryConsumeToken(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002620 return nullptr;
Richard Smith72553fc2014-01-23 23:53:27 +00002621 }
John Thompson5bc5cbe2009-11-25 22:58:06 +00002622
Richard Smith72553fc2014-01-23 23:53:27 +00002623 // Check for a member function definition.
Richard Smith4b5a9492014-01-24 22:34:35 +00002624 if (BitfieldSize.isUnset()) {
Richard Smith72553fc2014-01-23 23:53:27 +00002625 // MSVC permits pure specifier on inline functions defined at class scope.
Francois Pichet3abc9b82011-05-11 02:14:46 +00002626 // Hence check for =0 before checking for function definition.
Richard Smith9ba0fec2015-06-30 01:28:56 +00002627 if (getLangOpts().MicrosoftExt && DeclaratorInfo.isDeclarationOfFunction())
2628 TryConsumePureSpecifier(/*AllowDefinition*/ true);
Francois Pichet3abc9b82011-05-11 02:14:46 +00002629
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00002630 FunctionDefinitionKind DefinitionKind = FDK_Declaration;
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002631 // function-definition:
Richard Smith938f40b2011-06-11 17:19:42 +00002632 //
2633 // In C++11, a non-function declarator followed by an open brace is a
2634 // braced-init-list for an in-class member initialization, not an
2635 // erroneous function definition.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002636 if (Tok.is(tok::l_brace) && !getLangOpts().CPlusPlus11) {
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00002637 DefinitionKind = FDK_Definition;
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002638 } else if (DeclaratorInfo.isFunctionDeclarator()) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002639 if (Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try)) {
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00002640 DefinitionKind = FDK_Definition;
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002641 } else if (Tok.is(tok::equal)) {
2642 const Token &KW = NextToken();
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00002643 if (KW.is(tok::kw_default))
2644 DefinitionKind = FDK_Defaulted;
2645 else if (KW.is(tok::kw_delete))
2646 DefinitionKind = FDK_Deleted;
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002647 }
2648 }
Eli Bendersky41842222015-03-23 23:49:41 +00002649 DeclaratorInfo.setFunctionDefinitionKind(DefinitionKind);
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002650
Fangrui Song6907ce22018-07-30 19:24:48 +00002651 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
Michael Handdc016d2012-11-28 23:17:40 +00002652 // to a friend declaration, that declaration shall be a definition.
Fangrui Song6907ce22018-07-30 19:24:48 +00002653 if (DeclaratorInfo.isFunctionDeclarator() &&
Michael Handdc016d2012-11-28 23:17:40 +00002654 DefinitionKind != FDK_Definition && DS.isFriendSpecified()) {
2655 // Diagnose attributes that appear before decl specifier:
2656 // [[]] friend int foo();
2657 ProhibitAttributes(FnAttrs);
2658 }
2659
Nico Webera7f137d2015-01-16 19:35:01 +00002660 if (DefinitionKind != FDK_Declaration) {
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002661 if (!DeclaratorInfo.isFunctionDeclarator()) {
Richard Trieu0d730542012-01-21 02:59:18 +00002662 Diag(DeclaratorInfo.getIdentifierLoc(), diag::err_func_def_no_params);
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002663 ConsumeBrace();
Alexey Bataevee6507d2013-11-18 08:17:37 +00002664 SkipUntil(tok::r_brace);
Michael Handdc016d2012-11-28 23:17:40 +00002665
Douglas Gregor8a4db832011-01-19 16:41:58 +00002666 // Consume the optional ';'
Alp Toker35d87032013-12-30 23:29:50 +00002667 TryConsumeToken(tok::semi);
2668
David Blaikie0403cb12016-01-15 23:43:25 +00002669 return nullptr;
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002670 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002671
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002672 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
Richard Trieu0d730542012-01-21 02:59:18 +00002673 Diag(DeclaratorInfo.getIdentifierLoc(),
2674 diag::err_function_declared_typedef);
Douglas Gregor8a4db832011-01-19 16:41:58 +00002675
Richard Smith2603b092012-11-15 22:54:20 +00002676 // Recover by treating the 'typedef' as spurious.
2677 DS.ClearStorageClassSpecs();
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002678 }
2679
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002680 Decl *FunDecl =
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00002681 ParseCXXInlineMethodDef(AS, AccessAttrs, DeclaratorInfo, TemplateInfo,
Richard Smith9ba0fec2015-06-30 01:28:56 +00002682 VS, PureSpecLoc);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002683
David Majnemer23252a32013-08-01 04:22:55 +00002684 if (FunDecl) {
2685 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i) {
2686 CommonLateParsedAttrs[i]->addDecl(FunDecl);
2687 }
2688 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i) {
2689 LateParsedAttrs[i]->addDecl(FunDecl);
2690 }
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002691 }
2692 LateParsedAttrs.clear();
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002693
2694 // Consume the ';' - it's optional unless we have a delete or default
Richard Trieu2f7dc462012-05-16 19:04:59 +00002695 if (Tok.is(tok::semi))
Richard Smith87f5dc52012-07-23 05:45:25 +00002696 ConsumeExtraSemi(AfterMemberFunctionDefinition);
Douglas Gregor8a4db832011-01-19 16:41:58 +00002697
Alexey Bataev05c25d62015-07-31 08:42:25 +00002698 return DeclGroupPtrTy::make(DeclGroupRef(FunDecl));
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002699 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002700 }
2701
2702 // member-declarator-list:
2703 // member-declarator
2704 // member-declarator-list ',' member-declarator
2705
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002706 while (1) {
Richard Smith2b013182012-06-10 03:12:00 +00002707 InClassInitStyle HasInClassInit = ICIS_NoInit;
Richard Smith9ba0fec2015-06-30 01:28:56 +00002708 bool HasStaticInitializer = false;
2709 if (Tok.isOneOf(tok::equal, tok::l_brace) && PureSpecLoc.isInvalid()) {
Richard Smith6b8e3c02017-08-28 00:28:14 +00002710 if (DeclaratorInfo.isDeclarationOfFunction()) {
Richard Smith9ba0fec2015-06-30 01:28:56 +00002711 // It's a pure-specifier.
2712 if (!TryConsumePureSpecifier(/*AllowFunctionDefinition*/ false))
2713 // Parse it as an expression so that Sema can diagnose it.
2714 HasStaticInitializer = true;
2715 } else if (DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2716 DeclSpec::SCS_static &&
2717 DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2718 DeclSpec::SCS_typedef &&
2719 !DS.isFriendSpecified()) {
2720 // It's a default member initializer.
Richard Smith6b8e3c02017-08-28 00:28:14 +00002721 if (BitfieldSize.get())
2722 Diag(Tok, getLangOpts().CPlusPlus2a
2723 ? diag::warn_cxx17_compat_bitfield_member_init
2724 : diag::ext_bitfield_member_init);
Richard Smith9ba0fec2015-06-30 01:28:56 +00002725 HasInClassInit = Tok.is(tok::equal) ? ICIS_CopyInit : ICIS_ListInit;
Richard Smith938f40b2011-06-11 17:19:42 +00002726 } else {
Richard Smith9ba0fec2015-06-30 01:28:56 +00002727 HasStaticInitializer = true;
Richard Smith938f40b2011-06-11 17:19:42 +00002728 }
2729 }
2730
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002731 // NOTE: If Sema is the Action module and declarator is an instance field,
Chris Lattner5bbb3c82009-03-29 16:50:03 +00002732 // this call will *not* return the created decl; It will return null.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002733 // See Sema::ActOnCXXMemberDeclarator for details.
John McCall07e91c02009-08-06 02:15:43 +00002734
Craig Topper161e4db2014-05-21 06:02:52 +00002735 NamedDecl *ThisDecl = nullptr;
John McCall07e91c02009-08-06 02:15:43 +00002736 if (DS.isFriendSpecified()) {
Richard Smith72553fc2014-01-23 23:53:27 +00002737 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
Michael Handdc016d2012-11-28 23:17:40 +00002738 // to a friend declaration, that declaration shall be a definition.
2739 //
Richard Smith72553fc2014-01-23 23:53:27 +00002740 // Diagnose attributes that appear in a friend member function declarator:
2741 // friend int foo [[]] ();
Michael Handdc016d2012-11-28 23:17:40 +00002742 SmallVector<SourceRange, 4> Ranges;
2743 DeclaratorInfo.getCXX11AttributeRanges(Ranges);
Richard Smith72553fc2014-01-23 23:53:27 +00002744 for (SmallVectorImpl<SourceRange>::iterator I = Ranges.begin(),
2745 E = Ranges.end(); I != E; ++I)
2746 Diag((*I).getBegin(), diag::err_attributes_not_allowed) << *I;
Michael Handdc016d2012-11-28 23:17:40 +00002747
Douglas Gregor0be31a22010-07-02 17:43:08 +00002748 ThisDecl = Actions.ActOnFriendFunctionDecl(getCurScope(), DeclaratorInfo,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002749 TemplateParams);
Douglas Gregor3447e762009-08-20 22:52:58 +00002750 } else {
Douglas Gregor0be31a22010-07-02 17:43:08 +00002751 ThisDecl = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS,
John McCall07e91c02009-08-06 02:15:43 +00002752 DeclaratorInfo,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002753 TemplateParams,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002754 BitfieldSize.get(),
Richard Smith2b013182012-06-10 03:12:00 +00002755 VS, HasInClassInit);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002756
2757 if (VarTemplateDecl *VT =
Craig Topper161e4db2014-05-21 06:02:52 +00002758 ThisDecl ? dyn_cast<VarTemplateDecl>(ThisDecl) : nullptr)
Larisse Voufo39a1e502013-08-06 01:03:05 +00002759 // Re-direct this decl to refer to the templated decl so that we can
2760 // initialize it.
2761 ThisDecl = VT->getTemplatedDecl();
2762
Erich Keanec480f302018-07-12 21:09:05 +00002763 if (ThisDecl)
Richard Smithf8a75c32013-08-29 00:47:48 +00002764 Actions.ProcessDeclAttributeList(getCurScope(), ThisDecl, AccessAttrs);
Douglas Gregor3447e762009-08-20 22:52:58 +00002765 }
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002766
Richard Smith9ba0fec2015-06-30 01:28:56 +00002767 // Error recovery might have converted a non-static member into a static
2768 // member.
David Blaikie35506f82013-01-30 01:22:18 +00002769 if (HasInClassInit != ICIS_NoInit &&
Richard Smith9ba0fec2015-06-30 01:28:56 +00002770 DeclaratorInfo.getDeclSpec().getStorageClassSpec() ==
2771 DeclSpec::SCS_static) {
2772 HasInClassInit = ICIS_NoInit;
2773 HasStaticInitializer = true;
2774 }
2775
2776 if (ThisDecl && PureSpecLoc.isValid())
2777 Actions.ActOnPureSpecifier(ThisDecl, PureSpecLoc);
2778
2779 // Handle the initializer.
2780 if (HasInClassInit != ICIS_NoInit) {
Douglas Gregor728d00b2011-10-10 14:49:18 +00002781 // The initializer was deferred; parse it and cache the tokens.
David Majnemer23252a32013-08-01 04:22:55 +00002782 Diag(Tok, getLangOpts().CPlusPlus11
2783 ? diag::warn_cxx98_compat_nonstatic_member_init
2784 : diag::ext_nonstatic_member_init);
Richard Smith5d164bc2011-10-15 05:09:34 +00002785
Richard Smith938f40b2011-06-11 17:19:42 +00002786 if (DeclaratorInfo.isArrayOfUnknownBound()) {
Richard Smith2b013182012-06-10 03:12:00 +00002787 // C++11 [dcl.array]p3: An array bound may also be omitted when the
2788 // declarator is followed by an initializer.
Richard Smith938f40b2011-06-11 17:19:42 +00002789 //
2790 // A brace-or-equal-initializer for a member-declarator is not an
David Blaikiecdd91db2012-02-14 09:00:46 +00002791 // initializer in the grammar, so this is ill-formed.
Richard Smith938f40b2011-06-11 17:19:42 +00002792 Diag(Tok, diag::err_incomplete_array_member_init);
Alexey Bataevee6507d2013-11-18 08:17:37 +00002793 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
David Majnemer23252a32013-08-01 04:22:55 +00002794
2795 // Avoid later warnings about a class member of incomplete type.
David Blaikiecdd91db2012-02-14 09:00:46 +00002796 if (ThisDecl)
David Blaikiecdd91db2012-02-14 09:00:46 +00002797 ThisDecl->setInvalidDecl();
Richard Smith938f40b2011-06-11 17:19:42 +00002798 } else
2799 ParseCXXNonStaticMemberInitializer(ThisDecl);
Richard Smith9ba0fec2015-06-30 01:28:56 +00002800 } else if (HasStaticInitializer) {
Douglas Gregor728d00b2011-10-10 14:49:18 +00002801 // Normal initializer.
Richard Smith9ba0fec2015-06-30 01:28:56 +00002802 ExprResult Init = ParseCXXMemberInitializer(
2803 ThisDecl, DeclaratorInfo.isDeclarationOfFunction(), EqualLoc);
David Majnemer23252a32013-08-01 04:22:55 +00002804
Douglas Gregor728d00b2011-10-10 14:49:18 +00002805 if (Init.isInvalid())
Alexey Bataevee6507d2013-11-18 08:17:37 +00002806 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
Douglas Gregor728d00b2011-10-10 14:49:18 +00002807 else if (ThisDecl)
Richard Smith3beb7c62017-01-12 02:27:38 +00002808 Actions.AddInitializerToDecl(ThisDecl, Init.get(), EqualLoc.isInvalid());
David Majnemer23252a32013-08-01 04:22:55 +00002809 } else if (ThisDecl && DS.getStorageClassSpec() == DeclSpec::SCS_static)
Douglas Gregor728d00b2011-10-10 14:49:18 +00002810 // No initializer.
Richard Smith3beb7c62017-01-12 02:27:38 +00002811 Actions.ActOnUninitializedDecl(ThisDecl);
David Majnemer23252a32013-08-01 04:22:55 +00002812
Douglas Gregor728d00b2011-10-10 14:49:18 +00002813 if (ThisDecl) {
David Majnemer23252a32013-08-01 04:22:55 +00002814 if (!ThisDecl->isInvalidDecl()) {
2815 // Set the Decl for any late parsed attributes
2816 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i)
2817 CommonLateParsedAttrs[i]->addDecl(ThisDecl);
2818
2819 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i)
2820 LateParsedAttrs[i]->addDecl(ThisDecl);
2821 }
Douglas Gregor728d00b2011-10-10 14:49:18 +00002822 Actions.FinalizeDeclaration(ThisDecl);
2823 DeclsInGroup.push_back(ThisDecl);
David Majnemer23252a32013-08-01 04:22:55 +00002824
2825 if (DeclaratorInfo.isFunctionDeclarator() &&
2826 DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2827 DeclSpec::SCS_typedef)
2828 HandleMemberFunctionDeclDelays(DeclaratorInfo, ThisDecl);
Douglas Gregor728d00b2011-10-10 14:49:18 +00002829 }
David Majnemer23252a32013-08-01 04:22:55 +00002830 LateParsedAttrs.clear();
Douglas Gregor728d00b2011-10-10 14:49:18 +00002831
2832 DeclaratorInfo.complete(ThisDecl);
Richard Smith938f40b2011-06-11 17:19:42 +00002833
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002834 // If we don't have a comma, it is either the end of the list (a ';')
2835 // or an error, bail out.
Alp Toker094e5212014-01-05 03:27:11 +00002836 SourceLocation CommaLoc;
2837 if (!TryConsumeToken(tok::comma, CommaLoc))
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002838 break;
Mike Stump11289f42009-09-09 15:08:12 +00002839
Richard Smithc8a79032012-01-09 22:31:44 +00002840 if (Tok.isAtStartOfLine() &&
Faisal Vali421b2d12017-12-29 05:41:00 +00002841 !MightBeDeclarator(DeclaratorContext::MemberContext)) {
Richard Smithc8a79032012-01-09 22:31:44 +00002842 // This comma was followed by a line-break and something which can't be
2843 // the start of a declarator. The comma was probably a typo for a
2844 // semicolon.
2845 Diag(CommaLoc, diag::err_expected_semi_declaration)
2846 << FixItHint::CreateReplacement(CommaLoc, ";");
2847 ExpectSemi = false;
2848 break;
2849 }
Mike Stump11289f42009-09-09 15:08:12 +00002850
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002851 // Parse the next declarator.
2852 DeclaratorInfo.clear();
Nico Weber24b2a822011-01-28 06:07:34 +00002853 VS.clear();
Nico Weberf56c85b2015-01-17 02:26:40 +00002854 BitfieldSize = ExprResult(/*Invalid=*/false);
Richard Smith9ba0fec2015-06-30 01:28:56 +00002855 EqualLoc = PureSpecLoc = SourceLocation();
Richard Smith8d06f422012-01-12 23:53:29 +00002856 DeclaratorInfo.setCommaLoc(CommaLoc);
Mike Stump11289f42009-09-09 15:08:12 +00002857
Richard Smith72553fc2014-01-23 23:53:27 +00002858 // GNU attributes are allowed before the second and subsequent declarator.
John McCall53fa7142010-12-24 02:08:15 +00002859 MaybeParseGNUAttributes(DeclaratorInfo);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002860
Nico Weberd89e6f72015-01-16 19:34:13 +00002861 if (ParseCXXMemberDeclaratorBeforeInitializer(
2862 DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs))
2863 break;
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002864 }
2865
Richard Smithc8a79032012-01-09 22:31:44 +00002866 if (ExpectSemi &&
2867 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list)) {
Chris Lattner916dbf12010-02-02 00:43:15 +00002868 // Skip to end of block or statement.
Alexey Bataevee6507d2013-11-18 08:17:37 +00002869 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Chris Lattner916dbf12010-02-02 00:43:15 +00002870 // If we stopped at a ';', eat it.
Alp Toker35d87032013-12-30 23:29:50 +00002871 TryConsumeToken(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002872 return nullptr;
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002873 }
2874
Alexey Bataev05c25d62015-07-31 08:42:25 +00002875 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002876}
2877
Richard Smith9ba0fec2015-06-30 01:28:56 +00002878/// ParseCXXMemberInitializer - Parse the brace-or-equal-initializer.
2879/// Also detect and reject any attempted defaulted/deleted function definition.
2880/// The location of the '=', if any, will be placed in EqualLoc.
Richard Smith938f40b2011-06-11 17:19:42 +00002881///
Richard Smith9ba0fec2015-06-30 01:28:56 +00002882/// This does not check for a pure-specifier; that's handled elsewhere.
Sebastian Redleef474c2012-02-22 10:50:08 +00002883///
Richard Smith938f40b2011-06-11 17:19:42 +00002884/// brace-or-equal-initializer:
2885/// '=' initializer-expression
Sebastian Redleef474c2012-02-22 10:50:08 +00002886/// braced-init-list
2887///
Richard Smith938f40b2011-06-11 17:19:42 +00002888/// initializer-clause:
2889/// assignment-expression
Sebastian Redleef474c2012-02-22 10:50:08 +00002890/// braced-init-list
2891///
Richard Smithda35e962013-11-09 04:52:51 +00002892/// defaulted/deleted function-definition:
Richard Smith938f40b2011-06-11 17:19:42 +00002893/// '=' 'default'
2894/// '=' 'delete'
2895///
2896/// Prior to C++0x, the assignment-expression in an initializer-clause must
2897/// be a constant-expression.
Douglas Gregor926410d2012-02-21 02:22:07 +00002898ExprResult Parser::ParseCXXMemberInitializer(Decl *D, bool IsFunction,
Richard Smith938f40b2011-06-11 17:19:42 +00002899 SourceLocation &EqualLoc) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002900 assert(Tok.isOneOf(tok::equal, tok::l_brace)
Richard Smith938f40b2011-06-11 17:19:42 +00002901 && "Data member initializer not starting with '=' or '{'");
2902
Faisal Valid143a0c2017-04-01 21:30:49 +00002903 EnterExpressionEvaluationContext Context(
2904 Actions, Sema::ExpressionEvaluationContext::PotentiallyEvaluated, D);
Alp Toker094e5212014-01-05 03:27:11 +00002905 if (TryConsumeToken(tok::equal, EqualLoc)) {
Richard Smith938f40b2011-06-11 17:19:42 +00002906 if (Tok.is(tok::kw_delete)) {
2907 // In principle, an initializer of '= delete p;' is legal, but it will
2908 // never type-check. It's better to diagnose it as an ill-formed expression
2909 // than as an ill-formed deleted non-function member.
2910 // An initializer of '= delete p, foo' will never be parsed, because
2911 // a top-level comma always ends the initializer expression.
2912 const Token &Next = NextToken();
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002913 if (IsFunction || Next.isOneOf(tok::semi, tok::comma, tok::eof)) {
Richard Smith938f40b2011-06-11 17:19:42 +00002914 if (IsFunction)
2915 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2916 << 1 /* delete */;
2917 else
2918 Diag(ConsumeToken(), diag::err_deleted_non_function);
Richard Smithedcb26e2014-06-11 00:49:52 +00002919 return ExprError();
Richard Smith938f40b2011-06-11 17:19:42 +00002920 }
2921 } else if (Tok.is(tok::kw_default)) {
Richard Smith938f40b2011-06-11 17:19:42 +00002922 if (IsFunction)
2923 Diag(Tok, diag::err_default_delete_in_multiple_declaration)
2924 << 0 /* default */;
2925 else
2926 Diag(ConsumeToken(), diag::err_default_special_members);
Richard Smithedcb26e2014-06-11 00:49:52 +00002927 return ExprError();
Richard Smith938f40b2011-06-11 17:19:42 +00002928 }
David Majnemer87ff66c2014-12-13 11:34:16 +00002929 }
2930 if (const auto *PD = dyn_cast_or_null<MSPropertyDecl>(D)) {
2931 Diag(Tok, diag::err_ms_property_initializer) << PD;
2932 return ExprError();
Sebastian Redleef474c2012-02-22 10:50:08 +00002933 }
2934 return ParseInitializer();
Richard Smith938f40b2011-06-11 17:19:42 +00002935}
2936
Richard Smith65ebb4a2015-03-26 04:09:53 +00002937void Parser::SkipCXXMemberSpecification(SourceLocation RecordLoc,
2938 SourceLocation AttrFixitLoc,
Faisal Vali090da2d2018-01-01 18:23:28 +00002939 unsigned TagType, Decl *TagDecl) {
Richard Smith65ebb4a2015-03-26 04:09:53 +00002940 // Skip the optional 'final' keyword.
2941 if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
2942 assert(isCXX11FinalKeyword() && "not a class definition");
2943 ConsumeToken();
2944
2945 // Diagnose any C++11 attributes after 'final' keyword.
2946 // We deliberately discard these attributes.
2947 ParsedAttributesWithRange Attrs(AttrFactory);
2948 CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
2949
2950 // This can only happen if we had malformed misplaced attributes;
2951 // we only get called if there is a colon or left-brace after the
2952 // attributes.
2953 if (Tok.isNot(tok::colon) && Tok.isNot(tok::l_brace))
2954 return;
2955 }
2956
2957 // Skip the base clauses. This requires actually parsing them, because
2958 // otherwise we can't be sure where they end (a left brace may appear
2959 // within a template argument).
2960 if (Tok.is(tok::colon)) {
2961 // Enter the scope of the class so that we can correctly parse its bases.
2962 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
2963 ParsingClassDefinition ParsingDef(*this, TagDecl, /*NonNestedClass*/ true,
2964 TagType == DeclSpec::TST_interface);
Richard Smith0f192e82015-06-11 22:48:25 +00002965 auto OldContext =
2966 Actions.ActOnTagStartSkippedDefinition(getCurScope(), TagDecl);
Richard Smith65ebb4a2015-03-26 04:09:53 +00002967
2968 // Parse the bases but don't attach them to the class.
2969 ParseBaseClause(nullptr);
2970
Richard Smith0f192e82015-06-11 22:48:25 +00002971 Actions.ActOnTagFinishSkippedDefinition(OldContext);
Richard Smith65ebb4a2015-03-26 04:09:53 +00002972
2973 if (!Tok.is(tok::l_brace)) {
2974 Diag(PP.getLocForEndOfToken(PrevTokLocation),
2975 diag::err_expected_lbrace_after_base_specifiers);
2976 return;
2977 }
2978 }
2979
2980 // Skip the body.
2981 assert(Tok.is(tok::l_brace));
2982 BalancedDelimiterTracker T(*this, tok::l_brace);
2983 T.consumeOpen();
2984 T.skipToEnd();
Richard Smith04c6c1f2015-07-01 18:56:50 +00002985
2986 // Parse and discard any trailing attributes.
2987 ParsedAttributes Attrs(AttrFactory);
2988 if (Tok.is(tok::kw___attribute))
2989 MaybeParseGNUAttributes(Attrs);
Richard Smith65ebb4a2015-03-26 04:09:53 +00002990}
2991
Alexey Bataev05c25d62015-07-31 08:42:25 +00002992Parser::DeclGroupPtrTy Parser::ParseCXXClassMemberDeclarationWithPragmas(
2993 AccessSpecifier &AS, ParsedAttributesWithRange &AccessAttrs,
2994 DeclSpec::TST TagType, Decl *TagDecl) {
Richard Smithbf5bcf22018-06-26 23:20:26 +00002995 ParenBraceBracketBalancer BalancerRAIIObj(*this);
2996
Richard Smithb55f7582017-01-28 01:12:10 +00002997 switch (Tok.getKind()) {
2998 case tok::kw___if_exists:
2999 case tok::kw___if_not_exists:
Erich Keanec480f302018-07-12 21:09:05 +00003000 ParseMicrosoftIfExistsClassDeclaration(TagType, AccessAttrs, AS);
David Blaikie0403cb12016-01-15 23:43:25 +00003001 return nullptr;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003002
Richard Smithb55f7582017-01-28 01:12:10 +00003003 case tok::semi:
3004 // Check for extraneous top-level semicolon.
Alexey Bataev05c25d62015-07-31 08:42:25 +00003005 ConsumeExtraSemi(InsideStruct, TagType);
David Blaikie0403cb12016-01-15 23:43:25 +00003006 return nullptr;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003007
Richard Smithb55f7582017-01-28 01:12:10 +00003008 // Handle pragmas that can appear as member declarations.
3009 case tok::annot_pragma_vis:
Alexey Bataev05c25d62015-07-31 08:42:25 +00003010 HandlePragmaVisibility();
David Blaikie0403cb12016-01-15 23:43:25 +00003011 return nullptr;
Richard Smithb55f7582017-01-28 01:12:10 +00003012 case tok::annot_pragma_pack:
Alexey Bataev05c25d62015-07-31 08:42:25 +00003013 HandlePragmaPack();
David Blaikie0403cb12016-01-15 23:43:25 +00003014 return nullptr;
Richard Smithb55f7582017-01-28 01:12:10 +00003015 case tok::annot_pragma_align:
Alexey Bataev05c25d62015-07-31 08:42:25 +00003016 HandlePragmaAlign();
David Blaikie0403cb12016-01-15 23:43:25 +00003017 return nullptr;
Richard Smithb55f7582017-01-28 01:12:10 +00003018 case tok::annot_pragma_ms_pointers_to_members:
Alexey Bataev05c25d62015-07-31 08:42:25 +00003019 HandlePragmaMSPointersToMembers();
David Blaikie0403cb12016-01-15 23:43:25 +00003020 return nullptr;
Richard Smithb55f7582017-01-28 01:12:10 +00003021 case tok::annot_pragma_ms_pragma:
Alexey Bataev05c25d62015-07-31 08:42:25 +00003022 HandlePragmaMSPragma();
David Blaikie0403cb12016-01-15 23:43:25 +00003023 return nullptr;
Richard Smithb55f7582017-01-28 01:12:10 +00003024 case tok::annot_pragma_ms_vtordisp:
Alexey Bataev3d42f342015-11-20 07:02:57 +00003025 HandlePragmaMSVtorDisp();
David Blaikie0403cb12016-01-15 23:43:25 +00003026 return nullptr;
Richard Smithb256d302017-01-28 01:20:57 +00003027 case tok::annot_pragma_dump:
3028 HandlePragmaDump();
3029 return nullptr;
Alexey Bataev3d42f342015-11-20 07:02:57 +00003030
Richard Smithb55f7582017-01-28 01:12:10 +00003031 case tok::kw_namespace:
3032 // If we see a namespace here, a close brace was missing somewhere.
Alexey Bataev05c25d62015-07-31 08:42:25 +00003033 DiagnoseUnexpectedNamespace(cast<NamedDecl>(TagDecl));
David Blaikie0403cb12016-01-15 23:43:25 +00003034 return nullptr;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003035
Richard Smithb55f7582017-01-28 01:12:10 +00003036 case tok::kw_public:
3037 case tok::kw_protected:
3038 case tok::kw_private: {
3039 AccessSpecifier NewAS = getAccessSpecifierIfPresent();
3040 assert(NewAS != AS_none);
Alexey Bataev05c25d62015-07-31 08:42:25 +00003041 // Current token is a C++ access specifier.
3042 AS = NewAS;
3043 SourceLocation ASLoc = Tok.getLocation();
3044 unsigned TokLength = Tok.getLength();
3045 ConsumeToken();
3046 AccessAttrs.clear();
3047 MaybeParseGNUAttributes(AccessAttrs);
3048
3049 SourceLocation EndLoc;
3050 if (TryConsumeToken(tok::colon, EndLoc)) {
3051 } else if (TryConsumeToken(tok::semi, EndLoc)) {
3052 Diag(EndLoc, diag::err_expected)
3053 << tok::colon << FixItHint::CreateReplacement(EndLoc, ":");
3054 } else {
3055 EndLoc = ASLoc.getLocWithOffset(TokLength);
3056 Diag(EndLoc, diag::err_expected)
3057 << tok::colon << FixItHint::CreateInsertion(EndLoc, ":");
3058 }
3059
3060 // The Microsoft extension __interface does not permit non-public
3061 // access specifiers.
3062 if (TagType == DeclSpec::TST_interface && AS != AS_public) {
3063 Diag(ASLoc, diag::err_access_specifier_interface) << (AS == AS_protected);
3064 }
3065
Erich Keanec480f302018-07-12 21:09:05 +00003066 if (Actions.ActOnAccessSpecifier(NewAS, ASLoc, EndLoc, AccessAttrs)) {
Alexey Bataev05c25d62015-07-31 08:42:25 +00003067 // found another attribute than only annotations
3068 AccessAttrs.clear();
3069 }
3070
David Blaikie0403cb12016-01-15 23:43:25 +00003071 return nullptr;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003072 }
3073
Richard Smithb55f7582017-01-28 01:12:10 +00003074 case tok::annot_pragma_openmp:
Alexey Bataev587e1de2016-03-30 10:43:55 +00003075 return ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, AccessAttrs, TagType,
3076 TagDecl);
Alexey Bataev05c25d62015-07-31 08:42:25 +00003077
Richard Smithb55f7582017-01-28 01:12:10 +00003078 default:
Erich Keanec480f302018-07-12 21:09:05 +00003079 return ParseCXXClassMemberDeclaration(AS, AccessAttrs);
Richard Smithb55f7582017-01-28 01:12:10 +00003080 }
Alexey Bataev05c25d62015-07-31 08:42:25 +00003081}
3082
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003083/// ParseCXXMemberSpecification - Parse the class definition.
3084///
3085/// member-specification:
3086/// member-declaration member-specification[opt]
3087/// access-specifier ':' member-specification[opt]
3088///
Joao Matose9a3ed42012-08-31 22:18:20 +00003089void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc,
Michael Han309af292013-01-07 16:57:11 +00003090 SourceLocation AttrFixitLoc,
Richard Smith4c96e992013-02-19 23:47:15 +00003091 ParsedAttributesWithRange &Attrs,
Faisal Vali090da2d2018-01-01 18:23:28 +00003092 unsigned TagType, Decl *TagDecl) {
Joao Matose9a3ed42012-08-31 22:18:20 +00003093 assert((TagType == DeclSpec::TST_struct ||
Faisal Vali090da2d2018-01-01 18:23:28 +00003094 TagType == DeclSpec::TST_interface ||
3095 TagType == DeclSpec::TST_union ||
3096 TagType == DeclSpec::TST_class) && "Invalid TagType!");
Joao Matose9a3ed42012-08-31 22:18:20 +00003097
Jordan Rose1e879d82018-03-23 00:07:18 +00003098 PrettyDeclStackTraceEntry CrashInfo(Actions.Context, TagDecl, RecordLoc,
John McCallfaf5fb42010-08-26 23:41:50 +00003099 "parsing struct/union/class body");
Mike Stump11289f42009-09-09 15:08:12 +00003100
Douglas Gregoredf8f392010-01-16 20:52:59 +00003101 // Determine whether this is a non-nested class. Note that local
3102 // classes are *not* considered to be nested classes.
3103 bool NonNestedClass = true;
3104 if (!ClassStack.empty()) {
Douglas Gregor0be31a22010-07-02 17:43:08 +00003105 for (const Scope *S = getCurScope(); S; S = S->getParent()) {
Douglas Gregoredf8f392010-01-16 20:52:59 +00003106 if (S->isClassScope()) {
3107 // We're inside a class scope, so this is a nested class.
3108 NonNestedClass = false;
John McCalldb632ac2012-09-25 07:32:39 +00003109
3110 // The Microsoft extension __interface does not permit nested classes.
3111 if (getCurrentClass().IsInterface) {
3112 Diag(RecordLoc, diag::err_invalid_member_in_interface)
3113 << /*ErrorType=*/6
3114 << (isa<NamedDecl>(TagDecl)
3115 ? cast<NamedDecl>(TagDecl)->getQualifiedNameAsString()
David Blaikieabe1a392014-04-02 05:58:29 +00003116 : "(anonymous)");
John McCalldb632ac2012-09-25 07:32:39 +00003117 }
Douglas Gregoredf8f392010-01-16 20:52:59 +00003118 break;
3119 }
3120
Serge Pavlovd9c0bcf2015-07-14 10:02:10 +00003121 if ((S->getFlags() & Scope::FnScope))
3122 // If we're in a function or function template then this is a local
3123 // class rather than a nested class.
3124 break;
Douglas Gregoredf8f392010-01-16 20:52:59 +00003125 }
3126 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003127
3128 // Enter a scope for the class.
Douglas Gregor658b9552009-01-09 22:42:13 +00003129 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003130
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003131 // Note that we are parsing a new (potentially-nested) class definition.
John McCalldb632ac2012-09-25 07:32:39 +00003132 ParsingClassDefinition ParsingDef(*this, TagDecl, NonNestedClass,
3133 TagType == DeclSpec::TST_interface);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003134
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003135 if (TagDecl)
Douglas Gregor0be31a22010-07-02 17:43:08 +00003136 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
John McCall2d814c32009-12-19 21:48:58 +00003137
Anders Carlssonf9eb63b2011-03-25 14:46:08 +00003138 SourceLocation FinalLoc;
David Majnemera5433082013-10-18 00:33:31 +00003139 bool IsFinalSpelledSealed = false;
Anders Carlssonf9eb63b2011-03-25 14:46:08 +00003140
3141 // Parse the optional 'final' keyword.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003142 if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
David Majnemera5433082013-10-18 00:33:31 +00003143 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier(Tok);
3144 assert((Specifier == VirtSpecifiers::VS_Final ||
Fangrui Song6907ce22018-07-30 19:24:48 +00003145 Specifier == VirtSpecifiers::VS_GNU_Final ||
David Majnemera5433082013-10-18 00:33:31 +00003146 Specifier == VirtSpecifiers::VS_Sealed) &&
3147 "not a class definition");
Richard Smithda261112011-10-15 04:21:46 +00003148 FinalLoc = ConsumeToken();
David Majnemera5433082013-10-18 00:33:31 +00003149 IsFinalSpelledSealed = Specifier == VirtSpecifiers::VS_Sealed;
Anders Carlssonf9eb63b2011-03-25 14:46:08 +00003150
David Majnemera5433082013-10-18 00:33:31 +00003151 if (TagType == DeclSpec::TST_interface)
John McCalldb632ac2012-09-25 07:32:39 +00003152 Diag(FinalLoc, diag::err_override_control_interface)
David Majnemera5433082013-10-18 00:33:31 +00003153 << VirtSpecifiers::getSpecifierName(Specifier);
3154 else if (Specifier == VirtSpecifiers::VS_Final)
3155 Diag(FinalLoc, getLangOpts().CPlusPlus11
3156 ? diag::warn_cxx98_compat_override_control_keyword
3157 : diag::ext_override_control_keyword)
3158 << VirtSpecifiers::getSpecifierName(Specifier);
3159 else if (Specifier == VirtSpecifiers::VS_Sealed)
3160 Diag(FinalLoc, diag::ext_ms_sealed_keyword);
Andrey Bokhanko276055b2016-07-29 10:42:48 +00003161 else if (Specifier == VirtSpecifiers::VS_GNU_Final)
3162 Diag(FinalLoc, diag::ext_warn_gnu_final);
Michael Han9407e502012-11-26 22:54:45 +00003163
Michael Han309af292013-01-07 16:57:11 +00003164 // Parse any C++11 attributes after 'final' keyword.
3165 // These attributes are not allowed to appear here,
3166 // and the only possible place for them to appertain
3167 // to the class would be between class-key and class-name.
Richard Smith4c96e992013-02-19 23:47:15 +00003168 CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
Nico Weber4b4be842014-12-29 06:56:50 +00003169
3170 // ParseClassSpecifier() does only a superficial check for attributes before
3171 // deciding to call this method. For example, for
3172 // `class C final alignas ([l) {` it will decide that this looks like a
3173 // misplaced attribute since it sees `alignas '(' ')'`. But the actual
3174 // attribute parsing code will try to parse the '[' as a constexpr lambda
3175 // and consume enough tokens that the alignas parsing code will eat the
3176 // opening '{'. So bail out if the next token isn't one we expect.
Nico Weber36de3a22014-12-29 21:56:22 +00003177 if (!Tok.is(tok::colon) && !Tok.is(tok::l_brace)) {
3178 if (TagDecl)
3179 Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
Nico Weber4b4be842014-12-29 06:56:50 +00003180 return;
Nico Weber36de3a22014-12-29 21:56:22 +00003181 }
Anders Carlssonf9eb63b2011-03-25 14:46:08 +00003182 }
Anders Carlsson4b63d0e2011-01-22 16:56:46 +00003183
John McCall2d814c32009-12-19 21:48:58 +00003184 if (Tok.is(tok::colon)) {
Erik Verbruggen6524c052017-10-24 13:46:58 +00003185 ParseScope InheritanceScope(this, getCurScope()->getFlags() |
3186 Scope::ClassInheritanceScope);
3187
John McCall2d814c32009-12-19 21:48:58 +00003188 ParseBaseClause(TagDecl);
John McCall2d814c32009-12-19 21:48:58 +00003189 if (!Tok.is(tok::l_brace)) {
Ismail Pazarbasi129c44c2014-09-25 21:13:02 +00003190 bool SuggestFixIt = false;
3191 SourceLocation BraceLoc = PP.getLocForEndOfToken(PrevTokLocation);
3192 if (Tok.isAtStartOfLine()) {
3193 switch (Tok.getKind()) {
3194 case tok::kw_private:
3195 case tok::kw_protected:
3196 case tok::kw_public:
3197 SuggestFixIt = NextToken().getKind() == tok::colon;
3198 break;
3199 case tok::kw_static_assert:
3200 case tok::r_brace:
3201 case tok::kw_using:
3202 // base-clause can have simple-template-id; 'template' can't be there
3203 case tok::kw_template:
3204 SuggestFixIt = true;
3205 break;
3206 case tok::identifier:
3207 SuggestFixIt = isConstructorDeclarator(true);
3208 break;
3209 default:
3210 SuggestFixIt = isCXXSimpleDeclaration(/*AllowForRangeDecl=*/false);
3211 break;
3212 }
3213 }
3214 DiagnosticBuilder LBraceDiag =
3215 Diag(BraceLoc, diag::err_expected_lbrace_after_base_specifiers);
3216 if (SuggestFixIt) {
3217 LBraceDiag << FixItHint::CreateInsertion(BraceLoc, " {");
3218 // Try recovering from missing { after base-clause.
3219 PP.EnterToken(Tok);
3220 Tok.setKind(tok::l_brace);
3221 } else {
3222 if (TagDecl)
3223 Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
3224 return;
3225 }
John McCall2d814c32009-12-19 21:48:58 +00003226 }
3227 }
3228
3229 assert(Tok.is(tok::l_brace));
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003230 BalancedDelimiterTracker T(*this, tok::l_brace);
3231 T.consumeOpen();
John McCall2d814c32009-12-19 21:48:58 +00003232
John McCall08bede42010-05-28 08:11:17 +00003233 if (TagDecl)
Anders Carlsson30f29442011-03-25 14:31:08 +00003234 Actions.ActOnStartCXXMemberDeclarations(getCurScope(), TagDecl, FinalLoc,
David Majnemera5433082013-10-18 00:33:31 +00003235 IsFinalSpelledSealed,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003236 T.getOpenLocation());
John McCall1c7e6ec2009-12-20 07:58:13 +00003237
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003238 // C++ 11p3: Members of a class defined with the keyword class are private
3239 // by default. Members of a class defined with the keywords struct or union
3240 // are public by default.
3241 AccessSpecifier CurAS;
3242 if (TagType == DeclSpec::TST_class)
3243 CurAS = AS_private;
3244 else
3245 CurAS = AS_public;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003246 ParsedAttributesWithRange AccessAttrs(AttrFactory);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003247
Douglas Gregor9377c822010-06-21 22:31:09 +00003248 if (TagDecl) {
3249 // While we still have something to read, read the member-declarations.
Richard Smith752ada82015-11-17 23:32:01 +00003250 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
3251 Tok.isNot(tok::eof)) {
Douglas Gregor9377c822010-06-21 22:31:09 +00003252 // Each iteration of this loop reads one member-declaration.
Alexey Bataev05c25d62015-07-31 08:42:25 +00003253 ParseCXXClassMemberDeclarationWithPragmas(
3254 CurAS, AccessAttrs, static_cast<DeclSpec::TST>(TagType), TagDecl);
Serge Pavlovc4e04a22015-09-19 05:32:57 +00003255 }
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003256 T.consumeClose();
Douglas Gregor9377c822010-06-21 22:31:09 +00003257 } else {
Alexey Bataevee6507d2013-11-18 08:17:37 +00003258 SkipUntil(tok::r_brace);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003259 }
Mike Stump11289f42009-09-09 15:08:12 +00003260
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003261 // If attributes exist after class contents, parse them.
John McCall084e83d2011-03-24 11:26:52 +00003262 ParsedAttributes attrs(AttrFactory);
John McCall53fa7142010-12-24 02:08:15 +00003263 MaybeParseGNUAttributes(attrs);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003264
John McCall08bede42010-05-28 08:11:17 +00003265 if (TagDecl)
Douglas Gregor0be31a22010-07-02 17:43:08 +00003266 Actions.ActOnFinishCXXMemberSpecification(getCurScope(), RecordLoc, TagDecl,
Erich Keanec480f302018-07-12 21:09:05 +00003267 T.getOpenLocation(),
3268 T.getCloseLocation(), attrs);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003269
Douglas Gregor433e0532012-04-16 18:27:27 +00003270 // C++11 [class.mem]p2:
3271 // Within the class member-specification, the class is regarded as complete
Richard Smith0b3a4622014-11-13 20:01:57 +00003272 // within function bodies, default arguments, exception-specifications, and
Douglas Gregor433e0532012-04-16 18:27:27 +00003273 // brace-or-equal-initializers for non-static data members (including such
3274 // things in nested classes).
Douglas Gregor9377c822010-06-21 22:31:09 +00003275 if (TagDecl && NonNestedClass) {
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003276 // We are not inside a nested class. This class and its nested classes
Douglas Gregor4d87df52008-12-16 21:30:33 +00003277 // are complete and we can parse the delayed portions of method
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00003278 // declarations and the lexed inline method definitions, along with any
3279 // delayed attributes.
Douglas Gregor428119e2010-06-16 23:45:56 +00003280 SourceLocation SavedPrevTokLocation = PrevTokLocation;
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00003281 ParseLexedAttributes(getCurrentClass());
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003282 ParseLexedMethodDeclarations(getCurrentClass());
Richard Smith84973e52012-04-21 18:42:51 +00003283
3284 // We've finished with all pending member declarations.
3285 Actions.ActOnFinishCXXMemberDecls();
3286
Richard Smith938f40b2011-06-11 17:19:42 +00003287 ParseLexedMemberInitializers(getCurrentClass());
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003288 ParseLexedMethodDefs(getCurrentClass());
Douglas Gregor428119e2010-06-16 23:45:56 +00003289 PrevTokLocation = SavedPrevTokLocation;
Reid Klecknerbba3cb92015-03-17 19:00:50 +00003290
3291 // We've finished parsing everything, including default argument
3292 // initializers.
Hans Wennborg99000c22015-08-15 01:18:16 +00003293 Actions.ActOnFinishCXXNonNestedClass(TagDecl);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003294 }
3295
John McCall08bede42010-05-28 08:11:17 +00003296 if (TagDecl)
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00003297 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getRange());
John McCall2ff380a2010-03-17 00:38:33 +00003298
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003299 // Leave the class scope.
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003300 ParsingDef.Pop();
Douglas Gregor7307d6c2008-12-10 06:34:36 +00003301 ClassScope.Exit();
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003302}
Douglas Gregore8381c02008-11-05 04:29:56 +00003303
Richard Smith2ac43ad2013-11-15 23:00:02 +00003304void Parser::DiagnoseUnexpectedNamespace(NamedDecl *D) {
Richard Smithda35e962013-11-09 04:52:51 +00003305 assert(Tok.is(tok::kw_namespace));
3306
3307 // FIXME: Suggest where the close brace should have gone by looking
3308 // at indentation changes within the definition body.
Richard Smith2ac43ad2013-11-15 23:00:02 +00003309 Diag(D->getLocation(),
3310 diag::err_missing_end_of_definition) << D;
Richard Smithda35e962013-11-09 04:52:51 +00003311 Diag(Tok.getLocation(),
Richard Smith2ac43ad2013-11-15 23:00:02 +00003312 diag::note_missing_end_of_definition_before) << D;
Richard Smithda35e962013-11-09 04:52:51 +00003313
3314 // Push '};' onto the token stream to recover.
3315 PP.EnterToken(Tok);
3316
3317 Tok.startToken();
3318 Tok.setLocation(PP.getLocForEndOfToken(PrevTokLocation));
3319 Tok.setKind(tok::semi);
3320 PP.EnterToken(Tok);
3321
3322 Tok.setKind(tok::r_brace);
3323}
3324
Douglas Gregore8381c02008-11-05 04:29:56 +00003325/// ParseConstructorInitializer - Parse a C++ constructor initializer,
3326/// which explicitly initializes the members or base classes of a
3327/// class (C++ [class.base.init]). For example, the three initializers
3328/// after the ':' in the Derived constructor below:
3329///
3330/// @code
3331/// class Base { };
3332/// class Derived : Base {
3333/// int x;
3334/// float f;
3335/// public:
3336/// Derived(float f) : Base(), x(17), f(f) { }
3337/// };
3338/// @endcode
3339///
Mike Stump11289f42009-09-09 15:08:12 +00003340/// [C++] ctor-initializer:
3341/// ':' mem-initializer-list
Douglas Gregore8381c02008-11-05 04:29:56 +00003342///
Mike Stump11289f42009-09-09 15:08:12 +00003343/// [C++] mem-initializer-list:
Douglas Gregor44e7df62011-01-04 00:32:56 +00003344/// mem-initializer ...[opt]
3345/// mem-initializer ...[opt] , mem-initializer-list
John McCall48871652010-08-21 09:40:31 +00003346void Parser::ParseConstructorInitializer(Decl *ConstructorDecl) {
Nico Weber3b00fdc2015-03-07 19:52:39 +00003347 assert(Tok.is(tok::colon) &&
3348 "Constructor initializer always starts with ':'");
Douglas Gregore8381c02008-11-05 04:29:56 +00003349
Nico Weber3b00fdc2015-03-07 19:52:39 +00003350 // Poison the SEH identifiers so they are flagged as illegal in constructor
3351 // initializers.
John Wiegley1c0675e2011-04-28 01:08:34 +00003352 PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
Douglas Gregore8381c02008-11-05 04:29:56 +00003353 SourceLocation ColonLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +00003354
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003355 SmallVector<CXXCtorInitializer*, 4> MemInitializers;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003356 bool AnyErrors = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003357
Douglas Gregore8381c02008-11-05 04:29:56 +00003358 do {
Douglas Gregoreaeeca92010-08-28 00:00:50 +00003359 if (Tok.is(tok::code_completion)) {
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00003360 Actions.CodeCompleteConstructorInitializer(ConstructorDecl,
3361 MemInitializers);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00003362 return cutOffParsing();
Douglas Gregoreaeeca92010-08-28 00:00:50 +00003363 }
Alexey Bataev79de17d2016-01-20 05:25:51 +00003364
3365 MemInitResult MemInit = ParseMemInitializer(ConstructorDecl);
3366 if (!MemInit.isInvalid())
3367 MemInitializers.push_back(MemInit.get());
3368 else
3369 AnyErrors = true;
3370
Douglas Gregore8381c02008-11-05 04:29:56 +00003371 if (Tok.is(tok::comma))
3372 ConsumeToken();
3373 else if (Tok.is(tok::l_brace))
3374 break;
Alexey Bataev79de17d2016-01-20 05:25:51 +00003375 // If the previous initializer was valid and the next token looks like a
3376 // base or member initializer, assume that we're just missing a comma.
3377 else if (!MemInit.isInvalid() &&
3378 Tok.isOneOf(tok::identifier, tok::coloncolon)) {
Douglas Gregorce66d022010-09-07 14:51:08 +00003379 SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation);
3380 Diag(Loc, diag::err_ctor_init_missing_comma)
3381 << FixItHint::CreateInsertion(Loc, ", ");
3382 } else {
Douglas Gregore8381c02008-11-05 04:29:56 +00003383 // Skip over garbage, until we get to '{'. Don't eat the '{'.
Alexey Bataev79de17d2016-01-20 05:25:51 +00003384 if (!MemInit.isInvalid())
3385 Diag(Tok.getLocation(), diag::err_expected_either) << tok::l_brace
3386 << tok::comma;
Alexey Bataevee6507d2013-11-18 08:17:37 +00003387 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
Douglas Gregore8381c02008-11-05 04:29:56 +00003388 break;
3389 }
3390 } while (true);
3391
David Blaikie3fc2f912013-01-17 05:26:25 +00003392 Actions.ActOnMemInitializers(ConstructorDecl, ColonLoc, MemInitializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003393 AnyErrors);
Douglas Gregore8381c02008-11-05 04:29:56 +00003394}
3395
3396/// ParseMemInitializer - Parse a C++ member initializer, which is
3397/// part of a constructor initializer that explicitly initializes one
3398/// member or base class (C++ [class.base.init]). See
3399/// ParseConstructorInitializer for an example.
3400///
3401/// [C++] mem-initializer:
3402/// mem-initializer-id '(' expression-list[opt] ')'
Sebastian Redl3da34892011-06-05 12:23:16 +00003403/// [C++0x] mem-initializer-id braced-init-list
Mike Stump11289f42009-09-09 15:08:12 +00003404///
Douglas Gregore8381c02008-11-05 04:29:56 +00003405/// [C++] mem-initializer-id:
3406/// '::'[opt] nested-name-specifier[opt] class-name
3407/// identifier
Craig Topper9ad7e262014-10-31 06:57:07 +00003408MemInitResult Parser::ParseMemInitializer(Decl *ConstructorDecl) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00003409 // parse '::'[opt] nested-name-specifier[opt]
3410 CXXScopeSpec SS;
David Blaikieefdccaa2016-01-15 23:43:34 +00003411 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false);
Richard Smithaf3b3252017-05-18 19:21:48 +00003412
3413 // : identifier
3414 IdentifierInfo *II = nullptr;
3415 SourceLocation IdLoc = Tok.getLocation();
3416 // : declype(...)
3417 DeclSpec DS(AttrFactory);
3418 // : template_name<...>
John McCallba7bf592010-08-24 05:47:05 +00003419 ParsedType TemplateTypeTy;
Richard Smithaf3b3252017-05-18 19:21:48 +00003420
3421 if (Tok.is(tok::identifier)) {
3422 // Get the identifier. This may be a member name or a class name,
3423 // but we'll let the semantic analysis determine which it is.
3424 II = Tok.getIdentifierInfo();
3425 ConsumeToken();
3426 } else if (Tok.is(tok::annot_decltype)) {
3427 // Get the decltype expression, if there is one.
3428 // Uses of decltype will already have been converted to annot_decltype by
3429 // ParseOptionalCXXScopeSpecifier at this point.
3430 // FIXME: Can we get here with a scope specifier?
3431 ParseDecltypeSpecifier(DS);
3432 } else {
3433 TemplateIdAnnotation *TemplateId = Tok.is(tok::annot_template_id)
3434 ? takeTemplateIdAnnotation(Tok)
3435 : nullptr;
3436 if (TemplateId && (TemplateId->Kind == TNK_Type_template ||
3437 TemplateId->Kind == TNK_Dependent_template_name)) {
Richard Smith62559bd2017-02-01 21:36:38 +00003438 AnnotateTemplateIdTokenAsType(/*IsClassName*/true);
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00003439 assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
John McCallba7bf592010-08-24 05:47:05 +00003440 TemplateTypeTy = getTypeAnnotation(Tok);
Richard Smithaf3b3252017-05-18 19:21:48 +00003441 ConsumeAnnotationToken();
3442 } else {
3443 Diag(Tok, diag::err_expected_member_or_base_name);
3444 return true;
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00003445 }
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00003446 }
Douglas Gregore8381c02008-11-05 04:29:56 +00003447
3448 // Parse the '('.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003449 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
Richard Smith5d164bc2011-10-15 05:09:34 +00003450 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
3451
Kadir Cetinkaya84774c32018-09-11 15:02:18 +00003452 // FIXME: Add support for signature help inside initializer lists.
Sebastian Redla74948d2011-09-24 17:48:25 +00003453 ExprResult InitList = ParseBraceInitializer();
3454 if (InitList.isInvalid())
3455 return true;
3456
3457 SourceLocation EllipsisLoc;
Alp Toker094e5212014-01-05 03:27:11 +00003458 TryConsumeToken(tok::ellipsis, EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00003459
3460 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
Fangrui Song6907ce22018-07-30 19:24:48 +00003461 TemplateTypeTy, DS, IdLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003462 InitList.get(), EllipsisLoc);
Sebastian Redl3da34892011-06-05 12:23:16 +00003463 } else if(Tok.is(tok::l_paren)) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003464 BalancedDelimiterTracker T(*this, tok::l_paren);
3465 T.consumeOpen();
Douglas Gregore8381c02008-11-05 04:29:56 +00003466
Sebastian Redl3da34892011-06-05 12:23:16 +00003467 // Parse the optional expression-list.
Benjamin Kramerf0623432012-08-23 22:51:59 +00003468 ExprVector ArgExprs;
Sebastian Redl3da34892011-06-05 12:23:16 +00003469 CommaLocsTy CommaLocs;
Kadir Cetinkaya84774c32018-09-11 15:02:18 +00003470 if (Tok.isNot(tok::r_paren) &&
3471 ParseExpressionList(ArgExprs, CommaLocs, [&] {
3472 QualType PreferredType = Actions.ProduceCtorInitMemberSignatureHelp(
3473 getCurScope(), ConstructorDecl, SS, TemplateTypeTy, ArgExprs, II,
3474 T.getOpenLocation());
3475 CalledSignatureHelp = true;
3476 Actions.CodeCompleteExpression(getCurScope(), PreferredType);
3477 })) {
3478 if (PP.isCodeCompletionReached() && !CalledSignatureHelp) {
3479 Actions.ProduceCtorInitMemberSignatureHelp(
3480 getCurScope(), ConstructorDecl, SS, TemplateTypeTy, ArgExprs, II,
3481 T.getOpenLocation());
3482 CalledSignatureHelp = true;
3483 }
Alexey Bataevee6507d2013-11-18 08:17:37 +00003484 SkipUntil(tok::r_paren, StopAtSemi);
Sebastian Redl3da34892011-06-05 12:23:16 +00003485 return true;
3486 }
3487
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003488 T.consumeClose();
Sebastian Redl3da34892011-06-05 12:23:16 +00003489
3490 SourceLocation EllipsisLoc;
Alp Toker97650562014-01-10 11:19:30 +00003491 TryConsumeToken(tok::ellipsis, EllipsisLoc);
Sebastian Redl3da34892011-06-05 12:23:16 +00003492
3493 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
David Blaikie186a8892012-01-24 06:03:59 +00003494 TemplateTypeTy, DS, IdLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00003495 T.getOpenLocation(), ArgExprs,
3496 T.getCloseLocation(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00003497 }
3498
Alp Tokerec543272013-12-24 09:48:30 +00003499 if (getLangOpts().CPlusPlus11)
3500 return Diag(Tok, diag::err_expected_either) << tok::l_paren << tok::l_brace;
3501 else
3502 return Diag(Tok, diag::err_expected) << tok::l_paren;
Douglas Gregore8381c02008-11-05 04:29:56 +00003503}
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003504
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003505/// Parse a C++ exception-specification if present (C++0x [except.spec]).
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003506///
Douglas Gregor356513d2008-12-01 18:00:20 +00003507/// exception-specification:
Sebastian Redl965b0e32011-03-05 14:45:16 +00003508/// dynamic-exception-specification
3509/// noexcept-specification
3510///
3511/// noexcept-specification:
3512/// 'noexcept'
3513/// 'noexcept' '(' constant-expression ')'
3514ExceptionSpecificationType
Richard Smith0b3a4622014-11-13 20:01:57 +00003515Parser::tryParseExceptionSpecification(bool Delayed,
Douglas Gregor433e0532012-04-16 18:27:27 +00003516 SourceRange &SpecificationRange,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003517 SmallVectorImpl<ParsedType> &DynamicExceptions,
3518 SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
Richard Smith0b3a4622014-11-13 20:01:57 +00003519 ExprResult &NoexceptExpr,
3520 CachedTokens *&ExceptionSpecTokens) {
Sebastian Redl965b0e32011-03-05 14:45:16 +00003521 ExceptionSpecificationType Result = EST_None;
Hans Wennborgdcfba332015-10-06 23:40:43 +00003522 ExceptionSpecTokens = nullptr;
Fangrui Song6907ce22018-07-30 19:24:48 +00003523
Richard Smith0b3a4622014-11-13 20:01:57 +00003524 // Handle delayed parsing of exception-specifications.
3525 if (Delayed) {
3526 if (Tok.isNot(tok::kw_throw) && Tok.isNot(tok::kw_noexcept))
3527 return EST_None;
Sebastian Redl965b0e32011-03-05 14:45:16 +00003528
Richard Smith0b3a4622014-11-13 20:01:57 +00003529 // Consume and cache the starting token.
3530 bool IsNoexcept = Tok.is(tok::kw_noexcept);
3531 Token StartTok = Tok;
3532 SpecificationRange = SourceRange(ConsumeToken());
3533
3534 // Check for a '('.
3535 if (!Tok.is(tok::l_paren)) {
3536 // If this is a bare 'noexcept', we're done.
3537 if (IsNoexcept) {
3538 Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
Hans Wennborgdcfba332015-10-06 23:40:43 +00003539 NoexceptExpr = nullptr;
Richard Smith0b3a4622014-11-13 20:01:57 +00003540 return EST_BasicNoexcept;
3541 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003542
Richard Smith0b3a4622014-11-13 20:01:57 +00003543 Diag(Tok, diag::err_expected_lparen_after) << "throw";
3544 return EST_DynamicNone;
3545 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003546
Richard Smith0b3a4622014-11-13 20:01:57 +00003547 // Cache the tokens for the exception-specification.
3548 ExceptionSpecTokens = new CachedTokens;
3549 ExceptionSpecTokens->push_back(StartTok); // 'throw' or 'noexcept'
3550 ExceptionSpecTokens->push_back(Tok); // '('
3551 SpecificationRange.setEnd(ConsumeParen()); // '('
Richard Smithb1c217e2015-01-13 02:24:58 +00003552
3553 ConsumeAndStoreUntil(tok::r_paren, *ExceptionSpecTokens,
3554 /*StopAtSemi=*/true,
3555 /*ConsumeFinalToken=*/true);
Aaron Ballman580ccaf2016-01-12 21:04:22 +00003556 SpecificationRange.setEnd(ExceptionSpecTokens->back().getLocation());
3557
Richard Smith0b3a4622014-11-13 20:01:57 +00003558 return EST_Unparsed;
3559 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003560
Sebastian Redl965b0e32011-03-05 14:45:16 +00003561 // See if there's a dynamic specification.
3562 if (Tok.is(tok::kw_throw)) {
3563 Result = ParseDynamicExceptionSpecification(SpecificationRange,
3564 DynamicExceptions,
3565 DynamicExceptionRanges);
3566 assert(DynamicExceptions.size() == DynamicExceptionRanges.size() &&
3567 "Produced different number of exception types and ranges.");
3568 }
3569
3570 // If there's no noexcept specification, we're done.
3571 if (Tok.isNot(tok::kw_noexcept))
3572 return Result;
3573
Richard Smithb15c11c2011-10-17 23:06:20 +00003574 Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
3575
Sebastian Redl965b0e32011-03-05 14:45:16 +00003576 // If we already had a dynamic specification, parse the noexcept for,
3577 // recovery, but emit a diagnostic and don't store the results.
3578 SourceRange NoexceptRange;
3579 ExceptionSpecificationType NoexceptType = EST_None;
3580
3581 SourceLocation KeywordLoc = ConsumeToken();
3582 if (Tok.is(tok::l_paren)) {
3583 // There is an argument.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003584 BalancedDelimiterTracker T(*this, tok::l_paren);
3585 T.consumeOpen();
Sebastian Redl965b0e32011-03-05 14:45:16 +00003586 NoexceptExpr = ParseConstantExpression();
Serge Pavlov3739f5e72015-06-29 17:50:19 +00003587 T.consumeClose();
Serge Pavlov3739f5e72015-06-29 17:50:19 +00003588 if (!NoexceptExpr.isInvalid()) {
Richard Smitheaf11ad2018-05-03 03:58:32 +00003589 NoexceptExpr = Actions.ActOnNoexceptSpec(KeywordLoc, NoexceptExpr.get(),
3590 NoexceptType);
Serge Pavlov3739f5e72015-06-29 17:50:19 +00003591 NoexceptRange = SourceRange(KeywordLoc, T.getCloseLocation());
3592 } else {
Malcolm Parsonsa3220ce2017-01-12 16:11:28 +00003593 NoexceptType = EST_BasicNoexcept;
Serge Pavlov3739f5e72015-06-29 17:50:19 +00003594 }
Sebastian Redl965b0e32011-03-05 14:45:16 +00003595 } else {
3596 // There is no argument.
3597 NoexceptType = EST_BasicNoexcept;
3598 NoexceptRange = SourceRange(KeywordLoc, KeywordLoc);
3599 }
3600
3601 if (Result == EST_None) {
3602 SpecificationRange = NoexceptRange;
3603 Result = NoexceptType;
3604
3605 // If there's a dynamic specification after a noexcept specification,
3606 // parse that and ignore the results.
3607 if (Tok.is(tok::kw_throw)) {
3608 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
3609 ParseDynamicExceptionSpecification(NoexceptRange, DynamicExceptions,
3610 DynamicExceptionRanges);
3611 }
3612 } else {
3613 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
3614 }
3615
3616 return Result;
3617}
3618
Richard Smith8ca78a12013-06-13 02:02:51 +00003619static void diagnoseDynamicExceptionSpecification(
Craig Toppere335f252015-10-04 04:53:55 +00003620 Parser &P, SourceRange Range, bool IsNoexcept) {
Richard Smith8ca78a12013-06-13 02:02:51 +00003621 if (P.getLangOpts().CPlusPlus11) {
3622 const char *Replacement = IsNoexcept ? "noexcept" : "noexcept(false)";
Richard Smith82da19d2016-12-08 02:49:07 +00003623 P.Diag(Range.getBegin(),
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003624 P.getLangOpts().CPlusPlus17 && !IsNoexcept
Richard Smith82da19d2016-12-08 02:49:07 +00003625 ? diag::ext_dynamic_exception_spec
3626 : diag::warn_exception_spec_deprecated)
3627 << Range;
Richard Smith8ca78a12013-06-13 02:02:51 +00003628 P.Diag(Range.getBegin(), diag::note_exception_spec_deprecated)
3629 << Replacement << FixItHint::CreateReplacement(Range, Replacement);
3630 }
3631}
3632
Sebastian Redl965b0e32011-03-05 14:45:16 +00003633/// ParseDynamicExceptionSpecification - Parse a C++
3634/// dynamic-exception-specification (C++ [except.spec]).
3635///
3636/// dynamic-exception-specification:
Douglas Gregor356513d2008-12-01 18:00:20 +00003637/// 'throw' '(' type-id-list [opt] ')'
3638/// [MS] 'throw' '(' '...' ')'
Mike Stump11289f42009-09-09 15:08:12 +00003639///
Douglas Gregor356513d2008-12-01 18:00:20 +00003640/// type-id-list:
Douglas Gregor830837d2010-12-20 23:57:46 +00003641/// type-id ... [opt]
3642/// type-id-list ',' type-id ... [opt]
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003643///
Sebastian Redl965b0e32011-03-05 14:45:16 +00003644ExceptionSpecificationType Parser::ParseDynamicExceptionSpecification(
3645 SourceRange &SpecificationRange,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003646 SmallVectorImpl<ParsedType> &Exceptions,
3647 SmallVectorImpl<SourceRange> &Ranges) {
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003648 assert(Tok.is(tok::kw_throw) && "expected throw");
Mike Stump11289f42009-09-09 15:08:12 +00003649
Sebastian Redl965b0e32011-03-05 14:45:16 +00003650 SpecificationRange.setBegin(ConsumeToken());
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003651 BalancedDelimiterTracker T(*this, tok::l_paren);
3652 if (T.consumeOpen()) {
Sebastian Redl965b0e32011-03-05 14:45:16 +00003653 Diag(Tok, diag::err_expected_lparen_after) << "throw";
3654 SpecificationRange.setEnd(SpecificationRange.getBegin());
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003655 return EST_DynamicNone;
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003656 }
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003657
Douglas Gregor356513d2008-12-01 18:00:20 +00003658 // Parse throw(...), a Microsoft extension that means "this function
3659 // can throw anything".
3660 if (Tok.is(tok::ellipsis)) {
3661 SourceLocation EllipsisLoc = ConsumeToken();
David Blaikiebbafb8a2012-03-11 07:00:24 +00003662 if (!getLangOpts().MicrosoftExt)
Douglas Gregor356513d2008-12-01 18:00:20 +00003663 Diag(EllipsisLoc, diag::ext_ellipsis_exception_spec);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003664 T.consumeClose();
3665 SpecificationRange.setEnd(T.getCloseLocation());
Richard Smith8ca78a12013-06-13 02:02:51 +00003666 diagnoseDynamicExceptionSpecification(*this, SpecificationRange, false);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003667 return EST_MSAny;
Douglas Gregor356513d2008-12-01 18:00:20 +00003668 }
3669
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003670 // Parse the sequence of type-ids.
Sebastian Redld6434562009-05-29 18:02:33 +00003671 SourceRange Range;
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003672 while (Tok.isNot(tok::r_paren)) {
Sebastian Redld6434562009-05-29 18:02:33 +00003673 TypeResult Res(ParseTypeName(&Range));
Sebastian Redl965b0e32011-03-05 14:45:16 +00003674
Douglas Gregor830837d2010-12-20 23:57:46 +00003675 if (Tok.is(tok::ellipsis)) {
3676 // C++0x [temp.variadic]p5:
Fangrui Song6907ce22018-07-30 19:24:48 +00003677 // - In a dynamic-exception-specification (15.4); the pattern is a
Douglas Gregor830837d2010-12-20 23:57:46 +00003678 // type-id.
3679 SourceLocation Ellipsis = ConsumeToken();
Sebastian Redl965b0e32011-03-05 14:45:16 +00003680 Range.setEnd(Ellipsis);
Douglas Gregor830837d2010-12-20 23:57:46 +00003681 if (!Res.isInvalid())
3682 Res = Actions.ActOnPackExpansion(Res.get(), Ellipsis);
3683 }
Sebastian Redl965b0e32011-03-05 14:45:16 +00003684
Sebastian Redld6434562009-05-29 18:02:33 +00003685 if (!Res.isInvalid()) {
Sebastian Redl2b9cacb2009-04-29 17:30:04 +00003686 Exceptions.push_back(Res.get());
Sebastian Redld6434562009-05-29 18:02:33 +00003687 Ranges.push_back(Range);
3688 }
Alp Toker97650562014-01-10 11:19:30 +00003689
3690 if (!TryConsumeToken(tok::comma))
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003691 break;
3692 }
3693
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003694 T.consumeClose();
3695 SpecificationRange.setEnd(T.getCloseLocation());
Richard Smith8ca78a12013-06-13 02:02:51 +00003696 diagnoseDynamicExceptionSpecification(*this, SpecificationRange,
3697 Exceptions.empty());
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003698 return Exceptions.empty() ? EST_DynamicNone : EST_Dynamic;
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003699}
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003700
Douglas Gregor7fb25412010-10-01 18:44:50 +00003701/// ParseTrailingReturnType - Parse a trailing return type on a new-style
3702/// function declaration.
Richard Smithe303e352018-02-02 22:24:54 +00003703TypeResult Parser::ParseTrailingReturnType(SourceRange &Range,
3704 bool MayBeFollowedByDirectInit) {
Douglas Gregor7fb25412010-10-01 18:44:50 +00003705 assert(Tok.is(tok::arrow) && "expected arrow");
3706
3707 ConsumeToken();
3708
Richard Smithe303e352018-02-02 22:24:54 +00003709 return ParseTypeName(&Range, MayBeFollowedByDirectInit
3710 ? DeclaratorContext::TrailingReturnVarContext
3711 : DeclaratorContext::TrailingReturnContext);
Douglas Gregor7fb25412010-10-01 18:44:50 +00003712}
3713
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003714/// We have just started parsing the definition of a new class,
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003715/// so push that class onto our stack of classes that is currently
3716/// being parsed.
John McCallc1465822011-02-14 07:13:47 +00003717Sema::ParsingClassState
John McCalldb632ac2012-09-25 07:32:39 +00003718Parser::PushParsingClass(Decl *ClassDecl, bool NonNestedClass,
3719 bool IsInterface) {
Douglas Gregoredf8f392010-01-16 20:52:59 +00003720 assert((NonNestedClass || !ClassStack.empty()) &&
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003721 "Nested class without outer class");
John McCalldb632ac2012-09-25 07:32:39 +00003722 ClassStack.push(new ParsingClass(ClassDecl, NonNestedClass, IsInterface));
John McCallc1465822011-02-14 07:13:47 +00003723 return Actions.PushParsingClass();
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003724}
3725
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003726/// Deallocate the given parsed class and all of its nested
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003727/// classes.
3728void Parser::DeallocateParsedClasses(Parser::ParsingClass *Class) {
Douglas Gregorefc46952010-10-12 16:25:54 +00003729 for (unsigned I = 0, N = Class->LateParsedDeclarations.size(); I != N; ++I)
3730 delete Class->LateParsedDeclarations[I];
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003731 delete Class;
3732}
3733
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003734/// Pop the top class of the stack of classes that are
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003735/// currently being parsed.
3736///
3737/// This routine should be called when we have finished parsing the
3738/// definition of a class, but have not yet popped the Scope
3739/// associated with the class's definition.
John McCallc1465822011-02-14 07:13:47 +00003740void Parser::PopParsingClass(Sema::ParsingClassState state) {
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003741 assert(!ClassStack.empty() && "Mismatched push/pop for class parsing");
Mike Stump11289f42009-09-09 15:08:12 +00003742
John McCallc1465822011-02-14 07:13:47 +00003743 Actions.PopParsingClass(state);
3744
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003745 ParsingClass *Victim = ClassStack.top();
3746 ClassStack.pop();
3747 if (Victim->TopLevelClass) {
3748 // Deallocate all of the nested classes of this class,
3749 // recursively: we don't need to keep any of this information.
3750 DeallocateParsedClasses(Victim);
3751 return;
Mike Stump11289f42009-09-09 15:08:12 +00003752 }
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003753 assert(!ClassStack.empty() && "Missing top-level class?");
3754
Douglas Gregorefc46952010-10-12 16:25:54 +00003755 if (Victim->LateParsedDeclarations.empty()) {
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003756 // The victim is a nested class, but we will not need to perform
3757 // any processing after the definition of this class since it has
3758 // no members whose handling was delayed. Therefore, we can just
3759 // remove this nested class.
Douglas Gregorefc46952010-10-12 16:25:54 +00003760 DeallocateParsedClasses(Victim);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003761 return;
3762 }
3763
3764 // This nested class has some members that will need to be processed
3765 // after the top-level class is completely defined. Therefore, add
3766 // it to the list of nested classes within its parent.
Douglas Gregor0be31a22010-07-02 17:43:08 +00003767 assert(getCurScope()->isClassScope() && "Nested class outside of class scope?");
Douglas Gregorefc46952010-10-12 16:25:54 +00003768 ClassStack.top()->LateParsedDeclarations.push_back(new LateParsedClass(this, Victim));
Douglas Gregor0be31a22010-07-02 17:43:08 +00003769 Victim->TemplateScope = getCurScope()->getParent()->isTemplateParamScope();
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003770}
Alexis Hunt96d5c762009-11-21 08:43:09 +00003771
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003772/// Try to parse an 'identifier' which appears within an attribute-token.
Richard Smith3dff2512012-04-10 03:25:07 +00003773///
3774/// \return the parsed identifier on success, and 0 if the next token is not an
3775/// attribute-token.
3776///
3777/// C++11 [dcl.attr.grammar]p3:
3778/// If a keyword or an alternative token that satisfies the syntactic
3779/// requirements of an identifier is contained in an attribute-token,
3780/// it is considered an identifier.
3781IdentifierInfo *Parser::TryParseCXX11AttributeIdentifier(SourceLocation &Loc) {
3782 switch (Tok.getKind()) {
3783 default:
3784 // Identifiers and keywords have identifier info attached.
David Majnemerd5271992015-01-09 18:09:39 +00003785 if (!Tok.isAnnotation()) {
3786 if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
3787 Loc = ConsumeToken();
3788 return II;
3789 }
Richard Smith3dff2512012-04-10 03:25:07 +00003790 }
Craig Topper161e4db2014-05-21 06:02:52 +00003791 return nullptr;
Richard Smith3dff2512012-04-10 03:25:07 +00003792
3793 case tok::ampamp: // 'and'
3794 case tok::pipe: // 'bitor'
3795 case tok::pipepipe: // 'or'
3796 case tok::caret: // 'xor'
3797 case tok::tilde: // 'compl'
3798 case tok::amp: // 'bitand'
3799 case tok::ampequal: // 'and_eq'
3800 case tok::pipeequal: // 'or_eq'
3801 case tok::caretequal: // 'xor_eq'
3802 case tok::exclaim: // 'not'
3803 case tok::exclaimequal: // 'not_eq'
3804 // Alternative tokens do not have identifier info, but their spelling
3805 // starts with an alphabetical character.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003806 SmallString<8> SpellingBuf;
Benjamin Kramer60be5632015-03-29 19:25:07 +00003807 SourceLocation SpellingLoc =
3808 PP.getSourceManager().getSpellingLoc(Tok.getLocation());
3809 StringRef Spelling = PP.getSpelling(SpellingLoc, SpellingBuf);
Jordan Rosea7d03842013-02-08 22:30:41 +00003810 if (isLetter(Spelling[0])) {
Richard Smith3dff2512012-04-10 03:25:07 +00003811 Loc = ConsumeToken();
Benjamin Kramer5c17f9c2012-04-22 20:43:30 +00003812 return &PP.getIdentifierTable().get(Spelling);
Richard Smith3dff2512012-04-10 03:25:07 +00003813 }
Craig Topper161e4db2014-05-21 06:02:52 +00003814 return nullptr;
Richard Smith3dff2512012-04-10 03:25:07 +00003815 }
3816}
3817
Michael Han23214e52012-10-03 01:56:22 +00003818static bool IsBuiltInOrStandardCXX11Attribute(IdentifierInfo *AttrName,
Aaron Ballman606093a2017-10-15 15:01:42 +00003819 IdentifierInfo *ScopeName) {
Erich Keanee891aa92018-07-13 15:07:47 +00003820 switch (ParsedAttr::getKind(AttrName, ScopeName, ParsedAttr::AS_CXX11)) {
3821 case ParsedAttr::AT_CarriesDependency:
3822 case ParsedAttr::AT_Deprecated:
3823 case ParsedAttr::AT_FallThrough:
3824 case ParsedAttr::AT_CXX11NoReturn:
Michael Han23214e52012-10-03 01:56:22 +00003825 return true;
Erich Keanee891aa92018-07-13 15:07:47 +00003826 case ParsedAttr::AT_WarnUnusedResult:
Aaron Ballmane7964782016-03-07 22:44:55 +00003827 return !ScopeName && AttrName->getName().equals("nodiscard");
Erich Keanee891aa92018-07-13 15:07:47 +00003828 case ParsedAttr::AT_Unused:
Nico Weberac03bce2016-08-23 19:59:55 +00003829 return !ScopeName && AttrName->getName().equals("maybe_unused");
Michael Han23214e52012-10-03 01:56:22 +00003830 default:
3831 return false;
3832 }
3833}
3834
Aaron Ballmanb8e20392014-03-31 17:32:39 +00003835/// ParseCXX11AttributeArgs -- Parse a C++11 attribute-argument-clause.
3836///
3837/// [C++11] attribute-argument-clause:
3838/// '(' balanced-token-seq ')'
3839///
3840/// [C++11] balanced-token-seq:
3841/// balanced-token
3842/// balanced-token-seq balanced-token
3843///
3844/// [C++11] balanced-token:
3845/// '(' balanced-token-seq ')'
3846/// '[' balanced-token-seq ']'
3847/// '{' balanced-token-seq '}'
3848/// any token but '(', ')', '[', ']', '{', or '}'
3849bool Parser::ParseCXX11AttributeArgs(IdentifierInfo *AttrName,
3850 SourceLocation AttrNameLoc,
3851 ParsedAttributes &Attrs,
3852 SourceLocation *EndLoc,
3853 IdentifierInfo *ScopeName,
3854 SourceLocation ScopeLoc) {
3855 assert(Tok.is(tok::l_paren) && "Not a C++11 attribute argument list");
Aaron Ballman35f94212014-04-14 16:03:22 +00003856 SourceLocation LParenLoc = Tok.getLocation();
Aaron Ballman606093a2017-10-15 15:01:42 +00003857 const LangOptions &LO = getLangOpts();
Erich Keanee891aa92018-07-13 15:07:47 +00003858 ParsedAttr::Syntax Syntax =
3859 LO.CPlusPlus ? ParsedAttr::AS_CXX11 : ParsedAttr::AS_C2x;
Aaron Ballmanb8e20392014-03-31 17:32:39 +00003860
3861 // If the attribute isn't known, we will not attempt to parse any
3862 // arguments.
Aaron Ballman606093a2017-10-15 15:01:42 +00003863 if (!hasAttribute(LO.CPlusPlus ? AttrSyntax::CXX : AttrSyntax::C, ScopeName,
3864 AttrName, getTargetInfo(), getLangOpts())) {
Aaron Ballmanb8e20392014-03-31 17:32:39 +00003865 // Eat the left paren, then skip to the ending right paren.
3866 ConsumeParen();
3867 SkipUntil(tok::r_paren);
3868 return false;
3869 }
3870
Alex Lorenzd5d27e12017-03-01 18:06:25 +00003871 if (ScopeName && ScopeName->getName() == "gnu") {
Aaron Ballmanb8e20392014-03-31 17:32:39 +00003872 // GNU-scoped attributes have some special cases to handle GNU-specific
3873 // behaviors.
3874 ParseGNUAttributeArgs(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
Aaron Ballman606093a2017-10-15 15:01:42 +00003875 ScopeLoc, Syntax, nullptr);
Alex Lorenzd5d27e12017-03-01 18:06:25 +00003876 return true;
3877 }
3878
3879 unsigned NumArgs;
3880 // Some Clang-scoped attributes have some special parsing behavior.
3881 if (ScopeName && ScopeName->getName() == "clang")
3882 NumArgs =
3883 ParseClangAttributeArgs(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
Aaron Ballman606093a2017-10-15 15:01:42 +00003884 ScopeLoc, Syntax);
Alex Lorenzd5d27e12017-03-01 18:06:25 +00003885 else
3886 NumArgs =
Aaron Ballman35f94212014-04-14 16:03:22 +00003887 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc,
Aaron Ballman606093a2017-10-15 15:01:42 +00003888 ScopeName, ScopeLoc, Syntax);
Alex Lorenzd5d27e12017-03-01 18:06:25 +00003889
Erich Keanec480f302018-07-12 21:09:05 +00003890 if (!Attrs.empty() &&
3891 IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName)) {
Michael Krusedc5ce722018-08-03 01:21:16 +00003892 ParsedAttr &Attr = Attrs.back();
Alex Lorenzd5d27e12017-03-01 18:06:25 +00003893 // If the attribute is a standard or built-in attribute and we are
3894 // parsing an argument list, we need to determine whether this attribute
3895 // was allowed to have an argument list (such as [[deprecated]]), and how
3896 // many arguments were parsed (so we can diagnose on [[deprecated()]]).
Erich Keanec480f302018-07-12 21:09:05 +00003897 if (Attr.getMaxArgs() && !NumArgs) {
Alex Lorenzd5d27e12017-03-01 18:06:25 +00003898 // The attribute was allowed to have arguments, but none were provided
3899 // even though the attribute parsed successfully. This is an error.
3900 Diag(LParenLoc, diag::err_attribute_requires_arguments) << AttrName;
Erich Keanec480f302018-07-12 21:09:05 +00003901 Attr.setInvalid(true);
3902 } else if (!Attr.getMaxArgs()) {
Alex Lorenzd5d27e12017-03-01 18:06:25 +00003903 // The attribute parsed successfully, but was not allowed to have any
3904 // arguments. It doesn't matter whether any were provided -- the
3905 // presence of the argument list (even if empty) is diagnosed.
3906 Diag(LParenLoc, diag::err_cxx11_attribute_forbids_arguments)
3907 << AttrName
3908 << FixItHint::CreateRemoval(SourceRange(LParenLoc, *EndLoc));
Erich Keanec480f302018-07-12 21:09:05 +00003909 Attr.setInvalid(true);
Aaron Ballman35f94212014-04-14 16:03:22 +00003910 }
3911 }
Aaron Ballmanb8e20392014-03-31 17:32:39 +00003912 return true;
3913}
3914
Aaron Ballman606093a2017-10-15 15:01:42 +00003915/// ParseCXX11AttributeSpecifier - Parse a C++11 or C2x attribute-specifier.
Alexis Hunt96d5c762009-11-21 08:43:09 +00003916///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003917/// [C++11] attribute-specifier:
Alexis Hunt96d5c762009-11-21 08:43:09 +00003918/// '[' '[' attribute-list ']' ']'
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00003919/// alignment-specifier
Alexis Hunt96d5c762009-11-21 08:43:09 +00003920///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003921/// [C++11] attribute-list:
Alexis Hunt96d5c762009-11-21 08:43:09 +00003922/// attribute[opt]
3923/// attribute-list ',' attribute[opt]
Richard Smith3dff2512012-04-10 03:25:07 +00003924/// attribute '...'
3925/// attribute-list ',' attribute '...'
Alexis Hunt96d5c762009-11-21 08:43:09 +00003926///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003927/// [C++11] attribute:
Alexis Hunt96d5c762009-11-21 08:43:09 +00003928/// attribute-token attribute-argument-clause[opt]
3929///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003930/// [C++11] attribute-token:
Alexis Hunt96d5c762009-11-21 08:43:09 +00003931/// identifier
3932/// attribute-scoped-token
3933///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003934/// [C++11] attribute-scoped-token:
Alexis Hunt96d5c762009-11-21 08:43:09 +00003935/// attribute-namespace '::' identifier
3936///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003937/// [C++11] attribute-namespace:
Alexis Hunt96d5c762009-11-21 08:43:09 +00003938/// identifier
Richard Smith3dff2512012-04-10 03:25:07 +00003939void Parser::ParseCXX11AttributeSpecifier(ParsedAttributes &attrs,
Peter Collingbourne49eedec2011-09-29 18:04:05 +00003940 SourceLocation *endLoc) {
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00003941 if (Tok.is(tok::kw_alignas)) {
Richard Smithf679b5b2011-10-14 20:48:27 +00003942 Diag(Tok.getLocation(), diag::warn_cxx98_compat_alignas);
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00003943 ParseAlignmentSpecifier(attrs, endLoc);
3944 return;
3945 }
3946
Aaron Ballman606093a2017-10-15 15:01:42 +00003947 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square) &&
3948 "Not a double square bracket attribute list");
Alexis Hunt96d5c762009-11-21 08:43:09 +00003949
Richard Smithf679b5b2011-10-14 20:48:27 +00003950 Diag(Tok.getLocation(), diag::warn_cxx98_compat_attribute);
3951
Alexis Hunt96d5c762009-11-21 08:43:09 +00003952 ConsumeBracket();
3953 ConsumeBracket();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003954
Richard Smithb7d7a042016-06-24 12:15:12 +00003955 SourceLocation CommonScopeLoc;
3956 IdentifierInfo *CommonScopeName = nullptr;
3957 if (Tok.is(tok::kw_using)) {
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003958 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
Richard Smithb7d7a042016-06-24 12:15:12 +00003959 ? diag::warn_cxx14_compat_using_attribute_ns
3960 : diag::ext_using_attribute_ns);
3961 ConsumeToken();
3962
3963 CommonScopeName = TryParseCXX11AttributeIdentifier(CommonScopeLoc);
3964 if (!CommonScopeName) {
3965 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
3966 SkipUntil(tok::r_square, tok::colon, StopBeforeMatch);
3967 }
3968 if (!TryConsumeToken(tok::colon) && CommonScopeName)
3969 Diag(Tok.getLocation(), diag::err_expected) << tok::colon;
3970 }
3971
Richard Smith10876ef2013-01-17 01:30:42 +00003972 llvm::SmallDenseMap<IdentifierInfo*, SourceLocation, 4> SeenAttrs;
3973
Richard Smith3dff2512012-04-10 03:25:07 +00003974 while (Tok.isNot(tok::r_square)) {
Alexis Hunt96d5c762009-11-21 08:43:09 +00003975 // attribute not present
Alp Toker97650562014-01-10 11:19:30 +00003976 if (TryConsumeToken(tok::comma))
Alexis Hunt96d5c762009-11-21 08:43:09 +00003977 continue;
Alexis Hunt96d5c762009-11-21 08:43:09 +00003978
Richard Smith3dff2512012-04-10 03:25:07 +00003979 SourceLocation ScopeLoc, AttrLoc;
Craig Topper161e4db2014-05-21 06:02:52 +00003980 IdentifierInfo *ScopeName = nullptr, *AttrName = nullptr;
Richard Smith3dff2512012-04-10 03:25:07 +00003981
3982 AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
3983 if (!AttrName)
3984 // Break out to the "expected ']'" diagnostic.
3985 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003986
Alexis Hunt96d5c762009-11-21 08:43:09 +00003987 // scoped attribute
Alp Toker97650562014-01-10 11:19:30 +00003988 if (TryConsumeToken(tok::coloncolon)) {
Richard Smith3dff2512012-04-10 03:25:07 +00003989 ScopeName = AttrName;
3990 ScopeLoc = AttrLoc;
3991
3992 AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
3993 if (!AttrName) {
Alp Tokerec543272013-12-24 09:48:30 +00003994 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
Alexey Bataevee6507d2013-11-18 08:17:37 +00003995 SkipUntil(tok::r_square, tok::comma, StopAtSemi | StopBeforeMatch);
Alexis Hunt96d5c762009-11-21 08:43:09 +00003996 continue;
3997 }
Alexis Hunt96d5c762009-11-21 08:43:09 +00003998 }
3999
Richard Smithb7d7a042016-06-24 12:15:12 +00004000 if (CommonScopeName) {
4001 if (ScopeName) {
4002 Diag(ScopeLoc, diag::err_using_attribute_ns_conflict)
4003 << SourceRange(CommonScopeLoc);
4004 } else {
4005 ScopeName = CommonScopeName;
4006 ScopeLoc = CommonScopeLoc;
4007 }
4008 }
4009
Aaron Ballmanb8e20392014-03-31 17:32:39 +00004010 bool StandardAttr = IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName);
Alexis Hunt96d5c762009-11-21 08:43:09 +00004011 bool AttrParsed = false;
Alexis Hunt96d5c762009-11-21 08:43:09 +00004012
Richard Smith10876ef2013-01-17 01:30:42 +00004013 if (StandardAttr &&
4014 !SeenAttrs.insert(std::make_pair(AttrName, AttrLoc)).second)
4015 Diag(AttrLoc, diag::err_cxx11_attribute_repeated)
Aaron Ballmanb8e20392014-03-31 17:32:39 +00004016 << AttrName << SourceRange(SeenAttrs[AttrName]);
Richard Smith10876ef2013-01-17 01:30:42 +00004017
Michael Han23214e52012-10-03 01:56:22 +00004018 // Parse attribute arguments
Aaron Ballman35f94212014-04-14 16:03:22 +00004019 if (Tok.is(tok::l_paren))
Aaron Ballmanb8e20392014-03-31 17:32:39 +00004020 AttrParsed = ParseCXX11AttributeArgs(AttrName, AttrLoc, attrs, endLoc,
4021 ScopeName, ScopeLoc);
Michael Han23214e52012-10-03 01:56:22 +00004022
4023 if (!AttrParsed)
Aaron Ballman606093a2017-10-15 15:01:42 +00004024 attrs.addNew(
4025 AttrName,
4026 SourceRange(ScopeLoc.isValid() ? ScopeLoc : AttrLoc, AttrLoc),
4027 ScopeName, ScopeLoc, nullptr, 0,
Erich Keanee891aa92018-07-13 15:07:47 +00004028 getLangOpts().CPlusPlus ? ParsedAttr::AS_CXX11 : ParsedAttr::AS_C2x);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004029
Alp Toker97650562014-01-10 11:19:30 +00004030 if (TryConsumeToken(tok::ellipsis))
Michael Han23214e52012-10-03 01:56:22 +00004031 Diag(Tok, diag::err_cxx11_attribute_forbids_ellipsis)
Richard Trieub4025802018-03-28 04:16:13 +00004032 << AttrName;
Alexis Hunt96d5c762009-11-21 08:43:09 +00004033 }
4034
Alp Toker383d2c42014-01-01 03:08:43 +00004035 if (ExpectAndConsume(tok::r_square))
Alexey Bataevee6507d2013-11-18 08:17:37 +00004036 SkipUntil(tok::r_square);
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004037 if (endLoc)
4038 *endLoc = Tok.getLocation();
Alp Toker383d2c42014-01-01 03:08:43 +00004039 if (ExpectAndConsume(tok::r_square))
Alexey Bataevee6507d2013-11-18 08:17:37 +00004040 SkipUntil(tok::r_square);
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004041}
Alexis Hunt96d5c762009-11-21 08:43:09 +00004042
Aaron Ballman606093a2017-10-15 15:01:42 +00004043/// ParseCXX11Attributes - Parse a C++11 or C2x attribute-specifier-seq.
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004044///
4045/// attribute-specifier-seq:
4046/// attribute-specifier-seq[opt] attribute-specifier
Richard Smith3dff2512012-04-10 03:25:07 +00004047void Parser::ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004048 SourceLocation *endLoc) {
Aaron Ballman606093a2017-10-15 15:01:42 +00004049 assert(standardAttributesAllowed());
Richard Smith4cabd042013-02-22 09:15:49 +00004050
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004051 SourceLocation StartLoc = Tok.getLocation(), Loc;
4052 if (!endLoc)
4053 endLoc = &Loc;
4054
Douglas Gregor6f981002011-10-07 20:35:25 +00004055 do {
Richard Smith3dff2512012-04-10 03:25:07 +00004056 ParseCXX11AttributeSpecifier(attrs, endLoc);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004057 } while (isCXX11AttributeSpecifier());
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004058
4059 attrs.Range = SourceRange(StartLoc, *endLoc);
Alexis Hunt96d5c762009-11-21 08:43:09 +00004060}
4061
Richard Smithc2c8bb82013-10-15 01:34:54 +00004062void Parser::DiagnoseAndSkipCXX11Attributes() {
Richard Smithc2c8bb82013-10-15 01:34:54 +00004063 // Start and end location of an attribute or an attribute list.
4064 SourceLocation StartLoc = Tok.getLocation();
Richard Smith955bf012014-06-19 11:42:00 +00004065 SourceLocation EndLoc = SkipCXX11Attributes();
4066
4067 if (EndLoc.isValid()) {
4068 SourceRange Range(StartLoc, EndLoc);
4069 Diag(StartLoc, diag::err_attributes_not_allowed)
4070 << Range;
4071 }
4072}
4073
4074SourceLocation Parser::SkipCXX11Attributes() {
Richard Smithc2c8bb82013-10-15 01:34:54 +00004075 SourceLocation EndLoc;
4076
Richard Smith955bf012014-06-19 11:42:00 +00004077 if (!isCXX11AttributeSpecifier())
4078 return EndLoc;
4079
Richard Smithc2c8bb82013-10-15 01:34:54 +00004080 do {
4081 if (Tok.is(tok::l_square)) {
4082 BalancedDelimiterTracker T(*this, tok::l_square);
4083 T.consumeOpen();
4084 T.skipToEnd();
4085 EndLoc = T.getCloseLocation();
4086 } else {
4087 assert(Tok.is(tok::kw_alignas) && "not an attribute specifier");
4088 ConsumeToken();
4089 BalancedDelimiterTracker T(*this, tok::l_paren);
4090 if (!T.consumeOpen())
4091 T.skipToEnd();
4092 EndLoc = T.getCloseLocation();
4093 }
4094 } while (isCXX11AttributeSpecifier());
4095
Richard Smith955bf012014-06-19 11:42:00 +00004096 return EndLoc;
Richard Smithc2c8bb82013-10-15 01:34:54 +00004097}
4098
Nico Weber05e1dad2016-09-03 03:25:22 +00004099/// Parse uuid() attribute when it appears in a [] Microsoft attribute.
4100void Parser::ParseMicrosoftUuidAttributeArgs(ParsedAttributes &Attrs) {
4101 assert(Tok.is(tok::identifier) && "Not a Microsoft attribute list");
4102 IdentifierInfo *UuidIdent = Tok.getIdentifierInfo();
4103 assert(UuidIdent->getName() == "uuid" && "Not a Microsoft attribute list");
4104
4105 SourceLocation UuidLoc = Tok.getLocation();
4106 ConsumeToken();
4107
4108 // Ignore the left paren location for now.
4109 BalancedDelimiterTracker T(*this, tok::l_paren);
4110 if (T.consumeOpen()) {
4111 Diag(Tok, diag::err_expected) << tok::l_paren;
4112 return;
4113 }
4114
4115 ArgsVector ArgExprs;
4116 if (Tok.is(tok::string_literal)) {
4117 // Easy case: uuid("...") -- quoted string.
4118 ExprResult StringResult = ParseStringLiteralExpression();
4119 if (StringResult.isInvalid())
4120 return;
4121 ArgExprs.push_back(StringResult.get());
4122 } else {
4123 // something like uuid({000000A0-0000-0000-C000-000000000049}) -- no
4124 // quotes in the parens. Just append the spelling of all tokens encountered
4125 // until the closing paren.
4126
4127 SmallString<42> StrBuffer; // 2 "", 36 bytes UUID, 2 optional {}, 1 nul
4128 StrBuffer += "\"";
4129
4130 // Since none of C++'s keywords match [a-f]+, accepting just tok::l_brace,
4131 // tok::r_brace, tok::minus, tok::identifier (think C000) and
4132 // tok::numeric_constant (0000) should be enough. But the spelling of the
4133 // uuid argument is checked later anyways, so there's no harm in accepting
4134 // almost anything here.
4135 // cl is very strict about whitespace in this form and errors out if any
4136 // is present, so check the space flags on the tokens.
4137 SourceLocation StartLoc = Tok.getLocation();
4138 while (Tok.isNot(tok::r_paren)) {
4139 if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
4140 Diag(Tok, diag::err_attribute_uuid_malformed_guid);
4141 SkipUntil(tok::r_paren, StopAtSemi);
4142 return;
4143 }
4144 SmallString<16> SpellingBuffer;
4145 SpellingBuffer.resize(Tok.getLength() + 1);
4146 bool Invalid = false;
4147 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
4148 if (Invalid) {
4149 SkipUntil(tok::r_paren, StopAtSemi);
4150 return;
4151 }
4152 StrBuffer += TokSpelling;
4153 ConsumeAnyToken();
4154 }
4155 StrBuffer += "\"";
4156
4157 if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
4158 Diag(Tok, diag::err_attribute_uuid_malformed_guid);
4159 ConsumeParen();
4160 return;
4161 }
4162
4163 // Pretend the user wrote the appropriate string literal here.
4164 // ActOnStringLiteral() copies the string data into the literal, so it's
4165 // ok that the Token points to StrBuffer.
4166 Token Toks[1];
4167 Toks[0].startToken();
4168 Toks[0].setKind(tok::string_literal);
4169 Toks[0].setLocation(StartLoc);
4170 Toks[0].setLiteralData(StrBuffer.data());
4171 Toks[0].setLength(StrBuffer.size());
4172 StringLiteral *UuidString =
4173 cast<StringLiteral>(Actions.ActOnStringLiteral(Toks, nullptr).get());
4174 ArgExprs.push_back(UuidString);
4175 }
4176
4177 if (!T.consumeClose()) {
Nico Weber05e1dad2016-09-03 03:25:22 +00004178 Attrs.addNew(UuidIdent, SourceRange(UuidLoc, T.getCloseLocation()), nullptr,
4179 SourceLocation(), ArgExprs.data(), ArgExprs.size(),
Erich Keanee891aa92018-07-13 15:07:47 +00004180 ParsedAttr::AS_Microsoft);
Nico Weber05e1dad2016-09-03 03:25:22 +00004181 }
4182}
4183
David Majnemere4752e752015-07-08 05:55:00 +00004184/// ParseMicrosoftAttributes - Parse Microsoft attributes [Attr]
Francois Pichetc2bc5ac2010-10-11 12:59:39 +00004185///
4186/// [MS] ms-attribute:
4187/// '[' token-seq ']'
4188///
4189/// [MS] ms-attribute-seq:
4190/// ms-attribute[opt]
4191/// ms-attribute ms-attribute-seq
John McCall53fa7142010-12-24 02:08:15 +00004192void Parser::ParseMicrosoftAttributes(ParsedAttributes &attrs,
4193 SourceLocation *endLoc) {
Francois Pichetc2bc5ac2010-10-11 12:59:39 +00004194 assert(Tok.is(tok::l_square) && "Not a Microsoft attribute list");
4195
Saleem Abdulrasool425efcf2015-06-15 20:57:04 +00004196 do {
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004197 // FIXME: If this is actually a C++11 attribute, parse it as one.
Saleem Abdulrasool425efcf2015-06-15 20:57:04 +00004198 BalancedDelimiterTracker T(*this, tok::l_square);
4199 T.consumeOpen();
Nico Weber05e1dad2016-09-03 03:25:22 +00004200
4201 // Skip most ms attributes except for a whitelist.
4202 while (true) {
4203 SkipUntil(tok::r_square, tok::identifier, StopAtSemi | StopBeforeMatch);
4204 if (Tok.isNot(tok::identifier)) // ']', but also eof
4205 break;
4206 if (Tok.getIdentifierInfo()->getName() == "uuid")
4207 ParseMicrosoftUuidAttributeArgs(attrs);
4208 else
4209 ConsumeToken();
4210 }
4211
Saleem Abdulrasool425efcf2015-06-15 20:57:04 +00004212 T.consumeClose();
4213 if (endLoc)
4214 *endLoc = T.getCloseLocation();
4215 } while (Tok.is(tok::l_square));
Francois Pichetc2bc5ac2010-10-11 12:59:39 +00004216}
Francois Pichet8f981d52011-05-25 10:19:49 +00004217
Erich Keanec480f302018-07-12 21:09:05 +00004218void Parser::ParseMicrosoftIfExistsClassDeclaration(
4219 DeclSpec::TST TagType, ParsedAttributes &AccessAttrs,
4220 AccessSpecifier &CurAS) {
Douglas Gregor43edb322011-10-24 22:31:10 +00004221 IfExistsCondition Result;
Francois Pichet8f981d52011-05-25 10:19:49 +00004222 if (ParseMicrosoftIfExistsCondition(Result))
4223 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00004224
Douglas Gregor43edb322011-10-24 22:31:10 +00004225 BalancedDelimiterTracker Braces(*this, tok::l_brace);
4226 if (Braces.consumeOpen()) {
Alp Tokerec543272013-12-24 09:48:30 +00004227 Diag(Tok, diag::err_expected) << tok::l_brace;
Francois Pichet8f981d52011-05-25 10:19:49 +00004228 return;
4229 }
Francois Pichet8f981d52011-05-25 10:19:49 +00004230
Douglas Gregor43edb322011-10-24 22:31:10 +00004231 switch (Result.Behavior) {
4232 case IEB_Parse:
4233 // Parse the declarations below.
4234 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00004235
Douglas Gregor43edb322011-10-24 22:31:10 +00004236 case IEB_Dependent:
4237 Diag(Result.KeywordLoc, diag::warn_microsoft_dependent_exists)
4238 << Result.IsIfExists;
4239 // Fall through to skip.
Galina Kistanovad819d5b2017-06-01 21:19:06 +00004240 LLVM_FALLTHROUGH;
Fangrui Song6907ce22018-07-30 19:24:48 +00004241
Douglas Gregor43edb322011-10-24 22:31:10 +00004242 case IEB_Skip:
4243 Braces.skipToEnd();
Francois Pichet8f981d52011-05-25 10:19:49 +00004244 return;
4245 }
4246
Richard Smith34f30512013-11-23 04:06:09 +00004247 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
Francois Pichet8f981d52011-05-25 10:19:49 +00004248 // __if_exists, __if_not_exists can nest.
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00004249 if (Tok.isOneOf(tok::kw___if_exists, tok::kw___if_not_exists)) {
Erich Keanec480f302018-07-12 21:09:05 +00004250 ParseMicrosoftIfExistsClassDeclaration((DeclSpec::TST)TagType,
4251 AccessAttrs, CurAS);
Francois Pichet8f981d52011-05-25 10:19:49 +00004252 continue;
4253 }
4254
4255 // Check for extraneous top-level semicolon.
4256 if (Tok.is(tok::semi)) {
Richard Smith87f5dc52012-07-23 05:45:25 +00004257 ConsumeExtraSemi(InsideStruct, TagType);
Francois Pichet8f981d52011-05-25 10:19:49 +00004258 continue;
4259 }
4260
4261 AccessSpecifier AS = getAccessSpecifierIfPresent();
4262 if (AS != AS_none) {
4263 // Current token is a C++ access specifier.
4264 CurAS = AS;
4265 SourceLocation ASLoc = Tok.getLocation();
4266 ConsumeToken();
4267 if (Tok.is(tok::colon))
Erich Keanec480f302018-07-12 21:09:05 +00004268 Actions.ActOnAccessSpecifier(AS, ASLoc, Tok.getLocation(),
4269 ParsedAttributesView{});
Francois Pichet8f981d52011-05-25 10:19:49 +00004270 else
Alp Toker35d87032013-12-30 23:29:50 +00004271 Diag(Tok, diag::err_expected) << tok::colon;
Francois Pichet8f981d52011-05-25 10:19:49 +00004272 ConsumeToken();
4273 continue;
4274 }
4275
4276 // Parse all the comma separated declarators.
Erich Keanec480f302018-07-12 21:09:05 +00004277 ParseCXXClassMemberDeclaration(CurAS, AccessAttrs);
Francois Pichet8f981d52011-05-25 10:19:49 +00004278 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004279
Douglas Gregor43edb322011-10-24 22:31:10 +00004280 Braces.consumeClose();
Francois Pichet8f981d52011-05-25 10:19:49 +00004281}