blob: de759c8c945e2b26e849e9f5ab3786895c57c3f2 [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);
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +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
Douglas Gregor0be31a22010-07-02 17:43:08 +0000133 if (getCurScope()->isClassScope() || getCurScope()->isTemplateParamScope() ||
134 getCurScope()->isInObjcMethodScope() || getCurScope()->getBlockParent() ||
135 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;
John McCall48871652010-08-21 09:40:31 +0000186 Decl *NamespcDecl =
Abramo Bagnarab5545be2011-03-08 12:38:20 +0000187 Actions.ActOnStartNamespaceDef(getCurScope(), InlineLoc, NamespaceLoc,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000188 IdentLoc, Ident, T.getOpenLocation(),
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +0000189 attrs.getList(), ImplicitUsingDirectiveDecl);
Chris Lattner4de55aa2009-03-29 14:02:43 +0000190
Jordan Rose1e879d82018-03-23 00:07:18 +0000191 PrettyDeclStackTraceEntry CrashInfo(Actions.Context, NamespcDecl,
192 NamespaceLoc, "parsing namespace");
Mike Stump11289f42009-09-09 15:08:12 +0000193
Richard Trieu61384cb2011-05-26 20:11:09 +0000194 // Parse the contents of the namespace. This includes parsing recovery on
195 // any improperly nested namespaces.
196 ParseInnerNamespace(ExtraIdentLoc, ExtraIdent, ExtraNamespaceLoc, 0,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000197 InlineLoc, attrs, T);
Mike Stump11289f42009-09-09 15:08:12 +0000198
Chris Lattner4de55aa2009-03-29 14:02:43 +0000199 // Leave the namespace scope.
200 NamespaceScope.Exit();
201
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000202 DeclEnd = T.getCloseLocation();
203 Actions.ActOnFinishNamespaceDef(NamespcDecl, DeclEnd);
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +0000204
205 return Actions.ConvertDeclToDeclGroup(NamespcDecl,
206 ImplicitUsingDirectiveDecl);
Chris Lattnera5235172007-08-25 06:57:03 +0000207}
Chris Lattner38376f12008-01-12 07:05:38 +0000208
Richard Trieu61384cb2011-05-26 20:11:09 +0000209/// ParseInnerNamespace - Parse the contents of a namespace.
Richard Smith13307f52014-11-08 05:37:34 +0000210void Parser::ParseInnerNamespace(std::vector<SourceLocation> &IdentLoc,
211 std::vector<IdentifierInfo *> &Ident,
212 std::vector<SourceLocation> &NamespaceLoc,
213 unsigned int index, SourceLocation &InlineLoc,
214 ParsedAttributes &attrs,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000215 BalancedDelimiterTracker &Tracker) {
Richard Trieu61384cb2011-05-26 20:11:09 +0000216 if (index == Ident.size()) {
Richard Smith752ada82015-11-17 23:32:01 +0000217 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
218 Tok.isNot(tok::eof)) {
Richard Trieu61384cb2011-05-26 20:11:09 +0000219 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +0000220 MaybeParseCXX11Attributes(attrs);
Richard Trieu61384cb2011-05-26 20:11:09 +0000221 ParseExternalDeclaration(attrs);
222 }
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000223
224 // The caller is what called check -- we are simply calling
225 // the close for it.
226 Tracker.consumeClose();
Richard Trieu61384cb2011-05-26 20:11:09 +0000227
228 return;
229 }
230
Richard Smith13307f52014-11-08 05:37:34 +0000231 // Handle a nested namespace definition.
232 // FIXME: Preserve the source information through to the AST rather than
233 // desugaring it here.
Richard Trieu61384cb2011-05-26 20:11:09 +0000234 ParseScope NamespaceScope(this, Scope::DeclScope);
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +0000235 UsingDirectiveDecl *ImplicitUsingDirectiveDecl = nullptr;
Richard Trieu61384cb2011-05-26 20:11:09 +0000236 Decl *NamespcDecl =
237 Actions.ActOnStartNamespaceDef(getCurScope(), SourceLocation(),
238 NamespaceLoc[index], IdentLoc[index],
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000239 Ident[index], Tracker.getOpenLocation(),
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +0000240 attrs.getList(), ImplicitUsingDirectiveDecl);
241 assert(!ImplicitUsingDirectiveDecl &&
242 "nested namespace definition cannot define anonymous namespace");
Richard Trieu61384cb2011-05-26 20:11:09 +0000243
244 ParseInnerNamespace(IdentLoc, Ident, NamespaceLoc, ++index, InlineLoc,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000245 attrs, Tracker);
Richard Trieu61384cb2011-05-26 20:11:09 +0000246
247 NamespaceScope.Exit();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000248 Actions.ActOnFinishNamespaceDef(NamespcDecl, Tracker.getCloseLocation());
Richard Trieu61384cb2011-05-26 20:11:09 +0000249}
250
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000251/// ParseNamespaceAlias - Parse the part after the '=' in a namespace
252/// alias definition.
253///
John McCall48871652010-08-21 09:40:31 +0000254Decl *Parser::ParseNamespaceAlias(SourceLocation NamespaceLoc,
John McCall084e83d2011-03-24 11:26:52 +0000255 SourceLocation AliasLoc,
256 IdentifierInfo *Alias,
257 SourceLocation &DeclEnd) {
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000258 assert(Tok.is(tok::equal) && "Not equal token");
Mike Stump11289f42009-09-09 15:08:12 +0000259
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000260 ConsumeToken(); // eat the '='.
Mike Stump11289f42009-09-09 15:08:12 +0000261
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000262 if (Tok.is(tok::code_completion)) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000263 Actions.CodeCompleteNamespaceAliasDecl(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000264 cutOffParsing();
Craig Topper161e4db2014-05-21 06:02:52 +0000265 return nullptr;
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000266 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000267
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000268 CXXScopeSpec SS;
269 // Parse (optional) nested-name-specifier.
Matthias Gehredc01bb42017-03-17 21:41:20 +0000270 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false,
271 /*MayBePseudoDestructor=*/nullptr,
272 /*IsTypename=*/false,
273 /*LastII=*/nullptr,
274 /*OnlyNamespace=*/true);
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000275
Matthias Gehredc01bb42017-03-17 21:41:20 +0000276 if (Tok.isNot(tok::identifier)) {
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000277 Diag(Tok, diag::err_expected_namespace_name);
278 // Skip to end of the definition and eat the ';'.
279 SkipUntil(tok::semi);
Craig Topper161e4db2014-05-21 06:02:52 +0000280 return nullptr;
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000281 }
282
Matthias Gehredc01bb42017-03-17 21:41:20 +0000283 if (SS.isInvalid()) {
284 // Diagnostics have been emitted in ParseOptionalCXXScopeSpecifier.
285 // Skip to end of the definition and eat the ';'.
286 SkipUntil(tok::semi);
287 return nullptr;
288 }
289
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000290 // Parse identifier.
Anders Carlsson47952ae2009-03-28 22:53:22 +0000291 IdentifierInfo *Ident = Tok.getIdentifierInfo();
292 SourceLocation IdentLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000293
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000294 // Eat the ';'.
Chris Lattner49836b42009-04-02 04:16:50 +0000295 DeclEnd = Tok.getLocation();
Alp Toker383d2c42014-01-01 03:08:43 +0000296 if (ExpectAndConsume(tok::semi, diag::err_expected_semi_after_namespace_name))
297 SkipUntil(tok::semi);
Mike Stump11289f42009-09-09 15:08:12 +0000298
Craig Topperff354282015-11-14 18:16:00 +0000299 return Actions.ActOnNamespaceAliasDef(getCurScope(), NamespaceLoc, AliasLoc,
300 Alias, SS, IdentLoc, Ident);
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000301}
302
Chris Lattner38376f12008-01-12 07:05:38 +0000303/// ParseLinkage - We know that the current token is a string_literal
304/// and just before that, that extern was seen.
305///
306/// linkage-specification: [C++ 7.5p2: dcl.link]
307/// 'extern' string-literal '{' declaration-seq[opt] '}'
308/// 'extern' string-literal declaration
309///
Faisal Vali421b2d12017-12-29 05:41:00 +0000310Decl *Parser::ParseLinkage(ParsingDeclSpec &DS, DeclaratorContext Context) {
Richard Smith4ee696d2014-02-17 23:25:27 +0000311 assert(isTokenStringLiteral() && "Not a string literal!");
312 ExprResult Lang = ParseStringLiteralExpression(false);
Chris Lattner38376f12008-01-12 07:05:38 +0000313
Douglas Gregor07665a62009-01-05 19:45:36 +0000314 ParseScope LinkageScope(this, Scope::DeclScope);
Richard Smith4ee696d2014-02-17 23:25:27 +0000315 Decl *LinkageSpec =
316 Lang.isInvalid()
Craig Topper161e4db2014-05-21 06:02:52 +0000317 ? nullptr
Richard Smith4ee696d2014-02-17 23:25:27 +0000318 : Actions.ActOnStartLinkageSpecification(
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000319 getCurScope(), DS.getSourceRange().getBegin(), Lang.get(),
Richard Smith4ee696d2014-02-17 23:25:27 +0000320 Tok.is(tok::l_brace) ? Tok.getLocation() : SourceLocation());
Douglas Gregor07665a62009-01-05 19:45:36 +0000321
John McCall084e83d2011-03-24 11:26:52 +0000322 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +0000323 MaybeParseCXX11Attributes(attrs);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000324
Douglas Gregor07665a62009-01-05 19:45:36 +0000325 if (Tok.isNot(tok::l_brace)) {
Abramo Bagnara4d423992011-05-01 16:25:54 +0000326 // Reset the source range in DS, as the leading "extern"
327 // does not really belong to the inner declaration ...
328 DS.SetRangeStart(SourceLocation());
329 DS.SetRangeEnd(SourceLocation());
330 // ... but anyway remember that such an "extern" was seen.
Abramo Bagnaraed5b6892010-07-30 16:47:02 +0000331 DS.setExternInLinkageSpec(true);
John McCall53fa7142010-12-24 02:08:15 +0000332 ParseExternalDeclaration(attrs, &DS);
Richard Smith4ee696d2014-02-17 23:25:27 +0000333 return LinkageSpec ? Actions.ActOnFinishLinkageSpecification(
334 getCurScope(), LinkageSpec, SourceLocation())
Craig Topper161e4db2014-05-21 06:02:52 +0000335 : nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000336 }
Douglas Gregor29ff7d02008-12-16 22:23:02 +0000337
Douglas Gregorb65a9132010-02-07 08:38:28 +0000338 DS.abort();
339
John McCall53fa7142010-12-24 02:08:15 +0000340 ProhibitAttributes(attrs);
Alexis Hunt96d5c762009-11-21 08:43:09 +0000341
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000342 BalancedDelimiterTracker T(*this, tok::l_brace);
343 T.consumeOpen();
Richard Smith77944862014-03-02 05:58:18 +0000344
345 unsigned NestedModules = 0;
346 while (true) {
347 switch (Tok.getKind()) {
348 case tok::annot_module_begin:
349 ++NestedModules;
350 ParseTopLevelDecl();
351 continue;
352
353 case tok::annot_module_end:
354 if (!NestedModules)
355 break;
356 --NestedModules;
357 ParseTopLevelDecl();
358 continue;
359
360 case tok::annot_module_include:
361 ParseTopLevelDecl();
362 continue;
363
364 case tok::eof:
365 break;
366
367 case tok::r_brace:
368 if (!NestedModules)
369 break;
370 // Fall through.
371 default:
372 ParsedAttributesWithRange attrs(AttrFactory);
373 MaybeParseCXX11Attributes(attrs);
Richard Smith77944862014-03-02 05:58:18 +0000374 ParseExternalDeclaration(attrs);
375 continue;
376 }
377
378 break;
Chris Lattner38376f12008-01-12 07:05:38 +0000379 }
380
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000381 T.consumeClose();
Richard Smith4ee696d2014-02-17 23:25:27 +0000382 return LinkageSpec ? Actions.ActOnFinishLinkageSpecification(
383 getCurScope(), LinkageSpec, T.getCloseLocation())
Craig Topper161e4db2014-05-21 06:02:52 +0000384 : nullptr;
Chris Lattner38376f12008-01-12 07:05:38 +0000385}
Douglas Gregor556877c2008-04-13 21:30:24 +0000386
Richard Smith8df390f2016-09-08 23:14:54 +0000387/// Parse a C++ Modules TS export-declaration.
388///
389/// export-declaration:
390/// 'export' declaration
391/// 'export' '{' declaration-seq[opt] '}'
392///
393Decl *Parser::ParseExportDeclaration() {
394 assert(Tok.is(tok::kw_export));
395 SourceLocation ExportLoc = ConsumeToken();
396
397 ParseScope ExportScope(this, Scope::DeclScope);
398 Decl *ExportDecl = Actions.ActOnStartExportDecl(
399 getCurScope(), ExportLoc,
400 Tok.is(tok::l_brace) ? Tok.getLocation() : SourceLocation());
401
402 if (Tok.isNot(tok::l_brace)) {
403 // FIXME: Factor out a ParseExternalDeclarationWithAttrs.
404 ParsedAttributesWithRange Attrs(AttrFactory);
405 MaybeParseCXX11Attributes(Attrs);
406 MaybeParseMicrosoftAttributes(Attrs);
407 ParseExternalDeclaration(Attrs);
408 return Actions.ActOnFinishExportDecl(getCurScope(), ExportDecl,
409 SourceLocation());
410 }
411
412 BalancedDelimiterTracker T(*this, tok::l_brace);
413 T.consumeOpen();
414
415 // The Modules TS draft says "An export-declaration shall declare at least one
416 // entity", but the intent is that it shall contain at least one declaration.
417 if (Tok.is(tok::r_brace))
418 Diag(ExportLoc, diag::err_export_empty)
419 << SourceRange(ExportLoc, Tok.getLocation());
420
421 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
422 Tok.isNot(tok::eof)) {
423 ParsedAttributesWithRange Attrs(AttrFactory);
424 MaybeParseCXX11Attributes(Attrs);
425 MaybeParseMicrosoftAttributes(Attrs);
426 ParseExternalDeclaration(Attrs);
427 }
428
429 T.consumeClose();
430 return Actions.ActOnFinishExportDecl(getCurScope(), ExportDecl,
431 T.getCloseLocation());
432}
433
Douglas Gregord7c4d982008-12-30 03:27:21 +0000434/// ParseUsingDirectiveOrDeclaration - Parse C++ using using-declaration or
435/// using-directive. Assumes that current token is 'using'.
Richard Smith6f1daa42016-12-16 00:58:48 +0000436Parser::DeclGroupPtrTy
Faisal Vali421b2d12017-12-29 05:41:00 +0000437Parser::ParseUsingDirectiveOrDeclaration(DeclaratorContext Context,
John McCall9b72f892010-11-10 02:40:36 +0000438 const ParsedTemplateInfo &TemplateInfo,
Richard Smith6f1daa42016-12-16 00:58:48 +0000439 SourceLocation &DeclEnd,
440 ParsedAttributesWithRange &attrs) {
Douglas Gregord7c4d982008-12-30 03:27:21 +0000441 assert(Tok.is(tok::kw_using) && "Not using token");
Fariborz Jahanian4bf82622011-08-22 17:59:19 +0000442 ObjCDeclContextSwitch ObjCDC(*this);
443
Douglas Gregord7c4d982008-12-30 03:27:21 +0000444 // Eat 'using'.
445 SourceLocation UsingLoc = ConsumeToken();
446
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000447 if (Tok.is(tok::code_completion)) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000448 Actions.CodeCompleteUsing(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000449 cutOffParsing();
Craig Topper161e4db2014-05-21 06:02:52 +0000450 return nullptr;
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000451 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000452
John McCall9b72f892010-11-10 02:40:36 +0000453 // 'using namespace' means this is a using-directive.
454 if (Tok.is(tok::kw_namespace)) {
455 // Template parameters are always an error here.
456 if (TemplateInfo.Kind) {
457 SourceRange R = TemplateInfo.getSourceRange();
Craig Topper54a6a682015-11-14 18:16:08 +0000458 Diag(UsingLoc, diag::err_templated_using_directive_declaration)
459 << 0 /* directive */ << R << FixItHint::CreateRemoval(R);
John McCall9b72f892010-11-10 02:40:36 +0000460 }
Alexis Hunt96d5c762009-11-21 08:43:09 +0000461
Richard Smith6f1daa42016-12-16 00:58:48 +0000462 Decl *UsingDir = ParseUsingDirective(Context, UsingLoc, DeclEnd, attrs);
463 return Actions.ConvertDeclToDeclGroup(UsingDir);
John McCall9b72f892010-11-10 02:40:36 +0000464 }
465
Richard Smithdda56e42011-04-15 14:24:37 +0000466 // Otherwise, it must be a using-declaration or an alias-declaration.
John McCall9b72f892010-11-10 02:40:36 +0000467
468 // Using declarations can't have attributes.
John McCall53fa7142010-12-24 02:08:15 +0000469 ProhibitAttributes(attrs);
Chris Lattner9b01ca12009-01-06 06:55:51 +0000470
Fariborz Jahanian4bf82622011-08-22 17:59:19 +0000471 return ParseUsingDeclaration(Context, TemplateInfo, UsingLoc, DeclEnd,
Richard Smith6f1daa42016-12-16 00:58:48 +0000472 AS_none);
Douglas Gregord7c4d982008-12-30 03:27:21 +0000473}
474
475/// ParseUsingDirective - Parse C++ using-directive, assumes
476/// that current token is 'namespace' and 'using' was already parsed.
477///
478/// using-directive: [C++ 7.3.p4: namespace.udir]
479/// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
480/// namespace-name ;
481/// [GNU] using-directive:
482/// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
483/// namespace-name attributes[opt] ;
484///
Faisal Vali421b2d12017-12-29 05:41:00 +0000485Decl *Parser::ParseUsingDirective(DeclaratorContext Context,
John McCall9b72f892010-11-10 02:40:36 +0000486 SourceLocation UsingLoc,
487 SourceLocation &DeclEnd,
John McCall53fa7142010-12-24 02:08:15 +0000488 ParsedAttributes &attrs) {
Douglas Gregord7c4d982008-12-30 03:27:21 +0000489 assert(Tok.is(tok::kw_namespace) && "Not 'namespace' token");
490
491 // Eat 'namespace'.
492 SourceLocation NamespcLoc = ConsumeToken();
493
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000494 if (Tok.is(tok::code_completion)) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000495 Actions.CodeCompleteUsingDirective(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000496 cutOffParsing();
Craig Topper161e4db2014-05-21 06:02:52 +0000497 return nullptr;
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000498 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000499
Douglas Gregord7c4d982008-12-30 03:27:21 +0000500 CXXScopeSpec SS;
501 // Parse (optional) nested-name-specifier.
Matthias Gehredc01bb42017-03-17 21:41:20 +0000502 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false,
503 /*MayBePseudoDestructor=*/nullptr,
504 /*IsTypename=*/false,
505 /*LastII=*/nullptr,
506 /*OnlyNamespace=*/true);
Douglas Gregord7c4d982008-12-30 03:27:21 +0000507
Craig Topper161e4db2014-05-21 06:02:52 +0000508 IdentifierInfo *NamespcName = nullptr;
Douglas Gregord7c4d982008-12-30 03:27:21 +0000509 SourceLocation IdentLoc = SourceLocation();
510
511 // Parse namespace-name.
Matthias Gehredc01bb42017-03-17 21:41:20 +0000512 if (Tok.isNot(tok::identifier)) {
Douglas Gregord7c4d982008-12-30 03:27:21 +0000513 Diag(Tok, diag::err_expected_namespace_name);
514 // If there was invalid namespace name, skip to end of decl, and eat ';'.
515 SkipUntil(tok::semi);
516 // FIXME: Are there cases, when we would like to call ActOnUsingDirective?
Craig Topper161e4db2014-05-21 06:02:52 +0000517 return nullptr;
Douglas Gregord7c4d982008-12-30 03:27:21 +0000518 }
Mike Stump11289f42009-09-09 15:08:12 +0000519
Matthias Gehredc01bb42017-03-17 21:41:20 +0000520 if (SS.isInvalid()) {
521 // Diagnostics have been emitted in ParseOptionalCXXScopeSpecifier.
522 // Skip to end of the definition and eat the ';'.
523 SkipUntil(tok::semi);
524 return nullptr;
525 }
526
Chris Lattnerce1da2c2009-01-06 07:27:21 +0000527 // Parse identifier.
528 NamespcName = Tok.getIdentifierInfo();
529 IdentLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000530
Chris Lattnerce1da2c2009-01-06 07:27:21 +0000531 // Parse (optional) attributes (most likely GNU strong-using extension).
Alexis Hunt96d5c762009-11-21 08:43:09 +0000532 bool GNUAttr = false;
533 if (Tok.is(tok::kw___attribute)) {
534 GNUAttr = true;
John McCall53fa7142010-12-24 02:08:15 +0000535 ParseGNUAttributes(attrs);
Alexis Hunt96d5c762009-11-21 08:43:09 +0000536 }
Mike Stump11289f42009-09-09 15:08:12 +0000537
Chris Lattnerce1da2c2009-01-06 07:27:21 +0000538 // Eat ';'.
Chris Lattner49836b42009-04-02 04:16:50 +0000539 DeclEnd = Tok.getLocation();
Alp Toker383d2c42014-01-01 03:08:43 +0000540 if (ExpectAndConsume(tok::semi,
541 GNUAttr ? diag::err_expected_semi_after_attribute_list
542 : diag::err_expected_semi_after_namespace_name))
543 SkipUntil(tok::semi);
Douglas Gregord7c4d982008-12-30 03:27:21 +0000544
Douglas Gregor0be31a22010-07-02 17:43:08 +0000545 return Actions.ActOnUsingDirective(getCurScope(), UsingLoc, NamespcLoc, SS,
John McCall53fa7142010-12-24 02:08:15 +0000546 IdentLoc, NamespcName, attrs.getList());
Douglas Gregord7c4d982008-12-30 03:27:21 +0000547}
548
Richard Smith6f1daa42016-12-16 00:58:48 +0000549/// Parse a using-declarator (or the identifier in a C++11 alias-declaration).
Douglas Gregord7c4d982008-12-30 03:27:21 +0000550///
Richard Smith6f1daa42016-12-16 00:58:48 +0000551/// using-declarator:
552/// 'typename'[opt] nested-name-specifier unqualified-id
Douglas Gregord7c4d982008-12-30 03:27:21 +0000553///
Faisal Vali421b2d12017-12-29 05:41:00 +0000554bool Parser::ParseUsingDeclarator(DeclaratorContext Context,
555 UsingDeclarator &D) {
Richard Smith6f1daa42016-12-16 00:58:48 +0000556 D.clear();
Douglas Gregorfec52632009-06-20 00:51:54 +0000557
558 // Ignore optional 'typename'.
Douglas Gregor220f4272009-11-04 16:30:06 +0000559 // FIXME: This is wrong; we should parse this as a typename-specifier.
Richard Smith6f1daa42016-12-16 00:58:48 +0000560 TryConsumeToken(tok::kw_typename, D.TypenameLoc);
Douglas Gregorfec52632009-06-20 00:51:54 +0000561
Nikola Smiljanic67860242014-09-26 00:28:20 +0000562 if (Tok.is(tok::kw___super)) {
563 Diag(Tok.getLocation(), diag::err_super_in_using_declaration);
Richard Smith6f1daa42016-12-16 00:58:48 +0000564 return true;
Nikola Smiljanic67860242014-09-26 00:28:20 +0000565 }
566
Douglas Gregorfec52632009-06-20 00:51:54 +0000567 // Parse nested-name-specifier.
Craig Topper161e4db2014-05-21 06:02:52 +0000568 IdentifierInfo *LastII = nullptr;
Richard Smith6f1daa42016-12-16 00:58:48 +0000569 ParseOptionalCXXScopeSpecifier(D.SS, nullptr, /*EnteringContext=*/false,
Craig Topper161e4db2014-05-21 06:02:52 +0000570 /*MayBePseudoDtor=*/nullptr,
571 /*IsTypename=*/false,
Richard Smith7447af42013-03-26 01:15:19 +0000572 /*LastII=*/&LastII);
Richard Smith6f1daa42016-12-16 00:58:48 +0000573 if (D.SS.isInvalid())
574 return true;
Richard Smith7447af42013-03-26 01:15:19 +0000575
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000576 // Parse the unqualified-id. We allow parsing of both constructor and
Douglas Gregor220f4272009-11-04 16:30:06 +0000577 // destructor names and allow the action module to diagnose any semantic
578 // errors.
Richard Smith7447af42013-03-26 01:15:19 +0000579 //
580 // C++11 [class.qual]p2:
581 // [...] in a using-declaration that is a member-declaration, if the name
582 // specified after the nested-name-specifier is the same as the identifier
583 // or the simple-template-id's template-name in the last component of the
584 // nested-name-specifier, the name is [...] considered to name the
585 // constructor.
Faisal Vali421b2d12017-12-29 05:41:00 +0000586 if (getLangOpts().CPlusPlus11 &&
587 Context == DeclaratorContext::MemberContext &&
Richard Smith151c4562016-12-20 21:35:28 +0000588 Tok.is(tok::identifier) &&
589 (NextToken().is(tok::semi) || NextToken().is(tok::comma) ||
590 NextToken().is(tok::ellipsis)) &&
Richard Smith6f1daa42016-12-16 00:58:48 +0000591 D.SS.isNotEmpty() && LastII == Tok.getIdentifierInfo() &&
592 !D.SS.getScopeRep()->getAsNamespace() &&
593 !D.SS.getScopeRep()->getAsNamespaceAlias()) {
Richard Smith7447af42013-03-26 01:15:19 +0000594 SourceLocation IdLoc = ConsumeToken();
Richard Smith6f1daa42016-12-16 00:58:48 +0000595 ParsedType Type =
596 Actions.getInheritingConstructorName(D.SS, IdLoc, *LastII);
597 D.Name.setConstructorName(Type, IdLoc, IdLoc);
598 } else {
599 if (ParseUnqualifiedId(
600 D.SS, /*EnteringContext=*/false,
601 /*AllowDestructorName=*/true,
602 /*AllowConstructorName=*/!(Tok.is(tok::identifier) &&
603 NextToken().is(tok::equal)),
Richard Smith35845152017-02-07 01:37:30 +0000604 /*AllowDeductionGuide=*/false,
Richard Smithc08b6932018-04-27 02:00:13 +0000605 nullptr, nullptr, D.Name))
Richard Smith6f1daa42016-12-16 00:58:48 +0000606 return true;
Douglas Gregorfec52632009-06-20 00:51:54 +0000607 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000608
Richard Smith151c4562016-12-20 21:35:28 +0000609 if (TryConsumeToken(tok::ellipsis, D.EllipsisLoc))
Aaron Ballmanc351fba2017-12-04 20:27:34 +0000610 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17 ?
Richard Smithb115e5d2017-08-13 23:37:29 +0000611 diag::warn_cxx17_compat_using_declaration_pack :
Richard Smith151c4562016-12-20 21:35:28 +0000612 diag::ext_using_declaration_pack);
Richard Smith6f1daa42016-12-16 00:58:48 +0000613
614 return false;
615}
616
617/// ParseUsingDeclaration - Parse C++ using-declaration or alias-declaration.
618/// Assumes that 'using' was already seen.
619///
620/// using-declaration: [C++ 7.3.p3: namespace.udecl]
621/// 'using' using-declarator-list[opt] ;
622///
623/// using-declarator-list: [C++1z]
624/// using-declarator '...'[opt]
625/// using-declarator-list ',' using-declarator '...'[opt]
626///
627/// using-declarator-list: [C++98-14]
628/// using-declarator
629///
630/// alias-declaration: C++11 [dcl.dcl]p1
631/// 'using' identifier attribute-specifier-seq[opt] = type-id ;
632///
633Parser::DeclGroupPtrTy
Faisal Vali421b2d12017-12-29 05:41:00 +0000634Parser::ParseUsingDeclaration(DeclaratorContext Context,
Richard Smith6f1daa42016-12-16 00:58:48 +0000635 const ParsedTemplateInfo &TemplateInfo,
636 SourceLocation UsingLoc, SourceLocation &DeclEnd,
637 AccessSpecifier AS) {
638 // Check for misplaced attributes before the identifier in an
639 // alias-declaration.
640 ParsedAttributesWithRange MisplacedAttrs(AttrFactory);
641 MaybeParseCXX11Attributes(MisplacedAttrs);
642
643 UsingDeclarator D;
644 bool InvalidDeclarator = ParseUsingDeclarator(Context, D);
645
Richard Smithc2c8bb82013-10-15 01:34:54 +0000646 ParsedAttributesWithRange Attrs(AttrFactory);
Richard Smith37a45dd2013-10-24 01:21:09 +0000647 MaybeParseGNUAttributes(Attrs);
Richard Smith54ecd982013-02-20 19:22:51 +0000648 MaybeParseCXX11Attributes(Attrs);
Richard Smithdda56e42011-04-15 14:24:37 +0000649
650 // Maybe this is an alias-declaration.
Richard Smith6f1daa42016-12-16 00:58:48 +0000651 if (Tok.is(tok::equal)) {
652 if (InvalidDeclarator) {
653 SkipUntil(tok::semi);
654 return nullptr;
655 }
656
Richard Smithc2c8bb82013-10-15 01:34:54 +0000657 // If we had any misplaced attributes from earlier, this is where they
658 // should have been written.
659 if (MisplacedAttrs.Range.isValid()) {
660 Diag(MisplacedAttrs.Range.getBegin(), diag::err_attributes_not_allowed)
661 << FixItHint::CreateInsertionFromRange(
662 Tok.getLocation(),
663 CharSourceRange::getTokenRange(MisplacedAttrs.Range))
664 << FixItHint::CreateRemoval(MisplacedAttrs.Range);
665 Attrs.takeAllFrom(MisplacedAttrs);
666 }
667
Richard Smith6f1daa42016-12-16 00:58:48 +0000668 Decl *DeclFromDeclSpec = nullptr;
669 Decl *AD = ParseAliasDeclarationAfterDeclarator(
670 TemplateInfo, UsingLoc, D, DeclEnd, AS, Attrs, &DeclFromDeclSpec);
671 return Actions.ConvertDeclToDeclGroup(AD, DeclFromDeclSpec);
Alexis Hunt6aa9bee2012-06-23 05:07:58 +0000672 }
Mike Stump11289f42009-09-09 15:08:12 +0000673
Richard Smith6f1daa42016-12-16 00:58:48 +0000674 // C++11 attributes are not allowed on a using-declaration, but GNU ones
675 // are.
676 ProhibitAttributes(MisplacedAttrs);
677 ProhibitAttributes(Attrs);
Douglas Gregorfec52632009-06-20 00:51:54 +0000678
John McCall9b72f892010-11-10 02:40:36 +0000679 // Diagnose an attempt to declare a templated using-declaration.
Richard Smith810ad3e2013-01-29 10:02:16 +0000680 // In C++11, alias-declarations can be templates:
Richard Smithdda56e42011-04-15 14:24:37 +0000681 // template <...> using id = type;
Richard Smith6f1daa42016-12-16 00:58:48 +0000682 if (TemplateInfo.Kind) {
John McCall9b72f892010-11-10 02:40:36 +0000683 SourceRange R = TemplateInfo.getSourceRange();
Craig Topper54a6a682015-11-14 18:16:08 +0000684 Diag(UsingLoc, diag::err_templated_using_directive_declaration)
685 << 1 /* declaration */ << R << FixItHint::CreateRemoval(R);
John McCall9b72f892010-11-10 02:40:36 +0000686
687 // Unfortunately, we have to bail out instead of recovering by
688 // ignoring the parameters, just in case the nested name specifier
689 // depends on the parameters.
Craig Topper161e4db2014-05-21 06:02:52 +0000690 return nullptr;
John McCall9b72f892010-11-10 02:40:36 +0000691 }
692
Richard Smith6f1daa42016-12-16 00:58:48 +0000693 SmallVector<Decl *, 8> DeclsInGroup;
694 while (true) {
695 // Parse (optional) attributes (most likely GNU strong-using extension).
696 MaybeParseGNUAttributes(Attrs);
697
698 if (InvalidDeclarator)
699 SkipUntil(tok::comma, tok::semi, StopBeforeMatch);
700 else {
701 // "typename" keyword is allowed for identifiers only,
702 // because it may be a type definition.
703 if (D.TypenameLoc.isValid() &&
Faisal Vali2ab8c152017-12-30 04:15:27 +0000704 D.Name.getKind() != UnqualifiedIdKind::IK_Identifier) {
Richard Smith6f1daa42016-12-16 00:58:48 +0000705 Diag(D.Name.getSourceRange().getBegin(),
706 diag::err_typename_identifiers_only)
707 << FixItHint::CreateRemoval(SourceRange(D.TypenameLoc));
708 // Proceed parsing, but discard the typename keyword.
709 D.TypenameLoc = SourceLocation();
710 }
711
Richard Smith151c4562016-12-20 21:35:28 +0000712 Decl *UD = Actions.ActOnUsingDeclaration(getCurScope(), AS, UsingLoc,
713 D.TypenameLoc, D.SS, D.Name,
714 D.EllipsisLoc, Attrs.getList());
Richard Smith6f1daa42016-12-16 00:58:48 +0000715 if (UD)
716 DeclsInGroup.push_back(UD);
717 }
718
719 if (!TryConsumeToken(tok::comma))
720 break;
721
722 // Parse another using-declarator.
723 Attrs.clear();
724 InvalidDeclarator = ParseUsingDeclarator(Context, D);
Douglas Gregor882a61a2011-09-26 14:30:28 +0000725 }
726
Richard Smith6f1daa42016-12-16 00:58:48 +0000727 if (DeclsInGroup.size() > 1)
Aaron Ballmanc351fba2017-12-04 20:27:34 +0000728 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17 ?
Richard Smithb115e5d2017-08-13 23:37:29 +0000729 diag::warn_cxx17_compat_multi_using_declaration :
Richard Smith6f1daa42016-12-16 00:58:48 +0000730 diag::ext_multi_using_declaration);
731
732 // Eat ';'.
733 DeclEnd = Tok.getLocation();
734 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
735 !Attrs.empty() ? "attributes list"
736 : "using declaration"))
737 SkipUntil(tok::semi);
738
Richard Smith3beb7c62017-01-12 02:27:38 +0000739 return Actions.BuildDeclaratorGroup(DeclsInGroup);
Richard Smith6f1daa42016-12-16 00:58:48 +0000740}
741
Richard Smith6f1daa42016-12-16 00:58:48 +0000742Decl *Parser::ParseAliasDeclarationAfterDeclarator(
743 const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc,
744 UsingDeclarator &D, SourceLocation &DeclEnd, AccessSpecifier AS,
745 ParsedAttributes &Attrs, Decl **OwnedType) {
746 if (ExpectAndConsume(tok::equal)) {
747 SkipUntil(tok::semi);
748 return nullptr;
749 }
750
751 Diag(Tok.getLocation(), getLangOpts().CPlusPlus11 ?
752 diag::warn_cxx98_compat_alias_declaration :
753 diag::ext_alias_declaration);
754
755 // Type alias templates cannot be specialized.
756 int SpecKind = -1;
757 if (TemplateInfo.Kind == ParsedTemplateInfo::Template &&
Faisal Vali2ab8c152017-12-30 04:15:27 +0000758 D.Name.getKind() == UnqualifiedIdKind::IK_TemplateId)
Richard Smith6f1daa42016-12-16 00:58:48 +0000759 SpecKind = 0;
760 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization)
761 SpecKind = 1;
762 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
763 SpecKind = 2;
764 if (SpecKind != -1) {
765 SourceRange Range;
766 if (SpecKind == 0)
767 Range = SourceRange(D.Name.TemplateId->LAngleLoc,
768 D.Name.TemplateId->RAngleLoc);
769 else
770 Range = TemplateInfo.getSourceRange();
771 Diag(Range.getBegin(), diag::err_alias_declaration_specialization)
772 << SpecKind << Range;
773 SkipUntil(tok::semi);
774 return nullptr;
775 }
776
777 // Name must be an identifier.
Faisal Vali2ab8c152017-12-30 04:15:27 +0000778 if (D.Name.getKind() != UnqualifiedIdKind::IK_Identifier) {
Richard Smith6f1daa42016-12-16 00:58:48 +0000779 Diag(D.Name.StartLocation, diag::err_alias_declaration_not_identifier);
780 // No removal fixit: can't recover from this.
781 SkipUntil(tok::semi);
782 return nullptr;
783 } else if (D.TypenameLoc.isValid())
784 Diag(D.TypenameLoc, diag::err_alias_declaration_not_identifier)
785 << FixItHint::CreateRemoval(SourceRange(
786 D.TypenameLoc,
787 D.SS.isNotEmpty() ? D.SS.getEndLoc() : D.TypenameLoc));
788 else if (D.SS.isNotEmpty())
789 Diag(D.SS.getBeginLoc(), diag::err_alias_declaration_not_identifier)
790 << FixItHint::CreateRemoval(D.SS.getRange());
Richard Smith151c4562016-12-20 21:35:28 +0000791 if (D.EllipsisLoc.isValid())
792 Diag(D.EllipsisLoc, diag::err_alias_declaration_pack_expansion)
793 << FixItHint::CreateRemoval(SourceRange(D.EllipsisLoc));
Richard Smith6f1daa42016-12-16 00:58:48 +0000794
795 Decl *DeclFromDeclSpec = nullptr;
Faisal Vali421b2d12017-12-29 05:41:00 +0000796 TypeResult TypeAlias = ParseTypeName(
797 nullptr,
798 TemplateInfo.Kind ? DeclaratorContext::AliasTemplateContext
799 : DeclaratorContext::AliasDeclContext,
800 AS, &DeclFromDeclSpec, &Attrs);
Richard Smith6f1daa42016-12-16 00:58:48 +0000801 if (OwnedType)
802 *OwnedType = DeclFromDeclSpec;
803
804 // Eat ';'.
805 DeclEnd = Tok.getLocation();
806 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
807 !Attrs.empty() ? "attributes list"
808 : "alias declaration"))
809 SkipUntil(tok::semi);
810
811 TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
812 MultiTemplateParamsArg TemplateParamsArg(
813 TemplateParams ? TemplateParams->data() : nullptr,
814 TemplateParams ? TemplateParams->size() : 0);
815 return Actions.ActOnAliasDeclaration(getCurScope(), AS, TemplateParamsArg,
816 UsingLoc, D.Name, Attrs.getList(),
817 TypeAlias, DeclFromDeclSpec);
Douglas Gregord7c4d982008-12-30 03:27:21 +0000818}
819
Benjamin Kramere56f3932011-12-23 17:00:35 +0000820/// ParseStaticAssertDeclaration - Parse C++0x or C11 static_assert-declaration.
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000821///
Peter Collingbourne3d9cbdc2011-04-15 00:35:57 +0000822/// [C++0x] static_assert-declaration:
823/// static_assert ( constant-expression , string-literal ) ;
824///
Benjamin Kramere56f3932011-12-23 17:00:35 +0000825/// [C11] static_assert-declaration:
Peter Collingbourne3d9cbdc2011-04-15 00:35:57 +0000826/// _Static_assert ( constant-expression , string-literal ) ;
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000827///
John McCall48871652010-08-21 09:40:31 +0000828Decl *Parser::ParseStaticAssertDeclaration(SourceLocation &DeclEnd){
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000829 assert(Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert) &&
Peter Collingbourne3d9cbdc2011-04-15 00:35:57 +0000830 "Not a static_assert declaration");
831
David Blaikiebbafb8a2012-03-11 07:00:24 +0000832 if (Tok.is(tok::kw__Static_assert) && !getLangOpts().C11)
Benjamin Kramere56f3932011-12-23 17:00:35 +0000833 Diag(Tok, diag::ext_c11_static_assert);
Richard Smithb15c11c2011-10-17 23:06:20 +0000834 if (Tok.is(tok::kw_static_assert))
835 Diag(Tok, diag::warn_cxx98_compat_static_assert);
Peter Collingbourne3d9cbdc2011-04-15 00:35:57 +0000836
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000837 SourceLocation StaticAssertLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000838
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000839 BalancedDelimiterTracker T(*this, tok::l_paren);
840 if (T.consumeOpen()) {
Alp Tokerec543272013-12-24 09:48:30 +0000841 Diag(Tok, diag::err_expected) << tok::l_paren;
Richard Smith76965712012-09-13 19:12:50 +0000842 SkipMalformedDecl();
Craig Topper161e4db2014-05-21 06:02:52 +0000843 return nullptr;
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000844 }
Mike Stump11289f42009-09-09 15:08:12 +0000845
Richard Smithb3018062017-06-06 01:34:24 +0000846 EnterExpressionEvaluationContext ConstantEvaluated(
847 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
848 ExprResult AssertExpr(ParseConstantExpressionInExprEvalContext());
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000849 if (AssertExpr.isInvalid()) {
Richard Smith76965712012-09-13 19:12:50 +0000850 SkipMalformedDecl();
Craig Topper161e4db2014-05-21 06:02:52 +0000851 return nullptr;
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000852 }
Mike Stump11289f42009-09-09 15:08:12 +0000853
Richard Smith085a64f2014-06-20 19:57:12 +0000854 ExprResult AssertMessage;
855 if (Tok.is(tok::r_paren)) {
Aaron Ballmanc351fba2017-12-04 20:27:34 +0000856 Diag(Tok, getLangOpts().CPlusPlus17
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000857 ? diag::warn_cxx14_compat_static_assert_no_message
Richard Smith085a64f2014-06-20 19:57:12 +0000858 : diag::ext_static_assert_no_message)
Aaron Ballmanc351fba2017-12-04 20:27:34 +0000859 << (getLangOpts().CPlusPlus17
Richard Smith085a64f2014-06-20 19:57:12 +0000860 ? FixItHint()
861 : FixItHint::CreateInsertion(Tok.getLocation(), ", \"\""));
862 } else {
863 if (ExpectAndConsume(tok::comma)) {
864 SkipUntil(tok::semi);
865 return nullptr;
866 }
Anders Carlssonb4cf3ad2009-03-13 23:29:20 +0000867
Richard Smith085a64f2014-06-20 19:57:12 +0000868 if (!isTokenStringLiteral()) {
869 Diag(Tok, diag::err_expected_string_literal)
870 << /*Source='static_assert'*/1;
871 SkipMalformedDecl();
872 return nullptr;
873 }
Mike Stump11289f42009-09-09 15:08:12 +0000874
Richard Smith085a64f2014-06-20 19:57:12 +0000875 AssertMessage = ParseStringLiteralExpression();
876 if (AssertMessage.isInvalid()) {
877 SkipMalformedDecl();
878 return nullptr;
879 }
Richard Smithd67aea22012-03-06 03:21:47 +0000880 }
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000881
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000882 T.consumeClose();
Mike Stump11289f42009-09-09 15:08:12 +0000883
Chris Lattner49836b42009-04-02 04:16:50 +0000884 DeclEnd = Tok.getLocation();
Douglas Gregor45d6bdf2010-09-07 15:23:11 +0000885 ExpectAndConsumeSemi(diag::err_expected_semi_after_static_assert);
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000886
John McCallb268a282010-08-23 23:25:46 +0000887 return Actions.ActOnStaticAssertDeclaration(StaticAssertLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000888 AssertExpr.get(),
889 AssertMessage.get(),
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000890 T.getCloseLocation());
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000891}
892
Richard Smith74aeef52013-04-26 16:15:35 +0000893/// ParseDecltypeSpecifier - Parse a C++11 decltype specifier.
Anders Carlsson74948d02009-06-24 17:47:40 +0000894///
895/// 'decltype' ( expression )
Richard Smith74aeef52013-04-26 16:15:35 +0000896/// 'decltype' ( 'auto' ) [C++1y]
Anders Carlsson74948d02009-06-24 17:47:40 +0000897///
David Blaikie15a430a2011-12-04 05:04:18 +0000898SourceLocation Parser::ParseDecltypeSpecifier(DeclSpec &DS) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000899 assert(Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)
David Blaikie15a430a2011-12-04 05:04:18 +0000900 && "Not a decltype specifier");
901
David Blaikie15a430a2011-12-04 05:04:18 +0000902 ExprResult Result;
903 SourceLocation StartLoc = Tok.getLocation();
904 SourceLocation EndLoc;
905
906 if (Tok.is(tok::annot_decltype)) {
907 Result = getExprAnnotation(Tok);
908 EndLoc = Tok.getAnnotationEndLoc();
Richard Smithaf3b3252017-05-18 19:21:48 +0000909 ConsumeAnnotationToken();
David Blaikie15a430a2011-12-04 05:04:18 +0000910 if (Result.isInvalid()) {
911 DS.SetTypeSpecError();
912 return EndLoc;
913 }
914 } else {
Richard Smith324df552012-02-24 22:30:04 +0000915 if (Tok.getIdentifierInfo()->isStr("decltype"))
916 Diag(Tok, diag::warn_cxx98_compat_decltype);
Richard Smithfd3da932012-02-24 18:10:23 +0000917
David Blaikie15a430a2011-12-04 05:04:18 +0000918 ConsumeToken();
919
920 BalancedDelimiterTracker T(*this, tok::l_paren);
921 if (T.expectAndConsume(diag::err_expected_lparen_after,
922 "decltype", tok::r_paren)) {
923 DS.SetTypeSpecError();
924 return T.getOpenLocation() == Tok.getLocation() ?
925 StartLoc : T.getOpenLocation();
926 }
927
Richard Smith74aeef52013-04-26 16:15:35 +0000928 // Check for C++1y 'decltype(auto)'.
929 if (Tok.is(tok::kw_auto)) {
930 // No need to disambiguate here: an expression can't start with 'auto',
931 // because the typename-specifier in a function-style cast operation can't
932 // be 'auto'.
933 Diag(Tok.getLocation(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000934 getLangOpts().CPlusPlus14
Richard Smith74aeef52013-04-26 16:15:35 +0000935 ? diag::warn_cxx11_compat_decltype_auto_type_specifier
936 : diag::ext_decltype_auto_type_specifier);
937 ConsumeToken();
938 } else {
939 // Parse the expression
David Blaikie15a430a2011-12-04 05:04:18 +0000940
Richard Smith74aeef52013-04-26 16:15:35 +0000941 // C++11 [dcl.type.simple]p4:
942 // The operand of the decltype specifier is an unevaluated operand.
Faisal Valid143a0c2017-04-01 21:30:49 +0000943 EnterExpressionEvaluationContext Unevaluated(
944 Actions, Sema::ExpressionEvaluationContext::Unevaluated, nullptr,
945 /*IsDecltype=*/true);
Kaelyn Takata5cc85352015-04-10 19:16:46 +0000946 Result =
947 Actions.CorrectDelayedTyposInExpr(ParseExpression(), [](Expr *E) {
948 return E->hasPlaceholderType() ? ExprError() : E;
949 });
Richard Smith74aeef52013-04-26 16:15:35 +0000950 if (Result.isInvalid()) {
951 DS.SetTypeSpecError();
Alexey Bataevee6507d2013-11-18 08:17:37 +0000952 if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch)) {
Richard Smith74aeef52013-04-26 16:15:35 +0000953 EndLoc = ConsumeParen();
Argyrios Kyrtzidisc38395a2012-10-26 22:53:44 +0000954 } else {
Richard Smith74aeef52013-04-26 16:15:35 +0000955 if (PP.isBacktrackEnabled() && Tok.is(tok::semi)) {
956 // Backtrack to get the location of the last token before the semi.
957 PP.RevertCachedTokens(2);
958 ConsumeToken(); // the semi.
959 EndLoc = ConsumeAnyToken();
960 assert(Tok.is(tok::semi));
961 } else {
962 EndLoc = Tok.getLocation();
963 }
Argyrios Kyrtzidisc38395a2012-10-26 22:53:44 +0000964 }
Richard Smith74aeef52013-04-26 16:15:35 +0000965 return EndLoc;
Argyrios Kyrtzidisc38395a2012-10-26 22:53:44 +0000966 }
Richard Smith74aeef52013-04-26 16:15:35 +0000967
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000968 Result = Actions.ActOnDecltypeExpression(Result.get());
David Blaikie15a430a2011-12-04 05:04:18 +0000969 }
970
971 // Match the ')'
972 T.consumeClose();
973 if (T.getCloseLocation().isInvalid()) {
974 DS.SetTypeSpecError();
975 // FIXME: this should return the location of the last token
976 // that was consumed (by "consumeClose()")
977 return T.getCloseLocation();
978 }
979
Richard Smithfd555f62012-02-22 02:04:18 +0000980 if (Result.isInvalid()) {
981 DS.SetTypeSpecError();
982 return T.getCloseLocation();
983 }
984
David Blaikie15a430a2011-12-04 05:04:18 +0000985 EndLoc = T.getCloseLocation();
Anders Carlsson74948d02009-06-24 17:47:40 +0000986 }
Richard Smith74aeef52013-04-26 16:15:35 +0000987 assert(!Result.isInvalid());
Mike Stump11289f42009-09-09 15:08:12 +0000988
Craig Topper161e4db2014-05-21 06:02:52 +0000989 const char *PrevSpec = nullptr;
John McCall49bfce42009-08-03 20:12:06 +0000990 unsigned DiagID;
Erik Verbruggen888d52a2014-01-15 09:15:43 +0000991 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
Anders Carlsson74948d02009-06-24 17:47:40 +0000992 // Check for duplicate type specifiers (e.g. "int decltype(a)").
Richard Smith74aeef52013-04-26 16:15:35 +0000993 if (Result.get()
994 ? DS.SetTypeSpecType(DeclSpec::TST_decltype, StartLoc, PrevSpec,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000995 DiagID, Result.get(), Policy)
Richard Smith74aeef52013-04-26 16:15:35 +0000996 : DS.SetTypeSpecType(DeclSpec::TST_decltype_auto, StartLoc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +0000997 DiagID, Policy)) {
John McCall49bfce42009-08-03 20:12:06 +0000998 Diag(StartLoc, DiagID) << PrevSpec;
David Blaikie15a430a2011-12-04 05:04:18 +0000999 DS.SetTypeSpecError();
1000 }
1001 return EndLoc;
1002}
1003
1004void Parser::AnnotateExistingDecltypeSpecifier(const DeclSpec& DS,
1005 SourceLocation StartLoc,
1006 SourceLocation EndLoc) {
1007 // make sure we have a token we can turn into an annotation token
1008 if (PP.isBacktrackEnabled())
1009 PP.RevertCachedTokens(1);
1010 else
1011 PP.EnterToken(Tok);
1012
1013 Tok.setKind(tok::annot_decltype);
Faisal Vali090da2d2018-01-01 18:23:28 +00001014 setExprAnnotation(Tok,
1015 DS.getTypeSpecType() == TST_decltype ? DS.getRepAsExpr() :
1016 DS.getTypeSpecType() == TST_decltype_auto ? ExprResult() :
1017 ExprError());
David Blaikie15a430a2011-12-04 05:04:18 +00001018 Tok.setAnnotationEndLoc(EndLoc);
1019 Tok.setLocation(StartLoc);
1020 PP.AnnotateCachedTokens(Tok);
Anders Carlsson74948d02009-06-24 17:47:40 +00001021}
1022
Alexis Hunt4a257072011-05-19 05:37:45 +00001023void Parser::ParseUnderlyingTypeSpecifier(DeclSpec &DS) {
1024 assert(Tok.is(tok::kw___underlying_type) &&
1025 "Not an underlying type specifier");
1026
1027 SourceLocation StartLoc = ConsumeToken();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001028 BalancedDelimiterTracker T(*this, tok::l_paren);
1029 if (T.expectAndConsume(diag::err_expected_lparen_after,
1030 "__underlying_type", tok::r_paren)) {
Alexis Hunt4a257072011-05-19 05:37:45 +00001031 return;
1032 }
1033
1034 TypeResult Result = ParseTypeName();
1035 if (Result.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00001036 SkipUntil(tok::r_paren, StopAtSemi);
Alexis Hunt4a257072011-05-19 05:37:45 +00001037 return;
1038 }
1039
1040 // Match the ')'
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001041 T.consumeClose();
1042 if (T.getCloseLocation().isInvalid())
Alexis Hunt4a257072011-05-19 05:37:45 +00001043 return;
1044
Craig Topper161e4db2014-05-21 06:02:52 +00001045 const char *PrevSpec = nullptr;
Alexis Hunt4a257072011-05-19 05:37:45 +00001046 unsigned DiagID;
Alexis Hunte852b102011-05-24 22:41:36 +00001047 if (DS.SetTypeSpecType(DeclSpec::TST_underlyingType, StartLoc, PrevSpec,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001048 DiagID, Result.get(),
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001049 Actions.getASTContext().getPrintingPolicy()))
Alexis Hunt4a257072011-05-19 05:37:45 +00001050 Diag(StartLoc, DiagID) << PrevSpec;
Enea Zaffanellaa90af722013-07-06 18:54:58 +00001051 DS.setTypeofParensRange(T.getRange());
Alexis Hunt4a257072011-05-19 05:37:45 +00001052}
1053
David Blaikie00ee7a082011-10-25 15:01:20 +00001054/// ParseBaseTypeSpecifier - Parse a C++ base-type-specifier which is either a
1055/// class name or decltype-specifier. Note that we only check that the result
1056/// names a type; semantic analysis will need to verify that the type names a
1057/// class. The result is either a type or null, depending on whether a type
1058/// name was found.
Douglas Gregor831c93f2008-11-05 20:51:48 +00001059///
Richard Smith4c96e992013-02-19 23:47:15 +00001060/// base-type-specifier: [C++11 class.derived]
David Blaikie00ee7a082011-10-25 15:01:20 +00001061/// class-or-decltype
Richard Smith4c96e992013-02-19 23:47:15 +00001062/// class-or-decltype: [C++11 class.derived]
David Blaikie00ee7a082011-10-25 15:01:20 +00001063/// nested-name-specifier[opt] class-name
1064/// decltype-specifier
Richard Smith4c96e992013-02-19 23:47:15 +00001065/// class-name: [C++ class.name]
Douglas Gregor831c93f2008-11-05 20:51:48 +00001066/// identifier
Douglas Gregord54dfb82009-02-25 23:52:28 +00001067/// simple-template-id
Mike Stump11289f42009-09-09 15:08:12 +00001068///
Richard Smith4c96e992013-02-19 23:47:15 +00001069/// In C++98, instead of base-type-specifier, we have:
1070///
1071/// ::[opt] nested-name-specifier[opt] class-name
Craig Topper9ad7e262014-10-31 06:57:07 +00001072TypeResult Parser::ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
1073 SourceLocation &EndLocation) {
David Blaikiedd58d4c2011-10-25 18:46:41 +00001074 // Ignore attempts to use typename
1075 if (Tok.is(tok::kw_typename)) {
1076 Diag(Tok, diag::err_expected_class_name_not_template)
1077 << FixItHint::CreateRemoval(Tok.getLocation());
1078 ConsumeToken();
1079 }
1080
David Blaikieafa155f2011-10-25 18:17:58 +00001081 // Parse optional nested-name-specifier
1082 CXXScopeSpec SS;
David Blaikieefdccaa2016-01-15 23:43:34 +00001083 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false);
David Blaikieafa155f2011-10-25 18:17:58 +00001084
1085 BaseLoc = Tok.getLocation();
1086
David Blaikie1cd50022011-10-25 17:10:12 +00001087 // Parse decltype-specifier
David Blaikie15a430a2011-12-04 05:04:18 +00001088 // tok == kw_decltype is just error recovery, it can only happen when SS
1089 // isn't empty
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001090 if (Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)) {
David Blaikieafa155f2011-10-25 18:17:58 +00001091 if (SS.isNotEmpty())
1092 Diag(SS.getBeginLoc(), diag::err_unexpected_scope_on_base_decltype)
1093 << FixItHint::CreateRemoval(SS.getRange());
David Blaikie1cd50022011-10-25 17:10:12 +00001094 // Fake up a Declarator to use with ActOnTypeName.
1095 DeclSpec DS(AttrFactory);
1096
David Blaikie7491e732011-12-08 04:53:15 +00001097 EndLocation = ParseDecltypeSpecifier(DS);
David Blaikie1cd50022011-10-25 17:10:12 +00001098
Faisal Vali421b2d12017-12-29 05:41:00 +00001099 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
David Blaikie1cd50022011-10-25 17:10:12 +00001100 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
1101 }
1102
Douglas Gregord54dfb82009-02-25 23:52:28 +00001103 // Check whether we have a template-id that names a type.
1104 if (Tok.is(tok::annot_template_id)) {
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00001105 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregor46c59612010-01-12 17:52:59 +00001106 if (TemplateId->Kind == TNK_Type_template ||
1107 TemplateId->Kind == TNK_Dependent_template_name) {
Richard Smith62559bd2017-02-01 21:36:38 +00001108 AnnotateTemplateIdTokenAsType(/*IsClassName*/true);
Douglas Gregord54dfb82009-02-25 23:52:28 +00001109
1110 assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
John McCallba7bf592010-08-24 05:47:05 +00001111 ParsedType Type = getTypeAnnotation(Tok);
Douglas Gregord54dfb82009-02-25 23:52:28 +00001112 EndLocation = Tok.getAnnotationEndLoc();
Richard Smithaf3b3252017-05-18 19:21:48 +00001113 ConsumeAnnotationToken();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001114
1115 if (Type)
1116 return Type;
1117 return true;
Douglas Gregord54dfb82009-02-25 23:52:28 +00001118 }
1119
1120 // Fall through to produce an error below.
1121 }
1122
Douglas Gregor831c93f2008-11-05 20:51:48 +00001123 if (Tok.isNot(tok::identifier)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00001124 Diag(Tok, diag::err_expected_class_name);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001125 return true;
Douglas Gregor831c93f2008-11-05 20:51:48 +00001126 }
1127
Douglas Gregor18473f32010-01-12 21:28:44 +00001128 IdentifierInfo *Id = Tok.getIdentifierInfo();
1129 SourceLocation IdLoc = ConsumeToken();
1130
1131 if (Tok.is(tok::less)) {
1132 // It looks the user intended to write a template-id here, but the
1133 // template-name was wrong. Try to fix that.
1134 TemplateNameKind TNK = TNK_Type_template;
1135 TemplateTy Template;
Douglas Gregor0be31a22010-07-02 17:43:08 +00001136 if (!Actions.DiagnoseUnknownTemplateName(*Id, IdLoc, getCurScope(),
Douglas Gregore7c20652011-03-02 00:47:37 +00001137 &SS, Template, TNK)) {
Douglas Gregor18473f32010-01-12 21:28:44 +00001138 Diag(IdLoc, diag::err_unknown_template_name)
1139 << Id;
1140 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001141
Serge Pavlovb716b3c2013-08-10 05:54:47 +00001142 if (!Template) {
1143 TemplateArgList TemplateArgs;
1144 SourceLocation LAngleLoc, RAngleLoc;
Richard Smith9a420f92017-05-10 21:47:30 +00001145 ParseTemplateIdAfterTemplateName(true, LAngleLoc, TemplateArgs,
1146 RAngleLoc);
Douglas Gregor18473f32010-01-12 21:28:44 +00001147 return true;
Serge Pavlovb716b3c2013-08-10 05:54:47 +00001148 }
Douglas Gregor18473f32010-01-12 21:28:44 +00001149
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001150 // Form the template name
Douglas Gregor18473f32010-01-12 21:28:44 +00001151 UnqualifiedId TemplateName;
1152 TemplateName.setIdentifier(Id, IdLoc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001153
Douglas Gregor18473f32010-01-12 21:28:44 +00001154 // Parse the full template-id, then turn it into a type.
Abramo Bagnara7945c982012-01-27 09:46:47 +00001155 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
Richard Smith62559bd2017-02-01 21:36:38 +00001156 TemplateName))
Douglas Gregor18473f32010-01-12 21:28:44 +00001157 return true;
Richard Smith62559bd2017-02-01 21:36:38 +00001158 if (TNK == TNK_Type_template || TNK == TNK_Dependent_template_name)
1159 AnnotateTemplateIdTokenAsType(/*IsClassName*/true);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001160
Douglas Gregor18473f32010-01-12 21:28:44 +00001161 // If we didn't end up with a typename token, there's nothing more we
1162 // can do.
1163 if (Tok.isNot(tok::annot_typename))
1164 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001165
Douglas Gregor18473f32010-01-12 21:28:44 +00001166 // Retrieve the type from the annotation token, consume that token, and
1167 // return.
1168 EndLocation = Tok.getAnnotationEndLoc();
John McCallba7bf592010-08-24 05:47:05 +00001169 ParsedType Type = getTypeAnnotation(Tok);
Richard Smithaf3b3252017-05-18 19:21:48 +00001170 ConsumeAnnotationToken();
Douglas Gregor18473f32010-01-12 21:28:44 +00001171 return Type;
1172 }
1173
Douglas Gregor831c93f2008-11-05 20:51:48 +00001174 // We have an identifier; check whether it is actually a type.
Craig Topper161e4db2014-05-21 06:02:52 +00001175 IdentifierInfo *CorrectedII = nullptr;
Richard Smith600b5262017-01-26 20:40:47 +00001176 ParsedType Type = Actions.getTypeName(
Richard Smith62559bd2017-02-01 21:36:38 +00001177 *Id, IdLoc, getCurScope(), &SS, /*IsClassName=*/true, false, nullptr,
Richard Smith600b5262017-01-26 20:40:47 +00001178 /*IsCtorOrDtorName=*/false,
1179 /*NonTrivialTypeSourceInfo=*/true,
1180 /*IsClassTemplateDeductionContext*/ false, &CorrectedII);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001181 if (!Type) {
Douglas Gregorfe17d252010-02-16 19:09:40 +00001182 Diag(IdLoc, diag::err_expected_class_name);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001183 return true;
Douglas Gregor831c93f2008-11-05 20:51:48 +00001184 }
1185
1186 // Consume the identifier.
Douglas Gregor18473f32010-01-12 21:28:44 +00001187 EndLocation = IdLoc;
Nick Lewycky19b9f952010-07-26 16:56:01 +00001188
1189 // Fake up a Declarator to use with ActOnTypeName.
John McCall084e83d2011-03-24 11:26:52 +00001190 DeclSpec DS(AttrFactory);
Nick Lewycky19b9f952010-07-26 16:56:01 +00001191 DS.SetRangeStart(IdLoc);
1192 DS.SetRangeEnd(EndLocation);
Douglas Gregore7c20652011-03-02 00:47:37 +00001193 DS.getTypeSpecScope() = SS;
Nick Lewycky19b9f952010-07-26 16:56:01 +00001194
Craig Topper161e4db2014-05-21 06:02:52 +00001195 const char *PrevSpec = nullptr;
Nick Lewycky19b9f952010-07-26 16:56:01 +00001196 unsigned DiagID;
Faisal Vali090da2d2018-01-01 18:23:28 +00001197 DS.SetTypeSpecType(TST_typename, IdLoc, PrevSpec, DiagID, Type,
1198 Actions.getASTContext().getPrintingPolicy());
Nick Lewycky19b9f952010-07-26 16:56:01 +00001199
Faisal Vali421b2d12017-12-29 05:41:00 +00001200 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
Nick Lewycky19b9f952010-07-26 16:56:01 +00001201 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
Douglas Gregor831c93f2008-11-05 20:51:48 +00001202}
1203
John McCall8d32c052012-05-22 21:28:12 +00001204void Parser::ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001205 while (Tok.isOneOf(tok::kw___single_inheritance,
1206 tok::kw___multiple_inheritance,
1207 tok::kw___virtual_inheritance)) {
John McCall8d32c052012-05-22 21:28:12 +00001208 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
1209 SourceLocation AttrNameLoc = ConsumeToken();
Craig Topper161e4db2014-05-21 06:02:52 +00001210 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
Aaron Ballman8edb5c22013-12-18 23:44:18 +00001211 AttributeList::AS_Keyword);
John McCall8d32c052012-05-22 21:28:12 +00001212 }
1213}
1214
Richard Smith369b9f92012-06-25 21:37:02 +00001215/// Determine whether the following tokens are valid after a type-specifier
1216/// which could be a standalone declaration. This will conservatively return
1217/// true if there's any doubt, and is appropriate for insert-';' fixits.
Richard Smith200f47c2012-07-02 19:14:01 +00001218bool Parser::isValidAfterTypeSpecifier(bool CouldBeBitfield) {
Richard Smith369b9f92012-06-25 21:37:02 +00001219 // This switch enumerates the valid "follow" set for type-specifiers.
1220 switch (Tok.getKind()) {
1221 default: break;
1222 case tok::semi: // struct foo {...} ;
1223 case tok::star: // struct foo {...} * P;
1224 case tok::amp: // struct foo {...} & R = ...
Richard Smith1ac67d12013-01-19 03:48:05 +00001225 case tok::ampamp: // struct foo {...} && R = ...
Richard Smith369b9f92012-06-25 21:37:02 +00001226 case tok::identifier: // struct foo {...} V ;
1227 case tok::r_paren: //(struct foo {...} ) {4}
1228 case tok::annot_cxxscope: // struct foo {...} a:: b;
1229 case tok::annot_typename: // struct foo {...} a ::b;
1230 case tok::annot_template_id: // struct foo {...} a<int> ::b;
1231 case tok::l_paren: // struct foo {...} ( x);
1232 case tok::comma: // __builtin_offsetof(struct foo{...} ,
Richard Smith1ac67d12013-01-19 03:48:05 +00001233 case tok::kw_operator: // struct foo operator ++() {...}
Alp Tokerd3f79c52013-11-24 20:24:54 +00001234 case tok::kw___declspec: // struct foo {...} __declspec(...)
Richard Smith843f18f2014-08-13 02:13:15 +00001235 case tok::l_square: // void f(struct f [ 3])
1236 case tok::ellipsis: // void f(struct f ... [Ns])
Abramo Bagnara152eb392014-08-16 08:29:27 +00001237 // FIXME: we should emit semantic diagnostic when declaration
1238 // attribute is in type attribute position.
1239 case tok::kw___attribute: // struct foo __attribute__((used)) x;
David Majnemer15b311c2016-06-14 03:20:28 +00001240 case tok::annot_pragma_pack: // struct foo {...} _Pragma(pack(pop));
1241 // struct foo {...} _Pragma(section(...));
1242 case tok::annot_pragma_ms_pragma:
1243 // struct foo {...} _Pragma(vtordisp(pop));
1244 case tok::annot_pragma_ms_vtordisp:
1245 // struct foo {...} _Pragma(pointers_to_members(...));
1246 case tok::annot_pragma_ms_pointers_to_members:
Richard Smith369b9f92012-06-25 21:37:02 +00001247 return true;
Richard Smith200f47c2012-07-02 19:14:01 +00001248 case tok::colon:
1249 return CouldBeBitfield; // enum E { ... } : 2;
Reid Klecknercfa91552016-03-21 16:08:49 +00001250 // Microsoft compatibility
1251 case tok::kw___cdecl: // struct foo {...} __cdecl x;
1252 case tok::kw___fastcall: // struct foo {...} __fastcall x;
1253 case tok::kw___stdcall: // struct foo {...} __stdcall x;
1254 case tok::kw___thiscall: // struct foo {...} __thiscall x;
1255 case tok::kw___vectorcall: // struct foo {...} __vectorcall x;
1256 // We will diagnose these calling-convention specifiers on non-function
1257 // declarations later, so claim they are valid after a type specifier.
1258 return getLangOpts().MicrosoftExt;
Richard Smith369b9f92012-06-25 21:37:02 +00001259 // Type qualifiers
1260 case tok::kw_const: // struct foo {...} const x;
1261 case tok::kw_volatile: // struct foo {...} volatile x;
1262 case tok::kw_restrict: // struct foo {...} restrict x;
Richard Smith843f18f2014-08-13 02:13:15 +00001263 case tok::kw__Atomic: // struct foo {...} _Atomic x;
Nico Rieck3e1ee832014-12-04 23:30:25 +00001264 case tok::kw___unaligned: // struct foo {...} __unaligned *x;
Richard Smith1ac67d12013-01-19 03:48:05 +00001265 // Function specifiers
1266 // Note, no 'explicit'. An explicit function must be either a conversion
1267 // operator or a constructor. Either way, it can't have a return type.
1268 case tok::kw_inline: // struct foo inline f();
1269 case tok::kw_virtual: // struct foo virtual f();
1270 case tok::kw_friend: // struct foo friend f();
Richard Smith369b9f92012-06-25 21:37:02 +00001271 // Storage-class specifiers
1272 case tok::kw_static: // struct foo {...} static x;
1273 case tok::kw_extern: // struct foo {...} extern x;
1274 case tok::kw_typedef: // struct foo {...} typedef x;
1275 case tok::kw_register: // struct foo {...} register x;
1276 case tok::kw_auto: // struct foo {...} auto x;
1277 case tok::kw_mutable: // struct foo {...} mutable x;
Richard Smith1ac67d12013-01-19 03:48:05 +00001278 case tok::kw_thread_local: // struct foo {...} thread_local x;
Richard Smith369b9f92012-06-25 21:37:02 +00001279 case tok::kw_constexpr: // struct foo {...} constexpr x;
1280 // As shown above, type qualifiers and storage class specifiers absolutely
1281 // can occur after class specifiers according to the grammar. However,
1282 // almost no one actually writes code like this. If we see one of these,
1283 // it is much more likely that someone missed a semi colon and the
1284 // type/storage class specifier we're seeing is part of the *next*
1285 // intended declaration, as in:
1286 //
1287 // struct foo { ... }
1288 // typedef int X;
1289 //
1290 // We'd really like to emit a missing semicolon error instead of emitting
1291 // an error on the 'int' saying that you can't have two type specifiers in
1292 // the same declaration of X. Because of this, we look ahead past this
1293 // token to see if it's a type specifier. If so, we know the code is
1294 // otherwise invalid, so we can produce the expected semi error.
1295 if (!isKnownToBeTypeSpecifier(NextToken()))
1296 return true;
1297 break;
1298 case tok::r_brace: // struct bar { struct foo {...} }
1299 // Missing ';' at end of struct is accepted as an extension in C mode.
1300 if (!getLangOpts().CPlusPlus)
1301 return true;
1302 break;
Richard Smith52c5b872013-01-29 04:13:32 +00001303 case tok::greater:
1304 // template<class T = class X>
1305 return getLangOpts().CPlusPlus;
Richard Smith369b9f92012-06-25 21:37:02 +00001306 }
1307 return false;
1308}
1309
Douglas Gregor556877c2008-04-13 21:30:24 +00001310/// ParseClassSpecifier - Parse a C++ class-specifier [C++ class] or
1311/// elaborated-type-specifier [C++ dcl.type.elab]; we can't tell which
1312/// until we reach the start of a definition or see a token that
Richard Smithc5b05522012-03-12 07:56:15 +00001313/// cannot start a definition.
Douglas Gregor556877c2008-04-13 21:30:24 +00001314///
1315/// class-specifier: [C++ class]
1316/// class-head '{' member-specification[opt] '}'
1317/// class-head '{' member-specification[opt] '}' attributes[opt]
1318/// class-head:
1319/// class-key identifier[opt] base-clause[opt]
1320/// class-key nested-name-specifier identifier base-clause[opt]
1321/// class-key nested-name-specifier[opt] simple-template-id
1322/// base-clause[opt]
1323/// [GNU] class-key attributes[opt] identifier[opt] base-clause[opt]
Mike Stump11289f42009-09-09 15:08:12 +00001324/// [GNU] class-key attributes[opt] nested-name-specifier
Douglas Gregor556877c2008-04-13 21:30:24 +00001325/// identifier base-clause[opt]
Mike Stump11289f42009-09-09 15:08:12 +00001326/// [GNU] class-key attributes[opt] nested-name-specifier[opt]
Douglas Gregor556877c2008-04-13 21:30:24 +00001327/// simple-template-id base-clause[opt]
1328/// class-key:
1329/// 'class'
1330/// 'struct'
1331/// 'union'
1332///
1333/// elaborated-type-specifier: [C++ dcl.type.elab]
Mike Stump11289f42009-09-09 15:08:12 +00001334/// class-key ::[opt] nested-name-specifier[opt] identifier
1335/// class-key ::[opt] nested-name-specifier[opt] 'template'[opt]
1336/// simple-template-id
Douglas Gregor556877c2008-04-13 21:30:24 +00001337///
1338/// Note that the C++ class-specifier and elaborated-type-specifier,
1339/// together, subsume the C99 struct-or-union-specifier:
1340///
1341/// struct-or-union-specifier: [C99 6.7.2.1]
1342/// struct-or-union identifier[opt] '{' struct-contents '}'
1343/// struct-or-union identifier
1344/// [GNU] struct-or-union attributes[opt] identifier[opt] '{' struct-contents
1345/// '}' attributes[opt]
1346/// [GNU] struct-or-union attributes[opt] identifier
1347/// struct-or-union:
1348/// 'struct'
1349/// 'union'
Chris Lattnerffaa0e62009-04-12 21:49:30 +00001350void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind,
1351 SourceLocation StartLoc, DeclSpec &DS,
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001352 const ParsedTemplateInfo &TemplateInfo,
Douglas Gregordf593fb2011-11-07 17:33:42 +00001353 AccessSpecifier AS,
Michael Han9407e502012-11-26 22:54:45 +00001354 bool EnteringContext, DeclSpecContext DSC,
Bill Wendling44426052012-12-20 19:22:21 +00001355 ParsedAttributesWithRange &Attributes) {
Joao Matose9a3ed42012-08-31 22:18:20 +00001356 DeclSpec::TST TagType;
1357 if (TagTokKind == tok::kw_struct)
1358 TagType = DeclSpec::TST_struct;
1359 else if (TagTokKind == tok::kw___interface)
1360 TagType = DeclSpec::TST_interface;
1361 else if (TagTokKind == tok::kw_class)
1362 TagType = DeclSpec::TST_class;
1363 else {
Chris Lattnerffaa0e62009-04-12 21:49:30 +00001364 assert(TagTokKind == tok::kw_union && "Not a class specifier");
1365 TagType = DeclSpec::TST_union;
1366 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001367
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00001368 if (Tok.is(tok::code_completion)) {
1369 // Code completion for a struct, class, or union name.
Douglas Gregor0be31a22010-07-02 17:43:08 +00001370 Actions.CodeCompleteTag(getCurScope(), TagType);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001371 return cutOffParsing();
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00001372 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001373
Chandler Carruth2d69ec72010-06-28 08:39:25 +00001374 // C++03 [temp.explicit] 14.7.2/8:
1375 // The usual access checking rules do not apply to names used to specify
1376 // explicit instantiations.
1377 //
1378 // As an extension we do not perform access checking on the names used to
1379 // specify explicit specializations either. This is important to allow
1380 // specializing traits classes for private types.
John McCall6347b682012-05-07 06:16:58 +00001381 //
1382 // Note that we don't suppress if this turns out to be an elaborated
1383 // type specifier.
1384 bool shouldDelayDiagsInTag =
1385 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
1386 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
1387 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
Chandler Carruth2d69ec72010-06-28 08:39:25 +00001388
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001389 ParsedAttributesWithRange attrs(AttrFactory);
Douglas Gregor556877c2008-04-13 21:30:24 +00001390 // If attributes exist after tag, parse them.
Richard Smith37a45dd2013-10-24 01:21:09 +00001391 MaybeParseGNUAttributes(attrs);
Aaron Ballman068aa512015-05-20 20:58:33 +00001392 MaybeParseMicrosoftDeclSpecs(attrs);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001393
John McCall8d32c052012-05-22 21:28:12 +00001394 // Parse inheritance specifiers.
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001395 if (Tok.isOneOf(tok::kw___single_inheritance,
1396 tok::kw___multiple_inheritance,
1397 tok::kw___virtual_inheritance))
Richard Smith37a45dd2013-10-24 01:21:09 +00001398 ParseMicrosoftInheritanceClassAttributes(attrs);
John McCall8d32c052012-05-22 21:28:12 +00001399
Alexis Hunt96d5c762009-11-21 08:43:09 +00001400 // If C++0x attributes exist here, parse them.
1401 // FIXME: Are we consistent with the ordering of parsing of different
1402 // styles of attributes?
Richard Smith89645bc2013-01-02 12:01:23 +00001403 MaybeParseCXX11Attributes(attrs);
Mike Stump11289f42009-09-09 15:08:12 +00001404
Michael Han309af292013-01-07 16:57:11 +00001405 // Source location used by FIXIT to insert misplaced
1406 // C++11 attributes
1407 SourceLocation AttrFixitLoc = Tok.getLocation();
1408
Nico Weber7c3c5be2014-09-23 04:09:56 +00001409 if (TagType == DeclSpec::TST_struct &&
David Majnemer86330af2014-12-29 02:14:26 +00001410 Tok.isNot(tok::identifier) &&
1411 !Tok.isAnnotation() &&
Nico Weber7c3c5be2014-09-23 04:09:56 +00001412 Tok.getIdentifierInfo() &&
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001413 Tok.isOneOf(tok::kw___is_abstract,
Eric Fiselier07360662017-04-12 22:12:15 +00001414 tok::kw___is_aggregate,
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001415 tok::kw___is_arithmetic,
1416 tok::kw___is_array,
David Majnemerb3d96882016-05-23 17:21:55 +00001417 tok::kw___is_assignable,
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001418 tok::kw___is_base_of,
1419 tok::kw___is_class,
1420 tok::kw___is_complete_type,
1421 tok::kw___is_compound,
1422 tok::kw___is_const,
1423 tok::kw___is_constructible,
1424 tok::kw___is_convertible,
1425 tok::kw___is_convertible_to,
1426 tok::kw___is_destructible,
1427 tok::kw___is_empty,
1428 tok::kw___is_enum,
1429 tok::kw___is_floating_point,
1430 tok::kw___is_final,
1431 tok::kw___is_function,
1432 tok::kw___is_fundamental,
1433 tok::kw___is_integral,
1434 tok::kw___is_interface_class,
1435 tok::kw___is_literal,
1436 tok::kw___is_lvalue_expr,
1437 tok::kw___is_lvalue_reference,
1438 tok::kw___is_member_function_pointer,
1439 tok::kw___is_member_object_pointer,
1440 tok::kw___is_member_pointer,
1441 tok::kw___is_nothrow_assignable,
1442 tok::kw___is_nothrow_constructible,
1443 tok::kw___is_nothrow_destructible,
1444 tok::kw___is_object,
1445 tok::kw___is_pod,
1446 tok::kw___is_pointer,
1447 tok::kw___is_polymorphic,
1448 tok::kw___is_reference,
1449 tok::kw___is_rvalue_expr,
1450 tok::kw___is_rvalue_reference,
1451 tok::kw___is_same,
1452 tok::kw___is_scalar,
1453 tok::kw___is_sealed,
1454 tok::kw___is_signed,
1455 tok::kw___is_standard_layout,
1456 tok::kw___is_trivial,
1457 tok::kw___is_trivially_assignable,
1458 tok::kw___is_trivially_constructible,
1459 tok::kw___is_trivially_copyable,
1460 tok::kw___is_union,
1461 tok::kw___is_unsigned,
1462 tok::kw___is_void,
1463 tok::kw___is_volatile))
Nico Weber7c3c5be2014-09-23 04:09:56 +00001464 // GNU libstdc++ 4.2 and libc++ use certain intrinsic names as the
1465 // name of struct templates, but some are keywords in GCC >= 4.3
1466 // and Clang. Therefore, when we see the token sequence "struct
1467 // X", make X into a normal identifier rather than a keyword, to
1468 // allow libstdc++ 4.2 and libc++ to work properly.
1469 TryKeywordIdentFallback(true);
Mike Stump11289f42009-09-09 15:08:12 +00001470
David Majnemer51fd8a02015-07-22 23:46:18 +00001471 struct PreserveAtomicIdentifierInfoRAII {
1472 PreserveAtomicIdentifierInfoRAII(Token &Tok, bool Enabled)
1473 : AtomicII(nullptr) {
1474 if (!Enabled)
1475 return;
1476 assert(Tok.is(tok::kw__Atomic));
1477 AtomicII = Tok.getIdentifierInfo();
1478 AtomicII->revertTokenIDToIdentifier();
1479 Tok.setKind(tok::identifier);
1480 }
1481 ~PreserveAtomicIdentifierInfoRAII() {
1482 if (!AtomicII)
1483 return;
1484 AtomicII->revertIdentifierToTokenID(tok::kw__Atomic);
1485 }
1486 IdentifierInfo *AtomicII;
1487 };
1488
1489 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
1490 // implementation for VS2013 uses _Atomic as an identifier for one of the
1491 // classes in <atomic>. When we are parsing 'struct _Atomic', don't consider
1492 // '_Atomic' to be a keyword. We are careful to undo this so that clang can
1493 // use '_Atomic' in its own header files.
1494 bool ShouldChangeAtomicToIdentifier = getLangOpts().MSVCCompat &&
1495 Tok.is(tok::kw__Atomic) &&
1496 TagType == DeclSpec::TST_struct;
1497 PreserveAtomicIdentifierInfoRAII AtomicTokenGuard(
1498 Tok, ShouldChangeAtomicToIdentifier);
1499
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001500 // Parse the (optional) nested-name-specifier.
John McCall9dab4e62009-12-12 11:40:51 +00001501 CXXScopeSpec &SS = DS.getTypeSpecScope();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001502 if (getLangOpts().CPlusPlus) {
Serge Pavlov458ea762014-07-16 05:16:52 +00001503 // "FOO : BAR" is not a potential typo for "FOO::BAR". In this context it
1504 // is a base-specifier-list.
Chris Lattnerd5c1c9d2009-12-10 00:32:41 +00001505 ColonProtectionRAIIObject X(*this);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001506
Nico Webercfaa4cd2015-02-15 07:26:13 +00001507 CXXScopeSpec Spec;
1508 bool HasValidSpec = true;
David Blaikieefdccaa2016-01-15 23:43:34 +00001509 if (ParseOptionalCXXScopeSpecifier(Spec, nullptr, EnteringContext)) {
John McCall413021a2010-07-30 06:26:29 +00001510 DS.SetTypeSpecError();
Nico Webercfaa4cd2015-02-15 07:26:13 +00001511 HasValidSpec = false;
1512 }
1513 if (Spec.isSet())
1514 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::annot_template_id)) {
Alp Tokerec543272013-12-24 09:48:30 +00001515 Diag(Tok, diag::err_expected) << tok::identifier;
Nico Webercfaa4cd2015-02-15 07:26:13 +00001516 HasValidSpec = false;
1517 }
1518 if (HasValidSpec)
1519 SS = Spec;
Chris Lattnerd5c1c9d2009-12-10 00:32:41 +00001520 }
Douglas Gregor67a65642009-02-17 23:15:12 +00001521
Douglas Gregor916462b2009-10-30 21:46:58 +00001522 TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
1523
Douglas Gregor67a65642009-02-17 23:15:12 +00001524 // Parse the (optional) class name or simple-template-id.
Craig Topper161e4db2014-05-21 06:02:52 +00001525 IdentifierInfo *Name = nullptr;
Douglas Gregor556877c2008-04-13 21:30:24 +00001526 SourceLocation NameLoc;
Craig Topper161e4db2014-05-21 06:02:52 +00001527 TemplateIdAnnotation *TemplateId = nullptr;
Douglas Gregor556877c2008-04-13 21:30:24 +00001528 if (Tok.is(tok::identifier)) {
1529 Name = Tok.getIdentifierInfo();
1530 NameLoc = ConsumeToken();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001531
David Blaikiebbafb8a2012-03-11 07:00:24 +00001532 if (Tok.is(tok::less) && getLangOpts().CPlusPlus) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001533 // The name was supposed to refer to a template, but didn't.
Douglas Gregor916462b2009-10-30 21:46:58 +00001534 // Eat the template argument list and try to continue parsing this as
1535 // a class (or template thereof).
1536 TemplateArgList TemplateArgs;
Douglas Gregor916462b2009-10-30 21:46:58 +00001537 SourceLocation LAngleLoc, RAngleLoc;
Richard Smith9a420f92017-05-10 21:47:30 +00001538 if (ParseTemplateIdAfterTemplateName(true, LAngleLoc, TemplateArgs,
1539 RAngleLoc)) {
Douglas Gregor916462b2009-10-30 21:46:58 +00001540 // We couldn't parse the template argument list at all, so don't
1541 // try to give any location information for the list.
1542 LAngleLoc = RAngleLoc = SourceLocation();
1543 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001544
Douglas Gregor916462b2009-10-30 21:46:58 +00001545 Diag(NameLoc, diag::err_explicit_spec_non_template)
Alp Toker01d65e12014-01-06 12:54:41 +00001546 << (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
1547 << TagTokKind << Name << SourceRange(LAngleLoc, RAngleLoc);
Joao Matose9a3ed42012-08-31 22:18:20 +00001548
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001549 // Strip off the last template parameter list if it was empty, since
Douglas Gregor1d0015f2009-10-30 22:09:44 +00001550 // we've removed its template argument list.
1551 if (TemplateParams && TemplateInfo.LastParameterListWasEmpty) {
Hubert Tong97b06632016-04-13 18:41:03 +00001552 if (TemplateParams->size() > 1) {
Douglas Gregor1d0015f2009-10-30 22:09:44 +00001553 TemplateParams->pop_back();
1554 } else {
Craig Topper161e4db2014-05-21 06:02:52 +00001555 TemplateParams = nullptr;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001556 const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind
Douglas Gregor1d0015f2009-10-30 22:09:44 +00001557 = ParsedTemplateInfo::NonTemplate;
1558 }
1559 } else if (TemplateInfo.Kind
1560 == ParsedTemplateInfo::ExplicitInstantiation) {
1561 // Pretend this is just a forward declaration.
Craig Topper161e4db2014-05-21 06:02:52 +00001562 TemplateParams = nullptr;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001563 const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind
Douglas Gregor916462b2009-10-30 21:46:58 +00001564 = ParsedTemplateInfo::NonTemplate;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001565 const_cast<ParsedTemplateInfo&>(TemplateInfo).TemplateLoc
Douglas Gregor1d0015f2009-10-30 22:09:44 +00001566 = SourceLocation();
1567 const_cast<ParsedTemplateInfo&>(TemplateInfo).ExternLoc
1568 = SourceLocation();
Douglas Gregor916462b2009-10-30 21:46:58 +00001569 }
Douglas Gregor916462b2009-10-30 21:46:58 +00001570 }
Douglas Gregor7f741122009-02-25 19:37:18 +00001571 } else if (Tok.is(tok::annot_template_id)) {
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00001572 TemplateId = takeTemplateIdAnnotation(Tok);
Richard Smithaf3b3252017-05-18 19:21:48 +00001573 NameLoc = ConsumeAnnotationToken();
Douglas Gregor67a65642009-02-17 23:15:12 +00001574
Douglas Gregore7c20652011-03-02 00:47:37 +00001575 if (TemplateId->Kind != TNK_Type_template &&
1576 TemplateId->Kind != TNK_Dependent_template_name) {
Douglas Gregor7f741122009-02-25 19:37:18 +00001577 // The template-name in the simple-template-id refers to
1578 // something other than a class template. Give an appropriate
1579 // error message and skip to the ';'.
1580 SourceRange Range(NameLoc);
1581 if (SS.isNotEmpty())
1582 Range.setBegin(SS.getBeginLoc());
Douglas Gregor67a65642009-02-17 23:15:12 +00001583
Richard Smith72bfbd82013-12-04 00:28:23 +00001584 // FIXME: Name may be null here.
Douglas Gregor7f741122009-02-25 19:37:18 +00001585 Diag(TemplateId->LAngleLoc, diag::err_template_spec_syntax_non_template)
Richard Trieu30f93852013-06-19 22:25:01 +00001586 << TemplateId->Name << static_cast<int>(TemplateId->Kind) << Range;
Mike Stump11289f42009-09-09 15:08:12 +00001587
Douglas Gregor7f741122009-02-25 19:37:18 +00001588 DS.SetTypeSpecError();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001589 SkipUntil(tok::semi, StopBeforeMatch);
Douglas Gregor7f741122009-02-25 19:37:18 +00001590 return;
Douglas Gregor67a65642009-02-17 23:15:12 +00001591 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001592 }
1593
Richard Smithbfdb1082012-03-12 08:56:40 +00001594 // There are four options here.
1595 // - If we are in a trailing return type, this is always just a reference,
1596 // and we must not try to parse a definition. For instance,
1597 // [] () -> struct S { };
1598 // does not define a type.
1599 // - If we have 'struct foo {...', 'struct foo :...',
1600 // 'struct foo final :' or 'struct foo final {', then this is a definition.
1601 // - If we have 'struct foo;', then this is either a forward declaration
1602 // or a friend declaration, which have to be treated differently.
1603 // - Otherwise we have something like 'struct foo xyz', a reference.
Michael Han9407e502012-11-26 22:54:45 +00001604 //
1605 // We also detect these erroneous cases to provide better diagnostic for
1606 // C++11 attributes parsing.
1607 // - attributes follow class name:
1608 // struct foo [[]] {};
1609 // - attributes appear before or after 'final':
1610 // struct foo [[]] final [[]] {};
1611 //
Richard Smithc5b05522012-03-12 07:56:15 +00001612 // However, in type-specifier-seq's, things look like declarations but are
1613 // just references, e.g.
1614 // new struct s;
Sebastian Redl2b372722010-02-03 21:21:43 +00001615 // or
Richard Smithc5b05522012-03-12 07:56:15 +00001616 // &T::operator struct s;
Faisal Vali7db85c52017-12-31 00:06:40 +00001617 // For these, DSC is DeclSpecContext::DSC_type_specifier or
1618 // DeclSpecContext::DSC_alias_declaration.
Michael Han9407e502012-11-26 22:54:45 +00001619
1620 // If there are attributes after class name, parse them.
Richard Smith89645bc2013-01-02 12:01:23 +00001621 MaybeParseCXX11Attributes(Attributes);
Michael Han9407e502012-11-26 22:54:45 +00001622
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001623 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
John McCallfaf5fb42010-08-26 23:41:50 +00001624 Sema::TagUseKind TUK;
Faisal Vali7db85c52017-12-31 00:06:40 +00001625 if (DSC == DeclSpecContext::DSC_trailing)
Richard Smithbfdb1082012-03-12 08:56:40 +00001626 TUK = Sema::TUK_Reference;
1627 else if (Tok.is(tok::l_brace) ||
1628 (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
Richard Smith89645bc2013-01-02 12:01:23 +00001629 (isCXX11FinalKeyword() &&
David Blaikie9933a5a2012-03-12 15:39:49 +00001630 (NextToken().is(tok::l_brace) || NextToken().is(tok::colon)))) {
Douglas Gregor3dad8422009-09-26 06:47:28 +00001631 if (DS.isFriendSpecified()) {
1632 // C++ [class.friend]p2:
1633 // A class shall not be defined in a friend declaration.
Richard Smith0f8ee222012-01-10 01:33:14 +00001634 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
Douglas Gregor3dad8422009-09-26 06:47:28 +00001635 << SourceRange(DS.getFriendSpecLoc());
1636
1637 // Skip everything up to the semicolon, so that this looks like a proper
1638 // friend class (or template thereof) declaration.
Alexey Bataevee6507d2013-11-18 08:17:37 +00001639 SkipUntil(tok::semi, StopBeforeMatch);
John McCallfaf5fb42010-08-26 23:41:50 +00001640 TUK = Sema::TUK_Friend;
Douglas Gregor3dad8422009-09-26 06:47:28 +00001641 } else {
1642 // Okay, this is a class definition.
John McCallfaf5fb42010-08-26 23:41:50 +00001643 TUK = Sema::TUK_Definition;
Douglas Gregor3dad8422009-09-26 06:47:28 +00001644 }
Richard Smith434516c2013-02-22 06:46:23 +00001645 } else if (isCXX11FinalKeyword() && (NextToken().is(tok::l_square) ||
1646 NextToken().is(tok::kw_alignas))) {
Michael Han9407e502012-11-26 22:54:45 +00001647 // We can't tell if this is a definition or reference
1648 // until we skipped the 'final' and C++11 attribute specifiers.
1649 TentativeParsingAction PA(*this);
1650
1651 // Skip the 'final' keyword.
1652 ConsumeToken();
1653
1654 // Skip C++11 attribute specifiers.
1655 while (true) {
1656 if (Tok.is(tok::l_square) && NextToken().is(tok::l_square)) {
1657 ConsumeBracket();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001658 if (!SkipUntil(tok::r_square, StopAtSemi))
Michael Han9407e502012-11-26 22:54:45 +00001659 break;
Richard Smith434516c2013-02-22 06:46:23 +00001660 } else if (Tok.is(tok::kw_alignas) && NextToken().is(tok::l_paren)) {
Michael Han9407e502012-11-26 22:54:45 +00001661 ConsumeToken();
1662 ConsumeParen();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001663 if (!SkipUntil(tok::r_paren, StopAtSemi))
Michael Han9407e502012-11-26 22:54:45 +00001664 break;
1665 } else {
1666 break;
1667 }
1668 }
1669
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001670 if (Tok.isOneOf(tok::l_brace, tok::colon))
Michael Han9407e502012-11-26 22:54:45 +00001671 TUK = Sema::TUK_Definition;
1672 else
1673 TUK = Sema::TUK_Reference;
1674
1675 PA.Revert();
Richard Smith649c7b062014-01-08 00:56:48 +00001676 } else if (!isTypeSpecifier(DSC) &&
Richard Smith369b9f92012-06-25 21:37:02 +00001677 (Tok.is(tok::semi) ||
Richard Smith200f47c2012-07-02 19:14:01 +00001678 (Tok.isAtStartOfLine() && !isValidAfterTypeSpecifier(false)))) {
John McCallfaf5fb42010-08-26 23:41:50 +00001679 TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
Joao Matose9a3ed42012-08-31 22:18:20 +00001680 if (Tok.isNot(tok::semi)) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001681 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
Joao Matose9a3ed42012-08-31 22:18:20 +00001682 // A semicolon was missing after this declaration. Diagnose and recover.
Alp Toker383d2c42014-01-01 03:08:43 +00001683 ExpectAndConsume(tok::semi, diag::err_expected_after,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001684 DeclSpec::getSpecifierName(TagType, PPol));
Joao Matose9a3ed42012-08-31 22:18:20 +00001685 PP.EnterToken(Tok);
1686 Tok.setKind(tok::semi);
1687 }
Richard Smith369b9f92012-06-25 21:37:02 +00001688 } else
John McCallfaf5fb42010-08-26 23:41:50 +00001689 TUK = Sema::TUK_Reference;
Douglas Gregor556877c2008-04-13 21:30:24 +00001690
Michael Han9407e502012-11-26 22:54:45 +00001691 // Forbid misplaced attributes. In cases of a reference, we pass attributes
1692 // to caller to handle.
Michael Han309af292013-01-07 16:57:11 +00001693 if (TUK != Sema::TUK_Reference) {
1694 // If this is not a reference, then the only possible
1695 // valid place for C++11 attributes to appear here
1696 // is between class-key and class-name. If there are
1697 // any attributes after class-name, we try a fixit to move
1698 // them to the right place.
1699 SourceRange AttrRange = Attributes.Range;
1700 if (AttrRange.isValid()) {
1701 Diag(AttrRange.getBegin(), diag::err_attributes_not_allowed)
1702 << AttrRange
1703 << FixItHint::CreateInsertionFromRange(AttrFixitLoc,
1704 CharSourceRange(AttrRange, true))
1705 << FixItHint::CreateRemoval(AttrRange);
1706
1707 // Recover by adding misplaced attributes to the attribute list
1708 // of the class so they can be applied on the class later.
1709 attrs.takeAllFrom(Attributes);
1710 }
1711 }
Michael Han9407e502012-11-26 22:54:45 +00001712
John McCall6347b682012-05-07 06:16:58 +00001713 // If this is an elaborated type specifier, and we delayed
1714 // diagnostics before, just merge them into the current pool.
1715 if (shouldDelayDiagsInTag) {
1716 diagsFromTag.done();
1717 if (TUK == Sema::TUK_Reference)
1718 diagsFromTag.redelay();
1719 }
1720
John McCall413021a2010-07-30 06:26:29 +00001721 if (!Name && !TemplateId && (DS.getTypeSpecType() == DeclSpec::TST_error ||
John McCallfaf5fb42010-08-26 23:41:50 +00001722 TUK != Sema::TUK_Definition)) {
John McCall413021a2010-07-30 06:26:29 +00001723 if (DS.getTypeSpecType() != DeclSpec::TST_error) {
1724 // We have a declaration or reference to an anonymous class.
1725 Diag(StartLoc, diag::err_anon_type_definition)
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001726 << DeclSpec::getSpecifierName(TagType, Policy);
John McCall413021a2010-07-30 06:26:29 +00001727 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001728
David Majnemer3252fd02013-12-05 01:36:53 +00001729 // If we are parsing a definition and stop at a base-clause, continue on
1730 // until the semicolon. Continuing from the comma will just trick us into
1731 // thinking we are seeing a variable declaration.
1732 if (TUK == Sema::TUK_Definition && Tok.is(tok::colon))
1733 SkipUntil(tok::semi, StopBeforeMatch);
1734 else
1735 SkipUntil(tok::comma, StopAtSemi);
Douglas Gregor556877c2008-04-13 21:30:24 +00001736 return;
1737 }
1738
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001739 // Create the tag portion of the class or class template.
John McCall48871652010-08-21 09:40:31 +00001740 DeclResult TagOrTempResult = true; // invalid
1741 TypeResult TypeResult = true; // invalid
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001742
Douglas Gregord6ab8742009-05-28 23:31:59 +00001743 bool Owned = false;
Richard Smithd9ba2242015-05-07 03:54:19 +00001744 Sema::SkipBodyInfo SkipBody;
John McCall06f6fe8d2009-09-04 01:14:41 +00001745 if (TemplateId) {
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001746 // Explicit specialization, class template partial specialization,
1747 // or explicit instantiation.
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00001748 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregor7f741122009-02-25 19:37:18 +00001749 TemplateId->NumArgs);
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001750 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
John McCallfaf5fb42010-08-26 23:41:50 +00001751 TUK == Sema::TUK_Declaration) {
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001752 // This is an explicit instantiation of a class template.
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001753 ProhibitAttributes(attrs);
1754
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001755 TagOrTempResult
Douglas Gregor0be31a22010-07-02 17:43:08 +00001756 = Actions.ActOnExplicitInstantiation(getCurScope(),
Douglas Gregor43e75172009-09-04 06:33:52 +00001757 TemplateInfo.ExternLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001758 TemplateInfo.TemplateLoc,
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001759 TagType,
Mike Stump11289f42009-09-09 15:08:12 +00001760 StartLoc,
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001761 SS,
John McCall3e56fd42010-08-23 07:28:44 +00001762 TemplateId->Template,
Mike Stump11289f42009-09-09 15:08:12 +00001763 TemplateId->TemplateNameLoc,
1764 TemplateId->LAngleLoc,
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001765 TemplateArgsPtr,
Mike Stump11289f42009-09-09 15:08:12 +00001766 TemplateId->RAngleLoc,
John McCall53fa7142010-12-24 02:08:15 +00001767 attrs.getList());
John McCallb7c5c272010-04-14 00:24:33 +00001768
1769 // Friend template-ids are treated as references unless
1770 // they have template headers, in which case they're ill-formed
1771 // (FIXME: "template <class T> friend class A<T>::B<int>;").
1772 // We diagnose this error in ActOnClassTemplateSpecialization.
John McCallfaf5fb42010-08-26 23:41:50 +00001773 } else if (TUK == Sema::TUK_Reference ||
1774 (TUK == Sema::TUK_Friend &&
John McCallb7c5c272010-04-14 00:24:33 +00001775 TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate)) {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001776 ProhibitAttributes(attrs);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00001777 TypeResult = Actions.ActOnTagTemplateIdType(TUK, TagType, StartLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00001778 TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00001779 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00001780 TemplateId->Template,
1781 TemplateId->TemplateNameLoc,
1782 TemplateId->LAngleLoc,
1783 TemplateArgsPtr,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00001784 TemplateId->RAngleLoc);
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001785 } else {
1786 // This is an explicit specialization or a class template
1787 // partial specialization.
1788 TemplateParameterLists FakedParamLists;
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001789 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1790 // This looks like an explicit instantiation, because we have
1791 // something like
1792 //
1793 // template class Foo<X>
1794 //
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001795 // but it actually has a definition. Most likely, this was
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001796 // meant to be an explicit specialization, but the user forgot
1797 // the '<>' after 'template'.
Richard Smith003c5e12013-11-08 19:03:29 +00001798 // It this is friend declaration however, since it cannot have a
1799 // template header, it is most likely that the user meant to
1800 // remove the 'template' keyword.
Larisse Voufob9bbaba2013-06-22 13:56:11 +00001801 assert((TUK == Sema::TUK_Definition || TUK == Sema::TUK_Friend) &&
Richard Smith003c5e12013-11-08 19:03:29 +00001802 "Expected a definition here");
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001803
Richard Smith003c5e12013-11-08 19:03:29 +00001804 if (TUK == Sema::TUK_Friend) {
1805 Diag(DS.getFriendSpecLoc(), diag::err_friend_explicit_instantiation);
Craig Topper161e4db2014-05-21 06:02:52 +00001806 TemplateParams = nullptr;
Richard Smith003c5e12013-11-08 19:03:29 +00001807 } else {
1808 SourceLocation LAngleLoc =
1809 PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
1810 Diag(TemplateId->TemplateNameLoc,
1811 diag::err_explicit_instantiation_with_definition)
1812 << SourceRange(TemplateInfo.TemplateLoc)
1813 << FixItHint::CreateInsertion(LAngleLoc, "<>");
1814
1815 // Create a fake template parameter list that contains only
1816 // "template<>", so that we treat this construct as a class
1817 // template specialization.
1818 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
Craig Topper96225a52015-12-24 23:58:25 +00001819 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
Hubert Tongf608c052016-04-29 18:05:37 +00001820 LAngleLoc, nullptr));
Richard Smith003c5e12013-11-08 19:03:29 +00001821 TemplateParams = &FakedParamLists;
1822 }
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001823 }
1824
1825 // Build the class template specialization.
Richard Smith4b55a9c2014-04-17 03:29:33 +00001826 TagOrTempResult = Actions.ActOnClassTemplateSpecialization(
1827 getCurScope(), TagType, TUK, StartLoc, DS.getModulePrivateSpecLoc(),
1828 *TemplateId, attrs.getList(),
Craig Topper161e4db2014-05-21 06:02:52 +00001829 MultiTemplateParamsArg(TemplateParams ? &(*TemplateParams)[0]
1830 : nullptr,
Richard Smithc7e6ff02015-05-18 20:36:47 +00001831 TemplateParams ? TemplateParams->size() : 0),
1832 &SkipBody);
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001833 }
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001834 } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
John McCallfaf5fb42010-08-26 23:41:50 +00001835 TUK == Sema::TUK_Declaration) {
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001836 // Explicit instantiation of a member of a class template
1837 // specialization, e.g.,
1838 //
1839 // template struct Outer<int>::Inner;
1840 //
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001841 ProhibitAttributes(attrs);
1842
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001843 TagOrTempResult
Douglas Gregor0be31a22010-07-02 17:43:08 +00001844 = Actions.ActOnExplicitInstantiation(getCurScope(),
Douglas Gregor43e75172009-09-04 06:33:52 +00001845 TemplateInfo.ExternLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001846 TemplateInfo.TemplateLoc,
1847 TagType, StartLoc, SS, Name,
John McCall53fa7142010-12-24 02:08:15 +00001848 NameLoc, attrs.getList());
John McCallace48cd2010-10-19 01:40:49 +00001849 } else if (TUK == Sema::TUK_Friend &&
1850 TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate) {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001851 ProhibitAttributes(attrs);
1852
John McCallace48cd2010-10-19 01:40:49 +00001853 TagOrTempResult =
1854 Actions.ActOnTemplatedFriendTag(getCurScope(), DS.getFriendSpecLoc(),
1855 TagType, StartLoc, SS,
John McCall53fa7142010-12-24 02:08:15 +00001856 Name, NameLoc, attrs.getList(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00001857 MultiTemplateParamsArg(
Craig Topper161e4db2014-05-21 06:02:52 +00001858 TemplateParams? &(*TemplateParams)[0]
1859 : nullptr,
John McCallace48cd2010-10-19 01:40:49 +00001860 TemplateParams? TemplateParams->size() : 0));
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001861 } else {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001862 if (TUK != Sema::TUK_Declaration && TUK != Sema::TUK_Definition)
1863 ProhibitAttributes(attrs);
Richard Smith003c5e12013-11-08 19:03:29 +00001864
Larisse Voufo725de3e2013-06-21 00:08:46 +00001865 if (TUK == Sema::TUK_Definition &&
1866 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1867 // If the declarator-id is not a template-id, issue a diagnostic and
1868 // recover by ignoring the 'template' keyword.
1869 Diag(Tok, diag::err_template_defn_explicit_instantiation)
1870 << 1 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
Craig Topper161e4db2014-05-21 06:02:52 +00001871 TemplateParams = nullptr;
Larisse Voufo725de3e2013-06-21 00:08:46 +00001872 }
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001873
John McCall7f41d982009-09-11 04:59:25 +00001874 bool IsDependent = false;
1875
John McCall32723e92010-10-19 18:40:57 +00001876 // Don't pass down template parameter lists if this is just a tag
1877 // reference. For example, we don't need the template parameters here:
1878 // template <class T> class A *makeA(T t);
1879 MultiTemplateParamsArg TParams;
1880 if (TUK != Sema::TUK_Reference && TemplateParams)
1881 TParams =
1882 MultiTemplateParamsArg(&(*TemplateParams)[0], TemplateParams->size());
1883
Nico Weber32a0fc72016-09-03 03:01:32 +00001884 stripTypeAttributesOffDeclSpec(attrs, DS, TUK);
David Majnemer936b4112015-04-19 07:53:29 +00001885
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001886 // Declaration or definition of a class type
Faisal Vali7db85c52017-12-31 00:06:40 +00001887 TagOrTempResult = Actions.ActOnTag(
1888 getCurScope(), TagType, TUK, StartLoc, SS, Name, NameLoc,
1889 attrs.getList(), AS, DS.getModulePrivateSpecLoc(), TParams, Owned,
1890 IsDependent, SourceLocation(), false, clang::TypeResult(),
1891 DSC == DeclSpecContext::DSC_type_specifier,
1892 DSC == DeclSpecContext::DSC_template_param ||
1893 DSC == DeclSpecContext::DSC_template_type_arg,
1894 &SkipBody);
John McCall7f41d982009-09-11 04:59:25 +00001895
1896 // If ActOnTag said the type was dependent, try again with the
1897 // less common call.
John McCallace48cd2010-10-19 01:40:49 +00001898 if (IsDependent) {
1899 assert(TUK == Sema::TUK_Reference || TUK == Sema::TUK_Friend);
Douglas Gregor0be31a22010-07-02 17:43:08 +00001900 TypeResult = Actions.ActOnDependentTag(getCurScope(), TagType, TUK,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001901 SS, Name, StartLoc, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +00001902 }
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001903 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001904
Douglas Gregor556877c2008-04-13 21:30:24 +00001905 // If there is a body, parse it and inform the actions module.
John McCallfaf5fb42010-08-26 23:41:50 +00001906 if (TUK == Sema::TUK_Definition) {
John McCall2d814c32009-12-19 21:48:58 +00001907 assert(Tok.is(tok::l_brace) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00001908 (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
Richard Smith89645bc2013-01-02 12:01:23 +00001909 isCXX11FinalKeyword());
Richard Smithd9ba2242015-05-07 03:54:19 +00001910 if (SkipBody.ShouldSkip)
Richard Smith65ebb4a2015-03-26 04:09:53 +00001911 SkipCXXMemberSpecification(StartLoc, AttrFixitLoc, TagType,
1912 TagOrTempResult.get());
1913 else if (getLangOpts().CPlusPlus)
Michael Han309af292013-01-07 16:57:11 +00001914 ParseCXXMemberSpecification(StartLoc, AttrFixitLoc, attrs, TagType,
1915 TagOrTempResult.get());
Bruno Cardoso Lopesdf0ee342017-07-01 00:06:47 +00001916 else {
1917 Decl *D =
1918 SkipBody.CheckSameAsPrevious ? SkipBody.New : TagOrTempResult.get();
1919 // Parse the definition body.
1920 ParseStructUnionBody(StartLoc, TagType, D);
1921 if (SkipBody.CheckSameAsPrevious &&
1922 !Actions.ActOnDuplicateDefinition(DS, TagOrTempResult.get(),
1923 SkipBody)) {
1924 DS.SetTypeSpecError();
1925 return;
1926 }
1927 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001928 }
1929
Erich Keane2fe684b2017-02-28 20:44:39 +00001930 if (!TagOrTempResult.isInvalid())
Hiroshi Inoue939d9322017-06-30 05:40:31 +00001931 // Delayed processing of attributes.
Erich Keane2fe684b2017-02-28 20:44:39 +00001932 Actions.ProcessDeclAttributeDelayed(TagOrTempResult.get(), attrs.getList());
1933
Craig Topper161e4db2014-05-21 06:02:52 +00001934 const char *PrevSpec = nullptr;
John McCallba7bf592010-08-24 05:47:05 +00001935 unsigned DiagID;
1936 bool Result;
John McCall7f41d982009-09-11 04:59:25 +00001937 if (!TypeResult.isInvalid()) {
Abramo Bagnara9875a3c2011-03-16 20:16:18 +00001938 Result = DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
1939 NameLoc.isValid() ? NameLoc : StartLoc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001940 PrevSpec, DiagID, TypeResult.get(), Policy);
John McCall7f41d982009-09-11 04:59:25 +00001941 } else if (!TagOrTempResult.isInvalid()) {
Abramo Bagnara9875a3c2011-03-16 20:16:18 +00001942 Result = DS.SetTypeSpecType(TagType, StartLoc,
1943 NameLoc.isValid() ? NameLoc : StartLoc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001944 PrevSpec, DiagID, TagOrTempResult.get(), Owned,
1945 Policy);
John McCall7f41d982009-09-11 04:59:25 +00001946 } else {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001947 DS.SetTypeSpecError();
Anders Carlssonf83c9fa2009-05-11 22:27:47 +00001948 return;
1949 }
Mike Stump11289f42009-09-09 15:08:12 +00001950
John McCallba7bf592010-08-24 05:47:05 +00001951 if (Result)
John McCall49bfce42009-08-03 20:12:06 +00001952 Diag(StartLoc, DiagID) << PrevSpec;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001953
Chris Lattnercf251412010-02-02 01:23:29 +00001954 // At this point, we've successfully parsed a class-specifier in 'definition'
1955 // form (e.g. "struct foo { int x; }". While we could just return here, we're
1956 // going to look at what comes after it to improve error recovery. If an
1957 // impossible token occurs next, we assume that the programmer forgot a ; at
1958 // the end of the declaration and recover that way.
1959 //
Richard Smith369b9f92012-06-25 21:37:02 +00001960 // Also enforce C++ [temp]p3:
1961 // In a template-declaration which defines a class, no declarator
1962 // is permitted.
Richard Smith843f18f2014-08-13 02:13:15 +00001963 //
1964 // After a type-specifier, we don't expect a semicolon. This only happens in
1965 // C, since definitions are not permitted in this context in C++.
Joao Matose9a3ed42012-08-31 22:18:20 +00001966 if (TUK == Sema::TUK_Definition &&
Richard Smith843f18f2014-08-13 02:13:15 +00001967 (getLangOpts().CPlusPlus || !isTypeSpecifier(DSC)) &&
Joao Matose9a3ed42012-08-31 22:18:20 +00001968 (TemplateInfo.Kind || !isValidAfterTypeSpecifier(false))) {
Argyrios Kyrtzidise6f69132012-12-17 20:10:43 +00001969 if (Tok.isNot(tok::semi)) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001970 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
Alp Toker383d2c42014-01-01 03:08:43 +00001971 ExpectAndConsume(tok::semi, diag::err_expected_after,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001972 DeclSpec::getSpecifierName(TagType, PPol));
Argyrios Kyrtzidise6f69132012-12-17 20:10:43 +00001973 // Push this token back into the preprocessor and change our current token
1974 // to ';' so that the rest of the code recovers as though there were an
1975 // ';' after the definition.
1976 PP.EnterToken(Tok);
1977 Tok.setKind(tok::semi);
1978 }
Chris Lattnercf251412010-02-02 01:23:29 +00001979 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001980}
1981
Mike Stump11289f42009-09-09 15:08:12 +00001982/// ParseBaseClause - Parse the base-clause of a C++ class [C++ class.derived].
Douglas Gregor556877c2008-04-13 21:30:24 +00001983///
1984/// base-clause : [C++ class.derived]
1985/// ':' base-specifier-list
1986/// base-specifier-list:
1987/// base-specifier '...'[opt]
1988/// base-specifier-list ',' base-specifier '...'[opt]
John McCall48871652010-08-21 09:40:31 +00001989void Parser::ParseBaseClause(Decl *ClassDecl) {
Douglas Gregor556877c2008-04-13 21:30:24 +00001990 assert(Tok.is(tok::colon) && "Not a base clause");
1991 ConsumeToken();
1992
Douglas Gregor29a92472008-10-22 17:49:05 +00001993 // Build up an array of parsed base specifiers.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001994 SmallVector<CXXBaseSpecifier *, 8> BaseInfo;
Douglas Gregor29a92472008-10-22 17:49:05 +00001995
Douglas Gregor556877c2008-04-13 21:30:24 +00001996 while (true) {
1997 // Parse a base-specifier.
Douglas Gregor29a92472008-10-22 17:49:05 +00001998 BaseResult Result = ParseBaseSpecifier(ClassDecl);
Douglas Gregorf8298252009-01-26 22:44:13 +00001999 if (Result.isInvalid()) {
Douglas Gregor556877c2008-04-13 21:30:24 +00002000 // Skip the rest of this base specifier, up until the comma or
2001 // opening brace.
Alexey Bataevee6507d2013-11-18 08:17:37 +00002002 SkipUntil(tok::comma, tok::l_brace, StopAtSemi | StopBeforeMatch);
Douglas Gregor29a92472008-10-22 17:49:05 +00002003 } else {
2004 // Add this to our array of base specifiers.
Douglas Gregorf8298252009-01-26 22:44:13 +00002005 BaseInfo.push_back(Result.get());
Douglas Gregor556877c2008-04-13 21:30:24 +00002006 }
2007
2008 // If the next token is a comma, consume it and keep reading
2009 // base-specifiers.
Alp Toker97650562014-01-10 11:19:30 +00002010 if (!TryConsumeToken(tok::comma))
2011 break;
Douglas Gregor556877c2008-04-13 21:30:24 +00002012 }
Douglas Gregor29a92472008-10-22 17:49:05 +00002013
2014 // Attach the base specifiers
Craig Topperaa700cb2015-12-27 21:55:19 +00002015 Actions.ActOnBaseSpecifiers(ClassDecl, BaseInfo);
Douglas Gregor556877c2008-04-13 21:30:24 +00002016}
2017
2018/// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is
2019/// one entry in the base class list of a class specifier, for example:
2020/// class foo : public bar, virtual private baz {
2021/// 'public bar' and 'virtual private baz' are each base-specifiers.
2022///
2023/// base-specifier: [C++ class.derived]
Richard Smith4c96e992013-02-19 23:47:15 +00002024/// attribute-specifier-seq[opt] base-type-specifier
2025/// attribute-specifier-seq[opt] 'virtual' access-specifier[opt]
2026/// base-type-specifier
2027/// attribute-specifier-seq[opt] access-specifier 'virtual'[opt]
2028/// base-type-specifier
Craig Topper9ad7e262014-10-31 06:57:07 +00002029BaseResult Parser::ParseBaseSpecifier(Decl *ClassDecl) {
Douglas Gregor556877c2008-04-13 21:30:24 +00002030 bool IsVirtual = false;
2031 SourceLocation StartLoc = Tok.getLocation();
2032
Richard Smith4c96e992013-02-19 23:47:15 +00002033 ParsedAttributesWithRange Attributes(AttrFactory);
2034 MaybeParseCXX11Attributes(Attributes);
2035
Douglas Gregor556877c2008-04-13 21:30:24 +00002036 // Parse the 'virtual' keyword.
Alp Toker97650562014-01-10 11:19:30 +00002037 if (TryConsumeToken(tok::kw_virtual))
Douglas Gregor556877c2008-04-13 21:30:24 +00002038 IsVirtual = true;
Douglas Gregor556877c2008-04-13 21:30:24 +00002039
Richard Smith4c96e992013-02-19 23:47:15 +00002040 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2041
Douglas Gregor556877c2008-04-13 21:30:24 +00002042 // Parse an (optional) access specifier.
2043 AccessSpecifier Access = getAccessSpecifierIfPresent();
John McCall553c0792010-01-23 00:46:32 +00002044 if (Access != AS_none)
Douglas Gregor556877c2008-04-13 21:30:24 +00002045 ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +00002046
Richard Smith4c96e992013-02-19 23:47:15 +00002047 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2048
Douglas Gregor556877c2008-04-13 21:30:24 +00002049 // Parse the 'virtual' keyword (again!), in case it came after the
2050 // access specifier.
2051 if (Tok.is(tok::kw_virtual)) {
2052 SourceLocation VirtualLoc = ConsumeToken();
2053 if (IsVirtual) {
2054 // Complain about duplicate 'virtual'
Chris Lattner6d29c102008-11-18 07:48:38 +00002055 Diag(VirtualLoc, diag::err_dup_virtual)
Douglas Gregora771f462010-03-31 17:46:05 +00002056 << FixItHint::CreateRemoval(VirtualLoc);
Douglas Gregor556877c2008-04-13 21:30:24 +00002057 }
2058
2059 IsVirtual = true;
2060 }
2061
Richard Smith4c96e992013-02-19 23:47:15 +00002062 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2063
Douglas Gregor831c93f2008-11-05 20:51:48 +00002064 // Parse the class-name.
David Majnemer51fd8a02015-07-22 23:46:18 +00002065
2066 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
2067 // implementation for VS2013 uses _Atomic as an identifier for one of the
2068 // classes in <atomic>. Treat '_Atomic' to be an identifier when we are
2069 // parsing the class-name for a base specifier.
2070 if (getLangOpts().MSVCCompat && Tok.is(tok::kw__Atomic) &&
2071 NextToken().is(tok::less))
2072 Tok.setKind(tok::identifier);
2073
Douglas Gregord54dfb82009-02-25 23:52:28 +00002074 SourceLocation EndLocation;
David Blaikie1cd50022011-10-25 17:10:12 +00002075 SourceLocation BaseLoc;
2076 TypeResult BaseType = ParseBaseTypeSpecifier(BaseLoc, EndLocation);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00002077 if (BaseType.isInvalid())
Douglas Gregor831c93f2008-11-05 20:51:48 +00002078 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002079
Douglas Gregor752a5952011-01-03 22:36:02 +00002080 // Parse the optional ellipsis (for a pack expansion). The ellipsis is
2081 // actually part of the base-specifier-list grammar productions, but we
2082 // parse it here for convenience.
2083 SourceLocation EllipsisLoc;
Alp Toker97650562014-01-10 11:19:30 +00002084 TryConsumeToken(tok::ellipsis, EllipsisLoc);
2085
Mike Stump11289f42009-09-09 15:08:12 +00002086 // Find the complete source range for the base-specifier.
Douglas Gregord54dfb82009-02-25 23:52:28 +00002087 SourceRange Range(StartLoc, EndLocation);
Mike Stump11289f42009-09-09 15:08:12 +00002088
Douglas Gregor556877c2008-04-13 21:30:24 +00002089 // Notify semantic analysis that we have parsed a complete
2090 // base-specifier.
Richard Smith4c96e992013-02-19 23:47:15 +00002091 return Actions.ActOnBaseSpecifier(ClassDecl, Range, Attributes, IsVirtual,
2092 Access, BaseType.get(), BaseLoc,
2093 EllipsisLoc);
Douglas Gregor556877c2008-04-13 21:30:24 +00002094}
2095
2096/// getAccessSpecifierIfPresent - Determine whether the next token is
2097/// a C++ access-specifier.
2098///
2099/// access-specifier: [C++ class.derived]
2100/// 'private'
2101/// 'protected'
2102/// 'public'
Mike Stump11289f42009-09-09 15:08:12 +00002103AccessSpecifier Parser::getAccessSpecifierIfPresent() const {
Douglas Gregor556877c2008-04-13 21:30:24 +00002104 switch (Tok.getKind()) {
2105 default: return AS_none;
2106 case tok::kw_private: return AS_private;
2107 case tok::kw_protected: return AS_protected;
2108 case tok::kw_public: return AS_public;
2109 }
2110}
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002111
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002112/// If the given declarator has any parts for which parsing has to be
Richard Smith0b3a4622014-11-13 20:01:57 +00002113/// delayed, e.g., default arguments or an exception-specification, create a
2114/// late-parsed method declaration record to handle the parsing at the end of
2115/// the class definition.
Douglas Gregor433e0532012-04-16 18:27:27 +00002116void Parser::HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
2117 Decl *ThisDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00002118 DeclaratorChunk::FunctionTypeInfo &FTI
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002119 = DeclaratorInfo.getFunctionTypeInfo();
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002120 // If there was a late-parsed exception-specification, we'll need a
2121 // late parse
2122 bool NeedLateParse = FTI.getExceptionSpecType() == EST_Unparsed;
Douglas Gregor433e0532012-04-16 18:27:27 +00002123
Nathan Sidwell5bb231c2015-02-19 14:03:22 +00002124 if (!NeedLateParse) {
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002125 // Look ahead to see if there are any default args
Nathan Sidwell5bb231c2015-02-19 14:03:22 +00002126 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx) {
2127 auto Param = cast<ParmVarDecl>(FTI.Params[ParamIdx].Param);
2128 if (Param->hasUnparsedDefaultArg()) {
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002129 NeedLateParse = true;
2130 break;
2131 }
Nathan Sidwell5bb231c2015-02-19 14:03:22 +00002132 }
2133 }
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002134
2135 if (NeedLateParse) {
Richard Smith0b3a4622014-11-13 20:01:57 +00002136 // Push this method onto the stack of late-parsed method
2137 // declarations.
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002138 auto LateMethod = new LateParsedMethodDeclaration(this, ThisDecl);
Richard Smith0b3a4622014-11-13 20:01:57 +00002139 getCurrentClass().LateParsedDeclarations.push_back(LateMethod);
2140 LateMethod->TemplateScope = getCurScope()->isTemplateParamScope();
2141
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002142 // Stash the exception-specification tokens in the late-pased method.
Richard Smith0b3a4622014-11-13 20:01:57 +00002143 LateMethod->ExceptionSpecTokens = FTI.ExceptionSpecTokens;
Hans Wennborgdcfba332015-10-06 23:40:43 +00002144 FTI.ExceptionSpecTokens = nullptr;
Richard Smith0b3a4622014-11-13 20:01:57 +00002145
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002146 // Push tokens for each parameter. Those that do not have
2147 // defaults will be NULL.
Richard Smith0b3a4622014-11-13 20:01:57 +00002148 LateMethod->DefaultArgs.reserve(FTI.NumParams);
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002149 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx)
Alp Tokerc5350722014-02-26 22:27:52 +00002150 LateMethod->DefaultArgs.push_back(LateParsedDefaultArgument(
Malcolm Parsonsca9d8342016-11-17 21:00:09 +00002151 FTI.Params[ParamIdx].Param,
2152 std::move(FTI.Params[ParamIdx].DefaultArgTokens)));
Eli Friedman3af2a772009-07-22 21:45:50 +00002153 }
2154}
2155
Richard Smith89645bc2013-01-02 12:01:23 +00002156/// isCXX11VirtSpecifier - Determine whether the given token is a C++11
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002157/// virt-specifier.
2158///
2159/// virt-specifier:
2160/// override
2161/// final
Andrey Bokhanko276055b2016-07-29 10:42:48 +00002162/// __final
Richard Smith89645bc2013-01-02 12:01:23 +00002163VirtSpecifiers::Specifier Parser::isCXX11VirtSpecifier(const Token &Tok) const {
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002164 if (!getLangOpts().CPlusPlus || Tok.isNot(tok::identifier))
Anders Carlsson4b63d0e2011-01-22 16:56:46 +00002165 return VirtSpecifiers::VS_None;
2166
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002167 IdentifierInfo *II = Tok.getIdentifierInfo();
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002168
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002169 // Initialize the contextual keywords.
2170 if (!Ident_final) {
2171 Ident_final = &PP.getIdentifierTable().get("final");
Andrey Bokhanko276055b2016-07-29 10:42:48 +00002172 if (getLangOpts().GNUKeywords)
2173 Ident_GNU_final = &PP.getIdentifierTable().get("__final");
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002174 if (getLangOpts().MicrosoftExt)
2175 Ident_sealed = &PP.getIdentifierTable().get("sealed");
2176 Ident_override = &PP.getIdentifierTable().get("override");
Anders Carlsson56104902011-01-17 03:05:47 +00002177 }
2178
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002179 if (II == Ident_override)
2180 return VirtSpecifiers::VS_Override;
2181
2182 if (II == Ident_sealed)
2183 return VirtSpecifiers::VS_Sealed;
2184
2185 if (II == Ident_final)
2186 return VirtSpecifiers::VS_Final;
2187
Andrey Bokhanko276055b2016-07-29 10:42:48 +00002188 if (II == Ident_GNU_final)
2189 return VirtSpecifiers::VS_GNU_Final;
2190
Anders Carlsson56104902011-01-17 03:05:47 +00002191 return VirtSpecifiers::VS_None;
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002192}
2193
Richard Smith89645bc2013-01-02 12:01:23 +00002194/// ParseOptionalCXX11VirtSpecifierSeq - Parse a virt-specifier-seq.
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002195///
2196/// virt-specifier-seq:
2197/// virt-specifier
2198/// virt-specifier-seq virt-specifier
Richard Smith89645bc2013-01-02 12:01:23 +00002199void Parser::ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS,
Richard Smith3d1a94c2014-08-12 00:22:39 +00002200 bool IsInterface,
2201 SourceLocation FriendLoc) {
Anders Carlsson56104902011-01-17 03:05:47 +00002202 while (true) {
Richard Smith89645bc2013-01-02 12:01:23 +00002203 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
Anders Carlsson56104902011-01-17 03:05:47 +00002204 if (Specifier == VirtSpecifiers::VS_None)
2205 return;
2206
Richard Smith3d1a94c2014-08-12 00:22:39 +00002207 if (FriendLoc.isValid()) {
2208 Diag(Tok.getLocation(), diag::err_friend_decl_spec)
2209 << VirtSpecifiers::getSpecifierName(Specifier)
2210 << FixItHint::CreateRemoval(Tok.getLocation())
2211 << SourceRange(FriendLoc, FriendLoc);
2212 ConsumeToken();
2213 continue;
2214 }
2215
Anders Carlsson56104902011-01-17 03:05:47 +00002216 // C++ [class.mem]p8:
2217 // A virt-specifier-seq shall contain at most one of each virt-specifier.
Craig Topper161e4db2014-05-21 06:02:52 +00002218 const char *PrevSpec = nullptr;
Anders Carlssonf2ca3892011-01-22 15:58:16 +00002219 if (VS.SetSpecifier(Specifier, Tok.getLocation(), PrevSpec))
Anders Carlsson56104902011-01-17 03:05:47 +00002220 Diag(Tok.getLocation(), diag::err_duplicate_virt_specifier)
2221 << PrevSpec
2222 << FixItHint::CreateRemoval(Tok.getLocation());
2223
David Majnemera5433082013-10-18 00:33:31 +00002224 if (IsInterface && (Specifier == VirtSpecifiers::VS_Final ||
2225 Specifier == VirtSpecifiers::VS_Sealed)) {
John McCalldb632ac2012-09-25 07:32:39 +00002226 Diag(Tok.getLocation(), diag::err_override_control_interface)
2227 << VirtSpecifiers::getSpecifierName(Specifier);
David Majnemera5433082013-10-18 00:33:31 +00002228 } else if (Specifier == VirtSpecifiers::VS_Sealed) {
2229 Diag(Tok.getLocation(), diag::ext_ms_sealed_keyword);
Andrey Bokhanko276055b2016-07-29 10:42:48 +00002230 } else if (Specifier == VirtSpecifiers::VS_GNU_Final) {
2231 Diag(Tok.getLocation(), diag::ext_warn_gnu_final);
John McCalldb632ac2012-09-25 07:32:39 +00002232 } else {
David Majnemera5433082013-10-18 00:33:31 +00002233 Diag(Tok.getLocation(),
2234 getLangOpts().CPlusPlus11
2235 ? diag::warn_cxx98_compat_override_control_keyword
2236 : diag::ext_override_control_keyword)
2237 << VirtSpecifiers::getSpecifierName(Specifier);
John McCalldb632ac2012-09-25 07:32:39 +00002238 }
Anders Carlsson56104902011-01-17 03:05:47 +00002239 ConsumeToken();
2240 }
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002241}
2242
Richard Smith89645bc2013-01-02 12:01:23 +00002243/// isCXX11FinalKeyword - Determine whether the next token is a C++11
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002244/// 'final' or Microsoft 'sealed' contextual keyword.
Richard Smith89645bc2013-01-02 12:01:23 +00002245bool Parser::isCXX11FinalKeyword() const {
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002246 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
2247 return Specifier == VirtSpecifiers::VS_Final ||
Andrey Bokhanko276055b2016-07-29 10:42:48 +00002248 Specifier == VirtSpecifiers::VS_GNU_Final ||
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002249 Specifier == VirtSpecifiers::VS_Sealed;
Anders Carlsson4b63d0e2011-01-22 16:56:46 +00002250}
2251
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002252/// Parse a C++ member-declarator up to, but not including, the optional
Richard Smith72553fc2014-01-23 23:53:27 +00002253/// brace-or-equal-initializer or pure-specifier.
Nico Weberd89e6f72015-01-16 19:34:13 +00002254bool Parser::ParseCXXMemberDeclaratorBeforeInitializer(
Richard Smith72553fc2014-01-23 23:53:27 +00002255 Declarator &DeclaratorInfo, VirtSpecifiers &VS, ExprResult &BitfieldSize,
2256 LateParsedAttrList &LateParsedAttrs) {
2257 // member-declarator:
2258 // declarator pure-specifier[opt]
2259 // declarator brace-or-equal-initializer[opt]
2260 // identifier[opt] ':' constant-expression
Serge Pavlov458ea762014-07-16 05:16:52 +00002261 if (Tok.isNot(tok::colon))
Richard Smith72553fc2014-01-23 23:53:27 +00002262 ParseDeclarator(DeclaratorInfo);
Richard Smith3d1a94c2014-08-12 00:22:39 +00002263 else
2264 DeclaratorInfo.SetIdentifier(nullptr, Tok.getLocation());
Richard Smith72553fc2014-01-23 23:53:27 +00002265
2266 if (!DeclaratorInfo.isFunctionDeclarator() && TryConsumeToken(tok::colon)) {
Richard Smith3d1a94c2014-08-12 00:22:39 +00002267 assert(DeclaratorInfo.isPastIdentifier() &&
2268 "don't know where identifier would go yet?");
Richard Smith72553fc2014-01-23 23:53:27 +00002269 BitfieldSize = ParseConstantExpression();
2270 if (BitfieldSize.isInvalid())
2271 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002272 } else {
Richard Smith3d1a94c2014-08-12 00:22:39 +00002273 ParseOptionalCXX11VirtSpecifierSeq(
2274 VS, getCurrentClass().IsInterface,
2275 DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002276 if (!VS.isUnset())
2277 MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo, VS);
2278 }
Richard Smith72553fc2014-01-23 23:53:27 +00002279
2280 // If a simple-asm-expr is present, parse it.
2281 if (Tok.is(tok::kw_asm)) {
2282 SourceLocation Loc;
2283 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
2284 if (AsmLabel.isInvalid())
2285 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2286
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002287 DeclaratorInfo.setAsmLabel(AsmLabel.get());
Richard Smith72553fc2014-01-23 23:53:27 +00002288 DeclaratorInfo.SetRangeEnd(Loc);
2289 }
2290
2291 // If attributes exist after the declarator, but before an '{', parse them.
2292 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
Richard Smith4b5a9492014-01-24 22:34:35 +00002293
2294 // For compatibility with code written to older Clang, also accept a
2295 // virt-specifier *after* the GNU attributes.
Aaron Ballman5d153e32014-08-04 17:03:51 +00002296 if (BitfieldSize.isUnset() && VS.isUnset()) {
Richard Smith3d1a94c2014-08-12 00:22:39 +00002297 ParseOptionalCXX11VirtSpecifierSeq(
2298 VS, getCurrentClass().IsInterface,
2299 DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
Aaron Ballman5d153e32014-08-04 17:03:51 +00002300 if (!VS.isUnset()) {
2301 // If we saw any GNU-style attributes that are known to GCC followed by a
2302 // virt-specifier, issue a GCC-compat warning.
2303 const AttributeList *Attr = DeclaratorInfo.getAttributes();
2304 while (Attr) {
2305 if (Attr->isKnownToGCC() && !Attr->isCXX11Attribute())
2306 Diag(Attr->getLoc(), diag::warn_gcc_attribute_location);
2307 Attr = Attr->getNext();
2308 }
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002309 MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo, VS);
Aaron Ballman5d153e32014-08-04 17:03:51 +00002310 }
2311 }
Nico Weberd89e6f72015-01-16 19:34:13 +00002312
2313 // If this has neither a name nor a bit width, something has gone seriously
2314 // wrong. Skip until the semi-colon or }.
2315 if (!DeclaratorInfo.hasName() && BitfieldSize.isUnset()) {
2316 // If so, skip until the semi-colon or a }.
2317 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2318 return true;
2319 }
2320 return false;
Richard Smith72553fc2014-01-23 23:53:27 +00002321}
2322
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002323/// Look for declaration specifiers possibly occurring after C++11
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002324/// virt-specifier-seq and diagnose them.
2325void Parser::MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(
2326 Declarator &D,
2327 VirtSpecifiers &VS) {
2328 DeclSpec DS(AttrFactory);
2329
2330 // GNU-style and C++11 attributes are not allowed here, but they will be
2331 // handled by the caller. Diagnose everything else.
Alex Lorenz8f4d3992017-02-13 23:19:40 +00002332 ParseTypeQualifierListOpt(
2333 DS, AR_NoAttributesParsed, false,
2334 /*IdentifierRequired=*/false, llvm::function_ref<void()>([&]() {
2335 Actions.CodeCompleteFunctionQualifiers(DS, D, &VS);
2336 }));
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002337 D.ExtendWithDeclSpec(DS);
2338
2339 if (D.isFunctionDeclarator()) {
Ehsan Akhgaric07d1e22015-03-25 00:53:33 +00002340 auto &Function = D.getFunctionTypeInfo();
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002341 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
2342 auto DeclSpecCheck = [&] (DeclSpec::TQ TypeQual,
2343 const char *FixItName,
2344 SourceLocation SpecLoc,
2345 unsigned* QualifierLoc) {
2346 FixItHint Insertion;
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002347 if (DS.getTypeQualifiers() & TypeQual) {
2348 if (!(Function.TypeQuals & TypeQual)) {
2349 std::string Name(FixItName);
2350 Name += " ";
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00002351 Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), Name);
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002352 Function.TypeQuals |= TypeQual;
2353 *QualifierLoc = SpecLoc.getRawEncoding();
2354 }
2355 Diag(SpecLoc, diag::err_declspec_after_virtspec)
2356 << FixItName
2357 << VirtSpecifiers::getSpecifierName(VS.getLastSpecifier())
2358 << FixItHint::CreateRemoval(SpecLoc)
2359 << Insertion;
2360 }
2361 };
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002362 DeclSpecCheck(DeclSpec::TQ_const, "const", DS.getConstSpecLoc(),
2363 &Function.ConstQualifierLoc);
2364 DeclSpecCheck(DeclSpec::TQ_volatile, "volatile", DS.getVolatileSpecLoc(),
2365 &Function.VolatileQualifierLoc);
2366 DeclSpecCheck(DeclSpec::TQ_restrict, "restrict", DS.getRestrictSpecLoc(),
2367 &Function.RestrictQualifierLoc);
2368 }
Ehsan Akhgaric07d1e22015-03-25 00:53:33 +00002369
2370 // Parse ref-qualifiers.
2371 bool RefQualifierIsLValueRef = true;
2372 SourceLocation RefQualifierLoc;
2373 if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc)) {
2374 const char *Name = (RefQualifierIsLValueRef ? "& " : "&& ");
2375 FixItHint Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), Name);
2376 Function.RefQualifierIsLValueRef = RefQualifierIsLValueRef;
2377 Function.RefQualifierLoc = RefQualifierLoc.getRawEncoding();
2378
2379 Diag(RefQualifierLoc, diag::err_declspec_after_virtspec)
2380 << (RefQualifierIsLValueRef ? "&" : "&&")
2381 << VirtSpecifiers::getSpecifierName(VS.getLastSpecifier())
2382 << FixItHint::CreateRemoval(RefQualifierLoc)
2383 << Insertion;
2384 D.SetRangeEnd(RefQualifierLoc);
2385 }
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002386 }
2387}
2388
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002389/// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration.
2390///
2391/// member-declaration:
2392/// decl-specifier-seq[opt] member-declarator-list[opt] ';'
2393/// function-definition ';'[opt]
2394/// ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO]
2395/// using-declaration [TODO]
Anders Carlssonf24fcff62009-03-11 16:27:10 +00002396/// [C++0x] static_assert-declaration
Anders Carlssondfbbdf62009-03-26 00:52:18 +00002397/// template-declaration
Chris Lattnerd19c1c02008-12-18 01:12:00 +00002398/// [GNU] '__extension__' member-declaration
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002399///
2400/// member-declarator-list:
2401/// member-declarator
2402/// member-declarator-list ',' member-declarator
2403///
2404/// member-declarator:
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002405/// declarator virt-specifier-seq[opt] pure-specifier[opt]
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002406/// declarator constant-initializer[opt]
Richard Smith938f40b2011-06-11 17:19:42 +00002407/// [C++11] declarator brace-or-equal-initializer[opt]
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002408/// identifier[opt] ':' constant-expression
2409///
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002410/// virt-specifier-seq:
2411/// virt-specifier
2412/// virt-specifier-seq virt-specifier
2413///
2414/// virt-specifier:
2415/// override
2416/// final
David Majnemera5433082013-10-18 00:33:31 +00002417/// [MS] sealed
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002418///
Sebastian Redl42e92c42009-04-12 17:16:29 +00002419/// pure-specifier:
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002420/// '= 0'
2421///
2422/// constant-initializer:
2423/// '=' constant-expression
2424///
Alexey Bataev05c25d62015-07-31 08:42:25 +00002425Parser::DeclGroupPtrTy
2426Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS,
2427 AttributeList *AccessAttrs,
John McCall796c2a52010-07-16 08:13:16 +00002428 const ParsedTemplateInfo &TemplateInfo,
2429 ParsingDeclRAIIObject *TemplateDiags) {
Douglas Gregor23c84762011-04-14 17:21:19 +00002430 if (Tok.is(tok::at)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002431 if (getLangOpts().ObjC1 && NextToken().isObjCAtKeyword(tok::objc_defs))
Douglas Gregor23c84762011-04-14 17:21:19 +00002432 Diag(Tok, diag::err_at_defs_cxx);
2433 else
2434 Diag(Tok, diag::err_at_in_class);
Richard Smithda35e962013-11-09 04:52:51 +00002435
Douglas Gregor23c84762011-04-14 17:21:19 +00002436 ConsumeToken();
Alexey Bataevee6507d2013-11-18 08:17:37 +00002437 SkipUntil(tok::r_brace, StopAtSemi);
David Blaikie0403cb12016-01-15 23:43:25 +00002438 return nullptr;
Douglas Gregor23c84762011-04-14 17:21:19 +00002439 }
Richard Smithda35e962013-11-09 04:52:51 +00002440
Serge Pavlov458ea762014-07-16 05:16:52 +00002441 // Turn on colon protection early, while parsing declspec, although there is
2442 // nothing to protect there. It prevents from false errors if error recovery
2443 // incorrectly determines where the declspec ends, as in the example:
2444 // struct A { enum class B { C }; };
2445 // const int C = 4;
2446 // struct D { A::B : C; };
2447 ColonProtectionRAIIObject X(*this);
2448
John McCalla0097262009-12-11 02:10:03 +00002449 // Access declarations.
Richard Smith45855df2012-05-09 08:23:23 +00002450 bool MalformedTypeSpec = false;
John McCalla0097262009-12-11 02:10:03 +00002451 if (!TemplateInfo.Kind &&
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002452 Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw___super)) {
Richard Smith45855df2012-05-09 08:23:23 +00002453 if (TryAnnotateCXXScopeToken())
2454 MalformedTypeSpec = true;
2455
2456 bool isAccessDecl;
2457 if (Tok.isNot(tok::annot_cxxscope))
2458 isAccessDecl = false;
2459 else if (NextToken().is(tok::identifier))
John McCalla0097262009-12-11 02:10:03 +00002460 isAccessDecl = GetLookAheadToken(2).is(tok::semi);
2461 else
2462 isAccessDecl = NextToken().is(tok::kw_operator);
2463
2464 if (isAccessDecl) {
2465 // Collect the scope specifier token we annotated earlier.
2466 CXXScopeSpec SS;
David Blaikieefdccaa2016-01-15 23:43:34 +00002467 ParseOptionalCXXScopeSpecifier(SS, nullptr,
Douglas Gregordf593fb2011-11-07 17:33:42 +00002468 /*EnteringContext=*/false);
John McCalla0097262009-12-11 02:10:03 +00002469
Nico Weberef03e702014-09-10 00:59:37 +00002470 if (SS.isInvalid()) {
2471 SkipUntil(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002472 return nullptr;
Nico Weberef03e702014-09-10 00:59:37 +00002473 }
2474
John McCalla0097262009-12-11 02:10:03 +00002475 // Try to parse an unqualified-id.
Abramo Bagnara7945c982012-01-27 09:46:47 +00002476 SourceLocation TemplateKWLoc;
John McCalla0097262009-12-11 02:10:03 +00002477 UnqualifiedId Name;
Richard Smith35845152017-02-07 01:37:30 +00002478 if (ParseUnqualifiedId(SS, false, true, true, false, nullptr,
Richard Smithc08b6932018-04-27 02:00:13 +00002479 &TemplateKWLoc, Name)) {
John McCalla0097262009-12-11 02:10:03 +00002480 SkipUntil(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002481 return nullptr;
John McCalla0097262009-12-11 02:10:03 +00002482 }
2483
2484 // TODO: recover from mistakenly-qualified operator declarations.
Alp Toker383d2c42014-01-01 03:08:43 +00002485 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
2486 "access declaration")) {
2487 SkipUntil(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002488 return nullptr;
Alp Toker383d2c42014-01-01 03:08:43 +00002489 }
John McCalla0097262009-12-11 02:10:03 +00002490
Richard Smithc08b6932018-04-27 02:00:13 +00002491 // FIXME: We should do something with the 'template' keyword here.
Alexey Bataev05c25d62015-07-31 08:42:25 +00002492 return DeclGroupPtrTy::make(DeclGroupRef(Actions.ActOnUsingDeclaration(
Richard Smith151c4562016-12-20 21:35:28 +00002493 getCurScope(), AS, /*UsingLoc*/ SourceLocation(),
2494 /*TypenameLoc*/ SourceLocation(), SS, Name,
2495 /*EllipsisLoc*/ SourceLocation(), /*AttrList*/ nullptr)));
John McCalla0097262009-12-11 02:10:03 +00002496 }
2497 }
2498
Aaron Ballmane7c544d2014-08-04 20:28:35 +00002499 // static_assert-declaration. A templated static_assert declaration is
2500 // diagnosed in Parser::ParseSingleDeclarationAfterTemplate.
2501 if (!TemplateInfo.Kind &&
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002502 Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert)) {
Chris Lattner49836b42009-04-02 04:16:50 +00002503 SourceLocation DeclEnd;
Alexey Bataev05c25d62015-07-31 08:42:25 +00002504 return DeclGroupPtrTy::make(
2505 DeclGroupRef(ParseStaticAssertDeclaration(DeclEnd)));
Chris Lattner5bbb3c82009-03-29 16:50:03 +00002506 }
Mike Stump11289f42009-09-09 15:08:12 +00002507
Chris Lattner5bbb3c82009-03-29 16:50:03 +00002508 if (Tok.is(tok::kw_template)) {
Mike Stump11289f42009-09-09 15:08:12 +00002509 assert(!TemplateInfo.TemplateParams &&
Douglas Gregor3447e762009-08-20 22:52:58 +00002510 "Nested template improperly parsed?");
Richard Smith3af70092017-02-09 22:14:25 +00002511 ObjCDeclContextSwitch ObjCDC(*this);
Chris Lattner49836b42009-04-02 04:16:50 +00002512 SourceLocation DeclEnd;
Alexey Bataev05c25d62015-07-31 08:42:25 +00002513 return DeclGroupPtrTy::make(
Richard Smith3af70092017-02-09 22:14:25 +00002514 DeclGroupRef(ParseTemplateDeclarationOrSpecialization(
Faisal Vali421b2d12017-12-29 05:41:00 +00002515 DeclaratorContext::MemberContext, DeclEnd, AS, AccessAttrs)));
Chris Lattner5bbb3c82009-03-29 16:50:03 +00002516 }
Anders Carlssondfbbdf62009-03-26 00:52:18 +00002517
Chris Lattnerd19c1c02008-12-18 01:12:00 +00002518 // Handle: member-declaration ::= '__extension__' member-declaration
2519 if (Tok.is(tok::kw___extension__)) {
2520 // __extension__ silences extension warnings in the subexpression.
2521 ExtensionRAIIObject O(Diags); // Use RAII to do this.
2522 ConsumeToken();
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00002523 return ParseCXXClassMemberDeclaration(AS, AccessAttrs,
2524 TemplateInfo, TemplateDiags);
Chris Lattnerd19c1c02008-12-18 01:12:00 +00002525 }
Douglas Gregorfec52632009-06-20 00:51:54 +00002526
John McCall084e83d2011-03-24 11:26:52 +00002527 ParsedAttributesWithRange attrs(AttrFactory);
Michael Handdc016d2012-11-28 23:17:40 +00002528 ParsedAttributesWithRange FnAttrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00002529 // Optional C++11 attribute-specifier
2530 MaybeParseCXX11Attributes(attrs);
Michael Handdc016d2012-11-28 23:17:40 +00002531 // We need to keep these attributes for future diagnostic
2532 // before they are taken over by declaration specifier.
2533 FnAttrs.addAll(attrs.getList());
2534 FnAttrs.Range = attrs.Range;
2535
John McCall53fa7142010-12-24 02:08:15 +00002536 MaybeParseMicrosoftAttributes(attrs);
Alexis Hunt96d5c762009-11-21 08:43:09 +00002537
Douglas Gregorfec52632009-06-20 00:51:54 +00002538 if (Tok.is(tok::kw_using)) {
John McCall53fa7142010-12-24 02:08:15 +00002539 ProhibitAttributes(attrs);
Mike Stump11289f42009-09-09 15:08:12 +00002540
Douglas Gregorfec52632009-06-20 00:51:54 +00002541 // Eat 'using'.
2542 SourceLocation UsingLoc = ConsumeToken();
2543
2544 if (Tok.is(tok::kw_namespace)) {
2545 Diag(UsingLoc, diag::err_using_namespace_in_class);
Alexey Bataevee6507d2013-11-18 08:17:37 +00002546 SkipUntil(tok::semi, StopBeforeMatch);
David Blaikie0403cb12016-01-15 23:43:25 +00002547 return nullptr;
Douglas Gregorfec52632009-06-20 00:51:54 +00002548 }
Alexey Bataev05c25d62015-07-31 08:42:25 +00002549 SourceLocation DeclEnd;
2550 // Otherwise, it must be a using-declaration or an alias-declaration.
Faisal Vali421b2d12017-12-29 05:41:00 +00002551 return ParseUsingDeclaration(DeclaratorContext::MemberContext, TemplateInfo,
Richard Smith6f1daa42016-12-16 00:58:48 +00002552 UsingLoc, DeclEnd, AS);
Douglas Gregorfec52632009-06-20 00:51:54 +00002553 }
2554
DeLesley Hutchinsbd2ee132012-03-02 22:12:59 +00002555 // Hold late-parsed attributes so we can attach a Decl to them later.
2556 LateParsedAttrList CommonLateParsedAttrs;
2557
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002558 // decl-specifier-seq:
2559 // Parse the common declaration-specifiers piece.
John McCall796c2a52010-07-16 08:13:16 +00002560 ParsingDeclSpec DS(*this, TemplateDiags);
John McCall53fa7142010-12-24 02:08:15 +00002561 DS.takeAttributesFrom(attrs);
Richard Smith45855df2012-05-09 08:23:23 +00002562 if (MalformedTypeSpec)
2563 DS.SetTypeSpecError();
Richard Smith72553fc2014-01-23 23:53:27 +00002564
Faisal Valia534f072018-04-26 00:42:40 +00002565 ParseDeclarationSpecifiers(DS, TemplateInfo, AS, DeclSpecContext::DSC_class,
2566 &CommonLateParsedAttrs);
Serge Pavlov458ea762014-07-16 05:16:52 +00002567
2568 // Turn off colon protection that was set for declspec.
2569 X.restore();
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002570
Richard Smith404dfb42013-11-19 22:47:36 +00002571 // If we had a free-standing type definition with a missing semicolon, we
2572 // may get this far before the problem becomes obvious.
2573 if (DS.hasTagDefinition() &&
2574 TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate &&
Faisal Vali7db85c52017-12-31 00:06:40 +00002575 DiagnoseMissingSemiAfterTagDefinition(DS, AS, DeclSpecContext::DSC_class,
Richard Smith404dfb42013-11-19 22:47:36 +00002576 &CommonLateParsedAttrs))
David Blaikie0403cb12016-01-15 23:43:25 +00002577 return nullptr;
Richard Smith404dfb42013-11-19 22:47:36 +00002578
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002579 MultiTemplateParamsArg TemplateParams(
Craig Topper161e4db2014-05-21 06:02:52 +00002580 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->data()
2581 : nullptr,
John McCall11083da2009-09-16 22:47:08 +00002582 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->size() : 0);
2583
Alp Toker35d87032013-12-30 23:29:50 +00002584 if (TryConsumeToken(tok::semi)) {
Michael Handdc016d2012-11-28 23:17:40 +00002585 if (DS.isFriendSpecified())
2586 ProhibitAttributes(FnAttrs);
2587
Nico Weber7b837f52016-01-28 19:25:00 +00002588 RecordDecl *AnonRecord = nullptr;
2589 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(
2590 getCurScope(), AS, DS, TemplateParams, false, AnonRecord);
John McCall796c2a52010-07-16 08:13:16 +00002591 DS.complete(TheDecl);
Nico Weber7b837f52016-01-28 19:25:00 +00002592 if (AnonRecord) {
2593 Decl* decls[] = {AnonRecord, TheDecl};
Richard Smith3beb7c62017-01-12 02:27:38 +00002594 return Actions.BuildDeclaratorGroup(decls);
Nico Weber7b837f52016-01-28 19:25:00 +00002595 }
2596 return Actions.ConvertDeclToDeclGroup(TheDecl);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002597 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002598
Faisal Vali421b2d12017-12-29 05:41:00 +00002599 ParsingDeclarator DeclaratorInfo(*this, DS, DeclaratorContext::MemberContext);
Nico Weber24b2a822011-01-28 06:07:34 +00002600 VirtSpecifiers VS;
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002601
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002602 // Hold late-parsed attributes so we can attach a Decl to them later.
2603 LateParsedAttrList LateParsedAttrs;
2604
Douglas Gregor50cefbf2011-10-17 17:09:53 +00002605 SourceLocation EqualLoc;
Richard Smith9ba0fec2015-06-30 01:28:56 +00002606 SourceLocation PureSpecLoc;
2607
Yaron Keren180c1672015-06-30 07:35:19 +00002608 auto TryConsumePureSpecifier = [&] (bool AllowDefinition) {
Richard Smith9ba0fec2015-06-30 01:28:56 +00002609 if (Tok.isNot(tok::equal))
2610 return false;
2611
2612 auto &Zero = NextToken();
2613 SmallString<8> Buffer;
2614 if (Zero.isNot(tok::numeric_constant) || Zero.getLength() != 1 ||
2615 PP.getSpelling(Zero, Buffer) != "0")
2616 return false;
2617
2618 auto &After = GetLookAheadToken(2);
2619 if (!After.isOneOf(tok::semi, tok::comma) &&
2620 !(AllowDefinition &&
2621 After.isOneOf(tok::l_brace, tok::colon, tok::kw_try)))
2622 return false;
2623
2624 EqualLoc = ConsumeToken();
2625 PureSpecLoc = ConsumeToken();
2626 return true;
2627 };
Chris Lattner17c3b1f2009-12-10 01:59:24 +00002628
Richard Smith72553fc2014-01-23 23:53:27 +00002629 SmallVector<Decl *, 8> DeclsInGroup;
2630 ExprResult BitfieldSize;
2631 bool ExpectSemi = true;
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002632
Richard Smith72553fc2014-01-23 23:53:27 +00002633 // Parse the first declarator.
Nico Weberd89e6f72015-01-16 19:34:13 +00002634 if (ParseCXXMemberDeclaratorBeforeInitializer(
2635 DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs)) {
Richard Smith72553fc2014-01-23 23:53:27 +00002636 TryConsumeToken(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002637 return nullptr;
Richard Smith72553fc2014-01-23 23:53:27 +00002638 }
John Thompson5bc5cbe2009-11-25 22:58:06 +00002639
Richard Smith72553fc2014-01-23 23:53:27 +00002640 // Check for a member function definition.
Richard Smith4b5a9492014-01-24 22:34:35 +00002641 if (BitfieldSize.isUnset()) {
Richard Smith72553fc2014-01-23 23:53:27 +00002642 // MSVC permits pure specifier on inline functions defined at class scope.
Francois Pichet3abc9b82011-05-11 02:14:46 +00002643 // Hence check for =0 before checking for function definition.
Richard Smith9ba0fec2015-06-30 01:28:56 +00002644 if (getLangOpts().MicrosoftExt && DeclaratorInfo.isDeclarationOfFunction())
2645 TryConsumePureSpecifier(/*AllowDefinition*/ true);
Francois Pichet3abc9b82011-05-11 02:14:46 +00002646
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00002647 FunctionDefinitionKind DefinitionKind = FDK_Declaration;
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002648 // function-definition:
Richard Smith938f40b2011-06-11 17:19:42 +00002649 //
2650 // In C++11, a non-function declarator followed by an open brace is a
2651 // braced-init-list for an in-class member initialization, not an
2652 // erroneous function definition.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002653 if (Tok.is(tok::l_brace) && !getLangOpts().CPlusPlus11) {
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00002654 DefinitionKind = FDK_Definition;
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002655 } else if (DeclaratorInfo.isFunctionDeclarator()) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002656 if (Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try)) {
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00002657 DefinitionKind = FDK_Definition;
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002658 } else if (Tok.is(tok::equal)) {
2659 const Token &KW = NextToken();
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00002660 if (KW.is(tok::kw_default))
2661 DefinitionKind = FDK_Defaulted;
2662 else if (KW.is(tok::kw_delete))
2663 DefinitionKind = FDK_Deleted;
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002664 }
2665 }
Eli Bendersky41842222015-03-23 23:49:41 +00002666 DeclaratorInfo.setFunctionDefinitionKind(DefinitionKind);
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002667
Michael Handdc016d2012-11-28 23:17:40 +00002668 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
2669 // to a friend declaration, that declaration shall be a definition.
2670 if (DeclaratorInfo.isFunctionDeclarator() &&
2671 DefinitionKind != FDK_Definition && DS.isFriendSpecified()) {
2672 // Diagnose attributes that appear before decl specifier:
2673 // [[]] friend int foo();
2674 ProhibitAttributes(FnAttrs);
2675 }
2676
Nico Webera7f137d2015-01-16 19:35:01 +00002677 if (DefinitionKind != FDK_Declaration) {
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002678 if (!DeclaratorInfo.isFunctionDeclarator()) {
Richard Trieu0d730542012-01-21 02:59:18 +00002679 Diag(DeclaratorInfo.getIdentifierLoc(), diag::err_func_def_no_params);
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002680 ConsumeBrace();
Alexey Bataevee6507d2013-11-18 08:17:37 +00002681 SkipUntil(tok::r_brace);
Michael Handdc016d2012-11-28 23:17:40 +00002682
Douglas Gregor8a4db832011-01-19 16:41:58 +00002683 // Consume the optional ';'
Alp Toker35d87032013-12-30 23:29:50 +00002684 TryConsumeToken(tok::semi);
2685
David Blaikie0403cb12016-01-15 23:43:25 +00002686 return nullptr;
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002687 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002688
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002689 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
Richard Trieu0d730542012-01-21 02:59:18 +00002690 Diag(DeclaratorInfo.getIdentifierLoc(),
2691 diag::err_function_declared_typedef);
Douglas Gregor8a4db832011-01-19 16:41:58 +00002692
Richard Smith2603b092012-11-15 22:54:20 +00002693 // Recover by treating the 'typedef' as spurious.
2694 DS.ClearStorageClassSpecs();
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002695 }
2696
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002697 Decl *FunDecl =
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00002698 ParseCXXInlineMethodDef(AS, AccessAttrs, DeclaratorInfo, TemplateInfo,
Richard Smith9ba0fec2015-06-30 01:28:56 +00002699 VS, PureSpecLoc);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002700
David Majnemer23252a32013-08-01 04:22:55 +00002701 if (FunDecl) {
2702 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i) {
2703 CommonLateParsedAttrs[i]->addDecl(FunDecl);
2704 }
2705 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i) {
2706 LateParsedAttrs[i]->addDecl(FunDecl);
2707 }
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002708 }
2709 LateParsedAttrs.clear();
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002710
2711 // Consume the ';' - it's optional unless we have a delete or default
Richard Trieu2f7dc462012-05-16 19:04:59 +00002712 if (Tok.is(tok::semi))
Richard Smith87f5dc52012-07-23 05:45:25 +00002713 ConsumeExtraSemi(AfterMemberFunctionDefinition);
Douglas Gregor8a4db832011-01-19 16:41:58 +00002714
Alexey Bataev05c25d62015-07-31 08:42:25 +00002715 return DeclGroupPtrTy::make(DeclGroupRef(FunDecl));
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002716 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002717 }
2718
2719 // member-declarator-list:
2720 // member-declarator
2721 // member-declarator-list ',' member-declarator
2722
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002723 while (1) {
Richard Smith2b013182012-06-10 03:12:00 +00002724 InClassInitStyle HasInClassInit = ICIS_NoInit;
Richard Smith9ba0fec2015-06-30 01:28:56 +00002725 bool HasStaticInitializer = false;
2726 if (Tok.isOneOf(tok::equal, tok::l_brace) && PureSpecLoc.isInvalid()) {
Richard Smith6b8e3c02017-08-28 00:28:14 +00002727 if (DeclaratorInfo.isDeclarationOfFunction()) {
Richard Smith9ba0fec2015-06-30 01:28:56 +00002728 // It's a pure-specifier.
2729 if (!TryConsumePureSpecifier(/*AllowFunctionDefinition*/ false))
2730 // Parse it as an expression so that Sema can diagnose it.
2731 HasStaticInitializer = true;
2732 } else if (DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2733 DeclSpec::SCS_static &&
2734 DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2735 DeclSpec::SCS_typedef &&
2736 !DS.isFriendSpecified()) {
2737 // It's a default member initializer.
Richard Smith6b8e3c02017-08-28 00:28:14 +00002738 if (BitfieldSize.get())
2739 Diag(Tok, getLangOpts().CPlusPlus2a
2740 ? diag::warn_cxx17_compat_bitfield_member_init
2741 : diag::ext_bitfield_member_init);
Richard Smith9ba0fec2015-06-30 01:28:56 +00002742 HasInClassInit = Tok.is(tok::equal) ? ICIS_CopyInit : ICIS_ListInit;
Richard Smith938f40b2011-06-11 17:19:42 +00002743 } else {
Richard Smith9ba0fec2015-06-30 01:28:56 +00002744 HasStaticInitializer = true;
Richard Smith938f40b2011-06-11 17:19:42 +00002745 }
2746 }
2747
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002748 // NOTE: If Sema is the Action module and declarator is an instance field,
Chris Lattner5bbb3c82009-03-29 16:50:03 +00002749 // this call will *not* return the created decl; It will return null.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002750 // See Sema::ActOnCXXMemberDeclarator for details.
John McCall07e91c02009-08-06 02:15:43 +00002751
Craig Topper161e4db2014-05-21 06:02:52 +00002752 NamedDecl *ThisDecl = nullptr;
John McCall07e91c02009-08-06 02:15:43 +00002753 if (DS.isFriendSpecified()) {
Richard Smith72553fc2014-01-23 23:53:27 +00002754 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
Michael Handdc016d2012-11-28 23:17:40 +00002755 // to a friend declaration, that declaration shall be a definition.
2756 //
Richard Smith72553fc2014-01-23 23:53:27 +00002757 // Diagnose attributes that appear in a friend member function declarator:
2758 // friend int foo [[]] ();
Michael Handdc016d2012-11-28 23:17:40 +00002759 SmallVector<SourceRange, 4> Ranges;
2760 DeclaratorInfo.getCXX11AttributeRanges(Ranges);
Richard Smith72553fc2014-01-23 23:53:27 +00002761 for (SmallVectorImpl<SourceRange>::iterator I = Ranges.begin(),
2762 E = Ranges.end(); I != E; ++I)
2763 Diag((*I).getBegin(), diag::err_attributes_not_allowed) << *I;
Michael Handdc016d2012-11-28 23:17:40 +00002764
Douglas Gregor0be31a22010-07-02 17:43:08 +00002765 ThisDecl = Actions.ActOnFriendFunctionDecl(getCurScope(), DeclaratorInfo,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002766 TemplateParams);
Douglas Gregor3447e762009-08-20 22:52:58 +00002767 } else {
Douglas Gregor0be31a22010-07-02 17:43:08 +00002768 ThisDecl = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS,
John McCall07e91c02009-08-06 02:15:43 +00002769 DeclaratorInfo,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002770 TemplateParams,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002771 BitfieldSize.get(),
Richard Smith2b013182012-06-10 03:12:00 +00002772 VS, HasInClassInit);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002773
2774 if (VarTemplateDecl *VT =
Craig Topper161e4db2014-05-21 06:02:52 +00002775 ThisDecl ? dyn_cast<VarTemplateDecl>(ThisDecl) : nullptr)
Larisse Voufo39a1e502013-08-06 01:03:05 +00002776 // Re-direct this decl to refer to the templated decl so that we can
2777 // initialize it.
2778 ThisDecl = VT->getTemplatedDecl();
2779
David Majnemer23252a32013-08-01 04:22:55 +00002780 if (ThisDecl && AccessAttrs)
Richard Smithf8a75c32013-08-29 00:47:48 +00002781 Actions.ProcessDeclAttributeList(getCurScope(), ThisDecl, AccessAttrs);
Douglas Gregor3447e762009-08-20 22:52:58 +00002782 }
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002783
Richard Smith9ba0fec2015-06-30 01:28:56 +00002784 // Error recovery might have converted a non-static member into a static
2785 // member.
David Blaikie35506f82013-01-30 01:22:18 +00002786 if (HasInClassInit != ICIS_NoInit &&
Richard Smith9ba0fec2015-06-30 01:28:56 +00002787 DeclaratorInfo.getDeclSpec().getStorageClassSpec() ==
2788 DeclSpec::SCS_static) {
2789 HasInClassInit = ICIS_NoInit;
2790 HasStaticInitializer = true;
2791 }
2792
2793 if (ThisDecl && PureSpecLoc.isValid())
2794 Actions.ActOnPureSpecifier(ThisDecl, PureSpecLoc);
2795
2796 // Handle the initializer.
2797 if (HasInClassInit != ICIS_NoInit) {
Douglas Gregor728d00b2011-10-10 14:49:18 +00002798 // The initializer was deferred; parse it and cache the tokens.
David Majnemer23252a32013-08-01 04:22:55 +00002799 Diag(Tok, getLangOpts().CPlusPlus11
2800 ? diag::warn_cxx98_compat_nonstatic_member_init
2801 : diag::ext_nonstatic_member_init);
Richard Smith5d164bc2011-10-15 05:09:34 +00002802
Richard Smith938f40b2011-06-11 17:19:42 +00002803 if (DeclaratorInfo.isArrayOfUnknownBound()) {
Richard Smith2b013182012-06-10 03:12:00 +00002804 // C++11 [dcl.array]p3: An array bound may also be omitted when the
2805 // declarator is followed by an initializer.
Richard Smith938f40b2011-06-11 17:19:42 +00002806 //
2807 // A brace-or-equal-initializer for a member-declarator is not an
David Blaikiecdd91db2012-02-14 09:00:46 +00002808 // initializer in the grammar, so this is ill-formed.
Richard Smith938f40b2011-06-11 17:19:42 +00002809 Diag(Tok, diag::err_incomplete_array_member_init);
Alexey Bataevee6507d2013-11-18 08:17:37 +00002810 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
David Majnemer23252a32013-08-01 04:22:55 +00002811
2812 // Avoid later warnings about a class member of incomplete type.
David Blaikiecdd91db2012-02-14 09:00:46 +00002813 if (ThisDecl)
David Blaikiecdd91db2012-02-14 09:00:46 +00002814 ThisDecl->setInvalidDecl();
Richard Smith938f40b2011-06-11 17:19:42 +00002815 } else
2816 ParseCXXNonStaticMemberInitializer(ThisDecl);
Richard Smith9ba0fec2015-06-30 01:28:56 +00002817 } else if (HasStaticInitializer) {
Douglas Gregor728d00b2011-10-10 14:49:18 +00002818 // Normal initializer.
Richard Smith9ba0fec2015-06-30 01:28:56 +00002819 ExprResult Init = ParseCXXMemberInitializer(
2820 ThisDecl, DeclaratorInfo.isDeclarationOfFunction(), EqualLoc);
David Majnemer23252a32013-08-01 04:22:55 +00002821
Douglas Gregor728d00b2011-10-10 14:49:18 +00002822 if (Init.isInvalid())
Alexey Bataevee6507d2013-11-18 08:17:37 +00002823 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
Douglas Gregor728d00b2011-10-10 14:49:18 +00002824 else if (ThisDecl)
Richard Smith3beb7c62017-01-12 02:27:38 +00002825 Actions.AddInitializerToDecl(ThisDecl, Init.get(), EqualLoc.isInvalid());
David Majnemer23252a32013-08-01 04:22:55 +00002826 } else if (ThisDecl && DS.getStorageClassSpec() == DeclSpec::SCS_static)
Douglas Gregor728d00b2011-10-10 14:49:18 +00002827 // No initializer.
Richard Smith3beb7c62017-01-12 02:27:38 +00002828 Actions.ActOnUninitializedDecl(ThisDecl);
David Majnemer23252a32013-08-01 04:22:55 +00002829
Douglas Gregor728d00b2011-10-10 14:49:18 +00002830 if (ThisDecl) {
David Majnemer23252a32013-08-01 04:22:55 +00002831 if (!ThisDecl->isInvalidDecl()) {
2832 // Set the Decl for any late parsed attributes
2833 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i)
2834 CommonLateParsedAttrs[i]->addDecl(ThisDecl);
2835
2836 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i)
2837 LateParsedAttrs[i]->addDecl(ThisDecl);
2838 }
Douglas Gregor728d00b2011-10-10 14:49:18 +00002839 Actions.FinalizeDeclaration(ThisDecl);
2840 DeclsInGroup.push_back(ThisDecl);
David Majnemer23252a32013-08-01 04:22:55 +00002841
2842 if (DeclaratorInfo.isFunctionDeclarator() &&
2843 DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2844 DeclSpec::SCS_typedef)
2845 HandleMemberFunctionDeclDelays(DeclaratorInfo, ThisDecl);
Douglas Gregor728d00b2011-10-10 14:49:18 +00002846 }
David Majnemer23252a32013-08-01 04:22:55 +00002847 LateParsedAttrs.clear();
Douglas Gregor728d00b2011-10-10 14:49:18 +00002848
2849 DeclaratorInfo.complete(ThisDecl);
Richard Smith938f40b2011-06-11 17:19:42 +00002850
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002851 // If we don't have a comma, it is either the end of the list (a ';')
2852 // or an error, bail out.
Alp Toker094e5212014-01-05 03:27:11 +00002853 SourceLocation CommaLoc;
2854 if (!TryConsumeToken(tok::comma, CommaLoc))
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002855 break;
Mike Stump11289f42009-09-09 15:08:12 +00002856
Richard Smithc8a79032012-01-09 22:31:44 +00002857 if (Tok.isAtStartOfLine() &&
Faisal Vali421b2d12017-12-29 05:41:00 +00002858 !MightBeDeclarator(DeclaratorContext::MemberContext)) {
Richard Smithc8a79032012-01-09 22:31:44 +00002859 // This comma was followed by a line-break and something which can't be
2860 // the start of a declarator. The comma was probably a typo for a
2861 // semicolon.
2862 Diag(CommaLoc, diag::err_expected_semi_declaration)
2863 << FixItHint::CreateReplacement(CommaLoc, ";");
2864 ExpectSemi = false;
2865 break;
2866 }
Mike Stump11289f42009-09-09 15:08:12 +00002867
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002868 // Parse the next declarator.
2869 DeclaratorInfo.clear();
Nico Weber24b2a822011-01-28 06:07:34 +00002870 VS.clear();
Nico Weberf56c85b2015-01-17 02:26:40 +00002871 BitfieldSize = ExprResult(/*Invalid=*/false);
Richard Smith9ba0fec2015-06-30 01:28:56 +00002872 EqualLoc = PureSpecLoc = SourceLocation();
Richard Smith8d06f422012-01-12 23:53:29 +00002873 DeclaratorInfo.setCommaLoc(CommaLoc);
Mike Stump11289f42009-09-09 15:08:12 +00002874
Richard Smith72553fc2014-01-23 23:53:27 +00002875 // GNU attributes are allowed before the second and subsequent declarator.
John McCall53fa7142010-12-24 02:08:15 +00002876 MaybeParseGNUAttributes(DeclaratorInfo);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002877
Nico Weberd89e6f72015-01-16 19:34:13 +00002878 if (ParseCXXMemberDeclaratorBeforeInitializer(
2879 DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs))
2880 break;
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002881 }
2882
Richard Smithc8a79032012-01-09 22:31:44 +00002883 if (ExpectSemi &&
2884 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list)) {
Chris Lattner916dbf12010-02-02 00:43:15 +00002885 // Skip to end of block or statement.
Alexey Bataevee6507d2013-11-18 08:17:37 +00002886 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Chris Lattner916dbf12010-02-02 00:43:15 +00002887 // If we stopped at a ';', eat it.
Alp Toker35d87032013-12-30 23:29:50 +00002888 TryConsumeToken(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002889 return nullptr;
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002890 }
2891
Alexey Bataev05c25d62015-07-31 08:42:25 +00002892 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002893}
2894
Richard Smith9ba0fec2015-06-30 01:28:56 +00002895/// ParseCXXMemberInitializer - Parse the brace-or-equal-initializer.
2896/// Also detect and reject any attempted defaulted/deleted function definition.
2897/// The location of the '=', if any, will be placed in EqualLoc.
Richard Smith938f40b2011-06-11 17:19:42 +00002898///
Richard Smith9ba0fec2015-06-30 01:28:56 +00002899/// This does not check for a pure-specifier; that's handled elsewhere.
Sebastian Redleef474c2012-02-22 10:50:08 +00002900///
Richard Smith938f40b2011-06-11 17:19:42 +00002901/// brace-or-equal-initializer:
2902/// '=' initializer-expression
Sebastian Redleef474c2012-02-22 10:50:08 +00002903/// braced-init-list
2904///
Richard Smith938f40b2011-06-11 17:19:42 +00002905/// initializer-clause:
2906/// assignment-expression
Sebastian Redleef474c2012-02-22 10:50:08 +00002907/// braced-init-list
2908///
Richard Smithda35e962013-11-09 04:52:51 +00002909/// defaulted/deleted function-definition:
Richard Smith938f40b2011-06-11 17:19:42 +00002910/// '=' 'default'
2911/// '=' 'delete'
2912///
2913/// Prior to C++0x, the assignment-expression in an initializer-clause must
2914/// be a constant-expression.
Douglas Gregor926410d2012-02-21 02:22:07 +00002915ExprResult Parser::ParseCXXMemberInitializer(Decl *D, bool IsFunction,
Richard Smith938f40b2011-06-11 17:19:42 +00002916 SourceLocation &EqualLoc) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002917 assert(Tok.isOneOf(tok::equal, tok::l_brace)
Richard Smith938f40b2011-06-11 17:19:42 +00002918 && "Data member initializer not starting with '=' or '{'");
2919
Faisal Valid143a0c2017-04-01 21:30:49 +00002920 EnterExpressionEvaluationContext Context(
2921 Actions, Sema::ExpressionEvaluationContext::PotentiallyEvaluated, D);
Alp Toker094e5212014-01-05 03:27:11 +00002922 if (TryConsumeToken(tok::equal, EqualLoc)) {
Richard Smith938f40b2011-06-11 17:19:42 +00002923 if (Tok.is(tok::kw_delete)) {
2924 // In principle, an initializer of '= delete p;' is legal, but it will
2925 // never type-check. It's better to diagnose it as an ill-formed expression
2926 // than as an ill-formed deleted non-function member.
2927 // An initializer of '= delete p, foo' will never be parsed, because
2928 // a top-level comma always ends the initializer expression.
2929 const Token &Next = NextToken();
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002930 if (IsFunction || Next.isOneOf(tok::semi, tok::comma, tok::eof)) {
Richard Smith938f40b2011-06-11 17:19:42 +00002931 if (IsFunction)
2932 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2933 << 1 /* delete */;
2934 else
2935 Diag(ConsumeToken(), diag::err_deleted_non_function);
Richard Smithedcb26e2014-06-11 00:49:52 +00002936 return ExprError();
Richard Smith938f40b2011-06-11 17:19:42 +00002937 }
2938 } else if (Tok.is(tok::kw_default)) {
Richard Smith938f40b2011-06-11 17:19:42 +00002939 if (IsFunction)
2940 Diag(Tok, diag::err_default_delete_in_multiple_declaration)
2941 << 0 /* default */;
2942 else
2943 Diag(ConsumeToken(), diag::err_default_special_members);
Richard Smithedcb26e2014-06-11 00:49:52 +00002944 return ExprError();
Richard Smith938f40b2011-06-11 17:19:42 +00002945 }
David Majnemer87ff66c2014-12-13 11:34:16 +00002946 }
2947 if (const auto *PD = dyn_cast_or_null<MSPropertyDecl>(D)) {
2948 Diag(Tok, diag::err_ms_property_initializer) << PD;
2949 return ExprError();
Sebastian Redleef474c2012-02-22 10:50:08 +00002950 }
2951 return ParseInitializer();
Richard Smith938f40b2011-06-11 17:19:42 +00002952}
2953
Richard Smith65ebb4a2015-03-26 04:09:53 +00002954void Parser::SkipCXXMemberSpecification(SourceLocation RecordLoc,
2955 SourceLocation AttrFixitLoc,
Faisal Vali090da2d2018-01-01 18:23:28 +00002956 unsigned TagType, Decl *TagDecl) {
Richard Smith65ebb4a2015-03-26 04:09:53 +00002957 // Skip the optional 'final' keyword.
2958 if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
2959 assert(isCXX11FinalKeyword() && "not a class definition");
2960 ConsumeToken();
2961
2962 // Diagnose any C++11 attributes after 'final' keyword.
2963 // We deliberately discard these attributes.
2964 ParsedAttributesWithRange Attrs(AttrFactory);
2965 CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
2966
2967 // This can only happen if we had malformed misplaced attributes;
2968 // we only get called if there is a colon or left-brace after the
2969 // attributes.
2970 if (Tok.isNot(tok::colon) && Tok.isNot(tok::l_brace))
2971 return;
2972 }
2973
2974 // Skip the base clauses. This requires actually parsing them, because
2975 // otherwise we can't be sure where they end (a left brace may appear
2976 // within a template argument).
2977 if (Tok.is(tok::colon)) {
2978 // Enter the scope of the class so that we can correctly parse its bases.
2979 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
2980 ParsingClassDefinition ParsingDef(*this, TagDecl, /*NonNestedClass*/ true,
2981 TagType == DeclSpec::TST_interface);
Richard Smith0f192e82015-06-11 22:48:25 +00002982 auto OldContext =
2983 Actions.ActOnTagStartSkippedDefinition(getCurScope(), TagDecl);
Richard Smith65ebb4a2015-03-26 04:09:53 +00002984
2985 // Parse the bases but don't attach them to the class.
2986 ParseBaseClause(nullptr);
2987
Richard Smith0f192e82015-06-11 22:48:25 +00002988 Actions.ActOnTagFinishSkippedDefinition(OldContext);
Richard Smith65ebb4a2015-03-26 04:09:53 +00002989
2990 if (!Tok.is(tok::l_brace)) {
2991 Diag(PP.getLocForEndOfToken(PrevTokLocation),
2992 diag::err_expected_lbrace_after_base_specifiers);
2993 return;
2994 }
2995 }
2996
2997 // Skip the body.
2998 assert(Tok.is(tok::l_brace));
2999 BalancedDelimiterTracker T(*this, tok::l_brace);
3000 T.consumeOpen();
3001 T.skipToEnd();
Richard Smith04c6c1f2015-07-01 18:56:50 +00003002
3003 // Parse and discard any trailing attributes.
3004 ParsedAttributes Attrs(AttrFactory);
3005 if (Tok.is(tok::kw___attribute))
3006 MaybeParseGNUAttributes(Attrs);
Richard Smith65ebb4a2015-03-26 04:09:53 +00003007}
3008
Alexey Bataev05c25d62015-07-31 08:42:25 +00003009Parser::DeclGroupPtrTy Parser::ParseCXXClassMemberDeclarationWithPragmas(
3010 AccessSpecifier &AS, ParsedAttributesWithRange &AccessAttrs,
3011 DeclSpec::TST TagType, Decl *TagDecl) {
Richard Smithbf5bcf22018-06-26 23:20:26 +00003012 ParenBraceBracketBalancer BalancerRAIIObj(*this);
3013
Richard Smithb55f7582017-01-28 01:12:10 +00003014 switch (Tok.getKind()) {
3015 case tok::kw___if_exists:
3016 case tok::kw___if_not_exists:
Alexey Bataev05c25d62015-07-31 08:42:25 +00003017 ParseMicrosoftIfExistsClassDeclaration(TagType, AS);
David Blaikie0403cb12016-01-15 23:43:25 +00003018 return nullptr;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003019
Richard Smithb55f7582017-01-28 01:12:10 +00003020 case tok::semi:
3021 // Check for extraneous top-level semicolon.
Alexey Bataev05c25d62015-07-31 08:42:25 +00003022 ConsumeExtraSemi(InsideStruct, TagType);
David Blaikie0403cb12016-01-15 23:43:25 +00003023 return nullptr;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003024
Richard Smithb55f7582017-01-28 01:12:10 +00003025 // Handle pragmas that can appear as member declarations.
3026 case tok::annot_pragma_vis:
Alexey Bataev05c25d62015-07-31 08:42:25 +00003027 HandlePragmaVisibility();
David Blaikie0403cb12016-01-15 23:43:25 +00003028 return nullptr;
Richard Smithb55f7582017-01-28 01:12:10 +00003029 case tok::annot_pragma_pack:
Alexey Bataev05c25d62015-07-31 08:42:25 +00003030 HandlePragmaPack();
David Blaikie0403cb12016-01-15 23:43:25 +00003031 return nullptr;
Richard Smithb55f7582017-01-28 01:12:10 +00003032 case tok::annot_pragma_align:
Alexey Bataev05c25d62015-07-31 08:42:25 +00003033 HandlePragmaAlign();
David Blaikie0403cb12016-01-15 23:43:25 +00003034 return nullptr;
Richard Smithb55f7582017-01-28 01:12:10 +00003035 case tok::annot_pragma_ms_pointers_to_members:
Alexey Bataev05c25d62015-07-31 08:42:25 +00003036 HandlePragmaMSPointersToMembers();
David Blaikie0403cb12016-01-15 23:43:25 +00003037 return nullptr;
Richard Smithb55f7582017-01-28 01:12:10 +00003038 case tok::annot_pragma_ms_pragma:
Alexey Bataev05c25d62015-07-31 08:42:25 +00003039 HandlePragmaMSPragma();
David Blaikie0403cb12016-01-15 23:43:25 +00003040 return nullptr;
Richard Smithb55f7582017-01-28 01:12:10 +00003041 case tok::annot_pragma_ms_vtordisp:
Alexey Bataev3d42f342015-11-20 07:02:57 +00003042 HandlePragmaMSVtorDisp();
David Blaikie0403cb12016-01-15 23:43:25 +00003043 return nullptr;
Richard Smithb256d302017-01-28 01:20:57 +00003044 case tok::annot_pragma_dump:
3045 HandlePragmaDump();
3046 return nullptr;
Alexey Bataev3d42f342015-11-20 07:02:57 +00003047
Richard Smithb55f7582017-01-28 01:12:10 +00003048 case tok::kw_namespace:
3049 // If we see a namespace here, a close brace was missing somewhere.
Alexey Bataev05c25d62015-07-31 08:42:25 +00003050 DiagnoseUnexpectedNamespace(cast<NamedDecl>(TagDecl));
David Blaikie0403cb12016-01-15 23:43:25 +00003051 return nullptr;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003052
Richard Smithb55f7582017-01-28 01:12:10 +00003053 case tok::kw_public:
3054 case tok::kw_protected:
3055 case tok::kw_private: {
3056 AccessSpecifier NewAS = getAccessSpecifierIfPresent();
3057 assert(NewAS != AS_none);
Alexey Bataev05c25d62015-07-31 08:42:25 +00003058 // Current token is a C++ access specifier.
3059 AS = NewAS;
3060 SourceLocation ASLoc = Tok.getLocation();
3061 unsigned TokLength = Tok.getLength();
3062 ConsumeToken();
3063 AccessAttrs.clear();
3064 MaybeParseGNUAttributes(AccessAttrs);
3065
3066 SourceLocation EndLoc;
3067 if (TryConsumeToken(tok::colon, EndLoc)) {
3068 } else if (TryConsumeToken(tok::semi, EndLoc)) {
3069 Diag(EndLoc, diag::err_expected)
3070 << tok::colon << FixItHint::CreateReplacement(EndLoc, ":");
3071 } else {
3072 EndLoc = ASLoc.getLocWithOffset(TokLength);
3073 Diag(EndLoc, diag::err_expected)
3074 << tok::colon << FixItHint::CreateInsertion(EndLoc, ":");
3075 }
3076
3077 // The Microsoft extension __interface does not permit non-public
3078 // access specifiers.
3079 if (TagType == DeclSpec::TST_interface && AS != AS_public) {
3080 Diag(ASLoc, diag::err_access_specifier_interface) << (AS == AS_protected);
3081 }
3082
3083 if (Actions.ActOnAccessSpecifier(NewAS, ASLoc, EndLoc,
3084 AccessAttrs.getList())) {
3085 // found another attribute than only annotations
3086 AccessAttrs.clear();
3087 }
3088
David Blaikie0403cb12016-01-15 23:43:25 +00003089 return nullptr;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003090 }
3091
Richard Smithb55f7582017-01-28 01:12:10 +00003092 case tok::annot_pragma_openmp:
Alexey Bataev587e1de2016-03-30 10:43:55 +00003093 return ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, AccessAttrs, TagType,
3094 TagDecl);
Alexey Bataev05c25d62015-07-31 08:42:25 +00003095
Richard Smithb55f7582017-01-28 01:12:10 +00003096 default:
3097 return ParseCXXClassMemberDeclaration(AS, AccessAttrs.getList());
3098 }
Alexey Bataev05c25d62015-07-31 08:42:25 +00003099}
3100
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003101/// ParseCXXMemberSpecification - Parse the class definition.
3102///
3103/// member-specification:
3104/// member-declaration member-specification[opt]
3105/// access-specifier ':' member-specification[opt]
3106///
Joao Matose9a3ed42012-08-31 22:18:20 +00003107void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc,
Michael Han309af292013-01-07 16:57:11 +00003108 SourceLocation AttrFixitLoc,
Richard Smith4c96e992013-02-19 23:47:15 +00003109 ParsedAttributesWithRange &Attrs,
Faisal Vali090da2d2018-01-01 18:23:28 +00003110 unsigned TagType, Decl *TagDecl) {
Joao Matose9a3ed42012-08-31 22:18:20 +00003111 assert((TagType == DeclSpec::TST_struct ||
Faisal Vali090da2d2018-01-01 18:23:28 +00003112 TagType == DeclSpec::TST_interface ||
3113 TagType == DeclSpec::TST_union ||
3114 TagType == DeclSpec::TST_class) && "Invalid TagType!");
Joao Matose9a3ed42012-08-31 22:18:20 +00003115
Jordan Rose1e879d82018-03-23 00:07:18 +00003116 PrettyDeclStackTraceEntry CrashInfo(Actions.Context, TagDecl, RecordLoc,
John McCallfaf5fb42010-08-26 23:41:50 +00003117 "parsing struct/union/class body");
Mike Stump11289f42009-09-09 15:08:12 +00003118
Douglas Gregoredf8f392010-01-16 20:52:59 +00003119 // Determine whether this is a non-nested class. Note that local
3120 // classes are *not* considered to be nested classes.
3121 bool NonNestedClass = true;
3122 if (!ClassStack.empty()) {
Douglas Gregor0be31a22010-07-02 17:43:08 +00003123 for (const Scope *S = getCurScope(); S; S = S->getParent()) {
Douglas Gregoredf8f392010-01-16 20:52:59 +00003124 if (S->isClassScope()) {
3125 // We're inside a class scope, so this is a nested class.
3126 NonNestedClass = false;
John McCalldb632ac2012-09-25 07:32:39 +00003127
3128 // The Microsoft extension __interface does not permit nested classes.
3129 if (getCurrentClass().IsInterface) {
3130 Diag(RecordLoc, diag::err_invalid_member_in_interface)
3131 << /*ErrorType=*/6
3132 << (isa<NamedDecl>(TagDecl)
3133 ? cast<NamedDecl>(TagDecl)->getQualifiedNameAsString()
David Blaikieabe1a392014-04-02 05:58:29 +00003134 : "(anonymous)");
John McCalldb632ac2012-09-25 07:32:39 +00003135 }
Douglas Gregoredf8f392010-01-16 20:52:59 +00003136 break;
3137 }
3138
Serge Pavlovd9c0bcf2015-07-14 10:02:10 +00003139 if ((S->getFlags() & Scope::FnScope))
3140 // If we're in a function or function template then this is a local
3141 // class rather than a nested class.
3142 break;
Douglas Gregoredf8f392010-01-16 20:52:59 +00003143 }
3144 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003145
3146 // Enter a scope for the class.
Douglas Gregor658b9552009-01-09 22:42:13 +00003147 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003148
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003149 // Note that we are parsing a new (potentially-nested) class definition.
John McCalldb632ac2012-09-25 07:32:39 +00003150 ParsingClassDefinition ParsingDef(*this, TagDecl, NonNestedClass,
3151 TagType == DeclSpec::TST_interface);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003152
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003153 if (TagDecl)
Douglas Gregor0be31a22010-07-02 17:43:08 +00003154 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
John McCall2d814c32009-12-19 21:48:58 +00003155
Anders Carlssonf9eb63b2011-03-25 14:46:08 +00003156 SourceLocation FinalLoc;
David Majnemera5433082013-10-18 00:33:31 +00003157 bool IsFinalSpelledSealed = false;
Anders Carlssonf9eb63b2011-03-25 14:46:08 +00003158
3159 // Parse the optional 'final' keyword.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003160 if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
David Majnemera5433082013-10-18 00:33:31 +00003161 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier(Tok);
3162 assert((Specifier == VirtSpecifiers::VS_Final ||
Andrey Bokhanko276055b2016-07-29 10:42:48 +00003163 Specifier == VirtSpecifiers::VS_GNU_Final ||
David Majnemera5433082013-10-18 00:33:31 +00003164 Specifier == VirtSpecifiers::VS_Sealed) &&
3165 "not a class definition");
Richard Smithda261112011-10-15 04:21:46 +00003166 FinalLoc = ConsumeToken();
David Majnemera5433082013-10-18 00:33:31 +00003167 IsFinalSpelledSealed = Specifier == VirtSpecifiers::VS_Sealed;
Anders Carlssonf9eb63b2011-03-25 14:46:08 +00003168
David Majnemera5433082013-10-18 00:33:31 +00003169 if (TagType == DeclSpec::TST_interface)
John McCalldb632ac2012-09-25 07:32:39 +00003170 Diag(FinalLoc, diag::err_override_control_interface)
David Majnemera5433082013-10-18 00:33:31 +00003171 << VirtSpecifiers::getSpecifierName(Specifier);
3172 else if (Specifier == VirtSpecifiers::VS_Final)
3173 Diag(FinalLoc, getLangOpts().CPlusPlus11
3174 ? diag::warn_cxx98_compat_override_control_keyword
3175 : diag::ext_override_control_keyword)
3176 << VirtSpecifiers::getSpecifierName(Specifier);
3177 else if (Specifier == VirtSpecifiers::VS_Sealed)
3178 Diag(FinalLoc, diag::ext_ms_sealed_keyword);
Andrey Bokhanko276055b2016-07-29 10:42:48 +00003179 else if (Specifier == VirtSpecifiers::VS_GNU_Final)
3180 Diag(FinalLoc, diag::ext_warn_gnu_final);
Michael Han9407e502012-11-26 22:54:45 +00003181
Michael Han309af292013-01-07 16:57:11 +00003182 // Parse any C++11 attributes after 'final' keyword.
3183 // These attributes are not allowed to appear here,
3184 // and the only possible place for them to appertain
3185 // to the class would be between class-key and class-name.
Richard Smith4c96e992013-02-19 23:47:15 +00003186 CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
Nico Weber4b4be842014-12-29 06:56:50 +00003187
3188 // ParseClassSpecifier() does only a superficial check for attributes before
3189 // deciding to call this method. For example, for
3190 // `class C final alignas ([l) {` it will decide that this looks like a
3191 // misplaced attribute since it sees `alignas '(' ')'`. But the actual
3192 // attribute parsing code will try to parse the '[' as a constexpr lambda
3193 // and consume enough tokens that the alignas parsing code will eat the
3194 // opening '{'. So bail out if the next token isn't one we expect.
Nico Weber36de3a22014-12-29 21:56:22 +00003195 if (!Tok.is(tok::colon) && !Tok.is(tok::l_brace)) {
3196 if (TagDecl)
3197 Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
Nico Weber4b4be842014-12-29 06:56:50 +00003198 return;
Nico Weber36de3a22014-12-29 21:56:22 +00003199 }
Anders Carlssonf9eb63b2011-03-25 14:46:08 +00003200 }
Anders Carlsson4b63d0e2011-01-22 16:56:46 +00003201
John McCall2d814c32009-12-19 21:48:58 +00003202 if (Tok.is(tok::colon)) {
Erik Verbruggen6524c052017-10-24 13:46:58 +00003203 ParseScope InheritanceScope(this, getCurScope()->getFlags() |
3204 Scope::ClassInheritanceScope);
3205
John McCall2d814c32009-12-19 21:48:58 +00003206 ParseBaseClause(TagDecl);
John McCall2d814c32009-12-19 21:48:58 +00003207 if (!Tok.is(tok::l_brace)) {
Ismail Pazarbasi129c44c2014-09-25 21:13:02 +00003208 bool SuggestFixIt = false;
3209 SourceLocation BraceLoc = PP.getLocForEndOfToken(PrevTokLocation);
3210 if (Tok.isAtStartOfLine()) {
3211 switch (Tok.getKind()) {
3212 case tok::kw_private:
3213 case tok::kw_protected:
3214 case tok::kw_public:
3215 SuggestFixIt = NextToken().getKind() == tok::colon;
3216 break;
3217 case tok::kw_static_assert:
3218 case tok::r_brace:
3219 case tok::kw_using:
3220 // base-clause can have simple-template-id; 'template' can't be there
3221 case tok::kw_template:
3222 SuggestFixIt = true;
3223 break;
3224 case tok::identifier:
3225 SuggestFixIt = isConstructorDeclarator(true);
3226 break;
3227 default:
3228 SuggestFixIt = isCXXSimpleDeclaration(/*AllowForRangeDecl=*/false);
3229 break;
3230 }
3231 }
3232 DiagnosticBuilder LBraceDiag =
3233 Diag(BraceLoc, diag::err_expected_lbrace_after_base_specifiers);
3234 if (SuggestFixIt) {
3235 LBraceDiag << FixItHint::CreateInsertion(BraceLoc, " {");
3236 // Try recovering from missing { after base-clause.
3237 PP.EnterToken(Tok);
3238 Tok.setKind(tok::l_brace);
3239 } else {
3240 if (TagDecl)
3241 Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
3242 return;
3243 }
John McCall2d814c32009-12-19 21:48:58 +00003244 }
3245 }
3246
3247 assert(Tok.is(tok::l_brace));
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003248 BalancedDelimiterTracker T(*this, tok::l_brace);
3249 T.consumeOpen();
John McCall2d814c32009-12-19 21:48:58 +00003250
John McCall08bede42010-05-28 08:11:17 +00003251 if (TagDecl)
Anders Carlsson30f29442011-03-25 14:31:08 +00003252 Actions.ActOnStartCXXMemberDeclarations(getCurScope(), TagDecl, FinalLoc,
David Majnemera5433082013-10-18 00:33:31 +00003253 IsFinalSpelledSealed,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003254 T.getOpenLocation());
John McCall1c7e6ec2009-12-20 07:58:13 +00003255
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003256 // C++ 11p3: Members of a class defined with the keyword class are private
3257 // by default. Members of a class defined with the keywords struct or union
3258 // are public by default.
3259 AccessSpecifier CurAS;
3260 if (TagType == DeclSpec::TST_class)
3261 CurAS = AS_private;
3262 else
3263 CurAS = AS_public;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003264 ParsedAttributesWithRange AccessAttrs(AttrFactory);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003265
Douglas Gregor9377c822010-06-21 22:31:09 +00003266 if (TagDecl) {
3267 // While we still have something to read, read the member-declarations.
Richard Smith752ada82015-11-17 23:32:01 +00003268 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
3269 Tok.isNot(tok::eof)) {
Douglas Gregor9377c822010-06-21 22:31:09 +00003270 // Each iteration of this loop reads one member-declaration.
Alexey Bataev05c25d62015-07-31 08:42:25 +00003271 ParseCXXClassMemberDeclarationWithPragmas(
3272 CurAS, AccessAttrs, static_cast<DeclSpec::TST>(TagType), TagDecl);
Serge Pavlovc4e04a22015-09-19 05:32:57 +00003273 }
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003274 T.consumeClose();
Douglas Gregor9377c822010-06-21 22:31:09 +00003275 } else {
Alexey Bataevee6507d2013-11-18 08:17:37 +00003276 SkipUntil(tok::r_brace);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003277 }
Mike Stump11289f42009-09-09 15:08:12 +00003278
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003279 // If attributes exist after class contents, parse them.
John McCall084e83d2011-03-24 11:26:52 +00003280 ParsedAttributes attrs(AttrFactory);
John McCall53fa7142010-12-24 02:08:15 +00003281 MaybeParseGNUAttributes(attrs);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003282
John McCall08bede42010-05-28 08:11:17 +00003283 if (TagDecl)
Douglas Gregor0be31a22010-07-02 17:43:08 +00003284 Actions.ActOnFinishCXXMemberSpecification(getCurScope(), RecordLoc, TagDecl,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003285 T.getOpenLocation(),
3286 T.getCloseLocation(),
John McCall53fa7142010-12-24 02:08:15 +00003287 attrs.getList());
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003288
Douglas Gregor433e0532012-04-16 18:27:27 +00003289 // C++11 [class.mem]p2:
3290 // Within the class member-specification, the class is regarded as complete
Richard Smith0b3a4622014-11-13 20:01:57 +00003291 // within function bodies, default arguments, exception-specifications, and
Douglas Gregor433e0532012-04-16 18:27:27 +00003292 // brace-or-equal-initializers for non-static data members (including such
3293 // things in nested classes).
Douglas Gregor9377c822010-06-21 22:31:09 +00003294 if (TagDecl && NonNestedClass) {
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003295 // We are not inside a nested class. This class and its nested classes
Douglas Gregor4d87df52008-12-16 21:30:33 +00003296 // are complete and we can parse the delayed portions of method
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00003297 // declarations and the lexed inline method definitions, along with any
3298 // delayed attributes.
Douglas Gregor428119e2010-06-16 23:45:56 +00003299 SourceLocation SavedPrevTokLocation = PrevTokLocation;
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00003300 ParseLexedAttributes(getCurrentClass());
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003301 ParseLexedMethodDeclarations(getCurrentClass());
Richard Smith84973e52012-04-21 18:42:51 +00003302
3303 // We've finished with all pending member declarations.
3304 Actions.ActOnFinishCXXMemberDecls();
3305
Richard Smith938f40b2011-06-11 17:19:42 +00003306 ParseLexedMemberInitializers(getCurrentClass());
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003307 ParseLexedMethodDefs(getCurrentClass());
Douglas Gregor428119e2010-06-16 23:45:56 +00003308 PrevTokLocation = SavedPrevTokLocation;
Reid Klecknerbba3cb92015-03-17 19:00:50 +00003309
3310 // We've finished parsing everything, including default argument
3311 // initializers.
Hans Wennborg99000c22015-08-15 01:18:16 +00003312 Actions.ActOnFinishCXXNonNestedClass(TagDecl);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003313 }
3314
John McCall08bede42010-05-28 08:11:17 +00003315 if (TagDecl)
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00003316 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getRange());
John McCall2ff380a2010-03-17 00:38:33 +00003317
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003318 // Leave the class scope.
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003319 ParsingDef.Pop();
Douglas Gregor7307d6c2008-12-10 06:34:36 +00003320 ClassScope.Exit();
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003321}
Douglas Gregore8381c02008-11-05 04:29:56 +00003322
Richard Smith2ac43ad2013-11-15 23:00:02 +00003323void Parser::DiagnoseUnexpectedNamespace(NamedDecl *D) {
Richard Smithda35e962013-11-09 04:52:51 +00003324 assert(Tok.is(tok::kw_namespace));
3325
3326 // FIXME: Suggest where the close brace should have gone by looking
3327 // at indentation changes within the definition body.
Richard Smith2ac43ad2013-11-15 23:00:02 +00003328 Diag(D->getLocation(),
3329 diag::err_missing_end_of_definition) << D;
Richard Smithda35e962013-11-09 04:52:51 +00003330 Diag(Tok.getLocation(),
Richard Smith2ac43ad2013-11-15 23:00:02 +00003331 diag::note_missing_end_of_definition_before) << D;
Richard Smithda35e962013-11-09 04:52:51 +00003332
3333 // Push '};' onto the token stream to recover.
3334 PP.EnterToken(Tok);
3335
3336 Tok.startToken();
3337 Tok.setLocation(PP.getLocForEndOfToken(PrevTokLocation));
3338 Tok.setKind(tok::semi);
3339 PP.EnterToken(Tok);
3340
3341 Tok.setKind(tok::r_brace);
3342}
3343
Douglas Gregore8381c02008-11-05 04:29:56 +00003344/// ParseConstructorInitializer - Parse a C++ constructor initializer,
3345/// which explicitly initializes the members or base classes of a
3346/// class (C++ [class.base.init]). For example, the three initializers
3347/// after the ':' in the Derived constructor below:
3348///
3349/// @code
3350/// class Base { };
3351/// class Derived : Base {
3352/// int x;
3353/// float f;
3354/// public:
3355/// Derived(float f) : Base(), x(17), f(f) { }
3356/// };
3357/// @endcode
3358///
Mike Stump11289f42009-09-09 15:08:12 +00003359/// [C++] ctor-initializer:
3360/// ':' mem-initializer-list
Douglas Gregore8381c02008-11-05 04:29:56 +00003361///
Mike Stump11289f42009-09-09 15:08:12 +00003362/// [C++] mem-initializer-list:
Douglas Gregor44e7df62011-01-04 00:32:56 +00003363/// mem-initializer ...[opt]
3364/// mem-initializer ...[opt] , mem-initializer-list
John McCall48871652010-08-21 09:40:31 +00003365void Parser::ParseConstructorInitializer(Decl *ConstructorDecl) {
Nico Weber3b00fdc2015-03-07 19:52:39 +00003366 assert(Tok.is(tok::colon) &&
3367 "Constructor initializer always starts with ':'");
Douglas Gregore8381c02008-11-05 04:29:56 +00003368
Nico Weber3b00fdc2015-03-07 19:52:39 +00003369 // Poison the SEH identifiers so they are flagged as illegal in constructor
3370 // initializers.
John Wiegley1c0675e2011-04-28 01:08:34 +00003371 PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
Douglas Gregore8381c02008-11-05 04:29:56 +00003372 SourceLocation ColonLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +00003373
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003374 SmallVector<CXXCtorInitializer*, 4> MemInitializers;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003375 bool AnyErrors = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003376
Douglas Gregore8381c02008-11-05 04:29:56 +00003377 do {
Douglas Gregoreaeeca92010-08-28 00:00:50 +00003378 if (Tok.is(tok::code_completion)) {
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00003379 Actions.CodeCompleteConstructorInitializer(ConstructorDecl,
3380 MemInitializers);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00003381 return cutOffParsing();
Douglas Gregoreaeeca92010-08-28 00:00:50 +00003382 }
Alexey Bataev79de17d2016-01-20 05:25:51 +00003383
3384 MemInitResult MemInit = ParseMemInitializer(ConstructorDecl);
3385 if (!MemInit.isInvalid())
3386 MemInitializers.push_back(MemInit.get());
3387 else
3388 AnyErrors = true;
3389
Douglas Gregore8381c02008-11-05 04:29:56 +00003390 if (Tok.is(tok::comma))
3391 ConsumeToken();
3392 else if (Tok.is(tok::l_brace))
3393 break;
Alexey Bataev79de17d2016-01-20 05:25:51 +00003394 // If the previous initializer was valid and the next token looks like a
3395 // base or member initializer, assume that we're just missing a comma.
3396 else if (!MemInit.isInvalid() &&
3397 Tok.isOneOf(tok::identifier, tok::coloncolon)) {
Douglas Gregorce66d022010-09-07 14:51:08 +00003398 SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation);
3399 Diag(Loc, diag::err_ctor_init_missing_comma)
3400 << FixItHint::CreateInsertion(Loc, ", ");
3401 } else {
Douglas Gregore8381c02008-11-05 04:29:56 +00003402 // Skip over garbage, until we get to '{'. Don't eat the '{'.
Alexey Bataev79de17d2016-01-20 05:25:51 +00003403 if (!MemInit.isInvalid())
3404 Diag(Tok.getLocation(), diag::err_expected_either) << tok::l_brace
3405 << tok::comma;
Alexey Bataevee6507d2013-11-18 08:17:37 +00003406 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
Douglas Gregore8381c02008-11-05 04:29:56 +00003407 break;
3408 }
3409 } while (true);
3410
David Blaikie3fc2f912013-01-17 05:26:25 +00003411 Actions.ActOnMemInitializers(ConstructorDecl, ColonLoc, MemInitializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003412 AnyErrors);
Douglas Gregore8381c02008-11-05 04:29:56 +00003413}
3414
3415/// ParseMemInitializer - Parse a C++ member initializer, which is
3416/// part of a constructor initializer that explicitly initializes one
3417/// member or base class (C++ [class.base.init]). See
3418/// ParseConstructorInitializer for an example.
3419///
3420/// [C++] mem-initializer:
3421/// mem-initializer-id '(' expression-list[opt] ')'
Sebastian Redl3da34892011-06-05 12:23:16 +00003422/// [C++0x] mem-initializer-id braced-init-list
Mike Stump11289f42009-09-09 15:08:12 +00003423///
Douglas Gregore8381c02008-11-05 04:29:56 +00003424/// [C++] mem-initializer-id:
3425/// '::'[opt] nested-name-specifier[opt] class-name
3426/// identifier
Craig Topper9ad7e262014-10-31 06:57:07 +00003427MemInitResult Parser::ParseMemInitializer(Decl *ConstructorDecl) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00003428 // parse '::'[opt] nested-name-specifier[opt]
3429 CXXScopeSpec SS;
David Blaikieefdccaa2016-01-15 23:43:34 +00003430 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false);
Richard Smithaf3b3252017-05-18 19:21:48 +00003431
3432 // : identifier
3433 IdentifierInfo *II = nullptr;
3434 SourceLocation IdLoc = Tok.getLocation();
3435 // : declype(...)
3436 DeclSpec DS(AttrFactory);
3437 // : template_name<...>
John McCallba7bf592010-08-24 05:47:05 +00003438 ParsedType TemplateTypeTy;
Richard Smithaf3b3252017-05-18 19:21:48 +00003439
3440 if (Tok.is(tok::identifier)) {
3441 // Get the identifier. This may be a member name or a class name,
3442 // but we'll let the semantic analysis determine which it is.
3443 II = Tok.getIdentifierInfo();
3444 ConsumeToken();
3445 } else if (Tok.is(tok::annot_decltype)) {
3446 // Get the decltype expression, if there is one.
3447 // Uses of decltype will already have been converted to annot_decltype by
3448 // ParseOptionalCXXScopeSpecifier at this point.
3449 // FIXME: Can we get here with a scope specifier?
3450 ParseDecltypeSpecifier(DS);
3451 } else {
3452 TemplateIdAnnotation *TemplateId = Tok.is(tok::annot_template_id)
3453 ? takeTemplateIdAnnotation(Tok)
3454 : nullptr;
3455 if (TemplateId && (TemplateId->Kind == TNK_Type_template ||
3456 TemplateId->Kind == TNK_Dependent_template_name)) {
Richard Smith62559bd2017-02-01 21:36:38 +00003457 AnnotateTemplateIdTokenAsType(/*IsClassName*/true);
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00003458 assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
John McCallba7bf592010-08-24 05:47:05 +00003459 TemplateTypeTy = getTypeAnnotation(Tok);
Richard Smithaf3b3252017-05-18 19:21:48 +00003460 ConsumeAnnotationToken();
3461 } else {
3462 Diag(Tok, diag::err_expected_member_or_base_name);
3463 return true;
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00003464 }
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00003465 }
Douglas Gregore8381c02008-11-05 04:29:56 +00003466
3467 // Parse the '('.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003468 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
Richard Smith5d164bc2011-10-15 05:09:34 +00003469 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
3470
Sebastian Redla74948d2011-09-24 17:48:25 +00003471 ExprResult InitList = ParseBraceInitializer();
3472 if (InitList.isInvalid())
3473 return true;
3474
3475 SourceLocation EllipsisLoc;
Alp Toker094e5212014-01-05 03:27:11 +00003476 TryConsumeToken(tok::ellipsis, EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00003477
3478 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
David Blaikie186a8892012-01-24 06:03:59 +00003479 TemplateTypeTy, DS, IdLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003480 InitList.get(), EllipsisLoc);
Sebastian Redl3da34892011-06-05 12:23:16 +00003481 } else if(Tok.is(tok::l_paren)) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003482 BalancedDelimiterTracker T(*this, tok::l_paren);
3483 T.consumeOpen();
Douglas Gregore8381c02008-11-05 04:29:56 +00003484
Sebastian Redl3da34892011-06-05 12:23:16 +00003485 // Parse the optional expression-list.
Benjamin Kramerf0623432012-08-23 22:51:59 +00003486 ExprVector ArgExprs;
Sebastian Redl3da34892011-06-05 12:23:16 +00003487 CommaLocsTy CommaLocs;
3488 if (Tok.isNot(tok::r_paren) && ParseExpressionList(ArgExprs, CommaLocs)) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00003489 SkipUntil(tok::r_paren, StopAtSemi);
Sebastian Redl3da34892011-06-05 12:23:16 +00003490 return true;
3491 }
3492
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003493 T.consumeClose();
Sebastian Redl3da34892011-06-05 12:23:16 +00003494
3495 SourceLocation EllipsisLoc;
Alp Toker97650562014-01-10 11:19:30 +00003496 TryConsumeToken(tok::ellipsis, EllipsisLoc);
Sebastian Redl3da34892011-06-05 12:23:16 +00003497
3498 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
David Blaikie186a8892012-01-24 06:03:59 +00003499 TemplateTypeTy, DS, IdLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00003500 T.getOpenLocation(), ArgExprs,
3501 T.getCloseLocation(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00003502 }
3503
Alp Tokerec543272013-12-24 09:48:30 +00003504 if (getLangOpts().CPlusPlus11)
3505 return Diag(Tok, diag::err_expected_either) << tok::l_paren << tok::l_brace;
3506 else
3507 return Diag(Tok, diag::err_expected) << tok::l_paren;
Douglas Gregore8381c02008-11-05 04:29:56 +00003508}
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003509
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003510/// Parse a C++ exception-specification if present (C++0x [except.spec]).
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003511///
Douglas Gregor356513d2008-12-01 18:00:20 +00003512/// exception-specification:
Sebastian Redl965b0e32011-03-05 14:45:16 +00003513/// dynamic-exception-specification
3514/// noexcept-specification
3515///
3516/// noexcept-specification:
3517/// 'noexcept'
3518/// 'noexcept' '(' constant-expression ')'
3519ExceptionSpecificationType
Richard Smith0b3a4622014-11-13 20:01:57 +00003520Parser::tryParseExceptionSpecification(bool Delayed,
Douglas Gregor433e0532012-04-16 18:27:27 +00003521 SourceRange &SpecificationRange,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003522 SmallVectorImpl<ParsedType> &DynamicExceptions,
3523 SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
Richard Smith0b3a4622014-11-13 20:01:57 +00003524 ExprResult &NoexceptExpr,
3525 CachedTokens *&ExceptionSpecTokens) {
Sebastian Redl965b0e32011-03-05 14:45:16 +00003526 ExceptionSpecificationType Result = EST_None;
Hans Wennborgdcfba332015-10-06 23:40:43 +00003527 ExceptionSpecTokens = nullptr;
Richard Smith0b3a4622014-11-13 20:01:57 +00003528
3529 // Handle delayed parsing of exception-specifications.
3530 if (Delayed) {
3531 if (Tok.isNot(tok::kw_throw) && Tok.isNot(tok::kw_noexcept))
3532 return EST_None;
Sebastian Redl965b0e32011-03-05 14:45:16 +00003533
Richard Smith0b3a4622014-11-13 20:01:57 +00003534 // Consume and cache the starting token.
3535 bool IsNoexcept = Tok.is(tok::kw_noexcept);
3536 Token StartTok = Tok;
3537 SpecificationRange = SourceRange(ConsumeToken());
3538
3539 // Check for a '('.
3540 if (!Tok.is(tok::l_paren)) {
3541 // If this is a bare 'noexcept', we're done.
3542 if (IsNoexcept) {
3543 Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
Hans Wennborgdcfba332015-10-06 23:40:43 +00003544 NoexceptExpr = nullptr;
Richard Smith0b3a4622014-11-13 20:01:57 +00003545 return EST_BasicNoexcept;
3546 }
3547
3548 Diag(Tok, diag::err_expected_lparen_after) << "throw";
3549 return EST_DynamicNone;
3550 }
3551
3552 // Cache the tokens for the exception-specification.
3553 ExceptionSpecTokens = new CachedTokens;
3554 ExceptionSpecTokens->push_back(StartTok); // 'throw' or 'noexcept'
3555 ExceptionSpecTokens->push_back(Tok); // '('
3556 SpecificationRange.setEnd(ConsumeParen()); // '('
Richard Smithb1c217e2015-01-13 02:24:58 +00003557
3558 ConsumeAndStoreUntil(tok::r_paren, *ExceptionSpecTokens,
3559 /*StopAtSemi=*/true,
3560 /*ConsumeFinalToken=*/true);
Aaron Ballman580ccaf2016-01-12 21:04:22 +00003561 SpecificationRange.setEnd(ExceptionSpecTokens->back().getLocation());
3562
Richard Smith0b3a4622014-11-13 20:01:57 +00003563 return EST_Unparsed;
3564 }
3565
Sebastian Redl965b0e32011-03-05 14:45:16 +00003566 // See if there's a dynamic specification.
3567 if (Tok.is(tok::kw_throw)) {
3568 Result = ParseDynamicExceptionSpecification(SpecificationRange,
3569 DynamicExceptions,
3570 DynamicExceptionRanges);
3571 assert(DynamicExceptions.size() == DynamicExceptionRanges.size() &&
3572 "Produced different number of exception types and ranges.");
3573 }
3574
3575 // If there's no noexcept specification, we're done.
3576 if (Tok.isNot(tok::kw_noexcept))
3577 return Result;
3578
Richard Smithb15c11c2011-10-17 23:06:20 +00003579 Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
3580
Sebastian Redl965b0e32011-03-05 14:45:16 +00003581 // If we already had a dynamic specification, parse the noexcept for,
3582 // recovery, but emit a diagnostic and don't store the results.
3583 SourceRange NoexceptRange;
3584 ExceptionSpecificationType NoexceptType = EST_None;
3585
3586 SourceLocation KeywordLoc = ConsumeToken();
3587 if (Tok.is(tok::l_paren)) {
3588 // There is an argument.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003589 BalancedDelimiterTracker T(*this, tok::l_paren);
3590 T.consumeOpen();
Sebastian Redl965b0e32011-03-05 14:45:16 +00003591 NoexceptExpr = ParseConstantExpression();
Serge Pavlov3739f5e72015-06-29 17:50:19 +00003592 T.consumeClose();
Serge Pavlov3739f5e72015-06-29 17:50:19 +00003593 if (!NoexceptExpr.isInvalid()) {
Richard Smitheaf11ad2018-05-03 03:58:32 +00003594 NoexceptExpr = Actions.ActOnNoexceptSpec(KeywordLoc, NoexceptExpr.get(),
3595 NoexceptType);
Serge Pavlov3739f5e72015-06-29 17:50:19 +00003596 NoexceptRange = SourceRange(KeywordLoc, T.getCloseLocation());
3597 } else {
Malcolm Parsonsa3220ce2017-01-12 16:11:28 +00003598 NoexceptType = EST_BasicNoexcept;
Serge Pavlov3739f5e72015-06-29 17:50:19 +00003599 }
Sebastian Redl965b0e32011-03-05 14:45:16 +00003600 } else {
3601 // There is no argument.
3602 NoexceptType = EST_BasicNoexcept;
3603 NoexceptRange = SourceRange(KeywordLoc, KeywordLoc);
3604 }
3605
3606 if (Result == EST_None) {
3607 SpecificationRange = NoexceptRange;
3608 Result = NoexceptType;
3609
3610 // If there's a dynamic specification after a noexcept specification,
3611 // parse that and ignore the results.
3612 if (Tok.is(tok::kw_throw)) {
3613 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
3614 ParseDynamicExceptionSpecification(NoexceptRange, DynamicExceptions,
3615 DynamicExceptionRanges);
3616 }
3617 } else {
3618 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
3619 }
3620
3621 return Result;
3622}
3623
Richard Smith8ca78a12013-06-13 02:02:51 +00003624static void diagnoseDynamicExceptionSpecification(
Craig Toppere335f252015-10-04 04:53:55 +00003625 Parser &P, SourceRange Range, bool IsNoexcept) {
Richard Smith8ca78a12013-06-13 02:02:51 +00003626 if (P.getLangOpts().CPlusPlus11) {
3627 const char *Replacement = IsNoexcept ? "noexcept" : "noexcept(false)";
Richard Smith82da19d2016-12-08 02:49:07 +00003628 P.Diag(Range.getBegin(),
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003629 P.getLangOpts().CPlusPlus17 && !IsNoexcept
Richard Smith82da19d2016-12-08 02:49:07 +00003630 ? diag::ext_dynamic_exception_spec
3631 : diag::warn_exception_spec_deprecated)
3632 << Range;
Richard Smith8ca78a12013-06-13 02:02:51 +00003633 P.Diag(Range.getBegin(), diag::note_exception_spec_deprecated)
3634 << Replacement << FixItHint::CreateReplacement(Range, Replacement);
3635 }
3636}
3637
Sebastian Redl965b0e32011-03-05 14:45:16 +00003638/// ParseDynamicExceptionSpecification - Parse a C++
3639/// dynamic-exception-specification (C++ [except.spec]).
3640///
3641/// dynamic-exception-specification:
Douglas Gregor356513d2008-12-01 18:00:20 +00003642/// 'throw' '(' type-id-list [opt] ')'
3643/// [MS] 'throw' '(' '...' ')'
Mike Stump11289f42009-09-09 15:08:12 +00003644///
Douglas Gregor356513d2008-12-01 18:00:20 +00003645/// type-id-list:
Douglas Gregor830837d2010-12-20 23:57:46 +00003646/// type-id ... [opt]
3647/// type-id-list ',' type-id ... [opt]
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003648///
Sebastian Redl965b0e32011-03-05 14:45:16 +00003649ExceptionSpecificationType Parser::ParseDynamicExceptionSpecification(
3650 SourceRange &SpecificationRange,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003651 SmallVectorImpl<ParsedType> &Exceptions,
3652 SmallVectorImpl<SourceRange> &Ranges) {
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003653 assert(Tok.is(tok::kw_throw) && "expected throw");
Mike Stump11289f42009-09-09 15:08:12 +00003654
Sebastian Redl965b0e32011-03-05 14:45:16 +00003655 SpecificationRange.setBegin(ConsumeToken());
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003656 BalancedDelimiterTracker T(*this, tok::l_paren);
3657 if (T.consumeOpen()) {
Sebastian Redl965b0e32011-03-05 14:45:16 +00003658 Diag(Tok, diag::err_expected_lparen_after) << "throw";
3659 SpecificationRange.setEnd(SpecificationRange.getBegin());
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003660 return EST_DynamicNone;
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003661 }
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003662
Douglas Gregor356513d2008-12-01 18:00:20 +00003663 // Parse throw(...), a Microsoft extension that means "this function
3664 // can throw anything".
3665 if (Tok.is(tok::ellipsis)) {
3666 SourceLocation EllipsisLoc = ConsumeToken();
David Blaikiebbafb8a2012-03-11 07:00:24 +00003667 if (!getLangOpts().MicrosoftExt)
Douglas Gregor356513d2008-12-01 18:00:20 +00003668 Diag(EllipsisLoc, diag::ext_ellipsis_exception_spec);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003669 T.consumeClose();
3670 SpecificationRange.setEnd(T.getCloseLocation());
Richard Smith8ca78a12013-06-13 02:02:51 +00003671 diagnoseDynamicExceptionSpecification(*this, SpecificationRange, false);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003672 return EST_MSAny;
Douglas Gregor356513d2008-12-01 18:00:20 +00003673 }
3674
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003675 // Parse the sequence of type-ids.
Sebastian Redld6434562009-05-29 18:02:33 +00003676 SourceRange Range;
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003677 while (Tok.isNot(tok::r_paren)) {
Sebastian Redld6434562009-05-29 18:02:33 +00003678 TypeResult Res(ParseTypeName(&Range));
Sebastian Redl965b0e32011-03-05 14:45:16 +00003679
Douglas Gregor830837d2010-12-20 23:57:46 +00003680 if (Tok.is(tok::ellipsis)) {
3681 // C++0x [temp.variadic]p5:
3682 // - In a dynamic-exception-specification (15.4); the pattern is a
3683 // type-id.
3684 SourceLocation Ellipsis = ConsumeToken();
Sebastian Redl965b0e32011-03-05 14:45:16 +00003685 Range.setEnd(Ellipsis);
Douglas Gregor830837d2010-12-20 23:57:46 +00003686 if (!Res.isInvalid())
3687 Res = Actions.ActOnPackExpansion(Res.get(), Ellipsis);
3688 }
Sebastian Redl965b0e32011-03-05 14:45:16 +00003689
Sebastian Redld6434562009-05-29 18:02:33 +00003690 if (!Res.isInvalid()) {
Sebastian Redl2b9cacb2009-04-29 17:30:04 +00003691 Exceptions.push_back(Res.get());
Sebastian Redld6434562009-05-29 18:02:33 +00003692 Ranges.push_back(Range);
3693 }
Alp Toker97650562014-01-10 11:19:30 +00003694
3695 if (!TryConsumeToken(tok::comma))
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003696 break;
3697 }
3698
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003699 T.consumeClose();
3700 SpecificationRange.setEnd(T.getCloseLocation());
Richard Smith8ca78a12013-06-13 02:02:51 +00003701 diagnoseDynamicExceptionSpecification(*this, SpecificationRange,
3702 Exceptions.empty());
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003703 return Exceptions.empty() ? EST_DynamicNone : EST_Dynamic;
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003704}
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003705
Douglas Gregor7fb25412010-10-01 18:44:50 +00003706/// ParseTrailingReturnType - Parse a trailing return type on a new-style
3707/// function declaration.
Richard Smithe303e352018-02-02 22:24:54 +00003708TypeResult Parser::ParseTrailingReturnType(SourceRange &Range,
3709 bool MayBeFollowedByDirectInit) {
Douglas Gregor7fb25412010-10-01 18:44:50 +00003710 assert(Tok.is(tok::arrow) && "expected arrow");
3711
3712 ConsumeToken();
3713
Richard Smithe303e352018-02-02 22:24:54 +00003714 return ParseTypeName(&Range, MayBeFollowedByDirectInit
3715 ? DeclaratorContext::TrailingReturnVarContext
3716 : DeclaratorContext::TrailingReturnContext);
Douglas Gregor7fb25412010-10-01 18:44:50 +00003717}
3718
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003719/// We have just started parsing the definition of a new class,
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003720/// so push that class onto our stack of classes that is currently
3721/// being parsed.
John McCallc1465822011-02-14 07:13:47 +00003722Sema::ParsingClassState
John McCalldb632ac2012-09-25 07:32:39 +00003723Parser::PushParsingClass(Decl *ClassDecl, bool NonNestedClass,
3724 bool IsInterface) {
Douglas Gregoredf8f392010-01-16 20:52:59 +00003725 assert((NonNestedClass || !ClassStack.empty()) &&
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003726 "Nested class without outer class");
John McCalldb632ac2012-09-25 07:32:39 +00003727 ClassStack.push(new ParsingClass(ClassDecl, NonNestedClass, IsInterface));
John McCallc1465822011-02-14 07:13:47 +00003728 return Actions.PushParsingClass();
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003729}
3730
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003731/// Deallocate the given parsed class and all of its nested
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003732/// classes.
3733void Parser::DeallocateParsedClasses(Parser::ParsingClass *Class) {
Douglas Gregorefc46952010-10-12 16:25:54 +00003734 for (unsigned I = 0, N = Class->LateParsedDeclarations.size(); I != N; ++I)
3735 delete Class->LateParsedDeclarations[I];
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003736 delete Class;
3737}
3738
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003739/// Pop the top class of the stack of classes that are
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003740/// currently being parsed.
3741///
3742/// This routine should be called when we have finished parsing the
3743/// definition of a class, but have not yet popped the Scope
3744/// associated with the class's definition.
John McCallc1465822011-02-14 07:13:47 +00003745void Parser::PopParsingClass(Sema::ParsingClassState state) {
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003746 assert(!ClassStack.empty() && "Mismatched push/pop for class parsing");
Mike Stump11289f42009-09-09 15:08:12 +00003747
John McCallc1465822011-02-14 07:13:47 +00003748 Actions.PopParsingClass(state);
3749
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003750 ParsingClass *Victim = ClassStack.top();
3751 ClassStack.pop();
3752 if (Victim->TopLevelClass) {
3753 // Deallocate all of the nested classes of this class,
3754 // recursively: we don't need to keep any of this information.
3755 DeallocateParsedClasses(Victim);
3756 return;
Mike Stump11289f42009-09-09 15:08:12 +00003757 }
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003758 assert(!ClassStack.empty() && "Missing top-level class?");
3759
Douglas Gregorefc46952010-10-12 16:25:54 +00003760 if (Victim->LateParsedDeclarations.empty()) {
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003761 // The victim is a nested class, but we will not need to perform
3762 // any processing after the definition of this class since it has
3763 // no members whose handling was delayed. Therefore, we can just
3764 // remove this nested class.
Douglas Gregorefc46952010-10-12 16:25:54 +00003765 DeallocateParsedClasses(Victim);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003766 return;
3767 }
3768
3769 // This nested class has some members that will need to be processed
3770 // after the top-level class is completely defined. Therefore, add
3771 // it to the list of nested classes within its parent.
Douglas Gregor0be31a22010-07-02 17:43:08 +00003772 assert(getCurScope()->isClassScope() && "Nested class outside of class scope?");
Douglas Gregorefc46952010-10-12 16:25:54 +00003773 ClassStack.top()->LateParsedDeclarations.push_back(new LateParsedClass(this, Victim));
Douglas Gregor0be31a22010-07-02 17:43:08 +00003774 Victim->TemplateScope = getCurScope()->getParent()->isTemplateParamScope();
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003775}
Alexis Hunt96d5c762009-11-21 08:43:09 +00003776
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003777/// Try to parse an 'identifier' which appears within an attribute-token.
Richard Smith3dff2512012-04-10 03:25:07 +00003778///
3779/// \return the parsed identifier on success, and 0 if the next token is not an
3780/// attribute-token.
3781///
3782/// C++11 [dcl.attr.grammar]p3:
3783/// If a keyword or an alternative token that satisfies the syntactic
3784/// requirements of an identifier is contained in an attribute-token,
3785/// it is considered an identifier.
3786IdentifierInfo *Parser::TryParseCXX11AttributeIdentifier(SourceLocation &Loc) {
3787 switch (Tok.getKind()) {
3788 default:
3789 // Identifiers and keywords have identifier info attached.
David Majnemerd5271992015-01-09 18:09:39 +00003790 if (!Tok.isAnnotation()) {
3791 if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
3792 Loc = ConsumeToken();
3793 return II;
3794 }
Richard Smith3dff2512012-04-10 03:25:07 +00003795 }
Craig Topper161e4db2014-05-21 06:02:52 +00003796 return nullptr;
Richard Smith3dff2512012-04-10 03:25:07 +00003797
3798 case tok::ampamp: // 'and'
3799 case tok::pipe: // 'bitor'
3800 case tok::pipepipe: // 'or'
3801 case tok::caret: // 'xor'
3802 case tok::tilde: // 'compl'
3803 case tok::amp: // 'bitand'
3804 case tok::ampequal: // 'and_eq'
3805 case tok::pipeequal: // 'or_eq'
3806 case tok::caretequal: // 'xor_eq'
3807 case tok::exclaim: // 'not'
3808 case tok::exclaimequal: // 'not_eq'
3809 // Alternative tokens do not have identifier info, but their spelling
3810 // starts with an alphabetical character.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003811 SmallString<8> SpellingBuf;
Benjamin Kramer60be5632015-03-29 19:25:07 +00003812 SourceLocation SpellingLoc =
3813 PP.getSourceManager().getSpellingLoc(Tok.getLocation());
3814 StringRef Spelling = PP.getSpelling(SpellingLoc, SpellingBuf);
Jordan Rosea7d03842013-02-08 22:30:41 +00003815 if (isLetter(Spelling[0])) {
Richard Smith3dff2512012-04-10 03:25:07 +00003816 Loc = ConsumeToken();
Benjamin Kramer5c17f9c2012-04-22 20:43:30 +00003817 return &PP.getIdentifierTable().get(Spelling);
Richard Smith3dff2512012-04-10 03:25:07 +00003818 }
Craig Topper161e4db2014-05-21 06:02:52 +00003819 return nullptr;
Richard Smith3dff2512012-04-10 03:25:07 +00003820 }
3821}
3822
Michael Han23214e52012-10-03 01:56:22 +00003823static bool IsBuiltInOrStandardCXX11Attribute(IdentifierInfo *AttrName,
Aaron Ballman606093a2017-10-15 15:01:42 +00003824 IdentifierInfo *ScopeName) {
Michael Han23214e52012-10-03 01:56:22 +00003825 switch (AttributeList::getKind(AttrName, ScopeName,
3826 AttributeList::AS_CXX11)) {
3827 case AttributeList::AT_CarriesDependency:
Aaron Ballman35f94212014-04-14 16:03:22 +00003828 case AttributeList::AT_Deprecated:
Michael Han23214e52012-10-03 01:56:22 +00003829 case AttributeList::AT_FallThrough:
Hans Wennborgdcfba332015-10-06 23:40:43 +00003830 case AttributeList::AT_CXX11NoReturn:
Michael Han23214e52012-10-03 01:56:22 +00003831 return true;
Aaron Ballmane7964782016-03-07 22:44:55 +00003832 case AttributeList::AT_WarnUnusedResult:
3833 return !ScopeName && AttrName->getName().equals("nodiscard");
Nico Weberac03bce2016-08-23 19:59:55 +00003834 case AttributeList::AT_Unused:
3835 return !ScopeName && AttrName->getName().equals("maybe_unused");
Michael Han23214e52012-10-03 01:56:22 +00003836 default:
3837 return false;
3838 }
3839}
3840
Aaron Ballmanb8e20392014-03-31 17:32:39 +00003841/// ParseCXX11AttributeArgs -- Parse a C++11 attribute-argument-clause.
3842///
3843/// [C++11] attribute-argument-clause:
3844/// '(' balanced-token-seq ')'
3845///
3846/// [C++11] balanced-token-seq:
3847/// balanced-token
3848/// balanced-token-seq balanced-token
3849///
3850/// [C++11] balanced-token:
3851/// '(' balanced-token-seq ')'
3852/// '[' balanced-token-seq ']'
3853/// '{' balanced-token-seq '}'
3854/// any token but '(', ')', '[', ']', '{', or '}'
3855bool Parser::ParseCXX11AttributeArgs(IdentifierInfo *AttrName,
3856 SourceLocation AttrNameLoc,
3857 ParsedAttributes &Attrs,
3858 SourceLocation *EndLoc,
3859 IdentifierInfo *ScopeName,
3860 SourceLocation ScopeLoc) {
3861 assert(Tok.is(tok::l_paren) && "Not a C++11 attribute argument list");
Aaron Ballman35f94212014-04-14 16:03:22 +00003862 SourceLocation LParenLoc = Tok.getLocation();
Aaron Ballman606093a2017-10-15 15:01:42 +00003863 const LangOptions &LO = getLangOpts();
3864 AttributeList::Syntax Syntax =
3865 LO.CPlusPlus ? AttributeList::AS_CXX11 : AttributeList::AS_C2x;
Aaron Ballmanb8e20392014-03-31 17:32:39 +00003866
3867 // If the attribute isn't known, we will not attempt to parse any
3868 // arguments.
Aaron Ballman606093a2017-10-15 15:01:42 +00003869 if (!hasAttribute(LO.CPlusPlus ? AttrSyntax::CXX : AttrSyntax::C, ScopeName,
3870 AttrName, getTargetInfo(), getLangOpts())) {
Aaron Ballmanb8e20392014-03-31 17:32:39 +00003871 // Eat the left paren, then skip to the ending right paren.
3872 ConsumeParen();
3873 SkipUntil(tok::r_paren);
3874 return false;
3875 }
3876
Alex Lorenzd5d27e12017-03-01 18:06:25 +00003877 if (ScopeName && ScopeName->getName() == "gnu") {
Aaron Ballmanb8e20392014-03-31 17:32:39 +00003878 // GNU-scoped attributes have some special cases to handle GNU-specific
3879 // behaviors.
3880 ParseGNUAttributeArgs(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
Aaron Ballman606093a2017-10-15 15:01:42 +00003881 ScopeLoc, Syntax, nullptr);
Alex Lorenzd5d27e12017-03-01 18:06:25 +00003882 return true;
3883 }
3884
3885 unsigned NumArgs;
3886 // Some Clang-scoped attributes have some special parsing behavior.
3887 if (ScopeName && ScopeName->getName() == "clang")
3888 NumArgs =
3889 ParseClangAttributeArgs(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
Aaron Ballman606093a2017-10-15 15:01:42 +00003890 ScopeLoc, Syntax);
Alex Lorenzd5d27e12017-03-01 18:06:25 +00003891 else
3892 NumArgs =
Aaron Ballman35f94212014-04-14 16:03:22 +00003893 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc,
Aaron Ballman606093a2017-10-15 15:01:42 +00003894 ScopeName, ScopeLoc, Syntax);
Alex Lorenzd5d27e12017-03-01 18:06:25 +00003895
3896 const AttributeList *Attr = Attrs.getList();
3897 if (Attr && IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName)) {
3898 // If the attribute is a standard or built-in attribute and we are
3899 // parsing an argument list, we need to determine whether this attribute
3900 // was allowed to have an argument list (such as [[deprecated]]), and how
3901 // many arguments were parsed (so we can diagnose on [[deprecated()]]).
3902 if (Attr->getMaxArgs() && !NumArgs) {
3903 // The attribute was allowed to have arguments, but none were provided
3904 // even though the attribute parsed successfully. This is an error.
3905 Diag(LParenLoc, diag::err_attribute_requires_arguments) << AttrName;
3906 Attr->setInvalid(true);
3907 } else if (!Attr->getMaxArgs()) {
3908 // The attribute parsed successfully, but was not allowed to have any
3909 // arguments. It doesn't matter whether any were provided -- the
3910 // presence of the argument list (even if empty) is diagnosed.
3911 Diag(LParenLoc, diag::err_cxx11_attribute_forbids_arguments)
3912 << AttrName
3913 << FixItHint::CreateRemoval(SourceRange(LParenLoc, *EndLoc));
3914 Attr->setInvalid(true);
Aaron Ballman35f94212014-04-14 16:03:22 +00003915 }
3916 }
Aaron Ballmanb8e20392014-03-31 17:32:39 +00003917 return true;
3918}
3919
Aaron Ballman606093a2017-10-15 15:01:42 +00003920/// ParseCXX11AttributeSpecifier - Parse a C++11 or C2x attribute-specifier.
Alexis Hunt96d5c762009-11-21 08:43:09 +00003921///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003922/// [C++11] attribute-specifier:
Alexis Hunt96d5c762009-11-21 08:43:09 +00003923/// '[' '[' attribute-list ']' ']'
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00003924/// alignment-specifier
Alexis Hunt96d5c762009-11-21 08:43:09 +00003925///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003926/// [C++11] attribute-list:
Alexis Hunt96d5c762009-11-21 08:43:09 +00003927/// attribute[opt]
3928/// attribute-list ',' attribute[opt]
Richard Smith3dff2512012-04-10 03:25:07 +00003929/// attribute '...'
3930/// attribute-list ',' attribute '...'
Alexis Hunt96d5c762009-11-21 08:43:09 +00003931///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003932/// [C++11] attribute:
Alexis Hunt96d5c762009-11-21 08:43:09 +00003933/// attribute-token attribute-argument-clause[opt]
3934///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003935/// [C++11] attribute-token:
Alexis Hunt96d5c762009-11-21 08:43:09 +00003936/// identifier
3937/// attribute-scoped-token
3938///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003939/// [C++11] attribute-scoped-token:
Alexis Hunt96d5c762009-11-21 08:43:09 +00003940/// attribute-namespace '::' identifier
3941///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003942/// [C++11] attribute-namespace:
Alexis Hunt96d5c762009-11-21 08:43:09 +00003943/// identifier
Richard Smith3dff2512012-04-10 03:25:07 +00003944void Parser::ParseCXX11AttributeSpecifier(ParsedAttributes &attrs,
Peter Collingbourne49eedec2011-09-29 18:04:05 +00003945 SourceLocation *endLoc) {
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00003946 if (Tok.is(tok::kw_alignas)) {
Richard Smithf679b5b2011-10-14 20:48:27 +00003947 Diag(Tok.getLocation(), diag::warn_cxx98_compat_alignas);
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00003948 ParseAlignmentSpecifier(attrs, endLoc);
3949 return;
3950 }
3951
Aaron Ballman606093a2017-10-15 15:01:42 +00003952 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square) &&
3953 "Not a double square bracket attribute list");
Alexis Hunt96d5c762009-11-21 08:43:09 +00003954
Richard Smithf679b5b2011-10-14 20:48:27 +00003955 Diag(Tok.getLocation(), diag::warn_cxx98_compat_attribute);
3956
Alexis Hunt96d5c762009-11-21 08:43:09 +00003957 ConsumeBracket();
3958 ConsumeBracket();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003959
Richard Smithb7d7a042016-06-24 12:15:12 +00003960 SourceLocation CommonScopeLoc;
3961 IdentifierInfo *CommonScopeName = nullptr;
3962 if (Tok.is(tok::kw_using)) {
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003963 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
Richard Smithb7d7a042016-06-24 12:15:12 +00003964 ? diag::warn_cxx14_compat_using_attribute_ns
3965 : diag::ext_using_attribute_ns);
3966 ConsumeToken();
3967
3968 CommonScopeName = TryParseCXX11AttributeIdentifier(CommonScopeLoc);
3969 if (!CommonScopeName) {
3970 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
3971 SkipUntil(tok::r_square, tok::colon, StopBeforeMatch);
3972 }
3973 if (!TryConsumeToken(tok::colon) && CommonScopeName)
3974 Diag(Tok.getLocation(), diag::err_expected) << tok::colon;
3975 }
3976
Richard Smith10876ef2013-01-17 01:30:42 +00003977 llvm::SmallDenseMap<IdentifierInfo*, SourceLocation, 4> SeenAttrs;
3978
Richard Smith3dff2512012-04-10 03:25:07 +00003979 while (Tok.isNot(tok::r_square)) {
Alexis Hunt96d5c762009-11-21 08:43:09 +00003980 // attribute not present
Alp Toker97650562014-01-10 11:19:30 +00003981 if (TryConsumeToken(tok::comma))
Alexis Hunt96d5c762009-11-21 08:43:09 +00003982 continue;
Alexis Hunt96d5c762009-11-21 08:43:09 +00003983
Richard Smith3dff2512012-04-10 03:25:07 +00003984 SourceLocation ScopeLoc, AttrLoc;
Craig Topper161e4db2014-05-21 06:02:52 +00003985 IdentifierInfo *ScopeName = nullptr, *AttrName = nullptr;
Richard Smith3dff2512012-04-10 03:25:07 +00003986
3987 AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
3988 if (!AttrName)
3989 // Break out to the "expected ']'" diagnostic.
3990 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003991
Alexis Hunt96d5c762009-11-21 08:43:09 +00003992 // scoped attribute
Alp Toker97650562014-01-10 11:19:30 +00003993 if (TryConsumeToken(tok::coloncolon)) {
Richard Smith3dff2512012-04-10 03:25:07 +00003994 ScopeName = AttrName;
3995 ScopeLoc = AttrLoc;
3996
3997 AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
3998 if (!AttrName) {
Alp Tokerec543272013-12-24 09:48:30 +00003999 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
Alexey Bataevee6507d2013-11-18 08:17:37 +00004000 SkipUntil(tok::r_square, tok::comma, StopAtSemi | StopBeforeMatch);
Alexis Hunt96d5c762009-11-21 08:43:09 +00004001 continue;
4002 }
Alexis Hunt96d5c762009-11-21 08:43:09 +00004003 }
4004
Richard Smithb7d7a042016-06-24 12:15:12 +00004005 if (CommonScopeName) {
4006 if (ScopeName) {
4007 Diag(ScopeLoc, diag::err_using_attribute_ns_conflict)
4008 << SourceRange(CommonScopeLoc);
4009 } else {
4010 ScopeName = CommonScopeName;
4011 ScopeLoc = CommonScopeLoc;
4012 }
4013 }
4014
Aaron Ballmanb8e20392014-03-31 17:32:39 +00004015 bool StandardAttr = IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName);
Alexis Hunt96d5c762009-11-21 08:43:09 +00004016 bool AttrParsed = false;
Alexis Hunt96d5c762009-11-21 08:43:09 +00004017
Richard Smith10876ef2013-01-17 01:30:42 +00004018 if (StandardAttr &&
4019 !SeenAttrs.insert(std::make_pair(AttrName, AttrLoc)).second)
4020 Diag(AttrLoc, diag::err_cxx11_attribute_repeated)
Aaron Ballmanb8e20392014-03-31 17:32:39 +00004021 << AttrName << SourceRange(SeenAttrs[AttrName]);
Richard Smith10876ef2013-01-17 01:30:42 +00004022
Michael Han23214e52012-10-03 01:56:22 +00004023 // Parse attribute arguments
Aaron Ballman35f94212014-04-14 16:03:22 +00004024 if (Tok.is(tok::l_paren))
Aaron Ballmanb8e20392014-03-31 17:32:39 +00004025 AttrParsed = ParseCXX11AttributeArgs(AttrName, AttrLoc, attrs, endLoc,
4026 ScopeName, ScopeLoc);
Michael Han23214e52012-10-03 01:56:22 +00004027
4028 if (!AttrParsed)
Aaron Ballman606093a2017-10-15 15:01:42 +00004029 attrs.addNew(
4030 AttrName,
4031 SourceRange(ScopeLoc.isValid() ? ScopeLoc : AttrLoc, AttrLoc),
4032 ScopeName, ScopeLoc, nullptr, 0,
4033 getLangOpts().CPlusPlus ? AttributeList::AS_CXX11
4034 : AttributeList::AS_C2x);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004035
Alp Toker97650562014-01-10 11:19:30 +00004036 if (TryConsumeToken(tok::ellipsis))
Michael Han23214e52012-10-03 01:56:22 +00004037 Diag(Tok, diag::err_cxx11_attribute_forbids_ellipsis)
Richard Trieub4025802018-03-28 04:16:13 +00004038 << AttrName;
Alexis Hunt96d5c762009-11-21 08:43:09 +00004039 }
4040
Alp Toker383d2c42014-01-01 03:08:43 +00004041 if (ExpectAndConsume(tok::r_square))
Alexey Bataevee6507d2013-11-18 08:17:37 +00004042 SkipUntil(tok::r_square);
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004043 if (endLoc)
4044 *endLoc = Tok.getLocation();
Alp Toker383d2c42014-01-01 03:08:43 +00004045 if (ExpectAndConsume(tok::r_square))
Alexey Bataevee6507d2013-11-18 08:17:37 +00004046 SkipUntil(tok::r_square);
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004047}
Alexis Hunt96d5c762009-11-21 08:43:09 +00004048
Aaron Ballman606093a2017-10-15 15:01:42 +00004049/// ParseCXX11Attributes - Parse a C++11 or C2x attribute-specifier-seq.
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004050///
4051/// attribute-specifier-seq:
4052/// attribute-specifier-seq[opt] attribute-specifier
Richard Smith3dff2512012-04-10 03:25:07 +00004053void Parser::ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004054 SourceLocation *endLoc) {
Aaron Ballman606093a2017-10-15 15:01:42 +00004055 assert(standardAttributesAllowed());
Richard Smith4cabd042013-02-22 09:15:49 +00004056
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004057 SourceLocation StartLoc = Tok.getLocation(), Loc;
4058 if (!endLoc)
4059 endLoc = &Loc;
4060
Douglas Gregor6f981002011-10-07 20:35:25 +00004061 do {
Richard Smith3dff2512012-04-10 03:25:07 +00004062 ParseCXX11AttributeSpecifier(attrs, endLoc);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004063 } while (isCXX11AttributeSpecifier());
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004064
4065 attrs.Range = SourceRange(StartLoc, *endLoc);
Alexis Hunt96d5c762009-11-21 08:43:09 +00004066}
4067
Richard Smithc2c8bb82013-10-15 01:34:54 +00004068void Parser::DiagnoseAndSkipCXX11Attributes() {
Richard Smithc2c8bb82013-10-15 01:34:54 +00004069 // Start and end location of an attribute or an attribute list.
4070 SourceLocation StartLoc = Tok.getLocation();
Richard Smith955bf012014-06-19 11:42:00 +00004071 SourceLocation EndLoc = SkipCXX11Attributes();
4072
4073 if (EndLoc.isValid()) {
4074 SourceRange Range(StartLoc, EndLoc);
4075 Diag(StartLoc, diag::err_attributes_not_allowed)
4076 << Range;
4077 }
4078}
4079
4080SourceLocation Parser::SkipCXX11Attributes() {
Richard Smithc2c8bb82013-10-15 01:34:54 +00004081 SourceLocation EndLoc;
4082
Richard Smith955bf012014-06-19 11:42:00 +00004083 if (!isCXX11AttributeSpecifier())
4084 return EndLoc;
4085
Richard Smithc2c8bb82013-10-15 01:34:54 +00004086 do {
4087 if (Tok.is(tok::l_square)) {
4088 BalancedDelimiterTracker T(*this, tok::l_square);
4089 T.consumeOpen();
4090 T.skipToEnd();
4091 EndLoc = T.getCloseLocation();
4092 } else {
4093 assert(Tok.is(tok::kw_alignas) && "not an attribute specifier");
4094 ConsumeToken();
4095 BalancedDelimiterTracker T(*this, tok::l_paren);
4096 if (!T.consumeOpen())
4097 T.skipToEnd();
4098 EndLoc = T.getCloseLocation();
4099 }
4100 } while (isCXX11AttributeSpecifier());
4101
Richard Smith955bf012014-06-19 11:42:00 +00004102 return EndLoc;
Richard Smithc2c8bb82013-10-15 01:34:54 +00004103}
4104
Nico Weber05e1dad2016-09-03 03:25:22 +00004105/// Parse uuid() attribute when it appears in a [] Microsoft attribute.
4106void Parser::ParseMicrosoftUuidAttributeArgs(ParsedAttributes &Attrs) {
4107 assert(Tok.is(tok::identifier) && "Not a Microsoft attribute list");
4108 IdentifierInfo *UuidIdent = Tok.getIdentifierInfo();
4109 assert(UuidIdent->getName() == "uuid" && "Not a Microsoft attribute list");
4110
4111 SourceLocation UuidLoc = Tok.getLocation();
4112 ConsumeToken();
4113
4114 // Ignore the left paren location for now.
4115 BalancedDelimiterTracker T(*this, tok::l_paren);
4116 if (T.consumeOpen()) {
4117 Diag(Tok, diag::err_expected) << tok::l_paren;
4118 return;
4119 }
4120
4121 ArgsVector ArgExprs;
4122 if (Tok.is(tok::string_literal)) {
4123 // Easy case: uuid("...") -- quoted string.
4124 ExprResult StringResult = ParseStringLiteralExpression();
4125 if (StringResult.isInvalid())
4126 return;
4127 ArgExprs.push_back(StringResult.get());
4128 } else {
4129 // something like uuid({000000A0-0000-0000-C000-000000000049}) -- no
4130 // quotes in the parens. Just append the spelling of all tokens encountered
4131 // until the closing paren.
4132
4133 SmallString<42> StrBuffer; // 2 "", 36 bytes UUID, 2 optional {}, 1 nul
4134 StrBuffer += "\"";
4135
4136 // Since none of C++'s keywords match [a-f]+, accepting just tok::l_brace,
4137 // tok::r_brace, tok::minus, tok::identifier (think C000) and
4138 // tok::numeric_constant (0000) should be enough. But the spelling of the
4139 // uuid argument is checked later anyways, so there's no harm in accepting
4140 // almost anything here.
4141 // cl is very strict about whitespace in this form and errors out if any
4142 // is present, so check the space flags on the tokens.
4143 SourceLocation StartLoc = Tok.getLocation();
4144 while (Tok.isNot(tok::r_paren)) {
4145 if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
4146 Diag(Tok, diag::err_attribute_uuid_malformed_guid);
4147 SkipUntil(tok::r_paren, StopAtSemi);
4148 return;
4149 }
4150 SmallString<16> SpellingBuffer;
4151 SpellingBuffer.resize(Tok.getLength() + 1);
4152 bool Invalid = false;
4153 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
4154 if (Invalid) {
4155 SkipUntil(tok::r_paren, StopAtSemi);
4156 return;
4157 }
4158 StrBuffer += TokSpelling;
4159 ConsumeAnyToken();
4160 }
4161 StrBuffer += "\"";
4162
4163 if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
4164 Diag(Tok, diag::err_attribute_uuid_malformed_guid);
4165 ConsumeParen();
4166 return;
4167 }
4168
4169 // Pretend the user wrote the appropriate string literal here.
4170 // ActOnStringLiteral() copies the string data into the literal, so it's
4171 // ok that the Token points to StrBuffer.
4172 Token Toks[1];
4173 Toks[0].startToken();
4174 Toks[0].setKind(tok::string_literal);
4175 Toks[0].setLocation(StartLoc);
4176 Toks[0].setLiteralData(StrBuffer.data());
4177 Toks[0].setLength(StrBuffer.size());
4178 StringLiteral *UuidString =
4179 cast<StringLiteral>(Actions.ActOnStringLiteral(Toks, nullptr).get());
4180 ArgExprs.push_back(UuidString);
4181 }
4182
4183 if (!T.consumeClose()) {
Nico Weber05e1dad2016-09-03 03:25:22 +00004184 Attrs.addNew(UuidIdent, SourceRange(UuidLoc, T.getCloseLocation()), nullptr,
4185 SourceLocation(), ArgExprs.data(), ArgExprs.size(),
4186 AttributeList::AS_Microsoft);
4187 }
4188}
4189
David Majnemere4752e752015-07-08 05:55:00 +00004190/// ParseMicrosoftAttributes - Parse Microsoft attributes [Attr]
Francois Pichetc2bc5ac2010-10-11 12:59:39 +00004191///
4192/// [MS] ms-attribute:
4193/// '[' token-seq ']'
4194///
4195/// [MS] ms-attribute-seq:
4196/// ms-attribute[opt]
4197/// ms-attribute ms-attribute-seq
John McCall53fa7142010-12-24 02:08:15 +00004198void Parser::ParseMicrosoftAttributes(ParsedAttributes &attrs,
4199 SourceLocation *endLoc) {
Francois Pichetc2bc5ac2010-10-11 12:59:39 +00004200 assert(Tok.is(tok::l_square) && "Not a Microsoft attribute list");
4201
Saleem Abdulrasool425efcf2015-06-15 20:57:04 +00004202 do {
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004203 // FIXME: If this is actually a C++11 attribute, parse it as one.
Saleem Abdulrasool425efcf2015-06-15 20:57:04 +00004204 BalancedDelimiterTracker T(*this, tok::l_square);
4205 T.consumeOpen();
Nico Weber05e1dad2016-09-03 03:25:22 +00004206
4207 // Skip most ms attributes except for a whitelist.
4208 while (true) {
4209 SkipUntil(tok::r_square, tok::identifier, StopAtSemi | StopBeforeMatch);
4210 if (Tok.isNot(tok::identifier)) // ']', but also eof
4211 break;
4212 if (Tok.getIdentifierInfo()->getName() == "uuid")
4213 ParseMicrosoftUuidAttributeArgs(attrs);
4214 else
4215 ConsumeToken();
4216 }
4217
Saleem Abdulrasool425efcf2015-06-15 20:57:04 +00004218 T.consumeClose();
4219 if (endLoc)
4220 *endLoc = T.getCloseLocation();
4221 } while (Tok.is(tok::l_square));
Francois Pichetc2bc5ac2010-10-11 12:59:39 +00004222}
Francois Pichet8f981d52011-05-25 10:19:49 +00004223
4224void Parser::ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType,
4225 AccessSpecifier& CurAS) {
Douglas Gregor43edb322011-10-24 22:31:10 +00004226 IfExistsCondition Result;
Francois Pichet8f981d52011-05-25 10:19:49 +00004227 if (ParseMicrosoftIfExistsCondition(Result))
4228 return;
4229
Douglas Gregor43edb322011-10-24 22:31:10 +00004230 BalancedDelimiterTracker Braces(*this, tok::l_brace);
4231 if (Braces.consumeOpen()) {
Alp Tokerec543272013-12-24 09:48:30 +00004232 Diag(Tok, diag::err_expected) << tok::l_brace;
Francois Pichet8f981d52011-05-25 10:19:49 +00004233 return;
4234 }
Francois Pichet8f981d52011-05-25 10:19:49 +00004235
Douglas Gregor43edb322011-10-24 22:31:10 +00004236 switch (Result.Behavior) {
4237 case IEB_Parse:
4238 // Parse the declarations below.
4239 break;
4240
4241 case IEB_Dependent:
4242 Diag(Result.KeywordLoc, diag::warn_microsoft_dependent_exists)
4243 << Result.IsIfExists;
4244 // Fall through to skip.
Galina Kistanovad819d5b2017-06-01 21:19:06 +00004245 LLVM_FALLTHROUGH;
Douglas Gregor43edb322011-10-24 22:31:10 +00004246
4247 case IEB_Skip:
4248 Braces.skipToEnd();
Francois Pichet8f981d52011-05-25 10:19:49 +00004249 return;
4250 }
4251
Richard Smith34f30512013-11-23 04:06:09 +00004252 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
Francois Pichet8f981d52011-05-25 10:19:49 +00004253 // __if_exists, __if_not_exists can nest.
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00004254 if (Tok.isOneOf(tok::kw___if_exists, tok::kw___if_not_exists)) {
Francois Pichet8f981d52011-05-25 10:19:49 +00004255 ParseMicrosoftIfExistsClassDeclaration((DeclSpec::TST)TagType, CurAS);
4256 continue;
4257 }
4258
4259 // Check for extraneous top-level semicolon.
4260 if (Tok.is(tok::semi)) {
Richard Smith87f5dc52012-07-23 05:45:25 +00004261 ConsumeExtraSemi(InsideStruct, TagType);
Francois Pichet8f981d52011-05-25 10:19:49 +00004262 continue;
4263 }
4264
4265 AccessSpecifier AS = getAccessSpecifierIfPresent();
4266 if (AS != AS_none) {
4267 // Current token is a C++ access specifier.
4268 CurAS = AS;
4269 SourceLocation ASLoc = Tok.getLocation();
4270 ConsumeToken();
4271 if (Tok.is(tok::colon))
4272 Actions.ActOnAccessSpecifier(AS, ASLoc, Tok.getLocation());
4273 else
Alp Toker35d87032013-12-30 23:29:50 +00004274 Diag(Tok, diag::err_expected) << tok::colon;
Francois Pichet8f981d52011-05-25 10:19:49 +00004275 ConsumeToken();
4276 continue;
4277 }
4278
4279 // Parse all the comma separated declarators.
Craig Topper161e4db2014-05-21 06:02:52 +00004280 ParseCXXClassMemberDeclaration(CurAS, nullptr);
Francois Pichet8f981d52011-05-25 10:19:49 +00004281 }
Douglas Gregor43edb322011-10-24 22:31:10 +00004282
4283 Braces.consumeClose();
Francois Pichet8f981d52011-05-25 10:19:49 +00004284}