blob: a724fa242268b80f794d3854d69b45a39fc28ef8 [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"
Aaron Ballmanb8e20392014-03-31 17:32:39 +000017#include "clang/Basic/Attributes.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000018#include "clang/Basic/CharInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "clang/Basic/OperatorKinds.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000020#include "clang/Basic/TargetInfo.h"
Chris Lattner60f36222009-01-29 05:15:15 +000021#include "clang/Parse/ParseDiagnostic.h"
Vassil Vassilev11ad3392017-03-23 15:11:07 +000022#include "clang/Parse/RAIIObjectsForParser.h"
John McCall8b0666c2010-08-20 18:27:03 +000023#include "clang/Sema/DeclSpec.h"
John McCall8b0666c2010-08-20 18:27:03 +000024#include "clang/Sema/ParsedTemplate.h"
John McCallfaf5fb42010-08-26 23:41:50 +000025#include "clang/Sema/PrettyDeclStackTrace.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///
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +000058Parser::DeclGroupPtrTy Parser::ParseNamespace(unsigned Context,
59 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()) {
80 if (!getLangOpts().CPlusPlus1z)
Aaron Ballmanc0ae7df2014-11-08 17:07:15 +000081 Diag(Tok.getLocation(), diag::warn_cxx14_compat_attribute)
82 << 0 /*namespace*/;
Aaron Ballman730476b2014-11-08 15:33:35 +000083 attrLoc = Tok.getLocation();
84 ParseCXX11Attributes(attrs);
85 }
Mike Stump11289f42009-09-09 15:08:12 +000086
Chris Lattner76c72282007-10-09 17:33:22 +000087 if (Tok.is(tok::identifier)) {
Chris Lattnera5235172007-08-25 06:57:03 +000088 Ident = Tok.getIdentifierInfo();
89 IdentLoc = ConsumeToken(); // eat the identifier.
Richard Trieu61384cb2011-05-26 20:11:09 +000090 while (Tok.is(tok::coloncolon) && NextToken().is(tok::identifier)) {
91 ExtraNamespaceLoc.push_back(ConsumeToken());
92 ExtraIdent.push_back(Tok.getIdentifierInfo());
93 ExtraIdentLoc.push_back(ConsumeToken());
94 }
Chris Lattnera5235172007-08-25 06:57:03 +000095 }
Mike Stump11289f42009-09-09 15:08:12 +000096
Aaron Ballmanc0ae7df2014-11-08 17:07:15 +000097 // A nested namespace definition cannot have attributes.
98 if (!ExtraNamespaceLoc.empty() && attrLoc.isValid())
99 Diag(attrLoc, diag::err_unexpected_nested_namespace_attribute);
100
Chris Lattnera5235172007-08-25 06:57:03 +0000101 // Read label attributes, if present.
Douglas Gregor6b6bba42009-06-17 19:49:00 +0000102 if (Tok.is(tok::kw___attribute)) {
Aaron Ballman730476b2014-11-08 15:33:35 +0000103 attrLoc = Tok.getLocation();
John McCall53fa7142010-12-24 02:08:15 +0000104 ParseGNUAttributes(attrs);
Douglas Gregor6b6bba42009-06-17 19:49:00 +0000105 }
Mike Stump11289f42009-09-09 15:08:12 +0000106
Douglas Gregor6b6bba42009-06-17 19:49:00 +0000107 if (Tok.is(tok::equal)) {
Craig Topper161e4db2014-05-21 06:02:52 +0000108 if (!Ident) {
Alp Tokerec543272013-12-24 09:48:30 +0000109 Diag(Tok, diag::err_expected) << tok::identifier;
Nico Weber729f1e22012-10-27 23:44:27 +0000110 // Skip to end of the definition and eat the ';'.
111 SkipUntil(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +0000112 return nullptr;
Nico Weber729f1e22012-10-27 23:44:27 +0000113 }
Aaron Ballman730476b2014-11-08 15:33:35 +0000114 if (attrLoc.isValid())
115 Diag(attrLoc, diag::err_unexpected_namespace_attributes_alias);
Sebastian Redl67667942010-08-27 23:12:46 +0000116 if (InlineLoc.isValid())
117 Diag(InlineLoc, diag::err_inline_namespace_alias)
118 << FixItHint::CreateRemoval(InlineLoc);
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +0000119 Decl *NSAlias = ParseNamespaceAlias(NamespaceLoc, IdentLoc, Ident, DeclEnd);
120 return Actions.ConvertDeclToDeclGroup(NSAlias);
121}
Mike Stump11289f42009-09-09 15:08:12 +0000122
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000123 BalancedDelimiterTracker T(*this, tok::l_brace);
124 if (T.consumeOpen()) {
Alp Tokerec543272013-12-24 09:48:30 +0000125 if (Ident)
126 Diag(Tok, diag::err_expected) << tok::l_brace;
127 else
128 Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace;
David Blaikie0403cb12016-01-15 23:43:25 +0000129 return nullptr;
Chris Lattnera5235172007-08-25 06:57:03 +0000130 }
Mike Stump11289f42009-09-09 15:08:12 +0000131
Douglas Gregor0be31a22010-07-02 17:43:08 +0000132 if (getCurScope()->isClassScope() || getCurScope()->isTemplateParamScope() ||
133 getCurScope()->isInObjcMethodScope() || getCurScope()->getBlockParent() ||
134 getCurScope()->getFnParent()) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000135 Diag(T.getOpenLocation(), diag::err_namespace_nonnamespace_scope);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000136 SkipUntil(tok::r_brace);
David Blaikie0403cb12016-01-15 23:43:25 +0000137 return nullptr;
Douglas Gregor05cfc292010-05-14 05:08:22 +0000138 }
139
Richard Smith13307f52014-11-08 05:37:34 +0000140 if (ExtraIdent.empty()) {
141 // Normal namespace definition, not a nested-namespace-definition.
142 } else if (InlineLoc.isValid()) {
143 Diag(InlineLoc, diag::err_inline_nested_namespace_definition);
144 } else if (getLangOpts().CPlusPlus1z) {
145 Diag(ExtraNamespaceLoc[0],
146 diag::warn_cxx14_compat_nested_namespace_definition);
147 } else {
Richard Trieu61384cb2011-05-26 20:11:09 +0000148 TentativeParsingAction TPA(*this);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000149 SkipUntil(tok::r_brace, StopBeforeMatch);
Richard Trieu61384cb2011-05-26 20:11:09 +0000150 Token rBraceToken = Tok;
151 TPA.Revert();
152
153 if (!rBraceToken.is(tok::r_brace)) {
Richard Smith13307f52014-11-08 05:37:34 +0000154 Diag(ExtraNamespaceLoc[0], diag::ext_nested_namespace_definition)
Richard Trieu61384cb2011-05-26 20:11:09 +0000155 << SourceRange(ExtraNamespaceLoc.front(), ExtraIdentLoc.back());
156 } else {
Benjamin Kramerf546f412011-05-26 21:32:30 +0000157 std::string NamespaceFix;
Richard Trieu61384cb2011-05-26 20:11:09 +0000158 for (std::vector<IdentifierInfo*>::iterator I = ExtraIdent.begin(),
159 E = ExtraIdent.end(); I != E; ++I) {
160 NamespaceFix += " { namespace ";
161 NamespaceFix += (*I)->getName();
162 }
Benjamin Kramerf546f412011-05-26 21:32:30 +0000163
Richard Trieu61384cb2011-05-26 20:11:09 +0000164 std::string RBraces;
Benjamin Kramerf546f412011-05-26 21:32:30 +0000165 for (unsigned i = 0, e = ExtraIdent.size(); i != e; ++i)
Richard Trieu61384cb2011-05-26 20:11:09 +0000166 RBraces += "} ";
Benjamin Kramerf546f412011-05-26 21:32:30 +0000167
Richard Smith13307f52014-11-08 05:37:34 +0000168 Diag(ExtraNamespaceLoc[0], diag::ext_nested_namespace_definition)
Richard Trieu61384cb2011-05-26 20:11:09 +0000169 << FixItHint::CreateReplacement(SourceRange(ExtraNamespaceLoc.front(),
170 ExtraIdentLoc.back()),
171 NamespaceFix)
172 << FixItHint::CreateInsertion(rBraceToken.getLocation(), RBraces);
173 }
174 }
175
Sebastian Redl5a5f2c72010-08-31 00:36:45 +0000176 // If we're still good, complain about inline namespaces in non-C++0x now.
Richard Smith5d164bc2011-10-15 05:09:34 +0000177 if (InlineLoc.isValid())
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000178 Diag(InlineLoc, getLangOpts().CPlusPlus11 ?
Richard Smith5d164bc2011-10-15 05:09:34 +0000179 diag::warn_cxx98_compat_inline_namespace : diag::ext_inline_namespace);
Sebastian Redl5a5f2c72010-08-31 00:36:45 +0000180
Chris Lattner4de55aa2009-03-29 14:02:43 +0000181 // Enter a scope for the namespace.
182 ParseScope NamespaceScope(this, Scope::DeclScope);
183
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +0000184 UsingDirectiveDecl *ImplicitUsingDirectiveDecl = nullptr;
John McCall48871652010-08-21 09:40:31 +0000185 Decl *NamespcDecl =
Abramo Bagnarab5545be2011-03-08 12:38:20 +0000186 Actions.ActOnStartNamespaceDef(getCurScope(), InlineLoc, NamespaceLoc,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000187 IdentLoc, Ident, T.getOpenLocation(),
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +0000188 attrs.getList(), ImplicitUsingDirectiveDecl);
Chris Lattner4de55aa2009-03-29 14:02:43 +0000189
John McCallfaf5fb42010-08-26 23:41:50 +0000190 PrettyDeclStackTraceEntry CrashInfo(Actions, NamespcDecl, NamespaceLoc,
191 "parsing namespace");
Mike Stump11289f42009-09-09 15:08:12 +0000192
Richard Trieu61384cb2011-05-26 20:11:09 +0000193 // Parse the contents of the namespace. This includes parsing recovery on
194 // any improperly nested namespaces.
195 ParseInnerNamespace(ExtraIdentLoc, ExtraIdent, ExtraNamespaceLoc, 0,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000196 InlineLoc, attrs, T);
Mike Stump11289f42009-09-09 15:08:12 +0000197
Chris Lattner4de55aa2009-03-29 14:02:43 +0000198 // Leave the namespace scope.
199 NamespaceScope.Exit();
200
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000201 DeclEnd = T.getCloseLocation();
202 Actions.ActOnFinishNamespaceDef(NamespcDecl, DeclEnd);
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +0000203
204 return Actions.ConvertDeclToDeclGroup(NamespcDecl,
205 ImplicitUsingDirectiveDecl);
Chris Lattnera5235172007-08-25 06:57:03 +0000206}
Chris Lattner38376f12008-01-12 07:05:38 +0000207
Richard Trieu61384cb2011-05-26 20:11:09 +0000208/// ParseInnerNamespace - Parse the contents of a namespace.
Richard Smith13307f52014-11-08 05:37:34 +0000209void Parser::ParseInnerNamespace(std::vector<SourceLocation> &IdentLoc,
210 std::vector<IdentifierInfo *> &Ident,
211 std::vector<SourceLocation> &NamespaceLoc,
212 unsigned int index, SourceLocation &InlineLoc,
213 ParsedAttributes &attrs,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000214 BalancedDelimiterTracker &Tracker) {
Richard Trieu61384cb2011-05-26 20:11:09 +0000215 if (index == Ident.size()) {
Richard Smith752ada82015-11-17 23:32:01 +0000216 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
217 Tok.isNot(tok::eof)) {
Richard Trieu61384cb2011-05-26 20:11:09 +0000218 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +0000219 MaybeParseCXX11Attributes(attrs);
Richard Trieu61384cb2011-05-26 20:11:09 +0000220 ParseExternalDeclaration(attrs);
221 }
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000222
223 // The caller is what called check -- we are simply calling
224 // the close for it.
225 Tracker.consumeClose();
Richard Trieu61384cb2011-05-26 20:11:09 +0000226
227 return;
228 }
229
Richard Smith13307f52014-11-08 05:37:34 +0000230 // Handle a nested namespace definition.
231 // FIXME: Preserve the source information through to the AST rather than
232 // desugaring it here.
Richard Trieu61384cb2011-05-26 20:11:09 +0000233 ParseScope NamespaceScope(this, Scope::DeclScope);
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +0000234 UsingDirectiveDecl *ImplicitUsingDirectiveDecl = nullptr;
Richard Trieu61384cb2011-05-26 20:11:09 +0000235 Decl *NamespcDecl =
236 Actions.ActOnStartNamespaceDef(getCurScope(), SourceLocation(),
237 NamespaceLoc[index], IdentLoc[index],
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000238 Ident[index], Tracker.getOpenLocation(),
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +0000239 attrs.getList(), ImplicitUsingDirectiveDecl);
240 assert(!ImplicitUsingDirectiveDecl &&
241 "nested namespace definition cannot define anonymous namespace");
Richard Trieu61384cb2011-05-26 20:11:09 +0000242
243 ParseInnerNamespace(IdentLoc, Ident, NamespaceLoc, ++index, InlineLoc,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000244 attrs, Tracker);
Richard Trieu61384cb2011-05-26 20:11:09 +0000245
246 NamespaceScope.Exit();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000247 Actions.ActOnFinishNamespaceDef(NamespcDecl, Tracker.getCloseLocation());
Richard Trieu61384cb2011-05-26 20:11:09 +0000248}
249
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000250/// ParseNamespaceAlias - Parse the part after the '=' in a namespace
251/// alias definition.
252///
John McCall48871652010-08-21 09:40:31 +0000253Decl *Parser::ParseNamespaceAlias(SourceLocation NamespaceLoc,
John McCall084e83d2011-03-24 11:26:52 +0000254 SourceLocation AliasLoc,
255 IdentifierInfo *Alias,
256 SourceLocation &DeclEnd) {
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000257 assert(Tok.is(tok::equal) && "Not equal token");
Mike Stump11289f42009-09-09 15:08:12 +0000258
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000259 ConsumeToken(); // eat the '='.
Mike Stump11289f42009-09-09 15:08:12 +0000260
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000261 if (Tok.is(tok::code_completion)) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000262 Actions.CodeCompleteNamespaceAliasDecl(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000263 cutOffParsing();
Craig Topper161e4db2014-05-21 06:02:52 +0000264 return nullptr;
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000265 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000266
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000267 CXXScopeSpec SS;
268 // Parse (optional) nested-name-specifier.
Matthias Gehredc01bb42017-03-17 21:41:20 +0000269 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false,
270 /*MayBePseudoDestructor=*/nullptr,
271 /*IsTypename=*/false,
272 /*LastII=*/nullptr,
273 /*OnlyNamespace=*/true);
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000274
Matthias Gehredc01bb42017-03-17 21:41:20 +0000275 if (Tok.isNot(tok::identifier)) {
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000276 Diag(Tok, diag::err_expected_namespace_name);
277 // Skip to end of the definition and eat the ';'.
278 SkipUntil(tok::semi);
Craig Topper161e4db2014-05-21 06:02:52 +0000279 return nullptr;
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000280 }
281
Matthias Gehredc01bb42017-03-17 21:41:20 +0000282 if (SS.isInvalid()) {
283 // Diagnostics have been emitted in ParseOptionalCXXScopeSpecifier.
284 // Skip to end of the definition and eat the ';'.
285 SkipUntil(tok::semi);
286 return nullptr;
287 }
288
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000289 // Parse identifier.
Anders Carlsson47952ae2009-03-28 22:53:22 +0000290 IdentifierInfo *Ident = Tok.getIdentifierInfo();
291 SourceLocation IdentLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000292
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000293 // Eat the ';'.
Chris Lattner49836b42009-04-02 04:16:50 +0000294 DeclEnd = Tok.getLocation();
Alp Toker383d2c42014-01-01 03:08:43 +0000295 if (ExpectAndConsume(tok::semi, diag::err_expected_semi_after_namespace_name))
296 SkipUntil(tok::semi);
Mike Stump11289f42009-09-09 15:08:12 +0000297
Craig Topperff354282015-11-14 18:16:00 +0000298 return Actions.ActOnNamespaceAliasDef(getCurScope(), NamespaceLoc, AliasLoc,
299 Alias, SS, IdentLoc, Ident);
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000300}
301
Chris Lattner38376f12008-01-12 07:05:38 +0000302/// ParseLinkage - We know that the current token is a string_literal
303/// and just before that, that extern was seen.
304///
305/// linkage-specification: [C++ 7.5p2: dcl.link]
306/// 'extern' string-literal '{' declaration-seq[opt] '}'
307/// 'extern' string-literal declaration
308///
Chris Lattner8ea64422010-11-09 20:15:55 +0000309Decl *Parser::ParseLinkage(ParsingDeclSpec &DS, unsigned Context) {
Richard Smith4ee696d2014-02-17 23:25:27 +0000310 assert(isTokenStringLiteral() && "Not a string literal!");
311 ExprResult Lang = ParseStringLiteralExpression(false);
Chris Lattner38376f12008-01-12 07:05:38 +0000312
Douglas Gregor07665a62009-01-05 19:45:36 +0000313 ParseScope LinkageScope(this, Scope::DeclScope);
Richard Smith4ee696d2014-02-17 23:25:27 +0000314 Decl *LinkageSpec =
315 Lang.isInvalid()
Craig Topper161e4db2014-05-21 06:02:52 +0000316 ? nullptr
Richard Smith4ee696d2014-02-17 23:25:27 +0000317 : Actions.ActOnStartLinkageSpecification(
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000318 getCurScope(), DS.getSourceRange().getBegin(), Lang.get(),
Richard Smith4ee696d2014-02-17 23:25:27 +0000319 Tok.is(tok::l_brace) ? Tok.getLocation() : SourceLocation());
Douglas Gregor07665a62009-01-05 19:45:36 +0000320
John McCall084e83d2011-03-24 11:26:52 +0000321 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +0000322 MaybeParseCXX11Attributes(attrs);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000323
Douglas Gregor07665a62009-01-05 19:45:36 +0000324 if (Tok.isNot(tok::l_brace)) {
Abramo Bagnara4d423992011-05-01 16:25:54 +0000325 // Reset the source range in DS, as the leading "extern"
326 // does not really belong to the inner declaration ...
327 DS.SetRangeStart(SourceLocation());
328 DS.SetRangeEnd(SourceLocation());
329 // ... but anyway remember that such an "extern" was seen.
Abramo Bagnaraed5b6892010-07-30 16:47:02 +0000330 DS.setExternInLinkageSpec(true);
John McCall53fa7142010-12-24 02:08:15 +0000331 ParseExternalDeclaration(attrs, &DS);
Richard Smith4ee696d2014-02-17 23:25:27 +0000332 return LinkageSpec ? Actions.ActOnFinishLinkageSpecification(
333 getCurScope(), LinkageSpec, SourceLocation())
Craig Topper161e4db2014-05-21 06:02:52 +0000334 : nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000335 }
Douglas Gregor29ff7d02008-12-16 22:23:02 +0000336
Douglas Gregorb65a9132010-02-07 08:38:28 +0000337 DS.abort();
338
John McCall53fa7142010-12-24 02:08:15 +0000339 ProhibitAttributes(attrs);
Alexis Hunt96d5c762009-11-21 08:43:09 +0000340
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000341 BalancedDelimiterTracker T(*this, tok::l_brace);
342 T.consumeOpen();
Richard Smith77944862014-03-02 05:58:18 +0000343
344 unsigned NestedModules = 0;
345 while (true) {
346 switch (Tok.getKind()) {
347 case tok::annot_module_begin:
348 ++NestedModules;
349 ParseTopLevelDecl();
350 continue;
351
352 case tok::annot_module_end:
353 if (!NestedModules)
354 break;
355 --NestedModules;
356 ParseTopLevelDecl();
357 continue;
358
359 case tok::annot_module_include:
360 ParseTopLevelDecl();
361 continue;
362
363 case tok::eof:
364 break;
365
366 case tok::r_brace:
367 if (!NestedModules)
368 break;
369 // Fall through.
370 default:
371 ParsedAttributesWithRange attrs(AttrFactory);
372 MaybeParseCXX11Attributes(attrs);
Richard Smith77944862014-03-02 05:58:18 +0000373 ParseExternalDeclaration(attrs);
374 continue;
375 }
376
377 break;
Chris Lattner38376f12008-01-12 07:05:38 +0000378 }
379
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000380 T.consumeClose();
Richard Smith4ee696d2014-02-17 23:25:27 +0000381 return LinkageSpec ? Actions.ActOnFinishLinkageSpecification(
382 getCurScope(), LinkageSpec, T.getCloseLocation())
Craig Topper161e4db2014-05-21 06:02:52 +0000383 : nullptr;
Chris Lattner38376f12008-01-12 07:05:38 +0000384}
Douglas Gregor556877c2008-04-13 21:30:24 +0000385
Richard Smith8df390f2016-09-08 23:14:54 +0000386/// Parse a C++ Modules TS export-declaration.
387///
388/// export-declaration:
389/// 'export' declaration
390/// 'export' '{' declaration-seq[opt] '}'
391///
392Decl *Parser::ParseExportDeclaration() {
393 assert(Tok.is(tok::kw_export));
394 SourceLocation ExportLoc = ConsumeToken();
395
396 ParseScope ExportScope(this, Scope::DeclScope);
397 Decl *ExportDecl = Actions.ActOnStartExportDecl(
398 getCurScope(), ExportLoc,
399 Tok.is(tok::l_brace) ? Tok.getLocation() : SourceLocation());
400
401 if (Tok.isNot(tok::l_brace)) {
402 // FIXME: Factor out a ParseExternalDeclarationWithAttrs.
403 ParsedAttributesWithRange Attrs(AttrFactory);
404 MaybeParseCXX11Attributes(Attrs);
405 MaybeParseMicrosoftAttributes(Attrs);
406 ParseExternalDeclaration(Attrs);
407 return Actions.ActOnFinishExportDecl(getCurScope(), ExportDecl,
408 SourceLocation());
409 }
410
411 BalancedDelimiterTracker T(*this, tok::l_brace);
412 T.consumeOpen();
413
414 // The Modules TS draft says "An export-declaration shall declare at least one
415 // entity", but the intent is that it shall contain at least one declaration.
416 if (Tok.is(tok::r_brace))
417 Diag(ExportLoc, diag::err_export_empty)
418 << SourceRange(ExportLoc, Tok.getLocation());
419
420 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
421 Tok.isNot(tok::eof)) {
422 ParsedAttributesWithRange Attrs(AttrFactory);
423 MaybeParseCXX11Attributes(Attrs);
424 MaybeParseMicrosoftAttributes(Attrs);
425 ParseExternalDeclaration(Attrs);
426 }
427
428 T.consumeClose();
429 return Actions.ActOnFinishExportDecl(getCurScope(), ExportDecl,
430 T.getCloseLocation());
431}
432
Douglas Gregord7c4d982008-12-30 03:27:21 +0000433/// ParseUsingDirectiveOrDeclaration - Parse C++ using using-declaration or
434/// using-directive. Assumes that current token is 'using'.
Richard Smith6f1daa42016-12-16 00:58:48 +0000435Parser::DeclGroupPtrTy
436Parser::ParseUsingDirectiveOrDeclaration(unsigned Context,
John McCall9b72f892010-11-10 02:40:36 +0000437 const ParsedTemplateInfo &TemplateInfo,
Richard Smith6f1daa42016-12-16 00:58:48 +0000438 SourceLocation &DeclEnd,
439 ParsedAttributesWithRange &attrs) {
Douglas Gregord7c4d982008-12-30 03:27:21 +0000440 assert(Tok.is(tok::kw_using) && "Not using token");
Fariborz Jahanian4bf82622011-08-22 17:59:19 +0000441 ObjCDeclContextSwitch ObjCDC(*this);
442
Douglas Gregord7c4d982008-12-30 03:27:21 +0000443 // Eat 'using'.
444 SourceLocation UsingLoc = ConsumeToken();
445
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000446 if (Tok.is(tok::code_completion)) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000447 Actions.CodeCompleteUsing(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000448 cutOffParsing();
Craig Topper161e4db2014-05-21 06:02:52 +0000449 return nullptr;
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000450 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000451
John McCall9b72f892010-11-10 02:40:36 +0000452 // 'using namespace' means this is a using-directive.
453 if (Tok.is(tok::kw_namespace)) {
454 // Template parameters are always an error here.
455 if (TemplateInfo.Kind) {
456 SourceRange R = TemplateInfo.getSourceRange();
Craig Topper54a6a682015-11-14 18:16:08 +0000457 Diag(UsingLoc, diag::err_templated_using_directive_declaration)
458 << 0 /* directive */ << R << FixItHint::CreateRemoval(R);
John McCall9b72f892010-11-10 02:40:36 +0000459 }
Alexis Hunt96d5c762009-11-21 08:43:09 +0000460
Richard Smith6f1daa42016-12-16 00:58:48 +0000461 Decl *UsingDir = ParseUsingDirective(Context, UsingLoc, DeclEnd, attrs);
462 return Actions.ConvertDeclToDeclGroup(UsingDir);
John McCall9b72f892010-11-10 02:40:36 +0000463 }
464
Richard Smithdda56e42011-04-15 14:24:37 +0000465 // Otherwise, it must be a using-declaration or an alias-declaration.
John McCall9b72f892010-11-10 02:40:36 +0000466
467 // Using declarations can't have attributes.
John McCall53fa7142010-12-24 02:08:15 +0000468 ProhibitAttributes(attrs);
Chris Lattner9b01ca12009-01-06 06:55:51 +0000469
Fariborz Jahanian4bf82622011-08-22 17:59:19 +0000470 return ParseUsingDeclaration(Context, TemplateInfo, UsingLoc, DeclEnd,
Richard Smith6f1daa42016-12-16 00:58:48 +0000471 AS_none);
Douglas Gregord7c4d982008-12-30 03:27:21 +0000472}
473
474/// ParseUsingDirective - Parse C++ using-directive, assumes
475/// that current token is 'namespace' and 'using' was already parsed.
476///
477/// using-directive: [C++ 7.3.p4: namespace.udir]
478/// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
479/// namespace-name ;
480/// [GNU] using-directive:
481/// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
482/// namespace-name attributes[opt] ;
483///
John McCall48871652010-08-21 09:40:31 +0000484Decl *Parser::ParseUsingDirective(unsigned Context,
John McCall9b72f892010-11-10 02:40:36 +0000485 SourceLocation UsingLoc,
486 SourceLocation &DeclEnd,
John McCall53fa7142010-12-24 02:08:15 +0000487 ParsedAttributes &attrs) {
Douglas Gregord7c4d982008-12-30 03:27:21 +0000488 assert(Tok.is(tok::kw_namespace) && "Not 'namespace' token");
489
490 // Eat 'namespace'.
491 SourceLocation NamespcLoc = ConsumeToken();
492
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000493 if (Tok.is(tok::code_completion)) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000494 Actions.CodeCompleteUsingDirective(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000495 cutOffParsing();
Craig Topper161e4db2014-05-21 06:02:52 +0000496 return nullptr;
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000497 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000498
Douglas Gregord7c4d982008-12-30 03:27:21 +0000499 CXXScopeSpec SS;
500 // Parse (optional) nested-name-specifier.
Matthias Gehredc01bb42017-03-17 21:41:20 +0000501 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false,
502 /*MayBePseudoDestructor=*/nullptr,
503 /*IsTypename=*/false,
504 /*LastII=*/nullptr,
505 /*OnlyNamespace=*/true);
Douglas Gregord7c4d982008-12-30 03:27:21 +0000506
Craig Topper161e4db2014-05-21 06:02:52 +0000507 IdentifierInfo *NamespcName = nullptr;
Douglas Gregord7c4d982008-12-30 03:27:21 +0000508 SourceLocation IdentLoc = SourceLocation();
509
510 // Parse namespace-name.
Matthias Gehredc01bb42017-03-17 21:41:20 +0000511 if (Tok.isNot(tok::identifier)) {
Douglas Gregord7c4d982008-12-30 03:27:21 +0000512 Diag(Tok, diag::err_expected_namespace_name);
513 // If there was invalid namespace name, skip to end of decl, and eat ';'.
514 SkipUntil(tok::semi);
515 // FIXME: Are there cases, when we would like to call ActOnUsingDirective?
Craig Topper161e4db2014-05-21 06:02:52 +0000516 return nullptr;
Douglas Gregord7c4d982008-12-30 03:27:21 +0000517 }
Mike Stump11289f42009-09-09 15:08:12 +0000518
Matthias Gehredc01bb42017-03-17 21:41:20 +0000519 if (SS.isInvalid()) {
520 // Diagnostics have been emitted in ParseOptionalCXXScopeSpecifier.
521 // Skip to end of the definition and eat the ';'.
522 SkipUntil(tok::semi);
523 return nullptr;
524 }
525
Chris Lattnerce1da2c2009-01-06 07:27:21 +0000526 // Parse identifier.
527 NamespcName = Tok.getIdentifierInfo();
528 IdentLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000529
Chris Lattnerce1da2c2009-01-06 07:27:21 +0000530 // Parse (optional) attributes (most likely GNU strong-using extension).
Alexis Hunt96d5c762009-11-21 08:43:09 +0000531 bool GNUAttr = false;
532 if (Tok.is(tok::kw___attribute)) {
533 GNUAttr = true;
John McCall53fa7142010-12-24 02:08:15 +0000534 ParseGNUAttributes(attrs);
Alexis Hunt96d5c762009-11-21 08:43:09 +0000535 }
Mike Stump11289f42009-09-09 15:08:12 +0000536
Chris Lattnerce1da2c2009-01-06 07:27:21 +0000537 // Eat ';'.
Chris Lattner49836b42009-04-02 04:16:50 +0000538 DeclEnd = Tok.getLocation();
Alp Toker383d2c42014-01-01 03:08:43 +0000539 if (ExpectAndConsume(tok::semi,
540 GNUAttr ? diag::err_expected_semi_after_attribute_list
541 : diag::err_expected_semi_after_namespace_name))
542 SkipUntil(tok::semi);
Douglas Gregord7c4d982008-12-30 03:27:21 +0000543
Douglas Gregor0be31a22010-07-02 17:43:08 +0000544 return Actions.ActOnUsingDirective(getCurScope(), UsingLoc, NamespcLoc, SS,
John McCall53fa7142010-12-24 02:08:15 +0000545 IdentLoc, NamespcName, attrs.getList());
Douglas Gregord7c4d982008-12-30 03:27:21 +0000546}
547
Richard Smith6f1daa42016-12-16 00:58:48 +0000548/// Parse a using-declarator (or the identifier in a C++11 alias-declaration).
Douglas Gregord7c4d982008-12-30 03:27:21 +0000549///
Richard Smith6f1daa42016-12-16 00:58:48 +0000550/// using-declarator:
551/// 'typename'[opt] nested-name-specifier unqualified-id
Douglas Gregord7c4d982008-12-30 03:27:21 +0000552///
Richard Smith6f1daa42016-12-16 00:58:48 +0000553bool Parser::ParseUsingDeclarator(unsigned Context, UsingDeclarator &D) {
554 D.clear();
Douglas Gregorfec52632009-06-20 00:51:54 +0000555
556 // Ignore optional 'typename'.
Douglas Gregor220f4272009-11-04 16:30:06 +0000557 // FIXME: This is wrong; we should parse this as a typename-specifier.
Richard Smith6f1daa42016-12-16 00:58:48 +0000558 TryConsumeToken(tok::kw_typename, D.TypenameLoc);
Douglas Gregorfec52632009-06-20 00:51:54 +0000559
Nikola Smiljanic67860242014-09-26 00:28:20 +0000560 if (Tok.is(tok::kw___super)) {
561 Diag(Tok.getLocation(), diag::err_super_in_using_declaration);
Richard Smith6f1daa42016-12-16 00:58:48 +0000562 return true;
Nikola Smiljanic67860242014-09-26 00:28:20 +0000563 }
564
Douglas Gregorfec52632009-06-20 00:51:54 +0000565 // Parse nested-name-specifier.
Craig Topper161e4db2014-05-21 06:02:52 +0000566 IdentifierInfo *LastII = nullptr;
Richard Smith6f1daa42016-12-16 00:58:48 +0000567 ParseOptionalCXXScopeSpecifier(D.SS, nullptr, /*EnteringContext=*/false,
Craig Topper161e4db2014-05-21 06:02:52 +0000568 /*MayBePseudoDtor=*/nullptr,
569 /*IsTypename=*/false,
Richard Smith7447af42013-03-26 01:15:19 +0000570 /*LastII=*/&LastII);
Richard Smith6f1daa42016-12-16 00:58:48 +0000571 if (D.SS.isInvalid())
572 return true;
Richard Smith7447af42013-03-26 01:15:19 +0000573
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000574 // Parse the unqualified-id. We allow parsing of both constructor and
Douglas Gregor220f4272009-11-04 16:30:06 +0000575 // destructor names and allow the action module to diagnose any semantic
576 // errors.
Richard Smith7447af42013-03-26 01:15:19 +0000577 //
578 // C++11 [class.qual]p2:
579 // [...] in a using-declaration that is a member-declaration, if the name
580 // specified after the nested-name-specifier is the same as the identifier
581 // or the simple-template-id's template-name in the last component of the
582 // nested-name-specifier, the name is [...] considered to name the
583 // constructor.
584 if (getLangOpts().CPlusPlus11 && Context == Declarator::MemberContext &&
Richard Smith151c4562016-12-20 21:35:28 +0000585 Tok.is(tok::identifier) &&
586 (NextToken().is(tok::semi) || NextToken().is(tok::comma) ||
587 NextToken().is(tok::ellipsis)) &&
Richard Smith6f1daa42016-12-16 00:58:48 +0000588 D.SS.isNotEmpty() && LastII == Tok.getIdentifierInfo() &&
589 !D.SS.getScopeRep()->getAsNamespace() &&
590 !D.SS.getScopeRep()->getAsNamespaceAlias()) {
Richard Smith7447af42013-03-26 01:15:19 +0000591 SourceLocation IdLoc = ConsumeToken();
Richard Smith6f1daa42016-12-16 00:58:48 +0000592 ParsedType Type =
593 Actions.getInheritingConstructorName(D.SS, IdLoc, *LastII);
594 D.Name.setConstructorName(Type, IdLoc, IdLoc);
595 } else {
596 if (ParseUnqualifiedId(
597 D.SS, /*EnteringContext=*/false,
598 /*AllowDestructorName=*/true,
599 /*AllowConstructorName=*/!(Tok.is(tok::identifier) &&
600 NextToken().is(tok::equal)),
Richard Smith35845152017-02-07 01:37:30 +0000601 /*AllowDeductionGuide=*/false,
Richard Smith6f1daa42016-12-16 00:58:48 +0000602 nullptr, D.TemplateKWLoc, D.Name))
603 return true;
Douglas Gregorfec52632009-06-20 00:51:54 +0000604 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000605
Richard Smith151c4562016-12-20 21:35:28 +0000606 if (TryConsumeToken(tok::ellipsis, D.EllipsisLoc))
607 Diag(Tok.getLocation(), getLangOpts().CPlusPlus1z ?
608 diag::warn_cxx1z_compat_using_declaration_pack :
609 diag::ext_using_declaration_pack);
Richard Smith6f1daa42016-12-16 00:58:48 +0000610
611 return false;
612}
613
614/// ParseUsingDeclaration - Parse C++ using-declaration or alias-declaration.
615/// Assumes that 'using' was already seen.
616///
617/// using-declaration: [C++ 7.3.p3: namespace.udecl]
618/// 'using' using-declarator-list[opt] ;
619///
620/// using-declarator-list: [C++1z]
621/// using-declarator '...'[opt]
622/// using-declarator-list ',' using-declarator '...'[opt]
623///
624/// using-declarator-list: [C++98-14]
625/// using-declarator
626///
627/// alias-declaration: C++11 [dcl.dcl]p1
628/// 'using' identifier attribute-specifier-seq[opt] = type-id ;
629///
630Parser::DeclGroupPtrTy
631Parser::ParseUsingDeclaration(unsigned Context,
632 const ParsedTemplateInfo &TemplateInfo,
633 SourceLocation UsingLoc, SourceLocation &DeclEnd,
634 AccessSpecifier AS) {
635 // Check for misplaced attributes before the identifier in an
636 // alias-declaration.
637 ParsedAttributesWithRange MisplacedAttrs(AttrFactory);
638 MaybeParseCXX11Attributes(MisplacedAttrs);
639
640 UsingDeclarator D;
641 bool InvalidDeclarator = ParseUsingDeclarator(Context, D);
642
Richard Smithc2c8bb82013-10-15 01:34:54 +0000643 ParsedAttributesWithRange Attrs(AttrFactory);
Richard Smith37a45dd2013-10-24 01:21:09 +0000644 MaybeParseGNUAttributes(Attrs);
Richard Smith54ecd982013-02-20 19:22:51 +0000645 MaybeParseCXX11Attributes(Attrs);
Richard Smithdda56e42011-04-15 14:24:37 +0000646
647 // Maybe this is an alias-declaration.
Richard Smith6f1daa42016-12-16 00:58:48 +0000648 if (Tok.is(tok::equal)) {
649 if (InvalidDeclarator) {
650 SkipUntil(tok::semi);
651 return nullptr;
652 }
653
Richard Smithc2c8bb82013-10-15 01:34:54 +0000654 // If we had any misplaced attributes from earlier, this is where they
655 // should have been written.
656 if (MisplacedAttrs.Range.isValid()) {
657 Diag(MisplacedAttrs.Range.getBegin(), diag::err_attributes_not_allowed)
658 << FixItHint::CreateInsertionFromRange(
659 Tok.getLocation(),
660 CharSourceRange::getTokenRange(MisplacedAttrs.Range))
661 << FixItHint::CreateRemoval(MisplacedAttrs.Range);
662 Attrs.takeAllFrom(MisplacedAttrs);
663 }
664
Richard Smith6f1daa42016-12-16 00:58:48 +0000665 Decl *DeclFromDeclSpec = nullptr;
666 Decl *AD = ParseAliasDeclarationAfterDeclarator(
667 TemplateInfo, UsingLoc, D, DeclEnd, AS, Attrs, &DeclFromDeclSpec);
668 return Actions.ConvertDeclToDeclGroup(AD, DeclFromDeclSpec);
Alexis Hunt6aa9bee2012-06-23 05:07:58 +0000669 }
Mike Stump11289f42009-09-09 15:08:12 +0000670
Richard Smith6f1daa42016-12-16 00:58:48 +0000671 // C++11 attributes are not allowed on a using-declaration, but GNU ones
672 // are.
673 ProhibitAttributes(MisplacedAttrs);
674 ProhibitAttributes(Attrs);
Douglas Gregorfec52632009-06-20 00:51:54 +0000675
John McCall9b72f892010-11-10 02:40:36 +0000676 // Diagnose an attempt to declare a templated using-declaration.
Richard Smith810ad3e2013-01-29 10:02:16 +0000677 // In C++11, alias-declarations can be templates:
Richard Smithdda56e42011-04-15 14:24:37 +0000678 // template <...> using id = type;
Richard Smith6f1daa42016-12-16 00:58:48 +0000679 if (TemplateInfo.Kind) {
John McCall9b72f892010-11-10 02:40:36 +0000680 SourceRange R = TemplateInfo.getSourceRange();
Craig Topper54a6a682015-11-14 18:16:08 +0000681 Diag(UsingLoc, diag::err_templated_using_directive_declaration)
682 << 1 /* declaration */ << R << FixItHint::CreateRemoval(R);
John McCall9b72f892010-11-10 02:40:36 +0000683
684 // Unfortunately, we have to bail out instead of recovering by
685 // ignoring the parameters, just in case the nested name specifier
686 // depends on the parameters.
Craig Topper161e4db2014-05-21 06:02:52 +0000687 return nullptr;
John McCall9b72f892010-11-10 02:40:36 +0000688 }
689
Richard Smith6f1daa42016-12-16 00:58:48 +0000690 SmallVector<Decl *, 8> DeclsInGroup;
691 while (true) {
692 // Parse (optional) attributes (most likely GNU strong-using extension).
693 MaybeParseGNUAttributes(Attrs);
694
695 if (InvalidDeclarator)
696 SkipUntil(tok::comma, tok::semi, StopBeforeMatch);
697 else {
698 // "typename" keyword is allowed for identifiers only,
699 // because it may be a type definition.
700 if (D.TypenameLoc.isValid() &&
701 D.Name.getKind() != UnqualifiedId::IK_Identifier) {
702 Diag(D.Name.getSourceRange().getBegin(),
703 diag::err_typename_identifiers_only)
704 << FixItHint::CreateRemoval(SourceRange(D.TypenameLoc));
705 // Proceed parsing, but discard the typename keyword.
706 D.TypenameLoc = SourceLocation();
707 }
708
Richard Smith151c4562016-12-20 21:35:28 +0000709 Decl *UD = Actions.ActOnUsingDeclaration(getCurScope(), AS, UsingLoc,
710 D.TypenameLoc, D.SS, D.Name,
711 D.EllipsisLoc, Attrs.getList());
Richard Smith6f1daa42016-12-16 00:58:48 +0000712 if (UD)
713 DeclsInGroup.push_back(UD);
714 }
715
716 if (!TryConsumeToken(tok::comma))
717 break;
718
719 // Parse another using-declarator.
720 Attrs.clear();
721 InvalidDeclarator = ParseUsingDeclarator(Context, D);
Douglas Gregor882a61a2011-09-26 14:30:28 +0000722 }
723
Richard Smith6f1daa42016-12-16 00:58:48 +0000724 if (DeclsInGroup.size() > 1)
725 Diag(Tok.getLocation(), getLangOpts().CPlusPlus1z ?
726 diag::warn_cxx1z_compat_multi_using_declaration :
727 diag::ext_multi_using_declaration);
728
729 // Eat ';'.
730 DeclEnd = Tok.getLocation();
731 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
732 !Attrs.empty() ? "attributes list"
733 : "using declaration"))
734 SkipUntil(tok::semi);
735
Richard Smith3beb7c62017-01-12 02:27:38 +0000736 return Actions.BuildDeclaratorGroup(DeclsInGroup);
Richard Smith6f1daa42016-12-16 00:58:48 +0000737}
738
Richard Smith6f1daa42016-12-16 00:58:48 +0000739Decl *Parser::ParseAliasDeclarationAfterDeclarator(
740 const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc,
741 UsingDeclarator &D, SourceLocation &DeclEnd, AccessSpecifier AS,
742 ParsedAttributes &Attrs, Decl **OwnedType) {
743 if (ExpectAndConsume(tok::equal)) {
744 SkipUntil(tok::semi);
745 return nullptr;
746 }
747
748 Diag(Tok.getLocation(), getLangOpts().CPlusPlus11 ?
749 diag::warn_cxx98_compat_alias_declaration :
750 diag::ext_alias_declaration);
751
752 // Type alias templates cannot be specialized.
753 int SpecKind = -1;
754 if (TemplateInfo.Kind == ParsedTemplateInfo::Template &&
755 D.Name.getKind() == UnqualifiedId::IK_TemplateId)
756 SpecKind = 0;
757 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization)
758 SpecKind = 1;
759 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
760 SpecKind = 2;
761 if (SpecKind != -1) {
762 SourceRange Range;
763 if (SpecKind == 0)
764 Range = SourceRange(D.Name.TemplateId->LAngleLoc,
765 D.Name.TemplateId->RAngleLoc);
766 else
767 Range = TemplateInfo.getSourceRange();
768 Diag(Range.getBegin(), diag::err_alias_declaration_specialization)
769 << SpecKind << Range;
770 SkipUntil(tok::semi);
771 return nullptr;
772 }
773
774 // Name must be an identifier.
775 if (D.Name.getKind() != UnqualifiedId::IK_Identifier) {
776 Diag(D.Name.StartLocation, diag::err_alias_declaration_not_identifier);
777 // No removal fixit: can't recover from this.
778 SkipUntil(tok::semi);
779 return nullptr;
780 } else if (D.TypenameLoc.isValid())
781 Diag(D.TypenameLoc, diag::err_alias_declaration_not_identifier)
782 << FixItHint::CreateRemoval(SourceRange(
783 D.TypenameLoc,
784 D.SS.isNotEmpty() ? D.SS.getEndLoc() : D.TypenameLoc));
785 else if (D.SS.isNotEmpty())
786 Diag(D.SS.getBeginLoc(), diag::err_alias_declaration_not_identifier)
787 << FixItHint::CreateRemoval(D.SS.getRange());
Richard Smith151c4562016-12-20 21:35:28 +0000788 if (D.EllipsisLoc.isValid())
789 Diag(D.EllipsisLoc, diag::err_alias_declaration_pack_expansion)
790 << FixItHint::CreateRemoval(SourceRange(D.EllipsisLoc));
Richard Smith6f1daa42016-12-16 00:58:48 +0000791
792 Decl *DeclFromDeclSpec = nullptr;
793 TypeResult TypeAlias =
794 ParseTypeName(nullptr,
795 TemplateInfo.Kind ? Declarator::AliasTemplateContext
796 : Declarator::AliasDeclContext,
797 AS, &DeclFromDeclSpec, &Attrs);
798 if (OwnedType)
799 *OwnedType = DeclFromDeclSpec;
800
801 // Eat ';'.
802 DeclEnd = Tok.getLocation();
803 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
804 !Attrs.empty() ? "attributes list"
805 : "alias declaration"))
806 SkipUntil(tok::semi);
807
808 TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
809 MultiTemplateParamsArg TemplateParamsArg(
810 TemplateParams ? TemplateParams->data() : nullptr,
811 TemplateParams ? TemplateParams->size() : 0);
812 return Actions.ActOnAliasDeclaration(getCurScope(), AS, TemplateParamsArg,
813 UsingLoc, D.Name, Attrs.getList(),
814 TypeAlias, DeclFromDeclSpec);
Douglas Gregord7c4d982008-12-30 03:27:21 +0000815}
816
Benjamin Kramere56f3932011-12-23 17:00:35 +0000817/// ParseStaticAssertDeclaration - Parse C++0x or C11 static_assert-declaration.
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000818///
Peter Collingbourne3d9cbdc2011-04-15 00:35:57 +0000819/// [C++0x] static_assert-declaration:
820/// static_assert ( constant-expression , string-literal ) ;
821///
Benjamin Kramere56f3932011-12-23 17:00:35 +0000822/// [C11] static_assert-declaration:
Peter Collingbourne3d9cbdc2011-04-15 00:35:57 +0000823/// _Static_assert ( constant-expression , string-literal ) ;
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000824///
John McCall48871652010-08-21 09:40:31 +0000825Decl *Parser::ParseStaticAssertDeclaration(SourceLocation &DeclEnd){
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000826 assert(Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert) &&
Peter Collingbourne3d9cbdc2011-04-15 00:35:57 +0000827 "Not a static_assert declaration");
828
David Blaikiebbafb8a2012-03-11 07:00:24 +0000829 if (Tok.is(tok::kw__Static_assert) && !getLangOpts().C11)
Benjamin Kramere56f3932011-12-23 17:00:35 +0000830 Diag(Tok, diag::ext_c11_static_assert);
Richard Smithb15c11c2011-10-17 23:06:20 +0000831 if (Tok.is(tok::kw_static_assert))
832 Diag(Tok, diag::warn_cxx98_compat_static_assert);
Peter Collingbourne3d9cbdc2011-04-15 00:35:57 +0000833
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000834 SourceLocation StaticAssertLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000835
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000836 BalancedDelimiterTracker T(*this, tok::l_paren);
837 if (T.consumeOpen()) {
Alp Tokerec543272013-12-24 09:48:30 +0000838 Diag(Tok, diag::err_expected) << tok::l_paren;
Richard Smith76965712012-09-13 19:12:50 +0000839 SkipMalformedDecl();
Craig Topper161e4db2014-05-21 06:02:52 +0000840 return nullptr;
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000841 }
Mike Stump11289f42009-09-09 15:08:12 +0000842
Richard Smithb3018062017-06-06 01:34:24 +0000843 EnterExpressionEvaluationContext ConstantEvaluated(
844 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
845 ExprResult AssertExpr(ParseConstantExpressionInExprEvalContext());
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000846 if (AssertExpr.isInvalid()) {
Richard Smith76965712012-09-13 19:12:50 +0000847 SkipMalformedDecl();
Craig Topper161e4db2014-05-21 06:02:52 +0000848 return nullptr;
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000849 }
Mike Stump11289f42009-09-09 15:08:12 +0000850
Richard Smith085a64f2014-06-20 19:57:12 +0000851 ExprResult AssertMessage;
852 if (Tok.is(tok::r_paren)) {
853 Diag(Tok, getLangOpts().CPlusPlus1z
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000854 ? diag::warn_cxx14_compat_static_assert_no_message
Richard Smith085a64f2014-06-20 19:57:12 +0000855 : diag::ext_static_assert_no_message)
856 << (getLangOpts().CPlusPlus1z
857 ? FixItHint()
858 : FixItHint::CreateInsertion(Tok.getLocation(), ", \"\""));
859 } else {
860 if (ExpectAndConsume(tok::comma)) {
861 SkipUntil(tok::semi);
862 return nullptr;
863 }
Anders Carlssonb4cf3ad2009-03-13 23:29:20 +0000864
Richard Smith085a64f2014-06-20 19:57:12 +0000865 if (!isTokenStringLiteral()) {
866 Diag(Tok, diag::err_expected_string_literal)
867 << /*Source='static_assert'*/1;
868 SkipMalformedDecl();
869 return nullptr;
870 }
Mike Stump11289f42009-09-09 15:08:12 +0000871
Richard Smith085a64f2014-06-20 19:57:12 +0000872 AssertMessage = ParseStringLiteralExpression();
873 if (AssertMessage.isInvalid()) {
874 SkipMalformedDecl();
875 return nullptr;
876 }
Richard Smithd67aea22012-03-06 03:21:47 +0000877 }
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000878
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000879 T.consumeClose();
Mike Stump11289f42009-09-09 15:08:12 +0000880
Chris Lattner49836b42009-04-02 04:16:50 +0000881 DeclEnd = Tok.getLocation();
Douglas Gregor45d6bdf2010-09-07 15:23:11 +0000882 ExpectAndConsumeSemi(diag::err_expected_semi_after_static_assert);
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000883
John McCallb268a282010-08-23 23:25:46 +0000884 return Actions.ActOnStaticAssertDeclaration(StaticAssertLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000885 AssertExpr.get(),
886 AssertMessage.get(),
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000887 T.getCloseLocation());
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000888}
889
Richard Smith74aeef52013-04-26 16:15:35 +0000890/// ParseDecltypeSpecifier - Parse a C++11 decltype specifier.
Anders Carlsson74948d02009-06-24 17:47:40 +0000891///
892/// 'decltype' ( expression )
Richard Smith74aeef52013-04-26 16:15:35 +0000893/// 'decltype' ( 'auto' ) [C++1y]
Anders Carlsson74948d02009-06-24 17:47:40 +0000894///
David Blaikie15a430a2011-12-04 05:04:18 +0000895SourceLocation Parser::ParseDecltypeSpecifier(DeclSpec &DS) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000896 assert(Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)
David Blaikie15a430a2011-12-04 05:04:18 +0000897 && "Not a decltype specifier");
898
David Blaikie15a430a2011-12-04 05:04:18 +0000899 ExprResult Result;
900 SourceLocation StartLoc = Tok.getLocation();
901 SourceLocation EndLoc;
902
903 if (Tok.is(tok::annot_decltype)) {
904 Result = getExprAnnotation(Tok);
905 EndLoc = Tok.getAnnotationEndLoc();
Richard Smithaf3b3252017-05-18 19:21:48 +0000906 ConsumeAnnotationToken();
David Blaikie15a430a2011-12-04 05:04:18 +0000907 if (Result.isInvalid()) {
908 DS.SetTypeSpecError();
909 return EndLoc;
910 }
911 } else {
Richard Smith324df552012-02-24 22:30:04 +0000912 if (Tok.getIdentifierInfo()->isStr("decltype"))
913 Diag(Tok, diag::warn_cxx98_compat_decltype);
Richard Smithfd3da932012-02-24 18:10:23 +0000914
David Blaikie15a430a2011-12-04 05:04:18 +0000915 ConsumeToken();
916
917 BalancedDelimiterTracker T(*this, tok::l_paren);
918 if (T.expectAndConsume(diag::err_expected_lparen_after,
919 "decltype", tok::r_paren)) {
920 DS.SetTypeSpecError();
921 return T.getOpenLocation() == Tok.getLocation() ?
922 StartLoc : T.getOpenLocation();
923 }
924
Richard Smith74aeef52013-04-26 16:15:35 +0000925 // Check for C++1y 'decltype(auto)'.
926 if (Tok.is(tok::kw_auto)) {
927 // No need to disambiguate here: an expression can't start with 'auto',
928 // because the typename-specifier in a function-style cast operation can't
929 // be 'auto'.
930 Diag(Tok.getLocation(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000931 getLangOpts().CPlusPlus14
Richard Smith74aeef52013-04-26 16:15:35 +0000932 ? diag::warn_cxx11_compat_decltype_auto_type_specifier
933 : diag::ext_decltype_auto_type_specifier);
934 ConsumeToken();
935 } else {
936 // Parse the expression
David Blaikie15a430a2011-12-04 05:04:18 +0000937
Richard Smith74aeef52013-04-26 16:15:35 +0000938 // C++11 [dcl.type.simple]p4:
939 // The operand of the decltype specifier is an unevaluated operand.
Faisal Valid143a0c2017-04-01 21:30:49 +0000940 EnterExpressionEvaluationContext Unevaluated(
941 Actions, Sema::ExpressionEvaluationContext::Unevaluated, nullptr,
942 /*IsDecltype=*/true);
Kaelyn Takata5cc85352015-04-10 19:16:46 +0000943 Result =
944 Actions.CorrectDelayedTyposInExpr(ParseExpression(), [](Expr *E) {
945 return E->hasPlaceholderType() ? ExprError() : E;
946 });
Richard Smith74aeef52013-04-26 16:15:35 +0000947 if (Result.isInvalid()) {
948 DS.SetTypeSpecError();
Alexey Bataevee6507d2013-11-18 08:17:37 +0000949 if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch)) {
Richard Smith74aeef52013-04-26 16:15:35 +0000950 EndLoc = ConsumeParen();
Argyrios Kyrtzidisc38395a2012-10-26 22:53:44 +0000951 } else {
Richard Smith74aeef52013-04-26 16:15:35 +0000952 if (PP.isBacktrackEnabled() && Tok.is(tok::semi)) {
953 // Backtrack to get the location of the last token before the semi.
954 PP.RevertCachedTokens(2);
955 ConsumeToken(); // the semi.
956 EndLoc = ConsumeAnyToken();
957 assert(Tok.is(tok::semi));
958 } else {
959 EndLoc = Tok.getLocation();
960 }
Argyrios Kyrtzidisc38395a2012-10-26 22:53:44 +0000961 }
Richard Smith74aeef52013-04-26 16:15:35 +0000962 return EndLoc;
Argyrios Kyrtzidisc38395a2012-10-26 22:53:44 +0000963 }
Richard Smith74aeef52013-04-26 16:15:35 +0000964
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000965 Result = Actions.ActOnDecltypeExpression(Result.get());
David Blaikie15a430a2011-12-04 05:04:18 +0000966 }
967
968 // Match the ')'
969 T.consumeClose();
970 if (T.getCloseLocation().isInvalid()) {
971 DS.SetTypeSpecError();
972 // FIXME: this should return the location of the last token
973 // that was consumed (by "consumeClose()")
974 return T.getCloseLocation();
975 }
976
Richard Smithfd555f62012-02-22 02:04:18 +0000977 if (Result.isInvalid()) {
978 DS.SetTypeSpecError();
979 return T.getCloseLocation();
980 }
981
David Blaikie15a430a2011-12-04 05:04:18 +0000982 EndLoc = T.getCloseLocation();
Anders Carlsson74948d02009-06-24 17:47:40 +0000983 }
Richard Smith74aeef52013-04-26 16:15:35 +0000984 assert(!Result.isInvalid());
Mike Stump11289f42009-09-09 15:08:12 +0000985
Craig Topper161e4db2014-05-21 06:02:52 +0000986 const char *PrevSpec = nullptr;
John McCall49bfce42009-08-03 20:12:06 +0000987 unsigned DiagID;
Erik Verbruggen888d52a2014-01-15 09:15:43 +0000988 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
Anders Carlsson74948d02009-06-24 17:47:40 +0000989 // Check for duplicate type specifiers (e.g. "int decltype(a)").
Richard Smith74aeef52013-04-26 16:15:35 +0000990 if (Result.get()
991 ? DS.SetTypeSpecType(DeclSpec::TST_decltype, StartLoc, PrevSpec,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000992 DiagID, Result.get(), Policy)
Richard Smith74aeef52013-04-26 16:15:35 +0000993 : DS.SetTypeSpecType(DeclSpec::TST_decltype_auto, StartLoc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +0000994 DiagID, Policy)) {
John McCall49bfce42009-08-03 20:12:06 +0000995 Diag(StartLoc, DiagID) << PrevSpec;
David Blaikie15a430a2011-12-04 05:04:18 +0000996 DS.SetTypeSpecError();
997 }
998 return EndLoc;
999}
1000
1001void Parser::AnnotateExistingDecltypeSpecifier(const DeclSpec& DS,
1002 SourceLocation StartLoc,
1003 SourceLocation EndLoc) {
1004 // make sure we have a token we can turn into an annotation token
1005 if (PP.isBacktrackEnabled())
1006 PP.RevertCachedTokens(1);
1007 else
1008 PP.EnterToken(Tok);
1009
1010 Tok.setKind(tok::annot_decltype);
Richard Smith74aeef52013-04-26 16:15:35 +00001011 setExprAnnotation(Tok,
1012 DS.getTypeSpecType() == TST_decltype ? DS.getRepAsExpr() :
1013 DS.getTypeSpecType() == TST_decltype_auto ? ExprResult() :
1014 ExprError());
David Blaikie15a430a2011-12-04 05:04:18 +00001015 Tok.setAnnotationEndLoc(EndLoc);
1016 Tok.setLocation(StartLoc);
1017 PP.AnnotateCachedTokens(Tok);
Anders Carlsson74948d02009-06-24 17:47:40 +00001018}
1019
Alexis Hunt4a257072011-05-19 05:37:45 +00001020void Parser::ParseUnderlyingTypeSpecifier(DeclSpec &DS) {
1021 assert(Tok.is(tok::kw___underlying_type) &&
1022 "Not an underlying type specifier");
1023
1024 SourceLocation StartLoc = ConsumeToken();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001025 BalancedDelimiterTracker T(*this, tok::l_paren);
1026 if (T.expectAndConsume(diag::err_expected_lparen_after,
1027 "__underlying_type", tok::r_paren)) {
Alexis Hunt4a257072011-05-19 05:37:45 +00001028 return;
1029 }
1030
1031 TypeResult Result = ParseTypeName();
1032 if (Result.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00001033 SkipUntil(tok::r_paren, StopAtSemi);
Alexis Hunt4a257072011-05-19 05:37:45 +00001034 return;
1035 }
1036
1037 // Match the ')'
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001038 T.consumeClose();
1039 if (T.getCloseLocation().isInvalid())
Alexis Hunt4a257072011-05-19 05:37:45 +00001040 return;
1041
Craig Topper161e4db2014-05-21 06:02:52 +00001042 const char *PrevSpec = nullptr;
Alexis Hunt4a257072011-05-19 05:37:45 +00001043 unsigned DiagID;
Alexis Hunte852b102011-05-24 22:41:36 +00001044 if (DS.SetTypeSpecType(DeclSpec::TST_underlyingType, StartLoc, PrevSpec,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001045 DiagID, Result.get(),
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001046 Actions.getASTContext().getPrintingPolicy()))
Alexis Hunt4a257072011-05-19 05:37:45 +00001047 Diag(StartLoc, DiagID) << PrevSpec;
Enea Zaffanellaa90af722013-07-06 18:54:58 +00001048 DS.setTypeofParensRange(T.getRange());
Alexis Hunt4a257072011-05-19 05:37:45 +00001049}
1050
David Blaikie00ee7a082011-10-25 15:01:20 +00001051/// ParseBaseTypeSpecifier - Parse a C++ base-type-specifier which is either a
1052/// class name or decltype-specifier. Note that we only check that the result
1053/// names a type; semantic analysis will need to verify that the type names a
1054/// class. The result is either a type or null, depending on whether a type
1055/// name was found.
Douglas Gregor831c93f2008-11-05 20:51:48 +00001056///
Richard Smith4c96e992013-02-19 23:47:15 +00001057/// base-type-specifier: [C++11 class.derived]
David Blaikie00ee7a082011-10-25 15:01:20 +00001058/// class-or-decltype
Richard Smith4c96e992013-02-19 23:47:15 +00001059/// class-or-decltype: [C++11 class.derived]
David Blaikie00ee7a082011-10-25 15:01:20 +00001060/// nested-name-specifier[opt] class-name
1061/// decltype-specifier
Richard Smith4c96e992013-02-19 23:47:15 +00001062/// class-name: [C++ class.name]
Douglas Gregor831c93f2008-11-05 20:51:48 +00001063/// identifier
Douglas Gregord54dfb82009-02-25 23:52:28 +00001064/// simple-template-id
Mike Stump11289f42009-09-09 15:08:12 +00001065///
Richard Smith4c96e992013-02-19 23:47:15 +00001066/// In C++98, instead of base-type-specifier, we have:
1067///
1068/// ::[opt] nested-name-specifier[opt] class-name
Craig Topper9ad7e262014-10-31 06:57:07 +00001069TypeResult Parser::ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
1070 SourceLocation &EndLocation) {
David Blaikiedd58d4c2011-10-25 18:46:41 +00001071 // Ignore attempts to use typename
1072 if (Tok.is(tok::kw_typename)) {
1073 Diag(Tok, diag::err_expected_class_name_not_template)
1074 << FixItHint::CreateRemoval(Tok.getLocation());
1075 ConsumeToken();
1076 }
1077
David Blaikieafa155f2011-10-25 18:17:58 +00001078 // Parse optional nested-name-specifier
1079 CXXScopeSpec SS;
David Blaikieefdccaa2016-01-15 23:43:34 +00001080 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false);
David Blaikieafa155f2011-10-25 18:17:58 +00001081
1082 BaseLoc = Tok.getLocation();
1083
David Blaikie1cd50022011-10-25 17:10:12 +00001084 // Parse decltype-specifier
David Blaikie15a430a2011-12-04 05:04:18 +00001085 // tok == kw_decltype is just error recovery, it can only happen when SS
1086 // isn't empty
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001087 if (Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)) {
David Blaikieafa155f2011-10-25 18:17:58 +00001088 if (SS.isNotEmpty())
1089 Diag(SS.getBeginLoc(), diag::err_unexpected_scope_on_base_decltype)
1090 << FixItHint::CreateRemoval(SS.getRange());
David Blaikie1cd50022011-10-25 17:10:12 +00001091 // Fake up a Declarator to use with ActOnTypeName.
1092 DeclSpec DS(AttrFactory);
1093
David Blaikie7491e732011-12-08 04:53:15 +00001094 EndLocation = ParseDecltypeSpecifier(DS);
David Blaikie1cd50022011-10-25 17:10:12 +00001095
1096 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1097 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
1098 }
1099
Douglas Gregord54dfb82009-02-25 23:52:28 +00001100 // Check whether we have a template-id that names a type.
1101 if (Tok.is(tok::annot_template_id)) {
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00001102 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregor46c59612010-01-12 17:52:59 +00001103 if (TemplateId->Kind == TNK_Type_template ||
1104 TemplateId->Kind == TNK_Dependent_template_name) {
Richard Smith62559bd2017-02-01 21:36:38 +00001105 AnnotateTemplateIdTokenAsType(/*IsClassName*/true);
Douglas Gregord54dfb82009-02-25 23:52:28 +00001106
1107 assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
John McCallba7bf592010-08-24 05:47:05 +00001108 ParsedType Type = getTypeAnnotation(Tok);
Douglas Gregord54dfb82009-02-25 23:52:28 +00001109 EndLocation = Tok.getAnnotationEndLoc();
Richard Smithaf3b3252017-05-18 19:21:48 +00001110 ConsumeAnnotationToken();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001111
1112 if (Type)
1113 return Type;
1114 return true;
Douglas Gregord54dfb82009-02-25 23:52:28 +00001115 }
1116
1117 // Fall through to produce an error below.
1118 }
1119
Douglas Gregor831c93f2008-11-05 20:51:48 +00001120 if (Tok.isNot(tok::identifier)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00001121 Diag(Tok, diag::err_expected_class_name);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001122 return true;
Douglas Gregor831c93f2008-11-05 20:51:48 +00001123 }
1124
Douglas Gregor18473f32010-01-12 21:28:44 +00001125 IdentifierInfo *Id = Tok.getIdentifierInfo();
1126 SourceLocation IdLoc = ConsumeToken();
1127
1128 if (Tok.is(tok::less)) {
1129 // It looks the user intended to write a template-id here, but the
1130 // template-name was wrong. Try to fix that.
1131 TemplateNameKind TNK = TNK_Type_template;
1132 TemplateTy Template;
Douglas Gregor0be31a22010-07-02 17:43:08 +00001133 if (!Actions.DiagnoseUnknownTemplateName(*Id, IdLoc, getCurScope(),
Douglas Gregore7c20652011-03-02 00:47:37 +00001134 &SS, Template, TNK)) {
Douglas Gregor18473f32010-01-12 21:28:44 +00001135 Diag(IdLoc, diag::err_unknown_template_name)
1136 << Id;
1137 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001138
Serge Pavlovb716b3c2013-08-10 05:54:47 +00001139 if (!Template) {
1140 TemplateArgList TemplateArgs;
1141 SourceLocation LAngleLoc, RAngleLoc;
Richard Smith9a420f92017-05-10 21:47:30 +00001142 ParseTemplateIdAfterTemplateName(true, LAngleLoc, TemplateArgs,
1143 RAngleLoc);
Douglas Gregor18473f32010-01-12 21:28:44 +00001144 return true;
Serge Pavlovb716b3c2013-08-10 05:54:47 +00001145 }
Douglas Gregor18473f32010-01-12 21:28:44 +00001146
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001147 // Form the template name
Douglas Gregor18473f32010-01-12 21:28:44 +00001148 UnqualifiedId TemplateName;
1149 TemplateName.setIdentifier(Id, IdLoc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001150
Douglas Gregor18473f32010-01-12 21:28:44 +00001151 // Parse the full template-id, then turn it into a type.
Abramo Bagnara7945c982012-01-27 09:46:47 +00001152 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
Richard Smith62559bd2017-02-01 21:36:38 +00001153 TemplateName))
Douglas Gregor18473f32010-01-12 21:28:44 +00001154 return true;
Richard Smith62559bd2017-02-01 21:36:38 +00001155 if (TNK == TNK_Type_template || TNK == TNK_Dependent_template_name)
1156 AnnotateTemplateIdTokenAsType(/*IsClassName*/true);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001157
Douglas Gregor18473f32010-01-12 21:28:44 +00001158 // If we didn't end up with a typename token, there's nothing more we
1159 // can do.
1160 if (Tok.isNot(tok::annot_typename))
1161 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001162
Douglas Gregor18473f32010-01-12 21:28:44 +00001163 // Retrieve the type from the annotation token, consume that token, and
1164 // return.
1165 EndLocation = Tok.getAnnotationEndLoc();
John McCallba7bf592010-08-24 05:47:05 +00001166 ParsedType Type = getTypeAnnotation(Tok);
Richard Smithaf3b3252017-05-18 19:21:48 +00001167 ConsumeAnnotationToken();
Douglas Gregor18473f32010-01-12 21:28:44 +00001168 return Type;
1169 }
1170
Douglas Gregor831c93f2008-11-05 20:51:48 +00001171 // We have an identifier; check whether it is actually a type.
Craig Topper161e4db2014-05-21 06:02:52 +00001172 IdentifierInfo *CorrectedII = nullptr;
Richard Smith600b5262017-01-26 20:40:47 +00001173 ParsedType Type = Actions.getTypeName(
Richard Smith62559bd2017-02-01 21:36:38 +00001174 *Id, IdLoc, getCurScope(), &SS, /*IsClassName=*/true, false, nullptr,
Richard Smith600b5262017-01-26 20:40:47 +00001175 /*IsCtorOrDtorName=*/false,
1176 /*NonTrivialTypeSourceInfo=*/true,
1177 /*IsClassTemplateDeductionContext*/ false, &CorrectedII);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001178 if (!Type) {
Douglas Gregorfe17d252010-02-16 19:09:40 +00001179 Diag(IdLoc, diag::err_expected_class_name);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001180 return true;
Douglas Gregor831c93f2008-11-05 20:51:48 +00001181 }
1182
1183 // Consume the identifier.
Douglas Gregor18473f32010-01-12 21:28:44 +00001184 EndLocation = IdLoc;
Nick Lewycky19b9f952010-07-26 16:56:01 +00001185
1186 // Fake up a Declarator to use with ActOnTypeName.
John McCall084e83d2011-03-24 11:26:52 +00001187 DeclSpec DS(AttrFactory);
Nick Lewycky19b9f952010-07-26 16:56:01 +00001188 DS.SetRangeStart(IdLoc);
1189 DS.SetRangeEnd(EndLocation);
Douglas Gregore7c20652011-03-02 00:47:37 +00001190 DS.getTypeSpecScope() = SS;
Nick Lewycky19b9f952010-07-26 16:56:01 +00001191
Craig Topper161e4db2014-05-21 06:02:52 +00001192 const char *PrevSpec = nullptr;
Nick Lewycky19b9f952010-07-26 16:56:01 +00001193 unsigned DiagID;
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001194 DS.SetTypeSpecType(TST_typename, IdLoc, PrevSpec, DiagID, Type,
1195 Actions.getASTContext().getPrintingPolicy());
Nick Lewycky19b9f952010-07-26 16:56:01 +00001196
1197 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1198 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
Douglas Gregor831c93f2008-11-05 20:51:48 +00001199}
1200
John McCall8d32c052012-05-22 21:28:12 +00001201void Parser::ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001202 while (Tok.isOneOf(tok::kw___single_inheritance,
1203 tok::kw___multiple_inheritance,
1204 tok::kw___virtual_inheritance)) {
John McCall8d32c052012-05-22 21:28:12 +00001205 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
1206 SourceLocation AttrNameLoc = ConsumeToken();
Craig Topper161e4db2014-05-21 06:02:52 +00001207 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
Aaron Ballman8edb5c22013-12-18 23:44:18 +00001208 AttributeList::AS_Keyword);
John McCall8d32c052012-05-22 21:28:12 +00001209 }
1210}
1211
Richard Smith369b9f92012-06-25 21:37:02 +00001212/// Determine whether the following tokens are valid after a type-specifier
1213/// which could be a standalone declaration. This will conservatively return
1214/// true if there's any doubt, and is appropriate for insert-';' fixits.
Richard Smith200f47c2012-07-02 19:14:01 +00001215bool Parser::isValidAfterTypeSpecifier(bool CouldBeBitfield) {
Richard Smith369b9f92012-06-25 21:37:02 +00001216 // This switch enumerates the valid "follow" set for type-specifiers.
1217 switch (Tok.getKind()) {
1218 default: break;
1219 case tok::semi: // struct foo {...} ;
1220 case tok::star: // struct foo {...} * P;
1221 case tok::amp: // struct foo {...} & R = ...
Richard Smith1ac67d12013-01-19 03:48:05 +00001222 case tok::ampamp: // struct foo {...} && R = ...
Richard Smith369b9f92012-06-25 21:37:02 +00001223 case tok::identifier: // struct foo {...} V ;
1224 case tok::r_paren: //(struct foo {...} ) {4}
1225 case tok::annot_cxxscope: // struct foo {...} a:: b;
1226 case tok::annot_typename: // struct foo {...} a ::b;
1227 case tok::annot_template_id: // struct foo {...} a<int> ::b;
1228 case tok::l_paren: // struct foo {...} ( x);
1229 case tok::comma: // __builtin_offsetof(struct foo{...} ,
Richard Smith1ac67d12013-01-19 03:48:05 +00001230 case tok::kw_operator: // struct foo operator ++() {...}
Alp Tokerd3f79c52013-11-24 20:24:54 +00001231 case tok::kw___declspec: // struct foo {...} __declspec(...)
Richard Smith843f18f2014-08-13 02:13:15 +00001232 case tok::l_square: // void f(struct f [ 3])
1233 case tok::ellipsis: // void f(struct f ... [Ns])
Abramo Bagnara152eb392014-08-16 08:29:27 +00001234 // FIXME: we should emit semantic diagnostic when declaration
1235 // attribute is in type attribute position.
1236 case tok::kw___attribute: // struct foo __attribute__((used)) x;
David Majnemer15b311c2016-06-14 03:20:28 +00001237 case tok::annot_pragma_pack: // struct foo {...} _Pragma(pack(pop));
1238 // struct foo {...} _Pragma(section(...));
1239 case tok::annot_pragma_ms_pragma:
1240 // struct foo {...} _Pragma(vtordisp(pop));
1241 case tok::annot_pragma_ms_vtordisp:
1242 // struct foo {...} _Pragma(pointers_to_members(...));
1243 case tok::annot_pragma_ms_pointers_to_members:
Richard Smith369b9f92012-06-25 21:37:02 +00001244 return true;
Richard Smith200f47c2012-07-02 19:14:01 +00001245 case tok::colon:
1246 return CouldBeBitfield; // enum E { ... } : 2;
Reid Klecknercfa91552016-03-21 16:08:49 +00001247 // Microsoft compatibility
1248 case tok::kw___cdecl: // struct foo {...} __cdecl x;
1249 case tok::kw___fastcall: // struct foo {...} __fastcall x;
1250 case tok::kw___stdcall: // struct foo {...} __stdcall x;
1251 case tok::kw___thiscall: // struct foo {...} __thiscall x;
1252 case tok::kw___vectorcall: // struct foo {...} __vectorcall x;
1253 // We will diagnose these calling-convention specifiers on non-function
1254 // declarations later, so claim they are valid after a type specifier.
1255 return getLangOpts().MicrosoftExt;
Richard Smith369b9f92012-06-25 21:37:02 +00001256 // Type qualifiers
1257 case tok::kw_const: // struct foo {...} const x;
1258 case tok::kw_volatile: // struct foo {...} volatile x;
1259 case tok::kw_restrict: // struct foo {...} restrict x;
Richard Smith843f18f2014-08-13 02:13:15 +00001260 case tok::kw__Atomic: // struct foo {...} _Atomic x;
Nico Rieck3e1ee832014-12-04 23:30:25 +00001261 case tok::kw___unaligned: // struct foo {...} __unaligned *x;
Richard Smith1ac67d12013-01-19 03:48:05 +00001262 // Function specifiers
1263 // Note, no 'explicit'. An explicit function must be either a conversion
1264 // operator or a constructor. Either way, it can't have a return type.
1265 case tok::kw_inline: // struct foo inline f();
1266 case tok::kw_virtual: // struct foo virtual f();
1267 case tok::kw_friend: // struct foo friend f();
Richard Smith369b9f92012-06-25 21:37:02 +00001268 // Storage-class specifiers
1269 case tok::kw_static: // struct foo {...} static x;
1270 case tok::kw_extern: // struct foo {...} extern x;
1271 case tok::kw_typedef: // struct foo {...} typedef x;
1272 case tok::kw_register: // struct foo {...} register x;
1273 case tok::kw_auto: // struct foo {...} auto x;
1274 case tok::kw_mutable: // struct foo {...} mutable x;
Richard Smith1ac67d12013-01-19 03:48:05 +00001275 case tok::kw_thread_local: // struct foo {...} thread_local x;
Richard Smith369b9f92012-06-25 21:37:02 +00001276 case tok::kw_constexpr: // struct foo {...} constexpr x;
1277 // As shown above, type qualifiers and storage class specifiers absolutely
1278 // can occur after class specifiers according to the grammar. However,
1279 // almost no one actually writes code like this. If we see one of these,
1280 // it is much more likely that someone missed a semi colon and the
1281 // type/storage class specifier we're seeing is part of the *next*
1282 // intended declaration, as in:
1283 //
1284 // struct foo { ... }
1285 // typedef int X;
1286 //
1287 // We'd really like to emit a missing semicolon error instead of emitting
1288 // an error on the 'int' saying that you can't have two type specifiers in
1289 // the same declaration of X. Because of this, we look ahead past this
1290 // token to see if it's a type specifier. If so, we know the code is
1291 // otherwise invalid, so we can produce the expected semi error.
1292 if (!isKnownToBeTypeSpecifier(NextToken()))
1293 return true;
1294 break;
1295 case tok::r_brace: // struct bar { struct foo {...} }
1296 // Missing ';' at end of struct is accepted as an extension in C mode.
1297 if (!getLangOpts().CPlusPlus)
1298 return true;
1299 break;
Richard Smith52c5b872013-01-29 04:13:32 +00001300 case tok::greater:
1301 // template<class T = class X>
1302 return getLangOpts().CPlusPlus;
Richard Smith369b9f92012-06-25 21:37:02 +00001303 }
1304 return false;
1305}
1306
Douglas Gregor556877c2008-04-13 21:30:24 +00001307/// ParseClassSpecifier - Parse a C++ class-specifier [C++ class] or
1308/// elaborated-type-specifier [C++ dcl.type.elab]; we can't tell which
1309/// until we reach the start of a definition or see a token that
Richard Smithc5b05522012-03-12 07:56:15 +00001310/// cannot start a definition.
Douglas Gregor556877c2008-04-13 21:30:24 +00001311///
1312/// class-specifier: [C++ class]
1313/// class-head '{' member-specification[opt] '}'
1314/// class-head '{' member-specification[opt] '}' attributes[opt]
1315/// class-head:
1316/// class-key identifier[opt] base-clause[opt]
1317/// class-key nested-name-specifier identifier base-clause[opt]
1318/// class-key nested-name-specifier[opt] simple-template-id
1319/// base-clause[opt]
1320/// [GNU] class-key attributes[opt] identifier[opt] base-clause[opt]
Mike Stump11289f42009-09-09 15:08:12 +00001321/// [GNU] class-key attributes[opt] nested-name-specifier
Douglas Gregor556877c2008-04-13 21:30:24 +00001322/// identifier base-clause[opt]
Mike Stump11289f42009-09-09 15:08:12 +00001323/// [GNU] class-key attributes[opt] nested-name-specifier[opt]
Douglas Gregor556877c2008-04-13 21:30:24 +00001324/// simple-template-id base-clause[opt]
1325/// class-key:
1326/// 'class'
1327/// 'struct'
1328/// 'union'
1329///
1330/// elaborated-type-specifier: [C++ dcl.type.elab]
Mike Stump11289f42009-09-09 15:08:12 +00001331/// class-key ::[opt] nested-name-specifier[opt] identifier
1332/// class-key ::[opt] nested-name-specifier[opt] 'template'[opt]
1333/// simple-template-id
Douglas Gregor556877c2008-04-13 21:30:24 +00001334///
1335/// Note that the C++ class-specifier and elaborated-type-specifier,
1336/// together, subsume the C99 struct-or-union-specifier:
1337///
1338/// struct-or-union-specifier: [C99 6.7.2.1]
1339/// struct-or-union identifier[opt] '{' struct-contents '}'
1340/// struct-or-union identifier
1341/// [GNU] struct-or-union attributes[opt] identifier[opt] '{' struct-contents
1342/// '}' attributes[opt]
1343/// [GNU] struct-or-union attributes[opt] identifier
1344/// struct-or-union:
1345/// 'struct'
1346/// 'union'
Chris Lattnerffaa0e62009-04-12 21:49:30 +00001347void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind,
1348 SourceLocation StartLoc, DeclSpec &DS,
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001349 const ParsedTemplateInfo &TemplateInfo,
Douglas Gregordf593fb2011-11-07 17:33:42 +00001350 AccessSpecifier AS,
Michael Han9407e502012-11-26 22:54:45 +00001351 bool EnteringContext, DeclSpecContext DSC,
Bill Wendling44426052012-12-20 19:22:21 +00001352 ParsedAttributesWithRange &Attributes) {
Joao Matose9a3ed42012-08-31 22:18:20 +00001353 DeclSpec::TST TagType;
1354 if (TagTokKind == tok::kw_struct)
1355 TagType = DeclSpec::TST_struct;
1356 else if (TagTokKind == tok::kw___interface)
1357 TagType = DeclSpec::TST_interface;
1358 else if (TagTokKind == tok::kw_class)
1359 TagType = DeclSpec::TST_class;
1360 else {
Chris Lattnerffaa0e62009-04-12 21:49:30 +00001361 assert(TagTokKind == tok::kw_union && "Not a class specifier");
1362 TagType = DeclSpec::TST_union;
1363 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001364
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00001365 if (Tok.is(tok::code_completion)) {
1366 // Code completion for a struct, class, or union name.
Douglas Gregor0be31a22010-07-02 17:43:08 +00001367 Actions.CodeCompleteTag(getCurScope(), TagType);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001368 return cutOffParsing();
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00001369 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001370
Chandler Carruth2d69ec72010-06-28 08:39:25 +00001371 // C++03 [temp.explicit] 14.7.2/8:
1372 // The usual access checking rules do not apply to names used to specify
1373 // explicit instantiations.
1374 //
1375 // As an extension we do not perform access checking on the names used to
1376 // specify explicit specializations either. This is important to allow
1377 // specializing traits classes for private types.
John McCall6347b682012-05-07 06:16:58 +00001378 //
1379 // Note that we don't suppress if this turns out to be an elaborated
1380 // type specifier.
1381 bool shouldDelayDiagsInTag =
1382 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
1383 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
1384 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
Chandler Carruth2d69ec72010-06-28 08:39:25 +00001385
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001386 ParsedAttributesWithRange attrs(AttrFactory);
Douglas Gregor556877c2008-04-13 21:30:24 +00001387 // If attributes exist after tag, parse them.
Richard Smith37a45dd2013-10-24 01:21:09 +00001388 MaybeParseGNUAttributes(attrs);
Aaron Ballman068aa512015-05-20 20:58:33 +00001389 MaybeParseMicrosoftDeclSpecs(attrs);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001390
John McCall8d32c052012-05-22 21:28:12 +00001391 // Parse inheritance specifiers.
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001392 if (Tok.isOneOf(tok::kw___single_inheritance,
1393 tok::kw___multiple_inheritance,
1394 tok::kw___virtual_inheritance))
Richard Smith37a45dd2013-10-24 01:21:09 +00001395 ParseMicrosoftInheritanceClassAttributes(attrs);
John McCall8d32c052012-05-22 21:28:12 +00001396
Alexis Hunt96d5c762009-11-21 08:43:09 +00001397 // If C++0x attributes exist here, parse them.
1398 // FIXME: Are we consistent with the ordering of parsing of different
1399 // styles of attributes?
Richard Smith89645bc2013-01-02 12:01:23 +00001400 MaybeParseCXX11Attributes(attrs);
Mike Stump11289f42009-09-09 15:08:12 +00001401
Michael Han309af292013-01-07 16:57:11 +00001402 // Source location used by FIXIT to insert misplaced
1403 // C++11 attributes
1404 SourceLocation AttrFixitLoc = Tok.getLocation();
1405
Nico Weber7c3c5be2014-09-23 04:09:56 +00001406 if (TagType == DeclSpec::TST_struct &&
David Majnemer86330af2014-12-29 02:14:26 +00001407 Tok.isNot(tok::identifier) &&
1408 !Tok.isAnnotation() &&
Nico Weber7c3c5be2014-09-23 04:09:56 +00001409 Tok.getIdentifierInfo() &&
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001410 Tok.isOneOf(tok::kw___is_abstract,
Eric Fiselier07360662017-04-12 22:12:15 +00001411 tok::kw___is_aggregate,
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001412 tok::kw___is_arithmetic,
1413 tok::kw___is_array,
David Majnemerb3d96882016-05-23 17:21:55 +00001414 tok::kw___is_assignable,
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001415 tok::kw___is_base_of,
1416 tok::kw___is_class,
1417 tok::kw___is_complete_type,
1418 tok::kw___is_compound,
1419 tok::kw___is_const,
1420 tok::kw___is_constructible,
1421 tok::kw___is_convertible,
1422 tok::kw___is_convertible_to,
1423 tok::kw___is_destructible,
1424 tok::kw___is_empty,
1425 tok::kw___is_enum,
1426 tok::kw___is_floating_point,
1427 tok::kw___is_final,
1428 tok::kw___is_function,
1429 tok::kw___is_fundamental,
1430 tok::kw___is_integral,
1431 tok::kw___is_interface_class,
1432 tok::kw___is_literal,
1433 tok::kw___is_lvalue_expr,
1434 tok::kw___is_lvalue_reference,
1435 tok::kw___is_member_function_pointer,
1436 tok::kw___is_member_object_pointer,
1437 tok::kw___is_member_pointer,
1438 tok::kw___is_nothrow_assignable,
1439 tok::kw___is_nothrow_constructible,
1440 tok::kw___is_nothrow_destructible,
1441 tok::kw___is_object,
1442 tok::kw___is_pod,
1443 tok::kw___is_pointer,
1444 tok::kw___is_polymorphic,
1445 tok::kw___is_reference,
1446 tok::kw___is_rvalue_expr,
1447 tok::kw___is_rvalue_reference,
1448 tok::kw___is_same,
1449 tok::kw___is_scalar,
1450 tok::kw___is_sealed,
1451 tok::kw___is_signed,
1452 tok::kw___is_standard_layout,
1453 tok::kw___is_trivial,
1454 tok::kw___is_trivially_assignable,
1455 tok::kw___is_trivially_constructible,
1456 tok::kw___is_trivially_copyable,
1457 tok::kw___is_union,
1458 tok::kw___is_unsigned,
1459 tok::kw___is_void,
1460 tok::kw___is_volatile))
Nico Weber7c3c5be2014-09-23 04:09:56 +00001461 // GNU libstdc++ 4.2 and libc++ use certain intrinsic names as the
1462 // name of struct templates, but some are keywords in GCC >= 4.3
1463 // and Clang. Therefore, when we see the token sequence "struct
1464 // X", make X into a normal identifier rather than a keyword, to
1465 // allow libstdc++ 4.2 and libc++ to work properly.
1466 TryKeywordIdentFallback(true);
Mike Stump11289f42009-09-09 15:08:12 +00001467
David Majnemer51fd8a02015-07-22 23:46:18 +00001468 struct PreserveAtomicIdentifierInfoRAII {
1469 PreserveAtomicIdentifierInfoRAII(Token &Tok, bool Enabled)
1470 : AtomicII(nullptr) {
1471 if (!Enabled)
1472 return;
1473 assert(Tok.is(tok::kw__Atomic));
1474 AtomicII = Tok.getIdentifierInfo();
1475 AtomicII->revertTokenIDToIdentifier();
1476 Tok.setKind(tok::identifier);
1477 }
1478 ~PreserveAtomicIdentifierInfoRAII() {
1479 if (!AtomicII)
1480 return;
1481 AtomicII->revertIdentifierToTokenID(tok::kw__Atomic);
1482 }
1483 IdentifierInfo *AtomicII;
1484 };
1485
1486 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
1487 // implementation for VS2013 uses _Atomic as an identifier for one of the
1488 // classes in <atomic>. When we are parsing 'struct _Atomic', don't consider
1489 // '_Atomic' to be a keyword. We are careful to undo this so that clang can
1490 // use '_Atomic' in its own header files.
1491 bool ShouldChangeAtomicToIdentifier = getLangOpts().MSVCCompat &&
1492 Tok.is(tok::kw__Atomic) &&
1493 TagType == DeclSpec::TST_struct;
1494 PreserveAtomicIdentifierInfoRAII AtomicTokenGuard(
1495 Tok, ShouldChangeAtomicToIdentifier);
1496
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001497 // Parse the (optional) nested-name-specifier.
John McCall9dab4e62009-12-12 11:40:51 +00001498 CXXScopeSpec &SS = DS.getTypeSpecScope();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001499 if (getLangOpts().CPlusPlus) {
Serge Pavlov458ea762014-07-16 05:16:52 +00001500 // "FOO : BAR" is not a potential typo for "FOO::BAR". In this context it
1501 // is a base-specifier-list.
Chris Lattnerd5c1c9d2009-12-10 00:32:41 +00001502 ColonProtectionRAIIObject X(*this);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001503
Nico Webercfaa4cd2015-02-15 07:26:13 +00001504 CXXScopeSpec Spec;
1505 bool HasValidSpec = true;
David Blaikieefdccaa2016-01-15 23:43:34 +00001506 if (ParseOptionalCXXScopeSpecifier(Spec, nullptr, EnteringContext)) {
John McCall413021a2010-07-30 06:26:29 +00001507 DS.SetTypeSpecError();
Nico Webercfaa4cd2015-02-15 07:26:13 +00001508 HasValidSpec = false;
1509 }
1510 if (Spec.isSet())
1511 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::annot_template_id)) {
Alp Tokerec543272013-12-24 09:48:30 +00001512 Diag(Tok, diag::err_expected) << tok::identifier;
Nico Webercfaa4cd2015-02-15 07:26:13 +00001513 HasValidSpec = false;
1514 }
1515 if (HasValidSpec)
1516 SS = Spec;
Chris Lattnerd5c1c9d2009-12-10 00:32:41 +00001517 }
Douglas Gregor67a65642009-02-17 23:15:12 +00001518
Douglas Gregor916462b2009-10-30 21:46:58 +00001519 TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
1520
Douglas Gregor67a65642009-02-17 23:15:12 +00001521 // Parse the (optional) class name or simple-template-id.
Craig Topper161e4db2014-05-21 06:02:52 +00001522 IdentifierInfo *Name = nullptr;
Douglas Gregor556877c2008-04-13 21:30:24 +00001523 SourceLocation NameLoc;
Craig Topper161e4db2014-05-21 06:02:52 +00001524 TemplateIdAnnotation *TemplateId = nullptr;
Douglas Gregor556877c2008-04-13 21:30:24 +00001525 if (Tok.is(tok::identifier)) {
1526 Name = Tok.getIdentifierInfo();
1527 NameLoc = ConsumeToken();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001528
David Blaikiebbafb8a2012-03-11 07:00:24 +00001529 if (Tok.is(tok::less) && getLangOpts().CPlusPlus) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001530 // The name was supposed to refer to a template, but didn't.
Douglas Gregor916462b2009-10-30 21:46:58 +00001531 // Eat the template argument list and try to continue parsing this as
1532 // a class (or template thereof).
1533 TemplateArgList TemplateArgs;
Douglas Gregor916462b2009-10-30 21:46:58 +00001534 SourceLocation LAngleLoc, RAngleLoc;
Richard Smith9a420f92017-05-10 21:47:30 +00001535 if (ParseTemplateIdAfterTemplateName(true, LAngleLoc, TemplateArgs,
1536 RAngleLoc)) {
Douglas Gregor916462b2009-10-30 21:46:58 +00001537 // We couldn't parse the template argument list at all, so don't
1538 // try to give any location information for the list.
1539 LAngleLoc = RAngleLoc = SourceLocation();
1540 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001541
Douglas Gregor916462b2009-10-30 21:46:58 +00001542 Diag(NameLoc, diag::err_explicit_spec_non_template)
Alp Toker01d65e12014-01-06 12:54:41 +00001543 << (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
1544 << TagTokKind << Name << SourceRange(LAngleLoc, RAngleLoc);
Joao Matose9a3ed42012-08-31 22:18:20 +00001545
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001546 // Strip off the last template parameter list if it was empty, since
Douglas Gregor1d0015f2009-10-30 22:09:44 +00001547 // we've removed its template argument list.
1548 if (TemplateParams && TemplateInfo.LastParameterListWasEmpty) {
Hubert Tong97b06632016-04-13 18:41:03 +00001549 if (TemplateParams->size() > 1) {
Douglas Gregor1d0015f2009-10-30 22:09:44 +00001550 TemplateParams->pop_back();
1551 } else {
Craig Topper161e4db2014-05-21 06:02:52 +00001552 TemplateParams = nullptr;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001553 const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind
Douglas Gregor1d0015f2009-10-30 22:09:44 +00001554 = ParsedTemplateInfo::NonTemplate;
1555 }
1556 } else if (TemplateInfo.Kind
1557 == ParsedTemplateInfo::ExplicitInstantiation) {
1558 // Pretend this is just a forward declaration.
Craig Topper161e4db2014-05-21 06:02:52 +00001559 TemplateParams = nullptr;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001560 const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind
Douglas Gregor916462b2009-10-30 21:46:58 +00001561 = ParsedTemplateInfo::NonTemplate;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001562 const_cast<ParsedTemplateInfo&>(TemplateInfo).TemplateLoc
Douglas Gregor1d0015f2009-10-30 22:09:44 +00001563 = SourceLocation();
1564 const_cast<ParsedTemplateInfo&>(TemplateInfo).ExternLoc
1565 = SourceLocation();
Douglas Gregor916462b2009-10-30 21:46:58 +00001566 }
Douglas Gregor916462b2009-10-30 21:46:58 +00001567 }
Douglas Gregor7f741122009-02-25 19:37:18 +00001568 } else if (Tok.is(tok::annot_template_id)) {
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00001569 TemplateId = takeTemplateIdAnnotation(Tok);
Richard Smithaf3b3252017-05-18 19:21:48 +00001570 NameLoc = ConsumeAnnotationToken();
Douglas Gregor67a65642009-02-17 23:15:12 +00001571
Douglas Gregore7c20652011-03-02 00:47:37 +00001572 if (TemplateId->Kind != TNK_Type_template &&
1573 TemplateId->Kind != TNK_Dependent_template_name) {
Douglas Gregor7f741122009-02-25 19:37:18 +00001574 // The template-name in the simple-template-id refers to
1575 // something other than a class template. Give an appropriate
1576 // error message and skip to the ';'.
1577 SourceRange Range(NameLoc);
1578 if (SS.isNotEmpty())
1579 Range.setBegin(SS.getBeginLoc());
Douglas Gregor67a65642009-02-17 23:15:12 +00001580
Richard Smith72bfbd82013-12-04 00:28:23 +00001581 // FIXME: Name may be null here.
Douglas Gregor7f741122009-02-25 19:37:18 +00001582 Diag(TemplateId->LAngleLoc, diag::err_template_spec_syntax_non_template)
Richard Trieu30f93852013-06-19 22:25:01 +00001583 << TemplateId->Name << static_cast<int>(TemplateId->Kind) << Range;
Mike Stump11289f42009-09-09 15:08:12 +00001584
Douglas Gregor7f741122009-02-25 19:37:18 +00001585 DS.SetTypeSpecError();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001586 SkipUntil(tok::semi, StopBeforeMatch);
Douglas Gregor7f741122009-02-25 19:37:18 +00001587 return;
Douglas Gregor67a65642009-02-17 23:15:12 +00001588 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001589 }
1590
Richard Smithbfdb1082012-03-12 08:56:40 +00001591 // There are four options here.
1592 // - If we are in a trailing return type, this is always just a reference,
1593 // and we must not try to parse a definition. For instance,
1594 // [] () -> struct S { };
1595 // does not define a type.
1596 // - If we have 'struct foo {...', 'struct foo :...',
1597 // 'struct foo final :' or 'struct foo final {', then this is a definition.
1598 // - If we have 'struct foo;', then this is either a forward declaration
1599 // or a friend declaration, which have to be treated differently.
1600 // - Otherwise we have something like 'struct foo xyz', a reference.
Michael Han9407e502012-11-26 22:54:45 +00001601 //
1602 // We also detect these erroneous cases to provide better diagnostic for
1603 // C++11 attributes parsing.
1604 // - attributes follow class name:
1605 // struct foo [[]] {};
1606 // - attributes appear before or after 'final':
1607 // struct foo [[]] final [[]] {};
1608 //
Richard Smithc5b05522012-03-12 07:56:15 +00001609 // However, in type-specifier-seq's, things look like declarations but are
1610 // just references, e.g.
1611 // new struct s;
Sebastian Redl2b372722010-02-03 21:21:43 +00001612 // or
Richard Smithc5b05522012-03-12 07:56:15 +00001613 // &T::operator struct s;
Richard Smith649c7b062014-01-08 00:56:48 +00001614 // For these, DSC is DSC_type_specifier or DSC_alias_declaration.
Michael Han9407e502012-11-26 22:54:45 +00001615
1616 // If there are attributes after class name, parse them.
Richard Smith89645bc2013-01-02 12:01:23 +00001617 MaybeParseCXX11Attributes(Attributes);
Michael Han9407e502012-11-26 22:54:45 +00001618
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001619 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
John McCallfaf5fb42010-08-26 23:41:50 +00001620 Sema::TagUseKind TUK;
Richard Smithbfdb1082012-03-12 08:56:40 +00001621 if (DSC == DSC_trailing)
1622 TUK = Sema::TUK_Reference;
1623 else if (Tok.is(tok::l_brace) ||
1624 (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
Richard Smith89645bc2013-01-02 12:01:23 +00001625 (isCXX11FinalKeyword() &&
David Blaikie9933a5a2012-03-12 15:39:49 +00001626 (NextToken().is(tok::l_brace) || NextToken().is(tok::colon)))) {
Douglas Gregor3dad8422009-09-26 06:47:28 +00001627 if (DS.isFriendSpecified()) {
1628 // C++ [class.friend]p2:
1629 // A class shall not be defined in a friend declaration.
Richard Smith0f8ee222012-01-10 01:33:14 +00001630 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
Douglas Gregor3dad8422009-09-26 06:47:28 +00001631 << SourceRange(DS.getFriendSpecLoc());
1632
1633 // Skip everything up to the semicolon, so that this looks like a proper
1634 // friend class (or template thereof) declaration.
Alexey Bataevee6507d2013-11-18 08:17:37 +00001635 SkipUntil(tok::semi, StopBeforeMatch);
John McCallfaf5fb42010-08-26 23:41:50 +00001636 TUK = Sema::TUK_Friend;
Douglas Gregor3dad8422009-09-26 06:47:28 +00001637 } else {
1638 // Okay, this is a class definition.
John McCallfaf5fb42010-08-26 23:41:50 +00001639 TUK = Sema::TUK_Definition;
Douglas Gregor3dad8422009-09-26 06:47:28 +00001640 }
Richard Smith434516c2013-02-22 06:46:23 +00001641 } else if (isCXX11FinalKeyword() && (NextToken().is(tok::l_square) ||
1642 NextToken().is(tok::kw_alignas))) {
Michael Han9407e502012-11-26 22:54:45 +00001643 // We can't tell if this is a definition or reference
1644 // until we skipped the 'final' and C++11 attribute specifiers.
1645 TentativeParsingAction PA(*this);
1646
1647 // Skip the 'final' keyword.
1648 ConsumeToken();
1649
1650 // Skip C++11 attribute specifiers.
1651 while (true) {
1652 if (Tok.is(tok::l_square) && NextToken().is(tok::l_square)) {
1653 ConsumeBracket();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001654 if (!SkipUntil(tok::r_square, StopAtSemi))
Michael Han9407e502012-11-26 22:54:45 +00001655 break;
Richard Smith434516c2013-02-22 06:46:23 +00001656 } else if (Tok.is(tok::kw_alignas) && NextToken().is(tok::l_paren)) {
Michael Han9407e502012-11-26 22:54:45 +00001657 ConsumeToken();
1658 ConsumeParen();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001659 if (!SkipUntil(tok::r_paren, StopAtSemi))
Michael Han9407e502012-11-26 22:54:45 +00001660 break;
1661 } else {
1662 break;
1663 }
1664 }
1665
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001666 if (Tok.isOneOf(tok::l_brace, tok::colon))
Michael Han9407e502012-11-26 22:54:45 +00001667 TUK = Sema::TUK_Definition;
1668 else
1669 TUK = Sema::TUK_Reference;
1670
1671 PA.Revert();
Richard Smith649c7b062014-01-08 00:56:48 +00001672 } else if (!isTypeSpecifier(DSC) &&
Richard Smith369b9f92012-06-25 21:37:02 +00001673 (Tok.is(tok::semi) ||
Richard Smith200f47c2012-07-02 19:14:01 +00001674 (Tok.isAtStartOfLine() && !isValidAfterTypeSpecifier(false)))) {
John McCallfaf5fb42010-08-26 23:41:50 +00001675 TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
Joao Matose9a3ed42012-08-31 22:18:20 +00001676 if (Tok.isNot(tok::semi)) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001677 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
Joao Matose9a3ed42012-08-31 22:18:20 +00001678 // A semicolon was missing after this declaration. Diagnose and recover.
Alp Toker383d2c42014-01-01 03:08:43 +00001679 ExpectAndConsume(tok::semi, diag::err_expected_after,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001680 DeclSpec::getSpecifierName(TagType, PPol));
Joao Matose9a3ed42012-08-31 22:18:20 +00001681 PP.EnterToken(Tok);
1682 Tok.setKind(tok::semi);
1683 }
Richard Smith369b9f92012-06-25 21:37:02 +00001684 } else
John McCallfaf5fb42010-08-26 23:41:50 +00001685 TUK = Sema::TUK_Reference;
Douglas Gregor556877c2008-04-13 21:30:24 +00001686
Michael Han9407e502012-11-26 22:54:45 +00001687 // Forbid misplaced attributes. In cases of a reference, we pass attributes
1688 // to caller to handle.
Michael Han309af292013-01-07 16:57:11 +00001689 if (TUK != Sema::TUK_Reference) {
1690 // If this is not a reference, then the only possible
1691 // valid place for C++11 attributes to appear here
1692 // is between class-key and class-name. If there are
1693 // any attributes after class-name, we try a fixit to move
1694 // them to the right place.
1695 SourceRange AttrRange = Attributes.Range;
1696 if (AttrRange.isValid()) {
1697 Diag(AttrRange.getBegin(), diag::err_attributes_not_allowed)
1698 << AttrRange
1699 << FixItHint::CreateInsertionFromRange(AttrFixitLoc,
1700 CharSourceRange(AttrRange, true))
1701 << FixItHint::CreateRemoval(AttrRange);
1702
1703 // Recover by adding misplaced attributes to the attribute list
1704 // of the class so they can be applied on the class later.
1705 attrs.takeAllFrom(Attributes);
1706 }
1707 }
Michael Han9407e502012-11-26 22:54:45 +00001708
John McCall6347b682012-05-07 06:16:58 +00001709 // If this is an elaborated type specifier, and we delayed
1710 // diagnostics before, just merge them into the current pool.
1711 if (shouldDelayDiagsInTag) {
1712 diagsFromTag.done();
1713 if (TUK == Sema::TUK_Reference)
1714 diagsFromTag.redelay();
1715 }
1716
John McCall413021a2010-07-30 06:26:29 +00001717 if (!Name && !TemplateId && (DS.getTypeSpecType() == DeclSpec::TST_error ||
John McCallfaf5fb42010-08-26 23:41:50 +00001718 TUK != Sema::TUK_Definition)) {
John McCall413021a2010-07-30 06:26:29 +00001719 if (DS.getTypeSpecType() != DeclSpec::TST_error) {
1720 // We have a declaration or reference to an anonymous class.
1721 Diag(StartLoc, diag::err_anon_type_definition)
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001722 << DeclSpec::getSpecifierName(TagType, Policy);
John McCall413021a2010-07-30 06:26:29 +00001723 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001724
David Majnemer3252fd02013-12-05 01:36:53 +00001725 // If we are parsing a definition and stop at a base-clause, continue on
1726 // until the semicolon. Continuing from the comma will just trick us into
1727 // thinking we are seeing a variable declaration.
1728 if (TUK == Sema::TUK_Definition && Tok.is(tok::colon))
1729 SkipUntil(tok::semi, StopBeforeMatch);
1730 else
1731 SkipUntil(tok::comma, StopAtSemi);
Douglas Gregor556877c2008-04-13 21:30:24 +00001732 return;
1733 }
1734
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001735 // Create the tag portion of the class or class template.
John McCall48871652010-08-21 09:40:31 +00001736 DeclResult TagOrTempResult = true; // invalid
1737 TypeResult TypeResult = true; // invalid
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001738
Douglas Gregord6ab8742009-05-28 23:31:59 +00001739 bool Owned = false;
Richard Smithd9ba2242015-05-07 03:54:19 +00001740 Sema::SkipBodyInfo SkipBody;
John McCall06f6fe8d2009-09-04 01:14:41 +00001741 if (TemplateId) {
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001742 // Explicit specialization, class template partial specialization,
1743 // or explicit instantiation.
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00001744 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregor7f741122009-02-25 19:37:18 +00001745 TemplateId->NumArgs);
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001746 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
John McCallfaf5fb42010-08-26 23:41:50 +00001747 TUK == Sema::TUK_Declaration) {
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001748 // This is an explicit instantiation of a class template.
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001749 ProhibitAttributes(attrs);
1750
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001751 TagOrTempResult
Douglas Gregor0be31a22010-07-02 17:43:08 +00001752 = Actions.ActOnExplicitInstantiation(getCurScope(),
Douglas Gregor43e75172009-09-04 06:33:52 +00001753 TemplateInfo.ExternLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001754 TemplateInfo.TemplateLoc,
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001755 TagType,
Mike Stump11289f42009-09-09 15:08:12 +00001756 StartLoc,
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001757 SS,
John McCall3e56fd42010-08-23 07:28:44 +00001758 TemplateId->Template,
Mike Stump11289f42009-09-09 15:08:12 +00001759 TemplateId->TemplateNameLoc,
1760 TemplateId->LAngleLoc,
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001761 TemplateArgsPtr,
Mike Stump11289f42009-09-09 15:08:12 +00001762 TemplateId->RAngleLoc,
John McCall53fa7142010-12-24 02:08:15 +00001763 attrs.getList());
John McCallb7c5c272010-04-14 00:24:33 +00001764
1765 // Friend template-ids are treated as references unless
1766 // they have template headers, in which case they're ill-formed
1767 // (FIXME: "template <class T> friend class A<T>::B<int>;").
1768 // We diagnose this error in ActOnClassTemplateSpecialization.
John McCallfaf5fb42010-08-26 23:41:50 +00001769 } else if (TUK == Sema::TUK_Reference ||
1770 (TUK == Sema::TUK_Friend &&
John McCallb7c5c272010-04-14 00:24:33 +00001771 TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate)) {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001772 ProhibitAttributes(attrs);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00001773 TypeResult = Actions.ActOnTagTemplateIdType(TUK, TagType, StartLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00001774 TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00001775 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00001776 TemplateId->Template,
1777 TemplateId->TemplateNameLoc,
1778 TemplateId->LAngleLoc,
1779 TemplateArgsPtr,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00001780 TemplateId->RAngleLoc);
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001781 } else {
1782 // This is an explicit specialization or a class template
1783 // partial specialization.
1784 TemplateParameterLists FakedParamLists;
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001785 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1786 // This looks like an explicit instantiation, because we have
1787 // something like
1788 //
1789 // template class Foo<X>
1790 //
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001791 // but it actually has a definition. Most likely, this was
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001792 // meant to be an explicit specialization, but the user forgot
1793 // the '<>' after 'template'.
Richard Smith003c5e12013-11-08 19:03:29 +00001794 // It this is friend declaration however, since it cannot have a
1795 // template header, it is most likely that the user meant to
1796 // remove the 'template' keyword.
Larisse Voufob9bbaba2013-06-22 13:56:11 +00001797 assert((TUK == Sema::TUK_Definition || TUK == Sema::TUK_Friend) &&
Richard Smith003c5e12013-11-08 19:03:29 +00001798 "Expected a definition here");
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001799
Richard Smith003c5e12013-11-08 19:03:29 +00001800 if (TUK == Sema::TUK_Friend) {
1801 Diag(DS.getFriendSpecLoc(), diag::err_friend_explicit_instantiation);
Craig Topper161e4db2014-05-21 06:02:52 +00001802 TemplateParams = nullptr;
Richard Smith003c5e12013-11-08 19:03:29 +00001803 } else {
1804 SourceLocation LAngleLoc =
1805 PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
1806 Diag(TemplateId->TemplateNameLoc,
1807 diag::err_explicit_instantiation_with_definition)
1808 << SourceRange(TemplateInfo.TemplateLoc)
1809 << FixItHint::CreateInsertion(LAngleLoc, "<>");
1810
1811 // Create a fake template parameter list that contains only
1812 // "template<>", so that we treat this construct as a class
1813 // template specialization.
1814 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
Craig Topper96225a52015-12-24 23:58:25 +00001815 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
Hubert Tongf608c052016-04-29 18:05:37 +00001816 LAngleLoc, nullptr));
Richard Smith003c5e12013-11-08 19:03:29 +00001817 TemplateParams = &FakedParamLists;
1818 }
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001819 }
1820
1821 // Build the class template specialization.
Richard Smith4b55a9c2014-04-17 03:29:33 +00001822 TagOrTempResult = Actions.ActOnClassTemplateSpecialization(
1823 getCurScope(), TagType, TUK, StartLoc, DS.getModulePrivateSpecLoc(),
1824 *TemplateId, attrs.getList(),
Craig Topper161e4db2014-05-21 06:02:52 +00001825 MultiTemplateParamsArg(TemplateParams ? &(*TemplateParams)[0]
1826 : nullptr,
Richard Smithc7e6ff02015-05-18 20:36:47 +00001827 TemplateParams ? TemplateParams->size() : 0),
1828 &SkipBody);
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001829 }
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001830 } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
John McCallfaf5fb42010-08-26 23:41:50 +00001831 TUK == Sema::TUK_Declaration) {
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001832 // Explicit instantiation of a member of a class template
1833 // specialization, e.g.,
1834 //
1835 // template struct Outer<int>::Inner;
1836 //
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001837 ProhibitAttributes(attrs);
1838
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001839 TagOrTempResult
Douglas Gregor0be31a22010-07-02 17:43:08 +00001840 = Actions.ActOnExplicitInstantiation(getCurScope(),
Douglas Gregor43e75172009-09-04 06:33:52 +00001841 TemplateInfo.ExternLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001842 TemplateInfo.TemplateLoc,
1843 TagType, StartLoc, SS, Name,
John McCall53fa7142010-12-24 02:08:15 +00001844 NameLoc, attrs.getList());
John McCallace48cd2010-10-19 01:40:49 +00001845 } else if (TUK == Sema::TUK_Friend &&
1846 TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate) {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001847 ProhibitAttributes(attrs);
1848
John McCallace48cd2010-10-19 01:40:49 +00001849 TagOrTempResult =
1850 Actions.ActOnTemplatedFriendTag(getCurScope(), DS.getFriendSpecLoc(),
1851 TagType, StartLoc, SS,
John McCall53fa7142010-12-24 02:08:15 +00001852 Name, NameLoc, attrs.getList(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00001853 MultiTemplateParamsArg(
Craig Topper161e4db2014-05-21 06:02:52 +00001854 TemplateParams? &(*TemplateParams)[0]
1855 : nullptr,
John McCallace48cd2010-10-19 01:40:49 +00001856 TemplateParams? TemplateParams->size() : 0));
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001857 } else {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001858 if (TUK != Sema::TUK_Declaration && TUK != Sema::TUK_Definition)
1859 ProhibitAttributes(attrs);
Richard Smith003c5e12013-11-08 19:03:29 +00001860
Larisse Voufo725de3e2013-06-21 00:08:46 +00001861 if (TUK == Sema::TUK_Definition &&
1862 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1863 // If the declarator-id is not a template-id, issue a diagnostic and
1864 // recover by ignoring the 'template' keyword.
1865 Diag(Tok, diag::err_template_defn_explicit_instantiation)
1866 << 1 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
Craig Topper161e4db2014-05-21 06:02:52 +00001867 TemplateParams = nullptr;
Larisse Voufo725de3e2013-06-21 00:08:46 +00001868 }
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001869
John McCall7f41d982009-09-11 04:59:25 +00001870 bool IsDependent = false;
1871
John McCall32723e92010-10-19 18:40:57 +00001872 // Don't pass down template parameter lists if this is just a tag
1873 // reference. For example, we don't need the template parameters here:
1874 // template <class T> class A *makeA(T t);
1875 MultiTemplateParamsArg TParams;
1876 if (TUK != Sema::TUK_Reference && TemplateParams)
1877 TParams =
1878 MultiTemplateParamsArg(&(*TemplateParams)[0], TemplateParams->size());
1879
Nico Weber32a0fc72016-09-03 03:01:32 +00001880 stripTypeAttributesOffDeclSpec(attrs, DS, TUK);
David Majnemer936b4112015-04-19 07:53:29 +00001881
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001882 // Declaration or definition of a class type
John McCallace48cd2010-10-19 01:40:49 +00001883 TagOrTempResult = Actions.ActOnTag(getCurScope(), TagType, TUK, StartLoc,
John McCall53fa7142010-12-24 02:08:15 +00001884 SS, Name, NameLoc, attrs.getList(), AS,
Douglas Gregor2820e692011-09-09 19:05:14 +00001885 DS.getModulePrivateSpecLoc(),
Richard Smith0f8ee222012-01-10 01:33:14 +00001886 TParams, Owned, IsDependent,
1887 SourceLocation(), false,
Richard Smith649c7b062014-01-08 00:56:48 +00001888 clang::TypeResult(),
Richard Smith65ebb4a2015-03-26 04:09:53 +00001889 DSC == DSC_type_specifier,
Akira Hatanaka12ddcee2017-06-26 18:46:12 +00001890 DSC == DSC_template_param ||
1891 DSC == DSC_template_type_arg, &SkipBody);
John McCall7f41d982009-09-11 04:59:25 +00001892
1893 // If ActOnTag said the type was dependent, try again with the
1894 // less common call.
John McCallace48cd2010-10-19 01:40:49 +00001895 if (IsDependent) {
1896 assert(TUK == Sema::TUK_Reference || TUK == Sema::TUK_Friend);
Douglas Gregor0be31a22010-07-02 17:43:08 +00001897 TypeResult = Actions.ActOnDependentTag(getCurScope(), TagType, TUK,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001898 SS, Name, StartLoc, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +00001899 }
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001900 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001901
Douglas Gregor556877c2008-04-13 21:30:24 +00001902 // If there is a body, parse it and inform the actions module.
John McCallfaf5fb42010-08-26 23:41:50 +00001903 if (TUK == Sema::TUK_Definition) {
John McCall2d814c32009-12-19 21:48:58 +00001904 assert(Tok.is(tok::l_brace) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00001905 (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
Richard Smith89645bc2013-01-02 12:01:23 +00001906 isCXX11FinalKeyword());
Richard Smithd9ba2242015-05-07 03:54:19 +00001907 if (SkipBody.ShouldSkip)
Richard Smith65ebb4a2015-03-26 04:09:53 +00001908 SkipCXXMemberSpecification(StartLoc, AttrFixitLoc, TagType,
1909 TagOrTempResult.get());
1910 else if (getLangOpts().CPlusPlus)
Michael Han309af292013-01-07 16:57:11 +00001911 ParseCXXMemberSpecification(StartLoc, AttrFixitLoc, attrs, TagType,
1912 TagOrTempResult.get());
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001913 else
Douglas Gregorc08f4892009-03-25 00:13:59 +00001914 ParseStructUnionBody(StartLoc, TagType, TagOrTempResult.get());
Douglas Gregor556877c2008-04-13 21:30:24 +00001915 }
1916
Erich Keane2fe684b2017-02-28 20:44:39 +00001917 if (!TagOrTempResult.isInvalid())
1918 // Delayed proccessing of attributes.
1919 Actions.ProcessDeclAttributeDelayed(TagOrTempResult.get(), attrs.getList());
1920
Craig Topper161e4db2014-05-21 06:02:52 +00001921 const char *PrevSpec = nullptr;
John McCallba7bf592010-08-24 05:47:05 +00001922 unsigned DiagID;
1923 bool Result;
John McCall7f41d982009-09-11 04:59:25 +00001924 if (!TypeResult.isInvalid()) {
Abramo Bagnara9875a3c2011-03-16 20:16:18 +00001925 Result = DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
1926 NameLoc.isValid() ? NameLoc : StartLoc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001927 PrevSpec, DiagID, TypeResult.get(), Policy);
John McCall7f41d982009-09-11 04:59:25 +00001928 } else if (!TagOrTempResult.isInvalid()) {
Abramo Bagnara9875a3c2011-03-16 20:16:18 +00001929 Result = DS.SetTypeSpecType(TagType, StartLoc,
1930 NameLoc.isValid() ? NameLoc : StartLoc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001931 PrevSpec, DiagID, TagOrTempResult.get(), Owned,
1932 Policy);
John McCall7f41d982009-09-11 04:59:25 +00001933 } else {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001934 DS.SetTypeSpecError();
Anders Carlssonf83c9fa2009-05-11 22:27:47 +00001935 return;
1936 }
Mike Stump11289f42009-09-09 15:08:12 +00001937
John McCallba7bf592010-08-24 05:47:05 +00001938 if (Result)
John McCall49bfce42009-08-03 20:12:06 +00001939 Diag(StartLoc, DiagID) << PrevSpec;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001940
Chris Lattnercf251412010-02-02 01:23:29 +00001941 // At this point, we've successfully parsed a class-specifier in 'definition'
1942 // form (e.g. "struct foo { int x; }". While we could just return here, we're
1943 // going to look at what comes after it to improve error recovery. If an
1944 // impossible token occurs next, we assume that the programmer forgot a ; at
1945 // the end of the declaration and recover that way.
1946 //
Richard Smith369b9f92012-06-25 21:37:02 +00001947 // Also enforce C++ [temp]p3:
1948 // In a template-declaration which defines a class, no declarator
1949 // is permitted.
Richard Smith843f18f2014-08-13 02:13:15 +00001950 //
1951 // After a type-specifier, we don't expect a semicolon. This only happens in
1952 // C, since definitions are not permitted in this context in C++.
Joao Matose9a3ed42012-08-31 22:18:20 +00001953 if (TUK == Sema::TUK_Definition &&
Richard Smith843f18f2014-08-13 02:13:15 +00001954 (getLangOpts().CPlusPlus || !isTypeSpecifier(DSC)) &&
Joao Matose9a3ed42012-08-31 22:18:20 +00001955 (TemplateInfo.Kind || !isValidAfterTypeSpecifier(false))) {
Argyrios Kyrtzidise6f69132012-12-17 20:10:43 +00001956 if (Tok.isNot(tok::semi)) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001957 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
Alp Toker383d2c42014-01-01 03:08:43 +00001958 ExpectAndConsume(tok::semi, diag::err_expected_after,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001959 DeclSpec::getSpecifierName(TagType, PPol));
Argyrios Kyrtzidise6f69132012-12-17 20:10:43 +00001960 // Push this token back into the preprocessor and change our current token
1961 // to ';' so that the rest of the code recovers as though there were an
1962 // ';' after the definition.
1963 PP.EnterToken(Tok);
1964 Tok.setKind(tok::semi);
1965 }
Chris Lattnercf251412010-02-02 01:23:29 +00001966 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001967}
1968
Mike Stump11289f42009-09-09 15:08:12 +00001969/// ParseBaseClause - Parse the base-clause of a C++ class [C++ class.derived].
Douglas Gregor556877c2008-04-13 21:30:24 +00001970///
1971/// base-clause : [C++ class.derived]
1972/// ':' base-specifier-list
1973/// base-specifier-list:
1974/// base-specifier '...'[opt]
1975/// base-specifier-list ',' base-specifier '...'[opt]
John McCall48871652010-08-21 09:40:31 +00001976void Parser::ParseBaseClause(Decl *ClassDecl) {
Douglas Gregor556877c2008-04-13 21:30:24 +00001977 assert(Tok.is(tok::colon) && "Not a base clause");
1978 ConsumeToken();
1979
Douglas Gregor29a92472008-10-22 17:49:05 +00001980 // Build up an array of parsed base specifiers.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001981 SmallVector<CXXBaseSpecifier *, 8> BaseInfo;
Douglas Gregor29a92472008-10-22 17:49:05 +00001982
Douglas Gregor556877c2008-04-13 21:30:24 +00001983 while (true) {
1984 // Parse a base-specifier.
Douglas Gregor29a92472008-10-22 17:49:05 +00001985 BaseResult Result = ParseBaseSpecifier(ClassDecl);
Douglas Gregorf8298252009-01-26 22:44:13 +00001986 if (Result.isInvalid()) {
Douglas Gregor556877c2008-04-13 21:30:24 +00001987 // Skip the rest of this base specifier, up until the comma or
1988 // opening brace.
Alexey Bataevee6507d2013-11-18 08:17:37 +00001989 SkipUntil(tok::comma, tok::l_brace, StopAtSemi | StopBeforeMatch);
Douglas Gregor29a92472008-10-22 17:49:05 +00001990 } else {
1991 // Add this to our array of base specifiers.
Douglas Gregorf8298252009-01-26 22:44:13 +00001992 BaseInfo.push_back(Result.get());
Douglas Gregor556877c2008-04-13 21:30:24 +00001993 }
1994
1995 // If the next token is a comma, consume it and keep reading
1996 // base-specifiers.
Alp Toker97650562014-01-10 11:19:30 +00001997 if (!TryConsumeToken(tok::comma))
1998 break;
Douglas Gregor556877c2008-04-13 21:30:24 +00001999 }
Douglas Gregor29a92472008-10-22 17:49:05 +00002000
2001 // Attach the base specifiers
Craig Topperaa700cb2015-12-27 21:55:19 +00002002 Actions.ActOnBaseSpecifiers(ClassDecl, BaseInfo);
Douglas Gregor556877c2008-04-13 21:30:24 +00002003}
2004
2005/// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is
2006/// one entry in the base class list of a class specifier, for example:
2007/// class foo : public bar, virtual private baz {
2008/// 'public bar' and 'virtual private baz' are each base-specifiers.
2009///
2010/// base-specifier: [C++ class.derived]
Richard Smith4c96e992013-02-19 23:47:15 +00002011/// attribute-specifier-seq[opt] base-type-specifier
2012/// attribute-specifier-seq[opt] 'virtual' access-specifier[opt]
2013/// base-type-specifier
2014/// attribute-specifier-seq[opt] access-specifier 'virtual'[opt]
2015/// base-type-specifier
Craig Topper9ad7e262014-10-31 06:57:07 +00002016BaseResult Parser::ParseBaseSpecifier(Decl *ClassDecl) {
Douglas Gregor556877c2008-04-13 21:30:24 +00002017 bool IsVirtual = false;
2018 SourceLocation StartLoc = Tok.getLocation();
2019
Richard Smith4c96e992013-02-19 23:47:15 +00002020 ParsedAttributesWithRange Attributes(AttrFactory);
2021 MaybeParseCXX11Attributes(Attributes);
2022
Douglas Gregor556877c2008-04-13 21:30:24 +00002023 // Parse the 'virtual' keyword.
Alp Toker97650562014-01-10 11:19:30 +00002024 if (TryConsumeToken(tok::kw_virtual))
Douglas Gregor556877c2008-04-13 21:30:24 +00002025 IsVirtual = true;
Douglas Gregor556877c2008-04-13 21:30:24 +00002026
Richard Smith4c96e992013-02-19 23:47:15 +00002027 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2028
Douglas Gregor556877c2008-04-13 21:30:24 +00002029 // Parse an (optional) access specifier.
2030 AccessSpecifier Access = getAccessSpecifierIfPresent();
John McCall553c0792010-01-23 00:46:32 +00002031 if (Access != AS_none)
Douglas Gregor556877c2008-04-13 21:30:24 +00002032 ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +00002033
Richard Smith4c96e992013-02-19 23:47:15 +00002034 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2035
Douglas Gregor556877c2008-04-13 21:30:24 +00002036 // Parse the 'virtual' keyword (again!), in case it came after the
2037 // access specifier.
2038 if (Tok.is(tok::kw_virtual)) {
2039 SourceLocation VirtualLoc = ConsumeToken();
2040 if (IsVirtual) {
2041 // Complain about duplicate 'virtual'
Chris Lattner6d29c102008-11-18 07:48:38 +00002042 Diag(VirtualLoc, diag::err_dup_virtual)
Douglas Gregora771f462010-03-31 17:46:05 +00002043 << FixItHint::CreateRemoval(VirtualLoc);
Douglas Gregor556877c2008-04-13 21:30:24 +00002044 }
2045
2046 IsVirtual = true;
2047 }
2048
Richard Smith4c96e992013-02-19 23:47:15 +00002049 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2050
Douglas Gregor831c93f2008-11-05 20:51:48 +00002051 // Parse the class-name.
David Majnemer51fd8a02015-07-22 23:46:18 +00002052
2053 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
2054 // implementation for VS2013 uses _Atomic as an identifier for one of the
2055 // classes in <atomic>. Treat '_Atomic' to be an identifier when we are
2056 // parsing the class-name for a base specifier.
2057 if (getLangOpts().MSVCCompat && Tok.is(tok::kw__Atomic) &&
2058 NextToken().is(tok::less))
2059 Tok.setKind(tok::identifier);
2060
Douglas Gregord54dfb82009-02-25 23:52:28 +00002061 SourceLocation EndLocation;
David Blaikie1cd50022011-10-25 17:10:12 +00002062 SourceLocation BaseLoc;
2063 TypeResult BaseType = ParseBaseTypeSpecifier(BaseLoc, EndLocation);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00002064 if (BaseType.isInvalid())
Douglas Gregor831c93f2008-11-05 20:51:48 +00002065 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002066
Douglas Gregor752a5952011-01-03 22:36:02 +00002067 // Parse the optional ellipsis (for a pack expansion). The ellipsis is
2068 // actually part of the base-specifier-list grammar productions, but we
2069 // parse it here for convenience.
2070 SourceLocation EllipsisLoc;
Alp Toker97650562014-01-10 11:19:30 +00002071 TryConsumeToken(tok::ellipsis, EllipsisLoc);
2072
Mike Stump11289f42009-09-09 15:08:12 +00002073 // Find the complete source range for the base-specifier.
Douglas Gregord54dfb82009-02-25 23:52:28 +00002074 SourceRange Range(StartLoc, EndLocation);
Mike Stump11289f42009-09-09 15:08:12 +00002075
Douglas Gregor556877c2008-04-13 21:30:24 +00002076 // Notify semantic analysis that we have parsed a complete
2077 // base-specifier.
Richard Smith4c96e992013-02-19 23:47:15 +00002078 return Actions.ActOnBaseSpecifier(ClassDecl, Range, Attributes, IsVirtual,
2079 Access, BaseType.get(), BaseLoc,
2080 EllipsisLoc);
Douglas Gregor556877c2008-04-13 21:30:24 +00002081}
2082
2083/// getAccessSpecifierIfPresent - Determine whether the next token is
2084/// a C++ access-specifier.
2085///
2086/// access-specifier: [C++ class.derived]
2087/// 'private'
2088/// 'protected'
2089/// 'public'
Mike Stump11289f42009-09-09 15:08:12 +00002090AccessSpecifier Parser::getAccessSpecifierIfPresent() const {
Douglas Gregor556877c2008-04-13 21:30:24 +00002091 switch (Tok.getKind()) {
2092 default: return AS_none;
2093 case tok::kw_private: return AS_private;
2094 case tok::kw_protected: return AS_protected;
2095 case tok::kw_public: return AS_public;
2096 }
2097}
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002098
Douglas Gregor433e0532012-04-16 18:27:27 +00002099/// \brief If the given declarator has any parts for which parsing has to be
Richard Smith0b3a4622014-11-13 20:01:57 +00002100/// delayed, e.g., default arguments or an exception-specification, create a
2101/// late-parsed method declaration record to handle the parsing at the end of
2102/// the class definition.
Douglas Gregor433e0532012-04-16 18:27:27 +00002103void Parser::HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
2104 Decl *ThisDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00002105 DeclaratorChunk::FunctionTypeInfo &FTI
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002106 = DeclaratorInfo.getFunctionTypeInfo();
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002107 // If there was a late-parsed exception-specification, we'll need a
2108 // late parse
2109 bool NeedLateParse = FTI.getExceptionSpecType() == EST_Unparsed;
Douglas Gregor433e0532012-04-16 18:27:27 +00002110
Nathan Sidwell5bb231c2015-02-19 14:03:22 +00002111 if (!NeedLateParse) {
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002112 // Look ahead to see if there are any default args
Nathan Sidwell5bb231c2015-02-19 14:03:22 +00002113 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx) {
2114 auto Param = cast<ParmVarDecl>(FTI.Params[ParamIdx].Param);
2115 if (Param->hasUnparsedDefaultArg()) {
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002116 NeedLateParse = true;
2117 break;
2118 }
Nathan Sidwell5bb231c2015-02-19 14:03:22 +00002119 }
2120 }
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002121
2122 if (NeedLateParse) {
Richard Smith0b3a4622014-11-13 20:01:57 +00002123 // Push this method onto the stack of late-parsed method
2124 // declarations.
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002125 auto LateMethod = new LateParsedMethodDeclaration(this, ThisDecl);
Richard Smith0b3a4622014-11-13 20:01:57 +00002126 getCurrentClass().LateParsedDeclarations.push_back(LateMethod);
2127 LateMethod->TemplateScope = getCurScope()->isTemplateParamScope();
2128
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002129 // Stash the exception-specification tokens in the late-pased method.
Richard Smith0b3a4622014-11-13 20:01:57 +00002130 LateMethod->ExceptionSpecTokens = FTI.ExceptionSpecTokens;
Hans Wennborgdcfba332015-10-06 23:40:43 +00002131 FTI.ExceptionSpecTokens = nullptr;
Richard Smith0b3a4622014-11-13 20:01:57 +00002132
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002133 // Push tokens for each parameter. Those that do not have
2134 // defaults will be NULL.
Richard Smith0b3a4622014-11-13 20:01:57 +00002135 LateMethod->DefaultArgs.reserve(FTI.NumParams);
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002136 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx)
Alp Tokerc5350722014-02-26 22:27:52 +00002137 LateMethod->DefaultArgs.push_back(LateParsedDefaultArgument(
Malcolm Parsonsca9d8342016-11-17 21:00:09 +00002138 FTI.Params[ParamIdx].Param,
2139 std::move(FTI.Params[ParamIdx].DefaultArgTokens)));
Eli Friedman3af2a772009-07-22 21:45:50 +00002140 }
2141}
2142
Richard Smith89645bc2013-01-02 12:01:23 +00002143/// isCXX11VirtSpecifier - Determine whether the given token is a C++11
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002144/// virt-specifier.
2145///
2146/// virt-specifier:
2147/// override
2148/// final
Andrey Bokhanko276055b2016-07-29 10:42:48 +00002149/// __final
Richard Smith89645bc2013-01-02 12:01:23 +00002150VirtSpecifiers::Specifier Parser::isCXX11VirtSpecifier(const Token &Tok) const {
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002151 if (!getLangOpts().CPlusPlus || Tok.isNot(tok::identifier))
Anders Carlsson4b63d0e2011-01-22 16:56:46 +00002152 return VirtSpecifiers::VS_None;
2153
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002154 IdentifierInfo *II = Tok.getIdentifierInfo();
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002155
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002156 // Initialize the contextual keywords.
2157 if (!Ident_final) {
2158 Ident_final = &PP.getIdentifierTable().get("final");
Andrey Bokhanko276055b2016-07-29 10:42:48 +00002159 if (getLangOpts().GNUKeywords)
2160 Ident_GNU_final = &PP.getIdentifierTable().get("__final");
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002161 if (getLangOpts().MicrosoftExt)
2162 Ident_sealed = &PP.getIdentifierTable().get("sealed");
2163 Ident_override = &PP.getIdentifierTable().get("override");
Anders Carlsson56104902011-01-17 03:05:47 +00002164 }
2165
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002166 if (II == Ident_override)
2167 return VirtSpecifiers::VS_Override;
2168
2169 if (II == Ident_sealed)
2170 return VirtSpecifiers::VS_Sealed;
2171
2172 if (II == Ident_final)
2173 return VirtSpecifiers::VS_Final;
2174
Andrey Bokhanko276055b2016-07-29 10:42:48 +00002175 if (II == Ident_GNU_final)
2176 return VirtSpecifiers::VS_GNU_Final;
2177
Anders Carlsson56104902011-01-17 03:05:47 +00002178 return VirtSpecifiers::VS_None;
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002179}
2180
Richard Smith89645bc2013-01-02 12:01:23 +00002181/// ParseOptionalCXX11VirtSpecifierSeq - Parse a virt-specifier-seq.
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002182///
2183/// virt-specifier-seq:
2184/// virt-specifier
2185/// virt-specifier-seq virt-specifier
Richard Smith89645bc2013-01-02 12:01:23 +00002186void Parser::ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS,
Richard Smith3d1a94c2014-08-12 00:22:39 +00002187 bool IsInterface,
2188 SourceLocation FriendLoc) {
Anders Carlsson56104902011-01-17 03:05:47 +00002189 while (true) {
Richard Smith89645bc2013-01-02 12:01:23 +00002190 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
Anders Carlsson56104902011-01-17 03:05:47 +00002191 if (Specifier == VirtSpecifiers::VS_None)
2192 return;
2193
Richard Smith3d1a94c2014-08-12 00:22:39 +00002194 if (FriendLoc.isValid()) {
2195 Diag(Tok.getLocation(), diag::err_friend_decl_spec)
2196 << VirtSpecifiers::getSpecifierName(Specifier)
2197 << FixItHint::CreateRemoval(Tok.getLocation())
2198 << SourceRange(FriendLoc, FriendLoc);
2199 ConsumeToken();
2200 continue;
2201 }
2202
Anders Carlsson56104902011-01-17 03:05:47 +00002203 // C++ [class.mem]p8:
2204 // A virt-specifier-seq shall contain at most one of each virt-specifier.
Craig Topper161e4db2014-05-21 06:02:52 +00002205 const char *PrevSpec = nullptr;
Anders Carlssonf2ca3892011-01-22 15:58:16 +00002206 if (VS.SetSpecifier(Specifier, Tok.getLocation(), PrevSpec))
Anders Carlsson56104902011-01-17 03:05:47 +00002207 Diag(Tok.getLocation(), diag::err_duplicate_virt_specifier)
2208 << PrevSpec
2209 << FixItHint::CreateRemoval(Tok.getLocation());
2210
David Majnemera5433082013-10-18 00:33:31 +00002211 if (IsInterface && (Specifier == VirtSpecifiers::VS_Final ||
2212 Specifier == VirtSpecifiers::VS_Sealed)) {
John McCalldb632ac2012-09-25 07:32:39 +00002213 Diag(Tok.getLocation(), diag::err_override_control_interface)
2214 << VirtSpecifiers::getSpecifierName(Specifier);
David Majnemera5433082013-10-18 00:33:31 +00002215 } else if (Specifier == VirtSpecifiers::VS_Sealed) {
2216 Diag(Tok.getLocation(), diag::ext_ms_sealed_keyword);
Andrey Bokhanko276055b2016-07-29 10:42:48 +00002217 } else if (Specifier == VirtSpecifiers::VS_GNU_Final) {
2218 Diag(Tok.getLocation(), diag::ext_warn_gnu_final);
John McCalldb632ac2012-09-25 07:32:39 +00002219 } else {
David Majnemera5433082013-10-18 00:33:31 +00002220 Diag(Tok.getLocation(),
2221 getLangOpts().CPlusPlus11
2222 ? diag::warn_cxx98_compat_override_control_keyword
2223 : diag::ext_override_control_keyword)
2224 << VirtSpecifiers::getSpecifierName(Specifier);
John McCalldb632ac2012-09-25 07:32:39 +00002225 }
Anders Carlsson56104902011-01-17 03:05:47 +00002226 ConsumeToken();
2227 }
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002228}
2229
Richard Smith89645bc2013-01-02 12:01:23 +00002230/// isCXX11FinalKeyword - Determine whether the next token is a C++11
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002231/// 'final' or Microsoft 'sealed' contextual keyword.
Richard Smith89645bc2013-01-02 12:01:23 +00002232bool Parser::isCXX11FinalKeyword() const {
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002233 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
2234 return Specifier == VirtSpecifiers::VS_Final ||
Andrey Bokhanko276055b2016-07-29 10:42:48 +00002235 Specifier == VirtSpecifiers::VS_GNU_Final ||
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002236 Specifier == VirtSpecifiers::VS_Sealed;
Anders Carlsson4b63d0e2011-01-22 16:56:46 +00002237}
2238
Richard Smith72553fc2014-01-23 23:53:27 +00002239/// \brief Parse a C++ member-declarator up to, but not including, the optional
2240/// brace-or-equal-initializer or pure-specifier.
Nico Weberd89e6f72015-01-16 19:34:13 +00002241bool Parser::ParseCXXMemberDeclaratorBeforeInitializer(
Richard Smith72553fc2014-01-23 23:53:27 +00002242 Declarator &DeclaratorInfo, VirtSpecifiers &VS, ExprResult &BitfieldSize,
2243 LateParsedAttrList &LateParsedAttrs) {
2244 // member-declarator:
2245 // declarator pure-specifier[opt]
2246 // declarator brace-or-equal-initializer[opt]
2247 // identifier[opt] ':' constant-expression
Serge Pavlov458ea762014-07-16 05:16:52 +00002248 if (Tok.isNot(tok::colon))
Richard Smith72553fc2014-01-23 23:53:27 +00002249 ParseDeclarator(DeclaratorInfo);
Richard Smith3d1a94c2014-08-12 00:22:39 +00002250 else
2251 DeclaratorInfo.SetIdentifier(nullptr, Tok.getLocation());
Richard Smith72553fc2014-01-23 23:53:27 +00002252
2253 if (!DeclaratorInfo.isFunctionDeclarator() && TryConsumeToken(tok::colon)) {
Richard Smith3d1a94c2014-08-12 00:22:39 +00002254 assert(DeclaratorInfo.isPastIdentifier() &&
2255 "don't know where identifier would go yet?");
Richard Smith72553fc2014-01-23 23:53:27 +00002256 BitfieldSize = ParseConstantExpression();
2257 if (BitfieldSize.isInvalid())
2258 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002259 } else {
Richard Smith3d1a94c2014-08-12 00:22:39 +00002260 ParseOptionalCXX11VirtSpecifierSeq(
2261 VS, getCurrentClass().IsInterface,
2262 DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002263 if (!VS.isUnset())
2264 MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo, VS);
2265 }
Richard Smith72553fc2014-01-23 23:53:27 +00002266
2267 // If a simple-asm-expr is present, parse it.
2268 if (Tok.is(tok::kw_asm)) {
2269 SourceLocation Loc;
2270 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
2271 if (AsmLabel.isInvalid())
2272 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2273
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002274 DeclaratorInfo.setAsmLabel(AsmLabel.get());
Richard Smith72553fc2014-01-23 23:53:27 +00002275 DeclaratorInfo.SetRangeEnd(Loc);
2276 }
2277
2278 // If attributes exist after the declarator, but before an '{', parse them.
2279 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
Richard Smith4b5a9492014-01-24 22:34:35 +00002280
2281 // For compatibility with code written to older Clang, also accept a
2282 // virt-specifier *after* the GNU attributes.
Aaron Ballman5d153e32014-08-04 17:03:51 +00002283 if (BitfieldSize.isUnset() && VS.isUnset()) {
Richard Smith3d1a94c2014-08-12 00:22:39 +00002284 ParseOptionalCXX11VirtSpecifierSeq(
2285 VS, getCurrentClass().IsInterface,
2286 DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
Aaron Ballman5d153e32014-08-04 17:03:51 +00002287 if (!VS.isUnset()) {
2288 // If we saw any GNU-style attributes that are known to GCC followed by a
2289 // virt-specifier, issue a GCC-compat warning.
2290 const AttributeList *Attr = DeclaratorInfo.getAttributes();
2291 while (Attr) {
2292 if (Attr->isKnownToGCC() && !Attr->isCXX11Attribute())
2293 Diag(Attr->getLoc(), diag::warn_gcc_attribute_location);
2294 Attr = Attr->getNext();
2295 }
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002296 MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo, VS);
Aaron Ballman5d153e32014-08-04 17:03:51 +00002297 }
2298 }
Nico Weberd89e6f72015-01-16 19:34:13 +00002299
2300 // If this has neither a name nor a bit width, something has gone seriously
2301 // wrong. Skip until the semi-colon or }.
2302 if (!DeclaratorInfo.hasName() && BitfieldSize.isUnset()) {
2303 // If so, skip until the semi-colon or a }.
2304 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2305 return true;
2306 }
2307 return false;
Richard Smith72553fc2014-01-23 23:53:27 +00002308}
2309
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002310/// \brief Look for declaration specifiers possibly occurring after C++11
2311/// virt-specifier-seq and diagnose them.
2312void Parser::MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(
2313 Declarator &D,
2314 VirtSpecifiers &VS) {
2315 DeclSpec DS(AttrFactory);
2316
2317 // GNU-style and C++11 attributes are not allowed here, but they will be
2318 // handled by the caller. Diagnose everything else.
Alex Lorenz8f4d3992017-02-13 23:19:40 +00002319 ParseTypeQualifierListOpt(
2320 DS, AR_NoAttributesParsed, false,
2321 /*IdentifierRequired=*/false, llvm::function_ref<void()>([&]() {
2322 Actions.CodeCompleteFunctionQualifiers(DS, D, &VS);
2323 }));
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002324 D.ExtendWithDeclSpec(DS);
2325
2326 if (D.isFunctionDeclarator()) {
Ehsan Akhgaric07d1e22015-03-25 00:53:33 +00002327 auto &Function = D.getFunctionTypeInfo();
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002328 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
2329 auto DeclSpecCheck = [&] (DeclSpec::TQ TypeQual,
2330 const char *FixItName,
2331 SourceLocation SpecLoc,
2332 unsigned* QualifierLoc) {
2333 FixItHint Insertion;
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002334 if (DS.getTypeQualifiers() & TypeQual) {
2335 if (!(Function.TypeQuals & TypeQual)) {
2336 std::string Name(FixItName);
2337 Name += " ";
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00002338 Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), Name);
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002339 Function.TypeQuals |= TypeQual;
2340 *QualifierLoc = SpecLoc.getRawEncoding();
2341 }
2342 Diag(SpecLoc, diag::err_declspec_after_virtspec)
2343 << FixItName
2344 << VirtSpecifiers::getSpecifierName(VS.getLastSpecifier())
2345 << FixItHint::CreateRemoval(SpecLoc)
2346 << Insertion;
2347 }
2348 };
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002349 DeclSpecCheck(DeclSpec::TQ_const, "const", DS.getConstSpecLoc(),
2350 &Function.ConstQualifierLoc);
2351 DeclSpecCheck(DeclSpec::TQ_volatile, "volatile", DS.getVolatileSpecLoc(),
2352 &Function.VolatileQualifierLoc);
2353 DeclSpecCheck(DeclSpec::TQ_restrict, "restrict", DS.getRestrictSpecLoc(),
2354 &Function.RestrictQualifierLoc);
2355 }
Ehsan Akhgaric07d1e22015-03-25 00:53:33 +00002356
2357 // Parse ref-qualifiers.
2358 bool RefQualifierIsLValueRef = true;
2359 SourceLocation RefQualifierLoc;
2360 if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc)) {
2361 const char *Name = (RefQualifierIsLValueRef ? "& " : "&& ");
2362 FixItHint Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), Name);
2363 Function.RefQualifierIsLValueRef = RefQualifierIsLValueRef;
2364 Function.RefQualifierLoc = RefQualifierLoc.getRawEncoding();
2365
2366 Diag(RefQualifierLoc, diag::err_declspec_after_virtspec)
2367 << (RefQualifierIsLValueRef ? "&" : "&&")
2368 << VirtSpecifiers::getSpecifierName(VS.getLastSpecifier())
2369 << FixItHint::CreateRemoval(RefQualifierLoc)
2370 << Insertion;
2371 D.SetRangeEnd(RefQualifierLoc);
2372 }
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002373 }
2374}
2375
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002376/// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration.
2377///
2378/// member-declaration:
2379/// decl-specifier-seq[opt] member-declarator-list[opt] ';'
2380/// function-definition ';'[opt]
2381/// ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO]
2382/// using-declaration [TODO]
Anders Carlssonf24fcff62009-03-11 16:27:10 +00002383/// [C++0x] static_assert-declaration
Anders Carlssondfbbdf62009-03-26 00:52:18 +00002384/// template-declaration
Chris Lattnerd19c1c02008-12-18 01:12:00 +00002385/// [GNU] '__extension__' member-declaration
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002386///
2387/// member-declarator-list:
2388/// member-declarator
2389/// member-declarator-list ',' member-declarator
2390///
2391/// member-declarator:
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002392/// declarator virt-specifier-seq[opt] pure-specifier[opt]
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002393/// declarator constant-initializer[opt]
Richard Smith938f40b2011-06-11 17:19:42 +00002394/// [C++11] declarator brace-or-equal-initializer[opt]
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002395/// identifier[opt] ':' constant-expression
2396///
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002397/// virt-specifier-seq:
2398/// virt-specifier
2399/// virt-specifier-seq virt-specifier
2400///
2401/// virt-specifier:
2402/// override
2403/// final
David Majnemera5433082013-10-18 00:33:31 +00002404/// [MS] sealed
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002405///
Sebastian Redl42e92c42009-04-12 17:16:29 +00002406/// pure-specifier:
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002407/// '= 0'
2408///
2409/// constant-initializer:
2410/// '=' constant-expression
2411///
Alexey Bataev05c25d62015-07-31 08:42:25 +00002412Parser::DeclGroupPtrTy
2413Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS,
2414 AttributeList *AccessAttrs,
John McCall796c2a52010-07-16 08:13:16 +00002415 const ParsedTemplateInfo &TemplateInfo,
2416 ParsingDeclRAIIObject *TemplateDiags) {
Douglas Gregor23c84762011-04-14 17:21:19 +00002417 if (Tok.is(tok::at)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002418 if (getLangOpts().ObjC1 && NextToken().isObjCAtKeyword(tok::objc_defs))
Douglas Gregor23c84762011-04-14 17:21:19 +00002419 Diag(Tok, diag::err_at_defs_cxx);
2420 else
2421 Diag(Tok, diag::err_at_in_class);
Richard Smithda35e962013-11-09 04:52:51 +00002422
Douglas Gregor23c84762011-04-14 17:21:19 +00002423 ConsumeToken();
Alexey Bataevee6507d2013-11-18 08:17:37 +00002424 SkipUntil(tok::r_brace, StopAtSemi);
David Blaikie0403cb12016-01-15 23:43:25 +00002425 return nullptr;
Douglas Gregor23c84762011-04-14 17:21:19 +00002426 }
Richard Smithda35e962013-11-09 04:52:51 +00002427
Serge Pavlov458ea762014-07-16 05:16:52 +00002428 // Turn on colon protection early, while parsing declspec, although there is
2429 // nothing to protect there. It prevents from false errors if error recovery
2430 // incorrectly determines where the declspec ends, as in the example:
2431 // struct A { enum class B { C }; };
2432 // const int C = 4;
2433 // struct D { A::B : C; };
2434 ColonProtectionRAIIObject X(*this);
2435
John McCalla0097262009-12-11 02:10:03 +00002436 // Access declarations.
Richard Smith45855df2012-05-09 08:23:23 +00002437 bool MalformedTypeSpec = false;
John McCalla0097262009-12-11 02:10:03 +00002438 if (!TemplateInfo.Kind &&
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002439 Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw___super)) {
Richard Smith45855df2012-05-09 08:23:23 +00002440 if (TryAnnotateCXXScopeToken())
2441 MalformedTypeSpec = true;
2442
2443 bool isAccessDecl;
2444 if (Tok.isNot(tok::annot_cxxscope))
2445 isAccessDecl = false;
2446 else if (NextToken().is(tok::identifier))
John McCalla0097262009-12-11 02:10:03 +00002447 isAccessDecl = GetLookAheadToken(2).is(tok::semi);
2448 else
2449 isAccessDecl = NextToken().is(tok::kw_operator);
2450
2451 if (isAccessDecl) {
2452 // Collect the scope specifier token we annotated earlier.
2453 CXXScopeSpec SS;
David Blaikieefdccaa2016-01-15 23:43:34 +00002454 ParseOptionalCXXScopeSpecifier(SS, nullptr,
Douglas Gregordf593fb2011-11-07 17:33:42 +00002455 /*EnteringContext=*/false);
John McCalla0097262009-12-11 02:10:03 +00002456
Nico Weberef03e702014-09-10 00:59:37 +00002457 if (SS.isInvalid()) {
2458 SkipUntil(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002459 return nullptr;
Nico Weberef03e702014-09-10 00:59:37 +00002460 }
2461
John McCalla0097262009-12-11 02:10:03 +00002462 // Try to parse an unqualified-id.
Abramo Bagnara7945c982012-01-27 09:46:47 +00002463 SourceLocation TemplateKWLoc;
John McCalla0097262009-12-11 02:10:03 +00002464 UnqualifiedId Name;
Richard Smith35845152017-02-07 01:37:30 +00002465 if (ParseUnqualifiedId(SS, false, true, true, false, nullptr,
2466 TemplateKWLoc, Name)) {
John McCalla0097262009-12-11 02:10:03 +00002467 SkipUntil(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002468 return nullptr;
John McCalla0097262009-12-11 02:10:03 +00002469 }
2470
2471 // TODO: recover from mistakenly-qualified operator declarations.
Alp Toker383d2c42014-01-01 03:08:43 +00002472 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
2473 "access declaration")) {
2474 SkipUntil(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002475 return nullptr;
Alp Toker383d2c42014-01-01 03:08:43 +00002476 }
John McCalla0097262009-12-11 02:10:03 +00002477
Alexey Bataev05c25d62015-07-31 08:42:25 +00002478 return DeclGroupPtrTy::make(DeclGroupRef(Actions.ActOnUsingDeclaration(
Richard Smith151c4562016-12-20 21:35:28 +00002479 getCurScope(), AS, /*UsingLoc*/ SourceLocation(),
2480 /*TypenameLoc*/ SourceLocation(), SS, Name,
2481 /*EllipsisLoc*/ SourceLocation(), /*AttrList*/ nullptr)));
John McCalla0097262009-12-11 02:10:03 +00002482 }
2483 }
2484
Aaron Ballmane7c544d2014-08-04 20:28:35 +00002485 // static_assert-declaration. A templated static_assert declaration is
2486 // diagnosed in Parser::ParseSingleDeclarationAfterTemplate.
2487 if (!TemplateInfo.Kind &&
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002488 Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert)) {
Chris Lattner49836b42009-04-02 04:16:50 +00002489 SourceLocation DeclEnd;
Alexey Bataev05c25d62015-07-31 08:42:25 +00002490 return DeclGroupPtrTy::make(
2491 DeclGroupRef(ParseStaticAssertDeclaration(DeclEnd)));
Chris Lattner5bbb3c82009-03-29 16:50:03 +00002492 }
Mike Stump11289f42009-09-09 15:08:12 +00002493
Chris Lattner5bbb3c82009-03-29 16:50:03 +00002494 if (Tok.is(tok::kw_template)) {
Mike Stump11289f42009-09-09 15:08:12 +00002495 assert(!TemplateInfo.TemplateParams &&
Douglas Gregor3447e762009-08-20 22:52:58 +00002496 "Nested template improperly parsed?");
Richard Smith3af70092017-02-09 22:14:25 +00002497 ObjCDeclContextSwitch ObjCDC(*this);
Chris Lattner49836b42009-04-02 04:16:50 +00002498 SourceLocation DeclEnd;
Alexey Bataev05c25d62015-07-31 08:42:25 +00002499 return DeclGroupPtrTy::make(
Richard Smith3af70092017-02-09 22:14:25 +00002500 DeclGroupRef(ParseTemplateDeclarationOrSpecialization(
Alexey Bataev05c25d62015-07-31 08:42:25 +00002501 Declarator::MemberContext, DeclEnd, AS, AccessAttrs)));
Chris Lattner5bbb3c82009-03-29 16:50:03 +00002502 }
Anders Carlssondfbbdf62009-03-26 00:52:18 +00002503
Chris Lattnerd19c1c02008-12-18 01:12:00 +00002504 // Handle: member-declaration ::= '__extension__' member-declaration
2505 if (Tok.is(tok::kw___extension__)) {
2506 // __extension__ silences extension warnings in the subexpression.
2507 ExtensionRAIIObject O(Diags); // Use RAII to do this.
2508 ConsumeToken();
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00002509 return ParseCXXClassMemberDeclaration(AS, AccessAttrs,
2510 TemplateInfo, TemplateDiags);
Chris Lattnerd19c1c02008-12-18 01:12:00 +00002511 }
Douglas Gregorfec52632009-06-20 00:51:54 +00002512
John McCall084e83d2011-03-24 11:26:52 +00002513 ParsedAttributesWithRange attrs(AttrFactory);
Michael Handdc016d2012-11-28 23:17:40 +00002514 ParsedAttributesWithRange FnAttrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00002515 // Optional C++11 attribute-specifier
2516 MaybeParseCXX11Attributes(attrs);
Michael Handdc016d2012-11-28 23:17:40 +00002517 // We need to keep these attributes for future diagnostic
2518 // before they are taken over by declaration specifier.
2519 FnAttrs.addAll(attrs.getList());
2520 FnAttrs.Range = attrs.Range;
2521
John McCall53fa7142010-12-24 02:08:15 +00002522 MaybeParseMicrosoftAttributes(attrs);
Alexis Hunt96d5c762009-11-21 08:43:09 +00002523
Douglas Gregorfec52632009-06-20 00:51:54 +00002524 if (Tok.is(tok::kw_using)) {
John McCall53fa7142010-12-24 02:08:15 +00002525 ProhibitAttributes(attrs);
Mike Stump11289f42009-09-09 15:08:12 +00002526
Douglas Gregorfec52632009-06-20 00:51:54 +00002527 // Eat 'using'.
2528 SourceLocation UsingLoc = ConsumeToken();
2529
2530 if (Tok.is(tok::kw_namespace)) {
2531 Diag(UsingLoc, diag::err_using_namespace_in_class);
Alexey Bataevee6507d2013-11-18 08:17:37 +00002532 SkipUntil(tok::semi, StopBeforeMatch);
David Blaikie0403cb12016-01-15 23:43:25 +00002533 return nullptr;
Douglas Gregorfec52632009-06-20 00:51:54 +00002534 }
Alexey Bataev05c25d62015-07-31 08:42:25 +00002535 SourceLocation DeclEnd;
2536 // Otherwise, it must be a using-declaration or an alias-declaration.
Richard Smith6f1daa42016-12-16 00:58:48 +00002537 return ParseUsingDeclaration(Declarator::MemberContext, TemplateInfo,
2538 UsingLoc, DeclEnd, AS);
Douglas Gregorfec52632009-06-20 00:51:54 +00002539 }
2540
DeLesley Hutchinsbd2ee132012-03-02 22:12:59 +00002541 // Hold late-parsed attributes so we can attach a Decl to them later.
2542 LateParsedAttrList CommonLateParsedAttrs;
2543
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002544 // decl-specifier-seq:
2545 // Parse the common declaration-specifiers piece.
John McCall796c2a52010-07-16 08:13:16 +00002546 ParsingDeclSpec DS(*this, TemplateDiags);
John McCall53fa7142010-12-24 02:08:15 +00002547 DS.takeAttributesFrom(attrs);
Richard Smith45855df2012-05-09 08:23:23 +00002548 if (MalformedTypeSpec)
2549 DS.SetTypeSpecError();
Richard Smith72553fc2014-01-23 23:53:27 +00002550
Serge Pavlov458ea762014-07-16 05:16:52 +00002551 ParseDeclarationSpecifiers(DS, TemplateInfo, AS, DSC_class,
2552 &CommonLateParsedAttrs);
2553
2554 // Turn off colon protection that was set for declspec.
2555 X.restore();
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002556
Richard Smith404dfb42013-11-19 22:47:36 +00002557 // If we had a free-standing type definition with a missing semicolon, we
2558 // may get this far before the problem becomes obvious.
2559 if (DS.hasTagDefinition() &&
2560 TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate &&
2561 DiagnoseMissingSemiAfterTagDefinition(DS, AS, DSC_class,
2562 &CommonLateParsedAttrs))
David Blaikie0403cb12016-01-15 23:43:25 +00002563 return nullptr;
Richard Smith404dfb42013-11-19 22:47:36 +00002564
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002565 MultiTemplateParamsArg TemplateParams(
Craig Topper161e4db2014-05-21 06:02:52 +00002566 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->data()
2567 : nullptr,
John McCall11083da2009-09-16 22:47:08 +00002568 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->size() : 0);
2569
Alp Toker35d87032013-12-30 23:29:50 +00002570 if (TryConsumeToken(tok::semi)) {
Michael Handdc016d2012-11-28 23:17:40 +00002571 if (DS.isFriendSpecified())
2572 ProhibitAttributes(FnAttrs);
2573
Nico Weber7b837f52016-01-28 19:25:00 +00002574 RecordDecl *AnonRecord = nullptr;
2575 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(
2576 getCurScope(), AS, DS, TemplateParams, false, AnonRecord);
John McCall796c2a52010-07-16 08:13:16 +00002577 DS.complete(TheDecl);
Nico Weber7b837f52016-01-28 19:25:00 +00002578 if (AnonRecord) {
2579 Decl* decls[] = {AnonRecord, TheDecl};
Richard Smith3beb7c62017-01-12 02:27:38 +00002580 return Actions.BuildDeclaratorGroup(decls);
Nico Weber7b837f52016-01-28 19:25:00 +00002581 }
2582 return Actions.ConvertDeclToDeclGroup(TheDecl);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002583 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002584
John McCall28a6aea2009-11-04 02:18:39 +00002585 ParsingDeclarator DeclaratorInfo(*this, DS, Declarator::MemberContext);
Nico Weber24b2a822011-01-28 06:07:34 +00002586 VirtSpecifiers VS;
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002587
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002588 // Hold late-parsed attributes so we can attach a Decl to them later.
2589 LateParsedAttrList LateParsedAttrs;
2590
Douglas Gregor50cefbf2011-10-17 17:09:53 +00002591 SourceLocation EqualLoc;
Richard Smith9ba0fec2015-06-30 01:28:56 +00002592 SourceLocation PureSpecLoc;
2593
Yaron Keren180c1672015-06-30 07:35:19 +00002594 auto TryConsumePureSpecifier = [&] (bool AllowDefinition) {
Richard Smith9ba0fec2015-06-30 01:28:56 +00002595 if (Tok.isNot(tok::equal))
2596 return false;
2597
2598 auto &Zero = NextToken();
2599 SmallString<8> Buffer;
2600 if (Zero.isNot(tok::numeric_constant) || Zero.getLength() != 1 ||
2601 PP.getSpelling(Zero, Buffer) != "0")
2602 return false;
2603
2604 auto &After = GetLookAheadToken(2);
2605 if (!After.isOneOf(tok::semi, tok::comma) &&
2606 !(AllowDefinition &&
2607 After.isOneOf(tok::l_brace, tok::colon, tok::kw_try)))
2608 return false;
2609
2610 EqualLoc = ConsumeToken();
2611 PureSpecLoc = ConsumeToken();
2612 return true;
2613 };
Chris Lattner17c3b1f2009-12-10 01:59:24 +00002614
Richard Smith72553fc2014-01-23 23:53:27 +00002615 SmallVector<Decl *, 8> DeclsInGroup;
2616 ExprResult BitfieldSize;
2617 bool ExpectSemi = true;
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002618
Richard Smith72553fc2014-01-23 23:53:27 +00002619 // Parse the first declarator.
Nico Weberd89e6f72015-01-16 19:34:13 +00002620 if (ParseCXXMemberDeclaratorBeforeInitializer(
2621 DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs)) {
Richard Smith72553fc2014-01-23 23:53:27 +00002622 TryConsumeToken(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002623 return nullptr;
Richard Smith72553fc2014-01-23 23:53:27 +00002624 }
John Thompson5bc5cbe2009-11-25 22:58:06 +00002625
Richard Smith72553fc2014-01-23 23:53:27 +00002626 // Check for a member function definition.
Richard Smith4b5a9492014-01-24 22:34:35 +00002627 if (BitfieldSize.isUnset()) {
Richard Smith72553fc2014-01-23 23:53:27 +00002628 // MSVC permits pure specifier on inline functions defined at class scope.
Francois Pichet3abc9b82011-05-11 02:14:46 +00002629 // Hence check for =0 before checking for function definition.
Richard Smith9ba0fec2015-06-30 01:28:56 +00002630 if (getLangOpts().MicrosoftExt && DeclaratorInfo.isDeclarationOfFunction())
2631 TryConsumePureSpecifier(/*AllowDefinition*/ true);
Francois Pichet3abc9b82011-05-11 02:14:46 +00002632
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00002633 FunctionDefinitionKind DefinitionKind = FDK_Declaration;
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002634 // function-definition:
Richard Smith938f40b2011-06-11 17:19:42 +00002635 //
2636 // In C++11, a non-function declarator followed by an open brace is a
2637 // braced-init-list for an in-class member initialization, not an
2638 // erroneous function definition.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002639 if (Tok.is(tok::l_brace) && !getLangOpts().CPlusPlus11) {
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00002640 DefinitionKind = FDK_Definition;
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002641 } else if (DeclaratorInfo.isFunctionDeclarator()) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002642 if (Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try)) {
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00002643 DefinitionKind = FDK_Definition;
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002644 } else if (Tok.is(tok::equal)) {
2645 const Token &KW = NextToken();
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00002646 if (KW.is(tok::kw_default))
2647 DefinitionKind = FDK_Defaulted;
2648 else if (KW.is(tok::kw_delete))
2649 DefinitionKind = FDK_Deleted;
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002650 }
2651 }
Eli Bendersky41842222015-03-23 23:49:41 +00002652 DeclaratorInfo.setFunctionDefinitionKind(DefinitionKind);
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002653
Michael Handdc016d2012-11-28 23:17:40 +00002654 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
2655 // to a friend declaration, that declaration shall be a definition.
2656 if (DeclaratorInfo.isFunctionDeclarator() &&
2657 DefinitionKind != FDK_Definition && DS.isFriendSpecified()) {
2658 // Diagnose attributes that appear before decl specifier:
2659 // [[]] friend int foo();
2660 ProhibitAttributes(FnAttrs);
2661 }
2662
Nico Webera7f137d2015-01-16 19:35:01 +00002663 if (DefinitionKind != FDK_Declaration) {
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002664 if (!DeclaratorInfo.isFunctionDeclarator()) {
Richard Trieu0d730542012-01-21 02:59:18 +00002665 Diag(DeclaratorInfo.getIdentifierLoc(), diag::err_func_def_no_params);
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002666 ConsumeBrace();
Alexey Bataevee6507d2013-11-18 08:17:37 +00002667 SkipUntil(tok::r_brace);
Michael Handdc016d2012-11-28 23:17:40 +00002668
Douglas Gregor8a4db832011-01-19 16:41:58 +00002669 // Consume the optional ';'
Alp Toker35d87032013-12-30 23:29:50 +00002670 TryConsumeToken(tok::semi);
2671
David Blaikie0403cb12016-01-15 23:43:25 +00002672 return nullptr;
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002673 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002674
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002675 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
Richard Trieu0d730542012-01-21 02:59:18 +00002676 Diag(DeclaratorInfo.getIdentifierLoc(),
2677 diag::err_function_declared_typedef);
Douglas Gregor8a4db832011-01-19 16:41:58 +00002678
Richard Smith2603b092012-11-15 22:54:20 +00002679 // Recover by treating the 'typedef' as spurious.
2680 DS.ClearStorageClassSpecs();
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002681 }
2682
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002683 Decl *FunDecl =
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00002684 ParseCXXInlineMethodDef(AS, AccessAttrs, DeclaratorInfo, TemplateInfo,
Richard Smith9ba0fec2015-06-30 01:28:56 +00002685 VS, PureSpecLoc);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002686
David Majnemer23252a32013-08-01 04:22:55 +00002687 if (FunDecl) {
2688 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i) {
2689 CommonLateParsedAttrs[i]->addDecl(FunDecl);
2690 }
2691 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i) {
2692 LateParsedAttrs[i]->addDecl(FunDecl);
2693 }
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002694 }
2695 LateParsedAttrs.clear();
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002696
2697 // Consume the ';' - it's optional unless we have a delete or default
Richard Trieu2f7dc462012-05-16 19:04:59 +00002698 if (Tok.is(tok::semi))
Richard Smith87f5dc52012-07-23 05:45:25 +00002699 ConsumeExtraSemi(AfterMemberFunctionDefinition);
Douglas Gregor8a4db832011-01-19 16:41:58 +00002700
Alexey Bataev05c25d62015-07-31 08:42:25 +00002701 return DeclGroupPtrTy::make(DeclGroupRef(FunDecl));
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002702 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002703 }
2704
2705 // member-declarator-list:
2706 // member-declarator
2707 // member-declarator-list ',' member-declarator
2708
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002709 while (1) {
Richard Smith2b013182012-06-10 03:12:00 +00002710 InClassInitStyle HasInClassInit = ICIS_NoInit;
Richard Smith9ba0fec2015-06-30 01:28:56 +00002711 bool HasStaticInitializer = false;
2712 if (Tok.isOneOf(tok::equal, tok::l_brace) && PureSpecLoc.isInvalid()) {
Richard Smith938f40b2011-06-11 17:19:42 +00002713 if (BitfieldSize.get()) {
2714 Diag(Tok, diag::err_bitfield_member_init);
Alexey Bataevee6507d2013-11-18 08:17:37 +00002715 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
Richard Smith9ba0fec2015-06-30 01:28:56 +00002716 } else if (DeclaratorInfo.isDeclarationOfFunction()) {
2717 // It's a pure-specifier.
2718 if (!TryConsumePureSpecifier(/*AllowFunctionDefinition*/ false))
2719 // Parse it as an expression so that Sema can diagnose it.
2720 HasStaticInitializer = true;
2721 } else if (DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2722 DeclSpec::SCS_static &&
2723 DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2724 DeclSpec::SCS_typedef &&
2725 !DS.isFriendSpecified()) {
2726 // It's a default member initializer.
2727 HasInClassInit = Tok.is(tok::equal) ? ICIS_CopyInit : ICIS_ListInit;
Richard Smith938f40b2011-06-11 17:19:42 +00002728 } else {
Richard Smith9ba0fec2015-06-30 01:28:56 +00002729 HasStaticInitializer = true;
Richard Smith938f40b2011-06-11 17:19:42 +00002730 }
2731 }
2732
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002733 // NOTE: If Sema is the Action module and declarator is an instance field,
Chris Lattner5bbb3c82009-03-29 16:50:03 +00002734 // this call will *not* return the created decl; It will return null.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002735 // See Sema::ActOnCXXMemberDeclarator for details.
John McCall07e91c02009-08-06 02:15:43 +00002736
Craig Topper161e4db2014-05-21 06:02:52 +00002737 NamedDecl *ThisDecl = nullptr;
John McCall07e91c02009-08-06 02:15:43 +00002738 if (DS.isFriendSpecified()) {
Richard Smith72553fc2014-01-23 23:53:27 +00002739 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
Michael Handdc016d2012-11-28 23:17:40 +00002740 // to a friend declaration, that declaration shall be a definition.
2741 //
Richard Smith72553fc2014-01-23 23:53:27 +00002742 // Diagnose attributes that appear in a friend member function declarator:
2743 // friend int foo [[]] ();
Michael Handdc016d2012-11-28 23:17:40 +00002744 SmallVector<SourceRange, 4> Ranges;
2745 DeclaratorInfo.getCXX11AttributeRanges(Ranges);
Richard Smith72553fc2014-01-23 23:53:27 +00002746 for (SmallVectorImpl<SourceRange>::iterator I = Ranges.begin(),
2747 E = Ranges.end(); I != E; ++I)
2748 Diag((*I).getBegin(), diag::err_attributes_not_allowed) << *I;
Michael Handdc016d2012-11-28 23:17:40 +00002749
Douglas Gregor0be31a22010-07-02 17:43:08 +00002750 ThisDecl = Actions.ActOnFriendFunctionDecl(getCurScope(), DeclaratorInfo,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002751 TemplateParams);
Douglas Gregor3447e762009-08-20 22:52:58 +00002752 } else {
Douglas Gregor0be31a22010-07-02 17:43:08 +00002753 ThisDecl = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS,
John McCall07e91c02009-08-06 02:15:43 +00002754 DeclaratorInfo,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002755 TemplateParams,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002756 BitfieldSize.get(),
Richard Smith2b013182012-06-10 03:12:00 +00002757 VS, HasInClassInit);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002758
2759 if (VarTemplateDecl *VT =
Craig Topper161e4db2014-05-21 06:02:52 +00002760 ThisDecl ? dyn_cast<VarTemplateDecl>(ThisDecl) : nullptr)
Larisse Voufo39a1e502013-08-06 01:03:05 +00002761 // Re-direct this decl to refer to the templated decl so that we can
2762 // initialize it.
2763 ThisDecl = VT->getTemplatedDecl();
2764
David Majnemer23252a32013-08-01 04:22:55 +00002765 if (ThisDecl && AccessAttrs)
Richard Smithf8a75c32013-08-29 00:47:48 +00002766 Actions.ProcessDeclAttributeList(getCurScope(), ThisDecl, AccessAttrs);
Douglas Gregor3447e762009-08-20 22:52:58 +00002767 }
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002768
Richard Smith9ba0fec2015-06-30 01:28:56 +00002769 // Error recovery might have converted a non-static member into a static
2770 // member.
David Blaikie35506f82013-01-30 01:22:18 +00002771 if (HasInClassInit != ICIS_NoInit &&
Richard Smith9ba0fec2015-06-30 01:28:56 +00002772 DeclaratorInfo.getDeclSpec().getStorageClassSpec() ==
2773 DeclSpec::SCS_static) {
2774 HasInClassInit = ICIS_NoInit;
2775 HasStaticInitializer = true;
2776 }
2777
2778 if (ThisDecl && PureSpecLoc.isValid())
2779 Actions.ActOnPureSpecifier(ThisDecl, PureSpecLoc);
2780
2781 // Handle the initializer.
2782 if (HasInClassInit != ICIS_NoInit) {
Douglas Gregor728d00b2011-10-10 14:49:18 +00002783 // The initializer was deferred; parse it and cache the tokens.
David Majnemer23252a32013-08-01 04:22:55 +00002784 Diag(Tok, getLangOpts().CPlusPlus11
2785 ? diag::warn_cxx98_compat_nonstatic_member_init
2786 : diag::ext_nonstatic_member_init);
Richard Smith5d164bc2011-10-15 05:09:34 +00002787
Richard Smith938f40b2011-06-11 17:19:42 +00002788 if (DeclaratorInfo.isArrayOfUnknownBound()) {
Richard Smith2b013182012-06-10 03:12:00 +00002789 // C++11 [dcl.array]p3: An array bound may also be omitted when the
2790 // declarator is followed by an initializer.
Richard Smith938f40b2011-06-11 17:19:42 +00002791 //
2792 // A brace-or-equal-initializer for a member-declarator is not an
David Blaikiecdd91db2012-02-14 09:00:46 +00002793 // initializer in the grammar, so this is ill-formed.
Richard Smith938f40b2011-06-11 17:19:42 +00002794 Diag(Tok, diag::err_incomplete_array_member_init);
Alexey Bataevee6507d2013-11-18 08:17:37 +00002795 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
David Majnemer23252a32013-08-01 04:22:55 +00002796
2797 // Avoid later warnings about a class member of incomplete type.
David Blaikiecdd91db2012-02-14 09:00:46 +00002798 if (ThisDecl)
David Blaikiecdd91db2012-02-14 09:00:46 +00002799 ThisDecl->setInvalidDecl();
Richard Smith938f40b2011-06-11 17:19:42 +00002800 } else
2801 ParseCXXNonStaticMemberInitializer(ThisDecl);
Richard Smith9ba0fec2015-06-30 01:28:56 +00002802 } else if (HasStaticInitializer) {
Douglas Gregor728d00b2011-10-10 14:49:18 +00002803 // Normal initializer.
Richard Smith9ba0fec2015-06-30 01:28:56 +00002804 ExprResult Init = ParseCXXMemberInitializer(
2805 ThisDecl, DeclaratorInfo.isDeclarationOfFunction(), EqualLoc);
David Majnemer23252a32013-08-01 04:22:55 +00002806
Douglas Gregor728d00b2011-10-10 14:49:18 +00002807 if (Init.isInvalid())
Alexey Bataevee6507d2013-11-18 08:17:37 +00002808 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
Douglas Gregor728d00b2011-10-10 14:49:18 +00002809 else if (ThisDecl)
Richard Smith3beb7c62017-01-12 02:27:38 +00002810 Actions.AddInitializerToDecl(ThisDecl, Init.get(), EqualLoc.isInvalid());
David Majnemer23252a32013-08-01 04:22:55 +00002811 } else if (ThisDecl && DS.getStorageClassSpec() == DeclSpec::SCS_static)
Douglas Gregor728d00b2011-10-10 14:49:18 +00002812 // No initializer.
Richard Smith3beb7c62017-01-12 02:27:38 +00002813 Actions.ActOnUninitializedDecl(ThisDecl);
David Majnemer23252a32013-08-01 04:22:55 +00002814
Douglas Gregor728d00b2011-10-10 14:49:18 +00002815 if (ThisDecl) {
David Majnemer23252a32013-08-01 04:22:55 +00002816 if (!ThisDecl->isInvalidDecl()) {
2817 // Set the Decl for any late parsed attributes
2818 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i)
2819 CommonLateParsedAttrs[i]->addDecl(ThisDecl);
2820
2821 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i)
2822 LateParsedAttrs[i]->addDecl(ThisDecl);
2823 }
Douglas Gregor728d00b2011-10-10 14:49:18 +00002824 Actions.FinalizeDeclaration(ThisDecl);
2825 DeclsInGroup.push_back(ThisDecl);
David Majnemer23252a32013-08-01 04:22:55 +00002826
2827 if (DeclaratorInfo.isFunctionDeclarator() &&
2828 DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2829 DeclSpec::SCS_typedef)
2830 HandleMemberFunctionDeclDelays(DeclaratorInfo, ThisDecl);
Douglas Gregor728d00b2011-10-10 14:49:18 +00002831 }
David Majnemer23252a32013-08-01 04:22:55 +00002832 LateParsedAttrs.clear();
Douglas Gregor728d00b2011-10-10 14:49:18 +00002833
2834 DeclaratorInfo.complete(ThisDecl);
Richard Smith938f40b2011-06-11 17:19:42 +00002835
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002836 // If we don't have a comma, it is either the end of the list (a ';')
2837 // or an error, bail out.
Alp Toker094e5212014-01-05 03:27:11 +00002838 SourceLocation CommaLoc;
2839 if (!TryConsumeToken(tok::comma, CommaLoc))
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002840 break;
Mike Stump11289f42009-09-09 15:08:12 +00002841
Richard Smithc8a79032012-01-09 22:31:44 +00002842 if (Tok.isAtStartOfLine() &&
2843 !MightBeDeclarator(Declarator::MemberContext)) {
2844 // This comma was followed by a line-break and something which can't be
2845 // the start of a declarator. The comma was probably a typo for a
2846 // semicolon.
2847 Diag(CommaLoc, diag::err_expected_semi_declaration)
2848 << FixItHint::CreateReplacement(CommaLoc, ";");
2849 ExpectSemi = false;
2850 break;
2851 }
Mike Stump11289f42009-09-09 15:08:12 +00002852
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002853 // Parse the next declarator.
2854 DeclaratorInfo.clear();
Nico Weber24b2a822011-01-28 06:07:34 +00002855 VS.clear();
Nico Weberf56c85b2015-01-17 02:26:40 +00002856 BitfieldSize = ExprResult(/*Invalid=*/false);
Richard Smith9ba0fec2015-06-30 01:28:56 +00002857 EqualLoc = PureSpecLoc = SourceLocation();
Richard Smith8d06f422012-01-12 23:53:29 +00002858 DeclaratorInfo.setCommaLoc(CommaLoc);
Mike Stump11289f42009-09-09 15:08:12 +00002859
Richard Smith72553fc2014-01-23 23:53:27 +00002860 // GNU attributes are allowed before the second and subsequent declarator.
John McCall53fa7142010-12-24 02:08:15 +00002861 MaybeParseGNUAttributes(DeclaratorInfo);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002862
Nico Weberd89e6f72015-01-16 19:34:13 +00002863 if (ParseCXXMemberDeclaratorBeforeInitializer(
2864 DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs))
2865 break;
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002866 }
2867
Richard Smithc8a79032012-01-09 22:31:44 +00002868 if (ExpectSemi &&
2869 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list)) {
Chris Lattner916dbf12010-02-02 00:43:15 +00002870 // Skip to end of block or statement.
Alexey Bataevee6507d2013-11-18 08:17:37 +00002871 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Chris Lattner916dbf12010-02-02 00:43:15 +00002872 // If we stopped at a ';', eat it.
Alp Toker35d87032013-12-30 23:29:50 +00002873 TryConsumeToken(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002874 return nullptr;
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002875 }
2876
Alexey Bataev05c25d62015-07-31 08:42:25 +00002877 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002878}
2879
Richard Smith9ba0fec2015-06-30 01:28:56 +00002880/// ParseCXXMemberInitializer - Parse the brace-or-equal-initializer.
2881/// Also detect and reject any attempted defaulted/deleted function definition.
2882/// The location of the '=', if any, will be placed in EqualLoc.
Richard Smith938f40b2011-06-11 17:19:42 +00002883///
Richard Smith9ba0fec2015-06-30 01:28:56 +00002884/// This does not check for a pure-specifier; that's handled elsewhere.
Sebastian Redleef474c2012-02-22 10:50:08 +00002885///
Richard Smith938f40b2011-06-11 17:19:42 +00002886/// brace-or-equal-initializer:
2887/// '=' initializer-expression
Sebastian Redleef474c2012-02-22 10:50:08 +00002888/// braced-init-list
2889///
Richard Smith938f40b2011-06-11 17:19:42 +00002890/// initializer-clause:
2891/// assignment-expression
Sebastian Redleef474c2012-02-22 10:50:08 +00002892/// braced-init-list
2893///
Richard Smithda35e962013-11-09 04:52:51 +00002894/// defaulted/deleted function-definition:
Richard Smith938f40b2011-06-11 17:19:42 +00002895/// '=' 'default'
2896/// '=' 'delete'
2897///
2898/// Prior to C++0x, the assignment-expression in an initializer-clause must
2899/// be a constant-expression.
Douglas Gregor926410d2012-02-21 02:22:07 +00002900ExprResult Parser::ParseCXXMemberInitializer(Decl *D, bool IsFunction,
Richard Smith938f40b2011-06-11 17:19:42 +00002901 SourceLocation &EqualLoc) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002902 assert(Tok.isOneOf(tok::equal, tok::l_brace)
Richard Smith938f40b2011-06-11 17:19:42 +00002903 && "Data member initializer not starting with '=' or '{'");
2904
Faisal Valid143a0c2017-04-01 21:30:49 +00002905 EnterExpressionEvaluationContext Context(
2906 Actions, Sema::ExpressionEvaluationContext::PotentiallyEvaluated, D);
Alp Toker094e5212014-01-05 03:27:11 +00002907 if (TryConsumeToken(tok::equal, EqualLoc)) {
Richard Smith938f40b2011-06-11 17:19:42 +00002908 if (Tok.is(tok::kw_delete)) {
2909 // In principle, an initializer of '= delete p;' is legal, but it will
2910 // never type-check. It's better to diagnose it as an ill-formed expression
2911 // than as an ill-formed deleted non-function member.
2912 // An initializer of '= delete p, foo' will never be parsed, because
2913 // a top-level comma always ends the initializer expression.
2914 const Token &Next = NextToken();
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002915 if (IsFunction || Next.isOneOf(tok::semi, tok::comma, tok::eof)) {
Richard Smith938f40b2011-06-11 17:19:42 +00002916 if (IsFunction)
2917 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2918 << 1 /* delete */;
2919 else
2920 Diag(ConsumeToken(), diag::err_deleted_non_function);
Richard Smithedcb26e2014-06-11 00:49:52 +00002921 return ExprError();
Richard Smith938f40b2011-06-11 17:19:42 +00002922 }
2923 } else if (Tok.is(tok::kw_default)) {
Richard Smith938f40b2011-06-11 17:19:42 +00002924 if (IsFunction)
2925 Diag(Tok, diag::err_default_delete_in_multiple_declaration)
2926 << 0 /* default */;
2927 else
2928 Diag(ConsumeToken(), diag::err_default_special_members);
Richard Smithedcb26e2014-06-11 00:49:52 +00002929 return ExprError();
Richard Smith938f40b2011-06-11 17:19:42 +00002930 }
David Majnemer87ff66c2014-12-13 11:34:16 +00002931 }
2932 if (const auto *PD = dyn_cast_or_null<MSPropertyDecl>(D)) {
2933 Diag(Tok, diag::err_ms_property_initializer) << PD;
2934 return ExprError();
Sebastian Redleef474c2012-02-22 10:50:08 +00002935 }
2936 return ParseInitializer();
Richard Smith938f40b2011-06-11 17:19:42 +00002937}
2938
Richard Smith65ebb4a2015-03-26 04:09:53 +00002939void Parser::SkipCXXMemberSpecification(SourceLocation RecordLoc,
2940 SourceLocation AttrFixitLoc,
2941 unsigned TagType, Decl *TagDecl) {
2942 // Skip the optional 'final' keyword.
2943 if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
2944 assert(isCXX11FinalKeyword() && "not a class definition");
2945 ConsumeToken();
2946
2947 // Diagnose any C++11 attributes after 'final' keyword.
2948 // We deliberately discard these attributes.
2949 ParsedAttributesWithRange Attrs(AttrFactory);
2950 CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
2951
2952 // This can only happen if we had malformed misplaced attributes;
2953 // we only get called if there is a colon or left-brace after the
2954 // attributes.
2955 if (Tok.isNot(tok::colon) && Tok.isNot(tok::l_brace))
2956 return;
2957 }
2958
2959 // Skip the base clauses. This requires actually parsing them, because
2960 // otherwise we can't be sure where they end (a left brace may appear
2961 // within a template argument).
2962 if (Tok.is(tok::colon)) {
2963 // Enter the scope of the class so that we can correctly parse its bases.
2964 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
2965 ParsingClassDefinition ParsingDef(*this, TagDecl, /*NonNestedClass*/ true,
2966 TagType == DeclSpec::TST_interface);
Richard Smith0f192e82015-06-11 22:48:25 +00002967 auto OldContext =
2968 Actions.ActOnTagStartSkippedDefinition(getCurScope(), TagDecl);
Richard Smith65ebb4a2015-03-26 04:09:53 +00002969
2970 // Parse the bases but don't attach them to the class.
2971 ParseBaseClause(nullptr);
2972
Richard Smith0f192e82015-06-11 22:48:25 +00002973 Actions.ActOnTagFinishSkippedDefinition(OldContext);
Richard Smith65ebb4a2015-03-26 04:09:53 +00002974
2975 if (!Tok.is(tok::l_brace)) {
2976 Diag(PP.getLocForEndOfToken(PrevTokLocation),
2977 diag::err_expected_lbrace_after_base_specifiers);
2978 return;
2979 }
2980 }
2981
2982 // Skip the body.
2983 assert(Tok.is(tok::l_brace));
2984 BalancedDelimiterTracker T(*this, tok::l_brace);
2985 T.consumeOpen();
2986 T.skipToEnd();
Richard Smith04c6c1f2015-07-01 18:56:50 +00002987
2988 // Parse and discard any trailing attributes.
2989 ParsedAttributes Attrs(AttrFactory);
2990 if (Tok.is(tok::kw___attribute))
2991 MaybeParseGNUAttributes(Attrs);
Richard Smith65ebb4a2015-03-26 04:09:53 +00002992}
2993
Alexey Bataev05c25d62015-07-31 08:42:25 +00002994Parser::DeclGroupPtrTy Parser::ParseCXXClassMemberDeclarationWithPragmas(
2995 AccessSpecifier &AS, ParsedAttributesWithRange &AccessAttrs,
2996 DeclSpec::TST TagType, Decl *TagDecl) {
Richard Smithb55f7582017-01-28 01:12:10 +00002997 switch (Tok.getKind()) {
2998 case tok::kw___if_exists:
2999 case tok::kw___if_not_exists:
Alexey Bataev05c25d62015-07-31 08:42:25 +00003000 ParseMicrosoftIfExistsClassDeclaration(TagType, AS);
David Blaikie0403cb12016-01-15 23:43:25 +00003001 return nullptr;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003002
Richard Smithb55f7582017-01-28 01:12:10 +00003003 case tok::semi:
3004 // Check for extraneous top-level semicolon.
Alexey Bataev05c25d62015-07-31 08:42:25 +00003005 ConsumeExtraSemi(InsideStruct, TagType);
David Blaikie0403cb12016-01-15 23:43:25 +00003006 return nullptr;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003007
Richard Smithb55f7582017-01-28 01:12:10 +00003008 // Handle pragmas that can appear as member declarations.
3009 case tok::annot_pragma_vis:
Alexey Bataev05c25d62015-07-31 08:42:25 +00003010 HandlePragmaVisibility();
David Blaikie0403cb12016-01-15 23:43:25 +00003011 return nullptr;
Richard Smithb55f7582017-01-28 01:12:10 +00003012 case tok::annot_pragma_pack:
Alexey Bataev05c25d62015-07-31 08:42:25 +00003013 HandlePragmaPack();
David Blaikie0403cb12016-01-15 23:43:25 +00003014 return nullptr;
Richard Smithb55f7582017-01-28 01:12:10 +00003015 case tok::annot_pragma_align:
Alexey Bataev05c25d62015-07-31 08:42:25 +00003016 HandlePragmaAlign();
David Blaikie0403cb12016-01-15 23:43:25 +00003017 return nullptr;
Richard Smithb55f7582017-01-28 01:12:10 +00003018 case tok::annot_pragma_ms_pointers_to_members:
Alexey Bataev05c25d62015-07-31 08:42:25 +00003019 HandlePragmaMSPointersToMembers();
David Blaikie0403cb12016-01-15 23:43:25 +00003020 return nullptr;
Richard Smithb55f7582017-01-28 01:12:10 +00003021 case tok::annot_pragma_ms_pragma:
Alexey Bataev05c25d62015-07-31 08:42:25 +00003022 HandlePragmaMSPragma();
David Blaikie0403cb12016-01-15 23:43:25 +00003023 return nullptr;
Richard Smithb55f7582017-01-28 01:12:10 +00003024 case tok::annot_pragma_ms_vtordisp:
Alexey Bataev3d42f342015-11-20 07:02:57 +00003025 HandlePragmaMSVtorDisp();
David Blaikie0403cb12016-01-15 23:43:25 +00003026 return nullptr;
Richard Smithb256d302017-01-28 01:20:57 +00003027 case tok::annot_pragma_dump:
3028 HandlePragmaDump();
3029 return nullptr;
Alexey Bataev3d42f342015-11-20 07:02:57 +00003030
Richard Smithb55f7582017-01-28 01:12:10 +00003031 case tok::kw_namespace:
3032 // If we see a namespace here, a close brace was missing somewhere.
Alexey Bataev05c25d62015-07-31 08:42:25 +00003033 DiagnoseUnexpectedNamespace(cast<NamedDecl>(TagDecl));
David Blaikie0403cb12016-01-15 23:43:25 +00003034 return nullptr;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003035
Richard Smithb55f7582017-01-28 01:12:10 +00003036 case tok::kw_public:
3037 case tok::kw_protected:
3038 case tok::kw_private: {
3039 AccessSpecifier NewAS = getAccessSpecifierIfPresent();
3040 assert(NewAS != AS_none);
Alexey Bataev05c25d62015-07-31 08:42:25 +00003041 // Current token is a C++ access specifier.
3042 AS = NewAS;
3043 SourceLocation ASLoc = Tok.getLocation();
3044 unsigned TokLength = Tok.getLength();
3045 ConsumeToken();
3046 AccessAttrs.clear();
3047 MaybeParseGNUAttributes(AccessAttrs);
3048
3049 SourceLocation EndLoc;
3050 if (TryConsumeToken(tok::colon, EndLoc)) {
3051 } else if (TryConsumeToken(tok::semi, EndLoc)) {
3052 Diag(EndLoc, diag::err_expected)
3053 << tok::colon << FixItHint::CreateReplacement(EndLoc, ":");
3054 } else {
3055 EndLoc = ASLoc.getLocWithOffset(TokLength);
3056 Diag(EndLoc, diag::err_expected)
3057 << tok::colon << FixItHint::CreateInsertion(EndLoc, ":");
3058 }
3059
3060 // The Microsoft extension __interface does not permit non-public
3061 // access specifiers.
3062 if (TagType == DeclSpec::TST_interface && AS != AS_public) {
3063 Diag(ASLoc, diag::err_access_specifier_interface) << (AS == AS_protected);
3064 }
3065
3066 if (Actions.ActOnAccessSpecifier(NewAS, ASLoc, EndLoc,
3067 AccessAttrs.getList())) {
3068 // found another attribute than only annotations
3069 AccessAttrs.clear();
3070 }
3071
David Blaikie0403cb12016-01-15 23:43:25 +00003072 return nullptr;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003073 }
3074
Richard Smithb55f7582017-01-28 01:12:10 +00003075 case tok::annot_pragma_openmp:
Alexey Bataev587e1de2016-03-30 10:43:55 +00003076 return ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, AccessAttrs, TagType,
3077 TagDecl);
Alexey Bataev05c25d62015-07-31 08:42:25 +00003078
Richard Smithb55f7582017-01-28 01:12:10 +00003079 default:
3080 return ParseCXXClassMemberDeclaration(AS, AccessAttrs.getList());
3081 }
Alexey Bataev05c25d62015-07-31 08:42:25 +00003082}
3083
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003084/// ParseCXXMemberSpecification - Parse the class definition.
3085///
3086/// member-specification:
3087/// member-declaration member-specification[opt]
3088/// access-specifier ':' member-specification[opt]
3089///
Joao Matose9a3ed42012-08-31 22:18:20 +00003090void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc,
Michael Han309af292013-01-07 16:57:11 +00003091 SourceLocation AttrFixitLoc,
Richard Smith4c96e992013-02-19 23:47:15 +00003092 ParsedAttributesWithRange &Attrs,
Joao Matose9a3ed42012-08-31 22:18:20 +00003093 unsigned TagType, Decl *TagDecl) {
3094 assert((TagType == DeclSpec::TST_struct ||
3095 TagType == DeclSpec::TST_interface ||
3096 TagType == DeclSpec::TST_union ||
3097 TagType == DeclSpec::TST_class) && "Invalid TagType!");
3098
John McCallfaf5fb42010-08-26 23:41:50 +00003099 PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc,
3100 "parsing struct/union/class body");
Mike Stump11289f42009-09-09 15:08:12 +00003101
Douglas Gregoredf8f392010-01-16 20:52:59 +00003102 // Determine whether this is a non-nested class. Note that local
3103 // classes are *not* considered to be nested classes.
3104 bool NonNestedClass = true;
3105 if (!ClassStack.empty()) {
Douglas Gregor0be31a22010-07-02 17:43:08 +00003106 for (const Scope *S = getCurScope(); S; S = S->getParent()) {
Douglas Gregoredf8f392010-01-16 20:52:59 +00003107 if (S->isClassScope()) {
3108 // We're inside a class scope, so this is a nested class.
3109 NonNestedClass = false;
John McCalldb632ac2012-09-25 07:32:39 +00003110
3111 // The Microsoft extension __interface does not permit nested classes.
3112 if (getCurrentClass().IsInterface) {
3113 Diag(RecordLoc, diag::err_invalid_member_in_interface)
3114 << /*ErrorType=*/6
3115 << (isa<NamedDecl>(TagDecl)
3116 ? cast<NamedDecl>(TagDecl)->getQualifiedNameAsString()
David Blaikieabe1a392014-04-02 05:58:29 +00003117 : "(anonymous)");
John McCalldb632ac2012-09-25 07:32:39 +00003118 }
Douglas Gregoredf8f392010-01-16 20:52:59 +00003119 break;
3120 }
3121
Serge Pavlovd9c0bcf2015-07-14 10:02:10 +00003122 if ((S->getFlags() & Scope::FnScope))
3123 // If we're in a function or function template then this is a local
3124 // class rather than a nested class.
3125 break;
Douglas Gregoredf8f392010-01-16 20:52:59 +00003126 }
3127 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003128
3129 // Enter a scope for the class.
Douglas Gregor658b9552009-01-09 22:42:13 +00003130 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003131
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003132 // Note that we are parsing a new (potentially-nested) class definition.
John McCalldb632ac2012-09-25 07:32:39 +00003133 ParsingClassDefinition ParsingDef(*this, TagDecl, NonNestedClass,
3134 TagType == DeclSpec::TST_interface);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003135
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003136 if (TagDecl)
Douglas Gregor0be31a22010-07-02 17:43:08 +00003137 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
John McCall2d814c32009-12-19 21:48:58 +00003138
Anders Carlssonf9eb63b2011-03-25 14:46:08 +00003139 SourceLocation FinalLoc;
David Majnemera5433082013-10-18 00:33:31 +00003140 bool IsFinalSpelledSealed = false;
Anders Carlssonf9eb63b2011-03-25 14:46:08 +00003141
3142 // Parse the optional 'final' keyword.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003143 if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
David Majnemera5433082013-10-18 00:33:31 +00003144 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier(Tok);
3145 assert((Specifier == VirtSpecifiers::VS_Final ||
Andrey Bokhanko276055b2016-07-29 10:42:48 +00003146 Specifier == VirtSpecifiers::VS_GNU_Final ||
David Majnemera5433082013-10-18 00:33:31 +00003147 Specifier == VirtSpecifiers::VS_Sealed) &&
3148 "not a class definition");
Richard Smithda261112011-10-15 04:21:46 +00003149 FinalLoc = ConsumeToken();
David Majnemera5433082013-10-18 00:33:31 +00003150 IsFinalSpelledSealed = Specifier == VirtSpecifiers::VS_Sealed;
Anders Carlssonf9eb63b2011-03-25 14:46:08 +00003151
David Majnemera5433082013-10-18 00:33:31 +00003152 if (TagType == DeclSpec::TST_interface)
John McCalldb632ac2012-09-25 07:32:39 +00003153 Diag(FinalLoc, diag::err_override_control_interface)
David Majnemera5433082013-10-18 00:33:31 +00003154 << VirtSpecifiers::getSpecifierName(Specifier);
3155 else if (Specifier == VirtSpecifiers::VS_Final)
3156 Diag(FinalLoc, getLangOpts().CPlusPlus11
3157 ? diag::warn_cxx98_compat_override_control_keyword
3158 : diag::ext_override_control_keyword)
3159 << VirtSpecifiers::getSpecifierName(Specifier);
3160 else if (Specifier == VirtSpecifiers::VS_Sealed)
3161 Diag(FinalLoc, diag::ext_ms_sealed_keyword);
Andrey Bokhanko276055b2016-07-29 10:42:48 +00003162 else if (Specifier == VirtSpecifiers::VS_GNU_Final)
3163 Diag(FinalLoc, diag::ext_warn_gnu_final);
Michael Han9407e502012-11-26 22:54:45 +00003164
Michael Han309af292013-01-07 16:57:11 +00003165 // Parse any C++11 attributes after 'final' keyword.
3166 // These attributes are not allowed to appear here,
3167 // and the only possible place for them to appertain
3168 // to the class would be between class-key and class-name.
Richard Smith4c96e992013-02-19 23:47:15 +00003169 CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
Nico Weber4b4be842014-12-29 06:56:50 +00003170
3171 // ParseClassSpecifier() does only a superficial check for attributes before
3172 // deciding to call this method. For example, for
3173 // `class C final alignas ([l) {` it will decide that this looks like a
3174 // misplaced attribute since it sees `alignas '(' ')'`. But the actual
3175 // attribute parsing code will try to parse the '[' as a constexpr lambda
3176 // and consume enough tokens that the alignas parsing code will eat the
3177 // opening '{'. So bail out if the next token isn't one we expect.
Nico Weber36de3a22014-12-29 21:56:22 +00003178 if (!Tok.is(tok::colon) && !Tok.is(tok::l_brace)) {
3179 if (TagDecl)
3180 Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
Nico Weber4b4be842014-12-29 06:56:50 +00003181 return;
Nico Weber36de3a22014-12-29 21:56:22 +00003182 }
Anders Carlssonf9eb63b2011-03-25 14:46:08 +00003183 }
Anders Carlsson4b63d0e2011-01-22 16:56:46 +00003184
John McCall2d814c32009-12-19 21:48:58 +00003185 if (Tok.is(tok::colon)) {
3186 ParseBaseClause(TagDecl);
John McCall2d814c32009-12-19 21:48:58 +00003187 if (!Tok.is(tok::l_brace)) {
Ismail Pazarbasi129c44c2014-09-25 21:13:02 +00003188 bool SuggestFixIt = false;
3189 SourceLocation BraceLoc = PP.getLocForEndOfToken(PrevTokLocation);
3190 if (Tok.isAtStartOfLine()) {
3191 switch (Tok.getKind()) {
3192 case tok::kw_private:
3193 case tok::kw_protected:
3194 case tok::kw_public:
3195 SuggestFixIt = NextToken().getKind() == tok::colon;
3196 break;
3197 case tok::kw_static_assert:
3198 case tok::r_brace:
3199 case tok::kw_using:
3200 // base-clause can have simple-template-id; 'template' can't be there
3201 case tok::kw_template:
3202 SuggestFixIt = true;
3203 break;
3204 case tok::identifier:
3205 SuggestFixIt = isConstructorDeclarator(true);
3206 break;
3207 default:
3208 SuggestFixIt = isCXXSimpleDeclaration(/*AllowForRangeDecl=*/false);
3209 break;
3210 }
3211 }
3212 DiagnosticBuilder LBraceDiag =
3213 Diag(BraceLoc, diag::err_expected_lbrace_after_base_specifiers);
3214 if (SuggestFixIt) {
3215 LBraceDiag << FixItHint::CreateInsertion(BraceLoc, " {");
3216 // Try recovering from missing { after base-clause.
3217 PP.EnterToken(Tok);
3218 Tok.setKind(tok::l_brace);
3219 } else {
3220 if (TagDecl)
3221 Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
3222 return;
3223 }
John McCall2d814c32009-12-19 21:48:58 +00003224 }
3225 }
3226
3227 assert(Tok.is(tok::l_brace));
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003228 BalancedDelimiterTracker T(*this, tok::l_brace);
3229 T.consumeOpen();
John McCall2d814c32009-12-19 21:48:58 +00003230
John McCall08bede42010-05-28 08:11:17 +00003231 if (TagDecl)
Anders Carlsson30f29442011-03-25 14:31:08 +00003232 Actions.ActOnStartCXXMemberDeclarations(getCurScope(), TagDecl, FinalLoc,
David Majnemera5433082013-10-18 00:33:31 +00003233 IsFinalSpelledSealed,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003234 T.getOpenLocation());
John McCall1c7e6ec2009-12-20 07:58:13 +00003235
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003236 // C++ 11p3: Members of a class defined with the keyword class are private
3237 // by default. Members of a class defined with the keywords struct or union
3238 // are public by default.
3239 AccessSpecifier CurAS;
3240 if (TagType == DeclSpec::TST_class)
3241 CurAS = AS_private;
3242 else
3243 CurAS = AS_public;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003244 ParsedAttributesWithRange AccessAttrs(AttrFactory);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003245
Douglas Gregor9377c822010-06-21 22:31:09 +00003246 if (TagDecl) {
3247 // While we still have something to read, read the member-declarations.
Richard Smith752ada82015-11-17 23:32:01 +00003248 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
3249 Tok.isNot(tok::eof)) {
Douglas Gregor9377c822010-06-21 22:31:09 +00003250 // Each iteration of this loop reads one member-declaration.
Alexey Bataev05c25d62015-07-31 08:42:25 +00003251 ParseCXXClassMemberDeclarationWithPragmas(
3252 CurAS, AccessAttrs, static_cast<DeclSpec::TST>(TagType), TagDecl);
Serge Pavlovc4e04a22015-09-19 05:32:57 +00003253 }
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003254 T.consumeClose();
Douglas Gregor9377c822010-06-21 22:31:09 +00003255 } else {
Alexey Bataevee6507d2013-11-18 08:17:37 +00003256 SkipUntil(tok::r_brace);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003257 }
Mike Stump11289f42009-09-09 15:08:12 +00003258
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003259 // If attributes exist after class contents, parse them.
John McCall084e83d2011-03-24 11:26:52 +00003260 ParsedAttributes attrs(AttrFactory);
John McCall53fa7142010-12-24 02:08:15 +00003261 MaybeParseGNUAttributes(attrs);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003262
John McCall08bede42010-05-28 08:11:17 +00003263 if (TagDecl)
Douglas Gregor0be31a22010-07-02 17:43:08 +00003264 Actions.ActOnFinishCXXMemberSpecification(getCurScope(), RecordLoc, TagDecl,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003265 T.getOpenLocation(),
3266 T.getCloseLocation(),
John McCall53fa7142010-12-24 02:08:15 +00003267 attrs.getList());
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003268
Douglas Gregor433e0532012-04-16 18:27:27 +00003269 // C++11 [class.mem]p2:
3270 // Within the class member-specification, the class is regarded as complete
Richard Smith0b3a4622014-11-13 20:01:57 +00003271 // within function bodies, default arguments, exception-specifications, and
Douglas Gregor433e0532012-04-16 18:27:27 +00003272 // brace-or-equal-initializers for non-static data members (including such
3273 // things in nested classes).
Douglas Gregor9377c822010-06-21 22:31:09 +00003274 if (TagDecl && NonNestedClass) {
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003275 // We are not inside a nested class. This class and its nested classes
Douglas Gregor4d87df52008-12-16 21:30:33 +00003276 // are complete and we can parse the delayed portions of method
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00003277 // declarations and the lexed inline method definitions, along with any
3278 // delayed attributes.
Douglas Gregor428119e2010-06-16 23:45:56 +00003279 SourceLocation SavedPrevTokLocation = PrevTokLocation;
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00003280 ParseLexedAttributes(getCurrentClass());
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003281 ParseLexedMethodDeclarations(getCurrentClass());
Richard Smith84973e52012-04-21 18:42:51 +00003282
3283 // We've finished with all pending member declarations.
3284 Actions.ActOnFinishCXXMemberDecls();
3285
Richard Smith938f40b2011-06-11 17:19:42 +00003286 ParseLexedMemberInitializers(getCurrentClass());
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003287 ParseLexedMethodDefs(getCurrentClass());
Douglas Gregor428119e2010-06-16 23:45:56 +00003288 PrevTokLocation = SavedPrevTokLocation;
Reid Klecknerbba3cb92015-03-17 19:00:50 +00003289
3290 // We've finished parsing everything, including default argument
3291 // initializers.
Hans Wennborg99000c22015-08-15 01:18:16 +00003292 Actions.ActOnFinishCXXNonNestedClass(TagDecl);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003293 }
3294
John McCall08bede42010-05-28 08:11:17 +00003295 if (TagDecl)
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00003296 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getRange());
John McCall2ff380a2010-03-17 00:38:33 +00003297
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003298 // Leave the class scope.
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003299 ParsingDef.Pop();
Douglas Gregor7307d6c2008-12-10 06:34:36 +00003300 ClassScope.Exit();
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003301}
Douglas Gregore8381c02008-11-05 04:29:56 +00003302
Richard Smith2ac43ad2013-11-15 23:00:02 +00003303void Parser::DiagnoseUnexpectedNamespace(NamedDecl *D) {
Richard Smithda35e962013-11-09 04:52:51 +00003304 assert(Tok.is(tok::kw_namespace));
3305
3306 // FIXME: Suggest where the close brace should have gone by looking
3307 // at indentation changes within the definition body.
Richard Smith2ac43ad2013-11-15 23:00:02 +00003308 Diag(D->getLocation(),
3309 diag::err_missing_end_of_definition) << D;
Richard Smithda35e962013-11-09 04:52:51 +00003310 Diag(Tok.getLocation(),
Richard Smith2ac43ad2013-11-15 23:00:02 +00003311 diag::note_missing_end_of_definition_before) << D;
Richard Smithda35e962013-11-09 04:52:51 +00003312
3313 // Push '};' onto the token stream to recover.
3314 PP.EnterToken(Tok);
3315
3316 Tok.startToken();
3317 Tok.setLocation(PP.getLocForEndOfToken(PrevTokLocation));
3318 Tok.setKind(tok::semi);
3319 PP.EnterToken(Tok);
3320
3321 Tok.setKind(tok::r_brace);
3322}
3323
Douglas Gregore8381c02008-11-05 04:29:56 +00003324/// ParseConstructorInitializer - Parse a C++ constructor initializer,
3325/// which explicitly initializes the members or base classes of a
3326/// class (C++ [class.base.init]). For example, the three initializers
3327/// after the ':' in the Derived constructor below:
3328///
3329/// @code
3330/// class Base { };
3331/// class Derived : Base {
3332/// int x;
3333/// float f;
3334/// public:
3335/// Derived(float f) : Base(), x(17), f(f) { }
3336/// };
3337/// @endcode
3338///
Mike Stump11289f42009-09-09 15:08:12 +00003339/// [C++] ctor-initializer:
3340/// ':' mem-initializer-list
Douglas Gregore8381c02008-11-05 04:29:56 +00003341///
Mike Stump11289f42009-09-09 15:08:12 +00003342/// [C++] mem-initializer-list:
Douglas Gregor44e7df62011-01-04 00:32:56 +00003343/// mem-initializer ...[opt]
3344/// mem-initializer ...[opt] , mem-initializer-list
John McCall48871652010-08-21 09:40:31 +00003345void Parser::ParseConstructorInitializer(Decl *ConstructorDecl) {
Nico Weber3b00fdc2015-03-07 19:52:39 +00003346 assert(Tok.is(tok::colon) &&
3347 "Constructor initializer always starts with ':'");
Douglas Gregore8381c02008-11-05 04:29:56 +00003348
Nico Weber3b00fdc2015-03-07 19:52:39 +00003349 // Poison the SEH identifiers so they are flagged as illegal in constructor
3350 // initializers.
John Wiegley1c0675e2011-04-28 01:08:34 +00003351 PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
Douglas Gregore8381c02008-11-05 04:29:56 +00003352 SourceLocation ColonLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +00003353
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003354 SmallVector<CXXCtorInitializer*, 4> MemInitializers;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003355 bool AnyErrors = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003356
Douglas Gregore8381c02008-11-05 04:29:56 +00003357 do {
Douglas Gregoreaeeca92010-08-28 00:00:50 +00003358 if (Tok.is(tok::code_completion)) {
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00003359 Actions.CodeCompleteConstructorInitializer(ConstructorDecl,
3360 MemInitializers);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00003361 return cutOffParsing();
Douglas Gregoreaeeca92010-08-28 00:00:50 +00003362 }
Alexey Bataev79de17d2016-01-20 05:25:51 +00003363
3364 MemInitResult MemInit = ParseMemInitializer(ConstructorDecl);
3365 if (!MemInit.isInvalid())
3366 MemInitializers.push_back(MemInit.get());
3367 else
3368 AnyErrors = true;
3369
Douglas Gregore8381c02008-11-05 04:29:56 +00003370 if (Tok.is(tok::comma))
3371 ConsumeToken();
3372 else if (Tok.is(tok::l_brace))
3373 break;
Alexey Bataev79de17d2016-01-20 05:25:51 +00003374 // If the previous initializer was valid and the next token looks like a
3375 // base or member initializer, assume that we're just missing a comma.
3376 else if (!MemInit.isInvalid() &&
3377 Tok.isOneOf(tok::identifier, tok::coloncolon)) {
Douglas Gregorce66d022010-09-07 14:51:08 +00003378 SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation);
3379 Diag(Loc, diag::err_ctor_init_missing_comma)
3380 << FixItHint::CreateInsertion(Loc, ", ");
3381 } else {
Douglas Gregore8381c02008-11-05 04:29:56 +00003382 // Skip over garbage, until we get to '{'. Don't eat the '{'.
Alexey Bataev79de17d2016-01-20 05:25:51 +00003383 if (!MemInit.isInvalid())
3384 Diag(Tok.getLocation(), diag::err_expected_either) << tok::l_brace
3385 << tok::comma;
Alexey Bataevee6507d2013-11-18 08:17:37 +00003386 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
Douglas Gregore8381c02008-11-05 04:29:56 +00003387 break;
3388 }
3389 } while (true);
3390
David Blaikie3fc2f912013-01-17 05:26:25 +00003391 Actions.ActOnMemInitializers(ConstructorDecl, ColonLoc, MemInitializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003392 AnyErrors);
Douglas Gregore8381c02008-11-05 04:29:56 +00003393}
3394
3395/// ParseMemInitializer - Parse a C++ member initializer, which is
3396/// part of a constructor initializer that explicitly initializes one
3397/// member or base class (C++ [class.base.init]). See
3398/// ParseConstructorInitializer for an example.
3399///
3400/// [C++] mem-initializer:
3401/// mem-initializer-id '(' expression-list[opt] ')'
Sebastian Redl3da34892011-06-05 12:23:16 +00003402/// [C++0x] mem-initializer-id braced-init-list
Mike Stump11289f42009-09-09 15:08:12 +00003403///
Douglas Gregore8381c02008-11-05 04:29:56 +00003404/// [C++] mem-initializer-id:
3405/// '::'[opt] nested-name-specifier[opt] class-name
3406/// identifier
Craig Topper9ad7e262014-10-31 06:57:07 +00003407MemInitResult Parser::ParseMemInitializer(Decl *ConstructorDecl) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00003408 // parse '::'[opt] nested-name-specifier[opt]
3409 CXXScopeSpec SS;
David Blaikieefdccaa2016-01-15 23:43:34 +00003410 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false);
Richard Smithaf3b3252017-05-18 19:21:48 +00003411
3412 // : identifier
3413 IdentifierInfo *II = nullptr;
3414 SourceLocation IdLoc = Tok.getLocation();
3415 // : declype(...)
3416 DeclSpec DS(AttrFactory);
3417 // : template_name<...>
John McCallba7bf592010-08-24 05:47:05 +00003418 ParsedType TemplateTypeTy;
Richard Smithaf3b3252017-05-18 19:21:48 +00003419
3420 if (Tok.is(tok::identifier)) {
3421 // Get the identifier. This may be a member name or a class name,
3422 // but we'll let the semantic analysis determine which it is.
3423 II = Tok.getIdentifierInfo();
3424 ConsumeToken();
3425 } else if (Tok.is(tok::annot_decltype)) {
3426 // Get the decltype expression, if there is one.
3427 // Uses of decltype will already have been converted to annot_decltype by
3428 // ParseOptionalCXXScopeSpecifier at this point.
3429 // FIXME: Can we get here with a scope specifier?
3430 ParseDecltypeSpecifier(DS);
3431 } else {
3432 TemplateIdAnnotation *TemplateId = Tok.is(tok::annot_template_id)
3433 ? takeTemplateIdAnnotation(Tok)
3434 : nullptr;
3435 if (TemplateId && (TemplateId->Kind == TNK_Type_template ||
3436 TemplateId->Kind == TNK_Dependent_template_name)) {
Richard Smith62559bd2017-02-01 21:36:38 +00003437 AnnotateTemplateIdTokenAsType(/*IsClassName*/true);
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00003438 assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
John McCallba7bf592010-08-24 05:47:05 +00003439 TemplateTypeTy = getTypeAnnotation(Tok);
Richard Smithaf3b3252017-05-18 19:21:48 +00003440 ConsumeAnnotationToken();
3441 } else {
3442 Diag(Tok, diag::err_expected_member_or_base_name);
3443 return true;
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00003444 }
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00003445 }
Douglas Gregore8381c02008-11-05 04:29:56 +00003446
3447 // Parse the '('.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003448 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
Richard Smith5d164bc2011-10-15 05:09:34 +00003449 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
3450
Sebastian Redla74948d2011-09-24 17:48:25 +00003451 ExprResult InitList = ParseBraceInitializer();
3452 if (InitList.isInvalid())
3453 return true;
3454
3455 SourceLocation EllipsisLoc;
Alp Toker094e5212014-01-05 03:27:11 +00003456 TryConsumeToken(tok::ellipsis, EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00003457
3458 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
David Blaikie186a8892012-01-24 06:03:59 +00003459 TemplateTypeTy, DS, IdLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003460 InitList.get(), EllipsisLoc);
Sebastian Redl3da34892011-06-05 12:23:16 +00003461 } else if(Tok.is(tok::l_paren)) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003462 BalancedDelimiterTracker T(*this, tok::l_paren);
3463 T.consumeOpen();
Douglas Gregore8381c02008-11-05 04:29:56 +00003464
Sebastian Redl3da34892011-06-05 12:23:16 +00003465 // Parse the optional expression-list.
Benjamin Kramerf0623432012-08-23 22:51:59 +00003466 ExprVector ArgExprs;
Sebastian Redl3da34892011-06-05 12:23:16 +00003467 CommaLocsTy CommaLocs;
3468 if (Tok.isNot(tok::r_paren) && ParseExpressionList(ArgExprs, CommaLocs)) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00003469 SkipUntil(tok::r_paren, StopAtSemi);
Sebastian Redl3da34892011-06-05 12:23:16 +00003470 return true;
3471 }
3472
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003473 T.consumeClose();
Sebastian Redl3da34892011-06-05 12:23:16 +00003474
3475 SourceLocation EllipsisLoc;
Alp Toker97650562014-01-10 11:19:30 +00003476 TryConsumeToken(tok::ellipsis, EllipsisLoc);
Sebastian Redl3da34892011-06-05 12:23:16 +00003477
3478 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
David Blaikie186a8892012-01-24 06:03:59 +00003479 TemplateTypeTy, DS, IdLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00003480 T.getOpenLocation(), ArgExprs,
3481 T.getCloseLocation(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00003482 }
3483
Alp Tokerec543272013-12-24 09:48:30 +00003484 if (getLangOpts().CPlusPlus11)
3485 return Diag(Tok, diag::err_expected_either) << tok::l_paren << tok::l_brace;
3486 else
3487 return Diag(Tok, diag::err_expected) << tok::l_paren;
Douglas Gregore8381c02008-11-05 04:29:56 +00003488}
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003489
Sebastian Redl965b0e32011-03-05 14:45:16 +00003490/// \brief Parse a C++ exception-specification if present (C++0x [except.spec]).
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003491///
Douglas Gregor356513d2008-12-01 18:00:20 +00003492/// exception-specification:
Sebastian Redl965b0e32011-03-05 14:45:16 +00003493/// dynamic-exception-specification
3494/// noexcept-specification
3495///
3496/// noexcept-specification:
3497/// 'noexcept'
3498/// 'noexcept' '(' constant-expression ')'
3499ExceptionSpecificationType
Richard Smith0b3a4622014-11-13 20:01:57 +00003500Parser::tryParseExceptionSpecification(bool Delayed,
Douglas Gregor433e0532012-04-16 18:27:27 +00003501 SourceRange &SpecificationRange,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003502 SmallVectorImpl<ParsedType> &DynamicExceptions,
3503 SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
Richard Smith0b3a4622014-11-13 20:01:57 +00003504 ExprResult &NoexceptExpr,
3505 CachedTokens *&ExceptionSpecTokens) {
Sebastian Redl965b0e32011-03-05 14:45:16 +00003506 ExceptionSpecificationType Result = EST_None;
Hans Wennborgdcfba332015-10-06 23:40:43 +00003507 ExceptionSpecTokens = nullptr;
Richard Smith0b3a4622014-11-13 20:01:57 +00003508
3509 // Handle delayed parsing of exception-specifications.
3510 if (Delayed) {
3511 if (Tok.isNot(tok::kw_throw) && Tok.isNot(tok::kw_noexcept))
3512 return EST_None;
Sebastian Redl965b0e32011-03-05 14:45:16 +00003513
Richard Smith0b3a4622014-11-13 20:01:57 +00003514 // Consume and cache the starting token.
3515 bool IsNoexcept = Tok.is(tok::kw_noexcept);
3516 Token StartTok = Tok;
3517 SpecificationRange = SourceRange(ConsumeToken());
3518
3519 // Check for a '('.
3520 if (!Tok.is(tok::l_paren)) {
3521 // If this is a bare 'noexcept', we're done.
3522 if (IsNoexcept) {
3523 Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
Hans Wennborgdcfba332015-10-06 23:40:43 +00003524 NoexceptExpr = nullptr;
Richard Smith0b3a4622014-11-13 20:01:57 +00003525 return EST_BasicNoexcept;
3526 }
3527
3528 Diag(Tok, diag::err_expected_lparen_after) << "throw";
3529 return EST_DynamicNone;
3530 }
3531
3532 // Cache the tokens for the exception-specification.
3533 ExceptionSpecTokens = new CachedTokens;
3534 ExceptionSpecTokens->push_back(StartTok); // 'throw' or 'noexcept'
3535 ExceptionSpecTokens->push_back(Tok); // '('
3536 SpecificationRange.setEnd(ConsumeParen()); // '('
Richard Smithb1c217e2015-01-13 02:24:58 +00003537
3538 ConsumeAndStoreUntil(tok::r_paren, *ExceptionSpecTokens,
3539 /*StopAtSemi=*/true,
3540 /*ConsumeFinalToken=*/true);
Aaron Ballman580ccaf2016-01-12 21:04:22 +00003541 SpecificationRange.setEnd(ExceptionSpecTokens->back().getLocation());
3542
Richard Smith0b3a4622014-11-13 20:01:57 +00003543 return EST_Unparsed;
3544 }
3545
Sebastian Redl965b0e32011-03-05 14:45:16 +00003546 // See if there's a dynamic specification.
3547 if (Tok.is(tok::kw_throw)) {
3548 Result = ParseDynamicExceptionSpecification(SpecificationRange,
3549 DynamicExceptions,
3550 DynamicExceptionRanges);
3551 assert(DynamicExceptions.size() == DynamicExceptionRanges.size() &&
3552 "Produced different number of exception types and ranges.");
3553 }
3554
3555 // If there's no noexcept specification, we're done.
3556 if (Tok.isNot(tok::kw_noexcept))
3557 return Result;
3558
Richard Smithb15c11c2011-10-17 23:06:20 +00003559 Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
3560
Sebastian Redl965b0e32011-03-05 14:45:16 +00003561 // If we already had a dynamic specification, parse the noexcept for,
3562 // recovery, but emit a diagnostic and don't store the results.
3563 SourceRange NoexceptRange;
3564 ExceptionSpecificationType NoexceptType = EST_None;
3565
3566 SourceLocation KeywordLoc = ConsumeToken();
3567 if (Tok.is(tok::l_paren)) {
3568 // There is an argument.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003569 BalancedDelimiterTracker T(*this, tok::l_paren);
3570 T.consumeOpen();
Sebastian Redl965b0e32011-03-05 14:45:16 +00003571 NoexceptType = EST_ComputedNoexcept;
3572 NoexceptExpr = ParseConstantExpression();
Serge Pavlov3739f5e72015-06-29 17:50:19 +00003573 T.consumeClose();
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003574 // The argument must be contextually convertible to bool. We use
Richard Smith03a4aa32016-06-23 19:02:52 +00003575 // CheckBooleanCondition for this purpose.
3576 // FIXME: Add a proper Sema entry point for this.
Serge Pavlov3739f5e72015-06-29 17:50:19 +00003577 if (!NoexceptExpr.isInvalid()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00003578 NoexceptExpr =
3579 Actions.CheckBooleanCondition(KeywordLoc, NoexceptExpr.get());
Serge Pavlov3739f5e72015-06-29 17:50:19 +00003580 NoexceptRange = SourceRange(KeywordLoc, T.getCloseLocation());
3581 } else {
Malcolm Parsonsa3220ce2017-01-12 16:11:28 +00003582 NoexceptType = EST_BasicNoexcept;
Serge Pavlov3739f5e72015-06-29 17:50:19 +00003583 }
Sebastian Redl965b0e32011-03-05 14:45:16 +00003584 } else {
3585 // There is no argument.
3586 NoexceptType = EST_BasicNoexcept;
3587 NoexceptRange = SourceRange(KeywordLoc, KeywordLoc);
3588 }
3589
3590 if (Result == EST_None) {
3591 SpecificationRange = NoexceptRange;
3592 Result = NoexceptType;
3593
3594 // If there's a dynamic specification after a noexcept specification,
3595 // parse that and ignore the results.
3596 if (Tok.is(tok::kw_throw)) {
3597 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
3598 ParseDynamicExceptionSpecification(NoexceptRange, DynamicExceptions,
3599 DynamicExceptionRanges);
3600 }
3601 } else {
3602 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
3603 }
3604
3605 return Result;
3606}
3607
Richard Smith8ca78a12013-06-13 02:02:51 +00003608static void diagnoseDynamicExceptionSpecification(
Craig Toppere335f252015-10-04 04:53:55 +00003609 Parser &P, SourceRange Range, bool IsNoexcept) {
Richard Smith8ca78a12013-06-13 02:02:51 +00003610 if (P.getLangOpts().CPlusPlus11) {
3611 const char *Replacement = IsNoexcept ? "noexcept" : "noexcept(false)";
Richard Smith82da19d2016-12-08 02:49:07 +00003612 P.Diag(Range.getBegin(),
3613 P.getLangOpts().CPlusPlus1z && !IsNoexcept
3614 ? diag::ext_dynamic_exception_spec
3615 : diag::warn_exception_spec_deprecated)
3616 << Range;
Richard Smith8ca78a12013-06-13 02:02:51 +00003617 P.Diag(Range.getBegin(), diag::note_exception_spec_deprecated)
3618 << Replacement << FixItHint::CreateReplacement(Range, Replacement);
3619 }
3620}
3621
Sebastian Redl965b0e32011-03-05 14:45:16 +00003622/// ParseDynamicExceptionSpecification - Parse a C++
3623/// dynamic-exception-specification (C++ [except.spec]).
3624///
3625/// dynamic-exception-specification:
Douglas Gregor356513d2008-12-01 18:00:20 +00003626/// 'throw' '(' type-id-list [opt] ')'
3627/// [MS] 'throw' '(' '...' ')'
Mike Stump11289f42009-09-09 15:08:12 +00003628///
Douglas Gregor356513d2008-12-01 18:00:20 +00003629/// type-id-list:
Douglas Gregor830837d2010-12-20 23:57:46 +00003630/// type-id ... [opt]
3631/// type-id-list ',' type-id ... [opt]
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003632///
Sebastian Redl965b0e32011-03-05 14:45:16 +00003633ExceptionSpecificationType Parser::ParseDynamicExceptionSpecification(
3634 SourceRange &SpecificationRange,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003635 SmallVectorImpl<ParsedType> &Exceptions,
3636 SmallVectorImpl<SourceRange> &Ranges) {
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003637 assert(Tok.is(tok::kw_throw) && "expected throw");
Mike Stump11289f42009-09-09 15:08:12 +00003638
Sebastian Redl965b0e32011-03-05 14:45:16 +00003639 SpecificationRange.setBegin(ConsumeToken());
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003640 BalancedDelimiterTracker T(*this, tok::l_paren);
3641 if (T.consumeOpen()) {
Sebastian Redl965b0e32011-03-05 14:45:16 +00003642 Diag(Tok, diag::err_expected_lparen_after) << "throw";
3643 SpecificationRange.setEnd(SpecificationRange.getBegin());
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003644 return EST_DynamicNone;
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003645 }
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003646
Douglas Gregor356513d2008-12-01 18:00:20 +00003647 // Parse throw(...), a Microsoft extension that means "this function
3648 // can throw anything".
3649 if (Tok.is(tok::ellipsis)) {
3650 SourceLocation EllipsisLoc = ConsumeToken();
David Blaikiebbafb8a2012-03-11 07:00:24 +00003651 if (!getLangOpts().MicrosoftExt)
Douglas Gregor356513d2008-12-01 18:00:20 +00003652 Diag(EllipsisLoc, diag::ext_ellipsis_exception_spec);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003653 T.consumeClose();
3654 SpecificationRange.setEnd(T.getCloseLocation());
Richard Smith8ca78a12013-06-13 02:02:51 +00003655 diagnoseDynamicExceptionSpecification(*this, SpecificationRange, false);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003656 return EST_MSAny;
Douglas Gregor356513d2008-12-01 18:00:20 +00003657 }
3658
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003659 // Parse the sequence of type-ids.
Sebastian Redld6434562009-05-29 18:02:33 +00003660 SourceRange Range;
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003661 while (Tok.isNot(tok::r_paren)) {
Sebastian Redld6434562009-05-29 18:02:33 +00003662 TypeResult Res(ParseTypeName(&Range));
Sebastian Redl965b0e32011-03-05 14:45:16 +00003663
Douglas Gregor830837d2010-12-20 23:57:46 +00003664 if (Tok.is(tok::ellipsis)) {
3665 // C++0x [temp.variadic]p5:
3666 // - In a dynamic-exception-specification (15.4); the pattern is a
3667 // type-id.
3668 SourceLocation Ellipsis = ConsumeToken();
Sebastian Redl965b0e32011-03-05 14:45:16 +00003669 Range.setEnd(Ellipsis);
Douglas Gregor830837d2010-12-20 23:57:46 +00003670 if (!Res.isInvalid())
3671 Res = Actions.ActOnPackExpansion(Res.get(), Ellipsis);
3672 }
Sebastian Redl965b0e32011-03-05 14:45:16 +00003673
Sebastian Redld6434562009-05-29 18:02:33 +00003674 if (!Res.isInvalid()) {
Sebastian Redl2b9cacb2009-04-29 17:30:04 +00003675 Exceptions.push_back(Res.get());
Sebastian Redld6434562009-05-29 18:02:33 +00003676 Ranges.push_back(Range);
3677 }
Alp Toker97650562014-01-10 11:19:30 +00003678
3679 if (!TryConsumeToken(tok::comma))
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003680 break;
3681 }
3682
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003683 T.consumeClose();
3684 SpecificationRange.setEnd(T.getCloseLocation());
Richard Smith8ca78a12013-06-13 02:02:51 +00003685 diagnoseDynamicExceptionSpecification(*this, SpecificationRange,
3686 Exceptions.empty());
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003687 return Exceptions.empty() ? EST_DynamicNone : EST_Dynamic;
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003688}
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003689
Douglas Gregor7fb25412010-10-01 18:44:50 +00003690/// ParseTrailingReturnType - Parse a trailing return type on a new-style
3691/// function declaration.
Douglas Gregordb0b9f12011-08-04 15:30:47 +00003692TypeResult Parser::ParseTrailingReturnType(SourceRange &Range) {
Douglas Gregor7fb25412010-10-01 18:44:50 +00003693 assert(Tok.is(tok::arrow) && "expected arrow");
3694
3695 ConsumeToken();
3696
Richard Smithbfdb1082012-03-12 08:56:40 +00003697 return ParseTypeName(&Range, Declarator::TrailingReturnContext);
Douglas Gregor7fb25412010-10-01 18:44:50 +00003698}
3699
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003700/// \brief We have just started parsing the definition of a new class,
3701/// so push that class onto our stack of classes that is currently
3702/// being parsed.
John McCallc1465822011-02-14 07:13:47 +00003703Sema::ParsingClassState
John McCalldb632ac2012-09-25 07:32:39 +00003704Parser::PushParsingClass(Decl *ClassDecl, bool NonNestedClass,
3705 bool IsInterface) {
Douglas Gregoredf8f392010-01-16 20:52:59 +00003706 assert((NonNestedClass || !ClassStack.empty()) &&
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003707 "Nested class without outer class");
John McCalldb632ac2012-09-25 07:32:39 +00003708 ClassStack.push(new ParsingClass(ClassDecl, NonNestedClass, IsInterface));
John McCallc1465822011-02-14 07:13:47 +00003709 return Actions.PushParsingClass();
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003710}
3711
3712/// \brief Deallocate the given parsed class and all of its nested
3713/// classes.
3714void Parser::DeallocateParsedClasses(Parser::ParsingClass *Class) {
Douglas Gregorefc46952010-10-12 16:25:54 +00003715 for (unsigned I = 0, N = Class->LateParsedDeclarations.size(); I != N; ++I)
3716 delete Class->LateParsedDeclarations[I];
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003717 delete Class;
3718}
3719
3720/// \brief Pop the top class of the stack of classes that are
3721/// currently being parsed.
3722///
3723/// This routine should be called when we have finished parsing the
3724/// definition of a class, but have not yet popped the Scope
3725/// associated with the class's definition.
John McCallc1465822011-02-14 07:13:47 +00003726void Parser::PopParsingClass(Sema::ParsingClassState state) {
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003727 assert(!ClassStack.empty() && "Mismatched push/pop for class parsing");
Mike Stump11289f42009-09-09 15:08:12 +00003728
John McCallc1465822011-02-14 07:13:47 +00003729 Actions.PopParsingClass(state);
3730
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003731 ParsingClass *Victim = ClassStack.top();
3732 ClassStack.pop();
3733 if (Victim->TopLevelClass) {
3734 // Deallocate all of the nested classes of this class,
3735 // recursively: we don't need to keep any of this information.
3736 DeallocateParsedClasses(Victim);
3737 return;
Mike Stump11289f42009-09-09 15:08:12 +00003738 }
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003739 assert(!ClassStack.empty() && "Missing top-level class?");
3740
Douglas Gregorefc46952010-10-12 16:25:54 +00003741 if (Victim->LateParsedDeclarations.empty()) {
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003742 // The victim is a nested class, but we will not need to perform
3743 // any processing after the definition of this class since it has
3744 // no members whose handling was delayed. Therefore, we can just
3745 // remove this nested class.
Douglas Gregorefc46952010-10-12 16:25:54 +00003746 DeallocateParsedClasses(Victim);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003747 return;
3748 }
3749
3750 // This nested class has some members that will need to be processed
3751 // after the top-level class is completely defined. Therefore, add
3752 // it to the list of nested classes within its parent.
Douglas Gregor0be31a22010-07-02 17:43:08 +00003753 assert(getCurScope()->isClassScope() && "Nested class outside of class scope?");
Douglas Gregorefc46952010-10-12 16:25:54 +00003754 ClassStack.top()->LateParsedDeclarations.push_back(new LateParsedClass(this, Victim));
Douglas Gregor0be31a22010-07-02 17:43:08 +00003755 Victim->TemplateScope = getCurScope()->getParent()->isTemplateParamScope();
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003756}
Alexis Hunt96d5c762009-11-21 08:43:09 +00003757
Richard Smith3dff2512012-04-10 03:25:07 +00003758/// \brief Try to parse an 'identifier' which appears within an attribute-token.
3759///
3760/// \return the parsed identifier on success, and 0 if the next token is not an
3761/// attribute-token.
3762///
3763/// C++11 [dcl.attr.grammar]p3:
3764/// If a keyword or an alternative token that satisfies the syntactic
3765/// requirements of an identifier is contained in an attribute-token,
3766/// it is considered an identifier.
3767IdentifierInfo *Parser::TryParseCXX11AttributeIdentifier(SourceLocation &Loc) {
3768 switch (Tok.getKind()) {
3769 default:
3770 // Identifiers and keywords have identifier info attached.
David Majnemerd5271992015-01-09 18:09:39 +00003771 if (!Tok.isAnnotation()) {
3772 if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
3773 Loc = ConsumeToken();
3774 return II;
3775 }
Richard Smith3dff2512012-04-10 03:25:07 +00003776 }
Craig Topper161e4db2014-05-21 06:02:52 +00003777 return nullptr;
Richard Smith3dff2512012-04-10 03:25:07 +00003778
3779 case tok::ampamp: // 'and'
3780 case tok::pipe: // 'bitor'
3781 case tok::pipepipe: // 'or'
3782 case tok::caret: // 'xor'
3783 case tok::tilde: // 'compl'
3784 case tok::amp: // 'bitand'
3785 case tok::ampequal: // 'and_eq'
3786 case tok::pipeequal: // 'or_eq'
3787 case tok::caretequal: // 'xor_eq'
3788 case tok::exclaim: // 'not'
3789 case tok::exclaimequal: // 'not_eq'
3790 // Alternative tokens do not have identifier info, but their spelling
3791 // starts with an alphabetical character.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003792 SmallString<8> SpellingBuf;
Benjamin Kramer60be5632015-03-29 19:25:07 +00003793 SourceLocation SpellingLoc =
3794 PP.getSourceManager().getSpellingLoc(Tok.getLocation());
3795 StringRef Spelling = PP.getSpelling(SpellingLoc, SpellingBuf);
Jordan Rosea7d03842013-02-08 22:30:41 +00003796 if (isLetter(Spelling[0])) {
Richard Smith3dff2512012-04-10 03:25:07 +00003797 Loc = ConsumeToken();
Benjamin Kramer5c17f9c2012-04-22 20:43:30 +00003798 return &PP.getIdentifierTable().get(Spelling);
Richard Smith3dff2512012-04-10 03:25:07 +00003799 }
Craig Topper161e4db2014-05-21 06:02:52 +00003800 return nullptr;
Richard Smith3dff2512012-04-10 03:25:07 +00003801 }
3802}
3803
Michael Han23214e52012-10-03 01:56:22 +00003804static bool IsBuiltInOrStandardCXX11Attribute(IdentifierInfo *AttrName,
3805 IdentifierInfo *ScopeName) {
3806 switch (AttributeList::getKind(AttrName, ScopeName,
3807 AttributeList::AS_CXX11)) {
3808 case AttributeList::AT_CarriesDependency:
Aaron Ballman35f94212014-04-14 16:03:22 +00003809 case AttributeList::AT_Deprecated:
Michael Han23214e52012-10-03 01:56:22 +00003810 case AttributeList::AT_FallThrough:
Hans Wennborgdcfba332015-10-06 23:40:43 +00003811 case AttributeList::AT_CXX11NoReturn:
Michael Han23214e52012-10-03 01:56:22 +00003812 return true;
Aaron Ballmane7964782016-03-07 22:44:55 +00003813 case AttributeList::AT_WarnUnusedResult:
3814 return !ScopeName && AttrName->getName().equals("nodiscard");
Nico Weberac03bce2016-08-23 19:59:55 +00003815 case AttributeList::AT_Unused:
3816 return !ScopeName && AttrName->getName().equals("maybe_unused");
Michael Han23214e52012-10-03 01:56:22 +00003817 default:
3818 return false;
3819 }
3820}
3821
Aaron Ballmanb8e20392014-03-31 17:32:39 +00003822/// ParseCXX11AttributeArgs -- Parse a C++11 attribute-argument-clause.
3823///
3824/// [C++11] attribute-argument-clause:
3825/// '(' balanced-token-seq ')'
3826///
3827/// [C++11] balanced-token-seq:
3828/// balanced-token
3829/// balanced-token-seq balanced-token
3830///
3831/// [C++11] balanced-token:
3832/// '(' balanced-token-seq ')'
3833/// '[' balanced-token-seq ']'
3834/// '{' balanced-token-seq '}'
3835/// any token but '(', ')', '[', ']', '{', or '}'
3836bool Parser::ParseCXX11AttributeArgs(IdentifierInfo *AttrName,
3837 SourceLocation AttrNameLoc,
3838 ParsedAttributes &Attrs,
3839 SourceLocation *EndLoc,
3840 IdentifierInfo *ScopeName,
3841 SourceLocation ScopeLoc) {
3842 assert(Tok.is(tok::l_paren) && "Not a C++11 attribute argument list");
Aaron Ballman35f94212014-04-14 16:03:22 +00003843 SourceLocation LParenLoc = Tok.getLocation();
Aaron Ballmanb8e20392014-03-31 17:32:39 +00003844
3845 // If the attribute isn't known, we will not attempt to parse any
3846 // arguments.
3847 if (!hasAttribute(AttrSyntax::CXX, ScopeName, AttrName,
Bob Wilson7c730832015-07-20 22:57:31 +00003848 getTargetInfo(), getLangOpts())) {
Aaron Ballmanb8e20392014-03-31 17:32:39 +00003849 // Eat the left paren, then skip to the ending right paren.
3850 ConsumeParen();
3851 SkipUntil(tok::r_paren);
3852 return false;
3853 }
3854
Alex Lorenzd5d27e12017-03-01 18:06:25 +00003855 if (ScopeName && ScopeName->getName() == "gnu") {
Aaron Ballmanb8e20392014-03-31 17:32:39 +00003856 // GNU-scoped attributes have some special cases to handle GNU-specific
3857 // behaviors.
3858 ParseGNUAttributeArgs(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
Craig Topper161e4db2014-05-21 06:02:52 +00003859 ScopeLoc, AttributeList::AS_CXX11, nullptr);
Alex Lorenzd5d27e12017-03-01 18:06:25 +00003860 return true;
3861 }
3862
3863 unsigned NumArgs;
3864 // Some Clang-scoped attributes have some special parsing behavior.
3865 if (ScopeName && ScopeName->getName() == "clang")
3866 NumArgs =
3867 ParseClangAttributeArgs(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
3868 ScopeLoc, AttributeList::AS_CXX11);
3869 else
3870 NumArgs =
Aaron Ballman35f94212014-04-14 16:03:22 +00003871 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc,
3872 ScopeName, ScopeLoc, AttributeList::AS_CXX11);
Alex Lorenzd5d27e12017-03-01 18:06:25 +00003873
3874 const AttributeList *Attr = Attrs.getList();
3875 if (Attr && IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName)) {
3876 // If the attribute is a standard or built-in attribute and we are
3877 // parsing an argument list, we need to determine whether this attribute
3878 // was allowed to have an argument list (such as [[deprecated]]), and how
3879 // many arguments were parsed (so we can diagnose on [[deprecated()]]).
3880 if (Attr->getMaxArgs() && !NumArgs) {
3881 // The attribute was allowed to have arguments, but none were provided
3882 // even though the attribute parsed successfully. This is an error.
3883 Diag(LParenLoc, diag::err_attribute_requires_arguments) << AttrName;
3884 Attr->setInvalid(true);
3885 } else if (!Attr->getMaxArgs()) {
3886 // The attribute parsed successfully, but was not allowed to have any
3887 // arguments. It doesn't matter whether any were provided -- the
3888 // presence of the argument list (even if empty) is diagnosed.
3889 Diag(LParenLoc, diag::err_cxx11_attribute_forbids_arguments)
3890 << AttrName
3891 << FixItHint::CreateRemoval(SourceRange(LParenLoc, *EndLoc));
3892 Attr->setInvalid(true);
Aaron Ballman35f94212014-04-14 16:03:22 +00003893 }
3894 }
Aaron Ballmanb8e20392014-03-31 17:32:39 +00003895 return true;
3896}
3897
3898/// ParseCXX11AttributeSpecifier - Parse a C++11 attribute-specifier.
Alexis Hunt96d5c762009-11-21 08:43:09 +00003899///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003900/// [C++11] attribute-specifier:
Alexis Hunt96d5c762009-11-21 08:43:09 +00003901/// '[' '[' attribute-list ']' ']'
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00003902/// alignment-specifier
Alexis Hunt96d5c762009-11-21 08:43:09 +00003903///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003904/// [C++11] attribute-list:
Alexis Hunt96d5c762009-11-21 08:43:09 +00003905/// attribute[opt]
3906/// attribute-list ',' attribute[opt]
Richard Smith3dff2512012-04-10 03:25:07 +00003907/// attribute '...'
3908/// attribute-list ',' attribute '...'
Alexis Hunt96d5c762009-11-21 08:43:09 +00003909///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003910/// [C++11] attribute:
Alexis Hunt96d5c762009-11-21 08:43:09 +00003911/// attribute-token attribute-argument-clause[opt]
3912///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003913/// [C++11] attribute-token:
Alexis Hunt96d5c762009-11-21 08:43:09 +00003914/// identifier
3915/// attribute-scoped-token
3916///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003917/// [C++11] attribute-scoped-token:
Alexis Hunt96d5c762009-11-21 08:43:09 +00003918/// attribute-namespace '::' identifier
3919///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003920/// [C++11] attribute-namespace:
Alexis Hunt96d5c762009-11-21 08:43:09 +00003921/// identifier
Richard Smith3dff2512012-04-10 03:25:07 +00003922void Parser::ParseCXX11AttributeSpecifier(ParsedAttributes &attrs,
Peter Collingbourne49eedec2011-09-29 18:04:05 +00003923 SourceLocation *endLoc) {
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00003924 if (Tok.is(tok::kw_alignas)) {
Richard Smithf679b5b2011-10-14 20:48:27 +00003925 Diag(Tok.getLocation(), diag::warn_cxx98_compat_alignas);
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00003926 ParseAlignmentSpecifier(attrs, endLoc);
3927 return;
3928 }
3929
Alexis Hunt96d5c762009-11-21 08:43:09 +00003930 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square)
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003931 && "Not a C++11 attribute list");
Alexis Hunt96d5c762009-11-21 08:43:09 +00003932
Richard Smithf679b5b2011-10-14 20:48:27 +00003933 Diag(Tok.getLocation(), diag::warn_cxx98_compat_attribute);
3934
Alexis Hunt96d5c762009-11-21 08:43:09 +00003935 ConsumeBracket();
3936 ConsumeBracket();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003937
Richard Smithb7d7a042016-06-24 12:15:12 +00003938 SourceLocation CommonScopeLoc;
3939 IdentifierInfo *CommonScopeName = nullptr;
3940 if (Tok.is(tok::kw_using)) {
3941 Diag(Tok.getLocation(), getLangOpts().CPlusPlus1z
3942 ? diag::warn_cxx14_compat_using_attribute_ns
3943 : diag::ext_using_attribute_ns);
3944 ConsumeToken();
3945
3946 CommonScopeName = TryParseCXX11AttributeIdentifier(CommonScopeLoc);
3947 if (!CommonScopeName) {
3948 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
3949 SkipUntil(tok::r_square, tok::colon, StopBeforeMatch);
3950 }
3951 if (!TryConsumeToken(tok::colon) && CommonScopeName)
3952 Diag(Tok.getLocation(), diag::err_expected) << tok::colon;
3953 }
3954
Richard Smith10876ef2013-01-17 01:30:42 +00003955 llvm::SmallDenseMap<IdentifierInfo*, SourceLocation, 4> SeenAttrs;
3956
Richard Smith3dff2512012-04-10 03:25:07 +00003957 while (Tok.isNot(tok::r_square)) {
Alexis Hunt96d5c762009-11-21 08:43:09 +00003958 // attribute not present
Alp Toker97650562014-01-10 11:19:30 +00003959 if (TryConsumeToken(tok::comma))
Alexis Hunt96d5c762009-11-21 08:43:09 +00003960 continue;
Alexis Hunt96d5c762009-11-21 08:43:09 +00003961
Richard Smith3dff2512012-04-10 03:25:07 +00003962 SourceLocation ScopeLoc, AttrLoc;
Craig Topper161e4db2014-05-21 06:02:52 +00003963 IdentifierInfo *ScopeName = nullptr, *AttrName = nullptr;
Richard Smith3dff2512012-04-10 03:25:07 +00003964
3965 AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
3966 if (!AttrName)
3967 // Break out to the "expected ']'" diagnostic.
3968 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003969
Alexis Hunt96d5c762009-11-21 08:43:09 +00003970 // scoped attribute
Alp Toker97650562014-01-10 11:19:30 +00003971 if (TryConsumeToken(tok::coloncolon)) {
Richard Smith3dff2512012-04-10 03:25:07 +00003972 ScopeName = AttrName;
3973 ScopeLoc = AttrLoc;
3974
3975 AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
3976 if (!AttrName) {
Alp Tokerec543272013-12-24 09:48:30 +00003977 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
Alexey Bataevee6507d2013-11-18 08:17:37 +00003978 SkipUntil(tok::r_square, tok::comma, StopAtSemi | StopBeforeMatch);
Alexis Hunt96d5c762009-11-21 08:43:09 +00003979 continue;
3980 }
Alexis Hunt96d5c762009-11-21 08:43:09 +00003981 }
3982
Richard Smithb7d7a042016-06-24 12:15:12 +00003983 if (CommonScopeName) {
3984 if (ScopeName) {
3985 Diag(ScopeLoc, diag::err_using_attribute_ns_conflict)
3986 << SourceRange(CommonScopeLoc);
3987 } else {
3988 ScopeName = CommonScopeName;
3989 ScopeLoc = CommonScopeLoc;
3990 }
3991 }
3992
Aaron Ballmanb8e20392014-03-31 17:32:39 +00003993 bool StandardAttr = IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName);
Alexis Hunt96d5c762009-11-21 08:43:09 +00003994 bool AttrParsed = false;
Alexis Hunt96d5c762009-11-21 08:43:09 +00003995
Richard Smith10876ef2013-01-17 01:30:42 +00003996 if (StandardAttr &&
3997 !SeenAttrs.insert(std::make_pair(AttrName, AttrLoc)).second)
3998 Diag(AttrLoc, diag::err_cxx11_attribute_repeated)
Aaron Ballmanb8e20392014-03-31 17:32:39 +00003999 << AttrName << SourceRange(SeenAttrs[AttrName]);
Richard Smith10876ef2013-01-17 01:30:42 +00004000
Michael Han23214e52012-10-03 01:56:22 +00004001 // Parse attribute arguments
Aaron Ballman35f94212014-04-14 16:03:22 +00004002 if (Tok.is(tok::l_paren))
Aaron Ballmanb8e20392014-03-31 17:32:39 +00004003 AttrParsed = ParseCXX11AttributeArgs(AttrName, AttrLoc, attrs, endLoc,
4004 ScopeName, ScopeLoc);
Michael Han23214e52012-10-03 01:56:22 +00004005
4006 if (!AttrParsed)
Richard Smith84837d52012-05-03 18:27:39 +00004007 attrs.addNew(AttrName,
4008 SourceRange(ScopeLoc.isValid() ? ScopeLoc : AttrLoc,
4009 AttrLoc),
Craig Topper161e4db2014-05-21 06:02:52 +00004010 ScopeName, ScopeLoc, nullptr, 0, AttributeList::AS_CXX11);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004011
Alp Toker97650562014-01-10 11:19:30 +00004012 if (TryConsumeToken(tok::ellipsis))
Michael Han23214e52012-10-03 01:56:22 +00004013 Diag(Tok, diag::err_cxx11_attribute_forbids_ellipsis)
4014 << AttrName->getName();
Alexis Hunt96d5c762009-11-21 08:43:09 +00004015 }
4016
Alp Toker383d2c42014-01-01 03:08:43 +00004017 if (ExpectAndConsume(tok::r_square))
Alexey Bataevee6507d2013-11-18 08:17:37 +00004018 SkipUntil(tok::r_square);
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004019 if (endLoc)
4020 *endLoc = Tok.getLocation();
Alp Toker383d2c42014-01-01 03:08:43 +00004021 if (ExpectAndConsume(tok::r_square))
Alexey Bataevee6507d2013-11-18 08:17:37 +00004022 SkipUntil(tok::r_square);
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004023}
Alexis Hunt96d5c762009-11-21 08:43:09 +00004024
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00004025/// ParseCXX11Attributes - Parse a C++11 attribute-specifier-seq.
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004026///
4027/// attribute-specifier-seq:
4028/// attribute-specifier-seq[opt] attribute-specifier
Richard Smith3dff2512012-04-10 03:25:07 +00004029void Parser::ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004030 SourceLocation *endLoc) {
Richard Smith4cabd042013-02-22 09:15:49 +00004031 assert(getLangOpts().CPlusPlus11);
4032
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004033 SourceLocation StartLoc = Tok.getLocation(), Loc;
4034 if (!endLoc)
4035 endLoc = &Loc;
4036
Douglas Gregor6f981002011-10-07 20:35:25 +00004037 do {
Richard Smith3dff2512012-04-10 03:25:07 +00004038 ParseCXX11AttributeSpecifier(attrs, endLoc);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004039 } while (isCXX11AttributeSpecifier());
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004040
4041 attrs.Range = SourceRange(StartLoc, *endLoc);
Alexis Hunt96d5c762009-11-21 08:43:09 +00004042}
4043
Richard Smithc2c8bb82013-10-15 01:34:54 +00004044void Parser::DiagnoseAndSkipCXX11Attributes() {
Richard Smithc2c8bb82013-10-15 01:34:54 +00004045 // Start and end location of an attribute or an attribute list.
4046 SourceLocation StartLoc = Tok.getLocation();
Richard Smith955bf012014-06-19 11:42:00 +00004047 SourceLocation EndLoc = SkipCXX11Attributes();
4048
4049 if (EndLoc.isValid()) {
4050 SourceRange Range(StartLoc, EndLoc);
4051 Diag(StartLoc, diag::err_attributes_not_allowed)
4052 << Range;
4053 }
4054}
4055
4056SourceLocation Parser::SkipCXX11Attributes() {
Richard Smithc2c8bb82013-10-15 01:34:54 +00004057 SourceLocation EndLoc;
4058
Richard Smith955bf012014-06-19 11:42:00 +00004059 if (!isCXX11AttributeSpecifier())
4060 return EndLoc;
4061
Richard Smithc2c8bb82013-10-15 01:34:54 +00004062 do {
4063 if (Tok.is(tok::l_square)) {
4064 BalancedDelimiterTracker T(*this, tok::l_square);
4065 T.consumeOpen();
4066 T.skipToEnd();
4067 EndLoc = T.getCloseLocation();
4068 } else {
4069 assert(Tok.is(tok::kw_alignas) && "not an attribute specifier");
4070 ConsumeToken();
4071 BalancedDelimiterTracker T(*this, tok::l_paren);
4072 if (!T.consumeOpen())
4073 T.skipToEnd();
4074 EndLoc = T.getCloseLocation();
4075 }
4076 } while (isCXX11AttributeSpecifier());
4077
Richard Smith955bf012014-06-19 11:42:00 +00004078 return EndLoc;
Richard Smithc2c8bb82013-10-15 01:34:54 +00004079}
4080
Nico Weber05e1dad2016-09-03 03:25:22 +00004081/// Parse uuid() attribute when it appears in a [] Microsoft attribute.
4082void Parser::ParseMicrosoftUuidAttributeArgs(ParsedAttributes &Attrs) {
4083 assert(Tok.is(tok::identifier) && "Not a Microsoft attribute list");
4084 IdentifierInfo *UuidIdent = Tok.getIdentifierInfo();
4085 assert(UuidIdent->getName() == "uuid" && "Not a Microsoft attribute list");
4086
4087 SourceLocation UuidLoc = Tok.getLocation();
4088 ConsumeToken();
4089
4090 // Ignore the left paren location for now.
4091 BalancedDelimiterTracker T(*this, tok::l_paren);
4092 if (T.consumeOpen()) {
4093 Diag(Tok, diag::err_expected) << tok::l_paren;
4094 return;
4095 }
4096
4097 ArgsVector ArgExprs;
4098 if (Tok.is(tok::string_literal)) {
4099 // Easy case: uuid("...") -- quoted string.
4100 ExprResult StringResult = ParseStringLiteralExpression();
4101 if (StringResult.isInvalid())
4102 return;
4103 ArgExprs.push_back(StringResult.get());
4104 } else {
4105 // something like uuid({000000A0-0000-0000-C000-000000000049}) -- no
4106 // quotes in the parens. Just append the spelling of all tokens encountered
4107 // until the closing paren.
4108
4109 SmallString<42> StrBuffer; // 2 "", 36 bytes UUID, 2 optional {}, 1 nul
4110 StrBuffer += "\"";
4111
4112 // Since none of C++'s keywords match [a-f]+, accepting just tok::l_brace,
4113 // tok::r_brace, tok::minus, tok::identifier (think C000) and
4114 // tok::numeric_constant (0000) should be enough. But the spelling of the
4115 // uuid argument is checked later anyways, so there's no harm in accepting
4116 // almost anything here.
4117 // cl is very strict about whitespace in this form and errors out if any
4118 // is present, so check the space flags on the tokens.
4119 SourceLocation StartLoc = Tok.getLocation();
4120 while (Tok.isNot(tok::r_paren)) {
4121 if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
4122 Diag(Tok, diag::err_attribute_uuid_malformed_guid);
4123 SkipUntil(tok::r_paren, StopAtSemi);
4124 return;
4125 }
4126 SmallString<16> SpellingBuffer;
4127 SpellingBuffer.resize(Tok.getLength() + 1);
4128 bool Invalid = false;
4129 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
4130 if (Invalid) {
4131 SkipUntil(tok::r_paren, StopAtSemi);
4132 return;
4133 }
4134 StrBuffer += TokSpelling;
4135 ConsumeAnyToken();
4136 }
4137 StrBuffer += "\"";
4138
4139 if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
4140 Diag(Tok, diag::err_attribute_uuid_malformed_guid);
4141 ConsumeParen();
4142 return;
4143 }
4144
4145 // Pretend the user wrote the appropriate string literal here.
4146 // ActOnStringLiteral() copies the string data into the literal, so it's
4147 // ok that the Token points to StrBuffer.
4148 Token Toks[1];
4149 Toks[0].startToken();
4150 Toks[0].setKind(tok::string_literal);
4151 Toks[0].setLocation(StartLoc);
4152 Toks[0].setLiteralData(StrBuffer.data());
4153 Toks[0].setLength(StrBuffer.size());
4154 StringLiteral *UuidString =
4155 cast<StringLiteral>(Actions.ActOnStringLiteral(Toks, nullptr).get());
4156 ArgExprs.push_back(UuidString);
4157 }
4158
4159 if (!T.consumeClose()) {
Nico Weber05e1dad2016-09-03 03:25:22 +00004160 Attrs.addNew(UuidIdent, SourceRange(UuidLoc, T.getCloseLocation()), nullptr,
4161 SourceLocation(), ArgExprs.data(), ArgExprs.size(),
4162 AttributeList::AS_Microsoft);
4163 }
4164}
4165
David Majnemere4752e752015-07-08 05:55:00 +00004166/// ParseMicrosoftAttributes - Parse Microsoft attributes [Attr]
Francois Pichetc2bc5ac2010-10-11 12:59:39 +00004167///
4168/// [MS] ms-attribute:
4169/// '[' token-seq ']'
4170///
4171/// [MS] ms-attribute-seq:
4172/// ms-attribute[opt]
4173/// ms-attribute ms-attribute-seq
John McCall53fa7142010-12-24 02:08:15 +00004174void Parser::ParseMicrosoftAttributes(ParsedAttributes &attrs,
4175 SourceLocation *endLoc) {
Francois Pichetc2bc5ac2010-10-11 12:59:39 +00004176 assert(Tok.is(tok::l_square) && "Not a Microsoft attribute list");
4177
Saleem Abdulrasool425efcf2015-06-15 20:57:04 +00004178 do {
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004179 // FIXME: If this is actually a C++11 attribute, parse it as one.
Saleem Abdulrasool425efcf2015-06-15 20:57:04 +00004180 BalancedDelimiterTracker T(*this, tok::l_square);
4181 T.consumeOpen();
Nico Weber05e1dad2016-09-03 03:25:22 +00004182
4183 // Skip most ms attributes except for a whitelist.
4184 while (true) {
4185 SkipUntil(tok::r_square, tok::identifier, StopAtSemi | StopBeforeMatch);
4186 if (Tok.isNot(tok::identifier)) // ']', but also eof
4187 break;
4188 if (Tok.getIdentifierInfo()->getName() == "uuid")
4189 ParseMicrosoftUuidAttributeArgs(attrs);
4190 else
4191 ConsumeToken();
4192 }
4193
Saleem Abdulrasool425efcf2015-06-15 20:57:04 +00004194 T.consumeClose();
4195 if (endLoc)
4196 *endLoc = T.getCloseLocation();
4197 } while (Tok.is(tok::l_square));
Francois Pichetc2bc5ac2010-10-11 12:59:39 +00004198}
Francois Pichet8f981d52011-05-25 10:19:49 +00004199
4200void Parser::ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType,
4201 AccessSpecifier& CurAS) {
Douglas Gregor43edb322011-10-24 22:31:10 +00004202 IfExistsCondition Result;
Francois Pichet8f981d52011-05-25 10:19:49 +00004203 if (ParseMicrosoftIfExistsCondition(Result))
4204 return;
4205
Douglas Gregor43edb322011-10-24 22:31:10 +00004206 BalancedDelimiterTracker Braces(*this, tok::l_brace);
4207 if (Braces.consumeOpen()) {
Alp Tokerec543272013-12-24 09:48:30 +00004208 Diag(Tok, diag::err_expected) << tok::l_brace;
Francois Pichet8f981d52011-05-25 10:19:49 +00004209 return;
4210 }
Francois Pichet8f981d52011-05-25 10:19:49 +00004211
Douglas Gregor43edb322011-10-24 22:31:10 +00004212 switch (Result.Behavior) {
4213 case IEB_Parse:
4214 // Parse the declarations below.
4215 break;
4216
4217 case IEB_Dependent:
4218 Diag(Result.KeywordLoc, diag::warn_microsoft_dependent_exists)
4219 << Result.IsIfExists;
4220 // Fall through to skip.
Galina Kistanovad819d5b2017-06-01 21:19:06 +00004221 LLVM_FALLTHROUGH;
Douglas Gregor43edb322011-10-24 22:31:10 +00004222
4223 case IEB_Skip:
4224 Braces.skipToEnd();
Francois Pichet8f981d52011-05-25 10:19:49 +00004225 return;
4226 }
4227
Richard Smith34f30512013-11-23 04:06:09 +00004228 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
Francois Pichet8f981d52011-05-25 10:19:49 +00004229 // __if_exists, __if_not_exists can nest.
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00004230 if (Tok.isOneOf(tok::kw___if_exists, tok::kw___if_not_exists)) {
Francois Pichet8f981d52011-05-25 10:19:49 +00004231 ParseMicrosoftIfExistsClassDeclaration((DeclSpec::TST)TagType, CurAS);
4232 continue;
4233 }
4234
4235 // Check for extraneous top-level semicolon.
4236 if (Tok.is(tok::semi)) {
Richard Smith87f5dc52012-07-23 05:45:25 +00004237 ConsumeExtraSemi(InsideStruct, TagType);
Francois Pichet8f981d52011-05-25 10:19:49 +00004238 continue;
4239 }
4240
4241 AccessSpecifier AS = getAccessSpecifierIfPresent();
4242 if (AS != AS_none) {
4243 // Current token is a C++ access specifier.
4244 CurAS = AS;
4245 SourceLocation ASLoc = Tok.getLocation();
4246 ConsumeToken();
4247 if (Tok.is(tok::colon))
4248 Actions.ActOnAccessSpecifier(AS, ASLoc, Tok.getLocation());
4249 else
Alp Toker35d87032013-12-30 23:29:50 +00004250 Diag(Tok, diag::err_expected) << tok::colon;
Francois Pichet8f981d52011-05-25 10:19:49 +00004251 ConsumeToken();
4252 continue;
4253 }
4254
4255 // Parse all the comma separated declarators.
Craig Topper161e4db2014-05-21 06:02:52 +00004256 ParseCXXClassMemberDeclaration(CurAS, nullptr);
Francois Pichet8f981d52011-05-25 10:19:49 +00004257 }
Douglas Gregor43edb322011-10-24 22:31:10 +00004258
4259 Braces.consumeClose();
Francois Pichet8f981d52011-05-25 10:19:49 +00004260}