blob: b98ce3e66292102a3cdc9abbfab3c22afa66901a [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)
Aaron Ballman1d935222019-08-27 14:41:39 +0000865 Diag(Tok, diag::ext_c11_feature) << Tok.getName();
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
Ilya Biryukov929af672019-05-17 09:32:05 +00001043 PP.EnterToken(Tok, /*IsReinject*/true);
David Blaikie15a430a2011-12-04 05:04:18 +00001044
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(
Rui Ueyama49a3ad22019-07-16 04:46:31 +00001211 *Id, IdLoc, getCurScope(), &SS, /*isClassName=*/true, false, nullptr,
Richard Smith600b5262017-01-26 20:40:47 +00001212 /*IsCtorOrDtorName=*/false,
Rui Ueyama49a3ad22019-07-16 04:46:31 +00001213 /*WantNontrivialTypeSourceInfo=*/true,
Richard Smith600b5262017-01-26 20:40:47 +00001214 /*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;
Richard Smitha6e8b682019-09-04 20:30:37 +00001316 case tok::kw_consteval: // struct foo {...} consteval x;
1317 case tok::kw_constinit: // struct foo {...} constinit x;
Richard Smith369b9f92012-06-25 21:37:02 +00001318 // As shown above, type qualifiers and storage class specifiers absolutely
1319 // can occur after class specifiers according to the grammar. However,
1320 // almost no one actually writes code like this. If we see one of these,
1321 // it is much more likely that someone missed a semi colon and the
1322 // type/storage class specifier we're seeing is part of the *next*
1323 // intended declaration, as in:
1324 //
1325 // struct foo { ... }
1326 // typedef int X;
1327 //
1328 // We'd really like to emit a missing semicolon error instead of emitting
1329 // an error on the 'int' saying that you can't have two type specifiers in
1330 // the same declaration of X. Because of this, we look ahead past this
1331 // token to see if it's a type specifier. If so, we know the code is
1332 // otherwise invalid, so we can produce the expected semi error.
1333 if (!isKnownToBeTypeSpecifier(NextToken()))
1334 return true;
1335 break;
1336 case tok::r_brace: // struct bar { struct foo {...} }
1337 // Missing ';' at end of struct is accepted as an extension in C mode.
1338 if (!getLangOpts().CPlusPlus)
1339 return true;
1340 break;
Richard Smith52c5b872013-01-29 04:13:32 +00001341 case tok::greater:
1342 // template<class T = class X>
1343 return getLangOpts().CPlusPlus;
Richard Smith369b9f92012-06-25 21:37:02 +00001344 }
1345 return false;
1346}
1347
Douglas Gregor556877c2008-04-13 21:30:24 +00001348/// ParseClassSpecifier - Parse a C++ class-specifier [C++ class] or
1349/// elaborated-type-specifier [C++ dcl.type.elab]; we can't tell which
1350/// until we reach the start of a definition or see a token that
Richard Smithc5b05522012-03-12 07:56:15 +00001351/// cannot start a definition.
Douglas Gregor556877c2008-04-13 21:30:24 +00001352///
1353/// class-specifier: [C++ class]
1354/// class-head '{' member-specification[opt] '}'
1355/// class-head '{' member-specification[opt] '}' attributes[opt]
1356/// class-head:
1357/// class-key identifier[opt] base-clause[opt]
1358/// class-key nested-name-specifier identifier base-clause[opt]
1359/// class-key nested-name-specifier[opt] simple-template-id
1360/// base-clause[opt]
1361/// [GNU] class-key attributes[opt] identifier[opt] base-clause[opt]
Mike Stump11289f42009-09-09 15:08:12 +00001362/// [GNU] class-key attributes[opt] nested-name-specifier
Douglas Gregor556877c2008-04-13 21:30:24 +00001363/// identifier base-clause[opt]
Mike Stump11289f42009-09-09 15:08:12 +00001364/// [GNU] class-key attributes[opt] nested-name-specifier[opt]
Douglas Gregor556877c2008-04-13 21:30:24 +00001365/// simple-template-id base-clause[opt]
1366/// class-key:
1367/// 'class'
1368/// 'struct'
1369/// 'union'
1370///
1371/// elaborated-type-specifier: [C++ dcl.type.elab]
Mike Stump11289f42009-09-09 15:08:12 +00001372/// class-key ::[opt] nested-name-specifier[opt] identifier
1373/// class-key ::[opt] nested-name-specifier[opt] 'template'[opt]
1374/// simple-template-id
Douglas Gregor556877c2008-04-13 21:30:24 +00001375///
1376/// Note that the C++ class-specifier and elaborated-type-specifier,
1377/// together, subsume the C99 struct-or-union-specifier:
1378///
1379/// struct-or-union-specifier: [C99 6.7.2.1]
1380/// struct-or-union identifier[opt] '{' struct-contents '}'
1381/// struct-or-union identifier
1382/// [GNU] struct-or-union attributes[opt] identifier[opt] '{' struct-contents
1383/// '}' attributes[opt]
1384/// [GNU] struct-or-union attributes[opt] identifier
1385/// struct-or-union:
1386/// 'struct'
1387/// 'union'
Chris Lattnerffaa0e62009-04-12 21:49:30 +00001388void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind,
1389 SourceLocation StartLoc, DeclSpec &DS,
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001390 const ParsedTemplateInfo &TemplateInfo,
Fangrui Song6907ce22018-07-30 19:24:48 +00001391 AccessSpecifier AS,
1392 bool EnteringContext, DeclSpecContext DSC,
Bill Wendling44426052012-12-20 19:22:21 +00001393 ParsedAttributesWithRange &Attributes) {
Joao Matose9a3ed42012-08-31 22:18:20 +00001394 DeclSpec::TST TagType;
1395 if (TagTokKind == tok::kw_struct)
1396 TagType = DeclSpec::TST_struct;
1397 else if (TagTokKind == tok::kw___interface)
1398 TagType = DeclSpec::TST_interface;
1399 else if (TagTokKind == tok::kw_class)
1400 TagType = DeclSpec::TST_class;
1401 else {
Chris Lattnerffaa0e62009-04-12 21:49:30 +00001402 assert(TagTokKind == tok::kw_union && "Not a class specifier");
1403 TagType = DeclSpec::TST_union;
1404 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001405
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00001406 if (Tok.is(tok::code_completion)) {
1407 // Code completion for a struct, class, or union name.
Douglas Gregor0be31a22010-07-02 17:43:08 +00001408 Actions.CodeCompleteTag(getCurScope(), TagType);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001409 return cutOffParsing();
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00001410 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001411
Chandler Carruth2d69ec72010-06-28 08:39:25 +00001412 // C++03 [temp.explicit] 14.7.2/8:
1413 // The usual access checking rules do not apply to names used to specify
1414 // explicit instantiations.
1415 //
1416 // As an extension we do not perform access checking on the names used to
1417 // specify explicit specializations either. This is important to allow
1418 // specializing traits classes for private types.
John McCall6347b682012-05-07 06:16:58 +00001419 //
1420 // Note that we don't suppress if this turns out to be an elaborated
1421 // type specifier.
1422 bool shouldDelayDiagsInTag =
1423 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
1424 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
1425 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
Chandler Carruth2d69ec72010-06-28 08:39:25 +00001426
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001427 ParsedAttributesWithRange attrs(AttrFactory);
Douglas Gregor556877c2008-04-13 21:30:24 +00001428 // If attributes exist after tag, parse them.
Richard Smith37a45dd2013-10-24 01:21:09 +00001429 MaybeParseGNUAttributes(attrs);
Aaron Ballman068aa512015-05-20 20:58:33 +00001430 MaybeParseMicrosoftDeclSpecs(attrs);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001431
John McCall8d32c052012-05-22 21:28:12 +00001432 // Parse inheritance specifiers.
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001433 if (Tok.isOneOf(tok::kw___single_inheritance,
1434 tok::kw___multiple_inheritance,
1435 tok::kw___virtual_inheritance))
Richard Smith37a45dd2013-10-24 01:21:09 +00001436 ParseMicrosoftInheritanceClassAttributes(attrs);
John McCall8d32c052012-05-22 21:28:12 +00001437
Alexis Hunt96d5c762009-11-21 08:43:09 +00001438 // If C++0x attributes exist here, parse them.
1439 // FIXME: Are we consistent with the ordering of parsing of different
1440 // styles of attributes?
Richard Smith89645bc2013-01-02 12:01:23 +00001441 MaybeParseCXX11Attributes(attrs);
Mike Stump11289f42009-09-09 15:08:12 +00001442
Michael Han309af292013-01-07 16:57:11 +00001443 // Source location used by FIXIT to insert misplaced
1444 // C++11 attributes
1445 SourceLocation AttrFixitLoc = Tok.getLocation();
1446
Nico Weber7c3c5be2014-09-23 04:09:56 +00001447 if (TagType == DeclSpec::TST_struct &&
David Majnemer86330af2014-12-29 02:14:26 +00001448 Tok.isNot(tok::identifier) &&
1449 !Tok.isAnnotation() &&
Nico Weber7c3c5be2014-09-23 04:09:56 +00001450 Tok.getIdentifierInfo() &&
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001451 Tok.isOneOf(tok::kw___is_abstract,
Eric Fiselier07360662017-04-12 22:12:15 +00001452 tok::kw___is_aggregate,
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001453 tok::kw___is_arithmetic,
1454 tok::kw___is_array,
David Majnemerb3d96882016-05-23 17:21:55 +00001455 tok::kw___is_assignable,
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001456 tok::kw___is_base_of,
1457 tok::kw___is_class,
1458 tok::kw___is_complete_type,
1459 tok::kw___is_compound,
1460 tok::kw___is_const,
1461 tok::kw___is_constructible,
1462 tok::kw___is_convertible,
1463 tok::kw___is_convertible_to,
1464 tok::kw___is_destructible,
1465 tok::kw___is_empty,
1466 tok::kw___is_enum,
1467 tok::kw___is_floating_point,
1468 tok::kw___is_final,
1469 tok::kw___is_function,
1470 tok::kw___is_fundamental,
1471 tok::kw___is_integral,
1472 tok::kw___is_interface_class,
1473 tok::kw___is_literal,
1474 tok::kw___is_lvalue_expr,
1475 tok::kw___is_lvalue_reference,
1476 tok::kw___is_member_function_pointer,
1477 tok::kw___is_member_object_pointer,
1478 tok::kw___is_member_pointer,
1479 tok::kw___is_nothrow_assignable,
1480 tok::kw___is_nothrow_constructible,
1481 tok::kw___is_nothrow_destructible,
1482 tok::kw___is_object,
1483 tok::kw___is_pod,
1484 tok::kw___is_pointer,
1485 tok::kw___is_polymorphic,
1486 tok::kw___is_reference,
1487 tok::kw___is_rvalue_expr,
1488 tok::kw___is_rvalue_reference,
1489 tok::kw___is_same,
1490 tok::kw___is_scalar,
1491 tok::kw___is_sealed,
1492 tok::kw___is_signed,
1493 tok::kw___is_standard_layout,
1494 tok::kw___is_trivial,
1495 tok::kw___is_trivially_assignable,
1496 tok::kw___is_trivially_constructible,
1497 tok::kw___is_trivially_copyable,
1498 tok::kw___is_union,
1499 tok::kw___is_unsigned,
1500 tok::kw___is_void,
1501 tok::kw___is_volatile))
Nico Weber7c3c5be2014-09-23 04:09:56 +00001502 // GNU libstdc++ 4.2 and libc++ use certain intrinsic names as the
1503 // name of struct templates, but some are keywords in GCC >= 4.3
1504 // and Clang. Therefore, when we see the token sequence "struct
1505 // X", make X into a normal identifier rather than a keyword, to
1506 // allow libstdc++ 4.2 and libc++ to work properly.
1507 TryKeywordIdentFallback(true);
Mike Stump11289f42009-09-09 15:08:12 +00001508
David Majnemer51fd8a02015-07-22 23:46:18 +00001509 struct PreserveAtomicIdentifierInfoRAII {
1510 PreserveAtomicIdentifierInfoRAII(Token &Tok, bool Enabled)
1511 : AtomicII(nullptr) {
1512 if (!Enabled)
1513 return;
1514 assert(Tok.is(tok::kw__Atomic));
1515 AtomicII = Tok.getIdentifierInfo();
1516 AtomicII->revertTokenIDToIdentifier();
1517 Tok.setKind(tok::identifier);
1518 }
1519 ~PreserveAtomicIdentifierInfoRAII() {
1520 if (!AtomicII)
1521 return;
1522 AtomicII->revertIdentifierToTokenID(tok::kw__Atomic);
1523 }
1524 IdentifierInfo *AtomicII;
1525 };
1526
1527 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
1528 // implementation for VS2013 uses _Atomic as an identifier for one of the
1529 // classes in <atomic>. When we are parsing 'struct _Atomic', don't consider
1530 // '_Atomic' to be a keyword. We are careful to undo this so that clang can
1531 // use '_Atomic' in its own header files.
1532 bool ShouldChangeAtomicToIdentifier = getLangOpts().MSVCCompat &&
1533 Tok.is(tok::kw__Atomic) &&
1534 TagType == DeclSpec::TST_struct;
1535 PreserveAtomicIdentifierInfoRAII AtomicTokenGuard(
1536 Tok, ShouldChangeAtomicToIdentifier);
1537
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001538 // Parse the (optional) nested-name-specifier.
John McCall9dab4e62009-12-12 11:40:51 +00001539 CXXScopeSpec &SS = DS.getTypeSpecScope();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001540 if (getLangOpts().CPlusPlus) {
Serge Pavlov458ea762014-07-16 05:16:52 +00001541 // "FOO : BAR" is not a potential typo for "FOO::BAR". In this context it
1542 // is a base-specifier-list.
Chris Lattnerd5c1c9d2009-12-10 00:32:41 +00001543 ColonProtectionRAIIObject X(*this);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001544
Nico Webercfaa4cd2015-02-15 07:26:13 +00001545 CXXScopeSpec Spec;
1546 bool HasValidSpec = true;
David Blaikieefdccaa2016-01-15 23:43:34 +00001547 if (ParseOptionalCXXScopeSpecifier(Spec, nullptr, EnteringContext)) {
John McCall413021a2010-07-30 06:26:29 +00001548 DS.SetTypeSpecError();
Nico Webercfaa4cd2015-02-15 07:26:13 +00001549 HasValidSpec = false;
1550 }
1551 if (Spec.isSet())
1552 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::annot_template_id)) {
Alp Tokerec543272013-12-24 09:48:30 +00001553 Diag(Tok, diag::err_expected) << tok::identifier;
Nico Webercfaa4cd2015-02-15 07:26:13 +00001554 HasValidSpec = false;
1555 }
1556 if (HasValidSpec)
1557 SS = Spec;
Chris Lattnerd5c1c9d2009-12-10 00:32:41 +00001558 }
Douglas Gregor67a65642009-02-17 23:15:12 +00001559
Douglas Gregor916462b2009-10-30 21:46:58 +00001560 TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
1561
Richard Smithb23c5e82019-05-09 03:31:27 +00001562 auto RecoverFromUndeclaredTemplateName = [&](IdentifierInfo *Name,
1563 SourceLocation NameLoc,
1564 SourceRange TemplateArgRange,
1565 bool KnownUndeclared) {
1566 Diag(NameLoc, diag::err_explicit_spec_non_template)
1567 << (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
1568 << TagTokKind << Name << TemplateArgRange << KnownUndeclared;
1569
1570 // Strip off the last template parameter list if it was empty, since
1571 // we've removed its template argument list.
1572 if (TemplateParams && TemplateInfo.LastParameterListWasEmpty) {
1573 if (TemplateParams->size() > 1) {
1574 TemplateParams->pop_back();
1575 } else {
1576 TemplateParams = nullptr;
1577 const_cast<ParsedTemplateInfo &>(TemplateInfo).Kind =
1578 ParsedTemplateInfo::NonTemplate;
1579 }
1580 } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1581 // Pretend this is just a forward declaration.
1582 TemplateParams = nullptr;
1583 const_cast<ParsedTemplateInfo &>(TemplateInfo).Kind =
1584 ParsedTemplateInfo::NonTemplate;
1585 const_cast<ParsedTemplateInfo &>(TemplateInfo).TemplateLoc =
1586 SourceLocation();
1587 const_cast<ParsedTemplateInfo &>(TemplateInfo).ExternLoc =
1588 SourceLocation();
1589 }
1590 };
1591
Douglas Gregor67a65642009-02-17 23:15:12 +00001592 // Parse the (optional) class name or simple-template-id.
Craig Topper161e4db2014-05-21 06:02:52 +00001593 IdentifierInfo *Name = nullptr;
Douglas Gregor556877c2008-04-13 21:30:24 +00001594 SourceLocation NameLoc;
Craig Topper161e4db2014-05-21 06:02:52 +00001595 TemplateIdAnnotation *TemplateId = nullptr;
Douglas Gregor556877c2008-04-13 21:30:24 +00001596 if (Tok.is(tok::identifier)) {
1597 Name = Tok.getIdentifierInfo();
1598 NameLoc = ConsumeToken();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001599
David Blaikiebbafb8a2012-03-11 07:00:24 +00001600 if (Tok.is(tok::less) && getLangOpts().CPlusPlus) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001601 // The name was supposed to refer to a template, but didn't.
Douglas Gregor916462b2009-10-30 21:46:58 +00001602 // Eat the template argument list and try to continue parsing this as
1603 // a class (or template thereof).
1604 TemplateArgList TemplateArgs;
Douglas Gregor916462b2009-10-30 21:46:58 +00001605 SourceLocation LAngleLoc, RAngleLoc;
Richard Smith9a420f92017-05-10 21:47:30 +00001606 if (ParseTemplateIdAfterTemplateName(true, LAngleLoc, TemplateArgs,
1607 RAngleLoc)) {
Douglas Gregor916462b2009-10-30 21:46:58 +00001608 // We couldn't parse the template argument list at all, so don't
1609 // try to give any location information for the list.
1610 LAngleLoc = RAngleLoc = SourceLocation();
1611 }
Richard Smithb23c5e82019-05-09 03:31:27 +00001612 RecoverFromUndeclaredTemplateName(
1613 Name, NameLoc, SourceRange(LAngleLoc, RAngleLoc), false);
Douglas Gregor916462b2009-10-30 21:46:58 +00001614 }
Douglas Gregor7f741122009-02-25 19:37:18 +00001615 } else if (Tok.is(tok::annot_template_id)) {
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00001616 TemplateId = takeTemplateIdAnnotation(Tok);
Richard Smithaf3b3252017-05-18 19:21:48 +00001617 NameLoc = ConsumeAnnotationToken();
Douglas Gregor67a65642009-02-17 23:15:12 +00001618
Richard Smithb23c5e82019-05-09 03:31:27 +00001619 if (TemplateId->Kind == TNK_Undeclared_template) {
1620 // Try to resolve the template name to a type template.
1621 Actions.ActOnUndeclaredTypeTemplateName(getCurScope(), TemplateId->Template,
1622 TemplateId->Kind, NameLoc, Name);
1623 if (TemplateId->Kind == TNK_Undeclared_template) {
1624 RecoverFromUndeclaredTemplateName(
1625 Name, NameLoc,
1626 SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc), true);
1627 TemplateId = nullptr;
1628 }
1629 }
1630
1631 if (TemplateId && TemplateId->Kind != TNK_Type_template &&
Douglas Gregore7c20652011-03-02 00:47:37 +00001632 TemplateId->Kind != TNK_Dependent_template_name) {
Douglas Gregor7f741122009-02-25 19:37:18 +00001633 // The template-name in the simple-template-id refers to
1634 // something other than a class template. Give an appropriate
1635 // error message and skip to the ';'.
1636 SourceRange Range(NameLoc);
1637 if (SS.isNotEmpty())
1638 Range.setBegin(SS.getBeginLoc());
Douglas Gregor67a65642009-02-17 23:15:12 +00001639
Richard Smith72bfbd82013-12-04 00:28:23 +00001640 // FIXME: Name may be null here.
Douglas Gregor7f741122009-02-25 19:37:18 +00001641 Diag(TemplateId->LAngleLoc, diag::err_template_spec_syntax_non_template)
Richard Smithb23c5e82019-05-09 03:31:27 +00001642 << TemplateId->Name << static_cast<int>(TemplateId->Kind) << Range;
Mike Stump11289f42009-09-09 15:08:12 +00001643
Douglas Gregor7f741122009-02-25 19:37:18 +00001644 DS.SetTypeSpecError();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001645 SkipUntil(tok::semi, StopBeforeMatch);
Douglas Gregor7f741122009-02-25 19:37:18 +00001646 return;
Douglas Gregor67a65642009-02-17 23:15:12 +00001647 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001648 }
1649
Richard Smithbfdb1082012-03-12 08:56:40 +00001650 // There are four options here.
1651 // - If we are in a trailing return type, this is always just a reference,
1652 // and we must not try to parse a definition. For instance,
1653 // [] () -> struct S { };
1654 // does not define a type.
1655 // - If we have 'struct foo {...', 'struct foo :...',
1656 // 'struct foo final :' or 'struct foo final {', then this is a definition.
1657 // - If we have 'struct foo;', then this is either a forward declaration
1658 // or a friend declaration, which have to be treated differently.
1659 // - Otherwise we have something like 'struct foo xyz', a reference.
Michael Han9407e502012-11-26 22:54:45 +00001660 //
1661 // We also detect these erroneous cases to provide better diagnostic for
1662 // C++11 attributes parsing.
1663 // - attributes follow class name:
1664 // struct foo [[]] {};
1665 // - attributes appear before or after 'final':
1666 // struct foo [[]] final [[]] {};
1667 //
Richard Smithc5b05522012-03-12 07:56:15 +00001668 // However, in type-specifier-seq's, things look like declarations but are
1669 // just references, e.g.
1670 // new struct s;
Sebastian Redl2b372722010-02-03 21:21:43 +00001671 // or
Richard Smithc5b05522012-03-12 07:56:15 +00001672 // &T::operator struct s;
Faisal Vali7db85c52017-12-31 00:06:40 +00001673 // For these, DSC is DeclSpecContext::DSC_type_specifier or
1674 // DeclSpecContext::DSC_alias_declaration.
Michael Han9407e502012-11-26 22:54:45 +00001675
1676 // If there are attributes after class name, parse them.
Richard Smith89645bc2013-01-02 12:01:23 +00001677 MaybeParseCXX11Attributes(Attributes);
Michael Han9407e502012-11-26 22:54:45 +00001678
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001679 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
John McCallfaf5fb42010-08-26 23:41:50 +00001680 Sema::TagUseKind TUK;
Faisal Vali7db85c52017-12-31 00:06:40 +00001681 if (DSC == DeclSpecContext::DSC_trailing)
Richard Smithbfdb1082012-03-12 08:56:40 +00001682 TUK = Sema::TUK_Reference;
1683 else if (Tok.is(tok::l_brace) ||
1684 (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
Richard Smith89645bc2013-01-02 12:01:23 +00001685 (isCXX11FinalKeyword() &&
David Blaikie9933a5a2012-03-12 15:39:49 +00001686 (NextToken().is(tok::l_brace) || NextToken().is(tok::colon)))) {
Douglas Gregor3dad8422009-09-26 06:47:28 +00001687 if (DS.isFriendSpecified()) {
1688 // C++ [class.friend]p2:
1689 // A class shall not be defined in a friend declaration.
Richard Smith0f8ee222012-01-10 01:33:14 +00001690 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
Douglas Gregor3dad8422009-09-26 06:47:28 +00001691 << SourceRange(DS.getFriendSpecLoc());
1692
1693 // Skip everything up to the semicolon, so that this looks like a proper
1694 // friend class (or template thereof) declaration.
Alexey Bataevee6507d2013-11-18 08:17:37 +00001695 SkipUntil(tok::semi, StopBeforeMatch);
John McCallfaf5fb42010-08-26 23:41:50 +00001696 TUK = Sema::TUK_Friend;
Douglas Gregor3dad8422009-09-26 06:47:28 +00001697 } else {
1698 // Okay, this is a class definition.
John McCallfaf5fb42010-08-26 23:41:50 +00001699 TUK = Sema::TUK_Definition;
Douglas Gregor3dad8422009-09-26 06:47:28 +00001700 }
Richard Smith434516c2013-02-22 06:46:23 +00001701 } else if (isCXX11FinalKeyword() && (NextToken().is(tok::l_square) ||
1702 NextToken().is(tok::kw_alignas))) {
Michael Han9407e502012-11-26 22:54:45 +00001703 // We can't tell if this is a definition or reference
1704 // until we skipped the 'final' and C++11 attribute specifiers.
1705 TentativeParsingAction PA(*this);
1706
1707 // Skip the 'final' keyword.
1708 ConsumeToken();
1709
1710 // Skip C++11 attribute specifiers.
1711 while (true) {
1712 if (Tok.is(tok::l_square) && NextToken().is(tok::l_square)) {
1713 ConsumeBracket();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001714 if (!SkipUntil(tok::r_square, StopAtSemi))
Michael Han9407e502012-11-26 22:54:45 +00001715 break;
Richard Smith434516c2013-02-22 06:46:23 +00001716 } else if (Tok.is(tok::kw_alignas) && NextToken().is(tok::l_paren)) {
Michael Han9407e502012-11-26 22:54:45 +00001717 ConsumeToken();
1718 ConsumeParen();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001719 if (!SkipUntil(tok::r_paren, StopAtSemi))
Michael Han9407e502012-11-26 22:54:45 +00001720 break;
1721 } else {
1722 break;
1723 }
1724 }
1725
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001726 if (Tok.isOneOf(tok::l_brace, tok::colon))
Michael Han9407e502012-11-26 22:54:45 +00001727 TUK = Sema::TUK_Definition;
1728 else
1729 TUK = Sema::TUK_Reference;
1730
1731 PA.Revert();
Richard Smith649c7b062014-01-08 00:56:48 +00001732 } else if (!isTypeSpecifier(DSC) &&
Richard Smith369b9f92012-06-25 21:37:02 +00001733 (Tok.is(tok::semi) ||
Richard Smith200f47c2012-07-02 19:14:01 +00001734 (Tok.isAtStartOfLine() && !isValidAfterTypeSpecifier(false)))) {
John McCallfaf5fb42010-08-26 23:41:50 +00001735 TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
Joao Matose9a3ed42012-08-31 22:18:20 +00001736 if (Tok.isNot(tok::semi)) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001737 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
Joao Matose9a3ed42012-08-31 22:18:20 +00001738 // A semicolon was missing after this declaration. Diagnose and recover.
Alp Toker383d2c42014-01-01 03:08:43 +00001739 ExpectAndConsume(tok::semi, diag::err_expected_after,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001740 DeclSpec::getSpecifierName(TagType, PPol));
Ilya Biryukov929af672019-05-17 09:32:05 +00001741 PP.EnterToken(Tok, /*IsReinject*/true);
Joao Matose9a3ed42012-08-31 22:18:20 +00001742 Tok.setKind(tok::semi);
1743 }
Richard Smith369b9f92012-06-25 21:37:02 +00001744 } else
John McCallfaf5fb42010-08-26 23:41:50 +00001745 TUK = Sema::TUK_Reference;
Douglas Gregor556877c2008-04-13 21:30:24 +00001746
Michael Han9407e502012-11-26 22:54:45 +00001747 // Forbid misplaced attributes. In cases of a reference, we pass attributes
1748 // to caller to handle.
Michael Han309af292013-01-07 16:57:11 +00001749 if (TUK != Sema::TUK_Reference) {
1750 // If this is not a reference, then the only possible
1751 // valid place for C++11 attributes to appear here
1752 // is between class-key and class-name. If there are
1753 // any attributes after class-name, we try a fixit to move
1754 // them to the right place.
1755 SourceRange AttrRange = Attributes.Range;
1756 if (AttrRange.isValid()) {
1757 Diag(AttrRange.getBegin(), diag::err_attributes_not_allowed)
1758 << AttrRange
1759 << FixItHint::CreateInsertionFromRange(AttrFixitLoc,
1760 CharSourceRange(AttrRange, true))
1761 << FixItHint::CreateRemoval(AttrRange);
1762
1763 // Recover by adding misplaced attributes to the attribute list
1764 // of the class so they can be applied on the class later.
1765 attrs.takeAllFrom(Attributes);
1766 }
1767 }
Michael Han9407e502012-11-26 22:54:45 +00001768
John McCall6347b682012-05-07 06:16:58 +00001769 // If this is an elaborated type specifier, and we delayed
1770 // diagnostics before, just merge them into the current pool.
1771 if (shouldDelayDiagsInTag) {
1772 diagsFromTag.done();
1773 if (TUK == Sema::TUK_Reference)
1774 diagsFromTag.redelay();
1775 }
1776
John McCall413021a2010-07-30 06:26:29 +00001777 if (!Name && !TemplateId && (DS.getTypeSpecType() == DeclSpec::TST_error ||
John McCallfaf5fb42010-08-26 23:41:50 +00001778 TUK != Sema::TUK_Definition)) {
John McCall413021a2010-07-30 06:26:29 +00001779 if (DS.getTypeSpecType() != DeclSpec::TST_error) {
1780 // We have a declaration or reference to an anonymous class.
1781 Diag(StartLoc, diag::err_anon_type_definition)
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001782 << DeclSpec::getSpecifierName(TagType, Policy);
John McCall413021a2010-07-30 06:26:29 +00001783 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001784
David Majnemer3252fd02013-12-05 01:36:53 +00001785 // If we are parsing a definition and stop at a base-clause, continue on
1786 // until the semicolon. Continuing from the comma will just trick us into
1787 // thinking we are seeing a variable declaration.
1788 if (TUK == Sema::TUK_Definition && Tok.is(tok::colon))
1789 SkipUntil(tok::semi, StopBeforeMatch);
1790 else
1791 SkipUntil(tok::comma, StopAtSemi);
Douglas Gregor556877c2008-04-13 21:30:24 +00001792 return;
1793 }
1794
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001795 // Create the tag portion of the class or class template.
John McCall48871652010-08-21 09:40:31 +00001796 DeclResult TagOrTempResult = true; // invalid
1797 TypeResult TypeResult = true; // invalid
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001798
Douglas Gregord6ab8742009-05-28 23:31:59 +00001799 bool Owned = false;
Richard Smithd9ba2242015-05-07 03:54:19 +00001800 Sema::SkipBodyInfo SkipBody;
John McCall06f6fe8d2009-09-04 01:14:41 +00001801 if (TemplateId) {
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001802 // Explicit specialization, class template partial specialization,
1803 // or explicit instantiation.
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00001804 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregor7f741122009-02-25 19:37:18 +00001805 TemplateId->NumArgs);
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001806 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
John McCallfaf5fb42010-08-26 23:41:50 +00001807 TUK == Sema::TUK_Declaration) {
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001808 // This is an explicit instantiation of a class template.
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001809 ProhibitAttributes(attrs);
1810
Erich Keanec480f302018-07-12 21:09:05 +00001811 TagOrTempResult = Actions.ActOnExplicitInstantiation(
1812 getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc,
1813 TagType, StartLoc, SS, TemplateId->Template,
1814 TemplateId->TemplateNameLoc, TemplateId->LAngleLoc, TemplateArgsPtr,
1815 TemplateId->RAngleLoc, attrs);
John McCallb7c5c272010-04-14 00:24:33 +00001816
Erich Keanec480f302018-07-12 21:09:05 +00001817 // Friend template-ids are treated as references unless
1818 // they have template headers, in which case they're ill-formed
1819 // (FIXME: "template <class T> friend class A<T>::B<int>;").
1820 // We diagnose this error in ActOnClassTemplateSpecialization.
John McCallfaf5fb42010-08-26 23:41:50 +00001821 } else if (TUK == Sema::TUK_Reference ||
1822 (TUK == Sema::TUK_Friend &&
John McCallb7c5c272010-04-14 00:24:33 +00001823 TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate)) {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001824 ProhibitAttributes(attrs);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00001825 TypeResult = Actions.ActOnTagTemplateIdType(TUK, TagType, StartLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00001826 TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00001827 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00001828 TemplateId->Template,
1829 TemplateId->TemplateNameLoc,
1830 TemplateId->LAngleLoc,
1831 TemplateArgsPtr,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00001832 TemplateId->RAngleLoc);
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001833 } else {
1834 // This is an explicit specialization or a class template
1835 // partial specialization.
1836 TemplateParameterLists FakedParamLists;
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001837 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1838 // This looks like an explicit instantiation, because we have
1839 // something like
1840 //
1841 // template class Foo<X>
1842 //
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001843 // but it actually has a definition. Most likely, this was
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001844 // meant to be an explicit specialization, but the user forgot
1845 // the '<>' after 'template'.
Richard Smith003c5e12013-11-08 19:03:29 +00001846 // It this is friend declaration however, since it cannot have a
1847 // template header, it is most likely that the user meant to
1848 // remove the 'template' keyword.
Larisse Voufob9bbaba2013-06-22 13:56:11 +00001849 assert((TUK == Sema::TUK_Definition || TUK == Sema::TUK_Friend) &&
Richard Smith003c5e12013-11-08 19:03:29 +00001850 "Expected a definition here");
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001851
Richard Smith003c5e12013-11-08 19:03:29 +00001852 if (TUK == Sema::TUK_Friend) {
1853 Diag(DS.getFriendSpecLoc(), diag::err_friend_explicit_instantiation);
Craig Topper161e4db2014-05-21 06:02:52 +00001854 TemplateParams = nullptr;
Richard Smith003c5e12013-11-08 19:03:29 +00001855 } else {
1856 SourceLocation LAngleLoc =
1857 PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
1858 Diag(TemplateId->TemplateNameLoc,
1859 diag::err_explicit_instantiation_with_definition)
1860 << SourceRange(TemplateInfo.TemplateLoc)
1861 << FixItHint::CreateInsertion(LAngleLoc, "<>");
1862
1863 // Create a fake template parameter list that contains only
1864 // "template<>", so that we treat this construct as a class
1865 // template specialization.
1866 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
Craig Topper96225a52015-12-24 23:58:25 +00001867 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
Hubert Tongf608c052016-04-29 18:05:37 +00001868 LAngleLoc, nullptr));
Richard Smith003c5e12013-11-08 19:03:29 +00001869 TemplateParams = &FakedParamLists;
1870 }
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001871 }
1872
1873 // Build the class template specialization.
Richard Smith4b55a9c2014-04-17 03:29:33 +00001874 TagOrTempResult = Actions.ActOnClassTemplateSpecialization(
1875 getCurScope(), TagType, TUK, StartLoc, DS.getModulePrivateSpecLoc(),
Erich Keanec480f302018-07-12 21:09:05 +00001876 *TemplateId, attrs,
Craig Topper161e4db2014-05-21 06:02:52 +00001877 MultiTemplateParamsArg(TemplateParams ? &(*TemplateParams)[0]
1878 : nullptr,
Richard Smithc7e6ff02015-05-18 20:36:47 +00001879 TemplateParams ? TemplateParams->size() : 0),
1880 &SkipBody);
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001881 }
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001882 } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
John McCallfaf5fb42010-08-26 23:41:50 +00001883 TUK == Sema::TUK_Declaration) {
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001884 // Explicit instantiation of a member of a class template
1885 // specialization, e.g.,
1886 //
1887 // template struct Outer<int>::Inner;
1888 //
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001889 ProhibitAttributes(attrs);
1890
Erich Keanec480f302018-07-12 21:09:05 +00001891 TagOrTempResult = Actions.ActOnExplicitInstantiation(
1892 getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc,
1893 TagType, StartLoc, SS, Name, NameLoc, attrs);
John McCallace48cd2010-10-19 01:40:49 +00001894 } else if (TUK == Sema::TUK_Friend &&
1895 TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate) {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001896 ProhibitAttributes(attrs);
1897
Erich Keanec480f302018-07-12 21:09:05 +00001898 TagOrTempResult = Actions.ActOnTemplatedFriendTag(
1899 getCurScope(), DS.getFriendSpecLoc(), TagType, StartLoc, SS, Name,
1900 NameLoc, attrs,
1901 MultiTemplateParamsArg(TemplateParams ? &(*TemplateParams)[0] : nullptr,
1902 TemplateParams ? TemplateParams->size() : 0));
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001903 } else {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001904 if (TUK != Sema::TUK_Declaration && TUK != Sema::TUK_Definition)
1905 ProhibitAttributes(attrs);
Richard Smith003c5e12013-11-08 19:03:29 +00001906
Larisse Voufo725de3e2013-06-21 00:08:46 +00001907 if (TUK == Sema::TUK_Definition &&
1908 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1909 // If the declarator-id is not a template-id, issue a diagnostic and
1910 // recover by ignoring the 'template' keyword.
1911 Diag(Tok, diag::err_template_defn_explicit_instantiation)
1912 << 1 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
Craig Topper161e4db2014-05-21 06:02:52 +00001913 TemplateParams = nullptr;
Larisse Voufo725de3e2013-06-21 00:08:46 +00001914 }
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001915
John McCall7f41d982009-09-11 04:59:25 +00001916 bool IsDependent = false;
1917
John McCall32723e92010-10-19 18:40:57 +00001918 // Don't pass down template parameter lists if this is just a tag
1919 // reference. For example, we don't need the template parameters here:
1920 // template <class T> class A *makeA(T t);
1921 MultiTemplateParamsArg TParams;
1922 if (TUK != Sema::TUK_Reference && TemplateParams)
1923 TParams =
1924 MultiTemplateParamsArg(&(*TemplateParams)[0], TemplateParams->size());
1925
Nico Weber32a0fc72016-09-03 03:01:32 +00001926 stripTypeAttributesOffDeclSpec(attrs, DS, TUK);
David Majnemer936b4112015-04-19 07:53:29 +00001927
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001928 // Declaration or definition of a class type
Faisal Vali7db85c52017-12-31 00:06:40 +00001929 TagOrTempResult = Actions.ActOnTag(
Erich Keanec480f302018-07-12 21:09:05 +00001930 getCurScope(), TagType, TUK, StartLoc, SS, Name, NameLoc, attrs, AS,
1931 DS.getModulePrivateSpecLoc(), TParams, Owned, IsDependent,
1932 SourceLocation(), false, clang::TypeResult(),
Faisal Vali7db85c52017-12-31 00:06:40 +00001933 DSC == DeclSpecContext::DSC_type_specifier,
1934 DSC == DeclSpecContext::DSC_template_param ||
1935 DSC == DeclSpecContext::DSC_template_type_arg,
1936 &SkipBody);
John McCall7f41d982009-09-11 04:59:25 +00001937
1938 // If ActOnTag said the type was dependent, try again with the
1939 // less common call.
John McCallace48cd2010-10-19 01:40:49 +00001940 if (IsDependent) {
1941 assert(TUK == Sema::TUK_Reference || TUK == Sema::TUK_Friend);
Douglas Gregor0be31a22010-07-02 17:43:08 +00001942 TypeResult = Actions.ActOnDependentTag(getCurScope(), TagType, TUK,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001943 SS, Name, StartLoc, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +00001944 }
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001945 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001946
Douglas Gregor556877c2008-04-13 21:30:24 +00001947 // If there is a body, parse it and inform the actions module.
John McCallfaf5fb42010-08-26 23:41:50 +00001948 if (TUK == Sema::TUK_Definition) {
John McCall2d814c32009-12-19 21:48:58 +00001949 assert(Tok.is(tok::l_brace) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00001950 (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
Richard Smith89645bc2013-01-02 12:01:23 +00001951 isCXX11FinalKeyword());
Richard Smithd9ba2242015-05-07 03:54:19 +00001952 if (SkipBody.ShouldSkip)
Richard Smith65ebb4a2015-03-26 04:09:53 +00001953 SkipCXXMemberSpecification(StartLoc, AttrFixitLoc, TagType,
1954 TagOrTempResult.get());
1955 else if (getLangOpts().CPlusPlus)
Michael Han309af292013-01-07 16:57:11 +00001956 ParseCXXMemberSpecification(StartLoc, AttrFixitLoc, attrs, TagType,
1957 TagOrTempResult.get());
Bruno Cardoso Lopesdf0ee342017-07-01 00:06:47 +00001958 else {
1959 Decl *D =
1960 SkipBody.CheckSameAsPrevious ? SkipBody.New : TagOrTempResult.get();
1961 // Parse the definition body.
1962 ParseStructUnionBody(StartLoc, TagType, D);
1963 if (SkipBody.CheckSameAsPrevious &&
1964 !Actions.ActOnDuplicateDefinition(DS, TagOrTempResult.get(),
1965 SkipBody)) {
1966 DS.SetTypeSpecError();
1967 return;
1968 }
1969 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001970 }
1971
Erich Keane2fe684b2017-02-28 20:44:39 +00001972 if (!TagOrTempResult.isInvalid())
Hiroshi Inoue939d9322017-06-30 05:40:31 +00001973 // Delayed processing of attributes.
Erich Keanec480f302018-07-12 21:09:05 +00001974 Actions.ProcessDeclAttributeDelayed(TagOrTempResult.get(), attrs);
Erich Keane2fe684b2017-02-28 20:44:39 +00001975
Craig Topper161e4db2014-05-21 06:02:52 +00001976 const char *PrevSpec = nullptr;
John McCallba7bf592010-08-24 05:47:05 +00001977 unsigned DiagID;
1978 bool Result;
John McCall7f41d982009-09-11 04:59:25 +00001979 if (!TypeResult.isInvalid()) {
Abramo Bagnara9875a3c2011-03-16 20:16:18 +00001980 Result = DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
1981 NameLoc.isValid() ? NameLoc : StartLoc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001982 PrevSpec, DiagID, TypeResult.get(), Policy);
John McCall7f41d982009-09-11 04:59:25 +00001983 } else if (!TagOrTempResult.isInvalid()) {
Abramo Bagnara9875a3c2011-03-16 20:16:18 +00001984 Result = DS.SetTypeSpecType(TagType, StartLoc,
1985 NameLoc.isValid() ? NameLoc : StartLoc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001986 PrevSpec, DiagID, TagOrTempResult.get(), Owned,
1987 Policy);
John McCall7f41d982009-09-11 04:59:25 +00001988 } else {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001989 DS.SetTypeSpecError();
Anders Carlssonf83c9fa2009-05-11 22:27:47 +00001990 return;
1991 }
Mike Stump11289f42009-09-09 15:08:12 +00001992
John McCallba7bf592010-08-24 05:47:05 +00001993 if (Result)
John McCall49bfce42009-08-03 20:12:06 +00001994 Diag(StartLoc, DiagID) << PrevSpec;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001995
Chris Lattnercf251412010-02-02 01:23:29 +00001996 // At this point, we've successfully parsed a class-specifier in 'definition'
1997 // form (e.g. "struct foo { int x; }". While we could just return here, we're
1998 // going to look at what comes after it to improve error recovery. If an
1999 // impossible token occurs next, we assume that the programmer forgot a ; at
2000 // the end of the declaration and recover that way.
2001 //
Richard Smith369b9f92012-06-25 21:37:02 +00002002 // Also enforce C++ [temp]p3:
2003 // In a template-declaration which defines a class, no declarator
2004 // is permitted.
Richard Smith843f18f2014-08-13 02:13:15 +00002005 //
2006 // After a type-specifier, we don't expect a semicolon. This only happens in
2007 // C, since definitions are not permitted in this context in C++.
Joao Matose9a3ed42012-08-31 22:18:20 +00002008 if (TUK == Sema::TUK_Definition &&
Richard Smith843f18f2014-08-13 02:13:15 +00002009 (getLangOpts().CPlusPlus || !isTypeSpecifier(DSC)) &&
Joao Matose9a3ed42012-08-31 22:18:20 +00002010 (TemplateInfo.Kind || !isValidAfterTypeSpecifier(false))) {
Argyrios Kyrtzidise6f69132012-12-17 20:10:43 +00002011 if (Tok.isNot(tok::semi)) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002012 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
Alp Toker383d2c42014-01-01 03:08:43 +00002013 ExpectAndConsume(tok::semi, diag::err_expected_after,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002014 DeclSpec::getSpecifierName(TagType, PPol));
Argyrios Kyrtzidise6f69132012-12-17 20:10:43 +00002015 // Push this token back into the preprocessor and change our current token
2016 // to ';' so that the rest of the code recovers as though there were an
2017 // ';' after the definition.
Ilya Biryukov929af672019-05-17 09:32:05 +00002018 PP.EnterToken(Tok, /*IsReinject=*/true);
Argyrios Kyrtzidise6f69132012-12-17 20:10:43 +00002019 Tok.setKind(tok::semi);
2020 }
Chris Lattnercf251412010-02-02 01:23:29 +00002021 }
Douglas Gregor556877c2008-04-13 21:30:24 +00002022}
2023
Mike Stump11289f42009-09-09 15:08:12 +00002024/// ParseBaseClause - Parse the base-clause of a C++ class [C++ class.derived].
Douglas Gregor556877c2008-04-13 21:30:24 +00002025///
2026/// base-clause : [C++ class.derived]
2027/// ':' base-specifier-list
2028/// base-specifier-list:
2029/// base-specifier '...'[opt]
2030/// base-specifier-list ',' base-specifier '...'[opt]
John McCall48871652010-08-21 09:40:31 +00002031void Parser::ParseBaseClause(Decl *ClassDecl) {
Douglas Gregor556877c2008-04-13 21:30:24 +00002032 assert(Tok.is(tok::colon) && "Not a base clause");
2033 ConsumeToken();
2034
Douglas Gregor29a92472008-10-22 17:49:05 +00002035 // Build up an array of parsed base specifiers.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002036 SmallVector<CXXBaseSpecifier *, 8> BaseInfo;
Douglas Gregor29a92472008-10-22 17:49:05 +00002037
Douglas Gregor556877c2008-04-13 21:30:24 +00002038 while (true) {
2039 // Parse a base-specifier.
Douglas Gregor29a92472008-10-22 17:49:05 +00002040 BaseResult Result = ParseBaseSpecifier(ClassDecl);
Douglas Gregorf8298252009-01-26 22:44:13 +00002041 if (Result.isInvalid()) {
Douglas Gregor556877c2008-04-13 21:30:24 +00002042 // Skip the rest of this base specifier, up until the comma or
2043 // opening brace.
Alexey Bataevee6507d2013-11-18 08:17:37 +00002044 SkipUntil(tok::comma, tok::l_brace, StopAtSemi | StopBeforeMatch);
Douglas Gregor29a92472008-10-22 17:49:05 +00002045 } else {
2046 // Add this to our array of base specifiers.
Douglas Gregorf8298252009-01-26 22:44:13 +00002047 BaseInfo.push_back(Result.get());
Douglas Gregor556877c2008-04-13 21:30:24 +00002048 }
2049
2050 // If the next token is a comma, consume it and keep reading
2051 // base-specifiers.
Alp Toker97650562014-01-10 11:19:30 +00002052 if (!TryConsumeToken(tok::comma))
2053 break;
Douglas Gregor556877c2008-04-13 21:30:24 +00002054 }
Douglas Gregor29a92472008-10-22 17:49:05 +00002055
2056 // Attach the base specifiers
Craig Topperaa700cb2015-12-27 21:55:19 +00002057 Actions.ActOnBaseSpecifiers(ClassDecl, BaseInfo);
Douglas Gregor556877c2008-04-13 21:30:24 +00002058}
2059
2060/// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is
2061/// one entry in the base class list of a class specifier, for example:
2062/// class foo : public bar, virtual private baz {
2063/// 'public bar' and 'virtual private baz' are each base-specifiers.
2064///
2065/// base-specifier: [C++ class.derived]
Richard Smith4c96e992013-02-19 23:47:15 +00002066/// attribute-specifier-seq[opt] base-type-specifier
2067/// attribute-specifier-seq[opt] 'virtual' access-specifier[opt]
2068/// base-type-specifier
2069/// attribute-specifier-seq[opt] access-specifier 'virtual'[opt]
2070/// base-type-specifier
Craig Topper9ad7e262014-10-31 06:57:07 +00002071BaseResult Parser::ParseBaseSpecifier(Decl *ClassDecl) {
Douglas Gregor556877c2008-04-13 21:30:24 +00002072 bool IsVirtual = false;
2073 SourceLocation StartLoc = Tok.getLocation();
2074
Richard Smith4c96e992013-02-19 23:47:15 +00002075 ParsedAttributesWithRange Attributes(AttrFactory);
2076 MaybeParseCXX11Attributes(Attributes);
2077
Douglas Gregor556877c2008-04-13 21:30:24 +00002078 // Parse the 'virtual' keyword.
Alp Toker97650562014-01-10 11:19:30 +00002079 if (TryConsumeToken(tok::kw_virtual))
Douglas Gregor556877c2008-04-13 21:30:24 +00002080 IsVirtual = true;
Douglas Gregor556877c2008-04-13 21:30:24 +00002081
Richard Smith4c96e992013-02-19 23:47:15 +00002082 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2083
Douglas Gregor556877c2008-04-13 21:30:24 +00002084 // Parse an (optional) access specifier.
2085 AccessSpecifier Access = getAccessSpecifierIfPresent();
John McCall553c0792010-01-23 00:46:32 +00002086 if (Access != AS_none)
Douglas Gregor556877c2008-04-13 21:30:24 +00002087 ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +00002088
Richard Smith4c96e992013-02-19 23:47:15 +00002089 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2090
Douglas Gregor556877c2008-04-13 21:30:24 +00002091 // Parse the 'virtual' keyword (again!), in case it came after the
2092 // access specifier.
2093 if (Tok.is(tok::kw_virtual)) {
2094 SourceLocation VirtualLoc = ConsumeToken();
2095 if (IsVirtual) {
2096 // Complain about duplicate 'virtual'
Chris Lattner6d29c102008-11-18 07:48:38 +00002097 Diag(VirtualLoc, diag::err_dup_virtual)
Douglas Gregora771f462010-03-31 17:46:05 +00002098 << FixItHint::CreateRemoval(VirtualLoc);
Douglas Gregor556877c2008-04-13 21:30:24 +00002099 }
2100
2101 IsVirtual = true;
2102 }
2103
Richard Smith4c96e992013-02-19 23:47:15 +00002104 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2105
Douglas Gregor831c93f2008-11-05 20:51:48 +00002106 // Parse the class-name.
David Majnemer51fd8a02015-07-22 23:46:18 +00002107
2108 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
2109 // implementation for VS2013 uses _Atomic as an identifier for one of the
2110 // classes in <atomic>. Treat '_Atomic' to be an identifier when we are
2111 // parsing the class-name for a base specifier.
2112 if (getLangOpts().MSVCCompat && Tok.is(tok::kw__Atomic) &&
2113 NextToken().is(tok::less))
2114 Tok.setKind(tok::identifier);
2115
Douglas Gregord54dfb82009-02-25 23:52:28 +00002116 SourceLocation EndLocation;
David Blaikie1cd50022011-10-25 17:10:12 +00002117 SourceLocation BaseLoc;
2118 TypeResult BaseType = ParseBaseTypeSpecifier(BaseLoc, EndLocation);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00002119 if (BaseType.isInvalid())
Douglas Gregor831c93f2008-11-05 20:51:48 +00002120 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002121
Fangrui Song6907ce22018-07-30 19:24:48 +00002122 // Parse the optional ellipsis (for a pack expansion). The ellipsis is
Douglas Gregor752a5952011-01-03 22:36:02 +00002123 // actually part of the base-specifier-list grammar productions, but we
2124 // parse it here for convenience.
2125 SourceLocation EllipsisLoc;
Alp Toker97650562014-01-10 11:19:30 +00002126 TryConsumeToken(tok::ellipsis, EllipsisLoc);
2127
Mike Stump11289f42009-09-09 15:08:12 +00002128 // Find the complete source range for the base-specifier.
Douglas Gregord54dfb82009-02-25 23:52:28 +00002129 SourceRange Range(StartLoc, EndLocation);
Mike Stump11289f42009-09-09 15:08:12 +00002130
Douglas Gregor556877c2008-04-13 21:30:24 +00002131 // Notify semantic analysis that we have parsed a complete
2132 // base-specifier.
Richard Smith4c96e992013-02-19 23:47:15 +00002133 return Actions.ActOnBaseSpecifier(ClassDecl, Range, Attributes, IsVirtual,
2134 Access, BaseType.get(), BaseLoc,
2135 EllipsisLoc);
Douglas Gregor556877c2008-04-13 21:30:24 +00002136}
2137
2138/// getAccessSpecifierIfPresent - Determine whether the next token is
2139/// a C++ access-specifier.
2140///
2141/// access-specifier: [C++ class.derived]
2142/// 'private'
2143/// 'protected'
2144/// 'public'
Mike Stump11289f42009-09-09 15:08:12 +00002145AccessSpecifier Parser::getAccessSpecifierIfPresent() const {
Douglas Gregor556877c2008-04-13 21:30:24 +00002146 switch (Tok.getKind()) {
2147 default: return AS_none;
2148 case tok::kw_private: return AS_private;
2149 case tok::kw_protected: return AS_protected;
2150 case tok::kw_public: return AS_public;
2151 }
2152}
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002153
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002154/// If the given declarator has any parts for which parsing has to be
Richard Smith0b3a4622014-11-13 20:01:57 +00002155/// delayed, e.g., default arguments or an exception-specification, create a
2156/// late-parsed method declaration record to handle the parsing at the end of
2157/// the class definition.
Douglas Gregor433e0532012-04-16 18:27:27 +00002158void Parser::HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
2159 Decl *ThisDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00002160 DeclaratorChunk::FunctionTypeInfo &FTI
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002161 = DeclaratorInfo.getFunctionTypeInfo();
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002162 // If there was a late-parsed exception-specification, we'll need a
2163 // late parse
2164 bool NeedLateParse = FTI.getExceptionSpecType() == EST_Unparsed;
Douglas Gregor433e0532012-04-16 18:27:27 +00002165
Nathan Sidwell5bb231c2015-02-19 14:03:22 +00002166 if (!NeedLateParse) {
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002167 // Look ahead to see if there are any default args
Nathan Sidwell5bb231c2015-02-19 14:03:22 +00002168 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx) {
2169 auto Param = cast<ParmVarDecl>(FTI.Params[ParamIdx].Param);
2170 if (Param->hasUnparsedDefaultArg()) {
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002171 NeedLateParse = true;
2172 break;
2173 }
Nathan Sidwell5bb231c2015-02-19 14:03:22 +00002174 }
2175 }
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002176
2177 if (NeedLateParse) {
Richard Smith0b3a4622014-11-13 20:01:57 +00002178 // Push this method onto the stack of late-parsed method
2179 // declarations.
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002180 auto LateMethod = new LateParsedMethodDeclaration(this, ThisDecl);
Richard Smith0b3a4622014-11-13 20:01:57 +00002181 getCurrentClass().LateParsedDeclarations.push_back(LateMethod);
2182 LateMethod->TemplateScope = getCurScope()->isTemplateParamScope();
2183
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002184 // Stash the exception-specification tokens in the late-pased method.
Richard Smith0b3a4622014-11-13 20:01:57 +00002185 LateMethod->ExceptionSpecTokens = FTI.ExceptionSpecTokens;
Hans Wennborgdcfba332015-10-06 23:40:43 +00002186 FTI.ExceptionSpecTokens = nullptr;
Richard Smith0b3a4622014-11-13 20:01:57 +00002187
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002188 // Push tokens for each parameter. Those that do not have
2189 // defaults will be NULL.
Richard Smith0b3a4622014-11-13 20:01:57 +00002190 LateMethod->DefaultArgs.reserve(FTI.NumParams);
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002191 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx)
Alp Tokerc5350722014-02-26 22:27:52 +00002192 LateMethod->DefaultArgs.push_back(LateParsedDefaultArgument(
Malcolm Parsonsca9d8342016-11-17 21:00:09 +00002193 FTI.Params[ParamIdx].Param,
2194 std::move(FTI.Params[ParamIdx].DefaultArgTokens)));
Eli Friedman3af2a772009-07-22 21:45:50 +00002195 }
2196}
2197
Richard Smith89645bc2013-01-02 12:01:23 +00002198/// isCXX11VirtSpecifier - Determine whether the given token is a C++11
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002199/// virt-specifier.
2200///
2201/// virt-specifier:
2202/// override
2203/// final
Andrey Bokhanko276055b2016-07-29 10:42:48 +00002204/// __final
Richard Smith89645bc2013-01-02 12:01:23 +00002205VirtSpecifiers::Specifier Parser::isCXX11VirtSpecifier(const Token &Tok) const {
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002206 if (!getLangOpts().CPlusPlus || Tok.isNot(tok::identifier))
Anders Carlsson4b63d0e2011-01-22 16:56:46 +00002207 return VirtSpecifiers::VS_None;
2208
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002209 IdentifierInfo *II = Tok.getIdentifierInfo();
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002210
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002211 // Initialize the contextual keywords.
2212 if (!Ident_final) {
2213 Ident_final = &PP.getIdentifierTable().get("final");
Andrey Bokhanko276055b2016-07-29 10:42:48 +00002214 if (getLangOpts().GNUKeywords)
2215 Ident_GNU_final = &PP.getIdentifierTable().get("__final");
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002216 if (getLangOpts().MicrosoftExt)
2217 Ident_sealed = &PP.getIdentifierTable().get("sealed");
2218 Ident_override = &PP.getIdentifierTable().get("override");
Anders Carlsson56104902011-01-17 03:05:47 +00002219 }
2220
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002221 if (II == Ident_override)
2222 return VirtSpecifiers::VS_Override;
2223
2224 if (II == Ident_sealed)
2225 return VirtSpecifiers::VS_Sealed;
2226
2227 if (II == Ident_final)
2228 return VirtSpecifiers::VS_Final;
2229
Andrey Bokhanko276055b2016-07-29 10:42:48 +00002230 if (II == Ident_GNU_final)
2231 return VirtSpecifiers::VS_GNU_Final;
2232
Anders Carlsson56104902011-01-17 03:05:47 +00002233 return VirtSpecifiers::VS_None;
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002234}
2235
Richard Smith89645bc2013-01-02 12:01:23 +00002236/// ParseOptionalCXX11VirtSpecifierSeq - Parse a virt-specifier-seq.
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002237///
2238/// virt-specifier-seq:
2239/// virt-specifier
2240/// virt-specifier-seq virt-specifier
Richard Smith89645bc2013-01-02 12:01:23 +00002241void Parser::ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS,
Richard Smith3d1a94c2014-08-12 00:22:39 +00002242 bool IsInterface,
2243 SourceLocation FriendLoc) {
Anders Carlsson56104902011-01-17 03:05:47 +00002244 while (true) {
Richard Smith89645bc2013-01-02 12:01:23 +00002245 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
Anders Carlsson56104902011-01-17 03:05:47 +00002246 if (Specifier == VirtSpecifiers::VS_None)
2247 return;
2248
Richard Smith3d1a94c2014-08-12 00:22:39 +00002249 if (FriendLoc.isValid()) {
2250 Diag(Tok.getLocation(), diag::err_friend_decl_spec)
2251 << VirtSpecifiers::getSpecifierName(Specifier)
2252 << FixItHint::CreateRemoval(Tok.getLocation())
2253 << SourceRange(FriendLoc, FriendLoc);
2254 ConsumeToken();
2255 continue;
2256 }
2257
Anders Carlsson56104902011-01-17 03:05:47 +00002258 // C++ [class.mem]p8:
2259 // A virt-specifier-seq shall contain at most one of each virt-specifier.
Craig Topper161e4db2014-05-21 06:02:52 +00002260 const char *PrevSpec = nullptr;
Anders Carlssonf2ca3892011-01-22 15:58:16 +00002261 if (VS.SetSpecifier(Specifier, Tok.getLocation(), PrevSpec))
Anders Carlsson56104902011-01-17 03:05:47 +00002262 Diag(Tok.getLocation(), diag::err_duplicate_virt_specifier)
2263 << PrevSpec
2264 << FixItHint::CreateRemoval(Tok.getLocation());
2265
David Majnemera5433082013-10-18 00:33:31 +00002266 if (IsInterface && (Specifier == VirtSpecifiers::VS_Final ||
2267 Specifier == VirtSpecifiers::VS_Sealed)) {
John McCalldb632ac2012-09-25 07:32:39 +00002268 Diag(Tok.getLocation(), diag::err_override_control_interface)
2269 << VirtSpecifiers::getSpecifierName(Specifier);
David Majnemera5433082013-10-18 00:33:31 +00002270 } else if (Specifier == VirtSpecifiers::VS_Sealed) {
2271 Diag(Tok.getLocation(), diag::ext_ms_sealed_keyword);
Andrey Bokhanko276055b2016-07-29 10:42:48 +00002272 } else if (Specifier == VirtSpecifiers::VS_GNU_Final) {
2273 Diag(Tok.getLocation(), diag::ext_warn_gnu_final);
John McCalldb632ac2012-09-25 07:32:39 +00002274 } else {
David Majnemera5433082013-10-18 00:33:31 +00002275 Diag(Tok.getLocation(),
2276 getLangOpts().CPlusPlus11
2277 ? diag::warn_cxx98_compat_override_control_keyword
2278 : diag::ext_override_control_keyword)
2279 << VirtSpecifiers::getSpecifierName(Specifier);
John McCalldb632ac2012-09-25 07:32:39 +00002280 }
Anders Carlsson56104902011-01-17 03:05:47 +00002281 ConsumeToken();
2282 }
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002283}
2284
Richard Smith89645bc2013-01-02 12:01:23 +00002285/// isCXX11FinalKeyword - Determine whether the next token is a C++11
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002286/// 'final' or Microsoft 'sealed' contextual keyword.
Richard Smith89645bc2013-01-02 12:01:23 +00002287bool Parser::isCXX11FinalKeyword() const {
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002288 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
2289 return Specifier == VirtSpecifiers::VS_Final ||
Fangrui Song6907ce22018-07-30 19:24:48 +00002290 Specifier == VirtSpecifiers::VS_GNU_Final ||
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002291 Specifier == VirtSpecifiers::VS_Sealed;
Anders Carlsson4b63d0e2011-01-22 16:56:46 +00002292}
2293
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002294/// Parse a C++ member-declarator up to, but not including, the optional
Richard Smith72553fc2014-01-23 23:53:27 +00002295/// brace-or-equal-initializer or pure-specifier.
Nico Weberd89e6f72015-01-16 19:34:13 +00002296bool Parser::ParseCXXMemberDeclaratorBeforeInitializer(
Richard Smith72553fc2014-01-23 23:53:27 +00002297 Declarator &DeclaratorInfo, VirtSpecifiers &VS, ExprResult &BitfieldSize,
2298 LateParsedAttrList &LateParsedAttrs) {
2299 // member-declarator:
2300 // declarator pure-specifier[opt]
2301 // declarator brace-or-equal-initializer[opt]
2302 // identifier[opt] ':' constant-expression
Serge Pavlov458ea762014-07-16 05:16:52 +00002303 if (Tok.isNot(tok::colon))
Richard Smith72553fc2014-01-23 23:53:27 +00002304 ParseDeclarator(DeclaratorInfo);
Richard Smith3d1a94c2014-08-12 00:22:39 +00002305 else
2306 DeclaratorInfo.SetIdentifier(nullptr, Tok.getLocation());
Richard Smith72553fc2014-01-23 23:53:27 +00002307
2308 if (!DeclaratorInfo.isFunctionDeclarator() && TryConsumeToken(tok::colon)) {
Richard Smith3d1a94c2014-08-12 00:22:39 +00002309 assert(DeclaratorInfo.isPastIdentifier() &&
2310 "don't know where identifier would go yet?");
Richard Smith72553fc2014-01-23 23:53:27 +00002311 BitfieldSize = ParseConstantExpression();
2312 if (BitfieldSize.isInvalid())
2313 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002314 } else {
Richard Smith3d1a94c2014-08-12 00:22:39 +00002315 ParseOptionalCXX11VirtSpecifierSeq(
2316 VS, getCurrentClass().IsInterface,
2317 DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002318 if (!VS.isUnset())
2319 MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo, VS);
2320 }
Richard Smith72553fc2014-01-23 23:53:27 +00002321
2322 // If a simple-asm-expr is present, parse it.
2323 if (Tok.is(tok::kw_asm)) {
2324 SourceLocation Loc;
2325 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
2326 if (AsmLabel.isInvalid())
2327 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2328
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002329 DeclaratorInfo.setAsmLabel(AsmLabel.get());
Richard Smith72553fc2014-01-23 23:53:27 +00002330 DeclaratorInfo.SetRangeEnd(Loc);
2331 }
2332
2333 // If attributes exist after the declarator, but before an '{', parse them.
2334 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
Richard Smith4b5a9492014-01-24 22:34:35 +00002335
2336 // For compatibility with code written to older Clang, also accept a
2337 // virt-specifier *after* the GNU attributes.
Aaron Ballman5d153e32014-08-04 17:03:51 +00002338 if (BitfieldSize.isUnset() && VS.isUnset()) {
Richard Smith3d1a94c2014-08-12 00:22:39 +00002339 ParseOptionalCXX11VirtSpecifierSeq(
2340 VS, getCurrentClass().IsInterface,
2341 DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
Aaron Ballman5d153e32014-08-04 17:03:51 +00002342 if (!VS.isUnset()) {
2343 // If we saw any GNU-style attributes that are known to GCC followed by a
2344 // virt-specifier, issue a GCC-compat warning.
Erich Keanee891aa92018-07-13 15:07:47 +00002345 for (const ParsedAttr &AL : DeclaratorInfo.getAttributes())
Erich Keanec480f302018-07-12 21:09:05 +00002346 if (AL.isKnownToGCC() && !AL.isCXX11Attribute())
2347 Diag(AL.getLoc(), diag::warn_gcc_attribute_location);
2348
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002349 MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo, VS);
Aaron Ballman5d153e32014-08-04 17:03:51 +00002350 }
2351 }
Nico Weberd89e6f72015-01-16 19:34:13 +00002352
2353 // If this has neither a name nor a bit width, something has gone seriously
2354 // wrong. Skip until the semi-colon or }.
2355 if (!DeclaratorInfo.hasName() && BitfieldSize.isUnset()) {
2356 // If so, skip until the semi-colon or a }.
2357 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2358 return true;
2359 }
2360 return false;
Richard Smith72553fc2014-01-23 23:53:27 +00002361}
2362
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002363/// Look for declaration specifiers possibly occurring after C++11
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002364/// virt-specifier-seq and diagnose them.
2365void Parser::MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(
2366 Declarator &D,
2367 VirtSpecifiers &VS) {
2368 DeclSpec DS(AttrFactory);
2369
2370 // GNU-style and C++11 attributes are not allowed here, but they will be
2371 // handled by the caller. Diagnose everything else.
Alex Lorenz8f4d3992017-02-13 23:19:40 +00002372 ParseTypeQualifierListOpt(
2373 DS, AR_NoAttributesParsed, false,
2374 /*IdentifierRequired=*/false, llvm::function_ref<void()>([&]() {
2375 Actions.CodeCompleteFunctionQualifiers(DS, D, &VS);
2376 }));
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002377 D.ExtendWithDeclSpec(DS);
2378
2379 if (D.isFunctionDeclarator()) {
Ehsan Akhgaric07d1e22015-03-25 00:53:33 +00002380 auto &Function = D.getFunctionTypeInfo();
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002381 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
Anastasia Stulovaa9bc4bd2019-01-09 11:25:09 +00002382 auto DeclSpecCheck = [&](DeclSpec::TQ TypeQual, StringRef FixItName,
2383 SourceLocation SpecLoc) {
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002384 FixItHint Insertion;
Anastasia Stulovaa9bc4bd2019-01-09 11:25:09 +00002385 auto &MQ = Function.getOrCreateMethodQualifiers();
2386 if (!(MQ.getTypeQualifiers() & TypeQual)) {
2387 std::string Name(FixItName.data());
2388 Name += " ";
2389 Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), Name);
2390 MQ.SetTypeQual(TypeQual, SpecLoc);
2391 }
2392 Diag(SpecLoc, diag::err_declspec_after_virtspec)
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002393 << FixItName
2394 << VirtSpecifiers::getSpecifierName(VS.getLastSpecifier())
Anastasia Stulovaa9bc4bd2019-01-09 11:25:09 +00002395 << FixItHint::CreateRemoval(SpecLoc) << Insertion;
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002396 };
Anastasia Stulovaa9bc4bd2019-01-09 11:25:09 +00002397 DS.forEachQualifier(DeclSpecCheck);
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002398 }
Ehsan Akhgaric07d1e22015-03-25 00:53:33 +00002399
2400 // Parse ref-qualifiers.
2401 bool RefQualifierIsLValueRef = true;
2402 SourceLocation RefQualifierLoc;
2403 if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc)) {
2404 const char *Name = (RefQualifierIsLValueRef ? "& " : "&& ");
2405 FixItHint Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), Name);
2406 Function.RefQualifierIsLValueRef = RefQualifierIsLValueRef;
2407 Function.RefQualifierLoc = RefQualifierLoc.getRawEncoding();
2408
2409 Diag(RefQualifierLoc, diag::err_declspec_after_virtspec)
2410 << (RefQualifierIsLValueRef ? "&" : "&&")
2411 << VirtSpecifiers::getSpecifierName(VS.getLastSpecifier())
2412 << FixItHint::CreateRemoval(RefQualifierLoc)
2413 << Insertion;
2414 D.SetRangeEnd(RefQualifierLoc);
2415 }
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002416 }
2417}
2418
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002419/// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration.
2420///
2421/// member-declaration:
2422/// decl-specifier-seq[opt] member-declarator-list[opt] ';'
2423/// function-definition ';'[opt]
2424/// ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO]
2425/// using-declaration [TODO]
Anders Carlssonf24fcff62009-03-11 16:27:10 +00002426/// [C++0x] static_assert-declaration
Anders Carlssondfbbdf62009-03-26 00:52:18 +00002427/// template-declaration
Chris Lattnerd19c1c02008-12-18 01:12:00 +00002428/// [GNU] '__extension__' member-declaration
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002429///
2430/// member-declarator-list:
2431/// member-declarator
2432/// member-declarator-list ',' member-declarator
2433///
2434/// member-declarator:
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002435/// declarator virt-specifier-seq[opt] pure-specifier[opt]
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002436/// declarator constant-initializer[opt]
Richard Smith938f40b2011-06-11 17:19:42 +00002437/// [C++11] declarator brace-or-equal-initializer[opt]
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002438/// identifier[opt] ':' constant-expression
2439///
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002440/// virt-specifier-seq:
2441/// virt-specifier
2442/// virt-specifier-seq virt-specifier
2443///
2444/// virt-specifier:
2445/// override
2446/// final
David Majnemera5433082013-10-18 00:33:31 +00002447/// [MS] sealed
Fangrui Song6907ce22018-07-30 19:24:48 +00002448///
Sebastian Redl42e92c42009-04-12 17:16:29 +00002449/// pure-specifier:
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002450/// '= 0'
2451///
2452/// constant-initializer:
2453/// '=' constant-expression
2454///
Alexey Bataev05c25d62015-07-31 08:42:25 +00002455Parser::DeclGroupPtrTy
2456Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS,
Erich Keanec480f302018-07-12 21:09:05 +00002457 ParsedAttributes &AccessAttrs,
John McCall796c2a52010-07-16 08:13:16 +00002458 const ParsedTemplateInfo &TemplateInfo,
2459 ParsingDeclRAIIObject *TemplateDiags) {
Douglas Gregor23c84762011-04-14 17:21:19 +00002460 if (Tok.is(tok::at)) {
Erik Pilkingtonfa983902018-10-30 20:31:30 +00002461 if (getLangOpts().ObjC && NextToken().isObjCAtKeyword(tok::objc_defs))
Douglas Gregor23c84762011-04-14 17:21:19 +00002462 Diag(Tok, diag::err_at_defs_cxx);
2463 else
2464 Diag(Tok, diag::err_at_in_class);
Richard Smithda35e962013-11-09 04:52:51 +00002465
Douglas Gregor23c84762011-04-14 17:21:19 +00002466 ConsumeToken();
Alexey Bataevee6507d2013-11-18 08:17:37 +00002467 SkipUntil(tok::r_brace, StopAtSemi);
David Blaikie0403cb12016-01-15 23:43:25 +00002468 return nullptr;
Douglas Gregor23c84762011-04-14 17:21:19 +00002469 }
Richard Smithda35e962013-11-09 04:52:51 +00002470
Serge Pavlov458ea762014-07-16 05:16:52 +00002471 // Turn on colon protection early, while parsing declspec, although there is
2472 // nothing to protect there. It prevents from false errors if error recovery
2473 // incorrectly determines where the declspec ends, as in the example:
2474 // struct A { enum class B { C }; };
2475 // const int C = 4;
2476 // struct D { A::B : C; };
2477 ColonProtectionRAIIObject X(*this);
2478
John McCalla0097262009-12-11 02:10:03 +00002479 // Access declarations.
Richard Smith45855df2012-05-09 08:23:23 +00002480 bool MalformedTypeSpec = false;
John McCalla0097262009-12-11 02:10:03 +00002481 if (!TemplateInfo.Kind &&
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002482 Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw___super)) {
Richard Smith45855df2012-05-09 08:23:23 +00002483 if (TryAnnotateCXXScopeToken())
2484 MalformedTypeSpec = true;
2485
2486 bool isAccessDecl;
2487 if (Tok.isNot(tok::annot_cxxscope))
2488 isAccessDecl = false;
2489 else if (NextToken().is(tok::identifier))
John McCalla0097262009-12-11 02:10:03 +00002490 isAccessDecl = GetLookAheadToken(2).is(tok::semi);
2491 else
2492 isAccessDecl = NextToken().is(tok::kw_operator);
2493
2494 if (isAccessDecl) {
2495 // Collect the scope specifier token we annotated earlier.
2496 CXXScopeSpec SS;
David Blaikieefdccaa2016-01-15 23:43:34 +00002497 ParseOptionalCXXScopeSpecifier(SS, nullptr,
Douglas Gregordf593fb2011-11-07 17:33:42 +00002498 /*EnteringContext=*/false);
John McCalla0097262009-12-11 02:10:03 +00002499
Nico Weberef03e702014-09-10 00:59:37 +00002500 if (SS.isInvalid()) {
2501 SkipUntil(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002502 return nullptr;
Nico Weberef03e702014-09-10 00:59:37 +00002503 }
2504
John McCalla0097262009-12-11 02:10:03 +00002505 // Try to parse an unqualified-id.
Abramo Bagnara7945c982012-01-27 09:46:47 +00002506 SourceLocation TemplateKWLoc;
John McCalla0097262009-12-11 02:10:03 +00002507 UnqualifiedId Name;
Richard Smith35845152017-02-07 01:37:30 +00002508 if (ParseUnqualifiedId(SS, false, true, true, false, nullptr,
Richard Smithc08b6932018-04-27 02:00:13 +00002509 &TemplateKWLoc, Name)) {
John McCalla0097262009-12-11 02:10:03 +00002510 SkipUntil(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002511 return nullptr;
John McCalla0097262009-12-11 02:10:03 +00002512 }
2513
2514 // TODO: recover from mistakenly-qualified operator declarations.
Alp Toker383d2c42014-01-01 03:08:43 +00002515 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
2516 "access declaration")) {
2517 SkipUntil(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002518 return nullptr;
Alp Toker383d2c42014-01-01 03:08:43 +00002519 }
John McCalla0097262009-12-11 02:10:03 +00002520
Richard Smithc08b6932018-04-27 02:00:13 +00002521 // FIXME: We should do something with the 'template' keyword here.
Alexey Bataev05c25d62015-07-31 08:42:25 +00002522 return DeclGroupPtrTy::make(DeclGroupRef(Actions.ActOnUsingDeclaration(
Richard Smith151c4562016-12-20 21:35:28 +00002523 getCurScope(), AS, /*UsingLoc*/ SourceLocation(),
2524 /*TypenameLoc*/ SourceLocation(), SS, Name,
Erich Keanec480f302018-07-12 21:09:05 +00002525 /*EllipsisLoc*/ SourceLocation(),
2526 /*AttrList*/ ParsedAttributesView())));
John McCalla0097262009-12-11 02:10:03 +00002527 }
2528 }
2529
Aaron Ballmane7c544d2014-08-04 20:28:35 +00002530 // static_assert-declaration. A templated static_assert declaration is
2531 // diagnosed in Parser::ParseSingleDeclarationAfterTemplate.
2532 if (!TemplateInfo.Kind &&
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002533 Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert)) {
Chris Lattner49836b42009-04-02 04:16:50 +00002534 SourceLocation DeclEnd;
Alexey Bataev05c25d62015-07-31 08:42:25 +00002535 return DeclGroupPtrTy::make(
2536 DeclGroupRef(ParseStaticAssertDeclaration(DeclEnd)));
Chris Lattner5bbb3c82009-03-29 16:50:03 +00002537 }
Mike Stump11289f42009-09-09 15:08:12 +00002538
Chris Lattner5bbb3c82009-03-29 16:50:03 +00002539 if (Tok.is(tok::kw_template)) {
Mike Stump11289f42009-09-09 15:08:12 +00002540 assert(!TemplateInfo.TemplateParams &&
Douglas Gregor3447e762009-08-20 22:52:58 +00002541 "Nested template improperly parsed?");
Richard Smith3af70092017-02-09 22:14:25 +00002542 ObjCDeclContextSwitch ObjCDC(*this);
Chris Lattner49836b42009-04-02 04:16:50 +00002543 SourceLocation DeclEnd;
Alexey Bataev05c25d62015-07-31 08:42:25 +00002544 return DeclGroupPtrTy::make(
Richard Smith3af70092017-02-09 22:14:25 +00002545 DeclGroupRef(ParseTemplateDeclarationOrSpecialization(
Erich Keanec480f302018-07-12 21:09:05 +00002546 DeclaratorContext::MemberContext, DeclEnd, AccessAttrs, AS)));
Chris Lattner5bbb3c82009-03-29 16:50:03 +00002547 }
Anders Carlssondfbbdf62009-03-26 00:52:18 +00002548
Chris Lattnerd19c1c02008-12-18 01:12:00 +00002549 // Handle: member-declaration ::= '__extension__' member-declaration
2550 if (Tok.is(tok::kw___extension__)) {
2551 // __extension__ silences extension warnings in the subexpression.
2552 ExtensionRAIIObject O(Diags); // Use RAII to do this.
2553 ConsumeToken();
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00002554 return ParseCXXClassMemberDeclaration(AS, AccessAttrs,
2555 TemplateInfo, TemplateDiags);
Chris Lattnerd19c1c02008-12-18 01:12:00 +00002556 }
Douglas Gregorfec52632009-06-20 00:51:54 +00002557
John McCall084e83d2011-03-24 11:26:52 +00002558 ParsedAttributesWithRange attrs(AttrFactory);
Erich Keanec480f302018-07-12 21:09:05 +00002559 ParsedAttributesViewWithRange FnAttrs;
Richard Smith89645bc2013-01-02 12:01:23 +00002560 // Optional C++11 attribute-specifier
2561 MaybeParseCXX11Attributes(attrs);
Michael Handdc016d2012-11-28 23:17:40 +00002562 // We need to keep these attributes for future diagnostic
2563 // before they are taken over by declaration specifier.
Erich Keanec480f302018-07-12 21:09:05 +00002564 FnAttrs.addAll(attrs.begin(), attrs.end());
Michael Handdc016d2012-11-28 23:17:40 +00002565 FnAttrs.Range = attrs.Range;
2566
John McCall53fa7142010-12-24 02:08:15 +00002567 MaybeParseMicrosoftAttributes(attrs);
Alexis Hunt96d5c762009-11-21 08:43:09 +00002568
Douglas Gregorfec52632009-06-20 00:51:54 +00002569 if (Tok.is(tok::kw_using)) {
John McCall53fa7142010-12-24 02:08:15 +00002570 ProhibitAttributes(attrs);
Mike Stump11289f42009-09-09 15:08:12 +00002571
Douglas Gregorfec52632009-06-20 00:51:54 +00002572 // Eat 'using'.
2573 SourceLocation UsingLoc = ConsumeToken();
2574
Richard Trieu2efd3052019-05-01 23:33:49 +00002575 // Consume unexpected 'template' keywords.
2576 while (Tok.is(tok::kw_template)) {
2577 SourceLocation TemplateLoc = ConsumeToken();
2578 Diag(TemplateLoc, diag::err_unexpected_template_after_using)
2579 << FixItHint::CreateRemoval(TemplateLoc);
2580 }
2581
Douglas Gregorfec52632009-06-20 00:51:54 +00002582 if (Tok.is(tok::kw_namespace)) {
2583 Diag(UsingLoc, diag::err_using_namespace_in_class);
Alexey Bataevee6507d2013-11-18 08:17:37 +00002584 SkipUntil(tok::semi, StopBeforeMatch);
David Blaikie0403cb12016-01-15 23:43:25 +00002585 return nullptr;
Douglas Gregorfec52632009-06-20 00:51:54 +00002586 }
Alexey Bataev05c25d62015-07-31 08:42:25 +00002587 SourceLocation DeclEnd;
2588 // Otherwise, it must be a using-declaration or an alias-declaration.
Faisal Vali421b2d12017-12-29 05:41:00 +00002589 return ParseUsingDeclaration(DeclaratorContext::MemberContext, TemplateInfo,
Richard Smith6f1daa42016-12-16 00:58:48 +00002590 UsingLoc, DeclEnd, AS);
Douglas Gregorfec52632009-06-20 00:51:54 +00002591 }
2592
DeLesley Hutchinsbd2ee132012-03-02 22:12:59 +00002593 // Hold late-parsed attributes so we can attach a Decl to them later.
2594 LateParsedAttrList CommonLateParsedAttrs;
2595
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002596 // decl-specifier-seq:
2597 // Parse the common declaration-specifiers piece.
John McCall796c2a52010-07-16 08:13:16 +00002598 ParsingDeclSpec DS(*this, TemplateDiags);
John McCall53fa7142010-12-24 02:08:15 +00002599 DS.takeAttributesFrom(attrs);
Richard Smith45855df2012-05-09 08:23:23 +00002600 if (MalformedTypeSpec)
2601 DS.SetTypeSpecError();
Richard Smith72553fc2014-01-23 23:53:27 +00002602
Faisal Valia534f072018-04-26 00:42:40 +00002603 ParseDeclarationSpecifiers(DS, TemplateInfo, AS, DeclSpecContext::DSC_class,
2604 &CommonLateParsedAttrs);
Serge Pavlov458ea762014-07-16 05:16:52 +00002605
2606 // Turn off colon protection that was set for declspec.
2607 X.restore();
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002608
Richard Smith404dfb42013-11-19 22:47:36 +00002609 // If we had a free-standing type definition with a missing semicolon, we
2610 // may get this far before the problem becomes obvious.
2611 if (DS.hasTagDefinition() &&
2612 TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate &&
Faisal Vali7db85c52017-12-31 00:06:40 +00002613 DiagnoseMissingSemiAfterTagDefinition(DS, AS, DeclSpecContext::DSC_class,
Richard Smith404dfb42013-11-19 22:47:36 +00002614 &CommonLateParsedAttrs))
David Blaikie0403cb12016-01-15 23:43:25 +00002615 return nullptr;
Richard Smith404dfb42013-11-19 22:47:36 +00002616
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002617 MultiTemplateParamsArg TemplateParams(
Craig Topper161e4db2014-05-21 06:02:52 +00002618 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->data()
2619 : nullptr,
John McCall11083da2009-09-16 22:47:08 +00002620 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->size() : 0);
2621
Alp Toker35d87032013-12-30 23:29:50 +00002622 if (TryConsumeToken(tok::semi)) {
Michael Handdc016d2012-11-28 23:17:40 +00002623 if (DS.isFriendSpecified())
2624 ProhibitAttributes(FnAttrs);
2625
Nico Weber7b837f52016-01-28 19:25:00 +00002626 RecordDecl *AnonRecord = nullptr;
2627 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(
2628 getCurScope(), AS, DS, TemplateParams, false, AnonRecord);
John McCall796c2a52010-07-16 08:13:16 +00002629 DS.complete(TheDecl);
Nico Weber7b837f52016-01-28 19:25:00 +00002630 if (AnonRecord) {
2631 Decl* decls[] = {AnonRecord, TheDecl};
Richard Smith3beb7c62017-01-12 02:27:38 +00002632 return Actions.BuildDeclaratorGroup(decls);
Nico Weber7b837f52016-01-28 19:25:00 +00002633 }
2634 return Actions.ConvertDeclToDeclGroup(TheDecl);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002635 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002636
Faisal Vali421b2d12017-12-29 05:41:00 +00002637 ParsingDeclarator DeclaratorInfo(*this, DS, DeclaratorContext::MemberContext);
Nico Weber24b2a822011-01-28 06:07:34 +00002638 VirtSpecifiers VS;
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002639
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002640 // Hold late-parsed attributes so we can attach a Decl to them later.
2641 LateParsedAttrList LateParsedAttrs;
2642
Douglas Gregor50cefbf2011-10-17 17:09:53 +00002643 SourceLocation EqualLoc;
Richard Smith9ba0fec2015-06-30 01:28:56 +00002644 SourceLocation PureSpecLoc;
2645
Yaron Keren180c1672015-06-30 07:35:19 +00002646 auto TryConsumePureSpecifier = [&] (bool AllowDefinition) {
Richard Smith9ba0fec2015-06-30 01:28:56 +00002647 if (Tok.isNot(tok::equal))
2648 return false;
2649
2650 auto &Zero = NextToken();
2651 SmallString<8> Buffer;
2652 if (Zero.isNot(tok::numeric_constant) || Zero.getLength() != 1 ||
2653 PP.getSpelling(Zero, Buffer) != "0")
2654 return false;
2655
2656 auto &After = GetLookAheadToken(2);
2657 if (!After.isOneOf(tok::semi, tok::comma) &&
2658 !(AllowDefinition &&
2659 After.isOneOf(tok::l_brace, tok::colon, tok::kw_try)))
2660 return false;
2661
2662 EqualLoc = ConsumeToken();
2663 PureSpecLoc = ConsumeToken();
2664 return true;
2665 };
Chris Lattner17c3b1f2009-12-10 01:59:24 +00002666
Richard Smith72553fc2014-01-23 23:53:27 +00002667 SmallVector<Decl *, 8> DeclsInGroup;
2668 ExprResult BitfieldSize;
2669 bool ExpectSemi = true;
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002670
Richard Smith72553fc2014-01-23 23:53:27 +00002671 // Parse the first declarator.
Nico Weberd89e6f72015-01-16 19:34:13 +00002672 if (ParseCXXMemberDeclaratorBeforeInitializer(
2673 DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs)) {
Richard Smith72553fc2014-01-23 23:53:27 +00002674 TryConsumeToken(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002675 return nullptr;
Richard Smith72553fc2014-01-23 23:53:27 +00002676 }
John Thompson5bc5cbe2009-11-25 22:58:06 +00002677
Richard Smith72553fc2014-01-23 23:53:27 +00002678 // Check for a member function definition.
Richard Smith4b5a9492014-01-24 22:34:35 +00002679 if (BitfieldSize.isUnset()) {
Richard Smith72553fc2014-01-23 23:53:27 +00002680 // MSVC permits pure specifier on inline functions defined at class scope.
Francois Pichet3abc9b82011-05-11 02:14:46 +00002681 // Hence check for =0 before checking for function definition.
Richard Smith9ba0fec2015-06-30 01:28:56 +00002682 if (getLangOpts().MicrosoftExt && DeclaratorInfo.isDeclarationOfFunction())
2683 TryConsumePureSpecifier(/*AllowDefinition*/ true);
Francois Pichet3abc9b82011-05-11 02:14:46 +00002684
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00002685 FunctionDefinitionKind DefinitionKind = FDK_Declaration;
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002686 // function-definition:
Richard Smith938f40b2011-06-11 17:19:42 +00002687 //
2688 // In C++11, a non-function declarator followed by an open brace is a
2689 // braced-init-list for an in-class member initialization, not an
2690 // erroneous function definition.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002691 if (Tok.is(tok::l_brace) && !getLangOpts().CPlusPlus11) {
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00002692 DefinitionKind = FDK_Definition;
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002693 } else if (DeclaratorInfo.isFunctionDeclarator()) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002694 if (Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try)) {
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00002695 DefinitionKind = FDK_Definition;
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002696 } else if (Tok.is(tok::equal)) {
2697 const Token &KW = NextToken();
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00002698 if (KW.is(tok::kw_default))
2699 DefinitionKind = FDK_Defaulted;
2700 else if (KW.is(tok::kw_delete))
2701 DefinitionKind = FDK_Deleted;
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002702 }
2703 }
Eli Bendersky41842222015-03-23 23:49:41 +00002704 DeclaratorInfo.setFunctionDefinitionKind(DefinitionKind);
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002705
Fangrui Song6907ce22018-07-30 19:24:48 +00002706 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
Michael Handdc016d2012-11-28 23:17:40 +00002707 // to a friend declaration, that declaration shall be a definition.
Fangrui Song6907ce22018-07-30 19:24:48 +00002708 if (DeclaratorInfo.isFunctionDeclarator() &&
Michael Handdc016d2012-11-28 23:17:40 +00002709 DefinitionKind != FDK_Definition && DS.isFriendSpecified()) {
2710 // Diagnose attributes that appear before decl specifier:
2711 // [[]] friend int foo();
2712 ProhibitAttributes(FnAttrs);
2713 }
2714
Nico Webera7f137d2015-01-16 19:35:01 +00002715 if (DefinitionKind != FDK_Declaration) {
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002716 if (!DeclaratorInfo.isFunctionDeclarator()) {
Richard Trieu0d730542012-01-21 02:59:18 +00002717 Diag(DeclaratorInfo.getIdentifierLoc(), diag::err_func_def_no_params);
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002718 ConsumeBrace();
Alexey Bataevee6507d2013-11-18 08:17:37 +00002719 SkipUntil(tok::r_brace);
Michael Handdc016d2012-11-28 23:17:40 +00002720
Douglas Gregor8a4db832011-01-19 16:41:58 +00002721 // Consume the optional ';'
Alp Toker35d87032013-12-30 23:29:50 +00002722 TryConsumeToken(tok::semi);
2723
David Blaikie0403cb12016-01-15 23:43:25 +00002724 return nullptr;
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002725 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002726
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002727 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
Richard Trieu0d730542012-01-21 02:59:18 +00002728 Diag(DeclaratorInfo.getIdentifierLoc(),
2729 diag::err_function_declared_typedef);
Douglas Gregor8a4db832011-01-19 16:41:58 +00002730
Richard Smith2603b092012-11-15 22:54:20 +00002731 // Recover by treating the 'typedef' as spurious.
2732 DS.ClearStorageClassSpecs();
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002733 }
2734
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002735 Decl *FunDecl =
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00002736 ParseCXXInlineMethodDef(AS, AccessAttrs, DeclaratorInfo, TemplateInfo,
Richard Smith9ba0fec2015-06-30 01:28:56 +00002737 VS, PureSpecLoc);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002738
David Majnemer23252a32013-08-01 04:22:55 +00002739 if (FunDecl) {
2740 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i) {
2741 CommonLateParsedAttrs[i]->addDecl(FunDecl);
2742 }
2743 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i) {
2744 LateParsedAttrs[i]->addDecl(FunDecl);
2745 }
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002746 }
2747 LateParsedAttrs.clear();
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002748
2749 // Consume the ';' - it's optional unless we have a delete or default
Richard Trieu2f7dc462012-05-16 19:04:59 +00002750 if (Tok.is(tok::semi))
Richard Smith87f5dc52012-07-23 05:45:25 +00002751 ConsumeExtraSemi(AfterMemberFunctionDefinition);
Douglas Gregor8a4db832011-01-19 16:41:58 +00002752
Alexey Bataev05c25d62015-07-31 08:42:25 +00002753 return DeclGroupPtrTy::make(DeclGroupRef(FunDecl));
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002754 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002755 }
2756
2757 // member-declarator-list:
2758 // member-declarator
2759 // member-declarator-list ',' member-declarator
2760
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002761 while (1) {
Richard Smith2b013182012-06-10 03:12:00 +00002762 InClassInitStyle HasInClassInit = ICIS_NoInit;
Richard Smith9ba0fec2015-06-30 01:28:56 +00002763 bool HasStaticInitializer = false;
2764 if (Tok.isOneOf(tok::equal, tok::l_brace) && PureSpecLoc.isInvalid()) {
Richard Smith6b8e3c02017-08-28 00:28:14 +00002765 if (DeclaratorInfo.isDeclarationOfFunction()) {
Richard Smith9ba0fec2015-06-30 01:28:56 +00002766 // It's a pure-specifier.
2767 if (!TryConsumePureSpecifier(/*AllowFunctionDefinition*/ false))
2768 // Parse it as an expression so that Sema can diagnose it.
2769 HasStaticInitializer = true;
2770 } else if (DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2771 DeclSpec::SCS_static &&
2772 DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2773 DeclSpec::SCS_typedef &&
2774 !DS.isFriendSpecified()) {
2775 // It's a default member initializer.
Richard Smith6b8e3c02017-08-28 00:28:14 +00002776 if (BitfieldSize.get())
2777 Diag(Tok, getLangOpts().CPlusPlus2a
2778 ? diag::warn_cxx17_compat_bitfield_member_init
2779 : diag::ext_bitfield_member_init);
Richard Smith9ba0fec2015-06-30 01:28:56 +00002780 HasInClassInit = Tok.is(tok::equal) ? ICIS_CopyInit : ICIS_ListInit;
Richard Smith938f40b2011-06-11 17:19:42 +00002781 } else {
Richard Smith9ba0fec2015-06-30 01:28:56 +00002782 HasStaticInitializer = true;
Richard Smith938f40b2011-06-11 17:19:42 +00002783 }
2784 }
2785
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002786 // NOTE: If Sema is the Action module and declarator is an instance field,
Chris Lattner5bbb3c82009-03-29 16:50:03 +00002787 // this call will *not* return the created decl; It will return null.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002788 // See Sema::ActOnCXXMemberDeclarator for details.
John McCall07e91c02009-08-06 02:15:43 +00002789
Craig Topper161e4db2014-05-21 06:02:52 +00002790 NamedDecl *ThisDecl = nullptr;
John McCall07e91c02009-08-06 02:15:43 +00002791 if (DS.isFriendSpecified()) {
Richard Smith72553fc2014-01-23 23:53:27 +00002792 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
Michael Handdc016d2012-11-28 23:17:40 +00002793 // to a friend declaration, that declaration shall be a definition.
2794 //
Richard Smith72553fc2014-01-23 23:53:27 +00002795 // Diagnose attributes that appear in a friend member function declarator:
2796 // friend int foo [[]] ();
Michael Handdc016d2012-11-28 23:17:40 +00002797 SmallVector<SourceRange, 4> Ranges;
2798 DeclaratorInfo.getCXX11AttributeRanges(Ranges);
Richard Smith72553fc2014-01-23 23:53:27 +00002799 for (SmallVectorImpl<SourceRange>::iterator I = Ranges.begin(),
2800 E = Ranges.end(); I != E; ++I)
2801 Diag((*I).getBegin(), diag::err_attributes_not_allowed) << *I;
Michael Handdc016d2012-11-28 23:17:40 +00002802
Douglas Gregor0be31a22010-07-02 17:43:08 +00002803 ThisDecl = Actions.ActOnFriendFunctionDecl(getCurScope(), DeclaratorInfo,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002804 TemplateParams);
Douglas Gregor3447e762009-08-20 22:52:58 +00002805 } else {
Douglas Gregor0be31a22010-07-02 17:43:08 +00002806 ThisDecl = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS,
John McCall07e91c02009-08-06 02:15:43 +00002807 DeclaratorInfo,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002808 TemplateParams,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002809 BitfieldSize.get(),
Richard Smith2b013182012-06-10 03:12:00 +00002810 VS, HasInClassInit);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002811
2812 if (VarTemplateDecl *VT =
Craig Topper161e4db2014-05-21 06:02:52 +00002813 ThisDecl ? dyn_cast<VarTemplateDecl>(ThisDecl) : nullptr)
Larisse Voufo39a1e502013-08-06 01:03:05 +00002814 // Re-direct this decl to refer to the templated decl so that we can
2815 // initialize it.
2816 ThisDecl = VT->getTemplatedDecl();
2817
Erich Keanec480f302018-07-12 21:09:05 +00002818 if (ThisDecl)
Richard Smithf8a75c32013-08-29 00:47:48 +00002819 Actions.ProcessDeclAttributeList(getCurScope(), ThisDecl, AccessAttrs);
Douglas Gregor3447e762009-08-20 22:52:58 +00002820 }
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002821
Richard Smith9ba0fec2015-06-30 01:28:56 +00002822 // Error recovery might have converted a non-static member into a static
2823 // member.
David Blaikie35506f82013-01-30 01:22:18 +00002824 if (HasInClassInit != ICIS_NoInit &&
Richard Smith9ba0fec2015-06-30 01:28:56 +00002825 DeclaratorInfo.getDeclSpec().getStorageClassSpec() ==
2826 DeclSpec::SCS_static) {
2827 HasInClassInit = ICIS_NoInit;
2828 HasStaticInitializer = true;
2829 }
2830
2831 if (ThisDecl && PureSpecLoc.isValid())
2832 Actions.ActOnPureSpecifier(ThisDecl, PureSpecLoc);
2833
2834 // Handle the initializer.
2835 if (HasInClassInit != ICIS_NoInit) {
Douglas Gregor728d00b2011-10-10 14:49:18 +00002836 // The initializer was deferred; parse it and cache the tokens.
David Majnemer23252a32013-08-01 04:22:55 +00002837 Diag(Tok, getLangOpts().CPlusPlus11
2838 ? diag::warn_cxx98_compat_nonstatic_member_init
2839 : diag::ext_nonstatic_member_init);
Richard Smith5d164bc2011-10-15 05:09:34 +00002840
Richard Smith938f40b2011-06-11 17:19:42 +00002841 if (DeclaratorInfo.isArrayOfUnknownBound()) {
Richard Smith2b013182012-06-10 03:12:00 +00002842 // C++11 [dcl.array]p3: An array bound may also be omitted when the
2843 // declarator is followed by an initializer.
Richard Smith938f40b2011-06-11 17:19:42 +00002844 //
2845 // A brace-or-equal-initializer for a member-declarator is not an
David Blaikiecdd91db2012-02-14 09:00:46 +00002846 // initializer in the grammar, so this is ill-formed.
Richard Smith938f40b2011-06-11 17:19:42 +00002847 Diag(Tok, diag::err_incomplete_array_member_init);
Alexey Bataevee6507d2013-11-18 08:17:37 +00002848 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
David Majnemer23252a32013-08-01 04:22:55 +00002849
2850 // Avoid later warnings about a class member of incomplete type.
David Blaikiecdd91db2012-02-14 09:00:46 +00002851 if (ThisDecl)
David Blaikiecdd91db2012-02-14 09:00:46 +00002852 ThisDecl->setInvalidDecl();
Richard Smith938f40b2011-06-11 17:19:42 +00002853 } else
2854 ParseCXXNonStaticMemberInitializer(ThisDecl);
Richard Smith9ba0fec2015-06-30 01:28:56 +00002855 } else if (HasStaticInitializer) {
Douglas Gregor728d00b2011-10-10 14:49:18 +00002856 // Normal initializer.
Richard Smith9ba0fec2015-06-30 01:28:56 +00002857 ExprResult Init = ParseCXXMemberInitializer(
2858 ThisDecl, DeclaratorInfo.isDeclarationOfFunction(), EqualLoc);
David Majnemer23252a32013-08-01 04:22:55 +00002859
Douglas Gregor728d00b2011-10-10 14:49:18 +00002860 if (Init.isInvalid())
Alexey Bataevee6507d2013-11-18 08:17:37 +00002861 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
Douglas Gregor728d00b2011-10-10 14:49:18 +00002862 else if (ThisDecl)
Richard Smith3beb7c62017-01-12 02:27:38 +00002863 Actions.AddInitializerToDecl(ThisDecl, Init.get(), EqualLoc.isInvalid());
David Majnemer23252a32013-08-01 04:22:55 +00002864 } else if (ThisDecl && DS.getStorageClassSpec() == DeclSpec::SCS_static)
Douglas Gregor728d00b2011-10-10 14:49:18 +00002865 // No initializer.
Richard Smith3beb7c62017-01-12 02:27:38 +00002866 Actions.ActOnUninitializedDecl(ThisDecl);
David Majnemer23252a32013-08-01 04:22:55 +00002867
Douglas Gregor728d00b2011-10-10 14:49:18 +00002868 if (ThisDecl) {
David Majnemer23252a32013-08-01 04:22:55 +00002869 if (!ThisDecl->isInvalidDecl()) {
2870 // Set the Decl for any late parsed attributes
2871 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i)
2872 CommonLateParsedAttrs[i]->addDecl(ThisDecl);
2873
2874 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i)
2875 LateParsedAttrs[i]->addDecl(ThisDecl);
2876 }
Douglas Gregor728d00b2011-10-10 14:49:18 +00002877 Actions.FinalizeDeclaration(ThisDecl);
2878 DeclsInGroup.push_back(ThisDecl);
David Majnemer23252a32013-08-01 04:22:55 +00002879
2880 if (DeclaratorInfo.isFunctionDeclarator() &&
2881 DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2882 DeclSpec::SCS_typedef)
2883 HandleMemberFunctionDeclDelays(DeclaratorInfo, ThisDecl);
Douglas Gregor728d00b2011-10-10 14:49:18 +00002884 }
David Majnemer23252a32013-08-01 04:22:55 +00002885 LateParsedAttrs.clear();
Douglas Gregor728d00b2011-10-10 14:49:18 +00002886
2887 DeclaratorInfo.complete(ThisDecl);
Richard Smith938f40b2011-06-11 17:19:42 +00002888
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002889 // If we don't have a comma, it is either the end of the list (a ';')
2890 // or an error, bail out.
Alp Toker094e5212014-01-05 03:27:11 +00002891 SourceLocation CommaLoc;
2892 if (!TryConsumeToken(tok::comma, CommaLoc))
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002893 break;
Mike Stump11289f42009-09-09 15:08:12 +00002894
Richard Smithc8a79032012-01-09 22:31:44 +00002895 if (Tok.isAtStartOfLine() &&
Faisal Vali421b2d12017-12-29 05:41:00 +00002896 !MightBeDeclarator(DeclaratorContext::MemberContext)) {
Richard Smithc8a79032012-01-09 22:31:44 +00002897 // This comma was followed by a line-break and something which can't be
2898 // the start of a declarator. The comma was probably a typo for a
2899 // semicolon.
2900 Diag(CommaLoc, diag::err_expected_semi_declaration)
2901 << FixItHint::CreateReplacement(CommaLoc, ";");
2902 ExpectSemi = false;
2903 break;
2904 }
Mike Stump11289f42009-09-09 15:08:12 +00002905
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002906 // Parse the next declarator.
2907 DeclaratorInfo.clear();
Nico Weber24b2a822011-01-28 06:07:34 +00002908 VS.clear();
Nico Weberf56c85b2015-01-17 02:26:40 +00002909 BitfieldSize = ExprResult(/*Invalid=*/false);
Richard Smith9ba0fec2015-06-30 01:28:56 +00002910 EqualLoc = PureSpecLoc = SourceLocation();
Richard Smith8d06f422012-01-12 23:53:29 +00002911 DeclaratorInfo.setCommaLoc(CommaLoc);
Mike Stump11289f42009-09-09 15:08:12 +00002912
Richard Smith72553fc2014-01-23 23:53:27 +00002913 // GNU attributes are allowed before the second and subsequent declarator.
John McCall53fa7142010-12-24 02:08:15 +00002914 MaybeParseGNUAttributes(DeclaratorInfo);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002915
Nico Weberd89e6f72015-01-16 19:34:13 +00002916 if (ParseCXXMemberDeclaratorBeforeInitializer(
2917 DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs))
2918 break;
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002919 }
2920
Richard Smithc8a79032012-01-09 22:31:44 +00002921 if (ExpectSemi &&
2922 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list)) {
Chris Lattner916dbf12010-02-02 00:43:15 +00002923 // Skip to end of block or statement.
Alexey Bataevee6507d2013-11-18 08:17:37 +00002924 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Chris Lattner916dbf12010-02-02 00:43:15 +00002925 // If we stopped at a ';', eat it.
Alp Toker35d87032013-12-30 23:29:50 +00002926 TryConsumeToken(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002927 return nullptr;
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002928 }
2929
Alexey Bataev05c25d62015-07-31 08:42:25 +00002930 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002931}
2932
Richard Smith9ba0fec2015-06-30 01:28:56 +00002933/// ParseCXXMemberInitializer - Parse the brace-or-equal-initializer.
2934/// Also detect and reject any attempted defaulted/deleted function definition.
2935/// The location of the '=', if any, will be placed in EqualLoc.
Richard Smith938f40b2011-06-11 17:19:42 +00002936///
Richard Smith9ba0fec2015-06-30 01:28:56 +00002937/// This does not check for a pure-specifier; that's handled elsewhere.
Sebastian Redleef474c2012-02-22 10:50:08 +00002938///
Richard Smith938f40b2011-06-11 17:19:42 +00002939/// brace-or-equal-initializer:
2940/// '=' initializer-expression
Sebastian Redleef474c2012-02-22 10:50:08 +00002941/// braced-init-list
2942///
Richard Smith938f40b2011-06-11 17:19:42 +00002943/// initializer-clause:
2944/// assignment-expression
Sebastian Redleef474c2012-02-22 10:50:08 +00002945/// braced-init-list
2946///
Richard Smithda35e962013-11-09 04:52:51 +00002947/// defaulted/deleted function-definition:
Richard Smith938f40b2011-06-11 17:19:42 +00002948/// '=' 'default'
2949/// '=' 'delete'
2950///
2951/// Prior to C++0x, the assignment-expression in an initializer-clause must
2952/// be a constant-expression.
Douglas Gregor926410d2012-02-21 02:22:07 +00002953ExprResult Parser::ParseCXXMemberInitializer(Decl *D, bool IsFunction,
Richard Smith938f40b2011-06-11 17:19:42 +00002954 SourceLocation &EqualLoc) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002955 assert(Tok.isOneOf(tok::equal, tok::l_brace)
Richard Smith938f40b2011-06-11 17:19:42 +00002956 && "Data member initializer not starting with '=' or '{'");
2957
Faisal Valid143a0c2017-04-01 21:30:49 +00002958 EnterExpressionEvaluationContext Context(
2959 Actions, Sema::ExpressionEvaluationContext::PotentiallyEvaluated, D);
Alp Toker094e5212014-01-05 03:27:11 +00002960 if (TryConsumeToken(tok::equal, EqualLoc)) {
Richard Smith938f40b2011-06-11 17:19:42 +00002961 if (Tok.is(tok::kw_delete)) {
2962 // In principle, an initializer of '= delete p;' is legal, but it will
2963 // never type-check. It's better to diagnose it as an ill-formed expression
2964 // than as an ill-formed deleted non-function member.
2965 // An initializer of '= delete p, foo' will never be parsed, because
2966 // a top-level comma always ends the initializer expression.
2967 const Token &Next = NextToken();
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002968 if (IsFunction || Next.isOneOf(tok::semi, tok::comma, tok::eof)) {
Richard Smith938f40b2011-06-11 17:19:42 +00002969 if (IsFunction)
2970 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2971 << 1 /* delete */;
2972 else
2973 Diag(ConsumeToken(), diag::err_deleted_non_function);
Richard Smithedcb26e2014-06-11 00:49:52 +00002974 return ExprError();
Richard Smith938f40b2011-06-11 17:19:42 +00002975 }
2976 } else if (Tok.is(tok::kw_default)) {
Richard Smith938f40b2011-06-11 17:19:42 +00002977 if (IsFunction)
2978 Diag(Tok, diag::err_default_delete_in_multiple_declaration)
2979 << 0 /* default */;
2980 else
2981 Diag(ConsumeToken(), diag::err_default_special_members);
Richard Smithedcb26e2014-06-11 00:49:52 +00002982 return ExprError();
Richard Smith938f40b2011-06-11 17:19:42 +00002983 }
David Majnemer87ff66c2014-12-13 11:34:16 +00002984 }
2985 if (const auto *PD = dyn_cast_or_null<MSPropertyDecl>(D)) {
2986 Diag(Tok, diag::err_ms_property_initializer) << PD;
2987 return ExprError();
Sebastian Redleef474c2012-02-22 10:50:08 +00002988 }
2989 return ParseInitializer();
Richard Smith938f40b2011-06-11 17:19:42 +00002990}
2991
Richard Smith65ebb4a2015-03-26 04:09:53 +00002992void Parser::SkipCXXMemberSpecification(SourceLocation RecordLoc,
2993 SourceLocation AttrFixitLoc,
Faisal Vali090da2d2018-01-01 18:23:28 +00002994 unsigned TagType, Decl *TagDecl) {
Richard Smith65ebb4a2015-03-26 04:09:53 +00002995 // Skip the optional 'final' keyword.
2996 if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
2997 assert(isCXX11FinalKeyword() && "not a class definition");
2998 ConsumeToken();
2999
3000 // Diagnose any C++11 attributes after 'final' keyword.
3001 // We deliberately discard these attributes.
3002 ParsedAttributesWithRange Attrs(AttrFactory);
3003 CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
3004
3005 // This can only happen if we had malformed misplaced attributes;
3006 // we only get called if there is a colon or left-brace after the
3007 // attributes.
3008 if (Tok.isNot(tok::colon) && Tok.isNot(tok::l_brace))
3009 return;
3010 }
3011
3012 // Skip the base clauses. This requires actually parsing them, because
3013 // otherwise we can't be sure where they end (a left brace may appear
3014 // within a template argument).
3015 if (Tok.is(tok::colon)) {
3016 // Enter the scope of the class so that we can correctly parse its bases.
3017 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
3018 ParsingClassDefinition ParsingDef(*this, TagDecl, /*NonNestedClass*/ true,
3019 TagType == DeclSpec::TST_interface);
Richard Smith0f192e82015-06-11 22:48:25 +00003020 auto OldContext =
3021 Actions.ActOnTagStartSkippedDefinition(getCurScope(), TagDecl);
Richard Smith65ebb4a2015-03-26 04:09:53 +00003022
3023 // Parse the bases but don't attach them to the class.
3024 ParseBaseClause(nullptr);
3025
Richard Smith0f192e82015-06-11 22:48:25 +00003026 Actions.ActOnTagFinishSkippedDefinition(OldContext);
Richard Smith65ebb4a2015-03-26 04:09:53 +00003027
3028 if (!Tok.is(tok::l_brace)) {
3029 Diag(PP.getLocForEndOfToken(PrevTokLocation),
3030 diag::err_expected_lbrace_after_base_specifiers);
3031 return;
3032 }
3033 }
3034
3035 // Skip the body.
3036 assert(Tok.is(tok::l_brace));
3037 BalancedDelimiterTracker T(*this, tok::l_brace);
3038 T.consumeOpen();
3039 T.skipToEnd();
Richard Smith04c6c1f2015-07-01 18:56:50 +00003040
3041 // Parse and discard any trailing attributes.
3042 ParsedAttributes Attrs(AttrFactory);
3043 if (Tok.is(tok::kw___attribute))
3044 MaybeParseGNUAttributes(Attrs);
Richard Smith65ebb4a2015-03-26 04:09:53 +00003045}
3046
Alexey Bataev05c25d62015-07-31 08:42:25 +00003047Parser::DeclGroupPtrTy Parser::ParseCXXClassMemberDeclarationWithPragmas(
3048 AccessSpecifier &AS, ParsedAttributesWithRange &AccessAttrs,
3049 DeclSpec::TST TagType, Decl *TagDecl) {
Richard Smithbf5bcf22018-06-26 23:20:26 +00003050 ParenBraceBracketBalancer BalancerRAIIObj(*this);
3051
Richard Smithb55f7582017-01-28 01:12:10 +00003052 switch (Tok.getKind()) {
3053 case tok::kw___if_exists:
3054 case tok::kw___if_not_exists:
Erich Keanec480f302018-07-12 21:09:05 +00003055 ParseMicrosoftIfExistsClassDeclaration(TagType, AccessAttrs, AS);
David Blaikie0403cb12016-01-15 23:43:25 +00003056 return nullptr;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003057
Richard Smithb55f7582017-01-28 01:12:10 +00003058 case tok::semi:
3059 // Check for extraneous top-level semicolon.
Alexey Bataev05c25d62015-07-31 08:42:25 +00003060 ConsumeExtraSemi(InsideStruct, TagType);
David Blaikie0403cb12016-01-15 23:43:25 +00003061 return nullptr;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003062
Richard Smithb55f7582017-01-28 01:12:10 +00003063 // Handle pragmas that can appear as member declarations.
3064 case tok::annot_pragma_vis:
Alexey Bataev05c25d62015-07-31 08:42:25 +00003065 HandlePragmaVisibility();
David Blaikie0403cb12016-01-15 23:43:25 +00003066 return nullptr;
Richard Smithb55f7582017-01-28 01:12:10 +00003067 case tok::annot_pragma_pack:
Alexey Bataev05c25d62015-07-31 08:42:25 +00003068 HandlePragmaPack();
David Blaikie0403cb12016-01-15 23:43:25 +00003069 return nullptr;
Richard Smithb55f7582017-01-28 01:12:10 +00003070 case tok::annot_pragma_align:
Alexey Bataev05c25d62015-07-31 08:42:25 +00003071 HandlePragmaAlign();
David Blaikie0403cb12016-01-15 23:43:25 +00003072 return nullptr;
Richard Smithb55f7582017-01-28 01:12:10 +00003073 case tok::annot_pragma_ms_pointers_to_members:
Alexey Bataev05c25d62015-07-31 08:42:25 +00003074 HandlePragmaMSPointersToMembers();
David Blaikie0403cb12016-01-15 23:43:25 +00003075 return nullptr;
Richard Smithb55f7582017-01-28 01:12:10 +00003076 case tok::annot_pragma_ms_pragma:
Alexey Bataev05c25d62015-07-31 08:42:25 +00003077 HandlePragmaMSPragma();
David Blaikie0403cb12016-01-15 23:43:25 +00003078 return nullptr;
Richard Smithb55f7582017-01-28 01:12:10 +00003079 case tok::annot_pragma_ms_vtordisp:
Alexey Bataev3d42f342015-11-20 07:02:57 +00003080 HandlePragmaMSVtorDisp();
David Blaikie0403cb12016-01-15 23:43:25 +00003081 return nullptr;
Richard Smithb256d302017-01-28 01:20:57 +00003082 case tok::annot_pragma_dump:
3083 HandlePragmaDump();
3084 return nullptr;
Alexey Bataev3d42f342015-11-20 07:02:57 +00003085
Richard Smithb55f7582017-01-28 01:12:10 +00003086 case tok::kw_namespace:
3087 // If we see a namespace here, a close brace was missing somewhere.
Alexey Bataev05c25d62015-07-31 08:42:25 +00003088 DiagnoseUnexpectedNamespace(cast<NamedDecl>(TagDecl));
David Blaikie0403cb12016-01-15 23:43:25 +00003089 return nullptr;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003090
Anastasia Stulova948e37c2019-03-25 11:54:02 +00003091 case tok::kw_private:
3092 // FIXME: We don't accept GNU attributes on access specifiers in OpenCL mode
3093 // yet.
3094 if (getLangOpts().OpenCL && !NextToken().is(tok::colon))
3095 return ParseCXXClassMemberDeclaration(AS, AccessAttrs);
3096 LLVM_FALLTHROUGH;
Richard Smithb55f7582017-01-28 01:12:10 +00003097 case tok::kw_public:
Anastasia Stulova948e37c2019-03-25 11:54:02 +00003098 case tok::kw_protected: {
Richard Smithb55f7582017-01-28 01:12:10 +00003099 AccessSpecifier NewAS = getAccessSpecifierIfPresent();
3100 assert(NewAS != AS_none);
Alexey Bataev05c25d62015-07-31 08:42:25 +00003101 // Current token is a C++ access specifier.
3102 AS = NewAS;
3103 SourceLocation ASLoc = Tok.getLocation();
3104 unsigned TokLength = Tok.getLength();
3105 ConsumeToken();
3106 AccessAttrs.clear();
3107 MaybeParseGNUAttributes(AccessAttrs);
3108
3109 SourceLocation EndLoc;
3110 if (TryConsumeToken(tok::colon, EndLoc)) {
3111 } else if (TryConsumeToken(tok::semi, EndLoc)) {
3112 Diag(EndLoc, diag::err_expected)
3113 << tok::colon << FixItHint::CreateReplacement(EndLoc, ":");
3114 } else {
3115 EndLoc = ASLoc.getLocWithOffset(TokLength);
3116 Diag(EndLoc, diag::err_expected)
3117 << tok::colon << FixItHint::CreateInsertion(EndLoc, ":");
3118 }
3119
3120 // The Microsoft extension __interface does not permit non-public
3121 // access specifiers.
3122 if (TagType == DeclSpec::TST_interface && AS != AS_public) {
3123 Diag(ASLoc, diag::err_access_specifier_interface) << (AS == AS_protected);
3124 }
3125
Erich Keanec480f302018-07-12 21:09:05 +00003126 if (Actions.ActOnAccessSpecifier(NewAS, ASLoc, EndLoc, AccessAttrs)) {
Alexey Bataev05c25d62015-07-31 08:42:25 +00003127 // found another attribute than only annotations
3128 AccessAttrs.clear();
3129 }
3130
David Blaikie0403cb12016-01-15 23:43:25 +00003131 return nullptr;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003132 }
3133
Richard Smithb55f7582017-01-28 01:12:10 +00003134 case tok::annot_pragma_openmp:
Alexey Bataev587e1de2016-03-30 10:43:55 +00003135 return ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, AccessAttrs, TagType,
3136 TagDecl);
Alexey Bataev05c25d62015-07-31 08:42:25 +00003137
Richard Smithb55f7582017-01-28 01:12:10 +00003138 default:
Serge Pavlov037861b2019-08-04 10:08:51 +00003139 if (tok::isPragmaAnnotation(Tok.getKind())) {
3140 Diag(Tok.getLocation(), diag::err_pragma_misplaced_in_decl)
3141 << DeclSpec::getSpecifierName(TagType,
3142 Actions.getASTContext().getPrintingPolicy());
3143 ConsumeAnnotationToken();
3144 return nullptr;
3145 }
Erich Keanec480f302018-07-12 21:09:05 +00003146 return ParseCXXClassMemberDeclaration(AS, AccessAttrs);
Richard Smithb55f7582017-01-28 01:12:10 +00003147 }
Alexey Bataev05c25d62015-07-31 08:42:25 +00003148}
3149
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003150/// ParseCXXMemberSpecification - Parse the class definition.
3151///
3152/// member-specification:
3153/// member-declaration member-specification[opt]
3154/// access-specifier ':' member-specification[opt]
3155///
Joao Matose9a3ed42012-08-31 22:18:20 +00003156void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc,
Michael Han309af292013-01-07 16:57:11 +00003157 SourceLocation AttrFixitLoc,
Richard Smith4c96e992013-02-19 23:47:15 +00003158 ParsedAttributesWithRange &Attrs,
Faisal Vali090da2d2018-01-01 18:23:28 +00003159 unsigned TagType, Decl *TagDecl) {
Joao Matose9a3ed42012-08-31 22:18:20 +00003160 assert((TagType == DeclSpec::TST_struct ||
Faisal Vali090da2d2018-01-01 18:23:28 +00003161 TagType == DeclSpec::TST_interface ||
3162 TagType == DeclSpec::TST_union ||
3163 TagType == DeclSpec::TST_class) && "Invalid TagType!");
Joao Matose9a3ed42012-08-31 22:18:20 +00003164
Anton Afanasyevd880de22019-03-30 08:42:48 +00003165 llvm::TimeTraceScope TimeScope("ParseClass", [&]() {
3166 if (auto *TD = dyn_cast_or_null<NamedDecl>(TagDecl))
3167 return TD->getQualifiedNameAsString();
3168 return std::string("<anonymous>");
3169 });
3170
Jordan Rose1e879d82018-03-23 00:07:18 +00003171 PrettyDeclStackTraceEntry CrashInfo(Actions.Context, TagDecl, RecordLoc,
John McCallfaf5fb42010-08-26 23:41:50 +00003172 "parsing struct/union/class body");
Mike Stump11289f42009-09-09 15:08:12 +00003173
Douglas Gregoredf8f392010-01-16 20:52:59 +00003174 // Determine whether this is a non-nested class. Note that local
3175 // classes are *not* considered to be nested classes.
3176 bool NonNestedClass = true;
3177 if (!ClassStack.empty()) {
Douglas Gregor0be31a22010-07-02 17:43:08 +00003178 for (const Scope *S = getCurScope(); S; S = S->getParent()) {
Douglas Gregoredf8f392010-01-16 20:52:59 +00003179 if (S->isClassScope()) {
3180 // We're inside a class scope, so this is a nested class.
3181 NonNestedClass = false;
John McCalldb632ac2012-09-25 07:32:39 +00003182
3183 // The Microsoft extension __interface does not permit nested classes.
3184 if (getCurrentClass().IsInterface) {
3185 Diag(RecordLoc, diag::err_invalid_member_in_interface)
3186 << /*ErrorType=*/6
3187 << (isa<NamedDecl>(TagDecl)
3188 ? cast<NamedDecl>(TagDecl)->getQualifiedNameAsString()
David Blaikieabe1a392014-04-02 05:58:29 +00003189 : "(anonymous)");
John McCalldb632ac2012-09-25 07:32:39 +00003190 }
Douglas Gregoredf8f392010-01-16 20:52:59 +00003191 break;
3192 }
3193
Serge Pavlovd9c0bcf2015-07-14 10:02:10 +00003194 if ((S->getFlags() & Scope::FnScope))
3195 // If we're in a function or function template then this is a local
3196 // class rather than a nested class.
3197 break;
Douglas Gregoredf8f392010-01-16 20:52:59 +00003198 }
3199 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003200
3201 // Enter a scope for the class.
Douglas Gregor658b9552009-01-09 22:42:13 +00003202 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003203
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003204 // Note that we are parsing a new (potentially-nested) class definition.
John McCalldb632ac2012-09-25 07:32:39 +00003205 ParsingClassDefinition ParsingDef(*this, TagDecl, NonNestedClass,
3206 TagType == DeclSpec::TST_interface);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003207
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003208 if (TagDecl)
Douglas Gregor0be31a22010-07-02 17:43:08 +00003209 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
John McCall2d814c32009-12-19 21:48:58 +00003210
Anders Carlssonf9eb63b2011-03-25 14:46:08 +00003211 SourceLocation FinalLoc;
David Majnemera5433082013-10-18 00:33:31 +00003212 bool IsFinalSpelledSealed = false;
Anders Carlssonf9eb63b2011-03-25 14:46:08 +00003213
3214 // Parse the optional 'final' keyword.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003215 if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
David Majnemera5433082013-10-18 00:33:31 +00003216 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier(Tok);
3217 assert((Specifier == VirtSpecifiers::VS_Final ||
Fangrui Song6907ce22018-07-30 19:24:48 +00003218 Specifier == VirtSpecifiers::VS_GNU_Final ||
David Majnemera5433082013-10-18 00:33:31 +00003219 Specifier == VirtSpecifiers::VS_Sealed) &&
3220 "not a class definition");
Richard Smithda261112011-10-15 04:21:46 +00003221 FinalLoc = ConsumeToken();
David Majnemera5433082013-10-18 00:33:31 +00003222 IsFinalSpelledSealed = Specifier == VirtSpecifiers::VS_Sealed;
Anders Carlssonf9eb63b2011-03-25 14:46:08 +00003223
David Majnemera5433082013-10-18 00:33:31 +00003224 if (TagType == DeclSpec::TST_interface)
John McCalldb632ac2012-09-25 07:32:39 +00003225 Diag(FinalLoc, diag::err_override_control_interface)
David Majnemera5433082013-10-18 00:33:31 +00003226 << VirtSpecifiers::getSpecifierName(Specifier);
3227 else if (Specifier == VirtSpecifiers::VS_Final)
3228 Diag(FinalLoc, getLangOpts().CPlusPlus11
3229 ? diag::warn_cxx98_compat_override_control_keyword
3230 : diag::ext_override_control_keyword)
3231 << VirtSpecifiers::getSpecifierName(Specifier);
3232 else if (Specifier == VirtSpecifiers::VS_Sealed)
3233 Diag(FinalLoc, diag::ext_ms_sealed_keyword);
Andrey Bokhanko276055b2016-07-29 10:42:48 +00003234 else if (Specifier == VirtSpecifiers::VS_GNU_Final)
3235 Diag(FinalLoc, diag::ext_warn_gnu_final);
Michael Han9407e502012-11-26 22:54:45 +00003236
Michael Han309af292013-01-07 16:57:11 +00003237 // Parse any C++11 attributes after 'final' keyword.
3238 // These attributes are not allowed to appear here,
3239 // and the only possible place for them to appertain
3240 // to the class would be between class-key and class-name.
Richard Smith4c96e992013-02-19 23:47:15 +00003241 CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
Nico Weber4b4be842014-12-29 06:56:50 +00003242
3243 // ParseClassSpecifier() does only a superficial check for attributes before
3244 // deciding to call this method. For example, for
3245 // `class C final alignas ([l) {` it will decide that this looks like a
3246 // misplaced attribute since it sees `alignas '(' ')'`. But the actual
3247 // attribute parsing code will try to parse the '[' as a constexpr lambda
3248 // and consume enough tokens that the alignas parsing code will eat the
3249 // opening '{'. So bail out if the next token isn't one we expect.
Nico Weber36de3a22014-12-29 21:56:22 +00003250 if (!Tok.is(tok::colon) && !Tok.is(tok::l_brace)) {
3251 if (TagDecl)
3252 Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
Nico Weber4b4be842014-12-29 06:56:50 +00003253 return;
Nico Weber36de3a22014-12-29 21:56:22 +00003254 }
Anders Carlssonf9eb63b2011-03-25 14:46:08 +00003255 }
Anders Carlsson4b63d0e2011-01-22 16:56:46 +00003256
John McCall2d814c32009-12-19 21:48:58 +00003257 if (Tok.is(tok::colon)) {
Erik Verbruggen6524c052017-10-24 13:46:58 +00003258 ParseScope InheritanceScope(this, getCurScope()->getFlags() |
3259 Scope::ClassInheritanceScope);
3260
John McCall2d814c32009-12-19 21:48:58 +00003261 ParseBaseClause(TagDecl);
John McCall2d814c32009-12-19 21:48:58 +00003262 if (!Tok.is(tok::l_brace)) {
Ismail Pazarbasi129c44c2014-09-25 21:13:02 +00003263 bool SuggestFixIt = false;
3264 SourceLocation BraceLoc = PP.getLocForEndOfToken(PrevTokLocation);
3265 if (Tok.isAtStartOfLine()) {
3266 switch (Tok.getKind()) {
3267 case tok::kw_private:
3268 case tok::kw_protected:
3269 case tok::kw_public:
3270 SuggestFixIt = NextToken().getKind() == tok::colon;
3271 break;
3272 case tok::kw_static_assert:
3273 case tok::r_brace:
3274 case tok::kw_using:
3275 // base-clause can have simple-template-id; 'template' can't be there
3276 case tok::kw_template:
3277 SuggestFixIt = true;
3278 break;
3279 case tok::identifier:
3280 SuggestFixIt = isConstructorDeclarator(true);
3281 break;
3282 default:
3283 SuggestFixIt = isCXXSimpleDeclaration(/*AllowForRangeDecl=*/false);
3284 break;
3285 }
3286 }
3287 DiagnosticBuilder LBraceDiag =
3288 Diag(BraceLoc, diag::err_expected_lbrace_after_base_specifiers);
3289 if (SuggestFixIt) {
3290 LBraceDiag << FixItHint::CreateInsertion(BraceLoc, " {");
3291 // Try recovering from missing { after base-clause.
Ilya Biryukov929af672019-05-17 09:32:05 +00003292 PP.EnterToken(Tok, /*IsReinject*/true);
Ismail Pazarbasi129c44c2014-09-25 21:13:02 +00003293 Tok.setKind(tok::l_brace);
3294 } else {
3295 if (TagDecl)
3296 Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
3297 return;
3298 }
John McCall2d814c32009-12-19 21:48:58 +00003299 }
3300 }
3301
3302 assert(Tok.is(tok::l_brace));
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003303 BalancedDelimiterTracker T(*this, tok::l_brace);
3304 T.consumeOpen();
John McCall2d814c32009-12-19 21:48:58 +00003305
John McCall08bede42010-05-28 08:11:17 +00003306 if (TagDecl)
Anders Carlsson30f29442011-03-25 14:31:08 +00003307 Actions.ActOnStartCXXMemberDeclarations(getCurScope(), TagDecl, FinalLoc,
David Majnemera5433082013-10-18 00:33:31 +00003308 IsFinalSpelledSealed,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003309 T.getOpenLocation());
John McCall1c7e6ec2009-12-20 07:58:13 +00003310
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003311 // C++ 11p3: Members of a class defined with the keyword class are private
3312 // by default. Members of a class defined with the keywords struct or union
3313 // are public by default.
3314 AccessSpecifier CurAS;
3315 if (TagType == DeclSpec::TST_class)
3316 CurAS = AS_private;
3317 else
3318 CurAS = AS_public;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003319 ParsedAttributesWithRange AccessAttrs(AttrFactory);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003320
Douglas Gregor9377c822010-06-21 22:31:09 +00003321 if (TagDecl) {
3322 // While we still have something to read, read the member-declarations.
Richard Smith752ada82015-11-17 23:32:01 +00003323 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
3324 Tok.isNot(tok::eof)) {
Douglas Gregor9377c822010-06-21 22:31:09 +00003325 // Each iteration of this loop reads one member-declaration.
Alexey Bataev05c25d62015-07-31 08:42:25 +00003326 ParseCXXClassMemberDeclarationWithPragmas(
3327 CurAS, AccessAttrs, static_cast<DeclSpec::TST>(TagType), TagDecl);
Serge Pavlovc4e04a22015-09-19 05:32:57 +00003328 }
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003329 T.consumeClose();
Douglas Gregor9377c822010-06-21 22:31:09 +00003330 } else {
Alexey Bataevee6507d2013-11-18 08:17:37 +00003331 SkipUntil(tok::r_brace);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003332 }
Mike Stump11289f42009-09-09 15:08:12 +00003333
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003334 // If attributes exist after class contents, parse them.
John McCall084e83d2011-03-24 11:26:52 +00003335 ParsedAttributes attrs(AttrFactory);
John McCall53fa7142010-12-24 02:08:15 +00003336 MaybeParseGNUAttributes(attrs);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003337
John McCall08bede42010-05-28 08:11:17 +00003338 if (TagDecl)
Douglas Gregor0be31a22010-07-02 17:43:08 +00003339 Actions.ActOnFinishCXXMemberSpecification(getCurScope(), RecordLoc, TagDecl,
Erich Keanec480f302018-07-12 21:09:05 +00003340 T.getOpenLocation(),
3341 T.getCloseLocation(), attrs);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003342
Douglas Gregor433e0532012-04-16 18:27:27 +00003343 // C++11 [class.mem]p2:
3344 // Within the class member-specification, the class is regarded as complete
Richard Smith0b3a4622014-11-13 20:01:57 +00003345 // within function bodies, default arguments, exception-specifications, and
Douglas Gregor433e0532012-04-16 18:27:27 +00003346 // brace-or-equal-initializers for non-static data members (including such
3347 // things in nested classes).
Douglas Gregor9377c822010-06-21 22:31:09 +00003348 if (TagDecl && NonNestedClass) {
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003349 // We are not inside a nested class. This class and its nested classes
Douglas Gregor4d87df52008-12-16 21:30:33 +00003350 // are complete and we can parse the delayed portions of method
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00003351 // declarations and the lexed inline method definitions, along with any
3352 // delayed attributes.
Douglas Gregor428119e2010-06-16 23:45:56 +00003353 SourceLocation SavedPrevTokLocation = PrevTokLocation;
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00003354 ParseLexedAttributes(getCurrentClass());
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003355 ParseLexedMethodDeclarations(getCurrentClass());
Richard Smith84973e52012-04-21 18:42:51 +00003356
3357 // We've finished with all pending member declarations.
3358 Actions.ActOnFinishCXXMemberDecls();
3359
Richard Smith938f40b2011-06-11 17:19:42 +00003360 ParseLexedMemberInitializers(getCurrentClass());
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003361 ParseLexedMethodDefs(getCurrentClass());
Douglas Gregor428119e2010-06-16 23:45:56 +00003362 PrevTokLocation = SavedPrevTokLocation;
Reid Klecknerbba3cb92015-03-17 19:00:50 +00003363
3364 // We've finished parsing everything, including default argument
3365 // initializers.
Hans Wennborg99000c22015-08-15 01:18:16 +00003366 Actions.ActOnFinishCXXNonNestedClass(TagDecl);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003367 }
3368
John McCall08bede42010-05-28 08:11:17 +00003369 if (TagDecl)
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00003370 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getRange());
John McCall2ff380a2010-03-17 00:38:33 +00003371
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003372 // Leave the class scope.
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003373 ParsingDef.Pop();
Douglas Gregor7307d6c2008-12-10 06:34:36 +00003374 ClassScope.Exit();
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003375}
Douglas Gregore8381c02008-11-05 04:29:56 +00003376
Richard Smith2ac43ad2013-11-15 23:00:02 +00003377void Parser::DiagnoseUnexpectedNamespace(NamedDecl *D) {
Richard Smithda35e962013-11-09 04:52:51 +00003378 assert(Tok.is(tok::kw_namespace));
3379
3380 // FIXME: Suggest where the close brace should have gone by looking
3381 // at indentation changes within the definition body.
Richard Smith2ac43ad2013-11-15 23:00:02 +00003382 Diag(D->getLocation(),
3383 diag::err_missing_end_of_definition) << D;
Richard Smithda35e962013-11-09 04:52:51 +00003384 Diag(Tok.getLocation(),
Richard Smith2ac43ad2013-11-15 23:00:02 +00003385 diag::note_missing_end_of_definition_before) << D;
Richard Smithda35e962013-11-09 04:52:51 +00003386
3387 // Push '};' onto the token stream to recover.
Ilya Biryukov929af672019-05-17 09:32:05 +00003388 PP.EnterToken(Tok, /*IsReinject*/ true);
Richard Smithda35e962013-11-09 04:52:51 +00003389
3390 Tok.startToken();
3391 Tok.setLocation(PP.getLocForEndOfToken(PrevTokLocation));
3392 Tok.setKind(tok::semi);
Ilya Biryukov929af672019-05-17 09:32:05 +00003393 PP.EnterToken(Tok, /*IsReinject*/ true);
Richard Smithda35e962013-11-09 04:52:51 +00003394
3395 Tok.setKind(tok::r_brace);
3396}
3397
Douglas Gregore8381c02008-11-05 04:29:56 +00003398/// ParseConstructorInitializer - Parse a C++ constructor initializer,
3399/// which explicitly initializes the members or base classes of a
3400/// class (C++ [class.base.init]). For example, the three initializers
3401/// after the ':' in the Derived constructor below:
3402///
3403/// @code
3404/// class Base { };
3405/// class Derived : Base {
3406/// int x;
3407/// float f;
3408/// public:
3409/// Derived(float f) : Base(), x(17), f(f) { }
3410/// };
3411/// @endcode
3412///
Mike Stump11289f42009-09-09 15:08:12 +00003413/// [C++] ctor-initializer:
3414/// ':' mem-initializer-list
Douglas Gregore8381c02008-11-05 04:29:56 +00003415///
Mike Stump11289f42009-09-09 15:08:12 +00003416/// [C++] mem-initializer-list:
Douglas Gregor44e7df62011-01-04 00:32:56 +00003417/// mem-initializer ...[opt]
3418/// mem-initializer ...[opt] , mem-initializer-list
John McCall48871652010-08-21 09:40:31 +00003419void Parser::ParseConstructorInitializer(Decl *ConstructorDecl) {
Nico Weber3b00fdc2015-03-07 19:52:39 +00003420 assert(Tok.is(tok::colon) &&
3421 "Constructor initializer always starts with ':'");
Douglas Gregore8381c02008-11-05 04:29:56 +00003422
Nico Weber3b00fdc2015-03-07 19:52:39 +00003423 // Poison the SEH identifiers so they are flagged as illegal in constructor
3424 // initializers.
John Wiegley1c0675e2011-04-28 01:08:34 +00003425 PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
Douglas Gregore8381c02008-11-05 04:29:56 +00003426 SourceLocation ColonLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +00003427
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003428 SmallVector<CXXCtorInitializer*, 4> MemInitializers;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003429 bool AnyErrors = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003430
Douglas Gregore8381c02008-11-05 04:29:56 +00003431 do {
Douglas Gregoreaeeca92010-08-28 00:00:50 +00003432 if (Tok.is(tok::code_completion)) {
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00003433 Actions.CodeCompleteConstructorInitializer(ConstructorDecl,
3434 MemInitializers);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00003435 return cutOffParsing();
Douglas Gregoreaeeca92010-08-28 00:00:50 +00003436 }
Alexey Bataev79de17d2016-01-20 05:25:51 +00003437
3438 MemInitResult MemInit = ParseMemInitializer(ConstructorDecl);
3439 if (!MemInit.isInvalid())
3440 MemInitializers.push_back(MemInit.get());
3441 else
3442 AnyErrors = true;
3443
Douglas Gregore8381c02008-11-05 04:29:56 +00003444 if (Tok.is(tok::comma))
3445 ConsumeToken();
3446 else if (Tok.is(tok::l_brace))
3447 break;
Alexey Bataev79de17d2016-01-20 05:25:51 +00003448 // If the previous initializer was valid and the next token looks like a
3449 // base or member initializer, assume that we're just missing a comma.
3450 else if (!MemInit.isInvalid() &&
3451 Tok.isOneOf(tok::identifier, tok::coloncolon)) {
Douglas Gregorce66d022010-09-07 14:51:08 +00003452 SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation);
3453 Diag(Loc, diag::err_ctor_init_missing_comma)
3454 << FixItHint::CreateInsertion(Loc, ", ");
3455 } else {
Douglas Gregore8381c02008-11-05 04:29:56 +00003456 // Skip over garbage, until we get to '{'. Don't eat the '{'.
Alexey Bataev79de17d2016-01-20 05:25:51 +00003457 if (!MemInit.isInvalid())
3458 Diag(Tok.getLocation(), diag::err_expected_either) << tok::l_brace
3459 << tok::comma;
Alexey Bataevee6507d2013-11-18 08:17:37 +00003460 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
Douglas Gregore8381c02008-11-05 04:29:56 +00003461 break;
3462 }
3463 } while (true);
3464
David Blaikie3fc2f912013-01-17 05:26:25 +00003465 Actions.ActOnMemInitializers(ConstructorDecl, ColonLoc, MemInitializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003466 AnyErrors);
Douglas Gregore8381c02008-11-05 04:29:56 +00003467}
3468
3469/// ParseMemInitializer - Parse a C++ member initializer, which is
3470/// part of a constructor initializer that explicitly initializes one
3471/// member or base class (C++ [class.base.init]). See
3472/// ParseConstructorInitializer for an example.
3473///
3474/// [C++] mem-initializer:
3475/// mem-initializer-id '(' expression-list[opt] ')'
Sebastian Redl3da34892011-06-05 12:23:16 +00003476/// [C++0x] mem-initializer-id braced-init-list
Mike Stump11289f42009-09-09 15:08:12 +00003477///
Douglas Gregore8381c02008-11-05 04:29:56 +00003478/// [C++] mem-initializer-id:
3479/// '::'[opt] nested-name-specifier[opt] class-name
3480/// identifier
Craig Topper9ad7e262014-10-31 06:57:07 +00003481MemInitResult Parser::ParseMemInitializer(Decl *ConstructorDecl) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00003482 // parse '::'[opt] nested-name-specifier[opt]
3483 CXXScopeSpec SS;
Richard Smithb23c5e82019-05-09 03:31:27 +00003484 if (ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false))
3485 return true;
Richard Smithaf3b3252017-05-18 19:21:48 +00003486
3487 // : identifier
3488 IdentifierInfo *II = nullptr;
3489 SourceLocation IdLoc = Tok.getLocation();
3490 // : declype(...)
3491 DeclSpec DS(AttrFactory);
3492 // : template_name<...>
John McCallba7bf592010-08-24 05:47:05 +00003493 ParsedType TemplateTypeTy;
Richard Smithaf3b3252017-05-18 19:21:48 +00003494
3495 if (Tok.is(tok::identifier)) {
3496 // Get the identifier. This may be a member name or a class name,
3497 // but we'll let the semantic analysis determine which it is.
3498 II = Tok.getIdentifierInfo();
3499 ConsumeToken();
3500 } else if (Tok.is(tok::annot_decltype)) {
3501 // Get the decltype expression, if there is one.
3502 // Uses of decltype will already have been converted to annot_decltype by
3503 // ParseOptionalCXXScopeSpecifier at this point.
3504 // FIXME: Can we get here with a scope specifier?
3505 ParseDecltypeSpecifier(DS);
3506 } else {
3507 TemplateIdAnnotation *TemplateId = Tok.is(tok::annot_template_id)
3508 ? takeTemplateIdAnnotation(Tok)
3509 : nullptr;
3510 if (TemplateId && (TemplateId->Kind == TNK_Type_template ||
Richard Smithb23c5e82019-05-09 03:31:27 +00003511 TemplateId->Kind == TNK_Dependent_template_name ||
3512 TemplateId->Kind == TNK_Undeclared_template)) {
Richard Smith62559bd2017-02-01 21:36:38 +00003513 AnnotateTemplateIdTokenAsType(/*IsClassName*/true);
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00003514 assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
John McCallba7bf592010-08-24 05:47:05 +00003515 TemplateTypeTy = getTypeAnnotation(Tok);
Richard Smithaf3b3252017-05-18 19:21:48 +00003516 ConsumeAnnotationToken();
Richard Smithb23c5e82019-05-09 03:31:27 +00003517 if (!TemplateTypeTy)
3518 return true;
Richard Smithaf3b3252017-05-18 19:21:48 +00003519 } else {
3520 Diag(Tok, diag::err_expected_member_or_base_name);
3521 return true;
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00003522 }
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00003523 }
Douglas Gregore8381c02008-11-05 04:29:56 +00003524
3525 // Parse the '('.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003526 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
Richard Smith5d164bc2011-10-15 05:09:34 +00003527 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
3528
Kadir Cetinkaya84774c32018-09-11 15:02:18 +00003529 // FIXME: Add support for signature help inside initializer lists.
Sebastian Redla74948d2011-09-24 17:48:25 +00003530 ExprResult InitList = ParseBraceInitializer();
3531 if (InitList.isInvalid())
3532 return true;
3533
3534 SourceLocation EllipsisLoc;
Alp Toker094e5212014-01-05 03:27:11 +00003535 TryConsumeToken(tok::ellipsis, EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00003536
3537 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
Fangrui Song6907ce22018-07-30 19:24:48 +00003538 TemplateTypeTy, DS, IdLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003539 InitList.get(), EllipsisLoc);
Sebastian Redl3da34892011-06-05 12:23:16 +00003540 } else if(Tok.is(tok::l_paren)) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003541 BalancedDelimiterTracker T(*this, tok::l_paren);
3542 T.consumeOpen();
Douglas Gregore8381c02008-11-05 04:29:56 +00003543
Sebastian Redl3da34892011-06-05 12:23:16 +00003544 // Parse the optional expression-list.
Benjamin Kramerf0623432012-08-23 22:51:59 +00003545 ExprVector ArgExprs;
Sebastian Redl3da34892011-06-05 12:23:16 +00003546 CommaLocsTy CommaLocs;
Ilya Biryukovff2a9972019-02-26 11:01:50 +00003547 auto RunSignatureHelp = [&] {
3548 QualType PreferredType = Actions.ProduceCtorInitMemberSignatureHelp(
3549 getCurScope(), ConstructorDecl, SS, TemplateTypeTy, ArgExprs, II,
3550 T.getOpenLocation());
3551 CalledSignatureHelp = true;
3552 return PreferredType;
3553 };
Kadir Cetinkaya84774c32018-09-11 15:02:18 +00003554 if (Tok.isNot(tok::r_paren) &&
3555 ParseExpressionList(ArgExprs, CommaLocs, [&] {
Ilya Biryukovff2a9972019-02-26 11:01:50 +00003556 PreferredType.enterFunctionArgument(Tok.getLocation(),
3557 RunSignatureHelp);
Kadir Cetinkaya84774c32018-09-11 15:02:18 +00003558 })) {
Ilya Biryukovff2a9972019-02-26 11:01:50 +00003559 if (PP.isCodeCompletionReached() && !CalledSignatureHelp)
3560 RunSignatureHelp();
Alexey Bataevee6507d2013-11-18 08:17:37 +00003561 SkipUntil(tok::r_paren, StopAtSemi);
Sebastian Redl3da34892011-06-05 12:23:16 +00003562 return true;
3563 }
3564
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003565 T.consumeClose();
Sebastian Redl3da34892011-06-05 12:23:16 +00003566
3567 SourceLocation EllipsisLoc;
Alp Toker97650562014-01-10 11:19:30 +00003568 TryConsumeToken(tok::ellipsis, EllipsisLoc);
Sebastian Redl3da34892011-06-05 12:23:16 +00003569
3570 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
David Blaikie186a8892012-01-24 06:03:59 +00003571 TemplateTypeTy, DS, IdLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00003572 T.getOpenLocation(), ArgExprs,
3573 T.getCloseLocation(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00003574 }
3575
Alp Tokerec543272013-12-24 09:48:30 +00003576 if (getLangOpts().CPlusPlus11)
3577 return Diag(Tok, diag::err_expected_either) << tok::l_paren << tok::l_brace;
3578 else
3579 return Diag(Tok, diag::err_expected) << tok::l_paren;
Douglas Gregore8381c02008-11-05 04:29:56 +00003580}
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003581
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003582/// Parse a C++ exception-specification if present (C++0x [except.spec]).
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003583///
Douglas Gregor356513d2008-12-01 18:00:20 +00003584/// exception-specification:
Sebastian Redl965b0e32011-03-05 14:45:16 +00003585/// dynamic-exception-specification
3586/// noexcept-specification
3587///
3588/// noexcept-specification:
3589/// 'noexcept'
3590/// 'noexcept' '(' constant-expression ')'
3591ExceptionSpecificationType
Richard Smith0b3a4622014-11-13 20:01:57 +00003592Parser::tryParseExceptionSpecification(bool Delayed,
Douglas Gregor433e0532012-04-16 18:27:27 +00003593 SourceRange &SpecificationRange,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003594 SmallVectorImpl<ParsedType> &DynamicExceptions,
3595 SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
Richard Smith0b3a4622014-11-13 20:01:57 +00003596 ExprResult &NoexceptExpr,
3597 CachedTokens *&ExceptionSpecTokens) {
Sebastian Redl965b0e32011-03-05 14:45:16 +00003598 ExceptionSpecificationType Result = EST_None;
Hans Wennborgdcfba332015-10-06 23:40:43 +00003599 ExceptionSpecTokens = nullptr;
Fangrui Song6907ce22018-07-30 19:24:48 +00003600
Richard Smith0b3a4622014-11-13 20:01:57 +00003601 // Handle delayed parsing of exception-specifications.
3602 if (Delayed) {
3603 if (Tok.isNot(tok::kw_throw) && Tok.isNot(tok::kw_noexcept))
3604 return EST_None;
Sebastian Redl965b0e32011-03-05 14:45:16 +00003605
Richard Smith0b3a4622014-11-13 20:01:57 +00003606 // Consume and cache the starting token.
3607 bool IsNoexcept = Tok.is(tok::kw_noexcept);
3608 Token StartTok = Tok;
3609 SpecificationRange = SourceRange(ConsumeToken());
3610
3611 // Check for a '('.
3612 if (!Tok.is(tok::l_paren)) {
3613 // If this is a bare 'noexcept', we're done.
3614 if (IsNoexcept) {
3615 Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
Hans Wennborgdcfba332015-10-06 23:40:43 +00003616 NoexceptExpr = nullptr;
Richard Smith0b3a4622014-11-13 20:01:57 +00003617 return EST_BasicNoexcept;
3618 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003619
Richard Smith0b3a4622014-11-13 20:01:57 +00003620 Diag(Tok, diag::err_expected_lparen_after) << "throw";
3621 return EST_DynamicNone;
3622 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003623
Richard Smith0b3a4622014-11-13 20:01:57 +00003624 // Cache the tokens for the exception-specification.
3625 ExceptionSpecTokens = new CachedTokens;
3626 ExceptionSpecTokens->push_back(StartTok); // 'throw' or 'noexcept'
3627 ExceptionSpecTokens->push_back(Tok); // '('
3628 SpecificationRange.setEnd(ConsumeParen()); // '('
Richard Smithb1c217e2015-01-13 02:24:58 +00003629
3630 ConsumeAndStoreUntil(tok::r_paren, *ExceptionSpecTokens,
3631 /*StopAtSemi=*/true,
3632 /*ConsumeFinalToken=*/true);
Aaron Ballman580ccaf2016-01-12 21:04:22 +00003633 SpecificationRange.setEnd(ExceptionSpecTokens->back().getLocation());
3634
Richard Smith0b3a4622014-11-13 20:01:57 +00003635 return EST_Unparsed;
3636 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003637
Sebastian Redl965b0e32011-03-05 14:45:16 +00003638 // See if there's a dynamic specification.
3639 if (Tok.is(tok::kw_throw)) {
3640 Result = ParseDynamicExceptionSpecification(SpecificationRange,
3641 DynamicExceptions,
3642 DynamicExceptionRanges);
3643 assert(DynamicExceptions.size() == DynamicExceptionRanges.size() &&
3644 "Produced different number of exception types and ranges.");
3645 }
3646
3647 // If there's no noexcept specification, we're done.
3648 if (Tok.isNot(tok::kw_noexcept))
3649 return Result;
3650
Richard Smithb15c11c2011-10-17 23:06:20 +00003651 Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
3652
Sebastian Redl965b0e32011-03-05 14:45:16 +00003653 // If we already had a dynamic specification, parse the noexcept for,
3654 // recovery, but emit a diagnostic and don't store the results.
3655 SourceRange NoexceptRange;
3656 ExceptionSpecificationType NoexceptType = EST_None;
3657
3658 SourceLocation KeywordLoc = ConsumeToken();
3659 if (Tok.is(tok::l_paren)) {
3660 // There is an argument.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003661 BalancedDelimiterTracker T(*this, tok::l_paren);
3662 T.consumeOpen();
Sebastian Redl965b0e32011-03-05 14:45:16 +00003663 NoexceptExpr = ParseConstantExpression();
Serge Pavlov3739f5e72015-06-29 17:50:19 +00003664 T.consumeClose();
Serge Pavlov3739f5e72015-06-29 17:50:19 +00003665 if (!NoexceptExpr.isInvalid()) {
Richard Smitheaf11ad2018-05-03 03:58:32 +00003666 NoexceptExpr = Actions.ActOnNoexceptSpec(KeywordLoc, NoexceptExpr.get(),
3667 NoexceptType);
Serge Pavlov3739f5e72015-06-29 17:50:19 +00003668 NoexceptRange = SourceRange(KeywordLoc, T.getCloseLocation());
3669 } else {
Malcolm Parsonsa3220ce2017-01-12 16:11:28 +00003670 NoexceptType = EST_BasicNoexcept;
Serge Pavlov3739f5e72015-06-29 17:50:19 +00003671 }
Sebastian Redl965b0e32011-03-05 14:45:16 +00003672 } else {
3673 // There is no argument.
3674 NoexceptType = EST_BasicNoexcept;
3675 NoexceptRange = SourceRange(KeywordLoc, KeywordLoc);
3676 }
3677
3678 if (Result == EST_None) {
3679 SpecificationRange = NoexceptRange;
3680 Result = NoexceptType;
3681
3682 // If there's a dynamic specification after a noexcept specification,
3683 // parse that and ignore the results.
3684 if (Tok.is(tok::kw_throw)) {
3685 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
3686 ParseDynamicExceptionSpecification(NoexceptRange, DynamicExceptions,
3687 DynamicExceptionRanges);
3688 }
3689 } else {
3690 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
3691 }
3692
3693 return Result;
3694}
3695
Richard Smith8ca78a12013-06-13 02:02:51 +00003696static void diagnoseDynamicExceptionSpecification(
Craig Toppere335f252015-10-04 04:53:55 +00003697 Parser &P, SourceRange Range, bool IsNoexcept) {
Richard Smith8ca78a12013-06-13 02:02:51 +00003698 if (P.getLangOpts().CPlusPlus11) {
3699 const char *Replacement = IsNoexcept ? "noexcept" : "noexcept(false)";
Richard Smith82da19d2016-12-08 02:49:07 +00003700 P.Diag(Range.getBegin(),
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003701 P.getLangOpts().CPlusPlus17 && !IsNoexcept
Richard Smith82da19d2016-12-08 02:49:07 +00003702 ? diag::ext_dynamic_exception_spec
3703 : diag::warn_exception_spec_deprecated)
3704 << Range;
Richard Smith8ca78a12013-06-13 02:02:51 +00003705 P.Diag(Range.getBegin(), diag::note_exception_spec_deprecated)
3706 << Replacement << FixItHint::CreateReplacement(Range, Replacement);
3707 }
3708}
3709
Sebastian Redl965b0e32011-03-05 14:45:16 +00003710/// ParseDynamicExceptionSpecification - Parse a C++
3711/// dynamic-exception-specification (C++ [except.spec]).
3712///
3713/// dynamic-exception-specification:
Douglas Gregor356513d2008-12-01 18:00:20 +00003714/// 'throw' '(' type-id-list [opt] ')'
3715/// [MS] 'throw' '(' '...' ')'
Mike Stump11289f42009-09-09 15:08:12 +00003716///
Douglas Gregor356513d2008-12-01 18:00:20 +00003717/// type-id-list:
Douglas Gregor830837d2010-12-20 23:57:46 +00003718/// type-id ... [opt]
3719/// type-id-list ',' type-id ... [opt]
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003720///
Sebastian Redl965b0e32011-03-05 14:45:16 +00003721ExceptionSpecificationType Parser::ParseDynamicExceptionSpecification(
3722 SourceRange &SpecificationRange,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003723 SmallVectorImpl<ParsedType> &Exceptions,
3724 SmallVectorImpl<SourceRange> &Ranges) {
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003725 assert(Tok.is(tok::kw_throw) && "expected throw");
Mike Stump11289f42009-09-09 15:08:12 +00003726
Sebastian Redl965b0e32011-03-05 14:45:16 +00003727 SpecificationRange.setBegin(ConsumeToken());
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003728 BalancedDelimiterTracker T(*this, tok::l_paren);
3729 if (T.consumeOpen()) {
Sebastian Redl965b0e32011-03-05 14:45:16 +00003730 Diag(Tok, diag::err_expected_lparen_after) << "throw";
3731 SpecificationRange.setEnd(SpecificationRange.getBegin());
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003732 return EST_DynamicNone;
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003733 }
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003734
Douglas Gregor356513d2008-12-01 18:00:20 +00003735 // Parse throw(...), a Microsoft extension that means "this function
3736 // can throw anything".
3737 if (Tok.is(tok::ellipsis)) {
3738 SourceLocation EllipsisLoc = ConsumeToken();
David Blaikiebbafb8a2012-03-11 07:00:24 +00003739 if (!getLangOpts().MicrosoftExt)
Douglas Gregor356513d2008-12-01 18:00:20 +00003740 Diag(EllipsisLoc, diag::ext_ellipsis_exception_spec);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003741 T.consumeClose();
3742 SpecificationRange.setEnd(T.getCloseLocation());
Richard Smith8ca78a12013-06-13 02:02:51 +00003743 diagnoseDynamicExceptionSpecification(*this, SpecificationRange, false);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003744 return EST_MSAny;
Douglas Gregor356513d2008-12-01 18:00:20 +00003745 }
3746
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003747 // Parse the sequence of type-ids.
Sebastian Redld6434562009-05-29 18:02:33 +00003748 SourceRange Range;
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003749 while (Tok.isNot(tok::r_paren)) {
Sebastian Redld6434562009-05-29 18:02:33 +00003750 TypeResult Res(ParseTypeName(&Range));
Sebastian Redl965b0e32011-03-05 14:45:16 +00003751
Douglas Gregor830837d2010-12-20 23:57:46 +00003752 if (Tok.is(tok::ellipsis)) {
3753 // C++0x [temp.variadic]p5:
Fangrui Song6907ce22018-07-30 19:24:48 +00003754 // - In a dynamic-exception-specification (15.4); the pattern is a
Douglas Gregor830837d2010-12-20 23:57:46 +00003755 // type-id.
3756 SourceLocation Ellipsis = ConsumeToken();
Sebastian Redl965b0e32011-03-05 14:45:16 +00003757 Range.setEnd(Ellipsis);
Douglas Gregor830837d2010-12-20 23:57:46 +00003758 if (!Res.isInvalid())
3759 Res = Actions.ActOnPackExpansion(Res.get(), Ellipsis);
3760 }
Sebastian Redl965b0e32011-03-05 14:45:16 +00003761
Sebastian Redld6434562009-05-29 18:02:33 +00003762 if (!Res.isInvalid()) {
Sebastian Redl2b9cacb2009-04-29 17:30:04 +00003763 Exceptions.push_back(Res.get());
Sebastian Redld6434562009-05-29 18:02:33 +00003764 Ranges.push_back(Range);
3765 }
Alp Toker97650562014-01-10 11:19:30 +00003766
3767 if (!TryConsumeToken(tok::comma))
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003768 break;
3769 }
3770
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003771 T.consumeClose();
3772 SpecificationRange.setEnd(T.getCloseLocation());
Richard Smith8ca78a12013-06-13 02:02:51 +00003773 diagnoseDynamicExceptionSpecification(*this, SpecificationRange,
3774 Exceptions.empty());
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003775 return Exceptions.empty() ? EST_DynamicNone : EST_Dynamic;
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003776}
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003777
Douglas Gregor7fb25412010-10-01 18:44:50 +00003778/// ParseTrailingReturnType - Parse a trailing return type on a new-style
3779/// function declaration.
Richard Smithe303e352018-02-02 22:24:54 +00003780TypeResult Parser::ParseTrailingReturnType(SourceRange &Range,
3781 bool MayBeFollowedByDirectInit) {
Douglas Gregor7fb25412010-10-01 18:44:50 +00003782 assert(Tok.is(tok::arrow) && "expected arrow");
3783
3784 ConsumeToken();
3785
Richard Smithe303e352018-02-02 22:24:54 +00003786 return ParseTypeName(&Range, MayBeFollowedByDirectInit
3787 ? DeclaratorContext::TrailingReturnVarContext
3788 : DeclaratorContext::TrailingReturnContext);
Douglas Gregor7fb25412010-10-01 18:44:50 +00003789}
3790
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003791/// We have just started parsing the definition of a new class,
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003792/// so push that class onto our stack of classes that is currently
3793/// being parsed.
John McCallc1465822011-02-14 07:13:47 +00003794Sema::ParsingClassState
John McCalldb632ac2012-09-25 07:32:39 +00003795Parser::PushParsingClass(Decl *ClassDecl, bool NonNestedClass,
3796 bool IsInterface) {
Douglas Gregoredf8f392010-01-16 20:52:59 +00003797 assert((NonNestedClass || !ClassStack.empty()) &&
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003798 "Nested class without outer class");
John McCalldb632ac2012-09-25 07:32:39 +00003799 ClassStack.push(new ParsingClass(ClassDecl, NonNestedClass, IsInterface));
John McCallc1465822011-02-14 07:13:47 +00003800 return Actions.PushParsingClass();
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003801}
3802
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003803/// Deallocate the given parsed class and all of its nested
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003804/// classes.
3805void Parser::DeallocateParsedClasses(Parser::ParsingClass *Class) {
Douglas Gregorefc46952010-10-12 16:25:54 +00003806 for (unsigned I = 0, N = Class->LateParsedDeclarations.size(); I != N; ++I)
3807 delete Class->LateParsedDeclarations[I];
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003808 delete Class;
3809}
3810
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003811/// Pop the top class of the stack of classes that are
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003812/// currently being parsed.
3813///
3814/// This routine should be called when we have finished parsing the
3815/// definition of a class, but have not yet popped the Scope
3816/// associated with the class's definition.
John McCallc1465822011-02-14 07:13:47 +00003817void Parser::PopParsingClass(Sema::ParsingClassState state) {
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003818 assert(!ClassStack.empty() && "Mismatched push/pop for class parsing");
Mike Stump11289f42009-09-09 15:08:12 +00003819
John McCallc1465822011-02-14 07:13:47 +00003820 Actions.PopParsingClass(state);
3821
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003822 ParsingClass *Victim = ClassStack.top();
3823 ClassStack.pop();
3824 if (Victim->TopLevelClass) {
3825 // Deallocate all of the nested classes of this class,
3826 // recursively: we don't need to keep any of this information.
3827 DeallocateParsedClasses(Victim);
3828 return;
Mike Stump11289f42009-09-09 15:08:12 +00003829 }
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003830 assert(!ClassStack.empty() && "Missing top-level class?");
3831
Douglas Gregorefc46952010-10-12 16:25:54 +00003832 if (Victim->LateParsedDeclarations.empty()) {
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003833 // The victim is a nested class, but we will not need to perform
3834 // any processing after the definition of this class since it has
3835 // no members whose handling was delayed. Therefore, we can just
3836 // remove this nested class.
Douglas Gregorefc46952010-10-12 16:25:54 +00003837 DeallocateParsedClasses(Victim);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003838 return;
3839 }
3840
3841 // This nested class has some members that will need to be processed
3842 // after the top-level class is completely defined. Therefore, add
3843 // it to the list of nested classes within its parent.
Douglas Gregor0be31a22010-07-02 17:43:08 +00003844 assert(getCurScope()->isClassScope() && "Nested class outside of class scope?");
Douglas Gregorefc46952010-10-12 16:25:54 +00003845 ClassStack.top()->LateParsedDeclarations.push_back(new LateParsedClass(this, Victim));
Douglas Gregor0be31a22010-07-02 17:43:08 +00003846 Victim->TemplateScope = getCurScope()->getParent()->isTemplateParamScope();
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003847}
Alexis Hunt96d5c762009-11-21 08:43:09 +00003848
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003849/// Try to parse an 'identifier' which appears within an attribute-token.
Richard Smith3dff2512012-04-10 03:25:07 +00003850///
3851/// \return the parsed identifier on success, and 0 if the next token is not an
3852/// attribute-token.
3853///
3854/// C++11 [dcl.attr.grammar]p3:
3855/// If a keyword or an alternative token that satisfies the syntactic
3856/// requirements of an identifier is contained in an attribute-token,
3857/// it is considered an identifier.
3858IdentifierInfo *Parser::TryParseCXX11AttributeIdentifier(SourceLocation &Loc) {
3859 switch (Tok.getKind()) {
3860 default:
3861 // Identifiers and keywords have identifier info attached.
David Majnemerd5271992015-01-09 18:09:39 +00003862 if (!Tok.isAnnotation()) {
3863 if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
3864 Loc = ConsumeToken();
3865 return II;
3866 }
Richard Smith3dff2512012-04-10 03:25:07 +00003867 }
Craig Topper161e4db2014-05-21 06:02:52 +00003868 return nullptr;
Richard Smith3dff2512012-04-10 03:25:07 +00003869
Aaron Ballmanc44c17422018-11-09 17:19:45 +00003870 case tok::numeric_constant: {
3871 // If we got a numeric constant, check to see if it comes from a macro that
3872 // corresponds to the predefined __clang__ macro. If it does, warn the user
3873 // and recover by pretending they said _Clang instead.
3874 if (Tok.getLocation().isMacroID()) {
3875 SmallString<8> ExpansionBuf;
3876 SourceLocation ExpansionLoc =
3877 PP.getSourceManager().getExpansionLoc(Tok.getLocation());
3878 StringRef Spelling = PP.getSpelling(ExpansionLoc, ExpansionBuf);
3879 if (Spelling == "__clang__") {
3880 SourceRange TokRange(
3881 ExpansionLoc,
3882 PP.getSourceManager().getExpansionLoc(Tok.getEndLoc()));
3883 Diag(Tok, diag::warn_wrong_clang_attr_namespace)
3884 << FixItHint::CreateReplacement(TokRange, "_Clang");
3885 Loc = ConsumeToken();
3886 return &PP.getIdentifierTable().get("_Clang");
3887 }
3888 }
3889 return nullptr;
3890 }
3891
Richard Smith3dff2512012-04-10 03:25:07 +00003892 case tok::ampamp: // 'and'
3893 case tok::pipe: // 'bitor'
3894 case tok::pipepipe: // 'or'
3895 case tok::caret: // 'xor'
3896 case tok::tilde: // 'compl'
3897 case tok::amp: // 'bitand'
3898 case tok::ampequal: // 'and_eq'
3899 case tok::pipeequal: // 'or_eq'
3900 case tok::caretequal: // 'xor_eq'
3901 case tok::exclaim: // 'not'
3902 case tok::exclaimequal: // 'not_eq'
3903 // Alternative tokens do not have identifier info, but their spelling
3904 // starts with an alphabetical character.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003905 SmallString<8> SpellingBuf;
Benjamin Kramer60be5632015-03-29 19:25:07 +00003906 SourceLocation SpellingLoc =
3907 PP.getSourceManager().getSpellingLoc(Tok.getLocation());
3908 StringRef Spelling = PP.getSpelling(SpellingLoc, SpellingBuf);
Jordan Rosea7d03842013-02-08 22:30:41 +00003909 if (isLetter(Spelling[0])) {
Richard Smith3dff2512012-04-10 03:25:07 +00003910 Loc = ConsumeToken();
Benjamin Kramer5c17f9c2012-04-22 20:43:30 +00003911 return &PP.getIdentifierTable().get(Spelling);
Richard Smith3dff2512012-04-10 03:25:07 +00003912 }
Craig Topper161e4db2014-05-21 06:02:52 +00003913 return nullptr;
Richard Smith3dff2512012-04-10 03:25:07 +00003914 }
3915}
3916
Michael Han23214e52012-10-03 01:56:22 +00003917static bool IsBuiltInOrStandardCXX11Attribute(IdentifierInfo *AttrName,
Aaron Ballman606093a2017-10-15 15:01:42 +00003918 IdentifierInfo *ScopeName) {
Erich Keane6a24e802019-09-13 17:39:31 +00003919 switch (
3920 ParsedAttr::getParsedKind(AttrName, ScopeName, ParsedAttr::AS_CXX11)) {
Erich Keanee891aa92018-07-13 15:07:47 +00003921 case ParsedAttr::AT_CarriesDependency:
3922 case ParsedAttr::AT_Deprecated:
3923 case ParsedAttr::AT_FallThrough:
3924 case ParsedAttr::AT_CXX11NoReturn:
Richard Smith78b239e2019-06-20 20:44:45 +00003925 case ParsedAttr::AT_NoUniqueAddress:
Michael Han23214e52012-10-03 01:56:22 +00003926 return true;
Erich Keanee891aa92018-07-13 15:07:47 +00003927 case ParsedAttr::AT_WarnUnusedResult:
Aaron Ballmane7964782016-03-07 22:44:55 +00003928 return !ScopeName && AttrName->getName().equals("nodiscard");
Erich Keanee891aa92018-07-13 15:07:47 +00003929 case ParsedAttr::AT_Unused:
Nico Weberac03bce2016-08-23 19:59:55 +00003930 return !ScopeName && AttrName->getName().equals("maybe_unused");
Michael Han23214e52012-10-03 01:56:22 +00003931 default:
3932 return false;
3933 }
3934}
3935
Aaron Ballmanb8e20392014-03-31 17:32:39 +00003936/// ParseCXX11AttributeArgs -- Parse a C++11 attribute-argument-clause.
3937///
3938/// [C++11] attribute-argument-clause:
3939/// '(' balanced-token-seq ')'
3940///
3941/// [C++11] balanced-token-seq:
3942/// balanced-token
3943/// balanced-token-seq balanced-token
3944///
3945/// [C++11] balanced-token:
3946/// '(' balanced-token-seq ')'
3947/// '[' balanced-token-seq ']'
3948/// '{' balanced-token-seq '}'
3949/// any token but '(', ')', '[', ']', '{', or '}'
3950bool Parser::ParseCXX11AttributeArgs(IdentifierInfo *AttrName,
3951 SourceLocation AttrNameLoc,
3952 ParsedAttributes &Attrs,
3953 SourceLocation *EndLoc,
3954 IdentifierInfo *ScopeName,
3955 SourceLocation ScopeLoc) {
3956 assert(Tok.is(tok::l_paren) && "Not a C++11 attribute argument list");
Aaron Ballman35f94212014-04-14 16:03:22 +00003957 SourceLocation LParenLoc = Tok.getLocation();
Aaron Ballman606093a2017-10-15 15:01:42 +00003958 const LangOptions &LO = getLangOpts();
Erich Keanee891aa92018-07-13 15:07:47 +00003959 ParsedAttr::Syntax Syntax =
3960 LO.CPlusPlus ? ParsedAttr::AS_CXX11 : ParsedAttr::AS_C2x;
Aaron Ballmanb8e20392014-03-31 17:32:39 +00003961
3962 // If the attribute isn't known, we will not attempt to parse any
3963 // arguments.
Aaron Ballman606093a2017-10-15 15:01:42 +00003964 if (!hasAttribute(LO.CPlusPlus ? AttrSyntax::CXX : AttrSyntax::C, ScopeName,
3965 AttrName, getTargetInfo(), getLangOpts())) {
Aaron Ballmanb8e20392014-03-31 17:32:39 +00003966 // Eat the left paren, then skip to the ending right paren.
3967 ConsumeParen();
3968 SkipUntil(tok::r_paren);
Aaron Ballmanc44c17422018-11-09 17:19:45 +00003969 return false;
3970 }
3971
3972 if (ScopeName && (ScopeName->isStr("gnu") || ScopeName->isStr("__gnu__"))) {
3973 // GNU-scoped attributes have some special cases to handle GNU-specific
3974 // behaviors.
3975 ParseGNUAttributeArgs(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
Aaron Ballman606093a2017-10-15 15:01:42 +00003976 ScopeLoc, Syntax, nullptr);
Alex Lorenzd5d27e12017-03-01 18:06:25 +00003977 return true;
3978 }
3979
3980 unsigned NumArgs;
3981 // Some Clang-scoped attributes have some special parsing behavior.
Aaron Ballmanc44c17422018-11-09 17:19:45 +00003982 if (ScopeName && (ScopeName->isStr("clang") || ScopeName->isStr("_Clang")))
3983 NumArgs = ParseClangAttributeArgs(AttrName, AttrNameLoc, Attrs, EndLoc,
3984 ScopeName, ScopeLoc, Syntax);
Alex Lorenzd5d27e12017-03-01 18:06:25 +00003985 else
3986 NumArgs =
Aaron Ballman35f94212014-04-14 16:03:22 +00003987 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc,
Aaron Ballman606093a2017-10-15 15:01:42 +00003988 ScopeName, ScopeLoc, Syntax);
Alex Lorenzd5d27e12017-03-01 18:06:25 +00003989
Erich Keanec480f302018-07-12 21:09:05 +00003990 if (!Attrs.empty() &&
3991 IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName)) {
Michael Krusedc5ce722018-08-03 01:21:16 +00003992 ParsedAttr &Attr = Attrs.back();
Alex Lorenzd5d27e12017-03-01 18:06:25 +00003993 // If the attribute is a standard or built-in attribute and we are
3994 // parsing an argument list, we need to determine whether this attribute
3995 // was allowed to have an argument list (such as [[deprecated]]), and how
3996 // many arguments were parsed (so we can diagnose on [[deprecated()]]).
Erich Keanec480f302018-07-12 21:09:05 +00003997 if (Attr.getMaxArgs() && !NumArgs) {
Alex Lorenzd5d27e12017-03-01 18:06:25 +00003998 // The attribute was allowed to have arguments, but none were provided
3999 // even though the attribute parsed successfully. This is an error.
4000 Diag(LParenLoc, diag::err_attribute_requires_arguments) << AttrName;
Erich Keanec480f302018-07-12 21:09:05 +00004001 Attr.setInvalid(true);
4002 } else if (!Attr.getMaxArgs()) {
Alex Lorenzd5d27e12017-03-01 18:06:25 +00004003 // The attribute parsed successfully, but was not allowed to have any
4004 // arguments. It doesn't matter whether any were provided -- the
4005 // presence of the argument list (even if empty) is diagnosed.
4006 Diag(LParenLoc, diag::err_cxx11_attribute_forbids_arguments)
4007 << AttrName
4008 << FixItHint::CreateRemoval(SourceRange(LParenLoc, *EndLoc));
Erich Keanec480f302018-07-12 21:09:05 +00004009 Attr.setInvalid(true);
Aaron Ballman35f94212014-04-14 16:03:22 +00004010 }
4011 }
Aaron Ballmanb8e20392014-03-31 17:32:39 +00004012 return true;
4013}
4014
Aaron Ballman606093a2017-10-15 15:01:42 +00004015/// ParseCXX11AttributeSpecifier - Parse a C++11 or C2x attribute-specifier.
Alexis Hunt96d5c762009-11-21 08:43:09 +00004016///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004017/// [C++11] attribute-specifier:
Alexis Hunt96d5c762009-11-21 08:43:09 +00004018/// '[' '[' attribute-list ']' ']'
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00004019/// alignment-specifier
Alexis Hunt96d5c762009-11-21 08:43:09 +00004020///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004021/// [C++11] attribute-list:
Alexis Hunt96d5c762009-11-21 08:43:09 +00004022/// attribute[opt]
4023/// attribute-list ',' attribute[opt]
Richard Smith3dff2512012-04-10 03:25:07 +00004024/// attribute '...'
4025/// attribute-list ',' attribute '...'
Alexis Hunt96d5c762009-11-21 08:43:09 +00004026///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004027/// [C++11] attribute:
Alexis Hunt96d5c762009-11-21 08:43:09 +00004028/// attribute-token attribute-argument-clause[opt]
4029///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004030/// [C++11] attribute-token:
Alexis Hunt96d5c762009-11-21 08:43:09 +00004031/// identifier
4032/// attribute-scoped-token
4033///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004034/// [C++11] attribute-scoped-token:
Alexis Hunt96d5c762009-11-21 08:43:09 +00004035/// attribute-namespace '::' identifier
4036///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004037/// [C++11] attribute-namespace:
Alexis Hunt96d5c762009-11-21 08:43:09 +00004038/// identifier
Richard Smith3dff2512012-04-10 03:25:07 +00004039void Parser::ParseCXX11AttributeSpecifier(ParsedAttributes &attrs,
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004040 SourceLocation *endLoc) {
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00004041 if (Tok.is(tok::kw_alignas)) {
Richard Smithf679b5b2011-10-14 20:48:27 +00004042 Diag(Tok.getLocation(), diag::warn_cxx98_compat_alignas);
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00004043 ParseAlignmentSpecifier(attrs, endLoc);
4044 return;
4045 }
4046
Aaron Ballman606093a2017-10-15 15:01:42 +00004047 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square) &&
4048 "Not a double square bracket attribute list");
Alexis Hunt96d5c762009-11-21 08:43:09 +00004049
Richard Smithf679b5b2011-10-14 20:48:27 +00004050 Diag(Tok.getLocation(), diag::warn_cxx98_compat_attribute);
4051
Alexis Hunt96d5c762009-11-21 08:43:09 +00004052 ConsumeBracket();
4053 ConsumeBracket();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004054
Richard Smithb7d7a042016-06-24 12:15:12 +00004055 SourceLocation CommonScopeLoc;
4056 IdentifierInfo *CommonScopeName = nullptr;
4057 if (Tok.is(tok::kw_using)) {
Aaron Ballmanc351fba2017-12-04 20:27:34 +00004058 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
Richard Smithb7d7a042016-06-24 12:15:12 +00004059 ? diag::warn_cxx14_compat_using_attribute_ns
4060 : diag::ext_using_attribute_ns);
4061 ConsumeToken();
4062
4063 CommonScopeName = TryParseCXX11AttributeIdentifier(CommonScopeLoc);
4064 if (!CommonScopeName) {
4065 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
4066 SkipUntil(tok::r_square, tok::colon, StopBeforeMatch);
4067 }
4068 if (!TryConsumeToken(tok::colon) && CommonScopeName)
4069 Diag(Tok.getLocation(), diag::err_expected) << tok::colon;
4070 }
4071
Richard Smith10876ef2013-01-17 01:30:42 +00004072 llvm::SmallDenseMap<IdentifierInfo*, SourceLocation, 4> SeenAttrs;
4073
Richard Smith3dff2512012-04-10 03:25:07 +00004074 while (Tok.isNot(tok::r_square)) {
Alexis Hunt96d5c762009-11-21 08:43:09 +00004075 // attribute not present
Alp Toker97650562014-01-10 11:19:30 +00004076 if (TryConsumeToken(tok::comma))
Alexis Hunt96d5c762009-11-21 08:43:09 +00004077 continue;
Alexis Hunt96d5c762009-11-21 08:43:09 +00004078
Richard Smith3dff2512012-04-10 03:25:07 +00004079 SourceLocation ScopeLoc, AttrLoc;
Craig Topper161e4db2014-05-21 06:02:52 +00004080 IdentifierInfo *ScopeName = nullptr, *AttrName = nullptr;
Richard Smith3dff2512012-04-10 03:25:07 +00004081
4082 AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
4083 if (!AttrName)
4084 // Break out to the "expected ']'" diagnostic.
4085 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004086
Alexis Hunt96d5c762009-11-21 08:43:09 +00004087 // scoped attribute
Alp Toker97650562014-01-10 11:19:30 +00004088 if (TryConsumeToken(tok::coloncolon)) {
Richard Smith3dff2512012-04-10 03:25:07 +00004089 ScopeName = AttrName;
4090 ScopeLoc = AttrLoc;
4091
4092 AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
4093 if (!AttrName) {
Alp Tokerec543272013-12-24 09:48:30 +00004094 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
Alexey Bataevee6507d2013-11-18 08:17:37 +00004095 SkipUntil(tok::r_square, tok::comma, StopAtSemi | StopBeforeMatch);
Alexis Hunt96d5c762009-11-21 08:43:09 +00004096 continue;
4097 }
Alexis Hunt96d5c762009-11-21 08:43:09 +00004098 }
4099
Richard Smithb7d7a042016-06-24 12:15:12 +00004100 if (CommonScopeName) {
4101 if (ScopeName) {
4102 Diag(ScopeLoc, diag::err_using_attribute_ns_conflict)
4103 << SourceRange(CommonScopeLoc);
4104 } else {
4105 ScopeName = CommonScopeName;
4106 ScopeLoc = CommonScopeLoc;
4107 }
4108 }
4109
Aaron Ballmanb8e20392014-03-31 17:32:39 +00004110 bool StandardAttr = IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName);
Alexis Hunt96d5c762009-11-21 08:43:09 +00004111 bool AttrParsed = false;
Alexis Hunt96d5c762009-11-21 08:43:09 +00004112
Richard Smith10876ef2013-01-17 01:30:42 +00004113 if (StandardAttr &&
4114 !SeenAttrs.insert(std::make_pair(AttrName, AttrLoc)).second)
4115 Diag(AttrLoc, diag::err_cxx11_attribute_repeated)
Aaron Ballmanb8e20392014-03-31 17:32:39 +00004116 << AttrName << SourceRange(SeenAttrs[AttrName]);
Richard Smith10876ef2013-01-17 01:30:42 +00004117
Michael Han23214e52012-10-03 01:56:22 +00004118 // Parse attribute arguments
Aaron Ballman35f94212014-04-14 16:03:22 +00004119 if (Tok.is(tok::l_paren))
Aaron Ballmanb8e20392014-03-31 17:32:39 +00004120 AttrParsed = ParseCXX11AttributeArgs(AttrName, AttrLoc, attrs, endLoc,
4121 ScopeName, ScopeLoc);
Michael Han23214e52012-10-03 01:56:22 +00004122
4123 if (!AttrParsed)
Aaron Ballman606093a2017-10-15 15:01:42 +00004124 attrs.addNew(
4125 AttrName,
4126 SourceRange(ScopeLoc.isValid() ? ScopeLoc : AttrLoc, AttrLoc),
4127 ScopeName, ScopeLoc, nullptr, 0,
Erich Keanee891aa92018-07-13 15:07:47 +00004128 getLangOpts().CPlusPlus ? ParsedAttr::AS_CXX11 : ParsedAttr::AS_C2x);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004129
Alp Toker97650562014-01-10 11:19:30 +00004130 if (TryConsumeToken(tok::ellipsis))
Michael Han23214e52012-10-03 01:56:22 +00004131 Diag(Tok, diag::err_cxx11_attribute_forbids_ellipsis)
Richard Trieub4025802018-03-28 04:16:13 +00004132 << AttrName;
Alexis Hunt96d5c762009-11-21 08:43:09 +00004133 }
4134
Alp Toker383d2c42014-01-01 03:08:43 +00004135 if (ExpectAndConsume(tok::r_square))
Alexey Bataevee6507d2013-11-18 08:17:37 +00004136 SkipUntil(tok::r_square);
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004137 if (endLoc)
4138 *endLoc = Tok.getLocation();
Alp Toker383d2c42014-01-01 03:08:43 +00004139 if (ExpectAndConsume(tok::r_square))
Alexey Bataevee6507d2013-11-18 08:17:37 +00004140 SkipUntil(tok::r_square);
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004141}
Alexis Hunt96d5c762009-11-21 08:43:09 +00004142
Aaron Ballman606093a2017-10-15 15:01:42 +00004143/// ParseCXX11Attributes - Parse a C++11 or C2x attribute-specifier-seq.
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004144///
4145/// attribute-specifier-seq:
4146/// attribute-specifier-seq[opt] attribute-specifier
Richard Smith3dff2512012-04-10 03:25:07 +00004147void Parser::ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004148 SourceLocation *endLoc) {
Aaron Ballman606093a2017-10-15 15:01:42 +00004149 assert(standardAttributesAllowed());
Richard Smith4cabd042013-02-22 09:15:49 +00004150
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004151 SourceLocation StartLoc = Tok.getLocation(), Loc;
4152 if (!endLoc)
4153 endLoc = &Loc;
4154
Douglas Gregor6f981002011-10-07 20:35:25 +00004155 do {
Richard Smith3dff2512012-04-10 03:25:07 +00004156 ParseCXX11AttributeSpecifier(attrs, endLoc);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004157 } while (isCXX11AttributeSpecifier());
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004158
4159 attrs.Range = SourceRange(StartLoc, *endLoc);
Alexis Hunt96d5c762009-11-21 08:43:09 +00004160}
4161
Richard Smithc2c8bb82013-10-15 01:34:54 +00004162void Parser::DiagnoseAndSkipCXX11Attributes() {
Richard Smithc2c8bb82013-10-15 01:34:54 +00004163 // Start and end location of an attribute or an attribute list.
4164 SourceLocation StartLoc = Tok.getLocation();
Richard Smith955bf012014-06-19 11:42:00 +00004165 SourceLocation EndLoc = SkipCXX11Attributes();
4166
4167 if (EndLoc.isValid()) {
4168 SourceRange Range(StartLoc, EndLoc);
4169 Diag(StartLoc, diag::err_attributes_not_allowed)
4170 << Range;
4171 }
4172}
4173
4174SourceLocation Parser::SkipCXX11Attributes() {
Richard Smithc2c8bb82013-10-15 01:34:54 +00004175 SourceLocation EndLoc;
4176
Richard Smith955bf012014-06-19 11:42:00 +00004177 if (!isCXX11AttributeSpecifier())
4178 return EndLoc;
4179
Richard Smithc2c8bb82013-10-15 01:34:54 +00004180 do {
4181 if (Tok.is(tok::l_square)) {
4182 BalancedDelimiterTracker T(*this, tok::l_square);
4183 T.consumeOpen();
4184 T.skipToEnd();
4185 EndLoc = T.getCloseLocation();
4186 } else {
4187 assert(Tok.is(tok::kw_alignas) && "not an attribute specifier");
4188 ConsumeToken();
4189 BalancedDelimiterTracker T(*this, tok::l_paren);
4190 if (!T.consumeOpen())
4191 T.skipToEnd();
4192 EndLoc = T.getCloseLocation();
4193 }
4194 } while (isCXX11AttributeSpecifier());
4195
Richard Smith955bf012014-06-19 11:42:00 +00004196 return EndLoc;
Richard Smithc2c8bb82013-10-15 01:34:54 +00004197}
4198
Nico Weber05e1dad2016-09-03 03:25:22 +00004199/// Parse uuid() attribute when it appears in a [] Microsoft attribute.
4200void Parser::ParseMicrosoftUuidAttributeArgs(ParsedAttributes &Attrs) {
4201 assert(Tok.is(tok::identifier) && "Not a Microsoft attribute list");
4202 IdentifierInfo *UuidIdent = Tok.getIdentifierInfo();
4203 assert(UuidIdent->getName() == "uuid" && "Not a Microsoft attribute list");
4204
4205 SourceLocation UuidLoc = Tok.getLocation();
4206 ConsumeToken();
4207
4208 // Ignore the left paren location for now.
4209 BalancedDelimiterTracker T(*this, tok::l_paren);
4210 if (T.consumeOpen()) {
4211 Diag(Tok, diag::err_expected) << tok::l_paren;
4212 return;
4213 }
4214
4215 ArgsVector ArgExprs;
4216 if (Tok.is(tok::string_literal)) {
4217 // Easy case: uuid("...") -- quoted string.
4218 ExprResult StringResult = ParseStringLiteralExpression();
4219 if (StringResult.isInvalid())
4220 return;
4221 ArgExprs.push_back(StringResult.get());
4222 } else {
4223 // something like uuid({000000A0-0000-0000-C000-000000000049}) -- no
4224 // quotes in the parens. Just append the spelling of all tokens encountered
4225 // until the closing paren.
4226
4227 SmallString<42> StrBuffer; // 2 "", 36 bytes UUID, 2 optional {}, 1 nul
4228 StrBuffer += "\"";
4229
4230 // Since none of C++'s keywords match [a-f]+, accepting just tok::l_brace,
4231 // tok::r_brace, tok::minus, tok::identifier (think C000) and
4232 // tok::numeric_constant (0000) should be enough. But the spelling of the
4233 // uuid argument is checked later anyways, so there's no harm in accepting
4234 // almost anything here.
4235 // cl is very strict about whitespace in this form and errors out if any
4236 // is present, so check the space flags on the tokens.
4237 SourceLocation StartLoc = Tok.getLocation();
4238 while (Tok.isNot(tok::r_paren)) {
4239 if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
4240 Diag(Tok, diag::err_attribute_uuid_malformed_guid);
4241 SkipUntil(tok::r_paren, StopAtSemi);
4242 return;
4243 }
4244 SmallString<16> SpellingBuffer;
4245 SpellingBuffer.resize(Tok.getLength() + 1);
4246 bool Invalid = false;
4247 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
4248 if (Invalid) {
4249 SkipUntil(tok::r_paren, StopAtSemi);
4250 return;
4251 }
4252 StrBuffer += TokSpelling;
4253 ConsumeAnyToken();
4254 }
4255 StrBuffer += "\"";
4256
4257 if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
4258 Diag(Tok, diag::err_attribute_uuid_malformed_guid);
4259 ConsumeParen();
4260 return;
4261 }
4262
4263 // Pretend the user wrote the appropriate string literal here.
4264 // ActOnStringLiteral() copies the string data into the literal, so it's
4265 // ok that the Token points to StrBuffer.
4266 Token Toks[1];
4267 Toks[0].startToken();
4268 Toks[0].setKind(tok::string_literal);
4269 Toks[0].setLocation(StartLoc);
4270 Toks[0].setLiteralData(StrBuffer.data());
4271 Toks[0].setLength(StrBuffer.size());
4272 StringLiteral *UuidString =
4273 cast<StringLiteral>(Actions.ActOnStringLiteral(Toks, nullptr).get());
4274 ArgExprs.push_back(UuidString);
4275 }
4276
4277 if (!T.consumeClose()) {
Nico Weber05e1dad2016-09-03 03:25:22 +00004278 Attrs.addNew(UuidIdent, SourceRange(UuidLoc, T.getCloseLocation()), nullptr,
4279 SourceLocation(), ArgExprs.data(), ArgExprs.size(),
Erich Keanee891aa92018-07-13 15:07:47 +00004280 ParsedAttr::AS_Microsoft);
Nico Weber05e1dad2016-09-03 03:25:22 +00004281 }
4282}
4283
David Majnemere4752e752015-07-08 05:55:00 +00004284/// ParseMicrosoftAttributes - Parse Microsoft attributes [Attr]
Francois Pichetc2bc5ac2010-10-11 12:59:39 +00004285///
4286/// [MS] ms-attribute:
4287/// '[' token-seq ']'
4288///
4289/// [MS] ms-attribute-seq:
4290/// ms-attribute[opt]
4291/// ms-attribute ms-attribute-seq
John McCall53fa7142010-12-24 02:08:15 +00004292void Parser::ParseMicrosoftAttributes(ParsedAttributes &attrs,
4293 SourceLocation *endLoc) {
Francois Pichetc2bc5ac2010-10-11 12:59:39 +00004294 assert(Tok.is(tok::l_square) && "Not a Microsoft attribute list");
4295
Saleem Abdulrasool425efcf2015-06-15 20:57:04 +00004296 do {
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004297 // FIXME: If this is actually a C++11 attribute, parse it as one.
Saleem Abdulrasool425efcf2015-06-15 20:57:04 +00004298 BalancedDelimiterTracker T(*this, tok::l_square);
4299 T.consumeOpen();
Nico Weber05e1dad2016-09-03 03:25:22 +00004300
4301 // Skip most ms attributes except for a whitelist.
4302 while (true) {
4303 SkipUntil(tok::r_square, tok::identifier, StopAtSemi | StopBeforeMatch);
4304 if (Tok.isNot(tok::identifier)) // ']', but also eof
4305 break;
4306 if (Tok.getIdentifierInfo()->getName() == "uuid")
4307 ParseMicrosoftUuidAttributeArgs(attrs);
4308 else
4309 ConsumeToken();
4310 }
4311
Saleem Abdulrasool425efcf2015-06-15 20:57:04 +00004312 T.consumeClose();
4313 if (endLoc)
4314 *endLoc = T.getCloseLocation();
4315 } while (Tok.is(tok::l_square));
Francois Pichetc2bc5ac2010-10-11 12:59:39 +00004316}
Francois Pichet8f981d52011-05-25 10:19:49 +00004317
Erich Keanec480f302018-07-12 21:09:05 +00004318void Parser::ParseMicrosoftIfExistsClassDeclaration(
4319 DeclSpec::TST TagType, ParsedAttributes &AccessAttrs,
4320 AccessSpecifier &CurAS) {
Douglas Gregor43edb322011-10-24 22:31:10 +00004321 IfExistsCondition Result;
Francois Pichet8f981d52011-05-25 10:19:49 +00004322 if (ParseMicrosoftIfExistsCondition(Result))
4323 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00004324
Douglas Gregor43edb322011-10-24 22:31:10 +00004325 BalancedDelimiterTracker Braces(*this, tok::l_brace);
4326 if (Braces.consumeOpen()) {
Alp Tokerec543272013-12-24 09:48:30 +00004327 Diag(Tok, diag::err_expected) << tok::l_brace;
Francois Pichet8f981d52011-05-25 10:19:49 +00004328 return;
4329 }
Francois Pichet8f981d52011-05-25 10:19:49 +00004330
Douglas Gregor43edb322011-10-24 22:31:10 +00004331 switch (Result.Behavior) {
4332 case IEB_Parse:
4333 // Parse the declarations below.
4334 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00004335
Douglas Gregor43edb322011-10-24 22:31:10 +00004336 case IEB_Dependent:
4337 Diag(Result.KeywordLoc, diag::warn_microsoft_dependent_exists)
4338 << Result.IsIfExists;
4339 // Fall through to skip.
Galina Kistanovad819d5b2017-06-01 21:19:06 +00004340 LLVM_FALLTHROUGH;
Fangrui Song6907ce22018-07-30 19:24:48 +00004341
Douglas Gregor43edb322011-10-24 22:31:10 +00004342 case IEB_Skip:
4343 Braces.skipToEnd();
Francois Pichet8f981d52011-05-25 10:19:49 +00004344 return;
4345 }
4346
Richard Smith34f30512013-11-23 04:06:09 +00004347 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
Francois Pichet8f981d52011-05-25 10:19:49 +00004348 // __if_exists, __if_not_exists can nest.
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00004349 if (Tok.isOneOf(tok::kw___if_exists, tok::kw___if_not_exists)) {
Serge Pavlov0c503192019-08-01 11:46:28 +00004350 ParseMicrosoftIfExistsClassDeclaration(TagType,
Erich Keanec480f302018-07-12 21:09:05 +00004351 AccessAttrs, CurAS);
Francois Pichet8f981d52011-05-25 10:19:49 +00004352 continue;
4353 }
4354
4355 // Check for extraneous top-level semicolon.
4356 if (Tok.is(tok::semi)) {
Richard Smith87f5dc52012-07-23 05:45:25 +00004357 ConsumeExtraSemi(InsideStruct, TagType);
Francois Pichet8f981d52011-05-25 10:19:49 +00004358 continue;
4359 }
4360
4361 AccessSpecifier AS = getAccessSpecifierIfPresent();
4362 if (AS != AS_none) {
4363 // Current token is a C++ access specifier.
4364 CurAS = AS;
4365 SourceLocation ASLoc = Tok.getLocation();
4366 ConsumeToken();
4367 if (Tok.is(tok::colon))
Erich Keanec480f302018-07-12 21:09:05 +00004368 Actions.ActOnAccessSpecifier(AS, ASLoc, Tok.getLocation(),
4369 ParsedAttributesView{});
Francois Pichet8f981d52011-05-25 10:19:49 +00004370 else
Alp Toker35d87032013-12-30 23:29:50 +00004371 Diag(Tok, diag::err_expected) << tok::colon;
Francois Pichet8f981d52011-05-25 10:19:49 +00004372 ConsumeToken();
4373 continue;
4374 }
4375
4376 // Parse all the comma separated declarators.
Erich Keanec480f302018-07-12 21:09:05 +00004377 ParseCXXClassMemberDeclaration(CurAS, AccessAttrs);
Francois Pichet8f981d52011-05-25 10:19:49 +00004378 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004379
Douglas Gregor43edb322011-10-24 22:31:10 +00004380 Braces.consumeClose();
Francois Pichet8f981d52011-05-25 10:19:49 +00004381}