blob: b80f9ee1b02a7eba7e93f2ffc77b4bf7c09c732e [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"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "RAIIObjectsForParser.h"
Erik Verbruggen888d52a2014-01-15 09:15:43 +000016#include "clang/AST/ASTContext.h"
Chandler Carruth757fcd62014-03-04 10:05:20 +000017#include "clang/AST/DeclTemplate.h"
Aaron Ballmanb8e20392014-03-31 17:32:39 +000018#include "clang/Basic/Attributes.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000019#include "clang/Basic/CharInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/Basic/OperatorKinds.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000021#include "clang/Basic/TargetInfo.h"
Chris Lattner60f36222009-01-29 05:15:15 +000022#include "clang/Parse/ParseDiagnostic.h"
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 MaybeParseMicrosoftAttributes(attrs);
221 ParseExternalDeclaration(attrs);
222 }
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000223
224 // The caller is what called check -- we are simply calling
225 // the close for it.
226 Tracker.consumeClose();
Richard Trieu61384cb2011-05-26 20:11:09 +0000227
228 return;
229 }
230
Richard Smith13307f52014-11-08 05:37:34 +0000231 // Handle a nested namespace definition.
232 // FIXME: Preserve the source information through to the AST rather than
233 // desugaring it here.
Richard Trieu61384cb2011-05-26 20:11:09 +0000234 ParseScope NamespaceScope(this, Scope::DeclScope);
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +0000235 UsingDirectiveDecl *ImplicitUsingDirectiveDecl = nullptr;
Richard Trieu61384cb2011-05-26 20:11:09 +0000236 Decl *NamespcDecl =
237 Actions.ActOnStartNamespaceDef(getCurScope(), SourceLocation(),
238 NamespaceLoc[index], IdentLoc[index],
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000239 Ident[index], Tracker.getOpenLocation(),
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +0000240 attrs.getList(), ImplicitUsingDirectiveDecl);
241 assert(!ImplicitUsingDirectiveDecl &&
242 "nested namespace definition cannot define anonymous namespace");
Richard Trieu61384cb2011-05-26 20:11:09 +0000243
244 ParseInnerNamespace(IdentLoc, Ident, NamespaceLoc, ++index, InlineLoc,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000245 attrs, Tracker);
Richard Trieu61384cb2011-05-26 20:11:09 +0000246
247 NamespaceScope.Exit();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000248 Actions.ActOnFinishNamespaceDef(NamespcDecl, Tracker.getCloseLocation());
Richard Trieu61384cb2011-05-26 20:11:09 +0000249}
250
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000251/// ParseNamespaceAlias - Parse the part after the '=' in a namespace
252/// alias definition.
253///
John McCall48871652010-08-21 09:40:31 +0000254Decl *Parser::ParseNamespaceAlias(SourceLocation NamespaceLoc,
John McCall084e83d2011-03-24 11:26:52 +0000255 SourceLocation AliasLoc,
256 IdentifierInfo *Alias,
257 SourceLocation &DeclEnd) {
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000258 assert(Tok.is(tok::equal) && "Not equal token");
Mike Stump11289f42009-09-09 15:08:12 +0000259
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000260 ConsumeToken(); // eat the '='.
Mike Stump11289f42009-09-09 15:08:12 +0000261
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000262 if (Tok.is(tok::code_completion)) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000263 Actions.CodeCompleteNamespaceAliasDecl(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000264 cutOffParsing();
Craig Topper161e4db2014-05-21 06:02:52 +0000265 return nullptr;
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000266 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000267
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000268 CXXScopeSpec SS;
269 // Parse (optional) nested-name-specifier.
David Blaikieefdccaa2016-01-15 23:43:34 +0000270 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false);
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000271
272 if (SS.isInvalid() || Tok.isNot(tok::identifier)) {
273 Diag(Tok, diag::err_expected_namespace_name);
274 // Skip to end of the definition and eat the ';'.
275 SkipUntil(tok::semi);
Craig Topper161e4db2014-05-21 06:02:52 +0000276 return nullptr;
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000277 }
278
279 // Parse identifier.
Anders Carlsson47952ae2009-03-28 22:53:22 +0000280 IdentifierInfo *Ident = Tok.getIdentifierInfo();
281 SourceLocation IdentLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000282
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000283 // Eat the ';'.
Chris Lattner49836b42009-04-02 04:16:50 +0000284 DeclEnd = Tok.getLocation();
Alp Toker383d2c42014-01-01 03:08:43 +0000285 if (ExpectAndConsume(tok::semi, diag::err_expected_semi_after_namespace_name))
286 SkipUntil(tok::semi);
Mike Stump11289f42009-09-09 15:08:12 +0000287
Craig Topperff354282015-11-14 18:16:00 +0000288 return Actions.ActOnNamespaceAliasDef(getCurScope(), NamespaceLoc, AliasLoc,
289 Alias, SS, IdentLoc, Ident);
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000290}
291
Chris Lattner38376f12008-01-12 07:05:38 +0000292/// ParseLinkage - We know that the current token is a string_literal
293/// and just before that, that extern was seen.
294///
295/// linkage-specification: [C++ 7.5p2: dcl.link]
296/// 'extern' string-literal '{' declaration-seq[opt] '}'
297/// 'extern' string-literal declaration
298///
Chris Lattner8ea64422010-11-09 20:15:55 +0000299Decl *Parser::ParseLinkage(ParsingDeclSpec &DS, unsigned Context) {
Richard Smith4ee696d2014-02-17 23:25:27 +0000300 assert(isTokenStringLiteral() && "Not a string literal!");
301 ExprResult Lang = ParseStringLiteralExpression(false);
Chris Lattner38376f12008-01-12 07:05:38 +0000302
Douglas Gregor07665a62009-01-05 19:45:36 +0000303 ParseScope LinkageScope(this, Scope::DeclScope);
Richard Smith4ee696d2014-02-17 23:25:27 +0000304 Decl *LinkageSpec =
305 Lang.isInvalid()
Craig Topper161e4db2014-05-21 06:02:52 +0000306 ? nullptr
Richard Smith4ee696d2014-02-17 23:25:27 +0000307 : Actions.ActOnStartLinkageSpecification(
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000308 getCurScope(), DS.getSourceRange().getBegin(), Lang.get(),
Richard Smith4ee696d2014-02-17 23:25:27 +0000309 Tok.is(tok::l_brace) ? Tok.getLocation() : SourceLocation());
Douglas Gregor07665a62009-01-05 19:45:36 +0000310
John McCall084e83d2011-03-24 11:26:52 +0000311 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +0000312 MaybeParseCXX11Attributes(attrs);
John McCall53fa7142010-12-24 02:08:15 +0000313 MaybeParseMicrosoftAttributes(attrs);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000314
Douglas Gregor07665a62009-01-05 19:45:36 +0000315 if (Tok.isNot(tok::l_brace)) {
Abramo Bagnara4d423992011-05-01 16:25:54 +0000316 // Reset the source range in DS, as the leading "extern"
317 // does not really belong to the inner declaration ...
318 DS.SetRangeStart(SourceLocation());
319 DS.SetRangeEnd(SourceLocation());
320 // ... but anyway remember that such an "extern" was seen.
Abramo Bagnaraed5b6892010-07-30 16:47:02 +0000321 DS.setExternInLinkageSpec(true);
John McCall53fa7142010-12-24 02:08:15 +0000322 ParseExternalDeclaration(attrs, &DS);
Richard Smith4ee696d2014-02-17 23:25:27 +0000323 return LinkageSpec ? Actions.ActOnFinishLinkageSpecification(
324 getCurScope(), LinkageSpec, SourceLocation())
Craig Topper161e4db2014-05-21 06:02:52 +0000325 : nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000326 }
Douglas Gregor29ff7d02008-12-16 22:23:02 +0000327
Douglas Gregorb65a9132010-02-07 08:38:28 +0000328 DS.abort();
329
John McCall53fa7142010-12-24 02:08:15 +0000330 ProhibitAttributes(attrs);
Alexis Hunt96d5c762009-11-21 08:43:09 +0000331
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000332 BalancedDelimiterTracker T(*this, tok::l_brace);
333 T.consumeOpen();
Richard Smith77944862014-03-02 05:58:18 +0000334
335 unsigned NestedModules = 0;
336 while (true) {
337 switch (Tok.getKind()) {
338 case tok::annot_module_begin:
339 ++NestedModules;
340 ParseTopLevelDecl();
341 continue;
342
343 case tok::annot_module_end:
344 if (!NestedModules)
345 break;
346 --NestedModules;
347 ParseTopLevelDecl();
348 continue;
349
350 case tok::annot_module_include:
351 ParseTopLevelDecl();
352 continue;
353
354 case tok::eof:
355 break;
356
357 case tok::r_brace:
358 if (!NestedModules)
359 break;
360 // Fall through.
361 default:
362 ParsedAttributesWithRange attrs(AttrFactory);
363 MaybeParseCXX11Attributes(attrs);
364 MaybeParseMicrosoftAttributes(attrs);
365 ParseExternalDeclaration(attrs);
366 continue;
367 }
368
369 break;
Chris Lattner38376f12008-01-12 07:05:38 +0000370 }
371
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000372 T.consumeClose();
Richard Smith4ee696d2014-02-17 23:25:27 +0000373 return LinkageSpec ? Actions.ActOnFinishLinkageSpecification(
374 getCurScope(), LinkageSpec, T.getCloseLocation())
Craig Topper161e4db2014-05-21 06:02:52 +0000375 : nullptr;
Chris Lattner38376f12008-01-12 07:05:38 +0000376}
Douglas Gregor556877c2008-04-13 21:30:24 +0000377
Douglas Gregord7c4d982008-12-30 03:27:21 +0000378/// ParseUsingDirectiveOrDeclaration - Parse C++ using using-declaration or
379/// using-directive. Assumes that current token is 'using'.
John McCall48871652010-08-21 09:40:31 +0000380Decl *Parser::ParseUsingDirectiveOrDeclaration(unsigned Context,
John McCall9b72f892010-11-10 02:40:36 +0000381 const ParsedTemplateInfo &TemplateInfo,
382 SourceLocation &DeclEnd,
Richard Smithcd1c0552011-07-01 19:46:12 +0000383 ParsedAttributesWithRange &attrs,
384 Decl **OwnedType) {
Douglas Gregord7c4d982008-12-30 03:27:21 +0000385 assert(Tok.is(tok::kw_using) && "Not using token");
Fariborz Jahanian4bf82622011-08-22 17:59:19 +0000386 ObjCDeclContextSwitch ObjCDC(*this);
387
Douglas Gregord7c4d982008-12-30 03:27:21 +0000388 // Eat 'using'.
389 SourceLocation UsingLoc = ConsumeToken();
390
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000391 if (Tok.is(tok::code_completion)) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000392 Actions.CodeCompleteUsing(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000393 cutOffParsing();
Craig Topper161e4db2014-05-21 06:02:52 +0000394 return nullptr;
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000395 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000396
John McCall9b72f892010-11-10 02:40:36 +0000397 // 'using namespace' means this is a using-directive.
398 if (Tok.is(tok::kw_namespace)) {
399 // Template parameters are always an error here.
400 if (TemplateInfo.Kind) {
401 SourceRange R = TemplateInfo.getSourceRange();
Craig Topper54a6a682015-11-14 18:16:08 +0000402 Diag(UsingLoc, diag::err_templated_using_directive_declaration)
403 << 0 /* directive */ << R << FixItHint::CreateRemoval(R);
John McCall9b72f892010-11-10 02:40:36 +0000404 }
Alexis Hunt96d5c762009-11-21 08:43:09 +0000405
Fariborz Jahanian4bf82622011-08-22 17:59:19 +0000406 return ParseUsingDirective(Context, UsingLoc, DeclEnd, attrs);
John McCall9b72f892010-11-10 02:40:36 +0000407 }
408
Richard Smithdda56e42011-04-15 14:24:37 +0000409 // Otherwise, it must be a using-declaration or an alias-declaration.
John McCall9b72f892010-11-10 02:40:36 +0000410
411 // Using declarations can't have attributes.
John McCall53fa7142010-12-24 02:08:15 +0000412 ProhibitAttributes(attrs);
Chris Lattner9b01ca12009-01-06 06:55:51 +0000413
Fariborz Jahanian4bf82622011-08-22 17:59:19 +0000414 return ParseUsingDeclaration(Context, TemplateInfo, UsingLoc, DeclEnd,
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +0000415 AS_none, OwnedType);
Douglas Gregord7c4d982008-12-30 03:27:21 +0000416}
417
418/// ParseUsingDirective - Parse C++ using-directive, assumes
419/// that current token is 'namespace' and 'using' was already parsed.
420///
421/// using-directive: [C++ 7.3.p4: namespace.udir]
422/// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
423/// namespace-name ;
424/// [GNU] using-directive:
425/// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
426/// namespace-name attributes[opt] ;
427///
John McCall48871652010-08-21 09:40:31 +0000428Decl *Parser::ParseUsingDirective(unsigned Context,
John McCall9b72f892010-11-10 02:40:36 +0000429 SourceLocation UsingLoc,
430 SourceLocation &DeclEnd,
John McCall53fa7142010-12-24 02:08:15 +0000431 ParsedAttributes &attrs) {
Douglas Gregord7c4d982008-12-30 03:27:21 +0000432 assert(Tok.is(tok::kw_namespace) && "Not 'namespace' token");
433
434 // Eat 'namespace'.
435 SourceLocation NamespcLoc = ConsumeToken();
436
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000437 if (Tok.is(tok::code_completion)) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000438 Actions.CodeCompleteUsingDirective(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000439 cutOffParsing();
Craig Topper161e4db2014-05-21 06:02:52 +0000440 return nullptr;
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000441 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000442
Douglas Gregord7c4d982008-12-30 03:27:21 +0000443 CXXScopeSpec SS;
444 // Parse (optional) nested-name-specifier.
David Blaikieefdccaa2016-01-15 23:43:34 +0000445 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false);
Douglas Gregord7c4d982008-12-30 03:27:21 +0000446
Craig Topper161e4db2014-05-21 06:02:52 +0000447 IdentifierInfo *NamespcName = nullptr;
Douglas Gregord7c4d982008-12-30 03:27:21 +0000448 SourceLocation IdentLoc = SourceLocation();
449
450 // Parse namespace-name.
Chris Lattnerce1da2c2009-01-06 07:27:21 +0000451 if (SS.isInvalid() || Tok.isNot(tok::identifier)) {
Douglas Gregord7c4d982008-12-30 03:27:21 +0000452 Diag(Tok, diag::err_expected_namespace_name);
453 // If there was invalid namespace name, skip to end of decl, and eat ';'.
454 SkipUntil(tok::semi);
455 // FIXME: Are there cases, when we would like to call ActOnUsingDirective?
Craig Topper161e4db2014-05-21 06:02:52 +0000456 return nullptr;
Douglas Gregord7c4d982008-12-30 03:27:21 +0000457 }
Mike Stump11289f42009-09-09 15:08:12 +0000458
Chris Lattnerce1da2c2009-01-06 07:27:21 +0000459 // Parse identifier.
460 NamespcName = Tok.getIdentifierInfo();
461 IdentLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000462
Chris Lattnerce1da2c2009-01-06 07:27:21 +0000463 // Parse (optional) attributes (most likely GNU strong-using extension).
Alexis Hunt96d5c762009-11-21 08:43:09 +0000464 bool GNUAttr = false;
465 if (Tok.is(tok::kw___attribute)) {
466 GNUAttr = true;
John McCall53fa7142010-12-24 02:08:15 +0000467 ParseGNUAttributes(attrs);
Alexis Hunt96d5c762009-11-21 08:43:09 +0000468 }
Mike Stump11289f42009-09-09 15:08:12 +0000469
Chris Lattnerce1da2c2009-01-06 07:27:21 +0000470 // Eat ';'.
Chris Lattner49836b42009-04-02 04:16:50 +0000471 DeclEnd = Tok.getLocation();
Alp Toker383d2c42014-01-01 03:08:43 +0000472 if (ExpectAndConsume(tok::semi,
473 GNUAttr ? diag::err_expected_semi_after_attribute_list
474 : diag::err_expected_semi_after_namespace_name))
475 SkipUntil(tok::semi);
Douglas Gregord7c4d982008-12-30 03:27:21 +0000476
Douglas Gregor0be31a22010-07-02 17:43:08 +0000477 return Actions.ActOnUsingDirective(getCurScope(), UsingLoc, NamespcLoc, SS,
John McCall53fa7142010-12-24 02:08:15 +0000478 IdentLoc, NamespcName, attrs.getList());
Douglas Gregord7c4d982008-12-30 03:27:21 +0000479}
480
Richard Smithdda56e42011-04-15 14:24:37 +0000481/// ParseUsingDeclaration - Parse C++ using-declaration or alias-declaration.
482/// Assumes that 'using' was already seen.
Douglas Gregord7c4d982008-12-30 03:27:21 +0000483///
484/// using-declaration: [C++ 7.3.p3: namespace.udecl]
485/// 'using' 'typename'[opt] ::[opt] nested-name-specifier
Douglas Gregorfec52632009-06-20 00:51:54 +0000486/// unqualified-id
487/// 'using' :: unqualified-id
Douglas Gregord7c4d982008-12-30 03:27:21 +0000488///
Richard Smith810ad3e2013-01-29 10:02:16 +0000489/// alias-declaration: C++11 [dcl.dcl]p1
490/// 'using' identifier attribute-specifier-seq[opt] = type-id ;
Richard Smithdda56e42011-04-15 14:24:37 +0000491///
John McCall48871652010-08-21 09:40:31 +0000492Decl *Parser::ParseUsingDeclaration(unsigned Context,
John McCall9b72f892010-11-10 02:40:36 +0000493 const ParsedTemplateInfo &TemplateInfo,
494 SourceLocation UsingLoc,
495 SourceLocation &DeclEnd,
Richard Smithcd1c0552011-07-01 19:46:12 +0000496 AccessSpecifier AS,
497 Decl **OwnedType) {
Douglas Gregorfec52632009-06-20 00:51:54 +0000498 CXXScopeSpec SS;
John McCalle61f2ba2009-11-18 02:36:19 +0000499 SourceLocation TypenameLoc;
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +0000500 bool HasTypenameKeyword = false;
Alexis Hunt6aa9bee2012-06-23 05:07:58 +0000501
Richard Smithc2c8bb82013-10-15 01:34:54 +0000502 // Check for misplaced attributes before the identifier in an
503 // alias-declaration.
504 ParsedAttributesWithRange MisplacedAttrs(AttrFactory);
505 MaybeParseCXX11Attributes(MisplacedAttrs);
Douglas Gregorfec52632009-06-20 00:51:54 +0000506
507 // Ignore optional 'typename'.
Douglas Gregor220f4272009-11-04 16:30:06 +0000508 // FIXME: This is wrong; we should parse this as a typename-specifier.
Alp Toker97650562014-01-10 11:19:30 +0000509 if (TryConsumeToken(tok::kw_typename, TypenameLoc))
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +0000510 HasTypenameKeyword = true;
Douglas Gregorfec52632009-06-20 00:51:54 +0000511
Nikola Smiljanic67860242014-09-26 00:28:20 +0000512 if (Tok.is(tok::kw___super)) {
513 Diag(Tok.getLocation(), diag::err_super_in_using_declaration);
514 SkipUntil(tok::semi);
515 return nullptr;
516 }
517
Douglas Gregorfec52632009-06-20 00:51:54 +0000518 // Parse nested-name-specifier.
Craig Topper161e4db2014-05-21 06:02:52 +0000519 IdentifierInfo *LastII = nullptr;
David Blaikieefdccaa2016-01-15 23:43:34 +0000520 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false,
Craig Topper161e4db2014-05-21 06:02:52 +0000521 /*MayBePseudoDtor=*/nullptr,
522 /*IsTypename=*/false,
Richard Smith7447af42013-03-26 01:15:19 +0000523 /*LastII=*/&LastII);
Douglas Gregorfec52632009-06-20 00:51:54 +0000524
Douglas Gregorfec52632009-06-20 00:51:54 +0000525 // Check nested-name specifier.
526 if (SS.isInvalid()) {
527 SkipUntil(tok::semi);
Craig Topper161e4db2014-05-21 06:02:52 +0000528 return nullptr;
Douglas Gregorfec52632009-06-20 00:51:54 +0000529 }
Douglas Gregor220f4272009-11-04 16:30:06 +0000530
Richard Smith7447af42013-03-26 01:15:19 +0000531 SourceLocation TemplateKWLoc;
532 UnqualifiedId Name;
533
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000534 // Parse the unqualified-id. We allow parsing of both constructor and
Douglas Gregor220f4272009-11-04 16:30:06 +0000535 // destructor names and allow the action module to diagnose any semantic
536 // errors.
Richard Smith7447af42013-03-26 01:15:19 +0000537 //
538 // C++11 [class.qual]p2:
539 // [...] in a using-declaration that is a member-declaration, if the name
540 // specified after the nested-name-specifier is the same as the identifier
541 // or the simple-template-id's template-name in the last component of the
542 // nested-name-specifier, the name is [...] considered to name the
543 // constructor.
544 if (getLangOpts().CPlusPlus11 && Context == Declarator::MemberContext &&
545 Tok.is(tok::identifier) && NextToken().is(tok::semi) &&
546 SS.isNotEmpty() && LastII == Tok.getIdentifierInfo() &&
547 !SS.getScopeRep()->getAsNamespace() &&
548 !SS.getScopeRep()->getAsNamespaceAlias()) {
549 SourceLocation IdLoc = ConsumeToken();
550 ParsedType Type = Actions.getInheritingConstructorName(SS, IdLoc, *LastII);
551 Name.setConstructorName(Type, IdLoc, IdLoc);
Richard Smith88fe69c2015-07-06 01:45:27 +0000552 } else if (ParseUnqualifiedId(
553 SS, /*EnteringContext=*/false,
554 /*AllowDestructorName=*/true,
Richard Smithc7ae3e02015-07-21 00:23:34 +0000555 /*AllowConstructorName=*/!(Tok.is(tok::identifier) &&
556 NextToken().is(tok::equal)),
David Blaikieefdccaa2016-01-15 23:43:34 +0000557 nullptr, TemplateKWLoc, Name)) {
Douglas Gregorfec52632009-06-20 00:51:54 +0000558 SkipUntil(tok::semi);
Craig Topper161e4db2014-05-21 06:02:52 +0000559 return nullptr;
Douglas Gregorfec52632009-06-20 00:51:54 +0000560 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000561
Richard Smithc2c8bb82013-10-15 01:34:54 +0000562 ParsedAttributesWithRange Attrs(AttrFactory);
Richard Smith37a45dd2013-10-24 01:21:09 +0000563 MaybeParseGNUAttributes(Attrs);
Richard Smith54ecd982013-02-20 19:22:51 +0000564 MaybeParseCXX11Attributes(Attrs);
Richard Smithdda56e42011-04-15 14:24:37 +0000565
566 // Maybe this is an alias-declaration.
Richard Smithdda56e42011-04-15 14:24:37 +0000567 TypeResult TypeAlias;
Richard Smithc2c8bb82013-10-15 01:34:54 +0000568 bool IsAliasDecl = Tok.is(tok::equal);
David Majnemerf9bde282015-03-11 06:45:39 +0000569 Decl *DeclFromDeclSpec = nullptr;
Richard Smithdda56e42011-04-15 14:24:37 +0000570 if (IsAliasDecl) {
Richard Smithc2c8bb82013-10-15 01:34:54 +0000571 // If we had any misplaced attributes from earlier, this is where they
572 // should have been written.
573 if (MisplacedAttrs.Range.isValid()) {
574 Diag(MisplacedAttrs.Range.getBegin(), diag::err_attributes_not_allowed)
575 << FixItHint::CreateInsertionFromRange(
576 Tok.getLocation(),
577 CharSourceRange::getTokenRange(MisplacedAttrs.Range))
578 << FixItHint::CreateRemoval(MisplacedAttrs.Range);
579 Attrs.takeAllFrom(MisplacedAttrs);
580 }
581
Richard Smithdda56e42011-04-15 14:24:37 +0000582 ConsumeToken();
583
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000584 Diag(Tok.getLocation(), getLangOpts().CPlusPlus11 ?
Richard Smith5d164bc2011-10-15 05:09:34 +0000585 diag::warn_cxx98_compat_alias_declaration :
586 diag::ext_alias_declaration);
Richard Smithdda56e42011-04-15 14:24:37 +0000587
Richard Smith3f1b5d02011-05-05 21:57:07 +0000588 // Type alias templates cannot be specialized.
589 int SpecKind = -1;
Richard Smith14034022011-05-05 22:36:10 +0000590 if (TemplateInfo.Kind == ParsedTemplateInfo::Template &&
591 Name.getKind() == UnqualifiedId::IK_TemplateId)
Richard Smith3f1b5d02011-05-05 21:57:07 +0000592 SpecKind = 0;
593 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization)
594 SpecKind = 1;
595 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
596 SpecKind = 2;
597 if (SpecKind != -1) {
598 SourceRange Range;
599 if (SpecKind == 0)
600 Range = SourceRange(Name.TemplateId->LAngleLoc,
601 Name.TemplateId->RAngleLoc);
602 else
603 Range = TemplateInfo.getSourceRange();
604 Diag(Range.getBegin(), diag::err_alias_declaration_specialization)
605 << SpecKind << Range;
606 SkipUntil(tok::semi);
Craig Topper161e4db2014-05-21 06:02:52 +0000607 return nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +0000608 }
609
Richard Smithdda56e42011-04-15 14:24:37 +0000610 // Name must be an identifier.
611 if (Name.getKind() != UnqualifiedId::IK_Identifier) {
612 Diag(Name.StartLocation, diag::err_alias_declaration_not_identifier);
613 // No removal fixit: can't recover from this.
614 SkipUntil(tok::semi);
Craig Topper161e4db2014-05-21 06:02:52 +0000615 return nullptr;
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +0000616 } else if (HasTypenameKeyword)
Richard Smithdda56e42011-04-15 14:24:37 +0000617 Diag(TypenameLoc, diag::err_alias_declaration_not_identifier)
618 << FixItHint::CreateRemoval(SourceRange(TypenameLoc,
619 SS.isNotEmpty() ? SS.getEndLoc() : TypenameLoc));
620 else if (SS.isNotEmpty())
621 Diag(SS.getBeginLoc(), diag::err_alias_declaration_not_identifier)
622 << FixItHint::CreateRemoval(SS.getRange());
623
David Majnemerf9bde282015-03-11 06:45:39 +0000624 TypeAlias = ParseTypeName(nullptr, TemplateInfo.Kind
625 ? Declarator::AliasTemplateContext
626 : Declarator::AliasDeclContext,
627 AS, &DeclFromDeclSpec, &Attrs);
628 if (OwnedType)
629 *OwnedType = DeclFromDeclSpec;
Alexis Hunt6aa9bee2012-06-23 05:07:58 +0000630 } else {
631 // C++11 attributes are not allowed on a using-declaration, but GNU ones
632 // are.
Richard Smithc2c8bb82013-10-15 01:34:54 +0000633 ProhibitAttributes(MisplacedAttrs);
Richard Smith54ecd982013-02-20 19:22:51 +0000634 ProhibitAttributes(Attrs);
Alexis Hunt6aa9bee2012-06-23 05:07:58 +0000635
Richard Smithdda56e42011-04-15 14:24:37 +0000636 // Parse (optional) attributes (most likely GNU strong-using extension).
Richard Smith54ecd982013-02-20 19:22:51 +0000637 MaybeParseGNUAttributes(Attrs);
Alexis Hunt6aa9bee2012-06-23 05:07:58 +0000638 }
Mike Stump11289f42009-09-09 15:08:12 +0000639
Douglas Gregorfec52632009-06-20 00:51:54 +0000640 // Eat ';'.
641 DeclEnd = Tok.getLocation();
Alp Toker383d2c42014-01-01 03:08:43 +0000642 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
643 !Attrs.empty() ? "attributes list"
644 : IsAliasDecl ? "alias declaration"
645 : "using declaration"))
646 SkipUntil(tok::semi);
Douglas Gregorfec52632009-06-20 00:51:54 +0000647
John McCall9b72f892010-11-10 02:40:36 +0000648 // Diagnose an attempt to declare a templated using-declaration.
Richard Smith810ad3e2013-01-29 10:02:16 +0000649 // In C++11, alias-declarations can be templates:
Richard Smithdda56e42011-04-15 14:24:37 +0000650 // template <...> using id = type;
Richard Smith3f1b5d02011-05-05 21:57:07 +0000651 if (TemplateInfo.Kind && !IsAliasDecl) {
John McCall9b72f892010-11-10 02:40:36 +0000652 SourceRange R = TemplateInfo.getSourceRange();
Craig Topper54a6a682015-11-14 18:16:08 +0000653 Diag(UsingLoc, diag::err_templated_using_directive_declaration)
654 << 1 /* declaration */ << R << FixItHint::CreateRemoval(R);
John McCall9b72f892010-11-10 02:40:36 +0000655
656 // Unfortunately, we have to bail out instead of recovering by
657 // ignoring the parameters, just in case the nested name specifier
658 // depends on the parameters.
Craig Topper161e4db2014-05-21 06:02:52 +0000659 return nullptr;
John McCall9b72f892010-11-10 02:40:36 +0000660 }
661
Douglas Gregor882a61a2011-09-26 14:30:28 +0000662 // "typename" keyword is allowed for identifiers only,
663 // because it may be a type definition.
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +0000664 if (HasTypenameKeyword && Name.getKind() != UnqualifiedId::IK_Identifier) {
Douglas Gregor882a61a2011-09-26 14:30:28 +0000665 Diag(Name.getSourceRange().getBegin(), diag::err_typename_identifiers_only)
666 << FixItHint::CreateRemoval(SourceRange(TypenameLoc));
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +0000667 // Proceed parsing, but reset the HasTypenameKeyword flag.
668 HasTypenameKeyword = false;
Douglas Gregor882a61a2011-09-26 14:30:28 +0000669 }
670
Richard Smith3f1b5d02011-05-05 21:57:07 +0000671 if (IsAliasDecl) {
672 TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000673 MultiTemplateParamsArg TemplateParamsArg(
Craig Topper161e4db2014-05-21 06:02:52 +0000674 TemplateParams ? TemplateParams->data() : nullptr,
Richard Smith3f1b5d02011-05-05 21:57:07 +0000675 TemplateParams ? TemplateParams->size() : 0);
676 return Actions.ActOnAliasDeclaration(getCurScope(), AS, TemplateParamsArg,
Richard Smith54ecd982013-02-20 19:22:51 +0000677 UsingLoc, Name, Attrs.getList(),
David Majnemerf9bde282015-03-11 06:45:39 +0000678 TypeAlias, DeclFromDeclSpec);
Richard Smith3f1b5d02011-05-05 21:57:07 +0000679 }
Richard Smithdda56e42011-04-15 14:24:37 +0000680
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +0000681 return Actions.ActOnUsingDeclaration(getCurScope(), AS,
682 /* HasUsingKeyword */ true, UsingLoc,
683 SS, Name, Attrs.getList(),
684 HasTypenameKeyword, TypenameLoc);
Douglas Gregord7c4d982008-12-30 03:27:21 +0000685}
686
Benjamin Kramere56f3932011-12-23 17:00:35 +0000687/// ParseStaticAssertDeclaration - Parse C++0x or C11 static_assert-declaration.
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000688///
Peter Collingbourne3d9cbdc2011-04-15 00:35:57 +0000689/// [C++0x] static_assert-declaration:
690/// static_assert ( constant-expression , string-literal ) ;
691///
Benjamin Kramere56f3932011-12-23 17:00:35 +0000692/// [C11] static_assert-declaration:
Peter Collingbourne3d9cbdc2011-04-15 00:35:57 +0000693/// _Static_assert ( constant-expression , string-literal ) ;
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000694///
John McCall48871652010-08-21 09:40:31 +0000695Decl *Parser::ParseStaticAssertDeclaration(SourceLocation &DeclEnd){
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000696 assert(Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert) &&
Peter Collingbourne3d9cbdc2011-04-15 00:35:57 +0000697 "Not a static_assert declaration");
698
David Blaikiebbafb8a2012-03-11 07:00:24 +0000699 if (Tok.is(tok::kw__Static_assert) && !getLangOpts().C11)
Benjamin Kramere56f3932011-12-23 17:00:35 +0000700 Diag(Tok, diag::ext_c11_static_assert);
Richard Smithb15c11c2011-10-17 23:06:20 +0000701 if (Tok.is(tok::kw_static_assert))
702 Diag(Tok, diag::warn_cxx98_compat_static_assert);
Peter Collingbourne3d9cbdc2011-04-15 00:35:57 +0000703
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000704 SourceLocation StaticAssertLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000705
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000706 BalancedDelimiterTracker T(*this, tok::l_paren);
707 if (T.consumeOpen()) {
Alp Tokerec543272013-12-24 09:48:30 +0000708 Diag(Tok, diag::err_expected) << tok::l_paren;
Richard Smith76965712012-09-13 19:12:50 +0000709 SkipMalformedDecl();
Craig Topper161e4db2014-05-21 06:02:52 +0000710 return nullptr;
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000711 }
Mike Stump11289f42009-09-09 15:08:12 +0000712
John McCalldadc5752010-08-24 06:29:42 +0000713 ExprResult AssertExpr(ParseConstantExpression());
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000714 if (AssertExpr.isInvalid()) {
Richard Smith76965712012-09-13 19:12:50 +0000715 SkipMalformedDecl();
Craig Topper161e4db2014-05-21 06:02:52 +0000716 return nullptr;
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000717 }
Mike Stump11289f42009-09-09 15:08:12 +0000718
Richard Smith085a64f2014-06-20 19:57:12 +0000719 ExprResult AssertMessage;
720 if (Tok.is(tok::r_paren)) {
721 Diag(Tok, getLangOpts().CPlusPlus1z
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000722 ? diag::warn_cxx14_compat_static_assert_no_message
Richard Smith085a64f2014-06-20 19:57:12 +0000723 : diag::ext_static_assert_no_message)
724 << (getLangOpts().CPlusPlus1z
725 ? FixItHint()
726 : FixItHint::CreateInsertion(Tok.getLocation(), ", \"\""));
727 } else {
728 if (ExpectAndConsume(tok::comma)) {
729 SkipUntil(tok::semi);
730 return nullptr;
731 }
Anders Carlssonb4cf3ad2009-03-13 23:29:20 +0000732
Richard Smith085a64f2014-06-20 19:57:12 +0000733 if (!isTokenStringLiteral()) {
734 Diag(Tok, diag::err_expected_string_literal)
735 << /*Source='static_assert'*/1;
736 SkipMalformedDecl();
737 return nullptr;
738 }
Mike Stump11289f42009-09-09 15:08:12 +0000739
Richard Smith085a64f2014-06-20 19:57:12 +0000740 AssertMessage = ParseStringLiteralExpression();
741 if (AssertMessage.isInvalid()) {
742 SkipMalformedDecl();
743 return nullptr;
744 }
Richard Smithd67aea22012-03-06 03:21:47 +0000745 }
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000746
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000747 T.consumeClose();
Mike Stump11289f42009-09-09 15:08:12 +0000748
Chris Lattner49836b42009-04-02 04:16:50 +0000749 DeclEnd = Tok.getLocation();
Douglas Gregor45d6bdf2010-09-07 15:23:11 +0000750 ExpectAndConsumeSemi(diag::err_expected_semi_after_static_assert);
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000751
John McCallb268a282010-08-23 23:25:46 +0000752 return Actions.ActOnStaticAssertDeclaration(StaticAssertLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000753 AssertExpr.get(),
754 AssertMessage.get(),
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000755 T.getCloseLocation());
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000756}
757
Richard Smith74aeef52013-04-26 16:15:35 +0000758/// ParseDecltypeSpecifier - Parse a C++11 decltype specifier.
Anders Carlsson74948d02009-06-24 17:47:40 +0000759///
760/// 'decltype' ( expression )
Richard Smith74aeef52013-04-26 16:15:35 +0000761/// 'decltype' ( 'auto' ) [C++1y]
Anders Carlsson74948d02009-06-24 17:47:40 +0000762///
David Blaikie15a430a2011-12-04 05:04:18 +0000763SourceLocation Parser::ParseDecltypeSpecifier(DeclSpec &DS) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000764 assert(Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)
David Blaikie15a430a2011-12-04 05:04:18 +0000765 && "Not a decltype specifier");
766
David Blaikie15a430a2011-12-04 05:04:18 +0000767 ExprResult Result;
768 SourceLocation StartLoc = Tok.getLocation();
769 SourceLocation EndLoc;
770
771 if (Tok.is(tok::annot_decltype)) {
772 Result = getExprAnnotation(Tok);
773 EndLoc = Tok.getAnnotationEndLoc();
774 ConsumeToken();
775 if (Result.isInvalid()) {
776 DS.SetTypeSpecError();
777 return EndLoc;
778 }
779 } else {
Richard Smith324df552012-02-24 22:30:04 +0000780 if (Tok.getIdentifierInfo()->isStr("decltype"))
781 Diag(Tok, diag::warn_cxx98_compat_decltype);
Richard Smithfd3da932012-02-24 18:10:23 +0000782
David Blaikie15a430a2011-12-04 05:04:18 +0000783 ConsumeToken();
784
785 BalancedDelimiterTracker T(*this, tok::l_paren);
786 if (T.expectAndConsume(diag::err_expected_lparen_after,
787 "decltype", tok::r_paren)) {
788 DS.SetTypeSpecError();
789 return T.getOpenLocation() == Tok.getLocation() ?
790 StartLoc : T.getOpenLocation();
791 }
792
Richard Smith74aeef52013-04-26 16:15:35 +0000793 // Check for C++1y 'decltype(auto)'.
794 if (Tok.is(tok::kw_auto)) {
795 // No need to disambiguate here: an expression can't start with 'auto',
796 // because the typename-specifier in a function-style cast operation can't
797 // be 'auto'.
798 Diag(Tok.getLocation(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000799 getLangOpts().CPlusPlus14
Richard Smith74aeef52013-04-26 16:15:35 +0000800 ? diag::warn_cxx11_compat_decltype_auto_type_specifier
801 : diag::ext_decltype_auto_type_specifier);
802 ConsumeToken();
803 } else {
804 // Parse the expression
David Blaikie15a430a2011-12-04 05:04:18 +0000805
Richard Smith74aeef52013-04-26 16:15:35 +0000806 // C++11 [dcl.type.simple]p4:
807 // The operand of the decltype specifier is an unevaluated operand.
808 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
Craig Topper161e4db2014-05-21 06:02:52 +0000809 nullptr,/*IsDecltype=*/true);
Kaelyn Takata5cc85352015-04-10 19:16:46 +0000810 Result =
811 Actions.CorrectDelayedTyposInExpr(ParseExpression(), [](Expr *E) {
812 return E->hasPlaceholderType() ? ExprError() : E;
813 });
Richard Smith74aeef52013-04-26 16:15:35 +0000814 if (Result.isInvalid()) {
815 DS.SetTypeSpecError();
Alexey Bataevee6507d2013-11-18 08:17:37 +0000816 if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch)) {
Richard Smith74aeef52013-04-26 16:15:35 +0000817 EndLoc = ConsumeParen();
Argyrios Kyrtzidisc38395a2012-10-26 22:53:44 +0000818 } else {
Richard Smith74aeef52013-04-26 16:15:35 +0000819 if (PP.isBacktrackEnabled() && Tok.is(tok::semi)) {
820 // Backtrack to get the location of the last token before the semi.
821 PP.RevertCachedTokens(2);
822 ConsumeToken(); // the semi.
823 EndLoc = ConsumeAnyToken();
824 assert(Tok.is(tok::semi));
825 } else {
826 EndLoc = Tok.getLocation();
827 }
Argyrios Kyrtzidisc38395a2012-10-26 22:53:44 +0000828 }
Richard Smith74aeef52013-04-26 16:15:35 +0000829 return EndLoc;
Argyrios Kyrtzidisc38395a2012-10-26 22:53:44 +0000830 }
Richard Smith74aeef52013-04-26 16:15:35 +0000831
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000832 Result = Actions.ActOnDecltypeExpression(Result.get());
David Blaikie15a430a2011-12-04 05:04:18 +0000833 }
834
835 // Match the ')'
836 T.consumeClose();
837 if (T.getCloseLocation().isInvalid()) {
838 DS.SetTypeSpecError();
839 // FIXME: this should return the location of the last token
840 // that was consumed (by "consumeClose()")
841 return T.getCloseLocation();
842 }
843
Richard Smithfd555f62012-02-22 02:04:18 +0000844 if (Result.isInvalid()) {
845 DS.SetTypeSpecError();
846 return T.getCloseLocation();
847 }
848
David Blaikie15a430a2011-12-04 05:04:18 +0000849 EndLoc = T.getCloseLocation();
Anders Carlsson74948d02009-06-24 17:47:40 +0000850 }
Richard Smith74aeef52013-04-26 16:15:35 +0000851 assert(!Result.isInvalid());
Mike Stump11289f42009-09-09 15:08:12 +0000852
Craig Topper161e4db2014-05-21 06:02:52 +0000853 const char *PrevSpec = nullptr;
John McCall49bfce42009-08-03 20:12:06 +0000854 unsigned DiagID;
Erik Verbruggen888d52a2014-01-15 09:15:43 +0000855 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
Anders Carlsson74948d02009-06-24 17:47:40 +0000856 // Check for duplicate type specifiers (e.g. "int decltype(a)").
Richard Smith74aeef52013-04-26 16:15:35 +0000857 if (Result.get()
858 ? DS.SetTypeSpecType(DeclSpec::TST_decltype, StartLoc, PrevSpec,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000859 DiagID, Result.get(), Policy)
Richard Smith74aeef52013-04-26 16:15:35 +0000860 : DS.SetTypeSpecType(DeclSpec::TST_decltype_auto, StartLoc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +0000861 DiagID, Policy)) {
John McCall49bfce42009-08-03 20:12:06 +0000862 Diag(StartLoc, DiagID) << PrevSpec;
David Blaikie15a430a2011-12-04 05:04:18 +0000863 DS.SetTypeSpecError();
864 }
865 return EndLoc;
866}
867
868void Parser::AnnotateExistingDecltypeSpecifier(const DeclSpec& DS,
869 SourceLocation StartLoc,
870 SourceLocation EndLoc) {
871 // make sure we have a token we can turn into an annotation token
872 if (PP.isBacktrackEnabled())
873 PP.RevertCachedTokens(1);
874 else
875 PP.EnterToken(Tok);
876
877 Tok.setKind(tok::annot_decltype);
Richard Smith74aeef52013-04-26 16:15:35 +0000878 setExprAnnotation(Tok,
879 DS.getTypeSpecType() == TST_decltype ? DS.getRepAsExpr() :
880 DS.getTypeSpecType() == TST_decltype_auto ? ExprResult() :
881 ExprError());
David Blaikie15a430a2011-12-04 05:04:18 +0000882 Tok.setAnnotationEndLoc(EndLoc);
883 Tok.setLocation(StartLoc);
884 PP.AnnotateCachedTokens(Tok);
Anders Carlsson74948d02009-06-24 17:47:40 +0000885}
886
Alexis Hunt4a257072011-05-19 05:37:45 +0000887void Parser::ParseUnderlyingTypeSpecifier(DeclSpec &DS) {
888 assert(Tok.is(tok::kw___underlying_type) &&
889 "Not an underlying type specifier");
890
891 SourceLocation StartLoc = ConsumeToken();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000892 BalancedDelimiterTracker T(*this, tok::l_paren);
893 if (T.expectAndConsume(diag::err_expected_lparen_after,
894 "__underlying_type", tok::r_paren)) {
Alexis Hunt4a257072011-05-19 05:37:45 +0000895 return;
896 }
897
898 TypeResult Result = ParseTypeName();
899 if (Result.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +0000900 SkipUntil(tok::r_paren, StopAtSemi);
Alexis Hunt4a257072011-05-19 05:37:45 +0000901 return;
902 }
903
904 // Match the ')'
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000905 T.consumeClose();
906 if (T.getCloseLocation().isInvalid())
Alexis Hunt4a257072011-05-19 05:37:45 +0000907 return;
908
Craig Topper161e4db2014-05-21 06:02:52 +0000909 const char *PrevSpec = nullptr;
Alexis Hunt4a257072011-05-19 05:37:45 +0000910 unsigned DiagID;
Alexis Hunte852b102011-05-24 22:41:36 +0000911 if (DS.SetTypeSpecType(DeclSpec::TST_underlyingType, StartLoc, PrevSpec,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000912 DiagID, Result.get(),
Erik Verbruggen888d52a2014-01-15 09:15:43 +0000913 Actions.getASTContext().getPrintingPolicy()))
Alexis Hunt4a257072011-05-19 05:37:45 +0000914 Diag(StartLoc, DiagID) << PrevSpec;
Enea Zaffanellaa90af722013-07-06 18:54:58 +0000915 DS.setTypeofParensRange(T.getRange());
Alexis Hunt4a257072011-05-19 05:37:45 +0000916}
917
David Blaikie00ee7a082011-10-25 15:01:20 +0000918/// ParseBaseTypeSpecifier - Parse a C++ base-type-specifier which is either a
919/// class name or decltype-specifier. Note that we only check that the result
920/// names a type; semantic analysis will need to verify that the type names a
921/// class. The result is either a type or null, depending on whether a type
922/// name was found.
Douglas Gregor831c93f2008-11-05 20:51:48 +0000923///
Richard Smith4c96e992013-02-19 23:47:15 +0000924/// base-type-specifier: [C++11 class.derived]
David Blaikie00ee7a082011-10-25 15:01:20 +0000925/// class-or-decltype
Richard Smith4c96e992013-02-19 23:47:15 +0000926/// class-or-decltype: [C++11 class.derived]
David Blaikie00ee7a082011-10-25 15:01:20 +0000927/// nested-name-specifier[opt] class-name
928/// decltype-specifier
Richard Smith4c96e992013-02-19 23:47:15 +0000929/// class-name: [C++ class.name]
Douglas Gregor831c93f2008-11-05 20:51:48 +0000930/// identifier
Douglas Gregord54dfb82009-02-25 23:52:28 +0000931/// simple-template-id
Mike Stump11289f42009-09-09 15:08:12 +0000932///
Richard Smith4c96e992013-02-19 23:47:15 +0000933/// In C++98, instead of base-type-specifier, we have:
934///
935/// ::[opt] nested-name-specifier[opt] class-name
Craig Topper9ad7e262014-10-31 06:57:07 +0000936TypeResult Parser::ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
937 SourceLocation &EndLocation) {
David Blaikiedd58d4c2011-10-25 18:46:41 +0000938 // Ignore attempts to use typename
939 if (Tok.is(tok::kw_typename)) {
940 Diag(Tok, diag::err_expected_class_name_not_template)
941 << FixItHint::CreateRemoval(Tok.getLocation());
942 ConsumeToken();
943 }
944
David Blaikieafa155f2011-10-25 18:17:58 +0000945 // Parse optional nested-name-specifier
946 CXXScopeSpec SS;
David Blaikieefdccaa2016-01-15 23:43:34 +0000947 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false);
David Blaikieafa155f2011-10-25 18:17:58 +0000948
949 BaseLoc = Tok.getLocation();
950
David Blaikie1cd50022011-10-25 17:10:12 +0000951 // Parse decltype-specifier
David Blaikie15a430a2011-12-04 05:04:18 +0000952 // tok == kw_decltype is just error recovery, it can only happen when SS
953 // isn't empty
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000954 if (Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)) {
David Blaikieafa155f2011-10-25 18:17:58 +0000955 if (SS.isNotEmpty())
956 Diag(SS.getBeginLoc(), diag::err_unexpected_scope_on_base_decltype)
957 << FixItHint::CreateRemoval(SS.getRange());
David Blaikie1cd50022011-10-25 17:10:12 +0000958 // Fake up a Declarator to use with ActOnTypeName.
959 DeclSpec DS(AttrFactory);
960
David Blaikie7491e732011-12-08 04:53:15 +0000961 EndLocation = ParseDecltypeSpecifier(DS);
David Blaikie1cd50022011-10-25 17:10:12 +0000962
963 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
964 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
965 }
966
Douglas Gregord54dfb82009-02-25 23:52:28 +0000967 // Check whether we have a template-id that names a type.
968 if (Tok.is(tok::annot_template_id)) {
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +0000969 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregor46c59612010-01-12 17:52:59 +0000970 if (TemplateId->Kind == TNK_Type_template ||
971 TemplateId->Kind == TNK_Dependent_template_name) {
Douglas Gregore7c20652011-03-02 00:47:37 +0000972 AnnotateTemplateIdTokenAsType();
Douglas Gregord54dfb82009-02-25 23:52:28 +0000973
974 assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
John McCallba7bf592010-08-24 05:47:05 +0000975 ParsedType Type = getTypeAnnotation(Tok);
Douglas Gregord54dfb82009-02-25 23:52:28 +0000976 EndLocation = Tok.getAnnotationEndLoc();
977 ConsumeToken();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000978
979 if (Type)
980 return Type;
981 return true;
Douglas Gregord54dfb82009-02-25 23:52:28 +0000982 }
983
984 // Fall through to produce an error below.
985 }
986
Douglas Gregor831c93f2008-11-05 20:51:48 +0000987 if (Tok.isNot(tok::identifier)) {
Chris Lattner6d29c102008-11-18 07:48:38 +0000988 Diag(Tok, diag::err_expected_class_name);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000989 return true;
Douglas Gregor831c93f2008-11-05 20:51:48 +0000990 }
991
Douglas Gregor18473f32010-01-12 21:28:44 +0000992 IdentifierInfo *Id = Tok.getIdentifierInfo();
993 SourceLocation IdLoc = ConsumeToken();
994
995 if (Tok.is(tok::less)) {
996 // It looks the user intended to write a template-id here, but the
997 // template-name was wrong. Try to fix that.
998 TemplateNameKind TNK = TNK_Type_template;
999 TemplateTy Template;
Douglas Gregor0be31a22010-07-02 17:43:08 +00001000 if (!Actions.DiagnoseUnknownTemplateName(*Id, IdLoc, getCurScope(),
Douglas Gregore7c20652011-03-02 00:47:37 +00001001 &SS, Template, TNK)) {
Douglas Gregor18473f32010-01-12 21:28:44 +00001002 Diag(IdLoc, diag::err_unknown_template_name)
1003 << Id;
1004 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001005
Serge Pavlovb716b3c2013-08-10 05:54:47 +00001006 if (!Template) {
1007 TemplateArgList TemplateArgs;
1008 SourceLocation LAngleLoc, RAngleLoc;
David Blaikiee20506d2016-01-15 23:43:28 +00001009 ParseTemplateIdAfterTemplateName(nullptr, IdLoc, SS, true, LAngleLoc,
1010 TemplateArgs, RAngleLoc);
Douglas Gregor18473f32010-01-12 21:28:44 +00001011 return true;
Serge Pavlovb716b3c2013-08-10 05:54:47 +00001012 }
Douglas Gregor18473f32010-01-12 21:28:44 +00001013
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001014 // Form the template name
Douglas Gregor18473f32010-01-12 21:28:44 +00001015 UnqualifiedId TemplateName;
1016 TemplateName.setIdentifier(Id, IdLoc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001017
Douglas Gregor18473f32010-01-12 21:28:44 +00001018 // Parse the full template-id, then turn it into a type.
Abramo Bagnara7945c982012-01-27 09:46:47 +00001019 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
1020 TemplateName, true))
Douglas Gregor18473f32010-01-12 21:28:44 +00001021 return true;
1022 if (TNK == TNK_Dependent_template_name)
Douglas Gregore7c20652011-03-02 00:47:37 +00001023 AnnotateTemplateIdTokenAsType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001024
Douglas Gregor18473f32010-01-12 21:28:44 +00001025 // If we didn't end up with a typename token, there's nothing more we
1026 // can do.
1027 if (Tok.isNot(tok::annot_typename))
1028 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001029
Douglas Gregor18473f32010-01-12 21:28:44 +00001030 // Retrieve the type from the annotation token, consume that token, and
1031 // return.
1032 EndLocation = Tok.getAnnotationEndLoc();
John McCallba7bf592010-08-24 05:47:05 +00001033 ParsedType Type = getTypeAnnotation(Tok);
Douglas Gregor18473f32010-01-12 21:28:44 +00001034 ConsumeToken();
1035 return Type;
1036 }
1037
Douglas Gregor831c93f2008-11-05 20:51:48 +00001038 // We have an identifier; check whether it is actually a type.
Craig Topper161e4db2014-05-21 06:02:52 +00001039 IdentifierInfo *CorrectedII = nullptr;
David Blaikieefdccaa2016-01-15 23:43:34 +00001040 ParsedType Type =
1041 Actions.getTypeName(*Id, IdLoc, getCurScope(), &SS, true, false, nullptr,
1042 /*IsCtorOrDtorName=*/false,
1043 /*NonTrivialTypeSourceInfo=*/true, &CorrectedII);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001044 if (!Type) {
Douglas Gregorfe17d252010-02-16 19:09:40 +00001045 Diag(IdLoc, diag::err_expected_class_name);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001046 return true;
Douglas Gregor831c93f2008-11-05 20:51:48 +00001047 }
1048
1049 // Consume the identifier.
Douglas Gregor18473f32010-01-12 21:28:44 +00001050 EndLocation = IdLoc;
Nick Lewycky19b9f952010-07-26 16:56:01 +00001051
1052 // Fake up a Declarator to use with ActOnTypeName.
John McCall084e83d2011-03-24 11:26:52 +00001053 DeclSpec DS(AttrFactory);
Nick Lewycky19b9f952010-07-26 16:56:01 +00001054 DS.SetRangeStart(IdLoc);
1055 DS.SetRangeEnd(EndLocation);
Douglas Gregore7c20652011-03-02 00:47:37 +00001056 DS.getTypeSpecScope() = SS;
Nick Lewycky19b9f952010-07-26 16:56:01 +00001057
Craig Topper161e4db2014-05-21 06:02:52 +00001058 const char *PrevSpec = nullptr;
Nick Lewycky19b9f952010-07-26 16:56:01 +00001059 unsigned DiagID;
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001060 DS.SetTypeSpecType(TST_typename, IdLoc, PrevSpec, DiagID, Type,
1061 Actions.getASTContext().getPrintingPolicy());
Nick Lewycky19b9f952010-07-26 16:56:01 +00001062
1063 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1064 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
Douglas Gregor831c93f2008-11-05 20:51:48 +00001065}
1066
John McCall8d32c052012-05-22 21:28:12 +00001067void Parser::ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001068 while (Tok.isOneOf(tok::kw___single_inheritance,
1069 tok::kw___multiple_inheritance,
1070 tok::kw___virtual_inheritance)) {
John McCall8d32c052012-05-22 21:28:12 +00001071 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
1072 SourceLocation AttrNameLoc = ConsumeToken();
Craig Topper161e4db2014-05-21 06:02:52 +00001073 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
Aaron Ballman8edb5c22013-12-18 23:44:18 +00001074 AttributeList::AS_Keyword);
John McCall8d32c052012-05-22 21:28:12 +00001075 }
1076}
1077
Richard Smith369b9f92012-06-25 21:37:02 +00001078/// Determine whether the following tokens are valid after a type-specifier
1079/// which could be a standalone declaration. This will conservatively return
1080/// true if there's any doubt, and is appropriate for insert-';' fixits.
Richard Smith200f47c2012-07-02 19:14:01 +00001081bool Parser::isValidAfterTypeSpecifier(bool CouldBeBitfield) {
Richard Smith369b9f92012-06-25 21:37:02 +00001082 // This switch enumerates the valid "follow" set for type-specifiers.
1083 switch (Tok.getKind()) {
1084 default: break;
1085 case tok::semi: // struct foo {...} ;
1086 case tok::star: // struct foo {...} * P;
1087 case tok::amp: // struct foo {...} & R = ...
Richard Smith1ac67d12013-01-19 03:48:05 +00001088 case tok::ampamp: // struct foo {...} && R = ...
Richard Smith369b9f92012-06-25 21:37:02 +00001089 case tok::identifier: // struct foo {...} V ;
1090 case tok::r_paren: //(struct foo {...} ) {4}
1091 case tok::annot_cxxscope: // struct foo {...} a:: b;
1092 case tok::annot_typename: // struct foo {...} a ::b;
1093 case tok::annot_template_id: // struct foo {...} a<int> ::b;
1094 case tok::l_paren: // struct foo {...} ( x);
1095 case tok::comma: // __builtin_offsetof(struct foo{...} ,
Richard Smith1ac67d12013-01-19 03:48:05 +00001096 case tok::kw_operator: // struct foo operator ++() {...}
Alp Tokerd3f79c52013-11-24 20:24:54 +00001097 case tok::kw___declspec: // struct foo {...} __declspec(...)
Richard Smith843f18f2014-08-13 02:13:15 +00001098 case tok::l_square: // void f(struct f [ 3])
1099 case tok::ellipsis: // void f(struct f ... [Ns])
Abramo Bagnara152eb392014-08-16 08:29:27 +00001100 // FIXME: we should emit semantic diagnostic when declaration
1101 // attribute is in type attribute position.
1102 case tok::kw___attribute: // struct foo __attribute__((used)) x;
Richard Smith369b9f92012-06-25 21:37:02 +00001103 return true;
Richard Smith200f47c2012-07-02 19:14:01 +00001104 case tok::colon:
1105 return CouldBeBitfield; // enum E { ... } : 2;
Reid Klecknercfa91552016-03-21 16:08:49 +00001106 // Microsoft compatibility
1107 case tok::kw___cdecl: // struct foo {...} __cdecl x;
1108 case tok::kw___fastcall: // struct foo {...} __fastcall x;
1109 case tok::kw___stdcall: // struct foo {...} __stdcall x;
1110 case tok::kw___thiscall: // struct foo {...} __thiscall x;
1111 case tok::kw___vectorcall: // struct foo {...} __vectorcall x;
1112 // We will diagnose these calling-convention specifiers on non-function
1113 // declarations later, so claim they are valid after a type specifier.
1114 return getLangOpts().MicrosoftExt;
Richard Smith369b9f92012-06-25 21:37:02 +00001115 // Type qualifiers
1116 case tok::kw_const: // struct foo {...} const x;
1117 case tok::kw_volatile: // struct foo {...} volatile x;
1118 case tok::kw_restrict: // struct foo {...} restrict x;
Richard Smith843f18f2014-08-13 02:13:15 +00001119 case tok::kw__Atomic: // struct foo {...} _Atomic x;
Nico Rieck3e1ee832014-12-04 23:30:25 +00001120 case tok::kw___unaligned: // struct foo {...} __unaligned *x;
Richard Smith1ac67d12013-01-19 03:48:05 +00001121 // Function specifiers
1122 // Note, no 'explicit'. An explicit function must be either a conversion
1123 // operator or a constructor. Either way, it can't have a return type.
1124 case tok::kw_inline: // struct foo inline f();
1125 case tok::kw_virtual: // struct foo virtual f();
1126 case tok::kw_friend: // struct foo friend f();
Richard Smith369b9f92012-06-25 21:37:02 +00001127 // Storage-class specifiers
1128 case tok::kw_static: // struct foo {...} static x;
1129 case tok::kw_extern: // struct foo {...} extern x;
1130 case tok::kw_typedef: // struct foo {...} typedef x;
1131 case tok::kw_register: // struct foo {...} register x;
1132 case tok::kw_auto: // struct foo {...} auto x;
1133 case tok::kw_mutable: // struct foo {...} mutable x;
Richard Smith1ac67d12013-01-19 03:48:05 +00001134 case tok::kw_thread_local: // struct foo {...} thread_local x;
Richard Smith369b9f92012-06-25 21:37:02 +00001135 case tok::kw_constexpr: // struct foo {...} constexpr x;
1136 // As shown above, type qualifiers and storage class specifiers absolutely
1137 // can occur after class specifiers according to the grammar. However,
1138 // almost no one actually writes code like this. If we see one of these,
1139 // it is much more likely that someone missed a semi colon and the
1140 // type/storage class specifier we're seeing is part of the *next*
1141 // intended declaration, as in:
1142 //
1143 // struct foo { ... }
1144 // typedef int X;
1145 //
1146 // We'd really like to emit a missing semicolon error instead of emitting
1147 // an error on the 'int' saying that you can't have two type specifiers in
1148 // the same declaration of X. Because of this, we look ahead past this
1149 // token to see if it's a type specifier. If so, we know the code is
1150 // otherwise invalid, so we can produce the expected semi error.
1151 if (!isKnownToBeTypeSpecifier(NextToken()))
1152 return true;
1153 break;
1154 case tok::r_brace: // struct bar { struct foo {...} }
1155 // Missing ';' at end of struct is accepted as an extension in C mode.
1156 if (!getLangOpts().CPlusPlus)
1157 return true;
1158 break;
Richard Smith52c5b872013-01-29 04:13:32 +00001159 case tok::greater:
1160 // template<class T = class X>
1161 return getLangOpts().CPlusPlus;
Richard Smith369b9f92012-06-25 21:37:02 +00001162 }
1163 return false;
1164}
1165
Douglas Gregor556877c2008-04-13 21:30:24 +00001166/// ParseClassSpecifier - Parse a C++ class-specifier [C++ class] or
1167/// elaborated-type-specifier [C++ dcl.type.elab]; we can't tell which
1168/// until we reach the start of a definition or see a token that
Richard Smithc5b05522012-03-12 07:56:15 +00001169/// cannot start a definition.
Douglas Gregor556877c2008-04-13 21:30:24 +00001170///
1171/// class-specifier: [C++ class]
1172/// class-head '{' member-specification[opt] '}'
1173/// class-head '{' member-specification[opt] '}' attributes[opt]
1174/// class-head:
1175/// class-key identifier[opt] base-clause[opt]
1176/// class-key nested-name-specifier identifier base-clause[opt]
1177/// class-key nested-name-specifier[opt] simple-template-id
1178/// base-clause[opt]
1179/// [GNU] class-key attributes[opt] identifier[opt] base-clause[opt]
Mike Stump11289f42009-09-09 15:08:12 +00001180/// [GNU] class-key attributes[opt] nested-name-specifier
Douglas Gregor556877c2008-04-13 21:30:24 +00001181/// identifier base-clause[opt]
Mike Stump11289f42009-09-09 15:08:12 +00001182/// [GNU] class-key attributes[opt] nested-name-specifier[opt]
Douglas Gregor556877c2008-04-13 21:30:24 +00001183/// simple-template-id base-clause[opt]
1184/// class-key:
1185/// 'class'
1186/// 'struct'
1187/// 'union'
1188///
1189/// elaborated-type-specifier: [C++ dcl.type.elab]
Mike Stump11289f42009-09-09 15:08:12 +00001190/// class-key ::[opt] nested-name-specifier[opt] identifier
1191/// class-key ::[opt] nested-name-specifier[opt] 'template'[opt]
1192/// simple-template-id
Douglas Gregor556877c2008-04-13 21:30:24 +00001193///
1194/// Note that the C++ class-specifier and elaborated-type-specifier,
1195/// together, subsume the C99 struct-or-union-specifier:
1196///
1197/// struct-or-union-specifier: [C99 6.7.2.1]
1198/// struct-or-union identifier[opt] '{' struct-contents '}'
1199/// struct-or-union identifier
1200/// [GNU] struct-or-union attributes[opt] identifier[opt] '{' struct-contents
1201/// '}' attributes[opt]
1202/// [GNU] struct-or-union attributes[opt] identifier
1203/// struct-or-union:
1204/// 'struct'
1205/// 'union'
Chris Lattnerffaa0e62009-04-12 21:49:30 +00001206void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind,
1207 SourceLocation StartLoc, DeclSpec &DS,
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001208 const ParsedTemplateInfo &TemplateInfo,
Douglas Gregordf593fb2011-11-07 17:33:42 +00001209 AccessSpecifier AS,
Michael Han9407e502012-11-26 22:54:45 +00001210 bool EnteringContext, DeclSpecContext DSC,
Bill Wendling44426052012-12-20 19:22:21 +00001211 ParsedAttributesWithRange &Attributes) {
Joao Matose9a3ed42012-08-31 22:18:20 +00001212 DeclSpec::TST TagType;
1213 if (TagTokKind == tok::kw_struct)
1214 TagType = DeclSpec::TST_struct;
1215 else if (TagTokKind == tok::kw___interface)
1216 TagType = DeclSpec::TST_interface;
1217 else if (TagTokKind == tok::kw_class)
1218 TagType = DeclSpec::TST_class;
1219 else {
Chris Lattnerffaa0e62009-04-12 21:49:30 +00001220 assert(TagTokKind == tok::kw_union && "Not a class specifier");
1221 TagType = DeclSpec::TST_union;
1222 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001223
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00001224 if (Tok.is(tok::code_completion)) {
1225 // Code completion for a struct, class, or union name.
Douglas Gregor0be31a22010-07-02 17:43:08 +00001226 Actions.CodeCompleteTag(getCurScope(), TagType);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001227 return cutOffParsing();
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00001228 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001229
Chandler Carruth2d69ec72010-06-28 08:39:25 +00001230 // C++03 [temp.explicit] 14.7.2/8:
1231 // The usual access checking rules do not apply to names used to specify
1232 // explicit instantiations.
1233 //
1234 // As an extension we do not perform access checking on the names used to
1235 // specify explicit specializations either. This is important to allow
1236 // specializing traits classes for private types.
John McCall6347b682012-05-07 06:16:58 +00001237 //
1238 // Note that we don't suppress if this turns out to be an elaborated
1239 // type specifier.
1240 bool shouldDelayDiagsInTag =
1241 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
1242 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
1243 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
Chandler Carruth2d69ec72010-06-28 08:39:25 +00001244
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001245 ParsedAttributesWithRange attrs(AttrFactory);
Douglas Gregor556877c2008-04-13 21:30:24 +00001246 // If attributes exist after tag, parse them.
Richard Smith37a45dd2013-10-24 01:21:09 +00001247 MaybeParseGNUAttributes(attrs);
Aaron Ballman068aa512015-05-20 20:58:33 +00001248 MaybeParseMicrosoftDeclSpecs(attrs);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001249
John McCall8d32c052012-05-22 21:28:12 +00001250 // Parse inheritance specifiers.
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001251 if (Tok.isOneOf(tok::kw___single_inheritance,
1252 tok::kw___multiple_inheritance,
1253 tok::kw___virtual_inheritance))
Richard Smith37a45dd2013-10-24 01:21:09 +00001254 ParseMicrosoftInheritanceClassAttributes(attrs);
John McCall8d32c052012-05-22 21:28:12 +00001255
Alexis Hunt96d5c762009-11-21 08:43:09 +00001256 // If C++0x attributes exist here, parse them.
1257 // FIXME: Are we consistent with the ordering of parsing of different
1258 // styles of attributes?
Richard Smith89645bc2013-01-02 12:01:23 +00001259 MaybeParseCXX11Attributes(attrs);
Mike Stump11289f42009-09-09 15:08:12 +00001260
Michael Han309af292013-01-07 16:57:11 +00001261 // Source location used by FIXIT to insert misplaced
1262 // C++11 attributes
1263 SourceLocation AttrFixitLoc = Tok.getLocation();
1264
Nico Weber7c3c5be2014-09-23 04:09:56 +00001265 if (TagType == DeclSpec::TST_struct &&
David Majnemer86330af2014-12-29 02:14:26 +00001266 Tok.isNot(tok::identifier) &&
1267 !Tok.isAnnotation() &&
Nico Weber7c3c5be2014-09-23 04:09:56 +00001268 Tok.getIdentifierInfo() &&
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001269 Tok.isOneOf(tok::kw___is_abstract,
1270 tok::kw___is_arithmetic,
1271 tok::kw___is_array,
David Majnemerb3d96882016-05-23 17:21:55 +00001272 tok::kw___is_assignable,
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001273 tok::kw___is_base_of,
1274 tok::kw___is_class,
1275 tok::kw___is_complete_type,
1276 tok::kw___is_compound,
1277 tok::kw___is_const,
1278 tok::kw___is_constructible,
1279 tok::kw___is_convertible,
1280 tok::kw___is_convertible_to,
1281 tok::kw___is_destructible,
1282 tok::kw___is_empty,
1283 tok::kw___is_enum,
1284 tok::kw___is_floating_point,
1285 tok::kw___is_final,
1286 tok::kw___is_function,
1287 tok::kw___is_fundamental,
1288 tok::kw___is_integral,
1289 tok::kw___is_interface_class,
1290 tok::kw___is_literal,
1291 tok::kw___is_lvalue_expr,
1292 tok::kw___is_lvalue_reference,
1293 tok::kw___is_member_function_pointer,
1294 tok::kw___is_member_object_pointer,
1295 tok::kw___is_member_pointer,
1296 tok::kw___is_nothrow_assignable,
1297 tok::kw___is_nothrow_constructible,
1298 tok::kw___is_nothrow_destructible,
1299 tok::kw___is_object,
1300 tok::kw___is_pod,
1301 tok::kw___is_pointer,
1302 tok::kw___is_polymorphic,
1303 tok::kw___is_reference,
1304 tok::kw___is_rvalue_expr,
1305 tok::kw___is_rvalue_reference,
1306 tok::kw___is_same,
1307 tok::kw___is_scalar,
1308 tok::kw___is_sealed,
1309 tok::kw___is_signed,
1310 tok::kw___is_standard_layout,
1311 tok::kw___is_trivial,
1312 tok::kw___is_trivially_assignable,
1313 tok::kw___is_trivially_constructible,
1314 tok::kw___is_trivially_copyable,
1315 tok::kw___is_union,
1316 tok::kw___is_unsigned,
1317 tok::kw___is_void,
1318 tok::kw___is_volatile))
Nico Weber7c3c5be2014-09-23 04:09:56 +00001319 // GNU libstdc++ 4.2 and libc++ use certain intrinsic names as the
1320 // name of struct templates, but some are keywords in GCC >= 4.3
1321 // and Clang. Therefore, when we see the token sequence "struct
1322 // X", make X into a normal identifier rather than a keyword, to
1323 // allow libstdc++ 4.2 and libc++ to work properly.
1324 TryKeywordIdentFallback(true);
Mike Stump11289f42009-09-09 15:08:12 +00001325
David Majnemer51fd8a02015-07-22 23:46:18 +00001326 struct PreserveAtomicIdentifierInfoRAII {
1327 PreserveAtomicIdentifierInfoRAII(Token &Tok, bool Enabled)
1328 : AtomicII(nullptr) {
1329 if (!Enabled)
1330 return;
1331 assert(Tok.is(tok::kw__Atomic));
1332 AtomicII = Tok.getIdentifierInfo();
1333 AtomicII->revertTokenIDToIdentifier();
1334 Tok.setKind(tok::identifier);
1335 }
1336 ~PreserveAtomicIdentifierInfoRAII() {
1337 if (!AtomicII)
1338 return;
1339 AtomicII->revertIdentifierToTokenID(tok::kw__Atomic);
1340 }
1341 IdentifierInfo *AtomicII;
1342 };
1343
1344 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
1345 // implementation for VS2013 uses _Atomic as an identifier for one of the
1346 // classes in <atomic>. When we are parsing 'struct _Atomic', don't consider
1347 // '_Atomic' to be a keyword. We are careful to undo this so that clang can
1348 // use '_Atomic' in its own header files.
1349 bool ShouldChangeAtomicToIdentifier = getLangOpts().MSVCCompat &&
1350 Tok.is(tok::kw__Atomic) &&
1351 TagType == DeclSpec::TST_struct;
1352 PreserveAtomicIdentifierInfoRAII AtomicTokenGuard(
1353 Tok, ShouldChangeAtomicToIdentifier);
1354
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001355 // Parse the (optional) nested-name-specifier.
John McCall9dab4e62009-12-12 11:40:51 +00001356 CXXScopeSpec &SS = DS.getTypeSpecScope();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001357 if (getLangOpts().CPlusPlus) {
Serge Pavlov458ea762014-07-16 05:16:52 +00001358 // "FOO : BAR" is not a potential typo for "FOO::BAR". In this context it
1359 // is a base-specifier-list.
Chris Lattnerd5c1c9d2009-12-10 00:32:41 +00001360 ColonProtectionRAIIObject X(*this);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001361
Nico Webercfaa4cd2015-02-15 07:26:13 +00001362 CXXScopeSpec Spec;
1363 bool HasValidSpec = true;
David Blaikieefdccaa2016-01-15 23:43:34 +00001364 if (ParseOptionalCXXScopeSpecifier(Spec, nullptr, EnteringContext)) {
John McCall413021a2010-07-30 06:26:29 +00001365 DS.SetTypeSpecError();
Nico Webercfaa4cd2015-02-15 07:26:13 +00001366 HasValidSpec = false;
1367 }
1368 if (Spec.isSet())
1369 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::annot_template_id)) {
Alp Tokerec543272013-12-24 09:48:30 +00001370 Diag(Tok, diag::err_expected) << tok::identifier;
Nico Webercfaa4cd2015-02-15 07:26:13 +00001371 HasValidSpec = false;
1372 }
1373 if (HasValidSpec)
1374 SS = Spec;
Chris Lattnerd5c1c9d2009-12-10 00:32:41 +00001375 }
Douglas Gregor67a65642009-02-17 23:15:12 +00001376
Douglas Gregor916462b2009-10-30 21:46:58 +00001377 TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
1378
Douglas Gregor67a65642009-02-17 23:15:12 +00001379 // Parse the (optional) class name or simple-template-id.
Craig Topper161e4db2014-05-21 06:02:52 +00001380 IdentifierInfo *Name = nullptr;
Douglas Gregor556877c2008-04-13 21:30:24 +00001381 SourceLocation NameLoc;
Craig Topper161e4db2014-05-21 06:02:52 +00001382 TemplateIdAnnotation *TemplateId = nullptr;
Douglas Gregor556877c2008-04-13 21:30:24 +00001383 if (Tok.is(tok::identifier)) {
1384 Name = Tok.getIdentifierInfo();
1385 NameLoc = ConsumeToken();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001386
David Blaikiebbafb8a2012-03-11 07:00:24 +00001387 if (Tok.is(tok::less) && getLangOpts().CPlusPlus) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001388 // The name was supposed to refer to a template, but didn't.
Douglas Gregor916462b2009-10-30 21:46:58 +00001389 // Eat the template argument list and try to continue parsing this as
1390 // a class (or template thereof).
1391 TemplateArgList TemplateArgs;
Douglas Gregor916462b2009-10-30 21:46:58 +00001392 SourceLocation LAngleLoc, RAngleLoc;
David Blaikiee20506d2016-01-15 23:43:28 +00001393 if (ParseTemplateIdAfterTemplateName(
1394 nullptr, NameLoc, SS, true, LAngleLoc, TemplateArgs, RAngleLoc)) {
Douglas Gregor916462b2009-10-30 21:46:58 +00001395 // We couldn't parse the template argument list at all, so don't
1396 // try to give any location information for the list.
1397 LAngleLoc = RAngleLoc = SourceLocation();
1398 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001399
Douglas Gregor916462b2009-10-30 21:46:58 +00001400 Diag(NameLoc, diag::err_explicit_spec_non_template)
Alp Toker01d65e12014-01-06 12:54:41 +00001401 << (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
1402 << TagTokKind << Name << SourceRange(LAngleLoc, RAngleLoc);
Joao Matose9a3ed42012-08-31 22:18:20 +00001403
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001404 // Strip off the last template parameter list if it was empty, since
Douglas Gregor1d0015f2009-10-30 22:09:44 +00001405 // we've removed its template argument list.
1406 if (TemplateParams && TemplateInfo.LastParameterListWasEmpty) {
Hubert Tong97b06632016-04-13 18:41:03 +00001407 if (TemplateParams->size() > 1) {
Douglas Gregor1d0015f2009-10-30 22:09:44 +00001408 TemplateParams->pop_back();
1409 } else {
Craig Topper161e4db2014-05-21 06:02:52 +00001410 TemplateParams = nullptr;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001411 const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind
Douglas Gregor1d0015f2009-10-30 22:09:44 +00001412 = ParsedTemplateInfo::NonTemplate;
1413 }
1414 } else if (TemplateInfo.Kind
1415 == ParsedTemplateInfo::ExplicitInstantiation) {
1416 // Pretend this is just a forward declaration.
Craig Topper161e4db2014-05-21 06:02:52 +00001417 TemplateParams = nullptr;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001418 const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind
Douglas Gregor916462b2009-10-30 21:46:58 +00001419 = ParsedTemplateInfo::NonTemplate;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001420 const_cast<ParsedTemplateInfo&>(TemplateInfo).TemplateLoc
Douglas Gregor1d0015f2009-10-30 22:09:44 +00001421 = SourceLocation();
1422 const_cast<ParsedTemplateInfo&>(TemplateInfo).ExternLoc
1423 = SourceLocation();
Douglas Gregor916462b2009-10-30 21:46:58 +00001424 }
Douglas Gregor916462b2009-10-30 21:46:58 +00001425 }
Douglas Gregor7f741122009-02-25 19:37:18 +00001426 } else if (Tok.is(tok::annot_template_id)) {
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00001427 TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregor7f741122009-02-25 19:37:18 +00001428 NameLoc = ConsumeToken();
Douglas Gregor67a65642009-02-17 23:15:12 +00001429
Douglas Gregore7c20652011-03-02 00:47:37 +00001430 if (TemplateId->Kind != TNK_Type_template &&
1431 TemplateId->Kind != TNK_Dependent_template_name) {
Douglas Gregor7f741122009-02-25 19:37:18 +00001432 // The template-name in the simple-template-id refers to
1433 // something other than a class template. Give an appropriate
1434 // error message and skip to the ';'.
1435 SourceRange Range(NameLoc);
1436 if (SS.isNotEmpty())
1437 Range.setBegin(SS.getBeginLoc());
Douglas Gregor67a65642009-02-17 23:15:12 +00001438
Richard Smith72bfbd82013-12-04 00:28:23 +00001439 // FIXME: Name may be null here.
Douglas Gregor7f741122009-02-25 19:37:18 +00001440 Diag(TemplateId->LAngleLoc, diag::err_template_spec_syntax_non_template)
Richard Trieu30f93852013-06-19 22:25:01 +00001441 << TemplateId->Name << static_cast<int>(TemplateId->Kind) << Range;
Mike Stump11289f42009-09-09 15:08:12 +00001442
Douglas Gregor7f741122009-02-25 19:37:18 +00001443 DS.SetTypeSpecError();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001444 SkipUntil(tok::semi, StopBeforeMatch);
Douglas Gregor7f741122009-02-25 19:37:18 +00001445 return;
Douglas Gregor67a65642009-02-17 23:15:12 +00001446 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001447 }
1448
Richard Smithbfdb1082012-03-12 08:56:40 +00001449 // There are four options here.
1450 // - If we are in a trailing return type, this is always just a reference,
1451 // and we must not try to parse a definition. For instance,
1452 // [] () -> struct S { };
1453 // does not define a type.
1454 // - If we have 'struct foo {...', 'struct foo :...',
1455 // 'struct foo final :' or 'struct foo final {', then this is a definition.
1456 // - If we have 'struct foo;', then this is either a forward declaration
1457 // or a friend declaration, which have to be treated differently.
1458 // - Otherwise we have something like 'struct foo xyz', a reference.
Michael Han9407e502012-11-26 22:54:45 +00001459 //
1460 // We also detect these erroneous cases to provide better diagnostic for
1461 // C++11 attributes parsing.
1462 // - attributes follow class name:
1463 // struct foo [[]] {};
1464 // - attributes appear before or after 'final':
1465 // struct foo [[]] final [[]] {};
1466 //
Richard Smithc5b05522012-03-12 07:56:15 +00001467 // However, in type-specifier-seq's, things look like declarations but are
1468 // just references, e.g.
1469 // new struct s;
Sebastian Redl2b372722010-02-03 21:21:43 +00001470 // or
Richard Smithc5b05522012-03-12 07:56:15 +00001471 // &T::operator struct s;
Richard Smith649c7b062014-01-08 00:56:48 +00001472 // For these, DSC is DSC_type_specifier or DSC_alias_declaration.
Michael Han9407e502012-11-26 22:54:45 +00001473
1474 // If there are attributes after class name, parse them.
Richard Smith89645bc2013-01-02 12:01:23 +00001475 MaybeParseCXX11Attributes(Attributes);
Michael Han9407e502012-11-26 22:54:45 +00001476
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001477 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
John McCallfaf5fb42010-08-26 23:41:50 +00001478 Sema::TagUseKind TUK;
Richard Smithbfdb1082012-03-12 08:56:40 +00001479 if (DSC == DSC_trailing)
1480 TUK = Sema::TUK_Reference;
1481 else if (Tok.is(tok::l_brace) ||
1482 (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
Richard Smith89645bc2013-01-02 12:01:23 +00001483 (isCXX11FinalKeyword() &&
David Blaikie9933a5a2012-03-12 15:39:49 +00001484 (NextToken().is(tok::l_brace) || NextToken().is(tok::colon)))) {
Douglas Gregor3dad8422009-09-26 06:47:28 +00001485 if (DS.isFriendSpecified()) {
1486 // C++ [class.friend]p2:
1487 // A class shall not be defined in a friend declaration.
Richard Smith0f8ee222012-01-10 01:33:14 +00001488 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
Douglas Gregor3dad8422009-09-26 06:47:28 +00001489 << SourceRange(DS.getFriendSpecLoc());
1490
1491 // Skip everything up to the semicolon, so that this looks like a proper
1492 // friend class (or template thereof) declaration.
Alexey Bataevee6507d2013-11-18 08:17:37 +00001493 SkipUntil(tok::semi, StopBeforeMatch);
John McCallfaf5fb42010-08-26 23:41:50 +00001494 TUK = Sema::TUK_Friend;
Douglas Gregor3dad8422009-09-26 06:47:28 +00001495 } else {
1496 // Okay, this is a class definition.
John McCallfaf5fb42010-08-26 23:41:50 +00001497 TUK = Sema::TUK_Definition;
Douglas Gregor3dad8422009-09-26 06:47:28 +00001498 }
Richard Smith434516c2013-02-22 06:46:23 +00001499 } else if (isCXX11FinalKeyword() && (NextToken().is(tok::l_square) ||
1500 NextToken().is(tok::kw_alignas))) {
Michael Han9407e502012-11-26 22:54:45 +00001501 // We can't tell if this is a definition or reference
1502 // until we skipped the 'final' and C++11 attribute specifiers.
1503 TentativeParsingAction PA(*this);
1504
1505 // Skip the 'final' keyword.
1506 ConsumeToken();
1507
1508 // Skip C++11 attribute specifiers.
1509 while (true) {
1510 if (Tok.is(tok::l_square) && NextToken().is(tok::l_square)) {
1511 ConsumeBracket();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001512 if (!SkipUntil(tok::r_square, StopAtSemi))
Michael Han9407e502012-11-26 22:54:45 +00001513 break;
Richard Smith434516c2013-02-22 06:46:23 +00001514 } else if (Tok.is(tok::kw_alignas) && NextToken().is(tok::l_paren)) {
Michael Han9407e502012-11-26 22:54:45 +00001515 ConsumeToken();
1516 ConsumeParen();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001517 if (!SkipUntil(tok::r_paren, StopAtSemi))
Michael Han9407e502012-11-26 22:54:45 +00001518 break;
1519 } else {
1520 break;
1521 }
1522 }
1523
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001524 if (Tok.isOneOf(tok::l_brace, tok::colon))
Michael Han9407e502012-11-26 22:54:45 +00001525 TUK = Sema::TUK_Definition;
1526 else
1527 TUK = Sema::TUK_Reference;
1528
1529 PA.Revert();
Richard Smith649c7b062014-01-08 00:56:48 +00001530 } else if (!isTypeSpecifier(DSC) &&
Richard Smith369b9f92012-06-25 21:37:02 +00001531 (Tok.is(tok::semi) ||
Richard Smith200f47c2012-07-02 19:14:01 +00001532 (Tok.isAtStartOfLine() && !isValidAfterTypeSpecifier(false)))) {
John McCallfaf5fb42010-08-26 23:41:50 +00001533 TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
Joao Matose9a3ed42012-08-31 22:18:20 +00001534 if (Tok.isNot(tok::semi)) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001535 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
Joao Matose9a3ed42012-08-31 22:18:20 +00001536 // A semicolon was missing after this declaration. Diagnose and recover.
Alp Toker383d2c42014-01-01 03:08:43 +00001537 ExpectAndConsume(tok::semi, diag::err_expected_after,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001538 DeclSpec::getSpecifierName(TagType, PPol));
Joao Matose9a3ed42012-08-31 22:18:20 +00001539 PP.EnterToken(Tok);
1540 Tok.setKind(tok::semi);
1541 }
Richard Smith369b9f92012-06-25 21:37:02 +00001542 } else
John McCallfaf5fb42010-08-26 23:41:50 +00001543 TUK = Sema::TUK_Reference;
Douglas Gregor556877c2008-04-13 21:30:24 +00001544
Michael Han9407e502012-11-26 22:54:45 +00001545 // Forbid misplaced attributes. In cases of a reference, we pass attributes
1546 // to caller to handle.
Michael Han309af292013-01-07 16:57:11 +00001547 if (TUK != Sema::TUK_Reference) {
1548 // If this is not a reference, then the only possible
1549 // valid place for C++11 attributes to appear here
1550 // is between class-key and class-name. If there are
1551 // any attributes after class-name, we try a fixit to move
1552 // them to the right place.
1553 SourceRange AttrRange = Attributes.Range;
1554 if (AttrRange.isValid()) {
1555 Diag(AttrRange.getBegin(), diag::err_attributes_not_allowed)
1556 << AttrRange
1557 << FixItHint::CreateInsertionFromRange(AttrFixitLoc,
1558 CharSourceRange(AttrRange, true))
1559 << FixItHint::CreateRemoval(AttrRange);
1560
1561 // Recover by adding misplaced attributes to the attribute list
1562 // of the class so they can be applied on the class later.
1563 attrs.takeAllFrom(Attributes);
1564 }
1565 }
Michael Han9407e502012-11-26 22:54:45 +00001566
John McCall6347b682012-05-07 06:16:58 +00001567 // If this is an elaborated type specifier, and we delayed
1568 // diagnostics before, just merge them into the current pool.
1569 if (shouldDelayDiagsInTag) {
1570 diagsFromTag.done();
1571 if (TUK == Sema::TUK_Reference)
1572 diagsFromTag.redelay();
1573 }
1574
John McCall413021a2010-07-30 06:26:29 +00001575 if (!Name && !TemplateId && (DS.getTypeSpecType() == DeclSpec::TST_error ||
John McCallfaf5fb42010-08-26 23:41:50 +00001576 TUK != Sema::TUK_Definition)) {
John McCall413021a2010-07-30 06:26:29 +00001577 if (DS.getTypeSpecType() != DeclSpec::TST_error) {
1578 // We have a declaration or reference to an anonymous class.
1579 Diag(StartLoc, diag::err_anon_type_definition)
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001580 << DeclSpec::getSpecifierName(TagType, Policy);
John McCall413021a2010-07-30 06:26:29 +00001581 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001582
David Majnemer3252fd02013-12-05 01:36:53 +00001583 // If we are parsing a definition and stop at a base-clause, continue on
1584 // until the semicolon. Continuing from the comma will just trick us into
1585 // thinking we are seeing a variable declaration.
1586 if (TUK == Sema::TUK_Definition && Tok.is(tok::colon))
1587 SkipUntil(tok::semi, StopBeforeMatch);
1588 else
1589 SkipUntil(tok::comma, StopAtSemi);
Douglas Gregor556877c2008-04-13 21:30:24 +00001590 return;
1591 }
1592
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001593 // Create the tag portion of the class or class template.
John McCall48871652010-08-21 09:40:31 +00001594 DeclResult TagOrTempResult = true; // invalid
1595 TypeResult TypeResult = true; // invalid
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001596
Douglas Gregord6ab8742009-05-28 23:31:59 +00001597 bool Owned = false;
Richard Smithd9ba2242015-05-07 03:54:19 +00001598 Sema::SkipBodyInfo SkipBody;
John McCall06f6fe8d2009-09-04 01:14:41 +00001599 if (TemplateId) {
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001600 // Explicit specialization, class template partial specialization,
1601 // or explicit instantiation.
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00001602 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregor7f741122009-02-25 19:37:18 +00001603 TemplateId->NumArgs);
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001604 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
John McCallfaf5fb42010-08-26 23:41:50 +00001605 TUK == Sema::TUK_Declaration) {
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001606 // This is an explicit instantiation of a class template.
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001607 ProhibitAttributes(attrs);
1608
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001609 TagOrTempResult
Douglas Gregor0be31a22010-07-02 17:43:08 +00001610 = Actions.ActOnExplicitInstantiation(getCurScope(),
Douglas Gregor43e75172009-09-04 06:33:52 +00001611 TemplateInfo.ExternLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001612 TemplateInfo.TemplateLoc,
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001613 TagType,
Mike Stump11289f42009-09-09 15:08:12 +00001614 StartLoc,
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001615 SS,
John McCall3e56fd42010-08-23 07:28:44 +00001616 TemplateId->Template,
Mike Stump11289f42009-09-09 15:08:12 +00001617 TemplateId->TemplateNameLoc,
1618 TemplateId->LAngleLoc,
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001619 TemplateArgsPtr,
Mike Stump11289f42009-09-09 15:08:12 +00001620 TemplateId->RAngleLoc,
John McCall53fa7142010-12-24 02:08:15 +00001621 attrs.getList());
John McCallb7c5c272010-04-14 00:24:33 +00001622
1623 // Friend template-ids are treated as references unless
1624 // they have template headers, in which case they're ill-formed
1625 // (FIXME: "template <class T> friend class A<T>::B<int>;").
1626 // We diagnose this error in ActOnClassTemplateSpecialization.
John McCallfaf5fb42010-08-26 23:41:50 +00001627 } else if (TUK == Sema::TUK_Reference ||
1628 (TUK == Sema::TUK_Friend &&
John McCallb7c5c272010-04-14 00:24:33 +00001629 TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate)) {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001630 ProhibitAttributes(attrs);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00001631 TypeResult = Actions.ActOnTagTemplateIdType(TUK, TagType, StartLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00001632 TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00001633 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00001634 TemplateId->Template,
1635 TemplateId->TemplateNameLoc,
1636 TemplateId->LAngleLoc,
1637 TemplateArgsPtr,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00001638 TemplateId->RAngleLoc);
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001639 } else {
1640 // This is an explicit specialization or a class template
1641 // partial specialization.
1642 TemplateParameterLists FakedParamLists;
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001643 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1644 // This looks like an explicit instantiation, because we have
1645 // something like
1646 //
1647 // template class Foo<X>
1648 //
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001649 // but it actually has a definition. Most likely, this was
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001650 // meant to be an explicit specialization, but the user forgot
1651 // the '<>' after 'template'.
Richard Smith003c5e12013-11-08 19:03:29 +00001652 // It this is friend declaration however, since it cannot have a
1653 // template header, it is most likely that the user meant to
1654 // remove the 'template' keyword.
Larisse Voufob9bbaba2013-06-22 13:56:11 +00001655 assert((TUK == Sema::TUK_Definition || TUK == Sema::TUK_Friend) &&
Richard Smith003c5e12013-11-08 19:03:29 +00001656 "Expected a definition here");
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001657
Richard Smith003c5e12013-11-08 19:03:29 +00001658 if (TUK == Sema::TUK_Friend) {
1659 Diag(DS.getFriendSpecLoc(), diag::err_friend_explicit_instantiation);
Craig Topper161e4db2014-05-21 06:02:52 +00001660 TemplateParams = nullptr;
Richard Smith003c5e12013-11-08 19:03:29 +00001661 } else {
1662 SourceLocation LAngleLoc =
1663 PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
1664 Diag(TemplateId->TemplateNameLoc,
1665 diag::err_explicit_instantiation_with_definition)
1666 << SourceRange(TemplateInfo.TemplateLoc)
1667 << FixItHint::CreateInsertion(LAngleLoc, "<>");
1668
1669 // Create a fake template parameter list that contains only
1670 // "template<>", so that we treat this construct as a class
1671 // template specialization.
1672 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
Craig Topper96225a52015-12-24 23:58:25 +00001673 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
Hubert Tongf608c052016-04-29 18:05:37 +00001674 LAngleLoc, nullptr));
Richard Smith003c5e12013-11-08 19:03:29 +00001675 TemplateParams = &FakedParamLists;
1676 }
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001677 }
1678
1679 // Build the class template specialization.
Richard Smith4b55a9c2014-04-17 03:29:33 +00001680 TagOrTempResult = Actions.ActOnClassTemplateSpecialization(
1681 getCurScope(), TagType, TUK, StartLoc, DS.getModulePrivateSpecLoc(),
1682 *TemplateId, attrs.getList(),
Craig Topper161e4db2014-05-21 06:02:52 +00001683 MultiTemplateParamsArg(TemplateParams ? &(*TemplateParams)[0]
1684 : nullptr,
Richard Smithc7e6ff02015-05-18 20:36:47 +00001685 TemplateParams ? TemplateParams->size() : 0),
1686 &SkipBody);
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001687 }
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001688 } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
John McCallfaf5fb42010-08-26 23:41:50 +00001689 TUK == Sema::TUK_Declaration) {
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001690 // Explicit instantiation of a member of a class template
1691 // specialization, e.g.,
1692 //
1693 // template struct Outer<int>::Inner;
1694 //
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001695 ProhibitAttributes(attrs);
1696
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001697 TagOrTempResult
Douglas Gregor0be31a22010-07-02 17:43:08 +00001698 = Actions.ActOnExplicitInstantiation(getCurScope(),
Douglas Gregor43e75172009-09-04 06:33:52 +00001699 TemplateInfo.ExternLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001700 TemplateInfo.TemplateLoc,
1701 TagType, StartLoc, SS, Name,
John McCall53fa7142010-12-24 02:08:15 +00001702 NameLoc, attrs.getList());
John McCallace48cd2010-10-19 01:40:49 +00001703 } else if (TUK == Sema::TUK_Friend &&
1704 TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate) {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001705 ProhibitAttributes(attrs);
1706
John McCallace48cd2010-10-19 01:40:49 +00001707 TagOrTempResult =
1708 Actions.ActOnTemplatedFriendTag(getCurScope(), DS.getFriendSpecLoc(),
1709 TagType, StartLoc, SS,
John McCall53fa7142010-12-24 02:08:15 +00001710 Name, NameLoc, attrs.getList(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00001711 MultiTemplateParamsArg(
Craig Topper161e4db2014-05-21 06:02:52 +00001712 TemplateParams? &(*TemplateParams)[0]
1713 : nullptr,
John McCallace48cd2010-10-19 01:40:49 +00001714 TemplateParams? TemplateParams->size() : 0));
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001715 } else {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001716 if (TUK != Sema::TUK_Declaration && TUK != Sema::TUK_Definition)
1717 ProhibitAttributes(attrs);
Richard Smith003c5e12013-11-08 19:03:29 +00001718
Larisse Voufo725de3e2013-06-21 00:08:46 +00001719 if (TUK == Sema::TUK_Definition &&
1720 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1721 // If the declarator-id is not a template-id, issue a diagnostic and
1722 // recover by ignoring the 'template' keyword.
1723 Diag(Tok, diag::err_template_defn_explicit_instantiation)
1724 << 1 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
Craig Topper161e4db2014-05-21 06:02:52 +00001725 TemplateParams = nullptr;
Larisse Voufo725de3e2013-06-21 00:08:46 +00001726 }
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001727
John McCall7f41d982009-09-11 04:59:25 +00001728 bool IsDependent = false;
1729
John McCall32723e92010-10-19 18:40:57 +00001730 // Don't pass down template parameter lists if this is just a tag
1731 // reference. For example, we don't need the template parameters here:
1732 // template <class T> class A *makeA(T t);
1733 MultiTemplateParamsArg TParams;
1734 if (TUK != Sema::TUK_Reference && TemplateParams)
1735 TParams =
1736 MultiTemplateParamsArg(&(*TemplateParams)[0], TemplateParams->size());
1737
David Majnemer936b4112015-04-19 07:53:29 +00001738 handleDeclspecAlignBeforeClassKey(attrs, DS, TUK);
1739
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001740 // Declaration or definition of a class type
John McCallace48cd2010-10-19 01:40:49 +00001741 TagOrTempResult = Actions.ActOnTag(getCurScope(), TagType, TUK, StartLoc,
John McCall53fa7142010-12-24 02:08:15 +00001742 SS, Name, NameLoc, attrs.getList(), AS,
Douglas Gregor2820e692011-09-09 19:05:14 +00001743 DS.getModulePrivateSpecLoc(),
Richard Smith0f8ee222012-01-10 01:33:14 +00001744 TParams, Owned, IsDependent,
1745 SourceLocation(), false,
Richard Smith649c7b062014-01-08 00:56:48 +00001746 clang::TypeResult(),
Richard Smith65ebb4a2015-03-26 04:09:53 +00001747 DSC == DSC_type_specifier,
1748 &SkipBody);
John McCall7f41d982009-09-11 04:59:25 +00001749
1750 // If ActOnTag said the type was dependent, try again with the
1751 // less common call.
John McCallace48cd2010-10-19 01:40:49 +00001752 if (IsDependent) {
1753 assert(TUK == Sema::TUK_Reference || TUK == Sema::TUK_Friend);
Douglas Gregor0be31a22010-07-02 17:43:08 +00001754 TypeResult = Actions.ActOnDependentTag(getCurScope(), TagType, TUK,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001755 SS, Name, StartLoc, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +00001756 }
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001757 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001758
Douglas Gregor556877c2008-04-13 21:30:24 +00001759 // If there is a body, parse it and inform the actions module.
John McCallfaf5fb42010-08-26 23:41:50 +00001760 if (TUK == Sema::TUK_Definition) {
John McCall2d814c32009-12-19 21:48:58 +00001761 assert(Tok.is(tok::l_brace) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00001762 (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
Richard Smith89645bc2013-01-02 12:01:23 +00001763 isCXX11FinalKeyword());
Richard Smithd9ba2242015-05-07 03:54:19 +00001764 if (SkipBody.ShouldSkip)
Richard Smith65ebb4a2015-03-26 04:09:53 +00001765 SkipCXXMemberSpecification(StartLoc, AttrFixitLoc, TagType,
1766 TagOrTempResult.get());
1767 else if (getLangOpts().CPlusPlus)
Michael Han309af292013-01-07 16:57:11 +00001768 ParseCXXMemberSpecification(StartLoc, AttrFixitLoc, attrs, TagType,
1769 TagOrTempResult.get());
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001770 else
Douglas Gregorc08f4892009-03-25 00:13:59 +00001771 ParseStructUnionBody(StartLoc, TagType, TagOrTempResult.get());
Douglas Gregor556877c2008-04-13 21:30:24 +00001772 }
1773
Craig Topper161e4db2014-05-21 06:02:52 +00001774 const char *PrevSpec = nullptr;
John McCallba7bf592010-08-24 05:47:05 +00001775 unsigned DiagID;
1776 bool Result;
John McCall7f41d982009-09-11 04:59:25 +00001777 if (!TypeResult.isInvalid()) {
Abramo Bagnara9875a3c2011-03-16 20:16:18 +00001778 Result = DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
1779 NameLoc.isValid() ? NameLoc : StartLoc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001780 PrevSpec, DiagID, TypeResult.get(), Policy);
John McCall7f41d982009-09-11 04:59:25 +00001781 } else if (!TagOrTempResult.isInvalid()) {
Abramo Bagnara9875a3c2011-03-16 20:16:18 +00001782 Result = DS.SetTypeSpecType(TagType, StartLoc,
1783 NameLoc.isValid() ? NameLoc : StartLoc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001784 PrevSpec, DiagID, TagOrTempResult.get(), Owned,
1785 Policy);
John McCall7f41d982009-09-11 04:59:25 +00001786 } else {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001787 DS.SetTypeSpecError();
Anders Carlssonf83c9fa2009-05-11 22:27:47 +00001788 return;
1789 }
Mike Stump11289f42009-09-09 15:08:12 +00001790
John McCallba7bf592010-08-24 05:47:05 +00001791 if (Result)
John McCall49bfce42009-08-03 20:12:06 +00001792 Diag(StartLoc, DiagID) << PrevSpec;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001793
Chris Lattnercf251412010-02-02 01:23:29 +00001794 // At this point, we've successfully parsed a class-specifier in 'definition'
1795 // form (e.g. "struct foo { int x; }". While we could just return here, we're
1796 // going to look at what comes after it to improve error recovery. If an
1797 // impossible token occurs next, we assume that the programmer forgot a ; at
1798 // the end of the declaration and recover that way.
1799 //
Richard Smith369b9f92012-06-25 21:37:02 +00001800 // Also enforce C++ [temp]p3:
1801 // In a template-declaration which defines a class, no declarator
1802 // is permitted.
Richard Smith843f18f2014-08-13 02:13:15 +00001803 //
1804 // After a type-specifier, we don't expect a semicolon. This only happens in
1805 // C, since definitions are not permitted in this context in C++.
Joao Matose9a3ed42012-08-31 22:18:20 +00001806 if (TUK == Sema::TUK_Definition &&
Richard Smith843f18f2014-08-13 02:13:15 +00001807 (getLangOpts().CPlusPlus || !isTypeSpecifier(DSC)) &&
Joao Matose9a3ed42012-08-31 22:18:20 +00001808 (TemplateInfo.Kind || !isValidAfterTypeSpecifier(false))) {
Argyrios Kyrtzidise6f69132012-12-17 20:10:43 +00001809 if (Tok.isNot(tok::semi)) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001810 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
Alp Toker383d2c42014-01-01 03:08:43 +00001811 ExpectAndConsume(tok::semi, diag::err_expected_after,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001812 DeclSpec::getSpecifierName(TagType, PPol));
Argyrios Kyrtzidise6f69132012-12-17 20:10:43 +00001813 // Push this token back into the preprocessor and change our current token
1814 // to ';' so that the rest of the code recovers as though there were an
1815 // ';' after the definition.
1816 PP.EnterToken(Tok);
1817 Tok.setKind(tok::semi);
1818 }
Chris Lattnercf251412010-02-02 01:23:29 +00001819 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001820}
1821
Mike Stump11289f42009-09-09 15:08:12 +00001822/// ParseBaseClause - Parse the base-clause of a C++ class [C++ class.derived].
Douglas Gregor556877c2008-04-13 21:30:24 +00001823///
1824/// base-clause : [C++ class.derived]
1825/// ':' base-specifier-list
1826/// base-specifier-list:
1827/// base-specifier '...'[opt]
1828/// base-specifier-list ',' base-specifier '...'[opt]
John McCall48871652010-08-21 09:40:31 +00001829void Parser::ParseBaseClause(Decl *ClassDecl) {
Douglas Gregor556877c2008-04-13 21:30:24 +00001830 assert(Tok.is(tok::colon) && "Not a base clause");
1831 ConsumeToken();
1832
Douglas Gregor29a92472008-10-22 17:49:05 +00001833 // Build up an array of parsed base specifiers.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001834 SmallVector<CXXBaseSpecifier *, 8> BaseInfo;
Douglas Gregor29a92472008-10-22 17:49:05 +00001835
Douglas Gregor556877c2008-04-13 21:30:24 +00001836 while (true) {
1837 // Parse a base-specifier.
Douglas Gregor29a92472008-10-22 17:49:05 +00001838 BaseResult Result = ParseBaseSpecifier(ClassDecl);
Douglas Gregorf8298252009-01-26 22:44:13 +00001839 if (Result.isInvalid()) {
Douglas Gregor556877c2008-04-13 21:30:24 +00001840 // Skip the rest of this base specifier, up until the comma or
1841 // opening brace.
Alexey Bataevee6507d2013-11-18 08:17:37 +00001842 SkipUntil(tok::comma, tok::l_brace, StopAtSemi | StopBeforeMatch);
Douglas Gregor29a92472008-10-22 17:49:05 +00001843 } else {
1844 // Add this to our array of base specifiers.
Douglas Gregorf8298252009-01-26 22:44:13 +00001845 BaseInfo.push_back(Result.get());
Douglas Gregor556877c2008-04-13 21:30:24 +00001846 }
1847
1848 // If the next token is a comma, consume it and keep reading
1849 // base-specifiers.
Alp Toker97650562014-01-10 11:19:30 +00001850 if (!TryConsumeToken(tok::comma))
1851 break;
Douglas Gregor556877c2008-04-13 21:30:24 +00001852 }
Douglas Gregor29a92472008-10-22 17:49:05 +00001853
1854 // Attach the base specifiers
Craig Topperaa700cb2015-12-27 21:55:19 +00001855 Actions.ActOnBaseSpecifiers(ClassDecl, BaseInfo);
Douglas Gregor556877c2008-04-13 21:30:24 +00001856}
1857
1858/// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is
1859/// one entry in the base class list of a class specifier, for example:
1860/// class foo : public bar, virtual private baz {
1861/// 'public bar' and 'virtual private baz' are each base-specifiers.
1862///
1863/// base-specifier: [C++ class.derived]
Richard Smith4c96e992013-02-19 23:47:15 +00001864/// attribute-specifier-seq[opt] base-type-specifier
1865/// attribute-specifier-seq[opt] 'virtual' access-specifier[opt]
1866/// base-type-specifier
1867/// attribute-specifier-seq[opt] access-specifier 'virtual'[opt]
1868/// base-type-specifier
Craig Topper9ad7e262014-10-31 06:57:07 +00001869BaseResult Parser::ParseBaseSpecifier(Decl *ClassDecl) {
Douglas Gregor556877c2008-04-13 21:30:24 +00001870 bool IsVirtual = false;
1871 SourceLocation StartLoc = Tok.getLocation();
1872
Richard Smith4c96e992013-02-19 23:47:15 +00001873 ParsedAttributesWithRange Attributes(AttrFactory);
1874 MaybeParseCXX11Attributes(Attributes);
1875
Douglas Gregor556877c2008-04-13 21:30:24 +00001876 // Parse the 'virtual' keyword.
Alp Toker97650562014-01-10 11:19:30 +00001877 if (TryConsumeToken(tok::kw_virtual))
Douglas Gregor556877c2008-04-13 21:30:24 +00001878 IsVirtual = true;
Douglas Gregor556877c2008-04-13 21:30:24 +00001879
Richard Smith4c96e992013-02-19 23:47:15 +00001880 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
1881
Douglas Gregor556877c2008-04-13 21:30:24 +00001882 // Parse an (optional) access specifier.
1883 AccessSpecifier Access = getAccessSpecifierIfPresent();
John McCall553c0792010-01-23 00:46:32 +00001884 if (Access != AS_none)
Douglas Gregor556877c2008-04-13 21:30:24 +00001885 ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +00001886
Richard Smith4c96e992013-02-19 23:47:15 +00001887 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
1888
Douglas Gregor556877c2008-04-13 21:30:24 +00001889 // Parse the 'virtual' keyword (again!), in case it came after the
1890 // access specifier.
1891 if (Tok.is(tok::kw_virtual)) {
1892 SourceLocation VirtualLoc = ConsumeToken();
1893 if (IsVirtual) {
1894 // Complain about duplicate 'virtual'
Chris Lattner6d29c102008-11-18 07:48:38 +00001895 Diag(VirtualLoc, diag::err_dup_virtual)
Douglas Gregora771f462010-03-31 17:46:05 +00001896 << FixItHint::CreateRemoval(VirtualLoc);
Douglas Gregor556877c2008-04-13 21:30:24 +00001897 }
1898
1899 IsVirtual = true;
1900 }
1901
Richard Smith4c96e992013-02-19 23:47:15 +00001902 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
1903
Douglas Gregor831c93f2008-11-05 20:51:48 +00001904 // Parse the class-name.
David Majnemer51fd8a02015-07-22 23:46:18 +00001905
1906 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
1907 // implementation for VS2013 uses _Atomic as an identifier for one of the
1908 // classes in <atomic>. Treat '_Atomic' to be an identifier when we are
1909 // parsing the class-name for a base specifier.
1910 if (getLangOpts().MSVCCompat && Tok.is(tok::kw__Atomic) &&
1911 NextToken().is(tok::less))
1912 Tok.setKind(tok::identifier);
1913
Douglas Gregord54dfb82009-02-25 23:52:28 +00001914 SourceLocation EndLocation;
David Blaikie1cd50022011-10-25 17:10:12 +00001915 SourceLocation BaseLoc;
1916 TypeResult BaseType = ParseBaseTypeSpecifier(BaseLoc, EndLocation);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001917 if (BaseType.isInvalid())
Douglas Gregor831c93f2008-11-05 20:51:48 +00001918 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001919
Douglas Gregor752a5952011-01-03 22:36:02 +00001920 // Parse the optional ellipsis (for a pack expansion). The ellipsis is
1921 // actually part of the base-specifier-list grammar productions, but we
1922 // parse it here for convenience.
1923 SourceLocation EllipsisLoc;
Alp Toker97650562014-01-10 11:19:30 +00001924 TryConsumeToken(tok::ellipsis, EllipsisLoc);
1925
Mike Stump11289f42009-09-09 15:08:12 +00001926 // Find the complete source range for the base-specifier.
Douglas Gregord54dfb82009-02-25 23:52:28 +00001927 SourceRange Range(StartLoc, EndLocation);
Mike Stump11289f42009-09-09 15:08:12 +00001928
Douglas Gregor556877c2008-04-13 21:30:24 +00001929 // Notify semantic analysis that we have parsed a complete
1930 // base-specifier.
Richard Smith4c96e992013-02-19 23:47:15 +00001931 return Actions.ActOnBaseSpecifier(ClassDecl, Range, Attributes, IsVirtual,
1932 Access, BaseType.get(), BaseLoc,
1933 EllipsisLoc);
Douglas Gregor556877c2008-04-13 21:30:24 +00001934}
1935
1936/// getAccessSpecifierIfPresent - Determine whether the next token is
1937/// a C++ access-specifier.
1938///
1939/// access-specifier: [C++ class.derived]
1940/// 'private'
1941/// 'protected'
1942/// 'public'
Mike Stump11289f42009-09-09 15:08:12 +00001943AccessSpecifier Parser::getAccessSpecifierIfPresent() const {
Douglas Gregor556877c2008-04-13 21:30:24 +00001944 switch (Tok.getKind()) {
1945 default: return AS_none;
1946 case tok::kw_private: return AS_private;
1947 case tok::kw_protected: return AS_protected;
1948 case tok::kw_public: return AS_public;
1949 }
1950}
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00001951
Douglas Gregor433e0532012-04-16 18:27:27 +00001952/// \brief If the given declarator has any parts for which parsing has to be
Richard Smith0b3a4622014-11-13 20:01:57 +00001953/// delayed, e.g., default arguments or an exception-specification, create a
1954/// late-parsed method declaration record to handle the parsing at the end of
1955/// the class definition.
Douglas Gregor433e0532012-04-16 18:27:27 +00001956void Parser::HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
1957 Decl *ThisDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00001958 DeclaratorChunk::FunctionTypeInfo &FTI
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001959 = DeclaratorInfo.getFunctionTypeInfo();
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00001960 // If there was a late-parsed exception-specification, we'll need a
1961 // late parse
1962 bool NeedLateParse = FTI.getExceptionSpecType() == EST_Unparsed;
Douglas Gregor433e0532012-04-16 18:27:27 +00001963
Nathan Sidwell5bb231c2015-02-19 14:03:22 +00001964 if (!NeedLateParse) {
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00001965 // Look ahead to see if there are any default args
Nathan Sidwell5bb231c2015-02-19 14:03:22 +00001966 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx) {
1967 auto Param = cast<ParmVarDecl>(FTI.Params[ParamIdx].Param);
1968 if (Param->hasUnparsedDefaultArg()) {
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00001969 NeedLateParse = true;
1970 break;
1971 }
Nathan Sidwell5bb231c2015-02-19 14:03:22 +00001972 }
1973 }
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00001974
1975 if (NeedLateParse) {
Richard Smith0b3a4622014-11-13 20:01:57 +00001976 // Push this method onto the stack of late-parsed method
1977 // declarations.
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00001978 auto LateMethod = new LateParsedMethodDeclaration(this, ThisDecl);
Richard Smith0b3a4622014-11-13 20:01:57 +00001979 getCurrentClass().LateParsedDeclarations.push_back(LateMethod);
1980 LateMethod->TemplateScope = getCurScope()->isTemplateParamScope();
1981
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00001982 // Stash the exception-specification tokens in the late-pased method.
Richard Smith0b3a4622014-11-13 20:01:57 +00001983 LateMethod->ExceptionSpecTokens = FTI.ExceptionSpecTokens;
Hans Wennborgdcfba332015-10-06 23:40:43 +00001984 FTI.ExceptionSpecTokens = nullptr;
Richard Smith0b3a4622014-11-13 20:01:57 +00001985
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00001986 // Push tokens for each parameter. Those that do not have
1987 // defaults will be NULL.
Richard Smith0b3a4622014-11-13 20:01:57 +00001988 LateMethod->DefaultArgs.reserve(FTI.NumParams);
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00001989 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx)
Alp Tokerc5350722014-02-26 22:27:52 +00001990 LateMethod->DefaultArgs.push_back(LateParsedDefaultArgument(
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00001991 FTI.Params[ParamIdx].Param, FTI.Params[ParamIdx].DefaultArgTokens));
Eli Friedman3af2a772009-07-22 21:45:50 +00001992 }
1993}
1994
Richard Smith89645bc2013-01-02 12:01:23 +00001995/// isCXX11VirtSpecifier - Determine whether the given token is a C++11
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00001996/// virt-specifier.
1997///
1998/// virt-specifier:
1999/// override
2000/// final
Richard Smith89645bc2013-01-02 12:01:23 +00002001VirtSpecifiers::Specifier Parser::isCXX11VirtSpecifier(const Token &Tok) const {
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002002 if (!getLangOpts().CPlusPlus || Tok.isNot(tok::identifier))
Anders Carlsson4b63d0e2011-01-22 16:56:46 +00002003 return VirtSpecifiers::VS_None;
2004
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002005 IdentifierInfo *II = Tok.getIdentifierInfo();
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002006
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002007 // Initialize the contextual keywords.
2008 if (!Ident_final) {
2009 Ident_final = &PP.getIdentifierTable().get("final");
2010 if (getLangOpts().MicrosoftExt)
2011 Ident_sealed = &PP.getIdentifierTable().get("sealed");
2012 Ident_override = &PP.getIdentifierTable().get("override");
Anders Carlsson56104902011-01-17 03:05:47 +00002013 }
2014
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002015 if (II == Ident_override)
2016 return VirtSpecifiers::VS_Override;
2017
2018 if (II == Ident_sealed)
2019 return VirtSpecifiers::VS_Sealed;
2020
2021 if (II == Ident_final)
2022 return VirtSpecifiers::VS_Final;
2023
Anders Carlsson56104902011-01-17 03:05:47 +00002024 return VirtSpecifiers::VS_None;
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002025}
2026
Richard Smith89645bc2013-01-02 12:01:23 +00002027/// ParseOptionalCXX11VirtSpecifierSeq - Parse a virt-specifier-seq.
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002028///
2029/// virt-specifier-seq:
2030/// virt-specifier
2031/// virt-specifier-seq virt-specifier
Richard Smith89645bc2013-01-02 12:01:23 +00002032void Parser::ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS,
Richard Smith3d1a94c2014-08-12 00:22:39 +00002033 bool IsInterface,
2034 SourceLocation FriendLoc) {
Anders Carlsson56104902011-01-17 03:05:47 +00002035 while (true) {
Richard Smith89645bc2013-01-02 12:01:23 +00002036 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
Anders Carlsson56104902011-01-17 03:05:47 +00002037 if (Specifier == VirtSpecifiers::VS_None)
2038 return;
2039
Richard Smith3d1a94c2014-08-12 00:22:39 +00002040 if (FriendLoc.isValid()) {
2041 Diag(Tok.getLocation(), diag::err_friend_decl_spec)
2042 << VirtSpecifiers::getSpecifierName(Specifier)
2043 << FixItHint::CreateRemoval(Tok.getLocation())
2044 << SourceRange(FriendLoc, FriendLoc);
2045 ConsumeToken();
2046 continue;
2047 }
2048
Anders Carlsson56104902011-01-17 03:05:47 +00002049 // C++ [class.mem]p8:
2050 // A virt-specifier-seq shall contain at most one of each virt-specifier.
Craig Topper161e4db2014-05-21 06:02:52 +00002051 const char *PrevSpec = nullptr;
Anders Carlssonf2ca3892011-01-22 15:58:16 +00002052 if (VS.SetSpecifier(Specifier, Tok.getLocation(), PrevSpec))
Anders Carlsson56104902011-01-17 03:05:47 +00002053 Diag(Tok.getLocation(), diag::err_duplicate_virt_specifier)
2054 << PrevSpec
2055 << FixItHint::CreateRemoval(Tok.getLocation());
2056
David Majnemera5433082013-10-18 00:33:31 +00002057 if (IsInterface && (Specifier == VirtSpecifiers::VS_Final ||
2058 Specifier == VirtSpecifiers::VS_Sealed)) {
John McCalldb632ac2012-09-25 07:32:39 +00002059 Diag(Tok.getLocation(), diag::err_override_control_interface)
2060 << VirtSpecifiers::getSpecifierName(Specifier);
David Majnemera5433082013-10-18 00:33:31 +00002061 } else if (Specifier == VirtSpecifiers::VS_Sealed) {
2062 Diag(Tok.getLocation(), diag::ext_ms_sealed_keyword);
John McCalldb632ac2012-09-25 07:32:39 +00002063 } else {
David Majnemera5433082013-10-18 00:33:31 +00002064 Diag(Tok.getLocation(),
2065 getLangOpts().CPlusPlus11
2066 ? diag::warn_cxx98_compat_override_control_keyword
2067 : diag::ext_override_control_keyword)
2068 << VirtSpecifiers::getSpecifierName(Specifier);
John McCalldb632ac2012-09-25 07:32:39 +00002069 }
Anders Carlsson56104902011-01-17 03:05:47 +00002070 ConsumeToken();
2071 }
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002072}
2073
Richard Smith89645bc2013-01-02 12:01:23 +00002074/// isCXX11FinalKeyword - Determine whether the next token is a C++11
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002075/// 'final' or Microsoft 'sealed' contextual keyword.
Richard Smith89645bc2013-01-02 12:01:23 +00002076bool Parser::isCXX11FinalKeyword() const {
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002077 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
2078 return Specifier == VirtSpecifiers::VS_Final ||
2079 Specifier == VirtSpecifiers::VS_Sealed;
Anders Carlsson4b63d0e2011-01-22 16:56:46 +00002080}
2081
Richard Smith72553fc2014-01-23 23:53:27 +00002082/// \brief Parse a C++ member-declarator up to, but not including, the optional
2083/// brace-or-equal-initializer or pure-specifier.
Nico Weberd89e6f72015-01-16 19:34:13 +00002084bool Parser::ParseCXXMemberDeclaratorBeforeInitializer(
Richard Smith72553fc2014-01-23 23:53:27 +00002085 Declarator &DeclaratorInfo, VirtSpecifiers &VS, ExprResult &BitfieldSize,
2086 LateParsedAttrList &LateParsedAttrs) {
2087 // member-declarator:
2088 // declarator pure-specifier[opt]
2089 // declarator brace-or-equal-initializer[opt]
2090 // identifier[opt] ':' constant-expression
Serge Pavlov458ea762014-07-16 05:16:52 +00002091 if (Tok.isNot(tok::colon))
Richard Smith72553fc2014-01-23 23:53:27 +00002092 ParseDeclarator(DeclaratorInfo);
Richard Smith3d1a94c2014-08-12 00:22:39 +00002093 else
2094 DeclaratorInfo.SetIdentifier(nullptr, Tok.getLocation());
Richard Smith72553fc2014-01-23 23:53:27 +00002095
2096 if (!DeclaratorInfo.isFunctionDeclarator() && TryConsumeToken(tok::colon)) {
Richard Smith3d1a94c2014-08-12 00:22:39 +00002097 assert(DeclaratorInfo.isPastIdentifier() &&
2098 "don't know where identifier would go yet?");
Richard Smith72553fc2014-01-23 23:53:27 +00002099 BitfieldSize = ParseConstantExpression();
2100 if (BitfieldSize.isInvalid())
2101 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002102 } else {
Richard Smith3d1a94c2014-08-12 00:22:39 +00002103 ParseOptionalCXX11VirtSpecifierSeq(
2104 VS, getCurrentClass().IsInterface,
2105 DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002106 if (!VS.isUnset())
2107 MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo, VS);
2108 }
Richard Smith72553fc2014-01-23 23:53:27 +00002109
2110 // If a simple-asm-expr is present, parse it.
2111 if (Tok.is(tok::kw_asm)) {
2112 SourceLocation Loc;
2113 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
2114 if (AsmLabel.isInvalid())
2115 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2116
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002117 DeclaratorInfo.setAsmLabel(AsmLabel.get());
Richard Smith72553fc2014-01-23 23:53:27 +00002118 DeclaratorInfo.SetRangeEnd(Loc);
2119 }
2120
2121 // If attributes exist after the declarator, but before an '{', parse them.
2122 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
Richard Smith4b5a9492014-01-24 22:34:35 +00002123
2124 // For compatibility with code written to older Clang, also accept a
2125 // virt-specifier *after* the GNU attributes.
Aaron Ballman5d153e32014-08-04 17:03:51 +00002126 if (BitfieldSize.isUnset() && VS.isUnset()) {
Richard Smith3d1a94c2014-08-12 00:22:39 +00002127 ParseOptionalCXX11VirtSpecifierSeq(
2128 VS, getCurrentClass().IsInterface,
2129 DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
Aaron Ballman5d153e32014-08-04 17:03:51 +00002130 if (!VS.isUnset()) {
2131 // If we saw any GNU-style attributes that are known to GCC followed by a
2132 // virt-specifier, issue a GCC-compat warning.
2133 const AttributeList *Attr = DeclaratorInfo.getAttributes();
2134 while (Attr) {
2135 if (Attr->isKnownToGCC() && !Attr->isCXX11Attribute())
2136 Diag(Attr->getLoc(), diag::warn_gcc_attribute_location);
2137 Attr = Attr->getNext();
2138 }
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002139 MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo, VS);
Aaron Ballman5d153e32014-08-04 17:03:51 +00002140 }
2141 }
Nico Weberd89e6f72015-01-16 19:34:13 +00002142
2143 // If this has neither a name nor a bit width, something has gone seriously
2144 // wrong. Skip until the semi-colon or }.
2145 if (!DeclaratorInfo.hasName() && BitfieldSize.isUnset()) {
2146 // If so, skip until the semi-colon or a }.
2147 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2148 return true;
2149 }
2150 return false;
Richard Smith72553fc2014-01-23 23:53:27 +00002151}
2152
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002153/// \brief Look for declaration specifiers possibly occurring after C++11
2154/// virt-specifier-seq and diagnose them.
2155void Parser::MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(
2156 Declarator &D,
2157 VirtSpecifiers &VS) {
2158 DeclSpec DS(AttrFactory);
2159
2160 // GNU-style and C++11 attributes are not allowed here, but they will be
2161 // handled by the caller. Diagnose everything else.
2162 ParseTypeQualifierListOpt(DS, AR_NoAttributesParsed, false);
2163 D.ExtendWithDeclSpec(DS);
2164
2165 if (D.isFunctionDeclarator()) {
Ehsan Akhgaric07d1e22015-03-25 00:53:33 +00002166 auto &Function = D.getFunctionTypeInfo();
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002167 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
2168 auto DeclSpecCheck = [&] (DeclSpec::TQ TypeQual,
2169 const char *FixItName,
2170 SourceLocation SpecLoc,
2171 unsigned* QualifierLoc) {
2172 FixItHint Insertion;
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002173 if (DS.getTypeQualifiers() & TypeQual) {
2174 if (!(Function.TypeQuals & TypeQual)) {
2175 std::string Name(FixItName);
2176 Name += " ";
2177 Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), Name.c_str());
2178 Function.TypeQuals |= TypeQual;
2179 *QualifierLoc = SpecLoc.getRawEncoding();
2180 }
2181 Diag(SpecLoc, diag::err_declspec_after_virtspec)
2182 << FixItName
2183 << VirtSpecifiers::getSpecifierName(VS.getLastSpecifier())
2184 << FixItHint::CreateRemoval(SpecLoc)
2185 << Insertion;
2186 }
2187 };
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002188 DeclSpecCheck(DeclSpec::TQ_const, "const", DS.getConstSpecLoc(),
2189 &Function.ConstQualifierLoc);
2190 DeclSpecCheck(DeclSpec::TQ_volatile, "volatile", DS.getVolatileSpecLoc(),
2191 &Function.VolatileQualifierLoc);
2192 DeclSpecCheck(DeclSpec::TQ_restrict, "restrict", DS.getRestrictSpecLoc(),
2193 &Function.RestrictQualifierLoc);
2194 }
Ehsan Akhgaric07d1e22015-03-25 00:53:33 +00002195
2196 // Parse ref-qualifiers.
2197 bool RefQualifierIsLValueRef = true;
2198 SourceLocation RefQualifierLoc;
2199 if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc)) {
2200 const char *Name = (RefQualifierIsLValueRef ? "& " : "&& ");
2201 FixItHint Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), Name);
2202 Function.RefQualifierIsLValueRef = RefQualifierIsLValueRef;
2203 Function.RefQualifierLoc = RefQualifierLoc.getRawEncoding();
2204
2205 Diag(RefQualifierLoc, diag::err_declspec_after_virtspec)
2206 << (RefQualifierIsLValueRef ? "&" : "&&")
2207 << VirtSpecifiers::getSpecifierName(VS.getLastSpecifier())
2208 << FixItHint::CreateRemoval(RefQualifierLoc)
2209 << Insertion;
2210 D.SetRangeEnd(RefQualifierLoc);
2211 }
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002212 }
2213}
2214
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002215/// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration.
2216///
2217/// member-declaration:
2218/// decl-specifier-seq[opt] member-declarator-list[opt] ';'
2219/// function-definition ';'[opt]
2220/// ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO]
2221/// using-declaration [TODO]
Anders Carlssonf24fcff62009-03-11 16:27:10 +00002222/// [C++0x] static_assert-declaration
Anders Carlssondfbbdf62009-03-26 00:52:18 +00002223/// template-declaration
Chris Lattnerd19c1c02008-12-18 01:12:00 +00002224/// [GNU] '__extension__' member-declaration
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002225///
2226/// member-declarator-list:
2227/// member-declarator
2228/// member-declarator-list ',' member-declarator
2229///
2230/// member-declarator:
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002231/// declarator virt-specifier-seq[opt] pure-specifier[opt]
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002232/// declarator constant-initializer[opt]
Richard Smith938f40b2011-06-11 17:19:42 +00002233/// [C++11] declarator brace-or-equal-initializer[opt]
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002234/// identifier[opt] ':' constant-expression
2235///
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002236/// virt-specifier-seq:
2237/// virt-specifier
2238/// virt-specifier-seq virt-specifier
2239///
2240/// virt-specifier:
2241/// override
2242/// final
David Majnemera5433082013-10-18 00:33:31 +00002243/// [MS] sealed
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002244///
Sebastian Redl42e92c42009-04-12 17:16:29 +00002245/// pure-specifier:
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002246/// '= 0'
2247///
2248/// constant-initializer:
2249/// '=' constant-expression
2250///
Alexey Bataev05c25d62015-07-31 08:42:25 +00002251Parser::DeclGroupPtrTy
2252Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS,
2253 AttributeList *AccessAttrs,
John McCall796c2a52010-07-16 08:13:16 +00002254 const ParsedTemplateInfo &TemplateInfo,
2255 ParsingDeclRAIIObject *TemplateDiags) {
Douglas Gregor23c84762011-04-14 17:21:19 +00002256 if (Tok.is(tok::at)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002257 if (getLangOpts().ObjC1 && NextToken().isObjCAtKeyword(tok::objc_defs))
Douglas Gregor23c84762011-04-14 17:21:19 +00002258 Diag(Tok, diag::err_at_defs_cxx);
2259 else
2260 Diag(Tok, diag::err_at_in_class);
Richard Smithda35e962013-11-09 04:52:51 +00002261
Douglas Gregor23c84762011-04-14 17:21:19 +00002262 ConsumeToken();
Alexey Bataevee6507d2013-11-18 08:17:37 +00002263 SkipUntil(tok::r_brace, StopAtSemi);
David Blaikie0403cb12016-01-15 23:43:25 +00002264 return nullptr;
Douglas Gregor23c84762011-04-14 17:21:19 +00002265 }
Richard Smithda35e962013-11-09 04:52:51 +00002266
Serge Pavlov458ea762014-07-16 05:16:52 +00002267 // Turn on colon protection early, while parsing declspec, although there is
2268 // nothing to protect there. It prevents from false errors if error recovery
2269 // incorrectly determines where the declspec ends, as in the example:
2270 // struct A { enum class B { C }; };
2271 // const int C = 4;
2272 // struct D { A::B : C; };
2273 ColonProtectionRAIIObject X(*this);
2274
John McCalla0097262009-12-11 02:10:03 +00002275 // Access declarations.
Richard Smith45855df2012-05-09 08:23:23 +00002276 bool MalformedTypeSpec = false;
John McCalla0097262009-12-11 02:10:03 +00002277 if (!TemplateInfo.Kind &&
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002278 Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw___super)) {
Richard Smith45855df2012-05-09 08:23:23 +00002279 if (TryAnnotateCXXScopeToken())
2280 MalformedTypeSpec = true;
2281
2282 bool isAccessDecl;
2283 if (Tok.isNot(tok::annot_cxxscope))
2284 isAccessDecl = false;
2285 else if (NextToken().is(tok::identifier))
John McCalla0097262009-12-11 02:10:03 +00002286 isAccessDecl = GetLookAheadToken(2).is(tok::semi);
2287 else
2288 isAccessDecl = NextToken().is(tok::kw_operator);
2289
2290 if (isAccessDecl) {
2291 // Collect the scope specifier token we annotated earlier.
2292 CXXScopeSpec SS;
David Blaikieefdccaa2016-01-15 23:43:34 +00002293 ParseOptionalCXXScopeSpecifier(SS, nullptr,
Douglas Gregordf593fb2011-11-07 17:33:42 +00002294 /*EnteringContext=*/false);
John McCalla0097262009-12-11 02:10:03 +00002295
Nico Weberef03e702014-09-10 00:59:37 +00002296 if (SS.isInvalid()) {
2297 SkipUntil(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002298 return nullptr;
Nico Weberef03e702014-09-10 00:59:37 +00002299 }
2300
John McCalla0097262009-12-11 02:10:03 +00002301 // Try to parse an unqualified-id.
Abramo Bagnara7945c982012-01-27 09:46:47 +00002302 SourceLocation TemplateKWLoc;
John McCalla0097262009-12-11 02:10:03 +00002303 UnqualifiedId Name;
David Blaikieefdccaa2016-01-15 23:43:34 +00002304 if (ParseUnqualifiedId(SS, false, true, true, nullptr, TemplateKWLoc,
2305 Name)) {
John McCalla0097262009-12-11 02:10:03 +00002306 SkipUntil(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002307 return nullptr;
John McCalla0097262009-12-11 02:10:03 +00002308 }
2309
2310 // TODO: recover from mistakenly-qualified operator declarations.
Alp Toker383d2c42014-01-01 03:08:43 +00002311 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
2312 "access declaration")) {
2313 SkipUntil(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002314 return nullptr;
Alp Toker383d2c42014-01-01 03:08:43 +00002315 }
John McCalla0097262009-12-11 02:10:03 +00002316
Alexey Bataev05c25d62015-07-31 08:42:25 +00002317 return DeclGroupPtrTy::make(DeclGroupRef(Actions.ActOnUsingDeclaration(
2318 getCurScope(), AS,
2319 /* HasUsingKeyword */ false, SourceLocation(), SS, Name,
2320 /* AttrList */ nullptr,
2321 /* HasTypenameKeyword */ false, SourceLocation())));
John McCalla0097262009-12-11 02:10:03 +00002322 }
2323 }
2324
Aaron Ballmane7c544d2014-08-04 20:28:35 +00002325 // static_assert-declaration. A templated static_assert declaration is
2326 // diagnosed in Parser::ParseSingleDeclarationAfterTemplate.
2327 if (!TemplateInfo.Kind &&
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002328 Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert)) {
Chris Lattner49836b42009-04-02 04:16:50 +00002329 SourceLocation DeclEnd;
Alexey Bataev05c25d62015-07-31 08:42:25 +00002330 return DeclGroupPtrTy::make(
2331 DeclGroupRef(ParseStaticAssertDeclaration(DeclEnd)));
Chris Lattner5bbb3c82009-03-29 16:50:03 +00002332 }
Mike Stump11289f42009-09-09 15:08:12 +00002333
Chris Lattner5bbb3c82009-03-29 16:50:03 +00002334 if (Tok.is(tok::kw_template)) {
Mike Stump11289f42009-09-09 15:08:12 +00002335 assert(!TemplateInfo.TemplateParams &&
Douglas Gregor3447e762009-08-20 22:52:58 +00002336 "Nested template improperly parsed?");
Chris Lattner49836b42009-04-02 04:16:50 +00002337 SourceLocation DeclEnd;
Alexey Bataev05c25d62015-07-31 08:42:25 +00002338 return DeclGroupPtrTy::make(
2339 DeclGroupRef(ParseDeclarationStartingWithTemplate(
2340 Declarator::MemberContext, DeclEnd, AS, AccessAttrs)));
Chris Lattner5bbb3c82009-03-29 16:50:03 +00002341 }
Anders Carlssondfbbdf62009-03-26 00:52:18 +00002342
Chris Lattnerd19c1c02008-12-18 01:12:00 +00002343 // Handle: member-declaration ::= '__extension__' member-declaration
2344 if (Tok.is(tok::kw___extension__)) {
2345 // __extension__ silences extension warnings in the subexpression.
2346 ExtensionRAIIObject O(Diags); // Use RAII to do this.
2347 ConsumeToken();
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00002348 return ParseCXXClassMemberDeclaration(AS, AccessAttrs,
2349 TemplateInfo, TemplateDiags);
Chris Lattnerd19c1c02008-12-18 01:12:00 +00002350 }
Douglas Gregorfec52632009-06-20 00:51:54 +00002351
John McCall084e83d2011-03-24 11:26:52 +00002352 ParsedAttributesWithRange attrs(AttrFactory);
Michael Handdc016d2012-11-28 23:17:40 +00002353 ParsedAttributesWithRange FnAttrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00002354 // Optional C++11 attribute-specifier
2355 MaybeParseCXX11Attributes(attrs);
Michael Handdc016d2012-11-28 23:17:40 +00002356 // We need to keep these attributes for future diagnostic
2357 // before they are taken over by declaration specifier.
2358 FnAttrs.addAll(attrs.getList());
2359 FnAttrs.Range = attrs.Range;
2360
John McCall53fa7142010-12-24 02:08:15 +00002361 MaybeParseMicrosoftAttributes(attrs);
Alexis Hunt96d5c762009-11-21 08:43:09 +00002362
Douglas Gregorfec52632009-06-20 00:51:54 +00002363 if (Tok.is(tok::kw_using)) {
John McCall53fa7142010-12-24 02:08:15 +00002364 ProhibitAttributes(attrs);
Mike Stump11289f42009-09-09 15:08:12 +00002365
Douglas Gregorfec52632009-06-20 00:51:54 +00002366 // Eat 'using'.
2367 SourceLocation UsingLoc = ConsumeToken();
2368
2369 if (Tok.is(tok::kw_namespace)) {
2370 Diag(UsingLoc, diag::err_using_namespace_in_class);
Alexey Bataevee6507d2013-11-18 08:17:37 +00002371 SkipUntil(tok::semi, StopBeforeMatch);
David Blaikie0403cb12016-01-15 23:43:25 +00002372 return nullptr;
Douglas Gregorfec52632009-06-20 00:51:54 +00002373 }
Alexey Bataev05c25d62015-07-31 08:42:25 +00002374 SourceLocation DeclEnd;
2375 // Otherwise, it must be a using-declaration or an alias-declaration.
2376 return DeclGroupPtrTy::make(DeclGroupRef(ParseUsingDeclaration(
2377 Declarator::MemberContext, TemplateInfo, UsingLoc, DeclEnd, AS)));
Douglas Gregorfec52632009-06-20 00:51:54 +00002378 }
2379
DeLesley Hutchinsbd2ee132012-03-02 22:12:59 +00002380 // Hold late-parsed attributes so we can attach a Decl to them later.
2381 LateParsedAttrList CommonLateParsedAttrs;
2382
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002383 // decl-specifier-seq:
2384 // Parse the common declaration-specifiers piece.
John McCall796c2a52010-07-16 08:13:16 +00002385 ParsingDeclSpec DS(*this, TemplateDiags);
John McCall53fa7142010-12-24 02:08:15 +00002386 DS.takeAttributesFrom(attrs);
Richard Smith45855df2012-05-09 08:23:23 +00002387 if (MalformedTypeSpec)
2388 DS.SetTypeSpecError();
Richard Smith72553fc2014-01-23 23:53:27 +00002389
Serge Pavlov458ea762014-07-16 05:16:52 +00002390 ParseDeclarationSpecifiers(DS, TemplateInfo, AS, DSC_class,
2391 &CommonLateParsedAttrs);
2392
2393 // Turn off colon protection that was set for declspec.
2394 X.restore();
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002395
Richard Smith404dfb42013-11-19 22:47:36 +00002396 // If we had a free-standing type definition with a missing semicolon, we
2397 // may get this far before the problem becomes obvious.
2398 if (DS.hasTagDefinition() &&
2399 TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate &&
2400 DiagnoseMissingSemiAfterTagDefinition(DS, AS, DSC_class,
2401 &CommonLateParsedAttrs))
David Blaikie0403cb12016-01-15 23:43:25 +00002402 return nullptr;
Richard Smith404dfb42013-11-19 22:47:36 +00002403
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002404 MultiTemplateParamsArg TemplateParams(
Craig Topper161e4db2014-05-21 06:02:52 +00002405 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->data()
2406 : nullptr,
John McCall11083da2009-09-16 22:47:08 +00002407 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->size() : 0);
2408
Alp Toker35d87032013-12-30 23:29:50 +00002409 if (TryConsumeToken(tok::semi)) {
Michael Handdc016d2012-11-28 23:17:40 +00002410 if (DS.isFriendSpecified())
2411 ProhibitAttributes(FnAttrs);
2412
Nico Weber7b837f52016-01-28 19:25:00 +00002413 RecordDecl *AnonRecord = nullptr;
2414 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(
2415 getCurScope(), AS, DS, TemplateParams, false, AnonRecord);
John McCall796c2a52010-07-16 08:13:16 +00002416 DS.complete(TheDecl);
Nico Weber7b837f52016-01-28 19:25:00 +00002417 if (AnonRecord) {
2418 Decl* decls[] = {AnonRecord, TheDecl};
2419 return Actions.BuildDeclaratorGroup(decls, /*TypeMayContainAuto=*/false);
2420 }
2421 return Actions.ConvertDeclToDeclGroup(TheDecl);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002422 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002423
John McCall28a6aea2009-11-04 02:18:39 +00002424 ParsingDeclarator DeclaratorInfo(*this, DS, Declarator::MemberContext);
Nico Weber24b2a822011-01-28 06:07:34 +00002425 VirtSpecifiers VS;
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002426
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002427 // Hold late-parsed attributes so we can attach a Decl to them later.
2428 LateParsedAttrList LateParsedAttrs;
2429
Douglas Gregor50cefbf2011-10-17 17:09:53 +00002430 SourceLocation EqualLoc;
Richard Smith9ba0fec2015-06-30 01:28:56 +00002431 SourceLocation PureSpecLoc;
2432
Yaron Keren180c1672015-06-30 07:35:19 +00002433 auto TryConsumePureSpecifier = [&] (bool AllowDefinition) {
Richard Smith9ba0fec2015-06-30 01:28:56 +00002434 if (Tok.isNot(tok::equal))
2435 return false;
2436
2437 auto &Zero = NextToken();
2438 SmallString<8> Buffer;
2439 if (Zero.isNot(tok::numeric_constant) || Zero.getLength() != 1 ||
2440 PP.getSpelling(Zero, Buffer) != "0")
2441 return false;
2442
2443 auto &After = GetLookAheadToken(2);
2444 if (!After.isOneOf(tok::semi, tok::comma) &&
2445 !(AllowDefinition &&
2446 After.isOneOf(tok::l_brace, tok::colon, tok::kw_try)))
2447 return false;
2448
2449 EqualLoc = ConsumeToken();
2450 PureSpecLoc = ConsumeToken();
2451 return true;
2452 };
Chris Lattner17c3b1f2009-12-10 01:59:24 +00002453
Richard Smith72553fc2014-01-23 23:53:27 +00002454 SmallVector<Decl *, 8> DeclsInGroup;
2455 ExprResult BitfieldSize;
2456 bool ExpectSemi = true;
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002457
Richard Smith72553fc2014-01-23 23:53:27 +00002458 // Parse the first declarator.
Nico Weberd89e6f72015-01-16 19:34:13 +00002459 if (ParseCXXMemberDeclaratorBeforeInitializer(
2460 DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs)) {
Richard Smith72553fc2014-01-23 23:53:27 +00002461 TryConsumeToken(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002462 return nullptr;
Richard Smith72553fc2014-01-23 23:53:27 +00002463 }
John Thompson5bc5cbe2009-11-25 22:58:06 +00002464
Richard Smith72553fc2014-01-23 23:53:27 +00002465 // Check for a member function definition.
Richard Smith4b5a9492014-01-24 22:34:35 +00002466 if (BitfieldSize.isUnset()) {
Richard Smith72553fc2014-01-23 23:53:27 +00002467 // MSVC permits pure specifier on inline functions defined at class scope.
Francois Pichet3abc9b82011-05-11 02:14:46 +00002468 // Hence check for =0 before checking for function definition.
Richard Smith9ba0fec2015-06-30 01:28:56 +00002469 if (getLangOpts().MicrosoftExt && DeclaratorInfo.isDeclarationOfFunction())
2470 TryConsumePureSpecifier(/*AllowDefinition*/ true);
Francois Pichet3abc9b82011-05-11 02:14:46 +00002471
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00002472 FunctionDefinitionKind DefinitionKind = FDK_Declaration;
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002473 // function-definition:
Richard Smith938f40b2011-06-11 17:19:42 +00002474 //
2475 // In C++11, a non-function declarator followed by an open brace is a
2476 // braced-init-list for an in-class member initialization, not an
2477 // erroneous function definition.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002478 if (Tok.is(tok::l_brace) && !getLangOpts().CPlusPlus11) {
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00002479 DefinitionKind = FDK_Definition;
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002480 } else if (DeclaratorInfo.isFunctionDeclarator()) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002481 if (Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try)) {
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00002482 DefinitionKind = FDK_Definition;
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002483 } else if (Tok.is(tok::equal)) {
2484 const Token &KW = NextToken();
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00002485 if (KW.is(tok::kw_default))
2486 DefinitionKind = FDK_Defaulted;
2487 else if (KW.is(tok::kw_delete))
2488 DefinitionKind = FDK_Deleted;
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002489 }
2490 }
Eli Bendersky41842222015-03-23 23:49:41 +00002491 DeclaratorInfo.setFunctionDefinitionKind(DefinitionKind);
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002492
Michael Handdc016d2012-11-28 23:17:40 +00002493 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
2494 // to a friend declaration, that declaration shall be a definition.
2495 if (DeclaratorInfo.isFunctionDeclarator() &&
2496 DefinitionKind != FDK_Definition && DS.isFriendSpecified()) {
2497 // Diagnose attributes that appear before decl specifier:
2498 // [[]] friend int foo();
2499 ProhibitAttributes(FnAttrs);
2500 }
2501
Nico Webera7f137d2015-01-16 19:35:01 +00002502 if (DefinitionKind != FDK_Declaration) {
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002503 if (!DeclaratorInfo.isFunctionDeclarator()) {
Richard Trieu0d730542012-01-21 02:59:18 +00002504 Diag(DeclaratorInfo.getIdentifierLoc(), diag::err_func_def_no_params);
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002505 ConsumeBrace();
Alexey Bataevee6507d2013-11-18 08:17:37 +00002506 SkipUntil(tok::r_brace);
Michael Handdc016d2012-11-28 23:17:40 +00002507
Douglas Gregor8a4db832011-01-19 16:41:58 +00002508 // Consume the optional ';'
Alp Toker35d87032013-12-30 23:29:50 +00002509 TryConsumeToken(tok::semi);
2510
David Blaikie0403cb12016-01-15 23:43:25 +00002511 return nullptr;
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002512 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002513
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002514 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
Richard Trieu0d730542012-01-21 02:59:18 +00002515 Diag(DeclaratorInfo.getIdentifierLoc(),
2516 diag::err_function_declared_typedef);
Douglas Gregor8a4db832011-01-19 16:41:58 +00002517
Richard Smith2603b092012-11-15 22:54:20 +00002518 // Recover by treating the 'typedef' as spurious.
2519 DS.ClearStorageClassSpecs();
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002520 }
2521
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002522 Decl *FunDecl =
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00002523 ParseCXXInlineMethodDef(AS, AccessAttrs, DeclaratorInfo, TemplateInfo,
Richard Smith9ba0fec2015-06-30 01:28:56 +00002524 VS, PureSpecLoc);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002525
David Majnemer23252a32013-08-01 04:22:55 +00002526 if (FunDecl) {
2527 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i) {
2528 CommonLateParsedAttrs[i]->addDecl(FunDecl);
2529 }
2530 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i) {
2531 LateParsedAttrs[i]->addDecl(FunDecl);
2532 }
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002533 }
2534 LateParsedAttrs.clear();
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002535
2536 // Consume the ';' - it's optional unless we have a delete or default
Richard Trieu2f7dc462012-05-16 19:04:59 +00002537 if (Tok.is(tok::semi))
Richard Smith87f5dc52012-07-23 05:45:25 +00002538 ConsumeExtraSemi(AfterMemberFunctionDefinition);
Douglas Gregor8a4db832011-01-19 16:41:58 +00002539
Alexey Bataev05c25d62015-07-31 08:42:25 +00002540 return DeclGroupPtrTy::make(DeclGroupRef(FunDecl));
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002541 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002542 }
2543
2544 // member-declarator-list:
2545 // member-declarator
2546 // member-declarator-list ',' member-declarator
2547
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002548 while (1) {
Richard Smith2b013182012-06-10 03:12:00 +00002549 InClassInitStyle HasInClassInit = ICIS_NoInit;
Richard Smith9ba0fec2015-06-30 01:28:56 +00002550 bool HasStaticInitializer = false;
2551 if (Tok.isOneOf(tok::equal, tok::l_brace) && PureSpecLoc.isInvalid()) {
Richard Smith938f40b2011-06-11 17:19:42 +00002552 if (BitfieldSize.get()) {
2553 Diag(Tok, diag::err_bitfield_member_init);
Alexey Bataevee6507d2013-11-18 08:17:37 +00002554 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
Richard Smith9ba0fec2015-06-30 01:28:56 +00002555 } else if (DeclaratorInfo.isDeclarationOfFunction()) {
2556 // It's a pure-specifier.
2557 if (!TryConsumePureSpecifier(/*AllowFunctionDefinition*/ false))
2558 // Parse it as an expression so that Sema can diagnose it.
2559 HasStaticInitializer = true;
2560 } else if (DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2561 DeclSpec::SCS_static &&
2562 DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2563 DeclSpec::SCS_typedef &&
2564 !DS.isFriendSpecified()) {
2565 // It's a default member initializer.
2566 HasInClassInit = Tok.is(tok::equal) ? ICIS_CopyInit : ICIS_ListInit;
Richard Smith938f40b2011-06-11 17:19:42 +00002567 } else {
Richard Smith9ba0fec2015-06-30 01:28:56 +00002568 HasStaticInitializer = true;
Richard Smith938f40b2011-06-11 17:19:42 +00002569 }
2570 }
2571
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002572 // NOTE: If Sema is the Action module and declarator is an instance field,
Chris Lattner5bbb3c82009-03-29 16:50:03 +00002573 // this call will *not* return the created decl; It will return null.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002574 // See Sema::ActOnCXXMemberDeclarator for details.
John McCall07e91c02009-08-06 02:15:43 +00002575
Craig Topper161e4db2014-05-21 06:02:52 +00002576 NamedDecl *ThisDecl = nullptr;
John McCall07e91c02009-08-06 02:15:43 +00002577 if (DS.isFriendSpecified()) {
Richard Smith72553fc2014-01-23 23:53:27 +00002578 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
Michael Handdc016d2012-11-28 23:17:40 +00002579 // to a friend declaration, that declaration shall be a definition.
2580 //
Richard Smith72553fc2014-01-23 23:53:27 +00002581 // Diagnose attributes that appear in a friend member function declarator:
2582 // friend int foo [[]] ();
Michael Handdc016d2012-11-28 23:17:40 +00002583 SmallVector<SourceRange, 4> Ranges;
2584 DeclaratorInfo.getCXX11AttributeRanges(Ranges);
Richard Smith72553fc2014-01-23 23:53:27 +00002585 for (SmallVectorImpl<SourceRange>::iterator I = Ranges.begin(),
2586 E = Ranges.end(); I != E; ++I)
2587 Diag((*I).getBegin(), diag::err_attributes_not_allowed) << *I;
Michael Handdc016d2012-11-28 23:17:40 +00002588
Douglas Gregor0be31a22010-07-02 17:43:08 +00002589 ThisDecl = Actions.ActOnFriendFunctionDecl(getCurScope(), DeclaratorInfo,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002590 TemplateParams);
Douglas Gregor3447e762009-08-20 22:52:58 +00002591 } else {
Douglas Gregor0be31a22010-07-02 17:43:08 +00002592 ThisDecl = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS,
John McCall07e91c02009-08-06 02:15:43 +00002593 DeclaratorInfo,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002594 TemplateParams,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002595 BitfieldSize.get(),
Richard Smith2b013182012-06-10 03:12:00 +00002596 VS, HasInClassInit);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002597
2598 if (VarTemplateDecl *VT =
Craig Topper161e4db2014-05-21 06:02:52 +00002599 ThisDecl ? dyn_cast<VarTemplateDecl>(ThisDecl) : nullptr)
Larisse Voufo39a1e502013-08-06 01:03:05 +00002600 // Re-direct this decl to refer to the templated decl so that we can
2601 // initialize it.
2602 ThisDecl = VT->getTemplatedDecl();
2603
David Majnemer23252a32013-08-01 04:22:55 +00002604 if (ThisDecl && AccessAttrs)
Richard Smithf8a75c32013-08-29 00:47:48 +00002605 Actions.ProcessDeclAttributeList(getCurScope(), ThisDecl, AccessAttrs);
Douglas Gregor3447e762009-08-20 22:52:58 +00002606 }
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002607
Richard Smith9ba0fec2015-06-30 01:28:56 +00002608 // Error recovery might have converted a non-static member into a static
2609 // member.
David Blaikie35506f82013-01-30 01:22:18 +00002610 if (HasInClassInit != ICIS_NoInit &&
Richard Smith9ba0fec2015-06-30 01:28:56 +00002611 DeclaratorInfo.getDeclSpec().getStorageClassSpec() ==
2612 DeclSpec::SCS_static) {
2613 HasInClassInit = ICIS_NoInit;
2614 HasStaticInitializer = true;
2615 }
2616
2617 if (ThisDecl && PureSpecLoc.isValid())
2618 Actions.ActOnPureSpecifier(ThisDecl, PureSpecLoc);
2619
2620 // Handle the initializer.
2621 if (HasInClassInit != ICIS_NoInit) {
Douglas Gregor728d00b2011-10-10 14:49:18 +00002622 // The initializer was deferred; parse it and cache the tokens.
David Majnemer23252a32013-08-01 04:22:55 +00002623 Diag(Tok, getLangOpts().CPlusPlus11
2624 ? diag::warn_cxx98_compat_nonstatic_member_init
2625 : diag::ext_nonstatic_member_init);
Richard Smith5d164bc2011-10-15 05:09:34 +00002626
Richard Smith938f40b2011-06-11 17:19:42 +00002627 if (DeclaratorInfo.isArrayOfUnknownBound()) {
Richard Smith2b013182012-06-10 03:12:00 +00002628 // C++11 [dcl.array]p3: An array bound may also be omitted when the
2629 // declarator is followed by an initializer.
Richard Smith938f40b2011-06-11 17:19:42 +00002630 //
2631 // A brace-or-equal-initializer for a member-declarator is not an
David Blaikiecdd91db2012-02-14 09:00:46 +00002632 // initializer in the grammar, so this is ill-formed.
Richard Smith938f40b2011-06-11 17:19:42 +00002633 Diag(Tok, diag::err_incomplete_array_member_init);
Alexey Bataevee6507d2013-11-18 08:17:37 +00002634 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
David Majnemer23252a32013-08-01 04:22:55 +00002635
2636 // Avoid later warnings about a class member of incomplete type.
David Blaikiecdd91db2012-02-14 09:00:46 +00002637 if (ThisDecl)
David Blaikiecdd91db2012-02-14 09:00:46 +00002638 ThisDecl->setInvalidDecl();
Richard Smith938f40b2011-06-11 17:19:42 +00002639 } else
2640 ParseCXXNonStaticMemberInitializer(ThisDecl);
Richard Smith9ba0fec2015-06-30 01:28:56 +00002641 } else if (HasStaticInitializer) {
Douglas Gregor728d00b2011-10-10 14:49:18 +00002642 // Normal initializer.
Richard Smith9ba0fec2015-06-30 01:28:56 +00002643 ExprResult Init = ParseCXXMemberInitializer(
2644 ThisDecl, DeclaratorInfo.isDeclarationOfFunction(), EqualLoc);
David Majnemer23252a32013-08-01 04:22:55 +00002645
Douglas Gregor728d00b2011-10-10 14:49:18 +00002646 if (Init.isInvalid())
Alexey Bataevee6507d2013-11-18 08:17:37 +00002647 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
Douglas Gregor728d00b2011-10-10 14:49:18 +00002648 else if (ThisDecl)
Sebastian Redleef474c2012-02-22 10:50:08 +00002649 Actions.AddInitializerToDecl(ThisDecl, Init.get(), EqualLoc.isInvalid(),
Richard Smith74aeef52013-04-26 16:15:35 +00002650 DS.containsPlaceholderType());
David Majnemer23252a32013-08-01 04:22:55 +00002651 } else if (ThisDecl && DS.getStorageClassSpec() == DeclSpec::SCS_static)
Douglas Gregor728d00b2011-10-10 14:49:18 +00002652 // No initializer.
Richard Smith74aeef52013-04-26 16:15:35 +00002653 Actions.ActOnUninitializedDecl(ThisDecl, DS.containsPlaceholderType());
David Majnemer23252a32013-08-01 04:22:55 +00002654
Douglas Gregor728d00b2011-10-10 14:49:18 +00002655 if (ThisDecl) {
David Majnemer23252a32013-08-01 04:22:55 +00002656 if (!ThisDecl->isInvalidDecl()) {
2657 // Set the Decl for any late parsed attributes
2658 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i)
2659 CommonLateParsedAttrs[i]->addDecl(ThisDecl);
2660
2661 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i)
2662 LateParsedAttrs[i]->addDecl(ThisDecl);
2663 }
Douglas Gregor728d00b2011-10-10 14:49:18 +00002664 Actions.FinalizeDeclaration(ThisDecl);
2665 DeclsInGroup.push_back(ThisDecl);
David Majnemer23252a32013-08-01 04:22:55 +00002666
2667 if (DeclaratorInfo.isFunctionDeclarator() &&
2668 DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2669 DeclSpec::SCS_typedef)
2670 HandleMemberFunctionDeclDelays(DeclaratorInfo, ThisDecl);
Douglas Gregor728d00b2011-10-10 14:49:18 +00002671 }
David Majnemer23252a32013-08-01 04:22:55 +00002672 LateParsedAttrs.clear();
Douglas Gregor728d00b2011-10-10 14:49:18 +00002673
2674 DeclaratorInfo.complete(ThisDecl);
Richard Smith938f40b2011-06-11 17:19:42 +00002675
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002676 // If we don't have a comma, it is either the end of the list (a ';')
2677 // or an error, bail out.
Alp Toker094e5212014-01-05 03:27:11 +00002678 SourceLocation CommaLoc;
2679 if (!TryConsumeToken(tok::comma, CommaLoc))
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002680 break;
Mike Stump11289f42009-09-09 15:08:12 +00002681
Richard Smithc8a79032012-01-09 22:31:44 +00002682 if (Tok.isAtStartOfLine() &&
2683 !MightBeDeclarator(Declarator::MemberContext)) {
2684 // This comma was followed by a line-break and something which can't be
2685 // the start of a declarator. The comma was probably a typo for a
2686 // semicolon.
2687 Diag(CommaLoc, diag::err_expected_semi_declaration)
2688 << FixItHint::CreateReplacement(CommaLoc, ";");
2689 ExpectSemi = false;
2690 break;
2691 }
Mike Stump11289f42009-09-09 15:08:12 +00002692
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002693 // Parse the next declarator.
2694 DeclaratorInfo.clear();
Nico Weber24b2a822011-01-28 06:07:34 +00002695 VS.clear();
Nico Weberf56c85b2015-01-17 02:26:40 +00002696 BitfieldSize = ExprResult(/*Invalid=*/false);
Richard Smith9ba0fec2015-06-30 01:28:56 +00002697 EqualLoc = PureSpecLoc = SourceLocation();
Richard Smith8d06f422012-01-12 23:53:29 +00002698 DeclaratorInfo.setCommaLoc(CommaLoc);
Mike Stump11289f42009-09-09 15:08:12 +00002699
Richard Smith72553fc2014-01-23 23:53:27 +00002700 // GNU attributes are allowed before the second and subsequent declarator.
John McCall53fa7142010-12-24 02:08:15 +00002701 MaybeParseGNUAttributes(DeclaratorInfo);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002702
Nico Weberd89e6f72015-01-16 19:34:13 +00002703 if (ParseCXXMemberDeclaratorBeforeInitializer(
2704 DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs))
2705 break;
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002706 }
2707
Richard Smithc8a79032012-01-09 22:31:44 +00002708 if (ExpectSemi &&
2709 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list)) {
Chris Lattner916dbf12010-02-02 00:43:15 +00002710 // Skip to end of block or statement.
Alexey Bataevee6507d2013-11-18 08:17:37 +00002711 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Chris Lattner916dbf12010-02-02 00:43:15 +00002712 // If we stopped at a ';', eat it.
Alp Toker35d87032013-12-30 23:29:50 +00002713 TryConsumeToken(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002714 return nullptr;
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002715 }
2716
Alexey Bataev05c25d62015-07-31 08:42:25 +00002717 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002718}
2719
Richard Smith9ba0fec2015-06-30 01:28:56 +00002720/// ParseCXXMemberInitializer - Parse the brace-or-equal-initializer.
2721/// Also detect and reject any attempted defaulted/deleted function definition.
2722/// The location of the '=', if any, will be placed in EqualLoc.
Richard Smith938f40b2011-06-11 17:19:42 +00002723///
Richard Smith9ba0fec2015-06-30 01:28:56 +00002724/// This does not check for a pure-specifier; that's handled elsewhere.
Sebastian Redleef474c2012-02-22 10:50:08 +00002725///
Richard Smith938f40b2011-06-11 17:19:42 +00002726/// brace-or-equal-initializer:
2727/// '=' initializer-expression
Sebastian Redleef474c2012-02-22 10:50:08 +00002728/// braced-init-list
2729///
Richard Smith938f40b2011-06-11 17:19:42 +00002730/// initializer-clause:
2731/// assignment-expression
Sebastian Redleef474c2012-02-22 10:50:08 +00002732/// braced-init-list
2733///
Richard Smithda35e962013-11-09 04:52:51 +00002734/// defaulted/deleted function-definition:
Richard Smith938f40b2011-06-11 17:19:42 +00002735/// '=' 'default'
2736/// '=' 'delete'
2737///
2738/// Prior to C++0x, the assignment-expression in an initializer-clause must
2739/// be a constant-expression.
Douglas Gregor926410d2012-02-21 02:22:07 +00002740ExprResult Parser::ParseCXXMemberInitializer(Decl *D, bool IsFunction,
Richard Smith938f40b2011-06-11 17:19:42 +00002741 SourceLocation &EqualLoc) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002742 assert(Tok.isOneOf(tok::equal, tok::l_brace)
Richard Smith938f40b2011-06-11 17:19:42 +00002743 && "Data member initializer not starting with '=' or '{'");
2744
Douglas Gregor926410d2012-02-21 02:22:07 +00002745 EnterExpressionEvaluationContext Context(Actions,
2746 Sema::PotentiallyEvaluated,
2747 D);
Alp Toker094e5212014-01-05 03:27:11 +00002748 if (TryConsumeToken(tok::equal, EqualLoc)) {
Richard Smith938f40b2011-06-11 17:19:42 +00002749 if (Tok.is(tok::kw_delete)) {
2750 // In principle, an initializer of '= delete p;' is legal, but it will
2751 // never type-check. It's better to diagnose it as an ill-formed expression
2752 // than as an ill-formed deleted non-function member.
2753 // An initializer of '= delete p, foo' will never be parsed, because
2754 // a top-level comma always ends the initializer expression.
2755 const Token &Next = NextToken();
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002756 if (IsFunction || Next.isOneOf(tok::semi, tok::comma, tok::eof)) {
Richard Smith938f40b2011-06-11 17:19:42 +00002757 if (IsFunction)
2758 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2759 << 1 /* delete */;
2760 else
2761 Diag(ConsumeToken(), diag::err_deleted_non_function);
Richard Smithedcb26e2014-06-11 00:49:52 +00002762 return ExprError();
Richard Smith938f40b2011-06-11 17:19:42 +00002763 }
2764 } else if (Tok.is(tok::kw_default)) {
Richard Smith938f40b2011-06-11 17:19:42 +00002765 if (IsFunction)
2766 Diag(Tok, diag::err_default_delete_in_multiple_declaration)
2767 << 0 /* default */;
2768 else
2769 Diag(ConsumeToken(), diag::err_default_special_members);
Richard Smithedcb26e2014-06-11 00:49:52 +00002770 return ExprError();
Richard Smith938f40b2011-06-11 17:19:42 +00002771 }
David Majnemer87ff66c2014-12-13 11:34:16 +00002772 }
2773 if (const auto *PD = dyn_cast_or_null<MSPropertyDecl>(D)) {
2774 Diag(Tok, diag::err_ms_property_initializer) << PD;
2775 return ExprError();
Sebastian Redleef474c2012-02-22 10:50:08 +00002776 }
2777 return ParseInitializer();
Richard Smith938f40b2011-06-11 17:19:42 +00002778}
2779
Richard Smith65ebb4a2015-03-26 04:09:53 +00002780void Parser::SkipCXXMemberSpecification(SourceLocation RecordLoc,
2781 SourceLocation AttrFixitLoc,
2782 unsigned TagType, Decl *TagDecl) {
2783 // Skip the optional 'final' keyword.
2784 if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
2785 assert(isCXX11FinalKeyword() && "not a class definition");
2786 ConsumeToken();
2787
2788 // Diagnose any C++11 attributes after 'final' keyword.
2789 // We deliberately discard these attributes.
2790 ParsedAttributesWithRange Attrs(AttrFactory);
2791 CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
2792
2793 // This can only happen if we had malformed misplaced attributes;
2794 // we only get called if there is a colon or left-brace after the
2795 // attributes.
2796 if (Tok.isNot(tok::colon) && Tok.isNot(tok::l_brace))
2797 return;
2798 }
2799
2800 // Skip the base clauses. This requires actually parsing them, because
2801 // otherwise we can't be sure where they end (a left brace may appear
2802 // within a template argument).
2803 if (Tok.is(tok::colon)) {
2804 // Enter the scope of the class so that we can correctly parse its bases.
2805 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
2806 ParsingClassDefinition ParsingDef(*this, TagDecl, /*NonNestedClass*/ true,
2807 TagType == DeclSpec::TST_interface);
Richard Smith0f192e82015-06-11 22:48:25 +00002808 auto OldContext =
2809 Actions.ActOnTagStartSkippedDefinition(getCurScope(), TagDecl);
Richard Smith65ebb4a2015-03-26 04:09:53 +00002810
2811 // Parse the bases but don't attach them to the class.
2812 ParseBaseClause(nullptr);
2813
Richard Smith0f192e82015-06-11 22:48:25 +00002814 Actions.ActOnTagFinishSkippedDefinition(OldContext);
Richard Smith65ebb4a2015-03-26 04:09:53 +00002815
2816 if (!Tok.is(tok::l_brace)) {
2817 Diag(PP.getLocForEndOfToken(PrevTokLocation),
2818 diag::err_expected_lbrace_after_base_specifiers);
2819 return;
2820 }
2821 }
2822
2823 // Skip the body.
2824 assert(Tok.is(tok::l_brace));
2825 BalancedDelimiterTracker T(*this, tok::l_brace);
2826 T.consumeOpen();
2827 T.skipToEnd();
Richard Smith04c6c1f2015-07-01 18:56:50 +00002828
2829 // Parse and discard any trailing attributes.
2830 ParsedAttributes Attrs(AttrFactory);
2831 if (Tok.is(tok::kw___attribute))
2832 MaybeParseGNUAttributes(Attrs);
Richard Smith65ebb4a2015-03-26 04:09:53 +00002833}
2834
Alexey Bataev05c25d62015-07-31 08:42:25 +00002835Parser::DeclGroupPtrTy Parser::ParseCXXClassMemberDeclarationWithPragmas(
2836 AccessSpecifier &AS, ParsedAttributesWithRange &AccessAttrs,
2837 DeclSpec::TST TagType, Decl *TagDecl) {
2838 if (getLangOpts().MicrosoftExt &&
2839 Tok.isOneOf(tok::kw___if_exists, tok::kw___if_not_exists)) {
2840 ParseMicrosoftIfExistsClassDeclaration(TagType, AS);
David Blaikie0403cb12016-01-15 23:43:25 +00002841 return nullptr;
Alexey Bataev05c25d62015-07-31 08:42:25 +00002842 }
2843
2844 // Check for extraneous top-level semicolon.
2845 if (Tok.is(tok::semi)) {
2846 ConsumeExtraSemi(InsideStruct, TagType);
David Blaikie0403cb12016-01-15 23:43:25 +00002847 return nullptr;
Alexey Bataev05c25d62015-07-31 08:42:25 +00002848 }
2849
2850 if (Tok.is(tok::annot_pragma_vis)) {
2851 HandlePragmaVisibility();
David Blaikie0403cb12016-01-15 23:43:25 +00002852 return nullptr;
Alexey Bataev05c25d62015-07-31 08:42:25 +00002853 }
2854
2855 if (Tok.is(tok::annot_pragma_pack)) {
2856 HandlePragmaPack();
David Blaikie0403cb12016-01-15 23:43:25 +00002857 return nullptr;
Alexey Bataev05c25d62015-07-31 08:42:25 +00002858 }
2859
2860 if (Tok.is(tok::annot_pragma_align)) {
2861 HandlePragmaAlign();
David Blaikie0403cb12016-01-15 23:43:25 +00002862 return nullptr;
Alexey Bataev05c25d62015-07-31 08:42:25 +00002863 }
2864
2865 if (Tok.is(tok::annot_pragma_ms_pointers_to_members)) {
2866 HandlePragmaMSPointersToMembers();
David Blaikie0403cb12016-01-15 23:43:25 +00002867 return nullptr;
Alexey Bataev05c25d62015-07-31 08:42:25 +00002868 }
2869
2870 if (Tok.is(tok::annot_pragma_ms_pragma)) {
2871 HandlePragmaMSPragma();
David Blaikie0403cb12016-01-15 23:43:25 +00002872 return nullptr;
Alexey Bataev05c25d62015-07-31 08:42:25 +00002873 }
2874
Alexey Bataev3d42f342015-11-20 07:02:57 +00002875 if (Tok.is(tok::annot_pragma_ms_vtordisp)) {
2876 HandlePragmaMSVtorDisp();
David Blaikie0403cb12016-01-15 23:43:25 +00002877 return nullptr;
Alexey Bataev3d42f342015-11-20 07:02:57 +00002878 }
2879
Alexey Bataev05c25d62015-07-31 08:42:25 +00002880 // If we see a namespace here, a close brace was missing somewhere.
2881 if (Tok.is(tok::kw_namespace)) {
2882 DiagnoseUnexpectedNamespace(cast<NamedDecl>(TagDecl));
David Blaikie0403cb12016-01-15 23:43:25 +00002883 return nullptr;
Alexey Bataev05c25d62015-07-31 08:42:25 +00002884 }
2885
2886 AccessSpecifier NewAS = getAccessSpecifierIfPresent();
2887 if (NewAS != AS_none) {
2888 // Current token is a C++ access specifier.
2889 AS = NewAS;
2890 SourceLocation ASLoc = Tok.getLocation();
2891 unsigned TokLength = Tok.getLength();
2892 ConsumeToken();
2893 AccessAttrs.clear();
2894 MaybeParseGNUAttributes(AccessAttrs);
2895
2896 SourceLocation EndLoc;
2897 if (TryConsumeToken(tok::colon, EndLoc)) {
2898 } else if (TryConsumeToken(tok::semi, EndLoc)) {
2899 Diag(EndLoc, diag::err_expected)
2900 << tok::colon << FixItHint::CreateReplacement(EndLoc, ":");
2901 } else {
2902 EndLoc = ASLoc.getLocWithOffset(TokLength);
2903 Diag(EndLoc, diag::err_expected)
2904 << tok::colon << FixItHint::CreateInsertion(EndLoc, ":");
2905 }
2906
2907 // The Microsoft extension __interface does not permit non-public
2908 // access specifiers.
2909 if (TagType == DeclSpec::TST_interface && AS != AS_public) {
2910 Diag(ASLoc, diag::err_access_specifier_interface) << (AS == AS_protected);
2911 }
2912
2913 if (Actions.ActOnAccessSpecifier(NewAS, ASLoc, EndLoc,
2914 AccessAttrs.getList())) {
2915 // found another attribute than only annotations
2916 AccessAttrs.clear();
2917 }
2918
David Blaikie0403cb12016-01-15 23:43:25 +00002919 return nullptr;
Alexey Bataev05c25d62015-07-31 08:42:25 +00002920 }
2921
2922 if (Tok.is(tok::annot_pragma_openmp))
Alexey Bataev587e1de2016-03-30 10:43:55 +00002923 return ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, AccessAttrs, TagType,
2924 TagDecl);
Alexey Bataev05c25d62015-07-31 08:42:25 +00002925
2926 // Parse all the comma separated declarators.
2927 return ParseCXXClassMemberDeclaration(AS, AccessAttrs.getList());
2928}
2929
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002930/// ParseCXXMemberSpecification - Parse the class definition.
2931///
2932/// member-specification:
2933/// member-declaration member-specification[opt]
2934/// access-specifier ':' member-specification[opt]
2935///
Joao Matose9a3ed42012-08-31 22:18:20 +00002936void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc,
Michael Han309af292013-01-07 16:57:11 +00002937 SourceLocation AttrFixitLoc,
Richard Smith4c96e992013-02-19 23:47:15 +00002938 ParsedAttributesWithRange &Attrs,
Joao Matose9a3ed42012-08-31 22:18:20 +00002939 unsigned TagType, Decl *TagDecl) {
2940 assert((TagType == DeclSpec::TST_struct ||
2941 TagType == DeclSpec::TST_interface ||
2942 TagType == DeclSpec::TST_union ||
2943 TagType == DeclSpec::TST_class) && "Invalid TagType!");
2944
John McCallfaf5fb42010-08-26 23:41:50 +00002945 PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc,
2946 "parsing struct/union/class body");
Mike Stump11289f42009-09-09 15:08:12 +00002947
Douglas Gregoredf8f392010-01-16 20:52:59 +00002948 // Determine whether this is a non-nested class. Note that local
2949 // classes are *not* considered to be nested classes.
2950 bool NonNestedClass = true;
2951 if (!ClassStack.empty()) {
Douglas Gregor0be31a22010-07-02 17:43:08 +00002952 for (const Scope *S = getCurScope(); S; S = S->getParent()) {
Douglas Gregoredf8f392010-01-16 20:52:59 +00002953 if (S->isClassScope()) {
2954 // We're inside a class scope, so this is a nested class.
2955 NonNestedClass = false;
John McCalldb632ac2012-09-25 07:32:39 +00002956
2957 // The Microsoft extension __interface does not permit nested classes.
2958 if (getCurrentClass().IsInterface) {
2959 Diag(RecordLoc, diag::err_invalid_member_in_interface)
2960 << /*ErrorType=*/6
2961 << (isa<NamedDecl>(TagDecl)
2962 ? cast<NamedDecl>(TagDecl)->getQualifiedNameAsString()
David Blaikieabe1a392014-04-02 05:58:29 +00002963 : "(anonymous)");
John McCalldb632ac2012-09-25 07:32:39 +00002964 }
Douglas Gregoredf8f392010-01-16 20:52:59 +00002965 break;
2966 }
2967
Serge Pavlovd9c0bcf2015-07-14 10:02:10 +00002968 if ((S->getFlags() & Scope::FnScope))
2969 // If we're in a function or function template then this is a local
2970 // class rather than a nested class.
2971 break;
Douglas Gregoredf8f392010-01-16 20:52:59 +00002972 }
2973 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002974
2975 // Enter a scope for the class.
Douglas Gregor658b9552009-01-09 22:42:13 +00002976 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002977
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002978 // Note that we are parsing a new (potentially-nested) class definition.
John McCalldb632ac2012-09-25 07:32:39 +00002979 ParsingClassDefinition ParsingDef(*this, TagDecl, NonNestedClass,
2980 TagType == DeclSpec::TST_interface);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002981
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002982 if (TagDecl)
Douglas Gregor0be31a22010-07-02 17:43:08 +00002983 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
John McCall2d814c32009-12-19 21:48:58 +00002984
Anders Carlssonf9eb63b2011-03-25 14:46:08 +00002985 SourceLocation FinalLoc;
David Majnemera5433082013-10-18 00:33:31 +00002986 bool IsFinalSpelledSealed = false;
Anders Carlssonf9eb63b2011-03-25 14:46:08 +00002987
2988 // Parse the optional 'final' keyword.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002989 if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
David Majnemera5433082013-10-18 00:33:31 +00002990 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier(Tok);
2991 assert((Specifier == VirtSpecifiers::VS_Final ||
2992 Specifier == VirtSpecifiers::VS_Sealed) &&
2993 "not a class definition");
Richard Smithda261112011-10-15 04:21:46 +00002994 FinalLoc = ConsumeToken();
David Majnemera5433082013-10-18 00:33:31 +00002995 IsFinalSpelledSealed = Specifier == VirtSpecifiers::VS_Sealed;
Anders Carlssonf9eb63b2011-03-25 14:46:08 +00002996
David Majnemera5433082013-10-18 00:33:31 +00002997 if (TagType == DeclSpec::TST_interface)
John McCalldb632ac2012-09-25 07:32:39 +00002998 Diag(FinalLoc, diag::err_override_control_interface)
David Majnemera5433082013-10-18 00:33:31 +00002999 << VirtSpecifiers::getSpecifierName(Specifier);
3000 else if (Specifier == VirtSpecifiers::VS_Final)
3001 Diag(FinalLoc, getLangOpts().CPlusPlus11
3002 ? diag::warn_cxx98_compat_override_control_keyword
3003 : diag::ext_override_control_keyword)
3004 << VirtSpecifiers::getSpecifierName(Specifier);
3005 else if (Specifier == VirtSpecifiers::VS_Sealed)
3006 Diag(FinalLoc, diag::ext_ms_sealed_keyword);
Michael Han9407e502012-11-26 22:54:45 +00003007
Michael Han309af292013-01-07 16:57:11 +00003008 // Parse any C++11 attributes after 'final' keyword.
3009 // These attributes are not allowed to appear here,
3010 // and the only possible place for them to appertain
3011 // to the class would be between class-key and class-name.
Richard Smith4c96e992013-02-19 23:47:15 +00003012 CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
Nico Weber4b4be842014-12-29 06:56:50 +00003013
3014 // ParseClassSpecifier() does only a superficial check for attributes before
3015 // deciding to call this method. For example, for
3016 // `class C final alignas ([l) {` it will decide that this looks like a
3017 // misplaced attribute since it sees `alignas '(' ')'`. But the actual
3018 // attribute parsing code will try to parse the '[' as a constexpr lambda
3019 // and consume enough tokens that the alignas parsing code will eat the
3020 // opening '{'. So bail out if the next token isn't one we expect.
Nico Weber36de3a22014-12-29 21:56:22 +00003021 if (!Tok.is(tok::colon) && !Tok.is(tok::l_brace)) {
3022 if (TagDecl)
3023 Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
Nico Weber4b4be842014-12-29 06:56:50 +00003024 return;
Nico Weber36de3a22014-12-29 21:56:22 +00003025 }
Anders Carlssonf9eb63b2011-03-25 14:46:08 +00003026 }
Anders Carlsson4b63d0e2011-01-22 16:56:46 +00003027
John McCall2d814c32009-12-19 21:48:58 +00003028 if (Tok.is(tok::colon)) {
3029 ParseBaseClause(TagDecl);
John McCall2d814c32009-12-19 21:48:58 +00003030 if (!Tok.is(tok::l_brace)) {
Ismail Pazarbasi129c44c2014-09-25 21:13:02 +00003031 bool SuggestFixIt = false;
3032 SourceLocation BraceLoc = PP.getLocForEndOfToken(PrevTokLocation);
3033 if (Tok.isAtStartOfLine()) {
3034 switch (Tok.getKind()) {
3035 case tok::kw_private:
3036 case tok::kw_protected:
3037 case tok::kw_public:
3038 SuggestFixIt = NextToken().getKind() == tok::colon;
3039 break;
3040 case tok::kw_static_assert:
3041 case tok::r_brace:
3042 case tok::kw_using:
3043 // base-clause can have simple-template-id; 'template' can't be there
3044 case tok::kw_template:
3045 SuggestFixIt = true;
3046 break;
3047 case tok::identifier:
3048 SuggestFixIt = isConstructorDeclarator(true);
3049 break;
3050 default:
3051 SuggestFixIt = isCXXSimpleDeclaration(/*AllowForRangeDecl=*/false);
3052 break;
3053 }
3054 }
3055 DiagnosticBuilder LBraceDiag =
3056 Diag(BraceLoc, diag::err_expected_lbrace_after_base_specifiers);
3057 if (SuggestFixIt) {
3058 LBraceDiag << FixItHint::CreateInsertion(BraceLoc, " {");
3059 // Try recovering from missing { after base-clause.
3060 PP.EnterToken(Tok);
3061 Tok.setKind(tok::l_brace);
3062 } else {
3063 if (TagDecl)
3064 Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
3065 return;
3066 }
John McCall2d814c32009-12-19 21:48:58 +00003067 }
3068 }
3069
3070 assert(Tok.is(tok::l_brace));
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003071 BalancedDelimiterTracker T(*this, tok::l_brace);
3072 T.consumeOpen();
John McCall2d814c32009-12-19 21:48:58 +00003073
John McCall08bede42010-05-28 08:11:17 +00003074 if (TagDecl)
Anders Carlsson30f29442011-03-25 14:31:08 +00003075 Actions.ActOnStartCXXMemberDeclarations(getCurScope(), TagDecl, FinalLoc,
David Majnemera5433082013-10-18 00:33:31 +00003076 IsFinalSpelledSealed,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003077 T.getOpenLocation());
John McCall1c7e6ec2009-12-20 07:58:13 +00003078
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003079 // C++ 11p3: Members of a class defined with the keyword class are private
3080 // by default. Members of a class defined with the keywords struct or union
3081 // are public by default.
3082 AccessSpecifier CurAS;
3083 if (TagType == DeclSpec::TST_class)
3084 CurAS = AS_private;
3085 else
3086 CurAS = AS_public;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003087 ParsedAttributesWithRange AccessAttrs(AttrFactory);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003088
Douglas Gregor9377c822010-06-21 22:31:09 +00003089 if (TagDecl) {
3090 // While we still have something to read, read the member-declarations.
Richard Smith752ada82015-11-17 23:32:01 +00003091 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
3092 Tok.isNot(tok::eof)) {
Douglas Gregor9377c822010-06-21 22:31:09 +00003093 // Each iteration of this loop reads one member-declaration.
Alexey Bataev05c25d62015-07-31 08:42:25 +00003094 ParseCXXClassMemberDeclarationWithPragmas(
3095 CurAS, AccessAttrs, static_cast<DeclSpec::TST>(TagType), TagDecl);
Serge Pavlovc4e04a22015-09-19 05:32:57 +00003096 }
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003097 T.consumeClose();
Douglas Gregor9377c822010-06-21 22:31:09 +00003098 } else {
Alexey Bataevee6507d2013-11-18 08:17:37 +00003099 SkipUntil(tok::r_brace);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003100 }
Mike Stump11289f42009-09-09 15:08:12 +00003101
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003102 // If attributes exist after class contents, parse them.
John McCall084e83d2011-03-24 11:26:52 +00003103 ParsedAttributes attrs(AttrFactory);
John McCall53fa7142010-12-24 02:08:15 +00003104 MaybeParseGNUAttributes(attrs);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003105
John McCall08bede42010-05-28 08:11:17 +00003106 if (TagDecl)
Douglas Gregor0be31a22010-07-02 17:43:08 +00003107 Actions.ActOnFinishCXXMemberSpecification(getCurScope(), RecordLoc, TagDecl,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003108 T.getOpenLocation(),
3109 T.getCloseLocation(),
John McCall53fa7142010-12-24 02:08:15 +00003110 attrs.getList());
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003111
Douglas Gregor433e0532012-04-16 18:27:27 +00003112 // C++11 [class.mem]p2:
3113 // Within the class member-specification, the class is regarded as complete
Richard Smith0b3a4622014-11-13 20:01:57 +00003114 // within function bodies, default arguments, exception-specifications, and
Douglas Gregor433e0532012-04-16 18:27:27 +00003115 // brace-or-equal-initializers for non-static data members (including such
3116 // things in nested classes).
Douglas Gregor9377c822010-06-21 22:31:09 +00003117 if (TagDecl && NonNestedClass) {
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003118 // We are not inside a nested class. This class and its nested classes
Douglas Gregor4d87df52008-12-16 21:30:33 +00003119 // are complete and we can parse the delayed portions of method
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00003120 // declarations and the lexed inline method definitions, along with any
3121 // delayed attributes.
Douglas Gregor428119e2010-06-16 23:45:56 +00003122 SourceLocation SavedPrevTokLocation = PrevTokLocation;
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00003123 ParseLexedAttributes(getCurrentClass());
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003124 ParseLexedMethodDeclarations(getCurrentClass());
Richard Smith84973e52012-04-21 18:42:51 +00003125
3126 // We've finished with all pending member declarations.
3127 Actions.ActOnFinishCXXMemberDecls();
3128
Richard Smith938f40b2011-06-11 17:19:42 +00003129 ParseLexedMemberInitializers(getCurrentClass());
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003130 ParseLexedMethodDefs(getCurrentClass());
Douglas Gregor428119e2010-06-16 23:45:56 +00003131 PrevTokLocation = SavedPrevTokLocation;
Reid Klecknerbba3cb92015-03-17 19:00:50 +00003132
3133 // We've finished parsing everything, including default argument
3134 // initializers.
Hans Wennborg99000c22015-08-15 01:18:16 +00003135 Actions.ActOnFinishCXXNonNestedClass(TagDecl);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003136 }
3137
John McCall08bede42010-05-28 08:11:17 +00003138 if (TagDecl)
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003139 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl,
3140 T.getCloseLocation());
John McCall2ff380a2010-03-17 00:38:33 +00003141
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003142 // Leave the class scope.
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003143 ParsingDef.Pop();
Douglas Gregor7307d6c2008-12-10 06:34:36 +00003144 ClassScope.Exit();
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003145}
Douglas Gregore8381c02008-11-05 04:29:56 +00003146
Richard Smith2ac43ad2013-11-15 23:00:02 +00003147void Parser::DiagnoseUnexpectedNamespace(NamedDecl *D) {
Richard Smithda35e962013-11-09 04:52:51 +00003148 assert(Tok.is(tok::kw_namespace));
3149
3150 // FIXME: Suggest where the close brace should have gone by looking
3151 // at indentation changes within the definition body.
Richard Smith2ac43ad2013-11-15 23:00:02 +00003152 Diag(D->getLocation(),
3153 diag::err_missing_end_of_definition) << D;
Richard Smithda35e962013-11-09 04:52:51 +00003154 Diag(Tok.getLocation(),
Richard Smith2ac43ad2013-11-15 23:00:02 +00003155 diag::note_missing_end_of_definition_before) << D;
Richard Smithda35e962013-11-09 04:52:51 +00003156
3157 // Push '};' onto the token stream to recover.
3158 PP.EnterToken(Tok);
3159
3160 Tok.startToken();
3161 Tok.setLocation(PP.getLocForEndOfToken(PrevTokLocation));
3162 Tok.setKind(tok::semi);
3163 PP.EnterToken(Tok);
3164
3165 Tok.setKind(tok::r_brace);
3166}
3167
Douglas Gregore8381c02008-11-05 04:29:56 +00003168/// ParseConstructorInitializer - Parse a C++ constructor initializer,
3169/// which explicitly initializes the members or base classes of a
3170/// class (C++ [class.base.init]). For example, the three initializers
3171/// after the ':' in the Derived constructor below:
3172///
3173/// @code
3174/// class Base { };
3175/// class Derived : Base {
3176/// int x;
3177/// float f;
3178/// public:
3179/// Derived(float f) : Base(), x(17), f(f) { }
3180/// };
3181/// @endcode
3182///
Mike Stump11289f42009-09-09 15:08:12 +00003183/// [C++] ctor-initializer:
3184/// ':' mem-initializer-list
Douglas Gregore8381c02008-11-05 04:29:56 +00003185///
Mike Stump11289f42009-09-09 15:08:12 +00003186/// [C++] mem-initializer-list:
Douglas Gregor44e7df62011-01-04 00:32:56 +00003187/// mem-initializer ...[opt]
3188/// mem-initializer ...[opt] , mem-initializer-list
John McCall48871652010-08-21 09:40:31 +00003189void Parser::ParseConstructorInitializer(Decl *ConstructorDecl) {
Nico Weber3b00fdc2015-03-07 19:52:39 +00003190 assert(Tok.is(tok::colon) &&
3191 "Constructor initializer always starts with ':'");
Douglas Gregore8381c02008-11-05 04:29:56 +00003192
Nico Weber3b00fdc2015-03-07 19:52:39 +00003193 // Poison the SEH identifiers so they are flagged as illegal in constructor
3194 // initializers.
John Wiegley1c0675e2011-04-28 01:08:34 +00003195 PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
Douglas Gregore8381c02008-11-05 04:29:56 +00003196 SourceLocation ColonLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +00003197
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003198 SmallVector<CXXCtorInitializer*, 4> MemInitializers;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003199 bool AnyErrors = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003200
Douglas Gregore8381c02008-11-05 04:29:56 +00003201 do {
Douglas Gregoreaeeca92010-08-28 00:00:50 +00003202 if (Tok.is(tok::code_completion)) {
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00003203 Actions.CodeCompleteConstructorInitializer(ConstructorDecl,
3204 MemInitializers);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00003205 return cutOffParsing();
Douglas Gregoreaeeca92010-08-28 00:00:50 +00003206 }
Alexey Bataev79de17d2016-01-20 05:25:51 +00003207
3208 MemInitResult MemInit = ParseMemInitializer(ConstructorDecl);
3209 if (!MemInit.isInvalid())
3210 MemInitializers.push_back(MemInit.get());
3211 else
3212 AnyErrors = true;
3213
Douglas Gregore8381c02008-11-05 04:29:56 +00003214 if (Tok.is(tok::comma))
3215 ConsumeToken();
3216 else if (Tok.is(tok::l_brace))
3217 break;
Alexey Bataev79de17d2016-01-20 05:25:51 +00003218 // If the previous initializer was valid and the next token looks like a
3219 // base or member initializer, assume that we're just missing a comma.
3220 else if (!MemInit.isInvalid() &&
3221 Tok.isOneOf(tok::identifier, tok::coloncolon)) {
Douglas Gregorce66d022010-09-07 14:51:08 +00003222 SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation);
3223 Diag(Loc, diag::err_ctor_init_missing_comma)
3224 << FixItHint::CreateInsertion(Loc, ", ");
3225 } else {
Douglas Gregore8381c02008-11-05 04:29:56 +00003226 // Skip over garbage, until we get to '{'. Don't eat the '{'.
Alexey Bataev79de17d2016-01-20 05:25:51 +00003227 if (!MemInit.isInvalid())
3228 Diag(Tok.getLocation(), diag::err_expected_either) << tok::l_brace
3229 << tok::comma;
Alexey Bataevee6507d2013-11-18 08:17:37 +00003230 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
Douglas Gregore8381c02008-11-05 04:29:56 +00003231 break;
3232 }
3233 } while (true);
3234
David Blaikie3fc2f912013-01-17 05:26:25 +00003235 Actions.ActOnMemInitializers(ConstructorDecl, ColonLoc, MemInitializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003236 AnyErrors);
Douglas Gregore8381c02008-11-05 04:29:56 +00003237}
3238
3239/// ParseMemInitializer - Parse a C++ member initializer, which is
3240/// part of a constructor initializer that explicitly initializes one
3241/// member or base class (C++ [class.base.init]). See
3242/// ParseConstructorInitializer for an example.
3243///
3244/// [C++] mem-initializer:
3245/// mem-initializer-id '(' expression-list[opt] ')'
Sebastian Redl3da34892011-06-05 12:23:16 +00003246/// [C++0x] mem-initializer-id braced-init-list
Mike Stump11289f42009-09-09 15:08:12 +00003247///
Douglas Gregore8381c02008-11-05 04:29:56 +00003248/// [C++] mem-initializer-id:
3249/// '::'[opt] nested-name-specifier[opt] class-name
3250/// identifier
Craig Topper9ad7e262014-10-31 06:57:07 +00003251MemInitResult Parser::ParseMemInitializer(Decl *ConstructorDecl) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00003252 // parse '::'[opt] nested-name-specifier[opt]
3253 CXXScopeSpec SS;
David Blaikieefdccaa2016-01-15 23:43:34 +00003254 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false);
John McCallba7bf592010-08-24 05:47:05 +00003255 ParsedType TemplateTypeTy;
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00003256 if (Tok.is(tok::annot_template_id)) {
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00003257 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregor46c59612010-01-12 17:52:59 +00003258 if (TemplateId->Kind == TNK_Type_template ||
3259 TemplateId->Kind == TNK_Dependent_template_name) {
Douglas Gregore7c20652011-03-02 00:47:37 +00003260 AnnotateTemplateIdTokenAsType();
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00003261 assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
John McCallba7bf592010-08-24 05:47:05 +00003262 TemplateTypeTy = getTypeAnnotation(Tok);
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00003263 }
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00003264 }
David Blaikie186a8892012-01-24 06:03:59 +00003265 // Uses of decltype will already have been converted to annot_decltype by
3266 // ParseOptionalCXXScopeSpecifier at this point.
3267 if (!TemplateTypeTy && Tok.isNot(tok::identifier)
3268 && Tok.isNot(tok::annot_decltype)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00003269 Diag(Tok, diag::err_expected_member_or_base_name);
Douglas Gregore8381c02008-11-05 04:29:56 +00003270 return true;
3271 }
Mike Stump11289f42009-09-09 15:08:12 +00003272
Craig Topper161e4db2014-05-21 06:02:52 +00003273 IdentifierInfo *II = nullptr;
David Blaikie186a8892012-01-24 06:03:59 +00003274 DeclSpec DS(AttrFactory);
3275 SourceLocation IdLoc = Tok.getLocation();
3276 if (Tok.is(tok::annot_decltype)) {
3277 // Get the decltype expression, if there is one.
3278 ParseDecltypeSpecifier(DS);
3279 } else {
3280 if (Tok.is(tok::identifier))
3281 // Get the identifier. This may be a member name or a class name,
3282 // but we'll let the semantic analysis determine which it is.
3283 II = Tok.getIdentifierInfo();
3284 ConsumeToken();
3285 }
3286
Douglas Gregore8381c02008-11-05 04:29:56 +00003287
3288 // Parse the '('.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003289 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
Richard Smith5d164bc2011-10-15 05:09:34 +00003290 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
3291
Sebastian Redla74948d2011-09-24 17:48:25 +00003292 ExprResult InitList = ParseBraceInitializer();
3293 if (InitList.isInvalid())
3294 return true;
3295
3296 SourceLocation EllipsisLoc;
Alp Toker094e5212014-01-05 03:27:11 +00003297 TryConsumeToken(tok::ellipsis, EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00003298
3299 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
David Blaikie186a8892012-01-24 06:03:59 +00003300 TemplateTypeTy, DS, IdLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003301 InitList.get(), EllipsisLoc);
Sebastian Redl3da34892011-06-05 12:23:16 +00003302 } else if(Tok.is(tok::l_paren)) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003303 BalancedDelimiterTracker T(*this, tok::l_paren);
3304 T.consumeOpen();
Douglas Gregore8381c02008-11-05 04:29:56 +00003305
Sebastian Redl3da34892011-06-05 12:23:16 +00003306 // Parse the optional expression-list.
Benjamin Kramerf0623432012-08-23 22:51:59 +00003307 ExprVector ArgExprs;
Sebastian Redl3da34892011-06-05 12:23:16 +00003308 CommaLocsTy CommaLocs;
3309 if (Tok.isNot(tok::r_paren) && ParseExpressionList(ArgExprs, CommaLocs)) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00003310 SkipUntil(tok::r_paren, StopAtSemi);
Sebastian Redl3da34892011-06-05 12:23:16 +00003311 return true;
3312 }
3313
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003314 T.consumeClose();
Sebastian Redl3da34892011-06-05 12:23:16 +00003315
3316 SourceLocation EllipsisLoc;
Alp Toker97650562014-01-10 11:19:30 +00003317 TryConsumeToken(tok::ellipsis, EllipsisLoc);
Sebastian Redl3da34892011-06-05 12:23:16 +00003318
3319 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
David Blaikie186a8892012-01-24 06:03:59 +00003320 TemplateTypeTy, DS, IdLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00003321 T.getOpenLocation(), ArgExprs,
3322 T.getCloseLocation(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00003323 }
3324
Alp Tokerec543272013-12-24 09:48:30 +00003325 if (getLangOpts().CPlusPlus11)
3326 return Diag(Tok, diag::err_expected_either) << tok::l_paren << tok::l_brace;
3327 else
3328 return Diag(Tok, diag::err_expected) << tok::l_paren;
Douglas Gregore8381c02008-11-05 04:29:56 +00003329}
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003330
Sebastian Redl965b0e32011-03-05 14:45:16 +00003331/// \brief Parse a C++ exception-specification if present (C++0x [except.spec]).
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003332///
Douglas Gregor356513d2008-12-01 18:00:20 +00003333/// exception-specification:
Sebastian Redl965b0e32011-03-05 14:45:16 +00003334/// dynamic-exception-specification
3335/// noexcept-specification
3336///
3337/// noexcept-specification:
3338/// 'noexcept'
3339/// 'noexcept' '(' constant-expression ')'
3340ExceptionSpecificationType
Richard Smith0b3a4622014-11-13 20:01:57 +00003341Parser::tryParseExceptionSpecification(bool Delayed,
Douglas Gregor433e0532012-04-16 18:27:27 +00003342 SourceRange &SpecificationRange,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003343 SmallVectorImpl<ParsedType> &DynamicExceptions,
3344 SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
Richard Smith0b3a4622014-11-13 20:01:57 +00003345 ExprResult &NoexceptExpr,
3346 CachedTokens *&ExceptionSpecTokens) {
Sebastian Redl965b0e32011-03-05 14:45:16 +00003347 ExceptionSpecificationType Result = EST_None;
Hans Wennborgdcfba332015-10-06 23:40:43 +00003348 ExceptionSpecTokens = nullptr;
Richard Smith0b3a4622014-11-13 20:01:57 +00003349
3350 // Handle delayed parsing of exception-specifications.
3351 if (Delayed) {
3352 if (Tok.isNot(tok::kw_throw) && Tok.isNot(tok::kw_noexcept))
3353 return EST_None;
Sebastian Redl965b0e32011-03-05 14:45:16 +00003354
Richard Smith0b3a4622014-11-13 20:01:57 +00003355 // Consume and cache the starting token.
3356 bool IsNoexcept = Tok.is(tok::kw_noexcept);
3357 Token StartTok = Tok;
3358 SpecificationRange = SourceRange(ConsumeToken());
3359
3360 // Check for a '('.
3361 if (!Tok.is(tok::l_paren)) {
3362 // If this is a bare 'noexcept', we're done.
3363 if (IsNoexcept) {
3364 Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
Hans Wennborgdcfba332015-10-06 23:40:43 +00003365 NoexceptExpr = nullptr;
Richard Smith0b3a4622014-11-13 20:01:57 +00003366 return EST_BasicNoexcept;
3367 }
3368
3369 Diag(Tok, diag::err_expected_lparen_after) << "throw";
3370 return EST_DynamicNone;
3371 }
3372
3373 // Cache the tokens for the exception-specification.
3374 ExceptionSpecTokens = new CachedTokens;
3375 ExceptionSpecTokens->push_back(StartTok); // 'throw' or 'noexcept'
3376 ExceptionSpecTokens->push_back(Tok); // '('
3377 SpecificationRange.setEnd(ConsumeParen()); // '('
Richard Smithb1c217e2015-01-13 02:24:58 +00003378
3379 ConsumeAndStoreUntil(tok::r_paren, *ExceptionSpecTokens,
3380 /*StopAtSemi=*/true,
3381 /*ConsumeFinalToken=*/true);
Aaron Ballman580ccaf2016-01-12 21:04:22 +00003382 SpecificationRange.setEnd(ExceptionSpecTokens->back().getLocation());
3383
Richard Smith0b3a4622014-11-13 20:01:57 +00003384 return EST_Unparsed;
3385 }
3386
Sebastian Redl965b0e32011-03-05 14:45:16 +00003387 // See if there's a dynamic specification.
3388 if (Tok.is(tok::kw_throw)) {
3389 Result = ParseDynamicExceptionSpecification(SpecificationRange,
3390 DynamicExceptions,
3391 DynamicExceptionRanges);
3392 assert(DynamicExceptions.size() == DynamicExceptionRanges.size() &&
3393 "Produced different number of exception types and ranges.");
3394 }
3395
3396 // If there's no noexcept specification, we're done.
3397 if (Tok.isNot(tok::kw_noexcept))
3398 return Result;
3399
Richard Smithb15c11c2011-10-17 23:06:20 +00003400 Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
3401
Sebastian Redl965b0e32011-03-05 14:45:16 +00003402 // If we already had a dynamic specification, parse the noexcept for,
3403 // recovery, but emit a diagnostic and don't store the results.
3404 SourceRange NoexceptRange;
3405 ExceptionSpecificationType NoexceptType = EST_None;
3406
3407 SourceLocation KeywordLoc = ConsumeToken();
3408 if (Tok.is(tok::l_paren)) {
3409 // There is an argument.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003410 BalancedDelimiterTracker T(*this, tok::l_paren);
3411 T.consumeOpen();
Sebastian Redl965b0e32011-03-05 14:45:16 +00003412 NoexceptType = EST_ComputedNoexcept;
3413 NoexceptExpr = ParseConstantExpression();
Serge Pavlov3739f5e72015-06-29 17:50:19 +00003414 T.consumeClose();
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003415 // The argument must be contextually convertible to bool. We use
3416 // ActOnBooleanCondition for this purpose.
Serge Pavlov3739f5e72015-06-29 17:50:19 +00003417 if (!NoexceptExpr.isInvalid()) {
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003418 NoexceptExpr = Actions.ActOnBooleanCondition(getCurScope(), KeywordLoc,
3419 NoexceptExpr.get());
Serge Pavlov3739f5e72015-06-29 17:50:19 +00003420 NoexceptRange = SourceRange(KeywordLoc, T.getCloseLocation());
3421 } else {
3422 NoexceptType = EST_None;
3423 }
Sebastian Redl965b0e32011-03-05 14:45:16 +00003424 } else {
3425 // There is no argument.
3426 NoexceptType = EST_BasicNoexcept;
3427 NoexceptRange = SourceRange(KeywordLoc, KeywordLoc);
3428 }
3429
3430 if (Result == EST_None) {
3431 SpecificationRange = NoexceptRange;
3432 Result = NoexceptType;
3433
3434 // If there's a dynamic specification after a noexcept specification,
3435 // parse that and ignore the results.
3436 if (Tok.is(tok::kw_throw)) {
3437 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
3438 ParseDynamicExceptionSpecification(NoexceptRange, DynamicExceptions,
3439 DynamicExceptionRanges);
3440 }
3441 } else {
3442 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
3443 }
3444
3445 return Result;
3446}
3447
Richard Smith8ca78a12013-06-13 02:02:51 +00003448static void diagnoseDynamicExceptionSpecification(
Craig Toppere335f252015-10-04 04:53:55 +00003449 Parser &P, SourceRange Range, bool IsNoexcept) {
Richard Smith8ca78a12013-06-13 02:02:51 +00003450 if (P.getLangOpts().CPlusPlus11) {
3451 const char *Replacement = IsNoexcept ? "noexcept" : "noexcept(false)";
3452 P.Diag(Range.getBegin(), diag::warn_exception_spec_deprecated) << Range;
3453 P.Diag(Range.getBegin(), diag::note_exception_spec_deprecated)
3454 << Replacement << FixItHint::CreateReplacement(Range, Replacement);
3455 }
3456}
3457
Sebastian Redl965b0e32011-03-05 14:45:16 +00003458/// ParseDynamicExceptionSpecification - Parse a C++
3459/// dynamic-exception-specification (C++ [except.spec]).
3460///
3461/// dynamic-exception-specification:
Douglas Gregor356513d2008-12-01 18:00:20 +00003462/// 'throw' '(' type-id-list [opt] ')'
3463/// [MS] 'throw' '(' '...' ')'
Mike Stump11289f42009-09-09 15:08:12 +00003464///
Douglas Gregor356513d2008-12-01 18:00:20 +00003465/// type-id-list:
Douglas Gregor830837d2010-12-20 23:57:46 +00003466/// type-id ... [opt]
3467/// type-id-list ',' type-id ... [opt]
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003468///
Sebastian Redl965b0e32011-03-05 14:45:16 +00003469ExceptionSpecificationType Parser::ParseDynamicExceptionSpecification(
3470 SourceRange &SpecificationRange,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003471 SmallVectorImpl<ParsedType> &Exceptions,
3472 SmallVectorImpl<SourceRange> &Ranges) {
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003473 assert(Tok.is(tok::kw_throw) && "expected throw");
Mike Stump11289f42009-09-09 15:08:12 +00003474
Sebastian Redl965b0e32011-03-05 14:45:16 +00003475 SpecificationRange.setBegin(ConsumeToken());
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003476 BalancedDelimiterTracker T(*this, tok::l_paren);
3477 if (T.consumeOpen()) {
Sebastian Redl965b0e32011-03-05 14:45:16 +00003478 Diag(Tok, diag::err_expected_lparen_after) << "throw";
3479 SpecificationRange.setEnd(SpecificationRange.getBegin());
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003480 return EST_DynamicNone;
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003481 }
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003482
Douglas Gregor356513d2008-12-01 18:00:20 +00003483 // Parse throw(...), a Microsoft extension that means "this function
3484 // can throw anything".
3485 if (Tok.is(tok::ellipsis)) {
3486 SourceLocation EllipsisLoc = ConsumeToken();
David Blaikiebbafb8a2012-03-11 07:00:24 +00003487 if (!getLangOpts().MicrosoftExt)
Douglas Gregor356513d2008-12-01 18:00:20 +00003488 Diag(EllipsisLoc, diag::ext_ellipsis_exception_spec);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003489 T.consumeClose();
3490 SpecificationRange.setEnd(T.getCloseLocation());
Richard Smith8ca78a12013-06-13 02:02:51 +00003491 diagnoseDynamicExceptionSpecification(*this, SpecificationRange, false);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003492 return EST_MSAny;
Douglas Gregor356513d2008-12-01 18:00:20 +00003493 }
3494
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003495 // Parse the sequence of type-ids.
Sebastian Redld6434562009-05-29 18:02:33 +00003496 SourceRange Range;
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003497 while (Tok.isNot(tok::r_paren)) {
Sebastian Redld6434562009-05-29 18:02:33 +00003498 TypeResult Res(ParseTypeName(&Range));
Sebastian Redl965b0e32011-03-05 14:45:16 +00003499
Douglas Gregor830837d2010-12-20 23:57:46 +00003500 if (Tok.is(tok::ellipsis)) {
3501 // C++0x [temp.variadic]p5:
3502 // - In a dynamic-exception-specification (15.4); the pattern is a
3503 // type-id.
3504 SourceLocation Ellipsis = ConsumeToken();
Sebastian Redl965b0e32011-03-05 14:45:16 +00003505 Range.setEnd(Ellipsis);
Douglas Gregor830837d2010-12-20 23:57:46 +00003506 if (!Res.isInvalid())
3507 Res = Actions.ActOnPackExpansion(Res.get(), Ellipsis);
3508 }
Sebastian Redl965b0e32011-03-05 14:45:16 +00003509
Sebastian Redld6434562009-05-29 18:02:33 +00003510 if (!Res.isInvalid()) {
Sebastian Redl2b9cacb2009-04-29 17:30:04 +00003511 Exceptions.push_back(Res.get());
Sebastian Redld6434562009-05-29 18:02:33 +00003512 Ranges.push_back(Range);
3513 }
Alp Toker97650562014-01-10 11:19:30 +00003514
3515 if (!TryConsumeToken(tok::comma))
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003516 break;
3517 }
3518
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003519 T.consumeClose();
3520 SpecificationRange.setEnd(T.getCloseLocation());
Richard Smith8ca78a12013-06-13 02:02:51 +00003521 diagnoseDynamicExceptionSpecification(*this, SpecificationRange,
3522 Exceptions.empty());
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003523 return Exceptions.empty() ? EST_DynamicNone : EST_Dynamic;
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003524}
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003525
Douglas Gregor7fb25412010-10-01 18:44:50 +00003526/// ParseTrailingReturnType - Parse a trailing return type on a new-style
3527/// function declaration.
Douglas Gregordb0b9f12011-08-04 15:30:47 +00003528TypeResult Parser::ParseTrailingReturnType(SourceRange &Range) {
Douglas Gregor7fb25412010-10-01 18:44:50 +00003529 assert(Tok.is(tok::arrow) && "expected arrow");
3530
3531 ConsumeToken();
3532
Richard Smithbfdb1082012-03-12 08:56:40 +00003533 return ParseTypeName(&Range, Declarator::TrailingReturnContext);
Douglas Gregor7fb25412010-10-01 18:44:50 +00003534}
3535
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003536/// \brief We have just started parsing the definition of a new class,
3537/// so push that class onto our stack of classes that is currently
3538/// being parsed.
John McCallc1465822011-02-14 07:13:47 +00003539Sema::ParsingClassState
John McCalldb632ac2012-09-25 07:32:39 +00003540Parser::PushParsingClass(Decl *ClassDecl, bool NonNestedClass,
3541 bool IsInterface) {
Douglas Gregoredf8f392010-01-16 20:52:59 +00003542 assert((NonNestedClass || !ClassStack.empty()) &&
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003543 "Nested class without outer class");
John McCalldb632ac2012-09-25 07:32:39 +00003544 ClassStack.push(new ParsingClass(ClassDecl, NonNestedClass, IsInterface));
John McCallc1465822011-02-14 07:13:47 +00003545 return Actions.PushParsingClass();
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003546}
3547
3548/// \brief Deallocate the given parsed class and all of its nested
3549/// classes.
3550void Parser::DeallocateParsedClasses(Parser::ParsingClass *Class) {
Douglas Gregorefc46952010-10-12 16:25:54 +00003551 for (unsigned I = 0, N = Class->LateParsedDeclarations.size(); I != N; ++I)
3552 delete Class->LateParsedDeclarations[I];
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003553 delete Class;
3554}
3555
3556/// \brief Pop the top class of the stack of classes that are
3557/// currently being parsed.
3558///
3559/// This routine should be called when we have finished parsing the
3560/// definition of a class, but have not yet popped the Scope
3561/// associated with the class's definition.
John McCallc1465822011-02-14 07:13:47 +00003562void Parser::PopParsingClass(Sema::ParsingClassState state) {
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003563 assert(!ClassStack.empty() && "Mismatched push/pop for class parsing");
Mike Stump11289f42009-09-09 15:08:12 +00003564
John McCallc1465822011-02-14 07:13:47 +00003565 Actions.PopParsingClass(state);
3566
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003567 ParsingClass *Victim = ClassStack.top();
3568 ClassStack.pop();
3569 if (Victim->TopLevelClass) {
3570 // Deallocate all of the nested classes of this class,
3571 // recursively: we don't need to keep any of this information.
3572 DeallocateParsedClasses(Victim);
3573 return;
Mike Stump11289f42009-09-09 15:08:12 +00003574 }
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003575 assert(!ClassStack.empty() && "Missing top-level class?");
3576
Douglas Gregorefc46952010-10-12 16:25:54 +00003577 if (Victim->LateParsedDeclarations.empty()) {
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003578 // The victim is a nested class, but we will not need to perform
3579 // any processing after the definition of this class since it has
3580 // no members whose handling was delayed. Therefore, we can just
3581 // remove this nested class.
Douglas Gregorefc46952010-10-12 16:25:54 +00003582 DeallocateParsedClasses(Victim);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003583 return;
3584 }
3585
3586 // This nested class has some members that will need to be processed
3587 // after the top-level class is completely defined. Therefore, add
3588 // it to the list of nested classes within its parent.
Douglas Gregor0be31a22010-07-02 17:43:08 +00003589 assert(getCurScope()->isClassScope() && "Nested class outside of class scope?");
Douglas Gregorefc46952010-10-12 16:25:54 +00003590 ClassStack.top()->LateParsedDeclarations.push_back(new LateParsedClass(this, Victim));
Douglas Gregor0be31a22010-07-02 17:43:08 +00003591 Victim->TemplateScope = getCurScope()->getParent()->isTemplateParamScope();
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003592}
Alexis Hunt96d5c762009-11-21 08:43:09 +00003593
Richard Smith3dff2512012-04-10 03:25:07 +00003594/// \brief Try to parse an 'identifier' which appears within an attribute-token.
3595///
3596/// \return the parsed identifier on success, and 0 if the next token is not an
3597/// attribute-token.
3598///
3599/// C++11 [dcl.attr.grammar]p3:
3600/// If a keyword or an alternative token that satisfies the syntactic
3601/// requirements of an identifier is contained in an attribute-token,
3602/// it is considered an identifier.
3603IdentifierInfo *Parser::TryParseCXX11AttributeIdentifier(SourceLocation &Loc) {
3604 switch (Tok.getKind()) {
3605 default:
3606 // Identifiers and keywords have identifier info attached.
David Majnemerd5271992015-01-09 18:09:39 +00003607 if (!Tok.isAnnotation()) {
3608 if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
3609 Loc = ConsumeToken();
3610 return II;
3611 }
Richard Smith3dff2512012-04-10 03:25:07 +00003612 }
Craig Topper161e4db2014-05-21 06:02:52 +00003613 return nullptr;
Richard Smith3dff2512012-04-10 03:25:07 +00003614
3615 case tok::ampamp: // 'and'
3616 case tok::pipe: // 'bitor'
3617 case tok::pipepipe: // 'or'
3618 case tok::caret: // 'xor'
3619 case tok::tilde: // 'compl'
3620 case tok::amp: // 'bitand'
3621 case tok::ampequal: // 'and_eq'
3622 case tok::pipeequal: // 'or_eq'
3623 case tok::caretequal: // 'xor_eq'
3624 case tok::exclaim: // 'not'
3625 case tok::exclaimequal: // 'not_eq'
3626 // Alternative tokens do not have identifier info, but their spelling
3627 // starts with an alphabetical character.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003628 SmallString<8> SpellingBuf;
Benjamin Kramer60be5632015-03-29 19:25:07 +00003629 SourceLocation SpellingLoc =
3630 PP.getSourceManager().getSpellingLoc(Tok.getLocation());
3631 StringRef Spelling = PP.getSpelling(SpellingLoc, SpellingBuf);
Jordan Rosea7d03842013-02-08 22:30:41 +00003632 if (isLetter(Spelling[0])) {
Richard Smith3dff2512012-04-10 03:25:07 +00003633 Loc = ConsumeToken();
Benjamin Kramer5c17f9c2012-04-22 20:43:30 +00003634 return &PP.getIdentifierTable().get(Spelling);
Richard Smith3dff2512012-04-10 03:25:07 +00003635 }
Craig Topper161e4db2014-05-21 06:02:52 +00003636 return nullptr;
Richard Smith3dff2512012-04-10 03:25:07 +00003637 }
3638}
3639
Michael Han23214e52012-10-03 01:56:22 +00003640static bool IsBuiltInOrStandardCXX11Attribute(IdentifierInfo *AttrName,
3641 IdentifierInfo *ScopeName) {
3642 switch (AttributeList::getKind(AttrName, ScopeName,
3643 AttributeList::AS_CXX11)) {
3644 case AttributeList::AT_CarriesDependency:
Aaron Ballman35f94212014-04-14 16:03:22 +00003645 case AttributeList::AT_Deprecated:
Michael Han23214e52012-10-03 01:56:22 +00003646 case AttributeList::AT_FallThrough:
Hans Wennborgdcfba332015-10-06 23:40:43 +00003647 case AttributeList::AT_CXX11NoReturn:
Michael Han23214e52012-10-03 01:56:22 +00003648 return true;
Aaron Ballmane7964782016-03-07 22:44:55 +00003649 case AttributeList::AT_WarnUnusedResult:
3650 return !ScopeName && AttrName->getName().equals("nodiscard");
Aaron Ballman0bcd6c12016-03-09 16:48:08 +00003651 case AttributeList::AT_Unused:
3652 return !ScopeName && AttrName->getName().equals("maybe_unused");
Michael Han23214e52012-10-03 01:56:22 +00003653 default:
3654 return false;
3655 }
3656}
3657
Aaron Ballmanb8e20392014-03-31 17:32:39 +00003658/// ParseCXX11AttributeArgs -- Parse a C++11 attribute-argument-clause.
3659///
3660/// [C++11] attribute-argument-clause:
3661/// '(' balanced-token-seq ')'
3662///
3663/// [C++11] balanced-token-seq:
3664/// balanced-token
3665/// balanced-token-seq balanced-token
3666///
3667/// [C++11] balanced-token:
3668/// '(' balanced-token-seq ')'
3669/// '[' balanced-token-seq ']'
3670/// '{' balanced-token-seq '}'
3671/// any token but '(', ')', '[', ']', '{', or '}'
3672bool Parser::ParseCXX11AttributeArgs(IdentifierInfo *AttrName,
3673 SourceLocation AttrNameLoc,
3674 ParsedAttributes &Attrs,
3675 SourceLocation *EndLoc,
3676 IdentifierInfo *ScopeName,
3677 SourceLocation ScopeLoc) {
3678 assert(Tok.is(tok::l_paren) && "Not a C++11 attribute argument list");
Aaron Ballman35f94212014-04-14 16:03:22 +00003679 SourceLocation LParenLoc = Tok.getLocation();
Aaron Ballmanb8e20392014-03-31 17:32:39 +00003680
3681 // If the attribute isn't known, we will not attempt to parse any
3682 // arguments.
3683 if (!hasAttribute(AttrSyntax::CXX, ScopeName, AttrName,
Bob Wilson7c730832015-07-20 22:57:31 +00003684 getTargetInfo(), getLangOpts())) {
Aaron Ballmanb8e20392014-03-31 17:32:39 +00003685 // Eat the left paren, then skip to the ending right paren.
3686 ConsumeParen();
3687 SkipUntil(tok::r_paren);
3688 return false;
3689 }
3690
3691 if (ScopeName && ScopeName->getName() == "gnu")
3692 // GNU-scoped attributes have some special cases to handle GNU-specific
3693 // behaviors.
3694 ParseGNUAttributeArgs(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
Craig Topper161e4db2014-05-21 06:02:52 +00003695 ScopeLoc, AttributeList::AS_CXX11, nullptr);
Aaron Ballman35f94212014-04-14 16:03:22 +00003696 else {
3697 unsigned NumArgs =
3698 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc,
3699 ScopeName, ScopeLoc, AttributeList::AS_CXX11);
3700
3701 const AttributeList *Attr = Attrs.getList();
3702 if (Attr && IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName)) {
3703 // If the attribute is a standard or built-in attribute and we are
3704 // parsing an argument list, we need to determine whether this attribute
3705 // was allowed to have an argument list (such as [[deprecated]]), and how
3706 // many arguments were parsed (so we can diagnose on [[deprecated()]]).
Nikola Smiljanica9c45212014-05-28 11:19:43 +00003707 if (Attr->getMaxArgs() && !NumArgs) {
3708 // The attribute was allowed to have arguments, but none were provided
3709 // even though the attribute parsed successfully. This is an error.
Nikola Smiljanica9c45212014-05-28 11:19:43 +00003710 Diag(LParenLoc, diag::err_attribute_requires_arguments) << AttrName;
Aaron Ballmanbb5d8622016-03-08 21:31:32 +00003711 Attr->setInvalid(true);
Nikola Smiljanica9c45212014-05-28 11:19:43 +00003712 } else if (!Attr->getMaxArgs()) {
3713 // The attribute parsed successfully, but was not allowed to have any
3714 // arguments. It doesn't matter whether any were provided -- the
Aaron Ballman35f94212014-04-14 16:03:22 +00003715 // presence of the argument list (even if empty) is diagnosed.
3716 Diag(LParenLoc, diag::err_cxx11_attribute_forbids_arguments)
Aaron Ballman9b7cee62014-12-19 18:37:22 +00003717 << AttrName
3718 << FixItHint::CreateRemoval(SourceRange(LParenLoc, *EndLoc));
Aaron Ballmanbb5d8622016-03-08 21:31:32 +00003719 Attr->setInvalid(true);
Aaron Ballman35f94212014-04-14 16:03:22 +00003720 }
3721 }
3722 }
Aaron Ballmanb8e20392014-03-31 17:32:39 +00003723 return true;
3724}
3725
3726/// ParseCXX11AttributeSpecifier - Parse a C++11 attribute-specifier.
Alexis Hunt96d5c762009-11-21 08:43:09 +00003727///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003728/// [C++11] attribute-specifier:
Alexis Hunt96d5c762009-11-21 08:43:09 +00003729/// '[' '[' attribute-list ']' ']'
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00003730/// alignment-specifier
Alexis Hunt96d5c762009-11-21 08:43:09 +00003731///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003732/// [C++11] attribute-list:
Alexis Hunt96d5c762009-11-21 08:43:09 +00003733/// attribute[opt]
3734/// attribute-list ',' attribute[opt]
Richard Smith3dff2512012-04-10 03:25:07 +00003735/// attribute '...'
3736/// attribute-list ',' attribute '...'
Alexis Hunt96d5c762009-11-21 08:43:09 +00003737///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003738/// [C++11] attribute:
Alexis Hunt96d5c762009-11-21 08:43:09 +00003739/// attribute-token attribute-argument-clause[opt]
3740///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003741/// [C++11] attribute-token:
Alexis Hunt96d5c762009-11-21 08:43:09 +00003742/// identifier
3743/// attribute-scoped-token
3744///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003745/// [C++11] attribute-scoped-token:
Alexis Hunt96d5c762009-11-21 08:43:09 +00003746/// attribute-namespace '::' identifier
3747///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003748/// [C++11] attribute-namespace:
Alexis Hunt96d5c762009-11-21 08:43:09 +00003749/// identifier
Richard Smith3dff2512012-04-10 03:25:07 +00003750void Parser::ParseCXX11AttributeSpecifier(ParsedAttributes &attrs,
Peter Collingbourne49eedec2011-09-29 18:04:05 +00003751 SourceLocation *endLoc) {
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00003752 if (Tok.is(tok::kw_alignas)) {
Richard Smithf679b5b2011-10-14 20:48:27 +00003753 Diag(Tok.getLocation(), diag::warn_cxx98_compat_alignas);
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00003754 ParseAlignmentSpecifier(attrs, endLoc);
3755 return;
3756 }
3757
Alexis Hunt96d5c762009-11-21 08:43:09 +00003758 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square)
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003759 && "Not a C++11 attribute list");
Alexis Hunt96d5c762009-11-21 08:43:09 +00003760
Richard Smithf679b5b2011-10-14 20:48:27 +00003761 Diag(Tok.getLocation(), diag::warn_cxx98_compat_attribute);
3762
Alexis Hunt96d5c762009-11-21 08:43:09 +00003763 ConsumeBracket();
3764 ConsumeBracket();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003765
Richard Smith10876ef2013-01-17 01:30:42 +00003766 llvm::SmallDenseMap<IdentifierInfo*, SourceLocation, 4> SeenAttrs;
3767
Richard Smith3dff2512012-04-10 03:25:07 +00003768 while (Tok.isNot(tok::r_square)) {
Alexis Hunt96d5c762009-11-21 08:43:09 +00003769 // attribute not present
Alp Toker97650562014-01-10 11:19:30 +00003770 if (TryConsumeToken(tok::comma))
Alexis Hunt96d5c762009-11-21 08:43:09 +00003771 continue;
Alexis Hunt96d5c762009-11-21 08:43:09 +00003772
Richard Smith3dff2512012-04-10 03:25:07 +00003773 SourceLocation ScopeLoc, AttrLoc;
Craig Topper161e4db2014-05-21 06:02:52 +00003774 IdentifierInfo *ScopeName = nullptr, *AttrName = nullptr;
Richard Smith3dff2512012-04-10 03:25:07 +00003775
3776 AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
3777 if (!AttrName)
3778 // Break out to the "expected ']'" diagnostic.
3779 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003780
Alexis Hunt96d5c762009-11-21 08:43:09 +00003781 // scoped attribute
Alp Toker97650562014-01-10 11:19:30 +00003782 if (TryConsumeToken(tok::coloncolon)) {
Richard Smith3dff2512012-04-10 03:25:07 +00003783 ScopeName = AttrName;
3784 ScopeLoc = AttrLoc;
3785
3786 AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
3787 if (!AttrName) {
Alp Tokerec543272013-12-24 09:48:30 +00003788 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
Alexey Bataevee6507d2013-11-18 08:17:37 +00003789 SkipUntil(tok::r_square, tok::comma, StopAtSemi | StopBeforeMatch);
Alexis Hunt96d5c762009-11-21 08:43:09 +00003790 continue;
3791 }
Alexis Hunt96d5c762009-11-21 08:43:09 +00003792 }
3793
Aaron Ballmanb8e20392014-03-31 17:32:39 +00003794 bool StandardAttr = IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName);
Alexis Hunt96d5c762009-11-21 08:43:09 +00003795 bool AttrParsed = false;
Alexis Hunt96d5c762009-11-21 08:43:09 +00003796
Richard Smith10876ef2013-01-17 01:30:42 +00003797 if (StandardAttr &&
3798 !SeenAttrs.insert(std::make_pair(AttrName, AttrLoc)).second)
3799 Diag(AttrLoc, diag::err_cxx11_attribute_repeated)
Aaron Ballmanb8e20392014-03-31 17:32:39 +00003800 << AttrName << SourceRange(SeenAttrs[AttrName]);
Richard Smith10876ef2013-01-17 01:30:42 +00003801
Michael Han23214e52012-10-03 01:56:22 +00003802 // Parse attribute arguments
Aaron Ballman35f94212014-04-14 16:03:22 +00003803 if (Tok.is(tok::l_paren))
Aaron Ballmanb8e20392014-03-31 17:32:39 +00003804 AttrParsed = ParseCXX11AttributeArgs(AttrName, AttrLoc, attrs, endLoc,
3805 ScopeName, ScopeLoc);
Michael Han23214e52012-10-03 01:56:22 +00003806
3807 if (!AttrParsed)
Richard Smith84837d52012-05-03 18:27:39 +00003808 attrs.addNew(AttrName,
3809 SourceRange(ScopeLoc.isValid() ? ScopeLoc : AttrLoc,
3810 AttrLoc),
Craig Topper161e4db2014-05-21 06:02:52 +00003811 ScopeName, ScopeLoc, nullptr, 0, AttributeList::AS_CXX11);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003812
Alp Toker97650562014-01-10 11:19:30 +00003813 if (TryConsumeToken(tok::ellipsis))
Michael Han23214e52012-10-03 01:56:22 +00003814 Diag(Tok, diag::err_cxx11_attribute_forbids_ellipsis)
3815 << AttrName->getName();
Alexis Hunt96d5c762009-11-21 08:43:09 +00003816 }
3817
Alp Toker383d2c42014-01-01 03:08:43 +00003818 if (ExpectAndConsume(tok::r_square))
Alexey Bataevee6507d2013-11-18 08:17:37 +00003819 SkipUntil(tok::r_square);
Peter Collingbourne49eedec2011-09-29 18:04:05 +00003820 if (endLoc)
3821 *endLoc = Tok.getLocation();
Alp Toker383d2c42014-01-01 03:08:43 +00003822 if (ExpectAndConsume(tok::r_square))
Alexey Bataevee6507d2013-11-18 08:17:37 +00003823 SkipUntil(tok::r_square);
Peter Collingbourne49eedec2011-09-29 18:04:05 +00003824}
Alexis Hunt96d5c762009-11-21 08:43:09 +00003825
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00003826/// ParseCXX11Attributes - Parse a C++11 attribute-specifier-seq.
Peter Collingbourne49eedec2011-09-29 18:04:05 +00003827///
3828/// attribute-specifier-seq:
3829/// attribute-specifier-seq[opt] attribute-specifier
Richard Smith3dff2512012-04-10 03:25:07 +00003830void Parser::ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
Peter Collingbourne49eedec2011-09-29 18:04:05 +00003831 SourceLocation *endLoc) {
Richard Smith4cabd042013-02-22 09:15:49 +00003832 assert(getLangOpts().CPlusPlus11);
3833
Peter Collingbourne49eedec2011-09-29 18:04:05 +00003834 SourceLocation StartLoc = Tok.getLocation(), Loc;
3835 if (!endLoc)
3836 endLoc = &Loc;
3837
Douglas Gregor6f981002011-10-07 20:35:25 +00003838 do {
Richard Smith3dff2512012-04-10 03:25:07 +00003839 ParseCXX11AttributeSpecifier(attrs, endLoc);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003840 } while (isCXX11AttributeSpecifier());
Peter Collingbourne49eedec2011-09-29 18:04:05 +00003841
3842 attrs.Range = SourceRange(StartLoc, *endLoc);
Alexis Hunt96d5c762009-11-21 08:43:09 +00003843}
3844
Richard Smithc2c8bb82013-10-15 01:34:54 +00003845void Parser::DiagnoseAndSkipCXX11Attributes() {
Richard Smithc2c8bb82013-10-15 01:34:54 +00003846 // Start and end location of an attribute or an attribute list.
3847 SourceLocation StartLoc = Tok.getLocation();
Richard Smith955bf012014-06-19 11:42:00 +00003848 SourceLocation EndLoc = SkipCXX11Attributes();
3849
3850 if (EndLoc.isValid()) {
3851 SourceRange Range(StartLoc, EndLoc);
3852 Diag(StartLoc, diag::err_attributes_not_allowed)
3853 << Range;
3854 }
3855}
3856
3857SourceLocation Parser::SkipCXX11Attributes() {
Richard Smithc2c8bb82013-10-15 01:34:54 +00003858 SourceLocation EndLoc;
3859
Richard Smith955bf012014-06-19 11:42:00 +00003860 if (!isCXX11AttributeSpecifier())
3861 return EndLoc;
3862
Richard Smithc2c8bb82013-10-15 01:34:54 +00003863 do {
3864 if (Tok.is(tok::l_square)) {
3865 BalancedDelimiterTracker T(*this, tok::l_square);
3866 T.consumeOpen();
3867 T.skipToEnd();
3868 EndLoc = T.getCloseLocation();
3869 } else {
3870 assert(Tok.is(tok::kw_alignas) && "not an attribute specifier");
3871 ConsumeToken();
3872 BalancedDelimiterTracker T(*this, tok::l_paren);
3873 if (!T.consumeOpen())
3874 T.skipToEnd();
3875 EndLoc = T.getCloseLocation();
3876 }
3877 } while (isCXX11AttributeSpecifier());
3878
Richard Smith955bf012014-06-19 11:42:00 +00003879 return EndLoc;
Richard Smithc2c8bb82013-10-15 01:34:54 +00003880}
3881
David Majnemere4752e752015-07-08 05:55:00 +00003882/// ParseMicrosoftAttributes - Parse Microsoft attributes [Attr]
Francois Pichetc2bc5ac2010-10-11 12:59:39 +00003883///
3884/// [MS] ms-attribute:
3885/// '[' token-seq ']'
3886///
3887/// [MS] ms-attribute-seq:
3888/// ms-attribute[opt]
3889/// ms-attribute ms-attribute-seq
John McCall53fa7142010-12-24 02:08:15 +00003890void Parser::ParseMicrosoftAttributes(ParsedAttributes &attrs,
3891 SourceLocation *endLoc) {
Francois Pichetc2bc5ac2010-10-11 12:59:39 +00003892 assert(Tok.is(tok::l_square) && "Not a Microsoft attribute list");
3893
Saleem Abdulrasool425efcf2015-06-15 20:57:04 +00003894 do {
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003895 // FIXME: If this is actually a C++11 attribute, parse it as one.
Saleem Abdulrasool425efcf2015-06-15 20:57:04 +00003896 BalancedDelimiterTracker T(*this, tok::l_square);
3897 T.consumeOpen();
Alexey Bataevee6507d2013-11-18 08:17:37 +00003898 SkipUntil(tok::r_square, StopAtSemi | StopBeforeMatch);
Saleem Abdulrasool425efcf2015-06-15 20:57:04 +00003899 T.consumeClose();
3900 if (endLoc)
3901 *endLoc = T.getCloseLocation();
3902 } while (Tok.is(tok::l_square));
Francois Pichetc2bc5ac2010-10-11 12:59:39 +00003903}
Francois Pichet8f981d52011-05-25 10:19:49 +00003904
3905void Parser::ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType,
3906 AccessSpecifier& CurAS) {
Douglas Gregor43edb322011-10-24 22:31:10 +00003907 IfExistsCondition Result;
Francois Pichet8f981d52011-05-25 10:19:49 +00003908 if (ParseMicrosoftIfExistsCondition(Result))
3909 return;
3910
Douglas Gregor43edb322011-10-24 22:31:10 +00003911 BalancedDelimiterTracker Braces(*this, tok::l_brace);
3912 if (Braces.consumeOpen()) {
Alp Tokerec543272013-12-24 09:48:30 +00003913 Diag(Tok, diag::err_expected) << tok::l_brace;
Francois Pichet8f981d52011-05-25 10:19:49 +00003914 return;
3915 }
Francois Pichet8f981d52011-05-25 10:19:49 +00003916
Douglas Gregor43edb322011-10-24 22:31:10 +00003917 switch (Result.Behavior) {
3918 case IEB_Parse:
3919 // Parse the declarations below.
3920 break;
3921
3922 case IEB_Dependent:
3923 Diag(Result.KeywordLoc, diag::warn_microsoft_dependent_exists)
3924 << Result.IsIfExists;
3925 // Fall through to skip.
3926
3927 case IEB_Skip:
3928 Braces.skipToEnd();
Francois Pichet8f981d52011-05-25 10:19:49 +00003929 return;
3930 }
3931
Richard Smith34f30512013-11-23 04:06:09 +00003932 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
Francois Pichet8f981d52011-05-25 10:19:49 +00003933 // __if_exists, __if_not_exists can nest.
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00003934 if (Tok.isOneOf(tok::kw___if_exists, tok::kw___if_not_exists)) {
Francois Pichet8f981d52011-05-25 10:19:49 +00003935 ParseMicrosoftIfExistsClassDeclaration((DeclSpec::TST)TagType, CurAS);
3936 continue;
3937 }
3938
3939 // Check for extraneous top-level semicolon.
3940 if (Tok.is(tok::semi)) {
Richard Smith87f5dc52012-07-23 05:45:25 +00003941 ConsumeExtraSemi(InsideStruct, TagType);
Francois Pichet8f981d52011-05-25 10:19:49 +00003942 continue;
3943 }
3944
3945 AccessSpecifier AS = getAccessSpecifierIfPresent();
3946 if (AS != AS_none) {
3947 // Current token is a C++ access specifier.
3948 CurAS = AS;
3949 SourceLocation ASLoc = Tok.getLocation();
3950 ConsumeToken();
3951 if (Tok.is(tok::colon))
3952 Actions.ActOnAccessSpecifier(AS, ASLoc, Tok.getLocation());
3953 else
Alp Toker35d87032013-12-30 23:29:50 +00003954 Diag(Tok, diag::err_expected) << tok::colon;
Francois Pichet8f981d52011-05-25 10:19:49 +00003955 ConsumeToken();
3956 continue;
3957 }
3958
3959 // Parse all the comma separated declarators.
Craig Topper161e4db2014-05-21 06:02:52 +00003960 ParseCXXClassMemberDeclaration(CurAS, nullptr);
Francois Pichet8f981d52011-05-25 10:19:49 +00003961 }
Douglas Gregor43edb322011-10-24 22:31:10 +00003962
3963 Braces.consumeClose();
Francois Pichet8f981d52011-05-25 10:19:49 +00003964}