blob: 44e7a3512098b7997eb56e426683397745ff22ac [file] [log] [blame]
Hans Wennborgdcfba332015-10-06 23:40:43 +00001//===--- ParseDeclCXX.cpp - C++ Declaration Parsing -------------*- C++ -*-===//
Chris Lattnera5235172007-08-25 06:57:03 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnera5235172007-08-25 06:57:03 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the C++ Declaration portions of the Parser interfaces.
11//
12//===----------------------------------------------------------------------===//
13
Douglas Gregor423984d2008-04-14 00:13:42 +000014#include "clang/Parse/Parser.h"
Erik Verbruggen888d52a2014-01-15 09:15:43 +000015#include "clang/AST/ASTContext.h"
Chandler Carruth757fcd62014-03-04 10:05:20 +000016#include "clang/AST/DeclTemplate.h"
Aaron Ballmanb8e20392014-03-31 17:32:39 +000017#include "clang/Basic/Attributes.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000018#include "clang/Basic/CharInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "clang/Basic/OperatorKinds.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000020#include "clang/Basic/TargetInfo.h"
Chris Lattner60f36222009-01-29 05:15:15 +000021#include "clang/Parse/ParseDiagnostic.h"
Vassil Vassilev11ad3392017-03-23 15:11:07 +000022#include "clang/Parse/RAIIObjectsForParser.h"
John McCall8b0666c2010-08-20 18:27:03 +000023#include "clang/Sema/DeclSpec.h"
John McCall8b0666c2010-08-20 18:27:03 +000024#include "clang/Sema/ParsedTemplate.h"
John McCallfaf5fb42010-08-26 23:41:50 +000025#include "clang/Sema/PrettyDeclStackTrace.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "clang/Sema/Scope.h"
John McCalldb632ac2012-09-25 07:32:39 +000027#include "clang/Sema/SemaDiagnostic.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000028#include "llvm/ADT/SmallString.h"
Hans Wennborgdcfba332015-10-06 23:40:43 +000029
Chris Lattnera5235172007-08-25 06:57:03 +000030using namespace clang;
31
32/// ParseNamespace - We know that the current token is a namespace keyword. This
Sebastian Redl67667942010-08-27 23:12:46 +000033/// may either be a top level namespace or a block-level namespace alias. If
34/// there was an inline keyword, it has already been parsed.
Chris Lattnera5235172007-08-25 06:57:03 +000035///
36/// namespace-definition: [C++ 7.3: basic.namespace]
37/// named-namespace-definition
38/// unnamed-namespace-definition
39///
40/// unnamed-namespace-definition:
Sebastian Redl67667942010-08-27 23:12:46 +000041/// 'inline'[opt] 'namespace' attributes[opt] '{' namespace-body '}'
Chris Lattnera5235172007-08-25 06:57:03 +000042///
43/// named-namespace-definition:
44/// original-namespace-definition
45/// extension-namespace-definition
46///
47/// original-namespace-definition:
Sebastian Redl67667942010-08-27 23:12:46 +000048/// 'inline'[opt] 'namespace' identifier attributes[opt]
49/// '{' namespace-body '}'
Chris Lattnera5235172007-08-25 06:57:03 +000050///
51/// extension-namespace-definition:
Sebastian Redl67667942010-08-27 23:12:46 +000052/// 'inline'[opt] 'namespace' original-namespace-name
53/// '{' namespace-body '}'
Mike Stump11289f42009-09-09 15:08:12 +000054///
Chris Lattnera5235172007-08-25 06:57:03 +000055/// namespace-alias-definition: [C++ 7.3.2: namespace.alias]
56/// 'namespace' identifier '=' qualified-namespace-specifier ';'
57///
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +000058Parser::DeclGroupPtrTy Parser::ParseNamespace(unsigned Context,
59 SourceLocation &DeclEnd,
60 SourceLocation InlineLoc) {
Chris Lattner76c72282007-10-09 17:33:22 +000061 assert(Tok.is(tok::kw_namespace) && "Not a namespace!");
Chris Lattnera5235172007-08-25 06:57:03 +000062 SourceLocation NamespaceLoc = ConsumeToken(); // eat the 'namespace'.
Fariborz Jahanian4bf82622011-08-22 17:59:19 +000063 ObjCDeclContextSwitch ObjCDC(*this);
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000064
Douglas Gregor7e90c6d2009-09-18 19:03:04 +000065 if (Tok.is(tok::code_completion)) {
Douglas Gregor0be31a22010-07-02 17:43:08 +000066 Actions.CodeCompleteNamespaceDecl(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +000067 cutOffParsing();
David Blaikie0403cb12016-01-15 23:43:25 +000068 return nullptr;
Douglas Gregor7e90c6d2009-09-18 19:03:04 +000069 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000070
Chris Lattnera5235172007-08-25 06:57:03 +000071 SourceLocation IdentLoc;
Craig Topper161e4db2014-05-21 06:02:52 +000072 IdentifierInfo *Ident = nullptr;
Richard Trieu61384cb2011-05-26 20:11:09 +000073 std::vector<SourceLocation> ExtraIdentLoc;
74 std::vector<IdentifierInfo*> ExtraIdent;
75 std::vector<SourceLocation> ExtraNamespaceLoc;
Douglas Gregor6b6bba42009-06-17 19:49:00 +000076
Aaron Ballman730476b2014-11-08 15:33:35 +000077 ParsedAttributesWithRange attrs(AttrFactory);
78 SourceLocation attrLoc;
79 if (getLangOpts().CPlusPlus11 && isCXX11AttributeSpecifier()) {
Aaron Ballmanc351fba2017-12-04 20:27:34 +000080 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
Richard Smith40e202f2017-10-14 00:56:24 +000081 ? diag::warn_cxx14_compat_ns_enum_attribute
82 : diag::ext_ns_enum_attribute)
83 << 0 /*namespace*/;
Aaron Ballman730476b2014-11-08 15:33:35 +000084 attrLoc = Tok.getLocation();
85 ParseCXX11Attributes(attrs);
86 }
Mike Stump11289f42009-09-09 15:08:12 +000087
Chris Lattner76c72282007-10-09 17:33:22 +000088 if (Tok.is(tok::identifier)) {
Chris Lattnera5235172007-08-25 06:57:03 +000089 Ident = Tok.getIdentifierInfo();
90 IdentLoc = ConsumeToken(); // eat the identifier.
Richard Trieu61384cb2011-05-26 20:11:09 +000091 while (Tok.is(tok::coloncolon) && NextToken().is(tok::identifier)) {
92 ExtraNamespaceLoc.push_back(ConsumeToken());
93 ExtraIdent.push_back(Tok.getIdentifierInfo());
94 ExtraIdentLoc.push_back(ConsumeToken());
95 }
Chris Lattnera5235172007-08-25 06:57:03 +000096 }
Mike Stump11289f42009-09-09 15:08:12 +000097
Aaron Ballmanc0ae7df2014-11-08 17:07:15 +000098 // A nested namespace definition cannot have attributes.
99 if (!ExtraNamespaceLoc.empty() && attrLoc.isValid())
100 Diag(attrLoc, diag::err_unexpected_nested_namespace_attribute);
101
Chris Lattnera5235172007-08-25 06:57:03 +0000102 // Read label attributes, if present.
Douglas Gregor6b6bba42009-06-17 19:49:00 +0000103 if (Tok.is(tok::kw___attribute)) {
Aaron Ballman730476b2014-11-08 15:33:35 +0000104 attrLoc = Tok.getLocation();
John McCall53fa7142010-12-24 02:08:15 +0000105 ParseGNUAttributes(attrs);
Douglas Gregor6b6bba42009-06-17 19:49:00 +0000106 }
Mike Stump11289f42009-09-09 15:08:12 +0000107
Douglas Gregor6b6bba42009-06-17 19:49:00 +0000108 if (Tok.is(tok::equal)) {
Craig Topper161e4db2014-05-21 06:02:52 +0000109 if (!Ident) {
Alp Tokerec543272013-12-24 09:48:30 +0000110 Diag(Tok, diag::err_expected) << tok::identifier;
Nico Weber729f1e22012-10-27 23:44:27 +0000111 // Skip to end of the definition and eat the ';'.
112 SkipUntil(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +0000113 return nullptr;
Nico Weber729f1e22012-10-27 23:44:27 +0000114 }
Aaron Ballman730476b2014-11-08 15:33:35 +0000115 if (attrLoc.isValid())
116 Diag(attrLoc, diag::err_unexpected_namespace_attributes_alias);
Sebastian Redl67667942010-08-27 23:12:46 +0000117 if (InlineLoc.isValid())
118 Diag(InlineLoc, diag::err_inline_namespace_alias)
119 << FixItHint::CreateRemoval(InlineLoc);
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +0000120 Decl *NSAlias = ParseNamespaceAlias(NamespaceLoc, IdentLoc, Ident, DeclEnd);
121 return Actions.ConvertDeclToDeclGroup(NSAlias);
122}
Mike Stump11289f42009-09-09 15:08:12 +0000123
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000124 BalancedDelimiterTracker T(*this, tok::l_brace);
125 if (T.consumeOpen()) {
Alp Tokerec543272013-12-24 09:48:30 +0000126 if (Ident)
127 Diag(Tok, diag::err_expected) << tok::l_brace;
128 else
129 Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace;
David Blaikie0403cb12016-01-15 23:43:25 +0000130 return nullptr;
Chris Lattnera5235172007-08-25 06:57:03 +0000131 }
Mike Stump11289f42009-09-09 15:08:12 +0000132
Douglas Gregor0be31a22010-07-02 17:43:08 +0000133 if (getCurScope()->isClassScope() || getCurScope()->isTemplateParamScope() ||
134 getCurScope()->isInObjcMethodScope() || getCurScope()->getBlockParent() ||
135 getCurScope()->getFnParent()) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000136 Diag(T.getOpenLocation(), diag::err_namespace_nonnamespace_scope);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000137 SkipUntil(tok::r_brace);
David Blaikie0403cb12016-01-15 23:43:25 +0000138 return nullptr;
Douglas Gregor05cfc292010-05-14 05:08:22 +0000139 }
140
Richard Smith13307f52014-11-08 05:37:34 +0000141 if (ExtraIdent.empty()) {
142 // Normal namespace definition, not a nested-namespace-definition.
143 } else if (InlineLoc.isValid()) {
144 Diag(InlineLoc, diag::err_inline_nested_namespace_definition);
Aaron Ballmanc351fba2017-12-04 20:27:34 +0000145 } else if (getLangOpts().CPlusPlus17) {
Richard Smith13307f52014-11-08 05:37:34 +0000146 Diag(ExtraNamespaceLoc[0],
147 diag::warn_cxx14_compat_nested_namespace_definition);
148 } else {
Richard Trieu61384cb2011-05-26 20:11:09 +0000149 TentativeParsingAction TPA(*this);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000150 SkipUntil(tok::r_brace, StopBeforeMatch);
Richard Trieu61384cb2011-05-26 20:11:09 +0000151 Token rBraceToken = Tok;
152 TPA.Revert();
153
154 if (!rBraceToken.is(tok::r_brace)) {
Richard Smith13307f52014-11-08 05:37:34 +0000155 Diag(ExtraNamespaceLoc[0], diag::ext_nested_namespace_definition)
Richard Trieu61384cb2011-05-26 20:11:09 +0000156 << SourceRange(ExtraNamespaceLoc.front(), ExtraIdentLoc.back());
157 } else {
Benjamin Kramerf546f412011-05-26 21:32:30 +0000158 std::string NamespaceFix;
Richard Trieu61384cb2011-05-26 20:11:09 +0000159 for (std::vector<IdentifierInfo*>::iterator I = ExtraIdent.begin(),
160 E = ExtraIdent.end(); I != E; ++I) {
161 NamespaceFix += " { namespace ";
162 NamespaceFix += (*I)->getName();
163 }
Benjamin Kramerf546f412011-05-26 21:32:30 +0000164
Richard Trieu61384cb2011-05-26 20:11:09 +0000165 std::string RBraces;
Benjamin Kramerf546f412011-05-26 21:32:30 +0000166 for (unsigned i = 0, e = ExtraIdent.size(); i != e; ++i)
Richard Trieu61384cb2011-05-26 20:11:09 +0000167 RBraces += "} ";
Benjamin Kramerf546f412011-05-26 21:32:30 +0000168
Richard Smith13307f52014-11-08 05:37:34 +0000169 Diag(ExtraNamespaceLoc[0], diag::ext_nested_namespace_definition)
Richard Trieu61384cb2011-05-26 20:11:09 +0000170 << FixItHint::CreateReplacement(SourceRange(ExtraNamespaceLoc.front(),
171 ExtraIdentLoc.back()),
172 NamespaceFix)
173 << FixItHint::CreateInsertion(rBraceToken.getLocation(), RBraces);
174 }
175 }
176
Sebastian Redl5a5f2c72010-08-31 00:36:45 +0000177 // If we're still good, complain about inline namespaces in non-C++0x now.
Richard Smith5d164bc2011-10-15 05:09:34 +0000178 if (InlineLoc.isValid())
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000179 Diag(InlineLoc, getLangOpts().CPlusPlus11 ?
Richard Smith5d164bc2011-10-15 05:09:34 +0000180 diag::warn_cxx98_compat_inline_namespace : diag::ext_inline_namespace);
Sebastian Redl5a5f2c72010-08-31 00:36:45 +0000181
Chris Lattner4de55aa2009-03-29 14:02:43 +0000182 // Enter a scope for the namespace.
183 ParseScope NamespaceScope(this, Scope::DeclScope);
184
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +0000185 UsingDirectiveDecl *ImplicitUsingDirectiveDecl = nullptr;
John McCall48871652010-08-21 09:40:31 +0000186 Decl *NamespcDecl =
Abramo Bagnarab5545be2011-03-08 12:38:20 +0000187 Actions.ActOnStartNamespaceDef(getCurScope(), InlineLoc, NamespaceLoc,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000188 IdentLoc, Ident, T.getOpenLocation(),
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +0000189 attrs.getList(), ImplicitUsingDirectiveDecl);
Chris Lattner4de55aa2009-03-29 14:02:43 +0000190
John McCallfaf5fb42010-08-26 23:41:50 +0000191 PrettyDeclStackTraceEntry CrashInfo(Actions, NamespcDecl, NamespaceLoc,
192 "parsing namespace");
Mike Stump11289f42009-09-09 15:08:12 +0000193
Richard Trieu61384cb2011-05-26 20:11:09 +0000194 // Parse the contents of the namespace. This includes parsing recovery on
195 // any improperly nested namespaces.
196 ParseInnerNamespace(ExtraIdentLoc, ExtraIdent, ExtraNamespaceLoc, 0,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000197 InlineLoc, attrs, T);
Mike Stump11289f42009-09-09 15:08:12 +0000198
Chris Lattner4de55aa2009-03-29 14:02:43 +0000199 // Leave the namespace scope.
200 NamespaceScope.Exit();
201
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000202 DeclEnd = T.getCloseLocation();
203 Actions.ActOnFinishNamespaceDef(NamespcDecl, DeclEnd);
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +0000204
205 return Actions.ConvertDeclToDeclGroup(NamespcDecl,
206 ImplicitUsingDirectiveDecl);
Chris Lattnera5235172007-08-25 06:57:03 +0000207}
Chris Lattner38376f12008-01-12 07:05:38 +0000208
Richard Trieu61384cb2011-05-26 20:11:09 +0000209/// ParseInnerNamespace - Parse the contents of a namespace.
Richard Smith13307f52014-11-08 05:37:34 +0000210void Parser::ParseInnerNamespace(std::vector<SourceLocation> &IdentLoc,
211 std::vector<IdentifierInfo *> &Ident,
212 std::vector<SourceLocation> &NamespaceLoc,
213 unsigned int index, SourceLocation &InlineLoc,
214 ParsedAttributes &attrs,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000215 BalancedDelimiterTracker &Tracker) {
Richard Trieu61384cb2011-05-26 20:11:09 +0000216 if (index == Ident.size()) {
Richard Smith752ada82015-11-17 23:32:01 +0000217 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
218 Tok.isNot(tok::eof)) {
Richard Trieu61384cb2011-05-26 20:11:09 +0000219 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +0000220 MaybeParseCXX11Attributes(attrs);
Richard Trieu61384cb2011-05-26 20:11:09 +0000221 ParseExternalDeclaration(attrs);
222 }
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000223
224 // The caller is what called check -- we are simply calling
225 // the close for it.
226 Tracker.consumeClose();
Richard Trieu61384cb2011-05-26 20:11:09 +0000227
228 return;
229 }
230
Richard Smith13307f52014-11-08 05:37:34 +0000231 // Handle a nested namespace definition.
232 // FIXME: Preserve the source information through to the AST rather than
233 // desugaring it here.
Richard Trieu61384cb2011-05-26 20:11:09 +0000234 ParseScope NamespaceScope(this, Scope::DeclScope);
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +0000235 UsingDirectiveDecl *ImplicitUsingDirectiveDecl = nullptr;
Richard Trieu61384cb2011-05-26 20:11:09 +0000236 Decl *NamespcDecl =
237 Actions.ActOnStartNamespaceDef(getCurScope(), SourceLocation(),
238 NamespaceLoc[index], IdentLoc[index],
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000239 Ident[index], Tracker.getOpenLocation(),
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +0000240 attrs.getList(), ImplicitUsingDirectiveDecl);
241 assert(!ImplicitUsingDirectiveDecl &&
242 "nested namespace definition cannot define anonymous namespace");
Richard Trieu61384cb2011-05-26 20:11:09 +0000243
244 ParseInnerNamespace(IdentLoc, Ident, NamespaceLoc, ++index, InlineLoc,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000245 attrs, Tracker);
Richard Trieu61384cb2011-05-26 20:11:09 +0000246
247 NamespaceScope.Exit();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000248 Actions.ActOnFinishNamespaceDef(NamespcDecl, Tracker.getCloseLocation());
Richard Trieu61384cb2011-05-26 20:11:09 +0000249}
250
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000251/// ParseNamespaceAlias - Parse the part after the '=' in a namespace
252/// alias definition.
253///
John McCall48871652010-08-21 09:40:31 +0000254Decl *Parser::ParseNamespaceAlias(SourceLocation NamespaceLoc,
John McCall084e83d2011-03-24 11:26:52 +0000255 SourceLocation AliasLoc,
256 IdentifierInfo *Alias,
257 SourceLocation &DeclEnd) {
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000258 assert(Tok.is(tok::equal) && "Not equal token");
Mike Stump11289f42009-09-09 15:08:12 +0000259
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000260 ConsumeToken(); // eat the '='.
Mike Stump11289f42009-09-09 15:08:12 +0000261
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000262 if (Tok.is(tok::code_completion)) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000263 Actions.CodeCompleteNamespaceAliasDecl(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000264 cutOffParsing();
Craig Topper161e4db2014-05-21 06:02:52 +0000265 return nullptr;
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000266 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000267
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000268 CXXScopeSpec SS;
269 // Parse (optional) nested-name-specifier.
Matthias Gehredc01bb42017-03-17 21:41:20 +0000270 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false,
271 /*MayBePseudoDestructor=*/nullptr,
272 /*IsTypename=*/false,
273 /*LastII=*/nullptr,
274 /*OnlyNamespace=*/true);
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000275
Matthias Gehredc01bb42017-03-17 21:41:20 +0000276 if (Tok.isNot(tok::identifier)) {
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000277 Diag(Tok, diag::err_expected_namespace_name);
278 // Skip to end of the definition and eat the ';'.
279 SkipUntil(tok::semi);
Craig Topper161e4db2014-05-21 06:02:52 +0000280 return nullptr;
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000281 }
282
Matthias Gehredc01bb42017-03-17 21:41:20 +0000283 if (SS.isInvalid()) {
284 // Diagnostics have been emitted in ParseOptionalCXXScopeSpecifier.
285 // Skip to end of the definition and eat the ';'.
286 SkipUntil(tok::semi);
287 return nullptr;
288 }
289
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000290 // Parse identifier.
Anders Carlsson47952ae2009-03-28 22:53:22 +0000291 IdentifierInfo *Ident = Tok.getIdentifierInfo();
292 SourceLocation IdentLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000293
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000294 // Eat the ';'.
Chris Lattner49836b42009-04-02 04:16:50 +0000295 DeclEnd = Tok.getLocation();
Alp Toker383d2c42014-01-01 03:08:43 +0000296 if (ExpectAndConsume(tok::semi, diag::err_expected_semi_after_namespace_name))
297 SkipUntil(tok::semi);
Mike Stump11289f42009-09-09 15:08:12 +0000298
Craig Topperff354282015-11-14 18:16:00 +0000299 return Actions.ActOnNamespaceAliasDef(getCurScope(), NamespaceLoc, AliasLoc,
300 Alias, SS, IdentLoc, Ident);
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000301}
302
Chris Lattner38376f12008-01-12 07:05:38 +0000303/// ParseLinkage - We know that the current token is a string_literal
304/// and just before that, that extern was seen.
305///
306/// linkage-specification: [C++ 7.5p2: dcl.link]
307/// 'extern' string-literal '{' declaration-seq[opt] '}'
308/// 'extern' string-literal declaration
309///
Chris Lattner8ea64422010-11-09 20:15:55 +0000310Decl *Parser::ParseLinkage(ParsingDeclSpec &DS, unsigned Context) {
Richard Smith4ee696d2014-02-17 23:25:27 +0000311 assert(isTokenStringLiteral() && "Not a string literal!");
312 ExprResult Lang = ParseStringLiteralExpression(false);
Chris Lattner38376f12008-01-12 07:05:38 +0000313
Douglas Gregor07665a62009-01-05 19:45:36 +0000314 ParseScope LinkageScope(this, Scope::DeclScope);
Richard Smith4ee696d2014-02-17 23:25:27 +0000315 Decl *LinkageSpec =
316 Lang.isInvalid()
Craig Topper161e4db2014-05-21 06:02:52 +0000317 ? nullptr
Richard Smith4ee696d2014-02-17 23:25:27 +0000318 : Actions.ActOnStartLinkageSpecification(
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000319 getCurScope(), DS.getSourceRange().getBegin(), Lang.get(),
Richard Smith4ee696d2014-02-17 23:25:27 +0000320 Tok.is(tok::l_brace) ? Tok.getLocation() : SourceLocation());
Douglas Gregor07665a62009-01-05 19:45:36 +0000321
John McCall084e83d2011-03-24 11:26:52 +0000322 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +0000323 MaybeParseCXX11Attributes(attrs);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000324
Douglas Gregor07665a62009-01-05 19:45:36 +0000325 if (Tok.isNot(tok::l_brace)) {
Abramo Bagnara4d423992011-05-01 16:25:54 +0000326 // Reset the source range in DS, as the leading "extern"
327 // does not really belong to the inner declaration ...
328 DS.SetRangeStart(SourceLocation());
329 DS.SetRangeEnd(SourceLocation());
330 // ... but anyway remember that such an "extern" was seen.
Abramo Bagnaraed5b6892010-07-30 16:47:02 +0000331 DS.setExternInLinkageSpec(true);
John McCall53fa7142010-12-24 02:08:15 +0000332 ParseExternalDeclaration(attrs, &DS);
Richard Smith4ee696d2014-02-17 23:25:27 +0000333 return LinkageSpec ? Actions.ActOnFinishLinkageSpecification(
334 getCurScope(), LinkageSpec, SourceLocation())
Craig Topper161e4db2014-05-21 06:02:52 +0000335 : nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000336 }
Douglas Gregor29ff7d02008-12-16 22:23:02 +0000337
Douglas Gregorb65a9132010-02-07 08:38:28 +0000338 DS.abort();
339
John McCall53fa7142010-12-24 02:08:15 +0000340 ProhibitAttributes(attrs);
Alexis Hunt96d5c762009-11-21 08:43:09 +0000341
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000342 BalancedDelimiterTracker T(*this, tok::l_brace);
343 T.consumeOpen();
Richard Smith77944862014-03-02 05:58:18 +0000344
345 unsigned NestedModules = 0;
346 while (true) {
347 switch (Tok.getKind()) {
348 case tok::annot_module_begin:
349 ++NestedModules;
350 ParseTopLevelDecl();
351 continue;
352
353 case tok::annot_module_end:
354 if (!NestedModules)
355 break;
356 --NestedModules;
357 ParseTopLevelDecl();
358 continue;
359
360 case tok::annot_module_include:
361 ParseTopLevelDecl();
362 continue;
363
364 case tok::eof:
365 break;
366
367 case tok::r_brace:
368 if (!NestedModules)
369 break;
370 // Fall through.
371 default:
372 ParsedAttributesWithRange attrs(AttrFactory);
373 MaybeParseCXX11Attributes(attrs);
Richard Smith77944862014-03-02 05:58:18 +0000374 ParseExternalDeclaration(attrs);
375 continue;
376 }
377
378 break;
Chris Lattner38376f12008-01-12 07:05:38 +0000379 }
380
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000381 T.consumeClose();
Richard Smith4ee696d2014-02-17 23:25:27 +0000382 return LinkageSpec ? Actions.ActOnFinishLinkageSpecification(
383 getCurScope(), LinkageSpec, T.getCloseLocation())
Craig Topper161e4db2014-05-21 06:02:52 +0000384 : nullptr;
Chris Lattner38376f12008-01-12 07:05:38 +0000385}
Douglas Gregor556877c2008-04-13 21:30:24 +0000386
Richard Smith8df390f2016-09-08 23:14:54 +0000387/// Parse a C++ Modules TS export-declaration.
388///
389/// export-declaration:
390/// 'export' declaration
391/// 'export' '{' declaration-seq[opt] '}'
392///
393Decl *Parser::ParseExportDeclaration() {
394 assert(Tok.is(tok::kw_export));
395 SourceLocation ExportLoc = ConsumeToken();
396
397 ParseScope ExportScope(this, Scope::DeclScope);
398 Decl *ExportDecl = Actions.ActOnStartExportDecl(
399 getCurScope(), ExportLoc,
400 Tok.is(tok::l_brace) ? Tok.getLocation() : SourceLocation());
401
402 if (Tok.isNot(tok::l_brace)) {
403 // FIXME: Factor out a ParseExternalDeclarationWithAttrs.
404 ParsedAttributesWithRange Attrs(AttrFactory);
405 MaybeParseCXX11Attributes(Attrs);
406 MaybeParseMicrosoftAttributes(Attrs);
407 ParseExternalDeclaration(Attrs);
408 return Actions.ActOnFinishExportDecl(getCurScope(), ExportDecl,
409 SourceLocation());
410 }
411
412 BalancedDelimiterTracker T(*this, tok::l_brace);
413 T.consumeOpen();
414
415 // The Modules TS draft says "An export-declaration shall declare at least one
416 // entity", but the intent is that it shall contain at least one declaration.
417 if (Tok.is(tok::r_brace))
418 Diag(ExportLoc, diag::err_export_empty)
419 << SourceRange(ExportLoc, Tok.getLocation());
420
421 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
422 Tok.isNot(tok::eof)) {
423 ParsedAttributesWithRange Attrs(AttrFactory);
424 MaybeParseCXX11Attributes(Attrs);
425 MaybeParseMicrosoftAttributes(Attrs);
426 ParseExternalDeclaration(Attrs);
427 }
428
429 T.consumeClose();
430 return Actions.ActOnFinishExportDecl(getCurScope(), ExportDecl,
431 T.getCloseLocation());
432}
433
Douglas Gregord7c4d982008-12-30 03:27:21 +0000434/// ParseUsingDirectiveOrDeclaration - Parse C++ using using-declaration or
435/// using-directive. Assumes that current token is 'using'.
Richard Smith6f1daa42016-12-16 00:58:48 +0000436Parser::DeclGroupPtrTy
437Parser::ParseUsingDirectiveOrDeclaration(unsigned Context,
John McCall9b72f892010-11-10 02:40:36 +0000438 const ParsedTemplateInfo &TemplateInfo,
Richard Smith6f1daa42016-12-16 00:58:48 +0000439 SourceLocation &DeclEnd,
440 ParsedAttributesWithRange &attrs) {
Douglas Gregord7c4d982008-12-30 03:27:21 +0000441 assert(Tok.is(tok::kw_using) && "Not using token");
Fariborz Jahanian4bf82622011-08-22 17:59:19 +0000442 ObjCDeclContextSwitch ObjCDC(*this);
443
Douglas Gregord7c4d982008-12-30 03:27:21 +0000444 // Eat 'using'.
445 SourceLocation UsingLoc = ConsumeToken();
446
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000447 if (Tok.is(tok::code_completion)) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000448 Actions.CodeCompleteUsing(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000449 cutOffParsing();
Craig Topper161e4db2014-05-21 06:02:52 +0000450 return nullptr;
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000451 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000452
John McCall9b72f892010-11-10 02:40:36 +0000453 // 'using namespace' means this is a using-directive.
454 if (Tok.is(tok::kw_namespace)) {
455 // Template parameters are always an error here.
456 if (TemplateInfo.Kind) {
457 SourceRange R = TemplateInfo.getSourceRange();
Craig Topper54a6a682015-11-14 18:16:08 +0000458 Diag(UsingLoc, diag::err_templated_using_directive_declaration)
459 << 0 /* directive */ << R << FixItHint::CreateRemoval(R);
John McCall9b72f892010-11-10 02:40:36 +0000460 }
Alexis Hunt96d5c762009-11-21 08:43:09 +0000461
Richard Smith6f1daa42016-12-16 00:58:48 +0000462 Decl *UsingDir = ParseUsingDirective(Context, UsingLoc, DeclEnd, attrs);
463 return Actions.ConvertDeclToDeclGroup(UsingDir);
John McCall9b72f892010-11-10 02:40:36 +0000464 }
465
Richard Smithdda56e42011-04-15 14:24:37 +0000466 // Otherwise, it must be a using-declaration or an alias-declaration.
John McCall9b72f892010-11-10 02:40:36 +0000467
468 // Using declarations can't have attributes.
John McCall53fa7142010-12-24 02:08:15 +0000469 ProhibitAttributes(attrs);
Chris Lattner9b01ca12009-01-06 06:55:51 +0000470
Fariborz Jahanian4bf82622011-08-22 17:59:19 +0000471 return ParseUsingDeclaration(Context, TemplateInfo, UsingLoc, DeclEnd,
Richard Smith6f1daa42016-12-16 00:58:48 +0000472 AS_none);
Douglas Gregord7c4d982008-12-30 03:27:21 +0000473}
474
475/// ParseUsingDirective - Parse C++ using-directive, assumes
476/// that current token is 'namespace' and 'using' was already parsed.
477///
478/// using-directive: [C++ 7.3.p4: namespace.udir]
479/// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
480/// namespace-name ;
481/// [GNU] using-directive:
482/// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
483/// namespace-name attributes[opt] ;
484///
John McCall48871652010-08-21 09:40:31 +0000485Decl *Parser::ParseUsingDirective(unsigned Context,
John McCall9b72f892010-11-10 02:40:36 +0000486 SourceLocation UsingLoc,
487 SourceLocation &DeclEnd,
John McCall53fa7142010-12-24 02:08:15 +0000488 ParsedAttributes &attrs) {
Douglas Gregord7c4d982008-12-30 03:27:21 +0000489 assert(Tok.is(tok::kw_namespace) && "Not 'namespace' token");
490
491 // Eat 'namespace'.
492 SourceLocation NamespcLoc = ConsumeToken();
493
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000494 if (Tok.is(tok::code_completion)) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000495 Actions.CodeCompleteUsingDirective(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000496 cutOffParsing();
Craig Topper161e4db2014-05-21 06:02:52 +0000497 return nullptr;
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000498 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000499
Douglas Gregord7c4d982008-12-30 03:27:21 +0000500 CXXScopeSpec SS;
501 // Parse (optional) nested-name-specifier.
Matthias Gehredc01bb42017-03-17 21:41:20 +0000502 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false,
503 /*MayBePseudoDestructor=*/nullptr,
504 /*IsTypename=*/false,
505 /*LastII=*/nullptr,
506 /*OnlyNamespace=*/true);
Douglas Gregord7c4d982008-12-30 03:27:21 +0000507
Craig Topper161e4db2014-05-21 06:02:52 +0000508 IdentifierInfo *NamespcName = nullptr;
Douglas Gregord7c4d982008-12-30 03:27:21 +0000509 SourceLocation IdentLoc = SourceLocation();
510
511 // Parse namespace-name.
Matthias Gehredc01bb42017-03-17 21:41:20 +0000512 if (Tok.isNot(tok::identifier)) {
Douglas Gregord7c4d982008-12-30 03:27:21 +0000513 Diag(Tok, diag::err_expected_namespace_name);
514 // If there was invalid namespace name, skip to end of decl, and eat ';'.
515 SkipUntil(tok::semi);
516 // FIXME: Are there cases, when we would like to call ActOnUsingDirective?
Craig Topper161e4db2014-05-21 06:02:52 +0000517 return nullptr;
Douglas Gregord7c4d982008-12-30 03:27:21 +0000518 }
Mike Stump11289f42009-09-09 15:08:12 +0000519
Matthias Gehredc01bb42017-03-17 21:41:20 +0000520 if (SS.isInvalid()) {
521 // Diagnostics have been emitted in ParseOptionalCXXScopeSpecifier.
522 // Skip to end of the definition and eat the ';'.
523 SkipUntil(tok::semi);
524 return nullptr;
525 }
526
Chris Lattnerce1da2c2009-01-06 07:27:21 +0000527 // Parse identifier.
528 NamespcName = Tok.getIdentifierInfo();
529 IdentLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000530
Chris Lattnerce1da2c2009-01-06 07:27:21 +0000531 // Parse (optional) attributes (most likely GNU strong-using extension).
Alexis Hunt96d5c762009-11-21 08:43:09 +0000532 bool GNUAttr = false;
533 if (Tok.is(tok::kw___attribute)) {
534 GNUAttr = true;
John McCall53fa7142010-12-24 02:08:15 +0000535 ParseGNUAttributes(attrs);
Alexis Hunt96d5c762009-11-21 08:43:09 +0000536 }
Mike Stump11289f42009-09-09 15:08:12 +0000537
Chris Lattnerce1da2c2009-01-06 07:27:21 +0000538 // Eat ';'.
Chris Lattner49836b42009-04-02 04:16:50 +0000539 DeclEnd = Tok.getLocation();
Alp Toker383d2c42014-01-01 03:08:43 +0000540 if (ExpectAndConsume(tok::semi,
541 GNUAttr ? diag::err_expected_semi_after_attribute_list
542 : diag::err_expected_semi_after_namespace_name))
543 SkipUntil(tok::semi);
Douglas Gregord7c4d982008-12-30 03:27:21 +0000544
Douglas Gregor0be31a22010-07-02 17:43:08 +0000545 return Actions.ActOnUsingDirective(getCurScope(), UsingLoc, NamespcLoc, SS,
John McCall53fa7142010-12-24 02:08:15 +0000546 IdentLoc, NamespcName, attrs.getList());
Douglas Gregord7c4d982008-12-30 03:27:21 +0000547}
548
Richard Smith6f1daa42016-12-16 00:58:48 +0000549/// Parse a using-declarator (or the identifier in a C++11 alias-declaration).
Douglas Gregord7c4d982008-12-30 03:27:21 +0000550///
Richard Smith6f1daa42016-12-16 00:58:48 +0000551/// using-declarator:
552/// 'typename'[opt] nested-name-specifier unqualified-id
Douglas Gregord7c4d982008-12-30 03:27:21 +0000553///
Richard Smith6f1daa42016-12-16 00:58:48 +0000554bool Parser::ParseUsingDeclarator(unsigned Context, UsingDeclarator &D) {
555 D.clear();
Douglas Gregorfec52632009-06-20 00:51:54 +0000556
557 // Ignore optional 'typename'.
Douglas Gregor220f4272009-11-04 16:30:06 +0000558 // FIXME: This is wrong; we should parse this as a typename-specifier.
Richard Smith6f1daa42016-12-16 00:58:48 +0000559 TryConsumeToken(tok::kw_typename, D.TypenameLoc);
Douglas Gregorfec52632009-06-20 00:51:54 +0000560
Nikola Smiljanic67860242014-09-26 00:28:20 +0000561 if (Tok.is(tok::kw___super)) {
562 Diag(Tok.getLocation(), diag::err_super_in_using_declaration);
Richard Smith6f1daa42016-12-16 00:58:48 +0000563 return true;
Nikola Smiljanic67860242014-09-26 00:28:20 +0000564 }
565
Douglas Gregorfec52632009-06-20 00:51:54 +0000566 // Parse nested-name-specifier.
Craig Topper161e4db2014-05-21 06:02:52 +0000567 IdentifierInfo *LastII = nullptr;
Richard Smith6f1daa42016-12-16 00:58:48 +0000568 ParseOptionalCXXScopeSpecifier(D.SS, nullptr, /*EnteringContext=*/false,
Craig Topper161e4db2014-05-21 06:02:52 +0000569 /*MayBePseudoDtor=*/nullptr,
570 /*IsTypename=*/false,
Richard Smith7447af42013-03-26 01:15:19 +0000571 /*LastII=*/&LastII);
Richard Smith6f1daa42016-12-16 00:58:48 +0000572 if (D.SS.isInvalid())
573 return true;
Richard Smith7447af42013-03-26 01:15:19 +0000574
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000575 // Parse the unqualified-id. We allow parsing of both constructor and
Douglas Gregor220f4272009-11-04 16:30:06 +0000576 // destructor names and allow the action module to diagnose any semantic
577 // errors.
Richard Smith7447af42013-03-26 01:15:19 +0000578 //
579 // C++11 [class.qual]p2:
580 // [...] in a using-declaration that is a member-declaration, if the name
581 // specified after the nested-name-specifier is the same as the identifier
582 // or the simple-template-id's template-name in the last component of the
583 // nested-name-specifier, the name is [...] considered to name the
584 // constructor.
585 if (getLangOpts().CPlusPlus11 && Context == Declarator::MemberContext &&
Richard Smith151c4562016-12-20 21:35:28 +0000586 Tok.is(tok::identifier) &&
587 (NextToken().is(tok::semi) || NextToken().is(tok::comma) ||
588 NextToken().is(tok::ellipsis)) &&
Richard Smith6f1daa42016-12-16 00:58:48 +0000589 D.SS.isNotEmpty() && LastII == Tok.getIdentifierInfo() &&
590 !D.SS.getScopeRep()->getAsNamespace() &&
591 !D.SS.getScopeRep()->getAsNamespaceAlias()) {
Richard Smith7447af42013-03-26 01:15:19 +0000592 SourceLocation IdLoc = ConsumeToken();
Richard Smith6f1daa42016-12-16 00:58:48 +0000593 ParsedType Type =
594 Actions.getInheritingConstructorName(D.SS, IdLoc, *LastII);
595 D.Name.setConstructorName(Type, IdLoc, IdLoc);
596 } else {
597 if (ParseUnqualifiedId(
598 D.SS, /*EnteringContext=*/false,
599 /*AllowDestructorName=*/true,
600 /*AllowConstructorName=*/!(Tok.is(tok::identifier) &&
601 NextToken().is(tok::equal)),
Richard Smith35845152017-02-07 01:37:30 +0000602 /*AllowDeductionGuide=*/false,
Richard Smith6f1daa42016-12-16 00:58:48 +0000603 nullptr, D.TemplateKWLoc, D.Name))
604 return true;
Douglas Gregorfec52632009-06-20 00:51:54 +0000605 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000606
Richard Smith151c4562016-12-20 21:35:28 +0000607 if (TryConsumeToken(tok::ellipsis, D.EllipsisLoc))
Aaron Ballmanc351fba2017-12-04 20:27:34 +0000608 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17 ?
Richard Smithb115e5d2017-08-13 23:37:29 +0000609 diag::warn_cxx17_compat_using_declaration_pack :
Richard Smith151c4562016-12-20 21:35:28 +0000610 diag::ext_using_declaration_pack);
Richard Smith6f1daa42016-12-16 00:58:48 +0000611
612 return false;
613}
614
615/// ParseUsingDeclaration - Parse C++ using-declaration or alias-declaration.
616/// Assumes that 'using' was already seen.
617///
618/// using-declaration: [C++ 7.3.p3: namespace.udecl]
619/// 'using' using-declarator-list[opt] ;
620///
621/// using-declarator-list: [C++1z]
622/// using-declarator '...'[opt]
623/// using-declarator-list ',' using-declarator '...'[opt]
624///
625/// using-declarator-list: [C++98-14]
626/// using-declarator
627///
628/// alias-declaration: C++11 [dcl.dcl]p1
629/// 'using' identifier attribute-specifier-seq[opt] = type-id ;
630///
631Parser::DeclGroupPtrTy
632Parser::ParseUsingDeclaration(unsigned Context,
633 const ParsedTemplateInfo &TemplateInfo,
634 SourceLocation UsingLoc, SourceLocation &DeclEnd,
635 AccessSpecifier AS) {
636 // Check for misplaced attributes before the identifier in an
637 // alias-declaration.
638 ParsedAttributesWithRange MisplacedAttrs(AttrFactory);
639 MaybeParseCXX11Attributes(MisplacedAttrs);
640
641 UsingDeclarator D;
642 bool InvalidDeclarator = ParseUsingDeclarator(Context, D);
643
Richard Smithc2c8bb82013-10-15 01:34:54 +0000644 ParsedAttributesWithRange Attrs(AttrFactory);
Richard Smith37a45dd2013-10-24 01:21:09 +0000645 MaybeParseGNUAttributes(Attrs);
Richard Smith54ecd982013-02-20 19:22:51 +0000646 MaybeParseCXX11Attributes(Attrs);
Richard Smithdda56e42011-04-15 14:24:37 +0000647
648 // Maybe this is an alias-declaration.
Richard Smith6f1daa42016-12-16 00:58:48 +0000649 if (Tok.is(tok::equal)) {
650 if (InvalidDeclarator) {
651 SkipUntil(tok::semi);
652 return nullptr;
653 }
654
Richard Smithc2c8bb82013-10-15 01:34:54 +0000655 // If we had any misplaced attributes from earlier, this is where they
656 // should have been written.
657 if (MisplacedAttrs.Range.isValid()) {
658 Diag(MisplacedAttrs.Range.getBegin(), diag::err_attributes_not_allowed)
659 << FixItHint::CreateInsertionFromRange(
660 Tok.getLocation(),
661 CharSourceRange::getTokenRange(MisplacedAttrs.Range))
662 << FixItHint::CreateRemoval(MisplacedAttrs.Range);
663 Attrs.takeAllFrom(MisplacedAttrs);
664 }
665
Richard Smith6f1daa42016-12-16 00:58:48 +0000666 Decl *DeclFromDeclSpec = nullptr;
667 Decl *AD = ParseAliasDeclarationAfterDeclarator(
668 TemplateInfo, UsingLoc, D, DeclEnd, AS, Attrs, &DeclFromDeclSpec);
669 return Actions.ConvertDeclToDeclGroup(AD, DeclFromDeclSpec);
Alexis Hunt6aa9bee2012-06-23 05:07:58 +0000670 }
Mike Stump11289f42009-09-09 15:08:12 +0000671
Richard Smith6f1daa42016-12-16 00:58:48 +0000672 // C++11 attributes are not allowed on a using-declaration, but GNU ones
673 // are.
674 ProhibitAttributes(MisplacedAttrs);
675 ProhibitAttributes(Attrs);
Douglas Gregorfec52632009-06-20 00:51:54 +0000676
John McCall9b72f892010-11-10 02:40:36 +0000677 // Diagnose an attempt to declare a templated using-declaration.
Richard Smith810ad3e2013-01-29 10:02:16 +0000678 // In C++11, alias-declarations can be templates:
Richard Smithdda56e42011-04-15 14:24:37 +0000679 // template <...> using id = type;
Richard Smith6f1daa42016-12-16 00:58:48 +0000680 if (TemplateInfo.Kind) {
John McCall9b72f892010-11-10 02:40:36 +0000681 SourceRange R = TemplateInfo.getSourceRange();
Craig Topper54a6a682015-11-14 18:16:08 +0000682 Diag(UsingLoc, diag::err_templated_using_directive_declaration)
683 << 1 /* declaration */ << R << FixItHint::CreateRemoval(R);
John McCall9b72f892010-11-10 02:40:36 +0000684
685 // Unfortunately, we have to bail out instead of recovering by
686 // ignoring the parameters, just in case the nested name specifier
687 // depends on the parameters.
Craig Topper161e4db2014-05-21 06:02:52 +0000688 return nullptr;
John McCall9b72f892010-11-10 02:40:36 +0000689 }
690
Richard Smith6f1daa42016-12-16 00:58:48 +0000691 SmallVector<Decl *, 8> DeclsInGroup;
692 while (true) {
693 // Parse (optional) attributes (most likely GNU strong-using extension).
694 MaybeParseGNUAttributes(Attrs);
695
696 if (InvalidDeclarator)
697 SkipUntil(tok::comma, tok::semi, StopBeforeMatch);
698 else {
699 // "typename" keyword is allowed for identifiers only,
700 // because it may be a type definition.
701 if (D.TypenameLoc.isValid() &&
702 D.Name.getKind() != UnqualifiedId::IK_Identifier) {
703 Diag(D.Name.getSourceRange().getBegin(),
704 diag::err_typename_identifiers_only)
705 << FixItHint::CreateRemoval(SourceRange(D.TypenameLoc));
706 // Proceed parsing, but discard the typename keyword.
707 D.TypenameLoc = SourceLocation();
708 }
709
Richard Smith151c4562016-12-20 21:35:28 +0000710 Decl *UD = Actions.ActOnUsingDeclaration(getCurScope(), AS, UsingLoc,
711 D.TypenameLoc, D.SS, D.Name,
712 D.EllipsisLoc, Attrs.getList());
Richard Smith6f1daa42016-12-16 00:58:48 +0000713 if (UD)
714 DeclsInGroup.push_back(UD);
715 }
716
717 if (!TryConsumeToken(tok::comma))
718 break;
719
720 // Parse another using-declarator.
721 Attrs.clear();
722 InvalidDeclarator = ParseUsingDeclarator(Context, D);
Douglas Gregor882a61a2011-09-26 14:30:28 +0000723 }
724
Richard Smith6f1daa42016-12-16 00:58:48 +0000725 if (DeclsInGroup.size() > 1)
Aaron Ballmanc351fba2017-12-04 20:27:34 +0000726 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17 ?
Richard Smithb115e5d2017-08-13 23:37:29 +0000727 diag::warn_cxx17_compat_multi_using_declaration :
Richard Smith6f1daa42016-12-16 00:58:48 +0000728 diag::ext_multi_using_declaration);
729
730 // Eat ';'.
731 DeclEnd = Tok.getLocation();
732 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
733 !Attrs.empty() ? "attributes list"
734 : "using declaration"))
735 SkipUntil(tok::semi);
736
Richard Smith3beb7c62017-01-12 02:27:38 +0000737 return Actions.BuildDeclaratorGroup(DeclsInGroup);
Richard Smith6f1daa42016-12-16 00:58:48 +0000738}
739
Richard Smith6f1daa42016-12-16 00:58:48 +0000740Decl *Parser::ParseAliasDeclarationAfterDeclarator(
741 const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc,
742 UsingDeclarator &D, SourceLocation &DeclEnd, AccessSpecifier AS,
743 ParsedAttributes &Attrs, Decl **OwnedType) {
744 if (ExpectAndConsume(tok::equal)) {
745 SkipUntil(tok::semi);
746 return nullptr;
747 }
748
749 Diag(Tok.getLocation(), getLangOpts().CPlusPlus11 ?
750 diag::warn_cxx98_compat_alias_declaration :
751 diag::ext_alias_declaration);
752
753 // Type alias templates cannot be specialized.
754 int SpecKind = -1;
755 if (TemplateInfo.Kind == ParsedTemplateInfo::Template &&
756 D.Name.getKind() == UnqualifiedId::IK_TemplateId)
757 SpecKind = 0;
758 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization)
759 SpecKind = 1;
760 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
761 SpecKind = 2;
762 if (SpecKind != -1) {
763 SourceRange Range;
764 if (SpecKind == 0)
765 Range = SourceRange(D.Name.TemplateId->LAngleLoc,
766 D.Name.TemplateId->RAngleLoc);
767 else
768 Range = TemplateInfo.getSourceRange();
769 Diag(Range.getBegin(), diag::err_alias_declaration_specialization)
770 << SpecKind << Range;
771 SkipUntil(tok::semi);
772 return nullptr;
773 }
774
775 // Name must be an identifier.
776 if (D.Name.getKind() != UnqualifiedId::IK_Identifier) {
777 Diag(D.Name.StartLocation, diag::err_alias_declaration_not_identifier);
778 // No removal fixit: can't recover from this.
779 SkipUntil(tok::semi);
780 return nullptr;
781 } else if (D.TypenameLoc.isValid())
782 Diag(D.TypenameLoc, diag::err_alias_declaration_not_identifier)
783 << FixItHint::CreateRemoval(SourceRange(
784 D.TypenameLoc,
785 D.SS.isNotEmpty() ? D.SS.getEndLoc() : D.TypenameLoc));
786 else if (D.SS.isNotEmpty())
787 Diag(D.SS.getBeginLoc(), diag::err_alias_declaration_not_identifier)
788 << FixItHint::CreateRemoval(D.SS.getRange());
Richard Smith151c4562016-12-20 21:35:28 +0000789 if (D.EllipsisLoc.isValid())
790 Diag(D.EllipsisLoc, diag::err_alias_declaration_pack_expansion)
791 << FixItHint::CreateRemoval(SourceRange(D.EllipsisLoc));
Richard Smith6f1daa42016-12-16 00:58:48 +0000792
793 Decl *DeclFromDeclSpec = nullptr;
794 TypeResult TypeAlias =
795 ParseTypeName(nullptr,
796 TemplateInfo.Kind ? Declarator::AliasTemplateContext
797 : Declarator::AliasDeclContext,
798 AS, &DeclFromDeclSpec, &Attrs);
799 if (OwnedType)
800 *OwnedType = DeclFromDeclSpec;
801
802 // Eat ';'.
803 DeclEnd = Tok.getLocation();
804 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
805 !Attrs.empty() ? "attributes list"
806 : "alias declaration"))
807 SkipUntil(tok::semi);
808
809 TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
810 MultiTemplateParamsArg TemplateParamsArg(
811 TemplateParams ? TemplateParams->data() : nullptr,
812 TemplateParams ? TemplateParams->size() : 0);
813 return Actions.ActOnAliasDeclaration(getCurScope(), AS, TemplateParamsArg,
814 UsingLoc, D.Name, Attrs.getList(),
815 TypeAlias, DeclFromDeclSpec);
Douglas Gregord7c4d982008-12-30 03:27:21 +0000816}
817
Benjamin Kramere56f3932011-12-23 17:00:35 +0000818/// ParseStaticAssertDeclaration - Parse C++0x or C11 static_assert-declaration.
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000819///
Peter Collingbourne3d9cbdc2011-04-15 00:35:57 +0000820/// [C++0x] static_assert-declaration:
821/// static_assert ( constant-expression , string-literal ) ;
822///
Benjamin Kramere56f3932011-12-23 17:00:35 +0000823/// [C11] static_assert-declaration:
Peter Collingbourne3d9cbdc2011-04-15 00:35:57 +0000824/// _Static_assert ( constant-expression , string-literal ) ;
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000825///
John McCall48871652010-08-21 09:40:31 +0000826Decl *Parser::ParseStaticAssertDeclaration(SourceLocation &DeclEnd){
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000827 assert(Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert) &&
Peter Collingbourne3d9cbdc2011-04-15 00:35:57 +0000828 "Not a static_assert declaration");
829
David Blaikiebbafb8a2012-03-11 07:00:24 +0000830 if (Tok.is(tok::kw__Static_assert) && !getLangOpts().C11)
Benjamin Kramere56f3932011-12-23 17:00:35 +0000831 Diag(Tok, diag::ext_c11_static_assert);
Richard Smithb15c11c2011-10-17 23:06:20 +0000832 if (Tok.is(tok::kw_static_assert))
833 Diag(Tok, diag::warn_cxx98_compat_static_assert);
Peter Collingbourne3d9cbdc2011-04-15 00:35:57 +0000834
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000835 SourceLocation StaticAssertLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000836
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000837 BalancedDelimiterTracker T(*this, tok::l_paren);
838 if (T.consumeOpen()) {
Alp Tokerec543272013-12-24 09:48:30 +0000839 Diag(Tok, diag::err_expected) << tok::l_paren;
Richard Smith76965712012-09-13 19:12:50 +0000840 SkipMalformedDecl();
Craig Topper161e4db2014-05-21 06:02:52 +0000841 return nullptr;
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000842 }
Mike Stump11289f42009-09-09 15:08:12 +0000843
Richard Smithb3018062017-06-06 01:34:24 +0000844 EnterExpressionEvaluationContext ConstantEvaluated(
845 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
846 ExprResult AssertExpr(ParseConstantExpressionInExprEvalContext());
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000847 if (AssertExpr.isInvalid()) {
Richard Smith76965712012-09-13 19:12:50 +0000848 SkipMalformedDecl();
Craig Topper161e4db2014-05-21 06:02:52 +0000849 return nullptr;
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000850 }
Mike Stump11289f42009-09-09 15:08:12 +0000851
Richard Smith085a64f2014-06-20 19:57:12 +0000852 ExprResult AssertMessage;
853 if (Tok.is(tok::r_paren)) {
Aaron Ballmanc351fba2017-12-04 20:27:34 +0000854 Diag(Tok, getLangOpts().CPlusPlus17
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000855 ? diag::warn_cxx14_compat_static_assert_no_message
Richard Smith085a64f2014-06-20 19:57:12 +0000856 : diag::ext_static_assert_no_message)
Aaron Ballmanc351fba2017-12-04 20:27:34 +0000857 << (getLangOpts().CPlusPlus17
Richard Smith085a64f2014-06-20 19:57:12 +0000858 ? FixItHint()
859 : FixItHint::CreateInsertion(Tok.getLocation(), ", \"\""));
860 } else {
861 if (ExpectAndConsume(tok::comma)) {
862 SkipUntil(tok::semi);
863 return nullptr;
864 }
Anders Carlssonb4cf3ad2009-03-13 23:29:20 +0000865
Richard Smith085a64f2014-06-20 19:57:12 +0000866 if (!isTokenStringLiteral()) {
867 Diag(Tok, diag::err_expected_string_literal)
868 << /*Source='static_assert'*/1;
869 SkipMalformedDecl();
870 return nullptr;
871 }
Mike Stump11289f42009-09-09 15:08:12 +0000872
Richard Smith085a64f2014-06-20 19:57:12 +0000873 AssertMessage = ParseStringLiteralExpression();
874 if (AssertMessage.isInvalid()) {
875 SkipMalformedDecl();
876 return nullptr;
877 }
Richard Smithd67aea22012-03-06 03:21:47 +0000878 }
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000879
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000880 T.consumeClose();
Mike Stump11289f42009-09-09 15:08:12 +0000881
Chris Lattner49836b42009-04-02 04:16:50 +0000882 DeclEnd = Tok.getLocation();
Douglas Gregor45d6bdf2010-09-07 15:23:11 +0000883 ExpectAndConsumeSemi(diag::err_expected_semi_after_static_assert);
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000884
John McCallb268a282010-08-23 23:25:46 +0000885 return Actions.ActOnStaticAssertDeclaration(StaticAssertLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000886 AssertExpr.get(),
887 AssertMessage.get(),
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000888 T.getCloseLocation());
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000889}
890
Richard Smith74aeef52013-04-26 16:15:35 +0000891/// ParseDecltypeSpecifier - Parse a C++11 decltype specifier.
Anders Carlsson74948d02009-06-24 17:47:40 +0000892///
893/// 'decltype' ( expression )
Richard Smith74aeef52013-04-26 16:15:35 +0000894/// 'decltype' ( 'auto' ) [C++1y]
Anders Carlsson74948d02009-06-24 17:47:40 +0000895///
David Blaikie15a430a2011-12-04 05:04:18 +0000896SourceLocation Parser::ParseDecltypeSpecifier(DeclSpec &DS) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000897 assert(Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)
David Blaikie15a430a2011-12-04 05:04:18 +0000898 && "Not a decltype specifier");
899
David Blaikie15a430a2011-12-04 05:04:18 +0000900 ExprResult Result;
901 SourceLocation StartLoc = Tok.getLocation();
902 SourceLocation EndLoc;
903
904 if (Tok.is(tok::annot_decltype)) {
905 Result = getExprAnnotation(Tok);
906 EndLoc = Tok.getAnnotationEndLoc();
Richard Smithaf3b3252017-05-18 19:21:48 +0000907 ConsumeAnnotationToken();
David Blaikie15a430a2011-12-04 05:04:18 +0000908 if (Result.isInvalid()) {
909 DS.SetTypeSpecError();
910 return EndLoc;
911 }
912 } else {
Richard Smith324df552012-02-24 22:30:04 +0000913 if (Tok.getIdentifierInfo()->isStr("decltype"))
914 Diag(Tok, diag::warn_cxx98_compat_decltype);
Richard Smithfd3da932012-02-24 18:10:23 +0000915
David Blaikie15a430a2011-12-04 05:04:18 +0000916 ConsumeToken();
917
918 BalancedDelimiterTracker T(*this, tok::l_paren);
919 if (T.expectAndConsume(diag::err_expected_lparen_after,
920 "decltype", tok::r_paren)) {
921 DS.SetTypeSpecError();
922 return T.getOpenLocation() == Tok.getLocation() ?
923 StartLoc : T.getOpenLocation();
924 }
925
Richard Smith74aeef52013-04-26 16:15:35 +0000926 // Check for C++1y 'decltype(auto)'.
927 if (Tok.is(tok::kw_auto)) {
928 // No need to disambiguate here: an expression can't start with 'auto',
929 // because the typename-specifier in a function-style cast operation can't
930 // be 'auto'.
931 Diag(Tok.getLocation(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000932 getLangOpts().CPlusPlus14
Richard Smith74aeef52013-04-26 16:15:35 +0000933 ? diag::warn_cxx11_compat_decltype_auto_type_specifier
934 : diag::ext_decltype_auto_type_specifier);
935 ConsumeToken();
936 } else {
937 // Parse the expression
David Blaikie15a430a2011-12-04 05:04:18 +0000938
Richard Smith74aeef52013-04-26 16:15:35 +0000939 // C++11 [dcl.type.simple]p4:
940 // The operand of the decltype specifier is an unevaluated operand.
Faisal Valid143a0c2017-04-01 21:30:49 +0000941 EnterExpressionEvaluationContext Unevaluated(
942 Actions, Sema::ExpressionEvaluationContext::Unevaluated, nullptr,
943 /*IsDecltype=*/true);
Kaelyn Takata5cc85352015-04-10 19:16:46 +0000944 Result =
945 Actions.CorrectDelayedTyposInExpr(ParseExpression(), [](Expr *E) {
946 return E->hasPlaceholderType() ? ExprError() : E;
947 });
Richard Smith74aeef52013-04-26 16:15:35 +0000948 if (Result.isInvalid()) {
949 DS.SetTypeSpecError();
Alexey Bataevee6507d2013-11-18 08:17:37 +0000950 if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch)) {
Richard Smith74aeef52013-04-26 16:15:35 +0000951 EndLoc = ConsumeParen();
Argyrios Kyrtzidisc38395a2012-10-26 22:53:44 +0000952 } else {
Richard Smith74aeef52013-04-26 16:15:35 +0000953 if (PP.isBacktrackEnabled() && Tok.is(tok::semi)) {
954 // Backtrack to get the location of the last token before the semi.
955 PP.RevertCachedTokens(2);
956 ConsumeToken(); // the semi.
957 EndLoc = ConsumeAnyToken();
958 assert(Tok.is(tok::semi));
959 } else {
960 EndLoc = Tok.getLocation();
961 }
Argyrios Kyrtzidisc38395a2012-10-26 22:53:44 +0000962 }
Richard Smith74aeef52013-04-26 16:15:35 +0000963 return EndLoc;
Argyrios Kyrtzidisc38395a2012-10-26 22:53:44 +0000964 }
Richard Smith74aeef52013-04-26 16:15:35 +0000965
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000966 Result = Actions.ActOnDecltypeExpression(Result.get());
David Blaikie15a430a2011-12-04 05:04:18 +0000967 }
968
969 // Match the ')'
970 T.consumeClose();
971 if (T.getCloseLocation().isInvalid()) {
972 DS.SetTypeSpecError();
973 // FIXME: this should return the location of the last token
974 // that was consumed (by "consumeClose()")
975 return T.getCloseLocation();
976 }
977
Richard Smithfd555f62012-02-22 02:04:18 +0000978 if (Result.isInvalid()) {
979 DS.SetTypeSpecError();
980 return T.getCloseLocation();
981 }
982
David Blaikie15a430a2011-12-04 05:04:18 +0000983 EndLoc = T.getCloseLocation();
Anders Carlsson74948d02009-06-24 17:47:40 +0000984 }
Richard Smith74aeef52013-04-26 16:15:35 +0000985 assert(!Result.isInvalid());
Mike Stump11289f42009-09-09 15:08:12 +0000986
Craig Topper161e4db2014-05-21 06:02:52 +0000987 const char *PrevSpec = nullptr;
John McCall49bfce42009-08-03 20:12:06 +0000988 unsigned DiagID;
Erik Verbruggen888d52a2014-01-15 09:15:43 +0000989 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
Anders Carlsson74948d02009-06-24 17:47:40 +0000990 // Check for duplicate type specifiers (e.g. "int decltype(a)").
Richard Smith74aeef52013-04-26 16:15:35 +0000991 if (Result.get()
992 ? DS.SetTypeSpecType(DeclSpec::TST_decltype, StartLoc, PrevSpec,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000993 DiagID, Result.get(), Policy)
Richard Smith74aeef52013-04-26 16:15:35 +0000994 : DS.SetTypeSpecType(DeclSpec::TST_decltype_auto, StartLoc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +0000995 DiagID, Policy)) {
John McCall49bfce42009-08-03 20:12:06 +0000996 Diag(StartLoc, DiagID) << PrevSpec;
David Blaikie15a430a2011-12-04 05:04:18 +0000997 DS.SetTypeSpecError();
998 }
999 return EndLoc;
1000}
1001
1002void Parser::AnnotateExistingDecltypeSpecifier(const DeclSpec& DS,
1003 SourceLocation StartLoc,
1004 SourceLocation EndLoc) {
1005 // make sure we have a token we can turn into an annotation token
1006 if (PP.isBacktrackEnabled())
1007 PP.RevertCachedTokens(1);
1008 else
1009 PP.EnterToken(Tok);
1010
1011 Tok.setKind(tok::annot_decltype);
Richard Smith74aeef52013-04-26 16:15:35 +00001012 setExprAnnotation(Tok,
1013 DS.getTypeSpecType() == TST_decltype ? DS.getRepAsExpr() :
1014 DS.getTypeSpecType() == TST_decltype_auto ? ExprResult() :
1015 ExprError());
David Blaikie15a430a2011-12-04 05:04:18 +00001016 Tok.setAnnotationEndLoc(EndLoc);
1017 Tok.setLocation(StartLoc);
1018 PP.AnnotateCachedTokens(Tok);
Anders Carlsson74948d02009-06-24 17:47:40 +00001019}
1020
Alexis Hunt4a257072011-05-19 05:37:45 +00001021void Parser::ParseUnderlyingTypeSpecifier(DeclSpec &DS) {
1022 assert(Tok.is(tok::kw___underlying_type) &&
1023 "Not an underlying type specifier");
1024
1025 SourceLocation StartLoc = ConsumeToken();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001026 BalancedDelimiterTracker T(*this, tok::l_paren);
1027 if (T.expectAndConsume(diag::err_expected_lparen_after,
1028 "__underlying_type", tok::r_paren)) {
Alexis Hunt4a257072011-05-19 05:37:45 +00001029 return;
1030 }
1031
1032 TypeResult Result = ParseTypeName();
1033 if (Result.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00001034 SkipUntil(tok::r_paren, StopAtSemi);
Alexis Hunt4a257072011-05-19 05:37:45 +00001035 return;
1036 }
1037
1038 // Match the ')'
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001039 T.consumeClose();
1040 if (T.getCloseLocation().isInvalid())
Alexis Hunt4a257072011-05-19 05:37:45 +00001041 return;
1042
Craig Topper161e4db2014-05-21 06:02:52 +00001043 const char *PrevSpec = nullptr;
Alexis Hunt4a257072011-05-19 05:37:45 +00001044 unsigned DiagID;
Alexis Hunte852b102011-05-24 22:41:36 +00001045 if (DS.SetTypeSpecType(DeclSpec::TST_underlyingType, StartLoc, PrevSpec,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001046 DiagID, Result.get(),
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001047 Actions.getASTContext().getPrintingPolicy()))
Alexis Hunt4a257072011-05-19 05:37:45 +00001048 Diag(StartLoc, DiagID) << PrevSpec;
Enea Zaffanellaa90af722013-07-06 18:54:58 +00001049 DS.setTypeofParensRange(T.getRange());
Alexis Hunt4a257072011-05-19 05:37:45 +00001050}
1051
David Blaikie00ee7a082011-10-25 15:01:20 +00001052/// ParseBaseTypeSpecifier - Parse a C++ base-type-specifier which is either a
1053/// class name or decltype-specifier. Note that we only check that the result
1054/// names a type; semantic analysis will need to verify that the type names a
1055/// class. The result is either a type or null, depending on whether a type
1056/// name was found.
Douglas Gregor831c93f2008-11-05 20:51:48 +00001057///
Richard Smith4c96e992013-02-19 23:47:15 +00001058/// base-type-specifier: [C++11 class.derived]
David Blaikie00ee7a082011-10-25 15:01:20 +00001059/// class-or-decltype
Richard Smith4c96e992013-02-19 23:47:15 +00001060/// class-or-decltype: [C++11 class.derived]
David Blaikie00ee7a082011-10-25 15:01:20 +00001061/// nested-name-specifier[opt] class-name
1062/// decltype-specifier
Richard Smith4c96e992013-02-19 23:47:15 +00001063/// class-name: [C++ class.name]
Douglas Gregor831c93f2008-11-05 20:51:48 +00001064/// identifier
Douglas Gregord54dfb82009-02-25 23:52:28 +00001065/// simple-template-id
Mike Stump11289f42009-09-09 15:08:12 +00001066///
Richard Smith4c96e992013-02-19 23:47:15 +00001067/// In C++98, instead of base-type-specifier, we have:
1068///
1069/// ::[opt] nested-name-specifier[opt] class-name
Craig Topper9ad7e262014-10-31 06:57:07 +00001070TypeResult Parser::ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
1071 SourceLocation &EndLocation) {
David Blaikiedd58d4c2011-10-25 18:46:41 +00001072 // Ignore attempts to use typename
1073 if (Tok.is(tok::kw_typename)) {
1074 Diag(Tok, diag::err_expected_class_name_not_template)
1075 << FixItHint::CreateRemoval(Tok.getLocation());
1076 ConsumeToken();
1077 }
1078
David Blaikieafa155f2011-10-25 18:17:58 +00001079 // Parse optional nested-name-specifier
1080 CXXScopeSpec SS;
David Blaikieefdccaa2016-01-15 23:43:34 +00001081 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false);
David Blaikieafa155f2011-10-25 18:17:58 +00001082
1083 BaseLoc = Tok.getLocation();
1084
David Blaikie1cd50022011-10-25 17:10:12 +00001085 // Parse decltype-specifier
David Blaikie15a430a2011-12-04 05:04:18 +00001086 // tok == kw_decltype is just error recovery, it can only happen when SS
1087 // isn't empty
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001088 if (Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)) {
David Blaikieafa155f2011-10-25 18:17:58 +00001089 if (SS.isNotEmpty())
1090 Diag(SS.getBeginLoc(), diag::err_unexpected_scope_on_base_decltype)
1091 << FixItHint::CreateRemoval(SS.getRange());
David Blaikie1cd50022011-10-25 17:10:12 +00001092 // Fake up a Declarator to use with ActOnTypeName.
1093 DeclSpec DS(AttrFactory);
1094
David Blaikie7491e732011-12-08 04:53:15 +00001095 EndLocation = ParseDecltypeSpecifier(DS);
David Blaikie1cd50022011-10-25 17:10:12 +00001096
1097 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1098 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
1099 }
1100
Douglas Gregord54dfb82009-02-25 23:52:28 +00001101 // Check whether we have a template-id that names a type.
1102 if (Tok.is(tok::annot_template_id)) {
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00001103 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregor46c59612010-01-12 17:52:59 +00001104 if (TemplateId->Kind == TNK_Type_template ||
1105 TemplateId->Kind == TNK_Dependent_template_name) {
Richard Smith62559bd2017-02-01 21:36:38 +00001106 AnnotateTemplateIdTokenAsType(/*IsClassName*/true);
Douglas Gregord54dfb82009-02-25 23:52:28 +00001107
1108 assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
John McCallba7bf592010-08-24 05:47:05 +00001109 ParsedType Type = getTypeAnnotation(Tok);
Douglas Gregord54dfb82009-02-25 23:52:28 +00001110 EndLocation = Tok.getAnnotationEndLoc();
Richard Smithaf3b3252017-05-18 19:21:48 +00001111 ConsumeAnnotationToken();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001112
1113 if (Type)
1114 return Type;
1115 return true;
Douglas Gregord54dfb82009-02-25 23:52:28 +00001116 }
1117
1118 // Fall through to produce an error below.
1119 }
1120
Douglas Gregor831c93f2008-11-05 20:51:48 +00001121 if (Tok.isNot(tok::identifier)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00001122 Diag(Tok, diag::err_expected_class_name);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001123 return true;
Douglas Gregor831c93f2008-11-05 20:51:48 +00001124 }
1125
Douglas Gregor18473f32010-01-12 21:28:44 +00001126 IdentifierInfo *Id = Tok.getIdentifierInfo();
1127 SourceLocation IdLoc = ConsumeToken();
1128
1129 if (Tok.is(tok::less)) {
1130 // It looks the user intended to write a template-id here, but the
1131 // template-name was wrong. Try to fix that.
1132 TemplateNameKind TNK = TNK_Type_template;
1133 TemplateTy Template;
Douglas Gregor0be31a22010-07-02 17:43:08 +00001134 if (!Actions.DiagnoseUnknownTemplateName(*Id, IdLoc, getCurScope(),
Douglas Gregore7c20652011-03-02 00:47:37 +00001135 &SS, Template, TNK)) {
Douglas Gregor18473f32010-01-12 21:28:44 +00001136 Diag(IdLoc, diag::err_unknown_template_name)
1137 << Id;
1138 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001139
Serge Pavlovb716b3c2013-08-10 05:54:47 +00001140 if (!Template) {
1141 TemplateArgList TemplateArgs;
1142 SourceLocation LAngleLoc, RAngleLoc;
Richard Smith9a420f92017-05-10 21:47:30 +00001143 ParseTemplateIdAfterTemplateName(true, LAngleLoc, TemplateArgs,
1144 RAngleLoc);
Douglas Gregor18473f32010-01-12 21:28:44 +00001145 return true;
Serge Pavlovb716b3c2013-08-10 05:54:47 +00001146 }
Douglas Gregor18473f32010-01-12 21:28:44 +00001147
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001148 // Form the template name
Douglas Gregor18473f32010-01-12 21:28:44 +00001149 UnqualifiedId TemplateName;
1150 TemplateName.setIdentifier(Id, IdLoc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001151
Douglas Gregor18473f32010-01-12 21:28:44 +00001152 // Parse the full template-id, then turn it into a type.
Abramo Bagnara7945c982012-01-27 09:46:47 +00001153 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
Richard Smith62559bd2017-02-01 21:36:38 +00001154 TemplateName))
Douglas Gregor18473f32010-01-12 21:28:44 +00001155 return true;
Richard Smith62559bd2017-02-01 21:36:38 +00001156 if (TNK == TNK_Type_template || TNK == TNK_Dependent_template_name)
1157 AnnotateTemplateIdTokenAsType(/*IsClassName*/true);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001158
Douglas Gregor18473f32010-01-12 21:28:44 +00001159 // If we didn't end up with a typename token, there's nothing more we
1160 // can do.
1161 if (Tok.isNot(tok::annot_typename))
1162 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001163
Douglas Gregor18473f32010-01-12 21:28:44 +00001164 // Retrieve the type from the annotation token, consume that token, and
1165 // return.
1166 EndLocation = Tok.getAnnotationEndLoc();
John McCallba7bf592010-08-24 05:47:05 +00001167 ParsedType Type = getTypeAnnotation(Tok);
Richard Smithaf3b3252017-05-18 19:21:48 +00001168 ConsumeAnnotationToken();
Douglas Gregor18473f32010-01-12 21:28:44 +00001169 return Type;
1170 }
1171
Douglas Gregor831c93f2008-11-05 20:51:48 +00001172 // We have an identifier; check whether it is actually a type.
Craig Topper161e4db2014-05-21 06:02:52 +00001173 IdentifierInfo *CorrectedII = nullptr;
Richard Smith600b5262017-01-26 20:40:47 +00001174 ParsedType Type = Actions.getTypeName(
Richard Smith62559bd2017-02-01 21:36:38 +00001175 *Id, IdLoc, getCurScope(), &SS, /*IsClassName=*/true, false, nullptr,
Richard Smith600b5262017-01-26 20:40:47 +00001176 /*IsCtorOrDtorName=*/false,
1177 /*NonTrivialTypeSourceInfo=*/true,
1178 /*IsClassTemplateDeductionContext*/ false, &CorrectedII);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001179 if (!Type) {
Douglas Gregorfe17d252010-02-16 19:09:40 +00001180 Diag(IdLoc, diag::err_expected_class_name);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001181 return true;
Douglas Gregor831c93f2008-11-05 20:51:48 +00001182 }
1183
1184 // Consume the identifier.
Douglas Gregor18473f32010-01-12 21:28:44 +00001185 EndLocation = IdLoc;
Nick Lewycky19b9f952010-07-26 16:56:01 +00001186
1187 // Fake up a Declarator to use with ActOnTypeName.
John McCall084e83d2011-03-24 11:26:52 +00001188 DeclSpec DS(AttrFactory);
Nick Lewycky19b9f952010-07-26 16:56:01 +00001189 DS.SetRangeStart(IdLoc);
1190 DS.SetRangeEnd(EndLocation);
Douglas Gregore7c20652011-03-02 00:47:37 +00001191 DS.getTypeSpecScope() = SS;
Nick Lewycky19b9f952010-07-26 16:56:01 +00001192
Craig Topper161e4db2014-05-21 06:02:52 +00001193 const char *PrevSpec = nullptr;
Nick Lewycky19b9f952010-07-26 16:56:01 +00001194 unsigned DiagID;
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001195 DS.SetTypeSpecType(TST_typename, IdLoc, PrevSpec, DiagID, Type,
1196 Actions.getASTContext().getPrintingPolicy());
Nick Lewycky19b9f952010-07-26 16:56:01 +00001197
1198 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1199 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
Douglas Gregor831c93f2008-11-05 20:51:48 +00001200}
1201
John McCall8d32c052012-05-22 21:28:12 +00001202void Parser::ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001203 while (Tok.isOneOf(tok::kw___single_inheritance,
1204 tok::kw___multiple_inheritance,
1205 tok::kw___virtual_inheritance)) {
John McCall8d32c052012-05-22 21:28:12 +00001206 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
1207 SourceLocation AttrNameLoc = ConsumeToken();
Craig Topper161e4db2014-05-21 06:02:52 +00001208 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
Aaron Ballman8edb5c22013-12-18 23:44:18 +00001209 AttributeList::AS_Keyword);
John McCall8d32c052012-05-22 21:28:12 +00001210 }
1211}
1212
Richard Smith369b9f92012-06-25 21:37:02 +00001213/// Determine whether the following tokens are valid after a type-specifier
1214/// which could be a standalone declaration. This will conservatively return
1215/// true if there's any doubt, and is appropriate for insert-';' fixits.
Richard Smith200f47c2012-07-02 19:14:01 +00001216bool Parser::isValidAfterTypeSpecifier(bool CouldBeBitfield) {
Richard Smith369b9f92012-06-25 21:37:02 +00001217 // This switch enumerates the valid "follow" set for type-specifiers.
1218 switch (Tok.getKind()) {
1219 default: break;
1220 case tok::semi: // struct foo {...} ;
1221 case tok::star: // struct foo {...} * P;
1222 case tok::amp: // struct foo {...} & R = ...
Richard Smith1ac67d12013-01-19 03:48:05 +00001223 case tok::ampamp: // struct foo {...} && R = ...
Richard Smith369b9f92012-06-25 21:37:02 +00001224 case tok::identifier: // struct foo {...} V ;
1225 case tok::r_paren: //(struct foo {...} ) {4}
1226 case tok::annot_cxxscope: // struct foo {...} a:: b;
1227 case tok::annot_typename: // struct foo {...} a ::b;
1228 case tok::annot_template_id: // struct foo {...} a<int> ::b;
1229 case tok::l_paren: // struct foo {...} ( x);
1230 case tok::comma: // __builtin_offsetof(struct foo{...} ,
Richard Smith1ac67d12013-01-19 03:48:05 +00001231 case tok::kw_operator: // struct foo operator ++() {...}
Alp Tokerd3f79c52013-11-24 20:24:54 +00001232 case tok::kw___declspec: // struct foo {...} __declspec(...)
Richard Smith843f18f2014-08-13 02:13:15 +00001233 case tok::l_square: // void f(struct f [ 3])
1234 case tok::ellipsis: // void f(struct f ... [Ns])
Abramo Bagnara152eb392014-08-16 08:29:27 +00001235 // FIXME: we should emit semantic diagnostic when declaration
1236 // attribute is in type attribute position.
1237 case tok::kw___attribute: // struct foo __attribute__((used)) x;
David Majnemer15b311c2016-06-14 03:20:28 +00001238 case tok::annot_pragma_pack: // struct foo {...} _Pragma(pack(pop));
1239 // struct foo {...} _Pragma(section(...));
1240 case tok::annot_pragma_ms_pragma:
1241 // struct foo {...} _Pragma(vtordisp(pop));
1242 case tok::annot_pragma_ms_vtordisp:
1243 // struct foo {...} _Pragma(pointers_to_members(...));
1244 case tok::annot_pragma_ms_pointers_to_members:
Richard Smith369b9f92012-06-25 21:37:02 +00001245 return true;
Richard Smith200f47c2012-07-02 19:14:01 +00001246 case tok::colon:
1247 return CouldBeBitfield; // enum E { ... } : 2;
Reid Klecknercfa91552016-03-21 16:08:49 +00001248 // Microsoft compatibility
1249 case tok::kw___cdecl: // struct foo {...} __cdecl x;
1250 case tok::kw___fastcall: // struct foo {...} __fastcall x;
1251 case tok::kw___stdcall: // struct foo {...} __stdcall x;
1252 case tok::kw___thiscall: // struct foo {...} __thiscall x;
1253 case tok::kw___vectorcall: // struct foo {...} __vectorcall x;
1254 // We will diagnose these calling-convention specifiers on non-function
1255 // declarations later, so claim they are valid after a type specifier.
1256 return getLangOpts().MicrosoftExt;
Richard Smith369b9f92012-06-25 21:37:02 +00001257 // Type qualifiers
1258 case tok::kw_const: // struct foo {...} const x;
1259 case tok::kw_volatile: // struct foo {...} volatile x;
1260 case tok::kw_restrict: // struct foo {...} restrict x;
Richard Smith843f18f2014-08-13 02:13:15 +00001261 case tok::kw__Atomic: // struct foo {...} _Atomic x;
Nico Rieck3e1ee832014-12-04 23:30:25 +00001262 case tok::kw___unaligned: // struct foo {...} __unaligned *x;
Richard Smith1ac67d12013-01-19 03:48:05 +00001263 // Function specifiers
1264 // Note, no 'explicit'. An explicit function must be either a conversion
1265 // operator or a constructor. Either way, it can't have a return type.
1266 case tok::kw_inline: // struct foo inline f();
1267 case tok::kw_virtual: // struct foo virtual f();
1268 case tok::kw_friend: // struct foo friend f();
Richard Smith369b9f92012-06-25 21:37:02 +00001269 // Storage-class specifiers
1270 case tok::kw_static: // struct foo {...} static x;
1271 case tok::kw_extern: // struct foo {...} extern x;
1272 case tok::kw_typedef: // struct foo {...} typedef x;
1273 case tok::kw_register: // struct foo {...} register x;
1274 case tok::kw_auto: // struct foo {...} auto x;
1275 case tok::kw_mutable: // struct foo {...} mutable x;
Richard Smith1ac67d12013-01-19 03:48:05 +00001276 case tok::kw_thread_local: // struct foo {...} thread_local x;
Richard Smith369b9f92012-06-25 21:37:02 +00001277 case tok::kw_constexpr: // struct foo {...} constexpr x;
1278 // As shown above, type qualifiers and storage class specifiers absolutely
1279 // can occur after class specifiers according to the grammar. However,
1280 // almost no one actually writes code like this. If we see one of these,
1281 // it is much more likely that someone missed a semi colon and the
1282 // type/storage class specifier we're seeing is part of the *next*
1283 // intended declaration, as in:
1284 //
1285 // struct foo { ... }
1286 // typedef int X;
1287 //
1288 // We'd really like to emit a missing semicolon error instead of emitting
1289 // an error on the 'int' saying that you can't have two type specifiers in
1290 // the same declaration of X. Because of this, we look ahead past this
1291 // token to see if it's a type specifier. If so, we know the code is
1292 // otherwise invalid, so we can produce the expected semi error.
1293 if (!isKnownToBeTypeSpecifier(NextToken()))
1294 return true;
1295 break;
1296 case tok::r_brace: // struct bar { struct foo {...} }
1297 // Missing ';' at end of struct is accepted as an extension in C mode.
1298 if (!getLangOpts().CPlusPlus)
1299 return true;
1300 break;
Richard Smith52c5b872013-01-29 04:13:32 +00001301 case tok::greater:
1302 // template<class T = class X>
1303 return getLangOpts().CPlusPlus;
Richard Smith369b9f92012-06-25 21:37:02 +00001304 }
1305 return false;
1306}
1307
Douglas Gregor556877c2008-04-13 21:30:24 +00001308/// ParseClassSpecifier - Parse a C++ class-specifier [C++ class] or
1309/// elaborated-type-specifier [C++ dcl.type.elab]; we can't tell which
1310/// until we reach the start of a definition or see a token that
Richard Smithc5b05522012-03-12 07:56:15 +00001311/// cannot start a definition.
Douglas Gregor556877c2008-04-13 21:30:24 +00001312///
1313/// class-specifier: [C++ class]
1314/// class-head '{' member-specification[opt] '}'
1315/// class-head '{' member-specification[opt] '}' attributes[opt]
1316/// class-head:
1317/// class-key identifier[opt] base-clause[opt]
1318/// class-key nested-name-specifier identifier base-clause[opt]
1319/// class-key nested-name-specifier[opt] simple-template-id
1320/// base-clause[opt]
1321/// [GNU] class-key attributes[opt] identifier[opt] base-clause[opt]
Mike Stump11289f42009-09-09 15:08:12 +00001322/// [GNU] class-key attributes[opt] nested-name-specifier
Douglas Gregor556877c2008-04-13 21:30:24 +00001323/// identifier base-clause[opt]
Mike Stump11289f42009-09-09 15:08:12 +00001324/// [GNU] class-key attributes[opt] nested-name-specifier[opt]
Douglas Gregor556877c2008-04-13 21:30:24 +00001325/// simple-template-id base-clause[opt]
1326/// class-key:
1327/// 'class'
1328/// 'struct'
1329/// 'union'
1330///
1331/// elaborated-type-specifier: [C++ dcl.type.elab]
Mike Stump11289f42009-09-09 15:08:12 +00001332/// class-key ::[opt] nested-name-specifier[opt] identifier
1333/// class-key ::[opt] nested-name-specifier[opt] 'template'[opt]
1334/// simple-template-id
Douglas Gregor556877c2008-04-13 21:30:24 +00001335///
1336/// Note that the C++ class-specifier and elaborated-type-specifier,
1337/// together, subsume the C99 struct-or-union-specifier:
1338///
1339/// struct-or-union-specifier: [C99 6.7.2.1]
1340/// struct-or-union identifier[opt] '{' struct-contents '}'
1341/// struct-or-union identifier
1342/// [GNU] struct-or-union attributes[opt] identifier[opt] '{' struct-contents
1343/// '}' attributes[opt]
1344/// [GNU] struct-or-union attributes[opt] identifier
1345/// struct-or-union:
1346/// 'struct'
1347/// 'union'
Chris Lattnerffaa0e62009-04-12 21:49:30 +00001348void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind,
1349 SourceLocation StartLoc, DeclSpec &DS,
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001350 const ParsedTemplateInfo &TemplateInfo,
Douglas Gregordf593fb2011-11-07 17:33:42 +00001351 AccessSpecifier AS,
Michael Han9407e502012-11-26 22:54:45 +00001352 bool EnteringContext, DeclSpecContext DSC,
Bill Wendling44426052012-12-20 19:22:21 +00001353 ParsedAttributesWithRange &Attributes) {
Joao Matose9a3ed42012-08-31 22:18:20 +00001354 DeclSpec::TST TagType;
1355 if (TagTokKind == tok::kw_struct)
1356 TagType = DeclSpec::TST_struct;
1357 else if (TagTokKind == tok::kw___interface)
1358 TagType = DeclSpec::TST_interface;
1359 else if (TagTokKind == tok::kw_class)
1360 TagType = DeclSpec::TST_class;
1361 else {
Chris Lattnerffaa0e62009-04-12 21:49:30 +00001362 assert(TagTokKind == tok::kw_union && "Not a class specifier");
1363 TagType = DeclSpec::TST_union;
1364 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001365
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00001366 if (Tok.is(tok::code_completion)) {
1367 // Code completion for a struct, class, or union name.
Douglas Gregor0be31a22010-07-02 17:43:08 +00001368 Actions.CodeCompleteTag(getCurScope(), TagType);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001369 return cutOffParsing();
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00001370 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001371
Chandler Carruth2d69ec72010-06-28 08:39:25 +00001372 // C++03 [temp.explicit] 14.7.2/8:
1373 // The usual access checking rules do not apply to names used to specify
1374 // explicit instantiations.
1375 //
1376 // As an extension we do not perform access checking on the names used to
1377 // specify explicit specializations either. This is important to allow
1378 // specializing traits classes for private types.
John McCall6347b682012-05-07 06:16:58 +00001379 //
1380 // Note that we don't suppress if this turns out to be an elaborated
1381 // type specifier.
1382 bool shouldDelayDiagsInTag =
1383 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
1384 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
1385 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
Chandler Carruth2d69ec72010-06-28 08:39:25 +00001386
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001387 ParsedAttributesWithRange attrs(AttrFactory);
Douglas Gregor556877c2008-04-13 21:30:24 +00001388 // If attributes exist after tag, parse them.
Richard Smith37a45dd2013-10-24 01:21:09 +00001389 MaybeParseGNUAttributes(attrs);
Aaron Ballman068aa512015-05-20 20:58:33 +00001390 MaybeParseMicrosoftDeclSpecs(attrs);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001391
John McCall8d32c052012-05-22 21:28:12 +00001392 // Parse inheritance specifiers.
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001393 if (Tok.isOneOf(tok::kw___single_inheritance,
1394 tok::kw___multiple_inheritance,
1395 tok::kw___virtual_inheritance))
Richard Smith37a45dd2013-10-24 01:21:09 +00001396 ParseMicrosoftInheritanceClassAttributes(attrs);
John McCall8d32c052012-05-22 21:28:12 +00001397
Alexis Hunt96d5c762009-11-21 08:43:09 +00001398 // If C++0x attributes exist here, parse them.
1399 // FIXME: Are we consistent with the ordering of parsing of different
1400 // styles of attributes?
Richard Smith89645bc2013-01-02 12:01:23 +00001401 MaybeParseCXX11Attributes(attrs);
Mike Stump11289f42009-09-09 15:08:12 +00001402
Michael Han309af292013-01-07 16:57:11 +00001403 // Source location used by FIXIT to insert misplaced
1404 // C++11 attributes
1405 SourceLocation AttrFixitLoc = Tok.getLocation();
1406
Nico Weber7c3c5be2014-09-23 04:09:56 +00001407 if (TagType == DeclSpec::TST_struct &&
David Majnemer86330af2014-12-29 02:14:26 +00001408 Tok.isNot(tok::identifier) &&
1409 !Tok.isAnnotation() &&
Nico Weber7c3c5be2014-09-23 04:09:56 +00001410 Tok.getIdentifierInfo() &&
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001411 Tok.isOneOf(tok::kw___is_abstract,
Eric Fiselier07360662017-04-12 22:12:15 +00001412 tok::kw___is_aggregate,
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001413 tok::kw___is_arithmetic,
1414 tok::kw___is_array,
David Majnemerb3d96882016-05-23 17:21:55 +00001415 tok::kw___is_assignable,
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001416 tok::kw___is_base_of,
1417 tok::kw___is_class,
1418 tok::kw___is_complete_type,
1419 tok::kw___is_compound,
1420 tok::kw___is_const,
1421 tok::kw___is_constructible,
1422 tok::kw___is_convertible,
1423 tok::kw___is_convertible_to,
1424 tok::kw___is_destructible,
1425 tok::kw___is_empty,
1426 tok::kw___is_enum,
1427 tok::kw___is_floating_point,
1428 tok::kw___is_final,
1429 tok::kw___is_function,
1430 tok::kw___is_fundamental,
1431 tok::kw___is_integral,
1432 tok::kw___is_interface_class,
1433 tok::kw___is_literal,
1434 tok::kw___is_lvalue_expr,
1435 tok::kw___is_lvalue_reference,
1436 tok::kw___is_member_function_pointer,
1437 tok::kw___is_member_object_pointer,
1438 tok::kw___is_member_pointer,
1439 tok::kw___is_nothrow_assignable,
1440 tok::kw___is_nothrow_constructible,
1441 tok::kw___is_nothrow_destructible,
1442 tok::kw___is_object,
1443 tok::kw___is_pod,
1444 tok::kw___is_pointer,
1445 tok::kw___is_polymorphic,
1446 tok::kw___is_reference,
1447 tok::kw___is_rvalue_expr,
1448 tok::kw___is_rvalue_reference,
1449 tok::kw___is_same,
1450 tok::kw___is_scalar,
1451 tok::kw___is_sealed,
1452 tok::kw___is_signed,
1453 tok::kw___is_standard_layout,
1454 tok::kw___is_trivial,
1455 tok::kw___is_trivially_assignable,
1456 tok::kw___is_trivially_constructible,
1457 tok::kw___is_trivially_copyable,
1458 tok::kw___is_union,
1459 tok::kw___is_unsigned,
1460 tok::kw___is_void,
1461 tok::kw___is_volatile))
Nico Weber7c3c5be2014-09-23 04:09:56 +00001462 // GNU libstdc++ 4.2 and libc++ use certain intrinsic names as the
1463 // name of struct templates, but some are keywords in GCC >= 4.3
1464 // and Clang. Therefore, when we see the token sequence "struct
1465 // X", make X into a normal identifier rather than a keyword, to
1466 // allow libstdc++ 4.2 and libc++ to work properly.
1467 TryKeywordIdentFallback(true);
Mike Stump11289f42009-09-09 15:08:12 +00001468
David Majnemer51fd8a02015-07-22 23:46:18 +00001469 struct PreserveAtomicIdentifierInfoRAII {
1470 PreserveAtomicIdentifierInfoRAII(Token &Tok, bool Enabled)
1471 : AtomicII(nullptr) {
1472 if (!Enabled)
1473 return;
1474 assert(Tok.is(tok::kw__Atomic));
1475 AtomicII = Tok.getIdentifierInfo();
1476 AtomicII->revertTokenIDToIdentifier();
1477 Tok.setKind(tok::identifier);
1478 }
1479 ~PreserveAtomicIdentifierInfoRAII() {
1480 if (!AtomicII)
1481 return;
1482 AtomicII->revertIdentifierToTokenID(tok::kw__Atomic);
1483 }
1484 IdentifierInfo *AtomicII;
1485 };
1486
1487 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
1488 // implementation for VS2013 uses _Atomic as an identifier for one of the
1489 // classes in <atomic>. When we are parsing 'struct _Atomic', don't consider
1490 // '_Atomic' to be a keyword. We are careful to undo this so that clang can
1491 // use '_Atomic' in its own header files.
1492 bool ShouldChangeAtomicToIdentifier = getLangOpts().MSVCCompat &&
1493 Tok.is(tok::kw__Atomic) &&
1494 TagType == DeclSpec::TST_struct;
1495 PreserveAtomicIdentifierInfoRAII AtomicTokenGuard(
1496 Tok, ShouldChangeAtomicToIdentifier);
1497
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001498 // Parse the (optional) nested-name-specifier.
John McCall9dab4e62009-12-12 11:40:51 +00001499 CXXScopeSpec &SS = DS.getTypeSpecScope();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001500 if (getLangOpts().CPlusPlus) {
Serge Pavlov458ea762014-07-16 05:16:52 +00001501 // "FOO : BAR" is not a potential typo for "FOO::BAR". In this context it
1502 // is a base-specifier-list.
Chris Lattnerd5c1c9d2009-12-10 00:32:41 +00001503 ColonProtectionRAIIObject X(*this);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001504
Nico Webercfaa4cd2015-02-15 07:26:13 +00001505 CXXScopeSpec Spec;
1506 bool HasValidSpec = true;
David Blaikieefdccaa2016-01-15 23:43:34 +00001507 if (ParseOptionalCXXScopeSpecifier(Spec, nullptr, EnteringContext)) {
John McCall413021a2010-07-30 06:26:29 +00001508 DS.SetTypeSpecError();
Nico Webercfaa4cd2015-02-15 07:26:13 +00001509 HasValidSpec = false;
1510 }
1511 if (Spec.isSet())
1512 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::annot_template_id)) {
Alp Tokerec543272013-12-24 09:48:30 +00001513 Diag(Tok, diag::err_expected) << tok::identifier;
Nico Webercfaa4cd2015-02-15 07:26:13 +00001514 HasValidSpec = false;
1515 }
1516 if (HasValidSpec)
1517 SS = Spec;
Chris Lattnerd5c1c9d2009-12-10 00:32:41 +00001518 }
Douglas Gregor67a65642009-02-17 23:15:12 +00001519
Douglas Gregor916462b2009-10-30 21:46:58 +00001520 TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
1521
Douglas Gregor67a65642009-02-17 23:15:12 +00001522 // Parse the (optional) class name or simple-template-id.
Craig Topper161e4db2014-05-21 06:02:52 +00001523 IdentifierInfo *Name = nullptr;
Douglas Gregor556877c2008-04-13 21:30:24 +00001524 SourceLocation NameLoc;
Craig Topper161e4db2014-05-21 06:02:52 +00001525 TemplateIdAnnotation *TemplateId = nullptr;
Douglas Gregor556877c2008-04-13 21:30:24 +00001526 if (Tok.is(tok::identifier)) {
1527 Name = Tok.getIdentifierInfo();
1528 NameLoc = ConsumeToken();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001529
David Blaikiebbafb8a2012-03-11 07:00:24 +00001530 if (Tok.is(tok::less) && getLangOpts().CPlusPlus) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001531 // The name was supposed to refer to a template, but didn't.
Douglas Gregor916462b2009-10-30 21:46:58 +00001532 // Eat the template argument list and try to continue parsing this as
1533 // a class (or template thereof).
1534 TemplateArgList TemplateArgs;
Douglas Gregor916462b2009-10-30 21:46:58 +00001535 SourceLocation LAngleLoc, RAngleLoc;
Richard Smith9a420f92017-05-10 21:47:30 +00001536 if (ParseTemplateIdAfterTemplateName(true, LAngleLoc, TemplateArgs,
1537 RAngleLoc)) {
Douglas Gregor916462b2009-10-30 21:46:58 +00001538 // We couldn't parse the template argument list at all, so don't
1539 // try to give any location information for the list.
1540 LAngleLoc = RAngleLoc = SourceLocation();
1541 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001542
Douglas Gregor916462b2009-10-30 21:46:58 +00001543 Diag(NameLoc, diag::err_explicit_spec_non_template)
Alp Toker01d65e12014-01-06 12:54:41 +00001544 << (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
1545 << TagTokKind << Name << SourceRange(LAngleLoc, RAngleLoc);
Joao Matose9a3ed42012-08-31 22:18:20 +00001546
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001547 // Strip off the last template parameter list if it was empty, since
Douglas Gregor1d0015f2009-10-30 22:09:44 +00001548 // we've removed its template argument list.
1549 if (TemplateParams && TemplateInfo.LastParameterListWasEmpty) {
Hubert Tong97b06632016-04-13 18:41:03 +00001550 if (TemplateParams->size() > 1) {
Douglas Gregor1d0015f2009-10-30 22:09:44 +00001551 TemplateParams->pop_back();
1552 } else {
Craig Topper161e4db2014-05-21 06:02:52 +00001553 TemplateParams = nullptr;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001554 const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind
Douglas Gregor1d0015f2009-10-30 22:09:44 +00001555 = ParsedTemplateInfo::NonTemplate;
1556 }
1557 } else if (TemplateInfo.Kind
1558 == ParsedTemplateInfo::ExplicitInstantiation) {
1559 // Pretend this is just a forward declaration.
Craig Topper161e4db2014-05-21 06:02:52 +00001560 TemplateParams = nullptr;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001561 const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind
Douglas Gregor916462b2009-10-30 21:46:58 +00001562 = ParsedTemplateInfo::NonTemplate;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001563 const_cast<ParsedTemplateInfo&>(TemplateInfo).TemplateLoc
Douglas Gregor1d0015f2009-10-30 22:09:44 +00001564 = SourceLocation();
1565 const_cast<ParsedTemplateInfo&>(TemplateInfo).ExternLoc
1566 = SourceLocation();
Douglas Gregor916462b2009-10-30 21:46:58 +00001567 }
Douglas Gregor916462b2009-10-30 21:46:58 +00001568 }
Douglas Gregor7f741122009-02-25 19:37:18 +00001569 } else if (Tok.is(tok::annot_template_id)) {
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00001570 TemplateId = takeTemplateIdAnnotation(Tok);
Richard Smithaf3b3252017-05-18 19:21:48 +00001571 NameLoc = ConsumeAnnotationToken();
Douglas Gregor67a65642009-02-17 23:15:12 +00001572
Douglas Gregore7c20652011-03-02 00:47:37 +00001573 if (TemplateId->Kind != TNK_Type_template &&
1574 TemplateId->Kind != TNK_Dependent_template_name) {
Douglas Gregor7f741122009-02-25 19:37:18 +00001575 // The template-name in the simple-template-id refers to
1576 // something other than a class template. Give an appropriate
1577 // error message and skip to the ';'.
1578 SourceRange Range(NameLoc);
1579 if (SS.isNotEmpty())
1580 Range.setBegin(SS.getBeginLoc());
Douglas Gregor67a65642009-02-17 23:15:12 +00001581
Richard Smith72bfbd82013-12-04 00:28:23 +00001582 // FIXME: Name may be null here.
Douglas Gregor7f741122009-02-25 19:37:18 +00001583 Diag(TemplateId->LAngleLoc, diag::err_template_spec_syntax_non_template)
Richard Trieu30f93852013-06-19 22:25:01 +00001584 << TemplateId->Name << static_cast<int>(TemplateId->Kind) << Range;
Mike Stump11289f42009-09-09 15:08:12 +00001585
Douglas Gregor7f741122009-02-25 19:37:18 +00001586 DS.SetTypeSpecError();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001587 SkipUntil(tok::semi, StopBeforeMatch);
Douglas Gregor7f741122009-02-25 19:37:18 +00001588 return;
Douglas Gregor67a65642009-02-17 23:15:12 +00001589 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001590 }
1591
Richard Smithbfdb1082012-03-12 08:56:40 +00001592 // There are four options here.
1593 // - If we are in a trailing return type, this is always just a reference,
1594 // and we must not try to parse a definition. For instance,
1595 // [] () -> struct S { };
1596 // does not define a type.
1597 // - If we have 'struct foo {...', 'struct foo :...',
1598 // 'struct foo final :' or 'struct foo final {', then this is a definition.
1599 // - If we have 'struct foo;', then this is either a forward declaration
1600 // or a friend declaration, which have to be treated differently.
1601 // - Otherwise we have something like 'struct foo xyz', a reference.
Michael Han9407e502012-11-26 22:54:45 +00001602 //
1603 // We also detect these erroneous cases to provide better diagnostic for
1604 // C++11 attributes parsing.
1605 // - attributes follow class name:
1606 // struct foo [[]] {};
1607 // - attributes appear before or after 'final':
1608 // struct foo [[]] final [[]] {};
1609 //
Richard Smithc5b05522012-03-12 07:56:15 +00001610 // However, in type-specifier-seq's, things look like declarations but are
1611 // just references, e.g.
1612 // new struct s;
Sebastian Redl2b372722010-02-03 21:21:43 +00001613 // or
Richard Smithc5b05522012-03-12 07:56:15 +00001614 // &T::operator struct s;
Richard Smith649c7b062014-01-08 00:56:48 +00001615 // For these, DSC is DSC_type_specifier or DSC_alias_declaration.
Michael Han9407e502012-11-26 22:54:45 +00001616
1617 // If there are attributes after class name, parse them.
Richard Smith89645bc2013-01-02 12:01:23 +00001618 MaybeParseCXX11Attributes(Attributes);
Michael Han9407e502012-11-26 22:54:45 +00001619
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001620 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
John McCallfaf5fb42010-08-26 23:41:50 +00001621 Sema::TagUseKind TUK;
Richard Smithbfdb1082012-03-12 08:56:40 +00001622 if (DSC == DSC_trailing)
1623 TUK = Sema::TUK_Reference;
1624 else if (Tok.is(tok::l_brace) ||
1625 (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
Richard Smith89645bc2013-01-02 12:01:23 +00001626 (isCXX11FinalKeyword() &&
David Blaikie9933a5a2012-03-12 15:39:49 +00001627 (NextToken().is(tok::l_brace) || NextToken().is(tok::colon)))) {
Douglas Gregor3dad8422009-09-26 06:47:28 +00001628 if (DS.isFriendSpecified()) {
1629 // C++ [class.friend]p2:
1630 // A class shall not be defined in a friend declaration.
Richard Smith0f8ee222012-01-10 01:33:14 +00001631 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
Douglas Gregor3dad8422009-09-26 06:47:28 +00001632 << SourceRange(DS.getFriendSpecLoc());
1633
1634 // Skip everything up to the semicolon, so that this looks like a proper
1635 // friend class (or template thereof) declaration.
Alexey Bataevee6507d2013-11-18 08:17:37 +00001636 SkipUntil(tok::semi, StopBeforeMatch);
John McCallfaf5fb42010-08-26 23:41:50 +00001637 TUK = Sema::TUK_Friend;
Douglas Gregor3dad8422009-09-26 06:47:28 +00001638 } else {
1639 // Okay, this is a class definition.
John McCallfaf5fb42010-08-26 23:41:50 +00001640 TUK = Sema::TUK_Definition;
Douglas Gregor3dad8422009-09-26 06:47:28 +00001641 }
Richard Smith434516c2013-02-22 06:46:23 +00001642 } else if (isCXX11FinalKeyword() && (NextToken().is(tok::l_square) ||
1643 NextToken().is(tok::kw_alignas))) {
Michael Han9407e502012-11-26 22:54:45 +00001644 // We can't tell if this is a definition or reference
1645 // until we skipped the 'final' and C++11 attribute specifiers.
1646 TentativeParsingAction PA(*this);
1647
1648 // Skip the 'final' keyword.
1649 ConsumeToken();
1650
1651 // Skip C++11 attribute specifiers.
1652 while (true) {
1653 if (Tok.is(tok::l_square) && NextToken().is(tok::l_square)) {
1654 ConsumeBracket();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001655 if (!SkipUntil(tok::r_square, StopAtSemi))
Michael Han9407e502012-11-26 22:54:45 +00001656 break;
Richard Smith434516c2013-02-22 06:46:23 +00001657 } else if (Tok.is(tok::kw_alignas) && NextToken().is(tok::l_paren)) {
Michael Han9407e502012-11-26 22:54:45 +00001658 ConsumeToken();
1659 ConsumeParen();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001660 if (!SkipUntil(tok::r_paren, StopAtSemi))
Michael Han9407e502012-11-26 22:54:45 +00001661 break;
1662 } else {
1663 break;
1664 }
1665 }
1666
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001667 if (Tok.isOneOf(tok::l_brace, tok::colon))
Michael Han9407e502012-11-26 22:54:45 +00001668 TUK = Sema::TUK_Definition;
1669 else
1670 TUK = Sema::TUK_Reference;
1671
1672 PA.Revert();
Richard Smith649c7b062014-01-08 00:56:48 +00001673 } else if (!isTypeSpecifier(DSC) &&
Richard Smith369b9f92012-06-25 21:37:02 +00001674 (Tok.is(tok::semi) ||
Richard Smith200f47c2012-07-02 19:14:01 +00001675 (Tok.isAtStartOfLine() && !isValidAfterTypeSpecifier(false)))) {
John McCallfaf5fb42010-08-26 23:41:50 +00001676 TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
Joao Matose9a3ed42012-08-31 22:18:20 +00001677 if (Tok.isNot(tok::semi)) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001678 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
Joao Matose9a3ed42012-08-31 22:18:20 +00001679 // A semicolon was missing after this declaration. Diagnose and recover.
Alp Toker383d2c42014-01-01 03:08:43 +00001680 ExpectAndConsume(tok::semi, diag::err_expected_after,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001681 DeclSpec::getSpecifierName(TagType, PPol));
Joao Matose9a3ed42012-08-31 22:18:20 +00001682 PP.EnterToken(Tok);
1683 Tok.setKind(tok::semi);
1684 }
Richard Smith369b9f92012-06-25 21:37:02 +00001685 } else
John McCallfaf5fb42010-08-26 23:41:50 +00001686 TUK = Sema::TUK_Reference;
Douglas Gregor556877c2008-04-13 21:30:24 +00001687
Michael Han9407e502012-11-26 22:54:45 +00001688 // Forbid misplaced attributes. In cases of a reference, we pass attributes
1689 // to caller to handle.
Michael Han309af292013-01-07 16:57:11 +00001690 if (TUK != Sema::TUK_Reference) {
1691 // If this is not a reference, then the only possible
1692 // valid place for C++11 attributes to appear here
1693 // is between class-key and class-name. If there are
1694 // any attributes after class-name, we try a fixit to move
1695 // them to the right place.
1696 SourceRange AttrRange = Attributes.Range;
1697 if (AttrRange.isValid()) {
1698 Diag(AttrRange.getBegin(), diag::err_attributes_not_allowed)
1699 << AttrRange
1700 << FixItHint::CreateInsertionFromRange(AttrFixitLoc,
1701 CharSourceRange(AttrRange, true))
1702 << FixItHint::CreateRemoval(AttrRange);
1703
1704 // Recover by adding misplaced attributes to the attribute list
1705 // of the class so they can be applied on the class later.
1706 attrs.takeAllFrom(Attributes);
1707 }
1708 }
Michael Han9407e502012-11-26 22:54:45 +00001709
John McCall6347b682012-05-07 06:16:58 +00001710 // If this is an elaborated type specifier, and we delayed
1711 // diagnostics before, just merge them into the current pool.
1712 if (shouldDelayDiagsInTag) {
1713 diagsFromTag.done();
1714 if (TUK == Sema::TUK_Reference)
1715 diagsFromTag.redelay();
1716 }
1717
John McCall413021a2010-07-30 06:26:29 +00001718 if (!Name && !TemplateId && (DS.getTypeSpecType() == DeclSpec::TST_error ||
John McCallfaf5fb42010-08-26 23:41:50 +00001719 TUK != Sema::TUK_Definition)) {
John McCall413021a2010-07-30 06:26:29 +00001720 if (DS.getTypeSpecType() != DeclSpec::TST_error) {
1721 // We have a declaration or reference to an anonymous class.
1722 Diag(StartLoc, diag::err_anon_type_definition)
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001723 << DeclSpec::getSpecifierName(TagType, Policy);
John McCall413021a2010-07-30 06:26:29 +00001724 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001725
David Majnemer3252fd02013-12-05 01:36:53 +00001726 // If we are parsing a definition and stop at a base-clause, continue on
1727 // until the semicolon. Continuing from the comma will just trick us into
1728 // thinking we are seeing a variable declaration.
1729 if (TUK == Sema::TUK_Definition && Tok.is(tok::colon))
1730 SkipUntil(tok::semi, StopBeforeMatch);
1731 else
1732 SkipUntil(tok::comma, StopAtSemi);
Douglas Gregor556877c2008-04-13 21:30:24 +00001733 return;
1734 }
1735
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001736 // Create the tag portion of the class or class template.
John McCall48871652010-08-21 09:40:31 +00001737 DeclResult TagOrTempResult = true; // invalid
1738 TypeResult TypeResult = true; // invalid
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001739
Douglas Gregord6ab8742009-05-28 23:31:59 +00001740 bool Owned = false;
Richard Smithd9ba2242015-05-07 03:54:19 +00001741 Sema::SkipBodyInfo SkipBody;
John McCall06f6fe8d2009-09-04 01:14:41 +00001742 if (TemplateId) {
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001743 // Explicit specialization, class template partial specialization,
1744 // or explicit instantiation.
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00001745 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregor7f741122009-02-25 19:37:18 +00001746 TemplateId->NumArgs);
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001747 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
John McCallfaf5fb42010-08-26 23:41:50 +00001748 TUK == Sema::TUK_Declaration) {
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001749 // This is an explicit instantiation of a class template.
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001750 ProhibitAttributes(attrs);
1751
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001752 TagOrTempResult
Douglas Gregor0be31a22010-07-02 17:43:08 +00001753 = Actions.ActOnExplicitInstantiation(getCurScope(),
Douglas Gregor43e75172009-09-04 06:33:52 +00001754 TemplateInfo.ExternLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001755 TemplateInfo.TemplateLoc,
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001756 TagType,
Mike Stump11289f42009-09-09 15:08:12 +00001757 StartLoc,
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001758 SS,
John McCall3e56fd42010-08-23 07:28:44 +00001759 TemplateId->Template,
Mike Stump11289f42009-09-09 15:08:12 +00001760 TemplateId->TemplateNameLoc,
1761 TemplateId->LAngleLoc,
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001762 TemplateArgsPtr,
Mike Stump11289f42009-09-09 15:08:12 +00001763 TemplateId->RAngleLoc,
John McCall53fa7142010-12-24 02:08:15 +00001764 attrs.getList());
John McCallb7c5c272010-04-14 00:24:33 +00001765
1766 // Friend template-ids are treated as references unless
1767 // they have template headers, in which case they're ill-formed
1768 // (FIXME: "template <class T> friend class A<T>::B<int>;").
1769 // We diagnose this error in ActOnClassTemplateSpecialization.
John McCallfaf5fb42010-08-26 23:41:50 +00001770 } else if (TUK == Sema::TUK_Reference ||
1771 (TUK == Sema::TUK_Friend &&
John McCallb7c5c272010-04-14 00:24:33 +00001772 TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate)) {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001773 ProhibitAttributes(attrs);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00001774 TypeResult = Actions.ActOnTagTemplateIdType(TUK, TagType, StartLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00001775 TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00001776 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00001777 TemplateId->Template,
1778 TemplateId->TemplateNameLoc,
1779 TemplateId->LAngleLoc,
1780 TemplateArgsPtr,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00001781 TemplateId->RAngleLoc);
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001782 } else {
1783 // This is an explicit specialization or a class template
1784 // partial specialization.
1785 TemplateParameterLists FakedParamLists;
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001786 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1787 // This looks like an explicit instantiation, because we have
1788 // something like
1789 //
1790 // template class Foo<X>
1791 //
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001792 // but it actually has a definition. Most likely, this was
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001793 // meant to be an explicit specialization, but the user forgot
1794 // the '<>' after 'template'.
Richard Smith003c5e12013-11-08 19:03:29 +00001795 // It this is friend declaration however, since it cannot have a
1796 // template header, it is most likely that the user meant to
1797 // remove the 'template' keyword.
Larisse Voufob9bbaba2013-06-22 13:56:11 +00001798 assert((TUK == Sema::TUK_Definition || TUK == Sema::TUK_Friend) &&
Richard Smith003c5e12013-11-08 19:03:29 +00001799 "Expected a definition here");
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001800
Richard Smith003c5e12013-11-08 19:03:29 +00001801 if (TUK == Sema::TUK_Friend) {
1802 Diag(DS.getFriendSpecLoc(), diag::err_friend_explicit_instantiation);
Craig Topper161e4db2014-05-21 06:02:52 +00001803 TemplateParams = nullptr;
Richard Smith003c5e12013-11-08 19:03:29 +00001804 } else {
1805 SourceLocation LAngleLoc =
1806 PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
1807 Diag(TemplateId->TemplateNameLoc,
1808 diag::err_explicit_instantiation_with_definition)
1809 << SourceRange(TemplateInfo.TemplateLoc)
1810 << FixItHint::CreateInsertion(LAngleLoc, "<>");
1811
1812 // Create a fake template parameter list that contains only
1813 // "template<>", so that we treat this construct as a class
1814 // template specialization.
1815 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
Craig Topper96225a52015-12-24 23:58:25 +00001816 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
Hubert Tongf608c052016-04-29 18:05:37 +00001817 LAngleLoc, nullptr));
Richard Smith003c5e12013-11-08 19:03:29 +00001818 TemplateParams = &FakedParamLists;
1819 }
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001820 }
1821
1822 // Build the class template specialization.
Richard Smith4b55a9c2014-04-17 03:29:33 +00001823 TagOrTempResult = Actions.ActOnClassTemplateSpecialization(
1824 getCurScope(), TagType, TUK, StartLoc, DS.getModulePrivateSpecLoc(),
1825 *TemplateId, attrs.getList(),
Craig Topper161e4db2014-05-21 06:02:52 +00001826 MultiTemplateParamsArg(TemplateParams ? &(*TemplateParams)[0]
1827 : nullptr,
Richard Smithc7e6ff02015-05-18 20:36:47 +00001828 TemplateParams ? TemplateParams->size() : 0),
1829 &SkipBody);
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001830 }
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001831 } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
John McCallfaf5fb42010-08-26 23:41:50 +00001832 TUK == Sema::TUK_Declaration) {
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001833 // Explicit instantiation of a member of a class template
1834 // specialization, e.g.,
1835 //
1836 // template struct Outer<int>::Inner;
1837 //
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001838 ProhibitAttributes(attrs);
1839
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001840 TagOrTempResult
Douglas Gregor0be31a22010-07-02 17:43:08 +00001841 = Actions.ActOnExplicitInstantiation(getCurScope(),
Douglas Gregor43e75172009-09-04 06:33:52 +00001842 TemplateInfo.ExternLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001843 TemplateInfo.TemplateLoc,
1844 TagType, StartLoc, SS, Name,
John McCall53fa7142010-12-24 02:08:15 +00001845 NameLoc, attrs.getList());
John McCallace48cd2010-10-19 01:40:49 +00001846 } else if (TUK == Sema::TUK_Friend &&
1847 TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate) {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001848 ProhibitAttributes(attrs);
1849
John McCallace48cd2010-10-19 01:40:49 +00001850 TagOrTempResult =
1851 Actions.ActOnTemplatedFriendTag(getCurScope(), DS.getFriendSpecLoc(),
1852 TagType, StartLoc, SS,
John McCall53fa7142010-12-24 02:08:15 +00001853 Name, NameLoc, attrs.getList(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00001854 MultiTemplateParamsArg(
Craig Topper161e4db2014-05-21 06:02:52 +00001855 TemplateParams? &(*TemplateParams)[0]
1856 : nullptr,
John McCallace48cd2010-10-19 01:40:49 +00001857 TemplateParams? TemplateParams->size() : 0));
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001858 } else {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001859 if (TUK != Sema::TUK_Declaration && TUK != Sema::TUK_Definition)
1860 ProhibitAttributes(attrs);
Richard Smith003c5e12013-11-08 19:03:29 +00001861
Larisse Voufo725de3e2013-06-21 00:08:46 +00001862 if (TUK == Sema::TUK_Definition &&
1863 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1864 // If the declarator-id is not a template-id, issue a diagnostic and
1865 // recover by ignoring the 'template' keyword.
1866 Diag(Tok, diag::err_template_defn_explicit_instantiation)
1867 << 1 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
Craig Topper161e4db2014-05-21 06:02:52 +00001868 TemplateParams = nullptr;
Larisse Voufo725de3e2013-06-21 00:08:46 +00001869 }
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001870
John McCall7f41d982009-09-11 04:59:25 +00001871 bool IsDependent = false;
1872
John McCall32723e92010-10-19 18:40:57 +00001873 // Don't pass down template parameter lists if this is just a tag
1874 // reference. For example, we don't need the template parameters here:
1875 // template <class T> class A *makeA(T t);
1876 MultiTemplateParamsArg TParams;
1877 if (TUK != Sema::TUK_Reference && TemplateParams)
1878 TParams =
1879 MultiTemplateParamsArg(&(*TemplateParams)[0], TemplateParams->size());
1880
Nico Weber32a0fc72016-09-03 03:01:32 +00001881 stripTypeAttributesOffDeclSpec(attrs, DS, TUK);
David Majnemer936b4112015-04-19 07:53:29 +00001882
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001883 // Declaration or definition of a class type
John McCallace48cd2010-10-19 01:40:49 +00001884 TagOrTempResult = Actions.ActOnTag(getCurScope(), TagType, TUK, StartLoc,
John McCall53fa7142010-12-24 02:08:15 +00001885 SS, Name, NameLoc, attrs.getList(), AS,
Douglas Gregor2820e692011-09-09 19:05:14 +00001886 DS.getModulePrivateSpecLoc(),
Richard Smith0f8ee222012-01-10 01:33:14 +00001887 TParams, Owned, IsDependent,
1888 SourceLocation(), false,
Richard Smith649c7b062014-01-08 00:56:48 +00001889 clang::TypeResult(),
Richard Smith65ebb4a2015-03-26 04:09:53 +00001890 DSC == DSC_type_specifier,
Akira Hatanaka12ddcee2017-06-26 18:46:12 +00001891 DSC == DSC_template_param ||
1892 DSC == DSC_template_type_arg, &SkipBody);
John McCall7f41d982009-09-11 04:59:25 +00001893
1894 // If ActOnTag said the type was dependent, try again with the
1895 // less common call.
John McCallace48cd2010-10-19 01:40:49 +00001896 if (IsDependent) {
1897 assert(TUK == Sema::TUK_Reference || TUK == Sema::TUK_Friend);
Douglas Gregor0be31a22010-07-02 17:43:08 +00001898 TypeResult = Actions.ActOnDependentTag(getCurScope(), TagType, TUK,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001899 SS, Name, StartLoc, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +00001900 }
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001901 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001902
Douglas Gregor556877c2008-04-13 21:30:24 +00001903 // If there is a body, parse it and inform the actions module.
John McCallfaf5fb42010-08-26 23:41:50 +00001904 if (TUK == Sema::TUK_Definition) {
John McCall2d814c32009-12-19 21:48:58 +00001905 assert(Tok.is(tok::l_brace) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00001906 (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
Richard Smith89645bc2013-01-02 12:01:23 +00001907 isCXX11FinalKeyword());
Richard Smithd9ba2242015-05-07 03:54:19 +00001908 if (SkipBody.ShouldSkip)
Richard Smith65ebb4a2015-03-26 04:09:53 +00001909 SkipCXXMemberSpecification(StartLoc, AttrFixitLoc, TagType,
1910 TagOrTempResult.get());
1911 else if (getLangOpts().CPlusPlus)
Michael Han309af292013-01-07 16:57:11 +00001912 ParseCXXMemberSpecification(StartLoc, AttrFixitLoc, attrs, TagType,
1913 TagOrTempResult.get());
Bruno Cardoso Lopesdf0ee342017-07-01 00:06:47 +00001914 else {
1915 Decl *D =
1916 SkipBody.CheckSameAsPrevious ? SkipBody.New : TagOrTempResult.get();
1917 // Parse the definition body.
1918 ParseStructUnionBody(StartLoc, TagType, D);
1919 if (SkipBody.CheckSameAsPrevious &&
1920 !Actions.ActOnDuplicateDefinition(DS, TagOrTempResult.get(),
1921 SkipBody)) {
1922 DS.SetTypeSpecError();
1923 return;
1924 }
1925 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001926 }
1927
Erich Keane2fe684b2017-02-28 20:44:39 +00001928 if (!TagOrTempResult.isInvalid())
Hiroshi Inoue939d9322017-06-30 05:40:31 +00001929 // Delayed processing of attributes.
Erich Keane2fe684b2017-02-28 20:44:39 +00001930 Actions.ProcessDeclAttributeDelayed(TagOrTempResult.get(), attrs.getList());
1931
Craig Topper161e4db2014-05-21 06:02:52 +00001932 const char *PrevSpec = nullptr;
John McCallba7bf592010-08-24 05:47:05 +00001933 unsigned DiagID;
1934 bool Result;
John McCall7f41d982009-09-11 04:59:25 +00001935 if (!TypeResult.isInvalid()) {
Abramo Bagnara9875a3c2011-03-16 20:16:18 +00001936 Result = DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
1937 NameLoc.isValid() ? NameLoc : StartLoc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001938 PrevSpec, DiagID, TypeResult.get(), Policy);
John McCall7f41d982009-09-11 04:59:25 +00001939 } else if (!TagOrTempResult.isInvalid()) {
Abramo Bagnara9875a3c2011-03-16 20:16:18 +00001940 Result = DS.SetTypeSpecType(TagType, StartLoc,
1941 NameLoc.isValid() ? NameLoc : StartLoc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001942 PrevSpec, DiagID, TagOrTempResult.get(), Owned,
1943 Policy);
John McCall7f41d982009-09-11 04:59:25 +00001944 } else {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001945 DS.SetTypeSpecError();
Anders Carlssonf83c9fa2009-05-11 22:27:47 +00001946 return;
1947 }
Mike Stump11289f42009-09-09 15:08:12 +00001948
John McCallba7bf592010-08-24 05:47:05 +00001949 if (Result)
John McCall49bfce42009-08-03 20:12:06 +00001950 Diag(StartLoc, DiagID) << PrevSpec;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001951
Chris Lattnercf251412010-02-02 01:23:29 +00001952 // At this point, we've successfully parsed a class-specifier in 'definition'
1953 // form (e.g. "struct foo { int x; }". While we could just return here, we're
1954 // going to look at what comes after it to improve error recovery. If an
1955 // impossible token occurs next, we assume that the programmer forgot a ; at
1956 // the end of the declaration and recover that way.
1957 //
Richard Smith369b9f92012-06-25 21:37:02 +00001958 // Also enforce C++ [temp]p3:
1959 // In a template-declaration which defines a class, no declarator
1960 // is permitted.
Richard Smith843f18f2014-08-13 02:13:15 +00001961 //
1962 // After a type-specifier, we don't expect a semicolon. This only happens in
1963 // C, since definitions are not permitted in this context in C++.
Joao Matose9a3ed42012-08-31 22:18:20 +00001964 if (TUK == Sema::TUK_Definition &&
Richard Smith843f18f2014-08-13 02:13:15 +00001965 (getLangOpts().CPlusPlus || !isTypeSpecifier(DSC)) &&
Joao Matose9a3ed42012-08-31 22:18:20 +00001966 (TemplateInfo.Kind || !isValidAfterTypeSpecifier(false))) {
Argyrios Kyrtzidise6f69132012-12-17 20:10:43 +00001967 if (Tok.isNot(tok::semi)) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001968 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
Alp Toker383d2c42014-01-01 03:08:43 +00001969 ExpectAndConsume(tok::semi, diag::err_expected_after,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001970 DeclSpec::getSpecifierName(TagType, PPol));
Argyrios Kyrtzidise6f69132012-12-17 20:10:43 +00001971 // Push this token back into the preprocessor and change our current token
1972 // to ';' so that the rest of the code recovers as though there were an
1973 // ';' after the definition.
1974 PP.EnterToken(Tok);
1975 Tok.setKind(tok::semi);
1976 }
Chris Lattnercf251412010-02-02 01:23:29 +00001977 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001978}
1979
Mike Stump11289f42009-09-09 15:08:12 +00001980/// ParseBaseClause - Parse the base-clause of a C++ class [C++ class.derived].
Douglas Gregor556877c2008-04-13 21:30:24 +00001981///
1982/// base-clause : [C++ class.derived]
1983/// ':' base-specifier-list
1984/// base-specifier-list:
1985/// base-specifier '...'[opt]
1986/// base-specifier-list ',' base-specifier '...'[opt]
John McCall48871652010-08-21 09:40:31 +00001987void Parser::ParseBaseClause(Decl *ClassDecl) {
Douglas Gregor556877c2008-04-13 21:30:24 +00001988 assert(Tok.is(tok::colon) && "Not a base clause");
1989 ConsumeToken();
1990
Douglas Gregor29a92472008-10-22 17:49:05 +00001991 // Build up an array of parsed base specifiers.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001992 SmallVector<CXXBaseSpecifier *, 8> BaseInfo;
Douglas Gregor29a92472008-10-22 17:49:05 +00001993
Douglas Gregor556877c2008-04-13 21:30:24 +00001994 while (true) {
1995 // Parse a base-specifier.
Douglas Gregor29a92472008-10-22 17:49:05 +00001996 BaseResult Result = ParseBaseSpecifier(ClassDecl);
Douglas Gregorf8298252009-01-26 22:44:13 +00001997 if (Result.isInvalid()) {
Douglas Gregor556877c2008-04-13 21:30:24 +00001998 // Skip the rest of this base specifier, up until the comma or
1999 // opening brace.
Alexey Bataevee6507d2013-11-18 08:17:37 +00002000 SkipUntil(tok::comma, tok::l_brace, StopAtSemi | StopBeforeMatch);
Douglas Gregor29a92472008-10-22 17:49:05 +00002001 } else {
2002 // Add this to our array of base specifiers.
Douglas Gregorf8298252009-01-26 22:44:13 +00002003 BaseInfo.push_back(Result.get());
Douglas Gregor556877c2008-04-13 21:30:24 +00002004 }
2005
2006 // If the next token is a comma, consume it and keep reading
2007 // base-specifiers.
Alp Toker97650562014-01-10 11:19:30 +00002008 if (!TryConsumeToken(tok::comma))
2009 break;
Douglas Gregor556877c2008-04-13 21:30:24 +00002010 }
Douglas Gregor29a92472008-10-22 17:49:05 +00002011
2012 // Attach the base specifiers
Craig Topperaa700cb2015-12-27 21:55:19 +00002013 Actions.ActOnBaseSpecifiers(ClassDecl, BaseInfo);
Douglas Gregor556877c2008-04-13 21:30:24 +00002014}
2015
2016/// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is
2017/// one entry in the base class list of a class specifier, for example:
2018/// class foo : public bar, virtual private baz {
2019/// 'public bar' and 'virtual private baz' are each base-specifiers.
2020///
2021/// base-specifier: [C++ class.derived]
Richard Smith4c96e992013-02-19 23:47:15 +00002022/// attribute-specifier-seq[opt] base-type-specifier
2023/// attribute-specifier-seq[opt] 'virtual' access-specifier[opt]
2024/// base-type-specifier
2025/// attribute-specifier-seq[opt] access-specifier 'virtual'[opt]
2026/// base-type-specifier
Craig Topper9ad7e262014-10-31 06:57:07 +00002027BaseResult Parser::ParseBaseSpecifier(Decl *ClassDecl) {
Douglas Gregor556877c2008-04-13 21:30:24 +00002028 bool IsVirtual = false;
2029 SourceLocation StartLoc = Tok.getLocation();
2030
Richard Smith4c96e992013-02-19 23:47:15 +00002031 ParsedAttributesWithRange Attributes(AttrFactory);
2032 MaybeParseCXX11Attributes(Attributes);
2033
Douglas Gregor556877c2008-04-13 21:30:24 +00002034 // Parse the 'virtual' keyword.
Alp Toker97650562014-01-10 11:19:30 +00002035 if (TryConsumeToken(tok::kw_virtual))
Douglas Gregor556877c2008-04-13 21:30:24 +00002036 IsVirtual = true;
Douglas Gregor556877c2008-04-13 21:30:24 +00002037
Richard Smith4c96e992013-02-19 23:47:15 +00002038 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2039
Douglas Gregor556877c2008-04-13 21:30:24 +00002040 // Parse an (optional) access specifier.
2041 AccessSpecifier Access = getAccessSpecifierIfPresent();
John McCall553c0792010-01-23 00:46:32 +00002042 if (Access != AS_none)
Douglas Gregor556877c2008-04-13 21:30:24 +00002043 ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +00002044
Richard Smith4c96e992013-02-19 23:47:15 +00002045 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2046
Douglas Gregor556877c2008-04-13 21:30:24 +00002047 // Parse the 'virtual' keyword (again!), in case it came after the
2048 // access specifier.
2049 if (Tok.is(tok::kw_virtual)) {
2050 SourceLocation VirtualLoc = ConsumeToken();
2051 if (IsVirtual) {
2052 // Complain about duplicate 'virtual'
Chris Lattner6d29c102008-11-18 07:48:38 +00002053 Diag(VirtualLoc, diag::err_dup_virtual)
Douglas Gregora771f462010-03-31 17:46:05 +00002054 << FixItHint::CreateRemoval(VirtualLoc);
Douglas Gregor556877c2008-04-13 21:30:24 +00002055 }
2056
2057 IsVirtual = true;
2058 }
2059
Richard Smith4c96e992013-02-19 23:47:15 +00002060 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2061
Douglas Gregor831c93f2008-11-05 20:51:48 +00002062 // Parse the class-name.
David Majnemer51fd8a02015-07-22 23:46:18 +00002063
2064 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
2065 // implementation for VS2013 uses _Atomic as an identifier for one of the
2066 // classes in <atomic>. Treat '_Atomic' to be an identifier when we are
2067 // parsing the class-name for a base specifier.
2068 if (getLangOpts().MSVCCompat && Tok.is(tok::kw__Atomic) &&
2069 NextToken().is(tok::less))
2070 Tok.setKind(tok::identifier);
2071
Douglas Gregord54dfb82009-02-25 23:52:28 +00002072 SourceLocation EndLocation;
David Blaikie1cd50022011-10-25 17:10:12 +00002073 SourceLocation BaseLoc;
2074 TypeResult BaseType = ParseBaseTypeSpecifier(BaseLoc, EndLocation);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00002075 if (BaseType.isInvalid())
Douglas Gregor831c93f2008-11-05 20:51:48 +00002076 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002077
Douglas Gregor752a5952011-01-03 22:36:02 +00002078 // Parse the optional ellipsis (for a pack expansion). The ellipsis is
2079 // actually part of the base-specifier-list grammar productions, but we
2080 // parse it here for convenience.
2081 SourceLocation EllipsisLoc;
Alp Toker97650562014-01-10 11:19:30 +00002082 TryConsumeToken(tok::ellipsis, EllipsisLoc);
2083
Mike Stump11289f42009-09-09 15:08:12 +00002084 // Find the complete source range for the base-specifier.
Douglas Gregord54dfb82009-02-25 23:52:28 +00002085 SourceRange Range(StartLoc, EndLocation);
Mike Stump11289f42009-09-09 15:08:12 +00002086
Douglas Gregor556877c2008-04-13 21:30:24 +00002087 // Notify semantic analysis that we have parsed a complete
2088 // base-specifier.
Richard Smith4c96e992013-02-19 23:47:15 +00002089 return Actions.ActOnBaseSpecifier(ClassDecl, Range, Attributes, IsVirtual,
2090 Access, BaseType.get(), BaseLoc,
2091 EllipsisLoc);
Douglas Gregor556877c2008-04-13 21:30:24 +00002092}
2093
2094/// getAccessSpecifierIfPresent - Determine whether the next token is
2095/// a C++ access-specifier.
2096///
2097/// access-specifier: [C++ class.derived]
2098/// 'private'
2099/// 'protected'
2100/// 'public'
Mike Stump11289f42009-09-09 15:08:12 +00002101AccessSpecifier Parser::getAccessSpecifierIfPresent() const {
Douglas Gregor556877c2008-04-13 21:30:24 +00002102 switch (Tok.getKind()) {
2103 default: return AS_none;
2104 case tok::kw_private: return AS_private;
2105 case tok::kw_protected: return AS_protected;
2106 case tok::kw_public: return AS_public;
2107 }
2108}
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002109
Douglas Gregor433e0532012-04-16 18:27:27 +00002110/// \brief If the given declarator has any parts for which parsing has to be
Richard Smith0b3a4622014-11-13 20:01:57 +00002111/// delayed, e.g., default arguments or an exception-specification, create a
2112/// late-parsed method declaration record to handle the parsing at the end of
2113/// the class definition.
Douglas Gregor433e0532012-04-16 18:27:27 +00002114void Parser::HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
2115 Decl *ThisDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00002116 DeclaratorChunk::FunctionTypeInfo &FTI
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002117 = DeclaratorInfo.getFunctionTypeInfo();
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002118 // If there was a late-parsed exception-specification, we'll need a
2119 // late parse
2120 bool NeedLateParse = FTI.getExceptionSpecType() == EST_Unparsed;
Douglas Gregor433e0532012-04-16 18:27:27 +00002121
Nathan Sidwell5bb231c2015-02-19 14:03:22 +00002122 if (!NeedLateParse) {
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002123 // Look ahead to see if there are any default args
Nathan Sidwell5bb231c2015-02-19 14:03:22 +00002124 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx) {
2125 auto Param = cast<ParmVarDecl>(FTI.Params[ParamIdx].Param);
2126 if (Param->hasUnparsedDefaultArg()) {
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002127 NeedLateParse = true;
2128 break;
2129 }
Nathan Sidwell5bb231c2015-02-19 14:03:22 +00002130 }
2131 }
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002132
2133 if (NeedLateParse) {
Richard Smith0b3a4622014-11-13 20:01:57 +00002134 // Push this method onto the stack of late-parsed method
2135 // declarations.
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002136 auto LateMethod = new LateParsedMethodDeclaration(this, ThisDecl);
Richard Smith0b3a4622014-11-13 20:01:57 +00002137 getCurrentClass().LateParsedDeclarations.push_back(LateMethod);
2138 LateMethod->TemplateScope = getCurScope()->isTemplateParamScope();
2139
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002140 // Stash the exception-specification tokens in the late-pased method.
Richard Smith0b3a4622014-11-13 20:01:57 +00002141 LateMethod->ExceptionSpecTokens = FTI.ExceptionSpecTokens;
Hans Wennborgdcfba332015-10-06 23:40:43 +00002142 FTI.ExceptionSpecTokens = nullptr;
Richard Smith0b3a4622014-11-13 20:01:57 +00002143
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002144 // Push tokens for each parameter. Those that do not have
2145 // defaults will be NULL.
Richard Smith0b3a4622014-11-13 20:01:57 +00002146 LateMethod->DefaultArgs.reserve(FTI.NumParams);
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002147 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx)
Alp Tokerc5350722014-02-26 22:27:52 +00002148 LateMethod->DefaultArgs.push_back(LateParsedDefaultArgument(
Malcolm Parsonsca9d8342016-11-17 21:00:09 +00002149 FTI.Params[ParamIdx].Param,
2150 std::move(FTI.Params[ParamIdx].DefaultArgTokens)));
Eli Friedman3af2a772009-07-22 21:45:50 +00002151 }
2152}
2153
Richard Smith89645bc2013-01-02 12:01:23 +00002154/// isCXX11VirtSpecifier - Determine whether the given token is a C++11
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002155/// virt-specifier.
2156///
2157/// virt-specifier:
2158/// override
2159/// final
Andrey Bokhanko276055b2016-07-29 10:42:48 +00002160/// __final
Richard Smith89645bc2013-01-02 12:01:23 +00002161VirtSpecifiers::Specifier Parser::isCXX11VirtSpecifier(const Token &Tok) const {
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002162 if (!getLangOpts().CPlusPlus || Tok.isNot(tok::identifier))
Anders Carlsson4b63d0e2011-01-22 16:56:46 +00002163 return VirtSpecifiers::VS_None;
2164
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002165 IdentifierInfo *II = Tok.getIdentifierInfo();
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002166
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002167 // Initialize the contextual keywords.
2168 if (!Ident_final) {
2169 Ident_final = &PP.getIdentifierTable().get("final");
Andrey Bokhanko276055b2016-07-29 10:42:48 +00002170 if (getLangOpts().GNUKeywords)
2171 Ident_GNU_final = &PP.getIdentifierTable().get("__final");
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002172 if (getLangOpts().MicrosoftExt)
2173 Ident_sealed = &PP.getIdentifierTable().get("sealed");
2174 Ident_override = &PP.getIdentifierTable().get("override");
Anders Carlsson56104902011-01-17 03:05:47 +00002175 }
2176
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002177 if (II == Ident_override)
2178 return VirtSpecifiers::VS_Override;
2179
2180 if (II == Ident_sealed)
2181 return VirtSpecifiers::VS_Sealed;
2182
2183 if (II == Ident_final)
2184 return VirtSpecifiers::VS_Final;
2185
Andrey Bokhanko276055b2016-07-29 10:42:48 +00002186 if (II == Ident_GNU_final)
2187 return VirtSpecifiers::VS_GNU_Final;
2188
Anders Carlsson56104902011-01-17 03:05:47 +00002189 return VirtSpecifiers::VS_None;
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002190}
2191
Richard Smith89645bc2013-01-02 12:01:23 +00002192/// ParseOptionalCXX11VirtSpecifierSeq - Parse a virt-specifier-seq.
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002193///
2194/// virt-specifier-seq:
2195/// virt-specifier
2196/// virt-specifier-seq virt-specifier
Richard Smith89645bc2013-01-02 12:01:23 +00002197void Parser::ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS,
Richard Smith3d1a94c2014-08-12 00:22:39 +00002198 bool IsInterface,
2199 SourceLocation FriendLoc) {
Anders Carlsson56104902011-01-17 03:05:47 +00002200 while (true) {
Richard Smith89645bc2013-01-02 12:01:23 +00002201 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
Anders Carlsson56104902011-01-17 03:05:47 +00002202 if (Specifier == VirtSpecifiers::VS_None)
2203 return;
2204
Richard Smith3d1a94c2014-08-12 00:22:39 +00002205 if (FriendLoc.isValid()) {
2206 Diag(Tok.getLocation(), diag::err_friend_decl_spec)
2207 << VirtSpecifiers::getSpecifierName(Specifier)
2208 << FixItHint::CreateRemoval(Tok.getLocation())
2209 << SourceRange(FriendLoc, FriendLoc);
2210 ConsumeToken();
2211 continue;
2212 }
2213
Anders Carlsson56104902011-01-17 03:05:47 +00002214 // C++ [class.mem]p8:
2215 // A virt-specifier-seq shall contain at most one of each virt-specifier.
Craig Topper161e4db2014-05-21 06:02:52 +00002216 const char *PrevSpec = nullptr;
Anders Carlssonf2ca3892011-01-22 15:58:16 +00002217 if (VS.SetSpecifier(Specifier, Tok.getLocation(), PrevSpec))
Anders Carlsson56104902011-01-17 03:05:47 +00002218 Diag(Tok.getLocation(), diag::err_duplicate_virt_specifier)
2219 << PrevSpec
2220 << FixItHint::CreateRemoval(Tok.getLocation());
2221
David Majnemera5433082013-10-18 00:33:31 +00002222 if (IsInterface && (Specifier == VirtSpecifiers::VS_Final ||
2223 Specifier == VirtSpecifiers::VS_Sealed)) {
John McCalldb632ac2012-09-25 07:32:39 +00002224 Diag(Tok.getLocation(), diag::err_override_control_interface)
2225 << VirtSpecifiers::getSpecifierName(Specifier);
David Majnemera5433082013-10-18 00:33:31 +00002226 } else if (Specifier == VirtSpecifiers::VS_Sealed) {
2227 Diag(Tok.getLocation(), diag::ext_ms_sealed_keyword);
Andrey Bokhanko276055b2016-07-29 10:42:48 +00002228 } else if (Specifier == VirtSpecifiers::VS_GNU_Final) {
2229 Diag(Tok.getLocation(), diag::ext_warn_gnu_final);
John McCalldb632ac2012-09-25 07:32:39 +00002230 } else {
David Majnemera5433082013-10-18 00:33:31 +00002231 Diag(Tok.getLocation(),
2232 getLangOpts().CPlusPlus11
2233 ? diag::warn_cxx98_compat_override_control_keyword
2234 : diag::ext_override_control_keyword)
2235 << VirtSpecifiers::getSpecifierName(Specifier);
John McCalldb632ac2012-09-25 07:32:39 +00002236 }
Anders Carlsson56104902011-01-17 03:05:47 +00002237 ConsumeToken();
2238 }
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002239}
2240
Richard Smith89645bc2013-01-02 12:01:23 +00002241/// isCXX11FinalKeyword - Determine whether the next token is a C++11
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002242/// 'final' or Microsoft 'sealed' contextual keyword.
Richard Smith89645bc2013-01-02 12:01:23 +00002243bool Parser::isCXX11FinalKeyword() const {
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002244 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
2245 return Specifier == VirtSpecifiers::VS_Final ||
Andrey Bokhanko276055b2016-07-29 10:42:48 +00002246 Specifier == VirtSpecifiers::VS_GNU_Final ||
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002247 Specifier == VirtSpecifiers::VS_Sealed;
Anders Carlsson4b63d0e2011-01-22 16:56:46 +00002248}
2249
Richard Smith72553fc2014-01-23 23:53:27 +00002250/// \brief Parse a C++ member-declarator up to, but not including, the optional
2251/// brace-or-equal-initializer or pure-specifier.
Nico Weberd89e6f72015-01-16 19:34:13 +00002252bool Parser::ParseCXXMemberDeclaratorBeforeInitializer(
Richard Smith72553fc2014-01-23 23:53:27 +00002253 Declarator &DeclaratorInfo, VirtSpecifiers &VS, ExprResult &BitfieldSize,
2254 LateParsedAttrList &LateParsedAttrs) {
2255 // member-declarator:
2256 // declarator pure-specifier[opt]
2257 // declarator brace-or-equal-initializer[opt]
2258 // identifier[opt] ':' constant-expression
Serge Pavlov458ea762014-07-16 05:16:52 +00002259 if (Tok.isNot(tok::colon))
Richard Smith72553fc2014-01-23 23:53:27 +00002260 ParseDeclarator(DeclaratorInfo);
Richard Smith3d1a94c2014-08-12 00:22:39 +00002261 else
2262 DeclaratorInfo.SetIdentifier(nullptr, Tok.getLocation());
Richard Smith72553fc2014-01-23 23:53:27 +00002263
2264 if (!DeclaratorInfo.isFunctionDeclarator() && TryConsumeToken(tok::colon)) {
Richard Smith3d1a94c2014-08-12 00:22:39 +00002265 assert(DeclaratorInfo.isPastIdentifier() &&
2266 "don't know where identifier would go yet?");
Richard Smith72553fc2014-01-23 23:53:27 +00002267 BitfieldSize = ParseConstantExpression();
2268 if (BitfieldSize.isInvalid())
2269 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002270 } else {
Richard Smith3d1a94c2014-08-12 00:22:39 +00002271 ParseOptionalCXX11VirtSpecifierSeq(
2272 VS, getCurrentClass().IsInterface,
2273 DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002274 if (!VS.isUnset())
2275 MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo, VS);
2276 }
Richard Smith72553fc2014-01-23 23:53:27 +00002277
2278 // If a simple-asm-expr is present, parse it.
2279 if (Tok.is(tok::kw_asm)) {
2280 SourceLocation Loc;
2281 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
2282 if (AsmLabel.isInvalid())
2283 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2284
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002285 DeclaratorInfo.setAsmLabel(AsmLabel.get());
Richard Smith72553fc2014-01-23 23:53:27 +00002286 DeclaratorInfo.SetRangeEnd(Loc);
2287 }
2288
2289 // If attributes exist after the declarator, but before an '{', parse them.
2290 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
Richard Smith4b5a9492014-01-24 22:34:35 +00002291
2292 // For compatibility with code written to older Clang, also accept a
2293 // virt-specifier *after* the GNU attributes.
Aaron Ballman5d153e32014-08-04 17:03:51 +00002294 if (BitfieldSize.isUnset() && VS.isUnset()) {
Richard Smith3d1a94c2014-08-12 00:22:39 +00002295 ParseOptionalCXX11VirtSpecifierSeq(
2296 VS, getCurrentClass().IsInterface,
2297 DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
Aaron Ballman5d153e32014-08-04 17:03:51 +00002298 if (!VS.isUnset()) {
2299 // If we saw any GNU-style attributes that are known to GCC followed by a
2300 // virt-specifier, issue a GCC-compat warning.
2301 const AttributeList *Attr = DeclaratorInfo.getAttributes();
2302 while (Attr) {
2303 if (Attr->isKnownToGCC() && !Attr->isCXX11Attribute())
2304 Diag(Attr->getLoc(), diag::warn_gcc_attribute_location);
2305 Attr = Attr->getNext();
2306 }
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002307 MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo, VS);
Aaron Ballman5d153e32014-08-04 17:03:51 +00002308 }
2309 }
Nico Weberd89e6f72015-01-16 19:34:13 +00002310
2311 // If this has neither a name nor a bit width, something has gone seriously
2312 // wrong. Skip until the semi-colon or }.
2313 if (!DeclaratorInfo.hasName() && BitfieldSize.isUnset()) {
2314 // If so, skip until the semi-colon or a }.
2315 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2316 return true;
2317 }
2318 return false;
Richard Smith72553fc2014-01-23 23:53:27 +00002319}
2320
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002321/// \brief Look for declaration specifiers possibly occurring after C++11
2322/// virt-specifier-seq and diagnose them.
2323void Parser::MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(
2324 Declarator &D,
2325 VirtSpecifiers &VS) {
2326 DeclSpec DS(AttrFactory);
2327
2328 // GNU-style and C++11 attributes are not allowed here, but they will be
2329 // handled by the caller. Diagnose everything else.
Alex Lorenz8f4d3992017-02-13 23:19:40 +00002330 ParseTypeQualifierListOpt(
2331 DS, AR_NoAttributesParsed, false,
2332 /*IdentifierRequired=*/false, llvm::function_ref<void()>([&]() {
2333 Actions.CodeCompleteFunctionQualifiers(DS, D, &VS);
2334 }));
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002335 D.ExtendWithDeclSpec(DS);
2336
2337 if (D.isFunctionDeclarator()) {
Ehsan Akhgaric07d1e22015-03-25 00:53:33 +00002338 auto &Function = D.getFunctionTypeInfo();
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002339 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
2340 auto DeclSpecCheck = [&] (DeclSpec::TQ TypeQual,
2341 const char *FixItName,
2342 SourceLocation SpecLoc,
2343 unsigned* QualifierLoc) {
2344 FixItHint Insertion;
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002345 if (DS.getTypeQualifiers() & TypeQual) {
2346 if (!(Function.TypeQuals & TypeQual)) {
2347 std::string Name(FixItName);
2348 Name += " ";
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00002349 Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), Name);
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002350 Function.TypeQuals |= TypeQual;
2351 *QualifierLoc = SpecLoc.getRawEncoding();
2352 }
2353 Diag(SpecLoc, diag::err_declspec_after_virtspec)
2354 << FixItName
2355 << VirtSpecifiers::getSpecifierName(VS.getLastSpecifier())
2356 << FixItHint::CreateRemoval(SpecLoc)
2357 << Insertion;
2358 }
2359 };
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002360 DeclSpecCheck(DeclSpec::TQ_const, "const", DS.getConstSpecLoc(),
2361 &Function.ConstQualifierLoc);
2362 DeclSpecCheck(DeclSpec::TQ_volatile, "volatile", DS.getVolatileSpecLoc(),
2363 &Function.VolatileQualifierLoc);
2364 DeclSpecCheck(DeclSpec::TQ_restrict, "restrict", DS.getRestrictSpecLoc(),
2365 &Function.RestrictQualifierLoc);
2366 }
Ehsan Akhgaric07d1e22015-03-25 00:53:33 +00002367
2368 // Parse ref-qualifiers.
2369 bool RefQualifierIsLValueRef = true;
2370 SourceLocation RefQualifierLoc;
2371 if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc)) {
2372 const char *Name = (RefQualifierIsLValueRef ? "& " : "&& ");
2373 FixItHint Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), Name);
2374 Function.RefQualifierIsLValueRef = RefQualifierIsLValueRef;
2375 Function.RefQualifierLoc = RefQualifierLoc.getRawEncoding();
2376
2377 Diag(RefQualifierLoc, diag::err_declspec_after_virtspec)
2378 << (RefQualifierIsLValueRef ? "&" : "&&")
2379 << VirtSpecifiers::getSpecifierName(VS.getLastSpecifier())
2380 << FixItHint::CreateRemoval(RefQualifierLoc)
2381 << Insertion;
2382 D.SetRangeEnd(RefQualifierLoc);
2383 }
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002384 }
2385}
2386
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002387/// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration.
2388///
2389/// member-declaration:
2390/// decl-specifier-seq[opt] member-declarator-list[opt] ';'
2391/// function-definition ';'[opt]
2392/// ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO]
2393/// using-declaration [TODO]
Anders Carlssonf24fcff62009-03-11 16:27:10 +00002394/// [C++0x] static_assert-declaration
Anders Carlssondfbbdf62009-03-26 00:52:18 +00002395/// template-declaration
Chris Lattnerd19c1c02008-12-18 01:12:00 +00002396/// [GNU] '__extension__' member-declaration
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002397///
2398/// member-declarator-list:
2399/// member-declarator
2400/// member-declarator-list ',' member-declarator
2401///
2402/// member-declarator:
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002403/// declarator virt-specifier-seq[opt] pure-specifier[opt]
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002404/// declarator constant-initializer[opt]
Richard Smith938f40b2011-06-11 17:19:42 +00002405/// [C++11] declarator brace-or-equal-initializer[opt]
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002406/// identifier[opt] ':' constant-expression
2407///
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002408/// virt-specifier-seq:
2409/// virt-specifier
2410/// virt-specifier-seq virt-specifier
2411///
2412/// virt-specifier:
2413/// override
2414/// final
David Majnemera5433082013-10-18 00:33:31 +00002415/// [MS] sealed
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002416///
Sebastian Redl42e92c42009-04-12 17:16:29 +00002417/// pure-specifier:
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002418/// '= 0'
2419///
2420/// constant-initializer:
2421/// '=' constant-expression
2422///
Alexey Bataev05c25d62015-07-31 08:42:25 +00002423Parser::DeclGroupPtrTy
2424Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS,
2425 AttributeList *AccessAttrs,
John McCall796c2a52010-07-16 08:13:16 +00002426 const ParsedTemplateInfo &TemplateInfo,
2427 ParsingDeclRAIIObject *TemplateDiags) {
Douglas Gregor23c84762011-04-14 17:21:19 +00002428 if (Tok.is(tok::at)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002429 if (getLangOpts().ObjC1 && NextToken().isObjCAtKeyword(tok::objc_defs))
Douglas Gregor23c84762011-04-14 17:21:19 +00002430 Diag(Tok, diag::err_at_defs_cxx);
2431 else
2432 Diag(Tok, diag::err_at_in_class);
Richard Smithda35e962013-11-09 04:52:51 +00002433
Douglas Gregor23c84762011-04-14 17:21:19 +00002434 ConsumeToken();
Alexey Bataevee6507d2013-11-18 08:17:37 +00002435 SkipUntil(tok::r_brace, StopAtSemi);
David Blaikie0403cb12016-01-15 23:43:25 +00002436 return nullptr;
Douglas Gregor23c84762011-04-14 17:21:19 +00002437 }
Richard Smithda35e962013-11-09 04:52:51 +00002438
Serge Pavlov458ea762014-07-16 05:16:52 +00002439 // Turn on colon protection early, while parsing declspec, although there is
2440 // nothing to protect there. It prevents from false errors if error recovery
2441 // incorrectly determines where the declspec ends, as in the example:
2442 // struct A { enum class B { C }; };
2443 // const int C = 4;
2444 // struct D { A::B : C; };
2445 ColonProtectionRAIIObject X(*this);
2446
John McCalla0097262009-12-11 02:10:03 +00002447 // Access declarations.
Richard Smith45855df2012-05-09 08:23:23 +00002448 bool MalformedTypeSpec = false;
John McCalla0097262009-12-11 02:10:03 +00002449 if (!TemplateInfo.Kind &&
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002450 Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw___super)) {
Richard Smith45855df2012-05-09 08:23:23 +00002451 if (TryAnnotateCXXScopeToken())
2452 MalformedTypeSpec = true;
2453
2454 bool isAccessDecl;
2455 if (Tok.isNot(tok::annot_cxxscope))
2456 isAccessDecl = false;
2457 else if (NextToken().is(tok::identifier))
John McCalla0097262009-12-11 02:10:03 +00002458 isAccessDecl = GetLookAheadToken(2).is(tok::semi);
2459 else
2460 isAccessDecl = NextToken().is(tok::kw_operator);
2461
2462 if (isAccessDecl) {
2463 // Collect the scope specifier token we annotated earlier.
2464 CXXScopeSpec SS;
David Blaikieefdccaa2016-01-15 23:43:34 +00002465 ParseOptionalCXXScopeSpecifier(SS, nullptr,
Douglas Gregordf593fb2011-11-07 17:33:42 +00002466 /*EnteringContext=*/false);
John McCalla0097262009-12-11 02:10:03 +00002467
Nico Weberef03e702014-09-10 00:59:37 +00002468 if (SS.isInvalid()) {
2469 SkipUntil(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002470 return nullptr;
Nico Weberef03e702014-09-10 00:59:37 +00002471 }
2472
John McCalla0097262009-12-11 02:10:03 +00002473 // Try to parse an unqualified-id.
Abramo Bagnara7945c982012-01-27 09:46:47 +00002474 SourceLocation TemplateKWLoc;
John McCalla0097262009-12-11 02:10:03 +00002475 UnqualifiedId Name;
Richard Smith35845152017-02-07 01:37:30 +00002476 if (ParseUnqualifiedId(SS, false, true, true, false, nullptr,
2477 TemplateKWLoc, Name)) {
John McCalla0097262009-12-11 02:10:03 +00002478 SkipUntil(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002479 return nullptr;
John McCalla0097262009-12-11 02:10:03 +00002480 }
2481
2482 // TODO: recover from mistakenly-qualified operator declarations.
Alp Toker383d2c42014-01-01 03:08:43 +00002483 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
2484 "access declaration")) {
2485 SkipUntil(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002486 return nullptr;
Alp Toker383d2c42014-01-01 03:08:43 +00002487 }
John McCalla0097262009-12-11 02:10:03 +00002488
Alexey Bataev05c25d62015-07-31 08:42:25 +00002489 return DeclGroupPtrTy::make(DeclGroupRef(Actions.ActOnUsingDeclaration(
Richard Smith151c4562016-12-20 21:35:28 +00002490 getCurScope(), AS, /*UsingLoc*/ SourceLocation(),
2491 /*TypenameLoc*/ SourceLocation(), SS, Name,
2492 /*EllipsisLoc*/ SourceLocation(), /*AttrList*/ nullptr)));
John McCalla0097262009-12-11 02:10:03 +00002493 }
2494 }
2495
Aaron Ballmane7c544d2014-08-04 20:28:35 +00002496 // static_assert-declaration. A templated static_assert declaration is
2497 // diagnosed in Parser::ParseSingleDeclarationAfterTemplate.
2498 if (!TemplateInfo.Kind &&
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002499 Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert)) {
Chris Lattner49836b42009-04-02 04:16:50 +00002500 SourceLocation DeclEnd;
Alexey Bataev05c25d62015-07-31 08:42:25 +00002501 return DeclGroupPtrTy::make(
2502 DeclGroupRef(ParseStaticAssertDeclaration(DeclEnd)));
Chris Lattner5bbb3c82009-03-29 16:50:03 +00002503 }
Mike Stump11289f42009-09-09 15:08:12 +00002504
Chris Lattner5bbb3c82009-03-29 16:50:03 +00002505 if (Tok.is(tok::kw_template)) {
Mike Stump11289f42009-09-09 15:08:12 +00002506 assert(!TemplateInfo.TemplateParams &&
Douglas Gregor3447e762009-08-20 22:52:58 +00002507 "Nested template improperly parsed?");
Richard Smith3af70092017-02-09 22:14:25 +00002508 ObjCDeclContextSwitch ObjCDC(*this);
Chris Lattner49836b42009-04-02 04:16:50 +00002509 SourceLocation DeclEnd;
Alexey Bataev05c25d62015-07-31 08:42:25 +00002510 return DeclGroupPtrTy::make(
Richard Smith3af70092017-02-09 22:14:25 +00002511 DeclGroupRef(ParseTemplateDeclarationOrSpecialization(
Alexey Bataev05c25d62015-07-31 08:42:25 +00002512 Declarator::MemberContext, DeclEnd, AS, AccessAttrs)));
Chris Lattner5bbb3c82009-03-29 16:50:03 +00002513 }
Anders Carlssondfbbdf62009-03-26 00:52:18 +00002514
Chris Lattnerd19c1c02008-12-18 01:12:00 +00002515 // Handle: member-declaration ::= '__extension__' member-declaration
2516 if (Tok.is(tok::kw___extension__)) {
2517 // __extension__ silences extension warnings in the subexpression.
2518 ExtensionRAIIObject O(Diags); // Use RAII to do this.
2519 ConsumeToken();
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00002520 return ParseCXXClassMemberDeclaration(AS, AccessAttrs,
2521 TemplateInfo, TemplateDiags);
Chris Lattnerd19c1c02008-12-18 01:12:00 +00002522 }
Douglas Gregorfec52632009-06-20 00:51:54 +00002523
John McCall084e83d2011-03-24 11:26:52 +00002524 ParsedAttributesWithRange attrs(AttrFactory);
Michael Handdc016d2012-11-28 23:17:40 +00002525 ParsedAttributesWithRange FnAttrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00002526 // Optional C++11 attribute-specifier
2527 MaybeParseCXX11Attributes(attrs);
Michael Handdc016d2012-11-28 23:17:40 +00002528 // We need to keep these attributes for future diagnostic
2529 // before they are taken over by declaration specifier.
2530 FnAttrs.addAll(attrs.getList());
2531 FnAttrs.Range = attrs.Range;
2532
John McCall53fa7142010-12-24 02:08:15 +00002533 MaybeParseMicrosoftAttributes(attrs);
Alexis Hunt96d5c762009-11-21 08:43:09 +00002534
Douglas Gregorfec52632009-06-20 00:51:54 +00002535 if (Tok.is(tok::kw_using)) {
John McCall53fa7142010-12-24 02:08:15 +00002536 ProhibitAttributes(attrs);
Mike Stump11289f42009-09-09 15:08:12 +00002537
Douglas Gregorfec52632009-06-20 00:51:54 +00002538 // Eat 'using'.
2539 SourceLocation UsingLoc = ConsumeToken();
2540
2541 if (Tok.is(tok::kw_namespace)) {
2542 Diag(UsingLoc, diag::err_using_namespace_in_class);
Alexey Bataevee6507d2013-11-18 08:17:37 +00002543 SkipUntil(tok::semi, StopBeforeMatch);
David Blaikie0403cb12016-01-15 23:43:25 +00002544 return nullptr;
Douglas Gregorfec52632009-06-20 00:51:54 +00002545 }
Alexey Bataev05c25d62015-07-31 08:42:25 +00002546 SourceLocation DeclEnd;
2547 // Otherwise, it must be a using-declaration or an alias-declaration.
Richard Smith6f1daa42016-12-16 00:58:48 +00002548 return ParseUsingDeclaration(Declarator::MemberContext, TemplateInfo,
2549 UsingLoc, DeclEnd, AS);
Douglas Gregorfec52632009-06-20 00:51:54 +00002550 }
2551
DeLesley Hutchinsbd2ee132012-03-02 22:12:59 +00002552 // Hold late-parsed attributes so we can attach a Decl to them later.
2553 LateParsedAttrList CommonLateParsedAttrs;
2554
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002555 // decl-specifier-seq:
2556 // Parse the common declaration-specifiers piece.
John McCall796c2a52010-07-16 08:13:16 +00002557 ParsingDeclSpec DS(*this, TemplateDiags);
John McCall53fa7142010-12-24 02:08:15 +00002558 DS.takeAttributesFrom(attrs);
Richard Smith45855df2012-05-09 08:23:23 +00002559 if (MalformedTypeSpec)
2560 DS.SetTypeSpecError();
Richard Smith72553fc2014-01-23 23:53:27 +00002561
Serge Pavlov458ea762014-07-16 05:16:52 +00002562 ParseDeclarationSpecifiers(DS, TemplateInfo, AS, DSC_class,
2563 &CommonLateParsedAttrs);
2564
2565 // Turn off colon protection that was set for declspec.
2566 X.restore();
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002567
Richard Smith404dfb42013-11-19 22:47:36 +00002568 // If we had a free-standing type definition with a missing semicolon, we
2569 // may get this far before the problem becomes obvious.
2570 if (DS.hasTagDefinition() &&
2571 TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate &&
2572 DiagnoseMissingSemiAfterTagDefinition(DS, AS, DSC_class,
2573 &CommonLateParsedAttrs))
David Blaikie0403cb12016-01-15 23:43:25 +00002574 return nullptr;
Richard Smith404dfb42013-11-19 22:47:36 +00002575
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002576 MultiTemplateParamsArg TemplateParams(
Craig Topper161e4db2014-05-21 06:02:52 +00002577 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->data()
2578 : nullptr,
John McCall11083da2009-09-16 22:47:08 +00002579 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->size() : 0);
2580
Alp Toker35d87032013-12-30 23:29:50 +00002581 if (TryConsumeToken(tok::semi)) {
Michael Handdc016d2012-11-28 23:17:40 +00002582 if (DS.isFriendSpecified())
2583 ProhibitAttributes(FnAttrs);
2584
Nico Weber7b837f52016-01-28 19:25:00 +00002585 RecordDecl *AnonRecord = nullptr;
2586 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(
2587 getCurScope(), AS, DS, TemplateParams, false, AnonRecord);
John McCall796c2a52010-07-16 08:13:16 +00002588 DS.complete(TheDecl);
Nico Weber7b837f52016-01-28 19:25:00 +00002589 if (AnonRecord) {
2590 Decl* decls[] = {AnonRecord, TheDecl};
Richard Smith3beb7c62017-01-12 02:27:38 +00002591 return Actions.BuildDeclaratorGroup(decls);
Nico Weber7b837f52016-01-28 19:25:00 +00002592 }
2593 return Actions.ConvertDeclToDeclGroup(TheDecl);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002594 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002595
John McCall28a6aea2009-11-04 02:18:39 +00002596 ParsingDeclarator DeclaratorInfo(*this, DS, Declarator::MemberContext);
Nico Weber24b2a822011-01-28 06:07:34 +00002597 VirtSpecifiers VS;
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002598
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002599 // Hold late-parsed attributes so we can attach a Decl to them later.
2600 LateParsedAttrList LateParsedAttrs;
2601
Douglas Gregor50cefbf2011-10-17 17:09:53 +00002602 SourceLocation EqualLoc;
Richard Smith9ba0fec2015-06-30 01:28:56 +00002603 SourceLocation PureSpecLoc;
2604
Yaron Keren180c1672015-06-30 07:35:19 +00002605 auto TryConsumePureSpecifier = [&] (bool AllowDefinition) {
Richard Smith9ba0fec2015-06-30 01:28:56 +00002606 if (Tok.isNot(tok::equal))
2607 return false;
2608
2609 auto &Zero = NextToken();
2610 SmallString<8> Buffer;
2611 if (Zero.isNot(tok::numeric_constant) || Zero.getLength() != 1 ||
2612 PP.getSpelling(Zero, Buffer) != "0")
2613 return false;
2614
2615 auto &After = GetLookAheadToken(2);
2616 if (!After.isOneOf(tok::semi, tok::comma) &&
2617 !(AllowDefinition &&
2618 After.isOneOf(tok::l_brace, tok::colon, tok::kw_try)))
2619 return false;
2620
2621 EqualLoc = ConsumeToken();
2622 PureSpecLoc = ConsumeToken();
2623 return true;
2624 };
Chris Lattner17c3b1f2009-12-10 01:59:24 +00002625
Richard Smith72553fc2014-01-23 23:53:27 +00002626 SmallVector<Decl *, 8> DeclsInGroup;
2627 ExprResult BitfieldSize;
2628 bool ExpectSemi = true;
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002629
Richard Smith72553fc2014-01-23 23:53:27 +00002630 // Parse the first declarator.
Nico Weberd89e6f72015-01-16 19:34:13 +00002631 if (ParseCXXMemberDeclaratorBeforeInitializer(
2632 DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs)) {
Richard Smith72553fc2014-01-23 23:53:27 +00002633 TryConsumeToken(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002634 return nullptr;
Richard Smith72553fc2014-01-23 23:53:27 +00002635 }
John Thompson5bc5cbe2009-11-25 22:58:06 +00002636
Richard Smith72553fc2014-01-23 23:53:27 +00002637 // Check for a member function definition.
Richard Smith4b5a9492014-01-24 22:34:35 +00002638 if (BitfieldSize.isUnset()) {
Richard Smith72553fc2014-01-23 23:53:27 +00002639 // MSVC permits pure specifier on inline functions defined at class scope.
Francois Pichet3abc9b82011-05-11 02:14:46 +00002640 // Hence check for =0 before checking for function definition.
Richard Smith9ba0fec2015-06-30 01:28:56 +00002641 if (getLangOpts().MicrosoftExt && DeclaratorInfo.isDeclarationOfFunction())
2642 TryConsumePureSpecifier(/*AllowDefinition*/ true);
Francois Pichet3abc9b82011-05-11 02:14:46 +00002643
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00002644 FunctionDefinitionKind DefinitionKind = FDK_Declaration;
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002645 // function-definition:
Richard Smith938f40b2011-06-11 17:19:42 +00002646 //
2647 // In C++11, a non-function declarator followed by an open brace is a
2648 // braced-init-list for an in-class member initialization, not an
2649 // erroneous function definition.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002650 if (Tok.is(tok::l_brace) && !getLangOpts().CPlusPlus11) {
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00002651 DefinitionKind = FDK_Definition;
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002652 } else if (DeclaratorInfo.isFunctionDeclarator()) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002653 if (Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try)) {
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00002654 DefinitionKind = FDK_Definition;
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002655 } else if (Tok.is(tok::equal)) {
2656 const Token &KW = NextToken();
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00002657 if (KW.is(tok::kw_default))
2658 DefinitionKind = FDK_Defaulted;
2659 else if (KW.is(tok::kw_delete))
2660 DefinitionKind = FDK_Deleted;
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002661 }
2662 }
Eli Bendersky41842222015-03-23 23:49:41 +00002663 DeclaratorInfo.setFunctionDefinitionKind(DefinitionKind);
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002664
Michael Handdc016d2012-11-28 23:17:40 +00002665 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
2666 // to a friend declaration, that declaration shall be a definition.
2667 if (DeclaratorInfo.isFunctionDeclarator() &&
2668 DefinitionKind != FDK_Definition && DS.isFriendSpecified()) {
2669 // Diagnose attributes that appear before decl specifier:
2670 // [[]] friend int foo();
2671 ProhibitAttributes(FnAttrs);
2672 }
2673
Nico Webera7f137d2015-01-16 19:35:01 +00002674 if (DefinitionKind != FDK_Declaration) {
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002675 if (!DeclaratorInfo.isFunctionDeclarator()) {
Richard Trieu0d730542012-01-21 02:59:18 +00002676 Diag(DeclaratorInfo.getIdentifierLoc(), diag::err_func_def_no_params);
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002677 ConsumeBrace();
Alexey Bataevee6507d2013-11-18 08:17:37 +00002678 SkipUntil(tok::r_brace);
Michael Handdc016d2012-11-28 23:17:40 +00002679
Douglas Gregor8a4db832011-01-19 16:41:58 +00002680 // Consume the optional ';'
Alp Toker35d87032013-12-30 23:29:50 +00002681 TryConsumeToken(tok::semi);
2682
David Blaikie0403cb12016-01-15 23:43:25 +00002683 return nullptr;
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002684 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002685
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002686 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
Richard Trieu0d730542012-01-21 02:59:18 +00002687 Diag(DeclaratorInfo.getIdentifierLoc(),
2688 diag::err_function_declared_typedef);
Douglas Gregor8a4db832011-01-19 16:41:58 +00002689
Richard Smith2603b092012-11-15 22:54:20 +00002690 // Recover by treating the 'typedef' as spurious.
2691 DS.ClearStorageClassSpecs();
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002692 }
2693
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002694 Decl *FunDecl =
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00002695 ParseCXXInlineMethodDef(AS, AccessAttrs, DeclaratorInfo, TemplateInfo,
Richard Smith9ba0fec2015-06-30 01:28:56 +00002696 VS, PureSpecLoc);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002697
David Majnemer23252a32013-08-01 04:22:55 +00002698 if (FunDecl) {
2699 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i) {
2700 CommonLateParsedAttrs[i]->addDecl(FunDecl);
2701 }
2702 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i) {
2703 LateParsedAttrs[i]->addDecl(FunDecl);
2704 }
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002705 }
2706 LateParsedAttrs.clear();
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002707
2708 // Consume the ';' - it's optional unless we have a delete or default
Richard Trieu2f7dc462012-05-16 19:04:59 +00002709 if (Tok.is(tok::semi))
Richard Smith87f5dc52012-07-23 05:45:25 +00002710 ConsumeExtraSemi(AfterMemberFunctionDefinition);
Douglas Gregor8a4db832011-01-19 16:41:58 +00002711
Alexey Bataev05c25d62015-07-31 08:42:25 +00002712 return DeclGroupPtrTy::make(DeclGroupRef(FunDecl));
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002713 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002714 }
2715
2716 // member-declarator-list:
2717 // member-declarator
2718 // member-declarator-list ',' member-declarator
2719
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002720 while (1) {
Richard Smith2b013182012-06-10 03:12:00 +00002721 InClassInitStyle HasInClassInit = ICIS_NoInit;
Richard Smith9ba0fec2015-06-30 01:28:56 +00002722 bool HasStaticInitializer = false;
2723 if (Tok.isOneOf(tok::equal, tok::l_brace) && PureSpecLoc.isInvalid()) {
Richard Smith6b8e3c02017-08-28 00:28:14 +00002724 if (DeclaratorInfo.isDeclarationOfFunction()) {
Richard Smith9ba0fec2015-06-30 01:28:56 +00002725 // It's a pure-specifier.
2726 if (!TryConsumePureSpecifier(/*AllowFunctionDefinition*/ false))
2727 // Parse it as an expression so that Sema can diagnose it.
2728 HasStaticInitializer = true;
2729 } else if (DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2730 DeclSpec::SCS_static &&
2731 DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2732 DeclSpec::SCS_typedef &&
2733 !DS.isFriendSpecified()) {
2734 // It's a default member initializer.
Richard Smith6b8e3c02017-08-28 00:28:14 +00002735 if (BitfieldSize.get())
2736 Diag(Tok, getLangOpts().CPlusPlus2a
2737 ? diag::warn_cxx17_compat_bitfield_member_init
2738 : diag::ext_bitfield_member_init);
Richard Smith9ba0fec2015-06-30 01:28:56 +00002739 HasInClassInit = Tok.is(tok::equal) ? ICIS_CopyInit : ICIS_ListInit;
Richard Smith938f40b2011-06-11 17:19:42 +00002740 } else {
Richard Smith9ba0fec2015-06-30 01:28:56 +00002741 HasStaticInitializer = true;
Richard Smith938f40b2011-06-11 17:19:42 +00002742 }
2743 }
2744
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002745 // NOTE: If Sema is the Action module and declarator is an instance field,
Chris Lattner5bbb3c82009-03-29 16:50:03 +00002746 // this call will *not* return the created decl; It will return null.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002747 // See Sema::ActOnCXXMemberDeclarator for details.
John McCall07e91c02009-08-06 02:15:43 +00002748
Craig Topper161e4db2014-05-21 06:02:52 +00002749 NamedDecl *ThisDecl = nullptr;
John McCall07e91c02009-08-06 02:15:43 +00002750 if (DS.isFriendSpecified()) {
Richard Smith72553fc2014-01-23 23:53:27 +00002751 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
Michael Handdc016d2012-11-28 23:17:40 +00002752 // to a friend declaration, that declaration shall be a definition.
2753 //
Richard Smith72553fc2014-01-23 23:53:27 +00002754 // Diagnose attributes that appear in a friend member function declarator:
2755 // friend int foo [[]] ();
Michael Handdc016d2012-11-28 23:17:40 +00002756 SmallVector<SourceRange, 4> Ranges;
2757 DeclaratorInfo.getCXX11AttributeRanges(Ranges);
Richard Smith72553fc2014-01-23 23:53:27 +00002758 for (SmallVectorImpl<SourceRange>::iterator I = Ranges.begin(),
2759 E = Ranges.end(); I != E; ++I)
2760 Diag((*I).getBegin(), diag::err_attributes_not_allowed) << *I;
Michael Handdc016d2012-11-28 23:17:40 +00002761
Douglas Gregor0be31a22010-07-02 17:43:08 +00002762 ThisDecl = Actions.ActOnFriendFunctionDecl(getCurScope(), DeclaratorInfo,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002763 TemplateParams);
Douglas Gregor3447e762009-08-20 22:52:58 +00002764 } else {
Douglas Gregor0be31a22010-07-02 17:43:08 +00002765 ThisDecl = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS,
John McCall07e91c02009-08-06 02:15:43 +00002766 DeclaratorInfo,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002767 TemplateParams,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002768 BitfieldSize.get(),
Richard Smith2b013182012-06-10 03:12:00 +00002769 VS, HasInClassInit);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002770
2771 if (VarTemplateDecl *VT =
Craig Topper161e4db2014-05-21 06:02:52 +00002772 ThisDecl ? dyn_cast<VarTemplateDecl>(ThisDecl) : nullptr)
Larisse Voufo39a1e502013-08-06 01:03:05 +00002773 // Re-direct this decl to refer to the templated decl so that we can
2774 // initialize it.
2775 ThisDecl = VT->getTemplatedDecl();
2776
David Majnemer23252a32013-08-01 04:22:55 +00002777 if (ThisDecl && AccessAttrs)
Richard Smithf8a75c32013-08-29 00:47:48 +00002778 Actions.ProcessDeclAttributeList(getCurScope(), ThisDecl, AccessAttrs);
Douglas Gregor3447e762009-08-20 22:52:58 +00002779 }
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002780
Richard Smith9ba0fec2015-06-30 01:28:56 +00002781 // Error recovery might have converted a non-static member into a static
2782 // member.
David Blaikie35506f82013-01-30 01:22:18 +00002783 if (HasInClassInit != ICIS_NoInit &&
Richard Smith9ba0fec2015-06-30 01:28:56 +00002784 DeclaratorInfo.getDeclSpec().getStorageClassSpec() ==
2785 DeclSpec::SCS_static) {
2786 HasInClassInit = ICIS_NoInit;
2787 HasStaticInitializer = true;
2788 }
2789
2790 if (ThisDecl && PureSpecLoc.isValid())
2791 Actions.ActOnPureSpecifier(ThisDecl, PureSpecLoc);
2792
2793 // Handle the initializer.
2794 if (HasInClassInit != ICIS_NoInit) {
Douglas Gregor728d00b2011-10-10 14:49:18 +00002795 // The initializer was deferred; parse it and cache the tokens.
David Majnemer23252a32013-08-01 04:22:55 +00002796 Diag(Tok, getLangOpts().CPlusPlus11
2797 ? diag::warn_cxx98_compat_nonstatic_member_init
2798 : diag::ext_nonstatic_member_init);
Richard Smith5d164bc2011-10-15 05:09:34 +00002799
Richard Smith938f40b2011-06-11 17:19:42 +00002800 if (DeclaratorInfo.isArrayOfUnknownBound()) {
Richard Smith2b013182012-06-10 03:12:00 +00002801 // C++11 [dcl.array]p3: An array bound may also be omitted when the
2802 // declarator is followed by an initializer.
Richard Smith938f40b2011-06-11 17:19:42 +00002803 //
2804 // A brace-or-equal-initializer for a member-declarator is not an
David Blaikiecdd91db2012-02-14 09:00:46 +00002805 // initializer in the grammar, so this is ill-formed.
Richard Smith938f40b2011-06-11 17:19:42 +00002806 Diag(Tok, diag::err_incomplete_array_member_init);
Alexey Bataevee6507d2013-11-18 08:17:37 +00002807 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
David Majnemer23252a32013-08-01 04:22:55 +00002808
2809 // Avoid later warnings about a class member of incomplete type.
David Blaikiecdd91db2012-02-14 09:00:46 +00002810 if (ThisDecl)
David Blaikiecdd91db2012-02-14 09:00:46 +00002811 ThisDecl->setInvalidDecl();
Richard Smith938f40b2011-06-11 17:19:42 +00002812 } else
2813 ParseCXXNonStaticMemberInitializer(ThisDecl);
Richard Smith9ba0fec2015-06-30 01:28:56 +00002814 } else if (HasStaticInitializer) {
Douglas Gregor728d00b2011-10-10 14:49:18 +00002815 // Normal initializer.
Richard Smith9ba0fec2015-06-30 01:28:56 +00002816 ExprResult Init = ParseCXXMemberInitializer(
2817 ThisDecl, DeclaratorInfo.isDeclarationOfFunction(), EqualLoc);
David Majnemer23252a32013-08-01 04:22:55 +00002818
Douglas Gregor728d00b2011-10-10 14:49:18 +00002819 if (Init.isInvalid())
Alexey Bataevee6507d2013-11-18 08:17:37 +00002820 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
Douglas Gregor728d00b2011-10-10 14:49:18 +00002821 else if (ThisDecl)
Richard Smith3beb7c62017-01-12 02:27:38 +00002822 Actions.AddInitializerToDecl(ThisDecl, Init.get(), EqualLoc.isInvalid());
David Majnemer23252a32013-08-01 04:22:55 +00002823 } else if (ThisDecl && DS.getStorageClassSpec() == DeclSpec::SCS_static)
Douglas Gregor728d00b2011-10-10 14:49:18 +00002824 // No initializer.
Richard Smith3beb7c62017-01-12 02:27:38 +00002825 Actions.ActOnUninitializedDecl(ThisDecl);
David Majnemer23252a32013-08-01 04:22:55 +00002826
Douglas Gregor728d00b2011-10-10 14:49:18 +00002827 if (ThisDecl) {
David Majnemer23252a32013-08-01 04:22:55 +00002828 if (!ThisDecl->isInvalidDecl()) {
2829 // Set the Decl for any late parsed attributes
2830 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i)
2831 CommonLateParsedAttrs[i]->addDecl(ThisDecl);
2832
2833 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i)
2834 LateParsedAttrs[i]->addDecl(ThisDecl);
2835 }
Douglas Gregor728d00b2011-10-10 14:49:18 +00002836 Actions.FinalizeDeclaration(ThisDecl);
2837 DeclsInGroup.push_back(ThisDecl);
David Majnemer23252a32013-08-01 04:22:55 +00002838
2839 if (DeclaratorInfo.isFunctionDeclarator() &&
2840 DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2841 DeclSpec::SCS_typedef)
2842 HandleMemberFunctionDeclDelays(DeclaratorInfo, ThisDecl);
Douglas Gregor728d00b2011-10-10 14:49:18 +00002843 }
David Majnemer23252a32013-08-01 04:22:55 +00002844 LateParsedAttrs.clear();
Douglas Gregor728d00b2011-10-10 14:49:18 +00002845
2846 DeclaratorInfo.complete(ThisDecl);
Richard Smith938f40b2011-06-11 17:19:42 +00002847
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002848 // If we don't have a comma, it is either the end of the list (a ';')
2849 // or an error, bail out.
Alp Toker094e5212014-01-05 03:27:11 +00002850 SourceLocation CommaLoc;
2851 if (!TryConsumeToken(tok::comma, CommaLoc))
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002852 break;
Mike Stump11289f42009-09-09 15:08:12 +00002853
Richard Smithc8a79032012-01-09 22:31:44 +00002854 if (Tok.isAtStartOfLine() &&
2855 !MightBeDeclarator(Declarator::MemberContext)) {
2856 // This comma was followed by a line-break and something which can't be
2857 // the start of a declarator. The comma was probably a typo for a
2858 // semicolon.
2859 Diag(CommaLoc, diag::err_expected_semi_declaration)
2860 << FixItHint::CreateReplacement(CommaLoc, ";");
2861 ExpectSemi = false;
2862 break;
2863 }
Mike Stump11289f42009-09-09 15:08:12 +00002864
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002865 // Parse the next declarator.
2866 DeclaratorInfo.clear();
Nico Weber24b2a822011-01-28 06:07:34 +00002867 VS.clear();
Nico Weberf56c85b2015-01-17 02:26:40 +00002868 BitfieldSize = ExprResult(/*Invalid=*/false);
Richard Smith9ba0fec2015-06-30 01:28:56 +00002869 EqualLoc = PureSpecLoc = SourceLocation();
Richard Smith8d06f422012-01-12 23:53:29 +00002870 DeclaratorInfo.setCommaLoc(CommaLoc);
Mike Stump11289f42009-09-09 15:08:12 +00002871
Richard Smith72553fc2014-01-23 23:53:27 +00002872 // GNU attributes are allowed before the second and subsequent declarator.
John McCall53fa7142010-12-24 02:08:15 +00002873 MaybeParseGNUAttributes(DeclaratorInfo);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002874
Nico Weberd89e6f72015-01-16 19:34:13 +00002875 if (ParseCXXMemberDeclaratorBeforeInitializer(
2876 DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs))
2877 break;
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002878 }
2879
Richard Smithc8a79032012-01-09 22:31:44 +00002880 if (ExpectSemi &&
2881 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list)) {
Chris Lattner916dbf12010-02-02 00:43:15 +00002882 // Skip to end of block or statement.
Alexey Bataevee6507d2013-11-18 08:17:37 +00002883 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Chris Lattner916dbf12010-02-02 00:43:15 +00002884 // If we stopped at a ';', eat it.
Alp Toker35d87032013-12-30 23:29:50 +00002885 TryConsumeToken(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002886 return nullptr;
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002887 }
2888
Alexey Bataev05c25d62015-07-31 08:42:25 +00002889 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002890}
2891
Richard Smith9ba0fec2015-06-30 01:28:56 +00002892/// ParseCXXMemberInitializer - Parse the brace-or-equal-initializer.
2893/// Also detect and reject any attempted defaulted/deleted function definition.
2894/// The location of the '=', if any, will be placed in EqualLoc.
Richard Smith938f40b2011-06-11 17:19:42 +00002895///
Richard Smith9ba0fec2015-06-30 01:28:56 +00002896/// This does not check for a pure-specifier; that's handled elsewhere.
Sebastian Redleef474c2012-02-22 10:50:08 +00002897///
Richard Smith938f40b2011-06-11 17:19:42 +00002898/// brace-or-equal-initializer:
2899/// '=' initializer-expression
Sebastian Redleef474c2012-02-22 10:50:08 +00002900/// braced-init-list
2901///
Richard Smith938f40b2011-06-11 17:19:42 +00002902/// initializer-clause:
2903/// assignment-expression
Sebastian Redleef474c2012-02-22 10:50:08 +00002904/// braced-init-list
2905///
Richard Smithda35e962013-11-09 04:52:51 +00002906/// defaulted/deleted function-definition:
Richard Smith938f40b2011-06-11 17:19:42 +00002907/// '=' 'default'
2908/// '=' 'delete'
2909///
2910/// Prior to C++0x, the assignment-expression in an initializer-clause must
2911/// be a constant-expression.
Douglas Gregor926410d2012-02-21 02:22:07 +00002912ExprResult Parser::ParseCXXMemberInitializer(Decl *D, bool IsFunction,
Richard Smith938f40b2011-06-11 17:19:42 +00002913 SourceLocation &EqualLoc) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002914 assert(Tok.isOneOf(tok::equal, tok::l_brace)
Richard Smith938f40b2011-06-11 17:19:42 +00002915 && "Data member initializer not starting with '=' or '{'");
2916
Faisal Valid143a0c2017-04-01 21:30:49 +00002917 EnterExpressionEvaluationContext Context(
2918 Actions, Sema::ExpressionEvaluationContext::PotentiallyEvaluated, D);
Alp Toker094e5212014-01-05 03:27:11 +00002919 if (TryConsumeToken(tok::equal, EqualLoc)) {
Richard Smith938f40b2011-06-11 17:19:42 +00002920 if (Tok.is(tok::kw_delete)) {
2921 // In principle, an initializer of '= delete p;' is legal, but it will
2922 // never type-check. It's better to diagnose it as an ill-formed expression
2923 // than as an ill-formed deleted non-function member.
2924 // An initializer of '= delete p, foo' will never be parsed, because
2925 // a top-level comma always ends the initializer expression.
2926 const Token &Next = NextToken();
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002927 if (IsFunction || Next.isOneOf(tok::semi, tok::comma, tok::eof)) {
Richard Smith938f40b2011-06-11 17:19:42 +00002928 if (IsFunction)
2929 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2930 << 1 /* delete */;
2931 else
2932 Diag(ConsumeToken(), diag::err_deleted_non_function);
Richard Smithedcb26e2014-06-11 00:49:52 +00002933 return ExprError();
Richard Smith938f40b2011-06-11 17:19:42 +00002934 }
2935 } else if (Tok.is(tok::kw_default)) {
Richard Smith938f40b2011-06-11 17:19:42 +00002936 if (IsFunction)
2937 Diag(Tok, diag::err_default_delete_in_multiple_declaration)
2938 << 0 /* default */;
2939 else
2940 Diag(ConsumeToken(), diag::err_default_special_members);
Richard Smithedcb26e2014-06-11 00:49:52 +00002941 return ExprError();
Richard Smith938f40b2011-06-11 17:19:42 +00002942 }
David Majnemer87ff66c2014-12-13 11:34:16 +00002943 }
2944 if (const auto *PD = dyn_cast_or_null<MSPropertyDecl>(D)) {
2945 Diag(Tok, diag::err_ms_property_initializer) << PD;
2946 return ExprError();
Sebastian Redleef474c2012-02-22 10:50:08 +00002947 }
2948 return ParseInitializer();
Richard Smith938f40b2011-06-11 17:19:42 +00002949}
2950
Richard Smith65ebb4a2015-03-26 04:09:53 +00002951void Parser::SkipCXXMemberSpecification(SourceLocation RecordLoc,
2952 SourceLocation AttrFixitLoc,
2953 unsigned TagType, Decl *TagDecl) {
2954 // Skip the optional 'final' keyword.
2955 if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
2956 assert(isCXX11FinalKeyword() && "not a class definition");
2957 ConsumeToken();
2958
2959 // Diagnose any C++11 attributes after 'final' keyword.
2960 // We deliberately discard these attributes.
2961 ParsedAttributesWithRange Attrs(AttrFactory);
2962 CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
2963
2964 // This can only happen if we had malformed misplaced attributes;
2965 // we only get called if there is a colon or left-brace after the
2966 // attributes.
2967 if (Tok.isNot(tok::colon) && Tok.isNot(tok::l_brace))
2968 return;
2969 }
2970
2971 // Skip the base clauses. This requires actually parsing them, because
2972 // otherwise we can't be sure where they end (a left brace may appear
2973 // within a template argument).
2974 if (Tok.is(tok::colon)) {
2975 // Enter the scope of the class so that we can correctly parse its bases.
2976 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
2977 ParsingClassDefinition ParsingDef(*this, TagDecl, /*NonNestedClass*/ true,
2978 TagType == DeclSpec::TST_interface);
Richard Smith0f192e82015-06-11 22:48:25 +00002979 auto OldContext =
2980 Actions.ActOnTagStartSkippedDefinition(getCurScope(), TagDecl);
Richard Smith65ebb4a2015-03-26 04:09:53 +00002981
2982 // Parse the bases but don't attach them to the class.
2983 ParseBaseClause(nullptr);
2984
Richard Smith0f192e82015-06-11 22:48:25 +00002985 Actions.ActOnTagFinishSkippedDefinition(OldContext);
Richard Smith65ebb4a2015-03-26 04:09:53 +00002986
2987 if (!Tok.is(tok::l_brace)) {
2988 Diag(PP.getLocForEndOfToken(PrevTokLocation),
2989 diag::err_expected_lbrace_after_base_specifiers);
2990 return;
2991 }
2992 }
2993
2994 // Skip the body.
2995 assert(Tok.is(tok::l_brace));
2996 BalancedDelimiterTracker T(*this, tok::l_brace);
2997 T.consumeOpen();
2998 T.skipToEnd();
Richard Smith04c6c1f2015-07-01 18:56:50 +00002999
3000 // Parse and discard any trailing attributes.
3001 ParsedAttributes Attrs(AttrFactory);
3002 if (Tok.is(tok::kw___attribute))
3003 MaybeParseGNUAttributes(Attrs);
Richard Smith65ebb4a2015-03-26 04:09:53 +00003004}
3005
Alexey Bataev05c25d62015-07-31 08:42:25 +00003006Parser::DeclGroupPtrTy Parser::ParseCXXClassMemberDeclarationWithPragmas(
3007 AccessSpecifier &AS, ParsedAttributesWithRange &AccessAttrs,
3008 DeclSpec::TST TagType, Decl *TagDecl) {
Richard Smithb55f7582017-01-28 01:12:10 +00003009 switch (Tok.getKind()) {
3010 case tok::kw___if_exists:
3011 case tok::kw___if_not_exists:
Alexey Bataev05c25d62015-07-31 08:42:25 +00003012 ParseMicrosoftIfExistsClassDeclaration(TagType, AS);
David Blaikie0403cb12016-01-15 23:43:25 +00003013 return nullptr;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003014
Richard Smithb55f7582017-01-28 01:12:10 +00003015 case tok::semi:
3016 // Check for extraneous top-level semicolon.
Alexey Bataev05c25d62015-07-31 08:42:25 +00003017 ConsumeExtraSemi(InsideStruct, TagType);
David Blaikie0403cb12016-01-15 23:43:25 +00003018 return nullptr;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003019
Richard Smithb55f7582017-01-28 01:12:10 +00003020 // Handle pragmas that can appear as member declarations.
3021 case tok::annot_pragma_vis:
Alexey Bataev05c25d62015-07-31 08:42:25 +00003022 HandlePragmaVisibility();
David Blaikie0403cb12016-01-15 23:43:25 +00003023 return nullptr;
Richard Smithb55f7582017-01-28 01:12:10 +00003024 case tok::annot_pragma_pack:
Alexey Bataev05c25d62015-07-31 08:42:25 +00003025 HandlePragmaPack();
David Blaikie0403cb12016-01-15 23:43:25 +00003026 return nullptr;
Richard Smithb55f7582017-01-28 01:12:10 +00003027 case tok::annot_pragma_align:
Alexey Bataev05c25d62015-07-31 08:42:25 +00003028 HandlePragmaAlign();
David Blaikie0403cb12016-01-15 23:43:25 +00003029 return nullptr;
Richard Smithb55f7582017-01-28 01:12:10 +00003030 case tok::annot_pragma_ms_pointers_to_members:
Alexey Bataev05c25d62015-07-31 08:42:25 +00003031 HandlePragmaMSPointersToMembers();
David Blaikie0403cb12016-01-15 23:43:25 +00003032 return nullptr;
Richard Smithb55f7582017-01-28 01:12:10 +00003033 case tok::annot_pragma_ms_pragma:
Alexey Bataev05c25d62015-07-31 08:42:25 +00003034 HandlePragmaMSPragma();
David Blaikie0403cb12016-01-15 23:43:25 +00003035 return nullptr;
Richard Smithb55f7582017-01-28 01:12:10 +00003036 case tok::annot_pragma_ms_vtordisp:
Alexey Bataev3d42f342015-11-20 07:02:57 +00003037 HandlePragmaMSVtorDisp();
David Blaikie0403cb12016-01-15 23:43:25 +00003038 return nullptr;
Richard Smithb256d302017-01-28 01:20:57 +00003039 case tok::annot_pragma_dump:
3040 HandlePragmaDump();
3041 return nullptr;
Alexey Bataev3d42f342015-11-20 07:02:57 +00003042
Richard Smithb55f7582017-01-28 01:12:10 +00003043 case tok::kw_namespace:
3044 // If we see a namespace here, a close brace was missing somewhere.
Alexey Bataev05c25d62015-07-31 08:42:25 +00003045 DiagnoseUnexpectedNamespace(cast<NamedDecl>(TagDecl));
David Blaikie0403cb12016-01-15 23:43:25 +00003046 return nullptr;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003047
Richard Smithb55f7582017-01-28 01:12:10 +00003048 case tok::kw_public:
3049 case tok::kw_protected:
3050 case tok::kw_private: {
3051 AccessSpecifier NewAS = getAccessSpecifierIfPresent();
3052 assert(NewAS != AS_none);
Alexey Bataev05c25d62015-07-31 08:42:25 +00003053 // Current token is a C++ access specifier.
3054 AS = NewAS;
3055 SourceLocation ASLoc = Tok.getLocation();
3056 unsigned TokLength = Tok.getLength();
3057 ConsumeToken();
3058 AccessAttrs.clear();
3059 MaybeParseGNUAttributes(AccessAttrs);
3060
3061 SourceLocation EndLoc;
3062 if (TryConsumeToken(tok::colon, EndLoc)) {
3063 } else if (TryConsumeToken(tok::semi, EndLoc)) {
3064 Diag(EndLoc, diag::err_expected)
3065 << tok::colon << FixItHint::CreateReplacement(EndLoc, ":");
3066 } else {
3067 EndLoc = ASLoc.getLocWithOffset(TokLength);
3068 Diag(EndLoc, diag::err_expected)
3069 << tok::colon << FixItHint::CreateInsertion(EndLoc, ":");
3070 }
3071
3072 // The Microsoft extension __interface does not permit non-public
3073 // access specifiers.
3074 if (TagType == DeclSpec::TST_interface && AS != AS_public) {
3075 Diag(ASLoc, diag::err_access_specifier_interface) << (AS == AS_protected);
3076 }
3077
3078 if (Actions.ActOnAccessSpecifier(NewAS, ASLoc, EndLoc,
3079 AccessAttrs.getList())) {
3080 // found another attribute than only annotations
3081 AccessAttrs.clear();
3082 }
3083
David Blaikie0403cb12016-01-15 23:43:25 +00003084 return nullptr;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003085 }
3086
Richard Smithb55f7582017-01-28 01:12:10 +00003087 case tok::annot_pragma_openmp:
Alexey Bataev587e1de2016-03-30 10:43:55 +00003088 return ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, AccessAttrs, TagType,
3089 TagDecl);
Alexey Bataev05c25d62015-07-31 08:42:25 +00003090
Richard Smithb55f7582017-01-28 01:12:10 +00003091 default:
3092 return ParseCXXClassMemberDeclaration(AS, AccessAttrs.getList());
3093 }
Alexey Bataev05c25d62015-07-31 08:42:25 +00003094}
3095
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003096/// ParseCXXMemberSpecification - Parse the class definition.
3097///
3098/// member-specification:
3099/// member-declaration member-specification[opt]
3100/// access-specifier ':' member-specification[opt]
3101///
Joao Matose9a3ed42012-08-31 22:18:20 +00003102void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc,
Michael Han309af292013-01-07 16:57:11 +00003103 SourceLocation AttrFixitLoc,
Richard Smith4c96e992013-02-19 23:47:15 +00003104 ParsedAttributesWithRange &Attrs,
Joao Matose9a3ed42012-08-31 22:18:20 +00003105 unsigned TagType, Decl *TagDecl) {
3106 assert((TagType == DeclSpec::TST_struct ||
3107 TagType == DeclSpec::TST_interface ||
3108 TagType == DeclSpec::TST_union ||
3109 TagType == DeclSpec::TST_class) && "Invalid TagType!");
3110
John McCallfaf5fb42010-08-26 23:41:50 +00003111 PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc,
3112 "parsing struct/union/class body");
Mike Stump11289f42009-09-09 15:08:12 +00003113
Douglas Gregoredf8f392010-01-16 20:52:59 +00003114 // Determine whether this is a non-nested class. Note that local
3115 // classes are *not* considered to be nested classes.
3116 bool NonNestedClass = true;
3117 if (!ClassStack.empty()) {
Douglas Gregor0be31a22010-07-02 17:43:08 +00003118 for (const Scope *S = getCurScope(); S; S = S->getParent()) {
Douglas Gregoredf8f392010-01-16 20:52:59 +00003119 if (S->isClassScope()) {
3120 // We're inside a class scope, so this is a nested class.
3121 NonNestedClass = false;
John McCalldb632ac2012-09-25 07:32:39 +00003122
3123 // The Microsoft extension __interface does not permit nested classes.
3124 if (getCurrentClass().IsInterface) {
3125 Diag(RecordLoc, diag::err_invalid_member_in_interface)
3126 << /*ErrorType=*/6
3127 << (isa<NamedDecl>(TagDecl)
3128 ? cast<NamedDecl>(TagDecl)->getQualifiedNameAsString()
David Blaikieabe1a392014-04-02 05:58:29 +00003129 : "(anonymous)");
John McCalldb632ac2012-09-25 07:32:39 +00003130 }
Douglas Gregoredf8f392010-01-16 20:52:59 +00003131 break;
3132 }
3133
Serge Pavlovd9c0bcf2015-07-14 10:02:10 +00003134 if ((S->getFlags() & Scope::FnScope))
3135 // If we're in a function or function template then this is a local
3136 // class rather than a nested class.
3137 break;
Douglas Gregoredf8f392010-01-16 20:52:59 +00003138 }
3139 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003140
3141 // Enter a scope for the class.
Douglas Gregor658b9552009-01-09 22:42:13 +00003142 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003143
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003144 // Note that we are parsing a new (potentially-nested) class definition.
John McCalldb632ac2012-09-25 07:32:39 +00003145 ParsingClassDefinition ParsingDef(*this, TagDecl, NonNestedClass,
3146 TagType == DeclSpec::TST_interface);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003147
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003148 if (TagDecl)
Douglas Gregor0be31a22010-07-02 17:43:08 +00003149 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
John McCall2d814c32009-12-19 21:48:58 +00003150
Anders Carlssonf9eb63b2011-03-25 14:46:08 +00003151 SourceLocation FinalLoc;
David Majnemera5433082013-10-18 00:33:31 +00003152 bool IsFinalSpelledSealed = false;
Anders Carlssonf9eb63b2011-03-25 14:46:08 +00003153
3154 // Parse the optional 'final' keyword.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003155 if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
David Majnemera5433082013-10-18 00:33:31 +00003156 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier(Tok);
3157 assert((Specifier == VirtSpecifiers::VS_Final ||
Andrey Bokhanko276055b2016-07-29 10:42:48 +00003158 Specifier == VirtSpecifiers::VS_GNU_Final ||
David Majnemera5433082013-10-18 00:33:31 +00003159 Specifier == VirtSpecifiers::VS_Sealed) &&
3160 "not a class definition");
Richard Smithda261112011-10-15 04:21:46 +00003161 FinalLoc = ConsumeToken();
David Majnemera5433082013-10-18 00:33:31 +00003162 IsFinalSpelledSealed = Specifier == VirtSpecifiers::VS_Sealed;
Anders Carlssonf9eb63b2011-03-25 14:46:08 +00003163
David Majnemera5433082013-10-18 00:33:31 +00003164 if (TagType == DeclSpec::TST_interface)
John McCalldb632ac2012-09-25 07:32:39 +00003165 Diag(FinalLoc, diag::err_override_control_interface)
David Majnemera5433082013-10-18 00:33:31 +00003166 << VirtSpecifiers::getSpecifierName(Specifier);
3167 else if (Specifier == VirtSpecifiers::VS_Final)
3168 Diag(FinalLoc, getLangOpts().CPlusPlus11
3169 ? diag::warn_cxx98_compat_override_control_keyword
3170 : diag::ext_override_control_keyword)
3171 << VirtSpecifiers::getSpecifierName(Specifier);
3172 else if (Specifier == VirtSpecifiers::VS_Sealed)
3173 Diag(FinalLoc, diag::ext_ms_sealed_keyword);
Andrey Bokhanko276055b2016-07-29 10:42:48 +00003174 else if (Specifier == VirtSpecifiers::VS_GNU_Final)
3175 Diag(FinalLoc, diag::ext_warn_gnu_final);
Michael Han9407e502012-11-26 22:54:45 +00003176
Michael Han309af292013-01-07 16:57:11 +00003177 // Parse any C++11 attributes after 'final' keyword.
3178 // These attributes are not allowed to appear here,
3179 // and the only possible place for them to appertain
3180 // to the class would be between class-key and class-name.
Richard Smith4c96e992013-02-19 23:47:15 +00003181 CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
Nico Weber4b4be842014-12-29 06:56:50 +00003182
3183 // ParseClassSpecifier() does only a superficial check for attributes before
3184 // deciding to call this method. For example, for
3185 // `class C final alignas ([l) {` it will decide that this looks like a
3186 // misplaced attribute since it sees `alignas '(' ')'`. But the actual
3187 // attribute parsing code will try to parse the '[' as a constexpr lambda
3188 // and consume enough tokens that the alignas parsing code will eat the
3189 // opening '{'. So bail out if the next token isn't one we expect.
Nico Weber36de3a22014-12-29 21:56:22 +00003190 if (!Tok.is(tok::colon) && !Tok.is(tok::l_brace)) {
3191 if (TagDecl)
3192 Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
Nico Weber4b4be842014-12-29 06:56:50 +00003193 return;
Nico Weber36de3a22014-12-29 21:56:22 +00003194 }
Anders Carlssonf9eb63b2011-03-25 14:46:08 +00003195 }
Anders Carlsson4b63d0e2011-01-22 16:56:46 +00003196
John McCall2d814c32009-12-19 21:48:58 +00003197 if (Tok.is(tok::colon)) {
Erik Verbruggen6524c052017-10-24 13:46:58 +00003198 ParseScope InheritanceScope(this, getCurScope()->getFlags() |
3199 Scope::ClassInheritanceScope);
3200
John McCall2d814c32009-12-19 21:48:58 +00003201 ParseBaseClause(TagDecl);
John McCall2d814c32009-12-19 21:48:58 +00003202 if (!Tok.is(tok::l_brace)) {
Ismail Pazarbasi129c44c2014-09-25 21:13:02 +00003203 bool SuggestFixIt = false;
3204 SourceLocation BraceLoc = PP.getLocForEndOfToken(PrevTokLocation);
3205 if (Tok.isAtStartOfLine()) {
3206 switch (Tok.getKind()) {
3207 case tok::kw_private:
3208 case tok::kw_protected:
3209 case tok::kw_public:
3210 SuggestFixIt = NextToken().getKind() == tok::colon;
3211 break;
3212 case tok::kw_static_assert:
3213 case tok::r_brace:
3214 case tok::kw_using:
3215 // base-clause can have simple-template-id; 'template' can't be there
3216 case tok::kw_template:
3217 SuggestFixIt = true;
3218 break;
3219 case tok::identifier:
3220 SuggestFixIt = isConstructorDeclarator(true);
3221 break;
3222 default:
3223 SuggestFixIt = isCXXSimpleDeclaration(/*AllowForRangeDecl=*/false);
3224 break;
3225 }
3226 }
3227 DiagnosticBuilder LBraceDiag =
3228 Diag(BraceLoc, diag::err_expected_lbrace_after_base_specifiers);
3229 if (SuggestFixIt) {
3230 LBraceDiag << FixItHint::CreateInsertion(BraceLoc, " {");
3231 // Try recovering from missing { after base-clause.
3232 PP.EnterToken(Tok);
3233 Tok.setKind(tok::l_brace);
3234 } else {
3235 if (TagDecl)
3236 Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
3237 return;
3238 }
John McCall2d814c32009-12-19 21:48:58 +00003239 }
3240 }
3241
3242 assert(Tok.is(tok::l_brace));
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003243 BalancedDelimiterTracker T(*this, tok::l_brace);
3244 T.consumeOpen();
John McCall2d814c32009-12-19 21:48:58 +00003245
John McCall08bede42010-05-28 08:11:17 +00003246 if (TagDecl)
Anders Carlsson30f29442011-03-25 14:31:08 +00003247 Actions.ActOnStartCXXMemberDeclarations(getCurScope(), TagDecl, FinalLoc,
David Majnemera5433082013-10-18 00:33:31 +00003248 IsFinalSpelledSealed,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003249 T.getOpenLocation());
John McCall1c7e6ec2009-12-20 07:58:13 +00003250
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003251 // C++ 11p3: Members of a class defined with the keyword class are private
3252 // by default. Members of a class defined with the keywords struct or union
3253 // are public by default.
3254 AccessSpecifier CurAS;
3255 if (TagType == DeclSpec::TST_class)
3256 CurAS = AS_private;
3257 else
3258 CurAS = AS_public;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003259 ParsedAttributesWithRange AccessAttrs(AttrFactory);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003260
Douglas Gregor9377c822010-06-21 22:31:09 +00003261 if (TagDecl) {
3262 // While we still have something to read, read the member-declarations.
Richard Smith752ada82015-11-17 23:32:01 +00003263 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
3264 Tok.isNot(tok::eof)) {
Douglas Gregor9377c822010-06-21 22:31:09 +00003265 // Each iteration of this loop reads one member-declaration.
Alexey Bataev05c25d62015-07-31 08:42:25 +00003266 ParseCXXClassMemberDeclarationWithPragmas(
3267 CurAS, AccessAttrs, static_cast<DeclSpec::TST>(TagType), TagDecl);
Serge Pavlovc4e04a22015-09-19 05:32:57 +00003268 }
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003269 T.consumeClose();
Douglas Gregor9377c822010-06-21 22:31:09 +00003270 } else {
Alexey Bataevee6507d2013-11-18 08:17:37 +00003271 SkipUntil(tok::r_brace);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003272 }
Mike Stump11289f42009-09-09 15:08:12 +00003273
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003274 // If attributes exist after class contents, parse them.
John McCall084e83d2011-03-24 11:26:52 +00003275 ParsedAttributes attrs(AttrFactory);
John McCall53fa7142010-12-24 02:08:15 +00003276 MaybeParseGNUAttributes(attrs);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003277
John McCall08bede42010-05-28 08:11:17 +00003278 if (TagDecl)
Douglas Gregor0be31a22010-07-02 17:43:08 +00003279 Actions.ActOnFinishCXXMemberSpecification(getCurScope(), RecordLoc, TagDecl,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003280 T.getOpenLocation(),
3281 T.getCloseLocation(),
John McCall53fa7142010-12-24 02:08:15 +00003282 attrs.getList());
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003283
Douglas Gregor433e0532012-04-16 18:27:27 +00003284 // C++11 [class.mem]p2:
3285 // Within the class member-specification, the class is regarded as complete
Richard Smith0b3a4622014-11-13 20:01:57 +00003286 // within function bodies, default arguments, exception-specifications, and
Douglas Gregor433e0532012-04-16 18:27:27 +00003287 // brace-or-equal-initializers for non-static data members (including such
3288 // things in nested classes).
Douglas Gregor9377c822010-06-21 22:31:09 +00003289 if (TagDecl && NonNestedClass) {
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003290 // We are not inside a nested class. This class and its nested classes
Douglas Gregor4d87df52008-12-16 21:30:33 +00003291 // are complete and we can parse the delayed portions of method
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00003292 // declarations and the lexed inline method definitions, along with any
3293 // delayed attributes.
Douglas Gregor428119e2010-06-16 23:45:56 +00003294 SourceLocation SavedPrevTokLocation = PrevTokLocation;
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00003295 ParseLexedAttributes(getCurrentClass());
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003296 ParseLexedMethodDeclarations(getCurrentClass());
Richard Smith84973e52012-04-21 18:42:51 +00003297
3298 // We've finished with all pending member declarations.
3299 Actions.ActOnFinishCXXMemberDecls();
3300
Richard Smith938f40b2011-06-11 17:19:42 +00003301 ParseLexedMemberInitializers(getCurrentClass());
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003302 ParseLexedMethodDefs(getCurrentClass());
Douglas Gregor428119e2010-06-16 23:45:56 +00003303 PrevTokLocation = SavedPrevTokLocation;
Reid Klecknerbba3cb92015-03-17 19:00:50 +00003304
3305 // We've finished parsing everything, including default argument
3306 // initializers.
Hans Wennborg99000c22015-08-15 01:18:16 +00003307 Actions.ActOnFinishCXXNonNestedClass(TagDecl);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003308 }
3309
John McCall08bede42010-05-28 08:11:17 +00003310 if (TagDecl)
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00003311 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getRange());
John McCall2ff380a2010-03-17 00:38:33 +00003312
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003313 // Leave the class scope.
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003314 ParsingDef.Pop();
Douglas Gregor7307d6c2008-12-10 06:34:36 +00003315 ClassScope.Exit();
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003316}
Douglas Gregore8381c02008-11-05 04:29:56 +00003317
Richard Smith2ac43ad2013-11-15 23:00:02 +00003318void Parser::DiagnoseUnexpectedNamespace(NamedDecl *D) {
Richard Smithda35e962013-11-09 04:52:51 +00003319 assert(Tok.is(tok::kw_namespace));
3320
3321 // FIXME: Suggest where the close brace should have gone by looking
3322 // at indentation changes within the definition body.
Richard Smith2ac43ad2013-11-15 23:00:02 +00003323 Diag(D->getLocation(),
3324 diag::err_missing_end_of_definition) << D;
Richard Smithda35e962013-11-09 04:52:51 +00003325 Diag(Tok.getLocation(),
Richard Smith2ac43ad2013-11-15 23:00:02 +00003326 diag::note_missing_end_of_definition_before) << D;
Richard Smithda35e962013-11-09 04:52:51 +00003327
3328 // Push '};' onto the token stream to recover.
3329 PP.EnterToken(Tok);
3330
3331 Tok.startToken();
3332 Tok.setLocation(PP.getLocForEndOfToken(PrevTokLocation));
3333 Tok.setKind(tok::semi);
3334 PP.EnterToken(Tok);
3335
3336 Tok.setKind(tok::r_brace);
3337}
3338
Douglas Gregore8381c02008-11-05 04:29:56 +00003339/// ParseConstructorInitializer - Parse a C++ constructor initializer,
3340/// which explicitly initializes the members or base classes of a
3341/// class (C++ [class.base.init]). For example, the three initializers
3342/// after the ':' in the Derived constructor below:
3343///
3344/// @code
3345/// class Base { };
3346/// class Derived : Base {
3347/// int x;
3348/// float f;
3349/// public:
3350/// Derived(float f) : Base(), x(17), f(f) { }
3351/// };
3352/// @endcode
3353///
Mike Stump11289f42009-09-09 15:08:12 +00003354/// [C++] ctor-initializer:
3355/// ':' mem-initializer-list
Douglas Gregore8381c02008-11-05 04:29:56 +00003356///
Mike Stump11289f42009-09-09 15:08:12 +00003357/// [C++] mem-initializer-list:
Douglas Gregor44e7df62011-01-04 00:32:56 +00003358/// mem-initializer ...[opt]
3359/// mem-initializer ...[opt] , mem-initializer-list
John McCall48871652010-08-21 09:40:31 +00003360void Parser::ParseConstructorInitializer(Decl *ConstructorDecl) {
Nico Weber3b00fdc2015-03-07 19:52:39 +00003361 assert(Tok.is(tok::colon) &&
3362 "Constructor initializer always starts with ':'");
Douglas Gregore8381c02008-11-05 04:29:56 +00003363
Nico Weber3b00fdc2015-03-07 19:52:39 +00003364 // Poison the SEH identifiers so they are flagged as illegal in constructor
3365 // initializers.
John Wiegley1c0675e2011-04-28 01:08:34 +00003366 PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
Douglas Gregore8381c02008-11-05 04:29:56 +00003367 SourceLocation ColonLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +00003368
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003369 SmallVector<CXXCtorInitializer*, 4> MemInitializers;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003370 bool AnyErrors = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003371
Douglas Gregore8381c02008-11-05 04:29:56 +00003372 do {
Douglas Gregoreaeeca92010-08-28 00:00:50 +00003373 if (Tok.is(tok::code_completion)) {
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00003374 Actions.CodeCompleteConstructorInitializer(ConstructorDecl,
3375 MemInitializers);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00003376 return cutOffParsing();
Douglas Gregoreaeeca92010-08-28 00:00:50 +00003377 }
Alexey Bataev79de17d2016-01-20 05:25:51 +00003378
3379 MemInitResult MemInit = ParseMemInitializer(ConstructorDecl);
3380 if (!MemInit.isInvalid())
3381 MemInitializers.push_back(MemInit.get());
3382 else
3383 AnyErrors = true;
3384
Douglas Gregore8381c02008-11-05 04:29:56 +00003385 if (Tok.is(tok::comma))
3386 ConsumeToken();
3387 else if (Tok.is(tok::l_brace))
3388 break;
Alexey Bataev79de17d2016-01-20 05:25:51 +00003389 // If the previous initializer was valid and the next token looks like a
3390 // base or member initializer, assume that we're just missing a comma.
3391 else if (!MemInit.isInvalid() &&
3392 Tok.isOneOf(tok::identifier, tok::coloncolon)) {
Douglas Gregorce66d022010-09-07 14:51:08 +00003393 SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation);
3394 Diag(Loc, diag::err_ctor_init_missing_comma)
3395 << FixItHint::CreateInsertion(Loc, ", ");
3396 } else {
Douglas Gregore8381c02008-11-05 04:29:56 +00003397 // Skip over garbage, until we get to '{'. Don't eat the '{'.
Alexey Bataev79de17d2016-01-20 05:25:51 +00003398 if (!MemInit.isInvalid())
3399 Diag(Tok.getLocation(), diag::err_expected_either) << tok::l_brace
3400 << tok::comma;
Alexey Bataevee6507d2013-11-18 08:17:37 +00003401 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
Douglas Gregore8381c02008-11-05 04:29:56 +00003402 break;
3403 }
3404 } while (true);
3405
David Blaikie3fc2f912013-01-17 05:26:25 +00003406 Actions.ActOnMemInitializers(ConstructorDecl, ColonLoc, MemInitializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003407 AnyErrors);
Douglas Gregore8381c02008-11-05 04:29:56 +00003408}
3409
3410/// ParseMemInitializer - Parse a C++ member initializer, which is
3411/// part of a constructor initializer that explicitly initializes one
3412/// member or base class (C++ [class.base.init]). See
3413/// ParseConstructorInitializer for an example.
3414///
3415/// [C++] mem-initializer:
3416/// mem-initializer-id '(' expression-list[opt] ')'
Sebastian Redl3da34892011-06-05 12:23:16 +00003417/// [C++0x] mem-initializer-id braced-init-list
Mike Stump11289f42009-09-09 15:08:12 +00003418///
Douglas Gregore8381c02008-11-05 04:29:56 +00003419/// [C++] mem-initializer-id:
3420/// '::'[opt] nested-name-specifier[opt] class-name
3421/// identifier
Craig Topper9ad7e262014-10-31 06:57:07 +00003422MemInitResult Parser::ParseMemInitializer(Decl *ConstructorDecl) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00003423 // parse '::'[opt] nested-name-specifier[opt]
3424 CXXScopeSpec SS;
David Blaikieefdccaa2016-01-15 23:43:34 +00003425 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false);
Richard Smithaf3b3252017-05-18 19:21:48 +00003426
3427 // : identifier
3428 IdentifierInfo *II = nullptr;
3429 SourceLocation IdLoc = Tok.getLocation();
3430 // : declype(...)
3431 DeclSpec DS(AttrFactory);
3432 // : template_name<...>
John McCallba7bf592010-08-24 05:47:05 +00003433 ParsedType TemplateTypeTy;
Richard Smithaf3b3252017-05-18 19:21:48 +00003434
3435 if (Tok.is(tok::identifier)) {
3436 // Get the identifier. This may be a member name or a class name,
3437 // but we'll let the semantic analysis determine which it is.
3438 II = Tok.getIdentifierInfo();
3439 ConsumeToken();
3440 } else if (Tok.is(tok::annot_decltype)) {
3441 // Get the decltype expression, if there is one.
3442 // Uses of decltype will already have been converted to annot_decltype by
3443 // ParseOptionalCXXScopeSpecifier at this point.
3444 // FIXME: Can we get here with a scope specifier?
3445 ParseDecltypeSpecifier(DS);
3446 } else {
3447 TemplateIdAnnotation *TemplateId = Tok.is(tok::annot_template_id)
3448 ? takeTemplateIdAnnotation(Tok)
3449 : nullptr;
3450 if (TemplateId && (TemplateId->Kind == TNK_Type_template ||
3451 TemplateId->Kind == TNK_Dependent_template_name)) {
Richard Smith62559bd2017-02-01 21:36:38 +00003452 AnnotateTemplateIdTokenAsType(/*IsClassName*/true);
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00003453 assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
John McCallba7bf592010-08-24 05:47:05 +00003454 TemplateTypeTy = getTypeAnnotation(Tok);
Richard Smithaf3b3252017-05-18 19:21:48 +00003455 ConsumeAnnotationToken();
3456 } else {
3457 Diag(Tok, diag::err_expected_member_or_base_name);
3458 return true;
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00003459 }
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00003460 }
Douglas Gregore8381c02008-11-05 04:29:56 +00003461
3462 // Parse the '('.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003463 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
Richard Smith5d164bc2011-10-15 05:09:34 +00003464 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
3465
Sebastian Redla74948d2011-09-24 17:48:25 +00003466 ExprResult InitList = ParseBraceInitializer();
3467 if (InitList.isInvalid())
3468 return true;
3469
3470 SourceLocation EllipsisLoc;
Alp Toker094e5212014-01-05 03:27:11 +00003471 TryConsumeToken(tok::ellipsis, EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00003472
3473 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
David Blaikie186a8892012-01-24 06:03:59 +00003474 TemplateTypeTy, DS, IdLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003475 InitList.get(), EllipsisLoc);
Sebastian Redl3da34892011-06-05 12:23:16 +00003476 } else if(Tok.is(tok::l_paren)) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003477 BalancedDelimiterTracker T(*this, tok::l_paren);
3478 T.consumeOpen();
Douglas Gregore8381c02008-11-05 04:29:56 +00003479
Sebastian Redl3da34892011-06-05 12:23:16 +00003480 // Parse the optional expression-list.
Benjamin Kramerf0623432012-08-23 22:51:59 +00003481 ExprVector ArgExprs;
Sebastian Redl3da34892011-06-05 12:23:16 +00003482 CommaLocsTy CommaLocs;
3483 if (Tok.isNot(tok::r_paren) && ParseExpressionList(ArgExprs, CommaLocs)) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00003484 SkipUntil(tok::r_paren, StopAtSemi);
Sebastian Redl3da34892011-06-05 12:23:16 +00003485 return true;
3486 }
3487
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003488 T.consumeClose();
Sebastian Redl3da34892011-06-05 12:23:16 +00003489
3490 SourceLocation EllipsisLoc;
Alp Toker97650562014-01-10 11:19:30 +00003491 TryConsumeToken(tok::ellipsis, EllipsisLoc);
Sebastian Redl3da34892011-06-05 12:23:16 +00003492
3493 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
David Blaikie186a8892012-01-24 06:03:59 +00003494 TemplateTypeTy, DS, IdLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00003495 T.getOpenLocation(), ArgExprs,
3496 T.getCloseLocation(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00003497 }
3498
Alp Tokerec543272013-12-24 09:48:30 +00003499 if (getLangOpts().CPlusPlus11)
3500 return Diag(Tok, diag::err_expected_either) << tok::l_paren << tok::l_brace;
3501 else
3502 return Diag(Tok, diag::err_expected) << tok::l_paren;
Douglas Gregore8381c02008-11-05 04:29:56 +00003503}
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003504
Sebastian Redl965b0e32011-03-05 14:45:16 +00003505/// \brief Parse a C++ exception-specification if present (C++0x [except.spec]).
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003506///
Douglas Gregor356513d2008-12-01 18:00:20 +00003507/// exception-specification:
Sebastian Redl965b0e32011-03-05 14:45:16 +00003508/// dynamic-exception-specification
3509/// noexcept-specification
3510///
3511/// noexcept-specification:
3512/// 'noexcept'
3513/// 'noexcept' '(' constant-expression ')'
3514ExceptionSpecificationType
Richard Smith0b3a4622014-11-13 20:01:57 +00003515Parser::tryParseExceptionSpecification(bool Delayed,
Douglas Gregor433e0532012-04-16 18:27:27 +00003516 SourceRange &SpecificationRange,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003517 SmallVectorImpl<ParsedType> &DynamicExceptions,
3518 SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
Richard Smith0b3a4622014-11-13 20:01:57 +00003519 ExprResult &NoexceptExpr,
3520 CachedTokens *&ExceptionSpecTokens) {
Sebastian Redl965b0e32011-03-05 14:45:16 +00003521 ExceptionSpecificationType Result = EST_None;
Hans Wennborgdcfba332015-10-06 23:40:43 +00003522 ExceptionSpecTokens = nullptr;
Richard Smith0b3a4622014-11-13 20:01:57 +00003523
3524 // Handle delayed parsing of exception-specifications.
3525 if (Delayed) {
3526 if (Tok.isNot(tok::kw_throw) && Tok.isNot(tok::kw_noexcept))
3527 return EST_None;
Sebastian Redl965b0e32011-03-05 14:45:16 +00003528
Richard Smith0b3a4622014-11-13 20:01:57 +00003529 // Consume and cache the starting token.
3530 bool IsNoexcept = Tok.is(tok::kw_noexcept);
3531 Token StartTok = Tok;
3532 SpecificationRange = SourceRange(ConsumeToken());
3533
3534 // Check for a '('.
3535 if (!Tok.is(tok::l_paren)) {
3536 // If this is a bare 'noexcept', we're done.
3537 if (IsNoexcept) {
3538 Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
Hans Wennborgdcfba332015-10-06 23:40:43 +00003539 NoexceptExpr = nullptr;
Richard Smith0b3a4622014-11-13 20:01:57 +00003540 return EST_BasicNoexcept;
3541 }
3542
3543 Diag(Tok, diag::err_expected_lparen_after) << "throw";
3544 return EST_DynamicNone;
3545 }
3546
3547 // Cache the tokens for the exception-specification.
3548 ExceptionSpecTokens = new CachedTokens;
3549 ExceptionSpecTokens->push_back(StartTok); // 'throw' or 'noexcept'
3550 ExceptionSpecTokens->push_back(Tok); // '('
3551 SpecificationRange.setEnd(ConsumeParen()); // '('
Richard Smithb1c217e2015-01-13 02:24:58 +00003552
3553 ConsumeAndStoreUntil(tok::r_paren, *ExceptionSpecTokens,
3554 /*StopAtSemi=*/true,
3555 /*ConsumeFinalToken=*/true);
Aaron Ballman580ccaf2016-01-12 21:04:22 +00003556 SpecificationRange.setEnd(ExceptionSpecTokens->back().getLocation());
3557
Richard Smith0b3a4622014-11-13 20:01:57 +00003558 return EST_Unparsed;
3559 }
3560
Sebastian Redl965b0e32011-03-05 14:45:16 +00003561 // See if there's a dynamic specification.
3562 if (Tok.is(tok::kw_throw)) {
3563 Result = ParseDynamicExceptionSpecification(SpecificationRange,
3564 DynamicExceptions,
3565 DynamicExceptionRanges);
3566 assert(DynamicExceptions.size() == DynamicExceptionRanges.size() &&
3567 "Produced different number of exception types and ranges.");
3568 }
3569
3570 // If there's no noexcept specification, we're done.
3571 if (Tok.isNot(tok::kw_noexcept))
3572 return Result;
3573
Richard Smithb15c11c2011-10-17 23:06:20 +00003574 Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
3575
Sebastian Redl965b0e32011-03-05 14:45:16 +00003576 // If we already had a dynamic specification, parse the noexcept for,
3577 // recovery, but emit a diagnostic and don't store the results.
3578 SourceRange NoexceptRange;
3579 ExceptionSpecificationType NoexceptType = EST_None;
3580
3581 SourceLocation KeywordLoc = ConsumeToken();
3582 if (Tok.is(tok::l_paren)) {
3583 // There is an argument.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003584 BalancedDelimiterTracker T(*this, tok::l_paren);
3585 T.consumeOpen();
Sebastian Redl965b0e32011-03-05 14:45:16 +00003586 NoexceptType = EST_ComputedNoexcept;
3587 NoexceptExpr = ParseConstantExpression();
Serge Pavlov3739f5e72015-06-29 17:50:19 +00003588 T.consumeClose();
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003589 // The argument must be contextually convertible to bool. We use
Richard Smith03a4aa32016-06-23 19:02:52 +00003590 // CheckBooleanCondition for this purpose.
3591 // FIXME: Add a proper Sema entry point for this.
Serge Pavlov3739f5e72015-06-29 17:50:19 +00003592 if (!NoexceptExpr.isInvalid()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00003593 NoexceptExpr =
3594 Actions.CheckBooleanCondition(KeywordLoc, NoexceptExpr.get());
Serge Pavlov3739f5e72015-06-29 17:50:19 +00003595 NoexceptRange = SourceRange(KeywordLoc, T.getCloseLocation());
3596 } else {
Malcolm Parsonsa3220ce2017-01-12 16:11:28 +00003597 NoexceptType = EST_BasicNoexcept;
Serge Pavlov3739f5e72015-06-29 17:50:19 +00003598 }
Sebastian Redl965b0e32011-03-05 14:45:16 +00003599 } else {
3600 // There is no argument.
3601 NoexceptType = EST_BasicNoexcept;
3602 NoexceptRange = SourceRange(KeywordLoc, KeywordLoc);
3603 }
3604
3605 if (Result == EST_None) {
3606 SpecificationRange = NoexceptRange;
3607 Result = NoexceptType;
3608
3609 // If there's a dynamic specification after a noexcept specification,
3610 // parse that and ignore the results.
3611 if (Tok.is(tok::kw_throw)) {
3612 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
3613 ParseDynamicExceptionSpecification(NoexceptRange, DynamicExceptions,
3614 DynamicExceptionRanges);
3615 }
3616 } else {
3617 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
3618 }
3619
3620 return Result;
3621}
3622
Richard Smith8ca78a12013-06-13 02:02:51 +00003623static void diagnoseDynamicExceptionSpecification(
Craig Toppere335f252015-10-04 04:53:55 +00003624 Parser &P, SourceRange Range, bool IsNoexcept) {
Richard Smith8ca78a12013-06-13 02:02:51 +00003625 if (P.getLangOpts().CPlusPlus11) {
3626 const char *Replacement = IsNoexcept ? "noexcept" : "noexcept(false)";
Richard Smith82da19d2016-12-08 02:49:07 +00003627 P.Diag(Range.getBegin(),
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003628 P.getLangOpts().CPlusPlus17 && !IsNoexcept
Richard Smith82da19d2016-12-08 02:49:07 +00003629 ? diag::ext_dynamic_exception_spec
3630 : diag::warn_exception_spec_deprecated)
3631 << Range;
Richard Smith8ca78a12013-06-13 02:02:51 +00003632 P.Diag(Range.getBegin(), diag::note_exception_spec_deprecated)
3633 << Replacement << FixItHint::CreateReplacement(Range, Replacement);
3634 }
3635}
3636
Sebastian Redl965b0e32011-03-05 14:45:16 +00003637/// ParseDynamicExceptionSpecification - Parse a C++
3638/// dynamic-exception-specification (C++ [except.spec]).
3639///
3640/// dynamic-exception-specification:
Douglas Gregor356513d2008-12-01 18:00:20 +00003641/// 'throw' '(' type-id-list [opt] ')'
3642/// [MS] 'throw' '(' '...' ')'
Mike Stump11289f42009-09-09 15:08:12 +00003643///
Douglas Gregor356513d2008-12-01 18:00:20 +00003644/// type-id-list:
Douglas Gregor830837d2010-12-20 23:57:46 +00003645/// type-id ... [opt]
3646/// type-id-list ',' type-id ... [opt]
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003647///
Sebastian Redl965b0e32011-03-05 14:45:16 +00003648ExceptionSpecificationType Parser::ParseDynamicExceptionSpecification(
3649 SourceRange &SpecificationRange,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003650 SmallVectorImpl<ParsedType> &Exceptions,
3651 SmallVectorImpl<SourceRange> &Ranges) {
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003652 assert(Tok.is(tok::kw_throw) && "expected throw");
Mike Stump11289f42009-09-09 15:08:12 +00003653
Sebastian Redl965b0e32011-03-05 14:45:16 +00003654 SpecificationRange.setBegin(ConsumeToken());
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003655 BalancedDelimiterTracker T(*this, tok::l_paren);
3656 if (T.consumeOpen()) {
Sebastian Redl965b0e32011-03-05 14:45:16 +00003657 Diag(Tok, diag::err_expected_lparen_after) << "throw";
3658 SpecificationRange.setEnd(SpecificationRange.getBegin());
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003659 return EST_DynamicNone;
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003660 }
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003661
Douglas Gregor356513d2008-12-01 18:00:20 +00003662 // Parse throw(...), a Microsoft extension that means "this function
3663 // can throw anything".
3664 if (Tok.is(tok::ellipsis)) {
3665 SourceLocation EllipsisLoc = ConsumeToken();
David Blaikiebbafb8a2012-03-11 07:00:24 +00003666 if (!getLangOpts().MicrosoftExt)
Douglas Gregor356513d2008-12-01 18:00:20 +00003667 Diag(EllipsisLoc, diag::ext_ellipsis_exception_spec);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003668 T.consumeClose();
3669 SpecificationRange.setEnd(T.getCloseLocation());
Richard Smith8ca78a12013-06-13 02:02:51 +00003670 diagnoseDynamicExceptionSpecification(*this, SpecificationRange, false);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003671 return EST_MSAny;
Douglas Gregor356513d2008-12-01 18:00:20 +00003672 }
3673
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003674 // Parse the sequence of type-ids.
Sebastian Redld6434562009-05-29 18:02:33 +00003675 SourceRange Range;
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003676 while (Tok.isNot(tok::r_paren)) {
Sebastian Redld6434562009-05-29 18:02:33 +00003677 TypeResult Res(ParseTypeName(&Range));
Sebastian Redl965b0e32011-03-05 14:45:16 +00003678
Douglas Gregor830837d2010-12-20 23:57:46 +00003679 if (Tok.is(tok::ellipsis)) {
3680 // C++0x [temp.variadic]p5:
3681 // - In a dynamic-exception-specification (15.4); the pattern is a
3682 // type-id.
3683 SourceLocation Ellipsis = ConsumeToken();
Sebastian Redl965b0e32011-03-05 14:45:16 +00003684 Range.setEnd(Ellipsis);
Douglas Gregor830837d2010-12-20 23:57:46 +00003685 if (!Res.isInvalid())
3686 Res = Actions.ActOnPackExpansion(Res.get(), Ellipsis);
3687 }
Sebastian Redl965b0e32011-03-05 14:45:16 +00003688
Sebastian Redld6434562009-05-29 18:02:33 +00003689 if (!Res.isInvalid()) {
Sebastian Redl2b9cacb2009-04-29 17:30:04 +00003690 Exceptions.push_back(Res.get());
Sebastian Redld6434562009-05-29 18:02:33 +00003691 Ranges.push_back(Range);
3692 }
Alp Toker97650562014-01-10 11:19:30 +00003693
3694 if (!TryConsumeToken(tok::comma))
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003695 break;
3696 }
3697
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003698 T.consumeClose();
3699 SpecificationRange.setEnd(T.getCloseLocation());
Richard Smith8ca78a12013-06-13 02:02:51 +00003700 diagnoseDynamicExceptionSpecification(*this, SpecificationRange,
3701 Exceptions.empty());
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003702 return Exceptions.empty() ? EST_DynamicNone : EST_Dynamic;
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003703}
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003704
Douglas Gregor7fb25412010-10-01 18:44:50 +00003705/// ParseTrailingReturnType - Parse a trailing return type on a new-style
3706/// function declaration.
Douglas Gregordb0b9f12011-08-04 15:30:47 +00003707TypeResult Parser::ParseTrailingReturnType(SourceRange &Range) {
Douglas Gregor7fb25412010-10-01 18:44:50 +00003708 assert(Tok.is(tok::arrow) && "expected arrow");
3709
3710 ConsumeToken();
3711
Richard Smithbfdb1082012-03-12 08:56:40 +00003712 return ParseTypeName(&Range, Declarator::TrailingReturnContext);
Douglas Gregor7fb25412010-10-01 18:44:50 +00003713}
3714
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003715/// \brief We have just started parsing the definition of a new class,
3716/// so push that class onto our stack of classes that is currently
3717/// being parsed.
John McCallc1465822011-02-14 07:13:47 +00003718Sema::ParsingClassState
John McCalldb632ac2012-09-25 07:32:39 +00003719Parser::PushParsingClass(Decl *ClassDecl, bool NonNestedClass,
3720 bool IsInterface) {
Douglas Gregoredf8f392010-01-16 20:52:59 +00003721 assert((NonNestedClass || !ClassStack.empty()) &&
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003722 "Nested class without outer class");
John McCalldb632ac2012-09-25 07:32:39 +00003723 ClassStack.push(new ParsingClass(ClassDecl, NonNestedClass, IsInterface));
John McCallc1465822011-02-14 07:13:47 +00003724 return Actions.PushParsingClass();
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003725}
3726
3727/// \brief Deallocate the given parsed class and all of its nested
3728/// classes.
3729void Parser::DeallocateParsedClasses(Parser::ParsingClass *Class) {
Douglas Gregorefc46952010-10-12 16:25:54 +00003730 for (unsigned I = 0, N = Class->LateParsedDeclarations.size(); I != N; ++I)
3731 delete Class->LateParsedDeclarations[I];
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003732 delete Class;
3733}
3734
3735/// \brief Pop the top class of the stack of classes that are
3736/// currently being parsed.
3737///
3738/// This routine should be called when we have finished parsing the
3739/// definition of a class, but have not yet popped the Scope
3740/// associated with the class's definition.
John McCallc1465822011-02-14 07:13:47 +00003741void Parser::PopParsingClass(Sema::ParsingClassState state) {
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003742 assert(!ClassStack.empty() && "Mismatched push/pop for class parsing");
Mike Stump11289f42009-09-09 15:08:12 +00003743
John McCallc1465822011-02-14 07:13:47 +00003744 Actions.PopParsingClass(state);
3745
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003746 ParsingClass *Victim = ClassStack.top();
3747 ClassStack.pop();
3748 if (Victim->TopLevelClass) {
3749 // Deallocate all of the nested classes of this class,
3750 // recursively: we don't need to keep any of this information.
3751 DeallocateParsedClasses(Victim);
3752 return;
Mike Stump11289f42009-09-09 15:08:12 +00003753 }
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003754 assert(!ClassStack.empty() && "Missing top-level class?");
3755
Douglas Gregorefc46952010-10-12 16:25:54 +00003756 if (Victim->LateParsedDeclarations.empty()) {
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003757 // The victim is a nested class, but we will not need to perform
3758 // any processing after the definition of this class since it has
3759 // no members whose handling was delayed. Therefore, we can just
3760 // remove this nested class.
Douglas Gregorefc46952010-10-12 16:25:54 +00003761 DeallocateParsedClasses(Victim);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003762 return;
3763 }
3764
3765 // This nested class has some members that will need to be processed
3766 // after the top-level class is completely defined. Therefore, add
3767 // it to the list of nested classes within its parent.
Douglas Gregor0be31a22010-07-02 17:43:08 +00003768 assert(getCurScope()->isClassScope() && "Nested class outside of class scope?");
Douglas Gregorefc46952010-10-12 16:25:54 +00003769 ClassStack.top()->LateParsedDeclarations.push_back(new LateParsedClass(this, Victim));
Douglas Gregor0be31a22010-07-02 17:43:08 +00003770 Victim->TemplateScope = getCurScope()->getParent()->isTemplateParamScope();
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003771}
Alexis Hunt96d5c762009-11-21 08:43:09 +00003772
Richard Smith3dff2512012-04-10 03:25:07 +00003773/// \brief Try to parse an 'identifier' which appears within an attribute-token.
3774///
3775/// \return the parsed identifier on success, and 0 if the next token is not an
3776/// attribute-token.
3777///
3778/// C++11 [dcl.attr.grammar]p3:
3779/// If a keyword or an alternative token that satisfies the syntactic
3780/// requirements of an identifier is contained in an attribute-token,
3781/// it is considered an identifier.
3782IdentifierInfo *Parser::TryParseCXX11AttributeIdentifier(SourceLocation &Loc) {
3783 switch (Tok.getKind()) {
3784 default:
3785 // Identifiers and keywords have identifier info attached.
David Majnemerd5271992015-01-09 18:09:39 +00003786 if (!Tok.isAnnotation()) {
3787 if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
3788 Loc = ConsumeToken();
3789 return II;
3790 }
Richard Smith3dff2512012-04-10 03:25:07 +00003791 }
Craig Topper161e4db2014-05-21 06:02:52 +00003792 return nullptr;
Richard Smith3dff2512012-04-10 03:25:07 +00003793
3794 case tok::ampamp: // 'and'
3795 case tok::pipe: // 'bitor'
3796 case tok::pipepipe: // 'or'
3797 case tok::caret: // 'xor'
3798 case tok::tilde: // 'compl'
3799 case tok::amp: // 'bitand'
3800 case tok::ampequal: // 'and_eq'
3801 case tok::pipeequal: // 'or_eq'
3802 case tok::caretequal: // 'xor_eq'
3803 case tok::exclaim: // 'not'
3804 case tok::exclaimequal: // 'not_eq'
3805 // Alternative tokens do not have identifier info, but their spelling
3806 // starts with an alphabetical character.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003807 SmallString<8> SpellingBuf;
Benjamin Kramer60be5632015-03-29 19:25:07 +00003808 SourceLocation SpellingLoc =
3809 PP.getSourceManager().getSpellingLoc(Tok.getLocation());
3810 StringRef Spelling = PP.getSpelling(SpellingLoc, SpellingBuf);
Jordan Rosea7d03842013-02-08 22:30:41 +00003811 if (isLetter(Spelling[0])) {
Richard Smith3dff2512012-04-10 03:25:07 +00003812 Loc = ConsumeToken();
Benjamin Kramer5c17f9c2012-04-22 20:43:30 +00003813 return &PP.getIdentifierTable().get(Spelling);
Richard Smith3dff2512012-04-10 03:25:07 +00003814 }
Craig Topper161e4db2014-05-21 06:02:52 +00003815 return nullptr;
Richard Smith3dff2512012-04-10 03:25:07 +00003816 }
3817}
3818
Michael Han23214e52012-10-03 01:56:22 +00003819static bool IsBuiltInOrStandardCXX11Attribute(IdentifierInfo *AttrName,
Aaron Ballman606093a2017-10-15 15:01:42 +00003820 IdentifierInfo *ScopeName) {
Michael Han23214e52012-10-03 01:56:22 +00003821 switch (AttributeList::getKind(AttrName, ScopeName,
3822 AttributeList::AS_CXX11)) {
3823 case AttributeList::AT_CarriesDependency:
Aaron Ballman35f94212014-04-14 16:03:22 +00003824 case AttributeList::AT_Deprecated:
Michael Han23214e52012-10-03 01:56:22 +00003825 case AttributeList::AT_FallThrough:
Hans Wennborgdcfba332015-10-06 23:40:43 +00003826 case AttributeList::AT_CXX11NoReturn:
Michael Han23214e52012-10-03 01:56:22 +00003827 return true;
Aaron Ballmane7964782016-03-07 22:44:55 +00003828 case AttributeList::AT_WarnUnusedResult:
3829 return !ScopeName && AttrName->getName().equals("nodiscard");
Nico Weberac03bce2016-08-23 19:59:55 +00003830 case AttributeList::AT_Unused:
3831 return !ScopeName && AttrName->getName().equals("maybe_unused");
Michael Han23214e52012-10-03 01:56:22 +00003832 default:
3833 return false;
3834 }
3835}
3836
Aaron Ballmanb8e20392014-03-31 17:32:39 +00003837/// ParseCXX11AttributeArgs -- Parse a C++11 attribute-argument-clause.
3838///
3839/// [C++11] attribute-argument-clause:
3840/// '(' balanced-token-seq ')'
3841///
3842/// [C++11] balanced-token-seq:
3843/// balanced-token
3844/// balanced-token-seq balanced-token
3845///
3846/// [C++11] balanced-token:
3847/// '(' balanced-token-seq ')'
3848/// '[' balanced-token-seq ']'
3849/// '{' balanced-token-seq '}'
3850/// any token but '(', ')', '[', ']', '{', or '}'
3851bool Parser::ParseCXX11AttributeArgs(IdentifierInfo *AttrName,
3852 SourceLocation AttrNameLoc,
3853 ParsedAttributes &Attrs,
3854 SourceLocation *EndLoc,
3855 IdentifierInfo *ScopeName,
3856 SourceLocation ScopeLoc) {
3857 assert(Tok.is(tok::l_paren) && "Not a C++11 attribute argument list");
Aaron Ballman35f94212014-04-14 16:03:22 +00003858 SourceLocation LParenLoc = Tok.getLocation();
Aaron Ballman606093a2017-10-15 15:01:42 +00003859 const LangOptions &LO = getLangOpts();
3860 AttributeList::Syntax Syntax =
3861 LO.CPlusPlus ? AttributeList::AS_CXX11 : AttributeList::AS_C2x;
Aaron Ballmanb8e20392014-03-31 17:32:39 +00003862
3863 // If the attribute isn't known, we will not attempt to parse any
3864 // arguments.
Aaron Ballman606093a2017-10-15 15:01:42 +00003865 if (!hasAttribute(LO.CPlusPlus ? AttrSyntax::CXX : AttrSyntax::C, ScopeName,
3866 AttrName, getTargetInfo(), getLangOpts())) {
Aaron Ballmanb8e20392014-03-31 17:32:39 +00003867 // Eat the left paren, then skip to the ending right paren.
3868 ConsumeParen();
3869 SkipUntil(tok::r_paren);
3870 return false;
3871 }
3872
Alex Lorenzd5d27e12017-03-01 18:06:25 +00003873 if (ScopeName && ScopeName->getName() == "gnu") {
Aaron Ballmanb8e20392014-03-31 17:32:39 +00003874 // GNU-scoped attributes have some special cases to handle GNU-specific
3875 // behaviors.
3876 ParseGNUAttributeArgs(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
Aaron Ballman606093a2017-10-15 15:01:42 +00003877 ScopeLoc, Syntax, nullptr);
Alex Lorenzd5d27e12017-03-01 18:06:25 +00003878 return true;
3879 }
3880
3881 unsigned NumArgs;
3882 // Some Clang-scoped attributes have some special parsing behavior.
3883 if (ScopeName && ScopeName->getName() == "clang")
3884 NumArgs =
3885 ParseClangAttributeArgs(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
Aaron Ballman606093a2017-10-15 15:01:42 +00003886 ScopeLoc, Syntax);
Alex Lorenzd5d27e12017-03-01 18:06:25 +00003887 else
3888 NumArgs =
Aaron Ballman35f94212014-04-14 16:03:22 +00003889 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc,
Aaron Ballman606093a2017-10-15 15:01:42 +00003890 ScopeName, ScopeLoc, Syntax);
Alex Lorenzd5d27e12017-03-01 18:06:25 +00003891
3892 const AttributeList *Attr = Attrs.getList();
3893 if (Attr && IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName)) {
3894 // If the attribute is a standard or built-in attribute and we are
3895 // parsing an argument list, we need to determine whether this attribute
3896 // was allowed to have an argument list (such as [[deprecated]]), and how
3897 // many arguments were parsed (so we can diagnose on [[deprecated()]]).
3898 if (Attr->getMaxArgs() && !NumArgs) {
3899 // The attribute was allowed to have arguments, but none were provided
3900 // even though the attribute parsed successfully. This is an error.
3901 Diag(LParenLoc, diag::err_attribute_requires_arguments) << AttrName;
3902 Attr->setInvalid(true);
3903 } else if (!Attr->getMaxArgs()) {
3904 // The attribute parsed successfully, but was not allowed to have any
3905 // arguments. It doesn't matter whether any were provided -- the
3906 // presence of the argument list (even if empty) is diagnosed.
3907 Diag(LParenLoc, diag::err_cxx11_attribute_forbids_arguments)
3908 << AttrName
3909 << FixItHint::CreateRemoval(SourceRange(LParenLoc, *EndLoc));
3910 Attr->setInvalid(true);
Aaron Ballman35f94212014-04-14 16:03:22 +00003911 }
3912 }
Aaron Ballmanb8e20392014-03-31 17:32:39 +00003913 return true;
3914}
3915
Aaron Ballman606093a2017-10-15 15:01:42 +00003916/// ParseCXX11AttributeSpecifier - Parse a C++11 or C2x attribute-specifier.
Alexis Hunt96d5c762009-11-21 08:43:09 +00003917///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003918/// [C++11] attribute-specifier:
Alexis Hunt96d5c762009-11-21 08:43:09 +00003919/// '[' '[' attribute-list ']' ']'
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00003920/// alignment-specifier
Alexis Hunt96d5c762009-11-21 08:43:09 +00003921///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003922/// [C++11] attribute-list:
Alexis Hunt96d5c762009-11-21 08:43:09 +00003923/// attribute[opt]
3924/// attribute-list ',' attribute[opt]
Richard Smith3dff2512012-04-10 03:25:07 +00003925/// attribute '...'
3926/// attribute-list ',' attribute '...'
Alexis Hunt96d5c762009-11-21 08:43:09 +00003927///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003928/// [C++11] attribute:
Alexis Hunt96d5c762009-11-21 08:43:09 +00003929/// attribute-token attribute-argument-clause[opt]
3930///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003931/// [C++11] attribute-token:
Alexis Hunt96d5c762009-11-21 08:43:09 +00003932/// identifier
3933/// attribute-scoped-token
3934///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003935/// [C++11] attribute-scoped-token:
Alexis Hunt96d5c762009-11-21 08:43:09 +00003936/// attribute-namespace '::' identifier
3937///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003938/// [C++11] attribute-namespace:
Alexis Hunt96d5c762009-11-21 08:43:09 +00003939/// identifier
Richard Smith3dff2512012-04-10 03:25:07 +00003940void Parser::ParseCXX11AttributeSpecifier(ParsedAttributes &attrs,
Peter Collingbourne49eedec2011-09-29 18:04:05 +00003941 SourceLocation *endLoc) {
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00003942 if (Tok.is(tok::kw_alignas)) {
Richard Smithf679b5b2011-10-14 20:48:27 +00003943 Diag(Tok.getLocation(), diag::warn_cxx98_compat_alignas);
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00003944 ParseAlignmentSpecifier(attrs, endLoc);
3945 return;
3946 }
3947
Aaron Ballman606093a2017-10-15 15:01:42 +00003948 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square) &&
3949 "Not a double square bracket attribute list");
Alexis Hunt96d5c762009-11-21 08:43:09 +00003950
Richard Smithf679b5b2011-10-14 20:48:27 +00003951 Diag(Tok.getLocation(), diag::warn_cxx98_compat_attribute);
3952
Alexis Hunt96d5c762009-11-21 08:43:09 +00003953 ConsumeBracket();
3954 ConsumeBracket();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003955
Richard Smithb7d7a042016-06-24 12:15:12 +00003956 SourceLocation CommonScopeLoc;
3957 IdentifierInfo *CommonScopeName = nullptr;
3958 if (Tok.is(tok::kw_using)) {
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003959 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
Richard Smithb7d7a042016-06-24 12:15:12 +00003960 ? diag::warn_cxx14_compat_using_attribute_ns
3961 : diag::ext_using_attribute_ns);
3962 ConsumeToken();
3963
3964 CommonScopeName = TryParseCXX11AttributeIdentifier(CommonScopeLoc);
3965 if (!CommonScopeName) {
3966 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
3967 SkipUntil(tok::r_square, tok::colon, StopBeforeMatch);
3968 }
3969 if (!TryConsumeToken(tok::colon) && CommonScopeName)
3970 Diag(Tok.getLocation(), diag::err_expected) << tok::colon;
3971 }
3972
Richard Smith10876ef2013-01-17 01:30:42 +00003973 llvm::SmallDenseMap<IdentifierInfo*, SourceLocation, 4> SeenAttrs;
3974
Richard Smith3dff2512012-04-10 03:25:07 +00003975 while (Tok.isNot(tok::r_square)) {
Alexis Hunt96d5c762009-11-21 08:43:09 +00003976 // attribute not present
Alp Toker97650562014-01-10 11:19:30 +00003977 if (TryConsumeToken(tok::comma))
Alexis Hunt96d5c762009-11-21 08:43:09 +00003978 continue;
Alexis Hunt96d5c762009-11-21 08:43:09 +00003979
Richard Smith3dff2512012-04-10 03:25:07 +00003980 SourceLocation ScopeLoc, AttrLoc;
Craig Topper161e4db2014-05-21 06:02:52 +00003981 IdentifierInfo *ScopeName = nullptr, *AttrName = nullptr;
Richard Smith3dff2512012-04-10 03:25:07 +00003982
3983 AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
3984 if (!AttrName)
3985 // Break out to the "expected ']'" diagnostic.
3986 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003987
Alexis Hunt96d5c762009-11-21 08:43:09 +00003988 // scoped attribute
Alp Toker97650562014-01-10 11:19:30 +00003989 if (TryConsumeToken(tok::coloncolon)) {
Richard Smith3dff2512012-04-10 03:25:07 +00003990 ScopeName = AttrName;
3991 ScopeLoc = AttrLoc;
3992
3993 AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
3994 if (!AttrName) {
Alp Tokerec543272013-12-24 09:48:30 +00003995 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
Alexey Bataevee6507d2013-11-18 08:17:37 +00003996 SkipUntil(tok::r_square, tok::comma, StopAtSemi | StopBeforeMatch);
Alexis Hunt96d5c762009-11-21 08:43:09 +00003997 continue;
3998 }
Alexis Hunt96d5c762009-11-21 08:43:09 +00003999 }
4000
Richard Smithb7d7a042016-06-24 12:15:12 +00004001 if (CommonScopeName) {
4002 if (ScopeName) {
4003 Diag(ScopeLoc, diag::err_using_attribute_ns_conflict)
4004 << SourceRange(CommonScopeLoc);
4005 } else {
4006 ScopeName = CommonScopeName;
4007 ScopeLoc = CommonScopeLoc;
4008 }
4009 }
4010
Aaron Ballmanb8e20392014-03-31 17:32:39 +00004011 bool StandardAttr = IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName);
Alexis Hunt96d5c762009-11-21 08:43:09 +00004012 bool AttrParsed = false;
Alexis Hunt96d5c762009-11-21 08:43:09 +00004013
Richard Smith10876ef2013-01-17 01:30:42 +00004014 if (StandardAttr &&
4015 !SeenAttrs.insert(std::make_pair(AttrName, AttrLoc)).second)
4016 Diag(AttrLoc, diag::err_cxx11_attribute_repeated)
Aaron Ballmanb8e20392014-03-31 17:32:39 +00004017 << AttrName << SourceRange(SeenAttrs[AttrName]);
Richard Smith10876ef2013-01-17 01:30:42 +00004018
Michael Han23214e52012-10-03 01:56:22 +00004019 // Parse attribute arguments
Aaron Ballman35f94212014-04-14 16:03:22 +00004020 if (Tok.is(tok::l_paren))
Aaron Ballmanb8e20392014-03-31 17:32:39 +00004021 AttrParsed = ParseCXX11AttributeArgs(AttrName, AttrLoc, attrs, endLoc,
4022 ScopeName, ScopeLoc);
Michael Han23214e52012-10-03 01:56:22 +00004023
4024 if (!AttrParsed)
Aaron Ballman606093a2017-10-15 15:01:42 +00004025 attrs.addNew(
4026 AttrName,
4027 SourceRange(ScopeLoc.isValid() ? ScopeLoc : AttrLoc, AttrLoc),
4028 ScopeName, ScopeLoc, nullptr, 0,
4029 getLangOpts().CPlusPlus ? AttributeList::AS_CXX11
4030 : AttributeList::AS_C2x);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004031
Alp Toker97650562014-01-10 11:19:30 +00004032 if (TryConsumeToken(tok::ellipsis))
Michael Han23214e52012-10-03 01:56:22 +00004033 Diag(Tok, diag::err_cxx11_attribute_forbids_ellipsis)
4034 << AttrName->getName();
Alexis Hunt96d5c762009-11-21 08:43:09 +00004035 }
4036
Alp Toker383d2c42014-01-01 03:08:43 +00004037 if (ExpectAndConsume(tok::r_square))
Alexey Bataevee6507d2013-11-18 08:17:37 +00004038 SkipUntil(tok::r_square);
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004039 if (endLoc)
4040 *endLoc = Tok.getLocation();
Alp Toker383d2c42014-01-01 03:08:43 +00004041 if (ExpectAndConsume(tok::r_square))
Alexey Bataevee6507d2013-11-18 08:17:37 +00004042 SkipUntil(tok::r_square);
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004043}
Alexis Hunt96d5c762009-11-21 08:43:09 +00004044
Aaron Ballman606093a2017-10-15 15:01:42 +00004045/// ParseCXX11Attributes - Parse a C++11 or C2x attribute-specifier-seq.
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004046///
4047/// attribute-specifier-seq:
4048/// attribute-specifier-seq[opt] attribute-specifier
Richard Smith3dff2512012-04-10 03:25:07 +00004049void Parser::ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004050 SourceLocation *endLoc) {
Aaron Ballman606093a2017-10-15 15:01:42 +00004051 assert(standardAttributesAllowed());
Richard Smith4cabd042013-02-22 09:15:49 +00004052
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004053 SourceLocation StartLoc = Tok.getLocation(), Loc;
4054 if (!endLoc)
4055 endLoc = &Loc;
4056
Douglas Gregor6f981002011-10-07 20:35:25 +00004057 do {
Richard Smith3dff2512012-04-10 03:25:07 +00004058 ParseCXX11AttributeSpecifier(attrs, endLoc);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004059 } while (isCXX11AttributeSpecifier());
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004060
4061 attrs.Range = SourceRange(StartLoc, *endLoc);
Alexis Hunt96d5c762009-11-21 08:43:09 +00004062}
4063
Richard Smithc2c8bb82013-10-15 01:34:54 +00004064void Parser::DiagnoseAndSkipCXX11Attributes() {
Richard Smithc2c8bb82013-10-15 01:34:54 +00004065 // Start and end location of an attribute or an attribute list.
4066 SourceLocation StartLoc = Tok.getLocation();
Richard Smith955bf012014-06-19 11:42:00 +00004067 SourceLocation EndLoc = SkipCXX11Attributes();
4068
4069 if (EndLoc.isValid()) {
4070 SourceRange Range(StartLoc, EndLoc);
4071 Diag(StartLoc, diag::err_attributes_not_allowed)
4072 << Range;
4073 }
4074}
4075
4076SourceLocation Parser::SkipCXX11Attributes() {
Richard Smithc2c8bb82013-10-15 01:34:54 +00004077 SourceLocation EndLoc;
4078
Richard Smith955bf012014-06-19 11:42:00 +00004079 if (!isCXX11AttributeSpecifier())
4080 return EndLoc;
4081
Richard Smithc2c8bb82013-10-15 01:34:54 +00004082 do {
4083 if (Tok.is(tok::l_square)) {
4084 BalancedDelimiterTracker T(*this, tok::l_square);
4085 T.consumeOpen();
4086 T.skipToEnd();
4087 EndLoc = T.getCloseLocation();
4088 } else {
4089 assert(Tok.is(tok::kw_alignas) && "not an attribute specifier");
4090 ConsumeToken();
4091 BalancedDelimiterTracker T(*this, tok::l_paren);
4092 if (!T.consumeOpen())
4093 T.skipToEnd();
4094 EndLoc = T.getCloseLocation();
4095 }
4096 } while (isCXX11AttributeSpecifier());
4097
Richard Smith955bf012014-06-19 11:42:00 +00004098 return EndLoc;
Richard Smithc2c8bb82013-10-15 01:34:54 +00004099}
4100
Nico Weber05e1dad2016-09-03 03:25:22 +00004101/// Parse uuid() attribute when it appears in a [] Microsoft attribute.
4102void Parser::ParseMicrosoftUuidAttributeArgs(ParsedAttributes &Attrs) {
4103 assert(Tok.is(tok::identifier) && "Not a Microsoft attribute list");
4104 IdentifierInfo *UuidIdent = Tok.getIdentifierInfo();
4105 assert(UuidIdent->getName() == "uuid" && "Not a Microsoft attribute list");
4106
4107 SourceLocation UuidLoc = Tok.getLocation();
4108 ConsumeToken();
4109
4110 // Ignore the left paren location for now.
4111 BalancedDelimiterTracker T(*this, tok::l_paren);
4112 if (T.consumeOpen()) {
4113 Diag(Tok, diag::err_expected) << tok::l_paren;
4114 return;
4115 }
4116
4117 ArgsVector ArgExprs;
4118 if (Tok.is(tok::string_literal)) {
4119 // Easy case: uuid("...") -- quoted string.
4120 ExprResult StringResult = ParseStringLiteralExpression();
4121 if (StringResult.isInvalid())
4122 return;
4123 ArgExprs.push_back(StringResult.get());
4124 } else {
4125 // something like uuid({000000A0-0000-0000-C000-000000000049}) -- no
4126 // quotes in the parens. Just append the spelling of all tokens encountered
4127 // until the closing paren.
4128
4129 SmallString<42> StrBuffer; // 2 "", 36 bytes UUID, 2 optional {}, 1 nul
4130 StrBuffer += "\"";
4131
4132 // Since none of C++'s keywords match [a-f]+, accepting just tok::l_brace,
4133 // tok::r_brace, tok::minus, tok::identifier (think C000) and
4134 // tok::numeric_constant (0000) should be enough. But the spelling of the
4135 // uuid argument is checked later anyways, so there's no harm in accepting
4136 // almost anything here.
4137 // cl is very strict about whitespace in this form and errors out if any
4138 // is present, so check the space flags on the tokens.
4139 SourceLocation StartLoc = Tok.getLocation();
4140 while (Tok.isNot(tok::r_paren)) {
4141 if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
4142 Diag(Tok, diag::err_attribute_uuid_malformed_guid);
4143 SkipUntil(tok::r_paren, StopAtSemi);
4144 return;
4145 }
4146 SmallString<16> SpellingBuffer;
4147 SpellingBuffer.resize(Tok.getLength() + 1);
4148 bool Invalid = false;
4149 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
4150 if (Invalid) {
4151 SkipUntil(tok::r_paren, StopAtSemi);
4152 return;
4153 }
4154 StrBuffer += TokSpelling;
4155 ConsumeAnyToken();
4156 }
4157 StrBuffer += "\"";
4158
4159 if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
4160 Diag(Tok, diag::err_attribute_uuid_malformed_guid);
4161 ConsumeParen();
4162 return;
4163 }
4164
4165 // Pretend the user wrote the appropriate string literal here.
4166 // ActOnStringLiteral() copies the string data into the literal, so it's
4167 // ok that the Token points to StrBuffer.
4168 Token Toks[1];
4169 Toks[0].startToken();
4170 Toks[0].setKind(tok::string_literal);
4171 Toks[0].setLocation(StartLoc);
4172 Toks[0].setLiteralData(StrBuffer.data());
4173 Toks[0].setLength(StrBuffer.size());
4174 StringLiteral *UuidString =
4175 cast<StringLiteral>(Actions.ActOnStringLiteral(Toks, nullptr).get());
4176 ArgExprs.push_back(UuidString);
4177 }
4178
4179 if (!T.consumeClose()) {
Nico Weber05e1dad2016-09-03 03:25:22 +00004180 Attrs.addNew(UuidIdent, SourceRange(UuidLoc, T.getCloseLocation()), nullptr,
4181 SourceLocation(), ArgExprs.data(), ArgExprs.size(),
4182 AttributeList::AS_Microsoft);
4183 }
4184}
4185
David Majnemere4752e752015-07-08 05:55:00 +00004186/// ParseMicrosoftAttributes - Parse Microsoft attributes [Attr]
Francois Pichetc2bc5ac2010-10-11 12:59:39 +00004187///
4188/// [MS] ms-attribute:
4189/// '[' token-seq ']'
4190///
4191/// [MS] ms-attribute-seq:
4192/// ms-attribute[opt]
4193/// ms-attribute ms-attribute-seq
John McCall53fa7142010-12-24 02:08:15 +00004194void Parser::ParseMicrosoftAttributes(ParsedAttributes &attrs,
4195 SourceLocation *endLoc) {
Francois Pichetc2bc5ac2010-10-11 12:59:39 +00004196 assert(Tok.is(tok::l_square) && "Not a Microsoft attribute list");
4197
Saleem Abdulrasool425efcf2015-06-15 20:57:04 +00004198 do {
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004199 // FIXME: If this is actually a C++11 attribute, parse it as one.
Saleem Abdulrasool425efcf2015-06-15 20:57:04 +00004200 BalancedDelimiterTracker T(*this, tok::l_square);
4201 T.consumeOpen();
Nico Weber05e1dad2016-09-03 03:25:22 +00004202
4203 // Skip most ms attributes except for a whitelist.
4204 while (true) {
4205 SkipUntil(tok::r_square, tok::identifier, StopAtSemi | StopBeforeMatch);
4206 if (Tok.isNot(tok::identifier)) // ']', but also eof
4207 break;
4208 if (Tok.getIdentifierInfo()->getName() == "uuid")
4209 ParseMicrosoftUuidAttributeArgs(attrs);
4210 else
4211 ConsumeToken();
4212 }
4213
Saleem Abdulrasool425efcf2015-06-15 20:57:04 +00004214 T.consumeClose();
4215 if (endLoc)
4216 *endLoc = T.getCloseLocation();
4217 } while (Tok.is(tok::l_square));
Francois Pichetc2bc5ac2010-10-11 12:59:39 +00004218}
Francois Pichet8f981d52011-05-25 10:19:49 +00004219
4220void Parser::ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType,
4221 AccessSpecifier& CurAS) {
Douglas Gregor43edb322011-10-24 22:31:10 +00004222 IfExistsCondition Result;
Francois Pichet8f981d52011-05-25 10:19:49 +00004223 if (ParseMicrosoftIfExistsCondition(Result))
4224 return;
4225
Douglas Gregor43edb322011-10-24 22:31:10 +00004226 BalancedDelimiterTracker Braces(*this, tok::l_brace);
4227 if (Braces.consumeOpen()) {
Alp Tokerec543272013-12-24 09:48:30 +00004228 Diag(Tok, diag::err_expected) << tok::l_brace;
Francois Pichet8f981d52011-05-25 10:19:49 +00004229 return;
4230 }
Francois Pichet8f981d52011-05-25 10:19:49 +00004231
Douglas Gregor43edb322011-10-24 22:31:10 +00004232 switch (Result.Behavior) {
4233 case IEB_Parse:
4234 // Parse the declarations below.
4235 break;
4236
4237 case IEB_Dependent:
4238 Diag(Result.KeywordLoc, diag::warn_microsoft_dependent_exists)
4239 << Result.IsIfExists;
4240 // Fall through to skip.
Galina Kistanovad819d5b2017-06-01 21:19:06 +00004241 LLVM_FALLTHROUGH;
Douglas Gregor43edb322011-10-24 22:31:10 +00004242
4243 case IEB_Skip:
4244 Braces.skipToEnd();
Francois Pichet8f981d52011-05-25 10:19:49 +00004245 return;
4246 }
4247
Richard Smith34f30512013-11-23 04:06:09 +00004248 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
Francois Pichet8f981d52011-05-25 10:19:49 +00004249 // __if_exists, __if_not_exists can nest.
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00004250 if (Tok.isOneOf(tok::kw___if_exists, tok::kw___if_not_exists)) {
Francois Pichet8f981d52011-05-25 10:19:49 +00004251 ParseMicrosoftIfExistsClassDeclaration((DeclSpec::TST)TagType, CurAS);
4252 continue;
4253 }
4254
4255 // Check for extraneous top-level semicolon.
4256 if (Tok.is(tok::semi)) {
Richard Smith87f5dc52012-07-23 05:45:25 +00004257 ConsumeExtraSemi(InsideStruct, TagType);
Francois Pichet8f981d52011-05-25 10:19:49 +00004258 continue;
4259 }
4260
4261 AccessSpecifier AS = getAccessSpecifierIfPresent();
4262 if (AS != AS_none) {
4263 // Current token is a C++ access specifier.
4264 CurAS = AS;
4265 SourceLocation ASLoc = Tok.getLocation();
4266 ConsumeToken();
4267 if (Tok.is(tok::colon))
4268 Actions.ActOnAccessSpecifier(AS, ASLoc, Tok.getLocation());
4269 else
Alp Toker35d87032013-12-30 23:29:50 +00004270 Diag(Tok, diag::err_expected) << tok::colon;
Francois Pichet8f981d52011-05-25 10:19:49 +00004271 ConsumeToken();
4272 continue;
4273 }
4274
4275 // Parse all the comma separated declarators.
Craig Topper161e4db2014-05-21 06:02:52 +00004276 ParseCXXClassMemberDeclaration(CurAS, nullptr);
Francois Pichet8f981d52011-05-25 10:19:49 +00004277 }
Douglas Gregor43edb322011-10-24 22:31:10 +00004278
4279 Braces.consumeClose();
Francois Pichet8f981d52011-05-25 10:19:49 +00004280}