blob: e88488416352123be3ddbf83b7dbc8d27a4baab3 [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//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattnera5235172007-08-25 06:57:03 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the C++ Declaration portions of the Parser interfaces.
10//
11//===----------------------------------------------------------------------===//
12
Douglas Gregor423984d2008-04-14 00:13:42 +000013#include "clang/Parse/Parser.h"
Erik Verbruggen888d52a2014-01-15 09:15:43 +000014#include "clang/AST/ASTContext.h"
Chandler Carruth757fcd62014-03-04 10:05:20 +000015#include "clang/AST/DeclTemplate.h"
Jordan Rose1e879d82018-03-23 00:07:18 +000016#include "clang/AST/PrettyDeclStackTrace.h"
Aaron Ballmanb8e20392014-03-31 17:32:39 +000017#include "clang/Basic/Attributes.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000018#include "clang/Basic/CharInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "clang/Basic/OperatorKinds.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000020#include "clang/Basic/TargetInfo.h"
Chris Lattner60f36222009-01-29 05:15:15 +000021#include "clang/Parse/ParseDiagnostic.h"
Vassil Vassilev11ad3392017-03-23 15:11:07 +000022#include "clang/Parse/RAIIObjectsForParser.h"
John McCall8b0666c2010-08-20 18:27:03 +000023#include "clang/Sema/DeclSpec.h"
John McCall8b0666c2010-08-20 18:27:03 +000024#include "clang/Sema/ParsedTemplate.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/Sema/Scope.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000026#include "llvm/ADT/SmallString.h"
Anton Afanasyevd880de22019-03-30 08:42:48 +000027#include "llvm/Support/TimeProfiler.h"
Hans Wennborgdcfba332015-10-06 23:40:43 +000028
Chris Lattnera5235172007-08-25 06:57:03 +000029using namespace clang;
30
31/// ParseNamespace - We know that the current token is a namespace keyword. This
Sebastian Redl67667942010-08-27 23:12:46 +000032/// may either be a top level namespace or a block-level namespace alias. If
33/// there was an inline keyword, it has already been parsed.
Chris Lattnera5235172007-08-25 06:57:03 +000034///
Erich Keane53f391d2018-11-12 17:19:48 +000035/// namespace-definition: [C++: namespace.def]
Chris Lattnera5235172007-08-25 06:57:03 +000036/// named-namespace-definition
37/// unnamed-namespace-definition
Erich Keane53f391d2018-11-12 17:19:48 +000038/// nested-namespace-definition
39///
40/// named-namespace-definition:
Erich Keanede6480a32018-11-13 15:48:08 +000041/// 'inline'[opt] 'namespace' attributes[opt] identifier '{'
42/// namespace-body '}'
Chris Lattnera5235172007-08-25 06:57:03 +000043///
44/// unnamed-namespace-definition:
Sebastian Redl67667942010-08-27 23:12:46 +000045/// 'inline'[opt] 'namespace' attributes[opt] '{' namespace-body '}'
Chris Lattnera5235172007-08-25 06:57:03 +000046///
Erich Keane53f391d2018-11-12 17:19:48 +000047/// nested-namespace-definition:
Erich Keanede6480a32018-11-13 15:48:08 +000048/// 'namespace' enclosing-namespace-specifier '::' 'inline'[opt]
49/// identifier '{' namespace-body '}'
Chris Lattnera5235172007-08-25 06:57:03 +000050///
Erich Keane53f391d2018-11-12 17:19:48 +000051/// enclosing-namespace-specifier:
52/// identifier
53/// enclosing-namespace-specifier '::' 'inline'[opt] identifier
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///
Faisal Vali421b2d12017-12-29 05:41:00 +000058Parser::DeclGroupPtrTy Parser::ParseNamespace(DeclaratorContext Context,
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +000059 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);
Fangrui Song6907ce22018-07-30 19:24:48 +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;
Erich Keane53f391d2018-11-12 17:19:48 +000073 InnerNamespaceInfoList ExtraNSs;
74 SourceLocation FirstNestedInlineLoc;
Douglas Gregor6b6bba42009-06-17 19:49:00 +000075
Aaron Ballman730476b2014-11-08 15:33:35 +000076 ParsedAttributesWithRange attrs(AttrFactory);
77 SourceLocation attrLoc;
78 if (getLangOpts().CPlusPlus11 && isCXX11AttributeSpecifier()) {
Aaron Ballmanc351fba2017-12-04 20:27:34 +000079 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
Richard Smith40e202f2017-10-14 00:56:24 +000080 ? diag::warn_cxx14_compat_ns_enum_attribute
81 : diag::ext_ns_enum_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.
Erich Keane53f391d2018-11-12 17:19:48 +000090 while (Tok.is(tok::coloncolon) &&
91 (NextToken().is(tok::identifier) ||
92 (NextToken().is(tok::kw_inline) &&
93 GetLookAheadToken(2).is(tok::identifier)))) {
94
95 InnerNamespaceInfo Info;
96 Info.NamespaceLoc = ConsumeToken();
97
98 if (Tok.is(tok::kw_inline)) {
99 Info.InlineLoc = ConsumeToken();
100 if (FirstNestedInlineLoc.isInvalid())
101 FirstNestedInlineLoc = Info.InlineLoc;
102 }
103
104 Info.Ident = Tok.getIdentifierInfo();
105 Info.IdentLoc = ConsumeToken();
106
107 ExtraNSs.push_back(Info);
Richard Trieu61384cb2011-05-26 20:11:09 +0000108 }
Chris Lattnera5235172007-08-25 06:57:03 +0000109 }
Mike Stump11289f42009-09-09 15:08:12 +0000110
Aaron Ballmanc0ae7df2014-11-08 17:07:15 +0000111 // A nested namespace definition cannot have attributes.
Erich Keane53f391d2018-11-12 17:19:48 +0000112 if (!ExtraNSs.empty() && attrLoc.isValid())
Aaron Ballmanc0ae7df2014-11-08 17:07:15 +0000113 Diag(attrLoc, diag::err_unexpected_nested_namespace_attribute);
114
Chris Lattnera5235172007-08-25 06:57:03 +0000115 // Read label attributes, if present.
Douglas Gregor6b6bba42009-06-17 19:49:00 +0000116 if (Tok.is(tok::kw___attribute)) {
Aaron Ballman730476b2014-11-08 15:33:35 +0000117 attrLoc = Tok.getLocation();
John McCall53fa7142010-12-24 02:08:15 +0000118 ParseGNUAttributes(attrs);
Douglas Gregor6b6bba42009-06-17 19:49:00 +0000119 }
Mike Stump11289f42009-09-09 15:08:12 +0000120
Douglas Gregor6b6bba42009-06-17 19:49:00 +0000121 if (Tok.is(tok::equal)) {
Craig Topper161e4db2014-05-21 06:02:52 +0000122 if (!Ident) {
Alp Tokerec543272013-12-24 09:48:30 +0000123 Diag(Tok, diag::err_expected) << tok::identifier;
Nico Weber729f1e22012-10-27 23:44:27 +0000124 // Skip to end of the definition and eat the ';'.
125 SkipUntil(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +0000126 return nullptr;
Nico Weber729f1e22012-10-27 23:44:27 +0000127 }
Aaron Ballman730476b2014-11-08 15:33:35 +0000128 if (attrLoc.isValid())
129 Diag(attrLoc, diag::err_unexpected_namespace_attributes_alias);
Sebastian Redl67667942010-08-27 23:12:46 +0000130 if (InlineLoc.isValid())
131 Diag(InlineLoc, diag::err_inline_namespace_alias)
132 << FixItHint::CreateRemoval(InlineLoc);
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +0000133 Decl *NSAlias = ParseNamespaceAlias(NamespaceLoc, IdentLoc, Ident, DeclEnd);
134 return Actions.ConvertDeclToDeclGroup(NSAlias);
135}
Mike Stump11289f42009-09-09 15:08:12 +0000136
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000137 BalancedDelimiterTracker T(*this, tok::l_brace);
138 if (T.consumeOpen()) {
Alp Tokerec543272013-12-24 09:48:30 +0000139 if (Ident)
140 Diag(Tok, diag::err_expected) << tok::l_brace;
141 else
142 Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace;
David Blaikie0403cb12016-01-15 23:43:25 +0000143 return nullptr;
Chris Lattnera5235172007-08-25 06:57:03 +0000144 }
Mike Stump11289f42009-09-09 15:08:12 +0000145
Fangrui Song6907ce22018-07-30 19:24:48 +0000146 if (getCurScope()->isClassScope() || getCurScope()->isTemplateParamScope() ||
147 getCurScope()->isInObjcMethodScope() || getCurScope()->getBlockParent() ||
Douglas Gregor0be31a22010-07-02 17:43:08 +0000148 getCurScope()->getFnParent()) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000149 Diag(T.getOpenLocation(), diag::err_namespace_nonnamespace_scope);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000150 SkipUntil(tok::r_brace);
David Blaikie0403cb12016-01-15 23:43:25 +0000151 return nullptr;
Douglas Gregor05cfc292010-05-14 05:08:22 +0000152 }
153
Erich Keane53f391d2018-11-12 17:19:48 +0000154 if (ExtraNSs.empty()) {
Richard Smith13307f52014-11-08 05:37:34 +0000155 // Normal namespace definition, not a nested-namespace-definition.
156 } else if (InlineLoc.isValid()) {
157 Diag(InlineLoc, diag::err_inline_nested_namespace_definition);
Erich Keane53f391d2018-11-12 17:19:48 +0000158 } else if (getLangOpts().CPlusPlus2a) {
159 Diag(ExtraNSs[0].NamespaceLoc,
Richard Smith13307f52014-11-08 05:37:34 +0000160 diag::warn_cxx14_compat_nested_namespace_definition);
Erich Keane53f391d2018-11-12 17:19:48 +0000161 if (FirstNestedInlineLoc.isValid())
162 Diag(FirstNestedInlineLoc,
163 diag::warn_cxx17_compat_inline_nested_namespace_definition);
164 } else if (getLangOpts().CPlusPlus17) {
165 Diag(ExtraNSs[0].NamespaceLoc,
166 diag::warn_cxx14_compat_nested_namespace_definition);
167 if (FirstNestedInlineLoc.isValid())
168 Diag(FirstNestedInlineLoc, diag::ext_inline_nested_namespace_definition);
Richard Smith13307f52014-11-08 05:37:34 +0000169 } else {
Richard Trieu61384cb2011-05-26 20:11:09 +0000170 TentativeParsingAction TPA(*this);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000171 SkipUntil(tok::r_brace, StopBeforeMatch);
Richard Trieu61384cb2011-05-26 20:11:09 +0000172 Token rBraceToken = Tok;
173 TPA.Revert();
174
175 if (!rBraceToken.is(tok::r_brace)) {
Erich Keane53f391d2018-11-12 17:19:48 +0000176 Diag(ExtraNSs[0].NamespaceLoc, diag::ext_nested_namespace_definition)
177 << SourceRange(ExtraNSs.front().NamespaceLoc,
178 ExtraNSs.back().IdentLoc);
Richard Trieu61384cb2011-05-26 20:11:09 +0000179 } else {
Benjamin Kramerf546f412011-05-26 21:32:30 +0000180 std::string NamespaceFix;
Erich Keane53f391d2018-11-12 17:19:48 +0000181 for (const auto &ExtraNS : ExtraNSs) {
Erich Keanea946acd2018-11-12 21:08:41 +0000182 NamespaceFix += " { ";
183 if (ExtraNS.InlineLoc.isValid())
184 NamespaceFix += "inline ";
185 NamespaceFix += "namespace ";
Erich Keane53f391d2018-11-12 17:19:48 +0000186 NamespaceFix += ExtraNS.Ident->getName();
Richard Trieu61384cb2011-05-26 20:11:09 +0000187 }
Benjamin Kramerf546f412011-05-26 21:32:30 +0000188
Richard Trieu61384cb2011-05-26 20:11:09 +0000189 std::string RBraces;
Erich Keane53f391d2018-11-12 17:19:48 +0000190 for (unsigned i = 0, e = ExtraNSs.size(); i != e; ++i)
Richard Trieu61384cb2011-05-26 20:11:09 +0000191 RBraces += "} ";
Benjamin Kramerf546f412011-05-26 21:32:30 +0000192
Erich Keane53f391d2018-11-12 17:19:48 +0000193 Diag(ExtraNSs[0].NamespaceLoc, diag::ext_nested_namespace_definition)
194 << FixItHint::CreateReplacement(
195 SourceRange(ExtraNSs.front().NamespaceLoc,
196 ExtraNSs.back().IdentLoc),
197 NamespaceFix)
Richard Trieu61384cb2011-05-26 20:11:09 +0000198 << FixItHint::CreateInsertion(rBraceToken.getLocation(), RBraces);
199 }
Erich Keane53f391d2018-11-12 17:19:48 +0000200
201 // Warn about nested inline namespaces.
202 if (FirstNestedInlineLoc.isValid())
203 Diag(FirstNestedInlineLoc, diag::ext_inline_nested_namespace_definition);
Richard Trieu61384cb2011-05-26 20:11:09 +0000204 }
205
Sebastian Redl5a5f2c72010-08-31 00:36:45 +0000206 // If we're still good, complain about inline namespaces in non-C++0x now.
Richard Smith5d164bc2011-10-15 05:09:34 +0000207 if (InlineLoc.isValid())
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000208 Diag(InlineLoc, getLangOpts().CPlusPlus11 ?
Richard Smith5d164bc2011-10-15 05:09:34 +0000209 diag::warn_cxx98_compat_inline_namespace : diag::ext_inline_namespace);
Sebastian Redl5a5f2c72010-08-31 00:36:45 +0000210
Chris Lattner4de55aa2009-03-29 14:02:43 +0000211 // Enter a scope for the namespace.
212 ParseScope NamespaceScope(this, Scope::DeclScope);
213
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +0000214 UsingDirectiveDecl *ImplicitUsingDirectiveDecl = nullptr;
Erich Keanec480f302018-07-12 21:09:05 +0000215 Decl *NamespcDecl = Actions.ActOnStartNamespaceDef(
216 getCurScope(), InlineLoc, NamespaceLoc, IdentLoc, Ident,
217 T.getOpenLocation(), attrs, ImplicitUsingDirectiveDecl);
Chris Lattner4de55aa2009-03-29 14:02:43 +0000218
Jordan Rose1e879d82018-03-23 00:07:18 +0000219 PrettyDeclStackTraceEntry CrashInfo(Actions.Context, NamespcDecl,
220 NamespaceLoc, "parsing namespace");
Mike Stump11289f42009-09-09 15:08:12 +0000221
Fangrui Song6907ce22018-07-30 19:24:48 +0000222 // Parse the contents of the namespace. This includes parsing recovery on
Richard Trieu61384cb2011-05-26 20:11:09 +0000223 // any improperly nested namespaces.
Erich Keane53f391d2018-11-12 17:19:48 +0000224 ParseInnerNamespace(ExtraNSs, 0, InlineLoc, attrs, T);
Mike Stump11289f42009-09-09 15:08:12 +0000225
Chris Lattner4de55aa2009-03-29 14:02:43 +0000226 // Leave the namespace scope.
227 NamespaceScope.Exit();
228
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000229 DeclEnd = T.getCloseLocation();
230 Actions.ActOnFinishNamespaceDef(NamespcDecl, DeclEnd);
Fangrui Song6907ce22018-07-30 19:24:48 +0000231
232 return Actions.ConvertDeclToDeclGroup(NamespcDecl,
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +0000233 ImplicitUsingDirectiveDecl);
Chris Lattnera5235172007-08-25 06:57:03 +0000234}
Chris Lattner38376f12008-01-12 07:05:38 +0000235
Richard Trieu61384cb2011-05-26 20:11:09 +0000236/// ParseInnerNamespace - Parse the contents of a namespace.
Erich Keane53f391d2018-11-12 17:19:48 +0000237void Parser::ParseInnerNamespace(const InnerNamespaceInfoList &InnerNSs,
Richard Smith13307f52014-11-08 05:37:34 +0000238 unsigned int index, SourceLocation &InlineLoc,
239 ParsedAttributes &attrs,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000240 BalancedDelimiterTracker &Tracker) {
Erich Keane53f391d2018-11-12 17:19:48 +0000241 if (index == InnerNSs.size()) {
Richard Smith752ada82015-11-17 23:32:01 +0000242 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
243 Tok.isNot(tok::eof)) {
Richard Trieu61384cb2011-05-26 20:11:09 +0000244 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +0000245 MaybeParseCXX11Attributes(attrs);
Richard Trieu61384cb2011-05-26 20:11:09 +0000246 ParseExternalDeclaration(attrs);
247 }
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000248
249 // The caller is what called check -- we are simply calling
250 // the close for it.
251 Tracker.consumeClose();
Richard Trieu61384cb2011-05-26 20:11:09 +0000252
253 return;
254 }
255
Richard Smith13307f52014-11-08 05:37:34 +0000256 // Handle a nested namespace definition.
257 // FIXME: Preserve the source information through to the AST rather than
258 // desugaring it here.
Richard Trieu61384cb2011-05-26 20:11:09 +0000259 ParseScope NamespaceScope(this, Scope::DeclScope);
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +0000260 UsingDirectiveDecl *ImplicitUsingDirectiveDecl = nullptr;
Erich Keanec480f302018-07-12 21:09:05 +0000261 Decl *NamespcDecl = Actions.ActOnStartNamespaceDef(
Erich Keane53f391d2018-11-12 17:19:48 +0000262 getCurScope(), InnerNSs[index].InlineLoc, InnerNSs[index].NamespaceLoc,
263 InnerNSs[index].IdentLoc, InnerNSs[index].Ident,
264 Tracker.getOpenLocation(), attrs, ImplicitUsingDirectiveDecl);
Fangrui Song6907ce22018-07-30 19:24:48 +0000265 assert(!ImplicitUsingDirectiveDecl &&
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +0000266 "nested namespace definition cannot define anonymous namespace");
Richard Trieu61384cb2011-05-26 20:11:09 +0000267
Erich Keanede6480a32018-11-13 15:48:08 +0000268 ParseInnerNamespace(InnerNSs, ++index, InlineLoc, attrs, Tracker);
Richard Trieu61384cb2011-05-26 20:11:09 +0000269
270 NamespaceScope.Exit();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000271 Actions.ActOnFinishNamespaceDef(NamespcDecl, Tracker.getCloseLocation());
Richard Trieu61384cb2011-05-26 20:11:09 +0000272}
273
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000274/// ParseNamespaceAlias - Parse the part after the '=' in a namespace
275/// alias definition.
276///
John McCall48871652010-08-21 09:40:31 +0000277Decl *Parser::ParseNamespaceAlias(SourceLocation NamespaceLoc,
John McCall084e83d2011-03-24 11:26:52 +0000278 SourceLocation AliasLoc,
279 IdentifierInfo *Alias,
280 SourceLocation &DeclEnd) {
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000281 assert(Tok.is(tok::equal) && "Not equal token");
Mike Stump11289f42009-09-09 15:08:12 +0000282
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000283 ConsumeToken(); // eat the '='.
Mike Stump11289f42009-09-09 15:08:12 +0000284
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000285 if (Tok.is(tok::code_completion)) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000286 Actions.CodeCompleteNamespaceAliasDecl(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000287 cutOffParsing();
Craig Topper161e4db2014-05-21 06:02:52 +0000288 return nullptr;
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000289 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000290
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000291 CXXScopeSpec SS;
292 // Parse (optional) nested-name-specifier.
Matthias Gehredc01bb42017-03-17 21:41:20 +0000293 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false,
294 /*MayBePseudoDestructor=*/nullptr,
295 /*IsTypename=*/false,
296 /*LastII=*/nullptr,
297 /*OnlyNamespace=*/true);
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000298
Matthias Gehredc01bb42017-03-17 21:41:20 +0000299 if (Tok.isNot(tok::identifier)) {
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000300 Diag(Tok, diag::err_expected_namespace_name);
301 // Skip to end of the definition and eat the ';'.
302 SkipUntil(tok::semi);
Craig Topper161e4db2014-05-21 06:02:52 +0000303 return nullptr;
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000304 }
305
Matthias Gehredc01bb42017-03-17 21:41:20 +0000306 if (SS.isInvalid()) {
307 // Diagnostics have been emitted in ParseOptionalCXXScopeSpecifier.
308 // Skip to end of the definition and eat the ';'.
309 SkipUntil(tok::semi);
310 return nullptr;
311 }
312
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000313 // Parse identifier.
Anders Carlsson47952ae2009-03-28 22:53:22 +0000314 IdentifierInfo *Ident = Tok.getIdentifierInfo();
315 SourceLocation IdentLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000316
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000317 // Eat the ';'.
Chris Lattner49836b42009-04-02 04:16:50 +0000318 DeclEnd = Tok.getLocation();
Alp Toker383d2c42014-01-01 03:08:43 +0000319 if (ExpectAndConsume(tok::semi, diag::err_expected_semi_after_namespace_name))
320 SkipUntil(tok::semi);
Mike Stump11289f42009-09-09 15:08:12 +0000321
Craig Topperff354282015-11-14 18:16:00 +0000322 return Actions.ActOnNamespaceAliasDef(getCurScope(), NamespaceLoc, AliasLoc,
323 Alias, SS, IdentLoc, Ident);
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000324}
325
Chris Lattner38376f12008-01-12 07:05:38 +0000326/// ParseLinkage - We know that the current token is a string_literal
327/// and just before that, that extern was seen.
328///
329/// linkage-specification: [C++ 7.5p2: dcl.link]
330/// 'extern' string-literal '{' declaration-seq[opt] '}'
331/// 'extern' string-literal declaration
332///
Faisal Vali421b2d12017-12-29 05:41:00 +0000333Decl *Parser::ParseLinkage(ParsingDeclSpec &DS, DeclaratorContext Context) {
Richard Smith4ee696d2014-02-17 23:25:27 +0000334 assert(isTokenStringLiteral() && "Not a string literal!");
335 ExprResult Lang = ParseStringLiteralExpression(false);
Chris Lattner38376f12008-01-12 07:05:38 +0000336
Douglas Gregor07665a62009-01-05 19:45:36 +0000337 ParseScope LinkageScope(this, Scope::DeclScope);
Richard Smith4ee696d2014-02-17 23:25:27 +0000338 Decl *LinkageSpec =
339 Lang.isInvalid()
Craig Topper161e4db2014-05-21 06:02:52 +0000340 ? nullptr
Richard Smith4ee696d2014-02-17 23:25:27 +0000341 : Actions.ActOnStartLinkageSpecification(
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000342 getCurScope(), DS.getSourceRange().getBegin(), Lang.get(),
Richard Smith4ee696d2014-02-17 23:25:27 +0000343 Tok.is(tok::l_brace) ? Tok.getLocation() : SourceLocation());
Douglas Gregor07665a62009-01-05 19:45:36 +0000344
John McCall084e83d2011-03-24 11:26:52 +0000345 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +0000346 MaybeParseCXX11Attributes(attrs);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000347
Douglas Gregor07665a62009-01-05 19:45:36 +0000348 if (Tok.isNot(tok::l_brace)) {
Abramo Bagnara4d423992011-05-01 16:25:54 +0000349 // Reset the source range in DS, as the leading "extern"
350 // does not really belong to the inner declaration ...
351 DS.SetRangeStart(SourceLocation());
352 DS.SetRangeEnd(SourceLocation());
353 // ... but anyway remember that such an "extern" was seen.
Abramo Bagnaraed5b6892010-07-30 16:47:02 +0000354 DS.setExternInLinkageSpec(true);
John McCall53fa7142010-12-24 02:08:15 +0000355 ParseExternalDeclaration(attrs, &DS);
Richard Smith4ee696d2014-02-17 23:25:27 +0000356 return LinkageSpec ? Actions.ActOnFinishLinkageSpecification(
357 getCurScope(), LinkageSpec, SourceLocation())
Craig Topper161e4db2014-05-21 06:02:52 +0000358 : nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000359 }
Douglas Gregor29ff7d02008-12-16 22:23:02 +0000360
Douglas Gregorb65a9132010-02-07 08:38:28 +0000361 DS.abort();
362
John McCall53fa7142010-12-24 02:08:15 +0000363 ProhibitAttributes(attrs);
Alexis Hunt96d5c762009-11-21 08:43:09 +0000364
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000365 BalancedDelimiterTracker T(*this, tok::l_brace);
366 T.consumeOpen();
Richard Smith77944862014-03-02 05:58:18 +0000367
368 unsigned NestedModules = 0;
369 while (true) {
370 switch (Tok.getKind()) {
371 case tok::annot_module_begin:
372 ++NestedModules;
373 ParseTopLevelDecl();
374 continue;
375
376 case tok::annot_module_end:
377 if (!NestedModules)
378 break;
379 --NestedModules;
380 ParseTopLevelDecl();
381 continue;
382
383 case tok::annot_module_include:
384 ParseTopLevelDecl();
385 continue;
386
387 case tok::eof:
388 break;
389
390 case tok::r_brace:
391 if (!NestedModules)
392 break;
Reid Kleckner4dc0b1a2018-11-01 19:54:45 +0000393 LLVM_FALLTHROUGH;
Richard Smith77944862014-03-02 05:58:18 +0000394 default:
395 ParsedAttributesWithRange attrs(AttrFactory);
396 MaybeParseCXX11Attributes(attrs);
Richard Smith77944862014-03-02 05:58:18 +0000397 ParseExternalDeclaration(attrs);
398 continue;
399 }
400
401 break;
Chris Lattner38376f12008-01-12 07:05:38 +0000402 }
403
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000404 T.consumeClose();
Richard Smith4ee696d2014-02-17 23:25:27 +0000405 return LinkageSpec ? Actions.ActOnFinishLinkageSpecification(
406 getCurScope(), LinkageSpec, T.getCloseLocation())
Craig Topper161e4db2014-05-21 06:02:52 +0000407 : nullptr;
Chris Lattner38376f12008-01-12 07:05:38 +0000408}
Douglas Gregor556877c2008-04-13 21:30:24 +0000409
Richard Smith8df390f2016-09-08 23:14:54 +0000410/// Parse a C++ Modules TS export-declaration.
411///
412/// export-declaration:
413/// 'export' declaration
414/// 'export' '{' declaration-seq[opt] '}'
415///
416Decl *Parser::ParseExportDeclaration() {
417 assert(Tok.is(tok::kw_export));
418 SourceLocation ExportLoc = ConsumeToken();
419
420 ParseScope ExportScope(this, Scope::DeclScope);
421 Decl *ExportDecl = Actions.ActOnStartExportDecl(
422 getCurScope(), ExportLoc,
423 Tok.is(tok::l_brace) ? Tok.getLocation() : SourceLocation());
424
425 if (Tok.isNot(tok::l_brace)) {
426 // FIXME: Factor out a ParseExternalDeclarationWithAttrs.
427 ParsedAttributesWithRange Attrs(AttrFactory);
428 MaybeParseCXX11Attributes(Attrs);
429 MaybeParseMicrosoftAttributes(Attrs);
430 ParseExternalDeclaration(Attrs);
431 return Actions.ActOnFinishExportDecl(getCurScope(), ExportDecl,
432 SourceLocation());
433 }
434
435 BalancedDelimiterTracker T(*this, tok::l_brace);
436 T.consumeOpen();
437
438 // The Modules TS draft says "An export-declaration shall declare at least one
439 // entity", but the intent is that it shall contain at least one declaration.
Richard Smithe181de72019-04-22 22:50:11 +0000440 if (Tok.is(tok::r_brace) && getLangOpts().ModulesTS) {
Richard Smith8df390f2016-09-08 23:14:54 +0000441 Diag(ExportLoc, diag::err_export_empty)
442 << SourceRange(ExportLoc, Tok.getLocation());
Richard Smithe181de72019-04-22 22:50:11 +0000443 }
Richard Smith8df390f2016-09-08 23:14:54 +0000444
445 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
446 Tok.isNot(tok::eof)) {
447 ParsedAttributesWithRange Attrs(AttrFactory);
448 MaybeParseCXX11Attributes(Attrs);
449 MaybeParseMicrosoftAttributes(Attrs);
450 ParseExternalDeclaration(Attrs);
451 }
452
453 T.consumeClose();
454 return Actions.ActOnFinishExportDecl(getCurScope(), ExportDecl,
455 T.getCloseLocation());
456}
457
Douglas Gregord7c4d982008-12-30 03:27:21 +0000458/// ParseUsingDirectiveOrDeclaration - Parse C++ using using-declaration or
459/// using-directive. Assumes that current token is 'using'.
Richard Smith6f1daa42016-12-16 00:58:48 +0000460Parser::DeclGroupPtrTy
Faisal Vali421b2d12017-12-29 05:41:00 +0000461Parser::ParseUsingDirectiveOrDeclaration(DeclaratorContext Context,
John McCall9b72f892010-11-10 02:40:36 +0000462 const ParsedTemplateInfo &TemplateInfo,
Richard Smith6f1daa42016-12-16 00:58:48 +0000463 SourceLocation &DeclEnd,
464 ParsedAttributesWithRange &attrs) {
Douglas Gregord7c4d982008-12-30 03:27:21 +0000465 assert(Tok.is(tok::kw_using) && "Not using token");
Fariborz Jahanian4bf82622011-08-22 17:59:19 +0000466 ObjCDeclContextSwitch ObjCDC(*this);
Fangrui Song6907ce22018-07-30 19:24:48 +0000467
Douglas Gregord7c4d982008-12-30 03:27:21 +0000468 // Eat 'using'.
469 SourceLocation UsingLoc = ConsumeToken();
470
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000471 if (Tok.is(tok::code_completion)) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000472 Actions.CodeCompleteUsing(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000473 cutOffParsing();
Craig Topper161e4db2014-05-21 06:02:52 +0000474 return nullptr;
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000475 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000476
Richard Trieu2efd3052019-05-01 23:33:49 +0000477 // Consume unexpected 'template' keywords.
478 while (Tok.is(tok::kw_template)) {
479 SourceLocation TemplateLoc = ConsumeToken();
480 Diag(TemplateLoc, diag::err_unexpected_template_after_using)
481 << FixItHint::CreateRemoval(TemplateLoc);
482 }
483
John McCall9b72f892010-11-10 02:40:36 +0000484 // 'using namespace' means this is a using-directive.
485 if (Tok.is(tok::kw_namespace)) {
486 // Template parameters are always an error here.
487 if (TemplateInfo.Kind) {
488 SourceRange R = TemplateInfo.getSourceRange();
Craig Topper54a6a682015-11-14 18:16:08 +0000489 Diag(UsingLoc, diag::err_templated_using_directive_declaration)
490 << 0 /* directive */ << R << FixItHint::CreateRemoval(R);
John McCall9b72f892010-11-10 02:40:36 +0000491 }
Alexis Hunt96d5c762009-11-21 08:43:09 +0000492
Richard Smith6f1daa42016-12-16 00:58:48 +0000493 Decl *UsingDir = ParseUsingDirective(Context, UsingLoc, DeclEnd, attrs);
494 return Actions.ConvertDeclToDeclGroup(UsingDir);
John McCall9b72f892010-11-10 02:40:36 +0000495 }
496
Richard Smithdda56e42011-04-15 14:24:37 +0000497 // Otherwise, it must be a using-declaration or an alias-declaration.
John McCall9b72f892010-11-10 02:40:36 +0000498
499 // Using declarations can't have attributes.
John McCall53fa7142010-12-24 02:08:15 +0000500 ProhibitAttributes(attrs);
Chris Lattner9b01ca12009-01-06 06:55:51 +0000501
Fariborz Jahanian4bf82622011-08-22 17:59:19 +0000502 return ParseUsingDeclaration(Context, TemplateInfo, UsingLoc, DeclEnd,
Richard Smith6f1daa42016-12-16 00:58:48 +0000503 AS_none);
Douglas Gregord7c4d982008-12-30 03:27:21 +0000504}
505
506/// ParseUsingDirective - Parse C++ using-directive, assumes
507/// that current token is 'namespace' and 'using' was already parsed.
508///
509/// using-directive: [C++ 7.3.p4: namespace.udir]
510/// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
511/// namespace-name ;
512/// [GNU] using-directive:
513/// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
514/// namespace-name attributes[opt] ;
515///
Faisal Vali421b2d12017-12-29 05:41:00 +0000516Decl *Parser::ParseUsingDirective(DeclaratorContext Context,
John McCall9b72f892010-11-10 02:40:36 +0000517 SourceLocation UsingLoc,
518 SourceLocation &DeclEnd,
John McCall53fa7142010-12-24 02:08:15 +0000519 ParsedAttributes &attrs) {
Douglas Gregord7c4d982008-12-30 03:27:21 +0000520 assert(Tok.is(tok::kw_namespace) && "Not 'namespace' token");
521
522 // Eat 'namespace'.
523 SourceLocation NamespcLoc = ConsumeToken();
524
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000525 if (Tok.is(tok::code_completion)) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000526 Actions.CodeCompleteUsingDirective(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000527 cutOffParsing();
Craig Topper161e4db2014-05-21 06:02:52 +0000528 return nullptr;
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000529 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000530
Douglas Gregord7c4d982008-12-30 03:27:21 +0000531 CXXScopeSpec SS;
532 // Parse (optional) nested-name-specifier.
Matthias Gehredc01bb42017-03-17 21:41:20 +0000533 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false,
534 /*MayBePseudoDestructor=*/nullptr,
535 /*IsTypename=*/false,
536 /*LastII=*/nullptr,
537 /*OnlyNamespace=*/true);
Douglas Gregord7c4d982008-12-30 03:27:21 +0000538
Craig Topper161e4db2014-05-21 06:02:52 +0000539 IdentifierInfo *NamespcName = nullptr;
Douglas Gregord7c4d982008-12-30 03:27:21 +0000540 SourceLocation IdentLoc = SourceLocation();
541
542 // Parse namespace-name.
Matthias Gehredc01bb42017-03-17 21:41:20 +0000543 if (Tok.isNot(tok::identifier)) {
Douglas Gregord7c4d982008-12-30 03:27:21 +0000544 Diag(Tok, diag::err_expected_namespace_name);
545 // If there was invalid namespace name, skip to end of decl, and eat ';'.
546 SkipUntil(tok::semi);
547 // FIXME: Are there cases, when we would like to call ActOnUsingDirective?
Craig Topper161e4db2014-05-21 06:02:52 +0000548 return nullptr;
Douglas Gregord7c4d982008-12-30 03:27:21 +0000549 }
Mike Stump11289f42009-09-09 15:08:12 +0000550
Matthias Gehredc01bb42017-03-17 21:41:20 +0000551 if (SS.isInvalid()) {
552 // Diagnostics have been emitted in ParseOptionalCXXScopeSpecifier.
553 // Skip to end of the definition and eat the ';'.
554 SkipUntil(tok::semi);
555 return nullptr;
556 }
557
Chris Lattnerce1da2c2009-01-06 07:27:21 +0000558 // Parse identifier.
559 NamespcName = Tok.getIdentifierInfo();
560 IdentLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000561
Chris Lattnerce1da2c2009-01-06 07:27:21 +0000562 // Parse (optional) attributes (most likely GNU strong-using extension).
Alexis Hunt96d5c762009-11-21 08:43:09 +0000563 bool GNUAttr = false;
564 if (Tok.is(tok::kw___attribute)) {
565 GNUAttr = true;
John McCall53fa7142010-12-24 02:08:15 +0000566 ParseGNUAttributes(attrs);
Alexis Hunt96d5c762009-11-21 08:43:09 +0000567 }
Mike Stump11289f42009-09-09 15:08:12 +0000568
Chris Lattnerce1da2c2009-01-06 07:27:21 +0000569 // Eat ';'.
Chris Lattner49836b42009-04-02 04:16:50 +0000570 DeclEnd = Tok.getLocation();
Alp Toker383d2c42014-01-01 03:08:43 +0000571 if (ExpectAndConsume(tok::semi,
572 GNUAttr ? diag::err_expected_semi_after_attribute_list
573 : diag::err_expected_semi_after_namespace_name))
574 SkipUntil(tok::semi);
Douglas Gregord7c4d982008-12-30 03:27:21 +0000575
Douglas Gregor0be31a22010-07-02 17:43:08 +0000576 return Actions.ActOnUsingDirective(getCurScope(), UsingLoc, NamespcLoc, SS,
Erich Keanec480f302018-07-12 21:09:05 +0000577 IdentLoc, NamespcName, attrs);
Douglas Gregord7c4d982008-12-30 03:27:21 +0000578}
579
Richard Smith6f1daa42016-12-16 00:58:48 +0000580/// Parse a using-declarator (or the identifier in a C++11 alias-declaration).
Douglas Gregord7c4d982008-12-30 03:27:21 +0000581///
Richard Smith6f1daa42016-12-16 00:58:48 +0000582/// using-declarator:
583/// 'typename'[opt] nested-name-specifier unqualified-id
Douglas Gregord7c4d982008-12-30 03:27:21 +0000584///
Faisal Vali421b2d12017-12-29 05:41:00 +0000585bool Parser::ParseUsingDeclarator(DeclaratorContext Context,
586 UsingDeclarator &D) {
Richard Smith6f1daa42016-12-16 00:58:48 +0000587 D.clear();
Douglas Gregorfec52632009-06-20 00:51:54 +0000588
589 // Ignore optional 'typename'.
Douglas Gregor220f4272009-11-04 16:30:06 +0000590 // FIXME: This is wrong; we should parse this as a typename-specifier.
Richard Smith6f1daa42016-12-16 00:58:48 +0000591 TryConsumeToken(tok::kw_typename, D.TypenameLoc);
Douglas Gregorfec52632009-06-20 00:51:54 +0000592
Nikola Smiljanic67860242014-09-26 00:28:20 +0000593 if (Tok.is(tok::kw___super)) {
594 Diag(Tok.getLocation(), diag::err_super_in_using_declaration);
Richard Smith6f1daa42016-12-16 00:58:48 +0000595 return true;
Nikola Smiljanic67860242014-09-26 00:28:20 +0000596 }
597
Douglas Gregorfec52632009-06-20 00:51:54 +0000598 // Parse nested-name-specifier.
Craig Topper161e4db2014-05-21 06:02:52 +0000599 IdentifierInfo *LastII = nullptr;
Richard Smithb23c5e82019-05-09 03:31:27 +0000600 if (ParseOptionalCXXScopeSpecifier(D.SS, nullptr, /*EnteringContext=*/false,
601 /*MayBePseudoDtor=*/nullptr,
602 /*IsTypename=*/false,
603 /*LastII=*/&LastII))
604 return true;
Richard Smith6f1daa42016-12-16 00:58:48 +0000605 if (D.SS.isInvalid())
606 return true;
Richard Smith7447af42013-03-26 01:15:19 +0000607
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000608 // Parse the unqualified-id. We allow parsing of both constructor and
Douglas Gregor220f4272009-11-04 16:30:06 +0000609 // destructor names and allow the action module to diagnose any semantic
610 // errors.
Richard Smith7447af42013-03-26 01:15:19 +0000611 //
612 // C++11 [class.qual]p2:
613 // [...] in a using-declaration that is a member-declaration, if the name
614 // specified after the nested-name-specifier is the same as the identifier
615 // or the simple-template-id's template-name in the last component of the
616 // nested-name-specifier, the name is [...] considered to name the
617 // constructor.
Faisal Vali421b2d12017-12-29 05:41:00 +0000618 if (getLangOpts().CPlusPlus11 &&
619 Context == DeclaratorContext::MemberContext &&
Richard Smith151c4562016-12-20 21:35:28 +0000620 Tok.is(tok::identifier) &&
621 (NextToken().is(tok::semi) || NextToken().is(tok::comma) ||
622 NextToken().is(tok::ellipsis)) &&
Richard Smith6f1daa42016-12-16 00:58:48 +0000623 D.SS.isNotEmpty() && LastII == Tok.getIdentifierInfo() &&
624 !D.SS.getScopeRep()->getAsNamespace() &&
625 !D.SS.getScopeRep()->getAsNamespaceAlias()) {
Richard Smith7447af42013-03-26 01:15:19 +0000626 SourceLocation IdLoc = ConsumeToken();
Richard Smith6f1daa42016-12-16 00:58:48 +0000627 ParsedType Type =
628 Actions.getInheritingConstructorName(D.SS, IdLoc, *LastII);
629 D.Name.setConstructorName(Type, IdLoc, IdLoc);
630 } else {
631 if (ParseUnqualifiedId(
632 D.SS, /*EnteringContext=*/false,
633 /*AllowDestructorName=*/true,
634 /*AllowConstructorName=*/!(Tok.is(tok::identifier) &&
635 NextToken().is(tok::equal)),
Richard Smith35845152017-02-07 01:37:30 +0000636 /*AllowDeductionGuide=*/false,
Richard Smithc08b6932018-04-27 02:00:13 +0000637 nullptr, nullptr, D.Name))
Richard Smith6f1daa42016-12-16 00:58:48 +0000638 return true;
Douglas Gregorfec52632009-06-20 00:51:54 +0000639 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000640
Richard Smith151c4562016-12-20 21:35:28 +0000641 if (TryConsumeToken(tok::ellipsis, D.EllipsisLoc))
Aaron Ballmanc351fba2017-12-04 20:27:34 +0000642 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17 ?
Richard Smithb115e5d2017-08-13 23:37:29 +0000643 diag::warn_cxx17_compat_using_declaration_pack :
Richard Smith151c4562016-12-20 21:35:28 +0000644 diag::ext_using_declaration_pack);
Richard Smith6f1daa42016-12-16 00:58:48 +0000645
646 return false;
647}
648
649/// ParseUsingDeclaration - Parse C++ using-declaration or alias-declaration.
650/// Assumes that 'using' was already seen.
651///
652/// using-declaration: [C++ 7.3.p3: namespace.udecl]
653/// 'using' using-declarator-list[opt] ;
654///
655/// using-declarator-list: [C++1z]
656/// using-declarator '...'[opt]
657/// using-declarator-list ',' using-declarator '...'[opt]
658///
659/// using-declarator-list: [C++98-14]
660/// using-declarator
661///
662/// alias-declaration: C++11 [dcl.dcl]p1
663/// 'using' identifier attribute-specifier-seq[opt] = type-id ;
664///
665Parser::DeclGroupPtrTy
Faisal Vali421b2d12017-12-29 05:41:00 +0000666Parser::ParseUsingDeclaration(DeclaratorContext Context,
Richard Smith6f1daa42016-12-16 00:58:48 +0000667 const ParsedTemplateInfo &TemplateInfo,
668 SourceLocation UsingLoc, SourceLocation &DeclEnd,
669 AccessSpecifier AS) {
670 // Check for misplaced attributes before the identifier in an
671 // alias-declaration.
672 ParsedAttributesWithRange MisplacedAttrs(AttrFactory);
673 MaybeParseCXX11Attributes(MisplacedAttrs);
674
675 UsingDeclarator D;
676 bool InvalidDeclarator = ParseUsingDeclarator(Context, D);
677
Richard Smithc2c8bb82013-10-15 01:34:54 +0000678 ParsedAttributesWithRange Attrs(AttrFactory);
Richard Smith37a45dd2013-10-24 01:21:09 +0000679 MaybeParseGNUAttributes(Attrs);
Richard Smith54ecd982013-02-20 19:22:51 +0000680 MaybeParseCXX11Attributes(Attrs);
Richard Smithdda56e42011-04-15 14:24:37 +0000681
682 // Maybe this is an alias-declaration.
Richard Smith6f1daa42016-12-16 00:58:48 +0000683 if (Tok.is(tok::equal)) {
684 if (InvalidDeclarator) {
685 SkipUntil(tok::semi);
686 return nullptr;
687 }
688
Richard Smithc2c8bb82013-10-15 01:34:54 +0000689 // If we had any misplaced attributes from earlier, this is where they
690 // should have been written.
691 if (MisplacedAttrs.Range.isValid()) {
692 Diag(MisplacedAttrs.Range.getBegin(), diag::err_attributes_not_allowed)
693 << FixItHint::CreateInsertionFromRange(
694 Tok.getLocation(),
695 CharSourceRange::getTokenRange(MisplacedAttrs.Range))
696 << FixItHint::CreateRemoval(MisplacedAttrs.Range);
697 Attrs.takeAllFrom(MisplacedAttrs);
698 }
699
Richard Smith6f1daa42016-12-16 00:58:48 +0000700 Decl *DeclFromDeclSpec = nullptr;
701 Decl *AD = ParseAliasDeclarationAfterDeclarator(
702 TemplateInfo, UsingLoc, D, DeclEnd, AS, Attrs, &DeclFromDeclSpec);
703 return Actions.ConvertDeclToDeclGroup(AD, DeclFromDeclSpec);
Alexis Hunt6aa9bee2012-06-23 05:07:58 +0000704 }
Mike Stump11289f42009-09-09 15:08:12 +0000705
Richard Smith6f1daa42016-12-16 00:58:48 +0000706 // C++11 attributes are not allowed on a using-declaration, but GNU ones
707 // are.
708 ProhibitAttributes(MisplacedAttrs);
709 ProhibitAttributes(Attrs);
Douglas Gregorfec52632009-06-20 00:51:54 +0000710
John McCall9b72f892010-11-10 02:40:36 +0000711 // Diagnose an attempt to declare a templated using-declaration.
Richard Smith810ad3e2013-01-29 10:02:16 +0000712 // In C++11, alias-declarations can be templates:
Richard Smithdda56e42011-04-15 14:24:37 +0000713 // template <...> using id = type;
Richard Smith6f1daa42016-12-16 00:58:48 +0000714 if (TemplateInfo.Kind) {
John McCall9b72f892010-11-10 02:40:36 +0000715 SourceRange R = TemplateInfo.getSourceRange();
Craig Topper54a6a682015-11-14 18:16:08 +0000716 Diag(UsingLoc, diag::err_templated_using_directive_declaration)
717 << 1 /* declaration */ << R << FixItHint::CreateRemoval(R);
John McCall9b72f892010-11-10 02:40:36 +0000718
719 // Unfortunately, we have to bail out instead of recovering by
720 // ignoring the parameters, just in case the nested name specifier
721 // depends on the parameters.
Craig Topper161e4db2014-05-21 06:02:52 +0000722 return nullptr;
John McCall9b72f892010-11-10 02:40:36 +0000723 }
724
Richard Smith6f1daa42016-12-16 00:58:48 +0000725 SmallVector<Decl *, 8> DeclsInGroup;
726 while (true) {
727 // Parse (optional) attributes (most likely GNU strong-using extension).
728 MaybeParseGNUAttributes(Attrs);
729
730 if (InvalidDeclarator)
731 SkipUntil(tok::comma, tok::semi, StopBeforeMatch);
732 else {
733 // "typename" keyword is allowed for identifiers only,
734 // because it may be a type definition.
735 if (D.TypenameLoc.isValid() &&
Faisal Vali2ab8c152017-12-30 04:15:27 +0000736 D.Name.getKind() != UnqualifiedIdKind::IK_Identifier) {
Richard Smith6f1daa42016-12-16 00:58:48 +0000737 Diag(D.Name.getSourceRange().getBegin(),
738 diag::err_typename_identifiers_only)
739 << FixItHint::CreateRemoval(SourceRange(D.TypenameLoc));
740 // Proceed parsing, but discard the typename keyword.
741 D.TypenameLoc = SourceLocation();
742 }
743
Richard Smith151c4562016-12-20 21:35:28 +0000744 Decl *UD = Actions.ActOnUsingDeclaration(getCurScope(), AS, UsingLoc,
745 D.TypenameLoc, D.SS, D.Name,
Erich Keanec480f302018-07-12 21:09:05 +0000746 D.EllipsisLoc, Attrs);
Richard Smith6f1daa42016-12-16 00:58:48 +0000747 if (UD)
748 DeclsInGroup.push_back(UD);
749 }
750
751 if (!TryConsumeToken(tok::comma))
752 break;
753
754 // Parse another using-declarator.
755 Attrs.clear();
756 InvalidDeclarator = ParseUsingDeclarator(Context, D);
Douglas Gregor882a61a2011-09-26 14:30:28 +0000757 }
758
Richard Smith6f1daa42016-12-16 00:58:48 +0000759 if (DeclsInGroup.size() > 1)
Aaron Ballmanc351fba2017-12-04 20:27:34 +0000760 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17 ?
Richard Smithb115e5d2017-08-13 23:37:29 +0000761 diag::warn_cxx17_compat_multi_using_declaration :
Richard Smith6f1daa42016-12-16 00:58:48 +0000762 diag::ext_multi_using_declaration);
763
764 // Eat ';'.
765 DeclEnd = Tok.getLocation();
766 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
767 !Attrs.empty() ? "attributes list"
768 : "using declaration"))
769 SkipUntil(tok::semi);
770
Richard Smith3beb7c62017-01-12 02:27:38 +0000771 return Actions.BuildDeclaratorGroup(DeclsInGroup);
Richard Smith6f1daa42016-12-16 00:58:48 +0000772}
773
Richard Smith6f1daa42016-12-16 00:58:48 +0000774Decl *Parser::ParseAliasDeclarationAfterDeclarator(
775 const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc,
776 UsingDeclarator &D, SourceLocation &DeclEnd, AccessSpecifier AS,
777 ParsedAttributes &Attrs, Decl **OwnedType) {
778 if (ExpectAndConsume(tok::equal)) {
779 SkipUntil(tok::semi);
780 return nullptr;
781 }
782
783 Diag(Tok.getLocation(), getLangOpts().CPlusPlus11 ?
784 diag::warn_cxx98_compat_alias_declaration :
785 diag::ext_alias_declaration);
786
787 // Type alias templates cannot be specialized.
788 int SpecKind = -1;
789 if (TemplateInfo.Kind == ParsedTemplateInfo::Template &&
Faisal Vali2ab8c152017-12-30 04:15:27 +0000790 D.Name.getKind() == UnqualifiedIdKind::IK_TemplateId)
Richard Smith6f1daa42016-12-16 00:58:48 +0000791 SpecKind = 0;
792 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization)
793 SpecKind = 1;
794 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
795 SpecKind = 2;
796 if (SpecKind != -1) {
797 SourceRange Range;
798 if (SpecKind == 0)
799 Range = SourceRange(D.Name.TemplateId->LAngleLoc,
800 D.Name.TemplateId->RAngleLoc);
801 else
802 Range = TemplateInfo.getSourceRange();
803 Diag(Range.getBegin(), diag::err_alias_declaration_specialization)
804 << SpecKind << Range;
805 SkipUntil(tok::semi);
806 return nullptr;
807 }
808
809 // Name must be an identifier.
Faisal Vali2ab8c152017-12-30 04:15:27 +0000810 if (D.Name.getKind() != UnqualifiedIdKind::IK_Identifier) {
Richard Smith6f1daa42016-12-16 00:58:48 +0000811 Diag(D.Name.StartLocation, diag::err_alias_declaration_not_identifier);
812 // No removal fixit: can't recover from this.
813 SkipUntil(tok::semi);
814 return nullptr;
815 } else if (D.TypenameLoc.isValid())
816 Diag(D.TypenameLoc, diag::err_alias_declaration_not_identifier)
817 << FixItHint::CreateRemoval(SourceRange(
818 D.TypenameLoc,
819 D.SS.isNotEmpty() ? D.SS.getEndLoc() : D.TypenameLoc));
820 else if (D.SS.isNotEmpty())
821 Diag(D.SS.getBeginLoc(), diag::err_alias_declaration_not_identifier)
822 << FixItHint::CreateRemoval(D.SS.getRange());
Richard Smith151c4562016-12-20 21:35:28 +0000823 if (D.EllipsisLoc.isValid())
824 Diag(D.EllipsisLoc, diag::err_alias_declaration_pack_expansion)
825 << FixItHint::CreateRemoval(SourceRange(D.EllipsisLoc));
Richard Smith6f1daa42016-12-16 00:58:48 +0000826
827 Decl *DeclFromDeclSpec = nullptr;
Faisal Vali421b2d12017-12-29 05:41:00 +0000828 TypeResult TypeAlias = ParseTypeName(
829 nullptr,
830 TemplateInfo.Kind ? DeclaratorContext::AliasTemplateContext
831 : DeclaratorContext::AliasDeclContext,
832 AS, &DeclFromDeclSpec, &Attrs);
Richard Smith6f1daa42016-12-16 00:58:48 +0000833 if (OwnedType)
834 *OwnedType = DeclFromDeclSpec;
835
836 // Eat ';'.
837 DeclEnd = Tok.getLocation();
838 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
839 !Attrs.empty() ? "attributes list"
840 : "alias declaration"))
841 SkipUntil(tok::semi);
842
843 TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
844 MultiTemplateParamsArg TemplateParamsArg(
845 TemplateParams ? TemplateParams->data() : nullptr,
846 TemplateParams ? TemplateParams->size() : 0);
847 return Actions.ActOnAliasDeclaration(getCurScope(), AS, TemplateParamsArg,
Erich Keanec480f302018-07-12 21:09:05 +0000848 UsingLoc, D.Name, Attrs, TypeAlias,
849 DeclFromDeclSpec);
Douglas Gregord7c4d982008-12-30 03:27:21 +0000850}
851
Benjamin Kramere56f3932011-12-23 17:00:35 +0000852/// ParseStaticAssertDeclaration - Parse C++0x or C11 static_assert-declaration.
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000853///
Peter Collingbourne3d9cbdc2011-04-15 00:35:57 +0000854/// [C++0x] static_assert-declaration:
855/// static_assert ( constant-expression , string-literal ) ;
856///
Benjamin Kramere56f3932011-12-23 17:00:35 +0000857/// [C11] static_assert-declaration:
Peter Collingbourne3d9cbdc2011-04-15 00:35:57 +0000858/// _Static_assert ( constant-expression , string-literal ) ;
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000859///
John McCall48871652010-08-21 09:40:31 +0000860Decl *Parser::ParseStaticAssertDeclaration(SourceLocation &DeclEnd){
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000861 assert(Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert) &&
Peter Collingbourne3d9cbdc2011-04-15 00:35:57 +0000862 "Not a static_assert declaration");
863
David Blaikiebbafb8a2012-03-11 07:00:24 +0000864 if (Tok.is(tok::kw__Static_assert) && !getLangOpts().C11)
Benjamin Kramere56f3932011-12-23 17:00:35 +0000865 Diag(Tok, diag::ext_c11_static_assert);
Richard Smithb15c11c2011-10-17 23:06:20 +0000866 if (Tok.is(tok::kw_static_assert))
867 Diag(Tok, diag::warn_cxx98_compat_static_assert);
Peter Collingbourne3d9cbdc2011-04-15 00:35:57 +0000868
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000869 SourceLocation StaticAssertLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000870
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000871 BalancedDelimiterTracker T(*this, tok::l_paren);
872 if (T.consumeOpen()) {
Alp Tokerec543272013-12-24 09:48:30 +0000873 Diag(Tok, diag::err_expected) << tok::l_paren;
Richard Smith76965712012-09-13 19:12:50 +0000874 SkipMalformedDecl();
Craig Topper161e4db2014-05-21 06:02:52 +0000875 return nullptr;
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000876 }
Mike Stump11289f42009-09-09 15:08:12 +0000877
Richard Smithb3018062017-06-06 01:34:24 +0000878 EnterExpressionEvaluationContext ConstantEvaluated(
879 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
880 ExprResult AssertExpr(ParseConstantExpressionInExprEvalContext());
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000881 if (AssertExpr.isInvalid()) {
Richard Smith76965712012-09-13 19:12:50 +0000882 SkipMalformedDecl();
Craig Topper161e4db2014-05-21 06:02:52 +0000883 return nullptr;
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000884 }
Mike Stump11289f42009-09-09 15:08:12 +0000885
Richard Smith085a64f2014-06-20 19:57:12 +0000886 ExprResult AssertMessage;
887 if (Tok.is(tok::r_paren)) {
Aaron Ballmanc351fba2017-12-04 20:27:34 +0000888 Diag(Tok, getLangOpts().CPlusPlus17
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000889 ? diag::warn_cxx14_compat_static_assert_no_message
Richard Smith085a64f2014-06-20 19:57:12 +0000890 : diag::ext_static_assert_no_message)
Aaron Ballmanc351fba2017-12-04 20:27:34 +0000891 << (getLangOpts().CPlusPlus17
Richard Smith085a64f2014-06-20 19:57:12 +0000892 ? FixItHint()
893 : FixItHint::CreateInsertion(Tok.getLocation(), ", \"\""));
894 } else {
895 if (ExpectAndConsume(tok::comma)) {
896 SkipUntil(tok::semi);
897 return nullptr;
898 }
Anders Carlssonb4cf3ad2009-03-13 23:29:20 +0000899
Richard Smith085a64f2014-06-20 19:57:12 +0000900 if (!isTokenStringLiteral()) {
901 Diag(Tok, diag::err_expected_string_literal)
902 << /*Source='static_assert'*/1;
903 SkipMalformedDecl();
904 return nullptr;
905 }
Mike Stump11289f42009-09-09 15:08:12 +0000906
Richard Smith085a64f2014-06-20 19:57:12 +0000907 AssertMessage = ParseStringLiteralExpression();
908 if (AssertMessage.isInvalid()) {
909 SkipMalformedDecl();
910 return nullptr;
911 }
Richard Smithd67aea22012-03-06 03:21:47 +0000912 }
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000913
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000914 T.consumeClose();
Mike Stump11289f42009-09-09 15:08:12 +0000915
Chris Lattner49836b42009-04-02 04:16:50 +0000916 DeclEnd = Tok.getLocation();
Douglas Gregor45d6bdf2010-09-07 15:23:11 +0000917 ExpectAndConsumeSemi(diag::err_expected_semi_after_static_assert);
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000918
John McCallb268a282010-08-23 23:25:46 +0000919 return Actions.ActOnStaticAssertDeclaration(StaticAssertLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000920 AssertExpr.get(),
921 AssertMessage.get(),
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000922 T.getCloseLocation());
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000923}
924
Richard Smith74aeef52013-04-26 16:15:35 +0000925/// ParseDecltypeSpecifier - Parse a C++11 decltype specifier.
Anders Carlsson74948d02009-06-24 17:47:40 +0000926///
927/// 'decltype' ( expression )
Richard Smith74aeef52013-04-26 16:15:35 +0000928/// 'decltype' ( 'auto' ) [C++1y]
Anders Carlsson74948d02009-06-24 17:47:40 +0000929///
David Blaikie15a430a2011-12-04 05:04:18 +0000930SourceLocation Parser::ParseDecltypeSpecifier(DeclSpec &DS) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000931 assert(Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)
David Blaikie15a430a2011-12-04 05:04:18 +0000932 && "Not a decltype specifier");
Fangrui Song6907ce22018-07-30 19:24:48 +0000933
David Blaikie15a430a2011-12-04 05:04:18 +0000934 ExprResult Result;
935 SourceLocation StartLoc = Tok.getLocation();
936 SourceLocation EndLoc;
937
938 if (Tok.is(tok::annot_decltype)) {
939 Result = getExprAnnotation(Tok);
940 EndLoc = Tok.getAnnotationEndLoc();
Richard Smithaf3b3252017-05-18 19:21:48 +0000941 ConsumeAnnotationToken();
David Blaikie15a430a2011-12-04 05:04:18 +0000942 if (Result.isInvalid()) {
943 DS.SetTypeSpecError();
944 return EndLoc;
945 }
946 } else {
Richard Smith324df552012-02-24 22:30:04 +0000947 if (Tok.getIdentifierInfo()->isStr("decltype"))
948 Diag(Tok, diag::warn_cxx98_compat_decltype);
Richard Smithfd3da932012-02-24 18:10:23 +0000949
David Blaikie15a430a2011-12-04 05:04:18 +0000950 ConsumeToken();
951
952 BalancedDelimiterTracker T(*this, tok::l_paren);
953 if (T.expectAndConsume(diag::err_expected_lparen_after,
954 "decltype", tok::r_paren)) {
955 DS.SetTypeSpecError();
956 return T.getOpenLocation() == Tok.getLocation() ?
957 StartLoc : T.getOpenLocation();
958 }
959
Richard Smith74aeef52013-04-26 16:15:35 +0000960 // Check for C++1y 'decltype(auto)'.
961 if (Tok.is(tok::kw_auto)) {
962 // No need to disambiguate here: an expression can't start with 'auto',
963 // because the typename-specifier in a function-style cast operation can't
964 // be 'auto'.
965 Diag(Tok.getLocation(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000966 getLangOpts().CPlusPlus14
Richard Smith74aeef52013-04-26 16:15:35 +0000967 ? diag::warn_cxx11_compat_decltype_auto_type_specifier
968 : diag::ext_decltype_auto_type_specifier);
969 ConsumeToken();
970 } else {
971 // Parse the expression
David Blaikie15a430a2011-12-04 05:04:18 +0000972
Richard Smith74aeef52013-04-26 16:15:35 +0000973 // C++11 [dcl.type.simple]p4:
974 // The operand of the decltype specifier is an unevaluated operand.
Faisal Valid143a0c2017-04-01 21:30:49 +0000975 EnterExpressionEvaluationContext Unevaluated(
976 Actions, Sema::ExpressionEvaluationContext::Unevaluated, nullptr,
Nicolas Lesserb6d5c582018-07-12 18:45:41 +0000977 Sema::ExpressionEvaluationContextRecord::EK_Decltype);
Kaelyn Takata5cc85352015-04-10 19:16:46 +0000978 Result =
979 Actions.CorrectDelayedTyposInExpr(ParseExpression(), [](Expr *E) {
980 return E->hasPlaceholderType() ? ExprError() : E;
981 });
Richard Smith74aeef52013-04-26 16:15:35 +0000982 if (Result.isInvalid()) {
983 DS.SetTypeSpecError();
Alexey Bataevee6507d2013-11-18 08:17:37 +0000984 if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch)) {
Richard Smith74aeef52013-04-26 16:15:35 +0000985 EndLoc = ConsumeParen();
Argyrios Kyrtzidisc38395a2012-10-26 22:53:44 +0000986 } else {
Richard Smith74aeef52013-04-26 16:15:35 +0000987 if (PP.isBacktrackEnabled() && Tok.is(tok::semi)) {
988 // Backtrack to get the location of the last token before the semi.
989 PP.RevertCachedTokens(2);
990 ConsumeToken(); // the semi.
991 EndLoc = ConsumeAnyToken();
992 assert(Tok.is(tok::semi));
993 } else {
994 EndLoc = Tok.getLocation();
995 }
Argyrios Kyrtzidisc38395a2012-10-26 22:53:44 +0000996 }
Richard Smith74aeef52013-04-26 16:15:35 +0000997 return EndLoc;
Argyrios Kyrtzidisc38395a2012-10-26 22:53:44 +0000998 }
Richard Smith74aeef52013-04-26 16:15:35 +0000999
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001000 Result = Actions.ActOnDecltypeExpression(Result.get());
David Blaikie15a430a2011-12-04 05:04:18 +00001001 }
1002
1003 // Match the ')'
1004 T.consumeClose();
1005 if (T.getCloseLocation().isInvalid()) {
1006 DS.SetTypeSpecError();
1007 // FIXME: this should return the location of the last token
1008 // that was consumed (by "consumeClose()")
1009 return T.getCloseLocation();
1010 }
1011
Richard Smithfd555f62012-02-22 02:04:18 +00001012 if (Result.isInvalid()) {
1013 DS.SetTypeSpecError();
1014 return T.getCloseLocation();
1015 }
1016
David Blaikie15a430a2011-12-04 05:04:18 +00001017 EndLoc = T.getCloseLocation();
Anders Carlsson74948d02009-06-24 17:47:40 +00001018 }
Richard Smith74aeef52013-04-26 16:15:35 +00001019 assert(!Result.isInvalid());
Mike Stump11289f42009-09-09 15:08:12 +00001020
Craig Topper161e4db2014-05-21 06:02:52 +00001021 const char *PrevSpec = nullptr;
John McCall49bfce42009-08-03 20:12:06 +00001022 unsigned DiagID;
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001023 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
Anders Carlsson74948d02009-06-24 17:47:40 +00001024 // Check for duplicate type specifiers (e.g. "int decltype(a)").
Richard Smith74aeef52013-04-26 16:15:35 +00001025 if (Result.get()
1026 ? DS.SetTypeSpecType(DeclSpec::TST_decltype, StartLoc, PrevSpec,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001027 DiagID, Result.get(), Policy)
Richard Smith74aeef52013-04-26 16:15:35 +00001028 : DS.SetTypeSpecType(DeclSpec::TST_decltype_auto, StartLoc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001029 DiagID, Policy)) {
John McCall49bfce42009-08-03 20:12:06 +00001030 Diag(StartLoc, DiagID) << PrevSpec;
David Blaikie15a430a2011-12-04 05:04:18 +00001031 DS.SetTypeSpecError();
1032 }
1033 return EndLoc;
1034}
1035
Fangrui Song6907ce22018-07-30 19:24:48 +00001036void Parser::AnnotateExistingDecltypeSpecifier(const DeclSpec& DS,
David Blaikie15a430a2011-12-04 05:04:18 +00001037 SourceLocation StartLoc,
1038 SourceLocation EndLoc) {
1039 // make sure we have a token we can turn into an annotation token
1040 if (PP.isBacktrackEnabled())
1041 PP.RevertCachedTokens(1);
1042 else
1043 PP.EnterToken(Tok);
1044
1045 Tok.setKind(tok::annot_decltype);
Faisal Vali090da2d2018-01-01 18:23:28 +00001046 setExprAnnotation(Tok,
1047 DS.getTypeSpecType() == TST_decltype ? DS.getRepAsExpr() :
1048 DS.getTypeSpecType() == TST_decltype_auto ? ExprResult() :
1049 ExprError());
David Blaikie15a430a2011-12-04 05:04:18 +00001050 Tok.setAnnotationEndLoc(EndLoc);
1051 Tok.setLocation(StartLoc);
1052 PP.AnnotateCachedTokens(Tok);
Anders Carlsson74948d02009-06-24 17:47:40 +00001053}
1054
Alexis Hunt4a257072011-05-19 05:37:45 +00001055void Parser::ParseUnderlyingTypeSpecifier(DeclSpec &DS) {
1056 assert(Tok.is(tok::kw___underlying_type) &&
1057 "Not an underlying type specifier");
1058
1059 SourceLocation StartLoc = ConsumeToken();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001060 BalancedDelimiterTracker T(*this, tok::l_paren);
1061 if (T.expectAndConsume(diag::err_expected_lparen_after,
1062 "__underlying_type", tok::r_paren)) {
Alexis Hunt4a257072011-05-19 05:37:45 +00001063 return;
1064 }
1065
1066 TypeResult Result = ParseTypeName();
1067 if (Result.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00001068 SkipUntil(tok::r_paren, StopAtSemi);
Alexis Hunt4a257072011-05-19 05:37:45 +00001069 return;
1070 }
1071
1072 // Match the ')'
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001073 T.consumeClose();
1074 if (T.getCloseLocation().isInvalid())
Alexis Hunt4a257072011-05-19 05:37:45 +00001075 return;
1076
Craig Topper161e4db2014-05-21 06:02:52 +00001077 const char *PrevSpec = nullptr;
Alexis Hunt4a257072011-05-19 05:37:45 +00001078 unsigned DiagID;
Alexis Hunte852b102011-05-24 22:41:36 +00001079 if (DS.SetTypeSpecType(DeclSpec::TST_underlyingType, StartLoc, PrevSpec,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001080 DiagID, Result.get(),
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001081 Actions.getASTContext().getPrintingPolicy()))
Alexis Hunt4a257072011-05-19 05:37:45 +00001082 Diag(StartLoc, DiagID) << PrevSpec;
Enea Zaffanellaa90af722013-07-06 18:54:58 +00001083 DS.setTypeofParensRange(T.getRange());
Alexis Hunt4a257072011-05-19 05:37:45 +00001084}
1085
David Blaikie00ee7a082011-10-25 15:01:20 +00001086/// ParseBaseTypeSpecifier - Parse a C++ base-type-specifier which is either a
Fangrui Song6907ce22018-07-30 19:24:48 +00001087/// class name or decltype-specifier. Note that we only check that the result
1088/// names a type; semantic analysis will need to verify that the type names a
1089/// class. The result is either a type or null, depending on whether a type
David Blaikie00ee7a082011-10-25 15:01:20 +00001090/// name was found.
Douglas Gregor831c93f2008-11-05 20:51:48 +00001091///
Richard Smith4c96e992013-02-19 23:47:15 +00001092/// base-type-specifier: [C++11 class.derived]
David Blaikie00ee7a082011-10-25 15:01:20 +00001093/// class-or-decltype
Richard Smith4c96e992013-02-19 23:47:15 +00001094/// class-or-decltype: [C++11 class.derived]
David Blaikie00ee7a082011-10-25 15:01:20 +00001095/// nested-name-specifier[opt] class-name
1096/// decltype-specifier
Richard Smith4c96e992013-02-19 23:47:15 +00001097/// class-name: [C++ class.name]
Douglas Gregor831c93f2008-11-05 20:51:48 +00001098/// identifier
Douglas Gregord54dfb82009-02-25 23:52:28 +00001099/// simple-template-id
Mike Stump11289f42009-09-09 15:08:12 +00001100///
Richard Smith4c96e992013-02-19 23:47:15 +00001101/// In C++98, instead of base-type-specifier, we have:
1102///
1103/// ::[opt] nested-name-specifier[opt] class-name
Craig Topper9ad7e262014-10-31 06:57:07 +00001104TypeResult Parser::ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
1105 SourceLocation &EndLocation) {
David Blaikiedd58d4c2011-10-25 18:46:41 +00001106 // Ignore attempts to use typename
1107 if (Tok.is(tok::kw_typename)) {
1108 Diag(Tok, diag::err_expected_class_name_not_template)
1109 << FixItHint::CreateRemoval(Tok.getLocation());
1110 ConsumeToken();
1111 }
1112
David Blaikieafa155f2011-10-25 18:17:58 +00001113 // Parse optional nested-name-specifier
1114 CXXScopeSpec SS;
Richard Smithb23c5e82019-05-09 03:31:27 +00001115 if (ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false))
1116 return true;
David Blaikieafa155f2011-10-25 18:17:58 +00001117
1118 BaseLoc = Tok.getLocation();
1119
David Blaikie1cd50022011-10-25 17:10:12 +00001120 // Parse decltype-specifier
Fangrui Song6907ce22018-07-30 19:24:48 +00001121 // tok == kw_decltype is just error recovery, it can only happen when SS
David Blaikie15a430a2011-12-04 05:04:18 +00001122 // isn't empty
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001123 if (Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)) {
David Blaikieafa155f2011-10-25 18:17:58 +00001124 if (SS.isNotEmpty())
1125 Diag(SS.getBeginLoc(), diag::err_unexpected_scope_on_base_decltype)
1126 << FixItHint::CreateRemoval(SS.getRange());
David Blaikie1cd50022011-10-25 17:10:12 +00001127 // Fake up a Declarator to use with ActOnTypeName.
1128 DeclSpec DS(AttrFactory);
1129
David Blaikie7491e732011-12-08 04:53:15 +00001130 EndLocation = ParseDecltypeSpecifier(DS);
David Blaikie1cd50022011-10-25 17:10:12 +00001131
Faisal Vali421b2d12017-12-29 05:41:00 +00001132 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
David Blaikie1cd50022011-10-25 17:10:12 +00001133 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
1134 }
1135
Douglas Gregord54dfb82009-02-25 23:52:28 +00001136 // Check whether we have a template-id that names a type.
1137 if (Tok.is(tok::annot_template_id)) {
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00001138 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregor46c59612010-01-12 17:52:59 +00001139 if (TemplateId->Kind == TNK_Type_template ||
Richard Smithb23c5e82019-05-09 03:31:27 +00001140 TemplateId->Kind == TNK_Dependent_template_name ||
1141 TemplateId->Kind == TNK_Undeclared_template) {
Richard Smith62559bd2017-02-01 21:36:38 +00001142 AnnotateTemplateIdTokenAsType(/*IsClassName*/true);
Douglas Gregord54dfb82009-02-25 23:52:28 +00001143
1144 assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
John McCallba7bf592010-08-24 05:47:05 +00001145 ParsedType Type = getTypeAnnotation(Tok);
Douglas Gregord54dfb82009-02-25 23:52:28 +00001146 EndLocation = Tok.getAnnotationEndLoc();
Richard Smithaf3b3252017-05-18 19:21:48 +00001147 ConsumeAnnotationToken();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001148
1149 if (Type)
1150 return Type;
1151 return true;
Douglas Gregord54dfb82009-02-25 23:52:28 +00001152 }
1153
1154 // Fall through to produce an error below.
1155 }
1156
Douglas Gregor831c93f2008-11-05 20:51:48 +00001157 if (Tok.isNot(tok::identifier)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00001158 Diag(Tok, diag::err_expected_class_name);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001159 return true;
Douglas Gregor831c93f2008-11-05 20:51:48 +00001160 }
1161
Douglas Gregor18473f32010-01-12 21:28:44 +00001162 IdentifierInfo *Id = Tok.getIdentifierInfo();
1163 SourceLocation IdLoc = ConsumeToken();
1164
1165 if (Tok.is(tok::less)) {
1166 // It looks the user intended to write a template-id here, but the
1167 // template-name was wrong. Try to fix that.
1168 TemplateNameKind TNK = TNK_Type_template;
1169 TemplateTy Template;
Douglas Gregor0be31a22010-07-02 17:43:08 +00001170 if (!Actions.DiagnoseUnknownTemplateName(*Id, IdLoc, getCurScope(),
Douglas Gregore7c20652011-03-02 00:47:37 +00001171 &SS, Template, TNK)) {
Douglas Gregor18473f32010-01-12 21:28:44 +00001172 Diag(IdLoc, diag::err_unknown_template_name)
1173 << Id;
1174 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001175
Serge Pavlovb716b3c2013-08-10 05:54:47 +00001176 if (!Template) {
1177 TemplateArgList TemplateArgs;
1178 SourceLocation LAngleLoc, RAngleLoc;
Richard Smith9a420f92017-05-10 21:47:30 +00001179 ParseTemplateIdAfterTemplateName(true, LAngleLoc, TemplateArgs,
1180 RAngleLoc);
Douglas Gregor18473f32010-01-12 21:28:44 +00001181 return true;
Serge Pavlovb716b3c2013-08-10 05:54:47 +00001182 }
Douglas Gregor18473f32010-01-12 21:28:44 +00001183
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001184 // Form the template name
Douglas Gregor18473f32010-01-12 21:28:44 +00001185 UnqualifiedId TemplateName;
1186 TemplateName.setIdentifier(Id, IdLoc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001187
Douglas Gregor18473f32010-01-12 21:28:44 +00001188 // Parse the full template-id, then turn it into a type.
Abramo Bagnara7945c982012-01-27 09:46:47 +00001189 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
Richard Smith62559bd2017-02-01 21:36:38 +00001190 TemplateName))
Douglas Gregor18473f32010-01-12 21:28:44 +00001191 return true;
Richard Smith62559bd2017-02-01 21:36:38 +00001192 if (TNK == TNK_Type_template || TNK == TNK_Dependent_template_name)
1193 AnnotateTemplateIdTokenAsType(/*IsClassName*/true);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001194
Douglas Gregor18473f32010-01-12 21:28:44 +00001195 // If we didn't end up with a typename token, there's nothing more we
1196 // can do.
1197 if (Tok.isNot(tok::annot_typename))
1198 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001199
Douglas Gregor18473f32010-01-12 21:28:44 +00001200 // Retrieve the type from the annotation token, consume that token, and
1201 // return.
1202 EndLocation = Tok.getAnnotationEndLoc();
John McCallba7bf592010-08-24 05:47:05 +00001203 ParsedType Type = getTypeAnnotation(Tok);
Richard Smithaf3b3252017-05-18 19:21:48 +00001204 ConsumeAnnotationToken();
Douglas Gregor18473f32010-01-12 21:28:44 +00001205 return Type;
1206 }
1207
Douglas Gregor831c93f2008-11-05 20:51:48 +00001208 // We have an identifier; check whether it is actually a type.
Craig Topper161e4db2014-05-21 06:02:52 +00001209 IdentifierInfo *CorrectedII = nullptr;
Richard Smith600b5262017-01-26 20:40:47 +00001210 ParsedType Type = Actions.getTypeName(
Richard Smith62559bd2017-02-01 21:36:38 +00001211 *Id, IdLoc, getCurScope(), &SS, /*IsClassName=*/true, false, nullptr,
Richard Smith600b5262017-01-26 20:40:47 +00001212 /*IsCtorOrDtorName=*/false,
1213 /*NonTrivialTypeSourceInfo=*/true,
1214 /*IsClassTemplateDeductionContext*/ false, &CorrectedII);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001215 if (!Type) {
Douglas Gregorfe17d252010-02-16 19:09:40 +00001216 Diag(IdLoc, diag::err_expected_class_name);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001217 return true;
Douglas Gregor831c93f2008-11-05 20:51:48 +00001218 }
1219
1220 // Consume the identifier.
Douglas Gregor18473f32010-01-12 21:28:44 +00001221 EndLocation = IdLoc;
Nick Lewycky19b9f952010-07-26 16:56:01 +00001222
1223 // Fake up a Declarator to use with ActOnTypeName.
John McCall084e83d2011-03-24 11:26:52 +00001224 DeclSpec DS(AttrFactory);
Nick Lewycky19b9f952010-07-26 16:56:01 +00001225 DS.SetRangeStart(IdLoc);
1226 DS.SetRangeEnd(EndLocation);
Douglas Gregore7c20652011-03-02 00:47:37 +00001227 DS.getTypeSpecScope() = SS;
Nick Lewycky19b9f952010-07-26 16:56:01 +00001228
Craig Topper161e4db2014-05-21 06:02:52 +00001229 const char *PrevSpec = nullptr;
Nick Lewycky19b9f952010-07-26 16:56:01 +00001230 unsigned DiagID;
Faisal Vali090da2d2018-01-01 18:23:28 +00001231 DS.SetTypeSpecType(TST_typename, IdLoc, PrevSpec, DiagID, Type,
1232 Actions.getASTContext().getPrintingPolicy());
Nick Lewycky19b9f952010-07-26 16:56:01 +00001233
Faisal Vali421b2d12017-12-29 05:41:00 +00001234 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
Nick Lewycky19b9f952010-07-26 16:56:01 +00001235 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
Douglas Gregor831c93f2008-11-05 20:51:48 +00001236}
1237
John McCall8d32c052012-05-22 21:28:12 +00001238void Parser::ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001239 while (Tok.isOneOf(tok::kw___single_inheritance,
1240 tok::kw___multiple_inheritance,
1241 tok::kw___virtual_inheritance)) {
John McCall8d32c052012-05-22 21:28:12 +00001242 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
1243 SourceLocation AttrNameLoc = ConsumeToken();
Craig Topper161e4db2014-05-21 06:02:52 +00001244 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
Erich Keanee891aa92018-07-13 15:07:47 +00001245 ParsedAttr::AS_Keyword);
John McCall8d32c052012-05-22 21:28:12 +00001246 }
1247}
1248
Richard Smith369b9f92012-06-25 21:37:02 +00001249/// Determine whether the following tokens are valid after a type-specifier
1250/// which could be a standalone declaration. This will conservatively return
1251/// true if there's any doubt, and is appropriate for insert-';' fixits.
Richard Smith200f47c2012-07-02 19:14:01 +00001252bool Parser::isValidAfterTypeSpecifier(bool CouldBeBitfield) {
Richard Smith369b9f92012-06-25 21:37:02 +00001253 // This switch enumerates the valid "follow" set for type-specifiers.
1254 switch (Tok.getKind()) {
1255 default: break;
1256 case tok::semi: // struct foo {...} ;
1257 case tok::star: // struct foo {...} * P;
1258 case tok::amp: // struct foo {...} & R = ...
Richard Smith1ac67d12013-01-19 03:48:05 +00001259 case tok::ampamp: // struct foo {...} && R = ...
Richard Smith369b9f92012-06-25 21:37:02 +00001260 case tok::identifier: // struct foo {...} V ;
1261 case tok::r_paren: //(struct foo {...} ) {4}
Richard Smith1600e242019-04-16 00:47:45 +00001262 case tok::coloncolon: // struct foo {...} :: a::b;
Richard Smith369b9f92012-06-25 21:37:02 +00001263 case tok::annot_cxxscope: // struct foo {...} a:: b;
1264 case tok::annot_typename: // struct foo {...} a ::b;
1265 case tok::annot_template_id: // struct foo {...} a<int> ::b;
Richard Smith1600e242019-04-16 00:47:45 +00001266 case tok::kw_decltype: // struct foo {...} decltype (a)::b;
Richard Smith369b9f92012-06-25 21:37:02 +00001267 case tok::l_paren: // struct foo {...} ( x);
1268 case tok::comma: // __builtin_offsetof(struct foo{...} ,
Richard Smith1ac67d12013-01-19 03:48:05 +00001269 case tok::kw_operator: // struct foo operator ++() {...}
Alp Tokerd3f79c52013-11-24 20:24:54 +00001270 case tok::kw___declspec: // struct foo {...} __declspec(...)
Richard Smith843f18f2014-08-13 02:13:15 +00001271 case tok::l_square: // void f(struct f [ 3])
1272 case tok::ellipsis: // void f(struct f ... [Ns])
Abramo Bagnara152eb392014-08-16 08:29:27 +00001273 // FIXME: we should emit semantic diagnostic when declaration
1274 // attribute is in type attribute position.
1275 case tok::kw___attribute: // struct foo __attribute__((used)) x;
David Majnemer15b311c2016-06-14 03:20:28 +00001276 case tok::annot_pragma_pack: // struct foo {...} _Pragma(pack(pop));
1277 // struct foo {...} _Pragma(section(...));
1278 case tok::annot_pragma_ms_pragma:
1279 // struct foo {...} _Pragma(vtordisp(pop));
1280 case tok::annot_pragma_ms_vtordisp:
1281 // struct foo {...} _Pragma(pointers_to_members(...));
1282 case tok::annot_pragma_ms_pointers_to_members:
Richard Smith369b9f92012-06-25 21:37:02 +00001283 return true;
Richard Smith200f47c2012-07-02 19:14:01 +00001284 case tok::colon:
1285 return CouldBeBitfield; // enum E { ... } : 2;
Reid Klecknercfa91552016-03-21 16:08:49 +00001286 // Microsoft compatibility
1287 case tok::kw___cdecl: // struct foo {...} __cdecl x;
1288 case tok::kw___fastcall: // struct foo {...} __fastcall x;
1289 case tok::kw___stdcall: // struct foo {...} __stdcall x;
1290 case tok::kw___thiscall: // struct foo {...} __thiscall x;
1291 case tok::kw___vectorcall: // struct foo {...} __vectorcall x;
1292 // We will diagnose these calling-convention specifiers on non-function
1293 // declarations later, so claim they are valid after a type specifier.
1294 return getLangOpts().MicrosoftExt;
Richard Smith369b9f92012-06-25 21:37:02 +00001295 // Type qualifiers
1296 case tok::kw_const: // struct foo {...} const x;
1297 case tok::kw_volatile: // struct foo {...} volatile x;
1298 case tok::kw_restrict: // struct foo {...} restrict x;
Richard Smith843f18f2014-08-13 02:13:15 +00001299 case tok::kw__Atomic: // struct foo {...} _Atomic x;
Nico Rieck3e1ee832014-12-04 23:30:25 +00001300 case tok::kw___unaligned: // struct foo {...} __unaligned *x;
Richard Smith1ac67d12013-01-19 03:48:05 +00001301 // Function specifiers
1302 // Note, no 'explicit'. An explicit function must be either a conversion
1303 // operator or a constructor. Either way, it can't have a return type.
1304 case tok::kw_inline: // struct foo inline f();
1305 case tok::kw_virtual: // struct foo virtual f();
1306 case tok::kw_friend: // struct foo friend f();
Richard Smith369b9f92012-06-25 21:37:02 +00001307 // Storage-class specifiers
1308 case tok::kw_static: // struct foo {...} static x;
1309 case tok::kw_extern: // struct foo {...} extern x;
1310 case tok::kw_typedef: // struct foo {...} typedef x;
1311 case tok::kw_register: // struct foo {...} register x;
1312 case tok::kw_auto: // struct foo {...} auto x;
1313 case tok::kw_mutable: // struct foo {...} mutable x;
Richard Smith1ac67d12013-01-19 03:48:05 +00001314 case tok::kw_thread_local: // struct foo {...} thread_local x;
Richard Smith369b9f92012-06-25 21:37:02 +00001315 case tok::kw_constexpr: // struct foo {...} constexpr x;
1316 // As shown above, type qualifiers and storage class specifiers absolutely
1317 // can occur after class specifiers according to the grammar. However,
1318 // almost no one actually writes code like this. If we see one of these,
1319 // it is much more likely that someone missed a semi colon and the
1320 // type/storage class specifier we're seeing is part of the *next*
1321 // intended declaration, as in:
1322 //
1323 // struct foo { ... }
1324 // typedef int X;
1325 //
1326 // We'd really like to emit a missing semicolon error instead of emitting
1327 // an error on the 'int' saying that you can't have two type specifiers in
1328 // the same declaration of X. Because of this, we look ahead past this
1329 // token to see if it's a type specifier. If so, we know the code is
1330 // otherwise invalid, so we can produce the expected semi error.
1331 if (!isKnownToBeTypeSpecifier(NextToken()))
1332 return true;
1333 break;
1334 case tok::r_brace: // struct bar { struct foo {...} }
1335 // Missing ';' at end of struct is accepted as an extension in C mode.
1336 if (!getLangOpts().CPlusPlus)
1337 return true;
1338 break;
Richard Smith52c5b872013-01-29 04:13:32 +00001339 case tok::greater:
1340 // template<class T = class X>
1341 return getLangOpts().CPlusPlus;
Richard Smith369b9f92012-06-25 21:37:02 +00001342 }
1343 return false;
1344}
1345
Douglas Gregor556877c2008-04-13 21:30:24 +00001346/// ParseClassSpecifier - Parse a C++ class-specifier [C++ class] or
1347/// elaborated-type-specifier [C++ dcl.type.elab]; we can't tell which
1348/// until we reach the start of a definition or see a token that
Richard Smithc5b05522012-03-12 07:56:15 +00001349/// cannot start a definition.
Douglas Gregor556877c2008-04-13 21:30:24 +00001350///
1351/// class-specifier: [C++ class]
1352/// class-head '{' member-specification[opt] '}'
1353/// class-head '{' member-specification[opt] '}' attributes[opt]
1354/// class-head:
1355/// class-key identifier[opt] base-clause[opt]
1356/// class-key nested-name-specifier identifier base-clause[opt]
1357/// class-key nested-name-specifier[opt] simple-template-id
1358/// base-clause[opt]
1359/// [GNU] class-key attributes[opt] identifier[opt] base-clause[opt]
Mike Stump11289f42009-09-09 15:08:12 +00001360/// [GNU] class-key attributes[opt] nested-name-specifier
Douglas Gregor556877c2008-04-13 21:30:24 +00001361/// identifier base-clause[opt]
Mike Stump11289f42009-09-09 15:08:12 +00001362/// [GNU] class-key attributes[opt] nested-name-specifier[opt]
Douglas Gregor556877c2008-04-13 21:30:24 +00001363/// simple-template-id base-clause[opt]
1364/// class-key:
1365/// 'class'
1366/// 'struct'
1367/// 'union'
1368///
1369/// elaborated-type-specifier: [C++ dcl.type.elab]
Mike Stump11289f42009-09-09 15:08:12 +00001370/// class-key ::[opt] nested-name-specifier[opt] identifier
1371/// class-key ::[opt] nested-name-specifier[opt] 'template'[opt]
1372/// simple-template-id
Douglas Gregor556877c2008-04-13 21:30:24 +00001373///
1374/// Note that the C++ class-specifier and elaborated-type-specifier,
1375/// together, subsume the C99 struct-or-union-specifier:
1376///
1377/// struct-or-union-specifier: [C99 6.7.2.1]
1378/// struct-or-union identifier[opt] '{' struct-contents '}'
1379/// struct-or-union identifier
1380/// [GNU] struct-or-union attributes[opt] identifier[opt] '{' struct-contents
1381/// '}' attributes[opt]
1382/// [GNU] struct-or-union attributes[opt] identifier
1383/// struct-or-union:
1384/// 'struct'
1385/// 'union'
Chris Lattnerffaa0e62009-04-12 21:49:30 +00001386void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind,
1387 SourceLocation StartLoc, DeclSpec &DS,
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001388 const ParsedTemplateInfo &TemplateInfo,
Fangrui Song6907ce22018-07-30 19:24:48 +00001389 AccessSpecifier AS,
1390 bool EnteringContext, DeclSpecContext DSC,
Bill Wendling44426052012-12-20 19:22:21 +00001391 ParsedAttributesWithRange &Attributes) {
Joao Matose9a3ed42012-08-31 22:18:20 +00001392 DeclSpec::TST TagType;
1393 if (TagTokKind == tok::kw_struct)
1394 TagType = DeclSpec::TST_struct;
1395 else if (TagTokKind == tok::kw___interface)
1396 TagType = DeclSpec::TST_interface;
1397 else if (TagTokKind == tok::kw_class)
1398 TagType = DeclSpec::TST_class;
1399 else {
Chris Lattnerffaa0e62009-04-12 21:49:30 +00001400 assert(TagTokKind == tok::kw_union && "Not a class specifier");
1401 TagType = DeclSpec::TST_union;
1402 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001403
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00001404 if (Tok.is(tok::code_completion)) {
1405 // Code completion for a struct, class, or union name.
Douglas Gregor0be31a22010-07-02 17:43:08 +00001406 Actions.CodeCompleteTag(getCurScope(), TagType);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001407 return cutOffParsing();
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00001408 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001409
Chandler Carruth2d69ec72010-06-28 08:39:25 +00001410 // C++03 [temp.explicit] 14.7.2/8:
1411 // The usual access checking rules do not apply to names used to specify
1412 // explicit instantiations.
1413 //
1414 // As an extension we do not perform access checking on the names used to
1415 // specify explicit specializations either. This is important to allow
1416 // specializing traits classes for private types.
John McCall6347b682012-05-07 06:16:58 +00001417 //
1418 // Note that we don't suppress if this turns out to be an elaborated
1419 // type specifier.
1420 bool shouldDelayDiagsInTag =
1421 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
1422 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
1423 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
Chandler Carruth2d69ec72010-06-28 08:39:25 +00001424
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001425 ParsedAttributesWithRange attrs(AttrFactory);
Douglas Gregor556877c2008-04-13 21:30:24 +00001426 // If attributes exist after tag, parse them.
Richard Smith37a45dd2013-10-24 01:21:09 +00001427 MaybeParseGNUAttributes(attrs);
Aaron Ballman068aa512015-05-20 20:58:33 +00001428 MaybeParseMicrosoftDeclSpecs(attrs);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001429
John McCall8d32c052012-05-22 21:28:12 +00001430 // Parse inheritance specifiers.
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001431 if (Tok.isOneOf(tok::kw___single_inheritance,
1432 tok::kw___multiple_inheritance,
1433 tok::kw___virtual_inheritance))
Richard Smith37a45dd2013-10-24 01:21:09 +00001434 ParseMicrosoftInheritanceClassAttributes(attrs);
John McCall8d32c052012-05-22 21:28:12 +00001435
Alexis Hunt96d5c762009-11-21 08:43:09 +00001436 // If C++0x attributes exist here, parse them.
1437 // FIXME: Are we consistent with the ordering of parsing of different
1438 // styles of attributes?
Richard Smith89645bc2013-01-02 12:01:23 +00001439 MaybeParseCXX11Attributes(attrs);
Mike Stump11289f42009-09-09 15:08:12 +00001440
Michael Han309af292013-01-07 16:57:11 +00001441 // Source location used by FIXIT to insert misplaced
1442 // C++11 attributes
1443 SourceLocation AttrFixitLoc = Tok.getLocation();
1444
Nico Weber7c3c5be2014-09-23 04:09:56 +00001445 if (TagType == DeclSpec::TST_struct &&
David Majnemer86330af2014-12-29 02:14:26 +00001446 Tok.isNot(tok::identifier) &&
1447 !Tok.isAnnotation() &&
Nico Weber7c3c5be2014-09-23 04:09:56 +00001448 Tok.getIdentifierInfo() &&
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001449 Tok.isOneOf(tok::kw___is_abstract,
Eric Fiselier07360662017-04-12 22:12:15 +00001450 tok::kw___is_aggregate,
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001451 tok::kw___is_arithmetic,
1452 tok::kw___is_array,
David Majnemerb3d96882016-05-23 17:21:55 +00001453 tok::kw___is_assignable,
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001454 tok::kw___is_base_of,
1455 tok::kw___is_class,
1456 tok::kw___is_complete_type,
1457 tok::kw___is_compound,
1458 tok::kw___is_const,
1459 tok::kw___is_constructible,
1460 tok::kw___is_convertible,
1461 tok::kw___is_convertible_to,
1462 tok::kw___is_destructible,
1463 tok::kw___is_empty,
1464 tok::kw___is_enum,
1465 tok::kw___is_floating_point,
1466 tok::kw___is_final,
1467 tok::kw___is_function,
1468 tok::kw___is_fundamental,
1469 tok::kw___is_integral,
1470 tok::kw___is_interface_class,
1471 tok::kw___is_literal,
1472 tok::kw___is_lvalue_expr,
1473 tok::kw___is_lvalue_reference,
1474 tok::kw___is_member_function_pointer,
1475 tok::kw___is_member_object_pointer,
1476 tok::kw___is_member_pointer,
1477 tok::kw___is_nothrow_assignable,
1478 tok::kw___is_nothrow_constructible,
1479 tok::kw___is_nothrow_destructible,
1480 tok::kw___is_object,
1481 tok::kw___is_pod,
1482 tok::kw___is_pointer,
1483 tok::kw___is_polymorphic,
1484 tok::kw___is_reference,
1485 tok::kw___is_rvalue_expr,
1486 tok::kw___is_rvalue_reference,
1487 tok::kw___is_same,
1488 tok::kw___is_scalar,
1489 tok::kw___is_sealed,
1490 tok::kw___is_signed,
1491 tok::kw___is_standard_layout,
1492 tok::kw___is_trivial,
1493 tok::kw___is_trivially_assignable,
1494 tok::kw___is_trivially_constructible,
1495 tok::kw___is_trivially_copyable,
1496 tok::kw___is_union,
1497 tok::kw___is_unsigned,
1498 tok::kw___is_void,
1499 tok::kw___is_volatile))
Nico Weber7c3c5be2014-09-23 04:09:56 +00001500 // GNU libstdc++ 4.2 and libc++ use certain intrinsic names as the
1501 // name of struct templates, but some are keywords in GCC >= 4.3
1502 // and Clang. Therefore, when we see the token sequence "struct
1503 // X", make X into a normal identifier rather than a keyword, to
1504 // allow libstdc++ 4.2 and libc++ to work properly.
1505 TryKeywordIdentFallback(true);
Mike Stump11289f42009-09-09 15:08:12 +00001506
David Majnemer51fd8a02015-07-22 23:46:18 +00001507 struct PreserveAtomicIdentifierInfoRAII {
1508 PreserveAtomicIdentifierInfoRAII(Token &Tok, bool Enabled)
1509 : AtomicII(nullptr) {
1510 if (!Enabled)
1511 return;
1512 assert(Tok.is(tok::kw__Atomic));
1513 AtomicII = Tok.getIdentifierInfo();
1514 AtomicII->revertTokenIDToIdentifier();
1515 Tok.setKind(tok::identifier);
1516 }
1517 ~PreserveAtomicIdentifierInfoRAII() {
1518 if (!AtomicII)
1519 return;
1520 AtomicII->revertIdentifierToTokenID(tok::kw__Atomic);
1521 }
1522 IdentifierInfo *AtomicII;
1523 };
1524
1525 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
1526 // implementation for VS2013 uses _Atomic as an identifier for one of the
1527 // classes in <atomic>. When we are parsing 'struct _Atomic', don't consider
1528 // '_Atomic' to be a keyword. We are careful to undo this so that clang can
1529 // use '_Atomic' in its own header files.
1530 bool ShouldChangeAtomicToIdentifier = getLangOpts().MSVCCompat &&
1531 Tok.is(tok::kw__Atomic) &&
1532 TagType == DeclSpec::TST_struct;
1533 PreserveAtomicIdentifierInfoRAII AtomicTokenGuard(
1534 Tok, ShouldChangeAtomicToIdentifier);
1535
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001536 // Parse the (optional) nested-name-specifier.
John McCall9dab4e62009-12-12 11:40:51 +00001537 CXXScopeSpec &SS = DS.getTypeSpecScope();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001538 if (getLangOpts().CPlusPlus) {
Serge Pavlov458ea762014-07-16 05:16:52 +00001539 // "FOO : BAR" is not a potential typo for "FOO::BAR". In this context it
1540 // is a base-specifier-list.
Chris Lattnerd5c1c9d2009-12-10 00:32:41 +00001541 ColonProtectionRAIIObject X(*this);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001542
Nico Webercfaa4cd2015-02-15 07:26:13 +00001543 CXXScopeSpec Spec;
1544 bool HasValidSpec = true;
David Blaikieefdccaa2016-01-15 23:43:34 +00001545 if (ParseOptionalCXXScopeSpecifier(Spec, nullptr, EnteringContext)) {
John McCall413021a2010-07-30 06:26:29 +00001546 DS.SetTypeSpecError();
Nico Webercfaa4cd2015-02-15 07:26:13 +00001547 HasValidSpec = false;
1548 }
1549 if (Spec.isSet())
1550 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::annot_template_id)) {
Alp Tokerec543272013-12-24 09:48:30 +00001551 Diag(Tok, diag::err_expected) << tok::identifier;
Nico Webercfaa4cd2015-02-15 07:26:13 +00001552 HasValidSpec = false;
1553 }
1554 if (HasValidSpec)
1555 SS = Spec;
Chris Lattnerd5c1c9d2009-12-10 00:32:41 +00001556 }
Douglas Gregor67a65642009-02-17 23:15:12 +00001557
Douglas Gregor916462b2009-10-30 21:46:58 +00001558 TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
1559
Richard Smithb23c5e82019-05-09 03:31:27 +00001560 auto RecoverFromUndeclaredTemplateName = [&](IdentifierInfo *Name,
1561 SourceLocation NameLoc,
1562 SourceRange TemplateArgRange,
1563 bool KnownUndeclared) {
1564 Diag(NameLoc, diag::err_explicit_spec_non_template)
1565 << (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
1566 << TagTokKind << Name << TemplateArgRange << KnownUndeclared;
1567
1568 // Strip off the last template parameter list if it was empty, since
1569 // we've removed its template argument list.
1570 if (TemplateParams && TemplateInfo.LastParameterListWasEmpty) {
1571 if (TemplateParams->size() > 1) {
1572 TemplateParams->pop_back();
1573 } else {
1574 TemplateParams = nullptr;
1575 const_cast<ParsedTemplateInfo &>(TemplateInfo).Kind =
1576 ParsedTemplateInfo::NonTemplate;
1577 }
1578 } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1579 // Pretend this is just a forward declaration.
1580 TemplateParams = nullptr;
1581 const_cast<ParsedTemplateInfo &>(TemplateInfo).Kind =
1582 ParsedTemplateInfo::NonTemplate;
1583 const_cast<ParsedTemplateInfo &>(TemplateInfo).TemplateLoc =
1584 SourceLocation();
1585 const_cast<ParsedTemplateInfo &>(TemplateInfo).ExternLoc =
1586 SourceLocation();
1587 }
1588 };
1589
Douglas Gregor67a65642009-02-17 23:15:12 +00001590 // Parse the (optional) class name or simple-template-id.
Craig Topper161e4db2014-05-21 06:02:52 +00001591 IdentifierInfo *Name = nullptr;
Douglas Gregor556877c2008-04-13 21:30:24 +00001592 SourceLocation NameLoc;
Craig Topper161e4db2014-05-21 06:02:52 +00001593 TemplateIdAnnotation *TemplateId = nullptr;
Douglas Gregor556877c2008-04-13 21:30:24 +00001594 if (Tok.is(tok::identifier)) {
1595 Name = Tok.getIdentifierInfo();
1596 NameLoc = ConsumeToken();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001597
David Blaikiebbafb8a2012-03-11 07:00:24 +00001598 if (Tok.is(tok::less) && getLangOpts().CPlusPlus) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001599 // The name was supposed to refer to a template, but didn't.
Douglas Gregor916462b2009-10-30 21:46:58 +00001600 // Eat the template argument list and try to continue parsing this as
1601 // a class (or template thereof).
1602 TemplateArgList TemplateArgs;
Douglas Gregor916462b2009-10-30 21:46:58 +00001603 SourceLocation LAngleLoc, RAngleLoc;
Richard Smith9a420f92017-05-10 21:47:30 +00001604 if (ParseTemplateIdAfterTemplateName(true, LAngleLoc, TemplateArgs,
1605 RAngleLoc)) {
Douglas Gregor916462b2009-10-30 21:46:58 +00001606 // We couldn't parse the template argument list at all, so don't
1607 // try to give any location information for the list.
1608 LAngleLoc = RAngleLoc = SourceLocation();
1609 }
Richard Smithb23c5e82019-05-09 03:31:27 +00001610 RecoverFromUndeclaredTemplateName(
1611 Name, NameLoc, SourceRange(LAngleLoc, RAngleLoc), false);
Douglas Gregor916462b2009-10-30 21:46:58 +00001612 }
Douglas Gregor7f741122009-02-25 19:37:18 +00001613 } else if (Tok.is(tok::annot_template_id)) {
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00001614 TemplateId = takeTemplateIdAnnotation(Tok);
Richard Smithaf3b3252017-05-18 19:21:48 +00001615 NameLoc = ConsumeAnnotationToken();
Douglas Gregor67a65642009-02-17 23:15:12 +00001616
Richard Smithb23c5e82019-05-09 03:31:27 +00001617 if (TemplateId->Kind == TNK_Undeclared_template) {
1618 // Try to resolve the template name to a type template.
1619 Actions.ActOnUndeclaredTypeTemplateName(getCurScope(), TemplateId->Template,
1620 TemplateId->Kind, NameLoc, Name);
1621 if (TemplateId->Kind == TNK_Undeclared_template) {
1622 RecoverFromUndeclaredTemplateName(
1623 Name, NameLoc,
1624 SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc), true);
1625 TemplateId = nullptr;
1626 }
1627 }
1628
1629 if (TemplateId && TemplateId->Kind != TNK_Type_template &&
Douglas Gregore7c20652011-03-02 00:47:37 +00001630 TemplateId->Kind != TNK_Dependent_template_name) {
Douglas Gregor7f741122009-02-25 19:37:18 +00001631 // The template-name in the simple-template-id refers to
1632 // something other than a class template. Give an appropriate
1633 // error message and skip to the ';'.
1634 SourceRange Range(NameLoc);
1635 if (SS.isNotEmpty())
1636 Range.setBegin(SS.getBeginLoc());
Douglas Gregor67a65642009-02-17 23:15:12 +00001637
Richard Smith72bfbd82013-12-04 00:28:23 +00001638 // FIXME: Name may be null here.
Douglas Gregor7f741122009-02-25 19:37:18 +00001639 Diag(TemplateId->LAngleLoc, diag::err_template_spec_syntax_non_template)
Richard Smithb23c5e82019-05-09 03:31:27 +00001640 << TemplateId->Name << static_cast<int>(TemplateId->Kind) << Range;
Mike Stump11289f42009-09-09 15:08:12 +00001641
Douglas Gregor7f741122009-02-25 19:37:18 +00001642 DS.SetTypeSpecError();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001643 SkipUntil(tok::semi, StopBeforeMatch);
Douglas Gregor7f741122009-02-25 19:37:18 +00001644 return;
Douglas Gregor67a65642009-02-17 23:15:12 +00001645 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001646 }
1647
Richard Smithbfdb1082012-03-12 08:56:40 +00001648 // There are four options here.
1649 // - If we are in a trailing return type, this is always just a reference,
1650 // and we must not try to parse a definition. For instance,
1651 // [] () -> struct S { };
1652 // does not define a type.
1653 // - If we have 'struct foo {...', 'struct foo :...',
1654 // 'struct foo final :' or 'struct foo final {', then this is a definition.
1655 // - If we have 'struct foo;', then this is either a forward declaration
1656 // or a friend declaration, which have to be treated differently.
1657 // - Otherwise we have something like 'struct foo xyz', a reference.
Michael Han9407e502012-11-26 22:54:45 +00001658 //
1659 // We also detect these erroneous cases to provide better diagnostic for
1660 // C++11 attributes parsing.
1661 // - attributes follow class name:
1662 // struct foo [[]] {};
1663 // - attributes appear before or after 'final':
1664 // struct foo [[]] final [[]] {};
1665 //
Richard Smithc5b05522012-03-12 07:56:15 +00001666 // However, in type-specifier-seq's, things look like declarations but are
1667 // just references, e.g.
1668 // new struct s;
Sebastian Redl2b372722010-02-03 21:21:43 +00001669 // or
Richard Smithc5b05522012-03-12 07:56:15 +00001670 // &T::operator struct s;
Faisal Vali7db85c52017-12-31 00:06:40 +00001671 // For these, DSC is DeclSpecContext::DSC_type_specifier or
1672 // DeclSpecContext::DSC_alias_declaration.
Michael Han9407e502012-11-26 22:54:45 +00001673
1674 // If there are attributes after class name, parse them.
Richard Smith89645bc2013-01-02 12:01:23 +00001675 MaybeParseCXX11Attributes(Attributes);
Michael Han9407e502012-11-26 22:54:45 +00001676
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001677 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
John McCallfaf5fb42010-08-26 23:41:50 +00001678 Sema::TagUseKind TUK;
Faisal Vali7db85c52017-12-31 00:06:40 +00001679 if (DSC == DeclSpecContext::DSC_trailing)
Richard Smithbfdb1082012-03-12 08:56:40 +00001680 TUK = Sema::TUK_Reference;
1681 else if (Tok.is(tok::l_brace) ||
1682 (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
Richard Smith89645bc2013-01-02 12:01:23 +00001683 (isCXX11FinalKeyword() &&
David Blaikie9933a5a2012-03-12 15:39:49 +00001684 (NextToken().is(tok::l_brace) || NextToken().is(tok::colon)))) {
Douglas Gregor3dad8422009-09-26 06:47:28 +00001685 if (DS.isFriendSpecified()) {
1686 // C++ [class.friend]p2:
1687 // A class shall not be defined in a friend declaration.
Richard Smith0f8ee222012-01-10 01:33:14 +00001688 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
Douglas Gregor3dad8422009-09-26 06:47:28 +00001689 << SourceRange(DS.getFriendSpecLoc());
1690
1691 // Skip everything up to the semicolon, so that this looks like a proper
1692 // friend class (or template thereof) declaration.
Alexey Bataevee6507d2013-11-18 08:17:37 +00001693 SkipUntil(tok::semi, StopBeforeMatch);
John McCallfaf5fb42010-08-26 23:41:50 +00001694 TUK = Sema::TUK_Friend;
Douglas Gregor3dad8422009-09-26 06:47:28 +00001695 } else {
1696 // Okay, this is a class definition.
John McCallfaf5fb42010-08-26 23:41:50 +00001697 TUK = Sema::TUK_Definition;
Douglas Gregor3dad8422009-09-26 06:47:28 +00001698 }
Richard Smith434516c2013-02-22 06:46:23 +00001699 } else if (isCXX11FinalKeyword() && (NextToken().is(tok::l_square) ||
1700 NextToken().is(tok::kw_alignas))) {
Michael Han9407e502012-11-26 22:54:45 +00001701 // We can't tell if this is a definition or reference
1702 // until we skipped the 'final' and C++11 attribute specifiers.
1703 TentativeParsingAction PA(*this);
1704
1705 // Skip the 'final' keyword.
1706 ConsumeToken();
1707
1708 // Skip C++11 attribute specifiers.
1709 while (true) {
1710 if (Tok.is(tok::l_square) && NextToken().is(tok::l_square)) {
1711 ConsumeBracket();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001712 if (!SkipUntil(tok::r_square, StopAtSemi))
Michael Han9407e502012-11-26 22:54:45 +00001713 break;
Richard Smith434516c2013-02-22 06:46:23 +00001714 } else if (Tok.is(tok::kw_alignas) && NextToken().is(tok::l_paren)) {
Michael Han9407e502012-11-26 22:54:45 +00001715 ConsumeToken();
1716 ConsumeParen();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001717 if (!SkipUntil(tok::r_paren, StopAtSemi))
Michael Han9407e502012-11-26 22:54:45 +00001718 break;
1719 } else {
1720 break;
1721 }
1722 }
1723
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001724 if (Tok.isOneOf(tok::l_brace, tok::colon))
Michael Han9407e502012-11-26 22:54:45 +00001725 TUK = Sema::TUK_Definition;
1726 else
1727 TUK = Sema::TUK_Reference;
1728
1729 PA.Revert();
Richard Smith649c7b062014-01-08 00:56:48 +00001730 } else if (!isTypeSpecifier(DSC) &&
Richard Smith369b9f92012-06-25 21:37:02 +00001731 (Tok.is(tok::semi) ||
Richard Smith200f47c2012-07-02 19:14:01 +00001732 (Tok.isAtStartOfLine() && !isValidAfterTypeSpecifier(false)))) {
John McCallfaf5fb42010-08-26 23:41:50 +00001733 TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
Joao Matose9a3ed42012-08-31 22:18:20 +00001734 if (Tok.isNot(tok::semi)) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001735 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
Joao Matose9a3ed42012-08-31 22:18:20 +00001736 // A semicolon was missing after this declaration. Diagnose and recover.
Alp Toker383d2c42014-01-01 03:08:43 +00001737 ExpectAndConsume(tok::semi, diag::err_expected_after,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001738 DeclSpec::getSpecifierName(TagType, PPol));
Joao Matose9a3ed42012-08-31 22:18:20 +00001739 PP.EnterToken(Tok);
1740 Tok.setKind(tok::semi);
1741 }
Richard Smith369b9f92012-06-25 21:37:02 +00001742 } else
John McCallfaf5fb42010-08-26 23:41:50 +00001743 TUK = Sema::TUK_Reference;
Douglas Gregor556877c2008-04-13 21:30:24 +00001744
Michael Han9407e502012-11-26 22:54:45 +00001745 // Forbid misplaced attributes. In cases of a reference, we pass attributes
1746 // to caller to handle.
Michael Han309af292013-01-07 16:57:11 +00001747 if (TUK != Sema::TUK_Reference) {
1748 // If this is not a reference, then the only possible
1749 // valid place for C++11 attributes to appear here
1750 // is between class-key and class-name. If there are
1751 // any attributes after class-name, we try a fixit to move
1752 // them to the right place.
1753 SourceRange AttrRange = Attributes.Range;
1754 if (AttrRange.isValid()) {
1755 Diag(AttrRange.getBegin(), diag::err_attributes_not_allowed)
1756 << AttrRange
1757 << FixItHint::CreateInsertionFromRange(AttrFixitLoc,
1758 CharSourceRange(AttrRange, true))
1759 << FixItHint::CreateRemoval(AttrRange);
1760
1761 // Recover by adding misplaced attributes to the attribute list
1762 // of the class so they can be applied on the class later.
1763 attrs.takeAllFrom(Attributes);
1764 }
1765 }
Michael Han9407e502012-11-26 22:54:45 +00001766
John McCall6347b682012-05-07 06:16:58 +00001767 // If this is an elaborated type specifier, and we delayed
1768 // diagnostics before, just merge them into the current pool.
1769 if (shouldDelayDiagsInTag) {
1770 diagsFromTag.done();
1771 if (TUK == Sema::TUK_Reference)
1772 diagsFromTag.redelay();
1773 }
1774
John McCall413021a2010-07-30 06:26:29 +00001775 if (!Name && !TemplateId && (DS.getTypeSpecType() == DeclSpec::TST_error ||
John McCallfaf5fb42010-08-26 23:41:50 +00001776 TUK != Sema::TUK_Definition)) {
John McCall413021a2010-07-30 06:26:29 +00001777 if (DS.getTypeSpecType() != DeclSpec::TST_error) {
1778 // We have a declaration or reference to an anonymous class.
1779 Diag(StartLoc, diag::err_anon_type_definition)
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001780 << DeclSpec::getSpecifierName(TagType, Policy);
John McCall413021a2010-07-30 06:26:29 +00001781 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001782
David Majnemer3252fd02013-12-05 01:36:53 +00001783 // If we are parsing a definition and stop at a base-clause, continue on
1784 // until the semicolon. Continuing from the comma will just trick us into
1785 // thinking we are seeing a variable declaration.
1786 if (TUK == Sema::TUK_Definition && Tok.is(tok::colon))
1787 SkipUntil(tok::semi, StopBeforeMatch);
1788 else
1789 SkipUntil(tok::comma, StopAtSemi);
Douglas Gregor556877c2008-04-13 21:30:24 +00001790 return;
1791 }
1792
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001793 // Create the tag portion of the class or class template.
John McCall48871652010-08-21 09:40:31 +00001794 DeclResult TagOrTempResult = true; // invalid
1795 TypeResult TypeResult = true; // invalid
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001796
Douglas Gregord6ab8742009-05-28 23:31:59 +00001797 bool Owned = false;
Richard Smithd9ba2242015-05-07 03:54:19 +00001798 Sema::SkipBodyInfo SkipBody;
John McCall06f6fe8d2009-09-04 01:14:41 +00001799 if (TemplateId) {
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001800 // Explicit specialization, class template partial specialization,
1801 // or explicit instantiation.
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00001802 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregor7f741122009-02-25 19:37:18 +00001803 TemplateId->NumArgs);
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001804 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
John McCallfaf5fb42010-08-26 23:41:50 +00001805 TUK == Sema::TUK_Declaration) {
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001806 // This is an explicit instantiation of a class template.
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001807 ProhibitAttributes(attrs);
1808
Erich Keanec480f302018-07-12 21:09:05 +00001809 TagOrTempResult = Actions.ActOnExplicitInstantiation(
1810 getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc,
1811 TagType, StartLoc, SS, TemplateId->Template,
1812 TemplateId->TemplateNameLoc, TemplateId->LAngleLoc, TemplateArgsPtr,
1813 TemplateId->RAngleLoc, attrs);
John McCallb7c5c272010-04-14 00:24:33 +00001814
Erich Keanec480f302018-07-12 21:09:05 +00001815 // Friend template-ids are treated as references unless
1816 // they have template headers, in which case they're ill-formed
1817 // (FIXME: "template <class T> friend class A<T>::B<int>;").
1818 // We diagnose this error in ActOnClassTemplateSpecialization.
John McCallfaf5fb42010-08-26 23:41:50 +00001819 } else if (TUK == Sema::TUK_Reference ||
1820 (TUK == Sema::TUK_Friend &&
John McCallb7c5c272010-04-14 00:24:33 +00001821 TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate)) {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001822 ProhibitAttributes(attrs);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00001823 TypeResult = Actions.ActOnTagTemplateIdType(TUK, TagType, StartLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00001824 TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00001825 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00001826 TemplateId->Template,
1827 TemplateId->TemplateNameLoc,
1828 TemplateId->LAngleLoc,
1829 TemplateArgsPtr,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00001830 TemplateId->RAngleLoc);
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001831 } else {
1832 // This is an explicit specialization or a class template
1833 // partial specialization.
1834 TemplateParameterLists FakedParamLists;
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001835 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1836 // This looks like an explicit instantiation, because we have
1837 // something like
1838 //
1839 // template class Foo<X>
1840 //
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001841 // but it actually has a definition. Most likely, this was
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001842 // meant to be an explicit specialization, but the user forgot
1843 // the '<>' after 'template'.
Richard Smith003c5e12013-11-08 19:03:29 +00001844 // It this is friend declaration however, since it cannot have a
1845 // template header, it is most likely that the user meant to
1846 // remove the 'template' keyword.
Larisse Voufob9bbaba2013-06-22 13:56:11 +00001847 assert((TUK == Sema::TUK_Definition || TUK == Sema::TUK_Friend) &&
Richard Smith003c5e12013-11-08 19:03:29 +00001848 "Expected a definition here");
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001849
Richard Smith003c5e12013-11-08 19:03:29 +00001850 if (TUK == Sema::TUK_Friend) {
1851 Diag(DS.getFriendSpecLoc(), diag::err_friend_explicit_instantiation);
Craig Topper161e4db2014-05-21 06:02:52 +00001852 TemplateParams = nullptr;
Richard Smith003c5e12013-11-08 19:03:29 +00001853 } else {
1854 SourceLocation LAngleLoc =
1855 PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
1856 Diag(TemplateId->TemplateNameLoc,
1857 diag::err_explicit_instantiation_with_definition)
1858 << SourceRange(TemplateInfo.TemplateLoc)
1859 << FixItHint::CreateInsertion(LAngleLoc, "<>");
1860
1861 // Create a fake template parameter list that contains only
1862 // "template<>", so that we treat this construct as a class
1863 // template specialization.
1864 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
Craig Topper96225a52015-12-24 23:58:25 +00001865 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
Hubert Tongf608c052016-04-29 18:05:37 +00001866 LAngleLoc, nullptr));
Richard Smith003c5e12013-11-08 19:03:29 +00001867 TemplateParams = &FakedParamLists;
1868 }
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001869 }
1870
1871 // Build the class template specialization.
Richard Smith4b55a9c2014-04-17 03:29:33 +00001872 TagOrTempResult = Actions.ActOnClassTemplateSpecialization(
1873 getCurScope(), TagType, TUK, StartLoc, DS.getModulePrivateSpecLoc(),
Erich Keanec480f302018-07-12 21:09:05 +00001874 *TemplateId, attrs,
Craig Topper161e4db2014-05-21 06:02:52 +00001875 MultiTemplateParamsArg(TemplateParams ? &(*TemplateParams)[0]
1876 : nullptr,
Richard Smithc7e6ff02015-05-18 20:36:47 +00001877 TemplateParams ? TemplateParams->size() : 0),
1878 &SkipBody);
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001879 }
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001880 } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
John McCallfaf5fb42010-08-26 23:41:50 +00001881 TUK == Sema::TUK_Declaration) {
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001882 // Explicit instantiation of a member of a class template
1883 // specialization, e.g.,
1884 //
1885 // template struct Outer<int>::Inner;
1886 //
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001887 ProhibitAttributes(attrs);
1888
Erich Keanec480f302018-07-12 21:09:05 +00001889 TagOrTempResult = Actions.ActOnExplicitInstantiation(
1890 getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc,
1891 TagType, StartLoc, SS, Name, NameLoc, attrs);
John McCallace48cd2010-10-19 01:40:49 +00001892 } else if (TUK == Sema::TUK_Friend &&
1893 TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate) {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001894 ProhibitAttributes(attrs);
1895
Erich Keanec480f302018-07-12 21:09:05 +00001896 TagOrTempResult = Actions.ActOnTemplatedFriendTag(
1897 getCurScope(), DS.getFriendSpecLoc(), TagType, StartLoc, SS, Name,
1898 NameLoc, attrs,
1899 MultiTemplateParamsArg(TemplateParams ? &(*TemplateParams)[0] : nullptr,
1900 TemplateParams ? TemplateParams->size() : 0));
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001901 } else {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001902 if (TUK != Sema::TUK_Declaration && TUK != Sema::TUK_Definition)
1903 ProhibitAttributes(attrs);
Richard Smith003c5e12013-11-08 19:03:29 +00001904
Larisse Voufo725de3e2013-06-21 00:08:46 +00001905 if (TUK == Sema::TUK_Definition &&
1906 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1907 // If the declarator-id is not a template-id, issue a diagnostic and
1908 // recover by ignoring the 'template' keyword.
1909 Diag(Tok, diag::err_template_defn_explicit_instantiation)
1910 << 1 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
Craig Topper161e4db2014-05-21 06:02:52 +00001911 TemplateParams = nullptr;
Larisse Voufo725de3e2013-06-21 00:08:46 +00001912 }
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001913
John McCall7f41d982009-09-11 04:59:25 +00001914 bool IsDependent = false;
1915
John McCall32723e92010-10-19 18:40:57 +00001916 // Don't pass down template parameter lists if this is just a tag
1917 // reference. For example, we don't need the template parameters here:
1918 // template <class T> class A *makeA(T t);
1919 MultiTemplateParamsArg TParams;
1920 if (TUK != Sema::TUK_Reference && TemplateParams)
1921 TParams =
1922 MultiTemplateParamsArg(&(*TemplateParams)[0], TemplateParams->size());
1923
Nico Weber32a0fc72016-09-03 03:01:32 +00001924 stripTypeAttributesOffDeclSpec(attrs, DS, TUK);
David Majnemer936b4112015-04-19 07:53:29 +00001925
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001926 // Declaration or definition of a class type
Faisal Vali7db85c52017-12-31 00:06:40 +00001927 TagOrTempResult = Actions.ActOnTag(
Erich Keanec480f302018-07-12 21:09:05 +00001928 getCurScope(), TagType, TUK, StartLoc, SS, Name, NameLoc, attrs, AS,
1929 DS.getModulePrivateSpecLoc(), TParams, Owned, IsDependent,
1930 SourceLocation(), false, clang::TypeResult(),
Faisal Vali7db85c52017-12-31 00:06:40 +00001931 DSC == DeclSpecContext::DSC_type_specifier,
1932 DSC == DeclSpecContext::DSC_template_param ||
1933 DSC == DeclSpecContext::DSC_template_type_arg,
1934 &SkipBody);
John McCall7f41d982009-09-11 04:59:25 +00001935
1936 // If ActOnTag said the type was dependent, try again with the
1937 // less common call.
John McCallace48cd2010-10-19 01:40:49 +00001938 if (IsDependent) {
1939 assert(TUK == Sema::TUK_Reference || TUK == Sema::TUK_Friend);
Douglas Gregor0be31a22010-07-02 17:43:08 +00001940 TypeResult = Actions.ActOnDependentTag(getCurScope(), TagType, TUK,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001941 SS, Name, StartLoc, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +00001942 }
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001943 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001944
Douglas Gregor556877c2008-04-13 21:30:24 +00001945 // If there is a body, parse it and inform the actions module.
John McCallfaf5fb42010-08-26 23:41:50 +00001946 if (TUK == Sema::TUK_Definition) {
John McCall2d814c32009-12-19 21:48:58 +00001947 assert(Tok.is(tok::l_brace) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00001948 (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
Richard Smith89645bc2013-01-02 12:01:23 +00001949 isCXX11FinalKeyword());
Richard Smithd9ba2242015-05-07 03:54:19 +00001950 if (SkipBody.ShouldSkip)
Richard Smith65ebb4a2015-03-26 04:09:53 +00001951 SkipCXXMemberSpecification(StartLoc, AttrFixitLoc, TagType,
1952 TagOrTempResult.get());
1953 else if (getLangOpts().CPlusPlus)
Michael Han309af292013-01-07 16:57:11 +00001954 ParseCXXMemberSpecification(StartLoc, AttrFixitLoc, attrs, TagType,
1955 TagOrTempResult.get());
Bruno Cardoso Lopesdf0ee342017-07-01 00:06:47 +00001956 else {
1957 Decl *D =
1958 SkipBody.CheckSameAsPrevious ? SkipBody.New : TagOrTempResult.get();
1959 // Parse the definition body.
1960 ParseStructUnionBody(StartLoc, TagType, D);
1961 if (SkipBody.CheckSameAsPrevious &&
1962 !Actions.ActOnDuplicateDefinition(DS, TagOrTempResult.get(),
1963 SkipBody)) {
1964 DS.SetTypeSpecError();
1965 return;
1966 }
1967 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001968 }
1969
Erich Keane2fe684b2017-02-28 20:44:39 +00001970 if (!TagOrTempResult.isInvalid())
Hiroshi Inoue939d9322017-06-30 05:40:31 +00001971 // Delayed processing of attributes.
Erich Keanec480f302018-07-12 21:09:05 +00001972 Actions.ProcessDeclAttributeDelayed(TagOrTempResult.get(), attrs);
Erich Keane2fe684b2017-02-28 20:44:39 +00001973
Craig Topper161e4db2014-05-21 06:02:52 +00001974 const char *PrevSpec = nullptr;
John McCallba7bf592010-08-24 05:47:05 +00001975 unsigned DiagID;
1976 bool Result;
John McCall7f41d982009-09-11 04:59:25 +00001977 if (!TypeResult.isInvalid()) {
Abramo Bagnara9875a3c2011-03-16 20:16:18 +00001978 Result = DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
1979 NameLoc.isValid() ? NameLoc : StartLoc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001980 PrevSpec, DiagID, TypeResult.get(), Policy);
John McCall7f41d982009-09-11 04:59:25 +00001981 } else if (!TagOrTempResult.isInvalid()) {
Abramo Bagnara9875a3c2011-03-16 20:16:18 +00001982 Result = DS.SetTypeSpecType(TagType, StartLoc,
1983 NameLoc.isValid() ? NameLoc : StartLoc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001984 PrevSpec, DiagID, TagOrTempResult.get(), Owned,
1985 Policy);
John McCall7f41d982009-09-11 04:59:25 +00001986 } else {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001987 DS.SetTypeSpecError();
Anders Carlssonf83c9fa2009-05-11 22:27:47 +00001988 return;
1989 }
Mike Stump11289f42009-09-09 15:08:12 +00001990
John McCallba7bf592010-08-24 05:47:05 +00001991 if (Result)
John McCall49bfce42009-08-03 20:12:06 +00001992 Diag(StartLoc, DiagID) << PrevSpec;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001993
Chris Lattnercf251412010-02-02 01:23:29 +00001994 // At this point, we've successfully parsed a class-specifier in 'definition'
1995 // form (e.g. "struct foo { int x; }". While we could just return here, we're
1996 // going to look at what comes after it to improve error recovery. If an
1997 // impossible token occurs next, we assume that the programmer forgot a ; at
1998 // the end of the declaration and recover that way.
1999 //
Richard Smith369b9f92012-06-25 21:37:02 +00002000 // Also enforce C++ [temp]p3:
2001 // In a template-declaration which defines a class, no declarator
2002 // is permitted.
Richard Smith843f18f2014-08-13 02:13:15 +00002003 //
2004 // After a type-specifier, we don't expect a semicolon. This only happens in
2005 // C, since definitions are not permitted in this context in C++.
Joao Matose9a3ed42012-08-31 22:18:20 +00002006 if (TUK == Sema::TUK_Definition &&
Richard Smith843f18f2014-08-13 02:13:15 +00002007 (getLangOpts().CPlusPlus || !isTypeSpecifier(DSC)) &&
Joao Matose9a3ed42012-08-31 22:18:20 +00002008 (TemplateInfo.Kind || !isValidAfterTypeSpecifier(false))) {
Argyrios Kyrtzidise6f69132012-12-17 20:10:43 +00002009 if (Tok.isNot(tok::semi)) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002010 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
Alp Toker383d2c42014-01-01 03:08:43 +00002011 ExpectAndConsume(tok::semi, diag::err_expected_after,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002012 DeclSpec::getSpecifierName(TagType, PPol));
Argyrios Kyrtzidise6f69132012-12-17 20:10:43 +00002013 // Push this token back into the preprocessor and change our current token
2014 // to ';' so that the rest of the code recovers as though there were an
2015 // ';' after the definition.
2016 PP.EnterToken(Tok);
2017 Tok.setKind(tok::semi);
2018 }
Chris Lattnercf251412010-02-02 01:23:29 +00002019 }
Douglas Gregor556877c2008-04-13 21:30:24 +00002020}
2021
Mike Stump11289f42009-09-09 15:08:12 +00002022/// ParseBaseClause - Parse the base-clause of a C++ class [C++ class.derived].
Douglas Gregor556877c2008-04-13 21:30:24 +00002023///
2024/// base-clause : [C++ class.derived]
2025/// ':' base-specifier-list
2026/// base-specifier-list:
2027/// base-specifier '...'[opt]
2028/// base-specifier-list ',' base-specifier '...'[opt]
John McCall48871652010-08-21 09:40:31 +00002029void Parser::ParseBaseClause(Decl *ClassDecl) {
Douglas Gregor556877c2008-04-13 21:30:24 +00002030 assert(Tok.is(tok::colon) && "Not a base clause");
2031 ConsumeToken();
2032
Douglas Gregor29a92472008-10-22 17:49:05 +00002033 // Build up an array of parsed base specifiers.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002034 SmallVector<CXXBaseSpecifier *, 8> BaseInfo;
Douglas Gregor29a92472008-10-22 17:49:05 +00002035
Douglas Gregor556877c2008-04-13 21:30:24 +00002036 while (true) {
2037 // Parse a base-specifier.
Douglas Gregor29a92472008-10-22 17:49:05 +00002038 BaseResult Result = ParseBaseSpecifier(ClassDecl);
Douglas Gregorf8298252009-01-26 22:44:13 +00002039 if (Result.isInvalid()) {
Douglas Gregor556877c2008-04-13 21:30:24 +00002040 // Skip the rest of this base specifier, up until the comma or
2041 // opening brace.
Alexey Bataevee6507d2013-11-18 08:17:37 +00002042 SkipUntil(tok::comma, tok::l_brace, StopAtSemi | StopBeforeMatch);
Douglas Gregor29a92472008-10-22 17:49:05 +00002043 } else {
2044 // Add this to our array of base specifiers.
Douglas Gregorf8298252009-01-26 22:44:13 +00002045 BaseInfo.push_back(Result.get());
Douglas Gregor556877c2008-04-13 21:30:24 +00002046 }
2047
2048 // If the next token is a comma, consume it and keep reading
2049 // base-specifiers.
Alp Toker97650562014-01-10 11:19:30 +00002050 if (!TryConsumeToken(tok::comma))
2051 break;
Douglas Gregor556877c2008-04-13 21:30:24 +00002052 }
Douglas Gregor29a92472008-10-22 17:49:05 +00002053
2054 // Attach the base specifiers
Craig Topperaa700cb2015-12-27 21:55:19 +00002055 Actions.ActOnBaseSpecifiers(ClassDecl, BaseInfo);
Douglas Gregor556877c2008-04-13 21:30:24 +00002056}
2057
2058/// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is
2059/// one entry in the base class list of a class specifier, for example:
2060/// class foo : public bar, virtual private baz {
2061/// 'public bar' and 'virtual private baz' are each base-specifiers.
2062///
2063/// base-specifier: [C++ class.derived]
Richard Smith4c96e992013-02-19 23:47:15 +00002064/// attribute-specifier-seq[opt] base-type-specifier
2065/// attribute-specifier-seq[opt] 'virtual' access-specifier[opt]
2066/// base-type-specifier
2067/// attribute-specifier-seq[opt] access-specifier 'virtual'[opt]
2068/// base-type-specifier
Craig Topper9ad7e262014-10-31 06:57:07 +00002069BaseResult Parser::ParseBaseSpecifier(Decl *ClassDecl) {
Douglas Gregor556877c2008-04-13 21:30:24 +00002070 bool IsVirtual = false;
2071 SourceLocation StartLoc = Tok.getLocation();
2072
Richard Smith4c96e992013-02-19 23:47:15 +00002073 ParsedAttributesWithRange Attributes(AttrFactory);
2074 MaybeParseCXX11Attributes(Attributes);
2075
Douglas Gregor556877c2008-04-13 21:30:24 +00002076 // Parse the 'virtual' keyword.
Alp Toker97650562014-01-10 11:19:30 +00002077 if (TryConsumeToken(tok::kw_virtual))
Douglas Gregor556877c2008-04-13 21:30:24 +00002078 IsVirtual = true;
Douglas Gregor556877c2008-04-13 21:30:24 +00002079
Richard Smith4c96e992013-02-19 23:47:15 +00002080 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2081
Douglas Gregor556877c2008-04-13 21:30:24 +00002082 // Parse an (optional) access specifier.
2083 AccessSpecifier Access = getAccessSpecifierIfPresent();
John McCall553c0792010-01-23 00:46:32 +00002084 if (Access != AS_none)
Douglas Gregor556877c2008-04-13 21:30:24 +00002085 ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +00002086
Richard Smith4c96e992013-02-19 23:47:15 +00002087 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2088
Douglas Gregor556877c2008-04-13 21:30:24 +00002089 // Parse the 'virtual' keyword (again!), in case it came after the
2090 // access specifier.
2091 if (Tok.is(tok::kw_virtual)) {
2092 SourceLocation VirtualLoc = ConsumeToken();
2093 if (IsVirtual) {
2094 // Complain about duplicate 'virtual'
Chris Lattner6d29c102008-11-18 07:48:38 +00002095 Diag(VirtualLoc, diag::err_dup_virtual)
Douglas Gregora771f462010-03-31 17:46:05 +00002096 << FixItHint::CreateRemoval(VirtualLoc);
Douglas Gregor556877c2008-04-13 21:30:24 +00002097 }
2098
2099 IsVirtual = true;
2100 }
2101
Richard Smith4c96e992013-02-19 23:47:15 +00002102 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2103
Douglas Gregor831c93f2008-11-05 20:51:48 +00002104 // Parse the class-name.
David Majnemer51fd8a02015-07-22 23:46:18 +00002105
2106 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
2107 // implementation for VS2013 uses _Atomic as an identifier for one of the
2108 // classes in <atomic>. Treat '_Atomic' to be an identifier when we are
2109 // parsing the class-name for a base specifier.
2110 if (getLangOpts().MSVCCompat && Tok.is(tok::kw__Atomic) &&
2111 NextToken().is(tok::less))
2112 Tok.setKind(tok::identifier);
2113
Douglas Gregord54dfb82009-02-25 23:52:28 +00002114 SourceLocation EndLocation;
David Blaikie1cd50022011-10-25 17:10:12 +00002115 SourceLocation BaseLoc;
2116 TypeResult BaseType = ParseBaseTypeSpecifier(BaseLoc, EndLocation);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00002117 if (BaseType.isInvalid())
Douglas Gregor831c93f2008-11-05 20:51:48 +00002118 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002119
Fangrui Song6907ce22018-07-30 19:24:48 +00002120 // Parse the optional ellipsis (for a pack expansion). The ellipsis is
Douglas Gregor752a5952011-01-03 22:36:02 +00002121 // actually part of the base-specifier-list grammar productions, but we
2122 // parse it here for convenience.
2123 SourceLocation EllipsisLoc;
Alp Toker97650562014-01-10 11:19:30 +00002124 TryConsumeToken(tok::ellipsis, EllipsisLoc);
2125
Mike Stump11289f42009-09-09 15:08:12 +00002126 // Find the complete source range for the base-specifier.
Douglas Gregord54dfb82009-02-25 23:52:28 +00002127 SourceRange Range(StartLoc, EndLocation);
Mike Stump11289f42009-09-09 15:08:12 +00002128
Douglas Gregor556877c2008-04-13 21:30:24 +00002129 // Notify semantic analysis that we have parsed a complete
2130 // base-specifier.
Richard Smith4c96e992013-02-19 23:47:15 +00002131 return Actions.ActOnBaseSpecifier(ClassDecl, Range, Attributes, IsVirtual,
2132 Access, BaseType.get(), BaseLoc,
2133 EllipsisLoc);
Douglas Gregor556877c2008-04-13 21:30:24 +00002134}
2135
2136/// getAccessSpecifierIfPresent - Determine whether the next token is
2137/// a C++ access-specifier.
2138///
2139/// access-specifier: [C++ class.derived]
2140/// 'private'
2141/// 'protected'
2142/// 'public'
Mike Stump11289f42009-09-09 15:08:12 +00002143AccessSpecifier Parser::getAccessSpecifierIfPresent() const {
Douglas Gregor556877c2008-04-13 21:30:24 +00002144 switch (Tok.getKind()) {
2145 default: return AS_none;
2146 case tok::kw_private: return AS_private;
2147 case tok::kw_protected: return AS_protected;
2148 case tok::kw_public: return AS_public;
2149 }
2150}
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002151
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002152/// If the given declarator has any parts for which parsing has to be
Richard Smith0b3a4622014-11-13 20:01:57 +00002153/// delayed, e.g., default arguments or an exception-specification, create a
2154/// late-parsed method declaration record to handle the parsing at the end of
2155/// the class definition.
Douglas Gregor433e0532012-04-16 18:27:27 +00002156void Parser::HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
2157 Decl *ThisDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00002158 DeclaratorChunk::FunctionTypeInfo &FTI
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002159 = DeclaratorInfo.getFunctionTypeInfo();
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002160 // If there was a late-parsed exception-specification, we'll need a
2161 // late parse
2162 bool NeedLateParse = FTI.getExceptionSpecType() == EST_Unparsed;
Douglas Gregor433e0532012-04-16 18:27:27 +00002163
Nathan Sidwell5bb231c2015-02-19 14:03:22 +00002164 if (!NeedLateParse) {
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002165 // Look ahead to see if there are any default args
Nathan Sidwell5bb231c2015-02-19 14:03:22 +00002166 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx) {
2167 auto Param = cast<ParmVarDecl>(FTI.Params[ParamIdx].Param);
2168 if (Param->hasUnparsedDefaultArg()) {
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002169 NeedLateParse = true;
2170 break;
2171 }
Nathan Sidwell5bb231c2015-02-19 14:03:22 +00002172 }
2173 }
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002174
2175 if (NeedLateParse) {
Richard Smith0b3a4622014-11-13 20:01:57 +00002176 // Push this method onto the stack of late-parsed method
2177 // declarations.
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002178 auto LateMethod = new LateParsedMethodDeclaration(this, ThisDecl);
Richard Smith0b3a4622014-11-13 20:01:57 +00002179 getCurrentClass().LateParsedDeclarations.push_back(LateMethod);
2180 LateMethod->TemplateScope = getCurScope()->isTemplateParamScope();
2181
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002182 // Stash the exception-specification tokens in the late-pased method.
Richard Smith0b3a4622014-11-13 20:01:57 +00002183 LateMethod->ExceptionSpecTokens = FTI.ExceptionSpecTokens;
Hans Wennborgdcfba332015-10-06 23:40:43 +00002184 FTI.ExceptionSpecTokens = nullptr;
Richard Smith0b3a4622014-11-13 20:01:57 +00002185
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002186 // Push tokens for each parameter. Those that do not have
2187 // defaults will be NULL.
Richard Smith0b3a4622014-11-13 20:01:57 +00002188 LateMethod->DefaultArgs.reserve(FTI.NumParams);
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002189 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx)
Alp Tokerc5350722014-02-26 22:27:52 +00002190 LateMethod->DefaultArgs.push_back(LateParsedDefaultArgument(
Malcolm Parsonsca9d8342016-11-17 21:00:09 +00002191 FTI.Params[ParamIdx].Param,
2192 std::move(FTI.Params[ParamIdx].DefaultArgTokens)));
Eli Friedman3af2a772009-07-22 21:45:50 +00002193 }
2194}
2195
Richard Smith89645bc2013-01-02 12:01:23 +00002196/// isCXX11VirtSpecifier - Determine whether the given token is a C++11
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002197/// virt-specifier.
2198///
2199/// virt-specifier:
2200/// override
2201/// final
Andrey Bokhanko276055b2016-07-29 10:42:48 +00002202/// __final
Richard Smith89645bc2013-01-02 12:01:23 +00002203VirtSpecifiers::Specifier Parser::isCXX11VirtSpecifier(const Token &Tok) const {
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002204 if (!getLangOpts().CPlusPlus || Tok.isNot(tok::identifier))
Anders Carlsson4b63d0e2011-01-22 16:56:46 +00002205 return VirtSpecifiers::VS_None;
2206
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002207 IdentifierInfo *II = Tok.getIdentifierInfo();
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002208
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002209 // Initialize the contextual keywords.
2210 if (!Ident_final) {
2211 Ident_final = &PP.getIdentifierTable().get("final");
Andrey Bokhanko276055b2016-07-29 10:42:48 +00002212 if (getLangOpts().GNUKeywords)
2213 Ident_GNU_final = &PP.getIdentifierTable().get("__final");
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002214 if (getLangOpts().MicrosoftExt)
2215 Ident_sealed = &PP.getIdentifierTable().get("sealed");
2216 Ident_override = &PP.getIdentifierTable().get("override");
Anders Carlsson56104902011-01-17 03:05:47 +00002217 }
2218
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002219 if (II == Ident_override)
2220 return VirtSpecifiers::VS_Override;
2221
2222 if (II == Ident_sealed)
2223 return VirtSpecifiers::VS_Sealed;
2224
2225 if (II == Ident_final)
2226 return VirtSpecifiers::VS_Final;
2227
Andrey Bokhanko276055b2016-07-29 10:42:48 +00002228 if (II == Ident_GNU_final)
2229 return VirtSpecifiers::VS_GNU_Final;
2230
Anders Carlsson56104902011-01-17 03:05:47 +00002231 return VirtSpecifiers::VS_None;
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002232}
2233
Richard Smith89645bc2013-01-02 12:01:23 +00002234/// ParseOptionalCXX11VirtSpecifierSeq - Parse a virt-specifier-seq.
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002235///
2236/// virt-specifier-seq:
2237/// virt-specifier
2238/// virt-specifier-seq virt-specifier
Richard Smith89645bc2013-01-02 12:01:23 +00002239void Parser::ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS,
Richard Smith3d1a94c2014-08-12 00:22:39 +00002240 bool IsInterface,
2241 SourceLocation FriendLoc) {
Anders Carlsson56104902011-01-17 03:05:47 +00002242 while (true) {
Richard Smith89645bc2013-01-02 12:01:23 +00002243 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
Anders Carlsson56104902011-01-17 03:05:47 +00002244 if (Specifier == VirtSpecifiers::VS_None)
2245 return;
2246
Richard Smith3d1a94c2014-08-12 00:22:39 +00002247 if (FriendLoc.isValid()) {
2248 Diag(Tok.getLocation(), diag::err_friend_decl_spec)
2249 << VirtSpecifiers::getSpecifierName(Specifier)
2250 << FixItHint::CreateRemoval(Tok.getLocation())
2251 << SourceRange(FriendLoc, FriendLoc);
2252 ConsumeToken();
2253 continue;
2254 }
2255
Anders Carlsson56104902011-01-17 03:05:47 +00002256 // C++ [class.mem]p8:
2257 // A virt-specifier-seq shall contain at most one of each virt-specifier.
Craig Topper161e4db2014-05-21 06:02:52 +00002258 const char *PrevSpec = nullptr;
Anders Carlssonf2ca3892011-01-22 15:58:16 +00002259 if (VS.SetSpecifier(Specifier, Tok.getLocation(), PrevSpec))
Anders Carlsson56104902011-01-17 03:05:47 +00002260 Diag(Tok.getLocation(), diag::err_duplicate_virt_specifier)
2261 << PrevSpec
2262 << FixItHint::CreateRemoval(Tok.getLocation());
2263
David Majnemera5433082013-10-18 00:33:31 +00002264 if (IsInterface && (Specifier == VirtSpecifiers::VS_Final ||
2265 Specifier == VirtSpecifiers::VS_Sealed)) {
John McCalldb632ac2012-09-25 07:32:39 +00002266 Diag(Tok.getLocation(), diag::err_override_control_interface)
2267 << VirtSpecifiers::getSpecifierName(Specifier);
David Majnemera5433082013-10-18 00:33:31 +00002268 } else if (Specifier == VirtSpecifiers::VS_Sealed) {
2269 Diag(Tok.getLocation(), diag::ext_ms_sealed_keyword);
Andrey Bokhanko276055b2016-07-29 10:42:48 +00002270 } else if (Specifier == VirtSpecifiers::VS_GNU_Final) {
2271 Diag(Tok.getLocation(), diag::ext_warn_gnu_final);
John McCalldb632ac2012-09-25 07:32:39 +00002272 } else {
David Majnemera5433082013-10-18 00:33:31 +00002273 Diag(Tok.getLocation(),
2274 getLangOpts().CPlusPlus11
2275 ? diag::warn_cxx98_compat_override_control_keyword
2276 : diag::ext_override_control_keyword)
2277 << VirtSpecifiers::getSpecifierName(Specifier);
John McCalldb632ac2012-09-25 07:32:39 +00002278 }
Anders Carlsson56104902011-01-17 03:05:47 +00002279 ConsumeToken();
2280 }
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002281}
2282
Richard Smith89645bc2013-01-02 12:01:23 +00002283/// isCXX11FinalKeyword - Determine whether the next token is a C++11
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002284/// 'final' or Microsoft 'sealed' contextual keyword.
Richard Smith89645bc2013-01-02 12:01:23 +00002285bool Parser::isCXX11FinalKeyword() const {
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002286 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
2287 return Specifier == VirtSpecifiers::VS_Final ||
Fangrui Song6907ce22018-07-30 19:24:48 +00002288 Specifier == VirtSpecifiers::VS_GNU_Final ||
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002289 Specifier == VirtSpecifiers::VS_Sealed;
Anders Carlsson4b63d0e2011-01-22 16:56:46 +00002290}
2291
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002292/// Parse a C++ member-declarator up to, but not including, the optional
Richard Smith72553fc2014-01-23 23:53:27 +00002293/// brace-or-equal-initializer or pure-specifier.
Nico Weberd89e6f72015-01-16 19:34:13 +00002294bool Parser::ParseCXXMemberDeclaratorBeforeInitializer(
Richard Smith72553fc2014-01-23 23:53:27 +00002295 Declarator &DeclaratorInfo, VirtSpecifiers &VS, ExprResult &BitfieldSize,
2296 LateParsedAttrList &LateParsedAttrs) {
2297 // member-declarator:
2298 // declarator pure-specifier[opt]
2299 // declarator brace-or-equal-initializer[opt]
2300 // identifier[opt] ':' constant-expression
Serge Pavlov458ea762014-07-16 05:16:52 +00002301 if (Tok.isNot(tok::colon))
Richard Smith72553fc2014-01-23 23:53:27 +00002302 ParseDeclarator(DeclaratorInfo);
Richard Smith3d1a94c2014-08-12 00:22:39 +00002303 else
2304 DeclaratorInfo.SetIdentifier(nullptr, Tok.getLocation());
Richard Smith72553fc2014-01-23 23:53:27 +00002305
2306 if (!DeclaratorInfo.isFunctionDeclarator() && TryConsumeToken(tok::colon)) {
Richard Smith3d1a94c2014-08-12 00:22:39 +00002307 assert(DeclaratorInfo.isPastIdentifier() &&
2308 "don't know where identifier would go yet?");
Richard Smith72553fc2014-01-23 23:53:27 +00002309 BitfieldSize = ParseConstantExpression();
2310 if (BitfieldSize.isInvalid())
2311 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002312 } else {
Richard Smith3d1a94c2014-08-12 00:22:39 +00002313 ParseOptionalCXX11VirtSpecifierSeq(
2314 VS, getCurrentClass().IsInterface,
2315 DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002316 if (!VS.isUnset())
2317 MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo, VS);
2318 }
Richard Smith72553fc2014-01-23 23:53:27 +00002319
2320 // If a simple-asm-expr is present, parse it.
2321 if (Tok.is(tok::kw_asm)) {
2322 SourceLocation Loc;
2323 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
2324 if (AsmLabel.isInvalid())
2325 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2326
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002327 DeclaratorInfo.setAsmLabel(AsmLabel.get());
Richard Smith72553fc2014-01-23 23:53:27 +00002328 DeclaratorInfo.SetRangeEnd(Loc);
2329 }
2330
2331 // If attributes exist after the declarator, but before an '{', parse them.
2332 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
Richard Smith4b5a9492014-01-24 22:34:35 +00002333
2334 // For compatibility with code written to older Clang, also accept a
2335 // virt-specifier *after* the GNU attributes.
Aaron Ballman5d153e32014-08-04 17:03:51 +00002336 if (BitfieldSize.isUnset() && VS.isUnset()) {
Richard Smith3d1a94c2014-08-12 00:22:39 +00002337 ParseOptionalCXX11VirtSpecifierSeq(
2338 VS, getCurrentClass().IsInterface,
2339 DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
Aaron Ballman5d153e32014-08-04 17:03:51 +00002340 if (!VS.isUnset()) {
2341 // If we saw any GNU-style attributes that are known to GCC followed by a
2342 // virt-specifier, issue a GCC-compat warning.
Erich Keanee891aa92018-07-13 15:07:47 +00002343 for (const ParsedAttr &AL : DeclaratorInfo.getAttributes())
Erich Keanec480f302018-07-12 21:09:05 +00002344 if (AL.isKnownToGCC() && !AL.isCXX11Attribute())
2345 Diag(AL.getLoc(), diag::warn_gcc_attribute_location);
2346
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002347 MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo, VS);
Aaron Ballman5d153e32014-08-04 17:03:51 +00002348 }
2349 }
Nico Weberd89e6f72015-01-16 19:34:13 +00002350
2351 // If this has neither a name nor a bit width, something has gone seriously
2352 // wrong. Skip until the semi-colon or }.
2353 if (!DeclaratorInfo.hasName() && BitfieldSize.isUnset()) {
2354 // If so, skip until the semi-colon or a }.
2355 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2356 return true;
2357 }
2358 return false;
Richard Smith72553fc2014-01-23 23:53:27 +00002359}
2360
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002361/// Look for declaration specifiers possibly occurring after C++11
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002362/// virt-specifier-seq and diagnose them.
2363void Parser::MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(
2364 Declarator &D,
2365 VirtSpecifiers &VS) {
2366 DeclSpec DS(AttrFactory);
2367
2368 // GNU-style and C++11 attributes are not allowed here, but they will be
2369 // handled by the caller. Diagnose everything else.
Alex Lorenz8f4d3992017-02-13 23:19:40 +00002370 ParseTypeQualifierListOpt(
2371 DS, AR_NoAttributesParsed, false,
2372 /*IdentifierRequired=*/false, llvm::function_ref<void()>([&]() {
2373 Actions.CodeCompleteFunctionQualifiers(DS, D, &VS);
2374 }));
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002375 D.ExtendWithDeclSpec(DS);
2376
2377 if (D.isFunctionDeclarator()) {
Ehsan Akhgaric07d1e22015-03-25 00:53:33 +00002378 auto &Function = D.getFunctionTypeInfo();
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002379 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
Anastasia Stulovaa9bc4bd2019-01-09 11:25:09 +00002380 auto DeclSpecCheck = [&](DeclSpec::TQ TypeQual, StringRef FixItName,
2381 SourceLocation SpecLoc) {
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002382 FixItHint Insertion;
Anastasia Stulovaa9bc4bd2019-01-09 11:25:09 +00002383 auto &MQ = Function.getOrCreateMethodQualifiers();
2384 if (!(MQ.getTypeQualifiers() & TypeQual)) {
2385 std::string Name(FixItName.data());
2386 Name += " ";
2387 Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), Name);
2388 MQ.SetTypeQual(TypeQual, SpecLoc);
2389 }
2390 Diag(SpecLoc, diag::err_declspec_after_virtspec)
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002391 << FixItName
2392 << VirtSpecifiers::getSpecifierName(VS.getLastSpecifier())
Anastasia Stulovaa9bc4bd2019-01-09 11:25:09 +00002393 << FixItHint::CreateRemoval(SpecLoc) << Insertion;
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002394 };
Anastasia Stulovaa9bc4bd2019-01-09 11:25:09 +00002395 DS.forEachQualifier(DeclSpecCheck);
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002396 }
Ehsan Akhgaric07d1e22015-03-25 00:53:33 +00002397
2398 // Parse ref-qualifiers.
2399 bool RefQualifierIsLValueRef = true;
2400 SourceLocation RefQualifierLoc;
2401 if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc)) {
2402 const char *Name = (RefQualifierIsLValueRef ? "& " : "&& ");
2403 FixItHint Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), Name);
2404 Function.RefQualifierIsLValueRef = RefQualifierIsLValueRef;
2405 Function.RefQualifierLoc = RefQualifierLoc.getRawEncoding();
2406
2407 Diag(RefQualifierLoc, diag::err_declspec_after_virtspec)
2408 << (RefQualifierIsLValueRef ? "&" : "&&")
2409 << VirtSpecifiers::getSpecifierName(VS.getLastSpecifier())
2410 << FixItHint::CreateRemoval(RefQualifierLoc)
2411 << Insertion;
2412 D.SetRangeEnd(RefQualifierLoc);
2413 }
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002414 }
2415}
2416
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002417/// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration.
2418///
2419/// member-declaration:
2420/// decl-specifier-seq[opt] member-declarator-list[opt] ';'
2421/// function-definition ';'[opt]
2422/// ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO]
2423/// using-declaration [TODO]
Anders Carlssonf24fcff62009-03-11 16:27:10 +00002424/// [C++0x] static_assert-declaration
Anders Carlssondfbbdf62009-03-26 00:52:18 +00002425/// template-declaration
Chris Lattnerd19c1c02008-12-18 01:12:00 +00002426/// [GNU] '__extension__' member-declaration
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002427///
2428/// member-declarator-list:
2429/// member-declarator
2430/// member-declarator-list ',' member-declarator
2431///
2432/// member-declarator:
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002433/// declarator virt-specifier-seq[opt] pure-specifier[opt]
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002434/// declarator constant-initializer[opt]
Richard Smith938f40b2011-06-11 17:19:42 +00002435/// [C++11] declarator brace-or-equal-initializer[opt]
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002436/// identifier[opt] ':' constant-expression
2437///
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002438/// virt-specifier-seq:
2439/// virt-specifier
2440/// virt-specifier-seq virt-specifier
2441///
2442/// virt-specifier:
2443/// override
2444/// final
David Majnemera5433082013-10-18 00:33:31 +00002445/// [MS] sealed
Fangrui Song6907ce22018-07-30 19:24:48 +00002446///
Sebastian Redl42e92c42009-04-12 17:16:29 +00002447/// pure-specifier:
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002448/// '= 0'
2449///
2450/// constant-initializer:
2451/// '=' constant-expression
2452///
Alexey Bataev05c25d62015-07-31 08:42:25 +00002453Parser::DeclGroupPtrTy
2454Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS,
Erich Keanec480f302018-07-12 21:09:05 +00002455 ParsedAttributes &AccessAttrs,
John McCall796c2a52010-07-16 08:13:16 +00002456 const ParsedTemplateInfo &TemplateInfo,
2457 ParsingDeclRAIIObject *TemplateDiags) {
Douglas Gregor23c84762011-04-14 17:21:19 +00002458 if (Tok.is(tok::at)) {
Erik Pilkingtonfa983902018-10-30 20:31:30 +00002459 if (getLangOpts().ObjC && NextToken().isObjCAtKeyword(tok::objc_defs))
Douglas Gregor23c84762011-04-14 17:21:19 +00002460 Diag(Tok, diag::err_at_defs_cxx);
2461 else
2462 Diag(Tok, diag::err_at_in_class);
Richard Smithda35e962013-11-09 04:52:51 +00002463
Douglas Gregor23c84762011-04-14 17:21:19 +00002464 ConsumeToken();
Alexey Bataevee6507d2013-11-18 08:17:37 +00002465 SkipUntil(tok::r_brace, StopAtSemi);
David Blaikie0403cb12016-01-15 23:43:25 +00002466 return nullptr;
Douglas Gregor23c84762011-04-14 17:21:19 +00002467 }
Richard Smithda35e962013-11-09 04:52:51 +00002468
Serge Pavlov458ea762014-07-16 05:16:52 +00002469 // Turn on colon protection early, while parsing declspec, although there is
2470 // nothing to protect there. It prevents from false errors if error recovery
2471 // incorrectly determines where the declspec ends, as in the example:
2472 // struct A { enum class B { C }; };
2473 // const int C = 4;
2474 // struct D { A::B : C; };
2475 ColonProtectionRAIIObject X(*this);
2476
John McCalla0097262009-12-11 02:10:03 +00002477 // Access declarations.
Richard Smith45855df2012-05-09 08:23:23 +00002478 bool MalformedTypeSpec = false;
John McCalla0097262009-12-11 02:10:03 +00002479 if (!TemplateInfo.Kind &&
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002480 Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw___super)) {
Richard Smith45855df2012-05-09 08:23:23 +00002481 if (TryAnnotateCXXScopeToken())
2482 MalformedTypeSpec = true;
2483
2484 bool isAccessDecl;
2485 if (Tok.isNot(tok::annot_cxxscope))
2486 isAccessDecl = false;
2487 else if (NextToken().is(tok::identifier))
John McCalla0097262009-12-11 02:10:03 +00002488 isAccessDecl = GetLookAheadToken(2).is(tok::semi);
2489 else
2490 isAccessDecl = NextToken().is(tok::kw_operator);
2491
2492 if (isAccessDecl) {
2493 // Collect the scope specifier token we annotated earlier.
2494 CXXScopeSpec SS;
David Blaikieefdccaa2016-01-15 23:43:34 +00002495 ParseOptionalCXXScopeSpecifier(SS, nullptr,
Douglas Gregordf593fb2011-11-07 17:33:42 +00002496 /*EnteringContext=*/false);
John McCalla0097262009-12-11 02:10:03 +00002497
Nico Weberef03e702014-09-10 00:59:37 +00002498 if (SS.isInvalid()) {
2499 SkipUntil(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002500 return nullptr;
Nico Weberef03e702014-09-10 00:59:37 +00002501 }
2502
John McCalla0097262009-12-11 02:10:03 +00002503 // Try to parse an unqualified-id.
Abramo Bagnara7945c982012-01-27 09:46:47 +00002504 SourceLocation TemplateKWLoc;
John McCalla0097262009-12-11 02:10:03 +00002505 UnqualifiedId Name;
Richard Smith35845152017-02-07 01:37:30 +00002506 if (ParseUnqualifiedId(SS, false, true, true, false, nullptr,
Richard Smithc08b6932018-04-27 02:00:13 +00002507 &TemplateKWLoc, Name)) {
John McCalla0097262009-12-11 02:10:03 +00002508 SkipUntil(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002509 return nullptr;
John McCalla0097262009-12-11 02:10:03 +00002510 }
2511
2512 // TODO: recover from mistakenly-qualified operator declarations.
Alp Toker383d2c42014-01-01 03:08:43 +00002513 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
2514 "access declaration")) {
2515 SkipUntil(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002516 return nullptr;
Alp Toker383d2c42014-01-01 03:08:43 +00002517 }
John McCalla0097262009-12-11 02:10:03 +00002518
Richard Smithc08b6932018-04-27 02:00:13 +00002519 // FIXME: We should do something with the 'template' keyword here.
Alexey Bataev05c25d62015-07-31 08:42:25 +00002520 return DeclGroupPtrTy::make(DeclGroupRef(Actions.ActOnUsingDeclaration(
Richard Smith151c4562016-12-20 21:35:28 +00002521 getCurScope(), AS, /*UsingLoc*/ SourceLocation(),
2522 /*TypenameLoc*/ SourceLocation(), SS, Name,
Erich Keanec480f302018-07-12 21:09:05 +00002523 /*EllipsisLoc*/ SourceLocation(),
2524 /*AttrList*/ ParsedAttributesView())));
John McCalla0097262009-12-11 02:10:03 +00002525 }
2526 }
2527
Aaron Ballmane7c544d2014-08-04 20:28:35 +00002528 // static_assert-declaration. A templated static_assert declaration is
2529 // diagnosed in Parser::ParseSingleDeclarationAfterTemplate.
2530 if (!TemplateInfo.Kind &&
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002531 Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert)) {
Chris Lattner49836b42009-04-02 04:16:50 +00002532 SourceLocation DeclEnd;
Alexey Bataev05c25d62015-07-31 08:42:25 +00002533 return DeclGroupPtrTy::make(
2534 DeclGroupRef(ParseStaticAssertDeclaration(DeclEnd)));
Chris Lattner5bbb3c82009-03-29 16:50:03 +00002535 }
Mike Stump11289f42009-09-09 15:08:12 +00002536
Chris Lattner5bbb3c82009-03-29 16:50:03 +00002537 if (Tok.is(tok::kw_template)) {
Mike Stump11289f42009-09-09 15:08:12 +00002538 assert(!TemplateInfo.TemplateParams &&
Douglas Gregor3447e762009-08-20 22:52:58 +00002539 "Nested template improperly parsed?");
Richard Smith3af70092017-02-09 22:14:25 +00002540 ObjCDeclContextSwitch ObjCDC(*this);
Chris Lattner49836b42009-04-02 04:16:50 +00002541 SourceLocation DeclEnd;
Alexey Bataev05c25d62015-07-31 08:42:25 +00002542 return DeclGroupPtrTy::make(
Richard Smith3af70092017-02-09 22:14:25 +00002543 DeclGroupRef(ParseTemplateDeclarationOrSpecialization(
Erich Keanec480f302018-07-12 21:09:05 +00002544 DeclaratorContext::MemberContext, DeclEnd, AccessAttrs, AS)));
Chris Lattner5bbb3c82009-03-29 16:50:03 +00002545 }
Anders Carlssondfbbdf62009-03-26 00:52:18 +00002546
Chris Lattnerd19c1c02008-12-18 01:12:00 +00002547 // Handle: member-declaration ::= '__extension__' member-declaration
2548 if (Tok.is(tok::kw___extension__)) {
2549 // __extension__ silences extension warnings in the subexpression.
2550 ExtensionRAIIObject O(Diags); // Use RAII to do this.
2551 ConsumeToken();
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00002552 return ParseCXXClassMemberDeclaration(AS, AccessAttrs,
2553 TemplateInfo, TemplateDiags);
Chris Lattnerd19c1c02008-12-18 01:12:00 +00002554 }
Douglas Gregorfec52632009-06-20 00:51:54 +00002555
John McCall084e83d2011-03-24 11:26:52 +00002556 ParsedAttributesWithRange attrs(AttrFactory);
Erich Keanec480f302018-07-12 21:09:05 +00002557 ParsedAttributesViewWithRange FnAttrs;
Richard Smith89645bc2013-01-02 12:01:23 +00002558 // Optional C++11 attribute-specifier
2559 MaybeParseCXX11Attributes(attrs);
Michael Handdc016d2012-11-28 23:17:40 +00002560 // We need to keep these attributes for future diagnostic
2561 // before they are taken over by declaration specifier.
Erich Keanec480f302018-07-12 21:09:05 +00002562 FnAttrs.addAll(attrs.begin(), attrs.end());
Michael Handdc016d2012-11-28 23:17:40 +00002563 FnAttrs.Range = attrs.Range;
2564
John McCall53fa7142010-12-24 02:08:15 +00002565 MaybeParseMicrosoftAttributes(attrs);
Alexis Hunt96d5c762009-11-21 08:43:09 +00002566
Douglas Gregorfec52632009-06-20 00:51:54 +00002567 if (Tok.is(tok::kw_using)) {
John McCall53fa7142010-12-24 02:08:15 +00002568 ProhibitAttributes(attrs);
Mike Stump11289f42009-09-09 15:08:12 +00002569
Douglas Gregorfec52632009-06-20 00:51:54 +00002570 // Eat 'using'.
2571 SourceLocation UsingLoc = ConsumeToken();
2572
Richard Trieu2efd3052019-05-01 23:33:49 +00002573 // Consume unexpected 'template' keywords.
2574 while (Tok.is(tok::kw_template)) {
2575 SourceLocation TemplateLoc = ConsumeToken();
2576 Diag(TemplateLoc, diag::err_unexpected_template_after_using)
2577 << FixItHint::CreateRemoval(TemplateLoc);
2578 }
2579
Douglas Gregorfec52632009-06-20 00:51:54 +00002580 if (Tok.is(tok::kw_namespace)) {
2581 Diag(UsingLoc, diag::err_using_namespace_in_class);
Alexey Bataevee6507d2013-11-18 08:17:37 +00002582 SkipUntil(tok::semi, StopBeforeMatch);
David Blaikie0403cb12016-01-15 23:43:25 +00002583 return nullptr;
Douglas Gregorfec52632009-06-20 00:51:54 +00002584 }
Alexey Bataev05c25d62015-07-31 08:42:25 +00002585 SourceLocation DeclEnd;
2586 // Otherwise, it must be a using-declaration or an alias-declaration.
Faisal Vali421b2d12017-12-29 05:41:00 +00002587 return ParseUsingDeclaration(DeclaratorContext::MemberContext, TemplateInfo,
Richard Smith6f1daa42016-12-16 00:58:48 +00002588 UsingLoc, DeclEnd, AS);
Douglas Gregorfec52632009-06-20 00:51:54 +00002589 }
2590
DeLesley Hutchinsbd2ee132012-03-02 22:12:59 +00002591 // Hold late-parsed attributes so we can attach a Decl to them later.
2592 LateParsedAttrList CommonLateParsedAttrs;
2593
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002594 // decl-specifier-seq:
2595 // Parse the common declaration-specifiers piece.
John McCall796c2a52010-07-16 08:13:16 +00002596 ParsingDeclSpec DS(*this, TemplateDiags);
John McCall53fa7142010-12-24 02:08:15 +00002597 DS.takeAttributesFrom(attrs);
Richard Smith45855df2012-05-09 08:23:23 +00002598 if (MalformedTypeSpec)
2599 DS.SetTypeSpecError();
Richard Smith72553fc2014-01-23 23:53:27 +00002600
Faisal Valia534f072018-04-26 00:42:40 +00002601 ParseDeclarationSpecifiers(DS, TemplateInfo, AS, DeclSpecContext::DSC_class,
2602 &CommonLateParsedAttrs);
Serge Pavlov458ea762014-07-16 05:16:52 +00002603
2604 // Turn off colon protection that was set for declspec.
2605 X.restore();
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002606
Richard Smith404dfb42013-11-19 22:47:36 +00002607 // If we had a free-standing type definition with a missing semicolon, we
2608 // may get this far before the problem becomes obvious.
2609 if (DS.hasTagDefinition() &&
2610 TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate &&
Faisal Vali7db85c52017-12-31 00:06:40 +00002611 DiagnoseMissingSemiAfterTagDefinition(DS, AS, DeclSpecContext::DSC_class,
Richard Smith404dfb42013-11-19 22:47:36 +00002612 &CommonLateParsedAttrs))
David Blaikie0403cb12016-01-15 23:43:25 +00002613 return nullptr;
Richard Smith404dfb42013-11-19 22:47:36 +00002614
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002615 MultiTemplateParamsArg TemplateParams(
Craig Topper161e4db2014-05-21 06:02:52 +00002616 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->data()
2617 : nullptr,
John McCall11083da2009-09-16 22:47:08 +00002618 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->size() : 0);
2619
Alp Toker35d87032013-12-30 23:29:50 +00002620 if (TryConsumeToken(tok::semi)) {
Michael Handdc016d2012-11-28 23:17:40 +00002621 if (DS.isFriendSpecified())
2622 ProhibitAttributes(FnAttrs);
2623
Nico Weber7b837f52016-01-28 19:25:00 +00002624 RecordDecl *AnonRecord = nullptr;
2625 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(
2626 getCurScope(), AS, DS, TemplateParams, false, AnonRecord);
John McCall796c2a52010-07-16 08:13:16 +00002627 DS.complete(TheDecl);
Nico Weber7b837f52016-01-28 19:25:00 +00002628 if (AnonRecord) {
2629 Decl* decls[] = {AnonRecord, TheDecl};
Richard Smith3beb7c62017-01-12 02:27:38 +00002630 return Actions.BuildDeclaratorGroup(decls);
Nico Weber7b837f52016-01-28 19:25:00 +00002631 }
2632 return Actions.ConvertDeclToDeclGroup(TheDecl);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002633 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002634
Faisal Vali421b2d12017-12-29 05:41:00 +00002635 ParsingDeclarator DeclaratorInfo(*this, DS, DeclaratorContext::MemberContext);
Nico Weber24b2a822011-01-28 06:07:34 +00002636 VirtSpecifiers VS;
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002637
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002638 // Hold late-parsed attributes so we can attach a Decl to them later.
2639 LateParsedAttrList LateParsedAttrs;
2640
Douglas Gregor50cefbf2011-10-17 17:09:53 +00002641 SourceLocation EqualLoc;
Richard Smith9ba0fec2015-06-30 01:28:56 +00002642 SourceLocation PureSpecLoc;
2643
Yaron Keren180c1672015-06-30 07:35:19 +00002644 auto TryConsumePureSpecifier = [&] (bool AllowDefinition) {
Richard Smith9ba0fec2015-06-30 01:28:56 +00002645 if (Tok.isNot(tok::equal))
2646 return false;
2647
2648 auto &Zero = NextToken();
2649 SmallString<8> Buffer;
2650 if (Zero.isNot(tok::numeric_constant) || Zero.getLength() != 1 ||
2651 PP.getSpelling(Zero, Buffer) != "0")
2652 return false;
2653
2654 auto &After = GetLookAheadToken(2);
2655 if (!After.isOneOf(tok::semi, tok::comma) &&
2656 !(AllowDefinition &&
2657 After.isOneOf(tok::l_brace, tok::colon, tok::kw_try)))
2658 return false;
2659
2660 EqualLoc = ConsumeToken();
2661 PureSpecLoc = ConsumeToken();
2662 return true;
2663 };
Chris Lattner17c3b1f2009-12-10 01:59:24 +00002664
Richard Smith72553fc2014-01-23 23:53:27 +00002665 SmallVector<Decl *, 8> DeclsInGroup;
2666 ExprResult BitfieldSize;
2667 bool ExpectSemi = true;
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002668
Richard Smith72553fc2014-01-23 23:53:27 +00002669 // Parse the first declarator.
Nico Weberd89e6f72015-01-16 19:34:13 +00002670 if (ParseCXXMemberDeclaratorBeforeInitializer(
2671 DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs)) {
Richard Smith72553fc2014-01-23 23:53:27 +00002672 TryConsumeToken(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002673 return nullptr;
Richard Smith72553fc2014-01-23 23:53:27 +00002674 }
John Thompson5bc5cbe2009-11-25 22:58:06 +00002675
Richard Smith72553fc2014-01-23 23:53:27 +00002676 // Check for a member function definition.
Richard Smith4b5a9492014-01-24 22:34:35 +00002677 if (BitfieldSize.isUnset()) {
Richard Smith72553fc2014-01-23 23:53:27 +00002678 // MSVC permits pure specifier on inline functions defined at class scope.
Francois Pichet3abc9b82011-05-11 02:14:46 +00002679 // Hence check for =0 before checking for function definition.
Richard Smith9ba0fec2015-06-30 01:28:56 +00002680 if (getLangOpts().MicrosoftExt && DeclaratorInfo.isDeclarationOfFunction())
2681 TryConsumePureSpecifier(/*AllowDefinition*/ true);
Francois Pichet3abc9b82011-05-11 02:14:46 +00002682
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00002683 FunctionDefinitionKind DefinitionKind = FDK_Declaration;
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002684 // function-definition:
Richard Smith938f40b2011-06-11 17:19:42 +00002685 //
2686 // In C++11, a non-function declarator followed by an open brace is a
2687 // braced-init-list for an in-class member initialization, not an
2688 // erroneous function definition.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002689 if (Tok.is(tok::l_brace) && !getLangOpts().CPlusPlus11) {
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00002690 DefinitionKind = FDK_Definition;
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002691 } else if (DeclaratorInfo.isFunctionDeclarator()) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002692 if (Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try)) {
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00002693 DefinitionKind = FDK_Definition;
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002694 } else if (Tok.is(tok::equal)) {
2695 const Token &KW = NextToken();
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00002696 if (KW.is(tok::kw_default))
2697 DefinitionKind = FDK_Defaulted;
2698 else if (KW.is(tok::kw_delete))
2699 DefinitionKind = FDK_Deleted;
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002700 }
2701 }
Eli Bendersky41842222015-03-23 23:49:41 +00002702 DeclaratorInfo.setFunctionDefinitionKind(DefinitionKind);
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002703
Fangrui Song6907ce22018-07-30 19:24:48 +00002704 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
Michael Handdc016d2012-11-28 23:17:40 +00002705 // to a friend declaration, that declaration shall be a definition.
Fangrui Song6907ce22018-07-30 19:24:48 +00002706 if (DeclaratorInfo.isFunctionDeclarator() &&
Michael Handdc016d2012-11-28 23:17:40 +00002707 DefinitionKind != FDK_Definition && DS.isFriendSpecified()) {
2708 // Diagnose attributes that appear before decl specifier:
2709 // [[]] friend int foo();
2710 ProhibitAttributes(FnAttrs);
2711 }
2712
Nico Webera7f137d2015-01-16 19:35:01 +00002713 if (DefinitionKind != FDK_Declaration) {
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002714 if (!DeclaratorInfo.isFunctionDeclarator()) {
Richard Trieu0d730542012-01-21 02:59:18 +00002715 Diag(DeclaratorInfo.getIdentifierLoc(), diag::err_func_def_no_params);
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002716 ConsumeBrace();
Alexey Bataevee6507d2013-11-18 08:17:37 +00002717 SkipUntil(tok::r_brace);
Michael Handdc016d2012-11-28 23:17:40 +00002718
Douglas Gregor8a4db832011-01-19 16:41:58 +00002719 // Consume the optional ';'
Alp Toker35d87032013-12-30 23:29:50 +00002720 TryConsumeToken(tok::semi);
2721
David Blaikie0403cb12016-01-15 23:43:25 +00002722 return nullptr;
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002723 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002724
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002725 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
Richard Trieu0d730542012-01-21 02:59:18 +00002726 Diag(DeclaratorInfo.getIdentifierLoc(),
2727 diag::err_function_declared_typedef);
Douglas Gregor8a4db832011-01-19 16:41:58 +00002728
Richard Smith2603b092012-11-15 22:54:20 +00002729 // Recover by treating the 'typedef' as spurious.
2730 DS.ClearStorageClassSpecs();
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002731 }
2732
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002733 Decl *FunDecl =
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00002734 ParseCXXInlineMethodDef(AS, AccessAttrs, DeclaratorInfo, TemplateInfo,
Richard Smith9ba0fec2015-06-30 01:28:56 +00002735 VS, PureSpecLoc);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002736
David Majnemer23252a32013-08-01 04:22:55 +00002737 if (FunDecl) {
2738 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i) {
2739 CommonLateParsedAttrs[i]->addDecl(FunDecl);
2740 }
2741 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i) {
2742 LateParsedAttrs[i]->addDecl(FunDecl);
2743 }
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002744 }
2745 LateParsedAttrs.clear();
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002746
2747 // Consume the ';' - it's optional unless we have a delete or default
Richard Trieu2f7dc462012-05-16 19:04:59 +00002748 if (Tok.is(tok::semi))
Richard Smith87f5dc52012-07-23 05:45:25 +00002749 ConsumeExtraSemi(AfterMemberFunctionDefinition);
Douglas Gregor8a4db832011-01-19 16:41:58 +00002750
Alexey Bataev05c25d62015-07-31 08:42:25 +00002751 return DeclGroupPtrTy::make(DeclGroupRef(FunDecl));
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002752 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002753 }
2754
2755 // member-declarator-list:
2756 // member-declarator
2757 // member-declarator-list ',' member-declarator
2758
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002759 while (1) {
Richard Smith2b013182012-06-10 03:12:00 +00002760 InClassInitStyle HasInClassInit = ICIS_NoInit;
Richard Smith9ba0fec2015-06-30 01:28:56 +00002761 bool HasStaticInitializer = false;
2762 if (Tok.isOneOf(tok::equal, tok::l_brace) && PureSpecLoc.isInvalid()) {
Richard Smith6b8e3c02017-08-28 00:28:14 +00002763 if (DeclaratorInfo.isDeclarationOfFunction()) {
Richard Smith9ba0fec2015-06-30 01:28:56 +00002764 // It's a pure-specifier.
2765 if (!TryConsumePureSpecifier(/*AllowFunctionDefinition*/ false))
2766 // Parse it as an expression so that Sema can diagnose it.
2767 HasStaticInitializer = true;
2768 } else if (DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2769 DeclSpec::SCS_static &&
2770 DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2771 DeclSpec::SCS_typedef &&
2772 !DS.isFriendSpecified()) {
2773 // It's a default member initializer.
Richard Smith6b8e3c02017-08-28 00:28:14 +00002774 if (BitfieldSize.get())
2775 Diag(Tok, getLangOpts().CPlusPlus2a
2776 ? diag::warn_cxx17_compat_bitfield_member_init
2777 : diag::ext_bitfield_member_init);
Richard Smith9ba0fec2015-06-30 01:28:56 +00002778 HasInClassInit = Tok.is(tok::equal) ? ICIS_CopyInit : ICIS_ListInit;
Richard Smith938f40b2011-06-11 17:19:42 +00002779 } else {
Richard Smith9ba0fec2015-06-30 01:28:56 +00002780 HasStaticInitializer = true;
Richard Smith938f40b2011-06-11 17:19:42 +00002781 }
2782 }
2783
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002784 // NOTE: If Sema is the Action module and declarator is an instance field,
Chris Lattner5bbb3c82009-03-29 16:50:03 +00002785 // this call will *not* return the created decl; It will return null.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002786 // See Sema::ActOnCXXMemberDeclarator for details.
John McCall07e91c02009-08-06 02:15:43 +00002787
Craig Topper161e4db2014-05-21 06:02:52 +00002788 NamedDecl *ThisDecl = nullptr;
John McCall07e91c02009-08-06 02:15:43 +00002789 if (DS.isFriendSpecified()) {
Richard Smith72553fc2014-01-23 23:53:27 +00002790 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
Michael Handdc016d2012-11-28 23:17:40 +00002791 // to a friend declaration, that declaration shall be a definition.
2792 //
Richard Smith72553fc2014-01-23 23:53:27 +00002793 // Diagnose attributes that appear in a friend member function declarator:
2794 // friend int foo [[]] ();
Michael Handdc016d2012-11-28 23:17:40 +00002795 SmallVector<SourceRange, 4> Ranges;
2796 DeclaratorInfo.getCXX11AttributeRanges(Ranges);
Richard Smith72553fc2014-01-23 23:53:27 +00002797 for (SmallVectorImpl<SourceRange>::iterator I = Ranges.begin(),
2798 E = Ranges.end(); I != E; ++I)
2799 Diag((*I).getBegin(), diag::err_attributes_not_allowed) << *I;
Michael Handdc016d2012-11-28 23:17:40 +00002800
Douglas Gregor0be31a22010-07-02 17:43:08 +00002801 ThisDecl = Actions.ActOnFriendFunctionDecl(getCurScope(), DeclaratorInfo,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002802 TemplateParams);
Douglas Gregor3447e762009-08-20 22:52:58 +00002803 } else {
Douglas Gregor0be31a22010-07-02 17:43:08 +00002804 ThisDecl = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS,
John McCall07e91c02009-08-06 02:15:43 +00002805 DeclaratorInfo,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002806 TemplateParams,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002807 BitfieldSize.get(),
Richard Smith2b013182012-06-10 03:12:00 +00002808 VS, HasInClassInit);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002809
2810 if (VarTemplateDecl *VT =
Craig Topper161e4db2014-05-21 06:02:52 +00002811 ThisDecl ? dyn_cast<VarTemplateDecl>(ThisDecl) : nullptr)
Larisse Voufo39a1e502013-08-06 01:03:05 +00002812 // Re-direct this decl to refer to the templated decl so that we can
2813 // initialize it.
2814 ThisDecl = VT->getTemplatedDecl();
2815
Erich Keanec480f302018-07-12 21:09:05 +00002816 if (ThisDecl)
Richard Smithf8a75c32013-08-29 00:47:48 +00002817 Actions.ProcessDeclAttributeList(getCurScope(), ThisDecl, AccessAttrs);
Douglas Gregor3447e762009-08-20 22:52:58 +00002818 }
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002819
Richard Smith9ba0fec2015-06-30 01:28:56 +00002820 // Error recovery might have converted a non-static member into a static
2821 // member.
David Blaikie35506f82013-01-30 01:22:18 +00002822 if (HasInClassInit != ICIS_NoInit &&
Richard Smith9ba0fec2015-06-30 01:28:56 +00002823 DeclaratorInfo.getDeclSpec().getStorageClassSpec() ==
2824 DeclSpec::SCS_static) {
2825 HasInClassInit = ICIS_NoInit;
2826 HasStaticInitializer = true;
2827 }
2828
2829 if (ThisDecl && PureSpecLoc.isValid())
2830 Actions.ActOnPureSpecifier(ThisDecl, PureSpecLoc);
2831
2832 // Handle the initializer.
2833 if (HasInClassInit != ICIS_NoInit) {
Douglas Gregor728d00b2011-10-10 14:49:18 +00002834 // The initializer was deferred; parse it and cache the tokens.
David Majnemer23252a32013-08-01 04:22:55 +00002835 Diag(Tok, getLangOpts().CPlusPlus11
2836 ? diag::warn_cxx98_compat_nonstatic_member_init
2837 : diag::ext_nonstatic_member_init);
Richard Smith5d164bc2011-10-15 05:09:34 +00002838
Richard Smith938f40b2011-06-11 17:19:42 +00002839 if (DeclaratorInfo.isArrayOfUnknownBound()) {
Richard Smith2b013182012-06-10 03:12:00 +00002840 // C++11 [dcl.array]p3: An array bound may also be omitted when the
2841 // declarator is followed by an initializer.
Richard Smith938f40b2011-06-11 17:19:42 +00002842 //
2843 // A brace-or-equal-initializer for a member-declarator is not an
David Blaikiecdd91db2012-02-14 09:00:46 +00002844 // initializer in the grammar, so this is ill-formed.
Richard Smith938f40b2011-06-11 17:19:42 +00002845 Diag(Tok, diag::err_incomplete_array_member_init);
Alexey Bataevee6507d2013-11-18 08:17:37 +00002846 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
David Majnemer23252a32013-08-01 04:22:55 +00002847
2848 // Avoid later warnings about a class member of incomplete type.
David Blaikiecdd91db2012-02-14 09:00:46 +00002849 if (ThisDecl)
David Blaikiecdd91db2012-02-14 09:00:46 +00002850 ThisDecl->setInvalidDecl();
Richard Smith938f40b2011-06-11 17:19:42 +00002851 } else
2852 ParseCXXNonStaticMemberInitializer(ThisDecl);
Richard Smith9ba0fec2015-06-30 01:28:56 +00002853 } else if (HasStaticInitializer) {
Douglas Gregor728d00b2011-10-10 14:49:18 +00002854 // Normal initializer.
Richard Smith9ba0fec2015-06-30 01:28:56 +00002855 ExprResult Init = ParseCXXMemberInitializer(
2856 ThisDecl, DeclaratorInfo.isDeclarationOfFunction(), EqualLoc);
David Majnemer23252a32013-08-01 04:22:55 +00002857
Douglas Gregor728d00b2011-10-10 14:49:18 +00002858 if (Init.isInvalid())
Alexey Bataevee6507d2013-11-18 08:17:37 +00002859 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
Douglas Gregor728d00b2011-10-10 14:49:18 +00002860 else if (ThisDecl)
Richard Smith3beb7c62017-01-12 02:27:38 +00002861 Actions.AddInitializerToDecl(ThisDecl, Init.get(), EqualLoc.isInvalid());
David Majnemer23252a32013-08-01 04:22:55 +00002862 } else if (ThisDecl && DS.getStorageClassSpec() == DeclSpec::SCS_static)
Douglas Gregor728d00b2011-10-10 14:49:18 +00002863 // No initializer.
Richard Smith3beb7c62017-01-12 02:27:38 +00002864 Actions.ActOnUninitializedDecl(ThisDecl);
David Majnemer23252a32013-08-01 04:22:55 +00002865
Douglas Gregor728d00b2011-10-10 14:49:18 +00002866 if (ThisDecl) {
David Majnemer23252a32013-08-01 04:22:55 +00002867 if (!ThisDecl->isInvalidDecl()) {
2868 // Set the Decl for any late parsed attributes
2869 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i)
2870 CommonLateParsedAttrs[i]->addDecl(ThisDecl);
2871
2872 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i)
2873 LateParsedAttrs[i]->addDecl(ThisDecl);
2874 }
Douglas Gregor728d00b2011-10-10 14:49:18 +00002875 Actions.FinalizeDeclaration(ThisDecl);
2876 DeclsInGroup.push_back(ThisDecl);
David Majnemer23252a32013-08-01 04:22:55 +00002877
2878 if (DeclaratorInfo.isFunctionDeclarator() &&
2879 DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2880 DeclSpec::SCS_typedef)
2881 HandleMemberFunctionDeclDelays(DeclaratorInfo, ThisDecl);
Douglas Gregor728d00b2011-10-10 14:49:18 +00002882 }
David Majnemer23252a32013-08-01 04:22:55 +00002883 LateParsedAttrs.clear();
Douglas Gregor728d00b2011-10-10 14:49:18 +00002884
2885 DeclaratorInfo.complete(ThisDecl);
Richard Smith938f40b2011-06-11 17:19:42 +00002886
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002887 // If we don't have a comma, it is either the end of the list (a ';')
2888 // or an error, bail out.
Alp Toker094e5212014-01-05 03:27:11 +00002889 SourceLocation CommaLoc;
2890 if (!TryConsumeToken(tok::comma, CommaLoc))
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002891 break;
Mike Stump11289f42009-09-09 15:08:12 +00002892
Richard Smithc8a79032012-01-09 22:31:44 +00002893 if (Tok.isAtStartOfLine() &&
Faisal Vali421b2d12017-12-29 05:41:00 +00002894 !MightBeDeclarator(DeclaratorContext::MemberContext)) {
Richard Smithc8a79032012-01-09 22:31:44 +00002895 // This comma was followed by a line-break and something which can't be
2896 // the start of a declarator. The comma was probably a typo for a
2897 // semicolon.
2898 Diag(CommaLoc, diag::err_expected_semi_declaration)
2899 << FixItHint::CreateReplacement(CommaLoc, ";");
2900 ExpectSemi = false;
2901 break;
2902 }
Mike Stump11289f42009-09-09 15:08:12 +00002903
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002904 // Parse the next declarator.
2905 DeclaratorInfo.clear();
Nico Weber24b2a822011-01-28 06:07:34 +00002906 VS.clear();
Nico Weberf56c85b2015-01-17 02:26:40 +00002907 BitfieldSize = ExprResult(/*Invalid=*/false);
Richard Smith9ba0fec2015-06-30 01:28:56 +00002908 EqualLoc = PureSpecLoc = SourceLocation();
Richard Smith8d06f422012-01-12 23:53:29 +00002909 DeclaratorInfo.setCommaLoc(CommaLoc);
Mike Stump11289f42009-09-09 15:08:12 +00002910
Richard Smith72553fc2014-01-23 23:53:27 +00002911 // GNU attributes are allowed before the second and subsequent declarator.
John McCall53fa7142010-12-24 02:08:15 +00002912 MaybeParseGNUAttributes(DeclaratorInfo);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002913
Nico Weberd89e6f72015-01-16 19:34:13 +00002914 if (ParseCXXMemberDeclaratorBeforeInitializer(
2915 DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs))
2916 break;
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002917 }
2918
Richard Smithc8a79032012-01-09 22:31:44 +00002919 if (ExpectSemi &&
2920 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list)) {
Chris Lattner916dbf12010-02-02 00:43:15 +00002921 // Skip to end of block or statement.
Alexey Bataevee6507d2013-11-18 08:17:37 +00002922 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Chris Lattner916dbf12010-02-02 00:43:15 +00002923 // If we stopped at a ';', eat it.
Alp Toker35d87032013-12-30 23:29:50 +00002924 TryConsumeToken(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002925 return nullptr;
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002926 }
2927
Alexey Bataev05c25d62015-07-31 08:42:25 +00002928 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002929}
2930
Richard Smith9ba0fec2015-06-30 01:28:56 +00002931/// ParseCXXMemberInitializer - Parse the brace-or-equal-initializer.
2932/// Also detect and reject any attempted defaulted/deleted function definition.
2933/// The location of the '=', if any, will be placed in EqualLoc.
Richard Smith938f40b2011-06-11 17:19:42 +00002934///
Richard Smith9ba0fec2015-06-30 01:28:56 +00002935/// This does not check for a pure-specifier; that's handled elsewhere.
Sebastian Redleef474c2012-02-22 10:50:08 +00002936///
Richard Smith938f40b2011-06-11 17:19:42 +00002937/// brace-or-equal-initializer:
2938/// '=' initializer-expression
Sebastian Redleef474c2012-02-22 10:50:08 +00002939/// braced-init-list
2940///
Richard Smith938f40b2011-06-11 17:19:42 +00002941/// initializer-clause:
2942/// assignment-expression
Sebastian Redleef474c2012-02-22 10:50:08 +00002943/// braced-init-list
2944///
Richard Smithda35e962013-11-09 04:52:51 +00002945/// defaulted/deleted function-definition:
Richard Smith938f40b2011-06-11 17:19:42 +00002946/// '=' 'default'
2947/// '=' 'delete'
2948///
2949/// Prior to C++0x, the assignment-expression in an initializer-clause must
2950/// be a constant-expression.
Douglas Gregor926410d2012-02-21 02:22:07 +00002951ExprResult Parser::ParseCXXMemberInitializer(Decl *D, bool IsFunction,
Richard Smith938f40b2011-06-11 17:19:42 +00002952 SourceLocation &EqualLoc) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002953 assert(Tok.isOneOf(tok::equal, tok::l_brace)
Richard Smith938f40b2011-06-11 17:19:42 +00002954 && "Data member initializer not starting with '=' or '{'");
2955
Faisal Valid143a0c2017-04-01 21:30:49 +00002956 EnterExpressionEvaluationContext Context(
2957 Actions, Sema::ExpressionEvaluationContext::PotentiallyEvaluated, D);
Alp Toker094e5212014-01-05 03:27:11 +00002958 if (TryConsumeToken(tok::equal, EqualLoc)) {
Richard Smith938f40b2011-06-11 17:19:42 +00002959 if (Tok.is(tok::kw_delete)) {
2960 // In principle, an initializer of '= delete p;' is legal, but it will
2961 // never type-check. It's better to diagnose it as an ill-formed expression
2962 // than as an ill-formed deleted non-function member.
2963 // An initializer of '= delete p, foo' will never be parsed, because
2964 // a top-level comma always ends the initializer expression.
2965 const Token &Next = NextToken();
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002966 if (IsFunction || Next.isOneOf(tok::semi, tok::comma, tok::eof)) {
Richard Smith938f40b2011-06-11 17:19:42 +00002967 if (IsFunction)
2968 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2969 << 1 /* delete */;
2970 else
2971 Diag(ConsumeToken(), diag::err_deleted_non_function);
Richard Smithedcb26e2014-06-11 00:49:52 +00002972 return ExprError();
Richard Smith938f40b2011-06-11 17:19:42 +00002973 }
2974 } else if (Tok.is(tok::kw_default)) {
Richard Smith938f40b2011-06-11 17:19:42 +00002975 if (IsFunction)
2976 Diag(Tok, diag::err_default_delete_in_multiple_declaration)
2977 << 0 /* default */;
2978 else
2979 Diag(ConsumeToken(), diag::err_default_special_members);
Richard Smithedcb26e2014-06-11 00:49:52 +00002980 return ExprError();
Richard Smith938f40b2011-06-11 17:19:42 +00002981 }
David Majnemer87ff66c2014-12-13 11:34:16 +00002982 }
2983 if (const auto *PD = dyn_cast_or_null<MSPropertyDecl>(D)) {
2984 Diag(Tok, diag::err_ms_property_initializer) << PD;
2985 return ExprError();
Sebastian Redleef474c2012-02-22 10:50:08 +00002986 }
2987 return ParseInitializer();
Richard Smith938f40b2011-06-11 17:19:42 +00002988}
2989
Richard Smith65ebb4a2015-03-26 04:09:53 +00002990void Parser::SkipCXXMemberSpecification(SourceLocation RecordLoc,
2991 SourceLocation AttrFixitLoc,
Faisal Vali090da2d2018-01-01 18:23:28 +00002992 unsigned TagType, Decl *TagDecl) {
Richard Smith65ebb4a2015-03-26 04:09:53 +00002993 // Skip the optional 'final' keyword.
2994 if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
2995 assert(isCXX11FinalKeyword() && "not a class definition");
2996 ConsumeToken();
2997
2998 // Diagnose any C++11 attributes after 'final' keyword.
2999 // We deliberately discard these attributes.
3000 ParsedAttributesWithRange Attrs(AttrFactory);
3001 CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
3002
3003 // This can only happen if we had malformed misplaced attributes;
3004 // we only get called if there is a colon or left-brace after the
3005 // attributes.
3006 if (Tok.isNot(tok::colon) && Tok.isNot(tok::l_brace))
3007 return;
3008 }
3009
3010 // Skip the base clauses. This requires actually parsing them, because
3011 // otherwise we can't be sure where they end (a left brace may appear
3012 // within a template argument).
3013 if (Tok.is(tok::colon)) {
3014 // Enter the scope of the class so that we can correctly parse its bases.
3015 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
3016 ParsingClassDefinition ParsingDef(*this, TagDecl, /*NonNestedClass*/ true,
3017 TagType == DeclSpec::TST_interface);
Richard Smith0f192e82015-06-11 22:48:25 +00003018 auto OldContext =
3019 Actions.ActOnTagStartSkippedDefinition(getCurScope(), TagDecl);
Richard Smith65ebb4a2015-03-26 04:09:53 +00003020
3021 // Parse the bases but don't attach them to the class.
3022 ParseBaseClause(nullptr);
3023
Richard Smith0f192e82015-06-11 22:48:25 +00003024 Actions.ActOnTagFinishSkippedDefinition(OldContext);
Richard Smith65ebb4a2015-03-26 04:09:53 +00003025
3026 if (!Tok.is(tok::l_brace)) {
3027 Diag(PP.getLocForEndOfToken(PrevTokLocation),
3028 diag::err_expected_lbrace_after_base_specifiers);
3029 return;
3030 }
3031 }
3032
3033 // Skip the body.
3034 assert(Tok.is(tok::l_brace));
3035 BalancedDelimiterTracker T(*this, tok::l_brace);
3036 T.consumeOpen();
3037 T.skipToEnd();
Richard Smith04c6c1f2015-07-01 18:56:50 +00003038
3039 // Parse and discard any trailing attributes.
3040 ParsedAttributes Attrs(AttrFactory);
3041 if (Tok.is(tok::kw___attribute))
3042 MaybeParseGNUAttributes(Attrs);
Richard Smith65ebb4a2015-03-26 04:09:53 +00003043}
3044
Alexey Bataev05c25d62015-07-31 08:42:25 +00003045Parser::DeclGroupPtrTy Parser::ParseCXXClassMemberDeclarationWithPragmas(
3046 AccessSpecifier &AS, ParsedAttributesWithRange &AccessAttrs,
3047 DeclSpec::TST TagType, Decl *TagDecl) {
Richard Smithbf5bcf22018-06-26 23:20:26 +00003048 ParenBraceBracketBalancer BalancerRAIIObj(*this);
3049
Richard Smithb55f7582017-01-28 01:12:10 +00003050 switch (Tok.getKind()) {
3051 case tok::kw___if_exists:
3052 case tok::kw___if_not_exists:
Erich Keanec480f302018-07-12 21:09:05 +00003053 ParseMicrosoftIfExistsClassDeclaration(TagType, AccessAttrs, AS);
David Blaikie0403cb12016-01-15 23:43:25 +00003054 return nullptr;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003055
Richard Smithb55f7582017-01-28 01:12:10 +00003056 case tok::semi:
3057 // Check for extraneous top-level semicolon.
Alexey Bataev05c25d62015-07-31 08:42:25 +00003058 ConsumeExtraSemi(InsideStruct, TagType);
David Blaikie0403cb12016-01-15 23:43:25 +00003059 return nullptr;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003060
Richard Smithb55f7582017-01-28 01:12:10 +00003061 // Handle pragmas that can appear as member declarations.
3062 case tok::annot_pragma_vis:
Alexey Bataev05c25d62015-07-31 08:42:25 +00003063 HandlePragmaVisibility();
David Blaikie0403cb12016-01-15 23:43:25 +00003064 return nullptr;
Richard Smithb55f7582017-01-28 01:12:10 +00003065 case tok::annot_pragma_pack:
Alexey Bataev05c25d62015-07-31 08:42:25 +00003066 HandlePragmaPack();
David Blaikie0403cb12016-01-15 23:43:25 +00003067 return nullptr;
Richard Smithb55f7582017-01-28 01:12:10 +00003068 case tok::annot_pragma_align:
Alexey Bataev05c25d62015-07-31 08:42:25 +00003069 HandlePragmaAlign();
David Blaikie0403cb12016-01-15 23:43:25 +00003070 return nullptr;
Richard Smithb55f7582017-01-28 01:12:10 +00003071 case tok::annot_pragma_ms_pointers_to_members:
Alexey Bataev05c25d62015-07-31 08:42:25 +00003072 HandlePragmaMSPointersToMembers();
David Blaikie0403cb12016-01-15 23:43:25 +00003073 return nullptr;
Richard Smithb55f7582017-01-28 01:12:10 +00003074 case tok::annot_pragma_ms_pragma:
Alexey Bataev05c25d62015-07-31 08:42:25 +00003075 HandlePragmaMSPragma();
David Blaikie0403cb12016-01-15 23:43:25 +00003076 return nullptr;
Richard Smithb55f7582017-01-28 01:12:10 +00003077 case tok::annot_pragma_ms_vtordisp:
Alexey Bataev3d42f342015-11-20 07:02:57 +00003078 HandlePragmaMSVtorDisp();
David Blaikie0403cb12016-01-15 23:43:25 +00003079 return nullptr;
Richard Smithb256d302017-01-28 01:20:57 +00003080 case tok::annot_pragma_dump:
3081 HandlePragmaDump();
3082 return nullptr;
Alexey Bataev3d42f342015-11-20 07:02:57 +00003083
Richard Smithb55f7582017-01-28 01:12:10 +00003084 case tok::kw_namespace:
3085 // If we see a namespace here, a close brace was missing somewhere.
Alexey Bataev05c25d62015-07-31 08:42:25 +00003086 DiagnoseUnexpectedNamespace(cast<NamedDecl>(TagDecl));
David Blaikie0403cb12016-01-15 23:43:25 +00003087 return nullptr;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003088
Anastasia Stulova948e37c2019-03-25 11:54:02 +00003089 case tok::kw_private:
3090 // FIXME: We don't accept GNU attributes on access specifiers in OpenCL mode
3091 // yet.
3092 if (getLangOpts().OpenCL && !NextToken().is(tok::colon))
3093 return ParseCXXClassMemberDeclaration(AS, AccessAttrs);
3094 LLVM_FALLTHROUGH;
Richard Smithb55f7582017-01-28 01:12:10 +00003095 case tok::kw_public:
Anastasia Stulova948e37c2019-03-25 11:54:02 +00003096 case tok::kw_protected: {
Richard Smithb55f7582017-01-28 01:12:10 +00003097 AccessSpecifier NewAS = getAccessSpecifierIfPresent();
3098 assert(NewAS != AS_none);
Alexey Bataev05c25d62015-07-31 08:42:25 +00003099 // Current token is a C++ access specifier.
3100 AS = NewAS;
3101 SourceLocation ASLoc = Tok.getLocation();
3102 unsigned TokLength = Tok.getLength();
3103 ConsumeToken();
3104 AccessAttrs.clear();
3105 MaybeParseGNUAttributes(AccessAttrs);
3106
3107 SourceLocation EndLoc;
3108 if (TryConsumeToken(tok::colon, EndLoc)) {
3109 } else if (TryConsumeToken(tok::semi, EndLoc)) {
3110 Diag(EndLoc, diag::err_expected)
3111 << tok::colon << FixItHint::CreateReplacement(EndLoc, ":");
3112 } else {
3113 EndLoc = ASLoc.getLocWithOffset(TokLength);
3114 Diag(EndLoc, diag::err_expected)
3115 << tok::colon << FixItHint::CreateInsertion(EndLoc, ":");
3116 }
3117
3118 // The Microsoft extension __interface does not permit non-public
3119 // access specifiers.
3120 if (TagType == DeclSpec::TST_interface && AS != AS_public) {
3121 Diag(ASLoc, diag::err_access_specifier_interface) << (AS == AS_protected);
3122 }
3123
Erich Keanec480f302018-07-12 21:09:05 +00003124 if (Actions.ActOnAccessSpecifier(NewAS, ASLoc, EndLoc, AccessAttrs)) {
Alexey Bataev05c25d62015-07-31 08:42:25 +00003125 // found another attribute than only annotations
3126 AccessAttrs.clear();
3127 }
3128
David Blaikie0403cb12016-01-15 23:43:25 +00003129 return nullptr;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003130 }
3131
Richard Smithb55f7582017-01-28 01:12:10 +00003132 case tok::annot_pragma_openmp:
Alexey Bataev587e1de2016-03-30 10:43:55 +00003133 return ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, AccessAttrs, TagType,
3134 TagDecl);
Alexey Bataev05c25d62015-07-31 08:42:25 +00003135
Richard Smithb55f7582017-01-28 01:12:10 +00003136 default:
Erich Keanec480f302018-07-12 21:09:05 +00003137 return ParseCXXClassMemberDeclaration(AS, AccessAttrs);
Richard Smithb55f7582017-01-28 01:12:10 +00003138 }
Alexey Bataev05c25d62015-07-31 08:42:25 +00003139}
3140
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003141/// ParseCXXMemberSpecification - Parse the class definition.
3142///
3143/// member-specification:
3144/// member-declaration member-specification[opt]
3145/// access-specifier ':' member-specification[opt]
3146///
Joao Matose9a3ed42012-08-31 22:18:20 +00003147void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc,
Michael Han309af292013-01-07 16:57:11 +00003148 SourceLocation AttrFixitLoc,
Richard Smith4c96e992013-02-19 23:47:15 +00003149 ParsedAttributesWithRange &Attrs,
Faisal Vali090da2d2018-01-01 18:23:28 +00003150 unsigned TagType, Decl *TagDecl) {
Joao Matose9a3ed42012-08-31 22:18:20 +00003151 assert((TagType == DeclSpec::TST_struct ||
Faisal Vali090da2d2018-01-01 18:23:28 +00003152 TagType == DeclSpec::TST_interface ||
3153 TagType == DeclSpec::TST_union ||
3154 TagType == DeclSpec::TST_class) && "Invalid TagType!");
Joao Matose9a3ed42012-08-31 22:18:20 +00003155
Anton Afanasyevd880de22019-03-30 08:42:48 +00003156 llvm::TimeTraceScope TimeScope("ParseClass", [&]() {
3157 if (auto *TD = dyn_cast_or_null<NamedDecl>(TagDecl))
3158 return TD->getQualifiedNameAsString();
3159 return std::string("<anonymous>");
3160 });
3161
Jordan Rose1e879d82018-03-23 00:07:18 +00003162 PrettyDeclStackTraceEntry CrashInfo(Actions.Context, TagDecl, RecordLoc,
John McCallfaf5fb42010-08-26 23:41:50 +00003163 "parsing struct/union/class body");
Mike Stump11289f42009-09-09 15:08:12 +00003164
Douglas Gregoredf8f392010-01-16 20:52:59 +00003165 // Determine whether this is a non-nested class. Note that local
3166 // classes are *not* considered to be nested classes.
3167 bool NonNestedClass = true;
3168 if (!ClassStack.empty()) {
Douglas Gregor0be31a22010-07-02 17:43:08 +00003169 for (const Scope *S = getCurScope(); S; S = S->getParent()) {
Douglas Gregoredf8f392010-01-16 20:52:59 +00003170 if (S->isClassScope()) {
3171 // We're inside a class scope, so this is a nested class.
3172 NonNestedClass = false;
John McCalldb632ac2012-09-25 07:32:39 +00003173
3174 // The Microsoft extension __interface does not permit nested classes.
3175 if (getCurrentClass().IsInterface) {
3176 Diag(RecordLoc, diag::err_invalid_member_in_interface)
3177 << /*ErrorType=*/6
3178 << (isa<NamedDecl>(TagDecl)
3179 ? cast<NamedDecl>(TagDecl)->getQualifiedNameAsString()
David Blaikieabe1a392014-04-02 05:58:29 +00003180 : "(anonymous)");
John McCalldb632ac2012-09-25 07:32:39 +00003181 }
Douglas Gregoredf8f392010-01-16 20:52:59 +00003182 break;
3183 }
3184
Serge Pavlovd9c0bcf2015-07-14 10:02:10 +00003185 if ((S->getFlags() & Scope::FnScope))
3186 // If we're in a function or function template then this is a local
3187 // class rather than a nested class.
3188 break;
Douglas Gregoredf8f392010-01-16 20:52:59 +00003189 }
3190 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003191
3192 // Enter a scope for the class.
Douglas Gregor658b9552009-01-09 22:42:13 +00003193 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003194
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003195 // Note that we are parsing a new (potentially-nested) class definition.
John McCalldb632ac2012-09-25 07:32:39 +00003196 ParsingClassDefinition ParsingDef(*this, TagDecl, NonNestedClass,
3197 TagType == DeclSpec::TST_interface);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003198
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003199 if (TagDecl)
Douglas Gregor0be31a22010-07-02 17:43:08 +00003200 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
John McCall2d814c32009-12-19 21:48:58 +00003201
Anders Carlssonf9eb63b2011-03-25 14:46:08 +00003202 SourceLocation FinalLoc;
David Majnemera5433082013-10-18 00:33:31 +00003203 bool IsFinalSpelledSealed = false;
Anders Carlssonf9eb63b2011-03-25 14:46:08 +00003204
3205 // Parse the optional 'final' keyword.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003206 if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
David Majnemera5433082013-10-18 00:33:31 +00003207 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier(Tok);
3208 assert((Specifier == VirtSpecifiers::VS_Final ||
Fangrui Song6907ce22018-07-30 19:24:48 +00003209 Specifier == VirtSpecifiers::VS_GNU_Final ||
David Majnemera5433082013-10-18 00:33:31 +00003210 Specifier == VirtSpecifiers::VS_Sealed) &&
3211 "not a class definition");
Richard Smithda261112011-10-15 04:21:46 +00003212 FinalLoc = ConsumeToken();
David Majnemera5433082013-10-18 00:33:31 +00003213 IsFinalSpelledSealed = Specifier == VirtSpecifiers::VS_Sealed;
Anders Carlssonf9eb63b2011-03-25 14:46:08 +00003214
David Majnemera5433082013-10-18 00:33:31 +00003215 if (TagType == DeclSpec::TST_interface)
John McCalldb632ac2012-09-25 07:32:39 +00003216 Diag(FinalLoc, diag::err_override_control_interface)
David Majnemera5433082013-10-18 00:33:31 +00003217 << VirtSpecifiers::getSpecifierName(Specifier);
3218 else if (Specifier == VirtSpecifiers::VS_Final)
3219 Diag(FinalLoc, getLangOpts().CPlusPlus11
3220 ? diag::warn_cxx98_compat_override_control_keyword
3221 : diag::ext_override_control_keyword)
3222 << VirtSpecifiers::getSpecifierName(Specifier);
3223 else if (Specifier == VirtSpecifiers::VS_Sealed)
3224 Diag(FinalLoc, diag::ext_ms_sealed_keyword);
Andrey Bokhanko276055b2016-07-29 10:42:48 +00003225 else if (Specifier == VirtSpecifiers::VS_GNU_Final)
3226 Diag(FinalLoc, diag::ext_warn_gnu_final);
Michael Han9407e502012-11-26 22:54:45 +00003227
Michael Han309af292013-01-07 16:57:11 +00003228 // Parse any C++11 attributes after 'final' keyword.
3229 // These attributes are not allowed to appear here,
3230 // and the only possible place for them to appertain
3231 // to the class would be between class-key and class-name.
Richard Smith4c96e992013-02-19 23:47:15 +00003232 CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
Nico Weber4b4be842014-12-29 06:56:50 +00003233
3234 // ParseClassSpecifier() does only a superficial check for attributes before
3235 // deciding to call this method. For example, for
3236 // `class C final alignas ([l) {` it will decide that this looks like a
3237 // misplaced attribute since it sees `alignas '(' ')'`. But the actual
3238 // attribute parsing code will try to parse the '[' as a constexpr lambda
3239 // and consume enough tokens that the alignas parsing code will eat the
3240 // opening '{'. So bail out if the next token isn't one we expect.
Nico Weber36de3a22014-12-29 21:56:22 +00003241 if (!Tok.is(tok::colon) && !Tok.is(tok::l_brace)) {
3242 if (TagDecl)
3243 Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
Nico Weber4b4be842014-12-29 06:56:50 +00003244 return;
Nico Weber36de3a22014-12-29 21:56:22 +00003245 }
Anders Carlssonf9eb63b2011-03-25 14:46:08 +00003246 }
Anders Carlsson4b63d0e2011-01-22 16:56:46 +00003247
John McCall2d814c32009-12-19 21:48:58 +00003248 if (Tok.is(tok::colon)) {
Erik Verbruggen6524c052017-10-24 13:46:58 +00003249 ParseScope InheritanceScope(this, getCurScope()->getFlags() |
3250 Scope::ClassInheritanceScope);
3251
John McCall2d814c32009-12-19 21:48:58 +00003252 ParseBaseClause(TagDecl);
John McCall2d814c32009-12-19 21:48:58 +00003253 if (!Tok.is(tok::l_brace)) {
Ismail Pazarbasi129c44c2014-09-25 21:13:02 +00003254 bool SuggestFixIt = false;
3255 SourceLocation BraceLoc = PP.getLocForEndOfToken(PrevTokLocation);
3256 if (Tok.isAtStartOfLine()) {
3257 switch (Tok.getKind()) {
3258 case tok::kw_private:
3259 case tok::kw_protected:
3260 case tok::kw_public:
3261 SuggestFixIt = NextToken().getKind() == tok::colon;
3262 break;
3263 case tok::kw_static_assert:
3264 case tok::r_brace:
3265 case tok::kw_using:
3266 // base-clause can have simple-template-id; 'template' can't be there
3267 case tok::kw_template:
3268 SuggestFixIt = true;
3269 break;
3270 case tok::identifier:
3271 SuggestFixIt = isConstructorDeclarator(true);
3272 break;
3273 default:
3274 SuggestFixIt = isCXXSimpleDeclaration(/*AllowForRangeDecl=*/false);
3275 break;
3276 }
3277 }
3278 DiagnosticBuilder LBraceDiag =
3279 Diag(BraceLoc, diag::err_expected_lbrace_after_base_specifiers);
3280 if (SuggestFixIt) {
3281 LBraceDiag << FixItHint::CreateInsertion(BraceLoc, " {");
3282 // Try recovering from missing { after base-clause.
3283 PP.EnterToken(Tok);
3284 Tok.setKind(tok::l_brace);
3285 } else {
3286 if (TagDecl)
3287 Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
3288 return;
3289 }
John McCall2d814c32009-12-19 21:48:58 +00003290 }
3291 }
3292
3293 assert(Tok.is(tok::l_brace));
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003294 BalancedDelimiterTracker T(*this, tok::l_brace);
3295 T.consumeOpen();
John McCall2d814c32009-12-19 21:48:58 +00003296
John McCall08bede42010-05-28 08:11:17 +00003297 if (TagDecl)
Anders Carlsson30f29442011-03-25 14:31:08 +00003298 Actions.ActOnStartCXXMemberDeclarations(getCurScope(), TagDecl, FinalLoc,
David Majnemera5433082013-10-18 00:33:31 +00003299 IsFinalSpelledSealed,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003300 T.getOpenLocation());
John McCall1c7e6ec2009-12-20 07:58:13 +00003301
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003302 // C++ 11p3: Members of a class defined with the keyword class are private
3303 // by default. Members of a class defined with the keywords struct or union
3304 // are public by default.
3305 AccessSpecifier CurAS;
3306 if (TagType == DeclSpec::TST_class)
3307 CurAS = AS_private;
3308 else
3309 CurAS = AS_public;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003310 ParsedAttributesWithRange AccessAttrs(AttrFactory);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003311
Douglas Gregor9377c822010-06-21 22:31:09 +00003312 if (TagDecl) {
3313 // While we still have something to read, read the member-declarations.
Richard Smith752ada82015-11-17 23:32:01 +00003314 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
3315 Tok.isNot(tok::eof)) {
Douglas Gregor9377c822010-06-21 22:31:09 +00003316 // Each iteration of this loop reads one member-declaration.
Alexey Bataev05c25d62015-07-31 08:42:25 +00003317 ParseCXXClassMemberDeclarationWithPragmas(
3318 CurAS, AccessAttrs, static_cast<DeclSpec::TST>(TagType), TagDecl);
Serge Pavlovc4e04a22015-09-19 05:32:57 +00003319 }
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003320 T.consumeClose();
Douglas Gregor9377c822010-06-21 22:31:09 +00003321 } else {
Alexey Bataevee6507d2013-11-18 08:17:37 +00003322 SkipUntil(tok::r_brace);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003323 }
Mike Stump11289f42009-09-09 15:08:12 +00003324
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003325 // If attributes exist after class contents, parse them.
John McCall084e83d2011-03-24 11:26:52 +00003326 ParsedAttributes attrs(AttrFactory);
John McCall53fa7142010-12-24 02:08:15 +00003327 MaybeParseGNUAttributes(attrs);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003328
John McCall08bede42010-05-28 08:11:17 +00003329 if (TagDecl)
Douglas Gregor0be31a22010-07-02 17:43:08 +00003330 Actions.ActOnFinishCXXMemberSpecification(getCurScope(), RecordLoc, TagDecl,
Erich Keanec480f302018-07-12 21:09:05 +00003331 T.getOpenLocation(),
3332 T.getCloseLocation(), attrs);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003333
Douglas Gregor433e0532012-04-16 18:27:27 +00003334 // C++11 [class.mem]p2:
3335 // Within the class member-specification, the class is regarded as complete
Richard Smith0b3a4622014-11-13 20:01:57 +00003336 // within function bodies, default arguments, exception-specifications, and
Douglas Gregor433e0532012-04-16 18:27:27 +00003337 // brace-or-equal-initializers for non-static data members (including such
3338 // things in nested classes).
Douglas Gregor9377c822010-06-21 22:31:09 +00003339 if (TagDecl && NonNestedClass) {
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003340 // We are not inside a nested class. This class and its nested classes
Douglas Gregor4d87df52008-12-16 21:30:33 +00003341 // are complete and we can parse the delayed portions of method
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00003342 // declarations and the lexed inline method definitions, along with any
3343 // delayed attributes.
Douglas Gregor428119e2010-06-16 23:45:56 +00003344 SourceLocation SavedPrevTokLocation = PrevTokLocation;
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00003345 ParseLexedAttributes(getCurrentClass());
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003346 ParseLexedMethodDeclarations(getCurrentClass());
Richard Smith84973e52012-04-21 18:42:51 +00003347
3348 // We've finished with all pending member declarations.
3349 Actions.ActOnFinishCXXMemberDecls();
3350
Richard Smith938f40b2011-06-11 17:19:42 +00003351 ParseLexedMemberInitializers(getCurrentClass());
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003352 ParseLexedMethodDefs(getCurrentClass());
Douglas Gregor428119e2010-06-16 23:45:56 +00003353 PrevTokLocation = SavedPrevTokLocation;
Reid Klecknerbba3cb92015-03-17 19:00:50 +00003354
3355 // We've finished parsing everything, including default argument
3356 // initializers.
Hans Wennborg99000c22015-08-15 01:18:16 +00003357 Actions.ActOnFinishCXXNonNestedClass(TagDecl);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003358 }
3359
John McCall08bede42010-05-28 08:11:17 +00003360 if (TagDecl)
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00003361 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getRange());
John McCall2ff380a2010-03-17 00:38:33 +00003362
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003363 // Leave the class scope.
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003364 ParsingDef.Pop();
Douglas Gregor7307d6c2008-12-10 06:34:36 +00003365 ClassScope.Exit();
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003366}
Douglas Gregore8381c02008-11-05 04:29:56 +00003367
Richard Smith2ac43ad2013-11-15 23:00:02 +00003368void Parser::DiagnoseUnexpectedNamespace(NamedDecl *D) {
Richard Smithda35e962013-11-09 04:52:51 +00003369 assert(Tok.is(tok::kw_namespace));
3370
3371 // FIXME: Suggest where the close brace should have gone by looking
3372 // at indentation changes within the definition body.
Richard Smith2ac43ad2013-11-15 23:00:02 +00003373 Diag(D->getLocation(),
3374 diag::err_missing_end_of_definition) << D;
Richard Smithda35e962013-11-09 04:52:51 +00003375 Diag(Tok.getLocation(),
Richard Smith2ac43ad2013-11-15 23:00:02 +00003376 diag::note_missing_end_of_definition_before) << D;
Richard Smithda35e962013-11-09 04:52:51 +00003377
3378 // Push '};' onto the token stream to recover.
3379 PP.EnterToken(Tok);
3380
3381 Tok.startToken();
3382 Tok.setLocation(PP.getLocForEndOfToken(PrevTokLocation));
3383 Tok.setKind(tok::semi);
3384 PP.EnterToken(Tok);
3385
3386 Tok.setKind(tok::r_brace);
3387}
3388
Douglas Gregore8381c02008-11-05 04:29:56 +00003389/// ParseConstructorInitializer - Parse a C++ constructor initializer,
3390/// which explicitly initializes the members or base classes of a
3391/// class (C++ [class.base.init]). For example, the three initializers
3392/// after the ':' in the Derived constructor below:
3393///
3394/// @code
3395/// class Base { };
3396/// class Derived : Base {
3397/// int x;
3398/// float f;
3399/// public:
3400/// Derived(float f) : Base(), x(17), f(f) { }
3401/// };
3402/// @endcode
3403///
Mike Stump11289f42009-09-09 15:08:12 +00003404/// [C++] ctor-initializer:
3405/// ':' mem-initializer-list
Douglas Gregore8381c02008-11-05 04:29:56 +00003406///
Mike Stump11289f42009-09-09 15:08:12 +00003407/// [C++] mem-initializer-list:
Douglas Gregor44e7df62011-01-04 00:32:56 +00003408/// mem-initializer ...[opt]
3409/// mem-initializer ...[opt] , mem-initializer-list
John McCall48871652010-08-21 09:40:31 +00003410void Parser::ParseConstructorInitializer(Decl *ConstructorDecl) {
Nico Weber3b00fdc2015-03-07 19:52:39 +00003411 assert(Tok.is(tok::colon) &&
3412 "Constructor initializer always starts with ':'");
Douglas Gregore8381c02008-11-05 04:29:56 +00003413
Nico Weber3b00fdc2015-03-07 19:52:39 +00003414 // Poison the SEH identifiers so they are flagged as illegal in constructor
3415 // initializers.
John Wiegley1c0675e2011-04-28 01:08:34 +00003416 PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
Douglas Gregore8381c02008-11-05 04:29:56 +00003417 SourceLocation ColonLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +00003418
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003419 SmallVector<CXXCtorInitializer*, 4> MemInitializers;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003420 bool AnyErrors = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003421
Douglas Gregore8381c02008-11-05 04:29:56 +00003422 do {
Douglas Gregoreaeeca92010-08-28 00:00:50 +00003423 if (Tok.is(tok::code_completion)) {
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00003424 Actions.CodeCompleteConstructorInitializer(ConstructorDecl,
3425 MemInitializers);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00003426 return cutOffParsing();
Douglas Gregoreaeeca92010-08-28 00:00:50 +00003427 }
Alexey Bataev79de17d2016-01-20 05:25:51 +00003428
3429 MemInitResult MemInit = ParseMemInitializer(ConstructorDecl);
3430 if (!MemInit.isInvalid())
3431 MemInitializers.push_back(MemInit.get());
3432 else
3433 AnyErrors = true;
3434
Douglas Gregore8381c02008-11-05 04:29:56 +00003435 if (Tok.is(tok::comma))
3436 ConsumeToken();
3437 else if (Tok.is(tok::l_brace))
3438 break;
Alexey Bataev79de17d2016-01-20 05:25:51 +00003439 // If the previous initializer was valid and the next token looks like a
3440 // base or member initializer, assume that we're just missing a comma.
3441 else if (!MemInit.isInvalid() &&
3442 Tok.isOneOf(tok::identifier, tok::coloncolon)) {
Douglas Gregorce66d022010-09-07 14:51:08 +00003443 SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation);
3444 Diag(Loc, diag::err_ctor_init_missing_comma)
3445 << FixItHint::CreateInsertion(Loc, ", ");
3446 } else {
Douglas Gregore8381c02008-11-05 04:29:56 +00003447 // Skip over garbage, until we get to '{'. Don't eat the '{'.
Alexey Bataev79de17d2016-01-20 05:25:51 +00003448 if (!MemInit.isInvalid())
3449 Diag(Tok.getLocation(), diag::err_expected_either) << tok::l_brace
3450 << tok::comma;
Alexey Bataevee6507d2013-11-18 08:17:37 +00003451 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
Douglas Gregore8381c02008-11-05 04:29:56 +00003452 break;
3453 }
3454 } while (true);
3455
David Blaikie3fc2f912013-01-17 05:26:25 +00003456 Actions.ActOnMemInitializers(ConstructorDecl, ColonLoc, MemInitializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003457 AnyErrors);
Douglas Gregore8381c02008-11-05 04:29:56 +00003458}
3459
3460/// ParseMemInitializer - Parse a C++ member initializer, which is
3461/// part of a constructor initializer that explicitly initializes one
3462/// member or base class (C++ [class.base.init]). See
3463/// ParseConstructorInitializer for an example.
3464///
3465/// [C++] mem-initializer:
3466/// mem-initializer-id '(' expression-list[opt] ')'
Sebastian Redl3da34892011-06-05 12:23:16 +00003467/// [C++0x] mem-initializer-id braced-init-list
Mike Stump11289f42009-09-09 15:08:12 +00003468///
Douglas Gregore8381c02008-11-05 04:29:56 +00003469/// [C++] mem-initializer-id:
3470/// '::'[opt] nested-name-specifier[opt] class-name
3471/// identifier
Craig Topper9ad7e262014-10-31 06:57:07 +00003472MemInitResult Parser::ParseMemInitializer(Decl *ConstructorDecl) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00003473 // parse '::'[opt] nested-name-specifier[opt]
3474 CXXScopeSpec SS;
Richard Smithb23c5e82019-05-09 03:31:27 +00003475 if (ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false))
3476 return true;
Richard Smithaf3b3252017-05-18 19:21:48 +00003477
3478 // : identifier
3479 IdentifierInfo *II = nullptr;
3480 SourceLocation IdLoc = Tok.getLocation();
3481 // : declype(...)
3482 DeclSpec DS(AttrFactory);
3483 // : template_name<...>
John McCallba7bf592010-08-24 05:47:05 +00003484 ParsedType TemplateTypeTy;
Richard Smithaf3b3252017-05-18 19:21:48 +00003485
3486 if (Tok.is(tok::identifier)) {
3487 // Get the identifier. This may be a member name or a class name,
3488 // but we'll let the semantic analysis determine which it is.
3489 II = Tok.getIdentifierInfo();
3490 ConsumeToken();
3491 } else if (Tok.is(tok::annot_decltype)) {
3492 // Get the decltype expression, if there is one.
3493 // Uses of decltype will already have been converted to annot_decltype by
3494 // ParseOptionalCXXScopeSpecifier at this point.
3495 // FIXME: Can we get here with a scope specifier?
3496 ParseDecltypeSpecifier(DS);
3497 } else {
3498 TemplateIdAnnotation *TemplateId = Tok.is(tok::annot_template_id)
3499 ? takeTemplateIdAnnotation(Tok)
3500 : nullptr;
3501 if (TemplateId && (TemplateId->Kind == TNK_Type_template ||
Richard Smithb23c5e82019-05-09 03:31:27 +00003502 TemplateId->Kind == TNK_Dependent_template_name ||
3503 TemplateId->Kind == TNK_Undeclared_template)) {
Richard Smith62559bd2017-02-01 21:36:38 +00003504 AnnotateTemplateIdTokenAsType(/*IsClassName*/true);
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00003505 assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
John McCallba7bf592010-08-24 05:47:05 +00003506 TemplateTypeTy = getTypeAnnotation(Tok);
Richard Smithaf3b3252017-05-18 19:21:48 +00003507 ConsumeAnnotationToken();
Richard Smithb23c5e82019-05-09 03:31:27 +00003508 if (!TemplateTypeTy)
3509 return true;
Richard Smithaf3b3252017-05-18 19:21:48 +00003510 } else {
3511 Diag(Tok, diag::err_expected_member_or_base_name);
3512 return true;
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00003513 }
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00003514 }
Douglas Gregore8381c02008-11-05 04:29:56 +00003515
3516 // Parse the '('.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003517 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
Richard Smith5d164bc2011-10-15 05:09:34 +00003518 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
3519
Kadir Cetinkaya84774c32018-09-11 15:02:18 +00003520 // FIXME: Add support for signature help inside initializer lists.
Sebastian Redla74948d2011-09-24 17:48:25 +00003521 ExprResult InitList = ParseBraceInitializer();
3522 if (InitList.isInvalid())
3523 return true;
3524
3525 SourceLocation EllipsisLoc;
Alp Toker094e5212014-01-05 03:27:11 +00003526 TryConsumeToken(tok::ellipsis, EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00003527
3528 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
Fangrui Song6907ce22018-07-30 19:24:48 +00003529 TemplateTypeTy, DS, IdLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003530 InitList.get(), EllipsisLoc);
Sebastian Redl3da34892011-06-05 12:23:16 +00003531 } else if(Tok.is(tok::l_paren)) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003532 BalancedDelimiterTracker T(*this, tok::l_paren);
3533 T.consumeOpen();
Douglas Gregore8381c02008-11-05 04:29:56 +00003534
Sebastian Redl3da34892011-06-05 12:23:16 +00003535 // Parse the optional expression-list.
Benjamin Kramerf0623432012-08-23 22:51:59 +00003536 ExprVector ArgExprs;
Sebastian Redl3da34892011-06-05 12:23:16 +00003537 CommaLocsTy CommaLocs;
Ilya Biryukovff2a9972019-02-26 11:01:50 +00003538 auto RunSignatureHelp = [&] {
3539 QualType PreferredType = Actions.ProduceCtorInitMemberSignatureHelp(
3540 getCurScope(), ConstructorDecl, SS, TemplateTypeTy, ArgExprs, II,
3541 T.getOpenLocation());
3542 CalledSignatureHelp = true;
3543 return PreferredType;
3544 };
Kadir Cetinkaya84774c32018-09-11 15:02:18 +00003545 if (Tok.isNot(tok::r_paren) &&
3546 ParseExpressionList(ArgExprs, CommaLocs, [&] {
Ilya Biryukovff2a9972019-02-26 11:01:50 +00003547 PreferredType.enterFunctionArgument(Tok.getLocation(),
3548 RunSignatureHelp);
Kadir Cetinkaya84774c32018-09-11 15:02:18 +00003549 })) {
Ilya Biryukovff2a9972019-02-26 11:01:50 +00003550 if (PP.isCodeCompletionReached() && !CalledSignatureHelp)
3551 RunSignatureHelp();
Alexey Bataevee6507d2013-11-18 08:17:37 +00003552 SkipUntil(tok::r_paren, StopAtSemi);
Sebastian Redl3da34892011-06-05 12:23:16 +00003553 return true;
3554 }
3555
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003556 T.consumeClose();
Sebastian Redl3da34892011-06-05 12:23:16 +00003557
3558 SourceLocation EllipsisLoc;
Alp Toker97650562014-01-10 11:19:30 +00003559 TryConsumeToken(tok::ellipsis, EllipsisLoc);
Sebastian Redl3da34892011-06-05 12:23:16 +00003560
3561 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
David Blaikie186a8892012-01-24 06:03:59 +00003562 TemplateTypeTy, DS, IdLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00003563 T.getOpenLocation(), ArgExprs,
3564 T.getCloseLocation(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00003565 }
3566
Alp Tokerec543272013-12-24 09:48:30 +00003567 if (getLangOpts().CPlusPlus11)
3568 return Diag(Tok, diag::err_expected_either) << tok::l_paren << tok::l_brace;
3569 else
3570 return Diag(Tok, diag::err_expected) << tok::l_paren;
Douglas Gregore8381c02008-11-05 04:29:56 +00003571}
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003572
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003573/// Parse a C++ exception-specification if present (C++0x [except.spec]).
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003574///
Douglas Gregor356513d2008-12-01 18:00:20 +00003575/// exception-specification:
Sebastian Redl965b0e32011-03-05 14:45:16 +00003576/// dynamic-exception-specification
3577/// noexcept-specification
3578///
3579/// noexcept-specification:
3580/// 'noexcept'
3581/// 'noexcept' '(' constant-expression ')'
3582ExceptionSpecificationType
Richard Smith0b3a4622014-11-13 20:01:57 +00003583Parser::tryParseExceptionSpecification(bool Delayed,
Douglas Gregor433e0532012-04-16 18:27:27 +00003584 SourceRange &SpecificationRange,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003585 SmallVectorImpl<ParsedType> &DynamicExceptions,
3586 SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
Richard Smith0b3a4622014-11-13 20:01:57 +00003587 ExprResult &NoexceptExpr,
3588 CachedTokens *&ExceptionSpecTokens) {
Sebastian Redl965b0e32011-03-05 14:45:16 +00003589 ExceptionSpecificationType Result = EST_None;
Hans Wennborgdcfba332015-10-06 23:40:43 +00003590 ExceptionSpecTokens = nullptr;
Fangrui Song6907ce22018-07-30 19:24:48 +00003591
Richard Smith0b3a4622014-11-13 20:01:57 +00003592 // Handle delayed parsing of exception-specifications.
3593 if (Delayed) {
3594 if (Tok.isNot(tok::kw_throw) && Tok.isNot(tok::kw_noexcept))
3595 return EST_None;
Sebastian Redl965b0e32011-03-05 14:45:16 +00003596
Richard Smith0b3a4622014-11-13 20:01:57 +00003597 // Consume and cache the starting token.
3598 bool IsNoexcept = Tok.is(tok::kw_noexcept);
3599 Token StartTok = Tok;
3600 SpecificationRange = SourceRange(ConsumeToken());
3601
3602 // Check for a '('.
3603 if (!Tok.is(tok::l_paren)) {
3604 // If this is a bare 'noexcept', we're done.
3605 if (IsNoexcept) {
3606 Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
Hans Wennborgdcfba332015-10-06 23:40:43 +00003607 NoexceptExpr = nullptr;
Richard Smith0b3a4622014-11-13 20:01:57 +00003608 return EST_BasicNoexcept;
3609 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003610
Richard Smith0b3a4622014-11-13 20:01:57 +00003611 Diag(Tok, diag::err_expected_lparen_after) << "throw";
3612 return EST_DynamicNone;
3613 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003614
Richard Smith0b3a4622014-11-13 20:01:57 +00003615 // Cache the tokens for the exception-specification.
3616 ExceptionSpecTokens = new CachedTokens;
3617 ExceptionSpecTokens->push_back(StartTok); // 'throw' or 'noexcept'
3618 ExceptionSpecTokens->push_back(Tok); // '('
3619 SpecificationRange.setEnd(ConsumeParen()); // '('
Richard Smithb1c217e2015-01-13 02:24:58 +00003620
3621 ConsumeAndStoreUntil(tok::r_paren, *ExceptionSpecTokens,
3622 /*StopAtSemi=*/true,
3623 /*ConsumeFinalToken=*/true);
Aaron Ballman580ccaf2016-01-12 21:04:22 +00003624 SpecificationRange.setEnd(ExceptionSpecTokens->back().getLocation());
3625
Richard Smith0b3a4622014-11-13 20:01:57 +00003626 return EST_Unparsed;
3627 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003628
Sebastian Redl965b0e32011-03-05 14:45:16 +00003629 // See if there's a dynamic specification.
3630 if (Tok.is(tok::kw_throw)) {
3631 Result = ParseDynamicExceptionSpecification(SpecificationRange,
3632 DynamicExceptions,
3633 DynamicExceptionRanges);
3634 assert(DynamicExceptions.size() == DynamicExceptionRanges.size() &&
3635 "Produced different number of exception types and ranges.");
3636 }
3637
3638 // If there's no noexcept specification, we're done.
3639 if (Tok.isNot(tok::kw_noexcept))
3640 return Result;
3641
Richard Smithb15c11c2011-10-17 23:06:20 +00003642 Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
3643
Sebastian Redl965b0e32011-03-05 14:45:16 +00003644 // If we already had a dynamic specification, parse the noexcept for,
3645 // recovery, but emit a diagnostic and don't store the results.
3646 SourceRange NoexceptRange;
3647 ExceptionSpecificationType NoexceptType = EST_None;
3648
3649 SourceLocation KeywordLoc = ConsumeToken();
3650 if (Tok.is(tok::l_paren)) {
3651 // There is an argument.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003652 BalancedDelimiterTracker T(*this, tok::l_paren);
3653 T.consumeOpen();
Sebastian Redl965b0e32011-03-05 14:45:16 +00003654 NoexceptExpr = ParseConstantExpression();
Serge Pavlov3739f5e72015-06-29 17:50:19 +00003655 T.consumeClose();
Serge Pavlov3739f5e72015-06-29 17:50:19 +00003656 if (!NoexceptExpr.isInvalid()) {
Richard Smitheaf11ad2018-05-03 03:58:32 +00003657 NoexceptExpr = Actions.ActOnNoexceptSpec(KeywordLoc, NoexceptExpr.get(),
3658 NoexceptType);
Serge Pavlov3739f5e72015-06-29 17:50:19 +00003659 NoexceptRange = SourceRange(KeywordLoc, T.getCloseLocation());
3660 } else {
Malcolm Parsonsa3220ce2017-01-12 16:11:28 +00003661 NoexceptType = EST_BasicNoexcept;
Serge Pavlov3739f5e72015-06-29 17:50:19 +00003662 }
Sebastian Redl965b0e32011-03-05 14:45:16 +00003663 } else {
3664 // There is no argument.
3665 NoexceptType = EST_BasicNoexcept;
3666 NoexceptRange = SourceRange(KeywordLoc, KeywordLoc);
3667 }
3668
3669 if (Result == EST_None) {
3670 SpecificationRange = NoexceptRange;
3671 Result = NoexceptType;
3672
3673 // If there's a dynamic specification after a noexcept specification,
3674 // parse that and ignore the results.
3675 if (Tok.is(tok::kw_throw)) {
3676 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
3677 ParseDynamicExceptionSpecification(NoexceptRange, DynamicExceptions,
3678 DynamicExceptionRanges);
3679 }
3680 } else {
3681 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
3682 }
3683
3684 return Result;
3685}
3686
Richard Smith8ca78a12013-06-13 02:02:51 +00003687static void diagnoseDynamicExceptionSpecification(
Craig Toppere335f252015-10-04 04:53:55 +00003688 Parser &P, SourceRange Range, bool IsNoexcept) {
Richard Smith8ca78a12013-06-13 02:02:51 +00003689 if (P.getLangOpts().CPlusPlus11) {
3690 const char *Replacement = IsNoexcept ? "noexcept" : "noexcept(false)";
Richard Smith82da19d2016-12-08 02:49:07 +00003691 P.Diag(Range.getBegin(),
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003692 P.getLangOpts().CPlusPlus17 && !IsNoexcept
Richard Smith82da19d2016-12-08 02:49:07 +00003693 ? diag::ext_dynamic_exception_spec
3694 : diag::warn_exception_spec_deprecated)
3695 << Range;
Richard Smith8ca78a12013-06-13 02:02:51 +00003696 P.Diag(Range.getBegin(), diag::note_exception_spec_deprecated)
3697 << Replacement << FixItHint::CreateReplacement(Range, Replacement);
3698 }
3699}
3700
Sebastian Redl965b0e32011-03-05 14:45:16 +00003701/// ParseDynamicExceptionSpecification - Parse a C++
3702/// dynamic-exception-specification (C++ [except.spec]).
3703///
3704/// dynamic-exception-specification:
Douglas Gregor356513d2008-12-01 18:00:20 +00003705/// 'throw' '(' type-id-list [opt] ')'
3706/// [MS] 'throw' '(' '...' ')'
Mike Stump11289f42009-09-09 15:08:12 +00003707///
Douglas Gregor356513d2008-12-01 18:00:20 +00003708/// type-id-list:
Douglas Gregor830837d2010-12-20 23:57:46 +00003709/// type-id ... [opt]
3710/// type-id-list ',' type-id ... [opt]
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003711///
Sebastian Redl965b0e32011-03-05 14:45:16 +00003712ExceptionSpecificationType Parser::ParseDynamicExceptionSpecification(
3713 SourceRange &SpecificationRange,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003714 SmallVectorImpl<ParsedType> &Exceptions,
3715 SmallVectorImpl<SourceRange> &Ranges) {
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003716 assert(Tok.is(tok::kw_throw) && "expected throw");
Mike Stump11289f42009-09-09 15:08:12 +00003717
Sebastian Redl965b0e32011-03-05 14:45:16 +00003718 SpecificationRange.setBegin(ConsumeToken());
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003719 BalancedDelimiterTracker T(*this, tok::l_paren);
3720 if (T.consumeOpen()) {
Sebastian Redl965b0e32011-03-05 14:45:16 +00003721 Diag(Tok, diag::err_expected_lparen_after) << "throw";
3722 SpecificationRange.setEnd(SpecificationRange.getBegin());
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003723 return EST_DynamicNone;
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003724 }
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003725
Douglas Gregor356513d2008-12-01 18:00:20 +00003726 // Parse throw(...), a Microsoft extension that means "this function
3727 // can throw anything".
3728 if (Tok.is(tok::ellipsis)) {
3729 SourceLocation EllipsisLoc = ConsumeToken();
David Blaikiebbafb8a2012-03-11 07:00:24 +00003730 if (!getLangOpts().MicrosoftExt)
Douglas Gregor356513d2008-12-01 18:00:20 +00003731 Diag(EllipsisLoc, diag::ext_ellipsis_exception_spec);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003732 T.consumeClose();
3733 SpecificationRange.setEnd(T.getCloseLocation());
Richard Smith8ca78a12013-06-13 02:02:51 +00003734 diagnoseDynamicExceptionSpecification(*this, SpecificationRange, false);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003735 return EST_MSAny;
Douglas Gregor356513d2008-12-01 18:00:20 +00003736 }
3737
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003738 // Parse the sequence of type-ids.
Sebastian Redld6434562009-05-29 18:02:33 +00003739 SourceRange Range;
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003740 while (Tok.isNot(tok::r_paren)) {
Sebastian Redld6434562009-05-29 18:02:33 +00003741 TypeResult Res(ParseTypeName(&Range));
Sebastian Redl965b0e32011-03-05 14:45:16 +00003742
Douglas Gregor830837d2010-12-20 23:57:46 +00003743 if (Tok.is(tok::ellipsis)) {
3744 // C++0x [temp.variadic]p5:
Fangrui Song6907ce22018-07-30 19:24:48 +00003745 // - In a dynamic-exception-specification (15.4); the pattern is a
Douglas Gregor830837d2010-12-20 23:57:46 +00003746 // type-id.
3747 SourceLocation Ellipsis = ConsumeToken();
Sebastian Redl965b0e32011-03-05 14:45:16 +00003748 Range.setEnd(Ellipsis);
Douglas Gregor830837d2010-12-20 23:57:46 +00003749 if (!Res.isInvalid())
3750 Res = Actions.ActOnPackExpansion(Res.get(), Ellipsis);
3751 }
Sebastian Redl965b0e32011-03-05 14:45:16 +00003752
Sebastian Redld6434562009-05-29 18:02:33 +00003753 if (!Res.isInvalid()) {
Sebastian Redl2b9cacb2009-04-29 17:30:04 +00003754 Exceptions.push_back(Res.get());
Sebastian Redld6434562009-05-29 18:02:33 +00003755 Ranges.push_back(Range);
3756 }
Alp Toker97650562014-01-10 11:19:30 +00003757
3758 if (!TryConsumeToken(tok::comma))
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003759 break;
3760 }
3761
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003762 T.consumeClose();
3763 SpecificationRange.setEnd(T.getCloseLocation());
Richard Smith8ca78a12013-06-13 02:02:51 +00003764 diagnoseDynamicExceptionSpecification(*this, SpecificationRange,
3765 Exceptions.empty());
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003766 return Exceptions.empty() ? EST_DynamicNone : EST_Dynamic;
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003767}
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003768
Douglas Gregor7fb25412010-10-01 18:44:50 +00003769/// ParseTrailingReturnType - Parse a trailing return type on a new-style
3770/// function declaration.
Richard Smithe303e352018-02-02 22:24:54 +00003771TypeResult Parser::ParseTrailingReturnType(SourceRange &Range,
3772 bool MayBeFollowedByDirectInit) {
Douglas Gregor7fb25412010-10-01 18:44:50 +00003773 assert(Tok.is(tok::arrow) && "expected arrow");
3774
3775 ConsumeToken();
3776
Richard Smithe303e352018-02-02 22:24:54 +00003777 return ParseTypeName(&Range, MayBeFollowedByDirectInit
3778 ? DeclaratorContext::TrailingReturnVarContext
3779 : DeclaratorContext::TrailingReturnContext);
Douglas Gregor7fb25412010-10-01 18:44:50 +00003780}
3781
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003782/// We have just started parsing the definition of a new class,
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003783/// so push that class onto our stack of classes that is currently
3784/// being parsed.
John McCallc1465822011-02-14 07:13:47 +00003785Sema::ParsingClassState
John McCalldb632ac2012-09-25 07:32:39 +00003786Parser::PushParsingClass(Decl *ClassDecl, bool NonNestedClass,
3787 bool IsInterface) {
Douglas Gregoredf8f392010-01-16 20:52:59 +00003788 assert((NonNestedClass || !ClassStack.empty()) &&
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003789 "Nested class without outer class");
John McCalldb632ac2012-09-25 07:32:39 +00003790 ClassStack.push(new ParsingClass(ClassDecl, NonNestedClass, IsInterface));
John McCallc1465822011-02-14 07:13:47 +00003791 return Actions.PushParsingClass();
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003792}
3793
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003794/// Deallocate the given parsed class and all of its nested
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003795/// classes.
3796void Parser::DeallocateParsedClasses(Parser::ParsingClass *Class) {
Douglas Gregorefc46952010-10-12 16:25:54 +00003797 for (unsigned I = 0, N = Class->LateParsedDeclarations.size(); I != N; ++I)
3798 delete Class->LateParsedDeclarations[I];
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003799 delete Class;
3800}
3801
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003802/// Pop the top class of the stack of classes that are
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003803/// currently being parsed.
3804///
3805/// This routine should be called when we have finished parsing the
3806/// definition of a class, but have not yet popped the Scope
3807/// associated with the class's definition.
John McCallc1465822011-02-14 07:13:47 +00003808void Parser::PopParsingClass(Sema::ParsingClassState state) {
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003809 assert(!ClassStack.empty() && "Mismatched push/pop for class parsing");
Mike Stump11289f42009-09-09 15:08:12 +00003810
John McCallc1465822011-02-14 07:13:47 +00003811 Actions.PopParsingClass(state);
3812
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003813 ParsingClass *Victim = ClassStack.top();
3814 ClassStack.pop();
3815 if (Victim->TopLevelClass) {
3816 // Deallocate all of the nested classes of this class,
3817 // recursively: we don't need to keep any of this information.
3818 DeallocateParsedClasses(Victim);
3819 return;
Mike Stump11289f42009-09-09 15:08:12 +00003820 }
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003821 assert(!ClassStack.empty() && "Missing top-level class?");
3822
Douglas Gregorefc46952010-10-12 16:25:54 +00003823 if (Victim->LateParsedDeclarations.empty()) {
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003824 // The victim is a nested class, but we will not need to perform
3825 // any processing after the definition of this class since it has
3826 // no members whose handling was delayed. Therefore, we can just
3827 // remove this nested class.
Douglas Gregorefc46952010-10-12 16:25:54 +00003828 DeallocateParsedClasses(Victim);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003829 return;
3830 }
3831
3832 // This nested class has some members that will need to be processed
3833 // after the top-level class is completely defined. Therefore, add
3834 // it to the list of nested classes within its parent.
Douglas Gregor0be31a22010-07-02 17:43:08 +00003835 assert(getCurScope()->isClassScope() && "Nested class outside of class scope?");
Douglas Gregorefc46952010-10-12 16:25:54 +00003836 ClassStack.top()->LateParsedDeclarations.push_back(new LateParsedClass(this, Victim));
Douglas Gregor0be31a22010-07-02 17:43:08 +00003837 Victim->TemplateScope = getCurScope()->getParent()->isTemplateParamScope();
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003838}
Alexis Hunt96d5c762009-11-21 08:43:09 +00003839
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003840/// Try to parse an 'identifier' which appears within an attribute-token.
Richard Smith3dff2512012-04-10 03:25:07 +00003841///
3842/// \return the parsed identifier on success, and 0 if the next token is not an
3843/// attribute-token.
3844///
3845/// C++11 [dcl.attr.grammar]p3:
3846/// If a keyword or an alternative token that satisfies the syntactic
3847/// requirements of an identifier is contained in an attribute-token,
3848/// it is considered an identifier.
3849IdentifierInfo *Parser::TryParseCXX11AttributeIdentifier(SourceLocation &Loc) {
3850 switch (Tok.getKind()) {
3851 default:
3852 // Identifiers and keywords have identifier info attached.
David Majnemerd5271992015-01-09 18:09:39 +00003853 if (!Tok.isAnnotation()) {
3854 if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
3855 Loc = ConsumeToken();
3856 return II;
3857 }
Richard Smith3dff2512012-04-10 03:25:07 +00003858 }
Craig Topper161e4db2014-05-21 06:02:52 +00003859 return nullptr;
Richard Smith3dff2512012-04-10 03:25:07 +00003860
Aaron Ballmanc44c17422018-11-09 17:19:45 +00003861 case tok::numeric_constant: {
3862 // If we got a numeric constant, check to see if it comes from a macro that
3863 // corresponds to the predefined __clang__ macro. If it does, warn the user
3864 // and recover by pretending they said _Clang instead.
3865 if (Tok.getLocation().isMacroID()) {
3866 SmallString<8> ExpansionBuf;
3867 SourceLocation ExpansionLoc =
3868 PP.getSourceManager().getExpansionLoc(Tok.getLocation());
3869 StringRef Spelling = PP.getSpelling(ExpansionLoc, ExpansionBuf);
3870 if (Spelling == "__clang__") {
3871 SourceRange TokRange(
3872 ExpansionLoc,
3873 PP.getSourceManager().getExpansionLoc(Tok.getEndLoc()));
3874 Diag(Tok, diag::warn_wrong_clang_attr_namespace)
3875 << FixItHint::CreateReplacement(TokRange, "_Clang");
3876 Loc = ConsumeToken();
3877 return &PP.getIdentifierTable().get("_Clang");
3878 }
3879 }
3880 return nullptr;
3881 }
3882
Richard Smith3dff2512012-04-10 03:25:07 +00003883 case tok::ampamp: // 'and'
3884 case tok::pipe: // 'bitor'
3885 case tok::pipepipe: // 'or'
3886 case tok::caret: // 'xor'
3887 case tok::tilde: // 'compl'
3888 case tok::amp: // 'bitand'
3889 case tok::ampequal: // 'and_eq'
3890 case tok::pipeequal: // 'or_eq'
3891 case tok::caretequal: // 'xor_eq'
3892 case tok::exclaim: // 'not'
3893 case tok::exclaimequal: // 'not_eq'
3894 // Alternative tokens do not have identifier info, but their spelling
3895 // starts with an alphabetical character.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003896 SmallString<8> SpellingBuf;
Benjamin Kramer60be5632015-03-29 19:25:07 +00003897 SourceLocation SpellingLoc =
3898 PP.getSourceManager().getSpellingLoc(Tok.getLocation());
3899 StringRef Spelling = PP.getSpelling(SpellingLoc, SpellingBuf);
Jordan Rosea7d03842013-02-08 22:30:41 +00003900 if (isLetter(Spelling[0])) {
Richard Smith3dff2512012-04-10 03:25:07 +00003901 Loc = ConsumeToken();
Benjamin Kramer5c17f9c2012-04-22 20:43:30 +00003902 return &PP.getIdentifierTable().get(Spelling);
Richard Smith3dff2512012-04-10 03:25:07 +00003903 }
Craig Topper161e4db2014-05-21 06:02:52 +00003904 return nullptr;
Richard Smith3dff2512012-04-10 03:25:07 +00003905 }
3906}
3907
Michael Han23214e52012-10-03 01:56:22 +00003908static bool IsBuiltInOrStandardCXX11Attribute(IdentifierInfo *AttrName,
Aaron Ballman606093a2017-10-15 15:01:42 +00003909 IdentifierInfo *ScopeName) {
Erich Keanee891aa92018-07-13 15:07:47 +00003910 switch (ParsedAttr::getKind(AttrName, ScopeName, ParsedAttr::AS_CXX11)) {
3911 case ParsedAttr::AT_CarriesDependency:
3912 case ParsedAttr::AT_Deprecated:
3913 case ParsedAttr::AT_FallThrough:
3914 case ParsedAttr::AT_CXX11NoReturn:
Michael Han23214e52012-10-03 01:56:22 +00003915 return true;
Erich Keanee891aa92018-07-13 15:07:47 +00003916 case ParsedAttr::AT_WarnUnusedResult:
Aaron Ballmane7964782016-03-07 22:44:55 +00003917 return !ScopeName && AttrName->getName().equals("nodiscard");
Erich Keanee891aa92018-07-13 15:07:47 +00003918 case ParsedAttr::AT_Unused:
Nico Weberac03bce2016-08-23 19:59:55 +00003919 return !ScopeName && AttrName->getName().equals("maybe_unused");
Michael Han23214e52012-10-03 01:56:22 +00003920 default:
3921 return false;
3922 }
3923}
3924
Aaron Ballmanb8e20392014-03-31 17:32:39 +00003925/// ParseCXX11AttributeArgs -- Parse a C++11 attribute-argument-clause.
3926///
3927/// [C++11] attribute-argument-clause:
3928/// '(' balanced-token-seq ')'
3929///
3930/// [C++11] balanced-token-seq:
3931/// balanced-token
3932/// balanced-token-seq balanced-token
3933///
3934/// [C++11] balanced-token:
3935/// '(' balanced-token-seq ')'
3936/// '[' balanced-token-seq ']'
3937/// '{' balanced-token-seq '}'
3938/// any token but '(', ')', '[', ']', '{', or '}'
3939bool Parser::ParseCXX11AttributeArgs(IdentifierInfo *AttrName,
3940 SourceLocation AttrNameLoc,
3941 ParsedAttributes &Attrs,
3942 SourceLocation *EndLoc,
3943 IdentifierInfo *ScopeName,
3944 SourceLocation ScopeLoc) {
3945 assert(Tok.is(tok::l_paren) && "Not a C++11 attribute argument list");
Aaron Ballman35f94212014-04-14 16:03:22 +00003946 SourceLocation LParenLoc = Tok.getLocation();
Aaron Ballman606093a2017-10-15 15:01:42 +00003947 const LangOptions &LO = getLangOpts();
Erich Keanee891aa92018-07-13 15:07:47 +00003948 ParsedAttr::Syntax Syntax =
3949 LO.CPlusPlus ? ParsedAttr::AS_CXX11 : ParsedAttr::AS_C2x;
Aaron Ballmanb8e20392014-03-31 17:32:39 +00003950
3951 // If the attribute isn't known, we will not attempt to parse any
3952 // arguments.
Aaron Ballman606093a2017-10-15 15:01:42 +00003953 if (!hasAttribute(LO.CPlusPlus ? AttrSyntax::CXX : AttrSyntax::C, ScopeName,
3954 AttrName, getTargetInfo(), getLangOpts())) {
Aaron Ballmanb8e20392014-03-31 17:32:39 +00003955 // Eat the left paren, then skip to the ending right paren.
3956 ConsumeParen();
3957 SkipUntil(tok::r_paren);
Aaron Ballmanc44c17422018-11-09 17:19:45 +00003958 return false;
3959 }
3960
3961 if (ScopeName && (ScopeName->isStr("gnu") || ScopeName->isStr("__gnu__"))) {
3962 // GNU-scoped attributes have some special cases to handle GNU-specific
3963 // behaviors.
3964 ParseGNUAttributeArgs(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
Aaron Ballman606093a2017-10-15 15:01:42 +00003965 ScopeLoc, Syntax, nullptr);
Alex Lorenzd5d27e12017-03-01 18:06:25 +00003966 return true;
3967 }
3968
3969 unsigned NumArgs;
3970 // Some Clang-scoped attributes have some special parsing behavior.
Aaron Ballmanc44c17422018-11-09 17:19:45 +00003971 if (ScopeName && (ScopeName->isStr("clang") || ScopeName->isStr("_Clang")))
3972 NumArgs = ParseClangAttributeArgs(AttrName, AttrNameLoc, Attrs, EndLoc,
3973 ScopeName, ScopeLoc, Syntax);
Alex Lorenzd5d27e12017-03-01 18:06:25 +00003974 else
3975 NumArgs =
Aaron Ballman35f94212014-04-14 16:03:22 +00003976 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc,
Aaron Ballman606093a2017-10-15 15:01:42 +00003977 ScopeName, ScopeLoc, Syntax);
Alex Lorenzd5d27e12017-03-01 18:06:25 +00003978
Erich Keanec480f302018-07-12 21:09:05 +00003979 if (!Attrs.empty() &&
3980 IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName)) {
Michael Krusedc5ce722018-08-03 01:21:16 +00003981 ParsedAttr &Attr = Attrs.back();
Alex Lorenzd5d27e12017-03-01 18:06:25 +00003982 // If the attribute is a standard or built-in attribute and we are
3983 // parsing an argument list, we need to determine whether this attribute
3984 // was allowed to have an argument list (such as [[deprecated]]), and how
3985 // many arguments were parsed (so we can diagnose on [[deprecated()]]).
Erich Keanec480f302018-07-12 21:09:05 +00003986 if (Attr.getMaxArgs() && !NumArgs) {
Alex Lorenzd5d27e12017-03-01 18:06:25 +00003987 // The attribute was allowed to have arguments, but none were provided
3988 // even though the attribute parsed successfully. This is an error.
3989 Diag(LParenLoc, diag::err_attribute_requires_arguments) << AttrName;
Erich Keanec480f302018-07-12 21:09:05 +00003990 Attr.setInvalid(true);
3991 } else if (!Attr.getMaxArgs()) {
Alex Lorenzd5d27e12017-03-01 18:06:25 +00003992 // The attribute parsed successfully, but was not allowed to have any
3993 // arguments. It doesn't matter whether any were provided -- the
3994 // presence of the argument list (even if empty) is diagnosed.
3995 Diag(LParenLoc, diag::err_cxx11_attribute_forbids_arguments)
3996 << AttrName
3997 << FixItHint::CreateRemoval(SourceRange(LParenLoc, *EndLoc));
Erich Keanec480f302018-07-12 21:09:05 +00003998 Attr.setInvalid(true);
Aaron Ballman35f94212014-04-14 16:03:22 +00003999 }
4000 }
Aaron Ballmanb8e20392014-03-31 17:32:39 +00004001 return true;
4002}
4003
Aaron Ballman606093a2017-10-15 15:01:42 +00004004/// ParseCXX11AttributeSpecifier - Parse a C++11 or C2x attribute-specifier.
Alexis Hunt96d5c762009-11-21 08:43:09 +00004005///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004006/// [C++11] attribute-specifier:
Alexis Hunt96d5c762009-11-21 08:43:09 +00004007/// '[' '[' attribute-list ']' ']'
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00004008/// alignment-specifier
Alexis Hunt96d5c762009-11-21 08:43:09 +00004009///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004010/// [C++11] attribute-list:
Alexis Hunt96d5c762009-11-21 08:43:09 +00004011/// attribute[opt]
4012/// attribute-list ',' attribute[opt]
Richard Smith3dff2512012-04-10 03:25:07 +00004013/// attribute '...'
4014/// attribute-list ',' attribute '...'
Alexis Hunt96d5c762009-11-21 08:43:09 +00004015///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004016/// [C++11] attribute:
Alexis Hunt96d5c762009-11-21 08:43:09 +00004017/// attribute-token attribute-argument-clause[opt]
4018///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004019/// [C++11] attribute-token:
Alexis Hunt96d5c762009-11-21 08:43:09 +00004020/// identifier
4021/// attribute-scoped-token
4022///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004023/// [C++11] attribute-scoped-token:
Alexis Hunt96d5c762009-11-21 08:43:09 +00004024/// attribute-namespace '::' identifier
4025///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004026/// [C++11] attribute-namespace:
Alexis Hunt96d5c762009-11-21 08:43:09 +00004027/// identifier
Richard Smith3dff2512012-04-10 03:25:07 +00004028void Parser::ParseCXX11AttributeSpecifier(ParsedAttributes &attrs,
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004029 SourceLocation *endLoc) {
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00004030 if (Tok.is(tok::kw_alignas)) {
Richard Smithf679b5b2011-10-14 20:48:27 +00004031 Diag(Tok.getLocation(), diag::warn_cxx98_compat_alignas);
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00004032 ParseAlignmentSpecifier(attrs, endLoc);
4033 return;
4034 }
4035
Aaron Ballman606093a2017-10-15 15:01:42 +00004036 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square) &&
4037 "Not a double square bracket attribute list");
Alexis Hunt96d5c762009-11-21 08:43:09 +00004038
Richard Smithf679b5b2011-10-14 20:48:27 +00004039 Diag(Tok.getLocation(), diag::warn_cxx98_compat_attribute);
4040
Alexis Hunt96d5c762009-11-21 08:43:09 +00004041 ConsumeBracket();
4042 ConsumeBracket();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004043
Richard Smithb7d7a042016-06-24 12:15:12 +00004044 SourceLocation CommonScopeLoc;
4045 IdentifierInfo *CommonScopeName = nullptr;
4046 if (Tok.is(tok::kw_using)) {
Aaron Ballmanc351fba2017-12-04 20:27:34 +00004047 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
Richard Smithb7d7a042016-06-24 12:15:12 +00004048 ? diag::warn_cxx14_compat_using_attribute_ns
4049 : diag::ext_using_attribute_ns);
4050 ConsumeToken();
4051
4052 CommonScopeName = TryParseCXX11AttributeIdentifier(CommonScopeLoc);
4053 if (!CommonScopeName) {
4054 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
4055 SkipUntil(tok::r_square, tok::colon, StopBeforeMatch);
4056 }
4057 if (!TryConsumeToken(tok::colon) && CommonScopeName)
4058 Diag(Tok.getLocation(), diag::err_expected) << tok::colon;
4059 }
4060
Richard Smith10876ef2013-01-17 01:30:42 +00004061 llvm::SmallDenseMap<IdentifierInfo*, SourceLocation, 4> SeenAttrs;
4062
Richard Smith3dff2512012-04-10 03:25:07 +00004063 while (Tok.isNot(tok::r_square)) {
Alexis Hunt96d5c762009-11-21 08:43:09 +00004064 // attribute not present
Alp Toker97650562014-01-10 11:19:30 +00004065 if (TryConsumeToken(tok::comma))
Alexis Hunt96d5c762009-11-21 08:43:09 +00004066 continue;
Alexis Hunt96d5c762009-11-21 08:43:09 +00004067
Richard Smith3dff2512012-04-10 03:25:07 +00004068 SourceLocation ScopeLoc, AttrLoc;
Craig Topper161e4db2014-05-21 06:02:52 +00004069 IdentifierInfo *ScopeName = nullptr, *AttrName = nullptr;
Richard Smith3dff2512012-04-10 03:25:07 +00004070
4071 AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
4072 if (!AttrName)
4073 // Break out to the "expected ']'" diagnostic.
4074 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004075
Alexis Hunt96d5c762009-11-21 08:43:09 +00004076 // scoped attribute
Alp Toker97650562014-01-10 11:19:30 +00004077 if (TryConsumeToken(tok::coloncolon)) {
Richard Smith3dff2512012-04-10 03:25:07 +00004078 ScopeName = AttrName;
4079 ScopeLoc = AttrLoc;
4080
4081 AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
4082 if (!AttrName) {
Alp Tokerec543272013-12-24 09:48:30 +00004083 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
Alexey Bataevee6507d2013-11-18 08:17:37 +00004084 SkipUntil(tok::r_square, tok::comma, StopAtSemi | StopBeforeMatch);
Alexis Hunt96d5c762009-11-21 08:43:09 +00004085 continue;
4086 }
Alexis Hunt96d5c762009-11-21 08:43:09 +00004087 }
4088
Richard Smithb7d7a042016-06-24 12:15:12 +00004089 if (CommonScopeName) {
4090 if (ScopeName) {
4091 Diag(ScopeLoc, diag::err_using_attribute_ns_conflict)
4092 << SourceRange(CommonScopeLoc);
4093 } else {
4094 ScopeName = CommonScopeName;
4095 ScopeLoc = CommonScopeLoc;
4096 }
4097 }
4098
Aaron Ballmanb8e20392014-03-31 17:32:39 +00004099 bool StandardAttr = IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName);
Alexis Hunt96d5c762009-11-21 08:43:09 +00004100 bool AttrParsed = false;
Alexis Hunt96d5c762009-11-21 08:43:09 +00004101
Richard Smith10876ef2013-01-17 01:30:42 +00004102 if (StandardAttr &&
4103 !SeenAttrs.insert(std::make_pair(AttrName, AttrLoc)).second)
4104 Diag(AttrLoc, diag::err_cxx11_attribute_repeated)
Aaron Ballmanb8e20392014-03-31 17:32:39 +00004105 << AttrName << SourceRange(SeenAttrs[AttrName]);
Richard Smith10876ef2013-01-17 01:30:42 +00004106
Michael Han23214e52012-10-03 01:56:22 +00004107 // Parse attribute arguments
Aaron Ballman35f94212014-04-14 16:03:22 +00004108 if (Tok.is(tok::l_paren))
Aaron Ballmanb8e20392014-03-31 17:32:39 +00004109 AttrParsed = ParseCXX11AttributeArgs(AttrName, AttrLoc, attrs, endLoc,
4110 ScopeName, ScopeLoc);
Michael Han23214e52012-10-03 01:56:22 +00004111
4112 if (!AttrParsed)
Aaron Ballman606093a2017-10-15 15:01:42 +00004113 attrs.addNew(
4114 AttrName,
4115 SourceRange(ScopeLoc.isValid() ? ScopeLoc : AttrLoc, AttrLoc),
4116 ScopeName, ScopeLoc, nullptr, 0,
Erich Keanee891aa92018-07-13 15:07:47 +00004117 getLangOpts().CPlusPlus ? ParsedAttr::AS_CXX11 : ParsedAttr::AS_C2x);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004118
Alp Toker97650562014-01-10 11:19:30 +00004119 if (TryConsumeToken(tok::ellipsis))
Michael Han23214e52012-10-03 01:56:22 +00004120 Diag(Tok, diag::err_cxx11_attribute_forbids_ellipsis)
Richard Trieub4025802018-03-28 04:16:13 +00004121 << AttrName;
Alexis Hunt96d5c762009-11-21 08:43:09 +00004122 }
4123
Alp Toker383d2c42014-01-01 03:08:43 +00004124 if (ExpectAndConsume(tok::r_square))
Alexey Bataevee6507d2013-11-18 08:17:37 +00004125 SkipUntil(tok::r_square);
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004126 if (endLoc)
4127 *endLoc = Tok.getLocation();
Alp Toker383d2c42014-01-01 03:08:43 +00004128 if (ExpectAndConsume(tok::r_square))
Alexey Bataevee6507d2013-11-18 08:17:37 +00004129 SkipUntil(tok::r_square);
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004130}
Alexis Hunt96d5c762009-11-21 08:43:09 +00004131
Aaron Ballman606093a2017-10-15 15:01:42 +00004132/// ParseCXX11Attributes - Parse a C++11 or C2x attribute-specifier-seq.
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004133///
4134/// attribute-specifier-seq:
4135/// attribute-specifier-seq[opt] attribute-specifier
Richard Smith3dff2512012-04-10 03:25:07 +00004136void Parser::ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004137 SourceLocation *endLoc) {
Aaron Ballman606093a2017-10-15 15:01:42 +00004138 assert(standardAttributesAllowed());
Richard Smith4cabd042013-02-22 09:15:49 +00004139
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004140 SourceLocation StartLoc = Tok.getLocation(), Loc;
4141 if (!endLoc)
4142 endLoc = &Loc;
4143
Douglas Gregor6f981002011-10-07 20:35:25 +00004144 do {
Richard Smith3dff2512012-04-10 03:25:07 +00004145 ParseCXX11AttributeSpecifier(attrs, endLoc);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004146 } while (isCXX11AttributeSpecifier());
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004147
4148 attrs.Range = SourceRange(StartLoc, *endLoc);
Alexis Hunt96d5c762009-11-21 08:43:09 +00004149}
4150
Richard Smithc2c8bb82013-10-15 01:34:54 +00004151void Parser::DiagnoseAndSkipCXX11Attributes() {
Richard Smithc2c8bb82013-10-15 01:34:54 +00004152 // Start and end location of an attribute or an attribute list.
4153 SourceLocation StartLoc = Tok.getLocation();
Richard Smith955bf012014-06-19 11:42:00 +00004154 SourceLocation EndLoc = SkipCXX11Attributes();
4155
4156 if (EndLoc.isValid()) {
4157 SourceRange Range(StartLoc, EndLoc);
4158 Diag(StartLoc, diag::err_attributes_not_allowed)
4159 << Range;
4160 }
4161}
4162
4163SourceLocation Parser::SkipCXX11Attributes() {
Richard Smithc2c8bb82013-10-15 01:34:54 +00004164 SourceLocation EndLoc;
4165
Richard Smith955bf012014-06-19 11:42:00 +00004166 if (!isCXX11AttributeSpecifier())
4167 return EndLoc;
4168
Richard Smithc2c8bb82013-10-15 01:34:54 +00004169 do {
4170 if (Tok.is(tok::l_square)) {
4171 BalancedDelimiterTracker T(*this, tok::l_square);
4172 T.consumeOpen();
4173 T.skipToEnd();
4174 EndLoc = T.getCloseLocation();
4175 } else {
4176 assert(Tok.is(tok::kw_alignas) && "not an attribute specifier");
4177 ConsumeToken();
4178 BalancedDelimiterTracker T(*this, tok::l_paren);
4179 if (!T.consumeOpen())
4180 T.skipToEnd();
4181 EndLoc = T.getCloseLocation();
4182 }
4183 } while (isCXX11AttributeSpecifier());
4184
Richard Smith955bf012014-06-19 11:42:00 +00004185 return EndLoc;
Richard Smithc2c8bb82013-10-15 01:34:54 +00004186}
4187
Nico Weber05e1dad2016-09-03 03:25:22 +00004188/// Parse uuid() attribute when it appears in a [] Microsoft attribute.
4189void Parser::ParseMicrosoftUuidAttributeArgs(ParsedAttributes &Attrs) {
4190 assert(Tok.is(tok::identifier) && "Not a Microsoft attribute list");
4191 IdentifierInfo *UuidIdent = Tok.getIdentifierInfo();
4192 assert(UuidIdent->getName() == "uuid" && "Not a Microsoft attribute list");
4193
4194 SourceLocation UuidLoc = Tok.getLocation();
4195 ConsumeToken();
4196
4197 // Ignore the left paren location for now.
4198 BalancedDelimiterTracker T(*this, tok::l_paren);
4199 if (T.consumeOpen()) {
4200 Diag(Tok, diag::err_expected) << tok::l_paren;
4201 return;
4202 }
4203
4204 ArgsVector ArgExprs;
4205 if (Tok.is(tok::string_literal)) {
4206 // Easy case: uuid("...") -- quoted string.
4207 ExprResult StringResult = ParseStringLiteralExpression();
4208 if (StringResult.isInvalid())
4209 return;
4210 ArgExprs.push_back(StringResult.get());
4211 } else {
4212 // something like uuid({000000A0-0000-0000-C000-000000000049}) -- no
4213 // quotes in the parens. Just append the spelling of all tokens encountered
4214 // until the closing paren.
4215
4216 SmallString<42> StrBuffer; // 2 "", 36 bytes UUID, 2 optional {}, 1 nul
4217 StrBuffer += "\"";
4218
4219 // Since none of C++'s keywords match [a-f]+, accepting just tok::l_brace,
4220 // tok::r_brace, tok::minus, tok::identifier (think C000) and
4221 // tok::numeric_constant (0000) should be enough. But the spelling of the
4222 // uuid argument is checked later anyways, so there's no harm in accepting
4223 // almost anything here.
4224 // cl is very strict about whitespace in this form and errors out if any
4225 // is present, so check the space flags on the tokens.
4226 SourceLocation StartLoc = Tok.getLocation();
4227 while (Tok.isNot(tok::r_paren)) {
4228 if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
4229 Diag(Tok, diag::err_attribute_uuid_malformed_guid);
4230 SkipUntil(tok::r_paren, StopAtSemi);
4231 return;
4232 }
4233 SmallString<16> SpellingBuffer;
4234 SpellingBuffer.resize(Tok.getLength() + 1);
4235 bool Invalid = false;
4236 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
4237 if (Invalid) {
4238 SkipUntil(tok::r_paren, StopAtSemi);
4239 return;
4240 }
4241 StrBuffer += TokSpelling;
4242 ConsumeAnyToken();
4243 }
4244 StrBuffer += "\"";
4245
4246 if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
4247 Diag(Tok, diag::err_attribute_uuid_malformed_guid);
4248 ConsumeParen();
4249 return;
4250 }
4251
4252 // Pretend the user wrote the appropriate string literal here.
4253 // ActOnStringLiteral() copies the string data into the literal, so it's
4254 // ok that the Token points to StrBuffer.
4255 Token Toks[1];
4256 Toks[0].startToken();
4257 Toks[0].setKind(tok::string_literal);
4258 Toks[0].setLocation(StartLoc);
4259 Toks[0].setLiteralData(StrBuffer.data());
4260 Toks[0].setLength(StrBuffer.size());
4261 StringLiteral *UuidString =
4262 cast<StringLiteral>(Actions.ActOnStringLiteral(Toks, nullptr).get());
4263 ArgExprs.push_back(UuidString);
4264 }
4265
4266 if (!T.consumeClose()) {
Nico Weber05e1dad2016-09-03 03:25:22 +00004267 Attrs.addNew(UuidIdent, SourceRange(UuidLoc, T.getCloseLocation()), nullptr,
4268 SourceLocation(), ArgExprs.data(), ArgExprs.size(),
Erich Keanee891aa92018-07-13 15:07:47 +00004269 ParsedAttr::AS_Microsoft);
Nico Weber05e1dad2016-09-03 03:25:22 +00004270 }
4271}
4272
David Majnemere4752e752015-07-08 05:55:00 +00004273/// ParseMicrosoftAttributes - Parse Microsoft attributes [Attr]
Francois Pichetc2bc5ac2010-10-11 12:59:39 +00004274///
4275/// [MS] ms-attribute:
4276/// '[' token-seq ']'
4277///
4278/// [MS] ms-attribute-seq:
4279/// ms-attribute[opt]
4280/// ms-attribute ms-attribute-seq
John McCall53fa7142010-12-24 02:08:15 +00004281void Parser::ParseMicrosoftAttributes(ParsedAttributes &attrs,
4282 SourceLocation *endLoc) {
Francois Pichetc2bc5ac2010-10-11 12:59:39 +00004283 assert(Tok.is(tok::l_square) && "Not a Microsoft attribute list");
4284
Saleem Abdulrasool425efcf2015-06-15 20:57:04 +00004285 do {
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004286 // FIXME: If this is actually a C++11 attribute, parse it as one.
Saleem Abdulrasool425efcf2015-06-15 20:57:04 +00004287 BalancedDelimiterTracker T(*this, tok::l_square);
4288 T.consumeOpen();
Nico Weber05e1dad2016-09-03 03:25:22 +00004289
4290 // Skip most ms attributes except for a whitelist.
4291 while (true) {
4292 SkipUntil(tok::r_square, tok::identifier, StopAtSemi | StopBeforeMatch);
4293 if (Tok.isNot(tok::identifier)) // ']', but also eof
4294 break;
4295 if (Tok.getIdentifierInfo()->getName() == "uuid")
4296 ParseMicrosoftUuidAttributeArgs(attrs);
4297 else
4298 ConsumeToken();
4299 }
4300
Saleem Abdulrasool425efcf2015-06-15 20:57:04 +00004301 T.consumeClose();
4302 if (endLoc)
4303 *endLoc = T.getCloseLocation();
4304 } while (Tok.is(tok::l_square));
Francois Pichetc2bc5ac2010-10-11 12:59:39 +00004305}
Francois Pichet8f981d52011-05-25 10:19:49 +00004306
Erich Keanec480f302018-07-12 21:09:05 +00004307void Parser::ParseMicrosoftIfExistsClassDeclaration(
4308 DeclSpec::TST TagType, ParsedAttributes &AccessAttrs,
4309 AccessSpecifier &CurAS) {
Douglas Gregor43edb322011-10-24 22:31:10 +00004310 IfExistsCondition Result;
Francois Pichet8f981d52011-05-25 10:19:49 +00004311 if (ParseMicrosoftIfExistsCondition(Result))
4312 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00004313
Douglas Gregor43edb322011-10-24 22:31:10 +00004314 BalancedDelimiterTracker Braces(*this, tok::l_brace);
4315 if (Braces.consumeOpen()) {
Alp Tokerec543272013-12-24 09:48:30 +00004316 Diag(Tok, diag::err_expected) << tok::l_brace;
Francois Pichet8f981d52011-05-25 10:19:49 +00004317 return;
4318 }
Francois Pichet8f981d52011-05-25 10:19:49 +00004319
Douglas Gregor43edb322011-10-24 22:31:10 +00004320 switch (Result.Behavior) {
4321 case IEB_Parse:
4322 // Parse the declarations below.
4323 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00004324
Douglas Gregor43edb322011-10-24 22:31:10 +00004325 case IEB_Dependent:
4326 Diag(Result.KeywordLoc, diag::warn_microsoft_dependent_exists)
4327 << Result.IsIfExists;
4328 // Fall through to skip.
Galina Kistanovad819d5b2017-06-01 21:19:06 +00004329 LLVM_FALLTHROUGH;
Fangrui Song6907ce22018-07-30 19:24:48 +00004330
Douglas Gregor43edb322011-10-24 22:31:10 +00004331 case IEB_Skip:
4332 Braces.skipToEnd();
Francois Pichet8f981d52011-05-25 10:19:49 +00004333 return;
4334 }
4335
Richard Smith34f30512013-11-23 04:06:09 +00004336 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
Francois Pichet8f981d52011-05-25 10:19:49 +00004337 // __if_exists, __if_not_exists can nest.
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00004338 if (Tok.isOneOf(tok::kw___if_exists, tok::kw___if_not_exists)) {
Erich Keanec480f302018-07-12 21:09:05 +00004339 ParseMicrosoftIfExistsClassDeclaration((DeclSpec::TST)TagType,
4340 AccessAttrs, CurAS);
Francois Pichet8f981d52011-05-25 10:19:49 +00004341 continue;
4342 }
4343
4344 // Check for extraneous top-level semicolon.
4345 if (Tok.is(tok::semi)) {
Richard Smith87f5dc52012-07-23 05:45:25 +00004346 ConsumeExtraSemi(InsideStruct, TagType);
Francois Pichet8f981d52011-05-25 10:19:49 +00004347 continue;
4348 }
4349
4350 AccessSpecifier AS = getAccessSpecifierIfPresent();
4351 if (AS != AS_none) {
4352 // Current token is a C++ access specifier.
4353 CurAS = AS;
4354 SourceLocation ASLoc = Tok.getLocation();
4355 ConsumeToken();
4356 if (Tok.is(tok::colon))
Erich Keanec480f302018-07-12 21:09:05 +00004357 Actions.ActOnAccessSpecifier(AS, ASLoc, Tok.getLocation(),
4358 ParsedAttributesView{});
Francois Pichet8f981d52011-05-25 10:19:49 +00004359 else
Alp Toker35d87032013-12-30 23:29:50 +00004360 Diag(Tok, diag::err_expected) << tok::colon;
Francois Pichet8f981d52011-05-25 10:19:49 +00004361 ConsumeToken();
4362 continue;
4363 }
4364
4365 // Parse all the comma separated declarators.
Erich Keanec480f302018-07-12 21:09:05 +00004366 ParseCXXClassMemberDeclaration(CurAS, AccessAttrs);
Francois Pichet8f981d52011-05-25 10:19:49 +00004367 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004368
Douglas Gregor43edb322011-10-24 22:31:10 +00004369 Braces.consumeClose();
Francois Pichet8f981d52011-05-25 10:19:49 +00004370}