blob: d31d1142374e62168a8d8026dbfdbd5ca02055a5 [file] [log] [blame]
Hans Wennborgdcfba332015-10-06 23:40:43 +00001//===--- ParseDeclCXX.cpp - C++ Declaration Parsing -------------*- C++ -*-===//
Chris Lattnera5235172007-08-25 06:57:03 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnera5235172007-08-25 06:57:03 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the C++ Declaration portions of the Parser interfaces.
11//
12//===----------------------------------------------------------------------===//
13
Douglas Gregor423984d2008-04-14 00:13:42 +000014#include "clang/Parse/Parser.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "RAIIObjectsForParser.h"
Erik Verbruggen888d52a2014-01-15 09:15:43 +000016#include "clang/AST/ASTContext.h"
Chandler Carruth757fcd62014-03-04 10:05:20 +000017#include "clang/AST/DeclTemplate.h"
Aaron Ballmanb8e20392014-03-31 17:32:39 +000018#include "clang/Basic/Attributes.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000019#include "clang/Basic/CharInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/Basic/OperatorKinds.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000021#include "clang/Basic/TargetInfo.h"
Chris Lattner60f36222009-01-29 05:15:15 +000022#include "clang/Parse/ParseDiagnostic.h"
John McCall8b0666c2010-08-20 18:27:03 +000023#include "clang/Sema/DeclSpec.h"
John McCall8b0666c2010-08-20 18:27:03 +000024#include "clang/Sema/ParsedTemplate.h"
John McCallfaf5fb42010-08-26 23:41:50 +000025#include "clang/Sema/PrettyDeclStackTrace.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "clang/Sema/Scope.h"
John McCalldb632ac2012-09-25 07:32:39 +000027#include "clang/Sema/SemaDiagnostic.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000028#include "llvm/ADT/SmallString.h"
Hans Wennborgdcfba332015-10-06 23:40:43 +000029
Chris Lattnera5235172007-08-25 06:57:03 +000030using namespace clang;
31
32/// ParseNamespace - We know that the current token is a namespace keyword. This
Sebastian Redl67667942010-08-27 23:12:46 +000033/// may either be a top level namespace or a block-level namespace alias. If
34/// there was an inline keyword, it has already been parsed.
Chris Lattnera5235172007-08-25 06:57:03 +000035///
36/// namespace-definition: [C++ 7.3: basic.namespace]
37/// named-namespace-definition
38/// unnamed-namespace-definition
39///
40/// unnamed-namespace-definition:
Sebastian Redl67667942010-08-27 23:12:46 +000041/// 'inline'[opt] 'namespace' attributes[opt] '{' namespace-body '}'
Chris Lattnera5235172007-08-25 06:57:03 +000042///
43/// named-namespace-definition:
44/// original-namespace-definition
45/// extension-namespace-definition
46///
47/// original-namespace-definition:
Sebastian Redl67667942010-08-27 23:12:46 +000048/// 'inline'[opt] 'namespace' identifier attributes[opt]
49/// '{' namespace-body '}'
Chris Lattnera5235172007-08-25 06:57:03 +000050///
51/// extension-namespace-definition:
Sebastian Redl67667942010-08-27 23:12:46 +000052/// 'inline'[opt] 'namespace' original-namespace-name
53/// '{' namespace-body '}'
Mike Stump11289f42009-09-09 15:08:12 +000054///
Chris Lattnera5235172007-08-25 06:57:03 +000055/// namespace-alias-definition: [C++ 7.3.2: namespace.alias]
56/// 'namespace' identifier '=' qualified-namespace-specifier ';'
57///
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +000058Parser::DeclGroupPtrTy Parser::ParseNamespace(unsigned Context,
59 SourceLocation &DeclEnd,
60 SourceLocation InlineLoc) {
Chris Lattner76c72282007-10-09 17:33:22 +000061 assert(Tok.is(tok::kw_namespace) && "Not a namespace!");
Chris Lattnera5235172007-08-25 06:57:03 +000062 SourceLocation NamespaceLoc = ConsumeToken(); // eat the 'namespace'.
Fariborz Jahanian4bf82622011-08-22 17:59:19 +000063 ObjCDeclContextSwitch ObjCDC(*this);
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000064
Douglas Gregor7e90c6d2009-09-18 19:03:04 +000065 if (Tok.is(tok::code_completion)) {
Douglas Gregor0be31a22010-07-02 17:43:08 +000066 Actions.CodeCompleteNamespaceDecl(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +000067 cutOffParsing();
David Blaikie0403cb12016-01-15 23:43:25 +000068 return nullptr;
Douglas Gregor7e90c6d2009-09-18 19:03:04 +000069 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000070
Chris Lattnera5235172007-08-25 06:57:03 +000071 SourceLocation IdentLoc;
Craig Topper161e4db2014-05-21 06:02:52 +000072 IdentifierInfo *Ident = nullptr;
Richard Trieu61384cb2011-05-26 20:11:09 +000073 std::vector<SourceLocation> ExtraIdentLoc;
74 std::vector<IdentifierInfo*> ExtraIdent;
75 std::vector<SourceLocation> ExtraNamespaceLoc;
Douglas Gregor6b6bba42009-06-17 19:49:00 +000076
Aaron Ballman730476b2014-11-08 15:33:35 +000077 ParsedAttributesWithRange attrs(AttrFactory);
78 SourceLocation attrLoc;
79 if (getLangOpts().CPlusPlus11 && isCXX11AttributeSpecifier()) {
80 if (!getLangOpts().CPlusPlus1z)
Aaron Ballmanc0ae7df2014-11-08 17:07:15 +000081 Diag(Tok.getLocation(), diag::warn_cxx14_compat_attribute)
82 << 0 /*namespace*/;
Aaron Ballman730476b2014-11-08 15:33:35 +000083 attrLoc = Tok.getLocation();
84 ParseCXX11Attributes(attrs);
85 }
Mike Stump11289f42009-09-09 15:08:12 +000086
Chris Lattner76c72282007-10-09 17:33:22 +000087 if (Tok.is(tok::identifier)) {
Chris Lattnera5235172007-08-25 06:57:03 +000088 Ident = Tok.getIdentifierInfo();
89 IdentLoc = ConsumeToken(); // eat the identifier.
Richard Trieu61384cb2011-05-26 20:11:09 +000090 while (Tok.is(tok::coloncolon) && NextToken().is(tok::identifier)) {
91 ExtraNamespaceLoc.push_back(ConsumeToken());
92 ExtraIdent.push_back(Tok.getIdentifierInfo());
93 ExtraIdentLoc.push_back(ConsumeToken());
94 }
Chris Lattnera5235172007-08-25 06:57:03 +000095 }
Mike Stump11289f42009-09-09 15:08:12 +000096
Aaron Ballmanc0ae7df2014-11-08 17:07:15 +000097 // A nested namespace definition cannot have attributes.
98 if (!ExtraNamespaceLoc.empty() && attrLoc.isValid())
99 Diag(attrLoc, diag::err_unexpected_nested_namespace_attribute);
100
Chris Lattnera5235172007-08-25 06:57:03 +0000101 // Read label attributes, if present.
Douglas Gregor6b6bba42009-06-17 19:49:00 +0000102 if (Tok.is(tok::kw___attribute)) {
Aaron Ballman730476b2014-11-08 15:33:35 +0000103 attrLoc = Tok.getLocation();
John McCall53fa7142010-12-24 02:08:15 +0000104 ParseGNUAttributes(attrs);
Douglas Gregor6b6bba42009-06-17 19:49:00 +0000105 }
Mike Stump11289f42009-09-09 15:08:12 +0000106
Douglas Gregor6b6bba42009-06-17 19:49:00 +0000107 if (Tok.is(tok::equal)) {
Craig Topper161e4db2014-05-21 06:02:52 +0000108 if (!Ident) {
Alp Tokerec543272013-12-24 09:48:30 +0000109 Diag(Tok, diag::err_expected) << tok::identifier;
Nico Weber729f1e22012-10-27 23:44:27 +0000110 // Skip to end of the definition and eat the ';'.
111 SkipUntil(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +0000112 return nullptr;
Nico Weber729f1e22012-10-27 23:44:27 +0000113 }
Aaron Ballman730476b2014-11-08 15:33:35 +0000114 if (attrLoc.isValid())
115 Diag(attrLoc, diag::err_unexpected_namespace_attributes_alias);
Sebastian Redl67667942010-08-27 23:12:46 +0000116 if (InlineLoc.isValid())
117 Diag(InlineLoc, diag::err_inline_namespace_alias)
118 << FixItHint::CreateRemoval(InlineLoc);
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +0000119 Decl *NSAlias = ParseNamespaceAlias(NamespaceLoc, IdentLoc, Ident, DeclEnd);
120 return Actions.ConvertDeclToDeclGroup(NSAlias);
121}
Mike Stump11289f42009-09-09 15:08:12 +0000122
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000123 BalancedDelimiterTracker T(*this, tok::l_brace);
124 if (T.consumeOpen()) {
Alp Tokerec543272013-12-24 09:48:30 +0000125 if (Ident)
126 Diag(Tok, diag::err_expected) << tok::l_brace;
127 else
128 Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace;
David Blaikie0403cb12016-01-15 23:43:25 +0000129 return nullptr;
Chris Lattnera5235172007-08-25 06:57:03 +0000130 }
Mike Stump11289f42009-09-09 15:08:12 +0000131
Douglas Gregor0be31a22010-07-02 17:43:08 +0000132 if (getCurScope()->isClassScope() || getCurScope()->isTemplateParamScope() ||
133 getCurScope()->isInObjcMethodScope() || getCurScope()->getBlockParent() ||
134 getCurScope()->getFnParent()) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000135 Diag(T.getOpenLocation(), diag::err_namespace_nonnamespace_scope);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000136 SkipUntil(tok::r_brace);
David Blaikie0403cb12016-01-15 23:43:25 +0000137 return nullptr;
Douglas Gregor05cfc292010-05-14 05:08:22 +0000138 }
139
Richard Smith13307f52014-11-08 05:37:34 +0000140 if (ExtraIdent.empty()) {
141 // Normal namespace definition, not a nested-namespace-definition.
142 } else if (InlineLoc.isValid()) {
143 Diag(InlineLoc, diag::err_inline_nested_namespace_definition);
144 } else if (getLangOpts().CPlusPlus1z) {
145 Diag(ExtraNamespaceLoc[0],
146 diag::warn_cxx14_compat_nested_namespace_definition);
147 } else {
Richard Trieu61384cb2011-05-26 20:11:09 +0000148 TentativeParsingAction TPA(*this);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000149 SkipUntil(tok::r_brace, StopBeforeMatch);
Richard Trieu61384cb2011-05-26 20:11:09 +0000150 Token rBraceToken = Tok;
151 TPA.Revert();
152
153 if (!rBraceToken.is(tok::r_brace)) {
Richard Smith13307f52014-11-08 05:37:34 +0000154 Diag(ExtraNamespaceLoc[0], diag::ext_nested_namespace_definition)
Richard Trieu61384cb2011-05-26 20:11:09 +0000155 << SourceRange(ExtraNamespaceLoc.front(), ExtraIdentLoc.back());
156 } else {
Benjamin Kramerf546f412011-05-26 21:32:30 +0000157 std::string NamespaceFix;
Richard Trieu61384cb2011-05-26 20:11:09 +0000158 for (std::vector<IdentifierInfo*>::iterator I = ExtraIdent.begin(),
159 E = ExtraIdent.end(); I != E; ++I) {
160 NamespaceFix += " { namespace ";
161 NamespaceFix += (*I)->getName();
162 }
Benjamin Kramerf546f412011-05-26 21:32:30 +0000163
Richard Trieu61384cb2011-05-26 20:11:09 +0000164 std::string RBraces;
Benjamin Kramerf546f412011-05-26 21:32:30 +0000165 for (unsigned i = 0, e = ExtraIdent.size(); i != e; ++i)
Richard Trieu61384cb2011-05-26 20:11:09 +0000166 RBraces += "} ";
Benjamin Kramerf546f412011-05-26 21:32:30 +0000167
Richard Smith13307f52014-11-08 05:37:34 +0000168 Diag(ExtraNamespaceLoc[0], diag::ext_nested_namespace_definition)
Richard Trieu61384cb2011-05-26 20:11:09 +0000169 << FixItHint::CreateReplacement(SourceRange(ExtraNamespaceLoc.front(),
170 ExtraIdentLoc.back()),
171 NamespaceFix)
172 << FixItHint::CreateInsertion(rBraceToken.getLocation(), RBraces);
173 }
174 }
175
Sebastian Redl5a5f2c72010-08-31 00:36:45 +0000176 // If we're still good, complain about inline namespaces in non-C++0x now.
Richard Smith5d164bc2011-10-15 05:09:34 +0000177 if (InlineLoc.isValid())
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000178 Diag(InlineLoc, getLangOpts().CPlusPlus11 ?
Richard Smith5d164bc2011-10-15 05:09:34 +0000179 diag::warn_cxx98_compat_inline_namespace : diag::ext_inline_namespace);
Sebastian Redl5a5f2c72010-08-31 00:36:45 +0000180
Chris Lattner4de55aa2009-03-29 14:02:43 +0000181 // Enter a scope for the namespace.
182 ParseScope NamespaceScope(this, Scope::DeclScope);
183
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +0000184 UsingDirectiveDecl *ImplicitUsingDirectiveDecl = nullptr;
John McCall48871652010-08-21 09:40:31 +0000185 Decl *NamespcDecl =
Abramo Bagnarab5545be2011-03-08 12:38:20 +0000186 Actions.ActOnStartNamespaceDef(getCurScope(), InlineLoc, NamespaceLoc,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000187 IdentLoc, Ident, T.getOpenLocation(),
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +0000188 attrs.getList(), ImplicitUsingDirectiveDecl);
Chris Lattner4de55aa2009-03-29 14:02:43 +0000189
John McCallfaf5fb42010-08-26 23:41:50 +0000190 PrettyDeclStackTraceEntry CrashInfo(Actions, NamespcDecl, NamespaceLoc,
191 "parsing namespace");
Mike Stump11289f42009-09-09 15:08:12 +0000192
Richard Trieu61384cb2011-05-26 20:11:09 +0000193 // Parse the contents of the namespace. This includes parsing recovery on
194 // any improperly nested namespaces.
195 ParseInnerNamespace(ExtraIdentLoc, ExtraIdent, ExtraNamespaceLoc, 0,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000196 InlineLoc, attrs, T);
Mike Stump11289f42009-09-09 15:08:12 +0000197
Chris Lattner4de55aa2009-03-29 14:02:43 +0000198 // Leave the namespace scope.
199 NamespaceScope.Exit();
200
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000201 DeclEnd = T.getCloseLocation();
202 Actions.ActOnFinishNamespaceDef(NamespcDecl, DeclEnd);
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +0000203
204 return Actions.ConvertDeclToDeclGroup(NamespcDecl,
205 ImplicitUsingDirectiveDecl);
Chris Lattnera5235172007-08-25 06:57:03 +0000206}
Chris Lattner38376f12008-01-12 07:05:38 +0000207
Richard Trieu61384cb2011-05-26 20:11:09 +0000208/// ParseInnerNamespace - Parse the contents of a namespace.
Richard Smith13307f52014-11-08 05:37:34 +0000209void Parser::ParseInnerNamespace(std::vector<SourceLocation> &IdentLoc,
210 std::vector<IdentifierInfo *> &Ident,
211 std::vector<SourceLocation> &NamespaceLoc,
212 unsigned int index, SourceLocation &InlineLoc,
213 ParsedAttributes &attrs,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000214 BalancedDelimiterTracker &Tracker) {
Richard Trieu61384cb2011-05-26 20:11:09 +0000215 if (index == Ident.size()) {
Richard Smith752ada82015-11-17 23:32:01 +0000216 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
217 Tok.isNot(tok::eof)) {
Richard Trieu61384cb2011-05-26 20:11:09 +0000218 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +0000219 MaybeParseCXX11Attributes(attrs);
Richard Trieu61384cb2011-05-26 20:11:09 +0000220 ParseExternalDeclaration(attrs);
221 }
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000222
223 // The caller is what called check -- we are simply calling
224 // the close for it.
225 Tracker.consumeClose();
Richard Trieu61384cb2011-05-26 20:11:09 +0000226
227 return;
228 }
229
Richard Smith13307f52014-11-08 05:37:34 +0000230 // Handle a nested namespace definition.
231 // FIXME: Preserve the source information through to the AST rather than
232 // desugaring it here.
Richard Trieu61384cb2011-05-26 20:11:09 +0000233 ParseScope NamespaceScope(this, Scope::DeclScope);
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +0000234 UsingDirectiveDecl *ImplicitUsingDirectiveDecl = nullptr;
Richard Trieu61384cb2011-05-26 20:11:09 +0000235 Decl *NamespcDecl =
236 Actions.ActOnStartNamespaceDef(getCurScope(), SourceLocation(),
237 NamespaceLoc[index], IdentLoc[index],
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000238 Ident[index], Tracker.getOpenLocation(),
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +0000239 attrs.getList(), ImplicitUsingDirectiveDecl);
240 assert(!ImplicitUsingDirectiveDecl &&
241 "nested namespace definition cannot define anonymous namespace");
Richard Trieu61384cb2011-05-26 20:11:09 +0000242
243 ParseInnerNamespace(IdentLoc, Ident, NamespaceLoc, ++index, InlineLoc,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000244 attrs, Tracker);
Richard Trieu61384cb2011-05-26 20:11:09 +0000245
246 NamespaceScope.Exit();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000247 Actions.ActOnFinishNamespaceDef(NamespcDecl, Tracker.getCloseLocation());
Richard Trieu61384cb2011-05-26 20:11:09 +0000248}
249
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000250/// ParseNamespaceAlias - Parse the part after the '=' in a namespace
251/// alias definition.
252///
John McCall48871652010-08-21 09:40:31 +0000253Decl *Parser::ParseNamespaceAlias(SourceLocation NamespaceLoc,
John McCall084e83d2011-03-24 11:26:52 +0000254 SourceLocation AliasLoc,
255 IdentifierInfo *Alias,
256 SourceLocation &DeclEnd) {
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000257 assert(Tok.is(tok::equal) && "Not equal token");
Mike Stump11289f42009-09-09 15:08:12 +0000258
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000259 ConsumeToken(); // eat the '='.
Mike Stump11289f42009-09-09 15:08:12 +0000260
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000261 if (Tok.is(tok::code_completion)) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000262 Actions.CodeCompleteNamespaceAliasDecl(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000263 cutOffParsing();
Craig Topper161e4db2014-05-21 06:02:52 +0000264 return nullptr;
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000265 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000266
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000267 CXXScopeSpec SS;
268 // Parse (optional) nested-name-specifier.
David Blaikieefdccaa2016-01-15 23:43:34 +0000269 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false);
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000270
271 if (SS.isInvalid() || Tok.isNot(tok::identifier)) {
272 Diag(Tok, diag::err_expected_namespace_name);
273 // Skip to end of the definition and eat the ';'.
274 SkipUntil(tok::semi);
Craig Topper161e4db2014-05-21 06:02:52 +0000275 return nullptr;
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000276 }
277
278 // Parse identifier.
Anders Carlsson47952ae2009-03-28 22:53:22 +0000279 IdentifierInfo *Ident = Tok.getIdentifierInfo();
280 SourceLocation IdentLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000281
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000282 // Eat the ';'.
Chris Lattner49836b42009-04-02 04:16:50 +0000283 DeclEnd = Tok.getLocation();
Alp Toker383d2c42014-01-01 03:08:43 +0000284 if (ExpectAndConsume(tok::semi, diag::err_expected_semi_after_namespace_name))
285 SkipUntil(tok::semi);
Mike Stump11289f42009-09-09 15:08:12 +0000286
Craig Topperff354282015-11-14 18:16:00 +0000287 return Actions.ActOnNamespaceAliasDef(getCurScope(), NamespaceLoc, AliasLoc,
288 Alias, SS, IdentLoc, Ident);
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000289}
290
Chris Lattner38376f12008-01-12 07:05:38 +0000291/// ParseLinkage - We know that the current token is a string_literal
292/// and just before that, that extern was seen.
293///
294/// linkage-specification: [C++ 7.5p2: dcl.link]
295/// 'extern' string-literal '{' declaration-seq[opt] '}'
296/// 'extern' string-literal declaration
297///
Chris Lattner8ea64422010-11-09 20:15:55 +0000298Decl *Parser::ParseLinkage(ParsingDeclSpec &DS, unsigned Context) {
Richard Smith4ee696d2014-02-17 23:25:27 +0000299 assert(isTokenStringLiteral() && "Not a string literal!");
300 ExprResult Lang = ParseStringLiteralExpression(false);
Chris Lattner38376f12008-01-12 07:05:38 +0000301
Douglas Gregor07665a62009-01-05 19:45:36 +0000302 ParseScope LinkageScope(this, Scope::DeclScope);
Richard Smith4ee696d2014-02-17 23:25:27 +0000303 Decl *LinkageSpec =
304 Lang.isInvalid()
Craig Topper161e4db2014-05-21 06:02:52 +0000305 ? nullptr
Richard Smith4ee696d2014-02-17 23:25:27 +0000306 : Actions.ActOnStartLinkageSpecification(
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000307 getCurScope(), DS.getSourceRange().getBegin(), Lang.get(),
Richard Smith4ee696d2014-02-17 23:25:27 +0000308 Tok.is(tok::l_brace) ? Tok.getLocation() : SourceLocation());
Douglas Gregor07665a62009-01-05 19:45:36 +0000309
John McCall084e83d2011-03-24 11:26:52 +0000310 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +0000311 MaybeParseCXX11Attributes(attrs);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000312
Douglas Gregor07665a62009-01-05 19:45:36 +0000313 if (Tok.isNot(tok::l_brace)) {
Abramo Bagnara4d423992011-05-01 16:25:54 +0000314 // Reset the source range in DS, as the leading "extern"
315 // does not really belong to the inner declaration ...
316 DS.SetRangeStart(SourceLocation());
317 DS.SetRangeEnd(SourceLocation());
318 // ... but anyway remember that such an "extern" was seen.
Abramo Bagnaraed5b6892010-07-30 16:47:02 +0000319 DS.setExternInLinkageSpec(true);
John McCall53fa7142010-12-24 02:08:15 +0000320 ParseExternalDeclaration(attrs, &DS);
Richard Smith4ee696d2014-02-17 23:25:27 +0000321 return LinkageSpec ? Actions.ActOnFinishLinkageSpecification(
322 getCurScope(), LinkageSpec, SourceLocation())
Craig Topper161e4db2014-05-21 06:02:52 +0000323 : nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000324 }
Douglas Gregor29ff7d02008-12-16 22:23:02 +0000325
Douglas Gregorb65a9132010-02-07 08:38:28 +0000326 DS.abort();
327
John McCall53fa7142010-12-24 02:08:15 +0000328 ProhibitAttributes(attrs);
Alexis Hunt96d5c762009-11-21 08:43:09 +0000329
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000330 BalancedDelimiterTracker T(*this, tok::l_brace);
331 T.consumeOpen();
Richard Smith77944862014-03-02 05:58:18 +0000332
333 unsigned NestedModules = 0;
334 while (true) {
335 switch (Tok.getKind()) {
336 case tok::annot_module_begin:
337 ++NestedModules;
338 ParseTopLevelDecl();
339 continue;
340
341 case tok::annot_module_end:
342 if (!NestedModules)
343 break;
344 --NestedModules;
345 ParseTopLevelDecl();
346 continue;
347
348 case tok::annot_module_include:
349 ParseTopLevelDecl();
350 continue;
351
352 case tok::eof:
353 break;
354
355 case tok::r_brace:
356 if (!NestedModules)
357 break;
358 // Fall through.
359 default:
360 ParsedAttributesWithRange attrs(AttrFactory);
361 MaybeParseCXX11Attributes(attrs);
Richard Smith77944862014-03-02 05:58:18 +0000362 ParseExternalDeclaration(attrs);
363 continue;
364 }
365
366 break;
Chris Lattner38376f12008-01-12 07:05:38 +0000367 }
368
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000369 T.consumeClose();
Richard Smith4ee696d2014-02-17 23:25:27 +0000370 return LinkageSpec ? Actions.ActOnFinishLinkageSpecification(
371 getCurScope(), LinkageSpec, T.getCloseLocation())
Craig Topper161e4db2014-05-21 06:02:52 +0000372 : nullptr;
Chris Lattner38376f12008-01-12 07:05:38 +0000373}
Douglas Gregor556877c2008-04-13 21:30:24 +0000374
Richard Smith8df390f2016-09-08 23:14:54 +0000375/// Parse a C++ Modules TS export-declaration.
376///
377/// export-declaration:
378/// 'export' declaration
379/// 'export' '{' declaration-seq[opt] '}'
380///
381Decl *Parser::ParseExportDeclaration() {
382 assert(Tok.is(tok::kw_export));
383 SourceLocation ExportLoc = ConsumeToken();
384
385 ParseScope ExportScope(this, Scope::DeclScope);
386 Decl *ExportDecl = Actions.ActOnStartExportDecl(
387 getCurScope(), ExportLoc,
388 Tok.is(tok::l_brace) ? Tok.getLocation() : SourceLocation());
389
390 if (Tok.isNot(tok::l_brace)) {
391 // FIXME: Factor out a ParseExternalDeclarationWithAttrs.
392 ParsedAttributesWithRange Attrs(AttrFactory);
393 MaybeParseCXX11Attributes(Attrs);
394 MaybeParseMicrosoftAttributes(Attrs);
395 ParseExternalDeclaration(Attrs);
396 return Actions.ActOnFinishExportDecl(getCurScope(), ExportDecl,
397 SourceLocation());
398 }
399
400 BalancedDelimiterTracker T(*this, tok::l_brace);
401 T.consumeOpen();
402
403 // The Modules TS draft says "An export-declaration shall declare at least one
404 // entity", but the intent is that it shall contain at least one declaration.
405 if (Tok.is(tok::r_brace))
406 Diag(ExportLoc, diag::err_export_empty)
407 << SourceRange(ExportLoc, Tok.getLocation());
408
409 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
410 Tok.isNot(tok::eof)) {
411 ParsedAttributesWithRange Attrs(AttrFactory);
412 MaybeParseCXX11Attributes(Attrs);
413 MaybeParseMicrosoftAttributes(Attrs);
414 ParseExternalDeclaration(Attrs);
415 }
416
417 T.consumeClose();
418 return Actions.ActOnFinishExportDecl(getCurScope(), ExportDecl,
419 T.getCloseLocation());
420}
421
Douglas Gregord7c4d982008-12-30 03:27:21 +0000422/// ParseUsingDirectiveOrDeclaration - Parse C++ using using-declaration or
423/// using-directive. Assumes that current token is 'using'.
Richard Smith6f1daa42016-12-16 00:58:48 +0000424Parser::DeclGroupPtrTy
425Parser::ParseUsingDirectiveOrDeclaration(unsigned Context,
John McCall9b72f892010-11-10 02:40:36 +0000426 const ParsedTemplateInfo &TemplateInfo,
Richard Smith6f1daa42016-12-16 00:58:48 +0000427 SourceLocation &DeclEnd,
428 ParsedAttributesWithRange &attrs) {
Douglas Gregord7c4d982008-12-30 03:27:21 +0000429 assert(Tok.is(tok::kw_using) && "Not using token");
Fariborz Jahanian4bf82622011-08-22 17:59:19 +0000430 ObjCDeclContextSwitch ObjCDC(*this);
431
Douglas Gregord7c4d982008-12-30 03:27:21 +0000432 // Eat 'using'.
433 SourceLocation UsingLoc = ConsumeToken();
434
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000435 if (Tok.is(tok::code_completion)) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000436 Actions.CodeCompleteUsing(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000437 cutOffParsing();
Craig Topper161e4db2014-05-21 06:02:52 +0000438 return nullptr;
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000439 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000440
John McCall9b72f892010-11-10 02:40:36 +0000441 // 'using namespace' means this is a using-directive.
442 if (Tok.is(tok::kw_namespace)) {
443 // Template parameters are always an error here.
444 if (TemplateInfo.Kind) {
445 SourceRange R = TemplateInfo.getSourceRange();
Craig Topper54a6a682015-11-14 18:16:08 +0000446 Diag(UsingLoc, diag::err_templated_using_directive_declaration)
447 << 0 /* directive */ << R << FixItHint::CreateRemoval(R);
John McCall9b72f892010-11-10 02:40:36 +0000448 }
Alexis Hunt96d5c762009-11-21 08:43:09 +0000449
Richard Smith6f1daa42016-12-16 00:58:48 +0000450 Decl *UsingDir = ParseUsingDirective(Context, UsingLoc, DeclEnd, attrs);
451 return Actions.ConvertDeclToDeclGroup(UsingDir);
John McCall9b72f892010-11-10 02:40:36 +0000452 }
453
Richard Smithdda56e42011-04-15 14:24:37 +0000454 // Otherwise, it must be a using-declaration or an alias-declaration.
John McCall9b72f892010-11-10 02:40:36 +0000455
456 // Using declarations can't have attributes.
John McCall53fa7142010-12-24 02:08:15 +0000457 ProhibitAttributes(attrs);
Chris Lattner9b01ca12009-01-06 06:55:51 +0000458
Fariborz Jahanian4bf82622011-08-22 17:59:19 +0000459 return ParseUsingDeclaration(Context, TemplateInfo, UsingLoc, DeclEnd,
Richard Smith6f1daa42016-12-16 00:58:48 +0000460 AS_none);
Douglas Gregord7c4d982008-12-30 03:27:21 +0000461}
462
463/// ParseUsingDirective - Parse C++ using-directive, assumes
464/// that current token is 'namespace' and 'using' was already parsed.
465///
466/// using-directive: [C++ 7.3.p4: namespace.udir]
467/// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
468/// namespace-name ;
469/// [GNU] using-directive:
470/// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
471/// namespace-name attributes[opt] ;
472///
John McCall48871652010-08-21 09:40:31 +0000473Decl *Parser::ParseUsingDirective(unsigned Context,
John McCall9b72f892010-11-10 02:40:36 +0000474 SourceLocation UsingLoc,
475 SourceLocation &DeclEnd,
John McCall53fa7142010-12-24 02:08:15 +0000476 ParsedAttributes &attrs) {
Douglas Gregord7c4d982008-12-30 03:27:21 +0000477 assert(Tok.is(tok::kw_namespace) && "Not 'namespace' token");
478
479 // Eat 'namespace'.
480 SourceLocation NamespcLoc = ConsumeToken();
481
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000482 if (Tok.is(tok::code_completion)) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000483 Actions.CodeCompleteUsingDirective(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000484 cutOffParsing();
Craig Topper161e4db2014-05-21 06:02:52 +0000485 return nullptr;
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000486 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000487
Douglas Gregord7c4d982008-12-30 03:27:21 +0000488 CXXScopeSpec SS;
489 // Parse (optional) nested-name-specifier.
David Blaikieefdccaa2016-01-15 23:43:34 +0000490 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false);
Douglas Gregord7c4d982008-12-30 03:27:21 +0000491
Craig Topper161e4db2014-05-21 06:02:52 +0000492 IdentifierInfo *NamespcName = nullptr;
Douglas Gregord7c4d982008-12-30 03:27:21 +0000493 SourceLocation IdentLoc = SourceLocation();
494
495 // Parse namespace-name.
Chris Lattnerce1da2c2009-01-06 07:27:21 +0000496 if (SS.isInvalid() || Tok.isNot(tok::identifier)) {
Douglas Gregord7c4d982008-12-30 03:27:21 +0000497 Diag(Tok, diag::err_expected_namespace_name);
498 // If there was invalid namespace name, skip to end of decl, and eat ';'.
499 SkipUntil(tok::semi);
500 // FIXME: Are there cases, when we would like to call ActOnUsingDirective?
Craig Topper161e4db2014-05-21 06:02:52 +0000501 return nullptr;
Douglas Gregord7c4d982008-12-30 03:27:21 +0000502 }
Mike Stump11289f42009-09-09 15:08:12 +0000503
Chris Lattnerce1da2c2009-01-06 07:27:21 +0000504 // Parse identifier.
505 NamespcName = Tok.getIdentifierInfo();
506 IdentLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000507
Chris Lattnerce1da2c2009-01-06 07:27:21 +0000508 // Parse (optional) attributes (most likely GNU strong-using extension).
Alexis Hunt96d5c762009-11-21 08:43:09 +0000509 bool GNUAttr = false;
510 if (Tok.is(tok::kw___attribute)) {
511 GNUAttr = true;
John McCall53fa7142010-12-24 02:08:15 +0000512 ParseGNUAttributes(attrs);
Alexis Hunt96d5c762009-11-21 08:43:09 +0000513 }
Mike Stump11289f42009-09-09 15:08:12 +0000514
Chris Lattnerce1da2c2009-01-06 07:27:21 +0000515 // Eat ';'.
Chris Lattner49836b42009-04-02 04:16:50 +0000516 DeclEnd = Tok.getLocation();
Alp Toker383d2c42014-01-01 03:08:43 +0000517 if (ExpectAndConsume(tok::semi,
518 GNUAttr ? diag::err_expected_semi_after_attribute_list
519 : diag::err_expected_semi_after_namespace_name))
520 SkipUntil(tok::semi);
Douglas Gregord7c4d982008-12-30 03:27:21 +0000521
Douglas Gregor0be31a22010-07-02 17:43:08 +0000522 return Actions.ActOnUsingDirective(getCurScope(), UsingLoc, NamespcLoc, SS,
John McCall53fa7142010-12-24 02:08:15 +0000523 IdentLoc, NamespcName, attrs.getList());
Douglas Gregord7c4d982008-12-30 03:27:21 +0000524}
525
Richard Smith6f1daa42016-12-16 00:58:48 +0000526/// Parse a using-declarator (or the identifier in a C++11 alias-declaration).
Douglas Gregord7c4d982008-12-30 03:27:21 +0000527///
Richard Smith6f1daa42016-12-16 00:58:48 +0000528/// using-declarator:
529/// 'typename'[opt] nested-name-specifier unqualified-id
Douglas Gregord7c4d982008-12-30 03:27:21 +0000530///
Richard Smith6f1daa42016-12-16 00:58:48 +0000531bool Parser::ParseUsingDeclarator(unsigned Context, UsingDeclarator &D) {
532 D.clear();
Douglas Gregorfec52632009-06-20 00:51:54 +0000533
534 // Ignore optional 'typename'.
Douglas Gregor220f4272009-11-04 16:30:06 +0000535 // FIXME: This is wrong; we should parse this as a typename-specifier.
Richard Smith6f1daa42016-12-16 00:58:48 +0000536 TryConsumeToken(tok::kw_typename, D.TypenameLoc);
Douglas Gregorfec52632009-06-20 00:51:54 +0000537
Nikola Smiljanic67860242014-09-26 00:28:20 +0000538 if (Tok.is(tok::kw___super)) {
539 Diag(Tok.getLocation(), diag::err_super_in_using_declaration);
Richard Smith6f1daa42016-12-16 00:58:48 +0000540 return true;
Nikola Smiljanic67860242014-09-26 00:28:20 +0000541 }
542
Douglas Gregorfec52632009-06-20 00:51:54 +0000543 // Parse nested-name-specifier.
Craig Topper161e4db2014-05-21 06:02:52 +0000544 IdentifierInfo *LastII = nullptr;
Richard Smith6f1daa42016-12-16 00:58:48 +0000545 ParseOptionalCXXScopeSpecifier(D.SS, nullptr, /*EnteringContext=*/false,
Craig Topper161e4db2014-05-21 06:02:52 +0000546 /*MayBePseudoDtor=*/nullptr,
547 /*IsTypename=*/false,
Richard Smith7447af42013-03-26 01:15:19 +0000548 /*LastII=*/&LastII);
Richard Smith6f1daa42016-12-16 00:58:48 +0000549 if (D.SS.isInvalid())
550 return true;
Richard Smith7447af42013-03-26 01:15:19 +0000551
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000552 // Parse the unqualified-id. We allow parsing of both constructor and
Douglas Gregor220f4272009-11-04 16:30:06 +0000553 // destructor names and allow the action module to diagnose any semantic
554 // errors.
Richard Smith7447af42013-03-26 01:15:19 +0000555 //
556 // C++11 [class.qual]p2:
557 // [...] in a using-declaration that is a member-declaration, if the name
558 // specified after the nested-name-specifier is the same as the identifier
559 // or the simple-template-id's template-name in the last component of the
560 // nested-name-specifier, the name is [...] considered to name the
561 // constructor.
562 if (getLangOpts().CPlusPlus11 && Context == Declarator::MemberContext &&
563 Tok.is(tok::identifier) && NextToken().is(tok::semi) &&
Richard Smith6f1daa42016-12-16 00:58:48 +0000564 D.SS.isNotEmpty() && LastII == Tok.getIdentifierInfo() &&
565 !D.SS.getScopeRep()->getAsNamespace() &&
566 !D.SS.getScopeRep()->getAsNamespaceAlias()) {
Richard Smith7447af42013-03-26 01:15:19 +0000567 SourceLocation IdLoc = ConsumeToken();
Richard Smith6f1daa42016-12-16 00:58:48 +0000568 ParsedType Type =
569 Actions.getInheritingConstructorName(D.SS, IdLoc, *LastII);
570 D.Name.setConstructorName(Type, IdLoc, IdLoc);
571 } else {
572 if (ParseUnqualifiedId(
573 D.SS, /*EnteringContext=*/false,
574 /*AllowDestructorName=*/true,
575 /*AllowConstructorName=*/!(Tok.is(tok::identifier) &&
576 NextToken().is(tok::equal)),
577 nullptr, D.TemplateKWLoc, D.Name))
578 return true;
Douglas Gregorfec52632009-06-20 00:51:54 +0000579 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000580
Richard Smith6f1daa42016-12-16 00:58:48 +0000581 // FIXME: Parse optional ellipsis
582
583 return false;
584}
585
586/// ParseUsingDeclaration - Parse C++ using-declaration or alias-declaration.
587/// Assumes that 'using' was already seen.
588///
589/// using-declaration: [C++ 7.3.p3: namespace.udecl]
590/// 'using' using-declarator-list[opt] ;
591///
592/// using-declarator-list: [C++1z]
593/// using-declarator '...'[opt]
594/// using-declarator-list ',' using-declarator '...'[opt]
595///
596/// using-declarator-list: [C++98-14]
597/// using-declarator
598///
599/// alias-declaration: C++11 [dcl.dcl]p1
600/// 'using' identifier attribute-specifier-seq[opt] = type-id ;
601///
602Parser::DeclGroupPtrTy
603Parser::ParseUsingDeclaration(unsigned Context,
604 const ParsedTemplateInfo &TemplateInfo,
605 SourceLocation UsingLoc, SourceLocation &DeclEnd,
606 AccessSpecifier AS) {
607 // Check for misplaced attributes before the identifier in an
608 // alias-declaration.
609 ParsedAttributesWithRange MisplacedAttrs(AttrFactory);
610 MaybeParseCXX11Attributes(MisplacedAttrs);
611
612 UsingDeclarator D;
613 bool InvalidDeclarator = ParseUsingDeclarator(Context, D);
614
Richard Smithc2c8bb82013-10-15 01:34:54 +0000615 ParsedAttributesWithRange Attrs(AttrFactory);
Richard Smith37a45dd2013-10-24 01:21:09 +0000616 MaybeParseGNUAttributes(Attrs);
Richard Smith54ecd982013-02-20 19:22:51 +0000617 MaybeParseCXX11Attributes(Attrs);
Richard Smithdda56e42011-04-15 14:24:37 +0000618
619 // Maybe this is an alias-declaration.
Richard Smith6f1daa42016-12-16 00:58:48 +0000620 if (Tok.is(tok::equal)) {
621 if (InvalidDeclarator) {
622 SkipUntil(tok::semi);
623 return nullptr;
624 }
625
Richard Smithc2c8bb82013-10-15 01:34:54 +0000626 // If we had any misplaced attributes from earlier, this is where they
627 // should have been written.
628 if (MisplacedAttrs.Range.isValid()) {
629 Diag(MisplacedAttrs.Range.getBegin(), diag::err_attributes_not_allowed)
630 << FixItHint::CreateInsertionFromRange(
631 Tok.getLocation(),
632 CharSourceRange::getTokenRange(MisplacedAttrs.Range))
633 << FixItHint::CreateRemoval(MisplacedAttrs.Range);
634 Attrs.takeAllFrom(MisplacedAttrs);
635 }
636
Richard Smith6f1daa42016-12-16 00:58:48 +0000637 Decl *DeclFromDeclSpec = nullptr;
638 Decl *AD = ParseAliasDeclarationAfterDeclarator(
639 TemplateInfo, UsingLoc, D, DeclEnd, AS, Attrs, &DeclFromDeclSpec);
640 return Actions.ConvertDeclToDeclGroup(AD, DeclFromDeclSpec);
Alexis Hunt6aa9bee2012-06-23 05:07:58 +0000641 }
Mike Stump11289f42009-09-09 15:08:12 +0000642
Richard Smith6f1daa42016-12-16 00:58:48 +0000643 // C++11 attributes are not allowed on a using-declaration, but GNU ones
644 // are.
645 ProhibitAttributes(MisplacedAttrs);
646 ProhibitAttributes(Attrs);
Douglas Gregorfec52632009-06-20 00:51:54 +0000647
John McCall9b72f892010-11-10 02:40:36 +0000648 // Diagnose an attempt to declare a templated using-declaration.
Richard Smith810ad3e2013-01-29 10:02:16 +0000649 // In C++11, alias-declarations can be templates:
Richard Smithdda56e42011-04-15 14:24:37 +0000650 // template <...> using id = type;
Richard Smith6f1daa42016-12-16 00:58:48 +0000651 if (TemplateInfo.Kind) {
John McCall9b72f892010-11-10 02:40:36 +0000652 SourceRange R = TemplateInfo.getSourceRange();
Craig Topper54a6a682015-11-14 18:16:08 +0000653 Diag(UsingLoc, diag::err_templated_using_directive_declaration)
654 << 1 /* declaration */ << R << FixItHint::CreateRemoval(R);
John McCall9b72f892010-11-10 02:40:36 +0000655
656 // Unfortunately, we have to bail out instead of recovering by
657 // ignoring the parameters, just in case the nested name specifier
658 // depends on the parameters.
Craig Topper161e4db2014-05-21 06:02:52 +0000659 return nullptr;
John McCall9b72f892010-11-10 02:40:36 +0000660 }
661
Richard Smith6f1daa42016-12-16 00:58:48 +0000662 SmallVector<Decl *, 8> DeclsInGroup;
663 while (true) {
664 // Parse (optional) attributes (most likely GNU strong-using extension).
665 MaybeParseGNUAttributes(Attrs);
666
667 if (InvalidDeclarator)
668 SkipUntil(tok::comma, tok::semi, StopBeforeMatch);
669 else {
670 // "typename" keyword is allowed for identifiers only,
671 // because it may be a type definition.
672 if (D.TypenameLoc.isValid() &&
673 D.Name.getKind() != UnqualifiedId::IK_Identifier) {
674 Diag(D.Name.getSourceRange().getBegin(),
675 diag::err_typename_identifiers_only)
676 << FixItHint::CreateRemoval(SourceRange(D.TypenameLoc));
677 // Proceed parsing, but discard the typename keyword.
678 D.TypenameLoc = SourceLocation();
679 }
680
681 Decl *UD =
682 Actions.ActOnUsingDeclaration(getCurScope(), AS, UsingLoc, D.SS,
683 D.Name, Attrs.getList(), D.TypenameLoc);
684 if (UD)
685 DeclsInGroup.push_back(UD);
686 }
687
688 if (!TryConsumeToken(tok::comma))
689 break;
690
691 // Parse another using-declarator.
692 Attrs.clear();
693 InvalidDeclarator = ParseUsingDeclarator(Context, D);
Douglas Gregor882a61a2011-09-26 14:30:28 +0000694 }
695
Richard Smith6f1daa42016-12-16 00:58:48 +0000696 if (DeclsInGroup.size() > 1)
697 Diag(Tok.getLocation(), getLangOpts().CPlusPlus1z ?
698 diag::warn_cxx1z_compat_multi_using_declaration :
699 diag::ext_multi_using_declaration);
700
701 // Eat ';'.
702 DeclEnd = Tok.getLocation();
703 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
704 !Attrs.empty() ? "attributes list"
705 : "using declaration"))
706 SkipUntil(tok::semi);
707
708 return Actions.BuildDeclaratorGroup(DeclsInGroup, /*MayContainAuto*/false);
709}
710
711Decl *Parser::ParseAliasTemplate(const ParsedTemplateInfo &TemplateInfo,
712 SourceLocation &DeclEnd, AccessSpecifier AS,
713 ParsedAttributesWithRange &MisplacedAttrs1) {
714 assert(Tok.is(tok::kw_using) && "Not using token");
715 ObjCDeclContextSwitch ObjCDC(*this);
716
717 // Eat 'using'.
718 SourceLocation UsingLoc = ConsumeToken();
719 if (Tok.is(tok::code_completion)) {
720 Actions.CodeCompleteUsing(getCurScope());
721 cutOffParsing();
722 return nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +0000723 }
Richard Smithdda56e42011-04-15 14:24:37 +0000724
Richard Smith6f1daa42016-12-16 00:58:48 +0000725 // 'using namespace' means this is a using-directive.
726 if (Tok.is(tok::kw_namespace)) {
727 SourceRange R = TemplateInfo.getSourceRange();
728 Diag(UsingLoc, diag::err_templated_using_directive_declaration)
729 << 0 /* directive */ << R;
730 SkipUntil(tok::semi);
731 return nullptr;
732 }
733
734 // Check for misplaced attributes before the identifier.
735 ParsedAttributesWithRange MisplacedAttrs2(AttrFactory);
736 MaybeParseCXX11Attributes(MisplacedAttrs2);
737
738 // FIXME: Just parse an identifier here?
739 UsingDeclarator D;
740 if (ParseUsingDeclarator(Declarator::FileContext, D)) {
741 SkipUntil(tok::semi);
742 return nullptr;
743 }
744
745 ParsedAttributesWithRange Attrs(AttrFactory);
746
747 // If we had any misplaced attributes from earlier, this is where they
748 // should have been written.
749 for (auto *MisplacedAttrs : {&MisplacedAttrs1, &MisplacedAttrs2}) {
750 if (MisplacedAttrs->Range.isValid()) {
751 Diag(MisplacedAttrs->Range.getBegin(), diag::err_attributes_not_allowed)
752 << FixItHint::CreateInsertionFromRange(
753 Tok.getLocation(),
754 CharSourceRange::getTokenRange(MisplacedAttrs->Range))
755 << FixItHint::CreateRemoval(MisplacedAttrs->Range);
756 Attrs.takeAllFrom(*MisplacedAttrs);
757 }
758 }
759
760 MaybeParseGNUAttributes(Attrs);
761 MaybeParseCXX11Attributes(Attrs);
762
763 return ParseAliasDeclarationAfterDeclarator(TemplateInfo, UsingLoc, D,
764 DeclEnd, AS, Attrs);
765}
766
767Decl *Parser::ParseAliasDeclarationAfterDeclarator(
768 const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc,
769 UsingDeclarator &D, SourceLocation &DeclEnd, AccessSpecifier AS,
770 ParsedAttributes &Attrs, Decl **OwnedType) {
771 if (ExpectAndConsume(tok::equal)) {
772 SkipUntil(tok::semi);
773 return nullptr;
774 }
775
776 Diag(Tok.getLocation(), getLangOpts().CPlusPlus11 ?
777 diag::warn_cxx98_compat_alias_declaration :
778 diag::ext_alias_declaration);
779
780 // Type alias templates cannot be specialized.
781 int SpecKind = -1;
782 if (TemplateInfo.Kind == ParsedTemplateInfo::Template &&
783 D.Name.getKind() == UnqualifiedId::IK_TemplateId)
784 SpecKind = 0;
785 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization)
786 SpecKind = 1;
787 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
788 SpecKind = 2;
789 if (SpecKind != -1) {
790 SourceRange Range;
791 if (SpecKind == 0)
792 Range = SourceRange(D.Name.TemplateId->LAngleLoc,
793 D.Name.TemplateId->RAngleLoc);
794 else
795 Range = TemplateInfo.getSourceRange();
796 Diag(Range.getBegin(), diag::err_alias_declaration_specialization)
797 << SpecKind << Range;
798 SkipUntil(tok::semi);
799 return nullptr;
800 }
801
802 // Name must be an identifier.
803 if (D.Name.getKind() != UnqualifiedId::IK_Identifier) {
804 Diag(D.Name.StartLocation, diag::err_alias_declaration_not_identifier);
805 // No removal fixit: can't recover from this.
806 SkipUntil(tok::semi);
807 return nullptr;
808 } else if (D.TypenameLoc.isValid())
809 Diag(D.TypenameLoc, diag::err_alias_declaration_not_identifier)
810 << FixItHint::CreateRemoval(SourceRange(
811 D.TypenameLoc,
812 D.SS.isNotEmpty() ? D.SS.getEndLoc() : D.TypenameLoc));
813 else if (D.SS.isNotEmpty())
814 Diag(D.SS.getBeginLoc(), diag::err_alias_declaration_not_identifier)
815 << FixItHint::CreateRemoval(D.SS.getRange());
816
817 Decl *DeclFromDeclSpec = nullptr;
818 TypeResult TypeAlias =
819 ParseTypeName(nullptr,
820 TemplateInfo.Kind ? Declarator::AliasTemplateContext
821 : Declarator::AliasDeclContext,
822 AS, &DeclFromDeclSpec, &Attrs);
823 if (OwnedType)
824 *OwnedType = DeclFromDeclSpec;
825
826 // Eat ';'.
827 DeclEnd = Tok.getLocation();
828 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
829 !Attrs.empty() ? "attributes list"
830 : "alias declaration"))
831 SkipUntil(tok::semi);
832
833 TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
834 MultiTemplateParamsArg TemplateParamsArg(
835 TemplateParams ? TemplateParams->data() : nullptr,
836 TemplateParams ? TemplateParams->size() : 0);
837 return Actions.ActOnAliasDeclaration(getCurScope(), AS, TemplateParamsArg,
838 UsingLoc, D.Name, Attrs.getList(),
839 TypeAlias, DeclFromDeclSpec);
Douglas Gregord7c4d982008-12-30 03:27:21 +0000840}
841
Benjamin Kramere56f3932011-12-23 17:00:35 +0000842/// ParseStaticAssertDeclaration - Parse C++0x or C11 static_assert-declaration.
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000843///
Peter Collingbourne3d9cbdc2011-04-15 00:35:57 +0000844/// [C++0x] static_assert-declaration:
845/// static_assert ( constant-expression , string-literal ) ;
846///
Benjamin Kramere56f3932011-12-23 17:00:35 +0000847/// [C11] static_assert-declaration:
Peter Collingbourne3d9cbdc2011-04-15 00:35:57 +0000848/// _Static_assert ( constant-expression , string-literal ) ;
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000849///
John McCall48871652010-08-21 09:40:31 +0000850Decl *Parser::ParseStaticAssertDeclaration(SourceLocation &DeclEnd){
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000851 assert(Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert) &&
Peter Collingbourne3d9cbdc2011-04-15 00:35:57 +0000852 "Not a static_assert declaration");
853
David Blaikiebbafb8a2012-03-11 07:00:24 +0000854 if (Tok.is(tok::kw__Static_assert) && !getLangOpts().C11)
Benjamin Kramere56f3932011-12-23 17:00:35 +0000855 Diag(Tok, diag::ext_c11_static_assert);
Richard Smithb15c11c2011-10-17 23:06:20 +0000856 if (Tok.is(tok::kw_static_assert))
857 Diag(Tok, diag::warn_cxx98_compat_static_assert);
Peter Collingbourne3d9cbdc2011-04-15 00:35:57 +0000858
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000859 SourceLocation StaticAssertLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000860
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000861 BalancedDelimiterTracker T(*this, tok::l_paren);
862 if (T.consumeOpen()) {
Alp Tokerec543272013-12-24 09:48:30 +0000863 Diag(Tok, diag::err_expected) << tok::l_paren;
Richard Smith76965712012-09-13 19:12:50 +0000864 SkipMalformedDecl();
Craig Topper161e4db2014-05-21 06:02:52 +0000865 return nullptr;
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000866 }
Mike Stump11289f42009-09-09 15:08:12 +0000867
John McCalldadc5752010-08-24 06:29:42 +0000868 ExprResult AssertExpr(ParseConstantExpression());
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000869 if (AssertExpr.isInvalid()) {
Richard Smith76965712012-09-13 19:12:50 +0000870 SkipMalformedDecl();
Craig Topper161e4db2014-05-21 06:02:52 +0000871 return nullptr;
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000872 }
Mike Stump11289f42009-09-09 15:08:12 +0000873
Richard Smith085a64f2014-06-20 19:57:12 +0000874 ExprResult AssertMessage;
875 if (Tok.is(tok::r_paren)) {
876 Diag(Tok, getLangOpts().CPlusPlus1z
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000877 ? diag::warn_cxx14_compat_static_assert_no_message
Richard Smith085a64f2014-06-20 19:57:12 +0000878 : diag::ext_static_assert_no_message)
879 << (getLangOpts().CPlusPlus1z
880 ? FixItHint()
881 : FixItHint::CreateInsertion(Tok.getLocation(), ", \"\""));
882 } else {
883 if (ExpectAndConsume(tok::comma)) {
884 SkipUntil(tok::semi);
885 return nullptr;
886 }
Anders Carlssonb4cf3ad2009-03-13 23:29:20 +0000887
Richard Smith085a64f2014-06-20 19:57:12 +0000888 if (!isTokenStringLiteral()) {
889 Diag(Tok, diag::err_expected_string_literal)
890 << /*Source='static_assert'*/1;
891 SkipMalformedDecl();
892 return nullptr;
893 }
Mike Stump11289f42009-09-09 15:08:12 +0000894
Richard Smith085a64f2014-06-20 19:57:12 +0000895 AssertMessage = ParseStringLiteralExpression();
896 if (AssertMessage.isInvalid()) {
897 SkipMalformedDecl();
898 return nullptr;
899 }
Richard Smithd67aea22012-03-06 03:21:47 +0000900 }
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000901
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000902 T.consumeClose();
Mike Stump11289f42009-09-09 15:08:12 +0000903
Chris Lattner49836b42009-04-02 04:16:50 +0000904 DeclEnd = Tok.getLocation();
Douglas Gregor45d6bdf2010-09-07 15:23:11 +0000905 ExpectAndConsumeSemi(diag::err_expected_semi_after_static_assert);
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000906
John McCallb268a282010-08-23 23:25:46 +0000907 return Actions.ActOnStaticAssertDeclaration(StaticAssertLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000908 AssertExpr.get(),
909 AssertMessage.get(),
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000910 T.getCloseLocation());
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000911}
912
Richard Smith74aeef52013-04-26 16:15:35 +0000913/// ParseDecltypeSpecifier - Parse a C++11 decltype specifier.
Anders Carlsson74948d02009-06-24 17:47:40 +0000914///
915/// 'decltype' ( expression )
Richard Smith74aeef52013-04-26 16:15:35 +0000916/// 'decltype' ( 'auto' ) [C++1y]
Anders Carlsson74948d02009-06-24 17:47:40 +0000917///
David Blaikie15a430a2011-12-04 05:04:18 +0000918SourceLocation Parser::ParseDecltypeSpecifier(DeclSpec &DS) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000919 assert(Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)
David Blaikie15a430a2011-12-04 05:04:18 +0000920 && "Not a decltype specifier");
921
David Blaikie15a430a2011-12-04 05:04:18 +0000922 ExprResult Result;
923 SourceLocation StartLoc = Tok.getLocation();
924 SourceLocation EndLoc;
925
926 if (Tok.is(tok::annot_decltype)) {
927 Result = getExprAnnotation(Tok);
928 EndLoc = Tok.getAnnotationEndLoc();
929 ConsumeToken();
930 if (Result.isInvalid()) {
931 DS.SetTypeSpecError();
932 return EndLoc;
933 }
934 } else {
Richard Smith324df552012-02-24 22:30:04 +0000935 if (Tok.getIdentifierInfo()->isStr("decltype"))
936 Diag(Tok, diag::warn_cxx98_compat_decltype);
Richard Smithfd3da932012-02-24 18:10:23 +0000937
David Blaikie15a430a2011-12-04 05:04:18 +0000938 ConsumeToken();
939
940 BalancedDelimiterTracker T(*this, tok::l_paren);
941 if (T.expectAndConsume(diag::err_expected_lparen_after,
942 "decltype", tok::r_paren)) {
943 DS.SetTypeSpecError();
944 return T.getOpenLocation() == Tok.getLocation() ?
945 StartLoc : T.getOpenLocation();
946 }
947
Richard Smith74aeef52013-04-26 16:15:35 +0000948 // Check for C++1y 'decltype(auto)'.
949 if (Tok.is(tok::kw_auto)) {
950 // No need to disambiguate here: an expression can't start with 'auto',
951 // because the typename-specifier in a function-style cast operation can't
952 // be 'auto'.
953 Diag(Tok.getLocation(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000954 getLangOpts().CPlusPlus14
Richard Smith74aeef52013-04-26 16:15:35 +0000955 ? diag::warn_cxx11_compat_decltype_auto_type_specifier
956 : diag::ext_decltype_auto_type_specifier);
957 ConsumeToken();
958 } else {
959 // Parse the expression
David Blaikie15a430a2011-12-04 05:04:18 +0000960
Richard Smith74aeef52013-04-26 16:15:35 +0000961 // C++11 [dcl.type.simple]p4:
962 // The operand of the decltype specifier is an unevaluated operand.
963 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
Craig Topper161e4db2014-05-21 06:02:52 +0000964 nullptr,/*IsDecltype=*/true);
Kaelyn Takata5cc85352015-04-10 19:16:46 +0000965 Result =
966 Actions.CorrectDelayedTyposInExpr(ParseExpression(), [](Expr *E) {
967 return E->hasPlaceholderType() ? ExprError() : E;
968 });
Richard Smith74aeef52013-04-26 16:15:35 +0000969 if (Result.isInvalid()) {
970 DS.SetTypeSpecError();
Alexey Bataevee6507d2013-11-18 08:17:37 +0000971 if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch)) {
Richard Smith74aeef52013-04-26 16:15:35 +0000972 EndLoc = ConsumeParen();
Argyrios Kyrtzidisc38395a2012-10-26 22:53:44 +0000973 } else {
Richard Smith74aeef52013-04-26 16:15:35 +0000974 if (PP.isBacktrackEnabled() && Tok.is(tok::semi)) {
975 // Backtrack to get the location of the last token before the semi.
976 PP.RevertCachedTokens(2);
977 ConsumeToken(); // the semi.
978 EndLoc = ConsumeAnyToken();
979 assert(Tok.is(tok::semi));
980 } else {
981 EndLoc = Tok.getLocation();
982 }
Argyrios Kyrtzidisc38395a2012-10-26 22:53:44 +0000983 }
Richard Smith74aeef52013-04-26 16:15:35 +0000984 return EndLoc;
Argyrios Kyrtzidisc38395a2012-10-26 22:53:44 +0000985 }
Richard Smith74aeef52013-04-26 16:15:35 +0000986
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000987 Result = Actions.ActOnDecltypeExpression(Result.get());
David Blaikie15a430a2011-12-04 05:04:18 +0000988 }
989
990 // Match the ')'
991 T.consumeClose();
992 if (T.getCloseLocation().isInvalid()) {
993 DS.SetTypeSpecError();
994 // FIXME: this should return the location of the last token
995 // that was consumed (by "consumeClose()")
996 return T.getCloseLocation();
997 }
998
Richard Smithfd555f62012-02-22 02:04:18 +0000999 if (Result.isInvalid()) {
1000 DS.SetTypeSpecError();
1001 return T.getCloseLocation();
1002 }
1003
David Blaikie15a430a2011-12-04 05:04:18 +00001004 EndLoc = T.getCloseLocation();
Anders Carlsson74948d02009-06-24 17:47:40 +00001005 }
Richard Smith74aeef52013-04-26 16:15:35 +00001006 assert(!Result.isInvalid());
Mike Stump11289f42009-09-09 15:08:12 +00001007
Craig Topper161e4db2014-05-21 06:02:52 +00001008 const char *PrevSpec = nullptr;
John McCall49bfce42009-08-03 20:12:06 +00001009 unsigned DiagID;
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001010 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
Anders Carlsson74948d02009-06-24 17:47:40 +00001011 // Check for duplicate type specifiers (e.g. "int decltype(a)").
Richard Smith74aeef52013-04-26 16:15:35 +00001012 if (Result.get()
1013 ? DS.SetTypeSpecType(DeclSpec::TST_decltype, StartLoc, PrevSpec,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001014 DiagID, Result.get(), Policy)
Richard Smith74aeef52013-04-26 16:15:35 +00001015 : DS.SetTypeSpecType(DeclSpec::TST_decltype_auto, StartLoc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001016 DiagID, Policy)) {
John McCall49bfce42009-08-03 20:12:06 +00001017 Diag(StartLoc, DiagID) << PrevSpec;
David Blaikie15a430a2011-12-04 05:04:18 +00001018 DS.SetTypeSpecError();
1019 }
1020 return EndLoc;
1021}
1022
1023void Parser::AnnotateExistingDecltypeSpecifier(const DeclSpec& DS,
1024 SourceLocation StartLoc,
1025 SourceLocation EndLoc) {
1026 // make sure we have a token we can turn into an annotation token
1027 if (PP.isBacktrackEnabled())
1028 PP.RevertCachedTokens(1);
1029 else
1030 PP.EnterToken(Tok);
1031
1032 Tok.setKind(tok::annot_decltype);
Richard Smith74aeef52013-04-26 16:15:35 +00001033 setExprAnnotation(Tok,
1034 DS.getTypeSpecType() == TST_decltype ? DS.getRepAsExpr() :
1035 DS.getTypeSpecType() == TST_decltype_auto ? ExprResult() :
1036 ExprError());
David Blaikie15a430a2011-12-04 05:04:18 +00001037 Tok.setAnnotationEndLoc(EndLoc);
1038 Tok.setLocation(StartLoc);
1039 PP.AnnotateCachedTokens(Tok);
Anders Carlsson74948d02009-06-24 17:47:40 +00001040}
1041
Alexis Hunt4a257072011-05-19 05:37:45 +00001042void Parser::ParseUnderlyingTypeSpecifier(DeclSpec &DS) {
1043 assert(Tok.is(tok::kw___underlying_type) &&
1044 "Not an underlying type specifier");
1045
1046 SourceLocation StartLoc = ConsumeToken();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001047 BalancedDelimiterTracker T(*this, tok::l_paren);
1048 if (T.expectAndConsume(diag::err_expected_lparen_after,
1049 "__underlying_type", tok::r_paren)) {
Alexis Hunt4a257072011-05-19 05:37:45 +00001050 return;
1051 }
1052
1053 TypeResult Result = ParseTypeName();
1054 if (Result.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00001055 SkipUntil(tok::r_paren, StopAtSemi);
Alexis Hunt4a257072011-05-19 05:37:45 +00001056 return;
1057 }
1058
1059 // Match the ')'
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001060 T.consumeClose();
1061 if (T.getCloseLocation().isInvalid())
Alexis Hunt4a257072011-05-19 05:37:45 +00001062 return;
1063
Craig Topper161e4db2014-05-21 06:02:52 +00001064 const char *PrevSpec = nullptr;
Alexis Hunt4a257072011-05-19 05:37:45 +00001065 unsigned DiagID;
Alexis Hunte852b102011-05-24 22:41:36 +00001066 if (DS.SetTypeSpecType(DeclSpec::TST_underlyingType, StartLoc, PrevSpec,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001067 DiagID, Result.get(),
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001068 Actions.getASTContext().getPrintingPolicy()))
Alexis Hunt4a257072011-05-19 05:37:45 +00001069 Diag(StartLoc, DiagID) << PrevSpec;
Enea Zaffanellaa90af722013-07-06 18:54:58 +00001070 DS.setTypeofParensRange(T.getRange());
Alexis Hunt4a257072011-05-19 05:37:45 +00001071}
1072
David Blaikie00ee7a082011-10-25 15:01:20 +00001073/// ParseBaseTypeSpecifier - Parse a C++ base-type-specifier which is either a
1074/// class name or decltype-specifier. Note that we only check that the result
1075/// names a type; semantic analysis will need to verify that the type names a
1076/// class. The result is either a type or null, depending on whether a type
1077/// name was found.
Douglas Gregor831c93f2008-11-05 20:51:48 +00001078///
Richard Smith4c96e992013-02-19 23:47:15 +00001079/// base-type-specifier: [C++11 class.derived]
David Blaikie00ee7a082011-10-25 15:01:20 +00001080/// class-or-decltype
Richard Smith4c96e992013-02-19 23:47:15 +00001081/// class-or-decltype: [C++11 class.derived]
David Blaikie00ee7a082011-10-25 15:01:20 +00001082/// nested-name-specifier[opt] class-name
1083/// decltype-specifier
Richard Smith4c96e992013-02-19 23:47:15 +00001084/// class-name: [C++ class.name]
Douglas Gregor831c93f2008-11-05 20:51:48 +00001085/// identifier
Douglas Gregord54dfb82009-02-25 23:52:28 +00001086/// simple-template-id
Mike Stump11289f42009-09-09 15:08:12 +00001087///
Richard Smith4c96e992013-02-19 23:47:15 +00001088/// In C++98, instead of base-type-specifier, we have:
1089///
1090/// ::[opt] nested-name-specifier[opt] class-name
Craig Topper9ad7e262014-10-31 06:57:07 +00001091TypeResult Parser::ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
1092 SourceLocation &EndLocation) {
David Blaikiedd58d4c2011-10-25 18:46:41 +00001093 // Ignore attempts to use typename
1094 if (Tok.is(tok::kw_typename)) {
1095 Diag(Tok, diag::err_expected_class_name_not_template)
1096 << FixItHint::CreateRemoval(Tok.getLocation());
1097 ConsumeToken();
1098 }
1099
David Blaikieafa155f2011-10-25 18:17:58 +00001100 // Parse optional nested-name-specifier
1101 CXXScopeSpec SS;
David Blaikieefdccaa2016-01-15 23:43:34 +00001102 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false);
David Blaikieafa155f2011-10-25 18:17:58 +00001103
1104 BaseLoc = Tok.getLocation();
1105
David Blaikie1cd50022011-10-25 17:10:12 +00001106 // Parse decltype-specifier
David Blaikie15a430a2011-12-04 05:04:18 +00001107 // tok == kw_decltype is just error recovery, it can only happen when SS
1108 // isn't empty
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001109 if (Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)) {
David Blaikieafa155f2011-10-25 18:17:58 +00001110 if (SS.isNotEmpty())
1111 Diag(SS.getBeginLoc(), diag::err_unexpected_scope_on_base_decltype)
1112 << FixItHint::CreateRemoval(SS.getRange());
David Blaikie1cd50022011-10-25 17:10:12 +00001113 // Fake up a Declarator to use with ActOnTypeName.
1114 DeclSpec DS(AttrFactory);
1115
David Blaikie7491e732011-12-08 04:53:15 +00001116 EndLocation = ParseDecltypeSpecifier(DS);
David Blaikie1cd50022011-10-25 17:10:12 +00001117
1118 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1119 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
1120 }
1121
Douglas Gregord54dfb82009-02-25 23:52:28 +00001122 // Check whether we have a template-id that names a type.
1123 if (Tok.is(tok::annot_template_id)) {
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00001124 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregor46c59612010-01-12 17:52:59 +00001125 if (TemplateId->Kind == TNK_Type_template ||
1126 TemplateId->Kind == TNK_Dependent_template_name) {
Douglas Gregore7c20652011-03-02 00:47:37 +00001127 AnnotateTemplateIdTokenAsType();
Douglas Gregord54dfb82009-02-25 23:52:28 +00001128
1129 assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
John McCallba7bf592010-08-24 05:47:05 +00001130 ParsedType Type = getTypeAnnotation(Tok);
Douglas Gregord54dfb82009-02-25 23:52:28 +00001131 EndLocation = Tok.getAnnotationEndLoc();
1132 ConsumeToken();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001133
1134 if (Type)
1135 return Type;
1136 return true;
Douglas Gregord54dfb82009-02-25 23:52:28 +00001137 }
1138
1139 // Fall through to produce an error below.
1140 }
1141
Douglas Gregor831c93f2008-11-05 20:51:48 +00001142 if (Tok.isNot(tok::identifier)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00001143 Diag(Tok, diag::err_expected_class_name);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001144 return true;
Douglas Gregor831c93f2008-11-05 20:51:48 +00001145 }
1146
Douglas Gregor18473f32010-01-12 21:28:44 +00001147 IdentifierInfo *Id = Tok.getIdentifierInfo();
1148 SourceLocation IdLoc = ConsumeToken();
1149
1150 if (Tok.is(tok::less)) {
1151 // It looks the user intended to write a template-id here, but the
1152 // template-name was wrong. Try to fix that.
1153 TemplateNameKind TNK = TNK_Type_template;
1154 TemplateTy Template;
Douglas Gregor0be31a22010-07-02 17:43:08 +00001155 if (!Actions.DiagnoseUnknownTemplateName(*Id, IdLoc, getCurScope(),
Douglas Gregore7c20652011-03-02 00:47:37 +00001156 &SS, Template, TNK)) {
Douglas Gregor18473f32010-01-12 21:28:44 +00001157 Diag(IdLoc, diag::err_unknown_template_name)
1158 << Id;
1159 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001160
Serge Pavlovb716b3c2013-08-10 05:54:47 +00001161 if (!Template) {
1162 TemplateArgList TemplateArgs;
1163 SourceLocation LAngleLoc, RAngleLoc;
David Blaikiee20506d2016-01-15 23:43:28 +00001164 ParseTemplateIdAfterTemplateName(nullptr, IdLoc, SS, true, LAngleLoc,
1165 TemplateArgs, RAngleLoc);
Douglas Gregor18473f32010-01-12 21:28:44 +00001166 return true;
Serge Pavlovb716b3c2013-08-10 05:54:47 +00001167 }
Douglas Gregor18473f32010-01-12 21:28:44 +00001168
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001169 // Form the template name
Douglas Gregor18473f32010-01-12 21:28:44 +00001170 UnqualifiedId TemplateName;
1171 TemplateName.setIdentifier(Id, IdLoc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001172
Douglas Gregor18473f32010-01-12 21:28:44 +00001173 // Parse the full template-id, then turn it into a type.
Abramo Bagnara7945c982012-01-27 09:46:47 +00001174 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
1175 TemplateName, true))
Douglas Gregor18473f32010-01-12 21:28:44 +00001176 return true;
1177 if (TNK == TNK_Dependent_template_name)
Douglas Gregore7c20652011-03-02 00:47:37 +00001178 AnnotateTemplateIdTokenAsType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001179
Douglas Gregor18473f32010-01-12 21:28:44 +00001180 // If we didn't end up with a typename token, there's nothing more we
1181 // can do.
1182 if (Tok.isNot(tok::annot_typename))
1183 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001184
Douglas Gregor18473f32010-01-12 21:28:44 +00001185 // Retrieve the type from the annotation token, consume that token, and
1186 // return.
1187 EndLocation = Tok.getAnnotationEndLoc();
John McCallba7bf592010-08-24 05:47:05 +00001188 ParsedType Type = getTypeAnnotation(Tok);
Douglas Gregor18473f32010-01-12 21:28:44 +00001189 ConsumeToken();
1190 return Type;
1191 }
1192
Douglas Gregor831c93f2008-11-05 20:51:48 +00001193 // We have an identifier; check whether it is actually a type.
Craig Topper161e4db2014-05-21 06:02:52 +00001194 IdentifierInfo *CorrectedII = nullptr;
David Blaikieefdccaa2016-01-15 23:43:34 +00001195 ParsedType Type =
1196 Actions.getTypeName(*Id, IdLoc, getCurScope(), &SS, true, false, nullptr,
1197 /*IsCtorOrDtorName=*/false,
1198 /*NonTrivialTypeSourceInfo=*/true, &CorrectedII);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001199 if (!Type) {
Douglas Gregorfe17d252010-02-16 19:09:40 +00001200 Diag(IdLoc, diag::err_expected_class_name);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001201 return true;
Douglas Gregor831c93f2008-11-05 20:51:48 +00001202 }
1203
1204 // Consume the identifier.
Douglas Gregor18473f32010-01-12 21:28:44 +00001205 EndLocation = IdLoc;
Nick Lewycky19b9f952010-07-26 16:56:01 +00001206
1207 // Fake up a Declarator to use with ActOnTypeName.
John McCall084e83d2011-03-24 11:26:52 +00001208 DeclSpec DS(AttrFactory);
Nick Lewycky19b9f952010-07-26 16:56:01 +00001209 DS.SetRangeStart(IdLoc);
1210 DS.SetRangeEnd(EndLocation);
Douglas Gregore7c20652011-03-02 00:47:37 +00001211 DS.getTypeSpecScope() = SS;
Nick Lewycky19b9f952010-07-26 16:56:01 +00001212
Craig Topper161e4db2014-05-21 06:02:52 +00001213 const char *PrevSpec = nullptr;
Nick Lewycky19b9f952010-07-26 16:56:01 +00001214 unsigned DiagID;
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001215 DS.SetTypeSpecType(TST_typename, IdLoc, PrevSpec, DiagID, Type,
1216 Actions.getASTContext().getPrintingPolicy());
Nick Lewycky19b9f952010-07-26 16:56:01 +00001217
1218 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1219 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
Douglas Gregor831c93f2008-11-05 20:51:48 +00001220}
1221
John McCall8d32c052012-05-22 21:28:12 +00001222void Parser::ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001223 while (Tok.isOneOf(tok::kw___single_inheritance,
1224 tok::kw___multiple_inheritance,
1225 tok::kw___virtual_inheritance)) {
John McCall8d32c052012-05-22 21:28:12 +00001226 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
1227 SourceLocation AttrNameLoc = ConsumeToken();
Craig Topper161e4db2014-05-21 06:02:52 +00001228 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
Aaron Ballman8edb5c22013-12-18 23:44:18 +00001229 AttributeList::AS_Keyword);
John McCall8d32c052012-05-22 21:28:12 +00001230 }
1231}
1232
Richard Smith369b9f92012-06-25 21:37:02 +00001233/// Determine whether the following tokens are valid after a type-specifier
1234/// which could be a standalone declaration. This will conservatively return
1235/// true if there's any doubt, and is appropriate for insert-';' fixits.
Richard Smith200f47c2012-07-02 19:14:01 +00001236bool Parser::isValidAfterTypeSpecifier(bool CouldBeBitfield) {
Richard Smith369b9f92012-06-25 21:37:02 +00001237 // This switch enumerates the valid "follow" set for type-specifiers.
1238 switch (Tok.getKind()) {
1239 default: break;
1240 case tok::semi: // struct foo {...} ;
1241 case tok::star: // struct foo {...} * P;
1242 case tok::amp: // struct foo {...} & R = ...
Richard Smith1ac67d12013-01-19 03:48:05 +00001243 case tok::ampamp: // struct foo {...} && R = ...
Richard Smith369b9f92012-06-25 21:37:02 +00001244 case tok::identifier: // struct foo {...} V ;
1245 case tok::r_paren: //(struct foo {...} ) {4}
1246 case tok::annot_cxxscope: // struct foo {...} a:: b;
1247 case tok::annot_typename: // struct foo {...} a ::b;
1248 case tok::annot_template_id: // struct foo {...} a<int> ::b;
1249 case tok::l_paren: // struct foo {...} ( x);
1250 case tok::comma: // __builtin_offsetof(struct foo{...} ,
Richard Smith1ac67d12013-01-19 03:48:05 +00001251 case tok::kw_operator: // struct foo operator ++() {...}
Alp Tokerd3f79c52013-11-24 20:24:54 +00001252 case tok::kw___declspec: // struct foo {...} __declspec(...)
Richard Smith843f18f2014-08-13 02:13:15 +00001253 case tok::l_square: // void f(struct f [ 3])
1254 case tok::ellipsis: // void f(struct f ... [Ns])
Abramo Bagnara152eb392014-08-16 08:29:27 +00001255 // FIXME: we should emit semantic diagnostic when declaration
1256 // attribute is in type attribute position.
1257 case tok::kw___attribute: // struct foo __attribute__((used)) x;
David Majnemer15b311c2016-06-14 03:20:28 +00001258 case tok::annot_pragma_pack: // struct foo {...} _Pragma(pack(pop));
1259 // struct foo {...} _Pragma(section(...));
1260 case tok::annot_pragma_ms_pragma:
1261 // struct foo {...} _Pragma(vtordisp(pop));
1262 case tok::annot_pragma_ms_vtordisp:
1263 // struct foo {...} _Pragma(pointers_to_members(...));
1264 case tok::annot_pragma_ms_pointers_to_members:
Richard Smith369b9f92012-06-25 21:37:02 +00001265 return true;
Richard Smith200f47c2012-07-02 19:14:01 +00001266 case tok::colon:
1267 return CouldBeBitfield; // enum E { ... } : 2;
Reid Klecknercfa91552016-03-21 16:08:49 +00001268 // Microsoft compatibility
1269 case tok::kw___cdecl: // struct foo {...} __cdecl x;
1270 case tok::kw___fastcall: // struct foo {...} __fastcall x;
1271 case tok::kw___stdcall: // struct foo {...} __stdcall x;
1272 case tok::kw___thiscall: // struct foo {...} __thiscall x;
1273 case tok::kw___vectorcall: // struct foo {...} __vectorcall x;
1274 // We will diagnose these calling-convention specifiers on non-function
1275 // declarations later, so claim they are valid after a type specifier.
1276 return getLangOpts().MicrosoftExt;
Richard Smith369b9f92012-06-25 21:37:02 +00001277 // Type qualifiers
1278 case tok::kw_const: // struct foo {...} const x;
1279 case tok::kw_volatile: // struct foo {...} volatile x;
1280 case tok::kw_restrict: // struct foo {...} restrict x;
Richard Smith843f18f2014-08-13 02:13:15 +00001281 case tok::kw__Atomic: // struct foo {...} _Atomic x;
Nico Rieck3e1ee832014-12-04 23:30:25 +00001282 case tok::kw___unaligned: // struct foo {...} __unaligned *x;
Richard Smith1ac67d12013-01-19 03:48:05 +00001283 // Function specifiers
1284 // Note, no 'explicit'. An explicit function must be either a conversion
1285 // operator or a constructor. Either way, it can't have a return type.
1286 case tok::kw_inline: // struct foo inline f();
1287 case tok::kw_virtual: // struct foo virtual f();
1288 case tok::kw_friend: // struct foo friend f();
Richard Smith369b9f92012-06-25 21:37:02 +00001289 // Storage-class specifiers
1290 case tok::kw_static: // struct foo {...} static x;
1291 case tok::kw_extern: // struct foo {...} extern x;
1292 case tok::kw_typedef: // struct foo {...} typedef x;
1293 case tok::kw_register: // struct foo {...} register x;
1294 case tok::kw_auto: // struct foo {...} auto x;
1295 case tok::kw_mutable: // struct foo {...} mutable x;
Richard Smith1ac67d12013-01-19 03:48:05 +00001296 case tok::kw_thread_local: // struct foo {...} thread_local x;
Richard Smith369b9f92012-06-25 21:37:02 +00001297 case tok::kw_constexpr: // struct foo {...} constexpr x;
1298 // As shown above, type qualifiers and storage class specifiers absolutely
1299 // can occur after class specifiers according to the grammar. However,
1300 // almost no one actually writes code like this. If we see one of these,
1301 // it is much more likely that someone missed a semi colon and the
1302 // type/storage class specifier we're seeing is part of the *next*
1303 // intended declaration, as in:
1304 //
1305 // struct foo { ... }
1306 // typedef int X;
1307 //
1308 // We'd really like to emit a missing semicolon error instead of emitting
1309 // an error on the 'int' saying that you can't have two type specifiers in
1310 // the same declaration of X. Because of this, we look ahead past this
1311 // token to see if it's a type specifier. If so, we know the code is
1312 // otherwise invalid, so we can produce the expected semi error.
1313 if (!isKnownToBeTypeSpecifier(NextToken()))
1314 return true;
1315 break;
1316 case tok::r_brace: // struct bar { struct foo {...} }
1317 // Missing ';' at end of struct is accepted as an extension in C mode.
1318 if (!getLangOpts().CPlusPlus)
1319 return true;
1320 break;
Richard Smith52c5b872013-01-29 04:13:32 +00001321 case tok::greater:
1322 // template<class T = class X>
1323 return getLangOpts().CPlusPlus;
Richard Smith369b9f92012-06-25 21:37:02 +00001324 }
1325 return false;
1326}
1327
Douglas Gregor556877c2008-04-13 21:30:24 +00001328/// ParseClassSpecifier - Parse a C++ class-specifier [C++ class] or
1329/// elaborated-type-specifier [C++ dcl.type.elab]; we can't tell which
1330/// until we reach the start of a definition or see a token that
Richard Smithc5b05522012-03-12 07:56:15 +00001331/// cannot start a definition.
Douglas Gregor556877c2008-04-13 21:30:24 +00001332///
1333/// class-specifier: [C++ class]
1334/// class-head '{' member-specification[opt] '}'
1335/// class-head '{' member-specification[opt] '}' attributes[opt]
1336/// class-head:
1337/// class-key identifier[opt] base-clause[opt]
1338/// class-key nested-name-specifier identifier base-clause[opt]
1339/// class-key nested-name-specifier[opt] simple-template-id
1340/// base-clause[opt]
1341/// [GNU] class-key attributes[opt] identifier[opt] base-clause[opt]
Mike Stump11289f42009-09-09 15:08:12 +00001342/// [GNU] class-key attributes[opt] nested-name-specifier
Douglas Gregor556877c2008-04-13 21:30:24 +00001343/// identifier base-clause[opt]
Mike Stump11289f42009-09-09 15:08:12 +00001344/// [GNU] class-key attributes[opt] nested-name-specifier[opt]
Douglas Gregor556877c2008-04-13 21:30:24 +00001345/// simple-template-id base-clause[opt]
1346/// class-key:
1347/// 'class'
1348/// 'struct'
1349/// 'union'
1350///
1351/// elaborated-type-specifier: [C++ dcl.type.elab]
Mike Stump11289f42009-09-09 15:08:12 +00001352/// class-key ::[opt] nested-name-specifier[opt] identifier
1353/// class-key ::[opt] nested-name-specifier[opt] 'template'[opt]
1354/// simple-template-id
Douglas Gregor556877c2008-04-13 21:30:24 +00001355///
1356/// Note that the C++ class-specifier and elaborated-type-specifier,
1357/// together, subsume the C99 struct-or-union-specifier:
1358///
1359/// struct-or-union-specifier: [C99 6.7.2.1]
1360/// struct-or-union identifier[opt] '{' struct-contents '}'
1361/// struct-or-union identifier
1362/// [GNU] struct-or-union attributes[opt] identifier[opt] '{' struct-contents
1363/// '}' attributes[opt]
1364/// [GNU] struct-or-union attributes[opt] identifier
1365/// struct-or-union:
1366/// 'struct'
1367/// 'union'
Chris Lattnerffaa0e62009-04-12 21:49:30 +00001368void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind,
1369 SourceLocation StartLoc, DeclSpec &DS,
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001370 const ParsedTemplateInfo &TemplateInfo,
Douglas Gregordf593fb2011-11-07 17:33:42 +00001371 AccessSpecifier AS,
Michael Han9407e502012-11-26 22:54:45 +00001372 bool EnteringContext, DeclSpecContext DSC,
Bill Wendling44426052012-12-20 19:22:21 +00001373 ParsedAttributesWithRange &Attributes) {
Joao Matose9a3ed42012-08-31 22:18:20 +00001374 DeclSpec::TST TagType;
1375 if (TagTokKind == tok::kw_struct)
1376 TagType = DeclSpec::TST_struct;
1377 else if (TagTokKind == tok::kw___interface)
1378 TagType = DeclSpec::TST_interface;
1379 else if (TagTokKind == tok::kw_class)
1380 TagType = DeclSpec::TST_class;
1381 else {
Chris Lattnerffaa0e62009-04-12 21:49:30 +00001382 assert(TagTokKind == tok::kw_union && "Not a class specifier");
1383 TagType = DeclSpec::TST_union;
1384 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001385
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00001386 if (Tok.is(tok::code_completion)) {
1387 // Code completion for a struct, class, or union name.
Douglas Gregor0be31a22010-07-02 17:43:08 +00001388 Actions.CodeCompleteTag(getCurScope(), TagType);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001389 return cutOffParsing();
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00001390 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001391
Chandler Carruth2d69ec72010-06-28 08:39:25 +00001392 // C++03 [temp.explicit] 14.7.2/8:
1393 // The usual access checking rules do not apply to names used to specify
1394 // explicit instantiations.
1395 //
1396 // As an extension we do not perform access checking on the names used to
1397 // specify explicit specializations either. This is important to allow
1398 // specializing traits classes for private types.
John McCall6347b682012-05-07 06:16:58 +00001399 //
1400 // Note that we don't suppress if this turns out to be an elaborated
1401 // type specifier.
1402 bool shouldDelayDiagsInTag =
1403 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
1404 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
1405 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
Chandler Carruth2d69ec72010-06-28 08:39:25 +00001406
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001407 ParsedAttributesWithRange attrs(AttrFactory);
Douglas Gregor556877c2008-04-13 21:30:24 +00001408 // If attributes exist after tag, parse them.
Richard Smith37a45dd2013-10-24 01:21:09 +00001409 MaybeParseGNUAttributes(attrs);
Aaron Ballman068aa512015-05-20 20:58:33 +00001410 MaybeParseMicrosoftDeclSpecs(attrs);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001411
John McCall8d32c052012-05-22 21:28:12 +00001412 // Parse inheritance specifiers.
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001413 if (Tok.isOneOf(tok::kw___single_inheritance,
1414 tok::kw___multiple_inheritance,
1415 tok::kw___virtual_inheritance))
Richard Smith37a45dd2013-10-24 01:21:09 +00001416 ParseMicrosoftInheritanceClassAttributes(attrs);
John McCall8d32c052012-05-22 21:28:12 +00001417
Alexis Hunt96d5c762009-11-21 08:43:09 +00001418 // If C++0x attributes exist here, parse them.
1419 // FIXME: Are we consistent with the ordering of parsing of different
1420 // styles of attributes?
Richard Smith89645bc2013-01-02 12:01:23 +00001421 MaybeParseCXX11Attributes(attrs);
Mike Stump11289f42009-09-09 15:08:12 +00001422
Michael Han309af292013-01-07 16:57:11 +00001423 // Source location used by FIXIT to insert misplaced
1424 // C++11 attributes
1425 SourceLocation AttrFixitLoc = Tok.getLocation();
1426
Nico Weber7c3c5be2014-09-23 04:09:56 +00001427 if (TagType == DeclSpec::TST_struct &&
David Majnemer86330af2014-12-29 02:14:26 +00001428 Tok.isNot(tok::identifier) &&
1429 !Tok.isAnnotation() &&
Nico Weber7c3c5be2014-09-23 04:09:56 +00001430 Tok.getIdentifierInfo() &&
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001431 Tok.isOneOf(tok::kw___is_abstract,
1432 tok::kw___is_arithmetic,
1433 tok::kw___is_array,
David Majnemerb3d96882016-05-23 17:21:55 +00001434 tok::kw___is_assignable,
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001435 tok::kw___is_base_of,
1436 tok::kw___is_class,
1437 tok::kw___is_complete_type,
1438 tok::kw___is_compound,
1439 tok::kw___is_const,
1440 tok::kw___is_constructible,
1441 tok::kw___is_convertible,
1442 tok::kw___is_convertible_to,
1443 tok::kw___is_destructible,
1444 tok::kw___is_empty,
1445 tok::kw___is_enum,
1446 tok::kw___is_floating_point,
1447 tok::kw___is_final,
1448 tok::kw___is_function,
1449 tok::kw___is_fundamental,
1450 tok::kw___is_integral,
1451 tok::kw___is_interface_class,
1452 tok::kw___is_literal,
1453 tok::kw___is_lvalue_expr,
1454 tok::kw___is_lvalue_reference,
1455 tok::kw___is_member_function_pointer,
1456 tok::kw___is_member_object_pointer,
1457 tok::kw___is_member_pointer,
1458 tok::kw___is_nothrow_assignable,
1459 tok::kw___is_nothrow_constructible,
1460 tok::kw___is_nothrow_destructible,
1461 tok::kw___is_object,
1462 tok::kw___is_pod,
1463 tok::kw___is_pointer,
1464 tok::kw___is_polymorphic,
1465 tok::kw___is_reference,
1466 tok::kw___is_rvalue_expr,
1467 tok::kw___is_rvalue_reference,
1468 tok::kw___is_same,
1469 tok::kw___is_scalar,
1470 tok::kw___is_sealed,
1471 tok::kw___is_signed,
1472 tok::kw___is_standard_layout,
1473 tok::kw___is_trivial,
1474 tok::kw___is_trivially_assignable,
1475 tok::kw___is_trivially_constructible,
1476 tok::kw___is_trivially_copyable,
1477 tok::kw___is_union,
1478 tok::kw___is_unsigned,
1479 tok::kw___is_void,
1480 tok::kw___is_volatile))
Nico Weber7c3c5be2014-09-23 04:09:56 +00001481 // GNU libstdc++ 4.2 and libc++ use certain intrinsic names as the
1482 // name of struct templates, but some are keywords in GCC >= 4.3
1483 // and Clang. Therefore, when we see the token sequence "struct
1484 // X", make X into a normal identifier rather than a keyword, to
1485 // allow libstdc++ 4.2 and libc++ to work properly.
1486 TryKeywordIdentFallback(true);
Mike Stump11289f42009-09-09 15:08:12 +00001487
David Majnemer51fd8a02015-07-22 23:46:18 +00001488 struct PreserveAtomicIdentifierInfoRAII {
1489 PreserveAtomicIdentifierInfoRAII(Token &Tok, bool Enabled)
1490 : AtomicII(nullptr) {
1491 if (!Enabled)
1492 return;
1493 assert(Tok.is(tok::kw__Atomic));
1494 AtomicII = Tok.getIdentifierInfo();
1495 AtomicII->revertTokenIDToIdentifier();
1496 Tok.setKind(tok::identifier);
1497 }
1498 ~PreserveAtomicIdentifierInfoRAII() {
1499 if (!AtomicII)
1500 return;
1501 AtomicII->revertIdentifierToTokenID(tok::kw__Atomic);
1502 }
1503 IdentifierInfo *AtomicII;
1504 };
1505
1506 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
1507 // implementation for VS2013 uses _Atomic as an identifier for one of the
1508 // classes in <atomic>. When we are parsing 'struct _Atomic', don't consider
1509 // '_Atomic' to be a keyword. We are careful to undo this so that clang can
1510 // use '_Atomic' in its own header files.
1511 bool ShouldChangeAtomicToIdentifier = getLangOpts().MSVCCompat &&
1512 Tok.is(tok::kw__Atomic) &&
1513 TagType == DeclSpec::TST_struct;
1514 PreserveAtomicIdentifierInfoRAII AtomicTokenGuard(
1515 Tok, ShouldChangeAtomicToIdentifier);
1516
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001517 // Parse the (optional) nested-name-specifier.
John McCall9dab4e62009-12-12 11:40:51 +00001518 CXXScopeSpec &SS = DS.getTypeSpecScope();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001519 if (getLangOpts().CPlusPlus) {
Serge Pavlov458ea762014-07-16 05:16:52 +00001520 // "FOO : BAR" is not a potential typo for "FOO::BAR". In this context it
1521 // is a base-specifier-list.
Chris Lattnerd5c1c9d2009-12-10 00:32:41 +00001522 ColonProtectionRAIIObject X(*this);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001523
Nico Webercfaa4cd2015-02-15 07:26:13 +00001524 CXXScopeSpec Spec;
1525 bool HasValidSpec = true;
David Blaikieefdccaa2016-01-15 23:43:34 +00001526 if (ParseOptionalCXXScopeSpecifier(Spec, nullptr, EnteringContext)) {
John McCall413021a2010-07-30 06:26:29 +00001527 DS.SetTypeSpecError();
Nico Webercfaa4cd2015-02-15 07:26:13 +00001528 HasValidSpec = false;
1529 }
1530 if (Spec.isSet())
1531 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::annot_template_id)) {
Alp Tokerec543272013-12-24 09:48:30 +00001532 Diag(Tok, diag::err_expected) << tok::identifier;
Nico Webercfaa4cd2015-02-15 07:26:13 +00001533 HasValidSpec = false;
1534 }
1535 if (HasValidSpec)
1536 SS = Spec;
Chris Lattnerd5c1c9d2009-12-10 00:32:41 +00001537 }
Douglas Gregor67a65642009-02-17 23:15:12 +00001538
Douglas Gregor916462b2009-10-30 21:46:58 +00001539 TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
1540
Douglas Gregor67a65642009-02-17 23:15:12 +00001541 // Parse the (optional) class name or simple-template-id.
Craig Topper161e4db2014-05-21 06:02:52 +00001542 IdentifierInfo *Name = nullptr;
Douglas Gregor556877c2008-04-13 21:30:24 +00001543 SourceLocation NameLoc;
Craig Topper161e4db2014-05-21 06:02:52 +00001544 TemplateIdAnnotation *TemplateId = nullptr;
Douglas Gregor556877c2008-04-13 21:30:24 +00001545 if (Tok.is(tok::identifier)) {
1546 Name = Tok.getIdentifierInfo();
1547 NameLoc = ConsumeToken();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001548
David Blaikiebbafb8a2012-03-11 07:00:24 +00001549 if (Tok.is(tok::less) && getLangOpts().CPlusPlus) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001550 // The name was supposed to refer to a template, but didn't.
Douglas Gregor916462b2009-10-30 21:46:58 +00001551 // Eat the template argument list and try to continue parsing this as
1552 // a class (or template thereof).
1553 TemplateArgList TemplateArgs;
Douglas Gregor916462b2009-10-30 21:46:58 +00001554 SourceLocation LAngleLoc, RAngleLoc;
David Blaikiee20506d2016-01-15 23:43:28 +00001555 if (ParseTemplateIdAfterTemplateName(
1556 nullptr, NameLoc, SS, true, LAngleLoc, TemplateArgs, RAngleLoc)) {
Douglas Gregor916462b2009-10-30 21:46:58 +00001557 // We couldn't parse the template argument list at all, so don't
1558 // try to give any location information for the list.
1559 LAngleLoc = RAngleLoc = SourceLocation();
1560 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001561
Douglas Gregor916462b2009-10-30 21:46:58 +00001562 Diag(NameLoc, diag::err_explicit_spec_non_template)
Alp Toker01d65e12014-01-06 12:54:41 +00001563 << (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
1564 << TagTokKind << Name << SourceRange(LAngleLoc, RAngleLoc);
Joao Matose9a3ed42012-08-31 22:18:20 +00001565
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001566 // Strip off the last template parameter list if it was empty, since
Douglas Gregor1d0015f2009-10-30 22:09:44 +00001567 // we've removed its template argument list.
1568 if (TemplateParams && TemplateInfo.LastParameterListWasEmpty) {
Hubert Tong97b06632016-04-13 18:41:03 +00001569 if (TemplateParams->size() > 1) {
Douglas Gregor1d0015f2009-10-30 22:09:44 +00001570 TemplateParams->pop_back();
1571 } else {
Craig Topper161e4db2014-05-21 06:02:52 +00001572 TemplateParams = nullptr;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001573 const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind
Douglas Gregor1d0015f2009-10-30 22:09:44 +00001574 = ParsedTemplateInfo::NonTemplate;
1575 }
1576 } else if (TemplateInfo.Kind
1577 == ParsedTemplateInfo::ExplicitInstantiation) {
1578 // Pretend this is just a forward declaration.
Craig Topper161e4db2014-05-21 06:02:52 +00001579 TemplateParams = nullptr;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001580 const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind
Douglas Gregor916462b2009-10-30 21:46:58 +00001581 = ParsedTemplateInfo::NonTemplate;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001582 const_cast<ParsedTemplateInfo&>(TemplateInfo).TemplateLoc
Douglas Gregor1d0015f2009-10-30 22:09:44 +00001583 = SourceLocation();
1584 const_cast<ParsedTemplateInfo&>(TemplateInfo).ExternLoc
1585 = SourceLocation();
Douglas Gregor916462b2009-10-30 21:46:58 +00001586 }
Douglas Gregor916462b2009-10-30 21:46:58 +00001587 }
Douglas Gregor7f741122009-02-25 19:37:18 +00001588 } else if (Tok.is(tok::annot_template_id)) {
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00001589 TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregor7f741122009-02-25 19:37:18 +00001590 NameLoc = ConsumeToken();
Douglas Gregor67a65642009-02-17 23:15:12 +00001591
Douglas Gregore7c20652011-03-02 00:47:37 +00001592 if (TemplateId->Kind != TNK_Type_template &&
1593 TemplateId->Kind != TNK_Dependent_template_name) {
Douglas Gregor7f741122009-02-25 19:37:18 +00001594 // The template-name in the simple-template-id refers to
1595 // something other than a class template. Give an appropriate
1596 // error message and skip to the ';'.
1597 SourceRange Range(NameLoc);
1598 if (SS.isNotEmpty())
1599 Range.setBegin(SS.getBeginLoc());
Douglas Gregor67a65642009-02-17 23:15:12 +00001600
Richard Smith72bfbd82013-12-04 00:28:23 +00001601 // FIXME: Name may be null here.
Douglas Gregor7f741122009-02-25 19:37:18 +00001602 Diag(TemplateId->LAngleLoc, diag::err_template_spec_syntax_non_template)
Richard Trieu30f93852013-06-19 22:25:01 +00001603 << TemplateId->Name << static_cast<int>(TemplateId->Kind) << Range;
Mike Stump11289f42009-09-09 15:08:12 +00001604
Douglas Gregor7f741122009-02-25 19:37:18 +00001605 DS.SetTypeSpecError();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001606 SkipUntil(tok::semi, StopBeforeMatch);
Douglas Gregor7f741122009-02-25 19:37:18 +00001607 return;
Douglas Gregor67a65642009-02-17 23:15:12 +00001608 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001609 }
1610
Richard Smithbfdb1082012-03-12 08:56:40 +00001611 // There are four options here.
1612 // - If we are in a trailing return type, this is always just a reference,
1613 // and we must not try to parse a definition. For instance,
1614 // [] () -> struct S { };
1615 // does not define a type.
1616 // - If we have 'struct foo {...', 'struct foo :...',
1617 // 'struct foo final :' or 'struct foo final {', then this is a definition.
1618 // - If we have 'struct foo;', then this is either a forward declaration
1619 // or a friend declaration, which have to be treated differently.
1620 // - Otherwise we have something like 'struct foo xyz', a reference.
Michael Han9407e502012-11-26 22:54:45 +00001621 //
1622 // We also detect these erroneous cases to provide better diagnostic for
1623 // C++11 attributes parsing.
1624 // - attributes follow class name:
1625 // struct foo [[]] {};
1626 // - attributes appear before or after 'final':
1627 // struct foo [[]] final [[]] {};
1628 //
Richard Smithc5b05522012-03-12 07:56:15 +00001629 // However, in type-specifier-seq's, things look like declarations but are
1630 // just references, e.g.
1631 // new struct s;
Sebastian Redl2b372722010-02-03 21:21:43 +00001632 // or
Richard Smithc5b05522012-03-12 07:56:15 +00001633 // &T::operator struct s;
Richard Smith649c7b062014-01-08 00:56:48 +00001634 // For these, DSC is DSC_type_specifier or DSC_alias_declaration.
Michael Han9407e502012-11-26 22:54:45 +00001635
1636 // If there are attributes after class name, parse them.
Richard Smith89645bc2013-01-02 12:01:23 +00001637 MaybeParseCXX11Attributes(Attributes);
Michael Han9407e502012-11-26 22:54:45 +00001638
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001639 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
John McCallfaf5fb42010-08-26 23:41:50 +00001640 Sema::TagUseKind TUK;
Richard Smithbfdb1082012-03-12 08:56:40 +00001641 if (DSC == DSC_trailing)
1642 TUK = Sema::TUK_Reference;
1643 else if (Tok.is(tok::l_brace) ||
1644 (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
Richard Smith89645bc2013-01-02 12:01:23 +00001645 (isCXX11FinalKeyword() &&
David Blaikie9933a5a2012-03-12 15:39:49 +00001646 (NextToken().is(tok::l_brace) || NextToken().is(tok::colon)))) {
Douglas Gregor3dad8422009-09-26 06:47:28 +00001647 if (DS.isFriendSpecified()) {
1648 // C++ [class.friend]p2:
1649 // A class shall not be defined in a friend declaration.
Richard Smith0f8ee222012-01-10 01:33:14 +00001650 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
Douglas Gregor3dad8422009-09-26 06:47:28 +00001651 << SourceRange(DS.getFriendSpecLoc());
1652
1653 // Skip everything up to the semicolon, so that this looks like a proper
1654 // friend class (or template thereof) declaration.
Alexey Bataevee6507d2013-11-18 08:17:37 +00001655 SkipUntil(tok::semi, StopBeforeMatch);
John McCallfaf5fb42010-08-26 23:41:50 +00001656 TUK = Sema::TUK_Friend;
Douglas Gregor3dad8422009-09-26 06:47:28 +00001657 } else {
1658 // Okay, this is a class definition.
John McCallfaf5fb42010-08-26 23:41:50 +00001659 TUK = Sema::TUK_Definition;
Douglas Gregor3dad8422009-09-26 06:47:28 +00001660 }
Richard Smith434516c2013-02-22 06:46:23 +00001661 } else if (isCXX11FinalKeyword() && (NextToken().is(tok::l_square) ||
1662 NextToken().is(tok::kw_alignas))) {
Michael Han9407e502012-11-26 22:54:45 +00001663 // We can't tell if this is a definition or reference
1664 // until we skipped the 'final' and C++11 attribute specifiers.
1665 TentativeParsingAction PA(*this);
1666
1667 // Skip the 'final' keyword.
1668 ConsumeToken();
1669
1670 // Skip C++11 attribute specifiers.
1671 while (true) {
1672 if (Tok.is(tok::l_square) && NextToken().is(tok::l_square)) {
1673 ConsumeBracket();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001674 if (!SkipUntil(tok::r_square, StopAtSemi))
Michael Han9407e502012-11-26 22:54:45 +00001675 break;
Richard Smith434516c2013-02-22 06:46:23 +00001676 } else if (Tok.is(tok::kw_alignas) && NextToken().is(tok::l_paren)) {
Michael Han9407e502012-11-26 22:54:45 +00001677 ConsumeToken();
1678 ConsumeParen();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001679 if (!SkipUntil(tok::r_paren, StopAtSemi))
Michael Han9407e502012-11-26 22:54:45 +00001680 break;
1681 } else {
1682 break;
1683 }
1684 }
1685
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001686 if (Tok.isOneOf(tok::l_brace, tok::colon))
Michael Han9407e502012-11-26 22:54:45 +00001687 TUK = Sema::TUK_Definition;
1688 else
1689 TUK = Sema::TUK_Reference;
1690
1691 PA.Revert();
Richard Smith649c7b062014-01-08 00:56:48 +00001692 } else if (!isTypeSpecifier(DSC) &&
Richard Smith369b9f92012-06-25 21:37:02 +00001693 (Tok.is(tok::semi) ||
Richard Smith200f47c2012-07-02 19:14:01 +00001694 (Tok.isAtStartOfLine() && !isValidAfterTypeSpecifier(false)))) {
John McCallfaf5fb42010-08-26 23:41:50 +00001695 TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
Joao Matose9a3ed42012-08-31 22:18:20 +00001696 if (Tok.isNot(tok::semi)) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001697 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
Joao Matose9a3ed42012-08-31 22:18:20 +00001698 // A semicolon was missing after this declaration. Diagnose and recover.
Alp Toker383d2c42014-01-01 03:08:43 +00001699 ExpectAndConsume(tok::semi, diag::err_expected_after,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001700 DeclSpec::getSpecifierName(TagType, PPol));
Joao Matose9a3ed42012-08-31 22:18:20 +00001701 PP.EnterToken(Tok);
1702 Tok.setKind(tok::semi);
1703 }
Richard Smith369b9f92012-06-25 21:37:02 +00001704 } else
John McCallfaf5fb42010-08-26 23:41:50 +00001705 TUK = Sema::TUK_Reference;
Douglas Gregor556877c2008-04-13 21:30:24 +00001706
Michael Han9407e502012-11-26 22:54:45 +00001707 // Forbid misplaced attributes. In cases of a reference, we pass attributes
1708 // to caller to handle.
Michael Han309af292013-01-07 16:57:11 +00001709 if (TUK != Sema::TUK_Reference) {
1710 // If this is not a reference, then the only possible
1711 // valid place for C++11 attributes to appear here
1712 // is between class-key and class-name. If there are
1713 // any attributes after class-name, we try a fixit to move
1714 // them to the right place.
1715 SourceRange AttrRange = Attributes.Range;
1716 if (AttrRange.isValid()) {
1717 Diag(AttrRange.getBegin(), diag::err_attributes_not_allowed)
1718 << AttrRange
1719 << FixItHint::CreateInsertionFromRange(AttrFixitLoc,
1720 CharSourceRange(AttrRange, true))
1721 << FixItHint::CreateRemoval(AttrRange);
1722
1723 // Recover by adding misplaced attributes to the attribute list
1724 // of the class so they can be applied on the class later.
1725 attrs.takeAllFrom(Attributes);
1726 }
1727 }
Michael Han9407e502012-11-26 22:54:45 +00001728
John McCall6347b682012-05-07 06:16:58 +00001729 // If this is an elaborated type specifier, and we delayed
1730 // diagnostics before, just merge them into the current pool.
1731 if (shouldDelayDiagsInTag) {
1732 diagsFromTag.done();
1733 if (TUK == Sema::TUK_Reference)
1734 diagsFromTag.redelay();
1735 }
1736
John McCall413021a2010-07-30 06:26:29 +00001737 if (!Name && !TemplateId && (DS.getTypeSpecType() == DeclSpec::TST_error ||
John McCallfaf5fb42010-08-26 23:41:50 +00001738 TUK != Sema::TUK_Definition)) {
John McCall413021a2010-07-30 06:26:29 +00001739 if (DS.getTypeSpecType() != DeclSpec::TST_error) {
1740 // We have a declaration or reference to an anonymous class.
1741 Diag(StartLoc, diag::err_anon_type_definition)
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001742 << DeclSpec::getSpecifierName(TagType, Policy);
John McCall413021a2010-07-30 06:26:29 +00001743 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001744
David Majnemer3252fd02013-12-05 01:36:53 +00001745 // If we are parsing a definition and stop at a base-clause, continue on
1746 // until the semicolon. Continuing from the comma will just trick us into
1747 // thinking we are seeing a variable declaration.
1748 if (TUK == Sema::TUK_Definition && Tok.is(tok::colon))
1749 SkipUntil(tok::semi, StopBeforeMatch);
1750 else
1751 SkipUntil(tok::comma, StopAtSemi);
Douglas Gregor556877c2008-04-13 21:30:24 +00001752 return;
1753 }
1754
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001755 // Create the tag portion of the class or class template.
John McCall48871652010-08-21 09:40:31 +00001756 DeclResult TagOrTempResult = true; // invalid
1757 TypeResult TypeResult = true; // invalid
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001758
Douglas Gregord6ab8742009-05-28 23:31:59 +00001759 bool Owned = false;
Richard Smithd9ba2242015-05-07 03:54:19 +00001760 Sema::SkipBodyInfo SkipBody;
John McCall06f6fe8d2009-09-04 01:14:41 +00001761 if (TemplateId) {
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001762 // Explicit specialization, class template partial specialization,
1763 // or explicit instantiation.
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00001764 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregor7f741122009-02-25 19:37:18 +00001765 TemplateId->NumArgs);
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001766 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
John McCallfaf5fb42010-08-26 23:41:50 +00001767 TUK == Sema::TUK_Declaration) {
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001768 // This is an explicit instantiation of a class template.
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001769 ProhibitAttributes(attrs);
1770
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001771 TagOrTempResult
Douglas Gregor0be31a22010-07-02 17:43:08 +00001772 = Actions.ActOnExplicitInstantiation(getCurScope(),
Douglas Gregor43e75172009-09-04 06:33:52 +00001773 TemplateInfo.ExternLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001774 TemplateInfo.TemplateLoc,
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001775 TagType,
Mike Stump11289f42009-09-09 15:08:12 +00001776 StartLoc,
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001777 SS,
John McCall3e56fd42010-08-23 07:28:44 +00001778 TemplateId->Template,
Mike Stump11289f42009-09-09 15:08:12 +00001779 TemplateId->TemplateNameLoc,
1780 TemplateId->LAngleLoc,
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001781 TemplateArgsPtr,
Mike Stump11289f42009-09-09 15:08:12 +00001782 TemplateId->RAngleLoc,
John McCall53fa7142010-12-24 02:08:15 +00001783 attrs.getList());
John McCallb7c5c272010-04-14 00:24:33 +00001784
1785 // Friend template-ids are treated as references unless
1786 // they have template headers, in which case they're ill-formed
1787 // (FIXME: "template <class T> friend class A<T>::B<int>;").
1788 // We diagnose this error in ActOnClassTemplateSpecialization.
John McCallfaf5fb42010-08-26 23:41:50 +00001789 } else if (TUK == Sema::TUK_Reference ||
1790 (TUK == Sema::TUK_Friend &&
John McCallb7c5c272010-04-14 00:24:33 +00001791 TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate)) {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001792 ProhibitAttributes(attrs);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00001793 TypeResult = Actions.ActOnTagTemplateIdType(TUK, TagType, StartLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00001794 TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00001795 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00001796 TemplateId->Template,
1797 TemplateId->TemplateNameLoc,
1798 TemplateId->LAngleLoc,
1799 TemplateArgsPtr,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00001800 TemplateId->RAngleLoc);
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001801 } else {
1802 // This is an explicit specialization or a class template
1803 // partial specialization.
1804 TemplateParameterLists FakedParamLists;
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001805 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1806 // This looks like an explicit instantiation, because we have
1807 // something like
1808 //
1809 // template class Foo<X>
1810 //
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001811 // but it actually has a definition. Most likely, this was
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001812 // meant to be an explicit specialization, but the user forgot
1813 // the '<>' after 'template'.
Richard Smith003c5e12013-11-08 19:03:29 +00001814 // It this is friend declaration however, since it cannot have a
1815 // template header, it is most likely that the user meant to
1816 // remove the 'template' keyword.
Larisse Voufob9bbaba2013-06-22 13:56:11 +00001817 assert((TUK == Sema::TUK_Definition || TUK == Sema::TUK_Friend) &&
Richard Smith003c5e12013-11-08 19:03:29 +00001818 "Expected a definition here");
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001819
Richard Smith003c5e12013-11-08 19:03:29 +00001820 if (TUK == Sema::TUK_Friend) {
1821 Diag(DS.getFriendSpecLoc(), diag::err_friend_explicit_instantiation);
Craig Topper161e4db2014-05-21 06:02:52 +00001822 TemplateParams = nullptr;
Richard Smith003c5e12013-11-08 19:03:29 +00001823 } else {
1824 SourceLocation LAngleLoc =
1825 PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
1826 Diag(TemplateId->TemplateNameLoc,
1827 diag::err_explicit_instantiation_with_definition)
1828 << SourceRange(TemplateInfo.TemplateLoc)
1829 << FixItHint::CreateInsertion(LAngleLoc, "<>");
1830
1831 // Create a fake template parameter list that contains only
1832 // "template<>", so that we treat this construct as a class
1833 // template specialization.
1834 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
Craig Topper96225a52015-12-24 23:58:25 +00001835 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
Hubert Tongf608c052016-04-29 18:05:37 +00001836 LAngleLoc, nullptr));
Richard Smith003c5e12013-11-08 19:03:29 +00001837 TemplateParams = &FakedParamLists;
1838 }
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001839 }
1840
1841 // Build the class template specialization.
Richard Smith4b55a9c2014-04-17 03:29:33 +00001842 TagOrTempResult = Actions.ActOnClassTemplateSpecialization(
1843 getCurScope(), TagType, TUK, StartLoc, DS.getModulePrivateSpecLoc(),
1844 *TemplateId, attrs.getList(),
Craig Topper161e4db2014-05-21 06:02:52 +00001845 MultiTemplateParamsArg(TemplateParams ? &(*TemplateParams)[0]
1846 : nullptr,
Richard Smithc7e6ff02015-05-18 20:36:47 +00001847 TemplateParams ? TemplateParams->size() : 0),
1848 &SkipBody);
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001849 }
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001850 } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
John McCallfaf5fb42010-08-26 23:41:50 +00001851 TUK == Sema::TUK_Declaration) {
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001852 // Explicit instantiation of a member of a class template
1853 // specialization, e.g.,
1854 //
1855 // template struct Outer<int>::Inner;
1856 //
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001857 ProhibitAttributes(attrs);
1858
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001859 TagOrTempResult
Douglas Gregor0be31a22010-07-02 17:43:08 +00001860 = Actions.ActOnExplicitInstantiation(getCurScope(),
Douglas Gregor43e75172009-09-04 06:33:52 +00001861 TemplateInfo.ExternLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001862 TemplateInfo.TemplateLoc,
1863 TagType, StartLoc, SS, Name,
John McCall53fa7142010-12-24 02:08:15 +00001864 NameLoc, attrs.getList());
John McCallace48cd2010-10-19 01:40:49 +00001865 } else if (TUK == Sema::TUK_Friend &&
1866 TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate) {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001867 ProhibitAttributes(attrs);
1868
John McCallace48cd2010-10-19 01:40:49 +00001869 TagOrTempResult =
1870 Actions.ActOnTemplatedFriendTag(getCurScope(), DS.getFriendSpecLoc(),
1871 TagType, StartLoc, SS,
John McCall53fa7142010-12-24 02:08:15 +00001872 Name, NameLoc, attrs.getList(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00001873 MultiTemplateParamsArg(
Craig Topper161e4db2014-05-21 06:02:52 +00001874 TemplateParams? &(*TemplateParams)[0]
1875 : nullptr,
John McCallace48cd2010-10-19 01:40:49 +00001876 TemplateParams? TemplateParams->size() : 0));
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001877 } else {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001878 if (TUK != Sema::TUK_Declaration && TUK != Sema::TUK_Definition)
1879 ProhibitAttributes(attrs);
Richard Smith003c5e12013-11-08 19:03:29 +00001880
Larisse Voufo725de3e2013-06-21 00:08:46 +00001881 if (TUK == Sema::TUK_Definition &&
1882 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1883 // If the declarator-id is not a template-id, issue a diagnostic and
1884 // recover by ignoring the 'template' keyword.
1885 Diag(Tok, diag::err_template_defn_explicit_instantiation)
1886 << 1 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
Craig Topper161e4db2014-05-21 06:02:52 +00001887 TemplateParams = nullptr;
Larisse Voufo725de3e2013-06-21 00:08:46 +00001888 }
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001889
John McCall7f41d982009-09-11 04:59:25 +00001890 bool IsDependent = false;
1891
John McCall32723e92010-10-19 18:40:57 +00001892 // Don't pass down template parameter lists if this is just a tag
1893 // reference. For example, we don't need the template parameters here:
1894 // template <class T> class A *makeA(T t);
1895 MultiTemplateParamsArg TParams;
1896 if (TUK != Sema::TUK_Reference && TemplateParams)
1897 TParams =
1898 MultiTemplateParamsArg(&(*TemplateParams)[0], TemplateParams->size());
1899
Nico Weber32a0fc72016-09-03 03:01:32 +00001900 stripTypeAttributesOffDeclSpec(attrs, DS, TUK);
David Majnemer936b4112015-04-19 07:53:29 +00001901
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001902 // Declaration or definition of a class type
John McCallace48cd2010-10-19 01:40:49 +00001903 TagOrTempResult = Actions.ActOnTag(getCurScope(), TagType, TUK, StartLoc,
John McCall53fa7142010-12-24 02:08:15 +00001904 SS, Name, NameLoc, attrs.getList(), AS,
Douglas Gregor2820e692011-09-09 19:05:14 +00001905 DS.getModulePrivateSpecLoc(),
Richard Smith0f8ee222012-01-10 01:33:14 +00001906 TParams, Owned, IsDependent,
1907 SourceLocation(), false,
Richard Smith649c7b062014-01-08 00:56:48 +00001908 clang::TypeResult(),
Richard Smith65ebb4a2015-03-26 04:09:53 +00001909 DSC == DSC_type_specifier,
1910 &SkipBody);
John McCall7f41d982009-09-11 04:59:25 +00001911
1912 // If ActOnTag said the type was dependent, try again with the
1913 // less common call.
John McCallace48cd2010-10-19 01:40:49 +00001914 if (IsDependent) {
1915 assert(TUK == Sema::TUK_Reference || TUK == Sema::TUK_Friend);
Douglas Gregor0be31a22010-07-02 17:43:08 +00001916 TypeResult = Actions.ActOnDependentTag(getCurScope(), TagType, TUK,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001917 SS, Name, StartLoc, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +00001918 }
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001919 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001920
Douglas Gregor556877c2008-04-13 21:30:24 +00001921 // If there is a body, parse it and inform the actions module.
John McCallfaf5fb42010-08-26 23:41:50 +00001922 if (TUK == Sema::TUK_Definition) {
John McCall2d814c32009-12-19 21:48:58 +00001923 assert(Tok.is(tok::l_brace) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00001924 (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
Richard Smith89645bc2013-01-02 12:01:23 +00001925 isCXX11FinalKeyword());
Richard Smithd9ba2242015-05-07 03:54:19 +00001926 if (SkipBody.ShouldSkip)
Richard Smith65ebb4a2015-03-26 04:09:53 +00001927 SkipCXXMemberSpecification(StartLoc, AttrFixitLoc, TagType,
1928 TagOrTempResult.get());
1929 else if (getLangOpts().CPlusPlus)
Michael Han309af292013-01-07 16:57:11 +00001930 ParseCXXMemberSpecification(StartLoc, AttrFixitLoc, attrs, TagType,
1931 TagOrTempResult.get());
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001932 else
Douglas Gregorc08f4892009-03-25 00:13:59 +00001933 ParseStructUnionBody(StartLoc, TagType, TagOrTempResult.get());
Douglas Gregor556877c2008-04-13 21:30:24 +00001934 }
1935
Craig Topper161e4db2014-05-21 06:02:52 +00001936 const char *PrevSpec = nullptr;
John McCallba7bf592010-08-24 05:47:05 +00001937 unsigned DiagID;
1938 bool Result;
John McCall7f41d982009-09-11 04:59:25 +00001939 if (!TypeResult.isInvalid()) {
Abramo Bagnara9875a3c2011-03-16 20:16:18 +00001940 Result = DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
1941 NameLoc.isValid() ? NameLoc : StartLoc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001942 PrevSpec, DiagID, TypeResult.get(), Policy);
John McCall7f41d982009-09-11 04:59:25 +00001943 } else if (!TagOrTempResult.isInvalid()) {
Abramo Bagnara9875a3c2011-03-16 20:16:18 +00001944 Result = DS.SetTypeSpecType(TagType, StartLoc,
1945 NameLoc.isValid() ? NameLoc : StartLoc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001946 PrevSpec, DiagID, TagOrTempResult.get(), Owned,
1947 Policy);
John McCall7f41d982009-09-11 04:59:25 +00001948 } else {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001949 DS.SetTypeSpecError();
Anders Carlssonf83c9fa2009-05-11 22:27:47 +00001950 return;
1951 }
Mike Stump11289f42009-09-09 15:08:12 +00001952
John McCallba7bf592010-08-24 05:47:05 +00001953 if (Result)
John McCall49bfce42009-08-03 20:12:06 +00001954 Diag(StartLoc, DiagID) << PrevSpec;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001955
Chris Lattnercf251412010-02-02 01:23:29 +00001956 // At this point, we've successfully parsed a class-specifier in 'definition'
1957 // form (e.g. "struct foo { int x; }". While we could just return here, we're
1958 // going to look at what comes after it to improve error recovery. If an
1959 // impossible token occurs next, we assume that the programmer forgot a ; at
1960 // the end of the declaration and recover that way.
1961 //
Richard Smith369b9f92012-06-25 21:37:02 +00001962 // Also enforce C++ [temp]p3:
1963 // In a template-declaration which defines a class, no declarator
1964 // is permitted.
Richard Smith843f18f2014-08-13 02:13:15 +00001965 //
1966 // After a type-specifier, we don't expect a semicolon. This only happens in
1967 // C, since definitions are not permitted in this context in C++.
Joao Matose9a3ed42012-08-31 22:18:20 +00001968 if (TUK == Sema::TUK_Definition &&
Richard Smith843f18f2014-08-13 02:13:15 +00001969 (getLangOpts().CPlusPlus || !isTypeSpecifier(DSC)) &&
Joao Matose9a3ed42012-08-31 22:18:20 +00001970 (TemplateInfo.Kind || !isValidAfterTypeSpecifier(false))) {
Argyrios Kyrtzidise6f69132012-12-17 20:10:43 +00001971 if (Tok.isNot(tok::semi)) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001972 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
Alp Toker383d2c42014-01-01 03:08:43 +00001973 ExpectAndConsume(tok::semi, diag::err_expected_after,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001974 DeclSpec::getSpecifierName(TagType, PPol));
Argyrios Kyrtzidise6f69132012-12-17 20:10:43 +00001975 // Push this token back into the preprocessor and change our current token
1976 // to ';' so that the rest of the code recovers as though there were an
1977 // ';' after the definition.
1978 PP.EnterToken(Tok);
1979 Tok.setKind(tok::semi);
1980 }
Chris Lattnercf251412010-02-02 01:23:29 +00001981 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001982}
1983
Mike Stump11289f42009-09-09 15:08:12 +00001984/// ParseBaseClause - Parse the base-clause of a C++ class [C++ class.derived].
Douglas Gregor556877c2008-04-13 21:30:24 +00001985///
1986/// base-clause : [C++ class.derived]
1987/// ':' base-specifier-list
1988/// base-specifier-list:
1989/// base-specifier '...'[opt]
1990/// base-specifier-list ',' base-specifier '...'[opt]
John McCall48871652010-08-21 09:40:31 +00001991void Parser::ParseBaseClause(Decl *ClassDecl) {
Douglas Gregor556877c2008-04-13 21:30:24 +00001992 assert(Tok.is(tok::colon) && "Not a base clause");
1993 ConsumeToken();
1994
Douglas Gregor29a92472008-10-22 17:49:05 +00001995 // Build up an array of parsed base specifiers.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001996 SmallVector<CXXBaseSpecifier *, 8> BaseInfo;
Douglas Gregor29a92472008-10-22 17:49:05 +00001997
Douglas Gregor556877c2008-04-13 21:30:24 +00001998 while (true) {
1999 // Parse a base-specifier.
Douglas Gregor29a92472008-10-22 17:49:05 +00002000 BaseResult Result = ParseBaseSpecifier(ClassDecl);
Douglas Gregorf8298252009-01-26 22:44:13 +00002001 if (Result.isInvalid()) {
Douglas Gregor556877c2008-04-13 21:30:24 +00002002 // Skip the rest of this base specifier, up until the comma or
2003 // opening brace.
Alexey Bataevee6507d2013-11-18 08:17:37 +00002004 SkipUntil(tok::comma, tok::l_brace, StopAtSemi | StopBeforeMatch);
Douglas Gregor29a92472008-10-22 17:49:05 +00002005 } else {
2006 // Add this to our array of base specifiers.
Douglas Gregorf8298252009-01-26 22:44:13 +00002007 BaseInfo.push_back(Result.get());
Douglas Gregor556877c2008-04-13 21:30:24 +00002008 }
2009
2010 // If the next token is a comma, consume it and keep reading
2011 // base-specifiers.
Alp Toker97650562014-01-10 11:19:30 +00002012 if (!TryConsumeToken(tok::comma))
2013 break;
Douglas Gregor556877c2008-04-13 21:30:24 +00002014 }
Douglas Gregor29a92472008-10-22 17:49:05 +00002015
2016 // Attach the base specifiers
Craig Topperaa700cb2015-12-27 21:55:19 +00002017 Actions.ActOnBaseSpecifiers(ClassDecl, BaseInfo);
Douglas Gregor556877c2008-04-13 21:30:24 +00002018}
2019
2020/// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is
2021/// one entry in the base class list of a class specifier, for example:
2022/// class foo : public bar, virtual private baz {
2023/// 'public bar' and 'virtual private baz' are each base-specifiers.
2024///
2025/// base-specifier: [C++ class.derived]
Richard Smith4c96e992013-02-19 23:47:15 +00002026/// attribute-specifier-seq[opt] base-type-specifier
2027/// attribute-specifier-seq[opt] 'virtual' access-specifier[opt]
2028/// base-type-specifier
2029/// attribute-specifier-seq[opt] access-specifier 'virtual'[opt]
2030/// base-type-specifier
Craig Topper9ad7e262014-10-31 06:57:07 +00002031BaseResult Parser::ParseBaseSpecifier(Decl *ClassDecl) {
Douglas Gregor556877c2008-04-13 21:30:24 +00002032 bool IsVirtual = false;
2033 SourceLocation StartLoc = Tok.getLocation();
2034
Richard Smith4c96e992013-02-19 23:47:15 +00002035 ParsedAttributesWithRange Attributes(AttrFactory);
2036 MaybeParseCXX11Attributes(Attributes);
2037
Douglas Gregor556877c2008-04-13 21:30:24 +00002038 // Parse the 'virtual' keyword.
Alp Toker97650562014-01-10 11:19:30 +00002039 if (TryConsumeToken(tok::kw_virtual))
Douglas Gregor556877c2008-04-13 21:30:24 +00002040 IsVirtual = true;
Douglas Gregor556877c2008-04-13 21:30:24 +00002041
Richard Smith4c96e992013-02-19 23:47:15 +00002042 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2043
Douglas Gregor556877c2008-04-13 21:30:24 +00002044 // Parse an (optional) access specifier.
2045 AccessSpecifier Access = getAccessSpecifierIfPresent();
John McCall553c0792010-01-23 00:46:32 +00002046 if (Access != AS_none)
Douglas Gregor556877c2008-04-13 21:30:24 +00002047 ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +00002048
Richard Smith4c96e992013-02-19 23:47:15 +00002049 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2050
Douglas Gregor556877c2008-04-13 21:30:24 +00002051 // Parse the 'virtual' keyword (again!), in case it came after the
2052 // access specifier.
2053 if (Tok.is(tok::kw_virtual)) {
2054 SourceLocation VirtualLoc = ConsumeToken();
2055 if (IsVirtual) {
2056 // Complain about duplicate 'virtual'
Chris Lattner6d29c102008-11-18 07:48:38 +00002057 Diag(VirtualLoc, diag::err_dup_virtual)
Douglas Gregora771f462010-03-31 17:46:05 +00002058 << FixItHint::CreateRemoval(VirtualLoc);
Douglas Gregor556877c2008-04-13 21:30:24 +00002059 }
2060
2061 IsVirtual = true;
2062 }
2063
Richard Smith4c96e992013-02-19 23:47:15 +00002064 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2065
Douglas Gregor831c93f2008-11-05 20:51:48 +00002066 // Parse the class-name.
David Majnemer51fd8a02015-07-22 23:46:18 +00002067
2068 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
2069 // implementation for VS2013 uses _Atomic as an identifier for one of the
2070 // classes in <atomic>. Treat '_Atomic' to be an identifier when we are
2071 // parsing the class-name for a base specifier.
2072 if (getLangOpts().MSVCCompat && Tok.is(tok::kw__Atomic) &&
2073 NextToken().is(tok::less))
2074 Tok.setKind(tok::identifier);
2075
Douglas Gregord54dfb82009-02-25 23:52:28 +00002076 SourceLocation EndLocation;
David Blaikie1cd50022011-10-25 17:10:12 +00002077 SourceLocation BaseLoc;
2078 TypeResult BaseType = ParseBaseTypeSpecifier(BaseLoc, EndLocation);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00002079 if (BaseType.isInvalid())
Douglas Gregor831c93f2008-11-05 20:51:48 +00002080 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002081
Douglas Gregor752a5952011-01-03 22:36:02 +00002082 // Parse the optional ellipsis (for a pack expansion). The ellipsis is
2083 // actually part of the base-specifier-list grammar productions, but we
2084 // parse it here for convenience.
2085 SourceLocation EllipsisLoc;
Alp Toker97650562014-01-10 11:19:30 +00002086 TryConsumeToken(tok::ellipsis, EllipsisLoc);
2087
Mike Stump11289f42009-09-09 15:08:12 +00002088 // Find the complete source range for the base-specifier.
Douglas Gregord54dfb82009-02-25 23:52:28 +00002089 SourceRange Range(StartLoc, EndLocation);
Mike Stump11289f42009-09-09 15:08:12 +00002090
Douglas Gregor556877c2008-04-13 21:30:24 +00002091 // Notify semantic analysis that we have parsed a complete
2092 // base-specifier.
Richard Smith4c96e992013-02-19 23:47:15 +00002093 return Actions.ActOnBaseSpecifier(ClassDecl, Range, Attributes, IsVirtual,
2094 Access, BaseType.get(), BaseLoc,
2095 EllipsisLoc);
Douglas Gregor556877c2008-04-13 21:30:24 +00002096}
2097
2098/// getAccessSpecifierIfPresent - Determine whether the next token is
2099/// a C++ access-specifier.
2100///
2101/// access-specifier: [C++ class.derived]
2102/// 'private'
2103/// 'protected'
2104/// 'public'
Mike Stump11289f42009-09-09 15:08:12 +00002105AccessSpecifier Parser::getAccessSpecifierIfPresent() const {
Douglas Gregor556877c2008-04-13 21:30:24 +00002106 switch (Tok.getKind()) {
2107 default: return AS_none;
2108 case tok::kw_private: return AS_private;
2109 case tok::kw_protected: return AS_protected;
2110 case tok::kw_public: return AS_public;
2111 }
2112}
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002113
Douglas Gregor433e0532012-04-16 18:27:27 +00002114/// \brief If the given declarator has any parts for which parsing has to be
Richard Smith0b3a4622014-11-13 20:01:57 +00002115/// delayed, e.g., default arguments or an exception-specification, create a
2116/// late-parsed method declaration record to handle the parsing at the end of
2117/// the class definition.
Douglas Gregor433e0532012-04-16 18:27:27 +00002118void Parser::HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
2119 Decl *ThisDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00002120 DeclaratorChunk::FunctionTypeInfo &FTI
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002121 = DeclaratorInfo.getFunctionTypeInfo();
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002122 // If there was a late-parsed exception-specification, we'll need a
2123 // late parse
2124 bool NeedLateParse = FTI.getExceptionSpecType() == EST_Unparsed;
Douglas Gregor433e0532012-04-16 18:27:27 +00002125
Nathan Sidwell5bb231c2015-02-19 14:03:22 +00002126 if (!NeedLateParse) {
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002127 // Look ahead to see if there are any default args
Nathan Sidwell5bb231c2015-02-19 14:03:22 +00002128 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx) {
2129 auto Param = cast<ParmVarDecl>(FTI.Params[ParamIdx].Param);
2130 if (Param->hasUnparsedDefaultArg()) {
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002131 NeedLateParse = true;
2132 break;
2133 }
Nathan Sidwell5bb231c2015-02-19 14:03:22 +00002134 }
2135 }
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002136
2137 if (NeedLateParse) {
Richard Smith0b3a4622014-11-13 20:01:57 +00002138 // Push this method onto the stack of late-parsed method
2139 // declarations.
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002140 auto LateMethod = new LateParsedMethodDeclaration(this, ThisDecl);
Richard Smith0b3a4622014-11-13 20:01:57 +00002141 getCurrentClass().LateParsedDeclarations.push_back(LateMethod);
2142 LateMethod->TemplateScope = getCurScope()->isTemplateParamScope();
2143
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002144 // Stash the exception-specification tokens in the late-pased method.
Richard Smith0b3a4622014-11-13 20:01:57 +00002145 LateMethod->ExceptionSpecTokens = FTI.ExceptionSpecTokens;
Hans Wennborgdcfba332015-10-06 23:40:43 +00002146 FTI.ExceptionSpecTokens = nullptr;
Richard Smith0b3a4622014-11-13 20:01:57 +00002147
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002148 // Push tokens for each parameter. Those that do not have
2149 // defaults will be NULL.
Richard Smith0b3a4622014-11-13 20:01:57 +00002150 LateMethod->DefaultArgs.reserve(FTI.NumParams);
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002151 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx)
Alp Tokerc5350722014-02-26 22:27:52 +00002152 LateMethod->DefaultArgs.push_back(LateParsedDefaultArgument(
Malcolm Parsonsca9d8342016-11-17 21:00:09 +00002153 FTI.Params[ParamIdx].Param,
2154 std::move(FTI.Params[ParamIdx].DefaultArgTokens)));
Eli Friedman3af2a772009-07-22 21:45:50 +00002155 }
2156}
2157
Richard Smith89645bc2013-01-02 12:01:23 +00002158/// isCXX11VirtSpecifier - Determine whether the given token is a C++11
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002159/// virt-specifier.
2160///
2161/// virt-specifier:
2162/// override
2163/// final
Andrey Bokhanko276055b2016-07-29 10:42:48 +00002164/// __final
Richard Smith89645bc2013-01-02 12:01:23 +00002165VirtSpecifiers::Specifier Parser::isCXX11VirtSpecifier(const Token &Tok) const {
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002166 if (!getLangOpts().CPlusPlus || Tok.isNot(tok::identifier))
Anders Carlsson4b63d0e2011-01-22 16:56:46 +00002167 return VirtSpecifiers::VS_None;
2168
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002169 IdentifierInfo *II = Tok.getIdentifierInfo();
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002170
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002171 // Initialize the contextual keywords.
2172 if (!Ident_final) {
2173 Ident_final = &PP.getIdentifierTable().get("final");
Andrey Bokhanko276055b2016-07-29 10:42:48 +00002174 if (getLangOpts().GNUKeywords)
2175 Ident_GNU_final = &PP.getIdentifierTable().get("__final");
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002176 if (getLangOpts().MicrosoftExt)
2177 Ident_sealed = &PP.getIdentifierTable().get("sealed");
2178 Ident_override = &PP.getIdentifierTable().get("override");
Anders Carlsson56104902011-01-17 03:05:47 +00002179 }
2180
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002181 if (II == Ident_override)
2182 return VirtSpecifiers::VS_Override;
2183
2184 if (II == Ident_sealed)
2185 return VirtSpecifiers::VS_Sealed;
2186
2187 if (II == Ident_final)
2188 return VirtSpecifiers::VS_Final;
2189
Andrey Bokhanko276055b2016-07-29 10:42:48 +00002190 if (II == Ident_GNU_final)
2191 return VirtSpecifiers::VS_GNU_Final;
2192
Anders Carlsson56104902011-01-17 03:05:47 +00002193 return VirtSpecifiers::VS_None;
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002194}
2195
Richard Smith89645bc2013-01-02 12:01:23 +00002196/// ParseOptionalCXX11VirtSpecifierSeq - Parse a virt-specifier-seq.
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002197///
2198/// virt-specifier-seq:
2199/// virt-specifier
2200/// virt-specifier-seq virt-specifier
Richard Smith89645bc2013-01-02 12:01:23 +00002201void Parser::ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS,
Richard Smith3d1a94c2014-08-12 00:22:39 +00002202 bool IsInterface,
2203 SourceLocation FriendLoc) {
Anders Carlsson56104902011-01-17 03:05:47 +00002204 while (true) {
Richard Smith89645bc2013-01-02 12:01:23 +00002205 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
Anders Carlsson56104902011-01-17 03:05:47 +00002206 if (Specifier == VirtSpecifiers::VS_None)
2207 return;
2208
Richard Smith3d1a94c2014-08-12 00:22:39 +00002209 if (FriendLoc.isValid()) {
2210 Diag(Tok.getLocation(), diag::err_friend_decl_spec)
2211 << VirtSpecifiers::getSpecifierName(Specifier)
2212 << FixItHint::CreateRemoval(Tok.getLocation())
2213 << SourceRange(FriendLoc, FriendLoc);
2214 ConsumeToken();
2215 continue;
2216 }
2217
Anders Carlsson56104902011-01-17 03:05:47 +00002218 // C++ [class.mem]p8:
2219 // A virt-specifier-seq shall contain at most one of each virt-specifier.
Craig Topper161e4db2014-05-21 06:02:52 +00002220 const char *PrevSpec = nullptr;
Anders Carlssonf2ca3892011-01-22 15:58:16 +00002221 if (VS.SetSpecifier(Specifier, Tok.getLocation(), PrevSpec))
Anders Carlsson56104902011-01-17 03:05:47 +00002222 Diag(Tok.getLocation(), diag::err_duplicate_virt_specifier)
2223 << PrevSpec
2224 << FixItHint::CreateRemoval(Tok.getLocation());
2225
David Majnemera5433082013-10-18 00:33:31 +00002226 if (IsInterface && (Specifier == VirtSpecifiers::VS_Final ||
2227 Specifier == VirtSpecifiers::VS_Sealed)) {
John McCalldb632ac2012-09-25 07:32:39 +00002228 Diag(Tok.getLocation(), diag::err_override_control_interface)
2229 << VirtSpecifiers::getSpecifierName(Specifier);
David Majnemera5433082013-10-18 00:33:31 +00002230 } else if (Specifier == VirtSpecifiers::VS_Sealed) {
2231 Diag(Tok.getLocation(), diag::ext_ms_sealed_keyword);
Andrey Bokhanko276055b2016-07-29 10:42:48 +00002232 } else if (Specifier == VirtSpecifiers::VS_GNU_Final) {
2233 Diag(Tok.getLocation(), diag::ext_warn_gnu_final);
John McCalldb632ac2012-09-25 07:32:39 +00002234 } else {
David Majnemera5433082013-10-18 00:33:31 +00002235 Diag(Tok.getLocation(),
2236 getLangOpts().CPlusPlus11
2237 ? diag::warn_cxx98_compat_override_control_keyword
2238 : diag::ext_override_control_keyword)
2239 << VirtSpecifiers::getSpecifierName(Specifier);
John McCalldb632ac2012-09-25 07:32:39 +00002240 }
Anders Carlsson56104902011-01-17 03:05:47 +00002241 ConsumeToken();
2242 }
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002243}
2244
Richard Smith89645bc2013-01-02 12:01:23 +00002245/// isCXX11FinalKeyword - Determine whether the next token is a C++11
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002246/// 'final' or Microsoft 'sealed' contextual keyword.
Richard Smith89645bc2013-01-02 12:01:23 +00002247bool Parser::isCXX11FinalKeyword() const {
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002248 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
2249 return Specifier == VirtSpecifiers::VS_Final ||
Andrey Bokhanko276055b2016-07-29 10:42:48 +00002250 Specifier == VirtSpecifiers::VS_GNU_Final ||
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002251 Specifier == VirtSpecifiers::VS_Sealed;
Anders Carlsson4b63d0e2011-01-22 16:56:46 +00002252}
2253
Richard Smith72553fc2014-01-23 23:53:27 +00002254/// \brief Parse a C++ member-declarator up to, but not including, the optional
2255/// brace-or-equal-initializer or pure-specifier.
Nico Weberd89e6f72015-01-16 19:34:13 +00002256bool Parser::ParseCXXMemberDeclaratorBeforeInitializer(
Richard Smith72553fc2014-01-23 23:53:27 +00002257 Declarator &DeclaratorInfo, VirtSpecifiers &VS, ExprResult &BitfieldSize,
2258 LateParsedAttrList &LateParsedAttrs) {
2259 // member-declarator:
2260 // declarator pure-specifier[opt]
2261 // declarator brace-or-equal-initializer[opt]
2262 // identifier[opt] ':' constant-expression
Serge Pavlov458ea762014-07-16 05:16:52 +00002263 if (Tok.isNot(tok::colon))
Richard Smith72553fc2014-01-23 23:53:27 +00002264 ParseDeclarator(DeclaratorInfo);
Richard Smith3d1a94c2014-08-12 00:22:39 +00002265 else
2266 DeclaratorInfo.SetIdentifier(nullptr, Tok.getLocation());
Richard Smith72553fc2014-01-23 23:53:27 +00002267
2268 if (!DeclaratorInfo.isFunctionDeclarator() && TryConsumeToken(tok::colon)) {
Richard Smith3d1a94c2014-08-12 00:22:39 +00002269 assert(DeclaratorInfo.isPastIdentifier() &&
2270 "don't know where identifier would go yet?");
Richard Smith72553fc2014-01-23 23:53:27 +00002271 BitfieldSize = ParseConstantExpression();
2272 if (BitfieldSize.isInvalid())
2273 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002274 } else {
Richard Smith3d1a94c2014-08-12 00:22:39 +00002275 ParseOptionalCXX11VirtSpecifierSeq(
2276 VS, getCurrentClass().IsInterface,
2277 DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002278 if (!VS.isUnset())
2279 MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo, VS);
2280 }
Richard Smith72553fc2014-01-23 23:53:27 +00002281
2282 // If a simple-asm-expr is present, parse it.
2283 if (Tok.is(tok::kw_asm)) {
2284 SourceLocation Loc;
2285 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
2286 if (AsmLabel.isInvalid())
2287 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2288
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002289 DeclaratorInfo.setAsmLabel(AsmLabel.get());
Richard Smith72553fc2014-01-23 23:53:27 +00002290 DeclaratorInfo.SetRangeEnd(Loc);
2291 }
2292
2293 // If attributes exist after the declarator, but before an '{', parse them.
2294 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
Richard Smith4b5a9492014-01-24 22:34:35 +00002295
2296 // For compatibility with code written to older Clang, also accept a
2297 // virt-specifier *after* the GNU attributes.
Aaron Ballman5d153e32014-08-04 17:03:51 +00002298 if (BitfieldSize.isUnset() && VS.isUnset()) {
Richard Smith3d1a94c2014-08-12 00:22:39 +00002299 ParseOptionalCXX11VirtSpecifierSeq(
2300 VS, getCurrentClass().IsInterface,
2301 DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
Aaron Ballman5d153e32014-08-04 17:03:51 +00002302 if (!VS.isUnset()) {
2303 // If we saw any GNU-style attributes that are known to GCC followed by a
2304 // virt-specifier, issue a GCC-compat warning.
2305 const AttributeList *Attr = DeclaratorInfo.getAttributes();
2306 while (Attr) {
2307 if (Attr->isKnownToGCC() && !Attr->isCXX11Attribute())
2308 Diag(Attr->getLoc(), diag::warn_gcc_attribute_location);
2309 Attr = Attr->getNext();
2310 }
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002311 MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo, VS);
Aaron Ballman5d153e32014-08-04 17:03:51 +00002312 }
2313 }
Nico Weberd89e6f72015-01-16 19:34:13 +00002314
2315 // If this has neither a name nor a bit width, something has gone seriously
2316 // wrong. Skip until the semi-colon or }.
2317 if (!DeclaratorInfo.hasName() && BitfieldSize.isUnset()) {
2318 // If so, skip until the semi-colon or a }.
2319 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2320 return true;
2321 }
2322 return false;
Richard Smith72553fc2014-01-23 23:53:27 +00002323}
2324
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002325/// \brief Look for declaration specifiers possibly occurring after C++11
2326/// virt-specifier-seq and diagnose them.
2327void Parser::MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(
2328 Declarator &D,
2329 VirtSpecifiers &VS) {
2330 DeclSpec DS(AttrFactory);
2331
2332 // GNU-style and C++11 attributes are not allowed here, but they will be
2333 // handled by the caller. Diagnose everything else.
2334 ParseTypeQualifierListOpt(DS, AR_NoAttributesParsed, false);
2335 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;
David Blaikieefdccaa2016-01-15 23:43:34 +00002476 if (ParseUnqualifiedId(SS, false, true, true, nullptr, TemplateKWLoc,
2477 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 Smith6f1daa42016-12-16 00:58:48 +00002490 getCurScope(), AS, /*UsingLoc*/SourceLocation(), SS, Name,
2491 /*AttrList*/nullptr, /*TypenameLoc*/SourceLocation())));
John McCalla0097262009-12-11 02:10:03 +00002492 }
2493 }
2494
Aaron Ballmane7c544d2014-08-04 20:28:35 +00002495 // static_assert-declaration. A templated static_assert declaration is
2496 // diagnosed in Parser::ParseSingleDeclarationAfterTemplate.
2497 if (!TemplateInfo.Kind &&
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002498 Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert)) {
Chris Lattner49836b42009-04-02 04:16:50 +00002499 SourceLocation DeclEnd;
Alexey Bataev05c25d62015-07-31 08:42:25 +00002500 return DeclGroupPtrTy::make(
2501 DeclGroupRef(ParseStaticAssertDeclaration(DeclEnd)));
Chris Lattner5bbb3c82009-03-29 16:50:03 +00002502 }
Mike Stump11289f42009-09-09 15:08:12 +00002503
Chris Lattner5bbb3c82009-03-29 16:50:03 +00002504 if (Tok.is(tok::kw_template)) {
Mike Stump11289f42009-09-09 15:08:12 +00002505 assert(!TemplateInfo.TemplateParams &&
Douglas Gregor3447e762009-08-20 22:52:58 +00002506 "Nested template improperly parsed?");
Chris Lattner49836b42009-04-02 04:16:50 +00002507 SourceLocation DeclEnd;
Alexey Bataev05c25d62015-07-31 08:42:25 +00002508 return DeclGroupPtrTy::make(
2509 DeclGroupRef(ParseDeclarationStartingWithTemplate(
2510 Declarator::MemberContext, DeclEnd, AS, AccessAttrs)));
Chris Lattner5bbb3c82009-03-29 16:50:03 +00002511 }
Anders Carlssondfbbdf62009-03-26 00:52:18 +00002512
Chris Lattnerd19c1c02008-12-18 01:12:00 +00002513 // Handle: member-declaration ::= '__extension__' member-declaration
2514 if (Tok.is(tok::kw___extension__)) {
2515 // __extension__ silences extension warnings in the subexpression.
2516 ExtensionRAIIObject O(Diags); // Use RAII to do this.
2517 ConsumeToken();
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00002518 return ParseCXXClassMemberDeclaration(AS, AccessAttrs,
2519 TemplateInfo, TemplateDiags);
Chris Lattnerd19c1c02008-12-18 01:12:00 +00002520 }
Douglas Gregorfec52632009-06-20 00:51:54 +00002521
John McCall084e83d2011-03-24 11:26:52 +00002522 ParsedAttributesWithRange attrs(AttrFactory);
Michael Handdc016d2012-11-28 23:17:40 +00002523 ParsedAttributesWithRange FnAttrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00002524 // Optional C++11 attribute-specifier
2525 MaybeParseCXX11Attributes(attrs);
Michael Handdc016d2012-11-28 23:17:40 +00002526 // We need to keep these attributes for future diagnostic
2527 // before they are taken over by declaration specifier.
2528 FnAttrs.addAll(attrs.getList());
2529 FnAttrs.Range = attrs.Range;
2530
John McCall53fa7142010-12-24 02:08:15 +00002531 MaybeParseMicrosoftAttributes(attrs);
Alexis Hunt96d5c762009-11-21 08:43:09 +00002532
Douglas Gregorfec52632009-06-20 00:51:54 +00002533 if (Tok.is(tok::kw_using)) {
John McCall53fa7142010-12-24 02:08:15 +00002534 ProhibitAttributes(attrs);
Mike Stump11289f42009-09-09 15:08:12 +00002535
Douglas Gregorfec52632009-06-20 00:51:54 +00002536 // Eat 'using'.
2537 SourceLocation UsingLoc = ConsumeToken();
2538
2539 if (Tok.is(tok::kw_namespace)) {
2540 Diag(UsingLoc, diag::err_using_namespace_in_class);
Alexey Bataevee6507d2013-11-18 08:17:37 +00002541 SkipUntil(tok::semi, StopBeforeMatch);
David Blaikie0403cb12016-01-15 23:43:25 +00002542 return nullptr;
Douglas Gregorfec52632009-06-20 00:51:54 +00002543 }
Alexey Bataev05c25d62015-07-31 08:42:25 +00002544 SourceLocation DeclEnd;
2545 // Otherwise, it must be a using-declaration or an alias-declaration.
Richard Smith6f1daa42016-12-16 00:58:48 +00002546 return ParseUsingDeclaration(Declarator::MemberContext, TemplateInfo,
2547 UsingLoc, DeclEnd, AS);
Douglas Gregorfec52632009-06-20 00:51:54 +00002548 }
2549
DeLesley Hutchinsbd2ee132012-03-02 22:12:59 +00002550 // Hold late-parsed attributes so we can attach a Decl to them later.
2551 LateParsedAttrList CommonLateParsedAttrs;
2552
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002553 // decl-specifier-seq:
2554 // Parse the common declaration-specifiers piece.
John McCall796c2a52010-07-16 08:13:16 +00002555 ParsingDeclSpec DS(*this, TemplateDiags);
John McCall53fa7142010-12-24 02:08:15 +00002556 DS.takeAttributesFrom(attrs);
Richard Smith45855df2012-05-09 08:23:23 +00002557 if (MalformedTypeSpec)
2558 DS.SetTypeSpecError();
Richard Smith72553fc2014-01-23 23:53:27 +00002559
Serge Pavlov458ea762014-07-16 05:16:52 +00002560 ParseDeclarationSpecifiers(DS, TemplateInfo, AS, DSC_class,
2561 &CommonLateParsedAttrs);
2562
2563 // Turn off colon protection that was set for declspec.
2564 X.restore();
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002565
Richard Smith404dfb42013-11-19 22:47:36 +00002566 // If we had a free-standing type definition with a missing semicolon, we
2567 // may get this far before the problem becomes obvious.
2568 if (DS.hasTagDefinition() &&
2569 TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate &&
2570 DiagnoseMissingSemiAfterTagDefinition(DS, AS, DSC_class,
2571 &CommonLateParsedAttrs))
David Blaikie0403cb12016-01-15 23:43:25 +00002572 return nullptr;
Richard Smith404dfb42013-11-19 22:47:36 +00002573
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002574 MultiTemplateParamsArg TemplateParams(
Craig Topper161e4db2014-05-21 06:02:52 +00002575 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->data()
2576 : nullptr,
John McCall11083da2009-09-16 22:47:08 +00002577 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->size() : 0);
2578
Alp Toker35d87032013-12-30 23:29:50 +00002579 if (TryConsumeToken(tok::semi)) {
Michael Handdc016d2012-11-28 23:17:40 +00002580 if (DS.isFriendSpecified())
2581 ProhibitAttributes(FnAttrs);
2582
Nico Weber7b837f52016-01-28 19:25:00 +00002583 RecordDecl *AnonRecord = nullptr;
2584 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(
2585 getCurScope(), AS, DS, TemplateParams, false, AnonRecord);
John McCall796c2a52010-07-16 08:13:16 +00002586 DS.complete(TheDecl);
Nico Weber7b837f52016-01-28 19:25:00 +00002587 if (AnonRecord) {
2588 Decl* decls[] = {AnonRecord, TheDecl};
2589 return Actions.BuildDeclaratorGroup(decls, /*TypeMayContainAuto=*/false);
2590 }
2591 return Actions.ConvertDeclToDeclGroup(TheDecl);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002592 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002593
John McCall28a6aea2009-11-04 02:18:39 +00002594 ParsingDeclarator DeclaratorInfo(*this, DS, Declarator::MemberContext);
Nico Weber24b2a822011-01-28 06:07:34 +00002595 VirtSpecifiers VS;
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002596
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002597 // Hold late-parsed attributes so we can attach a Decl to them later.
2598 LateParsedAttrList LateParsedAttrs;
2599
Douglas Gregor50cefbf2011-10-17 17:09:53 +00002600 SourceLocation EqualLoc;
Richard Smith9ba0fec2015-06-30 01:28:56 +00002601 SourceLocation PureSpecLoc;
2602
Yaron Keren180c1672015-06-30 07:35:19 +00002603 auto TryConsumePureSpecifier = [&] (bool AllowDefinition) {
Richard Smith9ba0fec2015-06-30 01:28:56 +00002604 if (Tok.isNot(tok::equal))
2605 return false;
2606
2607 auto &Zero = NextToken();
2608 SmallString<8> Buffer;
2609 if (Zero.isNot(tok::numeric_constant) || Zero.getLength() != 1 ||
2610 PP.getSpelling(Zero, Buffer) != "0")
2611 return false;
2612
2613 auto &After = GetLookAheadToken(2);
2614 if (!After.isOneOf(tok::semi, tok::comma) &&
2615 !(AllowDefinition &&
2616 After.isOneOf(tok::l_brace, tok::colon, tok::kw_try)))
2617 return false;
2618
2619 EqualLoc = ConsumeToken();
2620 PureSpecLoc = ConsumeToken();
2621 return true;
2622 };
Chris Lattner17c3b1f2009-12-10 01:59:24 +00002623
Richard Smith72553fc2014-01-23 23:53:27 +00002624 SmallVector<Decl *, 8> DeclsInGroup;
2625 ExprResult BitfieldSize;
2626 bool ExpectSemi = true;
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002627
Richard Smith72553fc2014-01-23 23:53:27 +00002628 // Parse the first declarator.
Nico Weberd89e6f72015-01-16 19:34:13 +00002629 if (ParseCXXMemberDeclaratorBeforeInitializer(
2630 DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs)) {
Richard Smith72553fc2014-01-23 23:53:27 +00002631 TryConsumeToken(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002632 return nullptr;
Richard Smith72553fc2014-01-23 23:53:27 +00002633 }
John Thompson5bc5cbe2009-11-25 22:58:06 +00002634
Richard Smith72553fc2014-01-23 23:53:27 +00002635 // Check for a member function definition.
Richard Smith4b5a9492014-01-24 22:34:35 +00002636 if (BitfieldSize.isUnset()) {
Richard Smith72553fc2014-01-23 23:53:27 +00002637 // MSVC permits pure specifier on inline functions defined at class scope.
Francois Pichet3abc9b82011-05-11 02:14:46 +00002638 // Hence check for =0 before checking for function definition.
Richard Smith9ba0fec2015-06-30 01:28:56 +00002639 if (getLangOpts().MicrosoftExt && DeclaratorInfo.isDeclarationOfFunction())
2640 TryConsumePureSpecifier(/*AllowDefinition*/ true);
Francois Pichet3abc9b82011-05-11 02:14:46 +00002641
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00002642 FunctionDefinitionKind DefinitionKind = FDK_Declaration;
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002643 // function-definition:
Richard Smith938f40b2011-06-11 17:19:42 +00002644 //
2645 // In C++11, a non-function declarator followed by an open brace is a
2646 // braced-init-list for an in-class member initialization, not an
2647 // erroneous function definition.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002648 if (Tok.is(tok::l_brace) && !getLangOpts().CPlusPlus11) {
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00002649 DefinitionKind = FDK_Definition;
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002650 } else if (DeclaratorInfo.isFunctionDeclarator()) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002651 if (Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try)) {
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00002652 DefinitionKind = FDK_Definition;
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002653 } else if (Tok.is(tok::equal)) {
2654 const Token &KW = NextToken();
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00002655 if (KW.is(tok::kw_default))
2656 DefinitionKind = FDK_Defaulted;
2657 else if (KW.is(tok::kw_delete))
2658 DefinitionKind = FDK_Deleted;
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002659 }
2660 }
Eli Bendersky41842222015-03-23 23:49:41 +00002661 DeclaratorInfo.setFunctionDefinitionKind(DefinitionKind);
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002662
Michael Handdc016d2012-11-28 23:17:40 +00002663 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
2664 // to a friend declaration, that declaration shall be a definition.
2665 if (DeclaratorInfo.isFunctionDeclarator() &&
2666 DefinitionKind != FDK_Definition && DS.isFriendSpecified()) {
2667 // Diagnose attributes that appear before decl specifier:
2668 // [[]] friend int foo();
2669 ProhibitAttributes(FnAttrs);
2670 }
2671
Nico Webera7f137d2015-01-16 19:35:01 +00002672 if (DefinitionKind != FDK_Declaration) {
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002673 if (!DeclaratorInfo.isFunctionDeclarator()) {
Richard Trieu0d730542012-01-21 02:59:18 +00002674 Diag(DeclaratorInfo.getIdentifierLoc(), diag::err_func_def_no_params);
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002675 ConsumeBrace();
Alexey Bataevee6507d2013-11-18 08:17:37 +00002676 SkipUntil(tok::r_brace);
Michael Handdc016d2012-11-28 23:17:40 +00002677
Douglas Gregor8a4db832011-01-19 16:41:58 +00002678 // Consume the optional ';'
Alp Toker35d87032013-12-30 23:29:50 +00002679 TryConsumeToken(tok::semi);
2680
David Blaikie0403cb12016-01-15 23:43:25 +00002681 return nullptr;
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002682 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002683
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002684 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
Richard Trieu0d730542012-01-21 02:59:18 +00002685 Diag(DeclaratorInfo.getIdentifierLoc(),
2686 diag::err_function_declared_typedef);
Douglas Gregor8a4db832011-01-19 16:41:58 +00002687
Richard Smith2603b092012-11-15 22:54:20 +00002688 // Recover by treating the 'typedef' as spurious.
2689 DS.ClearStorageClassSpecs();
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002690 }
2691
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002692 Decl *FunDecl =
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00002693 ParseCXXInlineMethodDef(AS, AccessAttrs, DeclaratorInfo, TemplateInfo,
Richard Smith9ba0fec2015-06-30 01:28:56 +00002694 VS, PureSpecLoc);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002695
David Majnemer23252a32013-08-01 04:22:55 +00002696 if (FunDecl) {
2697 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i) {
2698 CommonLateParsedAttrs[i]->addDecl(FunDecl);
2699 }
2700 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i) {
2701 LateParsedAttrs[i]->addDecl(FunDecl);
2702 }
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002703 }
2704 LateParsedAttrs.clear();
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002705
2706 // Consume the ';' - it's optional unless we have a delete or default
Richard Trieu2f7dc462012-05-16 19:04:59 +00002707 if (Tok.is(tok::semi))
Richard Smith87f5dc52012-07-23 05:45:25 +00002708 ConsumeExtraSemi(AfterMemberFunctionDefinition);
Douglas Gregor8a4db832011-01-19 16:41:58 +00002709
Alexey Bataev05c25d62015-07-31 08:42:25 +00002710 return DeclGroupPtrTy::make(DeclGroupRef(FunDecl));
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002711 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002712 }
2713
2714 // member-declarator-list:
2715 // member-declarator
2716 // member-declarator-list ',' member-declarator
2717
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002718 while (1) {
Richard Smith2b013182012-06-10 03:12:00 +00002719 InClassInitStyle HasInClassInit = ICIS_NoInit;
Richard Smith9ba0fec2015-06-30 01:28:56 +00002720 bool HasStaticInitializer = false;
2721 if (Tok.isOneOf(tok::equal, tok::l_brace) && PureSpecLoc.isInvalid()) {
Richard Smith938f40b2011-06-11 17:19:42 +00002722 if (BitfieldSize.get()) {
2723 Diag(Tok, diag::err_bitfield_member_init);
Alexey Bataevee6507d2013-11-18 08:17:37 +00002724 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
Richard Smith9ba0fec2015-06-30 01:28:56 +00002725 } else if (DeclaratorInfo.isDeclarationOfFunction()) {
2726 // It's a pure-specifier.
2727 if (!TryConsumePureSpecifier(/*AllowFunctionDefinition*/ false))
2728 // Parse it as an expression so that Sema can diagnose it.
2729 HasStaticInitializer = true;
2730 } else if (DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2731 DeclSpec::SCS_static &&
2732 DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2733 DeclSpec::SCS_typedef &&
2734 !DS.isFriendSpecified()) {
2735 // It's a default member initializer.
2736 HasInClassInit = Tok.is(tok::equal) ? ICIS_CopyInit : ICIS_ListInit;
Richard Smith938f40b2011-06-11 17:19:42 +00002737 } else {
Richard Smith9ba0fec2015-06-30 01:28:56 +00002738 HasStaticInitializer = true;
Richard Smith938f40b2011-06-11 17:19:42 +00002739 }
2740 }
2741
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002742 // NOTE: If Sema is the Action module and declarator is an instance field,
Chris Lattner5bbb3c82009-03-29 16:50:03 +00002743 // this call will *not* return the created decl; It will return null.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002744 // See Sema::ActOnCXXMemberDeclarator for details.
John McCall07e91c02009-08-06 02:15:43 +00002745
Craig Topper161e4db2014-05-21 06:02:52 +00002746 NamedDecl *ThisDecl = nullptr;
John McCall07e91c02009-08-06 02:15:43 +00002747 if (DS.isFriendSpecified()) {
Richard Smith72553fc2014-01-23 23:53:27 +00002748 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
Michael Handdc016d2012-11-28 23:17:40 +00002749 // to a friend declaration, that declaration shall be a definition.
2750 //
Richard Smith72553fc2014-01-23 23:53:27 +00002751 // Diagnose attributes that appear in a friend member function declarator:
2752 // friend int foo [[]] ();
Michael Handdc016d2012-11-28 23:17:40 +00002753 SmallVector<SourceRange, 4> Ranges;
2754 DeclaratorInfo.getCXX11AttributeRanges(Ranges);
Richard Smith72553fc2014-01-23 23:53:27 +00002755 for (SmallVectorImpl<SourceRange>::iterator I = Ranges.begin(),
2756 E = Ranges.end(); I != E; ++I)
2757 Diag((*I).getBegin(), diag::err_attributes_not_allowed) << *I;
Michael Handdc016d2012-11-28 23:17:40 +00002758
Douglas Gregor0be31a22010-07-02 17:43:08 +00002759 ThisDecl = Actions.ActOnFriendFunctionDecl(getCurScope(), DeclaratorInfo,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002760 TemplateParams);
Douglas Gregor3447e762009-08-20 22:52:58 +00002761 } else {
Douglas Gregor0be31a22010-07-02 17:43:08 +00002762 ThisDecl = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS,
John McCall07e91c02009-08-06 02:15:43 +00002763 DeclaratorInfo,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002764 TemplateParams,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002765 BitfieldSize.get(),
Richard Smith2b013182012-06-10 03:12:00 +00002766 VS, HasInClassInit);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002767
2768 if (VarTemplateDecl *VT =
Craig Topper161e4db2014-05-21 06:02:52 +00002769 ThisDecl ? dyn_cast<VarTemplateDecl>(ThisDecl) : nullptr)
Larisse Voufo39a1e502013-08-06 01:03:05 +00002770 // Re-direct this decl to refer to the templated decl so that we can
2771 // initialize it.
2772 ThisDecl = VT->getTemplatedDecl();
2773
David Majnemer23252a32013-08-01 04:22:55 +00002774 if (ThisDecl && AccessAttrs)
Richard Smithf8a75c32013-08-29 00:47:48 +00002775 Actions.ProcessDeclAttributeList(getCurScope(), ThisDecl, AccessAttrs);
Douglas Gregor3447e762009-08-20 22:52:58 +00002776 }
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002777
Richard Smith9ba0fec2015-06-30 01:28:56 +00002778 // Error recovery might have converted a non-static member into a static
2779 // member.
David Blaikie35506f82013-01-30 01:22:18 +00002780 if (HasInClassInit != ICIS_NoInit &&
Richard Smith9ba0fec2015-06-30 01:28:56 +00002781 DeclaratorInfo.getDeclSpec().getStorageClassSpec() ==
2782 DeclSpec::SCS_static) {
2783 HasInClassInit = ICIS_NoInit;
2784 HasStaticInitializer = true;
2785 }
2786
2787 if (ThisDecl && PureSpecLoc.isValid())
2788 Actions.ActOnPureSpecifier(ThisDecl, PureSpecLoc);
2789
2790 // Handle the initializer.
2791 if (HasInClassInit != ICIS_NoInit) {
Douglas Gregor728d00b2011-10-10 14:49:18 +00002792 // The initializer was deferred; parse it and cache the tokens.
David Majnemer23252a32013-08-01 04:22:55 +00002793 Diag(Tok, getLangOpts().CPlusPlus11
2794 ? diag::warn_cxx98_compat_nonstatic_member_init
2795 : diag::ext_nonstatic_member_init);
Richard Smith5d164bc2011-10-15 05:09:34 +00002796
Richard Smith938f40b2011-06-11 17:19:42 +00002797 if (DeclaratorInfo.isArrayOfUnknownBound()) {
Richard Smith2b013182012-06-10 03:12:00 +00002798 // C++11 [dcl.array]p3: An array bound may also be omitted when the
2799 // declarator is followed by an initializer.
Richard Smith938f40b2011-06-11 17:19:42 +00002800 //
2801 // A brace-or-equal-initializer for a member-declarator is not an
David Blaikiecdd91db2012-02-14 09:00:46 +00002802 // initializer in the grammar, so this is ill-formed.
Richard Smith938f40b2011-06-11 17:19:42 +00002803 Diag(Tok, diag::err_incomplete_array_member_init);
Alexey Bataevee6507d2013-11-18 08:17:37 +00002804 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
David Majnemer23252a32013-08-01 04:22:55 +00002805
2806 // Avoid later warnings about a class member of incomplete type.
David Blaikiecdd91db2012-02-14 09:00:46 +00002807 if (ThisDecl)
David Blaikiecdd91db2012-02-14 09:00:46 +00002808 ThisDecl->setInvalidDecl();
Richard Smith938f40b2011-06-11 17:19:42 +00002809 } else
2810 ParseCXXNonStaticMemberInitializer(ThisDecl);
Richard Smith9ba0fec2015-06-30 01:28:56 +00002811 } else if (HasStaticInitializer) {
Douglas Gregor728d00b2011-10-10 14:49:18 +00002812 // Normal initializer.
Richard Smith9ba0fec2015-06-30 01:28:56 +00002813 ExprResult Init = ParseCXXMemberInitializer(
2814 ThisDecl, DeclaratorInfo.isDeclarationOfFunction(), EqualLoc);
David Majnemer23252a32013-08-01 04:22:55 +00002815
Douglas Gregor728d00b2011-10-10 14:49:18 +00002816 if (Init.isInvalid())
Alexey Bataevee6507d2013-11-18 08:17:37 +00002817 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
Douglas Gregor728d00b2011-10-10 14:49:18 +00002818 else if (ThisDecl)
Sebastian Redleef474c2012-02-22 10:50:08 +00002819 Actions.AddInitializerToDecl(ThisDecl, Init.get(), EqualLoc.isInvalid(),
Richard Smith74aeef52013-04-26 16:15:35 +00002820 DS.containsPlaceholderType());
David Majnemer23252a32013-08-01 04:22:55 +00002821 } else if (ThisDecl && DS.getStorageClassSpec() == DeclSpec::SCS_static)
Douglas Gregor728d00b2011-10-10 14:49:18 +00002822 // No initializer.
Richard Smith74aeef52013-04-26 16:15:35 +00002823 Actions.ActOnUninitializedDecl(ThisDecl, DS.containsPlaceholderType());
David Majnemer23252a32013-08-01 04:22:55 +00002824
Douglas Gregor728d00b2011-10-10 14:49:18 +00002825 if (ThisDecl) {
David Majnemer23252a32013-08-01 04:22:55 +00002826 if (!ThisDecl->isInvalidDecl()) {
2827 // Set the Decl for any late parsed attributes
2828 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i)
2829 CommonLateParsedAttrs[i]->addDecl(ThisDecl);
2830
2831 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i)
2832 LateParsedAttrs[i]->addDecl(ThisDecl);
2833 }
Douglas Gregor728d00b2011-10-10 14:49:18 +00002834 Actions.FinalizeDeclaration(ThisDecl);
2835 DeclsInGroup.push_back(ThisDecl);
David Majnemer23252a32013-08-01 04:22:55 +00002836
2837 if (DeclaratorInfo.isFunctionDeclarator() &&
2838 DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2839 DeclSpec::SCS_typedef)
2840 HandleMemberFunctionDeclDelays(DeclaratorInfo, ThisDecl);
Douglas Gregor728d00b2011-10-10 14:49:18 +00002841 }
David Majnemer23252a32013-08-01 04:22:55 +00002842 LateParsedAttrs.clear();
Douglas Gregor728d00b2011-10-10 14:49:18 +00002843
2844 DeclaratorInfo.complete(ThisDecl);
Richard Smith938f40b2011-06-11 17:19:42 +00002845
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002846 // If we don't have a comma, it is either the end of the list (a ';')
2847 // or an error, bail out.
Alp Toker094e5212014-01-05 03:27:11 +00002848 SourceLocation CommaLoc;
2849 if (!TryConsumeToken(tok::comma, CommaLoc))
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002850 break;
Mike Stump11289f42009-09-09 15:08:12 +00002851
Richard Smithc8a79032012-01-09 22:31:44 +00002852 if (Tok.isAtStartOfLine() &&
2853 !MightBeDeclarator(Declarator::MemberContext)) {
2854 // This comma was followed by a line-break and something which can't be
2855 // the start of a declarator. The comma was probably a typo for a
2856 // semicolon.
2857 Diag(CommaLoc, diag::err_expected_semi_declaration)
2858 << FixItHint::CreateReplacement(CommaLoc, ";");
2859 ExpectSemi = false;
2860 break;
2861 }
Mike Stump11289f42009-09-09 15:08:12 +00002862
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002863 // Parse the next declarator.
2864 DeclaratorInfo.clear();
Nico Weber24b2a822011-01-28 06:07:34 +00002865 VS.clear();
Nico Weberf56c85b2015-01-17 02:26:40 +00002866 BitfieldSize = ExprResult(/*Invalid=*/false);
Richard Smith9ba0fec2015-06-30 01:28:56 +00002867 EqualLoc = PureSpecLoc = SourceLocation();
Richard Smith8d06f422012-01-12 23:53:29 +00002868 DeclaratorInfo.setCommaLoc(CommaLoc);
Mike Stump11289f42009-09-09 15:08:12 +00002869
Richard Smith72553fc2014-01-23 23:53:27 +00002870 // GNU attributes are allowed before the second and subsequent declarator.
John McCall53fa7142010-12-24 02:08:15 +00002871 MaybeParseGNUAttributes(DeclaratorInfo);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002872
Nico Weberd89e6f72015-01-16 19:34:13 +00002873 if (ParseCXXMemberDeclaratorBeforeInitializer(
2874 DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs))
2875 break;
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002876 }
2877
Richard Smithc8a79032012-01-09 22:31:44 +00002878 if (ExpectSemi &&
2879 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list)) {
Chris Lattner916dbf12010-02-02 00:43:15 +00002880 // Skip to end of block or statement.
Alexey Bataevee6507d2013-11-18 08:17:37 +00002881 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Chris Lattner916dbf12010-02-02 00:43:15 +00002882 // If we stopped at a ';', eat it.
Alp Toker35d87032013-12-30 23:29:50 +00002883 TryConsumeToken(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002884 return nullptr;
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002885 }
2886
Alexey Bataev05c25d62015-07-31 08:42:25 +00002887 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002888}
2889
Richard Smith9ba0fec2015-06-30 01:28:56 +00002890/// ParseCXXMemberInitializer - Parse the brace-or-equal-initializer.
2891/// Also detect and reject any attempted defaulted/deleted function definition.
2892/// The location of the '=', if any, will be placed in EqualLoc.
Richard Smith938f40b2011-06-11 17:19:42 +00002893///
Richard Smith9ba0fec2015-06-30 01:28:56 +00002894/// This does not check for a pure-specifier; that's handled elsewhere.
Sebastian Redleef474c2012-02-22 10:50:08 +00002895///
Richard Smith938f40b2011-06-11 17:19:42 +00002896/// brace-or-equal-initializer:
2897/// '=' initializer-expression
Sebastian Redleef474c2012-02-22 10:50:08 +00002898/// braced-init-list
2899///
Richard Smith938f40b2011-06-11 17:19:42 +00002900/// initializer-clause:
2901/// assignment-expression
Sebastian Redleef474c2012-02-22 10:50:08 +00002902/// braced-init-list
2903///
Richard Smithda35e962013-11-09 04:52:51 +00002904/// defaulted/deleted function-definition:
Richard Smith938f40b2011-06-11 17:19:42 +00002905/// '=' 'default'
2906/// '=' 'delete'
2907///
2908/// Prior to C++0x, the assignment-expression in an initializer-clause must
2909/// be a constant-expression.
Douglas Gregor926410d2012-02-21 02:22:07 +00002910ExprResult Parser::ParseCXXMemberInitializer(Decl *D, bool IsFunction,
Richard Smith938f40b2011-06-11 17:19:42 +00002911 SourceLocation &EqualLoc) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002912 assert(Tok.isOneOf(tok::equal, tok::l_brace)
Richard Smith938f40b2011-06-11 17:19:42 +00002913 && "Data member initializer not starting with '=' or '{'");
2914
Douglas Gregor926410d2012-02-21 02:22:07 +00002915 EnterExpressionEvaluationContext Context(Actions,
2916 Sema::PotentiallyEvaluated,
2917 D);
Alp Toker094e5212014-01-05 03:27:11 +00002918 if (TryConsumeToken(tok::equal, EqualLoc)) {
Richard Smith938f40b2011-06-11 17:19:42 +00002919 if (Tok.is(tok::kw_delete)) {
2920 // In principle, an initializer of '= delete p;' is legal, but it will
2921 // never type-check. It's better to diagnose it as an ill-formed expression
2922 // than as an ill-formed deleted non-function member.
2923 // An initializer of '= delete p, foo' will never be parsed, because
2924 // a top-level comma always ends the initializer expression.
2925 const Token &Next = NextToken();
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002926 if (IsFunction || Next.isOneOf(tok::semi, tok::comma, tok::eof)) {
Richard Smith938f40b2011-06-11 17:19:42 +00002927 if (IsFunction)
2928 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2929 << 1 /* delete */;
2930 else
2931 Diag(ConsumeToken(), diag::err_deleted_non_function);
Richard Smithedcb26e2014-06-11 00:49:52 +00002932 return ExprError();
Richard Smith938f40b2011-06-11 17:19:42 +00002933 }
2934 } else if (Tok.is(tok::kw_default)) {
Richard Smith938f40b2011-06-11 17:19:42 +00002935 if (IsFunction)
2936 Diag(Tok, diag::err_default_delete_in_multiple_declaration)
2937 << 0 /* default */;
2938 else
2939 Diag(ConsumeToken(), diag::err_default_special_members);
Richard Smithedcb26e2014-06-11 00:49:52 +00002940 return ExprError();
Richard Smith938f40b2011-06-11 17:19:42 +00002941 }
David Majnemer87ff66c2014-12-13 11:34:16 +00002942 }
2943 if (const auto *PD = dyn_cast_or_null<MSPropertyDecl>(D)) {
2944 Diag(Tok, diag::err_ms_property_initializer) << PD;
2945 return ExprError();
Sebastian Redleef474c2012-02-22 10:50:08 +00002946 }
2947 return ParseInitializer();
Richard Smith938f40b2011-06-11 17:19:42 +00002948}
2949
Richard Smith65ebb4a2015-03-26 04:09:53 +00002950void Parser::SkipCXXMemberSpecification(SourceLocation RecordLoc,
2951 SourceLocation AttrFixitLoc,
2952 unsigned TagType, Decl *TagDecl) {
2953 // Skip the optional 'final' keyword.
2954 if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
2955 assert(isCXX11FinalKeyword() && "not a class definition");
2956 ConsumeToken();
2957
2958 // Diagnose any C++11 attributes after 'final' keyword.
2959 // We deliberately discard these attributes.
2960 ParsedAttributesWithRange Attrs(AttrFactory);
2961 CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
2962
2963 // This can only happen if we had malformed misplaced attributes;
2964 // we only get called if there is a colon or left-brace after the
2965 // attributes.
2966 if (Tok.isNot(tok::colon) && Tok.isNot(tok::l_brace))
2967 return;
2968 }
2969
2970 // Skip the base clauses. This requires actually parsing them, because
2971 // otherwise we can't be sure where they end (a left brace may appear
2972 // within a template argument).
2973 if (Tok.is(tok::colon)) {
2974 // Enter the scope of the class so that we can correctly parse its bases.
2975 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
2976 ParsingClassDefinition ParsingDef(*this, TagDecl, /*NonNestedClass*/ true,
2977 TagType == DeclSpec::TST_interface);
Richard Smith0f192e82015-06-11 22:48:25 +00002978 auto OldContext =
2979 Actions.ActOnTagStartSkippedDefinition(getCurScope(), TagDecl);
Richard Smith65ebb4a2015-03-26 04:09:53 +00002980
2981 // Parse the bases but don't attach them to the class.
2982 ParseBaseClause(nullptr);
2983
Richard Smith0f192e82015-06-11 22:48:25 +00002984 Actions.ActOnTagFinishSkippedDefinition(OldContext);
Richard Smith65ebb4a2015-03-26 04:09:53 +00002985
2986 if (!Tok.is(tok::l_brace)) {
2987 Diag(PP.getLocForEndOfToken(PrevTokLocation),
2988 diag::err_expected_lbrace_after_base_specifiers);
2989 return;
2990 }
2991 }
2992
2993 // Skip the body.
2994 assert(Tok.is(tok::l_brace));
2995 BalancedDelimiterTracker T(*this, tok::l_brace);
2996 T.consumeOpen();
2997 T.skipToEnd();
Richard Smith04c6c1f2015-07-01 18:56:50 +00002998
2999 // Parse and discard any trailing attributes.
3000 ParsedAttributes Attrs(AttrFactory);
3001 if (Tok.is(tok::kw___attribute))
3002 MaybeParseGNUAttributes(Attrs);
Richard Smith65ebb4a2015-03-26 04:09:53 +00003003}
3004
Alexey Bataev05c25d62015-07-31 08:42:25 +00003005Parser::DeclGroupPtrTy Parser::ParseCXXClassMemberDeclarationWithPragmas(
3006 AccessSpecifier &AS, ParsedAttributesWithRange &AccessAttrs,
3007 DeclSpec::TST TagType, Decl *TagDecl) {
3008 if (getLangOpts().MicrosoftExt &&
3009 Tok.isOneOf(tok::kw___if_exists, tok::kw___if_not_exists)) {
3010 ParseMicrosoftIfExistsClassDeclaration(TagType, AS);
David Blaikie0403cb12016-01-15 23:43:25 +00003011 return nullptr;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003012 }
3013
3014 // Check for extraneous top-level semicolon.
3015 if (Tok.is(tok::semi)) {
3016 ConsumeExtraSemi(InsideStruct, TagType);
David Blaikie0403cb12016-01-15 23:43:25 +00003017 return nullptr;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003018 }
3019
3020 if (Tok.is(tok::annot_pragma_vis)) {
3021 HandlePragmaVisibility();
David Blaikie0403cb12016-01-15 23:43:25 +00003022 return nullptr;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003023 }
3024
3025 if (Tok.is(tok::annot_pragma_pack)) {
3026 HandlePragmaPack();
David Blaikie0403cb12016-01-15 23:43:25 +00003027 return nullptr;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003028 }
3029
3030 if (Tok.is(tok::annot_pragma_align)) {
3031 HandlePragmaAlign();
David Blaikie0403cb12016-01-15 23:43:25 +00003032 return nullptr;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003033 }
3034
3035 if (Tok.is(tok::annot_pragma_ms_pointers_to_members)) {
3036 HandlePragmaMSPointersToMembers();
David Blaikie0403cb12016-01-15 23:43:25 +00003037 return nullptr;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003038 }
3039
3040 if (Tok.is(tok::annot_pragma_ms_pragma)) {
3041 HandlePragmaMSPragma();
David Blaikie0403cb12016-01-15 23:43:25 +00003042 return nullptr;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003043 }
3044
Alexey Bataev3d42f342015-11-20 07:02:57 +00003045 if (Tok.is(tok::annot_pragma_ms_vtordisp)) {
3046 HandlePragmaMSVtorDisp();
David Blaikie0403cb12016-01-15 23:43:25 +00003047 return nullptr;
Alexey Bataev3d42f342015-11-20 07:02:57 +00003048 }
3049
Alexey Bataev05c25d62015-07-31 08:42:25 +00003050 // If we see a namespace here, a close brace was missing somewhere.
3051 if (Tok.is(tok::kw_namespace)) {
3052 DiagnoseUnexpectedNamespace(cast<NamedDecl>(TagDecl));
David Blaikie0403cb12016-01-15 23:43:25 +00003053 return nullptr;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003054 }
3055
3056 AccessSpecifier NewAS = getAccessSpecifierIfPresent();
3057 if (NewAS != AS_none) {
3058 // Current token is a C++ access specifier.
3059 AS = NewAS;
3060 SourceLocation ASLoc = Tok.getLocation();
3061 unsigned TokLength = Tok.getLength();
3062 ConsumeToken();
3063 AccessAttrs.clear();
3064 MaybeParseGNUAttributes(AccessAttrs);
3065
3066 SourceLocation EndLoc;
3067 if (TryConsumeToken(tok::colon, EndLoc)) {
3068 } else if (TryConsumeToken(tok::semi, EndLoc)) {
3069 Diag(EndLoc, diag::err_expected)
3070 << tok::colon << FixItHint::CreateReplacement(EndLoc, ":");
3071 } else {
3072 EndLoc = ASLoc.getLocWithOffset(TokLength);
3073 Diag(EndLoc, diag::err_expected)
3074 << tok::colon << FixItHint::CreateInsertion(EndLoc, ":");
3075 }
3076
3077 // The Microsoft extension __interface does not permit non-public
3078 // access specifiers.
3079 if (TagType == DeclSpec::TST_interface && AS != AS_public) {
3080 Diag(ASLoc, diag::err_access_specifier_interface) << (AS == AS_protected);
3081 }
3082
3083 if (Actions.ActOnAccessSpecifier(NewAS, ASLoc, EndLoc,
3084 AccessAttrs.getList())) {
3085 // found another attribute than only annotations
3086 AccessAttrs.clear();
3087 }
3088
David Blaikie0403cb12016-01-15 23:43:25 +00003089 return nullptr;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003090 }
3091
3092 if (Tok.is(tok::annot_pragma_openmp))
Alexey Bataev587e1de2016-03-30 10:43:55 +00003093 return ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, AccessAttrs, TagType,
3094 TagDecl);
Alexey Bataev05c25d62015-07-31 08:42:25 +00003095
3096 // Parse all the comma separated declarators.
3097 return ParseCXXClassMemberDeclaration(AS, AccessAttrs.getList());
3098}
3099
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003100/// ParseCXXMemberSpecification - Parse the class definition.
3101///
3102/// member-specification:
3103/// member-declaration member-specification[opt]
3104/// access-specifier ':' member-specification[opt]
3105///
Joao Matose9a3ed42012-08-31 22:18:20 +00003106void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc,
Michael Han309af292013-01-07 16:57:11 +00003107 SourceLocation AttrFixitLoc,
Richard Smith4c96e992013-02-19 23:47:15 +00003108 ParsedAttributesWithRange &Attrs,
Joao Matose9a3ed42012-08-31 22:18:20 +00003109 unsigned TagType, Decl *TagDecl) {
3110 assert((TagType == DeclSpec::TST_struct ||
3111 TagType == DeclSpec::TST_interface ||
3112 TagType == DeclSpec::TST_union ||
3113 TagType == DeclSpec::TST_class) && "Invalid TagType!");
3114
John McCallfaf5fb42010-08-26 23:41:50 +00003115 PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc,
3116 "parsing struct/union/class body");
Mike Stump11289f42009-09-09 15:08:12 +00003117
Douglas Gregoredf8f392010-01-16 20:52:59 +00003118 // Determine whether this is a non-nested class. Note that local
3119 // classes are *not* considered to be nested classes.
3120 bool NonNestedClass = true;
3121 if (!ClassStack.empty()) {
Douglas Gregor0be31a22010-07-02 17:43:08 +00003122 for (const Scope *S = getCurScope(); S; S = S->getParent()) {
Douglas Gregoredf8f392010-01-16 20:52:59 +00003123 if (S->isClassScope()) {
3124 // We're inside a class scope, so this is a nested class.
3125 NonNestedClass = false;
John McCalldb632ac2012-09-25 07:32:39 +00003126
3127 // The Microsoft extension __interface does not permit nested classes.
3128 if (getCurrentClass().IsInterface) {
3129 Diag(RecordLoc, diag::err_invalid_member_in_interface)
3130 << /*ErrorType=*/6
3131 << (isa<NamedDecl>(TagDecl)
3132 ? cast<NamedDecl>(TagDecl)->getQualifiedNameAsString()
David Blaikieabe1a392014-04-02 05:58:29 +00003133 : "(anonymous)");
John McCalldb632ac2012-09-25 07:32:39 +00003134 }
Douglas Gregoredf8f392010-01-16 20:52:59 +00003135 break;
3136 }
3137
Serge Pavlovd9c0bcf2015-07-14 10:02:10 +00003138 if ((S->getFlags() & Scope::FnScope))
3139 // If we're in a function or function template then this is a local
3140 // class rather than a nested class.
3141 break;
Douglas Gregoredf8f392010-01-16 20:52:59 +00003142 }
3143 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003144
3145 // Enter a scope for the class.
Douglas Gregor658b9552009-01-09 22:42:13 +00003146 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003147
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003148 // Note that we are parsing a new (potentially-nested) class definition.
John McCalldb632ac2012-09-25 07:32:39 +00003149 ParsingClassDefinition ParsingDef(*this, TagDecl, NonNestedClass,
3150 TagType == DeclSpec::TST_interface);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003151
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003152 if (TagDecl)
Douglas Gregor0be31a22010-07-02 17:43:08 +00003153 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
John McCall2d814c32009-12-19 21:48:58 +00003154
Anders Carlssonf9eb63b2011-03-25 14:46:08 +00003155 SourceLocation FinalLoc;
David Majnemera5433082013-10-18 00:33:31 +00003156 bool IsFinalSpelledSealed = false;
Anders Carlssonf9eb63b2011-03-25 14:46:08 +00003157
3158 // Parse the optional 'final' keyword.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003159 if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
David Majnemera5433082013-10-18 00:33:31 +00003160 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier(Tok);
3161 assert((Specifier == VirtSpecifiers::VS_Final ||
Andrey Bokhanko276055b2016-07-29 10:42:48 +00003162 Specifier == VirtSpecifiers::VS_GNU_Final ||
David Majnemera5433082013-10-18 00:33:31 +00003163 Specifier == VirtSpecifiers::VS_Sealed) &&
3164 "not a class definition");
Richard Smithda261112011-10-15 04:21:46 +00003165 FinalLoc = ConsumeToken();
David Majnemera5433082013-10-18 00:33:31 +00003166 IsFinalSpelledSealed = Specifier == VirtSpecifiers::VS_Sealed;
Anders Carlssonf9eb63b2011-03-25 14:46:08 +00003167
David Majnemera5433082013-10-18 00:33:31 +00003168 if (TagType == DeclSpec::TST_interface)
John McCalldb632ac2012-09-25 07:32:39 +00003169 Diag(FinalLoc, diag::err_override_control_interface)
David Majnemera5433082013-10-18 00:33:31 +00003170 << VirtSpecifiers::getSpecifierName(Specifier);
3171 else if (Specifier == VirtSpecifiers::VS_Final)
3172 Diag(FinalLoc, getLangOpts().CPlusPlus11
3173 ? diag::warn_cxx98_compat_override_control_keyword
3174 : diag::ext_override_control_keyword)
3175 << VirtSpecifiers::getSpecifierName(Specifier);
3176 else if (Specifier == VirtSpecifiers::VS_Sealed)
3177 Diag(FinalLoc, diag::ext_ms_sealed_keyword);
Andrey Bokhanko276055b2016-07-29 10:42:48 +00003178 else if (Specifier == VirtSpecifiers::VS_GNU_Final)
3179 Diag(FinalLoc, diag::ext_warn_gnu_final);
Michael Han9407e502012-11-26 22:54:45 +00003180
Michael Han309af292013-01-07 16:57:11 +00003181 // Parse any C++11 attributes after 'final' keyword.
3182 // These attributes are not allowed to appear here,
3183 // and the only possible place for them to appertain
3184 // to the class would be between class-key and class-name.
Richard Smith4c96e992013-02-19 23:47:15 +00003185 CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
Nico Weber4b4be842014-12-29 06:56:50 +00003186
3187 // ParseClassSpecifier() does only a superficial check for attributes before
3188 // deciding to call this method. For example, for
3189 // `class C final alignas ([l) {` it will decide that this looks like a
3190 // misplaced attribute since it sees `alignas '(' ')'`. But the actual
3191 // attribute parsing code will try to parse the '[' as a constexpr lambda
3192 // and consume enough tokens that the alignas parsing code will eat the
3193 // opening '{'. So bail out if the next token isn't one we expect.
Nico Weber36de3a22014-12-29 21:56:22 +00003194 if (!Tok.is(tok::colon) && !Tok.is(tok::l_brace)) {
3195 if (TagDecl)
3196 Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
Nico Weber4b4be842014-12-29 06:56:50 +00003197 return;
Nico Weber36de3a22014-12-29 21:56:22 +00003198 }
Anders Carlssonf9eb63b2011-03-25 14:46:08 +00003199 }
Anders Carlsson4b63d0e2011-01-22 16:56:46 +00003200
John McCall2d814c32009-12-19 21:48:58 +00003201 if (Tok.is(tok::colon)) {
3202 ParseBaseClause(TagDecl);
John McCall2d814c32009-12-19 21:48:58 +00003203 if (!Tok.is(tok::l_brace)) {
Ismail Pazarbasi129c44c2014-09-25 21:13:02 +00003204 bool SuggestFixIt = false;
3205 SourceLocation BraceLoc = PP.getLocForEndOfToken(PrevTokLocation);
3206 if (Tok.isAtStartOfLine()) {
3207 switch (Tok.getKind()) {
3208 case tok::kw_private:
3209 case tok::kw_protected:
3210 case tok::kw_public:
3211 SuggestFixIt = NextToken().getKind() == tok::colon;
3212 break;
3213 case tok::kw_static_assert:
3214 case tok::r_brace:
3215 case tok::kw_using:
3216 // base-clause can have simple-template-id; 'template' can't be there
3217 case tok::kw_template:
3218 SuggestFixIt = true;
3219 break;
3220 case tok::identifier:
3221 SuggestFixIt = isConstructorDeclarator(true);
3222 break;
3223 default:
3224 SuggestFixIt = isCXXSimpleDeclaration(/*AllowForRangeDecl=*/false);
3225 break;
3226 }
3227 }
3228 DiagnosticBuilder LBraceDiag =
3229 Diag(BraceLoc, diag::err_expected_lbrace_after_base_specifiers);
3230 if (SuggestFixIt) {
3231 LBraceDiag << FixItHint::CreateInsertion(BraceLoc, " {");
3232 // Try recovering from missing { after base-clause.
3233 PP.EnterToken(Tok);
3234 Tok.setKind(tok::l_brace);
3235 } else {
3236 if (TagDecl)
3237 Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
3238 return;
3239 }
John McCall2d814c32009-12-19 21:48:58 +00003240 }
3241 }
3242
3243 assert(Tok.is(tok::l_brace));
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003244 BalancedDelimiterTracker T(*this, tok::l_brace);
3245 T.consumeOpen();
John McCall2d814c32009-12-19 21:48:58 +00003246
John McCall08bede42010-05-28 08:11:17 +00003247 if (TagDecl)
Anders Carlsson30f29442011-03-25 14:31:08 +00003248 Actions.ActOnStartCXXMemberDeclarations(getCurScope(), TagDecl, FinalLoc,
David Majnemera5433082013-10-18 00:33:31 +00003249 IsFinalSpelledSealed,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003250 T.getOpenLocation());
John McCall1c7e6ec2009-12-20 07:58:13 +00003251
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003252 // C++ 11p3: Members of a class defined with the keyword class are private
3253 // by default. Members of a class defined with the keywords struct or union
3254 // are public by default.
3255 AccessSpecifier CurAS;
3256 if (TagType == DeclSpec::TST_class)
3257 CurAS = AS_private;
3258 else
3259 CurAS = AS_public;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003260 ParsedAttributesWithRange AccessAttrs(AttrFactory);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003261
Douglas Gregor9377c822010-06-21 22:31:09 +00003262 if (TagDecl) {
3263 // While we still have something to read, read the member-declarations.
Richard Smith752ada82015-11-17 23:32:01 +00003264 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
3265 Tok.isNot(tok::eof)) {
Douglas Gregor9377c822010-06-21 22:31:09 +00003266 // Each iteration of this loop reads one member-declaration.
Alexey Bataev05c25d62015-07-31 08:42:25 +00003267 ParseCXXClassMemberDeclarationWithPragmas(
3268 CurAS, AccessAttrs, static_cast<DeclSpec::TST>(TagType), TagDecl);
Serge Pavlovc4e04a22015-09-19 05:32:57 +00003269 }
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003270 T.consumeClose();
Douglas Gregor9377c822010-06-21 22:31:09 +00003271 } else {
Alexey Bataevee6507d2013-11-18 08:17:37 +00003272 SkipUntil(tok::r_brace);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003273 }
Mike Stump11289f42009-09-09 15:08:12 +00003274
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003275 // If attributes exist after class contents, parse them.
John McCall084e83d2011-03-24 11:26:52 +00003276 ParsedAttributes attrs(AttrFactory);
John McCall53fa7142010-12-24 02:08:15 +00003277 MaybeParseGNUAttributes(attrs);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003278
John McCall08bede42010-05-28 08:11:17 +00003279 if (TagDecl)
Douglas Gregor0be31a22010-07-02 17:43:08 +00003280 Actions.ActOnFinishCXXMemberSpecification(getCurScope(), RecordLoc, TagDecl,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003281 T.getOpenLocation(),
3282 T.getCloseLocation(),
John McCall53fa7142010-12-24 02:08:15 +00003283 attrs.getList());
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003284
Douglas Gregor433e0532012-04-16 18:27:27 +00003285 // C++11 [class.mem]p2:
3286 // Within the class member-specification, the class is regarded as complete
Richard Smith0b3a4622014-11-13 20:01:57 +00003287 // within function bodies, default arguments, exception-specifications, and
Douglas Gregor433e0532012-04-16 18:27:27 +00003288 // brace-or-equal-initializers for non-static data members (including such
3289 // things in nested classes).
Douglas Gregor9377c822010-06-21 22:31:09 +00003290 if (TagDecl && NonNestedClass) {
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003291 // We are not inside a nested class. This class and its nested classes
Douglas Gregor4d87df52008-12-16 21:30:33 +00003292 // are complete and we can parse the delayed portions of method
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00003293 // declarations and the lexed inline method definitions, along with any
3294 // delayed attributes.
Douglas Gregor428119e2010-06-16 23:45:56 +00003295 SourceLocation SavedPrevTokLocation = PrevTokLocation;
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00003296 ParseLexedAttributes(getCurrentClass());
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003297 ParseLexedMethodDeclarations(getCurrentClass());
Richard Smith84973e52012-04-21 18:42:51 +00003298
3299 // We've finished with all pending member declarations.
3300 Actions.ActOnFinishCXXMemberDecls();
3301
Richard Smith938f40b2011-06-11 17:19:42 +00003302 ParseLexedMemberInitializers(getCurrentClass());
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003303 ParseLexedMethodDefs(getCurrentClass());
Douglas Gregor428119e2010-06-16 23:45:56 +00003304 PrevTokLocation = SavedPrevTokLocation;
Reid Klecknerbba3cb92015-03-17 19:00:50 +00003305
3306 // We've finished parsing everything, including default argument
3307 // initializers.
Hans Wennborg99000c22015-08-15 01:18:16 +00003308 Actions.ActOnFinishCXXNonNestedClass(TagDecl);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003309 }
3310
John McCall08bede42010-05-28 08:11:17 +00003311 if (TagDecl)
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00003312 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getRange());
John McCall2ff380a2010-03-17 00:38:33 +00003313
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003314 // Leave the class scope.
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003315 ParsingDef.Pop();
Douglas Gregor7307d6c2008-12-10 06:34:36 +00003316 ClassScope.Exit();
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003317}
Douglas Gregore8381c02008-11-05 04:29:56 +00003318
Richard Smith2ac43ad2013-11-15 23:00:02 +00003319void Parser::DiagnoseUnexpectedNamespace(NamedDecl *D) {
Richard Smithda35e962013-11-09 04:52:51 +00003320 assert(Tok.is(tok::kw_namespace));
3321
3322 // FIXME: Suggest where the close brace should have gone by looking
3323 // at indentation changes within the definition body.
Richard Smith2ac43ad2013-11-15 23:00:02 +00003324 Diag(D->getLocation(),
3325 diag::err_missing_end_of_definition) << D;
Richard Smithda35e962013-11-09 04:52:51 +00003326 Diag(Tok.getLocation(),
Richard Smith2ac43ad2013-11-15 23:00:02 +00003327 diag::note_missing_end_of_definition_before) << D;
Richard Smithda35e962013-11-09 04:52:51 +00003328
3329 // Push '};' onto the token stream to recover.
3330 PP.EnterToken(Tok);
3331
3332 Tok.startToken();
3333 Tok.setLocation(PP.getLocForEndOfToken(PrevTokLocation));
3334 Tok.setKind(tok::semi);
3335 PP.EnterToken(Tok);
3336
3337 Tok.setKind(tok::r_brace);
3338}
3339
Douglas Gregore8381c02008-11-05 04:29:56 +00003340/// ParseConstructorInitializer - Parse a C++ constructor initializer,
3341/// which explicitly initializes the members or base classes of a
3342/// class (C++ [class.base.init]). For example, the three initializers
3343/// after the ':' in the Derived constructor below:
3344///
3345/// @code
3346/// class Base { };
3347/// class Derived : Base {
3348/// int x;
3349/// float f;
3350/// public:
3351/// Derived(float f) : Base(), x(17), f(f) { }
3352/// };
3353/// @endcode
3354///
Mike Stump11289f42009-09-09 15:08:12 +00003355/// [C++] ctor-initializer:
3356/// ':' mem-initializer-list
Douglas Gregore8381c02008-11-05 04:29:56 +00003357///
Mike Stump11289f42009-09-09 15:08:12 +00003358/// [C++] mem-initializer-list:
Douglas Gregor44e7df62011-01-04 00:32:56 +00003359/// mem-initializer ...[opt]
3360/// mem-initializer ...[opt] , mem-initializer-list
John McCall48871652010-08-21 09:40:31 +00003361void Parser::ParseConstructorInitializer(Decl *ConstructorDecl) {
Nico Weber3b00fdc2015-03-07 19:52:39 +00003362 assert(Tok.is(tok::colon) &&
3363 "Constructor initializer always starts with ':'");
Douglas Gregore8381c02008-11-05 04:29:56 +00003364
Nico Weber3b00fdc2015-03-07 19:52:39 +00003365 // Poison the SEH identifiers so they are flagged as illegal in constructor
3366 // initializers.
John Wiegley1c0675e2011-04-28 01:08:34 +00003367 PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
Douglas Gregore8381c02008-11-05 04:29:56 +00003368 SourceLocation ColonLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +00003369
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003370 SmallVector<CXXCtorInitializer*, 4> MemInitializers;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003371 bool AnyErrors = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003372
Douglas Gregore8381c02008-11-05 04:29:56 +00003373 do {
Douglas Gregoreaeeca92010-08-28 00:00:50 +00003374 if (Tok.is(tok::code_completion)) {
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00003375 Actions.CodeCompleteConstructorInitializer(ConstructorDecl,
3376 MemInitializers);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00003377 return cutOffParsing();
Douglas Gregoreaeeca92010-08-28 00:00:50 +00003378 }
Alexey Bataev79de17d2016-01-20 05:25:51 +00003379
3380 MemInitResult MemInit = ParseMemInitializer(ConstructorDecl);
3381 if (!MemInit.isInvalid())
3382 MemInitializers.push_back(MemInit.get());
3383 else
3384 AnyErrors = true;
3385
Douglas Gregore8381c02008-11-05 04:29:56 +00003386 if (Tok.is(tok::comma))
3387 ConsumeToken();
3388 else if (Tok.is(tok::l_brace))
3389 break;
Alexey Bataev79de17d2016-01-20 05:25:51 +00003390 // If the previous initializer was valid and the next token looks like a
3391 // base or member initializer, assume that we're just missing a comma.
3392 else if (!MemInit.isInvalid() &&
3393 Tok.isOneOf(tok::identifier, tok::coloncolon)) {
Douglas Gregorce66d022010-09-07 14:51:08 +00003394 SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation);
3395 Diag(Loc, diag::err_ctor_init_missing_comma)
3396 << FixItHint::CreateInsertion(Loc, ", ");
3397 } else {
Douglas Gregore8381c02008-11-05 04:29:56 +00003398 // Skip over garbage, until we get to '{'. Don't eat the '{'.
Alexey Bataev79de17d2016-01-20 05:25:51 +00003399 if (!MemInit.isInvalid())
3400 Diag(Tok.getLocation(), diag::err_expected_either) << tok::l_brace
3401 << tok::comma;
Alexey Bataevee6507d2013-11-18 08:17:37 +00003402 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
Douglas Gregore8381c02008-11-05 04:29:56 +00003403 break;
3404 }
3405 } while (true);
3406
David Blaikie3fc2f912013-01-17 05:26:25 +00003407 Actions.ActOnMemInitializers(ConstructorDecl, ColonLoc, MemInitializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003408 AnyErrors);
Douglas Gregore8381c02008-11-05 04:29:56 +00003409}
3410
3411/// ParseMemInitializer - Parse a C++ member initializer, which is
3412/// part of a constructor initializer that explicitly initializes one
3413/// member or base class (C++ [class.base.init]). See
3414/// ParseConstructorInitializer for an example.
3415///
3416/// [C++] mem-initializer:
3417/// mem-initializer-id '(' expression-list[opt] ')'
Sebastian Redl3da34892011-06-05 12:23:16 +00003418/// [C++0x] mem-initializer-id braced-init-list
Mike Stump11289f42009-09-09 15:08:12 +00003419///
Douglas Gregore8381c02008-11-05 04:29:56 +00003420/// [C++] mem-initializer-id:
3421/// '::'[opt] nested-name-specifier[opt] class-name
3422/// identifier
Craig Topper9ad7e262014-10-31 06:57:07 +00003423MemInitResult Parser::ParseMemInitializer(Decl *ConstructorDecl) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00003424 // parse '::'[opt] nested-name-specifier[opt]
3425 CXXScopeSpec SS;
David Blaikieefdccaa2016-01-15 23:43:34 +00003426 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false);
John McCallba7bf592010-08-24 05:47:05 +00003427 ParsedType TemplateTypeTy;
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00003428 if (Tok.is(tok::annot_template_id)) {
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00003429 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregor46c59612010-01-12 17:52:59 +00003430 if (TemplateId->Kind == TNK_Type_template ||
3431 TemplateId->Kind == TNK_Dependent_template_name) {
Douglas Gregore7c20652011-03-02 00:47:37 +00003432 AnnotateTemplateIdTokenAsType();
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00003433 assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
John McCallba7bf592010-08-24 05:47:05 +00003434 TemplateTypeTy = getTypeAnnotation(Tok);
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00003435 }
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00003436 }
David Blaikie186a8892012-01-24 06:03:59 +00003437 // Uses of decltype will already have been converted to annot_decltype by
3438 // ParseOptionalCXXScopeSpecifier at this point.
3439 if (!TemplateTypeTy && Tok.isNot(tok::identifier)
3440 && Tok.isNot(tok::annot_decltype)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00003441 Diag(Tok, diag::err_expected_member_or_base_name);
Douglas Gregore8381c02008-11-05 04:29:56 +00003442 return true;
3443 }
Mike Stump11289f42009-09-09 15:08:12 +00003444
Craig Topper161e4db2014-05-21 06:02:52 +00003445 IdentifierInfo *II = nullptr;
David Blaikie186a8892012-01-24 06:03:59 +00003446 DeclSpec DS(AttrFactory);
3447 SourceLocation IdLoc = Tok.getLocation();
3448 if (Tok.is(tok::annot_decltype)) {
3449 // Get the decltype expression, if there is one.
3450 ParseDecltypeSpecifier(DS);
3451 } else {
3452 if (Tok.is(tok::identifier))
3453 // Get the identifier. This may be a member name or a class name,
3454 // but we'll let the semantic analysis determine which it is.
3455 II = Tok.getIdentifierInfo();
3456 ConsumeToken();
3457 }
3458
Douglas Gregore8381c02008-11-05 04:29:56 +00003459
3460 // Parse the '('.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003461 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
Richard Smith5d164bc2011-10-15 05:09:34 +00003462 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
3463
Sebastian Redla74948d2011-09-24 17:48:25 +00003464 ExprResult InitList = ParseBraceInitializer();
3465 if (InitList.isInvalid())
3466 return true;
3467
3468 SourceLocation EllipsisLoc;
Alp Toker094e5212014-01-05 03:27:11 +00003469 TryConsumeToken(tok::ellipsis, EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00003470
3471 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
David Blaikie186a8892012-01-24 06:03:59 +00003472 TemplateTypeTy, DS, IdLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003473 InitList.get(), EllipsisLoc);
Sebastian Redl3da34892011-06-05 12:23:16 +00003474 } else if(Tok.is(tok::l_paren)) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003475 BalancedDelimiterTracker T(*this, tok::l_paren);
3476 T.consumeOpen();
Douglas Gregore8381c02008-11-05 04:29:56 +00003477
Sebastian Redl3da34892011-06-05 12:23:16 +00003478 // Parse the optional expression-list.
Benjamin Kramerf0623432012-08-23 22:51:59 +00003479 ExprVector ArgExprs;
Sebastian Redl3da34892011-06-05 12:23:16 +00003480 CommaLocsTy CommaLocs;
3481 if (Tok.isNot(tok::r_paren) && ParseExpressionList(ArgExprs, CommaLocs)) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00003482 SkipUntil(tok::r_paren, StopAtSemi);
Sebastian Redl3da34892011-06-05 12:23:16 +00003483 return true;
3484 }
3485
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003486 T.consumeClose();
Sebastian Redl3da34892011-06-05 12:23:16 +00003487
3488 SourceLocation EllipsisLoc;
Alp Toker97650562014-01-10 11:19:30 +00003489 TryConsumeToken(tok::ellipsis, EllipsisLoc);
Sebastian Redl3da34892011-06-05 12:23:16 +00003490
3491 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
David Blaikie186a8892012-01-24 06:03:59 +00003492 TemplateTypeTy, DS, IdLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00003493 T.getOpenLocation(), ArgExprs,
3494 T.getCloseLocation(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00003495 }
3496
Alp Tokerec543272013-12-24 09:48:30 +00003497 if (getLangOpts().CPlusPlus11)
3498 return Diag(Tok, diag::err_expected_either) << tok::l_paren << tok::l_brace;
3499 else
3500 return Diag(Tok, diag::err_expected) << tok::l_paren;
Douglas Gregore8381c02008-11-05 04:29:56 +00003501}
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003502
Sebastian Redl965b0e32011-03-05 14:45:16 +00003503/// \brief Parse a C++ exception-specification if present (C++0x [except.spec]).
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003504///
Douglas Gregor356513d2008-12-01 18:00:20 +00003505/// exception-specification:
Sebastian Redl965b0e32011-03-05 14:45:16 +00003506/// dynamic-exception-specification
3507/// noexcept-specification
3508///
3509/// noexcept-specification:
3510/// 'noexcept'
3511/// 'noexcept' '(' constant-expression ')'
3512ExceptionSpecificationType
Richard Smith0b3a4622014-11-13 20:01:57 +00003513Parser::tryParseExceptionSpecification(bool Delayed,
Douglas Gregor433e0532012-04-16 18:27:27 +00003514 SourceRange &SpecificationRange,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003515 SmallVectorImpl<ParsedType> &DynamicExceptions,
3516 SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
Richard Smith0b3a4622014-11-13 20:01:57 +00003517 ExprResult &NoexceptExpr,
3518 CachedTokens *&ExceptionSpecTokens) {
Sebastian Redl965b0e32011-03-05 14:45:16 +00003519 ExceptionSpecificationType Result = EST_None;
Hans Wennborgdcfba332015-10-06 23:40:43 +00003520 ExceptionSpecTokens = nullptr;
Richard Smith0b3a4622014-11-13 20:01:57 +00003521
3522 // Handle delayed parsing of exception-specifications.
3523 if (Delayed) {
3524 if (Tok.isNot(tok::kw_throw) && Tok.isNot(tok::kw_noexcept))
3525 return EST_None;
Sebastian Redl965b0e32011-03-05 14:45:16 +00003526
Richard Smith0b3a4622014-11-13 20:01:57 +00003527 // Consume and cache the starting token.
3528 bool IsNoexcept = Tok.is(tok::kw_noexcept);
3529 Token StartTok = Tok;
3530 SpecificationRange = SourceRange(ConsumeToken());
3531
3532 // Check for a '('.
3533 if (!Tok.is(tok::l_paren)) {
3534 // If this is a bare 'noexcept', we're done.
3535 if (IsNoexcept) {
3536 Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
Hans Wennborgdcfba332015-10-06 23:40:43 +00003537 NoexceptExpr = nullptr;
Richard Smith0b3a4622014-11-13 20:01:57 +00003538 return EST_BasicNoexcept;
3539 }
3540
3541 Diag(Tok, diag::err_expected_lparen_after) << "throw";
3542 return EST_DynamicNone;
3543 }
3544
3545 // Cache the tokens for the exception-specification.
3546 ExceptionSpecTokens = new CachedTokens;
3547 ExceptionSpecTokens->push_back(StartTok); // 'throw' or 'noexcept'
3548 ExceptionSpecTokens->push_back(Tok); // '('
3549 SpecificationRange.setEnd(ConsumeParen()); // '('
Richard Smithb1c217e2015-01-13 02:24:58 +00003550
3551 ConsumeAndStoreUntil(tok::r_paren, *ExceptionSpecTokens,
3552 /*StopAtSemi=*/true,
3553 /*ConsumeFinalToken=*/true);
Aaron Ballman580ccaf2016-01-12 21:04:22 +00003554 SpecificationRange.setEnd(ExceptionSpecTokens->back().getLocation());
3555
Richard Smith0b3a4622014-11-13 20:01:57 +00003556 return EST_Unparsed;
3557 }
3558
Sebastian Redl965b0e32011-03-05 14:45:16 +00003559 // See if there's a dynamic specification.
3560 if (Tok.is(tok::kw_throw)) {
3561 Result = ParseDynamicExceptionSpecification(SpecificationRange,
3562 DynamicExceptions,
3563 DynamicExceptionRanges);
3564 assert(DynamicExceptions.size() == DynamicExceptionRanges.size() &&
3565 "Produced different number of exception types and ranges.");
3566 }
3567
3568 // If there's no noexcept specification, we're done.
3569 if (Tok.isNot(tok::kw_noexcept))
3570 return Result;
3571
Richard Smithb15c11c2011-10-17 23:06:20 +00003572 Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
3573
Sebastian Redl965b0e32011-03-05 14:45:16 +00003574 // If we already had a dynamic specification, parse the noexcept for,
3575 // recovery, but emit a diagnostic and don't store the results.
3576 SourceRange NoexceptRange;
3577 ExceptionSpecificationType NoexceptType = EST_None;
3578
3579 SourceLocation KeywordLoc = ConsumeToken();
3580 if (Tok.is(tok::l_paren)) {
3581 // There is an argument.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003582 BalancedDelimiterTracker T(*this, tok::l_paren);
3583 T.consumeOpen();
Sebastian Redl965b0e32011-03-05 14:45:16 +00003584 NoexceptType = EST_ComputedNoexcept;
3585 NoexceptExpr = ParseConstantExpression();
Serge Pavlov3739f5e72015-06-29 17:50:19 +00003586 T.consumeClose();
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003587 // The argument must be contextually convertible to bool. We use
Richard Smith03a4aa32016-06-23 19:02:52 +00003588 // CheckBooleanCondition for this purpose.
3589 // FIXME: Add a proper Sema entry point for this.
Serge Pavlov3739f5e72015-06-29 17:50:19 +00003590 if (!NoexceptExpr.isInvalid()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00003591 NoexceptExpr =
3592 Actions.CheckBooleanCondition(KeywordLoc, NoexceptExpr.get());
Serge Pavlov3739f5e72015-06-29 17:50:19 +00003593 NoexceptRange = SourceRange(KeywordLoc, T.getCloseLocation());
3594 } else {
3595 NoexceptType = EST_None;
3596 }
Sebastian Redl965b0e32011-03-05 14:45:16 +00003597 } else {
3598 // There is no argument.
3599 NoexceptType = EST_BasicNoexcept;
3600 NoexceptRange = SourceRange(KeywordLoc, KeywordLoc);
3601 }
3602
3603 if (Result == EST_None) {
3604 SpecificationRange = NoexceptRange;
3605 Result = NoexceptType;
3606
3607 // If there's a dynamic specification after a noexcept specification,
3608 // parse that and ignore the results.
3609 if (Tok.is(tok::kw_throw)) {
3610 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
3611 ParseDynamicExceptionSpecification(NoexceptRange, DynamicExceptions,
3612 DynamicExceptionRanges);
3613 }
3614 } else {
3615 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
3616 }
3617
3618 return Result;
3619}
3620
Richard Smith8ca78a12013-06-13 02:02:51 +00003621static void diagnoseDynamicExceptionSpecification(
Craig Toppere335f252015-10-04 04:53:55 +00003622 Parser &P, SourceRange Range, bool IsNoexcept) {
Richard Smith8ca78a12013-06-13 02:02:51 +00003623 if (P.getLangOpts().CPlusPlus11) {
3624 const char *Replacement = IsNoexcept ? "noexcept" : "noexcept(false)";
Richard Smith82da19d2016-12-08 02:49:07 +00003625 P.Diag(Range.getBegin(),
3626 P.getLangOpts().CPlusPlus1z && !IsNoexcept
3627 ? diag::ext_dynamic_exception_spec
3628 : diag::warn_exception_spec_deprecated)
3629 << Range;
Richard Smith8ca78a12013-06-13 02:02:51 +00003630 P.Diag(Range.getBegin(), diag::note_exception_spec_deprecated)
3631 << Replacement << FixItHint::CreateReplacement(Range, Replacement);
3632 }
3633}
3634
Sebastian Redl965b0e32011-03-05 14:45:16 +00003635/// ParseDynamicExceptionSpecification - Parse a C++
3636/// dynamic-exception-specification (C++ [except.spec]).
3637///
3638/// dynamic-exception-specification:
Douglas Gregor356513d2008-12-01 18:00:20 +00003639/// 'throw' '(' type-id-list [opt] ')'
3640/// [MS] 'throw' '(' '...' ')'
Mike Stump11289f42009-09-09 15:08:12 +00003641///
Douglas Gregor356513d2008-12-01 18:00:20 +00003642/// type-id-list:
Douglas Gregor830837d2010-12-20 23:57:46 +00003643/// type-id ... [opt]
3644/// type-id-list ',' type-id ... [opt]
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003645///
Sebastian Redl965b0e32011-03-05 14:45:16 +00003646ExceptionSpecificationType Parser::ParseDynamicExceptionSpecification(
3647 SourceRange &SpecificationRange,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003648 SmallVectorImpl<ParsedType> &Exceptions,
3649 SmallVectorImpl<SourceRange> &Ranges) {
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003650 assert(Tok.is(tok::kw_throw) && "expected throw");
Mike Stump11289f42009-09-09 15:08:12 +00003651
Sebastian Redl965b0e32011-03-05 14:45:16 +00003652 SpecificationRange.setBegin(ConsumeToken());
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003653 BalancedDelimiterTracker T(*this, tok::l_paren);
3654 if (T.consumeOpen()) {
Sebastian Redl965b0e32011-03-05 14:45:16 +00003655 Diag(Tok, diag::err_expected_lparen_after) << "throw";
3656 SpecificationRange.setEnd(SpecificationRange.getBegin());
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003657 return EST_DynamicNone;
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003658 }
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003659
Douglas Gregor356513d2008-12-01 18:00:20 +00003660 // Parse throw(...), a Microsoft extension that means "this function
3661 // can throw anything".
3662 if (Tok.is(tok::ellipsis)) {
3663 SourceLocation EllipsisLoc = ConsumeToken();
David Blaikiebbafb8a2012-03-11 07:00:24 +00003664 if (!getLangOpts().MicrosoftExt)
Douglas Gregor356513d2008-12-01 18:00:20 +00003665 Diag(EllipsisLoc, diag::ext_ellipsis_exception_spec);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003666 T.consumeClose();
3667 SpecificationRange.setEnd(T.getCloseLocation());
Richard Smith8ca78a12013-06-13 02:02:51 +00003668 diagnoseDynamicExceptionSpecification(*this, SpecificationRange, false);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003669 return EST_MSAny;
Douglas Gregor356513d2008-12-01 18:00:20 +00003670 }
3671
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003672 // Parse the sequence of type-ids.
Sebastian Redld6434562009-05-29 18:02:33 +00003673 SourceRange Range;
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003674 while (Tok.isNot(tok::r_paren)) {
Sebastian Redld6434562009-05-29 18:02:33 +00003675 TypeResult Res(ParseTypeName(&Range));
Sebastian Redl965b0e32011-03-05 14:45:16 +00003676
Douglas Gregor830837d2010-12-20 23:57:46 +00003677 if (Tok.is(tok::ellipsis)) {
3678 // C++0x [temp.variadic]p5:
3679 // - In a dynamic-exception-specification (15.4); the pattern is a
3680 // type-id.
3681 SourceLocation Ellipsis = ConsumeToken();
Sebastian Redl965b0e32011-03-05 14:45:16 +00003682 Range.setEnd(Ellipsis);
Douglas Gregor830837d2010-12-20 23:57:46 +00003683 if (!Res.isInvalid())
3684 Res = Actions.ActOnPackExpansion(Res.get(), Ellipsis);
3685 }
Sebastian Redl965b0e32011-03-05 14:45:16 +00003686
Sebastian Redld6434562009-05-29 18:02:33 +00003687 if (!Res.isInvalid()) {
Sebastian Redl2b9cacb2009-04-29 17:30:04 +00003688 Exceptions.push_back(Res.get());
Sebastian Redld6434562009-05-29 18:02:33 +00003689 Ranges.push_back(Range);
3690 }
Alp Toker97650562014-01-10 11:19:30 +00003691
3692 if (!TryConsumeToken(tok::comma))
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003693 break;
3694 }
3695
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003696 T.consumeClose();
3697 SpecificationRange.setEnd(T.getCloseLocation());
Richard Smith8ca78a12013-06-13 02:02:51 +00003698 diagnoseDynamicExceptionSpecification(*this, SpecificationRange,
3699 Exceptions.empty());
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003700 return Exceptions.empty() ? EST_DynamicNone : EST_Dynamic;
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003701}
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003702
Douglas Gregor7fb25412010-10-01 18:44:50 +00003703/// ParseTrailingReturnType - Parse a trailing return type on a new-style
3704/// function declaration.
Douglas Gregordb0b9f12011-08-04 15:30:47 +00003705TypeResult Parser::ParseTrailingReturnType(SourceRange &Range) {
Douglas Gregor7fb25412010-10-01 18:44:50 +00003706 assert(Tok.is(tok::arrow) && "expected arrow");
3707
3708 ConsumeToken();
3709
Richard Smithbfdb1082012-03-12 08:56:40 +00003710 return ParseTypeName(&Range, Declarator::TrailingReturnContext);
Douglas Gregor7fb25412010-10-01 18:44:50 +00003711}
3712
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003713/// \brief We have just started parsing the definition of a new class,
3714/// so push that class onto our stack of classes that is currently
3715/// being parsed.
John McCallc1465822011-02-14 07:13:47 +00003716Sema::ParsingClassState
John McCalldb632ac2012-09-25 07:32:39 +00003717Parser::PushParsingClass(Decl *ClassDecl, bool NonNestedClass,
3718 bool IsInterface) {
Douglas Gregoredf8f392010-01-16 20:52:59 +00003719 assert((NonNestedClass || !ClassStack.empty()) &&
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003720 "Nested class without outer class");
John McCalldb632ac2012-09-25 07:32:39 +00003721 ClassStack.push(new ParsingClass(ClassDecl, NonNestedClass, IsInterface));
John McCallc1465822011-02-14 07:13:47 +00003722 return Actions.PushParsingClass();
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003723}
3724
3725/// \brief Deallocate the given parsed class and all of its nested
3726/// classes.
3727void Parser::DeallocateParsedClasses(Parser::ParsingClass *Class) {
Douglas Gregorefc46952010-10-12 16:25:54 +00003728 for (unsigned I = 0, N = Class->LateParsedDeclarations.size(); I != N; ++I)
3729 delete Class->LateParsedDeclarations[I];
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003730 delete Class;
3731}
3732
3733/// \brief Pop the top class of the stack of classes that are
3734/// currently being parsed.
3735///
3736/// This routine should be called when we have finished parsing the
3737/// definition of a class, but have not yet popped the Scope
3738/// associated with the class's definition.
John McCallc1465822011-02-14 07:13:47 +00003739void Parser::PopParsingClass(Sema::ParsingClassState state) {
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003740 assert(!ClassStack.empty() && "Mismatched push/pop for class parsing");
Mike Stump11289f42009-09-09 15:08:12 +00003741
John McCallc1465822011-02-14 07:13:47 +00003742 Actions.PopParsingClass(state);
3743
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003744 ParsingClass *Victim = ClassStack.top();
3745 ClassStack.pop();
3746 if (Victim->TopLevelClass) {
3747 // Deallocate all of the nested classes of this class,
3748 // recursively: we don't need to keep any of this information.
3749 DeallocateParsedClasses(Victim);
3750 return;
Mike Stump11289f42009-09-09 15:08:12 +00003751 }
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003752 assert(!ClassStack.empty() && "Missing top-level class?");
3753
Douglas Gregorefc46952010-10-12 16:25:54 +00003754 if (Victim->LateParsedDeclarations.empty()) {
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003755 // The victim is a nested class, but we will not need to perform
3756 // any processing after the definition of this class since it has
3757 // no members whose handling was delayed. Therefore, we can just
3758 // remove this nested class.
Douglas Gregorefc46952010-10-12 16:25:54 +00003759 DeallocateParsedClasses(Victim);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003760 return;
3761 }
3762
3763 // This nested class has some members that will need to be processed
3764 // after the top-level class is completely defined. Therefore, add
3765 // it to the list of nested classes within its parent.
Douglas Gregor0be31a22010-07-02 17:43:08 +00003766 assert(getCurScope()->isClassScope() && "Nested class outside of class scope?");
Douglas Gregorefc46952010-10-12 16:25:54 +00003767 ClassStack.top()->LateParsedDeclarations.push_back(new LateParsedClass(this, Victim));
Douglas Gregor0be31a22010-07-02 17:43:08 +00003768 Victim->TemplateScope = getCurScope()->getParent()->isTemplateParamScope();
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003769}
Alexis Hunt96d5c762009-11-21 08:43:09 +00003770
Richard Smith3dff2512012-04-10 03:25:07 +00003771/// \brief Try to parse an 'identifier' which appears within an attribute-token.
3772///
3773/// \return the parsed identifier on success, and 0 if the next token is not an
3774/// attribute-token.
3775///
3776/// C++11 [dcl.attr.grammar]p3:
3777/// If a keyword or an alternative token that satisfies the syntactic
3778/// requirements of an identifier is contained in an attribute-token,
3779/// it is considered an identifier.
3780IdentifierInfo *Parser::TryParseCXX11AttributeIdentifier(SourceLocation &Loc) {
3781 switch (Tok.getKind()) {
3782 default:
3783 // Identifiers and keywords have identifier info attached.
David Majnemerd5271992015-01-09 18:09:39 +00003784 if (!Tok.isAnnotation()) {
3785 if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
3786 Loc = ConsumeToken();
3787 return II;
3788 }
Richard Smith3dff2512012-04-10 03:25:07 +00003789 }
Craig Topper161e4db2014-05-21 06:02:52 +00003790 return nullptr;
Richard Smith3dff2512012-04-10 03:25:07 +00003791
3792 case tok::ampamp: // 'and'
3793 case tok::pipe: // 'bitor'
3794 case tok::pipepipe: // 'or'
3795 case tok::caret: // 'xor'
3796 case tok::tilde: // 'compl'
3797 case tok::amp: // 'bitand'
3798 case tok::ampequal: // 'and_eq'
3799 case tok::pipeequal: // 'or_eq'
3800 case tok::caretequal: // 'xor_eq'
3801 case tok::exclaim: // 'not'
3802 case tok::exclaimequal: // 'not_eq'
3803 // Alternative tokens do not have identifier info, but their spelling
3804 // starts with an alphabetical character.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003805 SmallString<8> SpellingBuf;
Benjamin Kramer60be5632015-03-29 19:25:07 +00003806 SourceLocation SpellingLoc =
3807 PP.getSourceManager().getSpellingLoc(Tok.getLocation());
3808 StringRef Spelling = PP.getSpelling(SpellingLoc, SpellingBuf);
Jordan Rosea7d03842013-02-08 22:30:41 +00003809 if (isLetter(Spelling[0])) {
Richard Smith3dff2512012-04-10 03:25:07 +00003810 Loc = ConsumeToken();
Benjamin Kramer5c17f9c2012-04-22 20:43:30 +00003811 return &PP.getIdentifierTable().get(Spelling);
Richard Smith3dff2512012-04-10 03:25:07 +00003812 }
Craig Topper161e4db2014-05-21 06:02:52 +00003813 return nullptr;
Richard Smith3dff2512012-04-10 03:25:07 +00003814 }
3815}
3816
Michael Han23214e52012-10-03 01:56:22 +00003817static bool IsBuiltInOrStandardCXX11Attribute(IdentifierInfo *AttrName,
3818 IdentifierInfo *ScopeName) {
3819 switch (AttributeList::getKind(AttrName, ScopeName,
3820 AttributeList::AS_CXX11)) {
3821 case AttributeList::AT_CarriesDependency:
Aaron Ballman35f94212014-04-14 16:03:22 +00003822 case AttributeList::AT_Deprecated:
Michael Han23214e52012-10-03 01:56:22 +00003823 case AttributeList::AT_FallThrough:
Hans Wennborgdcfba332015-10-06 23:40:43 +00003824 case AttributeList::AT_CXX11NoReturn:
Michael Han23214e52012-10-03 01:56:22 +00003825 return true;
Aaron Ballmane7964782016-03-07 22:44:55 +00003826 case AttributeList::AT_WarnUnusedResult:
3827 return !ScopeName && AttrName->getName().equals("nodiscard");
Nico Weberac03bce2016-08-23 19:59:55 +00003828 case AttributeList::AT_Unused:
3829 return !ScopeName && AttrName->getName().equals("maybe_unused");
Michael Han23214e52012-10-03 01:56:22 +00003830 default:
3831 return false;
3832 }
3833}
3834
Aaron Ballmanb8e20392014-03-31 17:32:39 +00003835/// ParseCXX11AttributeArgs -- Parse a C++11 attribute-argument-clause.
3836///
3837/// [C++11] attribute-argument-clause:
3838/// '(' balanced-token-seq ')'
3839///
3840/// [C++11] balanced-token-seq:
3841/// balanced-token
3842/// balanced-token-seq balanced-token
3843///
3844/// [C++11] balanced-token:
3845/// '(' balanced-token-seq ')'
3846/// '[' balanced-token-seq ']'
3847/// '{' balanced-token-seq '}'
3848/// any token but '(', ')', '[', ']', '{', or '}'
3849bool Parser::ParseCXX11AttributeArgs(IdentifierInfo *AttrName,
3850 SourceLocation AttrNameLoc,
3851 ParsedAttributes &Attrs,
3852 SourceLocation *EndLoc,
3853 IdentifierInfo *ScopeName,
3854 SourceLocation ScopeLoc) {
3855 assert(Tok.is(tok::l_paren) && "Not a C++11 attribute argument list");
Aaron Ballman35f94212014-04-14 16:03:22 +00003856 SourceLocation LParenLoc = Tok.getLocation();
Aaron Ballmanb8e20392014-03-31 17:32:39 +00003857
3858 // If the attribute isn't known, we will not attempt to parse any
3859 // arguments.
3860 if (!hasAttribute(AttrSyntax::CXX, ScopeName, AttrName,
Bob Wilson7c730832015-07-20 22:57:31 +00003861 getTargetInfo(), getLangOpts())) {
Aaron Ballmanb8e20392014-03-31 17:32:39 +00003862 // Eat the left paren, then skip to the ending right paren.
3863 ConsumeParen();
3864 SkipUntil(tok::r_paren);
3865 return false;
3866 }
3867
3868 if (ScopeName && ScopeName->getName() == "gnu")
3869 // GNU-scoped attributes have some special cases to handle GNU-specific
3870 // behaviors.
3871 ParseGNUAttributeArgs(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
Craig Topper161e4db2014-05-21 06:02:52 +00003872 ScopeLoc, AttributeList::AS_CXX11, nullptr);
Aaron Ballman35f94212014-04-14 16:03:22 +00003873 else {
3874 unsigned NumArgs =
3875 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc,
3876 ScopeName, ScopeLoc, AttributeList::AS_CXX11);
3877
3878 const AttributeList *Attr = Attrs.getList();
3879 if (Attr && IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName)) {
3880 // If the attribute is a standard or built-in attribute and we are
3881 // parsing an argument list, we need to determine whether this attribute
3882 // was allowed to have an argument list (such as [[deprecated]]), and how
3883 // many arguments were parsed (so we can diagnose on [[deprecated()]]).
Nikola Smiljanica9c45212014-05-28 11:19:43 +00003884 if (Attr->getMaxArgs() && !NumArgs) {
3885 // The attribute was allowed to have arguments, but none were provided
3886 // even though the attribute parsed successfully. This is an error.
Nikola Smiljanica9c45212014-05-28 11:19:43 +00003887 Diag(LParenLoc, diag::err_attribute_requires_arguments) << AttrName;
Aaron Ballmanbb5d8622016-03-08 21:31:32 +00003888 Attr->setInvalid(true);
Nikola Smiljanica9c45212014-05-28 11:19:43 +00003889 } else if (!Attr->getMaxArgs()) {
3890 // The attribute parsed successfully, but was not allowed to have any
3891 // arguments. It doesn't matter whether any were provided -- the
Aaron Ballman35f94212014-04-14 16:03:22 +00003892 // presence of the argument list (even if empty) is diagnosed.
3893 Diag(LParenLoc, diag::err_cxx11_attribute_forbids_arguments)
Aaron Ballman9b7cee62014-12-19 18:37:22 +00003894 << AttrName
3895 << FixItHint::CreateRemoval(SourceRange(LParenLoc, *EndLoc));
Aaron Ballmanbb5d8622016-03-08 21:31:32 +00003896 Attr->setInvalid(true);
Aaron Ballman35f94212014-04-14 16:03:22 +00003897 }
3898 }
3899 }
Aaron Ballmanb8e20392014-03-31 17:32:39 +00003900 return true;
3901}
3902
3903/// ParseCXX11AttributeSpecifier - Parse a C++11 attribute-specifier.
Alexis Hunt96d5c762009-11-21 08:43:09 +00003904///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003905/// [C++11] attribute-specifier:
Alexis Hunt96d5c762009-11-21 08:43:09 +00003906/// '[' '[' attribute-list ']' ']'
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00003907/// alignment-specifier
Alexis Hunt96d5c762009-11-21 08:43:09 +00003908///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003909/// [C++11] attribute-list:
Alexis Hunt96d5c762009-11-21 08:43:09 +00003910/// attribute[opt]
3911/// attribute-list ',' attribute[opt]
Richard Smith3dff2512012-04-10 03:25:07 +00003912/// attribute '...'
3913/// attribute-list ',' attribute '...'
Alexis Hunt96d5c762009-11-21 08:43:09 +00003914///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003915/// [C++11] attribute:
Alexis Hunt96d5c762009-11-21 08:43:09 +00003916/// attribute-token attribute-argument-clause[opt]
3917///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003918/// [C++11] attribute-token:
Alexis Hunt96d5c762009-11-21 08:43:09 +00003919/// identifier
3920/// attribute-scoped-token
3921///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003922/// [C++11] attribute-scoped-token:
Alexis Hunt96d5c762009-11-21 08:43:09 +00003923/// attribute-namespace '::' identifier
3924///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003925/// [C++11] attribute-namespace:
Alexis Hunt96d5c762009-11-21 08:43:09 +00003926/// identifier
Richard Smith3dff2512012-04-10 03:25:07 +00003927void Parser::ParseCXX11AttributeSpecifier(ParsedAttributes &attrs,
Peter Collingbourne49eedec2011-09-29 18:04:05 +00003928 SourceLocation *endLoc) {
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00003929 if (Tok.is(tok::kw_alignas)) {
Richard Smithf679b5b2011-10-14 20:48:27 +00003930 Diag(Tok.getLocation(), diag::warn_cxx98_compat_alignas);
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00003931 ParseAlignmentSpecifier(attrs, endLoc);
3932 return;
3933 }
3934
Alexis Hunt96d5c762009-11-21 08:43:09 +00003935 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square)
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003936 && "Not a C++11 attribute list");
Alexis Hunt96d5c762009-11-21 08:43:09 +00003937
Richard Smithf679b5b2011-10-14 20:48:27 +00003938 Diag(Tok.getLocation(), diag::warn_cxx98_compat_attribute);
3939
Alexis Hunt96d5c762009-11-21 08:43:09 +00003940 ConsumeBracket();
3941 ConsumeBracket();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003942
Richard Smithb7d7a042016-06-24 12:15:12 +00003943 SourceLocation CommonScopeLoc;
3944 IdentifierInfo *CommonScopeName = nullptr;
3945 if (Tok.is(tok::kw_using)) {
3946 Diag(Tok.getLocation(), getLangOpts().CPlusPlus1z
3947 ? diag::warn_cxx14_compat_using_attribute_ns
3948 : diag::ext_using_attribute_ns);
3949 ConsumeToken();
3950
3951 CommonScopeName = TryParseCXX11AttributeIdentifier(CommonScopeLoc);
3952 if (!CommonScopeName) {
3953 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
3954 SkipUntil(tok::r_square, tok::colon, StopBeforeMatch);
3955 }
3956 if (!TryConsumeToken(tok::colon) && CommonScopeName)
3957 Diag(Tok.getLocation(), diag::err_expected) << tok::colon;
3958 }
3959
Richard Smith10876ef2013-01-17 01:30:42 +00003960 llvm::SmallDenseMap<IdentifierInfo*, SourceLocation, 4> SeenAttrs;
3961
Richard Smith3dff2512012-04-10 03:25:07 +00003962 while (Tok.isNot(tok::r_square)) {
Alexis Hunt96d5c762009-11-21 08:43:09 +00003963 // attribute not present
Alp Toker97650562014-01-10 11:19:30 +00003964 if (TryConsumeToken(tok::comma))
Alexis Hunt96d5c762009-11-21 08:43:09 +00003965 continue;
Alexis Hunt96d5c762009-11-21 08:43:09 +00003966
Richard Smith3dff2512012-04-10 03:25:07 +00003967 SourceLocation ScopeLoc, AttrLoc;
Craig Topper161e4db2014-05-21 06:02:52 +00003968 IdentifierInfo *ScopeName = nullptr, *AttrName = nullptr;
Richard Smith3dff2512012-04-10 03:25:07 +00003969
3970 AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
3971 if (!AttrName)
3972 // Break out to the "expected ']'" diagnostic.
3973 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003974
Alexis Hunt96d5c762009-11-21 08:43:09 +00003975 // scoped attribute
Alp Toker97650562014-01-10 11:19:30 +00003976 if (TryConsumeToken(tok::coloncolon)) {
Richard Smith3dff2512012-04-10 03:25:07 +00003977 ScopeName = AttrName;
3978 ScopeLoc = AttrLoc;
3979
3980 AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
3981 if (!AttrName) {
Alp Tokerec543272013-12-24 09:48:30 +00003982 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
Alexey Bataevee6507d2013-11-18 08:17:37 +00003983 SkipUntil(tok::r_square, tok::comma, StopAtSemi | StopBeforeMatch);
Alexis Hunt96d5c762009-11-21 08:43:09 +00003984 continue;
3985 }
Alexis Hunt96d5c762009-11-21 08:43:09 +00003986 }
3987
Richard Smithb7d7a042016-06-24 12:15:12 +00003988 if (CommonScopeName) {
3989 if (ScopeName) {
3990 Diag(ScopeLoc, diag::err_using_attribute_ns_conflict)
3991 << SourceRange(CommonScopeLoc);
3992 } else {
3993 ScopeName = CommonScopeName;
3994 ScopeLoc = CommonScopeLoc;
3995 }
3996 }
3997
Aaron Ballmanb8e20392014-03-31 17:32:39 +00003998 bool StandardAttr = IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName);
Alexis Hunt96d5c762009-11-21 08:43:09 +00003999 bool AttrParsed = false;
Alexis Hunt96d5c762009-11-21 08:43:09 +00004000
Richard Smith10876ef2013-01-17 01:30:42 +00004001 if (StandardAttr &&
4002 !SeenAttrs.insert(std::make_pair(AttrName, AttrLoc)).second)
4003 Diag(AttrLoc, diag::err_cxx11_attribute_repeated)
Aaron Ballmanb8e20392014-03-31 17:32:39 +00004004 << AttrName << SourceRange(SeenAttrs[AttrName]);
Richard Smith10876ef2013-01-17 01:30:42 +00004005
Michael Han23214e52012-10-03 01:56:22 +00004006 // Parse attribute arguments
Aaron Ballman35f94212014-04-14 16:03:22 +00004007 if (Tok.is(tok::l_paren))
Aaron Ballmanb8e20392014-03-31 17:32:39 +00004008 AttrParsed = ParseCXX11AttributeArgs(AttrName, AttrLoc, attrs, endLoc,
4009 ScopeName, ScopeLoc);
Michael Han23214e52012-10-03 01:56:22 +00004010
4011 if (!AttrParsed)
Richard Smith84837d52012-05-03 18:27:39 +00004012 attrs.addNew(AttrName,
4013 SourceRange(ScopeLoc.isValid() ? ScopeLoc : AttrLoc,
4014 AttrLoc),
Craig Topper161e4db2014-05-21 06:02:52 +00004015 ScopeName, ScopeLoc, nullptr, 0, AttributeList::AS_CXX11);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004016
Alp Toker97650562014-01-10 11:19:30 +00004017 if (TryConsumeToken(tok::ellipsis))
Michael Han23214e52012-10-03 01:56:22 +00004018 Diag(Tok, diag::err_cxx11_attribute_forbids_ellipsis)
4019 << AttrName->getName();
Alexis Hunt96d5c762009-11-21 08:43:09 +00004020 }
4021
Alp Toker383d2c42014-01-01 03:08:43 +00004022 if (ExpectAndConsume(tok::r_square))
Alexey Bataevee6507d2013-11-18 08:17:37 +00004023 SkipUntil(tok::r_square);
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004024 if (endLoc)
4025 *endLoc = Tok.getLocation();
Alp Toker383d2c42014-01-01 03:08:43 +00004026 if (ExpectAndConsume(tok::r_square))
Alexey Bataevee6507d2013-11-18 08:17:37 +00004027 SkipUntil(tok::r_square);
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004028}
Alexis Hunt96d5c762009-11-21 08:43:09 +00004029
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00004030/// ParseCXX11Attributes - Parse a C++11 attribute-specifier-seq.
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004031///
4032/// attribute-specifier-seq:
4033/// attribute-specifier-seq[opt] attribute-specifier
Richard Smith3dff2512012-04-10 03:25:07 +00004034void Parser::ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004035 SourceLocation *endLoc) {
Richard Smith4cabd042013-02-22 09:15:49 +00004036 assert(getLangOpts().CPlusPlus11);
4037
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004038 SourceLocation StartLoc = Tok.getLocation(), Loc;
4039 if (!endLoc)
4040 endLoc = &Loc;
4041
Douglas Gregor6f981002011-10-07 20:35:25 +00004042 do {
Richard Smith3dff2512012-04-10 03:25:07 +00004043 ParseCXX11AttributeSpecifier(attrs, endLoc);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004044 } while (isCXX11AttributeSpecifier());
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004045
4046 attrs.Range = SourceRange(StartLoc, *endLoc);
Alexis Hunt96d5c762009-11-21 08:43:09 +00004047}
4048
Richard Smithc2c8bb82013-10-15 01:34:54 +00004049void Parser::DiagnoseAndSkipCXX11Attributes() {
Richard Smithc2c8bb82013-10-15 01:34:54 +00004050 // Start and end location of an attribute or an attribute list.
4051 SourceLocation StartLoc = Tok.getLocation();
Richard Smith955bf012014-06-19 11:42:00 +00004052 SourceLocation EndLoc = SkipCXX11Attributes();
4053
4054 if (EndLoc.isValid()) {
4055 SourceRange Range(StartLoc, EndLoc);
4056 Diag(StartLoc, diag::err_attributes_not_allowed)
4057 << Range;
4058 }
4059}
4060
4061SourceLocation Parser::SkipCXX11Attributes() {
Richard Smithc2c8bb82013-10-15 01:34:54 +00004062 SourceLocation EndLoc;
4063
Richard Smith955bf012014-06-19 11:42:00 +00004064 if (!isCXX11AttributeSpecifier())
4065 return EndLoc;
4066
Richard Smithc2c8bb82013-10-15 01:34:54 +00004067 do {
4068 if (Tok.is(tok::l_square)) {
4069 BalancedDelimiterTracker T(*this, tok::l_square);
4070 T.consumeOpen();
4071 T.skipToEnd();
4072 EndLoc = T.getCloseLocation();
4073 } else {
4074 assert(Tok.is(tok::kw_alignas) && "not an attribute specifier");
4075 ConsumeToken();
4076 BalancedDelimiterTracker T(*this, tok::l_paren);
4077 if (!T.consumeOpen())
4078 T.skipToEnd();
4079 EndLoc = T.getCloseLocation();
4080 }
4081 } while (isCXX11AttributeSpecifier());
4082
Richard Smith955bf012014-06-19 11:42:00 +00004083 return EndLoc;
Richard Smithc2c8bb82013-10-15 01:34:54 +00004084}
4085
Nico Weber05e1dad2016-09-03 03:25:22 +00004086/// Parse uuid() attribute when it appears in a [] Microsoft attribute.
4087void Parser::ParseMicrosoftUuidAttributeArgs(ParsedAttributes &Attrs) {
4088 assert(Tok.is(tok::identifier) && "Not a Microsoft attribute list");
4089 IdentifierInfo *UuidIdent = Tok.getIdentifierInfo();
4090 assert(UuidIdent->getName() == "uuid" && "Not a Microsoft attribute list");
4091
4092 SourceLocation UuidLoc = Tok.getLocation();
4093 ConsumeToken();
4094
4095 // Ignore the left paren location for now.
4096 BalancedDelimiterTracker T(*this, tok::l_paren);
4097 if (T.consumeOpen()) {
4098 Diag(Tok, diag::err_expected) << tok::l_paren;
4099 return;
4100 }
4101
4102 ArgsVector ArgExprs;
4103 if (Tok.is(tok::string_literal)) {
4104 // Easy case: uuid("...") -- quoted string.
4105 ExprResult StringResult = ParseStringLiteralExpression();
4106 if (StringResult.isInvalid())
4107 return;
4108 ArgExprs.push_back(StringResult.get());
4109 } else {
4110 // something like uuid({000000A0-0000-0000-C000-000000000049}) -- no
4111 // quotes in the parens. Just append the spelling of all tokens encountered
4112 // until the closing paren.
4113
4114 SmallString<42> StrBuffer; // 2 "", 36 bytes UUID, 2 optional {}, 1 nul
4115 StrBuffer += "\"";
4116
4117 // Since none of C++'s keywords match [a-f]+, accepting just tok::l_brace,
4118 // tok::r_brace, tok::minus, tok::identifier (think C000) and
4119 // tok::numeric_constant (0000) should be enough. But the spelling of the
4120 // uuid argument is checked later anyways, so there's no harm in accepting
4121 // almost anything here.
4122 // cl is very strict about whitespace in this form and errors out if any
4123 // is present, so check the space flags on the tokens.
4124 SourceLocation StartLoc = Tok.getLocation();
4125 while (Tok.isNot(tok::r_paren)) {
4126 if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
4127 Diag(Tok, diag::err_attribute_uuid_malformed_guid);
4128 SkipUntil(tok::r_paren, StopAtSemi);
4129 return;
4130 }
4131 SmallString<16> SpellingBuffer;
4132 SpellingBuffer.resize(Tok.getLength() + 1);
4133 bool Invalid = false;
4134 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
4135 if (Invalid) {
4136 SkipUntil(tok::r_paren, StopAtSemi);
4137 return;
4138 }
4139 StrBuffer += TokSpelling;
4140 ConsumeAnyToken();
4141 }
4142 StrBuffer += "\"";
4143
4144 if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
4145 Diag(Tok, diag::err_attribute_uuid_malformed_guid);
4146 ConsumeParen();
4147 return;
4148 }
4149
4150 // Pretend the user wrote the appropriate string literal here.
4151 // ActOnStringLiteral() copies the string data into the literal, so it's
4152 // ok that the Token points to StrBuffer.
4153 Token Toks[1];
4154 Toks[0].startToken();
4155 Toks[0].setKind(tok::string_literal);
4156 Toks[0].setLocation(StartLoc);
4157 Toks[0].setLiteralData(StrBuffer.data());
4158 Toks[0].setLength(StrBuffer.size());
4159 StringLiteral *UuidString =
4160 cast<StringLiteral>(Actions.ActOnStringLiteral(Toks, nullptr).get());
4161 ArgExprs.push_back(UuidString);
4162 }
4163
4164 if (!T.consumeClose()) {
4165 // FIXME: Warn that this syntax is deprecated, with a Fix-It suggesting
4166 // using __declspec(uuid()) instead.
4167 Attrs.addNew(UuidIdent, SourceRange(UuidLoc, T.getCloseLocation()), nullptr,
4168 SourceLocation(), ArgExprs.data(), ArgExprs.size(),
4169 AttributeList::AS_Microsoft);
4170 }
4171}
4172
David Majnemere4752e752015-07-08 05:55:00 +00004173/// ParseMicrosoftAttributes - Parse Microsoft attributes [Attr]
Francois Pichetc2bc5ac2010-10-11 12:59:39 +00004174///
4175/// [MS] ms-attribute:
4176/// '[' token-seq ']'
4177///
4178/// [MS] ms-attribute-seq:
4179/// ms-attribute[opt]
4180/// ms-attribute ms-attribute-seq
John McCall53fa7142010-12-24 02:08:15 +00004181void Parser::ParseMicrosoftAttributes(ParsedAttributes &attrs,
4182 SourceLocation *endLoc) {
Francois Pichetc2bc5ac2010-10-11 12:59:39 +00004183 assert(Tok.is(tok::l_square) && "Not a Microsoft attribute list");
4184
Saleem Abdulrasool425efcf2015-06-15 20:57:04 +00004185 do {
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004186 // FIXME: If this is actually a C++11 attribute, parse it as one.
Saleem Abdulrasool425efcf2015-06-15 20:57:04 +00004187 BalancedDelimiterTracker T(*this, tok::l_square);
4188 T.consumeOpen();
Nico Weber05e1dad2016-09-03 03:25:22 +00004189
4190 // Skip most ms attributes except for a whitelist.
4191 while (true) {
4192 SkipUntil(tok::r_square, tok::identifier, StopAtSemi | StopBeforeMatch);
4193 if (Tok.isNot(tok::identifier)) // ']', but also eof
4194 break;
4195 if (Tok.getIdentifierInfo()->getName() == "uuid")
4196 ParseMicrosoftUuidAttributeArgs(attrs);
4197 else
4198 ConsumeToken();
4199 }
4200
Saleem Abdulrasool425efcf2015-06-15 20:57:04 +00004201 T.consumeClose();
4202 if (endLoc)
4203 *endLoc = T.getCloseLocation();
4204 } while (Tok.is(tok::l_square));
Francois Pichetc2bc5ac2010-10-11 12:59:39 +00004205}
Francois Pichet8f981d52011-05-25 10:19:49 +00004206
4207void Parser::ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType,
4208 AccessSpecifier& CurAS) {
Douglas Gregor43edb322011-10-24 22:31:10 +00004209 IfExistsCondition Result;
Francois Pichet8f981d52011-05-25 10:19:49 +00004210 if (ParseMicrosoftIfExistsCondition(Result))
4211 return;
4212
Douglas Gregor43edb322011-10-24 22:31:10 +00004213 BalancedDelimiterTracker Braces(*this, tok::l_brace);
4214 if (Braces.consumeOpen()) {
Alp Tokerec543272013-12-24 09:48:30 +00004215 Diag(Tok, diag::err_expected) << tok::l_brace;
Francois Pichet8f981d52011-05-25 10:19:49 +00004216 return;
4217 }
Francois Pichet8f981d52011-05-25 10:19:49 +00004218
Douglas Gregor43edb322011-10-24 22:31:10 +00004219 switch (Result.Behavior) {
4220 case IEB_Parse:
4221 // Parse the declarations below.
4222 break;
4223
4224 case IEB_Dependent:
4225 Diag(Result.KeywordLoc, diag::warn_microsoft_dependent_exists)
4226 << Result.IsIfExists;
4227 // Fall through to skip.
4228
4229 case IEB_Skip:
4230 Braces.skipToEnd();
Francois Pichet8f981d52011-05-25 10:19:49 +00004231 return;
4232 }
4233
Richard Smith34f30512013-11-23 04:06:09 +00004234 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
Francois Pichet8f981d52011-05-25 10:19:49 +00004235 // __if_exists, __if_not_exists can nest.
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00004236 if (Tok.isOneOf(tok::kw___if_exists, tok::kw___if_not_exists)) {
Francois Pichet8f981d52011-05-25 10:19:49 +00004237 ParseMicrosoftIfExistsClassDeclaration((DeclSpec::TST)TagType, CurAS);
4238 continue;
4239 }
4240
4241 // Check for extraneous top-level semicolon.
4242 if (Tok.is(tok::semi)) {
Richard Smith87f5dc52012-07-23 05:45:25 +00004243 ConsumeExtraSemi(InsideStruct, TagType);
Francois Pichet8f981d52011-05-25 10:19:49 +00004244 continue;
4245 }
4246
4247 AccessSpecifier AS = getAccessSpecifierIfPresent();
4248 if (AS != AS_none) {
4249 // Current token is a C++ access specifier.
4250 CurAS = AS;
4251 SourceLocation ASLoc = Tok.getLocation();
4252 ConsumeToken();
4253 if (Tok.is(tok::colon))
4254 Actions.ActOnAccessSpecifier(AS, ASLoc, Tok.getLocation());
4255 else
Alp Toker35d87032013-12-30 23:29:50 +00004256 Diag(Tok, diag::err_expected) << tok::colon;
Francois Pichet8f981d52011-05-25 10:19:49 +00004257 ConsumeToken();
4258 continue;
4259 }
4260
4261 // Parse all the comma separated declarators.
Craig Topper161e4db2014-05-21 06:02:52 +00004262 ParseCXXClassMemberDeclaration(CurAS, nullptr);
Francois Pichet8f981d52011-05-25 10:19:49 +00004263 }
Douglas Gregor43edb322011-10-24 22:31:10 +00004264
4265 Braces.consumeClose();
Francois Pichet8f981d52011-05-25 10:19:49 +00004266}