blob: 343b5f1a17229c0377e6bcf08ead517a8aae436b [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
John McCalldadc5752010-08-24 06:29:42 +0000843 ExprResult AssertExpr(ParseConstantExpression());
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000844 if (AssertExpr.isInvalid()) {
Richard Smith76965712012-09-13 19:12:50 +0000845 SkipMalformedDecl();
Craig Topper161e4db2014-05-21 06:02:52 +0000846 return nullptr;
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000847 }
Mike Stump11289f42009-09-09 15:08:12 +0000848
Richard Smith085a64f2014-06-20 19:57:12 +0000849 ExprResult AssertMessage;
850 if (Tok.is(tok::r_paren)) {
851 Diag(Tok, getLangOpts().CPlusPlus1z
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000852 ? diag::warn_cxx14_compat_static_assert_no_message
Richard Smith085a64f2014-06-20 19:57:12 +0000853 : diag::ext_static_assert_no_message)
854 << (getLangOpts().CPlusPlus1z
855 ? FixItHint()
856 : FixItHint::CreateInsertion(Tok.getLocation(), ", \"\""));
857 } else {
858 if (ExpectAndConsume(tok::comma)) {
859 SkipUntil(tok::semi);
860 return nullptr;
861 }
Anders Carlssonb4cf3ad2009-03-13 23:29:20 +0000862
Richard Smith085a64f2014-06-20 19:57:12 +0000863 if (!isTokenStringLiteral()) {
864 Diag(Tok, diag::err_expected_string_literal)
865 << /*Source='static_assert'*/1;
866 SkipMalformedDecl();
867 return nullptr;
868 }
Mike Stump11289f42009-09-09 15:08:12 +0000869
Richard Smith085a64f2014-06-20 19:57:12 +0000870 AssertMessage = ParseStringLiteralExpression();
871 if (AssertMessage.isInvalid()) {
872 SkipMalformedDecl();
873 return nullptr;
874 }
Richard Smithd67aea22012-03-06 03:21:47 +0000875 }
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000876
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000877 T.consumeClose();
Mike Stump11289f42009-09-09 15:08:12 +0000878
Chris Lattner49836b42009-04-02 04:16:50 +0000879 DeclEnd = Tok.getLocation();
Douglas Gregor45d6bdf2010-09-07 15:23:11 +0000880 ExpectAndConsumeSemi(diag::err_expected_semi_after_static_assert);
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000881
John McCallb268a282010-08-23 23:25:46 +0000882 return Actions.ActOnStaticAssertDeclaration(StaticAssertLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000883 AssertExpr.get(),
884 AssertMessage.get(),
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000885 T.getCloseLocation());
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000886}
887
Richard Smith74aeef52013-04-26 16:15:35 +0000888/// ParseDecltypeSpecifier - Parse a C++11 decltype specifier.
Anders Carlsson74948d02009-06-24 17:47:40 +0000889///
890/// 'decltype' ( expression )
Richard Smith74aeef52013-04-26 16:15:35 +0000891/// 'decltype' ( 'auto' ) [C++1y]
Anders Carlsson74948d02009-06-24 17:47:40 +0000892///
David Blaikie15a430a2011-12-04 05:04:18 +0000893SourceLocation Parser::ParseDecltypeSpecifier(DeclSpec &DS) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000894 assert(Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)
David Blaikie15a430a2011-12-04 05:04:18 +0000895 && "Not a decltype specifier");
896
David Blaikie15a430a2011-12-04 05:04:18 +0000897 ExprResult Result;
898 SourceLocation StartLoc = Tok.getLocation();
899 SourceLocation EndLoc;
900
901 if (Tok.is(tok::annot_decltype)) {
902 Result = getExprAnnotation(Tok);
903 EndLoc = Tok.getAnnotationEndLoc();
904 ConsumeToken();
905 if (Result.isInvalid()) {
906 DS.SetTypeSpecError();
907 return EndLoc;
908 }
909 } else {
Richard Smith324df552012-02-24 22:30:04 +0000910 if (Tok.getIdentifierInfo()->isStr("decltype"))
911 Diag(Tok, diag::warn_cxx98_compat_decltype);
Richard Smithfd3da932012-02-24 18:10:23 +0000912
David Blaikie15a430a2011-12-04 05:04:18 +0000913 ConsumeToken();
914
915 BalancedDelimiterTracker T(*this, tok::l_paren);
916 if (T.expectAndConsume(diag::err_expected_lparen_after,
917 "decltype", tok::r_paren)) {
918 DS.SetTypeSpecError();
919 return T.getOpenLocation() == Tok.getLocation() ?
920 StartLoc : T.getOpenLocation();
921 }
922
Richard Smith74aeef52013-04-26 16:15:35 +0000923 // Check for C++1y 'decltype(auto)'.
924 if (Tok.is(tok::kw_auto)) {
925 // No need to disambiguate here: an expression can't start with 'auto',
926 // because the typename-specifier in a function-style cast operation can't
927 // be 'auto'.
928 Diag(Tok.getLocation(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000929 getLangOpts().CPlusPlus14
Richard Smith74aeef52013-04-26 16:15:35 +0000930 ? diag::warn_cxx11_compat_decltype_auto_type_specifier
931 : diag::ext_decltype_auto_type_specifier);
932 ConsumeToken();
933 } else {
934 // Parse the expression
David Blaikie15a430a2011-12-04 05:04:18 +0000935
Richard Smith74aeef52013-04-26 16:15:35 +0000936 // C++11 [dcl.type.simple]p4:
937 // The operand of the decltype specifier is an unevaluated operand.
938 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
Craig Topper161e4db2014-05-21 06:02:52 +0000939 nullptr,/*IsDecltype=*/true);
Kaelyn Takata5cc85352015-04-10 19:16:46 +0000940 Result =
941 Actions.CorrectDelayedTyposInExpr(ParseExpression(), [](Expr *E) {
942 return E->hasPlaceholderType() ? ExprError() : E;
943 });
Richard Smith74aeef52013-04-26 16:15:35 +0000944 if (Result.isInvalid()) {
945 DS.SetTypeSpecError();
Alexey Bataevee6507d2013-11-18 08:17:37 +0000946 if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch)) {
Richard Smith74aeef52013-04-26 16:15:35 +0000947 EndLoc = ConsumeParen();
Argyrios Kyrtzidisc38395a2012-10-26 22:53:44 +0000948 } else {
Richard Smith74aeef52013-04-26 16:15:35 +0000949 if (PP.isBacktrackEnabled() && Tok.is(tok::semi)) {
950 // Backtrack to get the location of the last token before the semi.
951 PP.RevertCachedTokens(2);
952 ConsumeToken(); // the semi.
953 EndLoc = ConsumeAnyToken();
954 assert(Tok.is(tok::semi));
955 } else {
956 EndLoc = Tok.getLocation();
957 }
Argyrios Kyrtzidisc38395a2012-10-26 22:53:44 +0000958 }
Richard Smith74aeef52013-04-26 16:15:35 +0000959 return EndLoc;
Argyrios Kyrtzidisc38395a2012-10-26 22:53:44 +0000960 }
Richard Smith74aeef52013-04-26 16:15:35 +0000961
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000962 Result = Actions.ActOnDecltypeExpression(Result.get());
David Blaikie15a430a2011-12-04 05:04:18 +0000963 }
964
965 // Match the ')'
966 T.consumeClose();
967 if (T.getCloseLocation().isInvalid()) {
968 DS.SetTypeSpecError();
969 // FIXME: this should return the location of the last token
970 // that was consumed (by "consumeClose()")
971 return T.getCloseLocation();
972 }
973
Richard Smithfd555f62012-02-22 02:04:18 +0000974 if (Result.isInvalid()) {
975 DS.SetTypeSpecError();
976 return T.getCloseLocation();
977 }
978
David Blaikie15a430a2011-12-04 05:04:18 +0000979 EndLoc = T.getCloseLocation();
Anders Carlsson74948d02009-06-24 17:47:40 +0000980 }
Richard Smith74aeef52013-04-26 16:15:35 +0000981 assert(!Result.isInvalid());
Mike Stump11289f42009-09-09 15:08:12 +0000982
Craig Topper161e4db2014-05-21 06:02:52 +0000983 const char *PrevSpec = nullptr;
John McCall49bfce42009-08-03 20:12:06 +0000984 unsigned DiagID;
Erik Verbruggen888d52a2014-01-15 09:15:43 +0000985 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
Anders Carlsson74948d02009-06-24 17:47:40 +0000986 // Check for duplicate type specifiers (e.g. "int decltype(a)").
Richard Smith74aeef52013-04-26 16:15:35 +0000987 if (Result.get()
988 ? DS.SetTypeSpecType(DeclSpec::TST_decltype, StartLoc, PrevSpec,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000989 DiagID, Result.get(), Policy)
Richard Smith74aeef52013-04-26 16:15:35 +0000990 : DS.SetTypeSpecType(DeclSpec::TST_decltype_auto, StartLoc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +0000991 DiagID, Policy)) {
John McCall49bfce42009-08-03 20:12:06 +0000992 Diag(StartLoc, DiagID) << PrevSpec;
David Blaikie15a430a2011-12-04 05:04:18 +0000993 DS.SetTypeSpecError();
994 }
995 return EndLoc;
996}
997
998void Parser::AnnotateExistingDecltypeSpecifier(const DeclSpec& DS,
999 SourceLocation StartLoc,
1000 SourceLocation EndLoc) {
1001 // make sure we have a token we can turn into an annotation token
1002 if (PP.isBacktrackEnabled())
1003 PP.RevertCachedTokens(1);
1004 else
1005 PP.EnterToken(Tok);
1006
1007 Tok.setKind(tok::annot_decltype);
Richard Smith74aeef52013-04-26 16:15:35 +00001008 setExprAnnotation(Tok,
1009 DS.getTypeSpecType() == TST_decltype ? DS.getRepAsExpr() :
1010 DS.getTypeSpecType() == TST_decltype_auto ? ExprResult() :
1011 ExprError());
David Blaikie15a430a2011-12-04 05:04:18 +00001012 Tok.setAnnotationEndLoc(EndLoc);
1013 Tok.setLocation(StartLoc);
1014 PP.AnnotateCachedTokens(Tok);
Anders Carlsson74948d02009-06-24 17:47:40 +00001015}
1016
Alexis Hunt4a257072011-05-19 05:37:45 +00001017void Parser::ParseUnderlyingTypeSpecifier(DeclSpec &DS) {
1018 assert(Tok.is(tok::kw___underlying_type) &&
1019 "Not an underlying type specifier");
1020
1021 SourceLocation StartLoc = ConsumeToken();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001022 BalancedDelimiterTracker T(*this, tok::l_paren);
1023 if (T.expectAndConsume(diag::err_expected_lparen_after,
1024 "__underlying_type", tok::r_paren)) {
Alexis Hunt4a257072011-05-19 05:37:45 +00001025 return;
1026 }
1027
1028 TypeResult Result = ParseTypeName();
1029 if (Result.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00001030 SkipUntil(tok::r_paren, StopAtSemi);
Alexis Hunt4a257072011-05-19 05:37:45 +00001031 return;
1032 }
1033
1034 // Match the ')'
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001035 T.consumeClose();
1036 if (T.getCloseLocation().isInvalid())
Alexis Hunt4a257072011-05-19 05:37:45 +00001037 return;
1038
Craig Topper161e4db2014-05-21 06:02:52 +00001039 const char *PrevSpec = nullptr;
Alexis Hunt4a257072011-05-19 05:37:45 +00001040 unsigned DiagID;
Alexis Hunte852b102011-05-24 22:41:36 +00001041 if (DS.SetTypeSpecType(DeclSpec::TST_underlyingType, StartLoc, PrevSpec,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001042 DiagID, Result.get(),
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001043 Actions.getASTContext().getPrintingPolicy()))
Alexis Hunt4a257072011-05-19 05:37:45 +00001044 Diag(StartLoc, DiagID) << PrevSpec;
Enea Zaffanellaa90af722013-07-06 18:54:58 +00001045 DS.setTypeofParensRange(T.getRange());
Alexis Hunt4a257072011-05-19 05:37:45 +00001046}
1047
David Blaikie00ee7a082011-10-25 15:01:20 +00001048/// ParseBaseTypeSpecifier - Parse a C++ base-type-specifier which is either a
1049/// class name or decltype-specifier. Note that we only check that the result
1050/// names a type; semantic analysis will need to verify that the type names a
1051/// class. The result is either a type or null, depending on whether a type
1052/// name was found.
Douglas Gregor831c93f2008-11-05 20:51:48 +00001053///
Richard Smith4c96e992013-02-19 23:47:15 +00001054/// base-type-specifier: [C++11 class.derived]
David Blaikie00ee7a082011-10-25 15:01:20 +00001055/// class-or-decltype
Richard Smith4c96e992013-02-19 23:47:15 +00001056/// class-or-decltype: [C++11 class.derived]
David Blaikie00ee7a082011-10-25 15:01:20 +00001057/// nested-name-specifier[opt] class-name
1058/// decltype-specifier
Richard Smith4c96e992013-02-19 23:47:15 +00001059/// class-name: [C++ class.name]
Douglas Gregor831c93f2008-11-05 20:51:48 +00001060/// identifier
Douglas Gregord54dfb82009-02-25 23:52:28 +00001061/// simple-template-id
Mike Stump11289f42009-09-09 15:08:12 +00001062///
Richard Smith4c96e992013-02-19 23:47:15 +00001063/// In C++98, instead of base-type-specifier, we have:
1064///
1065/// ::[opt] nested-name-specifier[opt] class-name
Craig Topper9ad7e262014-10-31 06:57:07 +00001066TypeResult Parser::ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
1067 SourceLocation &EndLocation) {
David Blaikiedd58d4c2011-10-25 18:46:41 +00001068 // Ignore attempts to use typename
1069 if (Tok.is(tok::kw_typename)) {
1070 Diag(Tok, diag::err_expected_class_name_not_template)
1071 << FixItHint::CreateRemoval(Tok.getLocation());
1072 ConsumeToken();
1073 }
1074
David Blaikieafa155f2011-10-25 18:17:58 +00001075 // Parse optional nested-name-specifier
1076 CXXScopeSpec SS;
David Blaikieefdccaa2016-01-15 23:43:34 +00001077 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false);
David Blaikieafa155f2011-10-25 18:17:58 +00001078
1079 BaseLoc = Tok.getLocation();
1080
David Blaikie1cd50022011-10-25 17:10:12 +00001081 // Parse decltype-specifier
David Blaikie15a430a2011-12-04 05:04:18 +00001082 // tok == kw_decltype is just error recovery, it can only happen when SS
1083 // isn't empty
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001084 if (Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)) {
David Blaikieafa155f2011-10-25 18:17:58 +00001085 if (SS.isNotEmpty())
1086 Diag(SS.getBeginLoc(), diag::err_unexpected_scope_on_base_decltype)
1087 << FixItHint::CreateRemoval(SS.getRange());
David Blaikie1cd50022011-10-25 17:10:12 +00001088 // Fake up a Declarator to use with ActOnTypeName.
1089 DeclSpec DS(AttrFactory);
1090
David Blaikie7491e732011-12-08 04:53:15 +00001091 EndLocation = ParseDecltypeSpecifier(DS);
David Blaikie1cd50022011-10-25 17:10:12 +00001092
1093 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1094 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
1095 }
1096
Douglas Gregord54dfb82009-02-25 23:52:28 +00001097 // Check whether we have a template-id that names a type.
1098 if (Tok.is(tok::annot_template_id)) {
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00001099 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregor46c59612010-01-12 17:52:59 +00001100 if (TemplateId->Kind == TNK_Type_template ||
1101 TemplateId->Kind == TNK_Dependent_template_name) {
Richard Smith62559bd2017-02-01 21:36:38 +00001102 AnnotateTemplateIdTokenAsType(/*IsClassName*/true);
Douglas Gregord54dfb82009-02-25 23:52:28 +00001103
1104 assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
John McCallba7bf592010-08-24 05:47:05 +00001105 ParsedType Type = getTypeAnnotation(Tok);
Douglas Gregord54dfb82009-02-25 23:52:28 +00001106 EndLocation = Tok.getAnnotationEndLoc();
1107 ConsumeToken();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001108
1109 if (Type)
1110 return Type;
1111 return true;
Douglas Gregord54dfb82009-02-25 23:52:28 +00001112 }
1113
1114 // Fall through to produce an error below.
1115 }
1116
Douglas Gregor831c93f2008-11-05 20:51:48 +00001117 if (Tok.isNot(tok::identifier)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00001118 Diag(Tok, diag::err_expected_class_name);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001119 return true;
Douglas Gregor831c93f2008-11-05 20:51:48 +00001120 }
1121
Douglas Gregor18473f32010-01-12 21:28:44 +00001122 IdentifierInfo *Id = Tok.getIdentifierInfo();
1123 SourceLocation IdLoc = ConsumeToken();
1124
1125 if (Tok.is(tok::less)) {
1126 // It looks the user intended to write a template-id here, but the
1127 // template-name was wrong. Try to fix that.
1128 TemplateNameKind TNK = TNK_Type_template;
1129 TemplateTy Template;
Douglas Gregor0be31a22010-07-02 17:43:08 +00001130 if (!Actions.DiagnoseUnknownTemplateName(*Id, IdLoc, getCurScope(),
Douglas Gregore7c20652011-03-02 00:47:37 +00001131 &SS, Template, TNK)) {
Douglas Gregor18473f32010-01-12 21:28:44 +00001132 Diag(IdLoc, diag::err_unknown_template_name)
1133 << Id;
1134 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001135
Serge Pavlovb716b3c2013-08-10 05:54:47 +00001136 if (!Template) {
1137 TemplateArgList TemplateArgs;
1138 SourceLocation LAngleLoc, RAngleLoc;
David Blaikiee20506d2016-01-15 23:43:28 +00001139 ParseTemplateIdAfterTemplateName(nullptr, IdLoc, SS, true, LAngleLoc,
1140 TemplateArgs, RAngleLoc);
Douglas Gregor18473f32010-01-12 21:28:44 +00001141 return true;
Serge Pavlovb716b3c2013-08-10 05:54:47 +00001142 }
Douglas Gregor18473f32010-01-12 21:28:44 +00001143
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001144 // Form the template name
Douglas Gregor18473f32010-01-12 21:28:44 +00001145 UnqualifiedId TemplateName;
1146 TemplateName.setIdentifier(Id, IdLoc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001147
Douglas Gregor18473f32010-01-12 21:28:44 +00001148 // Parse the full template-id, then turn it into a type.
Abramo Bagnara7945c982012-01-27 09:46:47 +00001149 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
Richard Smith62559bd2017-02-01 21:36:38 +00001150 TemplateName))
Douglas Gregor18473f32010-01-12 21:28:44 +00001151 return true;
Richard Smith62559bd2017-02-01 21:36:38 +00001152 if (TNK == TNK_Type_template || TNK == TNK_Dependent_template_name)
1153 AnnotateTemplateIdTokenAsType(/*IsClassName*/true);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001154
Douglas Gregor18473f32010-01-12 21:28:44 +00001155 // If we didn't end up with a typename token, there's nothing more we
1156 // can do.
1157 if (Tok.isNot(tok::annot_typename))
1158 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001159
Douglas Gregor18473f32010-01-12 21:28:44 +00001160 // Retrieve the type from the annotation token, consume that token, and
1161 // return.
1162 EndLocation = Tok.getAnnotationEndLoc();
John McCallba7bf592010-08-24 05:47:05 +00001163 ParsedType Type = getTypeAnnotation(Tok);
Douglas Gregor18473f32010-01-12 21:28:44 +00001164 ConsumeToken();
1165 return Type;
1166 }
1167
Douglas Gregor831c93f2008-11-05 20:51:48 +00001168 // We have an identifier; check whether it is actually a type.
Craig Topper161e4db2014-05-21 06:02:52 +00001169 IdentifierInfo *CorrectedII = nullptr;
Richard Smith600b5262017-01-26 20:40:47 +00001170 ParsedType Type = Actions.getTypeName(
Richard Smith62559bd2017-02-01 21:36:38 +00001171 *Id, IdLoc, getCurScope(), &SS, /*IsClassName=*/true, false, nullptr,
Richard Smith600b5262017-01-26 20:40:47 +00001172 /*IsCtorOrDtorName=*/false,
1173 /*NonTrivialTypeSourceInfo=*/true,
1174 /*IsClassTemplateDeductionContext*/ false, &CorrectedII);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001175 if (!Type) {
Douglas Gregorfe17d252010-02-16 19:09:40 +00001176 Diag(IdLoc, diag::err_expected_class_name);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001177 return true;
Douglas Gregor831c93f2008-11-05 20:51:48 +00001178 }
1179
1180 // Consume the identifier.
Douglas Gregor18473f32010-01-12 21:28:44 +00001181 EndLocation = IdLoc;
Nick Lewycky19b9f952010-07-26 16:56:01 +00001182
1183 // Fake up a Declarator to use with ActOnTypeName.
John McCall084e83d2011-03-24 11:26:52 +00001184 DeclSpec DS(AttrFactory);
Nick Lewycky19b9f952010-07-26 16:56:01 +00001185 DS.SetRangeStart(IdLoc);
1186 DS.SetRangeEnd(EndLocation);
Douglas Gregore7c20652011-03-02 00:47:37 +00001187 DS.getTypeSpecScope() = SS;
Nick Lewycky19b9f952010-07-26 16:56:01 +00001188
Craig Topper161e4db2014-05-21 06:02:52 +00001189 const char *PrevSpec = nullptr;
Nick Lewycky19b9f952010-07-26 16:56:01 +00001190 unsigned DiagID;
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001191 DS.SetTypeSpecType(TST_typename, IdLoc, PrevSpec, DiagID, Type,
1192 Actions.getASTContext().getPrintingPolicy());
Nick Lewycky19b9f952010-07-26 16:56:01 +00001193
1194 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1195 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
Douglas Gregor831c93f2008-11-05 20:51:48 +00001196}
1197
John McCall8d32c052012-05-22 21:28:12 +00001198void Parser::ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001199 while (Tok.isOneOf(tok::kw___single_inheritance,
1200 tok::kw___multiple_inheritance,
1201 tok::kw___virtual_inheritance)) {
John McCall8d32c052012-05-22 21:28:12 +00001202 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
1203 SourceLocation AttrNameLoc = ConsumeToken();
Craig Topper161e4db2014-05-21 06:02:52 +00001204 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
Aaron Ballman8edb5c22013-12-18 23:44:18 +00001205 AttributeList::AS_Keyword);
John McCall8d32c052012-05-22 21:28:12 +00001206 }
1207}
1208
Richard Smith369b9f92012-06-25 21:37:02 +00001209/// Determine whether the following tokens are valid after a type-specifier
1210/// which could be a standalone declaration. This will conservatively return
1211/// true if there's any doubt, and is appropriate for insert-';' fixits.
Richard Smith200f47c2012-07-02 19:14:01 +00001212bool Parser::isValidAfterTypeSpecifier(bool CouldBeBitfield) {
Richard Smith369b9f92012-06-25 21:37:02 +00001213 // This switch enumerates the valid "follow" set for type-specifiers.
1214 switch (Tok.getKind()) {
1215 default: break;
1216 case tok::semi: // struct foo {...} ;
1217 case tok::star: // struct foo {...} * P;
1218 case tok::amp: // struct foo {...} & R = ...
Richard Smith1ac67d12013-01-19 03:48:05 +00001219 case tok::ampamp: // struct foo {...} && R = ...
Richard Smith369b9f92012-06-25 21:37:02 +00001220 case tok::identifier: // struct foo {...} V ;
1221 case tok::r_paren: //(struct foo {...} ) {4}
1222 case tok::annot_cxxscope: // struct foo {...} a:: b;
1223 case tok::annot_typename: // struct foo {...} a ::b;
1224 case tok::annot_template_id: // struct foo {...} a<int> ::b;
1225 case tok::l_paren: // struct foo {...} ( x);
1226 case tok::comma: // __builtin_offsetof(struct foo{...} ,
Richard Smith1ac67d12013-01-19 03:48:05 +00001227 case tok::kw_operator: // struct foo operator ++() {...}
Alp Tokerd3f79c52013-11-24 20:24:54 +00001228 case tok::kw___declspec: // struct foo {...} __declspec(...)
Richard Smith843f18f2014-08-13 02:13:15 +00001229 case tok::l_square: // void f(struct f [ 3])
1230 case tok::ellipsis: // void f(struct f ... [Ns])
Abramo Bagnara152eb392014-08-16 08:29:27 +00001231 // FIXME: we should emit semantic diagnostic when declaration
1232 // attribute is in type attribute position.
1233 case tok::kw___attribute: // struct foo __attribute__((used)) x;
David Majnemer15b311c2016-06-14 03:20:28 +00001234 case tok::annot_pragma_pack: // struct foo {...} _Pragma(pack(pop));
1235 // struct foo {...} _Pragma(section(...));
1236 case tok::annot_pragma_ms_pragma:
1237 // struct foo {...} _Pragma(vtordisp(pop));
1238 case tok::annot_pragma_ms_vtordisp:
1239 // struct foo {...} _Pragma(pointers_to_members(...));
1240 case tok::annot_pragma_ms_pointers_to_members:
Richard Smith369b9f92012-06-25 21:37:02 +00001241 return true;
Richard Smith200f47c2012-07-02 19:14:01 +00001242 case tok::colon:
1243 return CouldBeBitfield; // enum E { ... } : 2;
Reid Klecknercfa91552016-03-21 16:08:49 +00001244 // Microsoft compatibility
1245 case tok::kw___cdecl: // struct foo {...} __cdecl x;
1246 case tok::kw___fastcall: // struct foo {...} __fastcall x;
1247 case tok::kw___stdcall: // struct foo {...} __stdcall x;
1248 case tok::kw___thiscall: // struct foo {...} __thiscall x;
1249 case tok::kw___vectorcall: // struct foo {...} __vectorcall x;
1250 // We will diagnose these calling-convention specifiers on non-function
1251 // declarations later, so claim they are valid after a type specifier.
1252 return getLangOpts().MicrosoftExt;
Richard Smith369b9f92012-06-25 21:37:02 +00001253 // Type qualifiers
1254 case tok::kw_const: // struct foo {...} const x;
1255 case tok::kw_volatile: // struct foo {...} volatile x;
1256 case tok::kw_restrict: // struct foo {...} restrict x;
Richard Smith843f18f2014-08-13 02:13:15 +00001257 case tok::kw__Atomic: // struct foo {...} _Atomic x;
Nico Rieck3e1ee832014-12-04 23:30:25 +00001258 case tok::kw___unaligned: // struct foo {...} __unaligned *x;
Richard Smith1ac67d12013-01-19 03:48:05 +00001259 // Function specifiers
1260 // Note, no 'explicit'. An explicit function must be either a conversion
1261 // operator or a constructor. Either way, it can't have a return type.
1262 case tok::kw_inline: // struct foo inline f();
1263 case tok::kw_virtual: // struct foo virtual f();
1264 case tok::kw_friend: // struct foo friend f();
Richard Smith369b9f92012-06-25 21:37:02 +00001265 // Storage-class specifiers
1266 case tok::kw_static: // struct foo {...} static x;
1267 case tok::kw_extern: // struct foo {...} extern x;
1268 case tok::kw_typedef: // struct foo {...} typedef x;
1269 case tok::kw_register: // struct foo {...} register x;
1270 case tok::kw_auto: // struct foo {...} auto x;
1271 case tok::kw_mutable: // struct foo {...} mutable x;
Richard Smith1ac67d12013-01-19 03:48:05 +00001272 case tok::kw_thread_local: // struct foo {...} thread_local x;
Richard Smith369b9f92012-06-25 21:37:02 +00001273 case tok::kw_constexpr: // struct foo {...} constexpr x;
1274 // As shown above, type qualifiers and storage class specifiers absolutely
1275 // can occur after class specifiers according to the grammar. However,
1276 // almost no one actually writes code like this. If we see one of these,
1277 // it is much more likely that someone missed a semi colon and the
1278 // type/storage class specifier we're seeing is part of the *next*
1279 // intended declaration, as in:
1280 //
1281 // struct foo { ... }
1282 // typedef int X;
1283 //
1284 // We'd really like to emit a missing semicolon error instead of emitting
1285 // an error on the 'int' saying that you can't have two type specifiers in
1286 // the same declaration of X. Because of this, we look ahead past this
1287 // token to see if it's a type specifier. If so, we know the code is
1288 // otherwise invalid, so we can produce the expected semi error.
1289 if (!isKnownToBeTypeSpecifier(NextToken()))
1290 return true;
1291 break;
1292 case tok::r_brace: // struct bar { struct foo {...} }
1293 // Missing ';' at end of struct is accepted as an extension in C mode.
1294 if (!getLangOpts().CPlusPlus)
1295 return true;
1296 break;
Richard Smith52c5b872013-01-29 04:13:32 +00001297 case tok::greater:
1298 // template<class T = class X>
1299 return getLangOpts().CPlusPlus;
Richard Smith369b9f92012-06-25 21:37:02 +00001300 }
1301 return false;
1302}
1303
Douglas Gregor556877c2008-04-13 21:30:24 +00001304/// ParseClassSpecifier - Parse a C++ class-specifier [C++ class] or
1305/// elaborated-type-specifier [C++ dcl.type.elab]; we can't tell which
1306/// until we reach the start of a definition or see a token that
Richard Smithc5b05522012-03-12 07:56:15 +00001307/// cannot start a definition.
Douglas Gregor556877c2008-04-13 21:30:24 +00001308///
1309/// class-specifier: [C++ class]
1310/// class-head '{' member-specification[opt] '}'
1311/// class-head '{' member-specification[opt] '}' attributes[opt]
1312/// class-head:
1313/// class-key identifier[opt] base-clause[opt]
1314/// class-key nested-name-specifier identifier base-clause[opt]
1315/// class-key nested-name-specifier[opt] simple-template-id
1316/// base-clause[opt]
1317/// [GNU] class-key attributes[opt] identifier[opt] base-clause[opt]
Mike Stump11289f42009-09-09 15:08:12 +00001318/// [GNU] class-key attributes[opt] nested-name-specifier
Douglas Gregor556877c2008-04-13 21:30:24 +00001319/// identifier base-clause[opt]
Mike Stump11289f42009-09-09 15:08:12 +00001320/// [GNU] class-key attributes[opt] nested-name-specifier[opt]
Douglas Gregor556877c2008-04-13 21:30:24 +00001321/// simple-template-id base-clause[opt]
1322/// class-key:
1323/// 'class'
1324/// 'struct'
1325/// 'union'
1326///
1327/// elaborated-type-specifier: [C++ dcl.type.elab]
Mike Stump11289f42009-09-09 15:08:12 +00001328/// class-key ::[opt] nested-name-specifier[opt] identifier
1329/// class-key ::[opt] nested-name-specifier[opt] 'template'[opt]
1330/// simple-template-id
Douglas Gregor556877c2008-04-13 21:30:24 +00001331///
1332/// Note that the C++ class-specifier and elaborated-type-specifier,
1333/// together, subsume the C99 struct-or-union-specifier:
1334///
1335/// struct-or-union-specifier: [C99 6.7.2.1]
1336/// struct-or-union identifier[opt] '{' struct-contents '}'
1337/// struct-or-union identifier
1338/// [GNU] struct-or-union attributes[opt] identifier[opt] '{' struct-contents
1339/// '}' attributes[opt]
1340/// [GNU] struct-or-union attributes[opt] identifier
1341/// struct-or-union:
1342/// 'struct'
1343/// 'union'
Chris Lattnerffaa0e62009-04-12 21:49:30 +00001344void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind,
1345 SourceLocation StartLoc, DeclSpec &DS,
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001346 const ParsedTemplateInfo &TemplateInfo,
Douglas Gregordf593fb2011-11-07 17:33:42 +00001347 AccessSpecifier AS,
Michael Han9407e502012-11-26 22:54:45 +00001348 bool EnteringContext, DeclSpecContext DSC,
Bill Wendling44426052012-12-20 19:22:21 +00001349 ParsedAttributesWithRange &Attributes) {
Joao Matose9a3ed42012-08-31 22:18:20 +00001350 DeclSpec::TST TagType;
1351 if (TagTokKind == tok::kw_struct)
1352 TagType = DeclSpec::TST_struct;
1353 else if (TagTokKind == tok::kw___interface)
1354 TagType = DeclSpec::TST_interface;
1355 else if (TagTokKind == tok::kw_class)
1356 TagType = DeclSpec::TST_class;
1357 else {
Chris Lattnerffaa0e62009-04-12 21:49:30 +00001358 assert(TagTokKind == tok::kw_union && "Not a class specifier");
1359 TagType = DeclSpec::TST_union;
1360 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001361
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00001362 if (Tok.is(tok::code_completion)) {
1363 // Code completion for a struct, class, or union name.
Douglas Gregor0be31a22010-07-02 17:43:08 +00001364 Actions.CodeCompleteTag(getCurScope(), TagType);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001365 return cutOffParsing();
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00001366 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001367
Chandler Carruth2d69ec72010-06-28 08:39:25 +00001368 // C++03 [temp.explicit] 14.7.2/8:
1369 // The usual access checking rules do not apply to names used to specify
1370 // explicit instantiations.
1371 //
1372 // As an extension we do not perform access checking on the names used to
1373 // specify explicit specializations either. This is important to allow
1374 // specializing traits classes for private types.
John McCall6347b682012-05-07 06:16:58 +00001375 //
1376 // Note that we don't suppress if this turns out to be an elaborated
1377 // type specifier.
1378 bool shouldDelayDiagsInTag =
1379 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
1380 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
1381 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
Chandler Carruth2d69ec72010-06-28 08:39:25 +00001382
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001383 ParsedAttributesWithRange attrs(AttrFactory);
Douglas Gregor556877c2008-04-13 21:30:24 +00001384 // If attributes exist after tag, parse them.
Richard Smith37a45dd2013-10-24 01:21:09 +00001385 MaybeParseGNUAttributes(attrs);
Aaron Ballman068aa512015-05-20 20:58:33 +00001386 MaybeParseMicrosoftDeclSpecs(attrs);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001387
John McCall8d32c052012-05-22 21:28:12 +00001388 // Parse inheritance specifiers.
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001389 if (Tok.isOneOf(tok::kw___single_inheritance,
1390 tok::kw___multiple_inheritance,
1391 tok::kw___virtual_inheritance))
Richard Smith37a45dd2013-10-24 01:21:09 +00001392 ParseMicrosoftInheritanceClassAttributes(attrs);
John McCall8d32c052012-05-22 21:28:12 +00001393
Alexis Hunt96d5c762009-11-21 08:43:09 +00001394 // If C++0x attributes exist here, parse them.
1395 // FIXME: Are we consistent with the ordering of parsing of different
1396 // styles of attributes?
Richard Smith89645bc2013-01-02 12:01:23 +00001397 MaybeParseCXX11Attributes(attrs);
Mike Stump11289f42009-09-09 15:08:12 +00001398
Michael Han309af292013-01-07 16:57:11 +00001399 // Source location used by FIXIT to insert misplaced
1400 // C++11 attributes
1401 SourceLocation AttrFixitLoc = Tok.getLocation();
1402
Nico Weber7c3c5be2014-09-23 04:09:56 +00001403 if (TagType == DeclSpec::TST_struct &&
David Majnemer86330af2014-12-29 02:14:26 +00001404 Tok.isNot(tok::identifier) &&
1405 !Tok.isAnnotation() &&
Nico Weber7c3c5be2014-09-23 04:09:56 +00001406 Tok.getIdentifierInfo() &&
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001407 Tok.isOneOf(tok::kw___is_abstract,
1408 tok::kw___is_arithmetic,
1409 tok::kw___is_array,
David Majnemerb3d96882016-05-23 17:21:55 +00001410 tok::kw___is_assignable,
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001411 tok::kw___is_base_of,
1412 tok::kw___is_class,
1413 tok::kw___is_complete_type,
1414 tok::kw___is_compound,
1415 tok::kw___is_const,
1416 tok::kw___is_constructible,
1417 tok::kw___is_convertible,
1418 tok::kw___is_convertible_to,
1419 tok::kw___is_destructible,
1420 tok::kw___is_empty,
1421 tok::kw___is_enum,
1422 tok::kw___is_floating_point,
1423 tok::kw___is_final,
1424 tok::kw___is_function,
1425 tok::kw___is_fundamental,
1426 tok::kw___is_integral,
1427 tok::kw___is_interface_class,
1428 tok::kw___is_literal,
1429 tok::kw___is_lvalue_expr,
1430 tok::kw___is_lvalue_reference,
1431 tok::kw___is_member_function_pointer,
1432 tok::kw___is_member_object_pointer,
1433 tok::kw___is_member_pointer,
1434 tok::kw___is_nothrow_assignable,
1435 tok::kw___is_nothrow_constructible,
1436 tok::kw___is_nothrow_destructible,
1437 tok::kw___is_object,
1438 tok::kw___is_pod,
1439 tok::kw___is_pointer,
1440 tok::kw___is_polymorphic,
1441 tok::kw___is_reference,
1442 tok::kw___is_rvalue_expr,
1443 tok::kw___is_rvalue_reference,
1444 tok::kw___is_same,
1445 tok::kw___is_scalar,
1446 tok::kw___is_sealed,
1447 tok::kw___is_signed,
1448 tok::kw___is_standard_layout,
1449 tok::kw___is_trivial,
1450 tok::kw___is_trivially_assignable,
1451 tok::kw___is_trivially_constructible,
1452 tok::kw___is_trivially_copyable,
1453 tok::kw___is_union,
1454 tok::kw___is_unsigned,
1455 tok::kw___is_void,
1456 tok::kw___is_volatile))
Nico Weber7c3c5be2014-09-23 04:09:56 +00001457 // GNU libstdc++ 4.2 and libc++ use certain intrinsic names as the
1458 // name of struct templates, but some are keywords in GCC >= 4.3
1459 // and Clang. Therefore, when we see the token sequence "struct
1460 // X", make X into a normal identifier rather than a keyword, to
1461 // allow libstdc++ 4.2 and libc++ to work properly.
1462 TryKeywordIdentFallback(true);
Mike Stump11289f42009-09-09 15:08:12 +00001463
David Majnemer51fd8a02015-07-22 23:46:18 +00001464 struct PreserveAtomicIdentifierInfoRAII {
1465 PreserveAtomicIdentifierInfoRAII(Token &Tok, bool Enabled)
1466 : AtomicII(nullptr) {
1467 if (!Enabled)
1468 return;
1469 assert(Tok.is(tok::kw__Atomic));
1470 AtomicII = Tok.getIdentifierInfo();
1471 AtomicII->revertTokenIDToIdentifier();
1472 Tok.setKind(tok::identifier);
1473 }
1474 ~PreserveAtomicIdentifierInfoRAII() {
1475 if (!AtomicII)
1476 return;
1477 AtomicII->revertIdentifierToTokenID(tok::kw__Atomic);
1478 }
1479 IdentifierInfo *AtomicII;
1480 };
1481
1482 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
1483 // implementation for VS2013 uses _Atomic as an identifier for one of the
1484 // classes in <atomic>. When we are parsing 'struct _Atomic', don't consider
1485 // '_Atomic' to be a keyword. We are careful to undo this so that clang can
1486 // use '_Atomic' in its own header files.
1487 bool ShouldChangeAtomicToIdentifier = getLangOpts().MSVCCompat &&
1488 Tok.is(tok::kw__Atomic) &&
1489 TagType == DeclSpec::TST_struct;
1490 PreserveAtomicIdentifierInfoRAII AtomicTokenGuard(
1491 Tok, ShouldChangeAtomicToIdentifier);
1492
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001493 // Parse the (optional) nested-name-specifier.
John McCall9dab4e62009-12-12 11:40:51 +00001494 CXXScopeSpec &SS = DS.getTypeSpecScope();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001495 if (getLangOpts().CPlusPlus) {
Serge Pavlov458ea762014-07-16 05:16:52 +00001496 // "FOO : BAR" is not a potential typo for "FOO::BAR". In this context it
1497 // is a base-specifier-list.
Chris Lattnerd5c1c9d2009-12-10 00:32:41 +00001498 ColonProtectionRAIIObject X(*this);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001499
Nico Webercfaa4cd2015-02-15 07:26:13 +00001500 CXXScopeSpec Spec;
1501 bool HasValidSpec = true;
David Blaikieefdccaa2016-01-15 23:43:34 +00001502 if (ParseOptionalCXXScopeSpecifier(Spec, nullptr, EnteringContext)) {
John McCall413021a2010-07-30 06:26:29 +00001503 DS.SetTypeSpecError();
Nico Webercfaa4cd2015-02-15 07:26:13 +00001504 HasValidSpec = false;
1505 }
1506 if (Spec.isSet())
1507 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::annot_template_id)) {
Alp Tokerec543272013-12-24 09:48:30 +00001508 Diag(Tok, diag::err_expected) << tok::identifier;
Nico Webercfaa4cd2015-02-15 07:26:13 +00001509 HasValidSpec = false;
1510 }
1511 if (HasValidSpec)
1512 SS = Spec;
Chris Lattnerd5c1c9d2009-12-10 00:32:41 +00001513 }
Douglas Gregor67a65642009-02-17 23:15:12 +00001514
Douglas Gregor916462b2009-10-30 21:46:58 +00001515 TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
1516
Douglas Gregor67a65642009-02-17 23:15:12 +00001517 // Parse the (optional) class name or simple-template-id.
Craig Topper161e4db2014-05-21 06:02:52 +00001518 IdentifierInfo *Name = nullptr;
Douglas Gregor556877c2008-04-13 21:30:24 +00001519 SourceLocation NameLoc;
Craig Topper161e4db2014-05-21 06:02:52 +00001520 TemplateIdAnnotation *TemplateId = nullptr;
Douglas Gregor556877c2008-04-13 21:30:24 +00001521 if (Tok.is(tok::identifier)) {
1522 Name = Tok.getIdentifierInfo();
1523 NameLoc = ConsumeToken();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001524
David Blaikiebbafb8a2012-03-11 07:00:24 +00001525 if (Tok.is(tok::less) && getLangOpts().CPlusPlus) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001526 // The name was supposed to refer to a template, but didn't.
Douglas Gregor916462b2009-10-30 21:46:58 +00001527 // Eat the template argument list and try to continue parsing this as
1528 // a class (or template thereof).
1529 TemplateArgList TemplateArgs;
Douglas Gregor916462b2009-10-30 21:46:58 +00001530 SourceLocation LAngleLoc, RAngleLoc;
David Blaikiee20506d2016-01-15 23:43:28 +00001531 if (ParseTemplateIdAfterTemplateName(
1532 nullptr, NameLoc, SS, true, LAngleLoc, TemplateArgs, RAngleLoc)) {
Douglas Gregor916462b2009-10-30 21:46:58 +00001533 // We couldn't parse the template argument list at all, so don't
1534 // try to give any location information for the list.
1535 LAngleLoc = RAngleLoc = SourceLocation();
1536 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001537
Douglas Gregor916462b2009-10-30 21:46:58 +00001538 Diag(NameLoc, diag::err_explicit_spec_non_template)
Alp Toker01d65e12014-01-06 12:54:41 +00001539 << (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
1540 << TagTokKind << Name << SourceRange(LAngleLoc, RAngleLoc);
Joao Matose9a3ed42012-08-31 22:18:20 +00001541
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001542 // Strip off the last template parameter list if it was empty, since
Douglas Gregor1d0015f2009-10-30 22:09:44 +00001543 // we've removed its template argument list.
1544 if (TemplateParams && TemplateInfo.LastParameterListWasEmpty) {
Hubert Tong97b06632016-04-13 18:41:03 +00001545 if (TemplateParams->size() > 1) {
Douglas Gregor1d0015f2009-10-30 22:09:44 +00001546 TemplateParams->pop_back();
1547 } else {
Craig Topper161e4db2014-05-21 06:02:52 +00001548 TemplateParams = nullptr;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001549 const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind
Douglas Gregor1d0015f2009-10-30 22:09:44 +00001550 = ParsedTemplateInfo::NonTemplate;
1551 }
1552 } else if (TemplateInfo.Kind
1553 == ParsedTemplateInfo::ExplicitInstantiation) {
1554 // Pretend this is just a forward declaration.
Craig Topper161e4db2014-05-21 06:02:52 +00001555 TemplateParams = nullptr;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001556 const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind
Douglas Gregor916462b2009-10-30 21:46:58 +00001557 = ParsedTemplateInfo::NonTemplate;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001558 const_cast<ParsedTemplateInfo&>(TemplateInfo).TemplateLoc
Douglas Gregor1d0015f2009-10-30 22:09:44 +00001559 = SourceLocation();
1560 const_cast<ParsedTemplateInfo&>(TemplateInfo).ExternLoc
1561 = SourceLocation();
Douglas Gregor916462b2009-10-30 21:46:58 +00001562 }
Douglas Gregor916462b2009-10-30 21:46:58 +00001563 }
Douglas Gregor7f741122009-02-25 19:37:18 +00001564 } else if (Tok.is(tok::annot_template_id)) {
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00001565 TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregor7f741122009-02-25 19:37:18 +00001566 NameLoc = ConsumeToken();
Douglas Gregor67a65642009-02-17 23:15:12 +00001567
Douglas Gregore7c20652011-03-02 00:47:37 +00001568 if (TemplateId->Kind != TNK_Type_template &&
1569 TemplateId->Kind != TNK_Dependent_template_name) {
Douglas Gregor7f741122009-02-25 19:37:18 +00001570 // The template-name in the simple-template-id refers to
1571 // something other than a class template. Give an appropriate
1572 // error message and skip to the ';'.
1573 SourceRange Range(NameLoc);
1574 if (SS.isNotEmpty())
1575 Range.setBegin(SS.getBeginLoc());
Douglas Gregor67a65642009-02-17 23:15:12 +00001576
Richard Smith72bfbd82013-12-04 00:28:23 +00001577 // FIXME: Name may be null here.
Douglas Gregor7f741122009-02-25 19:37:18 +00001578 Diag(TemplateId->LAngleLoc, diag::err_template_spec_syntax_non_template)
Richard Trieu30f93852013-06-19 22:25:01 +00001579 << TemplateId->Name << static_cast<int>(TemplateId->Kind) << Range;
Mike Stump11289f42009-09-09 15:08:12 +00001580
Douglas Gregor7f741122009-02-25 19:37:18 +00001581 DS.SetTypeSpecError();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001582 SkipUntil(tok::semi, StopBeforeMatch);
Douglas Gregor7f741122009-02-25 19:37:18 +00001583 return;
Douglas Gregor67a65642009-02-17 23:15:12 +00001584 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001585 }
1586
Richard Smithbfdb1082012-03-12 08:56:40 +00001587 // There are four options here.
1588 // - If we are in a trailing return type, this is always just a reference,
1589 // and we must not try to parse a definition. For instance,
1590 // [] () -> struct S { };
1591 // does not define a type.
1592 // - If we have 'struct foo {...', 'struct foo :...',
1593 // 'struct foo final :' or 'struct foo final {', then this is a definition.
1594 // - If we have 'struct foo;', then this is either a forward declaration
1595 // or a friend declaration, which have to be treated differently.
1596 // - Otherwise we have something like 'struct foo xyz', a reference.
Michael Han9407e502012-11-26 22:54:45 +00001597 //
1598 // We also detect these erroneous cases to provide better diagnostic for
1599 // C++11 attributes parsing.
1600 // - attributes follow class name:
1601 // struct foo [[]] {};
1602 // - attributes appear before or after 'final':
1603 // struct foo [[]] final [[]] {};
1604 //
Richard Smithc5b05522012-03-12 07:56:15 +00001605 // However, in type-specifier-seq's, things look like declarations but are
1606 // just references, e.g.
1607 // new struct s;
Sebastian Redl2b372722010-02-03 21:21:43 +00001608 // or
Richard Smithc5b05522012-03-12 07:56:15 +00001609 // &T::operator struct s;
Richard Smith649c7b062014-01-08 00:56:48 +00001610 // For these, DSC is DSC_type_specifier or DSC_alias_declaration.
Michael Han9407e502012-11-26 22:54:45 +00001611
1612 // If there are attributes after class name, parse them.
Richard Smith89645bc2013-01-02 12:01:23 +00001613 MaybeParseCXX11Attributes(Attributes);
Michael Han9407e502012-11-26 22:54:45 +00001614
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001615 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
John McCallfaf5fb42010-08-26 23:41:50 +00001616 Sema::TagUseKind TUK;
Richard Smithbfdb1082012-03-12 08:56:40 +00001617 if (DSC == DSC_trailing)
1618 TUK = Sema::TUK_Reference;
1619 else if (Tok.is(tok::l_brace) ||
1620 (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
Richard Smith89645bc2013-01-02 12:01:23 +00001621 (isCXX11FinalKeyword() &&
David Blaikie9933a5a2012-03-12 15:39:49 +00001622 (NextToken().is(tok::l_brace) || NextToken().is(tok::colon)))) {
Douglas Gregor3dad8422009-09-26 06:47:28 +00001623 if (DS.isFriendSpecified()) {
1624 // C++ [class.friend]p2:
1625 // A class shall not be defined in a friend declaration.
Richard Smith0f8ee222012-01-10 01:33:14 +00001626 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
Douglas Gregor3dad8422009-09-26 06:47:28 +00001627 << SourceRange(DS.getFriendSpecLoc());
1628
1629 // Skip everything up to the semicolon, so that this looks like a proper
1630 // friend class (or template thereof) declaration.
Alexey Bataevee6507d2013-11-18 08:17:37 +00001631 SkipUntil(tok::semi, StopBeforeMatch);
John McCallfaf5fb42010-08-26 23:41:50 +00001632 TUK = Sema::TUK_Friend;
Douglas Gregor3dad8422009-09-26 06:47:28 +00001633 } else {
1634 // Okay, this is a class definition.
John McCallfaf5fb42010-08-26 23:41:50 +00001635 TUK = Sema::TUK_Definition;
Douglas Gregor3dad8422009-09-26 06:47:28 +00001636 }
Richard Smith434516c2013-02-22 06:46:23 +00001637 } else if (isCXX11FinalKeyword() && (NextToken().is(tok::l_square) ||
1638 NextToken().is(tok::kw_alignas))) {
Michael Han9407e502012-11-26 22:54:45 +00001639 // We can't tell if this is a definition or reference
1640 // until we skipped the 'final' and C++11 attribute specifiers.
1641 TentativeParsingAction PA(*this);
1642
1643 // Skip the 'final' keyword.
1644 ConsumeToken();
1645
1646 // Skip C++11 attribute specifiers.
1647 while (true) {
1648 if (Tok.is(tok::l_square) && NextToken().is(tok::l_square)) {
1649 ConsumeBracket();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001650 if (!SkipUntil(tok::r_square, StopAtSemi))
Michael Han9407e502012-11-26 22:54:45 +00001651 break;
Richard Smith434516c2013-02-22 06:46:23 +00001652 } else if (Tok.is(tok::kw_alignas) && NextToken().is(tok::l_paren)) {
Michael Han9407e502012-11-26 22:54:45 +00001653 ConsumeToken();
1654 ConsumeParen();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001655 if (!SkipUntil(tok::r_paren, StopAtSemi))
Michael Han9407e502012-11-26 22:54:45 +00001656 break;
1657 } else {
1658 break;
1659 }
1660 }
1661
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001662 if (Tok.isOneOf(tok::l_brace, tok::colon))
Michael Han9407e502012-11-26 22:54:45 +00001663 TUK = Sema::TUK_Definition;
1664 else
1665 TUK = Sema::TUK_Reference;
1666
1667 PA.Revert();
Richard Smith649c7b062014-01-08 00:56:48 +00001668 } else if (!isTypeSpecifier(DSC) &&
Richard Smith369b9f92012-06-25 21:37:02 +00001669 (Tok.is(tok::semi) ||
Richard Smith200f47c2012-07-02 19:14:01 +00001670 (Tok.isAtStartOfLine() && !isValidAfterTypeSpecifier(false)))) {
John McCallfaf5fb42010-08-26 23:41:50 +00001671 TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
Joao Matose9a3ed42012-08-31 22:18:20 +00001672 if (Tok.isNot(tok::semi)) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001673 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
Joao Matose9a3ed42012-08-31 22:18:20 +00001674 // A semicolon was missing after this declaration. Diagnose and recover.
Alp Toker383d2c42014-01-01 03:08:43 +00001675 ExpectAndConsume(tok::semi, diag::err_expected_after,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001676 DeclSpec::getSpecifierName(TagType, PPol));
Joao Matose9a3ed42012-08-31 22:18:20 +00001677 PP.EnterToken(Tok);
1678 Tok.setKind(tok::semi);
1679 }
Richard Smith369b9f92012-06-25 21:37:02 +00001680 } else
John McCallfaf5fb42010-08-26 23:41:50 +00001681 TUK = Sema::TUK_Reference;
Douglas Gregor556877c2008-04-13 21:30:24 +00001682
Michael Han9407e502012-11-26 22:54:45 +00001683 // Forbid misplaced attributes. In cases of a reference, we pass attributes
1684 // to caller to handle.
Michael Han309af292013-01-07 16:57:11 +00001685 if (TUK != Sema::TUK_Reference) {
1686 // If this is not a reference, then the only possible
1687 // valid place for C++11 attributes to appear here
1688 // is between class-key and class-name. If there are
1689 // any attributes after class-name, we try a fixit to move
1690 // them to the right place.
1691 SourceRange AttrRange = Attributes.Range;
1692 if (AttrRange.isValid()) {
1693 Diag(AttrRange.getBegin(), diag::err_attributes_not_allowed)
1694 << AttrRange
1695 << FixItHint::CreateInsertionFromRange(AttrFixitLoc,
1696 CharSourceRange(AttrRange, true))
1697 << FixItHint::CreateRemoval(AttrRange);
1698
1699 // Recover by adding misplaced attributes to the attribute list
1700 // of the class so they can be applied on the class later.
1701 attrs.takeAllFrom(Attributes);
1702 }
1703 }
Michael Han9407e502012-11-26 22:54:45 +00001704
John McCall6347b682012-05-07 06:16:58 +00001705 // If this is an elaborated type specifier, and we delayed
1706 // diagnostics before, just merge them into the current pool.
1707 if (shouldDelayDiagsInTag) {
1708 diagsFromTag.done();
1709 if (TUK == Sema::TUK_Reference)
1710 diagsFromTag.redelay();
1711 }
1712
John McCall413021a2010-07-30 06:26:29 +00001713 if (!Name && !TemplateId && (DS.getTypeSpecType() == DeclSpec::TST_error ||
John McCallfaf5fb42010-08-26 23:41:50 +00001714 TUK != Sema::TUK_Definition)) {
John McCall413021a2010-07-30 06:26:29 +00001715 if (DS.getTypeSpecType() != DeclSpec::TST_error) {
1716 // We have a declaration or reference to an anonymous class.
1717 Diag(StartLoc, diag::err_anon_type_definition)
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001718 << DeclSpec::getSpecifierName(TagType, Policy);
John McCall413021a2010-07-30 06:26:29 +00001719 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001720
David Majnemer3252fd02013-12-05 01:36:53 +00001721 // If we are parsing a definition and stop at a base-clause, continue on
1722 // until the semicolon. Continuing from the comma will just trick us into
1723 // thinking we are seeing a variable declaration.
1724 if (TUK == Sema::TUK_Definition && Tok.is(tok::colon))
1725 SkipUntil(tok::semi, StopBeforeMatch);
1726 else
1727 SkipUntil(tok::comma, StopAtSemi);
Douglas Gregor556877c2008-04-13 21:30:24 +00001728 return;
1729 }
1730
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001731 // Create the tag portion of the class or class template.
John McCall48871652010-08-21 09:40:31 +00001732 DeclResult TagOrTempResult = true; // invalid
1733 TypeResult TypeResult = true; // invalid
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001734
Douglas Gregord6ab8742009-05-28 23:31:59 +00001735 bool Owned = false;
Richard Smithd9ba2242015-05-07 03:54:19 +00001736 Sema::SkipBodyInfo SkipBody;
John McCall06f6fe8d2009-09-04 01:14:41 +00001737 if (TemplateId) {
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001738 // Explicit specialization, class template partial specialization,
1739 // or explicit instantiation.
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00001740 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregor7f741122009-02-25 19:37:18 +00001741 TemplateId->NumArgs);
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001742 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
John McCallfaf5fb42010-08-26 23:41:50 +00001743 TUK == Sema::TUK_Declaration) {
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001744 // This is an explicit instantiation of a class template.
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001745 ProhibitAttributes(attrs);
1746
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001747 TagOrTempResult
Douglas Gregor0be31a22010-07-02 17:43:08 +00001748 = Actions.ActOnExplicitInstantiation(getCurScope(),
Douglas Gregor43e75172009-09-04 06:33:52 +00001749 TemplateInfo.ExternLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001750 TemplateInfo.TemplateLoc,
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001751 TagType,
Mike Stump11289f42009-09-09 15:08:12 +00001752 StartLoc,
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001753 SS,
John McCall3e56fd42010-08-23 07:28:44 +00001754 TemplateId->Template,
Mike Stump11289f42009-09-09 15:08:12 +00001755 TemplateId->TemplateNameLoc,
1756 TemplateId->LAngleLoc,
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001757 TemplateArgsPtr,
Mike Stump11289f42009-09-09 15:08:12 +00001758 TemplateId->RAngleLoc,
John McCall53fa7142010-12-24 02:08:15 +00001759 attrs.getList());
John McCallb7c5c272010-04-14 00:24:33 +00001760
1761 // Friend template-ids are treated as references unless
1762 // they have template headers, in which case they're ill-formed
1763 // (FIXME: "template <class T> friend class A<T>::B<int>;").
1764 // We diagnose this error in ActOnClassTemplateSpecialization.
John McCallfaf5fb42010-08-26 23:41:50 +00001765 } else if (TUK == Sema::TUK_Reference ||
1766 (TUK == Sema::TUK_Friend &&
John McCallb7c5c272010-04-14 00:24:33 +00001767 TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate)) {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001768 ProhibitAttributes(attrs);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00001769 TypeResult = Actions.ActOnTagTemplateIdType(TUK, TagType, StartLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00001770 TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00001771 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00001772 TemplateId->Template,
1773 TemplateId->TemplateNameLoc,
1774 TemplateId->LAngleLoc,
1775 TemplateArgsPtr,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00001776 TemplateId->RAngleLoc);
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001777 } else {
1778 // This is an explicit specialization or a class template
1779 // partial specialization.
1780 TemplateParameterLists FakedParamLists;
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001781 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1782 // This looks like an explicit instantiation, because we have
1783 // something like
1784 //
1785 // template class Foo<X>
1786 //
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001787 // but it actually has a definition. Most likely, this was
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001788 // meant to be an explicit specialization, but the user forgot
1789 // the '<>' after 'template'.
Richard Smith003c5e12013-11-08 19:03:29 +00001790 // It this is friend declaration however, since it cannot have a
1791 // template header, it is most likely that the user meant to
1792 // remove the 'template' keyword.
Larisse Voufob9bbaba2013-06-22 13:56:11 +00001793 assert((TUK == Sema::TUK_Definition || TUK == Sema::TUK_Friend) &&
Richard Smith003c5e12013-11-08 19:03:29 +00001794 "Expected a definition here");
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001795
Richard Smith003c5e12013-11-08 19:03:29 +00001796 if (TUK == Sema::TUK_Friend) {
1797 Diag(DS.getFriendSpecLoc(), diag::err_friend_explicit_instantiation);
Craig Topper161e4db2014-05-21 06:02:52 +00001798 TemplateParams = nullptr;
Richard Smith003c5e12013-11-08 19:03:29 +00001799 } else {
1800 SourceLocation LAngleLoc =
1801 PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
1802 Diag(TemplateId->TemplateNameLoc,
1803 diag::err_explicit_instantiation_with_definition)
1804 << SourceRange(TemplateInfo.TemplateLoc)
1805 << FixItHint::CreateInsertion(LAngleLoc, "<>");
1806
1807 // Create a fake template parameter list that contains only
1808 // "template<>", so that we treat this construct as a class
1809 // template specialization.
1810 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
Craig Topper96225a52015-12-24 23:58:25 +00001811 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
Hubert Tongf608c052016-04-29 18:05:37 +00001812 LAngleLoc, nullptr));
Richard Smith003c5e12013-11-08 19:03:29 +00001813 TemplateParams = &FakedParamLists;
1814 }
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001815 }
1816
1817 // Build the class template specialization.
Richard Smith4b55a9c2014-04-17 03:29:33 +00001818 TagOrTempResult = Actions.ActOnClassTemplateSpecialization(
1819 getCurScope(), TagType, TUK, StartLoc, DS.getModulePrivateSpecLoc(),
1820 *TemplateId, attrs.getList(),
Craig Topper161e4db2014-05-21 06:02:52 +00001821 MultiTemplateParamsArg(TemplateParams ? &(*TemplateParams)[0]
1822 : nullptr,
Richard Smithc7e6ff02015-05-18 20:36:47 +00001823 TemplateParams ? TemplateParams->size() : 0),
1824 &SkipBody);
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001825 }
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001826 } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
John McCallfaf5fb42010-08-26 23:41:50 +00001827 TUK == Sema::TUK_Declaration) {
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001828 // Explicit instantiation of a member of a class template
1829 // specialization, e.g.,
1830 //
1831 // template struct Outer<int>::Inner;
1832 //
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001833 ProhibitAttributes(attrs);
1834
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001835 TagOrTempResult
Douglas Gregor0be31a22010-07-02 17:43:08 +00001836 = Actions.ActOnExplicitInstantiation(getCurScope(),
Douglas Gregor43e75172009-09-04 06:33:52 +00001837 TemplateInfo.ExternLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001838 TemplateInfo.TemplateLoc,
1839 TagType, StartLoc, SS, Name,
John McCall53fa7142010-12-24 02:08:15 +00001840 NameLoc, attrs.getList());
John McCallace48cd2010-10-19 01:40:49 +00001841 } else if (TUK == Sema::TUK_Friend &&
1842 TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate) {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001843 ProhibitAttributes(attrs);
1844
John McCallace48cd2010-10-19 01:40:49 +00001845 TagOrTempResult =
1846 Actions.ActOnTemplatedFriendTag(getCurScope(), DS.getFriendSpecLoc(),
1847 TagType, StartLoc, SS,
John McCall53fa7142010-12-24 02:08:15 +00001848 Name, NameLoc, attrs.getList(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00001849 MultiTemplateParamsArg(
Craig Topper161e4db2014-05-21 06:02:52 +00001850 TemplateParams? &(*TemplateParams)[0]
1851 : nullptr,
John McCallace48cd2010-10-19 01:40:49 +00001852 TemplateParams? TemplateParams->size() : 0));
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001853 } else {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001854 if (TUK != Sema::TUK_Declaration && TUK != Sema::TUK_Definition)
1855 ProhibitAttributes(attrs);
Richard Smith003c5e12013-11-08 19:03:29 +00001856
Larisse Voufo725de3e2013-06-21 00:08:46 +00001857 if (TUK == Sema::TUK_Definition &&
1858 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1859 // If the declarator-id is not a template-id, issue a diagnostic and
1860 // recover by ignoring the 'template' keyword.
1861 Diag(Tok, diag::err_template_defn_explicit_instantiation)
1862 << 1 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
Craig Topper161e4db2014-05-21 06:02:52 +00001863 TemplateParams = nullptr;
Larisse Voufo725de3e2013-06-21 00:08:46 +00001864 }
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001865
John McCall7f41d982009-09-11 04:59:25 +00001866 bool IsDependent = false;
1867
John McCall32723e92010-10-19 18:40:57 +00001868 // Don't pass down template parameter lists if this is just a tag
1869 // reference. For example, we don't need the template parameters here:
1870 // template <class T> class A *makeA(T t);
1871 MultiTemplateParamsArg TParams;
1872 if (TUK != Sema::TUK_Reference && TemplateParams)
1873 TParams =
1874 MultiTemplateParamsArg(&(*TemplateParams)[0], TemplateParams->size());
1875
Nico Weber32a0fc72016-09-03 03:01:32 +00001876 stripTypeAttributesOffDeclSpec(attrs, DS, TUK);
David Majnemer936b4112015-04-19 07:53:29 +00001877
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001878 // Declaration or definition of a class type
John McCallace48cd2010-10-19 01:40:49 +00001879 TagOrTempResult = Actions.ActOnTag(getCurScope(), TagType, TUK, StartLoc,
John McCall53fa7142010-12-24 02:08:15 +00001880 SS, Name, NameLoc, attrs.getList(), AS,
Douglas Gregor2820e692011-09-09 19:05:14 +00001881 DS.getModulePrivateSpecLoc(),
Richard Smith0f8ee222012-01-10 01:33:14 +00001882 TParams, Owned, IsDependent,
1883 SourceLocation(), false,
Richard Smith649c7b062014-01-08 00:56:48 +00001884 clang::TypeResult(),
Richard Smith65ebb4a2015-03-26 04:09:53 +00001885 DSC == DSC_type_specifier,
1886 &SkipBody);
John McCall7f41d982009-09-11 04:59:25 +00001887
1888 // If ActOnTag said the type was dependent, try again with the
1889 // less common call.
John McCallace48cd2010-10-19 01:40:49 +00001890 if (IsDependent) {
1891 assert(TUK == Sema::TUK_Reference || TUK == Sema::TUK_Friend);
Douglas Gregor0be31a22010-07-02 17:43:08 +00001892 TypeResult = Actions.ActOnDependentTag(getCurScope(), TagType, TUK,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001893 SS, Name, StartLoc, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +00001894 }
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001895 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001896
Douglas Gregor556877c2008-04-13 21:30:24 +00001897 // If there is a body, parse it and inform the actions module.
John McCallfaf5fb42010-08-26 23:41:50 +00001898 if (TUK == Sema::TUK_Definition) {
John McCall2d814c32009-12-19 21:48:58 +00001899 assert(Tok.is(tok::l_brace) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00001900 (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
Richard Smith89645bc2013-01-02 12:01:23 +00001901 isCXX11FinalKeyword());
Richard Smithd9ba2242015-05-07 03:54:19 +00001902 if (SkipBody.ShouldSkip)
Richard Smith65ebb4a2015-03-26 04:09:53 +00001903 SkipCXXMemberSpecification(StartLoc, AttrFixitLoc, TagType,
1904 TagOrTempResult.get());
1905 else if (getLangOpts().CPlusPlus)
Michael Han309af292013-01-07 16:57:11 +00001906 ParseCXXMemberSpecification(StartLoc, AttrFixitLoc, attrs, TagType,
1907 TagOrTempResult.get());
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001908 else
Douglas Gregorc08f4892009-03-25 00:13:59 +00001909 ParseStructUnionBody(StartLoc, TagType, TagOrTempResult.get());
Douglas Gregor556877c2008-04-13 21:30:24 +00001910 }
1911
Erich Keane2fe684b2017-02-28 20:44:39 +00001912 if (!TagOrTempResult.isInvalid())
1913 // Delayed proccessing of attributes.
1914 Actions.ProcessDeclAttributeDelayed(TagOrTempResult.get(), attrs.getList());
1915
Craig Topper161e4db2014-05-21 06:02:52 +00001916 const char *PrevSpec = nullptr;
John McCallba7bf592010-08-24 05:47:05 +00001917 unsigned DiagID;
1918 bool Result;
John McCall7f41d982009-09-11 04:59:25 +00001919 if (!TypeResult.isInvalid()) {
Abramo Bagnara9875a3c2011-03-16 20:16:18 +00001920 Result = DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
1921 NameLoc.isValid() ? NameLoc : StartLoc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001922 PrevSpec, DiagID, TypeResult.get(), Policy);
John McCall7f41d982009-09-11 04:59:25 +00001923 } else if (!TagOrTempResult.isInvalid()) {
Abramo Bagnara9875a3c2011-03-16 20:16:18 +00001924 Result = DS.SetTypeSpecType(TagType, StartLoc,
1925 NameLoc.isValid() ? NameLoc : StartLoc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001926 PrevSpec, DiagID, TagOrTempResult.get(), Owned,
1927 Policy);
John McCall7f41d982009-09-11 04:59:25 +00001928 } else {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001929 DS.SetTypeSpecError();
Anders Carlssonf83c9fa2009-05-11 22:27:47 +00001930 return;
1931 }
Mike Stump11289f42009-09-09 15:08:12 +00001932
John McCallba7bf592010-08-24 05:47:05 +00001933 if (Result)
John McCall49bfce42009-08-03 20:12:06 +00001934 Diag(StartLoc, DiagID) << PrevSpec;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001935
Chris Lattnercf251412010-02-02 01:23:29 +00001936 // At this point, we've successfully parsed a class-specifier in 'definition'
1937 // form (e.g. "struct foo { int x; }". While we could just return here, we're
1938 // going to look at what comes after it to improve error recovery. If an
1939 // impossible token occurs next, we assume that the programmer forgot a ; at
1940 // the end of the declaration and recover that way.
1941 //
Richard Smith369b9f92012-06-25 21:37:02 +00001942 // Also enforce C++ [temp]p3:
1943 // In a template-declaration which defines a class, no declarator
1944 // is permitted.
Richard Smith843f18f2014-08-13 02:13:15 +00001945 //
1946 // After a type-specifier, we don't expect a semicolon. This only happens in
1947 // C, since definitions are not permitted in this context in C++.
Joao Matose9a3ed42012-08-31 22:18:20 +00001948 if (TUK == Sema::TUK_Definition &&
Richard Smith843f18f2014-08-13 02:13:15 +00001949 (getLangOpts().CPlusPlus || !isTypeSpecifier(DSC)) &&
Joao Matose9a3ed42012-08-31 22:18:20 +00001950 (TemplateInfo.Kind || !isValidAfterTypeSpecifier(false))) {
Argyrios Kyrtzidise6f69132012-12-17 20:10:43 +00001951 if (Tok.isNot(tok::semi)) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001952 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
Alp Toker383d2c42014-01-01 03:08:43 +00001953 ExpectAndConsume(tok::semi, diag::err_expected_after,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001954 DeclSpec::getSpecifierName(TagType, PPol));
Argyrios Kyrtzidise6f69132012-12-17 20:10:43 +00001955 // Push this token back into the preprocessor and change our current token
1956 // to ';' so that the rest of the code recovers as though there were an
1957 // ';' after the definition.
1958 PP.EnterToken(Tok);
1959 Tok.setKind(tok::semi);
1960 }
Chris Lattnercf251412010-02-02 01:23:29 +00001961 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001962}
1963
Mike Stump11289f42009-09-09 15:08:12 +00001964/// ParseBaseClause - Parse the base-clause of a C++ class [C++ class.derived].
Douglas Gregor556877c2008-04-13 21:30:24 +00001965///
1966/// base-clause : [C++ class.derived]
1967/// ':' base-specifier-list
1968/// base-specifier-list:
1969/// base-specifier '...'[opt]
1970/// base-specifier-list ',' base-specifier '...'[opt]
John McCall48871652010-08-21 09:40:31 +00001971void Parser::ParseBaseClause(Decl *ClassDecl) {
Douglas Gregor556877c2008-04-13 21:30:24 +00001972 assert(Tok.is(tok::colon) && "Not a base clause");
1973 ConsumeToken();
1974
Douglas Gregor29a92472008-10-22 17:49:05 +00001975 // Build up an array of parsed base specifiers.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001976 SmallVector<CXXBaseSpecifier *, 8> BaseInfo;
Douglas Gregor29a92472008-10-22 17:49:05 +00001977
Douglas Gregor556877c2008-04-13 21:30:24 +00001978 while (true) {
1979 // Parse a base-specifier.
Douglas Gregor29a92472008-10-22 17:49:05 +00001980 BaseResult Result = ParseBaseSpecifier(ClassDecl);
Douglas Gregorf8298252009-01-26 22:44:13 +00001981 if (Result.isInvalid()) {
Douglas Gregor556877c2008-04-13 21:30:24 +00001982 // Skip the rest of this base specifier, up until the comma or
1983 // opening brace.
Alexey Bataevee6507d2013-11-18 08:17:37 +00001984 SkipUntil(tok::comma, tok::l_brace, StopAtSemi | StopBeforeMatch);
Douglas Gregor29a92472008-10-22 17:49:05 +00001985 } else {
1986 // Add this to our array of base specifiers.
Douglas Gregorf8298252009-01-26 22:44:13 +00001987 BaseInfo.push_back(Result.get());
Douglas Gregor556877c2008-04-13 21:30:24 +00001988 }
1989
1990 // If the next token is a comma, consume it and keep reading
1991 // base-specifiers.
Alp Toker97650562014-01-10 11:19:30 +00001992 if (!TryConsumeToken(tok::comma))
1993 break;
Douglas Gregor556877c2008-04-13 21:30:24 +00001994 }
Douglas Gregor29a92472008-10-22 17:49:05 +00001995
1996 // Attach the base specifiers
Craig Topperaa700cb2015-12-27 21:55:19 +00001997 Actions.ActOnBaseSpecifiers(ClassDecl, BaseInfo);
Douglas Gregor556877c2008-04-13 21:30:24 +00001998}
1999
2000/// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is
2001/// one entry in the base class list of a class specifier, for example:
2002/// class foo : public bar, virtual private baz {
2003/// 'public bar' and 'virtual private baz' are each base-specifiers.
2004///
2005/// base-specifier: [C++ class.derived]
Richard Smith4c96e992013-02-19 23:47:15 +00002006/// attribute-specifier-seq[opt] base-type-specifier
2007/// attribute-specifier-seq[opt] 'virtual' access-specifier[opt]
2008/// base-type-specifier
2009/// attribute-specifier-seq[opt] access-specifier 'virtual'[opt]
2010/// base-type-specifier
Craig Topper9ad7e262014-10-31 06:57:07 +00002011BaseResult Parser::ParseBaseSpecifier(Decl *ClassDecl) {
Douglas Gregor556877c2008-04-13 21:30:24 +00002012 bool IsVirtual = false;
2013 SourceLocation StartLoc = Tok.getLocation();
2014
Richard Smith4c96e992013-02-19 23:47:15 +00002015 ParsedAttributesWithRange Attributes(AttrFactory);
2016 MaybeParseCXX11Attributes(Attributes);
2017
Douglas Gregor556877c2008-04-13 21:30:24 +00002018 // Parse the 'virtual' keyword.
Alp Toker97650562014-01-10 11:19:30 +00002019 if (TryConsumeToken(tok::kw_virtual))
Douglas Gregor556877c2008-04-13 21:30:24 +00002020 IsVirtual = true;
Douglas Gregor556877c2008-04-13 21:30:24 +00002021
Richard Smith4c96e992013-02-19 23:47:15 +00002022 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2023
Douglas Gregor556877c2008-04-13 21:30:24 +00002024 // Parse an (optional) access specifier.
2025 AccessSpecifier Access = getAccessSpecifierIfPresent();
John McCall553c0792010-01-23 00:46:32 +00002026 if (Access != AS_none)
Douglas Gregor556877c2008-04-13 21:30:24 +00002027 ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +00002028
Richard Smith4c96e992013-02-19 23:47:15 +00002029 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2030
Douglas Gregor556877c2008-04-13 21:30:24 +00002031 // Parse the 'virtual' keyword (again!), in case it came after the
2032 // access specifier.
2033 if (Tok.is(tok::kw_virtual)) {
2034 SourceLocation VirtualLoc = ConsumeToken();
2035 if (IsVirtual) {
2036 // Complain about duplicate 'virtual'
Chris Lattner6d29c102008-11-18 07:48:38 +00002037 Diag(VirtualLoc, diag::err_dup_virtual)
Douglas Gregora771f462010-03-31 17:46:05 +00002038 << FixItHint::CreateRemoval(VirtualLoc);
Douglas Gregor556877c2008-04-13 21:30:24 +00002039 }
2040
2041 IsVirtual = true;
2042 }
2043
Richard Smith4c96e992013-02-19 23:47:15 +00002044 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2045
Douglas Gregor831c93f2008-11-05 20:51:48 +00002046 // Parse the class-name.
David Majnemer51fd8a02015-07-22 23:46:18 +00002047
2048 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
2049 // implementation for VS2013 uses _Atomic as an identifier for one of the
2050 // classes in <atomic>. Treat '_Atomic' to be an identifier when we are
2051 // parsing the class-name for a base specifier.
2052 if (getLangOpts().MSVCCompat && Tok.is(tok::kw__Atomic) &&
2053 NextToken().is(tok::less))
2054 Tok.setKind(tok::identifier);
2055
Douglas Gregord54dfb82009-02-25 23:52:28 +00002056 SourceLocation EndLocation;
David Blaikie1cd50022011-10-25 17:10:12 +00002057 SourceLocation BaseLoc;
2058 TypeResult BaseType = ParseBaseTypeSpecifier(BaseLoc, EndLocation);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00002059 if (BaseType.isInvalid())
Douglas Gregor831c93f2008-11-05 20:51:48 +00002060 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002061
Douglas Gregor752a5952011-01-03 22:36:02 +00002062 // Parse the optional ellipsis (for a pack expansion). The ellipsis is
2063 // actually part of the base-specifier-list grammar productions, but we
2064 // parse it here for convenience.
2065 SourceLocation EllipsisLoc;
Alp Toker97650562014-01-10 11:19:30 +00002066 TryConsumeToken(tok::ellipsis, EllipsisLoc);
2067
Mike Stump11289f42009-09-09 15:08:12 +00002068 // Find the complete source range for the base-specifier.
Douglas Gregord54dfb82009-02-25 23:52:28 +00002069 SourceRange Range(StartLoc, EndLocation);
Mike Stump11289f42009-09-09 15:08:12 +00002070
Douglas Gregor556877c2008-04-13 21:30:24 +00002071 // Notify semantic analysis that we have parsed a complete
2072 // base-specifier.
Richard Smith4c96e992013-02-19 23:47:15 +00002073 return Actions.ActOnBaseSpecifier(ClassDecl, Range, Attributes, IsVirtual,
2074 Access, BaseType.get(), BaseLoc,
2075 EllipsisLoc);
Douglas Gregor556877c2008-04-13 21:30:24 +00002076}
2077
2078/// getAccessSpecifierIfPresent - Determine whether the next token is
2079/// a C++ access-specifier.
2080///
2081/// access-specifier: [C++ class.derived]
2082/// 'private'
2083/// 'protected'
2084/// 'public'
Mike Stump11289f42009-09-09 15:08:12 +00002085AccessSpecifier Parser::getAccessSpecifierIfPresent() const {
Douglas Gregor556877c2008-04-13 21:30:24 +00002086 switch (Tok.getKind()) {
2087 default: return AS_none;
2088 case tok::kw_private: return AS_private;
2089 case tok::kw_protected: return AS_protected;
2090 case tok::kw_public: return AS_public;
2091 }
2092}
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002093
Douglas Gregor433e0532012-04-16 18:27:27 +00002094/// \brief If the given declarator has any parts for which parsing has to be
Richard Smith0b3a4622014-11-13 20:01:57 +00002095/// delayed, e.g., default arguments or an exception-specification, create a
2096/// late-parsed method declaration record to handle the parsing at the end of
2097/// the class definition.
Douglas Gregor433e0532012-04-16 18:27:27 +00002098void Parser::HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
2099 Decl *ThisDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00002100 DeclaratorChunk::FunctionTypeInfo &FTI
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002101 = DeclaratorInfo.getFunctionTypeInfo();
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002102 // If there was a late-parsed exception-specification, we'll need a
2103 // late parse
2104 bool NeedLateParse = FTI.getExceptionSpecType() == EST_Unparsed;
Douglas Gregor433e0532012-04-16 18:27:27 +00002105
Nathan Sidwell5bb231c2015-02-19 14:03:22 +00002106 if (!NeedLateParse) {
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002107 // Look ahead to see if there are any default args
Nathan Sidwell5bb231c2015-02-19 14:03:22 +00002108 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx) {
2109 auto Param = cast<ParmVarDecl>(FTI.Params[ParamIdx].Param);
2110 if (Param->hasUnparsedDefaultArg()) {
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002111 NeedLateParse = true;
2112 break;
2113 }
Nathan Sidwell5bb231c2015-02-19 14:03:22 +00002114 }
2115 }
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002116
2117 if (NeedLateParse) {
Richard Smith0b3a4622014-11-13 20:01:57 +00002118 // Push this method onto the stack of late-parsed method
2119 // declarations.
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002120 auto LateMethod = new LateParsedMethodDeclaration(this, ThisDecl);
Richard Smith0b3a4622014-11-13 20:01:57 +00002121 getCurrentClass().LateParsedDeclarations.push_back(LateMethod);
2122 LateMethod->TemplateScope = getCurScope()->isTemplateParamScope();
2123
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002124 // Stash the exception-specification tokens in the late-pased method.
Richard Smith0b3a4622014-11-13 20:01:57 +00002125 LateMethod->ExceptionSpecTokens = FTI.ExceptionSpecTokens;
Hans Wennborgdcfba332015-10-06 23:40:43 +00002126 FTI.ExceptionSpecTokens = nullptr;
Richard Smith0b3a4622014-11-13 20:01:57 +00002127
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002128 // Push tokens for each parameter. Those that do not have
2129 // defaults will be NULL.
Richard Smith0b3a4622014-11-13 20:01:57 +00002130 LateMethod->DefaultArgs.reserve(FTI.NumParams);
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002131 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx)
Alp Tokerc5350722014-02-26 22:27:52 +00002132 LateMethod->DefaultArgs.push_back(LateParsedDefaultArgument(
Malcolm Parsonsca9d8342016-11-17 21:00:09 +00002133 FTI.Params[ParamIdx].Param,
2134 std::move(FTI.Params[ParamIdx].DefaultArgTokens)));
Eli Friedman3af2a772009-07-22 21:45:50 +00002135 }
2136}
2137
Richard Smith89645bc2013-01-02 12:01:23 +00002138/// isCXX11VirtSpecifier - Determine whether the given token is a C++11
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002139/// virt-specifier.
2140///
2141/// virt-specifier:
2142/// override
2143/// final
Andrey Bokhanko276055b2016-07-29 10:42:48 +00002144/// __final
Richard Smith89645bc2013-01-02 12:01:23 +00002145VirtSpecifiers::Specifier Parser::isCXX11VirtSpecifier(const Token &Tok) const {
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002146 if (!getLangOpts().CPlusPlus || Tok.isNot(tok::identifier))
Anders Carlsson4b63d0e2011-01-22 16:56:46 +00002147 return VirtSpecifiers::VS_None;
2148
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002149 IdentifierInfo *II = Tok.getIdentifierInfo();
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002150
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002151 // Initialize the contextual keywords.
2152 if (!Ident_final) {
2153 Ident_final = &PP.getIdentifierTable().get("final");
Andrey Bokhanko276055b2016-07-29 10:42:48 +00002154 if (getLangOpts().GNUKeywords)
2155 Ident_GNU_final = &PP.getIdentifierTable().get("__final");
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002156 if (getLangOpts().MicrosoftExt)
2157 Ident_sealed = &PP.getIdentifierTable().get("sealed");
2158 Ident_override = &PP.getIdentifierTable().get("override");
Anders Carlsson56104902011-01-17 03:05:47 +00002159 }
2160
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002161 if (II == Ident_override)
2162 return VirtSpecifiers::VS_Override;
2163
2164 if (II == Ident_sealed)
2165 return VirtSpecifiers::VS_Sealed;
2166
2167 if (II == Ident_final)
2168 return VirtSpecifiers::VS_Final;
2169
Andrey Bokhanko276055b2016-07-29 10:42:48 +00002170 if (II == Ident_GNU_final)
2171 return VirtSpecifiers::VS_GNU_Final;
2172
Anders Carlsson56104902011-01-17 03:05:47 +00002173 return VirtSpecifiers::VS_None;
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002174}
2175
Richard Smith89645bc2013-01-02 12:01:23 +00002176/// ParseOptionalCXX11VirtSpecifierSeq - Parse a virt-specifier-seq.
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002177///
2178/// virt-specifier-seq:
2179/// virt-specifier
2180/// virt-specifier-seq virt-specifier
Richard Smith89645bc2013-01-02 12:01:23 +00002181void Parser::ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS,
Richard Smith3d1a94c2014-08-12 00:22:39 +00002182 bool IsInterface,
2183 SourceLocation FriendLoc) {
Anders Carlsson56104902011-01-17 03:05:47 +00002184 while (true) {
Richard Smith89645bc2013-01-02 12:01:23 +00002185 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
Anders Carlsson56104902011-01-17 03:05:47 +00002186 if (Specifier == VirtSpecifiers::VS_None)
2187 return;
2188
Richard Smith3d1a94c2014-08-12 00:22:39 +00002189 if (FriendLoc.isValid()) {
2190 Diag(Tok.getLocation(), diag::err_friend_decl_spec)
2191 << VirtSpecifiers::getSpecifierName(Specifier)
2192 << FixItHint::CreateRemoval(Tok.getLocation())
2193 << SourceRange(FriendLoc, FriendLoc);
2194 ConsumeToken();
2195 continue;
2196 }
2197
Anders Carlsson56104902011-01-17 03:05:47 +00002198 // C++ [class.mem]p8:
2199 // A virt-specifier-seq shall contain at most one of each virt-specifier.
Craig Topper161e4db2014-05-21 06:02:52 +00002200 const char *PrevSpec = nullptr;
Anders Carlssonf2ca3892011-01-22 15:58:16 +00002201 if (VS.SetSpecifier(Specifier, Tok.getLocation(), PrevSpec))
Anders Carlsson56104902011-01-17 03:05:47 +00002202 Diag(Tok.getLocation(), diag::err_duplicate_virt_specifier)
2203 << PrevSpec
2204 << FixItHint::CreateRemoval(Tok.getLocation());
2205
David Majnemera5433082013-10-18 00:33:31 +00002206 if (IsInterface && (Specifier == VirtSpecifiers::VS_Final ||
2207 Specifier == VirtSpecifiers::VS_Sealed)) {
John McCalldb632ac2012-09-25 07:32:39 +00002208 Diag(Tok.getLocation(), diag::err_override_control_interface)
2209 << VirtSpecifiers::getSpecifierName(Specifier);
David Majnemera5433082013-10-18 00:33:31 +00002210 } else if (Specifier == VirtSpecifiers::VS_Sealed) {
2211 Diag(Tok.getLocation(), diag::ext_ms_sealed_keyword);
Andrey Bokhanko276055b2016-07-29 10:42:48 +00002212 } else if (Specifier == VirtSpecifiers::VS_GNU_Final) {
2213 Diag(Tok.getLocation(), diag::ext_warn_gnu_final);
John McCalldb632ac2012-09-25 07:32:39 +00002214 } else {
David Majnemera5433082013-10-18 00:33:31 +00002215 Diag(Tok.getLocation(),
2216 getLangOpts().CPlusPlus11
2217 ? diag::warn_cxx98_compat_override_control_keyword
2218 : diag::ext_override_control_keyword)
2219 << VirtSpecifiers::getSpecifierName(Specifier);
John McCalldb632ac2012-09-25 07:32:39 +00002220 }
Anders Carlsson56104902011-01-17 03:05:47 +00002221 ConsumeToken();
2222 }
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002223}
2224
Richard Smith89645bc2013-01-02 12:01:23 +00002225/// isCXX11FinalKeyword - Determine whether the next token is a C++11
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002226/// 'final' or Microsoft 'sealed' contextual keyword.
Richard Smith89645bc2013-01-02 12:01:23 +00002227bool Parser::isCXX11FinalKeyword() const {
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002228 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
2229 return Specifier == VirtSpecifiers::VS_Final ||
Andrey Bokhanko276055b2016-07-29 10:42:48 +00002230 Specifier == VirtSpecifiers::VS_GNU_Final ||
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002231 Specifier == VirtSpecifiers::VS_Sealed;
Anders Carlsson4b63d0e2011-01-22 16:56:46 +00002232}
2233
Richard Smith72553fc2014-01-23 23:53:27 +00002234/// \brief Parse a C++ member-declarator up to, but not including, the optional
2235/// brace-or-equal-initializer or pure-specifier.
Nico Weberd89e6f72015-01-16 19:34:13 +00002236bool Parser::ParseCXXMemberDeclaratorBeforeInitializer(
Richard Smith72553fc2014-01-23 23:53:27 +00002237 Declarator &DeclaratorInfo, VirtSpecifiers &VS, ExprResult &BitfieldSize,
2238 LateParsedAttrList &LateParsedAttrs) {
2239 // member-declarator:
2240 // declarator pure-specifier[opt]
2241 // declarator brace-or-equal-initializer[opt]
2242 // identifier[opt] ':' constant-expression
Serge Pavlov458ea762014-07-16 05:16:52 +00002243 if (Tok.isNot(tok::colon))
Richard Smith72553fc2014-01-23 23:53:27 +00002244 ParseDeclarator(DeclaratorInfo);
Richard Smith3d1a94c2014-08-12 00:22:39 +00002245 else
2246 DeclaratorInfo.SetIdentifier(nullptr, Tok.getLocation());
Richard Smith72553fc2014-01-23 23:53:27 +00002247
2248 if (!DeclaratorInfo.isFunctionDeclarator() && TryConsumeToken(tok::colon)) {
Richard Smith3d1a94c2014-08-12 00:22:39 +00002249 assert(DeclaratorInfo.isPastIdentifier() &&
2250 "don't know where identifier would go yet?");
Richard Smith72553fc2014-01-23 23:53:27 +00002251 BitfieldSize = ParseConstantExpression();
2252 if (BitfieldSize.isInvalid())
2253 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002254 } else {
Richard Smith3d1a94c2014-08-12 00:22:39 +00002255 ParseOptionalCXX11VirtSpecifierSeq(
2256 VS, getCurrentClass().IsInterface,
2257 DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002258 if (!VS.isUnset())
2259 MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo, VS);
2260 }
Richard Smith72553fc2014-01-23 23:53:27 +00002261
2262 // If a simple-asm-expr is present, parse it.
2263 if (Tok.is(tok::kw_asm)) {
2264 SourceLocation Loc;
2265 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
2266 if (AsmLabel.isInvalid())
2267 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2268
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002269 DeclaratorInfo.setAsmLabel(AsmLabel.get());
Richard Smith72553fc2014-01-23 23:53:27 +00002270 DeclaratorInfo.SetRangeEnd(Loc);
2271 }
2272
2273 // If attributes exist after the declarator, but before an '{', parse them.
2274 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
Richard Smith4b5a9492014-01-24 22:34:35 +00002275
2276 // For compatibility with code written to older Clang, also accept a
2277 // virt-specifier *after* the GNU attributes.
Aaron Ballman5d153e32014-08-04 17:03:51 +00002278 if (BitfieldSize.isUnset() && VS.isUnset()) {
Richard Smith3d1a94c2014-08-12 00:22:39 +00002279 ParseOptionalCXX11VirtSpecifierSeq(
2280 VS, getCurrentClass().IsInterface,
2281 DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
Aaron Ballman5d153e32014-08-04 17:03:51 +00002282 if (!VS.isUnset()) {
2283 // If we saw any GNU-style attributes that are known to GCC followed by a
2284 // virt-specifier, issue a GCC-compat warning.
2285 const AttributeList *Attr = DeclaratorInfo.getAttributes();
2286 while (Attr) {
2287 if (Attr->isKnownToGCC() && !Attr->isCXX11Attribute())
2288 Diag(Attr->getLoc(), diag::warn_gcc_attribute_location);
2289 Attr = Attr->getNext();
2290 }
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002291 MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo, VS);
Aaron Ballman5d153e32014-08-04 17:03:51 +00002292 }
2293 }
Nico Weberd89e6f72015-01-16 19:34:13 +00002294
2295 // If this has neither a name nor a bit width, something has gone seriously
2296 // wrong. Skip until the semi-colon or }.
2297 if (!DeclaratorInfo.hasName() && BitfieldSize.isUnset()) {
2298 // If so, skip until the semi-colon or a }.
2299 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2300 return true;
2301 }
2302 return false;
Richard Smith72553fc2014-01-23 23:53:27 +00002303}
2304
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002305/// \brief Look for declaration specifiers possibly occurring after C++11
2306/// virt-specifier-seq and diagnose them.
2307void Parser::MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(
2308 Declarator &D,
2309 VirtSpecifiers &VS) {
2310 DeclSpec DS(AttrFactory);
2311
2312 // GNU-style and C++11 attributes are not allowed here, but they will be
2313 // handled by the caller. Diagnose everything else.
Alex Lorenz8f4d3992017-02-13 23:19:40 +00002314 ParseTypeQualifierListOpt(
2315 DS, AR_NoAttributesParsed, false,
2316 /*IdentifierRequired=*/false, llvm::function_ref<void()>([&]() {
2317 Actions.CodeCompleteFunctionQualifiers(DS, D, &VS);
2318 }));
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002319 D.ExtendWithDeclSpec(DS);
2320
2321 if (D.isFunctionDeclarator()) {
Ehsan Akhgaric07d1e22015-03-25 00:53:33 +00002322 auto &Function = D.getFunctionTypeInfo();
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002323 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
2324 auto DeclSpecCheck = [&] (DeclSpec::TQ TypeQual,
2325 const char *FixItName,
2326 SourceLocation SpecLoc,
2327 unsigned* QualifierLoc) {
2328 FixItHint Insertion;
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002329 if (DS.getTypeQualifiers() & TypeQual) {
2330 if (!(Function.TypeQuals & TypeQual)) {
2331 std::string Name(FixItName);
2332 Name += " ";
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00002333 Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), Name);
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002334 Function.TypeQuals |= TypeQual;
2335 *QualifierLoc = SpecLoc.getRawEncoding();
2336 }
2337 Diag(SpecLoc, diag::err_declspec_after_virtspec)
2338 << FixItName
2339 << VirtSpecifiers::getSpecifierName(VS.getLastSpecifier())
2340 << FixItHint::CreateRemoval(SpecLoc)
2341 << Insertion;
2342 }
2343 };
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002344 DeclSpecCheck(DeclSpec::TQ_const, "const", DS.getConstSpecLoc(),
2345 &Function.ConstQualifierLoc);
2346 DeclSpecCheck(DeclSpec::TQ_volatile, "volatile", DS.getVolatileSpecLoc(),
2347 &Function.VolatileQualifierLoc);
2348 DeclSpecCheck(DeclSpec::TQ_restrict, "restrict", DS.getRestrictSpecLoc(),
2349 &Function.RestrictQualifierLoc);
2350 }
Ehsan Akhgaric07d1e22015-03-25 00:53:33 +00002351
2352 // Parse ref-qualifiers.
2353 bool RefQualifierIsLValueRef = true;
2354 SourceLocation RefQualifierLoc;
2355 if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc)) {
2356 const char *Name = (RefQualifierIsLValueRef ? "& " : "&& ");
2357 FixItHint Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), Name);
2358 Function.RefQualifierIsLValueRef = RefQualifierIsLValueRef;
2359 Function.RefQualifierLoc = RefQualifierLoc.getRawEncoding();
2360
2361 Diag(RefQualifierLoc, diag::err_declspec_after_virtspec)
2362 << (RefQualifierIsLValueRef ? "&" : "&&")
2363 << VirtSpecifiers::getSpecifierName(VS.getLastSpecifier())
2364 << FixItHint::CreateRemoval(RefQualifierLoc)
2365 << Insertion;
2366 D.SetRangeEnd(RefQualifierLoc);
2367 }
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002368 }
2369}
2370
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002371/// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration.
2372///
2373/// member-declaration:
2374/// decl-specifier-seq[opt] member-declarator-list[opt] ';'
2375/// function-definition ';'[opt]
2376/// ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO]
2377/// using-declaration [TODO]
Anders Carlssonf24fcff62009-03-11 16:27:10 +00002378/// [C++0x] static_assert-declaration
Anders Carlssondfbbdf62009-03-26 00:52:18 +00002379/// template-declaration
Chris Lattnerd19c1c02008-12-18 01:12:00 +00002380/// [GNU] '__extension__' member-declaration
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002381///
2382/// member-declarator-list:
2383/// member-declarator
2384/// member-declarator-list ',' member-declarator
2385///
2386/// member-declarator:
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002387/// declarator virt-specifier-seq[opt] pure-specifier[opt]
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002388/// declarator constant-initializer[opt]
Richard Smith938f40b2011-06-11 17:19:42 +00002389/// [C++11] declarator brace-or-equal-initializer[opt]
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002390/// identifier[opt] ':' constant-expression
2391///
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002392/// virt-specifier-seq:
2393/// virt-specifier
2394/// virt-specifier-seq virt-specifier
2395///
2396/// virt-specifier:
2397/// override
2398/// final
David Majnemera5433082013-10-18 00:33:31 +00002399/// [MS] sealed
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002400///
Sebastian Redl42e92c42009-04-12 17:16:29 +00002401/// pure-specifier:
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002402/// '= 0'
2403///
2404/// constant-initializer:
2405/// '=' constant-expression
2406///
Alexey Bataev05c25d62015-07-31 08:42:25 +00002407Parser::DeclGroupPtrTy
2408Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS,
2409 AttributeList *AccessAttrs,
John McCall796c2a52010-07-16 08:13:16 +00002410 const ParsedTemplateInfo &TemplateInfo,
2411 ParsingDeclRAIIObject *TemplateDiags) {
Douglas Gregor23c84762011-04-14 17:21:19 +00002412 if (Tok.is(tok::at)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002413 if (getLangOpts().ObjC1 && NextToken().isObjCAtKeyword(tok::objc_defs))
Douglas Gregor23c84762011-04-14 17:21:19 +00002414 Diag(Tok, diag::err_at_defs_cxx);
2415 else
2416 Diag(Tok, diag::err_at_in_class);
Richard Smithda35e962013-11-09 04:52:51 +00002417
Douglas Gregor23c84762011-04-14 17:21:19 +00002418 ConsumeToken();
Alexey Bataevee6507d2013-11-18 08:17:37 +00002419 SkipUntil(tok::r_brace, StopAtSemi);
David Blaikie0403cb12016-01-15 23:43:25 +00002420 return nullptr;
Douglas Gregor23c84762011-04-14 17:21:19 +00002421 }
Richard Smithda35e962013-11-09 04:52:51 +00002422
Serge Pavlov458ea762014-07-16 05:16:52 +00002423 // Turn on colon protection early, while parsing declspec, although there is
2424 // nothing to protect there. It prevents from false errors if error recovery
2425 // incorrectly determines where the declspec ends, as in the example:
2426 // struct A { enum class B { C }; };
2427 // const int C = 4;
2428 // struct D { A::B : C; };
2429 ColonProtectionRAIIObject X(*this);
2430
John McCalla0097262009-12-11 02:10:03 +00002431 // Access declarations.
Richard Smith45855df2012-05-09 08:23:23 +00002432 bool MalformedTypeSpec = false;
John McCalla0097262009-12-11 02:10:03 +00002433 if (!TemplateInfo.Kind &&
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002434 Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw___super)) {
Richard Smith45855df2012-05-09 08:23:23 +00002435 if (TryAnnotateCXXScopeToken())
2436 MalformedTypeSpec = true;
2437
2438 bool isAccessDecl;
2439 if (Tok.isNot(tok::annot_cxxscope))
2440 isAccessDecl = false;
2441 else if (NextToken().is(tok::identifier))
John McCalla0097262009-12-11 02:10:03 +00002442 isAccessDecl = GetLookAheadToken(2).is(tok::semi);
2443 else
2444 isAccessDecl = NextToken().is(tok::kw_operator);
2445
2446 if (isAccessDecl) {
2447 // Collect the scope specifier token we annotated earlier.
2448 CXXScopeSpec SS;
David Blaikieefdccaa2016-01-15 23:43:34 +00002449 ParseOptionalCXXScopeSpecifier(SS, nullptr,
Douglas Gregordf593fb2011-11-07 17:33:42 +00002450 /*EnteringContext=*/false);
John McCalla0097262009-12-11 02:10:03 +00002451
Nico Weberef03e702014-09-10 00:59:37 +00002452 if (SS.isInvalid()) {
2453 SkipUntil(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002454 return nullptr;
Nico Weberef03e702014-09-10 00:59:37 +00002455 }
2456
John McCalla0097262009-12-11 02:10:03 +00002457 // Try to parse an unqualified-id.
Abramo Bagnara7945c982012-01-27 09:46:47 +00002458 SourceLocation TemplateKWLoc;
John McCalla0097262009-12-11 02:10:03 +00002459 UnqualifiedId Name;
Richard Smith35845152017-02-07 01:37:30 +00002460 if (ParseUnqualifiedId(SS, false, true, true, false, nullptr,
2461 TemplateKWLoc, Name)) {
John McCalla0097262009-12-11 02:10:03 +00002462 SkipUntil(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002463 return nullptr;
John McCalla0097262009-12-11 02:10:03 +00002464 }
2465
2466 // TODO: recover from mistakenly-qualified operator declarations.
Alp Toker383d2c42014-01-01 03:08:43 +00002467 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
2468 "access declaration")) {
2469 SkipUntil(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002470 return nullptr;
Alp Toker383d2c42014-01-01 03:08:43 +00002471 }
John McCalla0097262009-12-11 02:10:03 +00002472
Alexey Bataev05c25d62015-07-31 08:42:25 +00002473 return DeclGroupPtrTy::make(DeclGroupRef(Actions.ActOnUsingDeclaration(
Richard Smith151c4562016-12-20 21:35:28 +00002474 getCurScope(), AS, /*UsingLoc*/ SourceLocation(),
2475 /*TypenameLoc*/ SourceLocation(), SS, Name,
2476 /*EllipsisLoc*/ SourceLocation(), /*AttrList*/ nullptr)));
John McCalla0097262009-12-11 02:10:03 +00002477 }
2478 }
2479
Aaron Ballmane7c544d2014-08-04 20:28:35 +00002480 // static_assert-declaration. A templated static_assert declaration is
2481 // diagnosed in Parser::ParseSingleDeclarationAfterTemplate.
2482 if (!TemplateInfo.Kind &&
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002483 Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert)) {
Chris Lattner49836b42009-04-02 04:16:50 +00002484 SourceLocation DeclEnd;
Alexey Bataev05c25d62015-07-31 08:42:25 +00002485 return DeclGroupPtrTy::make(
2486 DeclGroupRef(ParseStaticAssertDeclaration(DeclEnd)));
Chris Lattner5bbb3c82009-03-29 16:50:03 +00002487 }
Mike Stump11289f42009-09-09 15:08:12 +00002488
Chris Lattner5bbb3c82009-03-29 16:50:03 +00002489 if (Tok.is(tok::kw_template)) {
Mike Stump11289f42009-09-09 15:08:12 +00002490 assert(!TemplateInfo.TemplateParams &&
Douglas Gregor3447e762009-08-20 22:52:58 +00002491 "Nested template improperly parsed?");
Richard Smith3af70092017-02-09 22:14:25 +00002492 ObjCDeclContextSwitch ObjCDC(*this);
Chris Lattner49836b42009-04-02 04:16:50 +00002493 SourceLocation DeclEnd;
Alexey Bataev05c25d62015-07-31 08:42:25 +00002494 return DeclGroupPtrTy::make(
Richard Smith3af70092017-02-09 22:14:25 +00002495 DeclGroupRef(ParseTemplateDeclarationOrSpecialization(
Alexey Bataev05c25d62015-07-31 08:42:25 +00002496 Declarator::MemberContext, DeclEnd, AS, AccessAttrs)));
Chris Lattner5bbb3c82009-03-29 16:50:03 +00002497 }
Anders Carlssondfbbdf62009-03-26 00:52:18 +00002498
Chris Lattnerd19c1c02008-12-18 01:12:00 +00002499 // Handle: member-declaration ::= '__extension__' member-declaration
2500 if (Tok.is(tok::kw___extension__)) {
2501 // __extension__ silences extension warnings in the subexpression.
2502 ExtensionRAIIObject O(Diags); // Use RAII to do this.
2503 ConsumeToken();
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00002504 return ParseCXXClassMemberDeclaration(AS, AccessAttrs,
2505 TemplateInfo, TemplateDiags);
Chris Lattnerd19c1c02008-12-18 01:12:00 +00002506 }
Douglas Gregorfec52632009-06-20 00:51:54 +00002507
John McCall084e83d2011-03-24 11:26:52 +00002508 ParsedAttributesWithRange attrs(AttrFactory);
Michael Handdc016d2012-11-28 23:17:40 +00002509 ParsedAttributesWithRange FnAttrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00002510 // Optional C++11 attribute-specifier
2511 MaybeParseCXX11Attributes(attrs);
Michael Handdc016d2012-11-28 23:17:40 +00002512 // We need to keep these attributes for future diagnostic
2513 // before they are taken over by declaration specifier.
2514 FnAttrs.addAll(attrs.getList());
2515 FnAttrs.Range = attrs.Range;
2516
John McCall53fa7142010-12-24 02:08:15 +00002517 MaybeParseMicrosoftAttributes(attrs);
Alexis Hunt96d5c762009-11-21 08:43:09 +00002518
Douglas Gregorfec52632009-06-20 00:51:54 +00002519 if (Tok.is(tok::kw_using)) {
John McCall53fa7142010-12-24 02:08:15 +00002520 ProhibitAttributes(attrs);
Mike Stump11289f42009-09-09 15:08:12 +00002521
Douglas Gregorfec52632009-06-20 00:51:54 +00002522 // Eat 'using'.
2523 SourceLocation UsingLoc = ConsumeToken();
2524
2525 if (Tok.is(tok::kw_namespace)) {
2526 Diag(UsingLoc, diag::err_using_namespace_in_class);
Alexey Bataevee6507d2013-11-18 08:17:37 +00002527 SkipUntil(tok::semi, StopBeforeMatch);
David Blaikie0403cb12016-01-15 23:43:25 +00002528 return nullptr;
Douglas Gregorfec52632009-06-20 00:51:54 +00002529 }
Alexey Bataev05c25d62015-07-31 08:42:25 +00002530 SourceLocation DeclEnd;
2531 // Otherwise, it must be a using-declaration or an alias-declaration.
Richard Smith6f1daa42016-12-16 00:58:48 +00002532 return ParseUsingDeclaration(Declarator::MemberContext, TemplateInfo,
2533 UsingLoc, DeclEnd, AS);
Douglas Gregorfec52632009-06-20 00:51:54 +00002534 }
2535
DeLesley Hutchinsbd2ee132012-03-02 22:12:59 +00002536 // Hold late-parsed attributes so we can attach a Decl to them later.
2537 LateParsedAttrList CommonLateParsedAttrs;
2538
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002539 // decl-specifier-seq:
2540 // Parse the common declaration-specifiers piece.
John McCall796c2a52010-07-16 08:13:16 +00002541 ParsingDeclSpec DS(*this, TemplateDiags);
John McCall53fa7142010-12-24 02:08:15 +00002542 DS.takeAttributesFrom(attrs);
Richard Smith45855df2012-05-09 08:23:23 +00002543 if (MalformedTypeSpec)
2544 DS.SetTypeSpecError();
Richard Smith72553fc2014-01-23 23:53:27 +00002545
Serge Pavlov458ea762014-07-16 05:16:52 +00002546 ParseDeclarationSpecifiers(DS, TemplateInfo, AS, DSC_class,
2547 &CommonLateParsedAttrs);
2548
2549 // Turn off colon protection that was set for declspec.
2550 X.restore();
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002551
Richard Smith404dfb42013-11-19 22:47:36 +00002552 // If we had a free-standing type definition with a missing semicolon, we
2553 // may get this far before the problem becomes obvious.
2554 if (DS.hasTagDefinition() &&
2555 TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate &&
2556 DiagnoseMissingSemiAfterTagDefinition(DS, AS, DSC_class,
2557 &CommonLateParsedAttrs))
David Blaikie0403cb12016-01-15 23:43:25 +00002558 return nullptr;
Richard Smith404dfb42013-11-19 22:47:36 +00002559
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002560 MultiTemplateParamsArg TemplateParams(
Craig Topper161e4db2014-05-21 06:02:52 +00002561 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->data()
2562 : nullptr,
John McCall11083da2009-09-16 22:47:08 +00002563 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->size() : 0);
2564
Alp Toker35d87032013-12-30 23:29:50 +00002565 if (TryConsumeToken(tok::semi)) {
Michael Handdc016d2012-11-28 23:17:40 +00002566 if (DS.isFriendSpecified())
2567 ProhibitAttributes(FnAttrs);
2568
Nico Weber7b837f52016-01-28 19:25:00 +00002569 RecordDecl *AnonRecord = nullptr;
2570 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(
2571 getCurScope(), AS, DS, TemplateParams, false, AnonRecord);
John McCall796c2a52010-07-16 08:13:16 +00002572 DS.complete(TheDecl);
Nico Weber7b837f52016-01-28 19:25:00 +00002573 if (AnonRecord) {
2574 Decl* decls[] = {AnonRecord, TheDecl};
Richard Smith3beb7c62017-01-12 02:27:38 +00002575 return Actions.BuildDeclaratorGroup(decls);
Nico Weber7b837f52016-01-28 19:25:00 +00002576 }
2577 return Actions.ConvertDeclToDeclGroup(TheDecl);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002578 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002579
John McCall28a6aea2009-11-04 02:18:39 +00002580 ParsingDeclarator DeclaratorInfo(*this, DS, Declarator::MemberContext);
Nico Weber24b2a822011-01-28 06:07:34 +00002581 VirtSpecifiers VS;
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002582
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002583 // Hold late-parsed attributes so we can attach a Decl to them later.
2584 LateParsedAttrList LateParsedAttrs;
2585
Douglas Gregor50cefbf2011-10-17 17:09:53 +00002586 SourceLocation EqualLoc;
Richard Smith9ba0fec2015-06-30 01:28:56 +00002587 SourceLocation PureSpecLoc;
2588
Yaron Keren180c1672015-06-30 07:35:19 +00002589 auto TryConsumePureSpecifier = [&] (bool AllowDefinition) {
Richard Smith9ba0fec2015-06-30 01:28:56 +00002590 if (Tok.isNot(tok::equal))
2591 return false;
2592
2593 auto &Zero = NextToken();
2594 SmallString<8> Buffer;
2595 if (Zero.isNot(tok::numeric_constant) || Zero.getLength() != 1 ||
2596 PP.getSpelling(Zero, Buffer) != "0")
2597 return false;
2598
2599 auto &After = GetLookAheadToken(2);
2600 if (!After.isOneOf(tok::semi, tok::comma) &&
2601 !(AllowDefinition &&
2602 After.isOneOf(tok::l_brace, tok::colon, tok::kw_try)))
2603 return false;
2604
2605 EqualLoc = ConsumeToken();
2606 PureSpecLoc = ConsumeToken();
2607 return true;
2608 };
Chris Lattner17c3b1f2009-12-10 01:59:24 +00002609
Richard Smith72553fc2014-01-23 23:53:27 +00002610 SmallVector<Decl *, 8> DeclsInGroup;
2611 ExprResult BitfieldSize;
2612 bool ExpectSemi = true;
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002613
Richard Smith72553fc2014-01-23 23:53:27 +00002614 // Parse the first declarator.
Nico Weberd89e6f72015-01-16 19:34:13 +00002615 if (ParseCXXMemberDeclaratorBeforeInitializer(
2616 DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs)) {
Richard Smith72553fc2014-01-23 23:53:27 +00002617 TryConsumeToken(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002618 return nullptr;
Richard Smith72553fc2014-01-23 23:53:27 +00002619 }
John Thompson5bc5cbe2009-11-25 22:58:06 +00002620
Richard Smith72553fc2014-01-23 23:53:27 +00002621 // Check for a member function definition.
Richard Smith4b5a9492014-01-24 22:34:35 +00002622 if (BitfieldSize.isUnset()) {
Richard Smith72553fc2014-01-23 23:53:27 +00002623 // MSVC permits pure specifier on inline functions defined at class scope.
Francois Pichet3abc9b82011-05-11 02:14:46 +00002624 // Hence check for =0 before checking for function definition.
Richard Smith9ba0fec2015-06-30 01:28:56 +00002625 if (getLangOpts().MicrosoftExt && DeclaratorInfo.isDeclarationOfFunction())
2626 TryConsumePureSpecifier(/*AllowDefinition*/ true);
Francois Pichet3abc9b82011-05-11 02:14:46 +00002627
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00002628 FunctionDefinitionKind DefinitionKind = FDK_Declaration;
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002629 // function-definition:
Richard Smith938f40b2011-06-11 17:19:42 +00002630 //
2631 // In C++11, a non-function declarator followed by an open brace is a
2632 // braced-init-list for an in-class member initialization, not an
2633 // erroneous function definition.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002634 if (Tok.is(tok::l_brace) && !getLangOpts().CPlusPlus11) {
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00002635 DefinitionKind = FDK_Definition;
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002636 } else if (DeclaratorInfo.isFunctionDeclarator()) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002637 if (Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try)) {
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00002638 DefinitionKind = FDK_Definition;
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002639 } else if (Tok.is(tok::equal)) {
2640 const Token &KW = NextToken();
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00002641 if (KW.is(tok::kw_default))
2642 DefinitionKind = FDK_Defaulted;
2643 else if (KW.is(tok::kw_delete))
2644 DefinitionKind = FDK_Deleted;
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002645 }
2646 }
Eli Bendersky41842222015-03-23 23:49:41 +00002647 DeclaratorInfo.setFunctionDefinitionKind(DefinitionKind);
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002648
Michael Handdc016d2012-11-28 23:17:40 +00002649 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
2650 // to a friend declaration, that declaration shall be a definition.
2651 if (DeclaratorInfo.isFunctionDeclarator() &&
2652 DefinitionKind != FDK_Definition && DS.isFriendSpecified()) {
2653 // Diagnose attributes that appear before decl specifier:
2654 // [[]] friend int foo();
2655 ProhibitAttributes(FnAttrs);
2656 }
2657
Nico Webera7f137d2015-01-16 19:35:01 +00002658 if (DefinitionKind != FDK_Declaration) {
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002659 if (!DeclaratorInfo.isFunctionDeclarator()) {
Richard Trieu0d730542012-01-21 02:59:18 +00002660 Diag(DeclaratorInfo.getIdentifierLoc(), diag::err_func_def_no_params);
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002661 ConsumeBrace();
Alexey Bataevee6507d2013-11-18 08:17:37 +00002662 SkipUntil(tok::r_brace);
Michael Handdc016d2012-11-28 23:17:40 +00002663
Douglas Gregor8a4db832011-01-19 16:41:58 +00002664 // Consume the optional ';'
Alp Toker35d87032013-12-30 23:29:50 +00002665 TryConsumeToken(tok::semi);
2666
David Blaikie0403cb12016-01-15 23:43:25 +00002667 return nullptr;
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002668 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002669
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002670 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
Richard Trieu0d730542012-01-21 02:59:18 +00002671 Diag(DeclaratorInfo.getIdentifierLoc(),
2672 diag::err_function_declared_typedef);
Douglas Gregor8a4db832011-01-19 16:41:58 +00002673
Richard Smith2603b092012-11-15 22:54:20 +00002674 // Recover by treating the 'typedef' as spurious.
2675 DS.ClearStorageClassSpecs();
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002676 }
2677
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002678 Decl *FunDecl =
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00002679 ParseCXXInlineMethodDef(AS, AccessAttrs, DeclaratorInfo, TemplateInfo,
Richard Smith9ba0fec2015-06-30 01:28:56 +00002680 VS, PureSpecLoc);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002681
David Majnemer23252a32013-08-01 04:22:55 +00002682 if (FunDecl) {
2683 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i) {
2684 CommonLateParsedAttrs[i]->addDecl(FunDecl);
2685 }
2686 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i) {
2687 LateParsedAttrs[i]->addDecl(FunDecl);
2688 }
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002689 }
2690 LateParsedAttrs.clear();
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002691
2692 // Consume the ';' - it's optional unless we have a delete or default
Richard Trieu2f7dc462012-05-16 19:04:59 +00002693 if (Tok.is(tok::semi))
Richard Smith87f5dc52012-07-23 05:45:25 +00002694 ConsumeExtraSemi(AfterMemberFunctionDefinition);
Douglas Gregor8a4db832011-01-19 16:41:58 +00002695
Alexey Bataev05c25d62015-07-31 08:42:25 +00002696 return DeclGroupPtrTy::make(DeclGroupRef(FunDecl));
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002697 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002698 }
2699
2700 // member-declarator-list:
2701 // member-declarator
2702 // member-declarator-list ',' member-declarator
2703
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002704 while (1) {
Richard Smith2b013182012-06-10 03:12:00 +00002705 InClassInitStyle HasInClassInit = ICIS_NoInit;
Richard Smith9ba0fec2015-06-30 01:28:56 +00002706 bool HasStaticInitializer = false;
2707 if (Tok.isOneOf(tok::equal, tok::l_brace) && PureSpecLoc.isInvalid()) {
Richard Smith938f40b2011-06-11 17:19:42 +00002708 if (BitfieldSize.get()) {
2709 Diag(Tok, diag::err_bitfield_member_init);
Alexey Bataevee6507d2013-11-18 08:17:37 +00002710 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
Richard Smith9ba0fec2015-06-30 01:28:56 +00002711 } else if (DeclaratorInfo.isDeclarationOfFunction()) {
2712 // It's a pure-specifier.
2713 if (!TryConsumePureSpecifier(/*AllowFunctionDefinition*/ false))
2714 // Parse it as an expression so that Sema can diagnose it.
2715 HasStaticInitializer = true;
2716 } else if (DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2717 DeclSpec::SCS_static &&
2718 DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2719 DeclSpec::SCS_typedef &&
2720 !DS.isFriendSpecified()) {
2721 // It's a default member initializer.
2722 HasInClassInit = Tok.is(tok::equal) ? ICIS_CopyInit : ICIS_ListInit;
Richard Smith938f40b2011-06-11 17:19:42 +00002723 } else {
Richard Smith9ba0fec2015-06-30 01:28:56 +00002724 HasStaticInitializer = true;
Richard Smith938f40b2011-06-11 17:19:42 +00002725 }
2726 }
2727
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002728 // NOTE: If Sema is the Action module and declarator is an instance field,
Chris Lattner5bbb3c82009-03-29 16:50:03 +00002729 // this call will *not* return the created decl; It will return null.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002730 // See Sema::ActOnCXXMemberDeclarator for details.
John McCall07e91c02009-08-06 02:15:43 +00002731
Craig Topper161e4db2014-05-21 06:02:52 +00002732 NamedDecl *ThisDecl = nullptr;
John McCall07e91c02009-08-06 02:15:43 +00002733 if (DS.isFriendSpecified()) {
Richard Smith72553fc2014-01-23 23:53:27 +00002734 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
Michael Handdc016d2012-11-28 23:17:40 +00002735 // to a friend declaration, that declaration shall be a definition.
2736 //
Richard Smith72553fc2014-01-23 23:53:27 +00002737 // Diagnose attributes that appear in a friend member function declarator:
2738 // friend int foo [[]] ();
Michael Handdc016d2012-11-28 23:17:40 +00002739 SmallVector<SourceRange, 4> Ranges;
2740 DeclaratorInfo.getCXX11AttributeRanges(Ranges);
Richard Smith72553fc2014-01-23 23:53:27 +00002741 for (SmallVectorImpl<SourceRange>::iterator I = Ranges.begin(),
2742 E = Ranges.end(); I != E; ++I)
2743 Diag((*I).getBegin(), diag::err_attributes_not_allowed) << *I;
Michael Handdc016d2012-11-28 23:17:40 +00002744
Douglas Gregor0be31a22010-07-02 17:43:08 +00002745 ThisDecl = Actions.ActOnFriendFunctionDecl(getCurScope(), DeclaratorInfo,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002746 TemplateParams);
Douglas Gregor3447e762009-08-20 22:52:58 +00002747 } else {
Douglas Gregor0be31a22010-07-02 17:43:08 +00002748 ThisDecl = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS,
John McCall07e91c02009-08-06 02:15:43 +00002749 DeclaratorInfo,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002750 TemplateParams,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002751 BitfieldSize.get(),
Richard Smith2b013182012-06-10 03:12:00 +00002752 VS, HasInClassInit);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002753
2754 if (VarTemplateDecl *VT =
Craig Topper161e4db2014-05-21 06:02:52 +00002755 ThisDecl ? dyn_cast<VarTemplateDecl>(ThisDecl) : nullptr)
Larisse Voufo39a1e502013-08-06 01:03:05 +00002756 // Re-direct this decl to refer to the templated decl so that we can
2757 // initialize it.
2758 ThisDecl = VT->getTemplatedDecl();
2759
David Majnemer23252a32013-08-01 04:22:55 +00002760 if (ThisDecl && AccessAttrs)
Richard Smithf8a75c32013-08-29 00:47:48 +00002761 Actions.ProcessDeclAttributeList(getCurScope(), ThisDecl, AccessAttrs);
Douglas Gregor3447e762009-08-20 22:52:58 +00002762 }
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002763
Richard Smith9ba0fec2015-06-30 01:28:56 +00002764 // Error recovery might have converted a non-static member into a static
2765 // member.
David Blaikie35506f82013-01-30 01:22:18 +00002766 if (HasInClassInit != ICIS_NoInit &&
Richard Smith9ba0fec2015-06-30 01:28:56 +00002767 DeclaratorInfo.getDeclSpec().getStorageClassSpec() ==
2768 DeclSpec::SCS_static) {
2769 HasInClassInit = ICIS_NoInit;
2770 HasStaticInitializer = true;
2771 }
2772
2773 if (ThisDecl && PureSpecLoc.isValid())
2774 Actions.ActOnPureSpecifier(ThisDecl, PureSpecLoc);
2775
2776 // Handle the initializer.
2777 if (HasInClassInit != ICIS_NoInit) {
Douglas Gregor728d00b2011-10-10 14:49:18 +00002778 // The initializer was deferred; parse it and cache the tokens.
David Majnemer23252a32013-08-01 04:22:55 +00002779 Diag(Tok, getLangOpts().CPlusPlus11
2780 ? diag::warn_cxx98_compat_nonstatic_member_init
2781 : diag::ext_nonstatic_member_init);
Richard Smith5d164bc2011-10-15 05:09:34 +00002782
Richard Smith938f40b2011-06-11 17:19:42 +00002783 if (DeclaratorInfo.isArrayOfUnknownBound()) {
Richard Smith2b013182012-06-10 03:12:00 +00002784 // C++11 [dcl.array]p3: An array bound may also be omitted when the
2785 // declarator is followed by an initializer.
Richard Smith938f40b2011-06-11 17:19:42 +00002786 //
2787 // A brace-or-equal-initializer for a member-declarator is not an
David Blaikiecdd91db2012-02-14 09:00:46 +00002788 // initializer in the grammar, so this is ill-formed.
Richard Smith938f40b2011-06-11 17:19:42 +00002789 Diag(Tok, diag::err_incomplete_array_member_init);
Alexey Bataevee6507d2013-11-18 08:17:37 +00002790 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
David Majnemer23252a32013-08-01 04:22:55 +00002791
2792 // Avoid later warnings about a class member of incomplete type.
David Blaikiecdd91db2012-02-14 09:00:46 +00002793 if (ThisDecl)
David Blaikiecdd91db2012-02-14 09:00:46 +00002794 ThisDecl->setInvalidDecl();
Richard Smith938f40b2011-06-11 17:19:42 +00002795 } else
2796 ParseCXXNonStaticMemberInitializer(ThisDecl);
Richard Smith9ba0fec2015-06-30 01:28:56 +00002797 } else if (HasStaticInitializer) {
Douglas Gregor728d00b2011-10-10 14:49:18 +00002798 // Normal initializer.
Richard Smith9ba0fec2015-06-30 01:28:56 +00002799 ExprResult Init = ParseCXXMemberInitializer(
2800 ThisDecl, DeclaratorInfo.isDeclarationOfFunction(), EqualLoc);
David Majnemer23252a32013-08-01 04:22:55 +00002801
Douglas Gregor728d00b2011-10-10 14:49:18 +00002802 if (Init.isInvalid())
Alexey Bataevee6507d2013-11-18 08:17:37 +00002803 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
Douglas Gregor728d00b2011-10-10 14:49:18 +00002804 else if (ThisDecl)
Richard Smith3beb7c62017-01-12 02:27:38 +00002805 Actions.AddInitializerToDecl(ThisDecl, Init.get(), EqualLoc.isInvalid());
David Majnemer23252a32013-08-01 04:22:55 +00002806 } else if (ThisDecl && DS.getStorageClassSpec() == DeclSpec::SCS_static)
Douglas Gregor728d00b2011-10-10 14:49:18 +00002807 // No initializer.
Richard Smith3beb7c62017-01-12 02:27:38 +00002808 Actions.ActOnUninitializedDecl(ThisDecl);
David Majnemer23252a32013-08-01 04:22:55 +00002809
Douglas Gregor728d00b2011-10-10 14:49:18 +00002810 if (ThisDecl) {
David Majnemer23252a32013-08-01 04:22:55 +00002811 if (!ThisDecl->isInvalidDecl()) {
2812 // Set the Decl for any late parsed attributes
2813 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i)
2814 CommonLateParsedAttrs[i]->addDecl(ThisDecl);
2815
2816 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i)
2817 LateParsedAttrs[i]->addDecl(ThisDecl);
2818 }
Douglas Gregor728d00b2011-10-10 14:49:18 +00002819 Actions.FinalizeDeclaration(ThisDecl);
2820 DeclsInGroup.push_back(ThisDecl);
David Majnemer23252a32013-08-01 04:22:55 +00002821
2822 if (DeclaratorInfo.isFunctionDeclarator() &&
2823 DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2824 DeclSpec::SCS_typedef)
2825 HandleMemberFunctionDeclDelays(DeclaratorInfo, ThisDecl);
Douglas Gregor728d00b2011-10-10 14:49:18 +00002826 }
David Majnemer23252a32013-08-01 04:22:55 +00002827 LateParsedAttrs.clear();
Douglas Gregor728d00b2011-10-10 14:49:18 +00002828
2829 DeclaratorInfo.complete(ThisDecl);
Richard Smith938f40b2011-06-11 17:19:42 +00002830
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002831 // If we don't have a comma, it is either the end of the list (a ';')
2832 // or an error, bail out.
Alp Toker094e5212014-01-05 03:27:11 +00002833 SourceLocation CommaLoc;
2834 if (!TryConsumeToken(tok::comma, CommaLoc))
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002835 break;
Mike Stump11289f42009-09-09 15:08:12 +00002836
Richard Smithc8a79032012-01-09 22:31:44 +00002837 if (Tok.isAtStartOfLine() &&
2838 !MightBeDeclarator(Declarator::MemberContext)) {
2839 // This comma was followed by a line-break and something which can't be
2840 // the start of a declarator. The comma was probably a typo for a
2841 // semicolon.
2842 Diag(CommaLoc, diag::err_expected_semi_declaration)
2843 << FixItHint::CreateReplacement(CommaLoc, ";");
2844 ExpectSemi = false;
2845 break;
2846 }
Mike Stump11289f42009-09-09 15:08:12 +00002847
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002848 // Parse the next declarator.
2849 DeclaratorInfo.clear();
Nico Weber24b2a822011-01-28 06:07:34 +00002850 VS.clear();
Nico Weberf56c85b2015-01-17 02:26:40 +00002851 BitfieldSize = ExprResult(/*Invalid=*/false);
Richard Smith9ba0fec2015-06-30 01:28:56 +00002852 EqualLoc = PureSpecLoc = SourceLocation();
Richard Smith8d06f422012-01-12 23:53:29 +00002853 DeclaratorInfo.setCommaLoc(CommaLoc);
Mike Stump11289f42009-09-09 15:08:12 +00002854
Richard Smith72553fc2014-01-23 23:53:27 +00002855 // GNU attributes are allowed before the second and subsequent declarator.
John McCall53fa7142010-12-24 02:08:15 +00002856 MaybeParseGNUAttributes(DeclaratorInfo);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002857
Nico Weberd89e6f72015-01-16 19:34:13 +00002858 if (ParseCXXMemberDeclaratorBeforeInitializer(
2859 DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs))
2860 break;
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002861 }
2862
Richard Smithc8a79032012-01-09 22:31:44 +00002863 if (ExpectSemi &&
2864 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list)) {
Chris Lattner916dbf12010-02-02 00:43:15 +00002865 // Skip to end of block or statement.
Alexey Bataevee6507d2013-11-18 08:17:37 +00002866 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Chris Lattner916dbf12010-02-02 00:43:15 +00002867 // If we stopped at a ';', eat it.
Alp Toker35d87032013-12-30 23:29:50 +00002868 TryConsumeToken(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002869 return nullptr;
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002870 }
2871
Alexey Bataev05c25d62015-07-31 08:42:25 +00002872 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002873}
2874
Richard Smith9ba0fec2015-06-30 01:28:56 +00002875/// ParseCXXMemberInitializer - Parse the brace-or-equal-initializer.
2876/// Also detect and reject any attempted defaulted/deleted function definition.
2877/// The location of the '=', if any, will be placed in EqualLoc.
Richard Smith938f40b2011-06-11 17:19:42 +00002878///
Richard Smith9ba0fec2015-06-30 01:28:56 +00002879/// This does not check for a pure-specifier; that's handled elsewhere.
Sebastian Redleef474c2012-02-22 10:50:08 +00002880///
Richard Smith938f40b2011-06-11 17:19:42 +00002881/// brace-or-equal-initializer:
2882/// '=' initializer-expression
Sebastian Redleef474c2012-02-22 10:50:08 +00002883/// braced-init-list
2884///
Richard Smith938f40b2011-06-11 17:19:42 +00002885/// initializer-clause:
2886/// assignment-expression
Sebastian Redleef474c2012-02-22 10:50:08 +00002887/// braced-init-list
2888///
Richard Smithda35e962013-11-09 04:52:51 +00002889/// defaulted/deleted function-definition:
Richard Smith938f40b2011-06-11 17:19:42 +00002890/// '=' 'default'
2891/// '=' 'delete'
2892///
2893/// Prior to C++0x, the assignment-expression in an initializer-clause must
2894/// be a constant-expression.
Douglas Gregor926410d2012-02-21 02:22:07 +00002895ExprResult Parser::ParseCXXMemberInitializer(Decl *D, bool IsFunction,
Richard Smith938f40b2011-06-11 17:19:42 +00002896 SourceLocation &EqualLoc) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002897 assert(Tok.isOneOf(tok::equal, tok::l_brace)
Richard Smith938f40b2011-06-11 17:19:42 +00002898 && "Data member initializer not starting with '=' or '{'");
2899
Douglas Gregor926410d2012-02-21 02:22:07 +00002900 EnterExpressionEvaluationContext Context(Actions,
2901 Sema::PotentiallyEvaluated,
2902 D);
Alp Toker094e5212014-01-05 03:27:11 +00002903 if (TryConsumeToken(tok::equal, EqualLoc)) {
Richard Smith938f40b2011-06-11 17:19:42 +00002904 if (Tok.is(tok::kw_delete)) {
2905 // In principle, an initializer of '= delete p;' is legal, but it will
2906 // never type-check. It's better to diagnose it as an ill-formed expression
2907 // than as an ill-formed deleted non-function member.
2908 // An initializer of '= delete p, foo' will never be parsed, because
2909 // a top-level comma always ends the initializer expression.
2910 const Token &Next = NextToken();
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002911 if (IsFunction || Next.isOneOf(tok::semi, tok::comma, tok::eof)) {
Richard Smith938f40b2011-06-11 17:19:42 +00002912 if (IsFunction)
2913 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2914 << 1 /* delete */;
2915 else
2916 Diag(ConsumeToken(), diag::err_deleted_non_function);
Richard Smithedcb26e2014-06-11 00:49:52 +00002917 return ExprError();
Richard Smith938f40b2011-06-11 17:19:42 +00002918 }
2919 } else if (Tok.is(tok::kw_default)) {
Richard Smith938f40b2011-06-11 17:19:42 +00002920 if (IsFunction)
2921 Diag(Tok, diag::err_default_delete_in_multiple_declaration)
2922 << 0 /* default */;
2923 else
2924 Diag(ConsumeToken(), diag::err_default_special_members);
Richard Smithedcb26e2014-06-11 00:49:52 +00002925 return ExprError();
Richard Smith938f40b2011-06-11 17:19:42 +00002926 }
David Majnemer87ff66c2014-12-13 11:34:16 +00002927 }
2928 if (const auto *PD = dyn_cast_or_null<MSPropertyDecl>(D)) {
2929 Diag(Tok, diag::err_ms_property_initializer) << PD;
2930 return ExprError();
Sebastian Redleef474c2012-02-22 10:50:08 +00002931 }
2932 return ParseInitializer();
Richard Smith938f40b2011-06-11 17:19:42 +00002933}
2934
Richard Smith65ebb4a2015-03-26 04:09:53 +00002935void Parser::SkipCXXMemberSpecification(SourceLocation RecordLoc,
2936 SourceLocation AttrFixitLoc,
2937 unsigned TagType, Decl *TagDecl) {
2938 // Skip the optional 'final' keyword.
2939 if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
2940 assert(isCXX11FinalKeyword() && "not a class definition");
2941 ConsumeToken();
2942
2943 // Diagnose any C++11 attributes after 'final' keyword.
2944 // We deliberately discard these attributes.
2945 ParsedAttributesWithRange Attrs(AttrFactory);
2946 CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
2947
2948 // This can only happen if we had malformed misplaced attributes;
2949 // we only get called if there is a colon or left-brace after the
2950 // attributes.
2951 if (Tok.isNot(tok::colon) && Tok.isNot(tok::l_brace))
2952 return;
2953 }
2954
2955 // Skip the base clauses. This requires actually parsing them, because
2956 // otherwise we can't be sure where they end (a left brace may appear
2957 // within a template argument).
2958 if (Tok.is(tok::colon)) {
2959 // Enter the scope of the class so that we can correctly parse its bases.
2960 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
2961 ParsingClassDefinition ParsingDef(*this, TagDecl, /*NonNestedClass*/ true,
2962 TagType == DeclSpec::TST_interface);
Richard Smith0f192e82015-06-11 22:48:25 +00002963 auto OldContext =
2964 Actions.ActOnTagStartSkippedDefinition(getCurScope(), TagDecl);
Richard Smith65ebb4a2015-03-26 04:09:53 +00002965
2966 // Parse the bases but don't attach them to the class.
2967 ParseBaseClause(nullptr);
2968
Richard Smith0f192e82015-06-11 22:48:25 +00002969 Actions.ActOnTagFinishSkippedDefinition(OldContext);
Richard Smith65ebb4a2015-03-26 04:09:53 +00002970
2971 if (!Tok.is(tok::l_brace)) {
2972 Diag(PP.getLocForEndOfToken(PrevTokLocation),
2973 diag::err_expected_lbrace_after_base_specifiers);
2974 return;
2975 }
2976 }
2977
2978 // Skip the body.
2979 assert(Tok.is(tok::l_brace));
2980 BalancedDelimiterTracker T(*this, tok::l_brace);
2981 T.consumeOpen();
2982 T.skipToEnd();
Richard Smith04c6c1f2015-07-01 18:56:50 +00002983
2984 // Parse and discard any trailing attributes.
2985 ParsedAttributes Attrs(AttrFactory);
2986 if (Tok.is(tok::kw___attribute))
2987 MaybeParseGNUAttributes(Attrs);
Richard Smith65ebb4a2015-03-26 04:09:53 +00002988}
2989
Alexey Bataev05c25d62015-07-31 08:42:25 +00002990Parser::DeclGroupPtrTy Parser::ParseCXXClassMemberDeclarationWithPragmas(
2991 AccessSpecifier &AS, ParsedAttributesWithRange &AccessAttrs,
2992 DeclSpec::TST TagType, Decl *TagDecl) {
Richard Smithb55f7582017-01-28 01:12:10 +00002993 switch (Tok.getKind()) {
2994 case tok::kw___if_exists:
2995 case tok::kw___if_not_exists:
Alexey Bataev05c25d62015-07-31 08:42:25 +00002996 ParseMicrosoftIfExistsClassDeclaration(TagType, AS);
David Blaikie0403cb12016-01-15 23:43:25 +00002997 return nullptr;
Alexey Bataev05c25d62015-07-31 08:42:25 +00002998
Richard Smithb55f7582017-01-28 01:12:10 +00002999 case tok::semi:
3000 // Check for extraneous top-level semicolon.
Alexey Bataev05c25d62015-07-31 08:42:25 +00003001 ConsumeExtraSemi(InsideStruct, TagType);
David Blaikie0403cb12016-01-15 23:43:25 +00003002 return nullptr;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003003
Richard Smithb55f7582017-01-28 01:12:10 +00003004 // Handle pragmas that can appear as member declarations.
3005 case tok::annot_pragma_vis:
Alexey Bataev05c25d62015-07-31 08:42:25 +00003006 HandlePragmaVisibility();
David Blaikie0403cb12016-01-15 23:43:25 +00003007 return nullptr;
Richard Smithb55f7582017-01-28 01:12:10 +00003008 case tok::annot_pragma_pack:
Alexey Bataev05c25d62015-07-31 08:42:25 +00003009 HandlePragmaPack();
David Blaikie0403cb12016-01-15 23:43:25 +00003010 return nullptr;
Richard Smithb55f7582017-01-28 01:12:10 +00003011 case tok::annot_pragma_align:
Alexey Bataev05c25d62015-07-31 08:42:25 +00003012 HandlePragmaAlign();
David Blaikie0403cb12016-01-15 23:43:25 +00003013 return nullptr;
Richard Smithb55f7582017-01-28 01:12:10 +00003014 case tok::annot_pragma_ms_pointers_to_members:
Alexey Bataev05c25d62015-07-31 08:42:25 +00003015 HandlePragmaMSPointersToMembers();
David Blaikie0403cb12016-01-15 23:43:25 +00003016 return nullptr;
Richard Smithb55f7582017-01-28 01:12:10 +00003017 case tok::annot_pragma_ms_pragma:
Alexey Bataev05c25d62015-07-31 08:42:25 +00003018 HandlePragmaMSPragma();
David Blaikie0403cb12016-01-15 23:43:25 +00003019 return nullptr;
Richard Smithb55f7582017-01-28 01:12:10 +00003020 case tok::annot_pragma_ms_vtordisp:
Alexey Bataev3d42f342015-11-20 07:02:57 +00003021 HandlePragmaMSVtorDisp();
David Blaikie0403cb12016-01-15 23:43:25 +00003022 return nullptr;
Richard Smithb256d302017-01-28 01:20:57 +00003023 case tok::annot_pragma_dump:
3024 HandlePragmaDump();
3025 return nullptr;
Alexey Bataev3d42f342015-11-20 07:02:57 +00003026
Richard Smithb55f7582017-01-28 01:12:10 +00003027 case tok::kw_namespace:
3028 // If we see a namespace here, a close brace was missing somewhere.
Alexey Bataev05c25d62015-07-31 08:42:25 +00003029 DiagnoseUnexpectedNamespace(cast<NamedDecl>(TagDecl));
David Blaikie0403cb12016-01-15 23:43:25 +00003030 return nullptr;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003031
Richard Smithb55f7582017-01-28 01:12:10 +00003032 case tok::kw_public:
3033 case tok::kw_protected:
3034 case tok::kw_private: {
3035 AccessSpecifier NewAS = getAccessSpecifierIfPresent();
3036 assert(NewAS != AS_none);
Alexey Bataev05c25d62015-07-31 08:42:25 +00003037 // Current token is a C++ access specifier.
3038 AS = NewAS;
3039 SourceLocation ASLoc = Tok.getLocation();
3040 unsigned TokLength = Tok.getLength();
3041 ConsumeToken();
3042 AccessAttrs.clear();
3043 MaybeParseGNUAttributes(AccessAttrs);
3044
3045 SourceLocation EndLoc;
3046 if (TryConsumeToken(tok::colon, EndLoc)) {
3047 } else if (TryConsumeToken(tok::semi, EndLoc)) {
3048 Diag(EndLoc, diag::err_expected)
3049 << tok::colon << FixItHint::CreateReplacement(EndLoc, ":");
3050 } else {
3051 EndLoc = ASLoc.getLocWithOffset(TokLength);
3052 Diag(EndLoc, diag::err_expected)
3053 << tok::colon << FixItHint::CreateInsertion(EndLoc, ":");
3054 }
3055
3056 // The Microsoft extension __interface does not permit non-public
3057 // access specifiers.
3058 if (TagType == DeclSpec::TST_interface && AS != AS_public) {
3059 Diag(ASLoc, diag::err_access_specifier_interface) << (AS == AS_protected);
3060 }
3061
3062 if (Actions.ActOnAccessSpecifier(NewAS, ASLoc, EndLoc,
3063 AccessAttrs.getList())) {
3064 // found another attribute than only annotations
3065 AccessAttrs.clear();
3066 }
3067
David Blaikie0403cb12016-01-15 23:43:25 +00003068 return nullptr;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003069 }
3070
Richard Smithb55f7582017-01-28 01:12:10 +00003071 case tok::annot_pragma_openmp:
Alexey Bataev587e1de2016-03-30 10:43:55 +00003072 return ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, AccessAttrs, TagType,
3073 TagDecl);
Alexey Bataev05c25d62015-07-31 08:42:25 +00003074
Richard Smithb55f7582017-01-28 01:12:10 +00003075 default:
3076 return ParseCXXClassMemberDeclaration(AS, AccessAttrs.getList());
3077 }
Alexey Bataev05c25d62015-07-31 08:42:25 +00003078}
3079
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003080/// ParseCXXMemberSpecification - Parse the class definition.
3081///
3082/// member-specification:
3083/// member-declaration member-specification[opt]
3084/// access-specifier ':' member-specification[opt]
3085///
Joao Matose9a3ed42012-08-31 22:18:20 +00003086void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc,
Michael Han309af292013-01-07 16:57:11 +00003087 SourceLocation AttrFixitLoc,
Richard Smith4c96e992013-02-19 23:47:15 +00003088 ParsedAttributesWithRange &Attrs,
Joao Matose9a3ed42012-08-31 22:18:20 +00003089 unsigned TagType, Decl *TagDecl) {
3090 assert((TagType == DeclSpec::TST_struct ||
3091 TagType == DeclSpec::TST_interface ||
3092 TagType == DeclSpec::TST_union ||
3093 TagType == DeclSpec::TST_class) && "Invalid TagType!");
3094
John McCallfaf5fb42010-08-26 23:41:50 +00003095 PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc,
3096 "parsing struct/union/class body");
Mike Stump11289f42009-09-09 15:08:12 +00003097
Douglas Gregoredf8f392010-01-16 20:52:59 +00003098 // Determine whether this is a non-nested class. Note that local
3099 // classes are *not* considered to be nested classes.
3100 bool NonNestedClass = true;
3101 if (!ClassStack.empty()) {
Douglas Gregor0be31a22010-07-02 17:43:08 +00003102 for (const Scope *S = getCurScope(); S; S = S->getParent()) {
Douglas Gregoredf8f392010-01-16 20:52:59 +00003103 if (S->isClassScope()) {
3104 // We're inside a class scope, so this is a nested class.
3105 NonNestedClass = false;
John McCalldb632ac2012-09-25 07:32:39 +00003106
3107 // The Microsoft extension __interface does not permit nested classes.
3108 if (getCurrentClass().IsInterface) {
3109 Diag(RecordLoc, diag::err_invalid_member_in_interface)
3110 << /*ErrorType=*/6
3111 << (isa<NamedDecl>(TagDecl)
3112 ? cast<NamedDecl>(TagDecl)->getQualifiedNameAsString()
David Blaikieabe1a392014-04-02 05:58:29 +00003113 : "(anonymous)");
John McCalldb632ac2012-09-25 07:32:39 +00003114 }
Douglas Gregoredf8f392010-01-16 20:52:59 +00003115 break;
3116 }
3117
Serge Pavlovd9c0bcf2015-07-14 10:02:10 +00003118 if ((S->getFlags() & Scope::FnScope))
3119 // If we're in a function or function template then this is a local
3120 // class rather than a nested class.
3121 break;
Douglas Gregoredf8f392010-01-16 20:52:59 +00003122 }
3123 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003124
3125 // Enter a scope for the class.
Douglas Gregor658b9552009-01-09 22:42:13 +00003126 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003127
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003128 // Note that we are parsing a new (potentially-nested) class definition.
John McCalldb632ac2012-09-25 07:32:39 +00003129 ParsingClassDefinition ParsingDef(*this, TagDecl, NonNestedClass,
3130 TagType == DeclSpec::TST_interface);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003131
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003132 if (TagDecl)
Douglas Gregor0be31a22010-07-02 17:43:08 +00003133 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
John McCall2d814c32009-12-19 21:48:58 +00003134
Anders Carlssonf9eb63b2011-03-25 14:46:08 +00003135 SourceLocation FinalLoc;
David Majnemera5433082013-10-18 00:33:31 +00003136 bool IsFinalSpelledSealed = false;
Anders Carlssonf9eb63b2011-03-25 14:46:08 +00003137
3138 // Parse the optional 'final' keyword.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003139 if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
David Majnemera5433082013-10-18 00:33:31 +00003140 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier(Tok);
3141 assert((Specifier == VirtSpecifiers::VS_Final ||
Andrey Bokhanko276055b2016-07-29 10:42:48 +00003142 Specifier == VirtSpecifiers::VS_GNU_Final ||
David Majnemera5433082013-10-18 00:33:31 +00003143 Specifier == VirtSpecifiers::VS_Sealed) &&
3144 "not a class definition");
Richard Smithda261112011-10-15 04:21:46 +00003145 FinalLoc = ConsumeToken();
David Majnemera5433082013-10-18 00:33:31 +00003146 IsFinalSpelledSealed = Specifier == VirtSpecifiers::VS_Sealed;
Anders Carlssonf9eb63b2011-03-25 14:46:08 +00003147
David Majnemera5433082013-10-18 00:33:31 +00003148 if (TagType == DeclSpec::TST_interface)
John McCalldb632ac2012-09-25 07:32:39 +00003149 Diag(FinalLoc, diag::err_override_control_interface)
David Majnemera5433082013-10-18 00:33:31 +00003150 << VirtSpecifiers::getSpecifierName(Specifier);
3151 else if (Specifier == VirtSpecifiers::VS_Final)
3152 Diag(FinalLoc, getLangOpts().CPlusPlus11
3153 ? diag::warn_cxx98_compat_override_control_keyword
3154 : diag::ext_override_control_keyword)
3155 << VirtSpecifiers::getSpecifierName(Specifier);
3156 else if (Specifier == VirtSpecifiers::VS_Sealed)
3157 Diag(FinalLoc, diag::ext_ms_sealed_keyword);
Andrey Bokhanko276055b2016-07-29 10:42:48 +00003158 else if (Specifier == VirtSpecifiers::VS_GNU_Final)
3159 Diag(FinalLoc, diag::ext_warn_gnu_final);
Michael Han9407e502012-11-26 22:54:45 +00003160
Michael Han309af292013-01-07 16:57:11 +00003161 // Parse any C++11 attributes after 'final' keyword.
3162 // These attributes are not allowed to appear here,
3163 // and the only possible place for them to appertain
3164 // to the class would be between class-key and class-name.
Richard Smith4c96e992013-02-19 23:47:15 +00003165 CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
Nico Weber4b4be842014-12-29 06:56:50 +00003166
3167 // ParseClassSpecifier() does only a superficial check for attributes before
3168 // deciding to call this method. For example, for
3169 // `class C final alignas ([l) {` it will decide that this looks like a
3170 // misplaced attribute since it sees `alignas '(' ')'`. But the actual
3171 // attribute parsing code will try to parse the '[' as a constexpr lambda
3172 // and consume enough tokens that the alignas parsing code will eat the
3173 // opening '{'. So bail out if the next token isn't one we expect.
Nico Weber36de3a22014-12-29 21:56:22 +00003174 if (!Tok.is(tok::colon) && !Tok.is(tok::l_brace)) {
3175 if (TagDecl)
3176 Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
Nico Weber4b4be842014-12-29 06:56:50 +00003177 return;
Nico Weber36de3a22014-12-29 21:56:22 +00003178 }
Anders Carlssonf9eb63b2011-03-25 14:46:08 +00003179 }
Anders Carlsson4b63d0e2011-01-22 16:56:46 +00003180
John McCall2d814c32009-12-19 21:48:58 +00003181 if (Tok.is(tok::colon)) {
3182 ParseBaseClause(TagDecl);
John McCall2d814c32009-12-19 21:48:58 +00003183 if (!Tok.is(tok::l_brace)) {
Ismail Pazarbasi129c44c2014-09-25 21:13:02 +00003184 bool SuggestFixIt = false;
3185 SourceLocation BraceLoc = PP.getLocForEndOfToken(PrevTokLocation);
3186 if (Tok.isAtStartOfLine()) {
3187 switch (Tok.getKind()) {
3188 case tok::kw_private:
3189 case tok::kw_protected:
3190 case tok::kw_public:
3191 SuggestFixIt = NextToken().getKind() == tok::colon;
3192 break;
3193 case tok::kw_static_assert:
3194 case tok::r_brace:
3195 case tok::kw_using:
3196 // base-clause can have simple-template-id; 'template' can't be there
3197 case tok::kw_template:
3198 SuggestFixIt = true;
3199 break;
3200 case tok::identifier:
3201 SuggestFixIt = isConstructorDeclarator(true);
3202 break;
3203 default:
3204 SuggestFixIt = isCXXSimpleDeclaration(/*AllowForRangeDecl=*/false);
3205 break;
3206 }
3207 }
3208 DiagnosticBuilder LBraceDiag =
3209 Diag(BraceLoc, diag::err_expected_lbrace_after_base_specifiers);
3210 if (SuggestFixIt) {
3211 LBraceDiag << FixItHint::CreateInsertion(BraceLoc, " {");
3212 // Try recovering from missing { after base-clause.
3213 PP.EnterToken(Tok);
3214 Tok.setKind(tok::l_brace);
3215 } else {
3216 if (TagDecl)
3217 Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
3218 return;
3219 }
John McCall2d814c32009-12-19 21:48:58 +00003220 }
3221 }
3222
3223 assert(Tok.is(tok::l_brace));
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003224 BalancedDelimiterTracker T(*this, tok::l_brace);
3225 T.consumeOpen();
John McCall2d814c32009-12-19 21:48:58 +00003226
John McCall08bede42010-05-28 08:11:17 +00003227 if (TagDecl)
Anders Carlsson30f29442011-03-25 14:31:08 +00003228 Actions.ActOnStartCXXMemberDeclarations(getCurScope(), TagDecl, FinalLoc,
David Majnemera5433082013-10-18 00:33:31 +00003229 IsFinalSpelledSealed,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003230 T.getOpenLocation());
John McCall1c7e6ec2009-12-20 07:58:13 +00003231
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003232 // C++ 11p3: Members of a class defined with the keyword class are private
3233 // by default. Members of a class defined with the keywords struct or union
3234 // are public by default.
3235 AccessSpecifier CurAS;
3236 if (TagType == DeclSpec::TST_class)
3237 CurAS = AS_private;
3238 else
3239 CurAS = AS_public;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003240 ParsedAttributesWithRange AccessAttrs(AttrFactory);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003241
Douglas Gregor9377c822010-06-21 22:31:09 +00003242 if (TagDecl) {
3243 // While we still have something to read, read the member-declarations.
Richard Smith752ada82015-11-17 23:32:01 +00003244 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
3245 Tok.isNot(tok::eof)) {
Douglas Gregor9377c822010-06-21 22:31:09 +00003246 // Each iteration of this loop reads one member-declaration.
Alexey Bataev05c25d62015-07-31 08:42:25 +00003247 ParseCXXClassMemberDeclarationWithPragmas(
3248 CurAS, AccessAttrs, static_cast<DeclSpec::TST>(TagType), TagDecl);
Serge Pavlovc4e04a22015-09-19 05:32:57 +00003249 }
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003250 T.consumeClose();
Douglas Gregor9377c822010-06-21 22:31:09 +00003251 } else {
Alexey Bataevee6507d2013-11-18 08:17:37 +00003252 SkipUntil(tok::r_brace);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003253 }
Mike Stump11289f42009-09-09 15:08:12 +00003254
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003255 // If attributes exist after class contents, parse them.
John McCall084e83d2011-03-24 11:26:52 +00003256 ParsedAttributes attrs(AttrFactory);
John McCall53fa7142010-12-24 02:08:15 +00003257 MaybeParseGNUAttributes(attrs);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003258
John McCall08bede42010-05-28 08:11:17 +00003259 if (TagDecl)
Douglas Gregor0be31a22010-07-02 17:43:08 +00003260 Actions.ActOnFinishCXXMemberSpecification(getCurScope(), RecordLoc, TagDecl,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003261 T.getOpenLocation(),
3262 T.getCloseLocation(),
John McCall53fa7142010-12-24 02:08:15 +00003263 attrs.getList());
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003264
Douglas Gregor433e0532012-04-16 18:27:27 +00003265 // C++11 [class.mem]p2:
3266 // Within the class member-specification, the class is regarded as complete
Richard Smith0b3a4622014-11-13 20:01:57 +00003267 // within function bodies, default arguments, exception-specifications, and
Douglas Gregor433e0532012-04-16 18:27:27 +00003268 // brace-or-equal-initializers for non-static data members (including such
3269 // things in nested classes).
Douglas Gregor9377c822010-06-21 22:31:09 +00003270 if (TagDecl && NonNestedClass) {
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003271 // We are not inside a nested class. This class and its nested classes
Douglas Gregor4d87df52008-12-16 21:30:33 +00003272 // are complete and we can parse the delayed portions of method
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00003273 // declarations and the lexed inline method definitions, along with any
3274 // delayed attributes.
Douglas Gregor428119e2010-06-16 23:45:56 +00003275 SourceLocation SavedPrevTokLocation = PrevTokLocation;
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00003276 ParseLexedAttributes(getCurrentClass());
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003277 ParseLexedMethodDeclarations(getCurrentClass());
Richard Smith84973e52012-04-21 18:42:51 +00003278
3279 // We've finished with all pending member declarations.
3280 Actions.ActOnFinishCXXMemberDecls();
3281
Richard Smith938f40b2011-06-11 17:19:42 +00003282 ParseLexedMemberInitializers(getCurrentClass());
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003283 ParseLexedMethodDefs(getCurrentClass());
Douglas Gregor428119e2010-06-16 23:45:56 +00003284 PrevTokLocation = SavedPrevTokLocation;
Reid Klecknerbba3cb92015-03-17 19:00:50 +00003285
3286 // We've finished parsing everything, including default argument
3287 // initializers.
Hans Wennborg99000c22015-08-15 01:18:16 +00003288 Actions.ActOnFinishCXXNonNestedClass(TagDecl);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003289 }
3290
John McCall08bede42010-05-28 08:11:17 +00003291 if (TagDecl)
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00003292 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getRange());
John McCall2ff380a2010-03-17 00:38:33 +00003293
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003294 // Leave the class scope.
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003295 ParsingDef.Pop();
Douglas Gregor7307d6c2008-12-10 06:34:36 +00003296 ClassScope.Exit();
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003297}
Douglas Gregore8381c02008-11-05 04:29:56 +00003298
Richard Smith2ac43ad2013-11-15 23:00:02 +00003299void Parser::DiagnoseUnexpectedNamespace(NamedDecl *D) {
Richard Smithda35e962013-11-09 04:52:51 +00003300 assert(Tok.is(tok::kw_namespace));
3301
3302 // FIXME: Suggest where the close brace should have gone by looking
3303 // at indentation changes within the definition body.
Richard Smith2ac43ad2013-11-15 23:00:02 +00003304 Diag(D->getLocation(),
3305 diag::err_missing_end_of_definition) << D;
Richard Smithda35e962013-11-09 04:52:51 +00003306 Diag(Tok.getLocation(),
Richard Smith2ac43ad2013-11-15 23:00:02 +00003307 diag::note_missing_end_of_definition_before) << D;
Richard Smithda35e962013-11-09 04:52:51 +00003308
3309 // Push '};' onto the token stream to recover.
3310 PP.EnterToken(Tok);
3311
3312 Tok.startToken();
3313 Tok.setLocation(PP.getLocForEndOfToken(PrevTokLocation));
3314 Tok.setKind(tok::semi);
3315 PP.EnterToken(Tok);
3316
3317 Tok.setKind(tok::r_brace);
3318}
3319
Douglas Gregore8381c02008-11-05 04:29:56 +00003320/// ParseConstructorInitializer - Parse a C++ constructor initializer,
3321/// which explicitly initializes the members or base classes of a
3322/// class (C++ [class.base.init]). For example, the three initializers
3323/// after the ':' in the Derived constructor below:
3324///
3325/// @code
3326/// class Base { };
3327/// class Derived : Base {
3328/// int x;
3329/// float f;
3330/// public:
3331/// Derived(float f) : Base(), x(17), f(f) { }
3332/// };
3333/// @endcode
3334///
Mike Stump11289f42009-09-09 15:08:12 +00003335/// [C++] ctor-initializer:
3336/// ':' mem-initializer-list
Douglas Gregore8381c02008-11-05 04:29:56 +00003337///
Mike Stump11289f42009-09-09 15:08:12 +00003338/// [C++] mem-initializer-list:
Douglas Gregor44e7df62011-01-04 00:32:56 +00003339/// mem-initializer ...[opt]
3340/// mem-initializer ...[opt] , mem-initializer-list
John McCall48871652010-08-21 09:40:31 +00003341void Parser::ParseConstructorInitializer(Decl *ConstructorDecl) {
Nico Weber3b00fdc2015-03-07 19:52:39 +00003342 assert(Tok.is(tok::colon) &&
3343 "Constructor initializer always starts with ':'");
Douglas Gregore8381c02008-11-05 04:29:56 +00003344
Nico Weber3b00fdc2015-03-07 19:52:39 +00003345 // Poison the SEH identifiers so they are flagged as illegal in constructor
3346 // initializers.
John Wiegley1c0675e2011-04-28 01:08:34 +00003347 PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
Douglas Gregore8381c02008-11-05 04:29:56 +00003348 SourceLocation ColonLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +00003349
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003350 SmallVector<CXXCtorInitializer*, 4> MemInitializers;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003351 bool AnyErrors = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003352
Douglas Gregore8381c02008-11-05 04:29:56 +00003353 do {
Douglas Gregoreaeeca92010-08-28 00:00:50 +00003354 if (Tok.is(tok::code_completion)) {
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00003355 Actions.CodeCompleteConstructorInitializer(ConstructorDecl,
3356 MemInitializers);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00003357 return cutOffParsing();
Douglas Gregoreaeeca92010-08-28 00:00:50 +00003358 }
Alexey Bataev79de17d2016-01-20 05:25:51 +00003359
3360 MemInitResult MemInit = ParseMemInitializer(ConstructorDecl);
3361 if (!MemInit.isInvalid())
3362 MemInitializers.push_back(MemInit.get());
3363 else
3364 AnyErrors = true;
3365
Douglas Gregore8381c02008-11-05 04:29:56 +00003366 if (Tok.is(tok::comma))
3367 ConsumeToken();
3368 else if (Tok.is(tok::l_brace))
3369 break;
Alexey Bataev79de17d2016-01-20 05:25:51 +00003370 // If the previous initializer was valid and the next token looks like a
3371 // base or member initializer, assume that we're just missing a comma.
3372 else if (!MemInit.isInvalid() &&
3373 Tok.isOneOf(tok::identifier, tok::coloncolon)) {
Douglas Gregorce66d022010-09-07 14:51:08 +00003374 SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation);
3375 Diag(Loc, diag::err_ctor_init_missing_comma)
3376 << FixItHint::CreateInsertion(Loc, ", ");
3377 } else {
Douglas Gregore8381c02008-11-05 04:29:56 +00003378 // Skip over garbage, until we get to '{'. Don't eat the '{'.
Alexey Bataev79de17d2016-01-20 05:25:51 +00003379 if (!MemInit.isInvalid())
3380 Diag(Tok.getLocation(), diag::err_expected_either) << tok::l_brace
3381 << tok::comma;
Alexey Bataevee6507d2013-11-18 08:17:37 +00003382 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
Douglas Gregore8381c02008-11-05 04:29:56 +00003383 break;
3384 }
3385 } while (true);
3386
David Blaikie3fc2f912013-01-17 05:26:25 +00003387 Actions.ActOnMemInitializers(ConstructorDecl, ColonLoc, MemInitializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003388 AnyErrors);
Douglas Gregore8381c02008-11-05 04:29:56 +00003389}
3390
3391/// ParseMemInitializer - Parse a C++ member initializer, which is
3392/// part of a constructor initializer that explicitly initializes one
3393/// member or base class (C++ [class.base.init]). See
3394/// ParseConstructorInitializer for an example.
3395///
3396/// [C++] mem-initializer:
3397/// mem-initializer-id '(' expression-list[opt] ')'
Sebastian Redl3da34892011-06-05 12:23:16 +00003398/// [C++0x] mem-initializer-id braced-init-list
Mike Stump11289f42009-09-09 15:08:12 +00003399///
Douglas Gregore8381c02008-11-05 04:29:56 +00003400/// [C++] mem-initializer-id:
3401/// '::'[opt] nested-name-specifier[opt] class-name
3402/// identifier
Craig Topper9ad7e262014-10-31 06:57:07 +00003403MemInitResult Parser::ParseMemInitializer(Decl *ConstructorDecl) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00003404 // parse '::'[opt] nested-name-specifier[opt]
3405 CXXScopeSpec SS;
David Blaikieefdccaa2016-01-15 23:43:34 +00003406 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false);
John McCallba7bf592010-08-24 05:47:05 +00003407 ParsedType TemplateTypeTy;
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00003408 if (Tok.is(tok::annot_template_id)) {
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00003409 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregor46c59612010-01-12 17:52:59 +00003410 if (TemplateId->Kind == TNK_Type_template ||
3411 TemplateId->Kind == TNK_Dependent_template_name) {
Richard Smith62559bd2017-02-01 21:36:38 +00003412 AnnotateTemplateIdTokenAsType(/*IsClassName*/true);
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00003413 assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
John McCallba7bf592010-08-24 05:47:05 +00003414 TemplateTypeTy = getTypeAnnotation(Tok);
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00003415 }
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00003416 }
David Blaikie186a8892012-01-24 06:03:59 +00003417 // Uses of decltype will already have been converted to annot_decltype by
3418 // ParseOptionalCXXScopeSpecifier at this point.
3419 if (!TemplateTypeTy && Tok.isNot(tok::identifier)
3420 && Tok.isNot(tok::annot_decltype)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00003421 Diag(Tok, diag::err_expected_member_or_base_name);
Douglas Gregore8381c02008-11-05 04:29:56 +00003422 return true;
3423 }
Mike Stump11289f42009-09-09 15:08:12 +00003424
Craig Topper161e4db2014-05-21 06:02:52 +00003425 IdentifierInfo *II = nullptr;
David Blaikie186a8892012-01-24 06:03:59 +00003426 DeclSpec DS(AttrFactory);
3427 SourceLocation IdLoc = Tok.getLocation();
3428 if (Tok.is(tok::annot_decltype)) {
3429 // Get the decltype expression, if there is one.
3430 ParseDecltypeSpecifier(DS);
3431 } else {
3432 if (Tok.is(tok::identifier))
3433 // Get the identifier. This may be a member name or a class name,
3434 // but we'll let the semantic analysis determine which it is.
3435 II = Tok.getIdentifierInfo();
3436 ConsumeToken();
3437 }
3438
Douglas Gregore8381c02008-11-05 04:29:56 +00003439
3440 // Parse the '('.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003441 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
Richard Smith5d164bc2011-10-15 05:09:34 +00003442 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
3443
Sebastian Redla74948d2011-09-24 17:48:25 +00003444 ExprResult InitList = ParseBraceInitializer();
3445 if (InitList.isInvalid())
3446 return true;
3447
3448 SourceLocation EllipsisLoc;
Alp Toker094e5212014-01-05 03:27:11 +00003449 TryConsumeToken(tok::ellipsis, EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00003450
3451 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
David Blaikie186a8892012-01-24 06:03:59 +00003452 TemplateTypeTy, DS, IdLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003453 InitList.get(), EllipsisLoc);
Sebastian Redl3da34892011-06-05 12:23:16 +00003454 } else if(Tok.is(tok::l_paren)) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003455 BalancedDelimiterTracker T(*this, tok::l_paren);
3456 T.consumeOpen();
Douglas Gregore8381c02008-11-05 04:29:56 +00003457
Sebastian Redl3da34892011-06-05 12:23:16 +00003458 // Parse the optional expression-list.
Benjamin Kramerf0623432012-08-23 22:51:59 +00003459 ExprVector ArgExprs;
Sebastian Redl3da34892011-06-05 12:23:16 +00003460 CommaLocsTy CommaLocs;
3461 if (Tok.isNot(tok::r_paren) && ParseExpressionList(ArgExprs, CommaLocs)) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00003462 SkipUntil(tok::r_paren, StopAtSemi);
Sebastian Redl3da34892011-06-05 12:23:16 +00003463 return true;
3464 }
3465
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003466 T.consumeClose();
Sebastian Redl3da34892011-06-05 12:23:16 +00003467
3468 SourceLocation EllipsisLoc;
Alp Toker97650562014-01-10 11:19:30 +00003469 TryConsumeToken(tok::ellipsis, EllipsisLoc);
Sebastian Redl3da34892011-06-05 12:23:16 +00003470
3471 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
David Blaikie186a8892012-01-24 06:03:59 +00003472 TemplateTypeTy, DS, IdLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00003473 T.getOpenLocation(), ArgExprs,
3474 T.getCloseLocation(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00003475 }
3476
Alp Tokerec543272013-12-24 09:48:30 +00003477 if (getLangOpts().CPlusPlus11)
3478 return Diag(Tok, diag::err_expected_either) << tok::l_paren << tok::l_brace;
3479 else
3480 return Diag(Tok, diag::err_expected) << tok::l_paren;
Douglas Gregore8381c02008-11-05 04:29:56 +00003481}
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003482
Sebastian Redl965b0e32011-03-05 14:45:16 +00003483/// \brief Parse a C++ exception-specification if present (C++0x [except.spec]).
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003484///
Douglas Gregor356513d2008-12-01 18:00:20 +00003485/// exception-specification:
Sebastian Redl965b0e32011-03-05 14:45:16 +00003486/// dynamic-exception-specification
3487/// noexcept-specification
3488///
3489/// noexcept-specification:
3490/// 'noexcept'
3491/// 'noexcept' '(' constant-expression ')'
3492ExceptionSpecificationType
Richard Smith0b3a4622014-11-13 20:01:57 +00003493Parser::tryParseExceptionSpecification(bool Delayed,
Douglas Gregor433e0532012-04-16 18:27:27 +00003494 SourceRange &SpecificationRange,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003495 SmallVectorImpl<ParsedType> &DynamicExceptions,
3496 SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
Richard Smith0b3a4622014-11-13 20:01:57 +00003497 ExprResult &NoexceptExpr,
3498 CachedTokens *&ExceptionSpecTokens) {
Sebastian Redl965b0e32011-03-05 14:45:16 +00003499 ExceptionSpecificationType Result = EST_None;
Hans Wennborgdcfba332015-10-06 23:40:43 +00003500 ExceptionSpecTokens = nullptr;
Richard Smith0b3a4622014-11-13 20:01:57 +00003501
3502 // Handle delayed parsing of exception-specifications.
3503 if (Delayed) {
3504 if (Tok.isNot(tok::kw_throw) && Tok.isNot(tok::kw_noexcept))
3505 return EST_None;
Sebastian Redl965b0e32011-03-05 14:45:16 +00003506
Richard Smith0b3a4622014-11-13 20:01:57 +00003507 // Consume and cache the starting token.
3508 bool IsNoexcept = Tok.is(tok::kw_noexcept);
3509 Token StartTok = Tok;
3510 SpecificationRange = SourceRange(ConsumeToken());
3511
3512 // Check for a '('.
3513 if (!Tok.is(tok::l_paren)) {
3514 // If this is a bare 'noexcept', we're done.
3515 if (IsNoexcept) {
3516 Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
Hans Wennborgdcfba332015-10-06 23:40:43 +00003517 NoexceptExpr = nullptr;
Richard Smith0b3a4622014-11-13 20:01:57 +00003518 return EST_BasicNoexcept;
3519 }
3520
3521 Diag(Tok, diag::err_expected_lparen_after) << "throw";
3522 return EST_DynamicNone;
3523 }
3524
3525 // Cache the tokens for the exception-specification.
3526 ExceptionSpecTokens = new CachedTokens;
3527 ExceptionSpecTokens->push_back(StartTok); // 'throw' or 'noexcept'
3528 ExceptionSpecTokens->push_back(Tok); // '('
3529 SpecificationRange.setEnd(ConsumeParen()); // '('
Richard Smithb1c217e2015-01-13 02:24:58 +00003530
3531 ConsumeAndStoreUntil(tok::r_paren, *ExceptionSpecTokens,
3532 /*StopAtSemi=*/true,
3533 /*ConsumeFinalToken=*/true);
Aaron Ballman580ccaf2016-01-12 21:04:22 +00003534 SpecificationRange.setEnd(ExceptionSpecTokens->back().getLocation());
3535
Richard Smith0b3a4622014-11-13 20:01:57 +00003536 return EST_Unparsed;
3537 }
3538
Sebastian Redl965b0e32011-03-05 14:45:16 +00003539 // See if there's a dynamic specification.
3540 if (Tok.is(tok::kw_throw)) {
3541 Result = ParseDynamicExceptionSpecification(SpecificationRange,
3542 DynamicExceptions,
3543 DynamicExceptionRanges);
3544 assert(DynamicExceptions.size() == DynamicExceptionRanges.size() &&
3545 "Produced different number of exception types and ranges.");
3546 }
3547
3548 // If there's no noexcept specification, we're done.
3549 if (Tok.isNot(tok::kw_noexcept))
3550 return Result;
3551
Richard Smithb15c11c2011-10-17 23:06:20 +00003552 Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
3553
Sebastian Redl965b0e32011-03-05 14:45:16 +00003554 // If we already had a dynamic specification, parse the noexcept for,
3555 // recovery, but emit a diagnostic and don't store the results.
3556 SourceRange NoexceptRange;
3557 ExceptionSpecificationType NoexceptType = EST_None;
3558
3559 SourceLocation KeywordLoc = ConsumeToken();
3560 if (Tok.is(tok::l_paren)) {
3561 // There is an argument.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003562 BalancedDelimiterTracker T(*this, tok::l_paren);
3563 T.consumeOpen();
Sebastian Redl965b0e32011-03-05 14:45:16 +00003564 NoexceptType = EST_ComputedNoexcept;
3565 NoexceptExpr = ParseConstantExpression();
Serge Pavlov3739f5e72015-06-29 17:50:19 +00003566 T.consumeClose();
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003567 // The argument must be contextually convertible to bool. We use
Richard Smith03a4aa32016-06-23 19:02:52 +00003568 // CheckBooleanCondition for this purpose.
3569 // FIXME: Add a proper Sema entry point for this.
Serge Pavlov3739f5e72015-06-29 17:50:19 +00003570 if (!NoexceptExpr.isInvalid()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00003571 NoexceptExpr =
3572 Actions.CheckBooleanCondition(KeywordLoc, NoexceptExpr.get());
Serge Pavlov3739f5e72015-06-29 17:50:19 +00003573 NoexceptRange = SourceRange(KeywordLoc, T.getCloseLocation());
3574 } else {
Malcolm Parsonsa3220ce2017-01-12 16:11:28 +00003575 NoexceptType = EST_BasicNoexcept;
Serge Pavlov3739f5e72015-06-29 17:50:19 +00003576 }
Sebastian Redl965b0e32011-03-05 14:45:16 +00003577 } else {
3578 // There is no argument.
3579 NoexceptType = EST_BasicNoexcept;
3580 NoexceptRange = SourceRange(KeywordLoc, KeywordLoc);
3581 }
3582
3583 if (Result == EST_None) {
3584 SpecificationRange = NoexceptRange;
3585 Result = NoexceptType;
3586
3587 // If there's a dynamic specification after a noexcept specification,
3588 // parse that and ignore the results.
3589 if (Tok.is(tok::kw_throw)) {
3590 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
3591 ParseDynamicExceptionSpecification(NoexceptRange, DynamicExceptions,
3592 DynamicExceptionRanges);
3593 }
3594 } else {
3595 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
3596 }
3597
3598 return Result;
3599}
3600
Richard Smith8ca78a12013-06-13 02:02:51 +00003601static void diagnoseDynamicExceptionSpecification(
Craig Toppere335f252015-10-04 04:53:55 +00003602 Parser &P, SourceRange Range, bool IsNoexcept) {
Richard Smith8ca78a12013-06-13 02:02:51 +00003603 if (P.getLangOpts().CPlusPlus11) {
3604 const char *Replacement = IsNoexcept ? "noexcept" : "noexcept(false)";
Richard Smith82da19d2016-12-08 02:49:07 +00003605 P.Diag(Range.getBegin(),
3606 P.getLangOpts().CPlusPlus1z && !IsNoexcept
3607 ? diag::ext_dynamic_exception_spec
3608 : diag::warn_exception_spec_deprecated)
3609 << Range;
Richard Smith8ca78a12013-06-13 02:02:51 +00003610 P.Diag(Range.getBegin(), diag::note_exception_spec_deprecated)
3611 << Replacement << FixItHint::CreateReplacement(Range, Replacement);
3612 }
3613}
3614
Sebastian Redl965b0e32011-03-05 14:45:16 +00003615/// ParseDynamicExceptionSpecification - Parse a C++
3616/// dynamic-exception-specification (C++ [except.spec]).
3617///
3618/// dynamic-exception-specification:
Douglas Gregor356513d2008-12-01 18:00:20 +00003619/// 'throw' '(' type-id-list [opt] ')'
3620/// [MS] 'throw' '(' '...' ')'
Mike Stump11289f42009-09-09 15:08:12 +00003621///
Douglas Gregor356513d2008-12-01 18:00:20 +00003622/// type-id-list:
Douglas Gregor830837d2010-12-20 23:57:46 +00003623/// type-id ... [opt]
3624/// type-id-list ',' type-id ... [opt]
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003625///
Sebastian Redl965b0e32011-03-05 14:45:16 +00003626ExceptionSpecificationType Parser::ParseDynamicExceptionSpecification(
3627 SourceRange &SpecificationRange,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003628 SmallVectorImpl<ParsedType> &Exceptions,
3629 SmallVectorImpl<SourceRange> &Ranges) {
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003630 assert(Tok.is(tok::kw_throw) && "expected throw");
Mike Stump11289f42009-09-09 15:08:12 +00003631
Sebastian Redl965b0e32011-03-05 14:45:16 +00003632 SpecificationRange.setBegin(ConsumeToken());
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003633 BalancedDelimiterTracker T(*this, tok::l_paren);
3634 if (T.consumeOpen()) {
Sebastian Redl965b0e32011-03-05 14:45:16 +00003635 Diag(Tok, diag::err_expected_lparen_after) << "throw";
3636 SpecificationRange.setEnd(SpecificationRange.getBegin());
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003637 return EST_DynamicNone;
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003638 }
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003639
Douglas Gregor356513d2008-12-01 18:00:20 +00003640 // Parse throw(...), a Microsoft extension that means "this function
3641 // can throw anything".
3642 if (Tok.is(tok::ellipsis)) {
3643 SourceLocation EllipsisLoc = ConsumeToken();
David Blaikiebbafb8a2012-03-11 07:00:24 +00003644 if (!getLangOpts().MicrosoftExt)
Douglas Gregor356513d2008-12-01 18:00:20 +00003645 Diag(EllipsisLoc, diag::ext_ellipsis_exception_spec);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003646 T.consumeClose();
3647 SpecificationRange.setEnd(T.getCloseLocation());
Richard Smith8ca78a12013-06-13 02:02:51 +00003648 diagnoseDynamicExceptionSpecification(*this, SpecificationRange, false);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003649 return EST_MSAny;
Douglas Gregor356513d2008-12-01 18:00:20 +00003650 }
3651
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003652 // Parse the sequence of type-ids.
Sebastian Redld6434562009-05-29 18:02:33 +00003653 SourceRange Range;
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003654 while (Tok.isNot(tok::r_paren)) {
Sebastian Redld6434562009-05-29 18:02:33 +00003655 TypeResult Res(ParseTypeName(&Range));
Sebastian Redl965b0e32011-03-05 14:45:16 +00003656
Douglas Gregor830837d2010-12-20 23:57:46 +00003657 if (Tok.is(tok::ellipsis)) {
3658 // C++0x [temp.variadic]p5:
3659 // - In a dynamic-exception-specification (15.4); the pattern is a
3660 // type-id.
3661 SourceLocation Ellipsis = ConsumeToken();
Sebastian Redl965b0e32011-03-05 14:45:16 +00003662 Range.setEnd(Ellipsis);
Douglas Gregor830837d2010-12-20 23:57:46 +00003663 if (!Res.isInvalid())
3664 Res = Actions.ActOnPackExpansion(Res.get(), Ellipsis);
3665 }
Sebastian Redl965b0e32011-03-05 14:45:16 +00003666
Sebastian Redld6434562009-05-29 18:02:33 +00003667 if (!Res.isInvalid()) {
Sebastian Redl2b9cacb2009-04-29 17:30:04 +00003668 Exceptions.push_back(Res.get());
Sebastian Redld6434562009-05-29 18:02:33 +00003669 Ranges.push_back(Range);
3670 }
Alp Toker97650562014-01-10 11:19:30 +00003671
3672 if (!TryConsumeToken(tok::comma))
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003673 break;
3674 }
3675
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003676 T.consumeClose();
3677 SpecificationRange.setEnd(T.getCloseLocation());
Richard Smith8ca78a12013-06-13 02:02:51 +00003678 diagnoseDynamicExceptionSpecification(*this, SpecificationRange,
3679 Exceptions.empty());
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003680 return Exceptions.empty() ? EST_DynamicNone : EST_Dynamic;
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003681}
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003682
Douglas Gregor7fb25412010-10-01 18:44:50 +00003683/// ParseTrailingReturnType - Parse a trailing return type on a new-style
3684/// function declaration.
Douglas Gregordb0b9f12011-08-04 15:30:47 +00003685TypeResult Parser::ParseTrailingReturnType(SourceRange &Range) {
Douglas Gregor7fb25412010-10-01 18:44:50 +00003686 assert(Tok.is(tok::arrow) && "expected arrow");
3687
3688 ConsumeToken();
3689
Richard Smithbfdb1082012-03-12 08:56:40 +00003690 return ParseTypeName(&Range, Declarator::TrailingReturnContext);
Douglas Gregor7fb25412010-10-01 18:44:50 +00003691}
3692
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003693/// \brief We have just started parsing the definition of a new class,
3694/// so push that class onto our stack of classes that is currently
3695/// being parsed.
John McCallc1465822011-02-14 07:13:47 +00003696Sema::ParsingClassState
John McCalldb632ac2012-09-25 07:32:39 +00003697Parser::PushParsingClass(Decl *ClassDecl, bool NonNestedClass,
3698 bool IsInterface) {
Douglas Gregoredf8f392010-01-16 20:52:59 +00003699 assert((NonNestedClass || !ClassStack.empty()) &&
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003700 "Nested class without outer class");
John McCalldb632ac2012-09-25 07:32:39 +00003701 ClassStack.push(new ParsingClass(ClassDecl, NonNestedClass, IsInterface));
John McCallc1465822011-02-14 07:13:47 +00003702 return Actions.PushParsingClass();
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003703}
3704
3705/// \brief Deallocate the given parsed class and all of its nested
3706/// classes.
3707void Parser::DeallocateParsedClasses(Parser::ParsingClass *Class) {
Douglas Gregorefc46952010-10-12 16:25:54 +00003708 for (unsigned I = 0, N = Class->LateParsedDeclarations.size(); I != N; ++I)
3709 delete Class->LateParsedDeclarations[I];
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003710 delete Class;
3711}
3712
3713/// \brief Pop the top class of the stack of classes that are
3714/// currently being parsed.
3715///
3716/// This routine should be called when we have finished parsing the
3717/// definition of a class, but have not yet popped the Scope
3718/// associated with the class's definition.
John McCallc1465822011-02-14 07:13:47 +00003719void Parser::PopParsingClass(Sema::ParsingClassState state) {
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003720 assert(!ClassStack.empty() && "Mismatched push/pop for class parsing");
Mike Stump11289f42009-09-09 15:08:12 +00003721
John McCallc1465822011-02-14 07:13:47 +00003722 Actions.PopParsingClass(state);
3723
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003724 ParsingClass *Victim = ClassStack.top();
3725 ClassStack.pop();
3726 if (Victim->TopLevelClass) {
3727 // Deallocate all of the nested classes of this class,
3728 // recursively: we don't need to keep any of this information.
3729 DeallocateParsedClasses(Victim);
3730 return;
Mike Stump11289f42009-09-09 15:08:12 +00003731 }
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003732 assert(!ClassStack.empty() && "Missing top-level class?");
3733
Douglas Gregorefc46952010-10-12 16:25:54 +00003734 if (Victim->LateParsedDeclarations.empty()) {
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003735 // The victim is a nested class, but we will not need to perform
3736 // any processing after the definition of this class since it has
3737 // no members whose handling was delayed. Therefore, we can just
3738 // remove this nested class.
Douglas Gregorefc46952010-10-12 16:25:54 +00003739 DeallocateParsedClasses(Victim);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003740 return;
3741 }
3742
3743 // This nested class has some members that will need to be processed
3744 // after the top-level class is completely defined. Therefore, add
3745 // it to the list of nested classes within its parent.
Douglas Gregor0be31a22010-07-02 17:43:08 +00003746 assert(getCurScope()->isClassScope() && "Nested class outside of class scope?");
Douglas Gregorefc46952010-10-12 16:25:54 +00003747 ClassStack.top()->LateParsedDeclarations.push_back(new LateParsedClass(this, Victim));
Douglas Gregor0be31a22010-07-02 17:43:08 +00003748 Victim->TemplateScope = getCurScope()->getParent()->isTemplateParamScope();
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003749}
Alexis Hunt96d5c762009-11-21 08:43:09 +00003750
Richard Smith3dff2512012-04-10 03:25:07 +00003751/// \brief Try to parse an 'identifier' which appears within an attribute-token.
3752///
3753/// \return the parsed identifier on success, and 0 if the next token is not an
3754/// attribute-token.
3755///
3756/// C++11 [dcl.attr.grammar]p3:
3757/// If a keyword or an alternative token that satisfies the syntactic
3758/// requirements of an identifier is contained in an attribute-token,
3759/// it is considered an identifier.
3760IdentifierInfo *Parser::TryParseCXX11AttributeIdentifier(SourceLocation &Loc) {
3761 switch (Tok.getKind()) {
3762 default:
3763 // Identifiers and keywords have identifier info attached.
David Majnemerd5271992015-01-09 18:09:39 +00003764 if (!Tok.isAnnotation()) {
3765 if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
3766 Loc = ConsumeToken();
3767 return II;
3768 }
Richard Smith3dff2512012-04-10 03:25:07 +00003769 }
Craig Topper161e4db2014-05-21 06:02:52 +00003770 return nullptr;
Richard Smith3dff2512012-04-10 03:25:07 +00003771
3772 case tok::ampamp: // 'and'
3773 case tok::pipe: // 'bitor'
3774 case tok::pipepipe: // 'or'
3775 case tok::caret: // 'xor'
3776 case tok::tilde: // 'compl'
3777 case tok::amp: // 'bitand'
3778 case tok::ampequal: // 'and_eq'
3779 case tok::pipeequal: // 'or_eq'
3780 case tok::caretequal: // 'xor_eq'
3781 case tok::exclaim: // 'not'
3782 case tok::exclaimequal: // 'not_eq'
3783 // Alternative tokens do not have identifier info, but their spelling
3784 // starts with an alphabetical character.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003785 SmallString<8> SpellingBuf;
Benjamin Kramer60be5632015-03-29 19:25:07 +00003786 SourceLocation SpellingLoc =
3787 PP.getSourceManager().getSpellingLoc(Tok.getLocation());
3788 StringRef Spelling = PP.getSpelling(SpellingLoc, SpellingBuf);
Jordan Rosea7d03842013-02-08 22:30:41 +00003789 if (isLetter(Spelling[0])) {
Richard Smith3dff2512012-04-10 03:25:07 +00003790 Loc = ConsumeToken();
Benjamin Kramer5c17f9c2012-04-22 20:43:30 +00003791 return &PP.getIdentifierTable().get(Spelling);
Richard Smith3dff2512012-04-10 03:25:07 +00003792 }
Craig Topper161e4db2014-05-21 06:02:52 +00003793 return nullptr;
Richard Smith3dff2512012-04-10 03:25:07 +00003794 }
3795}
3796
Michael Han23214e52012-10-03 01:56:22 +00003797static bool IsBuiltInOrStandardCXX11Attribute(IdentifierInfo *AttrName,
3798 IdentifierInfo *ScopeName) {
3799 switch (AttributeList::getKind(AttrName, ScopeName,
3800 AttributeList::AS_CXX11)) {
3801 case AttributeList::AT_CarriesDependency:
Aaron Ballman35f94212014-04-14 16:03:22 +00003802 case AttributeList::AT_Deprecated:
Michael Han23214e52012-10-03 01:56:22 +00003803 case AttributeList::AT_FallThrough:
Hans Wennborgdcfba332015-10-06 23:40:43 +00003804 case AttributeList::AT_CXX11NoReturn:
Michael Han23214e52012-10-03 01:56:22 +00003805 return true;
Aaron Ballmane7964782016-03-07 22:44:55 +00003806 case AttributeList::AT_WarnUnusedResult:
3807 return !ScopeName && AttrName->getName().equals("nodiscard");
Nico Weberac03bce2016-08-23 19:59:55 +00003808 case AttributeList::AT_Unused:
3809 return !ScopeName && AttrName->getName().equals("maybe_unused");
Michael Han23214e52012-10-03 01:56:22 +00003810 default:
3811 return false;
3812 }
3813}
3814
Aaron Ballmanb8e20392014-03-31 17:32:39 +00003815/// ParseCXX11AttributeArgs -- Parse a C++11 attribute-argument-clause.
3816///
3817/// [C++11] attribute-argument-clause:
3818/// '(' balanced-token-seq ')'
3819///
3820/// [C++11] balanced-token-seq:
3821/// balanced-token
3822/// balanced-token-seq balanced-token
3823///
3824/// [C++11] balanced-token:
3825/// '(' balanced-token-seq ')'
3826/// '[' balanced-token-seq ']'
3827/// '{' balanced-token-seq '}'
3828/// any token but '(', ')', '[', ']', '{', or '}'
3829bool Parser::ParseCXX11AttributeArgs(IdentifierInfo *AttrName,
3830 SourceLocation AttrNameLoc,
3831 ParsedAttributes &Attrs,
3832 SourceLocation *EndLoc,
3833 IdentifierInfo *ScopeName,
3834 SourceLocation ScopeLoc) {
3835 assert(Tok.is(tok::l_paren) && "Not a C++11 attribute argument list");
Aaron Ballman35f94212014-04-14 16:03:22 +00003836 SourceLocation LParenLoc = Tok.getLocation();
Aaron Ballmanb8e20392014-03-31 17:32:39 +00003837
3838 // If the attribute isn't known, we will not attempt to parse any
3839 // arguments.
3840 if (!hasAttribute(AttrSyntax::CXX, ScopeName, AttrName,
Bob Wilson7c730832015-07-20 22:57:31 +00003841 getTargetInfo(), getLangOpts())) {
Aaron Ballmanb8e20392014-03-31 17:32:39 +00003842 // Eat the left paren, then skip to the ending right paren.
3843 ConsumeParen();
3844 SkipUntil(tok::r_paren);
3845 return false;
3846 }
3847
Alex Lorenzd5d27e12017-03-01 18:06:25 +00003848 if (ScopeName && ScopeName->getName() == "gnu") {
Aaron Ballmanb8e20392014-03-31 17:32:39 +00003849 // GNU-scoped attributes have some special cases to handle GNU-specific
3850 // behaviors.
3851 ParseGNUAttributeArgs(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
Craig Topper161e4db2014-05-21 06:02:52 +00003852 ScopeLoc, AttributeList::AS_CXX11, nullptr);
Alex Lorenzd5d27e12017-03-01 18:06:25 +00003853 return true;
3854 }
3855
3856 unsigned NumArgs;
3857 // Some Clang-scoped attributes have some special parsing behavior.
3858 if (ScopeName && ScopeName->getName() == "clang")
3859 NumArgs =
3860 ParseClangAttributeArgs(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
3861 ScopeLoc, AttributeList::AS_CXX11);
3862 else
3863 NumArgs =
Aaron Ballman35f94212014-04-14 16:03:22 +00003864 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc,
3865 ScopeName, ScopeLoc, AttributeList::AS_CXX11);
Alex Lorenzd5d27e12017-03-01 18:06:25 +00003866
3867 const AttributeList *Attr = Attrs.getList();
3868 if (Attr && IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName)) {
3869 // If the attribute is a standard or built-in attribute and we are
3870 // parsing an argument list, we need to determine whether this attribute
3871 // was allowed to have an argument list (such as [[deprecated]]), and how
3872 // many arguments were parsed (so we can diagnose on [[deprecated()]]).
3873 if (Attr->getMaxArgs() && !NumArgs) {
3874 // The attribute was allowed to have arguments, but none were provided
3875 // even though the attribute parsed successfully. This is an error.
3876 Diag(LParenLoc, diag::err_attribute_requires_arguments) << AttrName;
3877 Attr->setInvalid(true);
3878 } else if (!Attr->getMaxArgs()) {
3879 // The attribute parsed successfully, but was not allowed to have any
3880 // arguments. It doesn't matter whether any were provided -- the
3881 // presence of the argument list (even if empty) is diagnosed.
3882 Diag(LParenLoc, diag::err_cxx11_attribute_forbids_arguments)
3883 << AttrName
3884 << FixItHint::CreateRemoval(SourceRange(LParenLoc, *EndLoc));
3885 Attr->setInvalid(true);
Aaron Ballman35f94212014-04-14 16:03:22 +00003886 }
3887 }
Aaron Ballmanb8e20392014-03-31 17:32:39 +00003888 return true;
3889}
3890
3891/// ParseCXX11AttributeSpecifier - Parse a C++11 attribute-specifier.
Alexis Hunt96d5c762009-11-21 08:43:09 +00003892///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003893/// [C++11] attribute-specifier:
Alexis Hunt96d5c762009-11-21 08:43:09 +00003894/// '[' '[' attribute-list ']' ']'
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00003895/// alignment-specifier
Alexis Hunt96d5c762009-11-21 08:43:09 +00003896///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003897/// [C++11] attribute-list:
Alexis Hunt96d5c762009-11-21 08:43:09 +00003898/// attribute[opt]
3899/// attribute-list ',' attribute[opt]
Richard Smith3dff2512012-04-10 03:25:07 +00003900/// attribute '...'
3901/// attribute-list ',' attribute '...'
Alexis Hunt96d5c762009-11-21 08:43:09 +00003902///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003903/// [C++11] attribute:
Alexis Hunt96d5c762009-11-21 08:43:09 +00003904/// attribute-token attribute-argument-clause[opt]
3905///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003906/// [C++11] attribute-token:
Alexis Hunt96d5c762009-11-21 08:43:09 +00003907/// identifier
3908/// attribute-scoped-token
3909///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003910/// [C++11] attribute-scoped-token:
Alexis Hunt96d5c762009-11-21 08:43:09 +00003911/// attribute-namespace '::' identifier
3912///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003913/// [C++11] attribute-namespace:
Alexis Hunt96d5c762009-11-21 08:43:09 +00003914/// identifier
Richard Smith3dff2512012-04-10 03:25:07 +00003915void Parser::ParseCXX11AttributeSpecifier(ParsedAttributes &attrs,
Peter Collingbourne49eedec2011-09-29 18:04:05 +00003916 SourceLocation *endLoc) {
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00003917 if (Tok.is(tok::kw_alignas)) {
Richard Smithf679b5b2011-10-14 20:48:27 +00003918 Diag(Tok.getLocation(), diag::warn_cxx98_compat_alignas);
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00003919 ParseAlignmentSpecifier(attrs, endLoc);
3920 return;
3921 }
3922
Alexis Hunt96d5c762009-11-21 08:43:09 +00003923 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square)
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003924 && "Not a C++11 attribute list");
Alexis Hunt96d5c762009-11-21 08:43:09 +00003925
Richard Smithf679b5b2011-10-14 20:48:27 +00003926 Diag(Tok.getLocation(), diag::warn_cxx98_compat_attribute);
3927
Alexis Hunt96d5c762009-11-21 08:43:09 +00003928 ConsumeBracket();
3929 ConsumeBracket();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003930
Richard Smithb7d7a042016-06-24 12:15:12 +00003931 SourceLocation CommonScopeLoc;
3932 IdentifierInfo *CommonScopeName = nullptr;
3933 if (Tok.is(tok::kw_using)) {
3934 Diag(Tok.getLocation(), getLangOpts().CPlusPlus1z
3935 ? diag::warn_cxx14_compat_using_attribute_ns
3936 : diag::ext_using_attribute_ns);
3937 ConsumeToken();
3938
3939 CommonScopeName = TryParseCXX11AttributeIdentifier(CommonScopeLoc);
3940 if (!CommonScopeName) {
3941 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
3942 SkipUntil(tok::r_square, tok::colon, StopBeforeMatch);
3943 }
3944 if (!TryConsumeToken(tok::colon) && CommonScopeName)
3945 Diag(Tok.getLocation(), diag::err_expected) << tok::colon;
3946 }
3947
Richard Smith10876ef2013-01-17 01:30:42 +00003948 llvm::SmallDenseMap<IdentifierInfo*, SourceLocation, 4> SeenAttrs;
3949
Richard Smith3dff2512012-04-10 03:25:07 +00003950 while (Tok.isNot(tok::r_square)) {
Alexis Hunt96d5c762009-11-21 08:43:09 +00003951 // attribute not present
Alp Toker97650562014-01-10 11:19:30 +00003952 if (TryConsumeToken(tok::comma))
Alexis Hunt96d5c762009-11-21 08:43:09 +00003953 continue;
Alexis Hunt96d5c762009-11-21 08:43:09 +00003954
Richard Smith3dff2512012-04-10 03:25:07 +00003955 SourceLocation ScopeLoc, AttrLoc;
Craig Topper161e4db2014-05-21 06:02:52 +00003956 IdentifierInfo *ScopeName = nullptr, *AttrName = nullptr;
Richard Smith3dff2512012-04-10 03:25:07 +00003957
3958 AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
3959 if (!AttrName)
3960 // Break out to the "expected ']'" diagnostic.
3961 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003962
Alexis Hunt96d5c762009-11-21 08:43:09 +00003963 // scoped attribute
Alp Toker97650562014-01-10 11:19:30 +00003964 if (TryConsumeToken(tok::coloncolon)) {
Richard Smith3dff2512012-04-10 03:25:07 +00003965 ScopeName = AttrName;
3966 ScopeLoc = AttrLoc;
3967
3968 AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
3969 if (!AttrName) {
Alp Tokerec543272013-12-24 09:48:30 +00003970 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
Alexey Bataevee6507d2013-11-18 08:17:37 +00003971 SkipUntil(tok::r_square, tok::comma, StopAtSemi | StopBeforeMatch);
Alexis Hunt96d5c762009-11-21 08:43:09 +00003972 continue;
3973 }
Alexis Hunt96d5c762009-11-21 08:43:09 +00003974 }
3975
Richard Smithb7d7a042016-06-24 12:15:12 +00003976 if (CommonScopeName) {
3977 if (ScopeName) {
3978 Diag(ScopeLoc, diag::err_using_attribute_ns_conflict)
3979 << SourceRange(CommonScopeLoc);
3980 } else {
3981 ScopeName = CommonScopeName;
3982 ScopeLoc = CommonScopeLoc;
3983 }
3984 }
3985
Aaron Ballmanb8e20392014-03-31 17:32:39 +00003986 bool StandardAttr = IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName);
Alexis Hunt96d5c762009-11-21 08:43:09 +00003987 bool AttrParsed = false;
Alexis Hunt96d5c762009-11-21 08:43:09 +00003988
Richard Smith10876ef2013-01-17 01:30:42 +00003989 if (StandardAttr &&
3990 !SeenAttrs.insert(std::make_pair(AttrName, AttrLoc)).second)
3991 Diag(AttrLoc, diag::err_cxx11_attribute_repeated)
Aaron Ballmanb8e20392014-03-31 17:32:39 +00003992 << AttrName << SourceRange(SeenAttrs[AttrName]);
Richard Smith10876ef2013-01-17 01:30:42 +00003993
Michael Han23214e52012-10-03 01:56:22 +00003994 // Parse attribute arguments
Aaron Ballman35f94212014-04-14 16:03:22 +00003995 if (Tok.is(tok::l_paren))
Aaron Ballmanb8e20392014-03-31 17:32:39 +00003996 AttrParsed = ParseCXX11AttributeArgs(AttrName, AttrLoc, attrs, endLoc,
3997 ScopeName, ScopeLoc);
Michael Han23214e52012-10-03 01:56:22 +00003998
3999 if (!AttrParsed)
Richard Smith84837d52012-05-03 18:27:39 +00004000 attrs.addNew(AttrName,
4001 SourceRange(ScopeLoc.isValid() ? ScopeLoc : AttrLoc,
4002 AttrLoc),
Craig Topper161e4db2014-05-21 06:02:52 +00004003 ScopeName, ScopeLoc, nullptr, 0, AttributeList::AS_CXX11);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004004
Alp Toker97650562014-01-10 11:19:30 +00004005 if (TryConsumeToken(tok::ellipsis))
Michael Han23214e52012-10-03 01:56:22 +00004006 Diag(Tok, diag::err_cxx11_attribute_forbids_ellipsis)
4007 << AttrName->getName();
Alexis Hunt96d5c762009-11-21 08:43:09 +00004008 }
4009
Alp Toker383d2c42014-01-01 03:08:43 +00004010 if (ExpectAndConsume(tok::r_square))
Alexey Bataevee6507d2013-11-18 08:17:37 +00004011 SkipUntil(tok::r_square);
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004012 if (endLoc)
4013 *endLoc = Tok.getLocation();
Alp Toker383d2c42014-01-01 03:08:43 +00004014 if (ExpectAndConsume(tok::r_square))
Alexey Bataevee6507d2013-11-18 08:17:37 +00004015 SkipUntil(tok::r_square);
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004016}
Alexis Hunt96d5c762009-11-21 08:43:09 +00004017
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00004018/// ParseCXX11Attributes - Parse a C++11 attribute-specifier-seq.
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004019///
4020/// attribute-specifier-seq:
4021/// attribute-specifier-seq[opt] attribute-specifier
Richard Smith3dff2512012-04-10 03:25:07 +00004022void Parser::ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004023 SourceLocation *endLoc) {
Richard Smith4cabd042013-02-22 09:15:49 +00004024 assert(getLangOpts().CPlusPlus11);
4025
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004026 SourceLocation StartLoc = Tok.getLocation(), Loc;
4027 if (!endLoc)
4028 endLoc = &Loc;
4029
Douglas Gregor6f981002011-10-07 20:35:25 +00004030 do {
Richard Smith3dff2512012-04-10 03:25:07 +00004031 ParseCXX11AttributeSpecifier(attrs, endLoc);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004032 } while (isCXX11AttributeSpecifier());
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004033
4034 attrs.Range = SourceRange(StartLoc, *endLoc);
Alexis Hunt96d5c762009-11-21 08:43:09 +00004035}
4036
Richard Smithc2c8bb82013-10-15 01:34:54 +00004037void Parser::DiagnoseAndSkipCXX11Attributes() {
Richard Smithc2c8bb82013-10-15 01:34:54 +00004038 // Start and end location of an attribute or an attribute list.
4039 SourceLocation StartLoc = Tok.getLocation();
Richard Smith955bf012014-06-19 11:42:00 +00004040 SourceLocation EndLoc = SkipCXX11Attributes();
4041
4042 if (EndLoc.isValid()) {
4043 SourceRange Range(StartLoc, EndLoc);
4044 Diag(StartLoc, diag::err_attributes_not_allowed)
4045 << Range;
4046 }
4047}
4048
4049SourceLocation Parser::SkipCXX11Attributes() {
Richard Smithc2c8bb82013-10-15 01:34:54 +00004050 SourceLocation EndLoc;
4051
Richard Smith955bf012014-06-19 11:42:00 +00004052 if (!isCXX11AttributeSpecifier())
4053 return EndLoc;
4054
Richard Smithc2c8bb82013-10-15 01:34:54 +00004055 do {
4056 if (Tok.is(tok::l_square)) {
4057 BalancedDelimiterTracker T(*this, tok::l_square);
4058 T.consumeOpen();
4059 T.skipToEnd();
4060 EndLoc = T.getCloseLocation();
4061 } else {
4062 assert(Tok.is(tok::kw_alignas) && "not an attribute specifier");
4063 ConsumeToken();
4064 BalancedDelimiterTracker T(*this, tok::l_paren);
4065 if (!T.consumeOpen())
4066 T.skipToEnd();
4067 EndLoc = T.getCloseLocation();
4068 }
4069 } while (isCXX11AttributeSpecifier());
4070
Richard Smith955bf012014-06-19 11:42:00 +00004071 return EndLoc;
Richard Smithc2c8bb82013-10-15 01:34:54 +00004072}
4073
Nico Weber05e1dad2016-09-03 03:25:22 +00004074/// Parse uuid() attribute when it appears in a [] Microsoft attribute.
4075void Parser::ParseMicrosoftUuidAttributeArgs(ParsedAttributes &Attrs) {
4076 assert(Tok.is(tok::identifier) && "Not a Microsoft attribute list");
4077 IdentifierInfo *UuidIdent = Tok.getIdentifierInfo();
4078 assert(UuidIdent->getName() == "uuid" && "Not a Microsoft attribute list");
4079
4080 SourceLocation UuidLoc = Tok.getLocation();
4081 ConsumeToken();
4082
4083 // Ignore the left paren location for now.
4084 BalancedDelimiterTracker T(*this, tok::l_paren);
4085 if (T.consumeOpen()) {
4086 Diag(Tok, diag::err_expected) << tok::l_paren;
4087 return;
4088 }
4089
4090 ArgsVector ArgExprs;
4091 if (Tok.is(tok::string_literal)) {
4092 // Easy case: uuid("...") -- quoted string.
4093 ExprResult StringResult = ParseStringLiteralExpression();
4094 if (StringResult.isInvalid())
4095 return;
4096 ArgExprs.push_back(StringResult.get());
4097 } else {
4098 // something like uuid({000000A0-0000-0000-C000-000000000049}) -- no
4099 // quotes in the parens. Just append the spelling of all tokens encountered
4100 // until the closing paren.
4101
4102 SmallString<42> StrBuffer; // 2 "", 36 bytes UUID, 2 optional {}, 1 nul
4103 StrBuffer += "\"";
4104
4105 // Since none of C++'s keywords match [a-f]+, accepting just tok::l_brace,
4106 // tok::r_brace, tok::minus, tok::identifier (think C000) and
4107 // tok::numeric_constant (0000) should be enough. But the spelling of the
4108 // uuid argument is checked later anyways, so there's no harm in accepting
4109 // almost anything here.
4110 // cl is very strict about whitespace in this form and errors out if any
4111 // is present, so check the space flags on the tokens.
4112 SourceLocation StartLoc = Tok.getLocation();
4113 while (Tok.isNot(tok::r_paren)) {
4114 if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
4115 Diag(Tok, diag::err_attribute_uuid_malformed_guid);
4116 SkipUntil(tok::r_paren, StopAtSemi);
4117 return;
4118 }
4119 SmallString<16> SpellingBuffer;
4120 SpellingBuffer.resize(Tok.getLength() + 1);
4121 bool Invalid = false;
4122 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
4123 if (Invalid) {
4124 SkipUntil(tok::r_paren, StopAtSemi);
4125 return;
4126 }
4127 StrBuffer += TokSpelling;
4128 ConsumeAnyToken();
4129 }
4130 StrBuffer += "\"";
4131
4132 if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
4133 Diag(Tok, diag::err_attribute_uuid_malformed_guid);
4134 ConsumeParen();
4135 return;
4136 }
4137
4138 // Pretend the user wrote the appropriate string literal here.
4139 // ActOnStringLiteral() copies the string data into the literal, so it's
4140 // ok that the Token points to StrBuffer.
4141 Token Toks[1];
4142 Toks[0].startToken();
4143 Toks[0].setKind(tok::string_literal);
4144 Toks[0].setLocation(StartLoc);
4145 Toks[0].setLiteralData(StrBuffer.data());
4146 Toks[0].setLength(StrBuffer.size());
4147 StringLiteral *UuidString =
4148 cast<StringLiteral>(Actions.ActOnStringLiteral(Toks, nullptr).get());
4149 ArgExprs.push_back(UuidString);
4150 }
4151
4152 if (!T.consumeClose()) {
4153 // FIXME: Warn that this syntax is deprecated, with a Fix-It suggesting
4154 // using __declspec(uuid()) instead.
4155 Attrs.addNew(UuidIdent, SourceRange(UuidLoc, T.getCloseLocation()), nullptr,
4156 SourceLocation(), ArgExprs.data(), ArgExprs.size(),
4157 AttributeList::AS_Microsoft);
4158 }
4159}
4160
David Majnemere4752e752015-07-08 05:55:00 +00004161/// ParseMicrosoftAttributes - Parse Microsoft attributes [Attr]
Francois Pichetc2bc5ac2010-10-11 12:59:39 +00004162///
4163/// [MS] ms-attribute:
4164/// '[' token-seq ']'
4165///
4166/// [MS] ms-attribute-seq:
4167/// ms-attribute[opt]
4168/// ms-attribute ms-attribute-seq
John McCall53fa7142010-12-24 02:08:15 +00004169void Parser::ParseMicrosoftAttributes(ParsedAttributes &attrs,
4170 SourceLocation *endLoc) {
Francois Pichetc2bc5ac2010-10-11 12:59:39 +00004171 assert(Tok.is(tok::l_square) && "Not a Microsoft attribute list");
4172
Saleem Abdulrasool425efcf2015-06-15 20:57:04 +00004173 do {
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004174 // FIXME: If this is actually a C++11 attribute, parse it as one.
Saleem Abdulrasool425efcf2015-06-15 20:57:04 +00004175 BalancedDelimiterTracker T(*this, tok::l_square);
4176 T.consumeOpen();
Nico Weber05e1dad2016-09-03 03:25:22 +00004177
4178 // Skip most ms attributes except for a whitelist.
4179 while (true) {
4180 SkipUntil(tok::r_square, tok::identifier, StopAtSemi | StopBeforeMatch);
4181 if (Tok.isNot(tok::identifier)) // ']', but also eof
4182 break;
4183 if (Tok.getIdentifierInfo()->getName() == "uuid")
4184 ParseMicrosoftUuidAttributeArgs(attrs);
4185 else
4186 ConsumeToken();
4187 }
4188
Saleem Abdulrasool425efcf2015-06-15 20:57:04 +00004189 T.consumeClose();
4190 if (endLoc)
4191 *endLoc = T.getCloseLocation();
4192 } while (Tok.is(tok::l_square));
Francois Pichetc2bc5ac2010-10-11 12:59:39 +00004193}
Francois Pichet8f981d52011-05-25 10:19:49 +00004194
4195void Parser::ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType,
4196 AccessSpecifier& CurAS) {
Douglas Gregor43edb322011-10-24 22:31:10 +00004197 IfExistsCondition Result;
Francois Pichet8f981d52011-05-25 10:19:49 +00004198 if (ParseMicrosoftIfExistsCondition(Result))
4199 return;
4200
Douglas Gregor43edb322011-10-24 22:31:10 +00004201 BalancedDelimiterTracker Braces(*this, tok::l_brace);
4202 if (Braces.consumeOpen()) {
Alp Tokerec543272013-12-24 09:48:30 +00004203 Diag(Tok, diag::err_expected) << tok::l_brace;
Francois Pichet8f981d52011-05-25 10:19:49 +00004204 return;
4205 }
Francois Pichet8f981d52011-05-25 10:19:49 +00004206
Douglas Gregor43edb322011-10-24 22:31:10 +00004207 switch (Result.Behavior) {
4208 case IEB_Parse:
4209 // Parse the declarations below.
4210 break;
4211
4212 case IEB_Dependent:
4213 Diag(Result.KeywordLoc, diag::warn_microsoft_dependent_exists)
4214 << Result.IsIfExists;
4215 // Fall through to skip.
4216
4217 case IEB_Skip:
4218 Braces.skipToEnd();
Francois Pichet8f981d52011-05-25 10:19:49 +00004219 return;
4220 }
4221
Richard Smith34f30512013-11-23 04:06:09 +00004222 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
Francois Pichet8f981d52011-05-25 10:19:49 +00004223 // __if_exists, __if_not_exists can nest.
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00004224 if (Tok.isOneOf(tok::kw___if_exists, tok::kw___if_not_exists)) {
Francois Pichet8f981d52011-05-25 10:19:49 +00004225 ParseMicrosoftIfExistsClassDeclaration((DeclSpec::TST)TagType, CurAS);
4226 continue;
4227 }
4228
4229 // Check for extraneous top-level semicolon.
4230 if (Tok.is(tok::semi)) {
Richard Smith87f5dc52012-07-23 05:45:25 +00004231 ConsumeExtraSemi(InsideStruct, TagType);
Francois Pichet8f981d52011-05-25 10:19:49 +00004232 continue;
4233 }
4234
4235 AccessSpecifier AS = getAccessSpecifierIfPresent();
4236 if (AS != AS_none) {
4237 // Current token is a C++ access specifier.
4238 CurAS = AS;
4239 SourceLocation ASLoc = Tok.getLocation();
4240 ConsumeToken();
4241 if (Tok.is(tok::colon))
4242 Actions.ActOnAccessSpecifier(AS, ASLoc, Tok.getLocation());
4243 else
Alp Toker35d87032013-12-30 23:29:50 +00004244 Diag(Tok, diag::err_expected) << tok::colon;
Francois Pichet8f981d52011-05-25 10:19:49 +00004245 ConsumeToken();
4246 continue;
4247 }
4248
4249 // Parse all the comma separated declarators.
Craig Topper161e4db2014-05-21 06:02:52 +00004250 ParseCXXClassMemberDeclaration(CurAS, nullptr);
Francois Pichet8f981d52011-05-25 10:19:49 +00004251 }
Douglas Gregor43edb322011-10-24 22:31:10 +00004252
4253 Braces.consumeClose();
Francois Pichet8f981d52011-05-25 10:19:49 +00004254}