blob: 2301284b7f43bc2b3e6be95a44f6a38bfd69072c [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());
Bruno Cardoso Lopesdf0ee342017-07-01 00:06:47 +00001913 else {
1914 Decl *D =
1915 SkipBody.CheckSameAsPrevious ? SkipBody.New : TagOrTempResult.get();
1916 // Parse the definition body.
1917 ParseStructUnionBody(StartLoc, TagType, D);
1918 if (SkipBody.CheckSameAsPrevious &&
1919 !Actions.ActOnDuplicateDefinition(DS, TagOrTempResult.get(),
1920 SkipBody)) {
1921 DS.SetTypeSpecError();
1922 return;
1923 }
1924 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001925 }
1926
Erich Keane2fe684b2017-02-28 20:44:39 +00001927 if (!TagOrTempResult.isInvalid())
Hiroshi Inoue939d9322017-06-30 05:40:31 +00001928 // Delayed processing of attributes.
Erich Keane2fe684b2017-02-28 20:44:39 +00001929 Actions.ProcessDeclAttributeDelayed(TagOrTempResult.get(), attrs.getList());
1930
Craig Topper161e4db2014-05-21 06:02:52 +00001931 const char *PrevSpec = nullptr;
John McCallba7bf592010-08-24 05:47:05 +00001932 unsigned DiagID;
1933 bool Result;
John McCall7f41d982009-09-11 04:59:25 +00001934 if (!TypeResult.isInvalid()) {
Abramo Bagnara9875a3c2011-03-16 20:16:18 +00001935 Result = DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
1936 NameLoc.isValid() ? NameLoc : StartLoc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001937 PrevSpec, DiagID, TypeResult.get(), Policy);
John McCall7f41d982009-09-11 04:59:25 +00001938 } else if (!TagOrTempResult.isInvalid()) {
Abramo Bagnara9875a3c2011-03-16 20:16:18 +00001939 Result = DS.SetTypeSpecType(TagType, StartLoc,
1940 NameLoc.isValid() ? NameLoc : StartLoc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001941 PrevSpec, DiagID, TagOrTempResult.get(), Owned,
1942 Policy);
John McCall7f41d982009-09-11 04:59:25 +00001943 } else {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001944 DS.SetTypeSpecError();
Anders Carlssonf83c9fa2009-05-11 22:27:47 +00001945 return;
1946 }
Mike Stump11289f42009-09-09 15:08:12 +00001947
John McCallba7bf592010-08-24 05:47:05 +00001948 if (Result)
John McCall49bfce42009-08-03 20:12:06 +00001949 Diag(StartLoc, DiagID) << PrevSpec;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001950
Chris Lattnercf251412010-02-02 01:23:29 +00001951 // At this point, we've successfully parsed a class-specifier in 'definition'
1952 // form (e.g. "struct foo { int x; }". While we could just return here, we're
1953 // going to look at what comes after it to improve error recovery. If an
1954 // impossible token occurs next, we assume that the programmer forgot a ; at
1955 // the end of the declaration and recover that way.
1956 //
Richard Smith369b9f92012-06-25 21:37:02 +00001957 // Also enforce C++ [temp]p3:
1958 // In a template-declaration which defines a class, no declarator
1959 // is permitted.
Richard Smith843f18f2014-08-13 02:13:15 +00001960 //
1961 // After a type-specifier, we don't expect a semicolon. This only happens in
1962 // C, since definitions are not permitted in this context in C++.
Joao Matose9a3ed42012-08-31 22:18:20 +00001963 if (TUK == Sema::TUK_Definition &&
Richard Smith843f18f2014-08-13 02:13:15 +00001964 (getLangOpts().CPlusPlus || !isTypeSpecifier(DSC)) &&
Joao Matose9a3ed42012-08-31 22:18:20 +00001965 (TemplateInfo.Kind || !isValidAfterTypeSpecifier(false))) {
Argyrios Kyrtzidise6f69132012-12-17 20:10:43 +00001966 if (Tok.isNot(tok::semi)) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001967 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
Alp Toker383d2c42014-01-01 03:08:43 +00001968 ExpectAndConsume(tok::semi, diag::err_expected_after,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001969 DeclSpec::getSpecifierName(TagType, PPol));
Argyrios Kyrtzidise6f69132012-12-17 20:10:43 +00001970 // Push this token back into the preprocessor and change our current token
1971 // to ';' so that the rest of the code recovers as though there were an
1972 // ';' after the definition.
1973 PP.EnterToken(Tok);
1974 Tok.setKind(tok::semi);
1975 }
Chris Lattnercf251412010-02-02 01:23:29 +00001976 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001977}
1978
Mike Stump11289f42009-09-09 15:08:12 +00001979/// ParseBaseClause - Parse the base-clause of a C++ class [C++ class.derived].
Douglas Gregor556877c2008-04-13 21:30:24 +00001980///
1981/// base-clause : [C++ class.derived]
1982/// ':' base-specifier-list
1983/// base-specifier-list:
1984/// base-specifier '...'[opt]
1985/// base-specifier-list ',' base-specifier '...'[opt]
John McCall48871652010-08-21 09:40:31 +00001986void Parser::ParseBaseClause(Decl *ClassDecl) {
Douglas Gregor556877c2008-04-13 21:30:24 +00001987 assert(Tok.is(tok::colon) && "Not a base clause");
1988 ConsumeToken();
1989
Douglas Gregor29a92472008-10-22 17:49:05 +00001990 // Build up an array of parsed base specifiers.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001991 SmallVector<CXXBaseSpecifier *, 8> BaseInfo;
Douglas Gregor29a92472008-10-22 17:49:05 +00001992
Douglas Gregor556877c2008-04-13 21:30:24 +00001993 while (true) {
1994 // Parse a base-specifier.
Douglas Gregor29a92472008-10-22 17:49:05 +00001995 BaseResult Result = ParseBaseSpecifier(ClassDecl);
Douglas Gregorf8298252009-01-26 22:44:13 +00001996 if (Result.isInvalid()) {
Douglas Gregor556877c2008-04-13 21:30:24 +00001997 // Skip the rest of this base specifier, up until the comma or
1998 // opening brace.
Alexey Bataevee6507d2013-11-18 08:17:37 +00001999 SkipUntil(tok::comma, tok::l_brace, StopAtSemi | StopBeforeMatch);
Douglas Gregor29a92472008-10-22 17:49:05 +00002000 } else {
2001 // Add this to our array of base specifiers.
Douglas Gregorf8298252009-01-26 22:44:13 +00002002 BaseInfo.push_back(Result.get());
Douglas Gregor556877c2008-04-13 21:30:24 +00002003 }
2004
2005 // If the next token is a comma, consume it and keep reading
2006 // base-specifiers.
Alp Toker97650562014-01-10 11:19:30 +00002007 if (!TryConsumeToken(tok::comma))
2008 break;
Douglas Gregor556877c2008-04-13 21:30:24 +00002009 }
Douglas Gregor29a92472008-10-22 17:49:05 +00002010
2011 // Attach the base specifiers
Craig Topperaa700cb2015-12-27 21:55:19 +00002012 Actions.ActOnBaseSpecifiers(ClassDecl, BaseInfo);
Douglas Gregor556877c2008-04-13 21:30:24 +00002013}
2014
2015/// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is
2016/// one entry in the base class list of a class specifier, for example:
2017/// class foo : public bar, virtual private baz {
2018/// 'public bar' and 'virtual private baz' are each base-specifiers.
2019///
2020/// base-specifier: [C++ class.derived]
Richard Smith4c96e992013-02-19 23:47:15 +00002021/// attribute-specifier-seq[opt] base-type-specifier
2022/// attribute-specifier-seq[opt] 'virtual' access-specifier[opt]
2023/// base-type-specifier
2024/// attribute-specifier-seq[opt] access-specifier 'virtual'[opt]
2025/// base-type-specifier
Craig Topper9ad7e262014-10-31 06:57:07 +00002026BaseResult Parser::ParseBaseSpecifier(Decl *ClassDecl) {
Douglas Gregor556877c2008-04-13 21:30:24 +00002027 bool IsVirtual = false;
2028 SourceLocation StartLoc = Tok.getLocation();
2029
Richard Smith4c96e992013-02-19 23:47:15 +00002030 ParsedAttributesWithRange Attributes(AttrFactory);
2031 MaybeParseCXX11Attributes(Attributes);
2032
Douglas Gregor556877c2008-04-13 21:30:24 +00002033 // Parse the 'virtual' keyword.
Alp Toker97650562014-01-10 11:19:30 +00002034 if (TryConsumeToken(tok::kw_virtual))
Douglas Gregor556877c2008-04-13 21:30:24 +00002035 IsVirtual = true;
Douglas Gregor556877c2008-04-13 21:30:24 +00002036
Richard Smith4c96e992013-02-19 23:47:15 +00002037 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2038
Douglas Gregor556877c2008-04-13 21:30:24 +00002039 // Parse an (optional) access specifier.
2040 AccessSpecifier Access = getAccessSpecifierIfPresent();
John McCall553c0792010-01-23 00:46:32 +00002041 if (Access != AS_none)
Douglas Gregor556877c2008-04-13 21:30:24 +00002042 ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +00002043
Richard Smith4c96e992013-02-19 23:47:15 +00002044 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2045
Douglas Gregor556877c2008-04-13 21:30:24 +00002046 // Parse the 'virtual' keyword (again!), in case it came after the
2047 // access specifier.
2048 if (Tok.is(tok::kw_virtual)) {
2049 SourceLocation VirtualLoc = ConsumeToken();
2050 if (IsVirtual) {
2051 // Complain about duplicate 'virtual'
Chris Lattner6d29c102008-11-18 07:48:38 +00002052 Diag(VirtualLoc, diag::err_dup_virtual)
Douglas Gregora771f462010-03-31 17:46:05 +00002053 << FixItHint::CreateRemoval(VirtualLoc);
Douglas Gregor556877c2008-04-13 21:30:24 +00002054 }
2055
2056 IsVirtual = true;
2057 }
2058
Richard Smith4c96e992013-02-19 23:47:15 +00002059 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2060
Douglas Gregor831c93f2008-11-05 20:51:48 +00002061 // Parse the class-name.
David Majnemer51fd8a02015-07-22 23:46:18 +00002062
2063 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
2064 // implementation for VS2013 uses _Atomic as an identifier for one of the
2065 // classes in <atomic>. Treat '_Atomic' to be an identifier when we are
2066 // parsing the class-name for a base specifier.
2067 if (getLangOpts().MSVCCompat && Tok.is(tok::kw__Atomic) &&
2068 NextToken().is(tok::less))
2069 Tok.setKind(tok::identifier);
2070
Douglas Gregord54dfb82009-02-25 23:52:28 +00002071 SourceLocation EndLocation;
David Blaikie1cd50022011-10-25 17:10:12 +00002072 SourceLocation BaseLoc;
2073 TypeResult BaseType = ParseBaseTypeSpecifier(BaseLoc, EndLocation);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00002074 if (BaseType.isInvalid())
Douglas Gregor831c93f2008-11-05 20:51:48 +00002075 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002076
Douglas Gregor752a5952011-01-03 22:36:02 +00002077 // Parse the optional ellipsis (for a pack expansion). The ellipsis is
2078 // actually part of the base-specifier-list grammar productions, but we
2079 // parse it here for convenience.
2080 SourceLocation EllipsisLoc;
Alp Toker97650562014-01-10 11:19:30 +00002081 TryConsumeToken(tok::ellipsis, EllipsisLoc);
2082
Mike Stump11289f42009-09-09 15:08:12 +00002083 // Find the complete source range for the base-specifier.
Douglas Gregord54dfb82009-02-25 23:52:28 +00002084 SourceRange Range(StartLoc, EndLocation);
Mike Stump11289f42009-09-09 15:08:12 +00002085
Douglas Gregor556877c2008-04-13 21:30:24 +00002086 // Notify semantic analysis that we have parsed a complete
2087 // base-specifier.
Richard Smith4c96e992013-02-19 23:47:15 +00002088 return Actions.ActOnBaseSpecifier(ClassDecl, Range, Attributes, IsVirtual,
2089 Access, BaseType.get(), BaseLoc,
2090 EllipsisLoc);
Douglas Gregor556877c2008-04-13 21:30:24 +00002091}
2092
2093/// getAccessSpecifierIfPresent - Determine whether the next token is
2094/// a C++ access-specifier.
2095///
2096/// access-specifier: [C++ class.derived]
2097/// 'private'
2098/// 'protected'
2099/// 'public'
Mike Stump11289f42009-09-09 15:08:12 +00002100AccessSpecifier Parser::getAccessSpecifierIfPresent() const {
Douglas Gregor556877c2008-04-13 21:30:24 +00002101 switch (Tok.getKind()) {
2102 default: return AS_none;
2103 case tok::kw_private: return AS_private;
2104 case tok::kw_protected: return AS_protected;
2105 case tok::kw_public: return AS_public;
2106 }
2107}
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002108
Douglas Gregor433e0532012-04-16 18:27:27 +00002109/// \brief If the given declarator has any parts for which parsing has to be
Richard Smith0b3a4622014-11-13 20:01:57 +00002110/// delayed, e.g., default arguments or an exception-specification, create a
2111/// late-parsed method declaration record to handle the parsing at the end of
2112/// the class definition.
Douglas Gregor433e0532012-04-16 18:27:27 +00002113void Parser::HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
2114 Decl *ThisDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00002115 DeclaratorChunk::FunctionTypeInfo &FTI
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002116 = DeclaratorInfo.getFunctionTypeInfo();
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002117 // If there was a late-parsed exception-specification, we'll need a
2118 // late parse
2119 bool NeedLateParse = FTI.getExceptionSpecType() == EST_Unparsed;
Douglas Gregor433e0532012-04-16 18:27:27 +00002120
Nathan Sidwell5bb231c2015-02-19 14:03:22 +00002121 if (!NeedLateParse) {
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002122 // Look ahead to see if there are any default args
Nathan Sidwell5bb231c2015-02-19 14:03:22 +00002123 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx) {
2124 auto Param = cast<ParmVarDecl>(FTI.Params[ParamIdx].Param);
2125 if (Param->hasUnparsedDefaultArg()) {
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002126 NeedLateParse = true;
2127 break;
2128 }
Nathan Sidwell5bb231c2015-02-19 14:03:22 +00002129 }
2130 }
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002131
2132 if (NeedLateParse) {
Richard Smith0b3a4622014-11-13 20:01:57 +00002133 // Push this method onto the stack of late-parsed method
2134 // declarations.
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002135 auto LateMethod = new LateParsedMethodDeclaration(this, ThisDecl);
Richard Smith0b3a4622014-11-13 20:01:57 +00002136 getCurrentClass().LateParsedDeclarations.push_back(LateMethod);
2137 LateMethod->TemplateScope = getCurScope()->isTemplateParamScope();
2138
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002139 // Stash the exception-specification tokens in the late-pased method.
Richard Smith0b3a4622014-11-13 20:01:57 +00002140 LateMethod->ExceptionSpecTokens = FTI.ExceptionSpecTokens;
Hans Wennborgdcfba332015-10-06 23:40:43 +00002141 FTI.ExceptionSpecTokens = nullptr;
Richard Smith0b3a4622014-11-13 20:01:57 +00002142
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002143 // Push tokens for each parameter. Those that do not have
2144 // defaults will be NULL.
Richard Smith0b3a4622014-11-13 20:01:57 +00002145 LateMethod->DefaultArgs.reserve(FTI.NumParams);
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002146 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx)
Alp Tokerc5350722014-02-26 22:27:52 +00002147 LateMethod->DefaultArgs.push_back(LateParsedDefaultArgument(
Malcolm Parsonsca9d8342016-11-17 21:00:09 +00002148 FTI.Params[ParamIdx].Param,
2149 std::move(FTI.Params[ParamIdx].DefaultArgTokens)));
Eli Friedman3af2a772009-07-22 21:45:50 +00002150 }
2151}
2152
Richard Smith89645bc2013-01-02 12:01:23 +00002153/// isCXX11VirtSpecifier - Determine whether the given token is a C++11
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002154/// virt-specifier.
2155///
2156/// virt-specifier:
2157/// override
2158/// final
Andrey Bokhanko276055b2016-07-29 10:42:48 +00002159/// __final
Richard Smith89645bc2013-01-02 12:01:23 +00002160VirtSpecifiers::Specifier Parser::isCXX11VirtSpecifier(const Token &Tok) const {
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002161 if (!getLangOpts().CPlusPlus || Tok.isNot(tok::identifier))
Anders Carlsson4b63d0e2011-01-22 16:56:46 +00002162 return VirtSpecifiers::VS_None;
2163
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002164 IdentifierInfo *II = Tok.getIdentifierInfo();
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002165
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002166 // Initialize the contextual keywords.
2167 if (!Ident_final) {
2168 Ident_final = &PP.getIdentifierTable().get("final");
Andrey Bokhanko276055b2016-07-29 10:42:48 +00002169 if (getLangOpts().GNUKeywords)
2170 Ident_GNU_final = &PP.getIdentifierTable().get("__final");
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002171 if (getLangOpts().MicrosoftExt)
2172 Ident_sealed = &PP.getIdentifierTable().get("sealed");
2173 Ident_override = &PP.getIdentifierTable().get("override");
Anders Carlsson56104902011-01-17 03:05:47 +00002174 }
2175
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002176 if (II == Ident_override)
2177 return VirtSpecifiers::VS_Override;
2178
2179 if (II == Ident_sealed)
2180 return VirtSpecifiers::VS_Sealed;
2181
2182 if (II == Ident_final)
2183 return VirtSpecifiers::VS_Final;
2184
Andrey Bokhanko276055b2016-07-29 10:42:48 +00002185 if (II == Ident_GNU_final)
2186 return VirtSpecifiers::VS_GNU_Final;
2187
Anders Carlsson56104902011-01-17 03:05:47 +00002188 return VirtSpecifiers::VS_None;
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002189}
2190
Richard Smith89645bc2013-01-02 12:01:23 +00002191/// ParseOptionalCXX11VirtSpecifierSeq - Parse a virt-specifier-seq.
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002192///
2193/// virt-specifier-seq:
2194/// virt-specifier
2195/// virt-specifier-seq virt-specifier
Richard Smith89645bc2013-01-02 12:01:23 +00002196void Parser::ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS,
Richard Smith3d1a94c2014-08-12 00:22:39 +00002197 bool IsInterface,
2198 SourceLocation FriendLoc) {
Anders Carlsson56104902011-01-17 03:05:47 +00002199 while (true) {
Richard Smith89645bc2013-01-02 12:01:23 +00002200 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
Anders Carlsson56104902011-01-17 03:05:47 +00002201 if (Specifier == VirtSpecifiers::VS_None)
2202 return;
2203
Richard Smith3d1a94c2014-08-12 00:22:39 +00002204 if (FriendLoc.isValid()) {
2205 Diag(Tok.getLocation(), diag::err_friend_decl_spec)
2206 << VirtSpecifiers::getSpecifierName(Specifier)
2207 << FixItHint::CreateRemoval(Tok.getLocation())
2208 << SourceRange(FriendLoc, FriendLoc);
2209 ConsumeToken();
2210 continue;
2211 }
2212
Anders Carlsson56104902011-01-17 03:05:47 +00002213 // C++ [class.mem]p8:
2214 // A virt-specifier-seq shall contain at most one of each virt-specifier.
Craig Topper161e4db2014-05-21 06:02:52 +00002215 const char *PrevSpec = nullptr;
Anders Carlssonf2ca3892011-01-22 15:58:16 +00002216 if (VS.SetSpecifier(Specifier, Tok.getLocation(), PrevSpec))
Anders Carlsson56104902011-01-17 03:05:47 +00002217 Diag(Tok.getLocation(), diag::err_duplicate_virt_specifier)
2218 << PrevSpec
2219 << FixItHint::CreateRemoval(Tok.getLocation());
2220
David Majnemera5433082013-10-18 00:33:31 +00002221 if (IsInterface && (Specifier == VirtSpecifiers::VS_Final ||
2222 Specifier == VirtSpecifiers::VS_Sealed)) {
John McCalldb632ac2012-09-25 07:32:39 +00002223 Diag(Tok.getLocation(), diag::err_override_control_interface)
2224 << VirtSpecifiers::getSpecifierName(Specifier);
David Majnemera5433082013-10-18 00:33:31 +00002225 } else if (Specifier == VirtSpecifiers::VS_Sealed) {
2226 Diag(Tok.getLocation(), diag::ext_ms_sealed_keyword);
Andrey Bokhanko276055b2016-07-29 10:42:48 +00002227 } else if (Specifier == VirtSpecifiers::VS_GNU_Final) {
2228 Diag(Tok.getLocation(), diag::ext_warn_gnu_final);
John McCalldb632ac2012-09-25 07:32:39 +00002229 } else {
David Majnemera5433082013-10-18 00:33:31 +00002230 Diag(Tok.getLocation(),
2231 getLangOpts().CPlusPlus11
2232 ? diag::warn_cxx98_compat_override_control_keyword
2233 : diag::ext_override_control_keyword)
2234 << VirtSpecifiers::getSpecifierName(Specifier);
John McCalldb632ac2012-09-25 07:32:39 +00002235 }
Anders Carlsson56104902011-01-17 03:05:47 +00002236 ConsumeToken();
2237 }
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002238}
2239
Richard Smith89645bc2013-01-02 12:01:23 +00002240/// isCXX11FinalKeyword - Determine whether the next token is a C++11
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002241/// 'final' or Microsoft 'sealed' contextual keyword.
Richard Smith89645bc2013-01-02 12:01:23 +00002242bool Parser::isCXX11FinalKeyword() const {
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002243 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
2244 return Specifier == VirtSpecifiers::VS_Final ||
Andrey Bokhanko276055b2016-07-29 10:42:48 +00002245 Specifier == VirtSpecifiers::VS_GNU_Final ||
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002246 Specifier == VirtSpecifiers::VS_Sealed;
Anders Carlsson4b63d0e2011-01-22 16:56:46 +00002247}
2248
Richard Smith72553fc2014-01-23 23:53:27 +00002249/// \brief Parse a C++ member-declarator up to, but not including, the optional
2250/// brace-or-equal-initializer or pure-specifier.
Nico Weberd89e6f72015-01-16 19:34:13 +00002251bool Parser::ParseCXXMemberDeclaratorBeforeInitializer(
Richard Smith72553fc2014-01-23 23:53:27 +00002252 Declarator &DeclaratorInfo, VirtSpecifiers &VS, ExprResult &BitfieldSize,
2253 LateParsedAttrList &LateParsedAttrs) {
2254 // member-declarator:
2255 // declarator pure-specifier[opt]
2256 // declarator brace-or-equal-initializer[opt]
2257 // identifier[opt] ':' constant-expression
Serge Pavlov458ea762014-07-16 05:16:52 +00002258 if (Tok.isNot(tok::colon))
Richard Smith72553fc2014-01-23 23:53:27 +00002259 ParseDeclarator(DeclaratorInfo);
Richard Smith3d1a94c2014-08-12 00:22:39 +00002260 else
2261 DeclaratorInfo.SetIdentifier(nullptr, Tok.getLocation());
Richard Smith72553fc2014-01-23 23:53:27 +00002262
2263 if (!DeclaratorInfo.isFunctionDeclarator() && TryConsumeToken(tok::colon)) {
Richard Smith3d1a94c2014-08-12 00:22:39 +00002264 assert(DeclaratorInfo.isPastIdentifier() &&
2265 "don't know where identifier would go yet?");
Richard Smith72553fc2014-01-23 23:53:27 +00002266 BitfieldSize = ParseConstantExpression();
2267 if (BitfieldSize.isInvalid())
2268 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002269 } else {
Richard Smith3d1a94c2014-08-12 00:22:39 +00002270 ParseOptionalCXX11VirtSpecifierSeq(
2271 VS, getCurrentClass().IsInterface,
2272 DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002273 if (!VS.isUnset())
2274 MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo, VS);
2275 }
Richard Smith72553fc2014-01-23 23:53:27 +00002276
2277 // If a simple-asm-expr is present, parse it.
2278 if (Tok.is(tok::kw_asm)) {
2279 SourceLocation Loc;
2280 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
2281 if (AsmLabel.isInvalid())
2282 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2283
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002284 DeclaratorInfo.setAsmLabel(AsmLabel.get());
Richard Smith72553fc2014-01-23 23:53:27 +00002285 DeclaratorInfo.SetRangeEnd(Loc);
2286 }
2287
2288 // If attributes exist after the declarator, but before an '{', parse them.
2289 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
Richard Smith4b5a9492014-01-24 22:34:35 +00002290
2291 // For compatibility with code written to older Clang, also accept a
2292 // virt-specifier *after* the GNU attributes.
Aaron Ballman5d153e32014-08-04 17:03:51 +00002293 if (BitfieldSize.isUnset() && VS.isUnset()) {
Richard Smith3d1a94c2014-08-12 00:22:39 +00002294 ParseOptionalCXX11VirtSpecifierSeq(
2295 VS, getCurrentClass().IsInterface,
2296 DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
Aaron Ballman5d153e32014-08-04 17:03:51 +00002297 if (!VS.isUnset()) {
2298 // If we saw any GNU-style attributes that are known to GCC followed by a
2299 // virt-specifier, issue a GCC-compat warning.
2300 const AttributeList *Attr = DeclaratorInfo.getAttributes();
2301 while (Attr) {
2302 if (Attr->isKnownToGCC() && !Attr->isCXX11Attribute())
2303 Diag(Attr->getLoc(), diag::warn_gcc_attribute_location);
2304 Attr = Attr->getNext();
2305 }
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002306 MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo, VS);
Aaron Ballman5d153e32014-08-04 17:03:51 +00002307 }
2308 }
Nico Weberd89e6f72015-01-16 19:34:13 +00002309
2310 // If this has neither a name nor a bit width, something has gone seriously
2311 // wrong. Skip until the semi-colon or }.
2312 if (!DeclaratorInfo.hasName() && BitfieldSize.isUnset()) {
2313 // If so, skip until the semi-colon or a }.
2314 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2315 return true;
2316 }
2317 return false;
Richard Smith72553fc2014-01-23 23:53:27 +00002318}
2319
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002320/// \brief Look for declaration specifiers possibly occurring after C++11
2321/// virt-specifier-seq and diagnose them.
2322void Parser::MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(
2323 Declarator &D,
2324 VirtSpecifiers &VS) {
2325 DeclSpec DS(AttrFactory);
2326
2327 // GNU-style and C++11 attributes are not allowed here, but they will be
2328 // handled by the caller. Diagnose everything else.
Alex Lorenz8f4d3992017-02-13 23:19:40 +00002329 ParseTypeQualifierListOpt(
2330 DS, AR_NoAttributesParsed, false,
2331 /*IdentifierRequired=*/false, llvm::function_ref<void()>([&]() {
2332 Actions.CodeCompleteFunctionQualifiers(DS, D, &VS);
2333 }));
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002334 D.ExtendWithDeclSpec(DS);
2335
2336 if (D.isFunctionDeclarator()) {
Ehsan Akhgaric07d1e22015-03-25 00:53:33 +00002337 auto &Function = D.getFunctionTypeInfo();
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002338 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
2339 auto DeclSpecCheck = [&] (DeclSpec::TQ TypeQual,
2340 const char *FixItName,
2341 SourceLocation SpecLoc,
2342 unsigned* QualifierLoc) {
2343 FixItHint Insertion;
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002344 if (DS.getTypeQualifiers() & TypeQual) {
2345 if (!(Function.TypeQuals & TypeQual)) {
2346 std::string Name(FixItName);
2347 Name += " ";
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00002348 Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), Name);
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002349 Function.TypeQuals |= TypeQual;
2350 *QualifierLoc = SpecLoc.getRawEncoding();
2351 }
2352 Diag(SpecLoc, diag::err_declspec_after_virtspec)
2353 << FixItName
2354 << VirtSpecifiers::getSpecifierName(VS.getLastSpecifier())
2355 << FixItHint::CreateRemoval(SpecLoc)
2356 << Insertion;
2357 }
2358 };
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002359 DeclSpecCheck(DeclSpec::TQ_const, "const", DS.getConstSpecLoc(),
2360 &Function.ConstQualifierLoc);
2361 DeclSpecCheck(DeclSpec::TQ_volatile, "volatile", DS.getVolatileSpecLoc(),
2362 &Function.VolatileQualifierLoc);
2363 DeclSpecCheck(DeclSpec::TQ_restrict, "restrict", DS.getRestrictSpecLoc(),
2364 &Function.RestrictQualifierLoc);
2365 }
Ehsan Akhgaric07d1e22015-03-25 00:53:33 +00002366
2367 // Parse ref-qualifiers.
2368 bool RefQualifierIsLValueRef = true;
2369 SourceLocation RefQualifierLoc;
2370 if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc)) {
2371 const char *Name = (RefQualifierIsLValueRef ? "& " : "&& ");
2372 FixItHint Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), Name);
2373 Function.RefQualifierIsLValueRef = RefQualifierIsLValueRef;
2374 Function.RefQualifierLoc = RefQualifierLoc.getRawEncoding();
2375
2376 Diag(RefQualifierLoc, diag::err_declspec_after_virtspec)
2377 << (RefQualifierIsLValueRef ? "&" : "&&")
2378 << VirtSpecifiers::getSpecifierName(VS.getLastSpecifier())
2379 << FixItHint::CreateRemoval(RefQualifierLoc)
2380 << Insertion;
2381 D.SetRangeEnd(RefQualifierLoc);
2382 }
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002383 }
2384}
2385
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002386/// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration.
2387///
2388/// member-declaration:
2389/// decl-specifier-seq[opt] member-declarator-list[opt] ';'
2390/// function-definition ';'[opt]
2391/// ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO]
2392/// using-declaration [TODO]
Anders Carlssonf24fcff62009-03-11 16:27:10 +00002393/// [C++0x] static_assert-declaration
Anders Carlssondfbbdf62009-03-26 00:52:18 +00002394/// template-declaration
Chris Lattnerd19c1c02008-12-18 01:12:00 +00002395/// [GNU] '__extension__' member-declaration
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002396///
2397/// member-declarator-list:
2398/// member-declarator
2399/// member-declarator-list ',' member-declarator
2400///
2401/// member-declarator:
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002402/// declarator virt-specifier-seq[opt] pure-specifier[opt]
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002403/// declarator constant-initializer[opt]
Richard Smith938f40b2011-06-11 17:19:42 +00002404/// [C++11] declarator brace-or-equal-initializer[opt]
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002405/// identifier[opt] ':' constant-expression
2406///
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002407/// virt-specifier-seq:
2408/// virt-specifier
2409/// virt-specifier-seq virt-specifier
2410///
2411/// virt-specifier:
2412/// override
2413/// final
David Majnemera5433082013-10-18 00:33:31 +00002414/// [MS] sealed
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002415///
Sebastian Redl42e92c42009-04-12 17:16:29 +00002416/// pure-specifier:
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002417/// '= 0'
2418///
2419/// constant-initializer:
2420/// '=' constant-expression
2421///
Alexey Bataev05c25d62015-07-31 08:42:25 +00002422Parser::DeclGroupPtrTy
2423Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS,
2424 AttributeList *AccessAttrs,
John McCall796c2a52010-07-16 08:13:16 +00002425 const ParsedTemplateInfo &TemplateInfo,
2426 ParsingDeclRAIIObject *TemplateDiags) {
Douglas Gregor23c84762011-04-14 17:21:19 +00002427 if (Tok.is(tok::at)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002428 if (getLangOpts().ObjC1 && NextToken().isObjCAtKeyword(tok::objc_defs))
Douglas Gregor23c84762011-04-14 17:21:19 +00002429 Diag(Tok, diag::err_at_defs_cxx);
2430 else
2431 Diag(Tok, diag::err_at_in_class);
Richard Smithda35e962013-11-09 04:52:51 +00002432
Douglas Gregor23c84762011-04-14 17:21:19 +00002433 ConsumeToken();
Alexey Bataevee6507d2013-11-18 08:17:37 +00002434 SkipUntil(tok::r_brace, StopAtSemi);
David Blaikie0403cb12016-01-15 23:43:25 +00002435 return nullptr;
Douglas Gregor23c84762011-04-14 17:21:19 +00002436 }
Richard Smithda35e962013-11-09 04:52:51 +00002437
Serge Pavlov458ea762014-07-16 05:16:52 +00002438 // Turn on colon protection early, while parsing declspec, although there is
2439 // nothing to protect there. It prevents from false errors if error recovery
2440 // incorrectly determines where the declspec ends, as in the example:
2441 // struct A { enum class B { C }; };
2442 // const int C = 4;
2443 // struct D { A::B : C; };
2444 ColonProtectionRAIIObject X(*this);
2445
John McCalla0097262009-12-11 02:10:03 +00002446 // Access declarations.
Richard Smith45855df2012-05-09 08:23:23 +00002447 bool MalformedTypeSpec = false;
John McCalla0097262009-12-11 02:10:03 +00002448 if (!TemplateInfo.Kind &&
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002449 Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw___super)) {
Richard Smith45855df2012-05-09 08:23:23 +00002450 if (TryAnnotateCXXScopeToken())
2451 MalformedTypeSpec = true;
2452
2453 bool isAccessDecl;
2454 if (Tok.isNot(tok::annot_cxxscope))
2455 isAccessDecl = false;
2456 else if (NextToken().is(tok::identifier))
John McCalla0097262009-12-11 02:10:03 +00002457 isAccessDecl = GetLookAheadToken(2).is(tok::semi);
2458 else
2459 isAccessDecl = NextToken().is(tok::kw_operator);
2460
2461 if (isAccessDecl) {
2462 // Collect the scope specifier token we annotated earlier.
2463 CXXScopeSpec SS;
David Blaikieefdccaa2016-01-15 23:43:34 +00002464 ParseOptionalCXXScopeSpecifier(SS, nullptr,
Douglas Gregordf593fb2011-11-07 17:33:42 +00002465 /*EnteringContext=*/false);
John McCalla0097262009-12-11 02:10:03 +00002466
Nico Weberef03e702014-09-10 00:59:37 +00002467 if (SS.isInvalid()) {
2468 SkipUntil(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002469 return nullptr;
Nico Weberef03e702014-09-10 00:59:37 +00002470 }
2471
John McCalla0097262009-12-11 02:10:03 +00002472 // Try to parse an unqualified-id.
Abramo Bagnara7945c982012-01-27 09:46:47 +00002473 SourceLocation TemplateKWLoc;
John McCalla0097262009-12-11 02:10:03 +00002474 UnqualifiedId Name;
Richard Smith35845152017-02-07 01:37:30 +00002475 if (ParseUnqualifiedId(SS, false, true, true, false, nullptr,
2476 TemplateKWLoc, Name)) {
John McCalla0097262009-12-11 02:10:03 +00002477 SkipUntil(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002478 return nullptr;
John McCalla0097262009-12-11 02:10:03 +00002479 }
2480
2481 // TODO: recover from mistakenly-qualified operator declarations.
Alp Toker383d2c42014-01-01 03:08:43 +00002482 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
2483 "access declaration")) {
2484 SkipUntil(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002485 return nullptr;
Alp Toker383d2c42014-01-01 03:08:43 +00002486 }
John McCalla0097262009-12-11 02:10:03 +00002487
Alexey Bataev05c25d62015-07-31 08:42:25 +00002488 return DeclGroupPtrTy::make(DeclGroupRef(Actions.ActOnUsingDeclaration(
Richard Smith151c4562016-12-20 21:35:28 +00002489 getCurScope(), AS, /*UsingLoc*/ SourceLocation(),
2490 /*TypenameLoc*/ SourceLocation(), SS, Name,
2491 /*EllipsisLoc*/ SourceLocation(), /*AttrList*/ nullptr)));
John McCalla0097262009-12-11 02:10:03 +00002492 }
2493 }
2494
Aaron Ballmane7c544d2014-08-04 20:28:35 +00002495 // static_assert-declaration. A templated static_assert declaration is
2496 // diagnosed in Parser::ParseSingleDeclarationAfterTemplate.
2497 if (!TemplateInfo.Kind &&
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002498 Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert)) {
Chris Lattner49836b42009-04-02 04:16:50 +00002499 SourceLocation DeclEnd;
Alexey Bataev05c25d62015-07-31 08:42:25 +00002500 return DeclGroupPtrTy::make(
2501 DeclGroupRef(ParseStaticAssertDeclaration(DeclEnd)));
Chris Lattner5bbb3c82009-03-29 16:50:03 +00002502 }
Mike Stump11289f42009-09-09 15:08:12 +00002503
Chris Lattner5bbb3c82009-03-29 16:50:03 +00002504 if (Tok.is(tok::kw_template)) {
Mike Stump11289f42009-09-09 15:08:12 +00002505 assert(!TemplateInfo.TemplateParams &&
Douglas Gregor3447e762009-08-20 22:52:58 +00002506 "Nested template improperly parsed?");
Richard Smith3af70092017-02-09 22:14:25 +00002507 ObjCDeclContextSwitch ObjCDC(*this);
Chris Lattner49836b42009-04-02 04:16:50 +00002508 SourceLocation DeclEnd;
Alexey Bataev05c25d62015-07-31 08:42:25 +00002509 return DeclGroupPtrTy::make(
Richard Smith3af70092017-02-09 22:14:25 +00002510 DeclGroupRef(ParseTemplateDeclarationOrSpecialization(
Alexey Bataev05c25d62015-07-31 08:42:25 +00002511 Declarator::MemberContext, DeclEnd, AS, AccessAttrs)));
Chris Lattner5bbb3c82009-03-29 16:50:03 +00002512 }
Anders Carlssondfbbdf62009-03-26 00:52:18 +00002513
Chris Lattnerd19c1c02008-12-18 01:12:00 +00002514 // Handle: member-declaration ::= '__extension__' member-declaration
2515 if (Tok.is(tok::kw___extension__)) {
2516 // __extension__ silences extension warnings in the subexpression.
2517 ExtensionRAIIObject O(Diags); // Use RAII to do this.
2518 ConsumeToken();
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00002519 return ParseCXXClassMemberDeclaration(AS, AccessAttrs,
2520 TemplateInfo, TemplateDiags);
Chris Lattnerd19c1c02008-12-18 01:12:00 +00002521 }
Douglas Gregorfec52632009-06-20 00:51:54 +00002522
John McCall084e83d2011-03-24 11:26:52 +00002523 ParsedAttributesWithRange attrs(AttrFactory);
Michael Handdc016d2012-11-28 23:17:40 +00002524 ParsedAttributesWithRange FnAttrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00002525 // Optional C++11 attribute-specifier
2526 MaybeParseCXX11Attributes(attrs);
Michael Handdc016d2012-11-28 23:17:40 +00002527 // We need to keep these attributes for future diagnostic
2528 // before they are taken over by declaration specifier.
2529 FnAttrs.addAll(attrs.getList());
2530 FnAttrs.Range = attrs.Range;
2531
John McCall53fa7142010-12-24 02:08:15 +00002532 MaybeParseMicrosoftAttributes(attrs);
Alexis Hunt96d5c762009-11-21 08:43:09 +00002533
Douglas Gregorfec52632009-06-20 00:51:54 +00002534 if (Tok.is(tok::kw_using)) {
John McCall53fa7142010-12-24 02:08:15 +00002535 ProhibitAttributes(attrs);
Mike Stump11289f42009-09-09 15:08:12 +00002536
Douglas Gregorfec52632009-06-20 00:51:54 +00002537 // Eat 'using'.
2538 SourceLocation UsingLoc = ConsumeToken();
2539
2540 if (Tok.is(tok::kw_namespace)) {
2541 Diag(UsingLoc, diag::err_using_namespace_in_class);
Alexey Bataevee6507d2013-11-18 08:17:37 +00002542 SkipUntil(tok::semi, StopBeforeMatch);
David Blaikie0403cb12016-01-15 23:43:25 +00002543 return nullptr;
Douglas Gregorfec52632009-06-20 00:51:54 +00002544 }
Alexey Bataev05c25d62015-07-31 08:42:25 +00002545 SourceLocation DeclEnd;
2546 // Otherwise, it must be a using-declaration or an alias-declaration.
Richard Smith6f1daa42016-12-16 00:58:48 +00002547 return ParseUsingDeclaration(Declarator::MemberContext, TemplateInfo,
2548 UsingLoc, DeclEnd, AS);
Douglas Gregorfec52632009-06-20 00:51:54 +00002549 }
2550
DeLesley Hutchinsbd2ee132012-03-02 22:12:59 +00002551 // Hold late-parsed attributes so we can attach a Decl to them later.
2552 LateParsedAttrList CommonLateParsedAttrs;
2553
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002554 // decl-specifier-seq:
2555 // Parse the common declaration-specifiers piece.
John McCall796c2a52010-07-16 08:13:16 +00002556 ParsingDeclSpec DS(*this, TemplateDiags);
John McCall53fa7142010-12-24 02:08:15 +00002557 DS.takeAttributesFrom(attrs);
Richard Smith45855df2012-05-09 08:23:23 +00002558 if (MalformedTypeSpec)
2559 DS.SetTypeSpecError();
Richard Smith72553fc2014-01-23 23:53:27 +00002560
Serge Pavlov458ea762014-07-16 05:16:52 +00002561 ParseDeclarationSpecifiers(DS, TemplateInfo, AS, DSC_class,
2562 &CommonLateParsedAttrs);
2563
2564 // Turn off colon protection that was set for declspec.
2565 X.restore();
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002566
Richard Smith404dfb42013-11-19 22:47:36 +00002567 // If we had a free-standing type definition with a missing semicolon, we
2568 // may get this far before the problem becomes obvious.
2569 if (DS.hasTagDefinition() &&
2570 TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate &&
2571 DiagnoseMissingSemiAfterTagDefinition(DS, AS, DSC_class,
2572 &CommonLateParsedAttrs))
David Blaikie0403cb12016-01-15 23:43:25 +00002573 return nullptr;
Richard Smith404dfb42013-11-19 22:47:36 +00002574
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002575 MultiTemplateParamsArg TemplateParams(
Craig Topper161e4db2014-05-21 06:02:52 +00002576 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->data()
2577 : nullptr,
John McCall11083da2009-09-16 22:47:08 +00002578 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->size() : 0);
2579
Alp Toker35d87032013-12-30 23:29:50 +00002580 if (TryConsumeToken(tok::semi)) {
Michael Handdc016d2012-11-28 23:17:40 +00002581 if (DS.isFriendSpecified())
2582 ProhibitAttributes(FnAttrs);
2583
Nico Weber7b837f52016-01-28 19:25:00 +00002584 RecordDecl *AnonRecord = nullptr;
2585 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(
2586 getCurScope(), AS, DS, TemplateParams, false, AnonRecord);
John McCall796c2a52010-07-16 08:13:16 +00002587 DS.complete(TheDecl);
Nico Weber7b837f52016-01-28 19:25:00 +00002588 if (AnonRecord) {
2589 Decl* decls[] = {AnonRecord, TheDecl};
Richard Smith3beb7c62017-01-12 02:27:38 +00002590 return Actions.BuildDeclaratorGroup(decls);
Nico Weber7b837f52016-01-28 19:25:00 +00002591 }
2592 return Actions.ConvertDeclToDeclGroup(TheDecl);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002593 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002594
John McCall28a6aea2009-11-04 02:18:39 +00002595 ParsingDeclarator DeclaratorInfo(*this, DS, Declarator::MemberContext);
Nico Weber24b2a822011-01-28 06:07:34 +00002596 VirtSpecifiers VS;
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002597
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002598 // Hold late-parsed attributes so we can attach a Decl to them later.
2599 LateParsedAttrList LateParsedAttrs;
2600
Douglas Gregor50cefbf2011-10-17 17:09:53 +00002601 SourceLocation EqualLoc;
Richard Smith9ba0fec2015-06-30 01:28:56 +00002602 SourceLocation PureSpecLoc;
2603
Yaron Keren180c1672015-06-30 07:35:19 +00002604 auto TryConsumePureSpecifier = [&] (bool AllowDefinition) {
Richard Smith9ba0fec2015-06-30 01:28:56 +00002605 if (Tok.isNot(tok::equal))
2606 return false;
2607
2608 auto &Zero = NextToken();
2609 SmallString<8> Buffer;
2610 if (Zero.isNot(tok::numeric_constant) || Zero.getLength() != 1 ||
2611 PP.getSpelling(Zero, Buffer) != "0")
2612 return false;
2613
2614 auto &After = GetLookAheadToken(2);
2615 if (!After.isOneOf(tok::semi, tok::comma) &&
2616 !(AllowDefinition &&
2617 After.isOneOf(tok::l_brace, tok::colon, tok::kw_try)))
2618 return false;
2619
2620 EqualLoc = ConsumeToken();
2621 PureSpecLoc = ConsumeToken();
2622 return true;
2623 };
Chris Lattner17c3b1f2009-12-10 01:59:24 +00002624
Richard Smith72553fc2014-01-23 23:53:27 +00002625 SmallVector<Decl *, 8> DeclsInGroup;
2626 ExprResult BitfieldSize;
2627 bool ExpectSemi = true;
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002628
Richard Smith72553fc2014-01-23 23:53:27 +00002629 // Parse the first declarator.
Nico Weberd89e6f72015-01-16 19:34:13 +00002630 if (ParseCXXMemberDeclaratorBeforeInitializer(
2631 DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs)) {
Richard Smith72553fc2014-01-23 23:53:27 +00002632 TryConsumeToken(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002633 return nullptr;
Richard Smith72553fc2014-01-23 23:53:27 +00002634 }
John Thompson5bc5cbe2009-11-25 22:58:06 +00002635
Richard Smith72553fc2014-01-23 23:53:27 +00002636 // Check for a member function definition.
Richard Smith4b5a9492014-01-24 22:34:35 +00002637 if (BitfieldSize.isUnset()) {
Richard Smith72553fc2014-01-23 23:53:27 +00002638 // MSVC permits pure specifier on inline functions defined at class scope.
Francois Pichet3abc9b82011-05-11 02:14:46 +00002639 // Hence check for =0 before checking for function definition.
Richard Smith9ba0fec2015-06-30 01:28:56 +00002640 if (getLangOpts().MicrosoftExt && DeclaratorInfo.isDeclarationOfFunction())
2641 TryConsumePureSpecifier(/*AllowDefinition*/ true);
Francois Pichet3abc9b82011-05-11 02:14:46 +00002642
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00002643 FunctionDefinitionKind DefinitionKind = FDK_Declaration;
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002644 // function-definition:
Richard Smith938f40b2011-06-11 17:19:42 +00002645 //
2646 // In C++11, a non-function declarator followed by an open brace is a
2647 // braced-init-list for an in-class member initialization, not an
2648 // erroneous function definition.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002649 if (Tok.is(tok::l_brace) && !getLangOpts().CPlusPlus11) {
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00002650 DefinitionKind = FDK_Definition;
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002651 } else if (DeclaratorInfo.isFunctionDeclarator()) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002652 if (Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try)) {
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00002653 DefinitionKind = FDK_Definition;
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002654 } else if (Tok.is(tok::equal)) {
2655 const Token &KW = NextToken();
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00002656 if (KW.is(tok::kw_default))
2657 DefinitionKind = FDK_Defaulted;
2658 else if (KW.is(tok::kw_delete))
2659 DefinitionKind = FDK_Deleted;
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002660 }
2661 }
Eli Bendersky41842222015-03-23 23:49:41 +00002662 DeclaratorInfo.setFunctionDefinitionKind(DefinitionKind);
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002663
Michael Handdc016d2012-11-28 23:17:40 +00002664 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
2665 // to a friend declaration, that declaration shall be a definition.
2666 if (DeclaratorInfo.isFunctionDeclarator() &&
2667 DefinitionKind != FDK_Definition && DS.isFriendSpecified()) {
2668 // Diagnose attributes that appear before decl specifier:
2669 // [[]] friend int foo();
2670 ProhibitAttributes(FnAttrs);
2671 }
2672
Nico Webera7f137d2015-01-16 19:35:01 +00002673 if (DefinitionKind != FDK_Declaration) {
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002674 if (!DeclaratorInfo.isFunctionDeclarator()) {
Richard Trieu0d730542012-01-21 02:59:18 +00002675 Diag(DeclaratorInfo.getIdentifierLoc(), diag::err_func_def_no_params);
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002676 ConsumeBrace();
Alexey Bataevee6507d2013-11-18 08:17:37 +00002677 SkipUntil(tok::r_brace);
Michael Handdc016d2012-11-28 23:17:40 +00002678
Douglas Gregor8a4db832011-01-19 16:41:58 +00002679 // Consume the optional ';'
Alp Toker35d87032013-12-30 23:29:50 +00002680 TryConsumeToken(tok::semi);
2681
David Blaikie0403cb12016-01-15 23:43:25 +00002682 return nullptr;
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002683 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002684
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002685 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
Richard Trieu0d730542012-01-21 02:59:18 +00002686 Diag(DeclaratorInfo.getIdentifierLoc(),
2687 diag::err_function_declared_typedef);
Douglas Gregor8a4db832011-01-19 16:41:58 +00002688
Richard Smith2603b092012-11-15 22:54:20 +00002689 // Recover by treating the 'typedef' as spurious.
2690 DS.ClearStorageClassSpecs();
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002691 }
2692
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002693 Decl *FunDecl =
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00002694 ParseCXXInlineMethodDef(AS, AccessAttrs, DeclaratorInfo, TemplateInfo,
Richard Smith9ba0fec2015-06-30 01:28:56 +00002695 VS, PureSpecLoc);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002696
David Majnemer23252a32013-08-01 04:22:55 +00002697 if (FunDecl) {
2698 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i) {
2699 CommonLateParsedAttrs[i]->addDecl(FunDecl);
2700 }
2701 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i) {
2702 LateParsedAttrs[i]->addDecl(FunDecl);
2703 }
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002704 }
2705 LateParsedAttrs.clear();
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002706
2707 // Consume the ';' - it's optional unless we have a delete or default
Richard Trieu2f7dc462012-05-16 19:04:59 +00002708 if (Tok.is(tok::semi))
Richard Smith87f5dc52012-07-23 05:45:25 +00002709 ConsumeExtraSemi(AfterMemberFunctionDefinition);
Douglas Gregor8a4db832011-01-19 16:41:58 +00002710
Alexey Bataev05c25d62015-07-31 08:42:25 +00002711 return DeclGroupPtrTy::make(DeclGroupRef(FunDecl));
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002712 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002713 }
2714
2715 // member-declarator-list:
2716 // member-declarator
2717 // member-declarator-list ',' member-declarator
2718
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002719 while (1) {
Richard Smith2b013182012-06-10 03:12:00 +00002720 InClassInitStyle HasInClassInit = ICIS_NoInit;
Richard Smith9ba0fec2015-06-30 01:28:56 +00002721 bool HasStaticInitializer = false;
2722 if (Tok.isOneOf(tok::equal, tok::l_brace) && PureSpecLoc.isInvalid()) {
Richard Smith938f40b2011-06-11 17:19:42 +00002723 if (BitfieldSize.get()) {
2724 Diag(Tok, diag::err_bitfield_member_init);
Alexey Bataevee6507d2013-11-18 08:17:37 +00002725 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
Richard Smith9ba0fec2015-06-30 01:28:56 +00002726 } else if (DeclaratorInfo.isDeclarationOfFunction()) {
2727 // It's a pure-specifier.
2728 if (!TryConsumePureSpecifier(/*AllowFunctionDefinition*/ false))
2729 // Parse it as an expression so that Sema can diagnose it.
2730 HasStaticInitializer = true;
2731 } else if (DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2732 DeclSpec::SCS_static &&
2733 DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2734 DeclSpec::SCS_typedef &&
2735 !DS.isFriendSpecified()) {
2736 // It's a default member initializer.
2737 HasInClassInit = Tok.is(tok::equal) ? ICIS_CopyInit : ICIS_ListInit;
Richard Smith938f40b2011-06-11 17:19:42 +00002738 } else {
Richard Smith9ba0fec2015-06-30 01:28:56 +00002739 HasStaticInitializer = true;
Richard Smith938f40b2011-06-11 17:19:42 +00002740 }
2741 }
2742
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002743 // NOTE: If Sema is the Action module and declarator is an instance field,
Chris Lattner5bbb3c82009-03-29 16:50:03 +00002744 // this call will *not* return the created decl; It will return null.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002745 // See Sema::ActOnCXXMemberDeclarator for details.
John McCall07e91c02009-08-06 02:15:43 +00002746
Craig Topper161e4db2014-05-21 06:02:52 +00002747 NamedDecl *ThisDecl = nullptr;
John McCall07e91c02009-08-06 02:15:43 +00002748 if (DS.isFriendSpecified()) {
Richard Smith72553fc2014-01-23 23:53:27 +00002749 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
Michael Handdc016d2012-11-28 23:17:40 +00002750 // to a friend declaration, that declaration shall be a definition.
2751 //
Richard Smith72553fc2014-01-23 23:53:27 +00002752 // Diagnose attributes that appear in a friend member function declarator:
2753 // friend int foo [[]] ();
Michael Handdc016d2012-11-28 23:17:40 +00002754 SmallVector<SourceRange, 4> Ranges;
2755 DeclaratorInfo.getCXX11AttributeRanges(Ranges);
Richard Smith72553fc2014-01-23 23:53:27 +00002756 for (SmallVectorImpl<SourceRange>::iterator I = Ranges.begin(),
2757 E = Ranges.end(); I != E; ++I)
2758 Diag((*I).getBegin(), diag::err_attributes_not_allowed) << *I;
Michael Handdc016d2012-11-28 23:17:40 +00002759
Douglas Gregor0be31a22010-07-02 17:43:08 +00002760 ThisDecl = Actions.ActOnFriendFunctionDecl(getCurScope(), DeclaratorInfo,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002761 TemplateParams);
Douglas Gregor3447e762009-08-20 22:52:58 +00002762 } else {
Douglas Gregor0be31a22010-07-02 17:43:08 +00002763 ThisDecl = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS,
John McCall07e91c02009-08-06 02:15:43 +00002764 DeclaratorInfo,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002765 TemplateParams,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002766 BitfieldSize.get(),
Richard Smith2b013182012-06-10 03:12:00 +00002767 VS, HasInClassInit);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002768
2769 if (VarTemplateDecl *VT =
Craig Topper161e4db2014-05-21 06:02:52 +00002770 ThisDecl ? dyn_cast<VarTemplateDecl>(ThisDecl) : nullptr)
Larisse Voufo39a1e502013-08-06 01:03:05 +00002771 // Re-direct this decl to refer to the templated decl so that we can
2772 // initialize it.
2773 ThisDecl = VT->getTemplatedDecl();
2774
David Majnemer23252a32013-08-01 04:22:55 +00002775 if (ThisDecl && AccessAttrs)
Richard Smithf8a75c32013-08-29 00:47:48 +00002776 Actions.ProcessDeclAttributeList(getCurScope(), ThisDecl, AccessAttrs);
Douglas Gregor3447e762009-08-20 22:52:58 +00002777 }
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002778
Richard Smith9ba0fec2015-06-30 01:28:56 +00002779 // Error recovery might have converted a non-static member into a static
2780 // member.
David Blaikie35506f82013-01-30 01:22:18 +00002781 if (HasInClassInit != ICIS_NoInit &&
Richard Smith9ba0fec2015-06-30 01:28:56 +00002782 DeclaratorInfo.getDeclSpec().getStorageClassSpec() ==
2783 DeclSpec::SCS_static) {
2784 HasInClassInit = ICIS_NoInit;
2785 HasStaticInitializer = true;
2786 }
2787
2788 if (ThisDecl && PureSpecLoc.isValid())
2789 Actions.ActOnPureSpecifier(ThisDecl, PureSpecLoc);
2790
2791 // Handle the initializer.
2792 if (HasInClassInit != ICIS_NoInit) {
Douglas Gregor728d00b2011-10-10 14:49:18 +00002793 // The initializer was deferred; parse it and cache the tokens.
David Majnemer23252a32013-08-01 04:22:55 +00002794 Diag(Tok, getLangOpts().CPlusPlus11
2795 ? diag::warn_cxx98_compat_nonstatic_member_init
2796 : diag::ext_nonstatic_member_init);
Richard Smith5d164bc2011-10-15 05:09:34 +00002797
Richard Smith938f40b2011-06-11 17:19:42 +00002798 if (DeclaratorInfo.isArrayOfUnknownBound()) {
Richard Smith2b013182012-06-10 03:12:00 +00002799 // C++11 [dcl.array]p3: An array bound may also be omitted when the
2800 // declarator is followed by an initializer.
Richard Smith938f40b2011-06-11 17:19:42 +00002801 //
2802 // A brace-or-equal-initializer for a member-declarator is not an
David Blaikiecdd91db2012-02-14 09:00:46 +00002803 // initializer in the grammar, so this is ill-formed.
Richard Smith938f40b2011-06-11 17:19:42 +00002804 Diag(Tok, diag::err_incomplete_array_member_init);
Alexey Bataevee6507d2013-11-18 08:17:37 +00002805 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
David Majnemer23252a32013-08-01 04:22:55 +00002806
2807 // Avoid later warnings about a class member of incomplete type.
David Blaikiecdd91db2012-02-14 09:00:46 +00002808 if (ThisDecl)
David Blaikiecdd91db2012-02-14 09:00:46 +00002809 ThisDecl->setInvalidDecl();
Richard Smith938f40b2011-06-11 17:19:42 +00002810 } else
2811 ParseCXXNonStaticMemberInitializer(ThisDecl);
Richard Smith9ba0fec2015-06-30 01:28:56 +00002812 } else if (HasStaticInitializer) {
Douglas Gregor728d00b2011-10-10 14:49:18 +00002813 // Normal initializer.
Richard Smith9ba0fec2015-06-30 01:28:56 +00002814 ExprResult Init = ParseCXXMemberInitializer(
2815 ThisDecl, DeclaratorInfo.isDeclarationOfFunction(), EqualLoc);
David Majnemer23252a32013-08-01 04:22:55 +00002816
Douglas Gregor728d00b2011-10-10 14:49:18 +00002817 if (Init.isInvalid())
Alexey Bataevee6507d2013-11-18 08:17:37 +00002818 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
Douglas Gregor728d00b2011-10-10 14:49:18 +00002819 else if (ThisDecl)
Richard Smith3beb7c62017-01-12 02:27:38 +00002820 Actions.AddInitializerToDecl(ThisDecl, Init.get(), EqualLoc.isInvalid());
David Majnemer23252a32013-08-01 04:22:55 +00002821 } else if (ThisDecl && DS.getStorageClassSpec() == DeclSpec::SCS_static)
Douglas Gregor728d00b2011-10-10 14:49:18 +00002822 // No initializer.
Richard Smith3beb7c62017-01-12 02:27:38 +00002823 Actions.ActOnUninitializedDecl(ThisDecl);
David Majnemer23252a32013-08-01 04:22:55 +00002824
Douglas Gregor728d00b2011-10-10 14:49:18 +00002825 if (ThisDecl) {
David Majnemer23252a32013-08-01 04:22:55 +00002826 if (!ThisDecl->isInvalidDecl()) {
2827 // Set the Decl for any late parsed attributes
2828 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i)
2829 CommonLateParsedAttrs[i]->addDecl(ThisDecl);
2830
2831 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i)
2832 LateParsedAttrs[i]->addDecl(ThisDecl);
2833 }
Douglas Gregor728d00b2011-10-10 14:49:18 +00002834 Actions.FinalizeDeclaration(ThisDecl);
2835 DeclsInGroup.push_back(ThisDecl);
David Majnemer23252a32013-08-01 04:22:55 +00002836
2837 if (DeclaratorInfo.isFunctionDeclarator() &&
2838 DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2839 DeclSpec::SCS_typedef)
2840 HandleMemberFunctionDeclDelays(DeclaratorInfo, ThisDecl);
Douglas Gregor728d00b2011-10-10 14:49:18 +00002841 }
David Majnemer23252a32013-08-01 04:22:55 +00002842 LateParsedAttrs.clear();
Douglas Gregor728d00b2011-10-10 14:49:18 +00002843
2844 DeclaratorInfo.complete(ThisDecl);
Richard Smith938f40b2011-06-11 17:19:42 +00002845
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002846 // If we don't have a comma, it is either the end of the list (a ';')
2847 // or an error, bail out.
Alp Toker094e5212014-01-05 03:27:11 +00002848 SourceLocation CommaLoc;
2849 if (!TryConsumeToken(tok::comma, CommaLoc))
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002850 break;
Mike Stump11289f42009-09-09 15:08:12 +00002851
Richard Smithc8a79032012-01-09 22:31:44 +00002852 if (Tok.isAtStartOfLine() &&
2853 !MightBeDeclarator(Declarator::MemberContext)) {
2854 // This comma was followed by a line-break and something which can't be
2855 // the start of a declarator. The comma was probably a typo for a
2856 // semicolon.
2857 Diag(CommaLoc, diag::err_expected_semi_declaration)
2858 << FixItHint::CreateReplacement(CommaLoc, ";");
2859 ExpectSemi = false;
2860 break;
2861 }
Mike Stump11289f42009-09-09 15:08:12 +00002862
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002863 // Parse the next declarator.
2864 DeclaratorInfo.clear();
Nico Weber24b2a822011-01-28 06:07:34 +00002865 VS.clear();
Nico Weberf56c85b2015-01-17 02:26:40 +00002866 BitfieldSize = ExprResult(/*Invalid=*/false);
Richard Smith9ba0fec2015-06-30 01:28:56 +00002867 EqualLoc = PureSpecLoc = SourceLocation();
Richard Smith8d06f422012-01-12 23:53:29 +00002868 DeclaratorInfo.setCommaLoc(CommaLoc);
Mike Stump11289f42009-09-09 15:08:12 +00002869
Richard Smith72553fc2014-01-23 23:53:27 +00002870 // GNU attributes are allowed before the second and subsequent declarator.
John McCall53fa7142010-12-24 02:08:15 +00002871 MaybeParseGNUAttributes(DeclaratorInfo);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002872
Nico Weberd89e6f72015-01-16 19:34:13 +00002873 if (ParseCXXMemberDeclaratorBeforeInitializer(
2874 DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs))
2875 break;
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002876 }
2877
Richard Smithc8a79032012-01-09 22:31:44 +00002878 if (ExpectSemi &&
2879 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list)) {
Chris Lattner916dbf12010-02-02 00:43:15 +00002880 // Skip to end of block or statement.
Alexey Bataevee6507d2013-11-18 08:17:37 +00002881 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Chris Lattner916dbf12010-02-02 00:43:15 +00002882 // If we stopped at a ';', eat it.
Alp Toker35d87032013-12-30 23:29:50 +00002883 TryConsumeToken(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002884 return nullptr;
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002885 }
2886
Alexey Bataev05c25d62015-07-31 08:42:25 +00002887 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002888}
2889
Richard Smith9ba0fec2015-06-30 01:28:56 +00002890/// ParseCXXMemberInitializer - Parse the brace-or-equal-initializer.
2891/// Also detect and reject any attempted defaulted/deleted function definition.
2892/// The location of the '=', if any, will be placed in EqualLoc.
Richard Smith938f40b2011-06-11 17:19:42 +00002893///
Richard Smith9ba0fec2015-06-30 01:28:56 +00002894/// This does not check for a pure-specifier; that's handled elsewhere.
Sebastian Redleef474c2012-02-22 10:50:08 +00002895///
Richard Smith938f40b2011-06-11 17:19:42 +00002896/// brace-or-equal-initializer:
2897/// '=' initializer-expression
Sebastian Redleef474c2012-02-22 10:50:08 +00002898/// braced-init-list
2899///
Richard Smith938f40b2011-06-11 17:19:42 +00002900/// initializer-clause:
2901/// assignment-expression
Sebastian Redleef474c2012-02-22 10:50:08 +00002902/// braced-init-list
2903///
Richard Smithda35e962013-11-09 04:52:51 +00002904/// defaulted/deleted function-definition:
Richard Smith938f40b2011-06-11 17:19:42 +00002905/// '=' 'default'
2906/// '=' 'delete'
2907///
2908/// Prior to C++0x, the assignment-expression in an initializer-clause must
2909/// be a constant-expression.
Douglas Gregor926410d2012-02-21 02:22:07 +00002910ExprResult Parser::ParseCXXMemberInitializer(Decl *D, bool IsFunction,
Richard Smith938f40b2011-06-11 17:19:42 +00002911 SourceLocation &EqualLoc) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002912 assert(Tok.isOneOf(tok::equal, tok::l_brace)
Richard Smith938f40b2011-06-11 17:19:42 +00002913 && "Data member initializer not starting with '=' or '{'");
2914
Faisal Valid143a0c2017-04-01 21:30:49 +00002915 EnterExpressionEvaluationContext Context(
2916 Actions, Sema::ExpressionEvaluationContext::PotentiallyEvaluated, D);
Alp Toker094e5212014-01-05 03:27:11 +00002917 if (TryConsumeToken(tok::equal, EqualLoc)) {
Richard Smith938f40b2011-06-11 17:19:42 +00002918 if (Tok.is(tok::kw_delete)) {
2919 // In principle, an initializer of '= delete p;' is legal, but it will
2920 // never type-check. It's better to diagnose it as an ill-formed expression
2921 // than as an ill-formed deleted non-function member.
2922 // An initializer of '= delete p, foo' will never be parsed, because
2923 // a top-level comma always ends the initializer expression.
2924 const Token &Next = NextToken();
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002925 if (IsFunction || Next.isOneOf(tok::semi, tok::comma, tok::eof)) {
Richard Smith938f40b2011-06-11 17:19:42 +00002926 if (IsFunction)
2927 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2928 << 1 /* delete */;
2929 else
2930 Diag(ConsumeToken(), diag::err_deleted_non_function);
Richard Smithedcb26e2014-06-11 00:49:52 +00002931 return ExprError();
Richard Smith938f40b2011-06-11 17:19:42 +00002932 }
2933 } else if (Tok.is(tok::kw_default)) {
Richard Smith938f40b2011-06-11 17:19:42 +00002934 if (IsFunction)
2935 Diag(Tok, diag::err_default_delete_in_multiple_declaration)
2936 << 0 /* default */;
2937 else
2938 Diag(ConsumeToken(), diag::err_default_special_members);
Richard Smithedcb26e2014-06-11 00:49:52 +00002939 return ExprError();
Richard Smith938f40b2011-06-11 17:19:42 +00002940 }
David Majnemer87ff66c2014-12-13 11:34:16 +00002941 }
2942 if (const auto *PD = dyn_cast_or_null<MSPropertyDecl>(D)) {
2943 Diag(Tok, diag::err_ms_property_initializer) << PD;
2944 return ExprError();
Sebastian Redleef474c2012-02-22 10:50:08 +00002945 }
2946 return ParseInitializer();
Richard Smith938f40b2011-06-11 17:19:42 +00002947}
2948
Richard Smith65ebb4a2015-03-26 04:09:53 +00002949void Parser::SkipCXXMemberSpecification(SourceLocation RecordLoc,
2950 SourceLocation AttrFixitLoc,
2951 unsigned TagType, Decl *TagDecl) {
2952 // Skip the optional 'final' keyword.
2953 if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
2954 assert(isCXX11FinalKeyword() && "not a class definition");
2955 ConsumeToken();
2956
2957 // Diagnose any C++11 attributes after 'final' keyword.
2958 // We deliberately discard these attributes.
2959 ParsedAttributesWithRange Attrs(AttrFactory);
2960 CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
2961
2962 // This can only happen if we had malformed misplaced attributes;
2963 // we only get called if there is a colon or left-brace after the
2964 // attributes.
2965 if (Tok.isNot(tok::colon) && Tok.isNot(tok::l_brace))
2966 return;
2967 }
2968
2969 // Skip the base clauses. This requires actually parsing them, because
2970 // otherwise we can't be sure where they end (a left brace may appear
2971 // within a template argument).
2972 if (Tok.is(tok::colon)) {
2973 // Enter the scope of the class so that we can correctly parse its bases.
2974 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
2975 ParsingClassDefinition ParsingDef(*this, TagDecl, /*NonNestedClass*/ true,
2976 TagType == DeclSpec::TST_interface);
Richard Smith0f192e82015-06-11 22:48:25 +00002977 auto OldContext =
2978 Actions.ActOnTagStartSkippedDefinition(getCurScope(), TagDecl);
Richard Smith65ebb4a2015-03-26 04:09:53 +00002979
2980 // Parse the bases but don't attach them to the class.
2981 ParseBaseClause(nullptr);
2982
Richard Smith0f192e82015-06-11 22:48:25 +00002983 Actions.ActOnTagFinishSkippedDefinition(OldContext);
Richard Smith65ebb4a2015-03-26 04:09:53 +00002984
2985 if (!Tok.is(tok::l_brace)) {
2986 Diag(PP.getLocForEndOfToken(PrevTokLocation),
2987 diag::err_expected_lbrace_after_base_specifiers);
2988 return;
2989 }
2990 }
2991
2992 // Skip the body.
2993 assert(Tok.is(tok::l_brace));
2994 BalancedDelimiterTracker T(*this, tok::l_brace);
2995 T.consumeOpen();
2996 T.skipToEnd();
Richard Smith04c6c1f2015-07-01 18:56:50 +00002997
2998 // Parse and discard any trailing attributes.
2999 ParsedAttributes Attrs(AttrFactory);
3000 if (Tok.is(tok::kw___attribute))
3001 MaybeParseGNUAttributes(Attrs);
Richard Smith65ebb4a2015-03-26 04:09:53 +00003002}
3003
Alexey Bataev05c25d62015-07-31 08:42:25 +00003004Parser::DeclGroupPtrTy Parser::ParseCXXClassMemberDeclarationWithPragmas(
3005 AccessSpecifier &AS, ParsedAttributesWithRange &AccessAttrs,
3006 DeclSpec::TST TagType, Decl *TagDecl) {
Richard Smithb55f7582017-01-28 01:12:10 +00003007 switch (Tok.getKind()) {
3008 case tok::kw___if_exists:
3009 case tok::kw___if_not_exists:
Alexey Bataev05c25d62015-07-31 08:42:25 +00003010 ParseMicrosoftIfExistsClassDeclaration(TagType, AS);
David Blaikie0403cb12016-01-15 23:43:25 +00003011 return nullptr;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003012
Richard Smithb55f7582017-01-28 01:12:10 +00003013 case tok::semi:
3014 // Check for extraneous top-level semicolon.
Alexey Bataev05c25d62015-07-31 08:42:25 +00003015 ConsumeExtraSemi(InsideStruct, TagType);
David Blaikie0403cb12016-01-15 23:43:25 +00003016 return nullptr;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003017
Richard Smithb55f7582017-01-28 01:12:10 +00003018 // Handle pragmas that can appear as member declarations.
3019 case tok::annot_pragma_vis:
Alexey Bataev05c25d62015-07-31 08:42:25 +00003020 HandlePragmaVisibility();
David Blaikie0403cb12016-01-15 23:43:25 +00003021 return nullptr;
Richard Smithb55f7582017-01-28 01:12:10 +00003022 case tok::annot_pragma_pack:
Alexey Bataev05c25d62015-07-31 08:42:25 +00003023 HandlePragmaPack();
David Blaikie0403cb12016-01-15 23:43:25 +00003024 return nullptr;
Richard Smithb55f7582017-01-28 01:12:10 +00003025 case tok::annot_pragma_align:
Alexey Bataev05c25d62015-07-31 08:42:25 +00003026 HandlePragmaAlign();
David Blaikie0403cb12016-01-15 23:43:25 +00003027 return nullptr;
Richard Smithb55f7582017-01-28 01:12:10 +00003028 case tok::annot_pragma_ms_pointers_to_members:
Alexey Bataev05c25d62015-07-31 08:42:25 +00003029 HandlePragmaMSPointersToMembers();
David Blaikie0403cb12016-01-15 23:43:25 +00003030 return nullptr;
Richard Smithb55f7582017-01-28 01:12:10 +00003031 case tok::annot_pragma_ms_pragma:
Alexey Bataev05c25d62015-07-31 08:42:25 +00003032 HandlePragmaMSPragma();
David Blaikie0403cb12016-01-15 23:43:25 +00003033 return nullptr;
Richard Smithb55f7582017-01-28 01:12:10 +00003034 case tok::annot_pragma_ms_vtordisp:
Alexey Bataev3d42f342015-11-20 07:02:57 +00003035 HandlePragmaMSVtorDisp();
David Blaikie0403cb12016-01-15 23:43:25 +00003036 return nullptr;
Richard Smithb256d302017-01-28 01:20:57 +00003037 case tok::annot_pragma_dump:
3038 HandlePragmaDump();
3039 return nullptr;
Alexey Bataev3d42f342015-11-20 07:02:57 +00003040
Richard Smithb55f7582017-01-28 01:12:10 +00003041 case tok::kw_namespace:
3042 // If we see a namespace here, a close brace was missing somewhere.
Alexey Bataev05c25d62015-07-31 08:42:25 +00003043 DiagnoseUnexpectedNamespace(cast<NamedDecl>(TagDecl));
David Blaikie0403cb12016-01-15 23:43:25 +00003044 return nullptr;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003045
Richard Smithb55f7582017-01-28 01:12:10 +00003046 case tok::kw_public:
3047 case tok::kw_protected:
3048 case tok::kw_private: {
3049 AccessSpecifier NewAS = getAccessSpecifierIfPresent();
3050 assert(NewAS != AS_none);
Alexey Bataev05c25d62015-07-31 08:42:25 +00003051 // Current token is a C++ access specifier.
3052 AS = NewAS;
3053 SourceLocation ASLoc = Tok.getLocation();
3054 unsigned TokLength = Tok.getLength();
3055 ConsumeToken();
3056 AccessAttrs.clear();
3057 MaybeParseGNUAttributes(AccessAttrs);
3058
3059 SourceLocation EndLoc;
3060 if (TryConsumeToken(tok::colon, EndLoc)) {
3061 } else if (TryConsumeToken(tok::semi, EndLoc)) {
3062 Diag(EndLoc, diag::err_expected)
3063 << tok::colon << FixItHint::CreateReplacement(EndLoc, ":");
3064 } else {
3065 EndLoc = ASLoc.getLocWithOffset(TokLength);
3066 Diag(EndLoc, diag::err_expected)
3067 << tok::colon << FixItHint::CreateInsertion(EndLoc, ":");
3068 }
3069
3070 // The Microsoft extension __interface does not permit non-public
3071 // access specifiers.
3072 if (TagType == DeclSpec::TST_interface && AS != AS_public) {
3073 Diag(ASLoc, diag::err_access_specifier_interface) << (AS == AS_protected);
3074 }
3075
3076 if (Actions.ActOnAccessSpecifier(NewAS, ASLoc, EndLoc,
3077 AccessAttrs.getList())) {
3078 // found another attribute than only annotations
3079 AccessAttrs.clear();
3080 }
3081
David Blaikie0403cb12016-01-15 23:43:25 +00003082 return nullptr;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003083 }
3084
Richard Smithb55f7582017-01-28 01:12:10 +00003085 case tok::annot_pragma_openmp:
Alexey Bataev587e1de2016-03-30 10:43:55 +00003086 return ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, AccessAttrs, TagType,
3087 TagDecl);
Alexey Bataev05c25d62015-07-31 08:42:25 +00003088
Richard Smithb55f7582017-01-28 01:12:10 +00003089 default:
3090 return ParseCXXClassMemberDeclaration(AS, AccessAttrs.getList());
3091 }
Alexey Bataev05c25d62015-07-31 08:42:25 +00003092}
3093
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003094/// ParseCXXMemberSpecification - Parse the class definition.
3095///
3096/// member-specification:
3097/// member-declaration member-specification[opt]
3098/// access-specifier ':' member-specification[opt]
3099///
Joao Matose9a3ed42012-08-31 22:18:20 +00003100void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc,
Michael Han309af292013-01-07 16:57:11 +00003101 SourceLocation AttrFixitLoc,
Richard Smith4c96e992013-02-19 23:47:15 +00003102 ParsedAttributesWithRange &Attrs,
Joao Matose9a3ed42012-08-31 22:18:20 +00003103 unsigned TagType, Decl *TagDecl) {
3104 assert((TagType == DeclSpec::TST_struct ||
3105 TagType == DeclSpec::TST_interface ||
3106 TagType == DeclSpec::TST_union ||
3107 TagType == DeclSpec::TST_class) && "Invalid TagType!");
3108
John McCallfaf5fb42010-08-26 23:41:50 +00003109 PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc,
3110 "parsing struct/union/class body");
Mike Stump11289f42009-09-09 15:08:12 +00003111
Douglas Gregoredf8f392010-01-16 20:52:59 +00003112 // Determine whether this is a non-nested class. Note that local
3113 // classes are *not* considered to be nested classes.
3114 bool NonNestedClass = true;
3115 if (!ClassStack.empty()) {
Douglas Gregor0be31a22010-07-02 17:43:08 +00003116 for (const Scope *S = getCurScope(); S; S = S->getParent()) {
Douglas Gregoredf8f392010-01-16 20:52:59 +00003117 if (S->isClassScope()) {
3118 // We're inside a class scope, so this is a nested class.
3119 NonNestedClass = false;
John McCalldb632ac2012-09-25 07:32:39 +00003120
3121 // The Microsoft extension __interface does not permit nested classes.
3122 if (getCurrentClass().IsInterface) {
3123 Diag(RecordLoc, diag::err_invalid_member_in_interface)
3124 << /*ErrorType=*/6
3125 << (isa<NamedDecl>(TagDecl)
3126 ? cast<NamedDecl>(TagDecl)->getQualifiedNameAsString()
David Blaikieabe1a392014-04-02 05:58:29 +00003127 : "(anonymous)");
John McCalldb632ac2012-09-25 07:32:39 +00003128 }
Douglas Gregoredf8f392010-01-16 20:52:59 +00003129 break;
3130 }
3131
Serge Pavlovd9c0bcf2015-07-14 10:02:10 +00003132 if ((S->getFlags() & Scope::FnScope))
3133 // If we're in a function or function template then this is a local
3134 // class rather than a nested class.
3135 break;
Douglas Gregoredf8f392010-01-16 20:52:59 +00003136 }
3137 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003138
3139 // Enter a scope for the class.
Douglas Gregor658b9552009-01-09 22:42:13 +00003140 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003141
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003142 // Note that we are parsing a new (potentially-nested) class definition.
John McCalldb632ac2012-09-25 07:32:39 +00003143 ParsingClassDefinition ParsingDef(*this, TagDecl, NonNestedClass,
3144 TagType == DeclSpec::TST_interface);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003145
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003146 if (TagDecl)
Douglas Gregor0be31a22010-07-02 17:43:08 +00003147 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
John McCall2d814c32009-12-19 21:48:58 +00003148
Anders Carlssonf9eb63b2011-03-25 14:46:08 +00003149 SourceLocation FinalLoc;
David Majnemera5433082013-10-18 00:33:31 +00003150 bool IsFinalSpelledSealed = false;
Anders Carlssonf9eb63b2011-03-25 14:46:08 +00003151
3152 // Parse the optional 'final' keyword.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003153 if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
David Majnemera5433082013-10-18 00:33:31 +00003154 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier(Tok);
3155 assert((Specifier == VirtSpecifiers::VS_Final ||
Andrey Bokhanko276055b2016-07-29 10:42:48 +00003156 Specifier == VirtSpecifiers::VS_GNU_Final ||
David Majnemera5433082013-10-18 00:33:31 +00003157 Specifier == VirtSpecifiers::VS_Sealed) &&
3158 "not a class definition");
Richard Smithda261112011-10-15 04:21:46 +00003159 FinalLoc = ConsumeToken();
David Majnemera5433082013-10-18 00:33:31 +00003160 IsFinalSpelledSealed = Specifier == VirtSpecifiers::VS_Sealed;
Anders Carlssonf9eb63b2011-03-25 14:46:08 +00003161
David Majnemera5433082013-10-18 00:33:31 +00003162 if (TagType == DeclSpec::TST_interface)
John McCalldb632ac2012-09-25 07:32:39 +00003163 Diag(FinalLoc, diag::err_override_control_interface)
David Majnemera5433082013-10-18 00:33:31 +00003164 << VirtSpecifiers::getSpecifierName(Specifier);
3165 else if (Specifier == VirtSpecifiers::VS_Final)
3166 Diag(FinalLoc, getLangOpts().CPlusPlus11
3167 ? diag::warn_cxx98_compat_override_control_keyword
3168 : diag::ext_override_control_keyword)
3169 << VirtSpecifiers::getSpecifierName(Specifier);
3170 else if (Specifier == VirtSpecifiers::VS_Sealed)
3171 Diag(FinalLoc, diag::ext_ms_sealed_keyword);
Andrey Bokhanko276055b2016-07-29 10:42:48 +00003172 else if (Specifier == VirtSpecifiers::VS_GNU_Final)
3173 Diag(FinalLoc, diag::ext_warn_gnu_final);
Michael Han9407e502012-11-26 22:54:45 +00003174
Michael Han309af292013-01-07 16:57:11 +00003175 // Parse any C++11 attributes after 'final' keyword.
3176 // These attributes are not allowed to appear here,
3177 // and the only possible place for them to appertain
3178 // to the class would be between class-key and class-name.
Richard Smith4c96e992013-02-19 23:47:15 +00003179 CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
Nico Weber4b4be842014-12-29 06:56:50 +00003180
3181 // ParseClassSpecifier() does only a superficial check for attributes before
3182 // deciding to call this method. For example, for
3183 // `class C final alignas ([l) {` it will decide that this looks like a
3184 // misplaced attribute since it sees `alignas '(' ')'`. But the actual
3185 // attribute parsing code will try to parse the '[' as a constexpr lambda
3186 // and consume enough tokens that the alignas parsing code will eat the
3187 // opening '{'. So bail out if the next token isn't one we expect.
Nico Weber36de3a22014-12-29 21:56:22 +00003188 if (!Tok.is(tok::colon) && !Tok.is(tok::l_brace)) {
3189 if (TagDecl)
3190 Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
Nico Weber4b4be842014-12-29 06:56:50 +00003191 return;
Nico Weber36de3a22014-12-29 21:56:22 +00003192 }
Anders Carlssonf9eb63b2011-03-25 14:46:08 +00003193 }
Anders Carlsson4b63d0e2011-01-22 16:56:46 +00003194
John McCall2d814c32009-12-19 21:48:58 +00003195 if (Tok.is(tok::colon)) {
3196 ParseBaseClause(TagDecl);
John McCall2d814c32009-12-19 21:48:58 +00003197 if (!Tok.is(tok::l_brace)) {
Ismail Pazarbasi129c44c2014-09-25 21:13:02 +00003198 bool SuggestFixIt = false;
3199 SourceLocation BraceLoc = PP.getLocForEndOfToken(PrevTokLocation);
3200 if (Tok.isAtStartOfLine()) {
3201 switch (Tok.getKind()) {
3202 case tok::kw_private:
3203 case tok::kw_protected:
3204 case tok::kw_public:
3205 SuggestFixIt = NextToken().getKind() == tok::colon;
3206 break;
3207 case tok::kw_static_assert:
3208 case tok::r_brace:
3209 case tok::kw_using:
3210 // base-clause can have simple-template-id; 'template' can't be there
3211 case tok::kw_template:
3212 SuggestFixIt = true;
3213 break;
3214 case tok::identifier:
3215 SuggestFixIt = isConstructorDeclarator(true);
3216 break;
3217 default:
3218 SuggestFixIt = isCXXSimpleDeclaration(/*AllowForRangeDecl=*/false);
3219 break;
3220 }
3221 }
3222 DiagnosticBuilder LBraceDiag =
3223 Diag(BraceLoc, diag::err_expected_lbrace_after_base_specifiers);
3224 if (SuggestFixIt) {
3225 LBraceDiag << FixItHint::CreateInsertion(BraceLoc, " {");
3226 // Try recovering from missing { after base-clause.
3227 PP.EnterToken(Tok);
3228 Tok.setKind(tok::l_brace);
3229 } else {
3230 if (TagDecl)
3231 Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
3232 return;
3233 }
John McCall2d814c32009-12-19 21:48:58 +00003234 }
3235 }
3236
3237 assert(Tok.is(tok::l_brace));
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003238 BalancedDelimiterTracker T(*this, tok::l_brace);
3239 T.consumeOpen();
John McCall2d814c32009-12-19 21:48:58 +00003240
John McCall08bede42010-05-28 08:11:17 +00003241 if (TagDecl)
Anders Carlsson30f29442011-03-25 14:31:08 +00003242 Actions.ActOnStartCXXMemberDeclarations(getCurScope(), TagDecl, FinalLoc,
David Majnemera5433082013-10-18 00:33:31 +00003243 IsFinalSpelledSealed,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003244 T.getOpenLocation());
John McCall1c7e6ec2009-12-20 07:58:13 +00003245
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003246 // C++ 11p3: Members of a class defined with the keyword class are private
3247 // by default. Members of a class defined with the keywords struct or union
3248 // are public by default.
3249 AccessSpecifier CurAS;
3250 if (TagType == DeclSpec::TST_class)
3251 CurAS = AS_private;
3252 else
3253 CurAS = AS_public;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003254 ParsedAttributesWithRange AccessAttrs(AttrFactory);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003255
Douglas Gregor9377c822010-06-21 22:31:09 +00003256 if (TagDecl) {
3257 // While we still have something to read, read the member-declarations.
Richard Smith752ada82015-11-17 23:32:01 +00003258 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
3259 Tok.isNot(tok::eof)) {
Douglas Gregor9377c822010-06-21 22:31:09 +00003260 // Each iteration of this loop reads one member-declaration.
Alexey Bataev05c25d62015-07-31 08:42:25 +00003261 ParseCXXClassMemberDeclarationWithPragmas(
3262 CurAS, AccessAttrs, static_cast<DeclSpec::TST>(TagType), TagDecl);
Serge Pavlovc4e04a22015-09-19 05:32:57 +00003263 }
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003264 T.consumeClose();
Douglas Gregor9377c822010-06-21 22:31:09 +00003265 } else {
Alexey Bataevee6507d2013-11-18 08:17:37 +00003266 SkipUntil(tok::r_brace);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003267 }
Mike Stump11289f42009-09-09 15:08:12 +00003268
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003269 // If attributes exist after class contents, parse them.
John McCall084e83d2011-03-24 11:26:52 +00003270 ParsedAttributes attrs(AttrFactory);
John McCall53fa7142010-12-24 02:08:15 +00003271 MaybeParseGNUAttributes(attrs);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003272
John McCall08bede42010-05-28 08:11:17 +00003273 if (TagDecl)
Douglas Gregor0be31a22010-07-02 17:43:08 +00003274 Actions.ActOnFinishCXXMemberSpecification(getCurScope(), RecordLoc, TagDecl,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003275 T.getOpenLocation(),
3276 T.getCloseLocation(),
John McCall53fa7142010-12-24 02:08:15 +00003277 attrs.getList());
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003278
Douglas Gregor433e0532012-04-16 18:27:27 +00003279 // C++11 [class.mem]p2:
3280 // Within the class member-specification, the class is regarded as complete
Richard Smith0b3a4622014-11-13 20:01:57 +00003281 // within function bodies, default arguments, exception-specifications, and
Douglas Gregor433e0532012-04-16 18:27:27 +00003282 // brace-or-equal-initializers for non-static data members (including such
3283 // things in nested classes).
Douglas Gregor9377c822010-06-21 22:31:09 +00003284 if (TagDecl && NonNestedClass) {
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003285 // We are not inside a nested class. This class and its nested classes
Douglas Gregor4d87df52008-12-16 21:30:33 +00003286 // are complete and we can parse the delayed portions of method
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00003287 // declarations and the lexed inline method definitions, along with any
3288 // delayed attributes.
Douglas Gregor428119e2010-06-16 23:45:56 +00003289 SourceLocation SavedPrevTokLocation = PrevTokLocation;
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00003290 ParseLexedAttributes(getCurrentClass());
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003291 ParseLexedMethodDeclarations(getCurrentClass());
Richard Smith84973e52012-04-21 18:42:51 +00003292
3293 // We've finished with all pending member declarations.
3294 Actions.ActOnFinishCXXMemberDecls();
3295
Richard Smith938f40b2011-06-11 17:19:42 +00003296 ParseLexedMemberInitializers(getCurrentClass());
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003297 ParseLexedMethodDefs(getCurrentClass());
Douglas Gregor428119e2010-06-16 23:45:56 +00003298 PrevTokLocation = SavedPrevTokLocation;
Reid Klecknerbba3cb92015-03-17 19:00:50 +00003299
3300 // We've finished parsing everything, including default argument
3301 // initializers.
Hans Wennborg99000c22015-08-15 01:18:16 +00003302 Actions.ActOnFinishCXXNonNestedClass(TagDecl);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003303 }
3304
John McCall08bede42010-05-28 08:11:17 +00003305 if (TagDecl)
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00003306 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getRange());
John McCall2ff380a2010-03-17 00:38:33 +00003307
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003308 // Leave the class scope.
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003309 ParsingDef.Pop();
Douglas Gregor7307d6c2008-12-10 06:34:36 +00003310 ClassScope.Exit();
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003311}
Douglas Gregore8381c02008-11-05 04:29:56 +00003312
Richard Smith2ac43ad2013-11-15 23:00:02 +00003313void Parser::DiagnoseUnexpectedNamespace(NamedDecl *D) {
Richard Smithda35e962013-11-09 04:52:51 +00003314 assert(Tok.is(tok::kw_namespace));
3315
3316 // FIXME: Suggest where the close brace should have gone by looking
3317 // at indentation changes within the definition body.
Richard Smith2ac43ad2013-11-15 23:00:02 +00003318 Diag(D->getLocation(),
3319 diag::err_missing_end_of_definition) << D;
Richard Smithda35e962013-11-09 04:52:51 +00003320 Diag(Tok.getLocation(),
Richard Smith2ac43ad2013-11-15 23:00:02 +00003321 diag::note_missing_end_of_definition_before) << D;
Richard Smithda35e962013-11-09 04:52:51 +00003322
3323 // Push '};' onto the token stream to recover.
3324 PP.EnterToken(Tok);
3325
3326 Tok.startToken();
3327 Tok.setLocation(PP.getLocForEndOfToken(PrevTokLocation));
3328 Tok.setKind(tok::semi);
3329 PP.EnterToken(Tok);
3330
3331 Tok.setKind(tok::r_brace);
3332}
3333
Douglas Gregore8381c02008-11-05 04:29:56 +00003334/// ParseConstructorInitializer - Parse a C++ constructor initializer,
3335/// which explicitly initializes the members or base classes of a
3336/// class (C++ [class.base.init]). For example, the three initializers
3337/// after the ':' in the Derived constructor below:
3338///
3339/// @code
3340/// class Base { };
3341/// class Derived : Base {
3342/// int x;
3343/// float f;
3344/// public:
3345/// Derived(float f) : Base(), x(17), f(f) { }
3346/// };
3347/// @endcode
3348///
Mike Stump11289f42009-09-09 15:08:12 +00003349/// [C++] ctor-initializer:
3350/// ':' mem-initializer-list
Douglas Gregore8381c02008-11-05 04:29:56 +00003351///
Mike Stump11289f42009-09-09 15:08:12 +00003352/// [C++] mem-initializer-list:
Douglas Gregor44e7df62011-01-04 00:32:56 +00003353/// mem-initializer ...[opt]
3354/// mem-initializer ...[opt] , mem-initializer-list
John McCall48871652010-08-21 09:40:31 +00003355void Parser::ParseConstructorInitializer(Decl *ConstructorDecl) {
Nico Weber3b00fdc2015-03-07 19:52:39 +00003356 assert(Tok.is(tok::colon) &&
3357 "Constructor initializer always starts with ':'");
Douglas Gregore8381c02008-11-05 04:29:56 +00003358
Nico Weber3b00fdc2015-03-07 19:52:39 +00003359 // Poison the SEH identifiers so they are flagged as illegal in constructor
3360 // initializers.
John Wiegley1c0675e2011-04-28 01:08:34 +00003361 PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
Douglas Gregore8381c02008-11-05 04:29:56 +00003362 SourceLocation ColonLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +00003363
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003364 SmallVector<CXXCtorInitializer*, 4> MemInitializers;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003365 bool AnyErrors = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003366
Douglas Gregore8381c02008-11-05 04:29:56 +00003367 do {
Douglas Gregoreaeeca92010-08-28 00:00:50 +00003368 if (Tok.is(tok::code_completion)) {
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00003369 Actions.CodeCompleteConstructorInitializer(ConstructorDecl,
3370 MemInitializers);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00003371 return cutOffParsing();
Douglas Gregoreaeeca92010-08-28 00:00:50 +00003372 }
Alexey Bataev79de17d2016-01-20 05:25:51 +00003373
3374 MemInitResult MemInit = ParseMemInitializer(ConstructorDecl);
3375 if (!MemInit.isInvalid())
3376 MemInitializers.push_back(MemInit.get());
3377 else
3378 AnyErrors = true;
3379
Douglas Gregore8381c02008-11-05 04:29:56 +00003380 if (Tok.is(tok::comma))
3381 ConsumeToken();
3382 else if (Tok.is(tok::l_brace))
3383 break;
Alexey Bataev79de17d2016-01-20 05:25:51 +00003384 // If the previous initializer was valid and the next token looks like a
3385 // base or member initializer, assume that we're just missing a comma.
3386 else if (!MemInit.isInvalid() &&
3387 Tok.isOneOf(tok::identifier, tok::coloncolon)) {
Douglas Gregorce66d022010-09-07 14:51:08 +00003388 SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation);
3389 Diag(Loc, diag::err_ctor_init_missing_comma)
3390 << FixItHint::CreateInsertion(Loc, ", ");
3391 } else {
Douglas Gregore8381c02008-11-05 04:29:56 +00003392 // Skip over garbage, until we get to '{'. Don't eat the '{'.
Alexey Bataev79de17d2016-01-20 05:25:51 +00003393 if (!MemInit.isInvalid())
3394 Diag(Tok.getLocation(), diag::err_expected_either) << tok::l_brace
3395 << tok::comma;
Alexey Bataevee6507d2013-11-18 08:17:37 +00003396 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
Douglas Gregore8381c02008-11-05 04:29:56 +00003397 break;
3398 }
3399 } while (true);
3400
David Blaikie3fc2f912013-01-17 05:26:25 +00003401 Actions.ActOnMemInitializers(ConstructorDecl, ColonLoc, MemInitializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003402 AnyErrors);
Douglas Gregore8381c02008-11-05 04:29:56 +00003403}
3404
3405/// ParseMemInitializer - Parse a C++ member initializer, which is
3406/// part of a constructor initializer that explicitly initializes one
3407/// member or base class (C++ [class.base.init]). See
3408/// ParseConstructorInitializer for an example.
3409///
3410/// [C++] mem-initializer:
3411/// mem-initializer-id '(' expression-list[opt] ')'
Sebastian Redl3da34892011-06-05 12:23:16 +00003412/// [C++0x] mem-initializer-id braced-init-list
Mike Stump11289f42009-09-09 15:08:12 +00003413///
Douglas Gregore8381c02008-11-05 04:29:56 +00003414/// [C++] mem-initializer-id:
3415/// '::'[opt] nested-name-specifier[opt] class-name
3416/// identifier
Craig Topper9ad7e262014-10-31 06:57:07 +00003417MemInitResult Parser::ParseMemInitializer(Decl *ConstructorDecl) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00003418 // parse '::'[opt] nested-name-specifier[opt]
3419 CXXScopeSpec SS;
David Blaikieefdccaa2016-01-15 23:43:34 +00003420 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false);
Richard Smithaf3b3252017-05-18 19:21:48 +00003421
3422 // : identifier
3423 IdentifierInfo *II = nullptr;
3424 SourceLocation IdLoc = Tok.getLocation();
3425 // : declype(...)
3426 DeclSpec DS(AttrFactory);
3427 // : template_name<...>
John McCallba7bf592010-08-24 05:47:05 +00003428 ParsedType TemplateTypeTy;
Richard Smithaf3b3252017-05-18 19:21:48 +00003429
3430 if (Tok.is(tok::identifier)) {
3431 // Get the identifier. This may be a member name or a class name,
3432 // but we'll let the semantic analysis determine which it is.
3433 II = Tok.getIdentifierInfo();
3434 ConsumeToken();
3435 } else if (Tok.is(tok::annot_decltype)) {
3436 // Get the decltype expression, if there is one.
3437 // Uses of decltype will already have been converted to annot_decltype by
3438 // ParseOptionalCXXScopeSpecifier at this point.
3439 // FIXME: Can we get here with a scope specifier?
3440 ParseDecltypeSpecifier(DS);
3441 } else {
3442 TemplateIdAnnotation *TemplateId = Tok.is(tok::annot_template_id)
3443 ? takeTemplateIdAnnotation(Tok)
3444 : nullptr;
3445 if (TemplateId && (TemplateId->Kind == TNK_Type_template ||
3446 TemplateId->Kind == TNK_Dependent_template_name)) {
Richard Smith62559bd2017-02-01 21:36:38 +00003447 AnnotateTemplateIdTokenAsType(/*IsClassName*/true);
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00003448 assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
John McCallba7bf592010-08-24 05:47:05 +00003449 TemplateTypeTy = getTypeAnnotation(Tok);
Richard Smithaf3b3252017-05-18 19:21:48 +00003450 ConsumeAnnotationToken();
3451 } else {
3452 Diag(Tok, diag::err_expected_member_or_base_name);
3453 return true;
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00003454 }
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00003455 }
Douglas Gregore8381c02008-11-05 04:29:56 +00003456
3457 // Parse the '('.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003458 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
Richard Smith5d164bc2011-10-15 05:09:34 +00003459 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
3460
Sebastian Redla74948d2011-09-24 17:48:25 +00003461 ExprResult InitList = ParseBraceInitializer();
3462 if (InitList.isInvalid())
3463 return true;
3464
3465 SourceLocation EllipsisLoc;
Alp Toker094e5212014-01-05 03:27:11 +00003466 TryConsumeToken(tok::ellipsis, EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00003467
3468 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
David Blaikie186a8892012-01-24 06:03:59 +00003469 TemplateTypeTy, DS, IdLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003470 InitList.get(), EllipsisLoc);
Sebastian Redl3da34892011-06-05 12:23:16 +00003471 } else if(Tok.is(tok::l_paren)) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003472 BalancedDelimiterTracker T(*this, tok::l_paren);
3473 T.consumeOpen();
Douglas Gregore8381c02008-11-05 04:29:56 +00003474
Sebastian Redl3da34892011-06-05 12:23:16 +00003475 // Parse the optional expression-list.
Benjamin Kramerf0623432012-08-23 22:51:59 +00003476 ExprVector ArgExprs;
Sebastian Redl3da34892011-06-05 12:23:16 +00003477 CommaLocsTy CommaLocs;
3478 if (Tok.isNot(tok::r_paren) && ParseExpressionList(ArgExprs, CommaLocs)) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00003479 SkipUntil(tok::r_paren, StopAtSemi);
Sebastian Redl3da34892011-06-05 12:23:16 +00003480 return true;
3481 }
3482
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003483 T.consumeClose();
Sebastian Redl3da34892011-06-05 12:23:16 +00003484
3485 SourceLocation EllipsisLoc;
Alp Toker97650562014-01-10 11:19:30 +00003486 TryConsumeToken(tok::ellipsis, EllipsisLoc);
Sebastian Redl3da34892011-06-05 12:23:16 +00003487
3488 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
David Blaikie186a8892012-01-24 06:03:59 +00003489 TemplateTypeTy, DS, IdLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00003490 T.getOpenLocation(), ArgExprs,
3491 T.getCloseLocation(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00003492 }
3493
Alp Tokerec543272013-12-24 09:48:30 +00003494 if (getLangOpts().CPlusPlus11)
3495 return Diag(Tok, diag::err_expected_either) << tok::l_paren << tok::l_brace;
3496 else
3497 return Diag(Tok, diag::err_expected) << tok::l_paren;
Douglas Gregore8381c02008-11-05 04:29:56 +00003498}
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003499
Sebastian Redl965b0e32011-03-05 14:45:16 +00003500/// \brief Parse a C++ exception-specification if present (C++0x [except.spec]).
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003501///
Douglas Gregor356513d2008-12-01 18:00:20 +00003502/// exception-specification:
Sebastian Redl965b0e32011-03-05 14:45:16 +00003503/// dynamic-exception-specification
3504/// noexcept-specification
3505///
3506/// noexcept-specification:
3507/// 'noexcept'
3508/// 'noexcept' '(' constant-expression ')'
3509ExceptionSpecificationType
Richard Smith0b3a4622014-11-13 20:01:57 +00003510Parser::tryParseExceptionSpecification(bool Delayed,
Douglas Gregor433e0532012-04-16 18:27:27 +00003511 SourceRange &SpecificationRange,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003512 SmallVectorImpl<ParsedType> &DynamicExceptions,
3513 SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
Richard Smith0b3a4622014-11-13 20:01:57 +00003514 ExprResult &NoexceptExpr,
3515 CachedTokens *&ExceptionSpecTokens) {
Sebastian Redl965b0e32011-03-05 14:45:16 +00003516 ExceptionSpecificationType Result = EST_None;
Hans Wennborgdcfba332015-10-06 23:40:43 +00003517 ExceptionSpecTokens = nullptr;
Richard Smith0b3a4622014-11-13 20:01:57 +00003518
3519 // Handle delayed parsing of exception-specifications.
3520 if (Delayed) {
3521 if (Tok.isNot(tok::kw_throw) && Tok.isNot(tok::kw_noexcept))
3522 return EST_None;
Sebastian Redl965b0e32011-03-05 14:45:16 +00003523
Richard Smith0b3a4622014-11-13 20:01:57 +00003524 // Consume and cache the starting token.
3525 bool IsNoexcept = Tok.is(tok::kw_noexcept);
3526 Token StartTok = Tok;
3527 SpecificationRange = SourceRange(ConsumeToken());
3528
3529 // Check for a '('.
3530 if (!Tok.is(tok::l_paren)) {
3531 // If this is a bare 'noexcept', we're done.
3532 if (IsNoexcept) {
3533 Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
Hans Wennborgdcfba332015-10-06 23:40:43 +00003534 NoexceptExpr = nullptr;
Richard Smith0b3a4622014-11-13 20:01:57 +00003535 return EST_BasicNoexcept;
3536 }
3537
3538 Diag(Tok, diag::err_expected_lparen_after) << "throw";
3539 return EST_DynamicNone;
3540 }
3541
3542 // Cache the tokens for the exception-specification.
3543 ExceptionSpecTokens = new CachedTokens;
3544 ExceptionSpecTokens->push_back(StartTok); // 'throw' or 'noexcept'
3545 ExceptionSpecTokens->push_back(Tok); // '('
3546 SpecificationRange.setEnd(ConsumeParen()); // '('
Richard Smithb1c217e2015-01-13 02:24:58 +00003547
3548 ConsumeAndStoreUntil(tok::r_paren, *ExceptionSpecTokens,
3549 /*StopAtSemi=*/true,
3550 /*ConsumeFinalToken=*/true);
Aaron Ballman580ccaf2016-01-12 21:04:22 +00003551 SpecificationRange.setEnd(ExceptionSpecTokens->back().getLocation());
3552
Richard Smith0b3a4622014-11-13 20:01:57 +00003553 return EST_Unparsed;
3554 }
3555
Sebastian Redl965b0e32011-03-05 14:45:16 +00003556 // See if there's a dynamic specification.
3557 if (Tok.is(tok::kw_throw)) {
3558 Result = ParseDynamicExceptionSpecification(SpecificationRange,
3559 DynamicExceptions,
3560 DynamicExceptionRanges);
3561 assert(DynamicExceptions.size() == DynamicExceptionRanges.size() &&
3562 "Produced different number of exception types and ranges.");
3563 }
3564
3565 // If there's no noexcept specification, we're done.
3566 if (Tok.isNot(tok::kw_noexcept))
3567 return Result;
3568
Richard Smithb15c11c2011-10-17 23:06:20 +00003569 Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
3570
Sebastian Redl965b0e32011-03-05 14:45:16 +00003571 // If we already had a dynamic specification, parse the noexcept for,
3572 // recovery, but emit a diagnostic and don't store the results.
3573 SourceRange NoexceptRange;
3574 ExceptionSpecificationType NoexceptType = EST_None;
3575
3576 SourceLocation KeywordLoc = ConsumeToken();
3577 if (Tok.is(tok::l_paren)) {
3578 // There is an argument.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003579 BalancedDelimiterTracker T(*this, tok::l_paren);
3580 T.consumeOpen();
Sebastian Redl965b0e32011-03-05 14:45:16 +00003581 NoexceptType = EST_ComputedNoexcept;
3582 NoexceptExpr = ParseConstantExpression();
Serge Pavlov3739f5e72015-06-29 17:50:19 +00003583 T.consumeClose();
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003584 // The argument must be contextually convertible to bool. We use
Richard Smith03a4aa32016-06-23 19:02:52 +00003585 // CheckBooleanCondition for this purpose.
3586 // FIXME: Add a proper Sema entry point for this.
Serge Pavlov3739f5e72015-06-29 17:50:19 +00003587 if (!NoexceptExpr.isInvalid()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00003588 NoexceptExpr =
3589 Actions.CheckBooleanCondition(KeywordLoc, NoexceptExpr.get());
Serge Pavlov3739f5e72015-06-29 17:50:19 +00003590 NoexceptRange = SourceRange(KeywordLoc, T.getCloseLocation());
3591 } else {
Malcolm Parsonsa3220ce2017-01-12 16:11:28 +00003592 NoexceptType = EST_BasicNoexcept;
Serge Pavlov3739f5e72015-06-29 17:50:19 +00003593 }
Sebastian Redl965b0e32011-03-05 14:45:16 +00003594 } else {
3595 // There is no argument.
3596 NoexceptType = EST_BasicNoexcept;
3597 NoexceptRange = SourceRange(KeywordLoc, KeywordLoc);
3598 }
3599
3600 if (Result == EST_None) {
3601 SpecificationRange = NoexceptRange;
3602 Result = NoexceptType;
3603
3604 // If there's a dynamic specification after a noexcept specification,
3605 // parse that and ignore the results.
3606 if (Tok.is(tok::kw_throw)) {
3607 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
3608 ParseDynamicExceptionSpecification(NoexceptRange, DynamicExceptions,
3609 DynamicExceptionRanges);
3610 }
3611 } else {
3612 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
3613 }
3614
3615 return Result;
3616}
3617
Richard Smith8ca78a12013-06-13 02:02:51 +00003618static void diagnoseDynamicExceptionSpecification(
Craig Toppere335f252015-10-04 04:53:55 +00003619 Parser &P, SourceRange Range, bool IsNoexcept) {
Richard Smith8ca78a12013-06-13 02:02:51 +00003620 if (P.getLangOpts().CPlusPlus11) {
3621 const char *Replacement = IsNoexcept ? "noexcept" : "noexcept(false)";
Richard Smith82da19d2016-12-08 02:49:07 +00003622 P.Diag(Range.getBegin(),
3623 P.getLangOpts().CPlusPlus1z && !IsNoexcept
3624 ? diag::ext_dynamic_exception_spec
3625 : diag::warn_exception_spec_deprecated)
3626 << Range;
Richard Smith8ca78a12013-06-13 02:02:51 +00003627 P.Diag(Range.getBegin(), diag::note_exception_spec_deprecated)
3628 << Replacement << FixItHint::CreateReplacement(Range, Replacement);
3629 }
3630}
3631
Sebastian Redl965b0e32011-03-05 14:45:16 +00003632/// ParseDynamicExceptionSpecification - Parse a C++
3633/// dynamic-exception-specification (C++ [except.spec]).
3634///
3635/// dynamic-exception-specification:
Douglas Gregor356513d2008-12-01 18:00:20 +00003636/// 'throw' '(' type-id-list [opt] ')'
3637/// [MS] 'throw' '(' '...' ')'
Mike Stump11289f42009-09-09 15:08:12 +00003638///
Douglas Gregor356513d2008-12-01 18:00:20 +00003639/// type-id-list:
Douglas Gregor830837d2010-12-20 23:57:46 +00003640/// type-id ... [opt]
3641/// type-id-list ',' type-id ... [opt]
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003642///
Sebastian Redl965b0e32011-03-05 14:45:16 +00003643ExceptionSpecificationType Parser::ParseDynamicExceptionSpecification(
3644 SourceRange &SpecificationRange,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003645 SmallVectorImpl<ParsedType> &Exceptions,
3646 SmallVectorImpl<SourceRange> &Ranges) {
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003647 assert(Tok.is(tok::kw_throw) && "expected throw");
Mike Stump11289f42009-09-09 15:08:12 +00003648
Sebastian Redl965b0e32011-03-05 14:45:16 +00003649 SpecificationRange.setBegin(ConsumeToken());
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003650 BalancedDelimiterTracker T(*this, tok::l_paren);
3651 if (T.consumeOpen()) {
Sebastian Redl965b0e32011-03-05 14:45:16 +00003652 Diag(Tok, diag::err_expected_lparen_after) << "throw";
3653 SpecificationRange.setEnd(SpecificationRange.getBegin());
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003654 return EST_DynamicNone;
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003655 }
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003656
Douglas Gregor356513d2008-12-01 18:00:20 +00003657 // Parse throw(...), a Microsoft extension that means "this function
3658 // can throw anything".
3659 if (Tok.is(tok::ellipsis)) {
3660 SourceLocation EllipsisLoc = ConsumeToken();
David Blaikiebbafb8a2012-03-11 07:00:24 +00003661 if (!getLangOpts().MicrosoftExt)
Douglas Gregor356513d2008-12-01 18:00:20 +00003662 Diag(EllipsisLoc, diag::ext_ellipsis_exception_spec);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003663 T.consumeClose();
3664 SpecificationRange.setEnd(T.getCloseLocation());
Richard Smith8ca78a12013-06-13 02:02:51 +00003665 diagnoseDynamicExceptionSpecification(*this, SpecificationRange, false);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003666 return EST_MSAny;
Douglas Gregor356513d2008-12-01 18:00:20 +00003667 }
3668
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003669 // Parse the sequence of type-ids.
Sebastian Redld6434562009-05-29 18:02:33 +00003670 SourceRange Range;
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003671 while (Tok.isNot(tok::r_paren)) {
Sebastian Redld6434562009-05-29 18:02:33 +00003672 TypeResult Res(ParseTypeName(&Range));
Sebastian Redl965b0e32011-03-05 14:45:16 +00003673
Douglas Gregor830837d2010-12-20 23:57:46 +00003674 if (Tok.is(tok::ellipsis)) {
3675 // C++0x [temp.variadic]p5:
3676 // - In a dynamic-exception-specification (15.4); the pattern is a
3677 // type-id.
3678 SourceLocation Ellipsis = ConsumeToken();
Sebastian Redl965b0e32011-03-05 14:45:16 +00003679 Range.setEnd(Ellipsis);
Douglas Gregor830837d2010-12-20 23:57:46 +00003680 if (!Res.isInvalid())
3681 Res = Actions.ActOnPackExpansion(Res.get(), Ellipsis);
3682 }
Sebastian Redl965b0e32011-03-05 14:45:16 +00003683
Sebastian Redld6434562009-05-29 18:02:33 +00003684 if (!Res.isInvalid()) {
Sebastian Redl2b9cacb2009-04-29 17:30:04 +00003685 Exceptions.push_back(Res.get());
Sebastian Redld6434562009-05-29 18:02:33 +00003686 Ranges.push_back(Range);
3687 }
Alp Toker97650562014-01-10 11:19:30 +00003688
3689 if (!TryConsumeToken(tok::comma))
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003690 break;
3691 }
3692
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003693 T.consumeClose();
3694 SpecificationRange.setEnd(T.getCloseLocation());
Richard Smith8ca78a12013-06-13 02:02:51 +00003695 diagnoseDynamicExceptionSpecification(*this, SpecificationRange,
3696 Exceptions.empty());
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003697 return Exceptions.empty() ? EST_DynamicNone : EST_Dynamic;
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003698}
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003699
Douglas Gregor7fb25412010-10-01 18:44:50 +00003700/// ParseTrailingReturnType - Parse a trailing return type on a new-style
3701/// function declaration.
Douglas Gregordb0b9f12011-08-04 15:30:47 +00003702TypeResult Parser::ParseTrailingReturnType(SourceRange &Range) {
Douglas Gregor7fb25412010-10-01 18:44:50 +00003703 assert(Tok.is(tok::arrow) && "expected arrow");
3704
3705 ConsumeToken();
3706
Richard Smithbfdb1082012-03-12 08:56:40 +00003707 return ParseTypeName(&Range, Declarator::TrailingReturnContext);
Douglas Gregor7fb25412010-10-01 18:44:50 +00003708}
3709
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003710/// \brief We have just started parsing the definition of a new class,
3711/// so push that class onto our stack of classes that is currently
3712/// being parsed.
John McCallc1465822011-02-14 07:13:47 +00003713Sema::ParsingClassState
John McCalldb632ac2012-09-25 07:32:39 +00003714Parser::PushParsingClass(Decl *ClassDecl, bool NonNestedClass,
3715 bool IsInterface) {
Douglas Gregoredf8f392010-01-16 20:52:59 +00003716 assert((NonNestedClass || !ClassStack.empty()) &&
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003717 "Nested class without outer class");
John McCalldb632ac2012-09-25 07:32:39 +00003718 ClassStack.push(new ParsingClass(ClassDecl, NonNestedClass, IsInterface));
John McCallc1465822011-02-14 07:13:47 +00003719 return Actions.PushParsingClass();
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003720}
3721
3722/// \brief Deallocate the given parsed class and all of its nested
3723/// classes.
3724void Parser::DeallocateParsedClasses(Parser::ParsingClass *Class) {
Douglas Gregorefc46952010-10-12 16:25:54 +00003725 for (unsigned I = 0, N = Class->LateParsedDeclarations.size(); I != N; ++I)
3726 delete Class->LateParsedDeclarations[I];
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003727 delete Class;
3728}
3729
3730/// \brief Pop the top class of the stack of classes that are
3731/// currently being parsed.
3732///
3733/// This routine should be called when we have finished parsing the
3734/// definition of a class, but have not yet popped the Scope
3735/// associated with the class's definition.
John McCallc1465822011-02-14 07:13:47 +00003736void Parser::PopParsingClass(Sema::ParsingClassState state) {
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003737 assert(!ClassStack.empty() && "Mismatched push/pop for class parsing");
Mike Stump11289f42009-09-09 15:08:12 +00003738
John McCallc1465822011-02-14 07:13:47 +00003739 Actions.PopParsingClass(state);
3740
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003741 ParsingClass *Victim = ClassStack.top();
3742 ClassStack.pop();
3743 if (Victim->TopLevelClass) {
3744 // Deallocate all of the nested classes of this class,
3745 // recursively: we don't need to keep any of this information.
3746 DeallocateParsedClasses(Victim);
3747 return;
Mike Stump11289f42009-09-09 15:08:12 +00003748 }
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003749 assert(!ClassStack.empty() && "Missing top-level class?");
3750
Douglas Gregorefc46952010-10-12 16:25:54 +00003751 if (Victim->LateParsedDeclarations.empty()) {
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003752 // The victim is a nested class, but we will not need to perform
3753 // any processing after the definition of this class since it has
3754 // no members whose handling was delayed. Therefore, we can just
3755 // remove this nested class.
Douglas Gregorefc46952010-10-12 16:25:54 +00003756 DeallocateParsedClasses(Victim);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003757 return;
3758 }
3759
3760 // This nested class has some members that will need to be processed
3761 // after the top-level class is completely defined. Therefore, add
3762 // it to the list of nested classes within its parent.
Douglas Gregor0be31a22010-07-02 17:43:08 +00003763 assert(getCurScope()->isClassScope() && "Nested class outside of class scope?");
Douglas Gregorefc46952010-10-12 16:25:54 +00003764 ClassStack.top()->LateParsedDeclarations.push_back(new LateParsedClass(this, Victim));
Douglas Gregor0be31a22010-07-02 17:43:08 +00003765 Victim->TemplateScope = getCurScope()->getParent()->isTemplateParamScope();
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003766}
Alexis Hunt96d5c762009-11-21 08:43:09 +00003767
Richard Smith3dff2512012-04-10 03:25:07 +00003768/// \brief Try to parse an 'identifier' which appears within an attribute-token.
3769///
3770/// \return the parsed identifier on success, and 0 if the next token is not an
3771/// attribute-token.
3772///
3773/// C++11 [dcl.attr.grammar]p3:
3774/// If a keyword or an alternative token that satisfies the syntactic
3775/// requirements of an identifier is contained in an attribute-token,
3776/// it is considered an identifier.
3777IdentifierInfo *Parser::TryParseCXX11AttributeIdentifier(SourceLocation &Loc) {
3778 switch (Tok.getKind()) {
3779 default:
3780 // Identifiers and keywords have identifier info attached.
David Majnemerd5271992015-01-09 18:09:39 +00003781 if (!Tok.isAnnotation()) {
3782 if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
3783 Loc = ConsumeToken();
3784 return II;
3785 }
Richard Smith3dff2512012-04-10 03:25:07 +00003786 }
Craig Topper161e4db2014-05-21 06:02:52 +00003787 return nullptr;
Richard Smith3dff2512012-04-10 03:25:07 +00003788
3789 case tok::ampamp: // 'and'
3790 case tok::pipe: // 'bitor'
3791 case tok::pipepipe: // 'or'
3792 case tok::caret: // 'xor'
3793 case tok::tilde: // 'compl'
3794 case tok::amp: // 'bitand'
3795 case tok::ampequal: // 'and_eq'
3796 case tok::pipeequal: // 'or_eq'
3797 case tok::caretequal: // 'xor_eq'
3798 case tok::exclaim: // 'not'
3799 case tok::exclaimequal: // 'not_eq'
3800 // Alternative tokens do not have identifier info, but their spelling
3801 // starts with an alphabetical character.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003802 SmallString<8> SpellingBuf;
Benjamin Kramer60be5632015-03-29 19:25:07 +00003803 SourceLocation SpellingLoc =
3804 PP.getSourceManager().getSpellingLoc(Tok.getLocation());
3805 StringRef Spelling = PP.getSpelling(SpellingLoc, SpellingBuf);
Jordan Rosea7d03842013-02-08 22:30:41 +00003806 if (isLetter(Spelling[0])) {
Richard Smith3dff2512012-04-10 03:25:07 +00003807 Loc = ConsumeToken();
Benjamin Kramer5c17f9c2012-04-22 20:43:30 +00003808 return &PP.getIdentifierTable().get(Spelling);
Richard Smith3dff2512012-04-10 03:25:07 +00003809 }
Craig Topper161e4db2014-05-21 06:02:52 +00003810 return nullptr;
Richard Smith3dff2512012-04-10 03:25:07 +00003811 }
3812}
3813
Michael Han23214e52012-10-03 01:56:22 +00003814static bool IsBuiltInOrStandardCXX11Attribute(IdentifierInfo *AttrName,
3815 IdentifierInfo *ScopeName) {
3816 switch (AttributeList::getKind(AttrName, ScopeName,
3817 AttributeList::AS_CXX11)) {
3818 case AttributeList::AT_CarriesDependency:
Aaron Ballman35f94212014-04-14 16:03:22 +00003819 case AttributeList::AT_Deprecated:
Michael Han23214e52012-10-03 01:56:22 +00003820 case AttributeList::AT_FallThrough:
Hans Wennborgdcfba332015-10-06 23:40:43 +00003821 case AttributeList::AT_CXX11NoReturn:
Michael Han23214e52012-10-03 01:56:22 +00003822 return true;
Aaron Ballmane7964782016-03-07 22:44:55 +00003823 case AttributeList::AT_WarnUnusedResult:
3824 return !ScopeName && AttrName->getName().equals("nodiscard");
Nico Weberac03bce2016-08-23 19:59:55 +00003825 case AttributeList::AT_Unused:
3826 return !ScopeName && AttrName->getName().equals("maybe_unused");
Michael Han23214e52012-10-03 01:56:22 +00003827 default:
3828 return false;
3829 }
3830}
3831
Aaron Ballmanb8e20392014-03-31 17:32:39 +00003832/// ParseCXX11AttributeArgs -- Parse a C++11 attribute-argument-clause.
3833///
3834/// [C++11] attribute-argument-clause:
3835/// '(' balanced-token-seq ')'
3836///
3837/// [C++11] balanced-token-seq:
3838/// balanced-token
3839/// balanced-token-seq balanced-token
3840///
3841/// [C++11] balanced-token:
3842/// '(' balanced-token-seq ')'
3843/// '[' balanced-token-seq ']'
3844/// '{' balanced-token-seq '}'
3845/// any token but '(', ')', '[', ']', '{', or '}'
3846bool Parser::ParseCXX11AttributeArgs(IdentifierInfo *AttrName,
3847 SourceLocation AttrNameLoc,
3848 ParsedAttributes &Attrs,
3849 SourceLocation *EndLoc,
3850 IdentifierInfo *ScopeName,
3851 SourceLocation ScopeLoc) {
3852 assert(Tok.is(tok::l_paren) && "Not a C++11 attribute argument list");
Aaron Ballman35f94212014-04-14 16:03:22 +00003853 SourceLocation LParenLoc = Tok.getLocation();
Aaron Ballmanb8e20392014-03-31 17:32:39 +00003854
3855 // If the attribute isn't known, we will not attempt to parse any
3856 // arguments.
3857 if (!hasAttribute(AttrSyntax::CXX, ScopeName, AttrName,
Bob Wilson7c730832015-07-20 22:57:31 +00003858 getTargetInfo(), getLangOpts())) {
Aaron Ballmanb8e20392014-03-31 17:32:39 +00003859 // Eat the left paren, then skip to the ending right paren.
3860 ConsumeParen();
3861 SkipUntil(tok::r_paren);
3862 return false;
3863 }
3864
Alex Lorenzd5d27e12017-03-01 18:06:25 +00003865 if (ScopeName && ScopeName->getName() == "gnu") {
Aaron Ballmanb8e20392014-03-31 17:32:39 +00003866 // GNU-scoped attributes have some special cases to handle GNU-specific
3867 // behaviors.
3868 ParseGNUAttributeArgs(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
Craig Topper161e4db2014-05-21 06:02:52 +00003869 ScopeLoc, AttributeList::AS_CXX11, nullptr);
Alex Lorenzd5d27e12017-03-01 18:06:25 +00003870 return true;
3871 }
3872
3873 unsigned NumArgs;
3874 // Some Clang-scoped attributes have some special parsing behavior.
3875 if (ScopeName && ScopeName->getName() == "clang")
3876 NumArgs =
3877 ParseClangAttributeArgs(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
3878 ScopeLoc, AttributeList::AS_CXX11);
3879 else
3880 NumArgs =
Aaron Ballman35f94212014-04-14 16:03:22 +00003881 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc,
3882 ScopeName, ScopeLoc, AttributeList::AS_CXX11);
Alex Lorenzd5d27e12017-03-01 18:06:25 +00003883
3884 const AttributeList *Attr = Attrs.getList();
3885 if (Attr && IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName)) {
3886 // If the attribute is a standard or built-in attribute and we are
3887 // parsing an argument list, we need to determine whether this attribute
3888 // was allowed to have an argument list (such as [[deprecated]]), and how
3889 // many arguments were parsed (so we can diagnose on [[deprecated()]]).
3890 if (Attr->getMaxArgs() && !NumArgs) {
3891 // The attribute was allowed to have arguments, but none were provided
3892 // even though the attribute parsed successfully. This is an error.
3893 Diag(LParenLoc, diag::err_attribute_requires_arguments) << AttrName;
3894 Attr->setInvalid(true);
3895 } else if (!Attr->getMaxArgs()) {
3896 // The attribute parsed successfully, but was not allowed to have any
3897 // arguments. It doesn't matter whether any were provided -- the
3898 // presence of the argument list (even if empty) is diagnosed.
3899 Diag(LParenLoc, diag::err_cxx11_attribute_forbids_arguments)
3900 << AttrName
3901 << FixItHint::CreateRemoval(SourceRange(LParenLoc, *EndLoc));
3902 Attr->setInvalid(true);
Aaron Ballman35f94212014-04-14 16:03:22 +00003903 }
3904 }
Aaron Ballmanb8e20392014-03-31 17:32:39 +00003905 return true;
3906}
3907
3908/// ParseCXX11AttributeSpecifier - Parse a C++11 attribute-specifier.
Alexis Hunt96d5c762009-11-21 08:43:09 +00003909///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003910/// [C++11] attribute-specifier:
Alexis Hunt96d5c762009-11-21 08:43:09 +00003911/// '[' '[' attribute-list ']' ']'
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00003912/// alignment-specifier
Alexis Hunt96d5c762009-11-21 08:43:09 +00003913///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003914/// [C++11] attribute-list:
Alexis Hunt96d5c762009-11-21 08:43:09 +00003915/// attribute[opt]
3916/// attribute-list ',' attribute[opt]
Richard Smith3dff2512012-04-10 03:25:07 +00003917/// attribute '...'
3918/// attribute-list ',' attribute '...'
Alexis Hunt96d5c762009-11-21 08:43:09 +00003919///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003920/// [C++11] attribute:
Alexis Hunt96d5c762009-11-21 08:43:09 +00003921/// attribute-token attribute-argument-clause[opt]
3922///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003923/// [C++11] attribute-token:
Alexis Hunt96d5c762009-11-21 08:43:09 +00003924/// identifier
3925/// attribute-scoped-token
3926///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003927/// [C++11] attribute-scoped-token:
Alexis Hunt96d5c762009-11-21 08:43:09 +00003928/// attribute-namespace '::' identifier
3929///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003930/// [C++11] attribute-namespace:
Alexis Hunt96d5c762009-11-21 08:43:09 +00003931/// identifier
Richard Smith3dff2512012-04-10 03:25:07 +00003932void Parser::ParseCXX11AttributeSpecifier(ParsedAttributes &attrs,
Peter Collingbourne49eedec2011-09-29 18:04:05 +00003933 SourceLocation *endLoc) {
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00003934 if (Tok.is(tok::kw_alignas)) {
Richard Smithf679b5b2011-10-14 20:48:27 +00003935 Diag(Tok.getLocation(), diag::warn_cxx98_compat_alignas);
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00003936 ParseAlignmentSpecifier(attrs, endLoc);
3937 return;
3938 }
3939
Alexis Hunt96d5c762009-11-21 08:43:09 +00003940 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square)
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003941 && "Not a C++11 attribute list");
Alexis Hunt96d5c762009-11-21 08:43:09 +00003942
Richard Smithf679b5b2011-10-14 20:48:27 +00003943 Diag(Tok.getLocation(), diag::warn_cxx98_compat_attribute);
3944
Alexis Hunt96d5c762009-11-21 08:43:09 +00003945 ConsumeBracket();
3946 ConsumeBracket();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003947
Richard Smithb7d7a042016-06-24 12:15:12 +00003948 SourceLocation CommonScopeLoc;
3949 IdentifierInfo *CommonScopeName = nullptr;
3950 if (Tok.is(tok::kw_using)) {
3951 Diag(Tok.getLocation(), getLangOpts().CPlusPlus1z
3952 ? diag::warn_cxx14_compat_using_attribute_ns
3953 : diag::ext_using_attribute_ns);
3954 ConsumeToken();
3955
3956 CommonScopeName = TryParseCXX11AttributeIdentifier(CommonScopeLoc);
3957 if (!CommonScopeName) {
3958 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
3959 SkipUntil(tok::r_square, tok::colon, StopBeforeMatch);
3960 }
3961 if (!TryConsumeToken(tok::colon) && CommonScopeName)
3962 Diag(Tok.getLocation(), diag::err_expected) << tok::colon;
3963 }
3964
Richard Smith10876ef2013-01-17 01:30:42 +00003965 llvm::SmallDenseMap<IdentifierInfo*, SourceLocation, 4> SeenAttrs;
3966
Richard Smith3dff2512012-04-10 03:25:07 +00003967 while (Tok.isNot(tok::r_square)) {
Alexis Hunt96d5c762009-11-21 08:43:09 +00003968 // attribute not present
Alp Toker97650562014-01-10 11:19:30 +00003969 if (TryConsumeToken(tok::comma))
Alexis Hunt96d5c762009-11-21 08:43:09 +00003970 continue;
Alexis Hunt96d5c762009-11-21 08:43:09 +00003971
Richard Smith3dff2512012-04-10 03:25:07 +00003972 SourceLocation ScopeLoc, AttrLoc;
Craig Topper161e4db2014-05-21 06:02:52 +00003973 IdentifierInfo *ScopeName = nullptr, *AttrName = nullptr;
Richard Smith3dff2512012-04-10 03:25:07 +00003974
3975 AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
3976 if (!AttrName)
3977 // Break out to the "expected ']'" diagnostic.
3978 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003979
Alexis Hunt96d5c762009-11-21 08:43:09 +00003980 // scoped attribute
Alp Toker97650562014-01-10 11:19:30 +00003981 if (TryConsumeToken(tok::coloncolon)) {
Richard Smith3dff2512012-04-10 03:25:07 +00003982 ScopeName = AttrName;
3983 ScopeLoc = AttrLoc;
3984
3985 AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
3986 if (!AttrName) {
Alp Tokerec543272013-12-24 09:48:30 +00003987 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
Alexey Bataevee6507d2013-11-18 08:17:37 +00003988 SkipUntil(tok::r_square, tok::comma, StopAtSemi | StopBeforeMatch);
Alexis Hunt96d5c762009-11-21 08:43:09 +00003989 continue;
3990 }
Alexis Hunt96d5c762009-11-21 08:43:09 +00003991 }
3992
Richard Smithb7d7a042016-06-24 12:15:12 +00003993 if (CommonScopeName) {
3994 if (ScopeName) {
3995 Diag(ScopeLoc, diag::err_using_attribute_ns_conflict)
3996 << SourceRange(CommonScopeLoc);
3997 } else {
3998 ScopeName = CommonScopeName;
3999 ScopeLoc = CommonScopeLoc;
4000 }
4001 }
4002
Aaron Ballmanb8e20392014-03-31 17:32:39 +00004003 bool StandardAttr = IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName);
Alexis Hunt96d5c762009-11-21 08:43:09 +00004004 bool AttrParsed = false;
Alexis Hunt96d5c762009-11-21 08:43:09 +00004005
Richard Smith10876ef2013-01-17 01:30:42 +00004006 if (StandardAttr &&
4007 !SeenAttrs.insert(std::make_pair(AttrName, AttrLoc)).second)
4008 Diag(AttrLoc, diag::err_cxx11_attribute_repeated)
Aaron Ballmanb8e20392014-03-31 17:32:39 +00004009 << AttrName << SourceRange(SeenAttrs[AttrName]);
Richard Smith10876ef2013-01-17 01:30:42 +00004010
Michael Han23214e52012-10-03 01:56:22 +00004011 // Parse attribute arguments
Aaron Ballman35f94212014-04-14 16:03:22 +00004012 if (Tok.is(tok::l_paren))
Aaron Ballmanb8e20392014-03-31 17:32:39 +00004013 AttrParsed = ParseCXX11AttributeArgs(AttrName, AttrLoc, attrs, endLoc,
4014 ScopeName, ScopeLoc);
Michael Han23214e52012-10-03 01:56:22 +00004015
4016 if (!AttrParsed)
Richard Smith84837d52012-05-03 18:27:39 +00004017 attrs.addNew(AttrName,
4018 SourceRange(ScopeLoc.isValid() ? ScopeLoc : AttrLoc,
4019 AttrLoc),
Craig Topper161e4db2014-05-21 06:02:52 +00004020 ScopeName, ScopeLoc, nullptr, 0, AttributeList::AS_CXX11);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004021
Alp Toker97650562014-01-10 11:19:30 +00004022 if (TryConsumeToken(tok::ellipsis))
Michael Han23214e52012-10-03 01:56:22 +00004023 Diag(Tok, diag::err_cxx11_attribute_forbids_ellipsis)
4024 << AttrName->getName();
Alexis Hunt96d5c762009-11-21 08:43:09 +00004025 }
4026
Alp Toker383d2c42014-01-01 03:08:43 +00004027 if (ExpectAndConsume(tok::r_square))
Alexey Bataevee6507d2013-11-18 08:17:37 +00004028 SkipUntil(tok::r_square);
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004029 if (endLoc)
4030 *endLoc = Tok.getLocation();
Alp Toker383d2c42014-01-01 03:08:43 +00004031 if (ExpectAndConsume(tok::r_square))
Alexey Bataevee6507d2013-11-18 08:17:37 +00004032 SkipUntil(tok::r_square);
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004033}
Alexis Hunt96d5c762009-11-21 08:43:09 +00004034
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00004035/// ParseCXX11Attributes - Parse a C++11 attribute-specifier-seq.
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004036///
4037/// attribute-specifier-seq:
4038/// attribute-specifier-seq[opt] attribute-specifier
Richard Smith3dff2512012-04-10 03:25:07 +00004039void Parser::ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004040 SourceLocation *endLoc) {
Richard Smith4cabd042013-02-22 09:15:49 +00004041 assert(getLangOpts().CPlusPlus11);
4042
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004043 SourceLocation StartLoc = Tok.getLocation(), Loc;
4044 if (!endLoc)
4045 endLoc = &Loc;
4046
Douglas Gregor6f981002011-10-07 20:35:25 +00004047 do {
Richard Smith3dff2512012-04-10 03:25:07 +00004048 ParseCXX11AttributeSpecifier(attrs, endLoc);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004049 } while (isCXX11AttributeSpecifier());
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004050
4051 attrs.Range = SourceRange(StartLoc, *endLoc);
Alexis Hunt96d5c762009-11-21 08:43:09 +00004052}
4053
Richard Smithc2c8bb82013-10-15 01:34:54 +00004054void Parser::DiagnoseAndSkipCXX11Attributes() {
Richard Smithc2c8bb82013-10-15 01:34:54 +00004055 // Start and end location of an attribute or an attribute list.
4056 SourceLocation StartLoc = Tok.getLocation();
Richard Smith955bf012014-06-19 11:42:00 +00004057 SourceLocation EndLoc = SkipCXX11Attributes();
4058
4059 if (EndLoc.isValid()) {
4060 SourceRange Range(StartLoc, EndLoc);
4061 Diag(StartLoc, diag::err_attributes_not_allowed)
4062 << Range;
4063 }
4064}
4065
4066SourceLocation Parser::SkipCXX11Attributes() {
Richard Smithc2c8bb82013-10-15 01:34:54 +00004067 SourceLocation EndLoc;
4068
Richard Smith955bf012014-06-19 11:42:00 +00004069 if (!isCXX11AttributeSpecifier())
4070 return EndLoc;
4071
Richard Smithc2c8bb82013-10-15 01:34:54 +00004072 do {
4073 if (Tok.is(tok::l_square)) {
4074 BalancedDelimiterTracker T(*this, tok::l_square);
4075 T.consumeOpen();
4076 T.skipToEnd();
4077 EndLoc = T.getCloseLocation();
4078 } else {
4079 assert(Tok.is(tok::kw_alignas) && "not an attribute specifier");
4080 ConsumeToken();
4081 BalancedDelimiterTracker T(*this, tok::l_paren);
4082 if (!T.consumeOpen())
4083 T.skipToEnd();
4084 EndLoc = T.getCloseLocation();
4085 }
4086 } while (isCXX11AttributeSpecifier());
4087
Richard Smith955bf012014-06-19 11:42:00 +00004088 return EndLoc;
Richard Smithc2c8bb82013-10-15 01:34:54 +00004089}
4090
Nico Weber05e1dad2016-09-03 03:25:22 +00004091/// Parse uuid() attribute when it appears in a [] Microsoft attribute.
4092void Parser::ParseMicrosoftUuidAttributeArgs(ParsedAttributes &Attrs) {
4093 assert(Tok.is(tok::identifier) && "Not a Microsoft attribute list");
4094 IdentifierInfo *UuidIdent = Tok.getIdentifierInfo();
4095 assert(UuidIdent->getName() == "uuid" && "Not a Microsoft attribute list");
4096
4097 SourceLocation UuidLoc = Tok.getLocation();
4098 ConsumeToken();
4099
4100 // Ignore the left paren location for now.
4101 BalancedDelimiterTracker T(*this, tok::l_paren);
4102 if (T.consumeOpen()) {
4103 Diag(Tok, diag::err_expected) << tok::l_paren;
4104 return;
4105 }
4106
4107 ArgsVector ArgExprs;
4108 if (Tok.is(tok::string_literal)) {
4109 // Easy case: uuid("...") -- quoted string.
4110 ExprResult StringResult = ParseStringLiteralExpression();
4111 if (StringResult.isInvalid())
4112 return;
4113 ArgExprs.push_back(StringResult.get());
4114 } else {
4115 // something like uuid({000000A0-0000-0000-C000-000000000049}) -- no
4116 // quotes in the parens. Just append the spelling of all tokens encountered
4117 // until the closing paren.
4118
4119 SmallString<42> StrBuffer; // 2 "", 36 bytes UUID, 2 optional {}, 1 nul
4120 StrBuffer += "\"";
4121
4122 // Since none of C++'s keywords match [a-f]+, accepting just tok::l_brace,
4123 // tok::r_brace, tok::minus, tok::identifier (think C000) and
4124 // tok::numeric_constant (0000) should be enough. But the spelling of the
4125 // uuid argument is checked later anyways, so there's no harm in accepting
4126 // almost anything here.
4127 // cl is very strict about whitespace in this form and errors out if any
4128 // is present, so check the space flags on the tokens.
4129 SourceLocation StartLoc = Tok.getLocation();
4130 while (Tok.isNot(tok::r_paren)) {
4131 if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
4132 Diag(Tok, diag::err_attribute_uuid_malformed_guid);
4133 SkipUntil(tok::r_paren, StopAtSemi);
4134 return;
4135 }
4136 SmallString<16> SpellingBuffer;
4137 SpellingBuffer.resize(Tok.getLength() + 1);
4138 bool Invalid = false;
4139 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
4140 if (Invalid) {
4141 SkipUntil(tok::r_paren, StopAtSemi);
4142 return;
4143 }
4144 StrBuffer += TokSpelling;
4145 ConsumeAnyToken();
4146 }
4147 StrBuffer += "\"";
4148
4149 if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
4150 Diag(Tok, diag::err_attribute_uuid_malformed_guid);
4151 ConsumeParen();
4152 return;
4153 }
4154
4155 // Pretend the user wrote the appropriate string literal here.
4156 // ActOnStringLiteral() copies the string data into the literal, so it's
4157 // ok that the Token points to StrBuffer.
4158 Token Toks[1];
4159 Toks[0].startToken();
4160 Toks[0].setKind(tok::string_literal);
4161 Toks[0].setLocation(StartLoc);
4162 Toks[0].setLiteralData(StrBuffer.data());
4163 Toks[0].setLength(StrBuffer.size());
4164 StringLiteral *UuidString =
4165 cast<StringLiteral>(Actions.ActOnStringLiteral(Toks, nullptr).get());
4166 ArgExprs.push_back(UuidString);
4167 }
4168
4169 if (!T.consumeClose()) {
Nico Weber05e1dad2016-09-03 03:25:22 +00004170 Attrs.addNew(UuidIdent, SourceRange(UuidLoc, T.getCloseLocation()), nullptr,
4171 SourceLocation(), ArgExprs.data(), ArgExprs.size(),
4172 AttributeList::AS_Microsoft);
4173 }
4174}
4175
David Majnemere4752e752015-07-08 05:55:00 +00004176/// ParseMicrosoftAttributes - Parse Microsoft attributes [Attr]
Francois Pichetc2bc5ac2010-10-11 12:59:39 +00004177///
4178/// [MS] ms-attribute:
4179/// '[' token-seq ']'
4180///
4181/// [MS] ms-attribute-seq:
4182/// ms-attribute[opt]
4183/// ms-attribute ms-attribute-seq
John McCall53fa7142010-12-24 02:08:15 +00004184void Parser::ParseMicrosoftAttributes(ParsedAttributes &attrs,
4185 SourceLocation *endLoc) {
Francois Pichetc2bc5ac2010-10-11 12:59:39 +00004186 assert(Tok.is(tok::l_square) && "Not a Microsoft attribute list");
4187
Saleem Abdulrasool425efcf2015-06-15 20:57:04 +00004188 do {
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004189 // FIXME: If this is actually a C++11 attribute, parse it as one.
Saleem Abdulrasool425efcf2015-06-15 20:57:04 +00004190 BalancedDelimiterTracker T(*this, tok::l_square);
4191 T.consumeOpen();
Nico Weber05e1dad2016-09-03 03:25:22 +00004192
4193 // Skip most ms attributes except for a whitelist.
4194 while (true) {
4195 SkipUntil(tok::r_square, tok::identifier, StopAtSemi | StopBeforeMatch);
4196 if (Tok.isNot(tok::identifier)) // ']', but also eof
4197 break;
4198 if (Tok.getIdentifierInfo()->getName() == "uuid")
4199 ParseMicrosoftUuidAttributeArgs(attrs);
4200 else
4201 ConsumeToken();
4202 }
4203
Saleem Abdulrasool425efcf2015-06-15 20:57:04 +00004204 T.consumeClose();
4205 if (endLoc)
4206 *endLoc = T.getCloseLocation();
4207 } while (Tok.is(tok::l_square));
Francois Pichetc2bc5ac2010-10-11 12:59:39 +00004208}
Francois Pichet8f981d52011-05-25 10:19:49 +00004209
4210void Parser::ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType,
4211 AccessSpecifier& CurAS) {
Douglas Gregor43edb322011-10-24 22:31:10 +00004212 IfExistsCondition Result;
Francois Pichet8f981d52011-05-25 10:19:49 +00004213 if (ParseMicrosoftIfExistsCondition(Result))
4214 return;
4215
Douglas Gregor43edb322011-10-24 22:31:10 +00004216 BalancedDelimiterTracker Braces(*this, tok::l_brace);
4217 if (Braces.consumeOpen()) {
Alp Tokerec543272013-12-24 09:48:30 +00004218 Diag(Tok, diag::err_expected) << tok::l_brace;
Francois Pichet8f981d52011-05-25 10:19:49 +00004219 return;
4220 }
Francois Pichet8f981d52011-05-25 10:19:49 +00004221
Douglas Gregor43edb322011-10-24 22:31:10 +00004222 switch (Result.Behavior) {
4223 case IEB_Parse:
4224 // Parse the declarations below.
4225 break;
4226
4227 case IEB_Dependent:
4228 Diag(Result.KeywordLoc, diag::warn_microsoft_dependent_exists)
4229 << Result.IsIfExists;
4230 // Fall through to skip.
Galina Kistanovad819d5b2017-06-01 21:19:06 +00004231 LLVM_FALLTHROUGH;
Douglas Gregor43edb322011-10-24 22:31:10 +00004232
4233 case IEB_Skip:
4234 Braces.skipToEnd();
Francois Pichet8f981d52011-05-25 10:19:49 +00004235 return;
4236 }
4237
Richard Smith34f30512013-11-23 04:06:09 +00004238 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
Francois Pichet8f981d52011-05-25 10:19:49 +00004239 // __if_exists, __if_not_exists can nest.
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00004240 if (Tok.isOneOf(tok::kw___if_exists, tok::kw___if_not_exists)) {
Francois Pichet8f981d52011-05-25 10:19:49 +00004241 ParseMicrosoftIfExistsClassDeclaration((DeclSpec::TST)TagType, CurAS);
4242 continue;
4243 }
4244
4245 // Check for extraneous top-level semicolon.
4246 if (Tok.is(tok::semi)) {
Richard Smith87f5dc52012-07-23 05:45:25 +00004247 ConsumeExtraSemi(InsideStruct, TagType);
Francois Pichet8f981d52011-05-25 10:19:49 +00004248 continue;
4249 }
4250
4251 AccessSpecifier AS = getAccessSpecifierIfPresent();
4252 if (AS != AS_none) {
4253 // Current token is a C++ access specifier.
4254 CurAS = AS;
4255 SourceLocation ASLoc = Tok.getLocation();
4256 ConsumeToken();
4257 if (Tok.is(tok::colon))
4258 Actions.ActOnAccessSpecifier(AS, ASLoc, Tok.getLocation());
4259 else
Alp Toker35d87032013-12-30 23:29:50 +00004260 Diag(Tok, diag::err_expected) << tok::colon;
Francois Pichet8f981d52011-05-25 10:19:49 +00004261 ConsumeToken();
4262 continue;
4263 }
4264
4265 // Parse all the comma separated declarators.
Craig Topper161e4db2014-05-21 06:02:52 +00004266 ParseCXXClassMemberDeclaration(CurAS, nullptr);
Francois Pichet8f981d52011-05-25 10:19:49 +00004267 }
Douglas Gregor43edb322011-10-24 22:31:10 +00004268
4269 Braces.consumeClose();
Francois Pichet8f981d52011-05-25 10:19:49 +00004270}