blob: 86a9a8208b2eb5caa16feac1b49cccb4f96600b6 [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.
Haojian Wu0dd0b102020-03-19 09:12:29 +0100293 ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
294 /*ObjectHadErrors=*/false,
295 /*EnteringContext=*/false,
Matthias Gehredc01bb42017-03-17 21:41:20 +0000296 /*MayBePseudoDestructor=*/nullptr,
297 /*IsTypename=*/false,
298 /*LastII=*/nullptr,
299 /*OnlyNamespace=*/true);
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000300
Matthias Gehredc01bb42017-03-17 21:41:20 +0000301 if (Tok.isNot(tok::identifier)) {
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000302 Diag(Tok, diag::err_expected_namespace_name);
303 // Skip to end of the definition and eat the ';'.
304 SkipUntil(tok::semi);
Craig Topper161e4db2014-05-21 06:02:52 +0000305 return nullptr;
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000306 }
307
Matthias Gehredc01bb42017-03-17 21:41:20 +0000308 if (SS.isInvalid()) {
309 // Diagnostics have been emitted in ParseOptionalCXXScopeSpecifier.
310 // Skip to end of the definition and eat the ';'.
311 SkipUntil(tok::semi);
312 return nullptr;
313 }
314
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000315 // Parse identifier.
Anders Carlsson47952ae2009-03-28 22:53:22 +0000316 IdentifierInfo *Ident = Tok.getIdentifierInfo();
317 SourceLocation IdentLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000318
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000319 // Eat the ';'.
Chris Lattner49836b42009-04-02 04:16:50 +0000320 DeclEnd = Tok.getLocation();
Alp Toker383d2c42014-01-01 03:08:43 +0000321 if (ExpectAndConsume(tok::semi, diag::err_expected_semi_after_namespace_name))
322 SkipUntil(tok::semi);
Mike Stump11289f42009-09-09 15:08:12 +0000323
Craig Topperff354282015-11-14 18:16:00 +0000324 return Actions.ActOnNamespaceAliasDef(getCurScope(), NamespaceLoc, AliasLoc,
325 Alias, SS, IdentLoc, Ident);
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000326}
327
Chris Lattner38376f12008-01-12 07:05:38 +0000328/// ParseLinkage - We know that the current token is a string_literal
329/// and just before that, that extern was seen.
330///
331/// linkage-specification: [C++ 7.5p2: dcl.link]
332/// 'extern' string-literal '{' declaration-seq[opt] '}'
333/// 'extern' string-literal declaration
334///
Faisal Vali421b2d12017-12-29 05:41:00 +0000335Decl *Parser::ParseLinkage(ParsingDeclSpec &DS, DeclaratorContext Context) {
Richard Smith4ee696d2014-02-17 23:25:27 +0000336 assert(isTokenStringLiteral() && "Not a string literal!");
337 ExprResult Lang = ParseStringLiteralExpression(false);
Chris Lattner38376f12008-01-12 07:05:38 +0000338
Douglas Gregor07665a62009-01-05 19:45:36 +0000339 ParseScope LinkageScope(this, Scope::DeclScope);
Richard Smith4ee696d2014-02-17 23:25:27 +0000340 Decl *LinkageSpec =
341 Lang.isInvalid()
Craig Topper161e4db2014-05-21 06:02:52 +0000342 ? nullptr
Richard Smith4ee696d2014-02-17 23:25:27 +0000343 : Actions.ActOnStartLinkageSpecification(
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000344 getCurScope(), DS.getSourceRange().getBegin(), Lang.get(),
Richard Smith4ee696d2014-02-17 23:25:27 +0000345 Tok.is(tok::l_brace) ? Tok.getLocation() : SourceLocation());
Douglas Gregor07665a62009-01-05 19:45:36 +0000346
John McCall084e83d2011-03-24 11:26:52 +0000347 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +0000348 MaybeParseCXX11Attributes(attrs);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000349
Douglas Gregor07665a62009-01-05 19:45:36 +0000350 if (Tok.isNot(tok::l_brace)) {
Abramo Bagnara4d423992011-05-01 16:25:54 +0000351 // Reset the source range in DS, as the leading "extern"
352 // does not really belong to the inner declaration ...
353 DS.SetRangeStart(SourceLocation());
354 DS.SetRangeEnd(SourceLocation());
355 // ... but anyway remember that such an "extern" was seen.
Abramo Bagnaraed5b6892010-07-30 16:47:02 +0000356 DS.setExternInLinkageSpec(true);
John McCall53fa7142010-12-24 02:08:15 +0000357 ParseExternalDeclaration(attrs, &DS);
Richard Smith4ee696d2014-02-17 23:25:27 +0000358 return LinkageSpec ? Actions.ActOnFinishLinkageSpecification(
359 getCurScope(), LinkageSpec, SourceLocation())
Craig Topper161e4db2014-05-21 06:02:52 +0000360 : nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000361 }
Douglas Gregor29ff7d02008-12-16 22:23:02 +0000362
Douglas Gregorb65a9132010-02-07 08:38:28 +0000363 DS.abort();
364
John McCall53fa7142010-12-24 02:08:15 +0000365 ProhibitAttributes(attrs);
Alexis Hunt96d5c762009-11-21 08:43:09 +0000366
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000367 BalancedDelimiterTracker T(*this, tok::l_brace);
368 T.consumeOpen();
Richard Smith77944862014-03-02 05:58:18 +0000369
370 unsigned NestedModules = 0;
371 while (true) {
372 switch (Tok.getKind()) {
373 case tok::annot_module_begin:
374 ++NestedModules;
375 ParseTopLevelDecl();
376 continue;
377
378 case tok::annot_module_end:
379 if (!NestedModules)
380 break;
381 --NestedModules;
382 ParseTopLevelDecl();
383 continue;
384
385 case tok::annot_module_include:
386 ParseTopLevelDecl();
387 continue;
388
389 case tok::eof:
390 break;
391
392 case tok::r_brace:
393 if (!NestedModules)
394 break;
Reid Kleckner4dc0b1a2018-11-01 19:54:45 +0000395 LLVM_FALLTHROUGH;
Richard Smith77944862014-03-02 05:58:18 +0000396 default:
397 ParsedAttributesWithRange attrs(AttrFactory);
398 MaybeParseCXX11Attributes(attrs);
Richard Smith77944862014-03-02 05:58:18 +0000399 ParseExternalDeclaration(attrs);
400 continue;
401 }
402
403 break;
Chris Lattner38376f12008-01-12 07:05:38 +0000404 }
405
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000406 T.consumeClose();
Richard Smith4ee696d2014-02-17 23:25:27 +0000407 return LinkageSpec ? Actions.ActOnFinishLinkageSpecification(
408 getCurScope(), LinkageSpec, T.getCloseLocation())
Craig Topper161e4db2014-05-21 06:02:52 +0000409 : nullptr;
Chris Lattner38376f12008-01-12 07:05:38 +0000410}
Douglas Gregor556877c2008-04-13 21:30:24 +0000411
Richard Smith8df390f2016-09-08 23:14:54 +0000412/// Parse a C++ Modules TS export-declaration.
413///
414/// export-declaration:
415/// 'export' declaration
416/// 'export' '{' declaration-seq[opt] '}'
417///
418Decl *Parser::ParseExportDeclaration() {
419 assert(Tok.is(tok::kw_export));
420 SourceLocation ExportLoc = ConsumeToken();
421
422 ParseScope ExportScope(this, Scope::DeclScope);
423 Decl *ExportDecl = Actions.ActOnStartExportDecl(
424 getCurScope(), ExportLoc,
425 Tok.is(tok::l_brace) ? Tok.getLocation() : SourceLocation());
426
427 if (Tok.isNot(tok::l_brace)) {
428 // FIXME: Factor out a ParseExternalDeclarationWithAttrs.
429 ParsedAttributesWithRange Attrs(AttrFactory);
430 MaybeParseCXX11Attributes(Attrs);
431 MaybeParseMicrosoftAttributes(Attrs);
432 ParseExternalDeclaration(Attrs);
433 return Actions.ActOnFinishExportDecl(getCurScope(), ExportDecl,
434 SourceLocation());
435 }
436
437 BalancedDelimiterTracker T(*this, tok::l_brace);
438 T.consumeOpen();
439
440 // The Modules TS draft says "An export-declaration shall declare at least one
441 // entity", but the intent is that it shall contain at least one declaration.
Richard Smithe181de72019-04-22 22:50:11 +0000442 if (Tok.is(tok::r_brace) && getLangOpts().ModulesTS) {
Richard Smith8df390f2016-09-08 23:14:54 +0000443 Diag(ExportLoc, diag::err_export_empty)
444 << SourceRange(ExportLoc, Tok.getLocation());
Richard Smithe181de72019-04-22 22:50:11 +0000445 }
Richard Smith8df390f2016-09-08 23:14:54 +0000446
447 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
448 Tok.isNot(tok::eof)) {
449 ParsedAttributesWithRange Attrs(AttrFactory);
450 MaybeParseCXX11Attributes(Attrs);
451 MaybeParseMicrosoftAttributes(Attrs);
452 ParseExternalDeclaration(Attrs);
453 }
454
455 T.consumeClose();
456 return Actions.ActOnFinishExportDecl(getCurScope(), ExportDecl,
457 T.getCloseLocation());
458}
459
Douglas Gregord7c4d982008-12-30 03:27:21 +0000460/// ParseUsingDirectiveOrDeclaration - Parse C++ using using-declaration or
461/// using-directive. Assumes that current token is 'using'.
Richard Smith6f1daa42016-12-16 00:58:48 +0000462Parser::DeclGroupPtrTy
Faisal Vali421b2d12017-12-29 05:41:00 +0000463Parser::ParseUsingDirectiveOrDeclaration(DeclaratorContext Context,
John McCall9b72f892010-11-10 02:40:36 +0000464 const ParsedTemplateInfo &TemplateInfo,
Richard Smith6f1daa42016-12-16 00:58:48 +0000465 SourceLocation &DeclEnd,
466 ParsedAttributesWithRange &attrs) {
Douglas Gregord7c4d982008-12-30 03:27:21 +0000467 assert(Tok.is(tok::kw_using) && "Not using token");
Fariborz Jahanian4bf82622011-08-22 17:59:19 +0000468 ObjCDeclContextSwitch ObjCDC(*this);
Fangrui Song6907ce22018-07-30 19:24:48 +0000469
Douglas Gregord7c4d982008-12-30 03:27:21 +0000470 // Eat 'using'.
471 SourceLocation UsingLoc = ConsumeToken();
472
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000473 if (Tok.is(tok::code_completion)) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000474 Actions.CodeCompleteUsing(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000475 cutOffParsing();
Craig Topper161e4db2014-05-21 06:02:52 +0000476 return nullptr;
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000477 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000478
Richard Trieu2efd3052019-05-01 23:33:49 +0000479 // Consume unexpected 'template' keywords.
480 while (Tok.is(tok::kw_template)) {
481 SourceLocation TemplateLoc = ConsumeToken();
482 Diag(TemplateLoc, diag::err_unexpected_template_after_using)
483 << FixItHint::CreateRemoval(TemplateLoc);
484 }
485
John McCall9b72f892010-11-10 02:40:36 +0000486 // 'using namespace' means this is a using-directive.
487 if (Tok.is(tok::kw_namespace)) {
488 // Template parameters are always an error here.
489 if (TemplateInfo.Kind) {
490 SourceRange R = TemplateInfo.getSourceRange();
Craig Topper54a6a682015-11-14 18:16:08 +0000491 Diag(UsingLoc, diag::err_templated_using_directive_declaration)
492 << 0 /* directive */ << R << FixItHint::CreateRemoval(R);
John McCall9b72f892010-11-10 02:40:36 +0000493 }
Alexis Hunt96d5c762009-11-21 08:43:09 +0000494
Richard Smith6f1daa42016-12-16 00:58:48 +0000495 Decl *UsingDir = ParseUsingDirective(Context, UsingLoc, DeclEnd, attrs);
496 return Actions.ConvertDeclToDeclGroup(UsingDir);
John McCall9b72f892010-11-10 02:40:36 +0000497 }
498
Richard Smithdda56e42011-04-15 14:24:37 +0000499 // Otherwise, it must be a using-declaration or an alias-declaration.
John McCall9b72f892010-11-10 02:40:36 +0000500
501 // Using declarations can't have attributes.
John McCall53fa7142010-12-24 02:08:15 +0000502 ProhibitAttributes(attrs);
Chris Lattner9b01ca12009-01-06 06:55:51 +0000503
Fariborz Jahanian4bf82622011-08-22 17:59:19 +0000504 return ParseUsingDeclaration(Context, TemplateInfo, UsingLoc, DeclEnd,
Richard Smith6f1daa42016-12-16 00:58:48 +0000505 AS_none);
Douglas Gregord7c4d982008-12-30 03:27:21 +0000506}
507
508/// ParseUsingDirective - Parse C++ using-directive, assumes
509/// that current token is 'namespace' and 'using' was already parsed.
510///
511/// using-directive: [C++ 7.3.p4: namespace.udir]
512/// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
513/// namespace-name ;
514/// [GNU] using-directive:
515/// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
516/// namespace-name attributes[opt] ;
517///
Faisal Vali421b2d12017-12-29 05:41:00 +0000518Decl *Parser::ParseUsingDirective(DeclaratorContext Context,
John McCall9b72f892010-11-10 02:40:36 +0000519 SourceLocation UsingLoc,
520 SourceLocation &DeclEnd,
John McCall53fa7142010-12-24 02:08:15 +0000521 ParsedAttributes &attrs) {
Douglas Gregord7c4d982008-12-30 03:27:21 +0000522 assert(Tok.is(tok::kw_namespace) && "Not 'namespace' token");
523
524 // Eat 'namespace'.
525 SourceLocation NamespcLoc = ConsumeToken();
526
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000527 if (Tok.is(tok::code_completion)) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000528 Actions.CodeCompleteUsingDirective(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000529 cutOffParsing();
Craig Topper161e4db2014-05-21 06:02:52 +0000530 return nullptr;
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000531 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000532
Douglas Gregord7c4d982008-12-30 03:27:21 +0000533 CXXScopeSpec SS;
534 // Parse (optional) nested-name-specifier.
Haojian Wu0dd0b102020-03-19 09:12:29 +0100535 ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
536 /*ObjectHadErrors=*/false,
537 /*EnteringContext=*/false,
Matthias Gehredc01bb42017-03-17 21:41:20 +0000538 /*MayBePseudoDestructor=*/nullptr,
539 /*IsTypename=*/false,
540 /*LastII=*/nullptr,
541 /*OnlyNamespace=*/true);
Douglas Gregord7c4d982008-12-30 03:27:21 +0000542
Craig Topper161e4db2014-05-21 06:02:52 +0000543 IdentifierInfo *NamespcName = nullptr;
Douglas Gregord7c4d982008-12-30 03:27:21 +0000544 SourceLocation IdentLoc = SourceLocation();
545
546 // Parse namespace-name.
Matthias Gehredc01bb42017-03-17 21:41:20 +0000547 if (Tok.isNot(tok::identifier)) {
Douglas Gregord7c4d982008-12-30 03:27:21 +0000548 Diag(Tok, diag::err_expected_namespace_name);
549 // If there was invalid namespace name, skip to end of decl, and eat ';'.
550 SkipUntil(tok::semi);
551 // FIXME: Are there cases, when we would like to call ActOnUsingDirective?
Craig Topper161e4db2014-05-21 06:02:52 +0000552 return nullptr;
Douglas Gregord7c4d982008-12-30 03:27:21 +0000553 }
Mike Stump11289f42009-09-09 15:08:12 +0000554
Matthias Gehredc01bb42017-03-17 21:41:20 +0000555 if (SS.isInvalid()) {
556 // Diagnostics have been emitted in ParseOptionalCXXScopeSpecifier.
557 // Skip to end of the definition and eat the ';'.
558 SkipUntil(tok::semi);
559 return nullptr;
560 }
561
Chris Lattnerce1da2c2009-01-06 07:27:21 +0000562 // Parse identifier.
563 NamespcName = Tok.getIdentifierInfo();
564 IdentLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000565
Chris Lattnerce1da2c2009-01-06 07:27:21 +0000566 // Parse (optional) attributes (most likely GNU strong-using extension).
Alexis Hunt96d5c762009-11-21 08:43:09 +0000567 bool GNUAttr = false;
568 if (Tok.is(tok::kw___attribute)) {
569 GNUAttr = true;
John McCall53fa7142010-12-24 02:08:15 +0000570 ParseGNUAttributes(attrs);
Alexis Hunt96d5c762009-11-21 08:43:09 +0000571 }
Mike Stump11289f42009-09-09 15:08:12 +0000572
Chris Lattnerce1da2c2009-01-06 07:27:21 +0000573 // Eat ';'.
Chris Lattner49836b42009-04-02 04:16:50 +0000574 DeclEnd = Tok.getLocation();
Alp Toker383d2c42014-01-01 03:08:43 +0000575 if (ExpectAndConsume(tok::semi,
576 GNUAttr ? diag::err_expected_semi_after_attribute_list
577 : diag::err_expected_semi_after_namespace_name))
578 SkipUntil(tok::semi);
Douglas Gregord7c4d982008-12-30 03:27:21 +0000579
Douglas Gregor0be31a22010-07-02 17:43:08 +0000580 return Actions.ActOnUsingDirective(getCurScope(), UsingLoc, NamespcLoc, SS,
Erich Keanec480f302018-07-12 21:09:05 +0000581 IdentLoc, NamespcName, attrs);
Douglas Gregord7c4d982008-12-30 03:27:21 +0000582}
583
Richard Smith6f1daa42016-12-16 00:58:48 +0000584/// Parse a using-declarator (or the identifier in a C++11 alias-declaration).
Douglas Gregord7c4d982008-12-30 03:27:21 +0000585///
Richard Smith6f1daa42016-12-16 00:58:48 +0000586/// using-declarator:
587/// 'typename'[opt] nested-name-specifier unqualified-id
Douglas Gregord7c4d982008-12-30 03:27:21 +0000588///
Faisal Vali421b2d12017-12-29 05:41:00 +0000589bool Parser::ParseUsingDeclarator(DeclaratorContext Context,
590 UsingDeclarator &D) {
Richard Smith6f1daa42016-12-16 00:58:48 +0000591 D.clear();
Douglas Gregorfec52632009-06-20 00:51:54 +0000592
593 // Ignore optional 'typename'.
Douglas Gregor220f4272009-11-04 16:30:06 +0000594 // FIXME: This is wrong; we should parse this as a typename-specifier.
Richard Smith6f1daa42016-12-16 00:58:48 +0000595 TryConsumeToken(tok::kw_typename, D.TypenameLoc);
Douglas Gregorfec52632009-06-20 00:51:54 +0000596
Nikola Smiljanic67860242014-09-26 00:28:20 +0000597 if (Tok.is(tok::kw___super)) {
598 Diag(Tok.getLocation(), diag::err_super_in_using_declaration);
Richard Smith6f1daa42016-12-16 00:58:48 +0000599 return true;
Nikola Smiljanic67860242014-09-26 00:28:20 +0000600 }
601
Douglas Gregorfec52632009-06-20 00:51:54 +0000602 // Parse nested-name-specifier.
Craig Topper161e4db2014-05-21 06:02:52 +0000603 IdentifierInfo *LastII = nullptr;
Haojian Wu0dd0b102020-03-19 09:12:29 +0100604 if (ParseOptionalCXXScopeSpecifier(D.SS, /*ObjectType=*/nullptr,
605 /*ObjectHadErrors=*/false,
606 /*EnteringContext=*/false,
Richard Smithb23c5e82019-05-09 03:31:27 +0000607 /*MayBePseudoDtor=*/nullptr,
608 /*IsTypename=*/false,
Ilya Biryukovd9971d02019-10-28 09:34:21 +0100609 /*LastII=*/&LastII,
610 /*OnlyNamespace=*/false,
611 /*InUsingDeclaration=*/true))
612
Richard Smithb23c5e82019-05-09 03:31:27 +0000613 return true;
Richard Smith6f1daa42016-12-16 00:58:48 +0000614 if (D.SS.isInvalid())
615 return true;
Richard Smith7447af42013-03-26 01:15:19 +0000616
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000617 // Parse the unqualified-id. We allow parsing of both constructor and
Douglas Gregor220f4272009-11-04 16:30:06 +0000618 // destructor names and allow the action module to diagnose any semantic
619 // errors.
Richard Smith7447af42013-03-26 01:15:19 +0000620 //
621 // C++11 [class.qual]p2:
622 // [...] in a using-declaration that is a member-declaration, if the name
623 // specified after the nested-name-specifier is the same as the identifier
624 // or the simple-template-id's template-name in the last component of the
625 // nested-name-specifier, the name is [...] considered to name the
626 // constructor.
Faisal Vali421b2d12017-12-29 05:41:00 +0000627 if (getLangOpts().CPlusPlus11 &&
628 Context == DeclaratorContext::MemberContext &&
Richard Smith151c4562016-12-20 21:35:28 +0000629 Tok.is(tok::identifier) &&
630 (NextToken().is(tok::semi) || NextToken().is(tok::comma) ||
631 NextToken().is(tok::ellipsis)) &&
Richard Smith6f1daa42016-12-16 00:58:48 +0000632 D.SS.isNotEmpty() && LastII == Tok.getIdentifierInfo() &&
633 !D.SS.getScopeRep()->getAsNamespace() &&
634 !D.SS.getScopeRep()->getAsNamespaceAlias()) {
Richard Smith7447af42013-03-26 01:15:19 +0000635 SourceLocation IdLoc = ConsumeToken();
Richard Smith6f1daa42016-12-16 00:58:48 +0000636 ParsedType Type =
637 Actions.getInheritingConstructorName(D.SS, IdLoc, *LastII);
638 D.Name.setConstructorName(Type, IdLoc, IdLoc);
639 } else {
640 if (ParseUnqualifiedId(
Haojian Wu0dd0b102020-03-19 09:12:29 +0100641 D.SS, /*ObjectType=*/nullptr,
642 /*ObjectHadErrors=*/false, /*EnteringContext=*/false,
Richard Smith6f1daa42016-12-16 00:58:48 +0000643 /*AllowDestructorName=*/true,
Haojian Wu0dd0b102020-03-19 09:12:29 +0100644 /*AllowConstructorName=*/
645 !(Tok.is(tok::identifier) && NextToken().is(tok::equal)),
646 /*AllowDeductionGuide=*/false, nullptr, D.Name))
Richard Smith6f1daa42016-12-16 00:58:48 +0000647 return true;
Douglas Gregorfec52632009-06-20 00:51:54 +0000648 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000649
Richard Smith151c4562016-12-20 21:35:28 +0000650 if (TryConsumeToken(tok::ellipsis, D.EllipsisLoc))
Aaron Ballmanc351fba2017-12-04 20:27:34 +0000651 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17 ?
Richard Smithb115e5d2017-08-13 23:37:29 +0000652 diag::warn_cxx17_compat_using_declaration_pack :
Richard Smith151c4562016-12-20 21:35:28 +0000653 diag::ext_using_declaration_pack);
Richard Smith6f1daa42016-12-16 00:58:48 +0000654
655 return false;
656}
657
658/// ParseUsingDeclaration - Parse C++ using-declaration or alias-declaration.
659/// Assumes that 'using' was already seen.
660///
661/// using-declaration: [C++ 7.3.p3: namespace.udecl]
662/// 'using' using-declarator-list[opt] ;
663///
664/// using-declarator-list: [C++1z]
665/// using-declarator '...'[opt]
666/// using-declarator-list ',' using-declarator '...'[opt]
667///
668/// using-declarator-list: [C++98-14]
669/// using-declarator
670///
671/// alias-declaration: C++11 [dcl.dcl]p1
672/// 'using' identifier attribute-specifier-seq[opt] = type-id ;
673///
674Parser::DeclGroupPtrTy
Faisal Vali421b2d12017-12-29 05:41:00 +0000675Parser::ParseUsingDeclaration(DeclaratorContext Context,
Richard Smith6f1daa42016-12-16 00:58:48 +0000676 const ParsedTemplateInfo &TemplateInfo,
677 SourceLocation UsingLoc, SourceLocation &DeclEnd,
678 AccessSpecifier AS) {
679 // Check for misplaced attributes before the identifier in an
680 // alias-declaration.
681 ParsedAttributesWithRange MisplacedAttrs(AttrFactory);
682 MaybeParseCXX11Attributes(MisplacedAttrs);
683
684 UsingDeclarator D;
685 bool InvalidDeclarator = ParseUsingDeclarator(Context, D);
686
Richard Smithc2c8bb82013-10-15 01:34:54 +0000687 ParsedAttributesWithRange Attrs(AttrFactory);
Richard Smith37a45dd2013-10-24 01:21:09 +0000688 MaybeParseGNUAttributes(Attrs);
Richard Smith54ecd982013-02-20 19:22:51 +0000689 MaybeParseCXX11Attributes(Attrs);
Richard Smithdda56e42011-04-15 14:24:37 +0000690
691 // Maybe this is an alias-declaration.
Richard Smith6f1daa42016-12-16 00:58:48 +0000692 if (Tok.is(tok::equal)) {
693 if (InvalidDeclarator) {
694 SkipUntil(tok::semi);
695 return nullptr;
696 }
697
Richard Smithc2c8bb82013-10-15 01:34:54 +0000698 // If we had any misplaced attributes from earlier, this is where they
699 // should have been written.
700 if (MisplacedAttrs.Range.isValid()) {
701 Diag(MisplacedAttrs.Range.getBegin(), diag::err_attributes_not_allowed)
702 << FixItHint::CreateInsertionFromRange(
703 Tok.getLocation(),
704 CharSourceRange::getTokenRange(MisplacedAttrs.Range))
705 << FixItHint::CreateRemoval(MisplacedAttrs.Range);
706 Attrs.takeAllFrom(MisplacedAttrs);
707 }
708
Richard Smith6f1daa42016-12-16 00:58:48 +0000709 Decl *DeclFromDeclSpec = nullptr;
710 Decl *AD = ParseAliasDeclarationAfterDeclarator(
711 TemplateInfo, UsingLoc, D, DeclEnd, AS, Attrs, &DeclFromDeclSpec);
712 return Actions.ConvertDeclToDeclGroup(AD, DeclFromDeclSpec);
Alexis Hunt6aa9bee2012-06-23 05:07:58 +0000713 }
Mike Stump11289f42009-09-09 15:08:12 +0000714
Richard Smith6f1daa42016-12-16 00:58:48 +0000715 // C++11 attributes are not allowed on a using-declaration, but GNU ones
716 // are.
717 ProhibitAttributes(MisplacedAttrs);
718 ProhibitAttributes(Attrs);
Douglas Gregorfec52632009-06-20 00:51:54 +0000719
John McCall9b72f892010-11-10 02:40:36 +0000720 // Diagnose an attempt to declare a templated using-declaration.
Richard Smith810ad3e2013-01-29 10:02:16 +0000721 // In C++11, alias-declarations can be templates:
Richard Smithdda56e42011-04-15 14:24:37 +0000722 // template <...> using id = type;
Richard Smith6f1daa42016-12-16 00:58:48 +0000723 if (TemplateInfo.Kind) {
John McCall9b72f892010-11-10 02:40:36 +0000724 SourceRange R = TemplateInfo.getSourceRange();
Craig Topper54a6a682015-11-14 18:16:08 +0000725 Diag(UsingLoc, diag::err_templated_using_directive_declaration)
726 << 1 /* declaration */ << R << FixItHint::CreateRemoval(R);
John McCall9b72f892010-11-10 02:40:36 +0000727
728 // Unfortunately, we have to bail out instead of recovering by
729 // ignoring the parameters, just in case the nested name specifier
730 // depends on the parameters.
Craig Topper161e4db2014-05-21 06:02:52 +0000731 return nullptr;
John McCall9b72f892010-11-10 02:40:36 +0000732 }
733
Richard Smith6f1daa42016-12-16 00:58:48 +0000734 SmallVector<Decl *, 8> DeclsInGroup;
735 while (true) {
736 // Parse (optional) attributes (most likely GNU strong-using extension).
737 MaybeParseGNUAttributes(Attrs);
738
739 if (InvalidDeclarator)
740 SkipUntil(tok::comma, tok::semi, StopBeforeMatch);
741 else {
742 // "typename" keyword is allowed for identifiers only,
743 // because it may be a type definition.
744 if (D.TypenameLoc.isValid() &&
Faisal Vali2ab8c152017-12-30 04:15:27 +0000745 D.Name.getKind() != UnqualifiedIdKind::IK_Identifier) {
Richard Smith6f1daa42016-12-16 00:58:48 +0000746 Diag(D.Name.getSourceRange().getBegin(),
747 diag::err_typename_identifiers_only)
748 << FixItHint::CreateRemoval(SourceRange(D.TypenameLoc));
749 // Proceed parsing, but discard the typename keyword.
750 D.TypenameLoc = SourceLocation();
751 }
752
Richard Smith151c4562016-12-20 21:35:28 +0000753 Decl *UD = Actions.ActOnUsingDeclaration(getCurScope(), AS, UsingLoc,
754 D.TypenameLoc, D.SS, D.Name,
Erich Keanec480f302018-07-12 21:09:05 +0000755 D.EllipsisLoc, Attrs);
Richard Smith6f1daa42016-12-16 00:58:48 +0000756 if (UD)
757 DeclsInGroup.push_back(UD);
758 }
759
760 if (!TryConsumeToken(tok::comma))
761 break;
762
763 // Parse another using-declarator.
764 Attrs.clear();
765 InvalidDeclarator = ParseUsingDeclarator(Context, D);
Douglas Gregor882a61a2011-09-26 14:30:28 +0000766 }
767
Richard Smith6f1daa42016-12-16 00:58:48 +0000768 if (DeclsInGroup.size() > 1)
Aaron Ballmanc351fba2017-12-04 20:27:34 +0000769 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17 ?
Richard Smithb115e5d2017-08-13 23:37:29 +0000770 diag::warn_cxx17_compat_multi_using_declaration :
Richard Smith6f1daa42016-12-16 00:58:48 +0000771 diag::ext_multi_using_declaration);
772
773 // Eat ';'.
774 DeclEnd = Tok.getLocation();
775 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
776 !Attrs.empty() ? "attributes list"
777 : "using declaration"))
778 SkipUntil(tok::semi);
779
Richard Smith3beb7c62017-01-12 02:27:38 +0000780 return Actions.BuildDeclaratorGroup(DeclsInGroup);
Richard Smith6f1daa42016-12-16 00:58:48 +0000781}
782
Richard Smith6f1daa42016-12-16 00:58:48 +0000783Decl *Parser::ParseAliasDeclarationAfterDeclarator(
784 const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc,
785 UsingDeclarator &D, SourceLocation &DeclEnd, AccessSpecifier AS,
786 ParsedAttributes &Attrs, Decl **OwnedType) {
787 if (ExpectAndConsume(tok::equal)) {
788 SkipUntil(tok::semi);
789 return nullptr;
790 }
791
792 Diag(Tok.getLocation(), getLangOpts().CPlusPlus11 ?
793 diag::warn_cxx98_compat_alias_declaration :
794 diag::ext_alias_declaration);
795
796 // Type alias templates cannot be specialized.
797 int SpecKind = -1;
798 if (TemplateInfo.Kind == ParsedTemplateInfo::Template &&
Faisal Vali2ab8c152017-12-30 04:15:27 +0000799 D.Name.getKind() == UnqualifiedIdKind::IK_TemplateId)
Richard Smith6f1daa42016-12-16 00:58:48 +0000800 SpecKind = 0;
801 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization)
802 SpecKind = 1;
803 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
804 SpecKind = 2;
805 if (SpecKind != -1) {
806 SourceRange Range;
807 if (SpecKind == 0)
808 Range = SourceRange(D.Name.TemplateId->LAngleLoc,
809 D.Name.TemplateId->RAngleLoc);
810 else
811 Range = TemplateInfo.getSourceRange();
812 Diag(Range.getBegin(), diag::err_alias_declaration_specialization)
813 << SpecKind << Range;
814 SkipUntil(tok::semi);
815 return nullptr;
816 }
817
818 // Name must be an identifier.
Faisal Vali2ab8c152017-12-30 04:15:27 +0000819 if (D.Name.getKind() != UnqualifiedIdKind::IK_Identifier) {
Richard Smith6f1daa42016-12-16 00:58:48 +0000820 Diag(D.Name.StartLocation, diag::err_alias_declaration_not_identifier);
821 // No removal fixit: can't recover from this.
822 SkipUntil(tok::semi);
823 return nullptr;
824 } else if (D.TypenameLoc.isValid())
825 Diag(D.TypenameLoc, diag::err_alias_declaration_not_identifier)
826 << FixItHint::CreateRemoval(SourceRange(
827 D.TypenameLoc,
828 D.SS.isNotEmpty() ? D.SS.getEndLoc() : D.TypenameLoc));
829 else if (D.SS.isNotEmpty())
830 Diag(D.SS.getBeginLoc(), diag::err_alias_declaration_not_identifier)
831 << FixItHint::CreateRemoval(D.SS.getRange());
Richard Smith151c4562016-12-20 21:35:28 +0000832 if (D.EllipsisLoc.isValid())
833 Diag(D.EllipsisLoc, diag::err_alias_declaration_pack_expansion)
834 << FixItHint::CreateRemoval(SourceRange(D.EllipsisLoc));
Richard Smith6f1daa42016-12-16 00:58:48 +0000835
836 Decl *DeclFromDeclSpec = nullptr;
Faisal Vali421b2d12017-12-29 05:41:00 +0000837 TypeResult TypeAlias = ParseTypeName(
838 nullptr,
839 TemplateInfo.Kind ? DeclaratorContext::AliasTemplateContext
840 : DeclaratorContext::AliasDeclContext,
841 AS, &DeclFromDeclSpec, &Attrs);
Richard Smith6f1daa42016-12-16 00:58:48 +0000842 if (OwnedType)
843 *OwnedType = DeclFromDeclSpec;
844
845 // Eat ';'.
846 DeclEnd = Tok.getLocation();
847 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
848 !Attrs.empty() ? "attributes list"
849 : "alias declaration"))
850 SkipUntil(tok::semi);
851
852 TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
853 MultiTemplateParamsArg TemplateParamsArg(
854 TemplateParams ? TemplateParams->data() : nullptr,
855 TemplateParams ? TemplateParams->size() : 0);
856 return Actions.ActOnAliasDeclaration(getCurScope(), AS, TemplateParamsArg,
Erich Keanec480f302018-07-12 21:09:05 +0000857 UsingLoc, D.Name, Attrs, TypeAlias,
858 DeclFromDeclSpec);
Douglas Gregord7c4d982008-12-30 03:27:21 +0000859}
860
Benjamin Kramere56f3932011-12-23 17:00:35 +0000861/// ParseStaticAssertDeclaration - Parse C++0x or C11 static_assert-declaration.
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000862///
Peter Collingbourne3d9cbdc2011-04-15 00:35:57 +0000863/// [C++0x] static_assert-declaration:
864/// static_assert ( constant-expression , string-literal ) ;
865///
Benjamin Kramere56f3932011-12-23 17:00:35 +0000866/// [C11] static_assert-declaration:
Peter Collingbourne3d9cbdc2011-04-15 00:35:57 +0000867/// _Static_assert ( constant-expression , string-literal ) ;
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000868///
John McCall48871652010-08-21 09:40:31 +0000869Decl *Parser::ParseStaticAssertDeclaration(SourceLocation &DeclEnd){
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000870 assert(Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert) &&
Peter Collingbourne3d9cbdc2011-04-15 00:35:57 +0000871 "Not a static_assert declaration");
872
David Blaikiebbafb8a2012-03-11 07:00:24 +0000873 if (Tok.is(tok::kw__Static_assert) && !getLangOpts().C11)
Aaron Ballman1d935222019-08-27 14:41:39 +0000874 Diag(Tok, diag::ext_c11_feature) << Tok.getName();
Richard Smithb15c11c2011-10-17 23:06:20 +0000875 if (Tok.is(tok::kw_static_assert))
876 Diag(Tok, diag::warn_cxx98_compat_static_assert);
Peter Collingbourne3d9cbdc2011-04-15 00:35:57 +0000877
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000878 SourceLocation StaticAssertLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000879
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000880 BalancedDelimiterTracker T(*this, tok::l_paren);
881 if (T.consumeOpen()) {
Alp Tokerec543272013-12-24 09:48:30 +0000882 Diag(Tok, diag::err_expected) << tok::l_paren;
Richard Smith76965712012-09-13 19:12:50 +0000883 SkipMalformedDecl();
Craig Topper161e4db2014-05-21 06:02:52 +0000884 return nullptr;
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000885 }
Mike Stump11289f42009-09-09 15:08:12 +0000886
Richard Smithb3018062017-06-06 01:34:24 +0000887 EnterExpressionEvaluationContext ConstantEvaluated(
888 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
889 ExprResult AssertExpr(ParseConstantExpressionInExprEvalContext());
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000890 if (AssertExpr.isInvalid()) {
Richard Smith76965712012-09-13 19:12:50 +0000891 SkipMalformedDecl();
Craig Topper161e4db2014-05-21 06:02:52 +0000892 return nullptr;
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000893 }
Mike Stump11289f42009-09-09 15:08:12 +0000894
Richard Smith085a64f2014-06-20 19:57:12 +0000895 ExprResult AssertMessage;
896 if (Tok.is(tok::r_paren)) {
Aaron Ballmanc351fba2017-12-04 20:27:34 +0000897 Diag(Tok, getLangOpts().CPlusPlus17
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000898 ? diag::warn_cxx14_compat_static_assert_no_message
Richard Smith085a64f2014-06-20 19:57:12 +0000899 : diag::ext_static_assert_no_message)
Aaron Ballmanc351fba2017-12-04 20:27:34 +0000900 << (getLangOpts().CPlusPlus17
Richard Smith085a64f2014-06-20 19:57:12 +0000901 ? FixItHint()
902 : FixItHint::CreateInsertion(Tok.getLocation(), ", \"\""));
903 } else {
904 if (ExpectAndConsume(tok::comma)) {
905 SkipUntil(tok::semi);
906 return nullptr;
907 }
Anders Carlssonb4cf3ad2009-03-13 23:29:20 +0000908
Richard Smith085a64f2014-06-20 19:57:12 +0000909 if (!isTokenStringLiteral()) {
910 Diag(Tok, diag::err_expected_string_literal)
911 << /*Source='static_assert'*/1;
912 SkipMalformedDecl();
913 return nullptr;
914 }
Mike Stump11289f42009-09-09 15:08:12 +0000915
Richard Smith085a64f2014-06-20 19:57:12 +0000916 AssertMessage = ParseStringLiteralExpression();
917 if (AssertMessage.isInvalid()) {
918 SkipMalformedDecl();
919 return nullptr;
920 }
Richard Smithd67aea22012-03-06 03:21:47 +0000921 }
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000922
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000923 T.consumeClose();
Mike Stump11289f42009-09-09 15:08:12 +0000924
Chris Lattner49836b42009-04-02 04:16:50 +0000925 DeclEnd = Tok.getLocation();
Douglas Gregor45d6bdf2010-09-07 15:23:11 +0000926 ExpectAndConsumeSemi(diag::err_expected_semi_after_static_assert);
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000927
John McCallb268a282010-08-23 23:25:46 +0000928 return Actions.ActOnStaticAssertDeclaration(StaticAssertLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000929 AssertExpr.get(),
930 AssertMessage.get(),
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000931 T.getCloseLocation());
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000932}
933
Richard Smith74aeef52013-04-26 16:15:35 +0000934/// ParseDecltypeSpecifier - Parse a C++11 decltype specifier.
Anders Carlsson74948d02009-06-24 17:47:40 +0000935///
936/// 'decltype' ( expression )
Richard Smith74aeef52013-04-26 16:15:35 +0000937/// 'decltype' ( 'auto' ) [C++1y]
Anders Carlsson74948d02009-06-24 17:47:40 +0000938///
David Blaikie15a430a2011-12-04 05:04:18 +0000939SourceLocation Parser::ParseDecltypeSpecifier(DeclSpec &DS) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000940 assert(Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)
David Blaikie15a430a2011-12-04 05:04:18 +0000941 && "Not a decltype specifier");
Fangrui Song6907ce22018-07-30 19:24:48 +0000942
David Blaikie15a430a2011-12-04 05:04:18 +0000943 ExprResult Result;
944 SourceLocation StartLoc = Tok.getLocation();
945 SourceLocation EndLoc;
946
947 if (Tok.is(tok::annot_decltype)) {
948 Result = getExprAnnotation(Tok);
949 EndLoc = Tok.getAnnotationEndLoc();
Richard Smithaf3b3252017-05-18 19:21:48 +0000950 ConsumeAnnotationToken();
David Blaikie15a430a2011-12-04 05:04:18 +0000951 if (Result.isInvalid()) {
952 DS.SetTypeSpecError();
953 return EndLoc;
954 }
955 } else {
Richard Smith324df552012-02-24 22:30:04 +0000956 if (Tok.getIdentifierInfo()->isStr("decltype"))
957 Diag(Tok, diag::warn_cxx98_compat_decltype);
Richard Smithfd3da932012-02-24 18:10:23 +0000958
David Blaikie15a430a2011-12-04 05:04:18 +0000959 ConsumeToken();
960
961 BalancedDelimiterTracker T(*this, tok::l_paren);
962 if (T.expectAndConsume(diag::err_expected_lparen_after,
963 "decltype", tok::r_paren)) {
964 DS.SetTypeSpecError();
965 return T.getOpenLocation() == Tok.getLocation() ?
966 StartLoc : T.getOpenLocation();
967 }
968
Richard Smith74aeef52013-04-26 16:15:35 +0000969 // Check for C++1y 'decltype(auto)'.
970 if (Tok.is(tok::kw_auto)) {
971 // No need to disambiguate here: an expression can't start with 'auto',
972 // because the typename-specifier in a function-style cast operation can't
973 // be 'auto'.
974 Diag(Tok.getLocation(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000975 getLangOpts().CPlusPlus14
Richard Smith74aeef52013-04-26 16:15:35 +0000976 ? diag::warn_cxx11_compat_decltype_auto_type_specifier
977 : diag::ext_decltype_auto_type_specifier);
978 ConsumeToken();
979 } else {
980 // Parse the expression
David Blaikie15a430a2011-12-04 05:04:18 +0000981
Richard Smith74aeef52013-04-26 16:15:35 +0000982 // C++11 [dcl.type.simple]p4:
983 // The operand of the decltype specifier is an unevaluated operand.
Faisal Valid143a0c2017-04-01 21:30:49 +0000984 EnterExpressionEvaluationContext Unevaluated(
985 Actions, Sema::ExpressionEvaluationContext::Unevaluated, nullptr,
Nicolas Lesserb6d5c582018-07-12 18:45:41 +0000986 Sema::ExpressionEvaluationContextRecord::EK_Decltype);
Kaelyn Takata5cc85352015-04-10 19:16:46 +0000987 Result =
988 Actions.CorrectDelayedTyposInExpr(ParseExpression(), [](Expr *E) {
989 return E->hasPlaceholderType() ? ExprError() : E;
990 });
Richard Smith74aeef52013-04-26 16:15:35 +0000991 if (Result.isInvalid()) {
992 DS.SetTypeSpecError();
Alexey Bataevee6507d2013-11-18 08:17:37 +0000993 if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch)) {
Richard Smith74aeef52013-04-26 16:15:35 +0000994 EndLoc = ConsumeParen();
Argyrios Kyrtzidisc38395a2012-10-26 22:53:44 +0000995 } else {
Richard Smith74aeef52013-04-26 16:15:35 +0000996 if (PP.isBacktrackEnabled() && Tok.is(tok::semi)) {
997 // Backtrack to get the location of the last token before the semi.
998 PP.RevertCachedTokens(2);
999 ConsumeToken(); // the semi.
1000 EndLoc = ConsumeAnyToken();
1001 assert(Tok.is(tok::semi));
1002 } else {
1003 EndLoc = Tok.getLocation();
1004 }
Argyrios Kyrtzidisc38395a2012-10-26 22:53:44 +00001005 }
Richard Smith74aeef52013-04-26 16:15:35 +00001006 return EndLoc;
Argyrios Kyrtzidisc38395a2012-10-26 22:53:44 +00001007 }
Richard Smith74aeef52013-04-26 16:15:35 +00001008
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001009 Result = Actions.ActOnDecltypeExpression(Result.get());
David Blaikie15a430a2011-12-04 05:04:18 +00001010 }
1011
1012 // Match the ')'
1013 T.consumeClose();
1014 if (T.getCloseLocation().isInvalid()) {
1015 DS.SetTypeSpecError();
1016 // FIXME: this should return the location of the last token
1017 // that was consumed (by "consumeClose()")
1018 return T.getCloseLocation();
1019 }
1020
Richard Smithfd555f62012-02-22 02:04:18 +00001021 if (Result.isInvalid()) {
1022 DS.SetTypeSpecError();
1023 return T.getCloseLocation();
1024 }
1025
David Blaikie15a430a2011-12-04 05:04:18 +00001026 EndLoc = T.getCloseLocation();
Anders Carlsson74948d02009-06-24 17:47:40 +00001027 }
Richard Smith74aeef52013-04-26 16:15:35 +00001028 assert(!Result.isInvalid());
Mike Stump11289f42009-09-09 15:08:12 +00001029
Craig Topper161e4db2014-05-21 06:02:52 +00001030 const char *PrevSpec = nullptr;
John McCall49bfce42009-08-03 20:12:06 +00001031 unsigned DiagID;
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001032 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
Anders Carlsson74948d02009-06-24 17:47:40 +00001033 // Check for duplicate type specifiers (e.g. "int decltype(a)").
Richard Smith74aeef52013-04-26 16:15:35 +00001034 if (Result.get()
1035 ? DS.SetTypeSpecType(DeclSpec::TST_decltype, StartLoc, PrevSpec,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001036 DiagID, Result.get(), Policy)
Richard Smith74aeef52013-04-26 16:15:35 +00001037 : DS.SetTypeSpecType(DeclSpec::TST_decltype_auto, StartLoc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001038 DiagID, Policy)) {
John McCall49bfce42009-08-03 20:12:06 +00001039 Diag(StartLoc, DiagID) << PrevSpec;
David Blaikie15a430a2011-12-04 05:04:18 +00001040 DS.SetTypeSpecError();
1041 }
1042 return EndLoc;
1043}
1044
Fangrui Song6907ce22018-07-30 19:24:48 +00001045void Parser::AnnotateExistingDecltypeSpecifier(const DeclSpec& DS,
David Blaikie15a430a2011-12-04 05:04:18 +00001046 SourceLocation StartLoc,
1047 SourceLocation EndLoc) {
1048 // make sure we have a token we can turn into an annotation token
1049 if (PP.isBacktrackEnabled())
1050 PP.RevertCachedTokens(1);
1051 else
Ilya Biryukov929af672019-05-17 09:32:05 +00001052 PP.EnterToken(Tok, /*IsReinject*/true);
David Blaikie15a430a2011-12-04 05:04:18 +00001053
1054 Tok.setKind(tok::annot_decltype);
Faisal Vali090da2d2018-01-01 18:23:28 +00001055 setExprAnnotation(Tok,
1056 DS.getTypeSpecType() == TST_decltype ? DS.getRepAsExpr() :
1057 DS.getTypeSpecType() == TST_decltype_auto ? ExprResult() :
1058 ExprError());
David Blaikie15a430a2011-12-04 05:04:18 +00001059 Tok.setAnnotationEndLoc(EndLoc);
1060 Tok.setLocation(StartLoc);
1061 PP.AnnotateCachedTokens(Tok);
Anders Carlsson74948d02009-06-24 17:47:40 +00001062}
1063
Alexis Hunt4a257072011-05-19 05:37:45 +00001064void Parser::ParseUnderlyingTypeSpecifier(DeclSpec &DS) {
1065 assert(Tok.is(tok::kw___underlying_type) &&
1066 "Not an underlying type specifier");
1067
1068 SourceLocation StartLoc = ConsumeToken();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001069 BalancedDelimiterTracker T(*this, tok::l_paren);
1070 if (T.expectAndConsume(diag::err_expected_lparen_after,
1071 "__underlying_type", tok::r_paren)) {
Alexis Hunt4a257072011-05-19 05:37:45 +00001072 return;
1073 }
1074
1075 TypeResult Result = ParseTypeName();
1076 if (Result.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00001077 SkipUntil(tok::r_paren, StopAtSemi);
Alexis Hunt4a257072011-05-19 05:37:45 +00001078 return;
1079 }
1080
1081 // Match the ')'
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001082 T.consumeClose();
1083 if (T.getCloseLocation().isInvalid())
Alexis Hunt4a257072011-05-19 05:37:45 +00001084 return;
1085
Craig Topper161e4db2014-05-21 06:02:52 +00001086 const char *PrevSpec = nullptr;
Alexis Hunt4a257072011-05-19 05:37:45 +00001087 unsigned DiagID;
Alexis Hunte852b102011-05-24 22:41:36 +00001088 if (DS.SetTypeSpecType(DeclSpec::TST_underlyingType, StartLoc, PrevSpec,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001089 DiagID, Result.get(),
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001090 Actions.getASTContext().getPrintingPolicy()))
Alexis Hunt4a257072011-05-19 05:37:45 +00001091 Diag(StartLoc, DiagID) << PrevSpec;
Enea Zaffanellaa90af722013-07-06 18:54:58 +00001092 DS.setTypeofParensRange(T.getRange());
Alexis Hunt4a257072011-05-19 05:37:45 +00001093}
1094
David Blaikie00ee7a082011-10-25 15:01:20 +00001095/// ParseBaseTypeSpecifier - Parse a C++ base-type-specifier which is either a
Fangrui Song6907ce22018-07-30 19:24:48 +00001096/// class name or decltype-specifier. Note that we only check that the result
1097/// names a type; semantic analysis will need to verify that the type names a
1098/// class. The result is either a type or null, depending on whether a type
David Blaikie00ee7a082011-10-25 15:01:20 +00001099/// name was found.
Douglas Gregor831c93f2008-11-05 20:51:48 +00001100///
Richard Smith4c96e992013-02-19 23:47:15 +00001101/// base-type-specifier: [C++11 class.derived]
David Blaikie00ee7a082011-10-25 15:01:20 +00001102/// class-or-decltype
Richard Smith4c96e992013-02-19 23:47:15 +00001103/// class-or-decltype: [C++11 class.derived]
David Blaikie00ee7a082011-10-25 15:01:20 +00001104/// nested-name-specifier[opt] class-name
1105/// decltype-specifier
Richard Smith4c96e992013-02-19 23:47:15 +00001106/// class-name: [C++ class.name]
Douglas Gregor831c93f2008-11-05 20:51:48 +00001107/// identifier
Douglas Gregord54dfb82009-02-25 23:52:28 +00001108/// simple-template-id
Mike Stump11289f42009-09-09 15:08:12 +00001109///
Richard Smith4c96e992013-02-19 23:47:15 +00001110/// In C++98, instead of base-type-specifier, we have:
1111///
1112/// ::[opt] nested-name-specifier[opt] class-name
Craig Topper9ad7e262014-10-31 06:57:07 +00001113TypeResult Parser::ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
1114 SourceLocation &EndLocation) {
David Blaikiedd58d4c2011-10-25 18:46:41 +00001115 // Ignore attempts to use typename
1116 if (Tok.is(tok::kw_typename)) {
1117 Diag(Tok, diag::err_expected_class_name_not_template)
1118 << FixItHint::CreateRemoval(Tok.getLocation());
1119 ConsumeToken();
1120 }
1121
David Blaikieafa155f2011-10-25 18:17:58 +00001122 // Parse optional nested-name-specifier
1123 CXXScopeSpec SS;
Haojian Wu0dd0b102020-03-19 09:12:29 +01001124 if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
1125 /*ObjectHadErrors=*/false,
1126 /*EnteringContext=*/false))
Richard Smithb23c5e82019-05-09 03:31:27 +00001127 return true;
David Blaikieafa155f2011-10-25 18:17:58 +00001128
1129 BaseLoc = Tok.getLocation();
1130
David Blaikie1cd50022011-10-25 17:10:12 +00001131 // Parse decltype-specifier
Fangrui Song6907ce22018-07-30 19:24:48 +00001132 // tok == kw_decltype is just error recovery, it can only happen when SS
David Blaikie15a430a2011-12-04 05:04:18 +00001133 // isn't empty
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001134 if (Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)) {
David Blaikieafa155f2011-10-25 18:17:58 +00001135 if (SS.isNotEmpty())
1136 Diag(SS.getBeginLoc(), diag::err_unexpected_scope_on_base_decltype)
1137 << FixItHint::CreateRemoval(SS.getRange());
David Blaikie1cd50022011-10-25 17:10:12 +00001138 // Fake up a Declarator to use with ActOnTypeName.
1139 DeclSpec DS(AttrFactory);
1140
David Blaikie7491e732011-12-08 04:53:15 +00001141 EndLocation = ParseDecltypeSpecifier(DS);
David Blaikie1cd50022011-10-25 17:10:12 +00001142
Faisal Vali421b2d12017-12-29 05:41:00 +00001143 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
David Blaikie1cd50022011-10-25 17:10:12 +00001144 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
1145 }
1146
Douglas Gregord54dfb82009-02-25 23:52:28 +00001147 // Check whether we have a template-id that names a type.
1148 if (Tok.is(tok::annot_template_id)) {
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00001149 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregor46c59612010-01-12 17:52:59 +00001150 if (TemplateId->Kind == TNK_Type_template ||
Richard Smithb23c5e82019-05-09 03:31:27 +00001151 TemplateId->Kind == TNK_Dependent_template_name ||
1152 TemplateId->Kind == TNK_Undeclared_template) {
Richard Smitha42fd842020-01-17 15:42:11 -08001153 AnnotateTemplateIdTokenAsType(SS, /*IsClassName*/true);
Douglas Gregord54dfb82009-02-25 23:52:28 +00001154
1155 assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
John McCallba7bf592010-08-24 05:47:05 +00001156 ParsedType Type = getTypeAnnotation(Tok);
Douglas Gregord54dfb82009-02-25 23:52:28 +00001157 EndLocation = Tok.getAnnotationEndLoc();
Richard Smithaf3b3252017-05-18 19:21:48 +00001158 ConsumeAnnotationToken();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001159
1160 if (Type)
1161 return Type;
1162 return true;
Douglas Gregord54dfb82009-02-25 23:52:28 +00001163 }
1164
1165 // Fall through to produce an error below.
1166 }
1167
Douglas Gregor831c93f2008-11-05 20:51:48 +00001168 if (Tok.isNot(tok::identifier)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00001169 Diag(Tok, diag::err_expected_class_name);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001170 return true;
Douglas Gregor831c93f2008-11-05 20:51:48 +00001171 }
1172
Douglas Gregor18473f32010-01-12 21:28:44 +00001173 IdentifierInfo *Id = Tok.getIdentifierInfo();
1174 SourceLocation IdLoc = ConsumeToken();
1175
1176 if (Tok.is(tok::less)) {
1177 // It looks the user intended to write a template-id here, but the
1178 // template-name was wrong. Try to fix that.
1179 TemplateNameKind TNK = TNK_Type_template;
1180 TemplateTy Template;
Douglas Gregor0be31a22010-07-02 17:43:08 +00001181 if (!Actions.DiagnoseUnknownTemplateName(*Id, IdLoc, getCurScope(),
Douglas Gregore7c20652011-03-02 00:47:37 +00001182 &SS, Template, TNK)) {
Douglas Gregor18473f32010-01-12 21:28:44 +00001183 Diag(IdLoc, diag::err_unknown_template_name)
1184 << Id;
1185 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001186
Serge Pavlovb716b3c2013-08-10 05:54:47 +00001187 if (!Template) {
1188 TemplateArgList TemplateArgs;
1189 SourceLocation LAngleLoc, RAngleLoc;
Richard Smith9a420f92017-05-10 21:47:30 +00001190 ParseTemplateIdAfterTemplateName(true, LAngleLoc, TemplateArgs,
1191 RAngleLoc);
Douglas Gregor18473f32010-01-12 21:28:44 +00001192 return true;
Serge Pavlovb716b3c2013-08-10 05:54:47 +00001193 }
Douglas Gregor18473f32010-01-12 21:28:44 +00001194
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001195 // Form the template name
Douglas Gregor18473f32010-01-12 21:28:44 +00001196 UnqualifiedId TemplateName;
1197 TemplateName.setIdentifier(Id, IdLoc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001198
Douglas Gregor18473f32010-01-12 21:28:44 +00001199 // Parse the full template-id, then turn it into a type.
Abramo Bagnara7945c982012-01-27 09:46:47 +00001200 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
Richard Smith62559bd2017-02-01 21:36:38 +00001201 TemplateName))
Douglas Gregor18473f32010-01-12 21:28:44 +00001202 return true;
Richard Smith62559bd2017-02-01 21:36:38 +00001203 if (TNK == TNK_Type_template || TNK == TNK_Dependent_template_name)
Richard Smitha42fd842020-01-17 15:42:11 -08001204 AnnotateTemplateIdTokenAsType(SS, /*IsClassName*/true);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001205
Douglas Gregor18473f32010-01-12 21:28:44 +00001206 // If we didn't end up with a typename token, there's nothing more we
1207 // can do.
1208 if (Tok.isNot(tok::annot_typename))
1209 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001210
Douglas Gregor18473f32010-01-12 21:28:44 +00001211 // Retrieve the type from the annotation token, consume that token, and
1212 // return.
1213 EndLocation = Tok.getAnnotationEndLoc();
John McCallba7bf592010-08-24 05:47:05 +00001214 ParsedType Type = getTypeAnnotation(Tok);
Richard Smithaf3b3252017-05-18 19:21:48 +00001215 ConsumeAnnotationToken();
Douglas Gregor18473f32010-01-12 21:28:44 +00001216 return Type;
1217 }
1218
Douglas Gregor831c93f2008-11-05 20:51:48 +00001219 // We have an identifier; check whether it is actually a type.
Craig Topper161e4db2014-05-21 06:02:52 +00001220 IdentifierInfo *CorrectedII = nullptr;
Richard Smith600b5262017-01-26 20:40:47 +00001221 ParsedType Type = Actions.getTypeName(
Rui Ueyama49a3ad22019-07-16 04:46:31 +00001222 *Id, IdLoc, getCurScope(), &SS, /*isClassName=*/true, false, nullptr,
Richard Smith600b5262017-01-26 20:40:47 +00001223 /*IsCtorOrDtorName=*/false,
Rui Ueyama49a3ad22019-07-16 04:46:31 +00001224 /*WantNontrivialTypeSourceInfo=*/true,
Richard Smith600b5262017-01-26 20:40:47 +00001225 /*IsClassTemplateDeductionContext*/ false, &CorrectedII);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001226 if (!Type) {
Douglas Gregorfe17d252010-02-16 19:09:40 +00001227 Diag(IdLoc, diag::err_expected_class_name);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001228 return true;
Douglas Gregor831c93f2008-11-05 20:51:48 +00001229 }
1230
1231 // Consume the identifier.
Douglas Gregor18473f32010-01-12 21:28:44 +00001232 EndLocation = IdLoc;
Nick Lewycky19b9f952010-07-26 16:56:01 +00001233
1234 // Fake up a Declarator to use with ActOnTypeName.
John McCall084e83d2011-03-24 11:26:52 +00001235 DeclSpec DS(AttrFactory);
Nick Lewycky19b9f952010-07-26 16:56:01 +00001236 DS.SetRangeStart(IdLoc);
1237 DS.SetRangeEnd(EndLocation);
Douglas Gregore7c20652011-03-02 00:47:37 +00001238 DS.getTypeSpecScope() = SS;
Nick Lewycky19b9f952010-07-26 16:56:01 +00001239
Craig Topper161e4db2014-05-21 06:02:52 +00001240 const char *PrevSpec = nullptr;
Nick Lewycky19b9f952010-07-26 16:56:01 +00001241 unsigned DiagID;
Faisal Vali090da2d2018-01-01 18:23:28 +00001242 DS.SetTypeSpecType(TST_typename, IdLoc, PrevSpec, DiagID, Type,
1243 Actions.getASTContext().getPrintingPolicy());
Nick Lewycky19b9f952010-07-26 16:56:01 +00001244
Faisal Vali421b2d12017-12-29 05:41:00 +00001245 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
Nick Lewycky19b9f952010-07-26 16:56:01 +00001246 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
Douglas Gregor831c93f2008-11-05 20:51:48 +00001247}
1248
John McCall8d32c052012-05-22 21:28:12 +00001249void Parser::ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001250 while (Tok.isOneOf(tok::kw___single_inheritance,
1251 tok::kw___multiple_inheritance,
1252 tok::kw___virtual_inheritance)) {
John McCall8d32c052012-05-22 21:28:12 +00001253 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
1254 SourceLocation AttrNameLoc = ConsumeToken();
Craig Topper161e4db2014-05-21 06:02:52 +00001255 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
Erich Keanee891aa92018-07-13 15:07:47 +00001256 ParsedAttr::AS_Keyword);
John McCall8d32c052012-05-22 21:28:12 +00001257 }
1258}
1259
Richard Smith369b9f92012-06-25 21:37:02 +00001260/// Determine whether the following tokens are valid after a type-specifier
1261/// which could be a standalone declaration. This will conservatively return
1262/// true if there's any doubt, and is appropriate for insert-';' fixits.
Richard Smith200f47c2012-07-02 19:14:01 +00001263bool Parser::isValidAfterTypeSpecifier(bool CouldBeBitfield) {
Richard Smith369b9f92012-06-25 21:37:02 +00001264 // This switch enumerates the valid "follow" set for type-specifiers.
1265 switch (Tok.getKind()) {
1266 default: break;
1267 case tok::semi: // struct foo {...} ;
1268 case tok::star: // struct foo {...} * P;
1269 case tok::amp: // struct foo {...} & R = ...
Richard Smith1ac67d12013-01-19 03:48:05 +00001270 case tok::ampamp: // struct foo {...} && R = ...
Richard Smith369b9f92012-06-25 21:37:02 +00001271 case tok::identifier: // struct foo {...} V ;
1272 case tok::r_paren: //(struct foo {...} ) {4}
Richard Smith1600e242019-04-16 00:47:45 +00001273 case tok::coloncolon: // struct foo {...} :: a::b;
Richard Smith369b9f92012-06-25 21:37:02 +00001274 case tok::annot_cxxscope: // struct foo {...} a:: b;
1275 case tok::annot_typename: // struct foo {...} a ::b;
1276 case tok::annot_template_id: // struct foo {...} a<int> ::b;
Richard Smith1600e242019-04-16 00:47:45 +00001277 case tok::kw_decltype: // struct foo {...} decltype (a)::b;
Richard Smith369b9f92012-06-25 21:37:02 +00001278 case tok::l_paren: // struct foo {...} ( x);
1279 case tok::comma: // __builtin_offsetof(struct foo{...} ,
Richard Smith1ac67d12013-01-19 03:48:05 +00001280 case tok::kw_operator: // struct foo operator ++() {...}
Alp Tokerd3f79c52013-11-24 20:24:54 +00001281 case tok::kw___declspec: // struct foo {...} __declspec(...)
Richard Smith843f18f2014-08-13 02:13:15 +00001282 case tok::l_square: // void f(struct f [ 3])
1283 case tok::ellipsis: // void f(struct f ... [Ns])
Abramo Bagnara152eb392014-08-16 08:29:27 +00001284 // FIXME: we should emit semantic diagnostic when declaration
1285 // attribute is in type attribute position.
1286 case tok::kw___attribute: // struct foo __attribute__((used)) x;
David Majnemer15b311c2016-06-14 03:20:28 +00001287 case tok::annot_pragma_pack: // struct foo {...} _Pragma(pack(pop));
1288 // struct foo {...} _Pragma(section(...));
1289 case tok::annot_pragma_ms_pragma:
1290 // struct foo {...} _Pragma(vtordisp(pop));
1291 case tok::annot_pragma_ms_vtordisp:
1292 // struct foo {...} _Pragma(pointers_to_members(...));
1293 case tok::annot_pragma_ms_pointers_to_members:
Richard Smith369b9f92012-06-25 21:37:02 +00001294 return true;
Richard Smith200f47c2012-07-02 19:14:01 +00001295 case tok::colon:
1296 return CouldBeBitfield; // enum E { ... } : 2;
Reid Klecknercfa91552016-03-21 16:08:49 +00001297 // Microsoft compatibility
1298 case tok::kw___cdecl: // struct foo {...} __cdecl x;
1299 case tok::kw___fastcall: // struct foo {...} __fastcall x;
1300 case tok::kw___stdcall: // struct foo {...} __stdcall x;
1301 case tok::kw___thiscall: // struct foo {...} __thiscall x;
1302 case tok::kw___vectorcall: // struct foo {...} __vectorcall x;
1303 // We will diagnose these calling-convention specifiers on non-function
1304 // declarations later, so claim they are valid after a type specifier.
1305 return getLangOpts().MicrosoftExt;
Richard Smith369b9f92012-06-25 21:37:02 +00001306 // Type qualifiers
1307 case tok::kw_const: // struct foo {...} const x;
1308 case tok::kw_volatile: // struct foo {...} volatile x;
1309 case tok::kw_restrict: // struct foo {...} restrict x;
Richard Smith843f18f2014-08-13 02:13:15 +00001310 case tok::kw__Atomic: // struct foo {...} _Atomic x;
Nico Rieck3e1ee832014-12-04 23:30:25 +00001311 case tok::kw___unaligned: // struct foo {...} __unaligned *x;
Richard Smith1ac67d12013-01-19 03:48:05 +00001312 // Function specifiers
1313 // Note, no 'explicit'. An explicit function must be either a conversion
1314 // operator or a constructor. Either way, it can't have a return type.
1315 case tok::kw_inline: // struct foo inline f();
1316 case tok::kw_virtual: // struct foo virtual f();
1317 case tok::kw_friend: // struct foo friend f();
Richard Smith369b9f92012-06-25 21:37:02 +00001318 // Storage-class specifiers
1319 case tok::kw_static: // struct foo {...} static x;
1320 case tok::kw_extern: // struct foo {...} extern x;
1321 case tok::kw_typedef: // struct foo {...} typedef x;
1322 case tok::kw_register: // struct foo {...} register x;
1323 case tok::kw_auto: // struct foo {...} auto x;
1324 case tok::kw_mutable: // struct foo {...} mutable x;
Richard Smith1ac67d12013-01-19 03:48:05 +00001325 case tok::kw_thread_local: // struct foo {...} thread_local x;
Richard Smith369b9f92012-06-25 21:37:02 +00001326 case tok::kw_constexpr: // struct foo {...} constexpr x;
Richard Smitha6e8b682019-09-04 20:30:37 +00001327 case tok::kw_consteval: // struct foo {...} consteval x;
1328 case tok::kw_constinit: // struct foo {...} constinit x;
Richard Smith369b9f92012-06-25 21:37:02 +00001329 // As shown above, type qualifiers and storage class specifiers absolutely
1330 // can occur after class specifiers according to the grammar. However,
1331 // almost no one actually writes code like this. If we see one of these,
1332 // it is much more likely that someone missed a semi colon and the
1333 // type/storage class specifier we're seeing is part of the *next*
1334 // intended declaration, as in:
1335 //
1336 // struct foo { ... }
1337 // typedef int X;
1338 //
1339 // We'd really like to emit a missing semicolon error instead of emitting
1340 // an error on the 'int' saying that you can't have two type specifiers in
1341 // the same declaration of X. Because of this, we look ahead past this
1342 // token to see if it's a type specifier. If so, we know the code is
1343 // otherwise invalid, so we can produce the expected semi error.
1344 if (!isKnownToBeTypeSpecifier(NextToken()))
1345 return true;
1346 break;
1347 case tok::r_brace: // struct bar { struct foo {...} }
1348 // Missing ';' at end of struct is accepted as an extension in C mode.
1349 if (!getLangOpts().CPlusPlus)
1350 return true;
1351 break;
Richard Smith52c5b872013-01-29 04:13:32 +00001352 case tok::greater:
1353 // template<class T = class X>
1354 return getLangOpts().CPlusPlus;
Richard Smith369b9f92012-06-25 21:37:02 +00001355 }
1356 return false;
1357}
1358
Douglas Gregor556877c2008-04-13 21:30:24 +00001359/// ParseClassSpecifier - Parse a C++ class-specifier [C++ class] or
1360/// elaborated-type-specifier [C++ dcl.type.elab]; we can't tell which
1361/// until we reach the start of a definition or see a token that
Richard Smithc5b05522012-03-12 07:56:15 +00001362/// cannot start a definition.
Douglas Gregor556877c2008-04-13 21:30:24 +00001363///
1364/// class-specifier: [C++ class]
1365/// class-head '{' member-specification[opt] '}'
1366/// class-head '{' member-specification[opt] '}' attributes[opt]
1367/// class-head:
1368/// class-key identifier[opt] base-clause[opt]
1369/// class-key nested-name-specifier identifier base-clause[opt]
1370/// class-key nested-name-specifier[opt] simple-template-id
1371/// base-clause[opt]
1372/// [GNU] class-key attributes[opt] identifier[opt] base-clause[opt]
Mike Stump11289f42009-09-09 15:08:12 +00001373/// [GNU] class-key attributes[opt] nested-name-specifier
Douglas Gregor556877c2008-04-13 21:30:24 +00001374/// identifier base-clause[opt]
Mike Stump11289f42009-09-09 15:08:12 +00001375/// [GNU] class-key attributes[opt] nested-name-specifier[opt]
Douglas Gregor556877c2008-04-13 21:30:24 +00001376/// simple-template-id base-clause[opt]
1377/// class-key:
1378/// 'class'
1379/// 'struct'
1380/// 'union'
1381///
1382/// elaborated-type-specifier: [C++ dcl.type.elab]
Mike Stump11289f42009-09-09 15:08:12 +00001383/// class-key ::[opt] nested-name-specifier[opt] identifier
1384/// class-key ::[opt] nested-name-specifier[opt] 'template'[opt]
1385/// simple-template-id
Douglas Gregor556877c2008-04-13 21:30:24 +00001386///
1387/// Note that the C++ class-specifier and elaborated-type-specifier,
1388/// together, subsume the C99 struct-or-union-specifier:
1389///
1390/// struct-or-union-specifier: [C99 6.7.2.1]
1391/// struct-or-union identifier[opt] '{' struct-contents '}'
1392/// struct-or-union identifier
1393/// [GNU] struct-or-union attributes[opt] identifier[opt] '{' struct-contents
1394/// '}' attributes[opt]
1395/// [GNU] struct-or-union attributes[opt] identifier
1396/// struct-or-union:
1397/// 'struct'
1398/// 'union'
Chris Lattnerffaa0e62009-04-12 21:49:30 +00001399void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind,
1400 SourceLocation StartLoc, DeclSpec &DS,
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001401 const ParsedTemplateInfo &TemplateInfo,
Fangrui Song6907ce22018-07-30 19:24:48 +00001402 AccessSpecifier AS,
1403 bool EnteringContext, DeclSpecContext DSC,
Bill Wendling44426052012-12-20 19:22:21 +00001404 ParsedAttributesWithRange &Attributes) {
Joao Matose9a3ed42012-08-31 22:18:20 +00001405 DeclSpec::TST TagType;
1406 if (TagTokKind == tok::kw_struct)
1407 TagType = DeclSpec::TST_struct;
1408 else if (TagTokKind == tok::kw___interface)
1409 TagType = DeclSpec::TST_interface;
1410 else if (TagTokKind == tok::kw_class)
1411 TagType = DeclSpec::TST_class;
1412 else {
Chris Lattnerffaa0e62009-04-12 21:49:30 +00001413 assert(TagTokKind == tok::kw_union && "Not a class specifier");
1414 TagType = DeclSpec::TST_union;
1415 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001416
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00001417 if (Tok.is(tok::code_completion)) {
1418 // Code completion for a struct, class, or union name.
Douglas Gregor0be31a22010-07-02 17:43:08 +00001419 Actions.CodeCompleteTag(getCurScope(), TagType);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001420 return cutOffParsing();
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00001421 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001422
Chandler Carruth2d69ec72010-06-28 08:39:25 +00001423 // C++03 [temp.explicit] 14.7.2/8:
1424 // The usual access checking rules do not apply to names used to specify
1425 // explicit instantiations.
1426 //
1427 // As an extension we do not perform access checking on the names used to
1428 // specify explicit specializations either. This is important to allow
1429 // specializing traits classes for private types.
John McCall6347b682012-05-07 06:16:58 +00001430 //
1431 // Note that we don't suppress if this turns out to be an elaborated
1432 // type specifier.
1433 bool shouldDelayDiagsInTag =
1434 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
1435 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
1436 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
Chandler Carruth2d69ec72010-06-28 08:39:25 +00001437
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001438 ParsedAttributesWithRange attrs(AttrFactory);
Douglas Gregor556877c2008-04-13 21:30:24 +00001439 // If attributes exist after tag, parse them.
Richard Smith37a45dd2013-10-24 01:21:09 +00001440 MaybeParseGNUAttributes(attrs);
Aaron Ballman068aa512015-05-20 20:58:33 +00001441 MaybeParseMicrosoftDeclSpecs(attrs);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001442
John McCall8d32c052012-05-22 21:28:12 +00001443 // Parse inheritance specifiers.
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001444 if (Tok.isOneOf(tok::kw___single_inheritance,
1445 tok::kw___multiple_inheritance,
1446 tok::kw___virtual_inheritance))
Richard Smith37a45dd2013-10-24 01:21:09 +00001447 ParseMicrosoftInheritanceClassAttributes(attrs);
John McCall8d32c052012-05-22 21:28:12 +00001448
Alexis Hunt96d5c762009-11-21 08:43:09 +00001449 // If C++0x attributes exist here, parse them.
1450 // FIXME: Are we consistent with the ordering of parsing of different
1451 // styles of attributes?
Richard Smith89645bc2013-01-02 12:01:23 +00001452 MaybeParseCXX11Attributes(attrs);
Mike Stump11289f42009-09-09 15:08:12 +00001453
Michael Han309af292013-01-07 16:57:11 +00001454 // Source location used by FIXIT to insert misplaced
1455 // C++11 attributes
1456 SourceLocation AttrFixitLoc = Tok.getLocation();
1457
Nico Weber7c3c5be2014-09-23 04:09:56 +00001458 if (TagType == DeclSpec::TST_struct &&
David Majnemer86330af2014-12-29 02:14:26 +00001459 Tok.isNot(tok::identifier) &&
1460 !Tok.isAnnotation() &&
Nico Weber7c3c5be2014-09-23 04:09:56 +00001461 Tok.getIdentifierInfo() &&
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001462 Tok.isOneOf(tok::kw___is_abstract,
Eric Fiselier07360662017-04-12 22:12:15 +00001463 tok::kw___is_aggregate,
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001464 tok::kw___is_arithmetic,
1465 tok::kw___is_array,
David Majnemerb3d96882016-05-23 17:21:55 +00001466 tok::kw___is_assignable,
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001467 tok::kw___is_base_of,
1468 tok::kw___is_class,
1469 tok::kw___is_complete_type,
1470 tok::kw___is_compound,
1471 tok::kw___is_const,
1472 tok::kw___is_constructible,
1473 tok::kw___is_convertible,
1474 tok::kw___is_convertible_to,
1475 tok::kw___is_destructible,
1476 tok::kw___is_empty,
1477 tok::kw___is_enum,
1478 tok::kw___is_floating_point,
1479 tok::kw___is_final,
1480 tok::kw___is_function,
1481 tok::kw___is_fundamental,
1482 tok::kw___is_integral,
1483 tok::kw___is_interface_class,
1484 tok::kw___is_literal,
1485 tok::kw___is_lvalue_expr,
1486 tok::kw___is_lvalue_reference,
1487 tok::kw___is_member_function_pointer,
1488 tok::kw___is_member_object_pointer,
1489 tok::kw___is_member_pointer,
1490 tok::kw___is_nothrow_assignable,
1491 tok::kw___is_nothrow_constructible,
1492 tok::kw___is_nothrow_destructible,
1493 tok::kw___is_object,
1494 tok::kw___is_pod,
1495 tok::kw___is_pointer,
1496 tok::kw___is_polymorphic,
1497 tok::kw___is_reference,
1498 tok::kw___is_rvalue_expr,
1499 tok::kw___is_rvalue_reference,
1500 tok::kw___is_same,
1501 tok::kw___is_scalar,
1502 tok::kw___is_sealed,
1503 tok::kw___is_signed,
1504 tok::kw___is_standard_layout,
1505 tok::kw___is_trivial,
1506 tok::kw___is_trivially_assignable,
1507 tok::kw___is_trivially_constructible,
1508 tok::kw___is_trivially_copyable,
1509 tok::kw___is_union,
1510 tok::kw___is_unsigned,
1511 tok::kw___is_void,
1512 tok::kw___is_volatile))
Nico Weber7c3c5be2014-09-23 04:09:56 +00001513 // GNU libstdc++ 4.2 and libc++ use certain intrinsic names as the
1514 // name of struct templates, but some are keywords in GCC >= 4.3
1515 // and Clang. Therefore, when we see the token sequence "struct
1516 // X", make X into a normal identifier rather than a keyword, to
1517 // allow libstdc++ 4.2 and libc++ to work properly.
1518 TryKeywordIdentFallback(true);
Mike Stump11289f42009-09-09 15:08:12 +00001519
David Majnemer51fd8a02015-07-22 23:46:18 +00001520 struct PreserveAtomicIdentifierInfoRAII {
1521 PreserveAtomicIdentifierInfoRAII(Token &Tok, bool Enabled)
1522 : AtomicII(nullptr) {
1523 if (!Enabled)
1524 return;
1525 assert(Tok.is(tok::kw__Atomic));
1526 AtomicII = Tok.getIdentifierInfo();
1527 AtomicII->revertTokenIDToIdentifier();
1528 Tok.setKind(tok::identifier);
1529 }
1530 ~PreserveAtomicIdentifierInfoRAII() {
1531 if (!AtomicII)
1532 return;
1533 AtomicII->revertIdentifierToTokenID(tok::kw__Atomic);
1534 }
1535 IdentifierInfo *AtomicII;
1536 };
1537
1538 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
1539 // implementation for VS2013 uses _Atomic as an identifier for one of the
1540 // classes in <atomic>. When we are parsing 'struct _Atomic', don't consider
1541 // '_Atomic' to be a keyword. We are careful to undo this so that clang can
1542 // use '_Atomic' in its own header files.
1543 bool ShouldChangeAtomicToIdentifier = getLangOpts().MSVCCompat &&
1544 Tok.is(tok::kw__Atomic) &&
1545 TagType == DeclSpec::TST_struct;
1546 PreserveAtomicIdentifierInfoRAII AtomicTokenGuard(
1547 Tok, ShouldChangeAtomicToIdentifier);
1548
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001549 // Parse the (optional) nested-name-specifier.
John McCall9dab4e62009-12-12 11:40:51 +00001550 CXXScopeSpec &SS = DS.getTypeSpecScope();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001551 if (getLangOpts().CPlusPlus) {
Serge Pavlov458ea762014-07-16 05:16:52 +00001552 // "FOO : BAR" is not a potential typo for "FOO::BAR". In this context it
1553 // is a base-specifier-list.
Chris Lattnerd5c1c9d2009-12-10 00:32:41 +00001554 ColonProtectionRAIIObject X(*this);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001555
Nico Webercfaa4cd2015-02-15 07:26:13 +00001556 CXXScopeSpec Spec;
1557 bool HasValidSpec = true;
Haojian Wu0dd0b102020-03-19 09:12:29 +01001558 if (ParseOptionalCXXScopeSpecifier(Spec, /*ObjectType=*/nullptr,
1559 /*ObjectHadErrors=*/false,
1560 EnteringContext)) {
John McCall413021a2010-07-30 06:26:29 +00001561 DS.SetTypeSpecError();
Nico Webercfaa4cd2015-02-15 07:26:13 +00001562 HasValidSpec = false;
1563 }
1564 if (Spec.isSet())
1565 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::annot_template_id)) {
Alp Tokerec543272013-12-24 09:48:30 +00001566 Diag(Tok, diag::err_expected) << tok::identifier;
Nico Webercfaa4cd2015-02-15 07:26:13 +00001567 HasValidSpec = false;
1568 }
1569 if (HasValidSpec)
1570 SS = Spec;
Chris Lattnerd5c1c9d2009-12-10 00:32:41 +00001571 }
Douglas Gregor67a65642009-02-17 23:15:12 +00001572
Douglas Gregor916462b2009-10-30 21:46:58 +00001573 TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
1574
Richard Smithb23c5e82019-05-09 03:31:27 +00001575 auto RecoverFromUndeclaredTemplateName = [&](IdentifierInfo *Name,
1576 SourceLocation NameLoc,
1577 SourceRange TemplateArgRange,
1578 bool KnownUndeclared) {
1579 Diag(NameLoc, diag::err_explicit_spec_non_template)
1580 << (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
1581 << TagTokKind << Name << TemplateArgRange << KnownUndeclared;
1582
1583 // Strip off the last template parameter list if it was empty, since
1584 // we've removed its template argument list.
1585 if (TemplateParams && TemplateInfo.LastParameterListWasEmpty) {
1586 if (TemplateParams->size() > 1) {
1587 TemplateParams->pop_back();
1588 } else {
1589 TemplateParams = nullptr;
1590 const_cast<ParsedTemplateInfo &>(TemplateInfo).Kind =
1591 ParsedTemplateInfo::NonTemplate;
1592 }
1593 } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1594 // Pretend this is just a forward declaration.
1595 TemplateParams = nullptr;
1596 const_cast<ParsedTemplateInfo &>(TemplateInfo).Kind =
1597 ParsedTemplateInfo::NonTemplate;
1598 const_cast<ParsedTemplateInfo &>(TemplateInfo).TemplateLoc =
1599 SourceLocation();
1600 const_cast<ParsedTemplateInfo &>(TemplateInfo).ExternLoc =
1601 SourceLocation();
1602 }
1603 };
1604
Douglas Gregor67a65642009-02-17 23:15:12 +00001605 // Parse the (optional) class name or simple-template-id.
Craig Topper161e4db2014-05-21 06:02:52 +00001606 IdentifierInfo *Name = nullptr;
Douglas Gregor556877c2008-04-13 21:30:24 +00001607 SourceLocation NameLoc;
Craig Topper161e4db2014-05-21 06:02:52 +00001608 TemplateIdAnnotation *TemplateId = nullptr;
Douglas Gregor556877c2008-04-13 21:30:24 +00001609 if (Tok.is(tok::identifier)) {
1610 Name = Tok.getIdentifierInfo();
1611 NameLoc = ConsumeToken();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001612
David Blaikiebbafb8a2012-03-11 07:00:24 +00001613 if (Tok.is(tok::less) && getLangOpts().CPlusPlus) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001614 // The name was supposed to refer to a template, but didn't.
Douglas Gregor916462b2009-10-30 21:46:58 +00001615 // Eat the template argument list and try to continue parsing this as
1616 // a class (or template thereof).
1617 TemplateArgList TemplateArgs;
Douglas Gregor916462b2009-10-30 21:46:58 +00001618 SourceLocation LAngleLoc, RAngleLoc;
Richard Smith9a420f92017-05-10 21:47:30 +00001619 if (ParseTemplateIdAfterTemplateName(true, LAngleLoc, TemplateArgs,
1620 RAngleLoc)) {
Douglas Gregor916462b2009-10-30 21:46:58 +00001621 // We couldn't parse the template argument list at all, so don't
1622 // try to give any location information for the list.
1623 LAngleLoc = RAngleLoc = SourceLocation();
1624 }
Richard Smithb23c5e82019-05-09 03:31:27 +00001625 RecoverFromUndeclaredTemplateName(
1626 Name, NameLoc, SourceRange(LAngleLoc, RAngleLoc), false);
Douglas Gregor916462b2009-10-30 21:46:58 +00001627 }
Douglas Gregor7f741122009-02-25 19:37:18 +00001628 } else if (Tok.is(tok::annot_template_id)) {
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00001629 TemplateId = takeTemplateIdAnnotation(Tok);
Richard Smithaf3b3252017-05-18 19:21:48 +00001630 NameLoc = ConsumeAnnotationToken();
Douglas Gregor67a65642009-02-17 23:15:12 +00001631
Richard Smithb23c5e82019-05-09 03:31:27 +00001632 if (TemplateId->Kind == TNK_Undeclared_template) {
1633 // Try to resolve the template name to a type template.
1634 Actions.ActOnUndeclaredTypeTemplateName(getCurScope(), TemplateId->Template,
1635 TemplateId->Kind, NameLoc, Name);
1636 if (TemplateId->Kind == TNK_Undeclared_template) {
1637 RecoverFromUndeclaredTemplateName(
1638 Name, NameLoc,
1639 SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc), true);
1640 TemplateId = nullptr;
1641 }
1642 }
1643
1644 if (TemplateId && TemplateId->Kind != TNK_Type_template &&
Douglas Gregore7c20652011-03-02 00:47:37 +00001645 TemplateId->Kind != TNK_Dependent_template_name) {
Douglas Gregor7f741122009-02-25 19:37:18 +00001646 // The template-name in the simple-template-id refers to
1647 // something other than a class template. Give an appropriate
1648 // error message and skip to the ';'.
1649 SourceRange Range(NameLoc);
1650 if (SS.isNotEmpty())
1651 Range.setBegin(SS.getBeginLoc());
Douglas Gregor67a65642009-02-17 23:15:12 +00001652
Richard Smith72bfbd82013-12-04 00:28:23 +00001653 // FIXME: Name may be null here.
Douglas Gregor7f741122009-02-25 19:37:18 +00001654 Diag(TemplateId->LAngleLoc, diag::err_template_spec_syntax_non_template)
Richard Smithb23c5e82019-05-09 03:31:27 +00001655 << TemplateId->Name << static_cast<int>(TemplateId->Kind) << Range;
Mike Stump11289f42009-09-09 15:08:12 +00001656
Douglas Gregor7f741122009-02-25 19:37:18 +00001657 DS.SetTypeSpecError();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001658 SkipUntil(tok::semi, StopBeforeMatch);
Douglas Gregor7f741122009-02-25 19:37:18 +00001659 return;
Douglas Gregor67a65642009-02-17 23:15:12 +00001660 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001661 }
1662
Richard Smithbfdb1082012-03-12 08:56:40 +00001663 // There are four options here.
1664 // - If we are in a trailing return type, this is always just a reference,
1665 // and we must not try to parse a definition. For instance,
1666 // [] () -> struct S { };
1667 // does not define a type.
1668 // - If we have 'struct foo {...', 'struct foo :...',
1669 // 'struct foo final :' or 'struct foo final {', then this is a definition.
1670 // - If we have 'struct foo;', then this is either a forward declaration
1671 // or a friend declaration, which have to be treated differently.
1672 // - Otherwise we have something like 'struct foo xyz', a reference.
Michael Han9407e502012-11-26 22:54:45 +00001673 //
1674 // We also detect these erroneous cases to provide better diagnostic for
1675 // C++11 attributes parsing.
1676 // - attributes follow class name:
1677 // struct foo [[]] {};
1678 // - attributes appear before or after 'final':
1679 // struct foo [[]] final [[]] {};
1680 //
Richard Smithc5b05522012-03-12 07:56:15 +00001681 // However, in type-specifier-seq's, things look like declarations but are
1682 // just references, e.g.
1683 // new struct s;
Sebastian Redl2b372722010-02-03 21:21:43 +00001684 // or
Richard Smithc5b05522012-03-12 07:56:15 +00001685 // &T::operator struct s;
Faisal Vali7db85c52017-12-31 00:06:40 +00001686 // For these, DSC is DeclSpecContext::DSC_type_specifier or
1687 // DeclSpecContext::DSC_alias_declaration.
Michael Han9407e502012-11-26 22:54:45 +00001688
1689 // If there are attributes after class name, parse them.
Richard Smith89645bc2013-01-02 12:01:23 +00001690 MaybeParseCXX11Attributes(Attributes);
Michael Han9407e502012-11-26 22:54:45 +00001691
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001692 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
John McCallfaf5fb42010-08-26 23:41:50 +00001693 Sema::TagUseKind TUK;
Faisal Vali7db85c52017-12-31 00:06:40 +00001694 if (DSC == DeclSpecContext::DSC_trailing)
Richard Smithbfdb1082012-03-12 08:56:40 +00001695 TUK = Sema::TUK_Reference;
1696 else if (Tok.is(tok::l_brace) ||
1697 (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
Richard Smith89645bc2013-01-02 12:01:23 +00001698 (isCXX11FinalKeyword() &&
David Blaikie9933a5a2012-03-12 15:39:49 +00001699 (NextToken().is(tok::l_brace) || NextToken().is(tok::colon)))) {
Douglas Gregor3dad8422009-09-26 06:47:28 +00001700 if (DS.isFriendSpecified()) {
1701 // C++ [class.friend]p2:
1702 // A class shall not be defined in a friend declaration.
Richard Smith0f8ee222012-01-10 01:33:14 +00001703 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
Douglas Gregor3dad8422009-09-26 06:47:28 +00001704 << SourceRange(DS.getFriendSpecLoc());
1705
1706 // Skip everything up to the semicolon, so that this looks like a proper
1707 // friend class (or template thereof) declaration.
Alexey Bataevee6507d2013-11-18 08:17:37 +00001708 SkipUntil(tok::semi, StopBeforeMatch);
John McCallfaf5fb42010-08-26 23:41:50 +00001709 TUK = Sema::TUK_Friend;
Douglas Gregor3dad8422009-09-26 06:47:28 +00001710 } else {
1711 // Okay, this is a class definition.
John McCallfaf5fb42010-08-26 23:41:50 +00001712 TUK = Sema::TUK_Definition;
Douglas Gregor3dad8422009-09-26 06:47:28 +00001713 }
Richard Smith434516c2013-02-22 06:46:23 +00001714 } else if (isCXX11FinalKeyword() && (NextToken().is(tok::l_square) ||
1715 NextToken().is(tok::kw_alignas))) {
Michael Han9407e502012-11-26 22:54:45 +00001716 // We can't tell if this is a definition or reference
1717 // until we skipped the 'final' and C++11 attribute specifiers.
1718 TentativeParsingAction PA(*this);
1719
1720 // Skip the 'final' keyword.
1721 ConsumeToken();
1722
1723 // Skip C++11 attribute specifiers.
1724 while (true) {
1725 if (Tok.is(tok::l_square) && NextToken().is(tok::l_square)) {
1726 ConsumeBracket();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001727 if (!SkipUntil(tok::r_square, StopAtSemi))
Michael Han9407e502012-11-26 22:54:45 +00001728 break;
Richard Smith434516c2013-02-22 06:46:23 +00001729 } else if (Tok.is(tok::kw_alignas) && NextToken().is(tok::l_paren)) {
Michael Han9407e502012-11-26 22:54:45 +00001730 ConsumeToken();
1731 ConsumeParen();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001732 if (!SkipUntil(tok::r_paren, StopAtSemi))
Michael Han9407e502012-11-26 22:54:45 +00001733 break;
1734 } else {
1735 break;
1736 }
1737 }
1738
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001739 if (Tok.isOneOf(tok::l_brace, tok::colon))
Michael Han9407e502012-11-26 22:54:45 +00001740 TUK = Sema::TUK_Definition;
1741 else
1742 TUK = Sema::TUK_Reference;
1743
1744 PA.Revert();
Richard Smith649c7b062014-01-08 00:56:48 +00001745 } else if (!isTypeSpecifier(DSC) &&
Richard Smith369b9f92012-06-25 21:37:02 +00001746 (Tok.is(tok::semi) ||
Richard Smith200f47c2012-07-02 19:14:01 +00001747 (Tok.isAtStartOfLine() && !isValidAfterTypeSpecifier(false)))) {
John McCallfaf5fb42010-08-26 23:41:50 +00001748 TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
Joao Matose9a3ed42012-08-31 22:18:20 +00001749 if (Tok.isNot(tok::semi)) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001750 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
Joao Matose9a3ed42012-08-31 22:18:20 +00001751 // A semicolon was missing after this declaration. Diagnose and recover.
Alp Toker383d2c42014-01-01 03:08:43 +00001752 ExpectAndConsume(tok::semi, diag::err_expected_after,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001753 DeclSpec::getSpecifierName(TagType, PPol));
Ilya Biryukov929af672019-05-17 09:32:05 +00001754 PP.EnterToken(Tok, /*IsReinject*/true);
Joao Matose9a3ed42012-08-31 22:18:20 +00001755 Tok.setKind(tok::semi);
1756 }
Richard Smith369b9f92012-06-25 21:37:02 +00001757 } else
John McCallfaf5fb42010-08-26 23:41:50 +00001758 TUK = Sema::TUK_Reference;
Douglas Gregor556877c2008-04-13 21:30:24 +00001759
Michael Han9407e502012-11-26 22:54:45 +00001760 // Forbid misplaced attributes. In cases of a reference, we pass attributes
1761 // to caller to handle.
Michael Han309af292013-01-07 16:57:11 +00001762 if (TUK != Sema::TUK_Reference) {
1763 // If this is not a reference, then the only possible
1764 // valid place for C++11 attributes to appear here
1765 // is between class-key and class-name. If there are
1766 // any attributes after class-name, we try a fixit to move
1767 // them to the right place.
1768 SourceRange AttrRange = Attributes.Range;
1769 if (AttrRange.isValid()) {
1770 Diag(AttrRange.getBegin(), diag::err_attributes_not_allowed)
1771 << AttrRange
1772 << FixItHint::CreateInsertionFromRange(AttrFixitLoc,
1773 CharSourceRange(AttrRange, true))
1774 << FixItHint::CreateRemoval(AttrRange);
1775
1776 // Recover by adding misplaced attributes to the attribute list
1777 // of the class so they can be applied on the class later.
1778 attrs.takeAllFrom(Attributes);
1779 }
1780 }
Michael Han9407e502012-11-26 22:54:45 +00001781
John McCall6347b682012-05-07 06:16:58 +00001782 // If this is an elaborated type specifier, and we delayed
1783 // diagnostics before, just merge them into the current pool.
1784 if (shouldDelayDiagsInTag) {
1785 diagsFromTag.done();
1786 if (TUK == Sema::TUK_Reference)
1787 diagsFromTag.redelay();
1788 }
1789
John McCall413021a2010-07-30 06:26:29 +00001790 if (!Name && !TemplateId && (DS.getTypeSpecType() == DeclSpec::TST_error ||
John McCallfaf5fb42010-08-26 23:41:50 +00001791 TUK != Sema::TUK_Definition)) {
John McCall413021a2010-07-30 06:26:29 +00001792 if (DS.getTypeSpecType() != DeclSpec::TST_error) {
1793 // We have a declaration or reference to an anonymous class.
1794 Diag(StartLoc, diag::err_anon_type_definition)
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001795 << DeclSpec::getSpecifierName(TagType, Policy);
John McCall413021a2010-07-30 06:26:29 +00001796 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001797
David Majnemer3252fd02013-12-05 01:36:53 +00001798 // If we are parsing a definition and stop at a base-clause, continue on
1799 // until the semicolon. Continuing from the comma will just trick us into
1800 // thinking we are seeing a variable declaration.
1801 if (TUK == Sema::TUK_Definition && Tok.is(tok::colon))
1802 SkipUntil(tok::semi, StopBeforeMatch);
1803 else
1804 SkipUntil(tok::comma, StopAtSemi);
Douglas Gregor556877c2008-04-13 21:30:24 +00001805 return;
1806 }
1807
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001808 // Create the tag portion of the class or class template.
John McCall48871652010-08-21 09:40:31 +00001809 DeclResult TagOrTempResult = true; // invalid
1810 TypeResult TypeResult = true; // invalid
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001811
Douglas Gregord6ab8742009-05-28 23:31:59 +00001812 bool Owned = false;
Richard Smithd9ba2242015-05-07 03:54:19 +00001813 Sema::SkipBodyInfo SkipBody;
John McCall06f6fe8d2009-09-04 01:14:41 +00001814 if (TemplateId) {
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001815 // Explicit specialization, class template partial specialization,
1816 // or explicit instantiation.
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00001817 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregor7f741122009-02-25 19:37:18 +00001818 TemplateId->NumArgs);
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001819 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
John McCallfaf5fb42010-08-26 23:41:50 +00001820 TUK == Sema::TUK_Declaration) {
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001821 // This is an explicit instantiation of a class template.
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001822 ProhibitAttributes(attrs);
1823
Erich Keanec480f302018-07-12 21:09:05 +00001824 TagOrTempResult = Actions.ActOnExplicitInstantiation(
1825 getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc,
1826 TagType, StartLoc, SS, TemplateId->Template,
1827 TemplateId->TemplateNameLoc, TemplateId->LAngleLoc, TemplateArgsPtr,
1828 TemplateId->RAngleLoc, attrs);
John McCallb7c5c272010-04-14 00:24:33 +00001829
Erich Keanec480f302018-07-12 21:09:05 +00001830 // Friend template-ids are treated as references unless
1831 // they have template headers, in which case they're ill-formed
1832 // (FIXME: "template <class T> friend class A<T>::B<int>;").
1833 // We diagnose this error in ActOnClassTemplateSpecialization.
John McCallfaf5fb42010-08-26 23:41:50 +00001834 } else if (TUK == Sema::TUK_Reference ||
1835 (TUK == Sema::TUK_Friend &&
John McCallb7c5c272010-04-14 00:24:33 +00001836 TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate)) {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001837 ProhibitAttributes(attrs);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00001838 TypeResult = Actions.ActOnTagTemplateIdType(TUK, TagType, StartLoc,
Richard Smitha42fd842020-01-17 15:42:11 -08001839 SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00001840 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00001841 TemplateId->Template,
1842 TemplateId->TemplateNameLoc,
1843 TemplateId->LAngleLoc,
1844 TemplateArgsPtr,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00001845 TemplateId->RAngleLoc);
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001846 } else {
1847 // This is an explicit specialization or a class template
1848 // partial specialization.
1849 TemplateParameterLists FakedParamLists;
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001850 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1851 // This looks like an explicit instantiation, because we have
1852 // something like
1853 //
1854 // template class Foo<X>
1855 //
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001856 // but it actually has a definition. Most likely, this was
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001857 // meant to be an explicit specialization, but the user forgot
1858 // the '<>' after 'template'.
Richard Smith003c5e12013-11-08 19:03:29 +00001859 // It this is friend declaration however, since it cannot have a
1860 // template header, it is most likely that the user meant to
1861 // remove the 'template' keyword.
Larisse Voufob9bbaba2013-06-22 13:56:11 +00001862 assert((TUK == Sema::TUK_Definition || TUK == Sema::TUK_Friend) &&
Richard Smith003c5e12013-11-08 19:03:29 +00001863 "Expected a definition here");
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001864
Richard Smith003c5e12013-11-08 19:03:29 +00001865 if (TUK == Sema::TUK_Friend) {
1866 Diag(DS.getFriendSpecLoc(), diag::err_friend_explicit_instantiation);
Craig Topper161e4db2014-05-21 06:02:52 +00001867 TemplateParams = nullptr;
Richard Smith003c5e12013-11-08 19:03:29 +00001868 } else {
1869 SourceLocation LAngleLoc =
1870 PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
1871 Diag(TemplateId->TemplateNameLoc,
1872 diag::err_explicit_instantiation_with_definition)
1873 << SourceRange(TemplateInfo.TemplateLoc)
1874 << FixItHint::CreateInsertion(LAngleLoc, "<>");
1875
1876 // Create a fake template parameter list that contains only
1877 // "template<>", so that we treat this construct as a class
1878 // template specialization.
1879 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
Craig Topper96225a52015-12-24 23:58:25 +00001880 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
Hubert Tongf608c052016-04-29 18:05:37 +00001881 LAngleLoc, nullptr));
Richard Smith003c5e12013-11-08 19:03:29 +00001882 TemplateParams = &FakedParamLists;
1883 }
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001884 }
1885
1886 // Build the class template specialization.
Richard Smith4b55a9c2014-04-17 03:29:33 +00001887 TagOrTempResult = Actions.ActOnClassTemplateSpecialization(
1888 getCurScope(), TagType, TUK, StartLoc, DS.getModulePrivateSpecLoc(),
Richard Smitha42fd842020-01-17 15:42:11 -08001889 SS, *TemplateId, attrs,
Craig Topper161e4db2014-05-21 06:02:52 +00001890 MultiTemplateParamsArg(TemplateParams ? &(*TemplateParams)[0]
1891 : nullptr,
Richard Smithc7e6ff02015-05-18 20:36:47 +00001892 TemplateParams ? TemplateParams->size() : 0),
1893 &SkipBody);
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001894 }
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001895 } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
John McCallfaf5fb42010-08-26 23:41:50 +00001896 TUK == Sema::TUK_Declaration) {
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001897 // Explicit instantiation of a member of a class template
1898 // specialization, e.g.,
1899 //
1900 // template struct Outer<int>::Inner;
1901 //
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001902 ProhibitAttributes(attrs);
1903
Erich Keanec480f302018-07-12 21:09:05 +00001904 TagOrTempResult = Actions.ActOnExplicitInstantiation(
1905 getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc,
1906 TagType, StartLoc, SS, Name, NameLoc, attrs);
John McCallace48cd2010-10-19 01:40:49 +00001907 } else if (TUK == Sema::TUK_Friend &&
1908 TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate) {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001909 ProhibitAttributes(attrs);
1910
Erich Keanec480f302018-07-12 21:09:05 +00001911 TagOrTempResult = Actions.ActOnTemplatedFriendTag(
1912 getCurScope(), DS.getFriendSpecLoc(), TagType, StartLoc, SS, Name,
1913 NameLoc, attrs,
1914 MultiTemplateParamsArg(TemplateParams ? &(*TemplateParams)[0] : nullptr,
1915 TemplateParams ? TemplateParams->size() : 0));
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001916 } else {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001917 if (TUK != Sema::TUK_Declaration && TUK != Sema::TUK_Definition)
1918 ProhibitAttributes(attrs);
Richard Smith003c5e12013-11-08 19:03:29 +00001919
Larisse Voufo725de3e2013-06-21 00:08:46 +00001920 if (TUK == Sema::TUK_Definition &&
1921 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1922 // If the declarator-id is not a template-id, issue a diagnostic and
1923 // recover by ignoring the 'template' keyword.
1924 Diag(Tok, diag::err_template_defn_explicit_instantiation)
1925 << 1 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
Craig Topper161e4db2014-05-21 06:02:52 +00001926 TemplateParams = nullptr;
Larisse Voufo725de3e2013-06-21 00:08:46 +00001927 }
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001928
John McCall7f41d982009-09-11 04:59:25 +00001929 bool IsDependent = false;
1930
John McCall32723e92010-10-19 18:40:57 +00001931 // Don't pass down template parameter lists if this is just a tag
1932 // reference. For example, we don't need the template parameters here:
1933 // template <class T> class A *makeA(T t);
1934 MultiTemplateParamsArg TParams;
1935 if (TUK != Sema::TUK_Reference && TemplateParams)
1936 TParams =
1937 MultiTemplateParamsArg(&(*TemplateParams)[0], TemplateParams->size());
1938
Nico Weber32a0fc72016-09-03 03:01:32 +00001939 stripTypeAttributesOffDeclSpec(attrs, DS, TUK);
David Majnemer936b4112015-04-19 07:53:29 +00001940
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001941 // Declaration or definition of a class type
Faisal Vali7db85c52017-12-31 00:06:40 +00001942 TagOrTempResult = Actions.ActOnTag(
Erich Keanec480f302018-07-12 21:09:05 +00001943 getCurScope(), TagType, TUK, StartLoc, SS, Name, NameLoc, attrs, AS,
1944 DS.getModulePrivateSpecLoc(), TParams, Owned, IsDependent,
1945 SourceLocation(), false, clang::TypeResult(),
Faisal Vali7db85c52017-12-31 00:06:40 +00001946 DSC == DeclSpecContext::DSC_type_specifier,
1947 DSC == DeclSpecContext::DSC_template_param ||
1948 DSC == DeclSpecContext::DSC_template_type_arg,
1949 &SkipBody);
John McCall7f41d982009-09-11 04:59:25 +00001950
1951 // If ActOnTag said the type was dependent, try again with the
1952 // less common call.
John McCallace48cd2010-10-19 01:40:49 +00001953 if (IsDependent) {
1954 assert(TUK == Sema::TUK_Reference || TUK == Sema::TUK_Friend);
Douglas Gregor0be31a22010-07-02 17:43:08 +00001955 TypeResult = Actions.ActOnDependentTag(getCurScope(), TagType, TUK,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001956 SS, Name, StartLoc, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +00001957 }
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001958 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001959
Douglas Gregor556877c2008-04-13 21:30:24 +00001960 // If there is a body, parse it and inform the actions module.
John McCallfaf5fb42010-08-26 23:41:50 +00001961 if (TUK == Sema::TUK_Definition) {
John McCall2d814c32009-12-19 21:48:58 +00001962 assert(Tok.is(tok::l_brace) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00001963 (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
Richard Smith89645bc2013-01-02 12:01:23 +00001964 isCXX11FinalKeyword());
Richard Smithd9ba2242015-05-07 03:54:19 +00001965 if (SkipBody.ShouldSkip)
Richard Smith65ebb4a2015-03-26 04:09:53 +00001966 SkipCXXMemberSpecification(StartLoc, AttrFixitLoc, TagType,
1967 TagOrTempResult.get());
1968 else if (getLangOpts().CPlusPlus)
Michael Han309af292013-01-07 16:57:11 +00001969 ParseCXXMemberSpecification(StartLoc, AttrFixitLoc, attrs, TagType,
1970 TagOrTempResult.get());
Bruno Cardoso Lopesdf0ee342017-07-01 00:06:47 +00001971 else {
1972 Decl *D =
1973 SkipBody.CheckSameAsPrevious ? SkipBody.New : TagOrTempResult.get();
1974 // Parse the definition body.
1975 ParseStructUnionBody(StartLoc, TagType, D);
1976 if (SkipBody.CheckSameAsPrevious &&
1977 !Actions.ActOnDuplicateDefinition(DS, TagOrTempResult.get(),
1978 SkipBody)) {
1979 DS.SetTypeSpecError();
1980 return;
1981 }
1982 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001983 }
1984
Erich Keane2fe684b2017-02-28 20:44:39 +00001985 if (!TagOrTempResult.isInvalid())
Hiroshi Inoue939d9322017-06-30 05:40:31 +00001986 // Delayed processing of attributes.
Erich Keanec480f302018-07-12 21:09:05 +00001987 Actions.ProcessDeclAttributeDelayed(TagOrTempResult.get(), attrs);
Erich Keane2fe684b2017-02-28 20:44:39 +00001988
Craig Topper161e4db2014-05-21 06:02:52 +00001989 const char *PrevSpec = nullptr;
John McCallba7bf592010-08-24 05:47:05 +00001990 unsigned DiagID;
1991 bool Result;
John McCall7f41d982009-09-11 04:59:25 +00001992 if (!TypeResult.isInvalid()) {
Abramo Bagnara9875a3c2011-03-16 20:16:18 +00001993 Result = DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
1994 NameLoc.isValid() ? NameLoc : StartLoc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001995 PrevSpec, DiagID, TypeResult.get(), Policy);
John McCall7f41d982009-09-11 04:59:25 +00001996 } else if (!TagOrTempResult.isInvalid()) {
Abramo Bagnara9875a3c2011-03-16 20:16:18 +00001997 Result = DS.SetTypeSpecType(TagType, StartLoc,
1998 NameLoc.isValid() ? NameLoc : StartLoc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001999 PrevSpec, DiagID, TagOrTempResult.get(), Owned,
2000 Policy);
John McCall7f41d982009-09-11 04:59:25 +00002001 } else {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002002 DS.SetTypeSpecError();
Anders Carlssonf83c9fa2009-05-11 22:27:47 +00002003 return;
2004 }
Mike Stump11289f42009-09-09 15:08:12 +00002005
John McCallba7bf592010-08-24 05:47:05 +00002006 if (Result)
John McCall49bfce42009-08-03 20:12:06 +00002007 Diag(StartLoc, DiagID) << PrevSpec;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002008
Chris Lattnercf251412010-02-02 01:23:29 +00002009 // At this point, we've successfully parsed a class-specifier in 'definition'
2010 // form (e.g. "struct foo { int x; }". While we could just return here, we're
2011 // going to look at what comes after it to improve error recovery. If an
2012 // impossible token occurs next, we assume that the programmer forgot a ; at
2013 // the end of the declaration and recover that way.
2014 //
Richard Smith369b9f92012-06-25 21:37:02 +00002015 // Also enforce C++ [temp]p3:
2016 // In a template-declaration which defines a class, no declarator
2017 // is permitted.
Richard Smith843f18f2014-08-13 02:13:15 +00002018 //
2019 // After a type-specifier, we don't expect a semicolon. This only happens in
2020 // C, since definitions are not permitted in this context in C++.
Joao Matose9a3ed42012-08-31 22:18:20 +00002021 if (TUK == Sema::TUK_Definition &&
Richard Smith843f18f2014-08-13 02:13:15 +00002022 (getLangOpts().CPlusPlus || !isTypeSpecifier(DSC)) &&
Joao Matose9a3ed42012-08-31 22:18:20 +00002023 (TemplateInfo.Kind || !isValidAfterTypeSpecifier(false))) {
Argyrios Kyrtzidise6f69132012-12-17 20:10:43 +00002024 if (Tok.isNot(tok::semi)) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002025 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
Alp Toker383d2c42014-01-01 03:08:43 +00002026 ExpectAndConsume(tok::semi, diag::err_expected_after,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002027 DeclSpec::getSpecifierName(TagType, PPol));
Argyrios Kyrtzidise6f69132012-12-17 20:10:43 +00002028 // Push this token back into the preprocessor and change our current token
2029 // to ';' so that the rest of the code recovers as though there were an
2030 // ';' after the definition.
Ilya Biryukov929af672019-05-17 09:32:05 +00002031 PP.EnterToken(Tok, /*IsReinject=*/true);
Argyrios Kyrtzidise6f69132012-12-17 20:10:43 +00002032 Tok.setKind(tok::semi);
2033 }
Chris Lattnercf251412010-02-02 01:23:29 +00002034 }
Douglas Gregor556877c2008-04-13 21:30:24 +00002035}
2036
Mike Stump11289f42009-09-09 15:08:12 +00002037/// ParseBaseClause - Parse the base-clause of a C++ class [C++ class.derived].
Douglas Gregor556877c2008-04-13 21:30:24 +00002038///
2039/// base-clause : [C++ class.derived]
2040/// ':' base-specifier-list
2041/// base-specifier-list:
2042/// base-specifier '...'[opt]
2043/// base-specifier-list ',' base-specifier '...'[opt]
John McCall48871652010-08-21 09:40:31 +00002044void Parser::ParseBaseClause(Decl *ClassDecl) {
Douglas Gregor556877c2008-04-13 21:30:24 +00002045 assert(Tok.is(tok::colon) && "Not a base clause");
2046 ConsumeToken();
2047
Douglas Gregor29a92472008-10-22 17:49:05 +00002048 // Build up an array of parsed base specifiers.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002049 SmallVector<CXXBaseSpecifier *, 8> BaseInfo;
Douglas Gregor29a92472008-10-22 17:49:05 +00002050
Douglas Gregor556877c2008-04-13 21:30:24 +00002051 while (true) {
2052 // Parse a base-specifier.
Douglas Gregor29a92472008-10-22 17:49:05 +00002053 BaseResult Result = ParseBaseSpecifier(ClassDecl);
Douglas Gregorf8298252009-01-26 22:44:13 +00002054 if (Result.isInvalid()) {
Douglas Gregor556877c2008-04-13 21:30:24 +00002055 // Skip the rest of this base specifier, up until the comma or
2056 // opening brace.
Alexey Bataevee6507d2013-11-18 08:17:37 +00002057 SkipUntil(tok::comma, tok::l_brace, StopAtSemi | StopBeforeMatch);
Douglas Gregor29a92472008-10-22 17:49:05 +00002058 } else {
2059 // Add this to our array of base specifiers.
Douglas Gregorf8298252009-01-26 22:44:13 +00002060 BaseInfo.push_back(Result.get());
Douglas Gregor556877c2008-04-13 21:30:24 +00002061 }
2062
2063 // If the next token is a comma, consume it and keep reading
2064 // base-specifiers.
Alp Toker97650562014-01-10 11:19:30 +00002065 if (!TryConsumeToken(tok::comma))
2066 break;
Douglas Gregor556877c2008-04-13 21:30:24 +00002067 }
Douglas Gregor29a92472008-10-22 17:49:05 +00002068
2069 // Attach the base specifiers
Craig Topperaa700cb2015-12-27 21:55:19 +00002070 Actions.ActOnBaseSpecifiers(ClassDecl, BaseInfo);
Douglas Gregor556877c2008-04-13 21:30:24 +00002071}
2072
2073/// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is
2074/// one entry in the base class list of a class specifier, for example:
2075/// class foo : public bar, virtual private baz {
2076/// 'public bar' and 'virtual private baz' are each base-specifiers.
2077///
2078/// base-specifier: [C++ class.derived]
Richard Smith4c96e992013-02-19 23:47:15 +00002079/// attribute-specifier-seq[opt] base-type-specifier
2080/// attribute-specifier-seq[opt] 'virtual' access-specifier[opt]
2081/// base-type-specifier
2082/// attribute-specifier-seq[opt] access-specifier 'virtual'[opt]
2083/// base-type-specifier
Craig Topper9ad7e262014-10-31 06:57:07 +00002084BaseResult Parser::ParseBaseSpecifier(Decl *ClassDecl) {
Douglas Gregor556877c2008-04-13 21:30:24 +00002085 bool IsVirtual = false;
2086 SourceLocation StartLoc = Tok.getLocation();
2087
Richard Smith4c96e992013-02-19 23:47:15 +00002088 ParsedAttributesWithRange Attributes(AttrFactory);
2089 MaybeParseCXX11Attributes(Attributes);
2090
Douglas Gregor556877c2008-04-13 21:30:24 +00002091 // Parse the 'virtual' keyword.
Alp Toker97650562014-01-10 11:19:30 +00002092 if (TryConsumeToken(tok::kw_virtual))
Douglas Gregor556877c2008-04-13 21:30:24 +00002093 IsVirtual = true;
Douglas Gregor556877c2008-04-13 21:30:24 +00002094
Richard Smith4c96e992013-02-19 23:47:15 +00002095 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2096
Douglas Gregor556877c2008-04-13 21:30:24 +00002097 // Parse an (optional) access specifier.
2098 AccessSpecifier Access = getAccessSpecifierIfPresent();
John McCall553c0792010-01-23 00:46:32 +00002099 if (Access != AS_none)
Douglas Gregor556877c2008-04-13 21:30:24 +00002100 ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +00002101
Richard Smith4c96e992013-02-19 23:47:15 +00002102 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2103
Douglas Gregor556877c2008-04-13 21:30:24 +00002104 // Parse the 'virtual' keyword (again!), in case it came after the
2105 // access specifier.
2106 if (Tok.is(tok::kw_virtual)) {
2107 SourceLocation VirtualLoc = ConsumeToken();
2108 if (IsVirtual) {
2109 // Complain about duplicate 'virtual'
Chris Lattner6d29c102008-11-18 07:48:38 +00002110 Diag(VirtualLoc, diag::err_dup_virtual)
Douglas Gregora771f462010-03-31 17:46:05 +00002111 << FixItHint::CreateRemoval(VirtualLoc);
Douglas Gregor556877c2008-04-13 21:30:24 +00002112 }
2113
2114 IsVirtual = true;
2115 }
2116
Richard Smith4c96e992013-02-19 23:47:15 +00002117 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2118
Douglas Gregor831c93f2008-11-05 20:51:48 +00002119 // Parse the class-name.
David Majnemer51fd8a02015-07-22 23:46:18 +00002120
2121 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
2122 // implementation for VS2013 uses _Atomic as an identifier for one of the
2123 // classes in <atomic>. Treat '_Atomic' to be an identifier when we are
2124 // parsing the class-name for a base specifier.
2125 if (getLangOpts().MSVCCompat && Tok.is(tok::kw__Atomic) &&
2126 NextToken().is(tok::less))
2127 Tok.setKind(tok::identifier);
2128
Douglas Gregord54dfb82009-02-25 23:52:28 +00002129 SourceLocation EndLocation;
David Blaikie1cd50022011-10-25 17:10:12 +00002130 SourceLocation BaseLoc;
2131 TypeResult BaseType = ParseBaseTypeSpecifier(BaseLoc, EndLocation);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00002132 if (BaseType.isInvalid())
Douglas Gregor831c93f2008-11-05 20:51:48 +00002133 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002134
Fangrui Song6907ce22018-07-30 19:24:48 +00002135 // Parse the optional ellipsis (for a pack expansion). The ellipsis is
Douglas Gregor752a5952011-01-03 22:36:02 +00002136 // actually part of the base-specifier-list grammar productions, but we
2137 // parse it here for convenience.
2138 SourceLocation EllipsisLoc;
Alp Toker97650562014-01-10 11:19:30 +00002139 TryConsumeToken(tok::ellipsis, EllipsisLoc);
2140
Mike Stump11289f42009-09-09 15:08:12 +00002141 // Find the complete source range for the base-specifier.
Douglas Gregord54dfb82009-02-25 23:52:28 +00002142 SourceRange Range(StartLoc, EndLocation);
Mike Stump11289f42009-09-09 15:08:12 +00002143
Douglas Gregor556877c2008-04-13 21:30:24 +00002144 // Notify semantic analysis that we have parsed a complete
2145 // base-specifier.
Richard Smith4c96e992013-02-19 23:47:15 +00002146 return Actions.ActOnBaseSpecifier(ClassDecl, Range, Attributes, IsVirtual,
2147 Access, BaseType.get(), BaseLoc,
2148 EllipsisLoc);
Douglas Gregor556877c2008-04-13 21:30:24 +00002149}
2150
2151/// getAccessSpecifierIfPresent - Determine whether the next token is
2152/// a C++ access-specifier.
2153///
2154/// access-specifier: [C++ class.derived]
2155/// 'private'
2156/// 'protected'
2157/// 'public'
Mike Stump11289f42009-09-09 15:08:12 +00002158AccessSpecifier Parser::getAccessSpecifierIfPresent() const {
Douglas Gregor556877c2008-04-13 21:30:24 +00002159 switch (Tok.getKind()) {
2160 default: return AS_none;
2161 case tok::kw_private: return AS_private;
2162 case tok::kw_protected: return AS_protected;
2163 case tok::kw_public: return AS_public;
2164 }
2165}
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002166
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002167/// If the given declarator has any parts for which parsing has to be
Richard Smith0b3a4622014-11-13 20:01:57 +00002168/// delayed, e.g., default arguments or an exception-specification, create a
2169/// late-parsed method declaration record to handle the parsing at the end of
2170/// the class definition.
Douglas Gregor433e0532012-04-16 18:27:27 +00002171void Parser::HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
2172 Decl *ThisDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00002173 DeclaratorChunk::FunctionTypeInfo &FTI
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002174 = DeclaratorInfo.getFunctionTypeInfo();
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002175 // If there was a late-parsed exception-specification, we'll need a
2176 // late parse
2177 bool NeedLateParse = FTI.getExceptionSpecType() == EST_Unparsed;
Douglas Gregor433e0532012-04-16 18:27:27 +00002178
Nathan Sidwell5bb231c2015-02-19 14:03:22 +00002179 if (!NeedLateParse) {
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002180 // Look ahead to see if there are any default args
Nathan Sidwell5bb231c2015-02-19 14:03:22 +00002181 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx) {
2182 auto Param = cast<ParmVarDecl>(FTI.Params[ParamIdx].Param);
2183 if (Param->hasUnparsedDefaultArg()) {
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002184 NeedLateParse = true;
2185 break;
2186 }
Nathan Sidwell5bb231c2015-02-19 14:03:22 +00002187 }
2188 }
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002189
2190 if (NeedLateParse) {
Richard Smith0b3a4622014-11-13 20:01:57 +00002191 // Push this method onto the stack of late-parsed method
2192 // declarations.
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002193 auto LateMethod = new LateParsedMethodDeclaration(this, ThisDecl);
Richard Smith0b3a4622014-11-13 20:01:57 +00002194 getCurrentClass().LateParsedDeclarations.push_back(LateMethod);
2195 LateMethod->TemplateScope = getCurScope()->isTemplateParamScope();
2196
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002197 // Stash the exception-specification tokens in the late-pased method.
Richard Smith0b3a4622014-11-13 20:01:57 +00002198 LateMethod->ExceptionSpecTokens = FTI.ExceptionSpecTokens;
Hans Wennborgdcfba332015-10-06 23:40:43 +00002199 FTI.ExceptionSpecTokens = nullptr;
Richard Smith0b3a4622014-11-13 20:01:57 +00002200
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002201 // Push tokens for each parameter. Those that do not have
2202 // defaults will be NULL.
Richard Smith0b3a4622014-11-13 20:01:57 +00002203 LateMethod->DefaultArgs.reserve(FTI.NumParams);
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002204 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx)
Alp Tokerc5350722014-02-26 22:27:52 +00002205 LateMethod->DefaultArgs.push_back(LateParsedDefaultArgument(
Malcolm Parsonsca9d8342016-11-17 21:00:09 +00002206 FTI.Params[ParamIdx].Param,
2207 std::move(FTI.Params[ParamIdx].DefaultArgTokens)));
Eli Friedman3af2a772009-07-22 21:45:50 +00002208 }
2209}
2210
Richard Smith89645bc2013-01-02 12:01:23 +00002211/// isCXX11VirtSpecifier - Determine whether the given token is a C++11
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002212/// virt-specifier.
2213///
2214/// virt-specifier:
2215/// override
2216/// final
Andrey Bokhanko276055b2016-07-29 10:42:48 +00002217/// __final
Richard Smith89645bc2013-01-02 12:01:23 +00002218VirtSpecifiers::Specifier Parser::isCXX11VirtSpecifier(const Token &Tok) const {
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002219 if (!getLangOpts().CPlusPlus || Tok.isNot(tok::identifier))
Anders Carlsson4b63d0e2011-01-22 16:56:46 +00002220 return VirtSpecifiers::VS_None;
2221
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002222 IdentifierInfo *II = Tok.getIdentifierInfo();
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002223
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002224 // Initialize the contextual keywords.
2225 if (!Ident_final) {
2226 Ident_final = &PP.getIdentifierTable().get("final");
Andrey Bokhanko276055b2016-07-29 10:42:48 +00002227 if (getLangOpts().GNUKeywords)
2228 Ident_GNU_final = &PP.getIdentifierTable().get("__final");
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002229 if (getLangOpts().MicrosoftExt)
2230 Ident_sealed = &PP.getIdentifierTable().get("sealed");
2231 Ident_override = &PP.getIdentifierTable().get("override");
Anders Carlsson56104902011-01-17 03:05:47 +00002232 }
2233
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002234 if (II == Ident_override)
2235 return VirtSpecifiers::VS_Override;
2236
2237 if (II == Ident_sealed)
2238 return VirtSpecifiers::VS_Sealed;
2239
2240 if (II == Ident_final)
2241 return VirtSpecifiers::VS_Final;
2242
Andrey Bokhanko276055b2016-07-29 10:42:48 +00002243 if (II == Ident_GNU_final)
2244 return VirtSpecifiers::VS_GNU_Final;
2245
Anders Carlsson56104902011-01-17 03:05:47 +00002246 return VirtSpecifiers::VS_None;
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002247}
2248
Richard Smith89645bc2013-01-02 12:01:23 +00002249/// ParseOptionalCXX11VirtSpecifierSeq - Parse a virt-specifier-seq.
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002250///
2251/// virt-specifier-seq:
2252/// virt-specifier
2253/// virt-specifier-seq virt-specifier
Richard Smith89645bc2013-01-02 12:01:23 +00002254void Parser::ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS,
Richard Smith3d1a94c2014-08-12 00:22:39 +00002255 bool IsInterface,
2256 SourceLocation FriendLoc) {
Anders Carlsson56104902011-01-17 03:05:47 +00002257 while (true) {
Richard Smith89645bc2013-01-02 12:01:23 +00002258 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
Anders Carlsson56104902011-01-17 03:05:47 +00002259 if (Specifier == VirtSpecifiers::VS_None)
2260 return;
2261
Richard Smith3d1a94c2014-08-12 00:22:39 +00002262 if (FriendLoc.isValid()) {
2263 Diag(Tok.getLocation(), diag::err_friend_decl_spec)
2264 << VirtSpecifiers::getSpecifierName(Specifier)
2265 << FixItHint::CreateRemoval(Tok.getLocation())
2266 << SourceRange(FriendLoc, FriendLoc);
2267 ConsumeToken();
2268 continue;
2269 }
2270
Anders Carlsson56104902011-01-17 03:05:47 +00002271 // C++ [class.mem]p8:
2272 // A virt-specifier-seq shall contain at most one of each virt-specifier.
Craig Topper161e4db2014-05-21 06:02:52 +00002273 const char *PrevSpec = nullptr;
Anders Carlssonf2ca3892011-01-22 15:58:16 +00002274 if (VS.SetSpecifier(Specifier, Tok.getLocation(), PrevSpec))
Anders Carlsson56104902011-01-17 03:05:47 +00002275 Diag(Tok.getLocation(), diag::err_duplicate_virt_specifier)
2276 << PrevSpec
2277 << FixItHint::CreateRemoval(Tok.getLocation());
2278
David Majnemera5433082013-10-18 00:33:31 +00002279 if (IsInterface && (Specifier == VirtSpecifiers::VS_Final ||
2280 Specifier == VirtSpecifiers::VS_Sealed)) {
John McCalldb632ac2012-09-25 07:32:39 +00002281 Diag(Tok.getLocation(), diag::err_override_control_interface)
2282 << VirtSpecifiers::getSpecifierName(Specifier);
David Majnemera5433082013-10-18 00:33:31 +00002283 } else if (Specifier == VirtSpecifiers::VS_Sealed) {
2284 Diag(Tok.getLocation(), diag::ext_ms_sealed_keyword);
Andrey Bokhanko276055b2016-07-29 10:42:48 +00002285 } else if (Specifier == VirtSpecifiers::VS_GNU_Final) {
2286 Diag(Tok.getLocation(), diag::ext_warn_gnu_final);
John McCalldb632ac2012-09-25 07:32:39 +00002287 } else {
David Majnemera5433082013-10-18 00:33:31 +00002288 Diag(Tok.getLocation(),
2289 getLangOpts().CPlusPlus11
2290 ? diag::warn_cxx98_compat_override_control_keyword
2291 : diag::ext_override_control_keyword)
2292 << VirtSpecifiers::getSpecifierName(Specifier);
John McCalldb632ac2012-09-25 07:32:39 +00002293 }
Anders Carlsson56104902011-01-17 03:05:47 +00002294 ConsumeToken();
2295 }
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002296}
2297
Richard Smith89645bc2013-01-02 12:01:23 +00002298/// isCXX11FinalKeyword - Determine whether the next token is a C++11
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002299/// 'final' or Microsoft 'sealed' contextual keyword.
Richard Smith89645bc2013-01-02 12:01:23 +00002300bool Parser::isCXX11FinalKeyword() const {
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002301 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
2302 return Specifier == VirtSpecifiers::VS_Final ||
Fangrui Song6907ce22018-07-30 19:24:48 +00002303 Specifier == VirtSpecifiers::VS_GNU_Final ||
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002304 Specifier == VirtSpecifiers::VS_Sealed;
Anders Carlsson4b63d0e2011-01-22 16:56:46 +00002305}
2306
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002307/// Parse a C++ member-declarator up to, but not including, the optional
Richard Smith72553fc2014-01-23 23:53:27 +00002308/// brace-or-equal-initializer or pure-specifier.
Nico Weberd89e6f72015-01-16 19:34:13 +00002309bool Parser::ParseCXXMemberDeclaratorBeforeInitializer(
Richard Smith72553fc2014-01-23 23:53:27 +00002310 Declarator &DeclaratorInfo, VirtSpecifiers &VS, ExprResult &BitfieldSize,
2311 LateParsedAttrList &LateParsedAttrs) {
2312 // member-declarator:
2313 // declarator pure-specifier[opt]
Saar Razb65b1f32020-01-09 15:07:51 +02002314 // declarator requires-clause
Richard Smith72553fc2014-01-23 23:53:27 +00002315 // declarator brace-or-equal-initializer[opt]
2316 // identifier[opt] ':' constant-expression
Serge Pavlov458ea762014-07-16 05:16:52 +00002317 if (Tok.isNot(tok::colon))
Richard Smith72553fc2014-01-23 23:53:27 +00002318 ParseDeclarator(DeclaratorInfo);
Richard Smith3d1a94c2014-08-12 00:22:39 +00002319 else
2320 DeclaratorInfo.SetIdentifier(nullptr, Tok.getLocation());
Richard Smith72553fc2014-01-23 23:53:27 +00002321
2322 if (!DeclaratorInfo.isFunctionDeclarator() && TryConsumeToken(tok::colon)) {
Richard Smith3d1a94c2014-08-12 00:22:39 +00002323 assert(DeclaratorInfo.isPastIdentifier() &&
2324 "don't know where identifier would go yet?");
Richard Smith72553fc2014-01-23 23:53:27 +00002325 BitfieldSize = ParseConstantExpression();
2326 if (BitfieldSize.isInvalid())
2327 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
Saar Razb65b1f32020-01-09 15:07:51 +02002328 } else if (Tok.is(tok::kw_requires)) {
2329 ParseTrailingRequiresClause(DeclaratorInfo);
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002330 } else {
Richard Smith3d1a94c2014-08-12 00:22:39 +00002331 ParseOptionalCXX11VirtSpecifierSeq(
2332 VS, getCurrentClass().IsInterface,
2333 DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002334 if (!VS.isUnset())
2335 MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo, VS);
2336 }
Richard Smith72553fc2014-01-23 23:53:27 +00002337
2338 // If a simple-asm-expr is present, parse it.
2339 if (Tok.is(tok::kw_asm)) {
2340 SourceLocation Loc;
Aaron Ballman55a51e12020-01-08 08:38:02 -05002341 ExprResult AsmLabel(ParseSimpleAsm(/*ForAsmLabel*/ true, &Loc));
Richard Smith72553fc2014-01-23 23:53:27 +00002342 if (AsmLabel.isInvalid())
2343 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2344
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002345 DeclaratorInfo.setAsmLabel(AsmLabel.get());
Richard Smith72553fc2014-01-23 23:53:27 +00002346 DeclaratorInfo.SetRangeEnd(Loc);
2347 }
2348
2349 // If attributes exist after the declarator, but before an '{', parse them.
2350 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
Richard Smith4b5a9492014-01-24 22:34:35 +00002351
2352 // For compatibility with code written to older Clang, also accept a
2353 // virt-specifier *after* the GNU attributes.
Aaron Ballman5d153e32014-08-04 17:03:51 +00002354 if (BitfieldSize.isUnset() && VS.isUnset()) {
Richard Smith3d1a94c2014-08-12 00:22:39 +00002355 ParseOptionalCXX11VirtSpecifierSeq(
2356 VS, getCurrentClass().IsInterface,
2357 DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
Aaron Ballman5d153e32014-08-04 17:03:51 +00002358 if (!VS.isUnset()) {
2359 // If we saw any GNU-style attributes that are known to GCC followed by a
2360 // virt-specifier, issue a GCC-compat warning.
Erich Keanee891aa92018-07-13 15:07:47 +00002361 for (const ParsedAttr &AL : DeclaratorInfo.getAttributes())
Erich Keanec480f302018-07-12 21:09:05 +00002362 if (AL.isKnownToGCC() && !AL.isCXX11Attribute())
2363 Diag(AL.getLoc(), diag::warn_gcc_attribute_location);
2364
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002365 MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo, VS);
Aaron Ballman5d153e32014-08-04 17:03:51 +00002366 }
2367 }
Nico Weberd89e6f72015-01-16 19:34:13 +00002368
2369 // If this has neither a name nor a bit width, something has gone seriously
2370 // wrong. Skip until the semi-colon or }.
2371 if (!DeclaratorInfo.hasName() && BitfieldSize.isUnset()) {
2372 // If so, skip until the semi-colon or a }.
2373 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2374 return true;
2375 }
2376 return false;
Richard Smith72553fc2014-01-23 23:53:27 +00002377}
2378
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002379/// Look for declaration specifiers possibly occurring after C++11
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002380/// virt-specifier-seq and diagnose them.
2381void Parser::MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(
2382 Declarator &D,
2383 VirtSpecifiers &VS) {
2384 DeclSpec DS(AttrFactory);
2385
2386 // GNU-style and C++11 attributes are not allowed here, but they will be
2387 // handled by the caller. Diagnose everything else.
Alex Lorenz8f4d3992017-02-13 23:19:40 +00002388 ParseTypeQualifierListOpt(
2389 DS, AR_NoAttributesParsed, false,
2390 /*IdentifierRequired=*/false, llvm::function_ref<void()>([&]() {
2391 Actions.CodeCompleteFunctionQualifiers(DS, D, &VS);
2392 }));
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002393 D.ExtendWithDeclSpec(DS);
2394
2395 if (D.isFunctionDeclarator()) {
Ehsan Akhgaric07d1e22015-03-25 00:53:33 +00002396 auto &Function = D.getFunctionTypeInfo();
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002397 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
Anastasia Stulovaa9bc4bd2019-01-09 11:25:09 +00002398 auto DeclSpecCheck = [&](DeclSpec::TQ TypeQual, StringRef FixItName,
2399 SourceLocation SpecLoc) {
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002400 FixItHint Insertion;
Anastasia Stulovaa9bc4bd2019-01-09 11:25:09 +00002401 auto &MQ = Function.getOrCreateMethodQualifiers();
2402 if (!(MQ.getTypeQualifiers() & TypeQual)) {
2403 std::string Name(FixItName.data());
2404 Name += " ";
2405 Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), Name);
2406 MQ.SetTypeQual(TypeQual, SpecLoc);
2407 }
2408 Diag(SpecLoc, diag::err_declspec_after_virtspec)
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002409 << FixItName
2410 << VirtSpecifiers::getSpecifierName(VS.getLastSpecifier())
Anastasia Stulovaa9bc4bd2019-01-09 11:25:09 +00002411 << FixItHint::CreateRemoval(SpecLoc) << Insertion;
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002412 };
Anastasia Stulovaa9bc4bd2019-01-09 11:25:09 +00002413 DS.forEachQualifier(DeclSpecCheck);
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002414 }
Ehsan Akhgaric07d1e22015-03-25 00:53:33 +00002415
2416 // Parse ref-qualifiers.
2417 bool RefQualifierIsLValueRef = true;
2418 SourceLocation RefQualifierLoc;
2419 if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc)) {
2420 const char *Name = (RefQualifierIsLValueRef ? "& " : "&& ");
2421 FixItHint Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), Name);
2422 Function.RefQualifierIsLValueRef = RefQualifierIsLValueRef;
2423 Function.RefQualifierLoc = RefQualifierLoc.getRawEncoding();
2424
2425 Diag(RefQualifierLoc, diag::err_declspec_after_virtspec)
2426 << (RefQualifierIsLValueRef ? "&" : "&&")
2427 << VirtSpecifiers::getSpecifierName(VS.getLastSpecifier())
2428 << FixItHint::CreateRemoval(RefQualifierLoc)
2429 << Insertion;
2430 D.SetRangeEnd(RefQualifierLoc);
2431 }
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002432 }
2433}
2434
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002435/// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration.
2436///
2437/// member-declaration:
2438/// decl-specifier-seq[opt] member-declarator-list[opt] ';'
2439/// function-definition ';'[opt]
2440/// ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO]
2441/// using-declaration [TODO]
Anders Carlssonf24fcff62009-03-11 16:27:10 +00002442/// [C++0x] static_assert-declaration
Anders Carlssondfbbdf62009-03-26 00:52:18 +00002443/// template-declaration
Chris Lattnerd19c1c02008-12-18 01:12:00 +00002444/// [GNU] '__extension__' member-declaration
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002445///
2446/// member-declarator-list:
2447/// member-declarator
2448/// member-declarator-list ',' member-declarator
2449///
2450/// member-declarator:
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002451/// declarator virt-specifier-seq[opt] pure-specifier[opt]
Saar Razb65b1f32020-01-09 15:07:51 +02002452/// [C++2a] declarator requires-clause
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002453/// declarator constant-initializer[opt]
Richard Smith938f40b2011-06-11 17:19:42 +00002454/// [C++11] declarator brace-or-equal-initializer[opt]
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002455/// identifier[opt] ':' constant-expression
2456///
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002457/// virt-specifier-seq:
2458/// virt-specifier
2459/// virt-specifier-seq virt-specifier
2460///
2461/// virt-specifier:
2462/// override
2463/// final
David Majnemera5433082013-10-18 00:33:31 +00002464/// [MS] sealed
Fangrui Song6907ce22018-07-30 19:24:48 +00002465///
Sebastian Redl42e92c42009-04-12 17:16:29 +00002466/// pure-specifier:
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002467/// '= 0'
2468///
2469/// constant-initializer:
2470/// '=' constant-expression
2471///
Alexey Bataev05c25d62015-07-31 08:42:25 +00002472Parser::DeclGroupPtrTy
2473Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS,
Erich Keanec480f302018-07-12 21:09:05 +00002474 ParsedAttributes &AccessAttrs,
John McCall796c2a52010-07-16 08:13:16 +00002475 const ParsedTemplateInfo &TemplateInfo,
2476 ParsingDeclRAIIObject *TemplateDiags) {
Douglas Gregor23c84762011-04-14 17:21:19 +00002477 if (Tok.is(tok::at)) {
Erik Pilkingtonfa983902018-10-30 20:31:30 +00002478 if (getLangOpts().ObjC && NextToken().isObjCAtKeyword(tok::objc_defs))
Douglas Gregor23c84762011-04-14 17:21:19 +00002479 Diag(Tok, diag::err_at_defs_cxx);
2480 else
2481 Diag(Tok, diag::err_at_in_class);
Richard Smithda35e962013-11-09 04:52:51 +00002482
Douglas Gregor23c84762011-04-14 17:21:19 +00002483 ConsumeToken();
Alexey Bataevee6507d2013-11-18 08:17:37 +00002484 SkipUntil(tok::r_brace, StopAtSemi);
David Blaikie0403cb12016-01-15 23:43:25 +00002485 return nullptr;
Douglas Gregor23c84762011-04-14 17:21:19 +00002486 }
Richard Smithda35e962013-11-09 04:52:51 +00002487
Serge Pavlov458ea762014-07-16 05:16:52 +00002488 // Turn on colon protection early, while parsing declspec, although there is
2489 // nothing to protect there. It prevents from false errors if error recovery
2490 // incorrectly determines where the declspec ends, as in the example:
2491 // struct A { enum class B { C }; };
2492 // const int C = 4;
2493 // struct D { A::B : C; };
2494 ColonProtectionRAIIObject X(*this);
2495
John McCalla0097262009-12-11 02:10:03 +00002496 // Access declarations.
Richard Smith45855df2012-05-09 08:23:23 +00002497 bool MalformedTypeSpec = false;
John McCalla0097262009-12-11 02:10:03 +00002498 if (!TemplateInfo.Kind &&
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002499 Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw___super)) {
Richard Smith45855df2012-05-09 08:23:23 +00002500 if (TryAnnotateCXXScopeToken())
2501 MalformedTypeSpec = true;
2502
2503 bool isAccessDecl;
2504 if (Tok.isNot(tok::annot_cxxscope))
2505 isAccessDecl = false;
2506 else if (NextToken().is(tok::identifier))
John McCalla0097262009-12-11 02:10:03 +00002507 isAccessDecl = GetLookAheadToken(2).is(tok::semi);
2508 else
2509 isAccessDecl = NextToken().is(tok::kw_operator);
2510
2511 if (isAccessDecl) {
2512 // Collect the scope specifier token we annotated earlier.
2513 CXXScopeSpec SS;
Haojian Wu0dd0b102020-03-19 09:12:29 +01002514 ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
2515 /*ObjectHadErrors=*/false,
Douglas Gregordf593fb2011-11-07 17:33:42 +00002516 /*EnteringContext=*/false);
John McCalla0097262009-12-11 02:10:03 +00002517
Nico Weberef03e702014-09-10 00:59:37 +00002518 if (SS.isInvalid()) {
2519 SkipUntil(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002520 return nullptr;
Nico Weberef03e702014-09-10 00:59:37 +00002521 }
2522
John McCalla0097262009-12-11 02:10:03 +00002523 // Try to parse an unqualified-id.
Abramo Bagnara7945c982012-01-27 09:46:47 +00002524 SourceLocation TemplateKWLoc;
John McCalla0097262009-12-11 02:10:03 +00002525 UnqualifiedId Name;
Haojian Wu0dd0b102020-03-19 09:12:29 +01002526 if (ParseUnqualifiedId(SS, /*ObjectType=*/nullptr,
2527 /*ObjectHadErrors=*/false, false, true, true,
2528 false, &TemplateKWLoc, Name)) {
John McCalla0097262009-12-11 02:10:03 +00002529 SkipUntil(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002530 return nullptr;
John McCalla0097262009-12-11 02:10:03 +00002531 }
2532
2533 // TODO: recover from mistakenly-qualified operator declarations.
Alp Toker383d2c42014-01-01 03:08:43 +00002534 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
2535 "access declaration")) {
2536 SkipUntil(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002537 return nullptr;
Alp Toker383d2c42014-01-01 03:08:43 +00002538 }
John McCalla0097262009-12-11 02:10:03 +00002539
Richard Smithc08b6932018-04-27 02:00:13 +00002540 // FIXME: We should do something with the 'template' keyword here.
Alexey Bataev05c25d62015-07-31 08:42:25 +00002541 return DeclGroupPtrTy::make(DeclGroupRef(Actions.ActOnUsingDeclaration(
Richard Smith151c4562016-12-20 21:35:28 +00002542 getCurScope(), AS, /*UsingLoc*/ SourceLocation(),
2543 /*TypenameLoc*/ SourceLocation(), SS, Name,
Erich Keanec480f302018-07-12 21:09:05 +00002544 /*EllipsisLoc*/ SourceLocation(),
2545 /*AttrList*/ ParsedAttributesView())));
John McCalla0097262009-12-11 02:10:03 +00002546 }
2547 }
2548
Aaron Ballmane7c544d2014-08-04 20:28:35 +00002549 // static_assert-declaration. A templated static_assert declaration is
2550 // diagnosed in Parser::ParseSingleDeclarationAfterTemplate.
2551 if (!TemplateInfo.Kind &&
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002552 Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert)) {
Chris Lattner49836b42009-04-02 04:16:50 +00002553 SourceLocation DeclEnd;
Alexey Bataev05c25d62015-07-31 08:42:25 +00002554 return DeclGroupPtrTy::make(
2555 DeclGroupRef(ParseStaticAssertDeclaration(DeclEnd)));
Chris Lattner5bbb3c82009-03-29 16:50:03 +00002556 }
Mike Stump11289f42009-09-09 15:08:12 +00002557
Chris Lattner5bbb3c82009-03-29 16:50:03 +00002558 if (Tok.is(tok::kw_template)) {
Mike Stump11289f42009-09-09 15:08:12 +00002559 assert(!TemplateInfo.TemplateParams &&
Douglas Gregor3447e762009-08-20 22:52:58 +00002560 "Nested template improperly parsed?");
Richard Smith3af70092017-02-09 22:14:25 +00002561 ObjCDeclContextSwitch ObjCDC(*this);
Chris Lattner49836b42009-04-02 04:16:50 +00002562 SourceLocation DeclEnd;
Alexey Bataev05c25d62015-07-31 08:42:25 +00002563 return DeclGroupPtrTy::make(
Richard Smith3af70092017-02-09 22:14:25 +00002564 DeclGroupRef(ParseTemplateDeclarationOrSpecialization(
Erich Keanec480f302018-07-12 21:09:05 +00002565 DeclaratorContext::MemberContext, DeclEnd, AccessAttrs, AS)));
Chris Lattner5bbb3c82009-03-29 16:50:03 +00002566 }
Anders Carlssondfbbdf62009-03-26 00:52:18 +00002567
Chris Lattnerd19c1c02008-12-18 01:12:00 +00002568 // Handle: member-declaration ::= '__extension__' member-declaration
2569 if (Tok.is(tok::kw___extension__)) {
2570 // __extension__ silences extension warnings in the subexpression.
2571 ExtensionRAIIObject O(Diags); // Use RAII to do this.
2572 ConsumeToken();
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00002573 return ParseCXXClassMemberDeclaration(AS, AccessAttrs,
2574 TemplateInfo, TemplateDiags);
Chris Lattnerd19c1c02008-12-18 01:12:00 +00002575 }
Douglas Gregorfec52632009-06-20 00:51:54 +00002576
John McCall084e83d2011-03-24 11:26:52 +00002577 ParsedAttributesWithRange attrs(AttrFactory);
Erich Keanec480f302018-07-12 21:09:05 +00002578 ParsedAttributesViewWithRange FnAttrs;
Richard Smith89645bc2013-01-02 12:01:23 +00002579 // Optional C++11 attribute-specifier
2580 MaybeParseCXX11Attributes(attrs);
Michael Handdc016d2012-11-28 23:17:40 +00002581 // We need to keep these attributes for future diagnostic
2582 // before they are taken over by declaration specifier.
Erich Keanec480f302018-07-12 21:09:05 +00002583 FnAttrs.addAll(attrs.begin(), attrs.end());
Michael Handdc016d2012-11-28 23:17:40 +00002584 FnAttrs.Range = attrs.Range;
2585
John McCall53fa7142010-12-24 02:08:15 +00002586 MaybeParseMicrosoftAttributes(attrs);
Alexis Hunt96d5c762009-11-21 08:43:09 +00002587
Douglas Gregorfec52632009-06-20 00:51:54 +00002588 if (Tok.is(tok::kw_using)) {
John McCall53fa7142010-12-24 02:08:15 +00002589 ProhibitAttributes(attrs);
Mike Stump11289f42009-09-09 15:08:12 +00002590
Douglas Gregorfec52632009-06-20 00:51:54 +00002591 // Eat 'using'.
2592 SourceLocation UsingLoc = ConsumeToken();
2593
Richard Trieu2efd3052019-05-01 23:33:49 +00002594 // Consume unexpected 'template' keywords.
2595 while (Tok.is(tok::kw_template)) {
2596 SourceLocation TemplateLoc = ConsumeToken();
2597 Diag(TemplateLoc, diag::err_unexpected_template_after_using)
2598 << FixItHint::CreateRemoval(TemplateLoc);
2599 }
2600
Douglas Gregorfec52632009-06-20 00:51:54 +00002601 if (Tok.is(tok::kw_namespace)) {
2602 Diag(UsingLoc, diag::err_using_namespace_in_class);
Alexey Bataevee6507d2013-11-18 08:17:37 +00002603 SkipUntil(tok::semi, StopBeforeMatch);
David Blaikie0403cb12016-01-15 23:43:25 +00002604 return nullptr;
Douglas Gregorfec52632009-06-20 00:51:54 +00002605 }
Alexey Bataev05c25d62015-07-31 08:42:25 +00002606 SourceLocation DeclEnd;
2607 // Otherwise, it must be a using-declaration or an alias-declaration.
Faisal Vali421b2d12017-12-29 05:41:00 +00002608 return ParseUsingDeclaration(DeclaratorContext::MemberContext, TemplateInfo,
Richard Smith6f1daa42016-12-16 00:58:48 +00002609 UsingLoc, DeclEnd, AS);
Douglas Gregorfec52632009-06-20 00:51:54 +00002610 }
2611
DeLesley Hutchinsbd2ee132012-03-02 22:12:59 +00002612 // Hold late-parsed attributes so we can attach a Decl to them later.
2613 LateParsedAttrList CommonLateParsedAttrs;
2614
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002615 // decl-specifier-seq:
2616 // Parse the common declaration-specifiers piece.
John McCall796c2a52010-07-16 08:13:16 +00002617 ParsingDeclSpec DS(*this, TemplateDiags);
John McCall53fa7142010-12-24 02:08:15 +00002618 DS.takeAttributesFrom(attrs);
Richard Smith45855df2012-05-09 08:23:23 +00002619 if (MalformedTypeSpec)
2620 DS.SetTypeSpecError();
Richard Smith72553fc2014-01-23 23:53:27 +00002621
Faisal Valia534f072018-04-26 00:42:40 +00002622 ParseDeclarationSpecifiers(DS, TemplateInfo, AS, DeclSpecContext::DSC_class,
2623 &CommonLateParsedAttrs);
Serge Pavlov458ea762014-07-16 05:16:52 +00002624
2625 // Turn off colon protection that was set for declspec.
2626 X.restore();
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002627
Richard Smith404dfb42013-11-19 22:47:36 +00002628 // If we had a free-standing type definition with a missing semicolon, we
2629 // may get this far before the problem becomes obvious.
2630 if (DS.hasTagDefinition() &&
2631 TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate &&
Faisal Vali7db85c52017-12-31 00:06:40 +00002632 DiagnoseMissingSemiAfterTagDefinition(DS, AS, DeclSpecContext::DSC_class,
Richard Smith404dfb42013-11-19 22:47:36 +00002633 &CommonLateParsedAttrs))
David Blaikie0403cb12016-01-15 23:43:25 +00002634 return nullptr;
Richard Smith404dfb42013-11-19 22:47:36 +00002635
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002636 MultiTemplateParamsArg TemplateParams(
Craig Topper161e4db2014-05-21 06:02:52 +00002637 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->data()
2638 : nullptr,
John McCall11083da2009-09-16 22:47:08 +00002639 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->size() : 0);
2640
Alp Toker35d87032013-12-30 23:29:50 +00002641 if (TryConsumeToken(tok::semi)) {
Michael Handdc016d2012-11-28 23:17:40 +00002642 if (DS.isFriendSpecified())
2643 ProhibitAttributes(FnAttrs);
2644
Nico Weber7b837f52016-01-28 19:25:00 +00002645 RecordDecl *AnonRecord = nullptr;
2646 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(
2647 getCurScope(), AS, DS, TemplateParams, false, AnonRecord);
John McCall796c2a52010-07-16 08:13:16 +00002648 DS.complete(TheDecl);
Nico Weber7b837f52016-01-28 19:25:00 +00002649 if (AnonRecord) {
2650 Decl* decls[] = {AnonRecord, TheDecl};
Richard Smith3beb7c62017-01-12 02:27:38 +00002651 return Actions.BuildDeclaratorGroup(decls);
Nico Weber7b837f52016-01-28 19:25:00 +00002652 }
2653 return Actions.ConvertDeclToDeclGroup(TheDecl);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002654 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002655
Faisal Vali421b2d12017-12-29 05:41:00 +00002656 ParsingDeclarator DeclaratorInfo(*this, DS, DeclaratorContext::MemberContext);
Saar Razb481f022020-01-22 02:03:05 +02002657 if (TemplateInfo.TemplateParams)
2658 DeclaratorInfo.setTemplateParameterLists(TemplateParams);
Nico Weber24b2a822011-01-28 06:07:34 +00002659 VirtSpecifiers VS;
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002660
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002661 // Hold late-parsed attributes so we can attach a Decl to them later.
2662 LateParsedAttrList LateParsedAttrs;
2663
Douglas Gregor50cefbf2011-10-17 17:09:53 +00002664 SourceLocation EqualLoc;
Richard Smith9ba0fec2015-06-30 01:28:56 +00002665 SourceLocation PureSpecLoc;
2666
Yaron Keren180c1672015-06-30 07:35:19 +00002667 auto TryConsumePureSpecifier = [&] (bool AllowDefinition) {
Richard Smith9ba0fec2015-06-30 01:28:56 +00002668 if (Tok.isNot(tok::equal))
2669 return false;
2670
2671 auto &Zero = NextToken();
2672 SmallString<8> Buffer;
Richard Smithced76172020-03-20 18:44:13 -07002673 if (Zero.isNot(tok::numeric_constant) ||
Richard Smith9ba0fec2015-06-30 01:28:56 +00002674 PP.getSpelling(Zero, Buffer) != "0")
2675 return false;
2676
2677 auto &After = GetLookAheadToken(2);
2678 if (!After.isOneOf(tok::semi, tok::comma) &&
2679 !(AllowDefinition &&
2680 After.isOneOf(tok::l_brace, tok::colon, tok::kw_try)))
2681 return false;
2682
2683 EqualLoc = ConsumeToken();
2684 PureSpecLoc = ConsumeToken();
2685 return true;
2686 };
Chris Lattner17c3b1f2009-12-10 01:59:24 +00002687
Richard Smith72553fc2014-01-23 23:53:27 +00002688 SmallVector<Decl *, 8> DeclsInGroup;
2689 ExprResult BitfieldSize;
Saar Razb65b1f32020-01-09 15:07:51 +02002690 ExprResult TrailingRequiresClause;
Richard Smith72553fc2014-01-23 23:53:27 +00002691 bool ExpectSemi = true;
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002692
Richard Smith72553fc2014-01-23 23:53:27 +00002693 // Parse the first declarator.
Nico Weberd89e6f72015-01-16 19:34:13 +00002694 if (ParseCXXMemberDeclaratorBeforeInitializer(
2695 DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs)) {
Richard Smith72553fc2014-01-23 23:53:27 +00002696 TryConsumeToken(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002697 return nullptr;
Richard Smith72553fc2014-01-23 23:53:27 +00002698 }
John Thompson5bc5cbe2009-11-25 22:58:06 +00002699
Richard Smith72553fc2014-01-23 23:53:27 +00002700 // Check for a member function definition.
Richard Smith4b5a9492014-01-24 22:34:35 +00002701 if (BitfieldSize.isUnset()) {
Richard Smith72553fc2014-01-23 23:53:27 +00002702 // MSVC permits pure specifier on inline functions defined at class scope.
Francois Pichet3abc9b82011-05-11 02:14:46 +00002703 // Hence check for =0 before checking for function definition.
Richard Smith9ba0fec2015-06-30 01:28:56 +00002704 if (getLangOpts().MicrosoftExt && DeclaratorInfo.isDeclarationOfFunction())
2705 TryConsumePureSpecifier(/*AllowDefinition*/ true);
Francois Pichet3abc9b82011-05-11 02:14:46 +00002706
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00002707 FunctionDefinitionKind DefinitionKind = FDK_Declaration;
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002708 // function-definition:
Richard Smith938f40b2011-06-11 17:19:42 +00002709 //
2710 // In C++11, a non-function declarator followed by an open brace is a
2711 // braced-init-list for an in-class member initialization, not an
2712 // erroneous function definition.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002713 if (Tok.is(tok::l_brace) && !getLangOpts().CPlusPlus11) {
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00002714 DefinitionKind = FDK_Definition;
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002715 } else if (DeclaratorInfo.isFunctionDeclarator()) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002716 if (Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try)) {
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00002717 DefinitionKind = FDK_Definition;
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002718 } else if (Tok.is(tok::equal)) {
2719 const Token &KW = NextToken();
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00002720 if (KW.is(tok::kw_default))
2721 DefinitionKind = FDK_Defaulted;
2722 else if (KW.is(tok::kw_delete))
2723 DefinitionKind = FDK_Deleted;
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002724 }
2725 }
Eli Bendersky41842222015-03-23 23:49:41 +00002726 DeclaratorInfo.setFunctionDefinitionKind(DefinitionKind);
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002727
Fangrui Song6907ce22018-07-30 19:24:48 +00002728 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
Michael Handdc016d2012-11-28 23:17:40 +00002729 // to a friend declaration, that declaration shall be a definition.
Fangrui Song6907ce22018-07-30 19:24:48 +00002730 if (DeclaratorInfo.isFunctionDeclarator() &&
Richard Smith5ae65542020-01-30 17:42:17 -08002731 DefinitionKind == FDK_Declaration && DS.isFriendSpecified()) {
Michael Handdc016d2012-11-28 23:17:40 +00002732 // Diagnose attributes that appear before decl specifier:
2733 // [[]] friend int foo();
2734 ProhibitAttributes(FnAttrs);
2735 }
2736
Nico Webera7f137d2015-01-16 19:35:01 +00002737 if (DefinitionKind != FDK_Declaration) {
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002738 if (!DeclaratorInfo.isFunctionDeclarator()) {
Richard Trieu0d730542012-01-21 02:59:18 +00002739 Diag(DeclaratorInfo.getIdentifierLoc(), diag::err_func_def_no_params);
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002740 ConsumeBrace();
Alexey Bataevee6507d2013-11-18 08:17:37 +00002741 SkipUntil(tok::r_brace);
Michael Handdc016d2012-11-28 23:17:40 +00002742
Douglas Gregor8a4db832011-01-19 16:41:58 +00002743 // Consume the optional ';'
Alp Toker35d87032013-12-30 23:29:50 +00002744 TryConsumeToken(tok::semi);
2745
David Blaikie0403cb12016-01-15 23:43:25 +00002746 return nullptr;
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002747 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002748
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002749 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
Richard Trieu0d730542012-01-21 02:59:18 +00002750 Diag(DeclaratorInfo.getIdentifierLoc(),
2751 diag::err_function_declared_typedef);
Douglas Gregor8a4db832011-01-19 16:41:58 +00002752
Richard Smith2603b092012-11-15 22:54:20 +00002753 // Recover by treating the 'typedef' as spurious.
2754 DS.ClearStorageClassSpecs();
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002755 }
2756
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002757 Decl *FunDecl =
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00002758 ParseCXXInlineMethodDef(AS, AccessAttrs, DeclaratorInfo, TemplateInfo,
Richard Smith9ba0fec2015-06-30 01:28:56 +00002759 VS, PureSpecLoc);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002760
David Majnemer23252a32013-08-01 04:22:55 +00002761 if (FunDecl) {
2762 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i) {
2763 CommonLateParsedAttrs[i]->addDecl(FunDecl);
2764 }
2765 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i) {
2766 LateParsedAttrs[i]->addDecl(FunDecl);
2767 }
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002768 }
2769 LateParsedAttrs.clear();
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002770
2771 // Consume the ';' - it's optional unless we have a delete or default
Richard Trieu2f7dc462012-05-16 19:04:59 +00002772 if (Tok.is(tok::semi))
Richard Smith87f5dc52012-07-23 05:45:25 +00002773 ConsumeExtraSemi(AfterMemberFunctionDefinition);
Douglas Gregor8a4db832011-01-19 16:41:58 +00002774
Alexey Bataev05c25d62015-07-31 08:42:25 +00002775 return DeclGroupPtrTy::make(DeclGroupRef(FunDecl));
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002776 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002777 }
2778
2779 // member-declarator-list:
2780 // member-declarator
2781 // member-declarator-list ',' member-declarator
2782
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002783 while (1) {
Richard Smith2b013182012-06-10 03:12:00 +00002784 InClassInitStyle HasInClassInit = ICIS_NoInit;
Richard Smith9ba0fec2015-06-30 01:28:56 +00002785 bool HasStaticInitializer = false;
2786 if (Tok.isOneOf(tok::equal, tok::l_brace) && PureSpecLoc.isInvalid()) {
Richard Smith6b8e3c02017-08-28 00:28:14 +00002787 if (DeclaratorInfo.isDeclarationOfFunction()) {
Richard Smith9ba0fec2015-06-30 01:28:56 +00002788 // It's a pure-specifier.
2789 if (!TryConsumePureSpecifier(/*AllowFunctionDefinition*/ false))
2790 // Parse it as an expression so that Sema can diagnose it.
2791 HasStaticInitializer = true;
2792 } else if (DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2793 DeclSpec::SCS_static &&
2794 DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2795 DeclSpec::SCS_typedef &&
2796 !DS.isFriendSpecified()) {
2797 // It's a default member initializer.
Richard Smith6b8e3c02017-08-28 00:28:14 +00002798 if (BitfieldSize.get())
2799 Diag(Tok, getLangOpts().CPlusPlus2a
2800 ? diag::warn_cxx17_compat_bitfield_member_init
2801 : diag::ext_bitfield_member_init);
Richard Smith9ba0fec2015-06-30 01:28:56 +00002802 HasInClassInit = Tok.is(tok::equal) ? ICIS_CopyInit : ICIS_ListInit;
Richard Smith938f40b2011-06-11 17:19:42 +00002803 } else {
Richard Smith9ba0fec2015-06-30 01:28:56 +00002804 HasStaticInitializer = true;
Richard Smith938f40b2011-06-11 17:19:42 +00002805 }
2806 }
2807
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002808 // NOTE: If Sema is the Action module and declarator is an instance field,
Chris Lattner5bbb3c82009-03-29 16:50:03 +00002809 // this call will *not* return the created decl; It will return null.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002810 // See Sema::ActOnCXXMemberDeclarator for details.
John McCall07e91c02009-08-06 02:15:43 +00002811
Craig Topper161e4db2014-05-21 06:02:52 +00002812 NamedDecl *ThisDecl = nullptr;
John McCall07e91c02009-08-06 02:15:43 +00002813 if (DS.isFriendSpecified()) {
Richard Smith72553fc2014-01-23 23:53:27 +00002814 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
Michael Handdc016d2012-11-28 23:17:40 +00002815 // to a friend declaration, that declaration shall be a definition.
2816 //
Richard Smith72553fc2014-01-23 23:53:27 +00002817 // Diagnose attributes that appear in a friend member function declarator:
2818 // friend int foo [[]] ();
Michael Handdc016d2012-11-28 23:17:40 +00002819 SmallVector<SourceRange, 4> Ranges;
2820 DeclaratorInfo.getCXX11AttributeRanges(Ranges);
Richard Smith72553fc2014-01-23 23:53:27 +00002821 for (SmallVectorImpl<SourceRange>::iterator I = Ranges.begin(),
2822 E = Ranges.end(); I != E; ++I)
2823 Diag((*I).getBegin(), diag::err_attributes_not_allowed) << *I;
Michael Handdc016d2012-11-28 23:17:40 +00002824
Douglas Gregor0be31a22010-07-02 17:43:08 +00002825 ThisDecl = Actions.ActOnFriendFunctionDecl(getCurScope(), DeclaratorInfo,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002826 TemplateParams);
Douglas Gregor3447e762009-08-20 22:52:58 +00002827 } else {
Douglas Gregor0be31a22010-07-02 17:43:08 +00002828 ThisDecl = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS,
John McCall07e91c02009-08-06 02:15:43 +00002829 DeclaratorInfo,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002830 TemplateParams,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002831 BitfieldSize.get(),
Richard Smith2b013182012-06-10 03:12:00 +00002832 VS, HasInClassInit);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002833
2834 if (VarTemplateDecl *VT =
Craig Topper161e4db2014-05-21 06:02:52 +00002835 ThisDecl ? dyn_cast<VarTemplateDecl>(ThisDecl) : nullptr)
Larisse Voufo39a1e502013-08-06 01:03:05 +00002836 // Re-direct this decl to refer to the templated decl so that we can
2837 // initialize it.
2838 ThisDecl = VT->getTemplatedDecl();
2839
Erich Keanec480f302018-07-12 21:09:05 +00002840 if (ThisDecl)
Richard Smithf8a75c32013-08-29 00:47:48 +00002841 Actions.ProcessDeclAttributeList(getCurScope(), ThisDecl, AccessAttrs);
Douglas Gregor3447e762009-08-20 22:52:58 +00002842 }
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002843
Richard Smith9ba0fec2015-06-30 01:28:56 +00002844 // Error recovery might have converted a non-static member into a static
2845 // member.
David Blaikie35506f82013-01-30 01:22:18 +00002846 if (HasInClassInit != ICIS_NoInit &&
Richard Smith9ba0fec2015-06-30 01:28:56 +00002847 DeclaratorInfo.getDeclSpec().getStorageClassSpec() ==
2848 DeclSpec::SCS_static) {
2849 HasInClassInit = ICIS_NoInit;
2850 HasStaticInitializer = true;
2851 }
2852
2853 if (ThisDecl && PureSpecLoc.isValid())
2854 Actions.ActOnPureSpecifier(ThisDecl, PureSpecLoc);
2855
2856 // Handle the initializer.
2857 if (HasInClassInit != ICIS_NoInit) {
Douglas Gregor728d00b2011-10-10 14:49:18 +00002858 // The initializer was deferred; parse it and cache the tokens.
David Majnemer23252a32013-08-01 04:22:55 +00002859 Diag(Tok, getLangOpts().CPlusPlus11
2860 ? diag::warn_cxx98_compat_nonstatic_member_init
2861 : diag::ext_nonstatic_member_init);
Richard Smith5d164bc2011-10-15 05:09:34 +00002862
Richard Smith938f40b2011-06-11 17:19:42 +00002863 if (DeclaratorInfo.isArrayOfUnknownBound()) {
Richard Smith2b013182012-06-10 03:12:00 +00002864 // C++11 [dcl.array]p3: An array bound may also be omitted when the
2865 // declarator is followed by an initializer.
Richard Smith938f40b2011-06-11 17:19:42 +00002866 //
2867 // A brace-or-equal-initializer for a member-declarator is not an
David Blaikiecdd91db2012-02-14 09:00:46 +00002868 // initializer in the grammar, so this is ill-formed.
Richard Smith938f40b2011-06-11 17:19:42 +00002869 Diag(Tok, diag::err_incomplete_array_member_init);
Alexey Bataevee6507d2013-11-18 08:17:37 +00002870 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
David Majnemer23252a32013-08-01 04:22:55 +00002871
2872 // Avoid later warnings about a class member of incomplete type.
David Blaikiecdd91db2012-02-14 09:00:46 +00002873 if (ThisDecl)
David Blaikiecdd91db2012-02-14 09:00:46 +00002874 ThisDecl->setInvalidDecl();
Richard Smith938f40b2011-06-11 17:19:42 +00002875 } else
2876 ParseCXXNonStaticMemberInitializer(ThisDecl);
Richard Smith9ba0fec2015-06-30 01:28:56 +00002877 } else if (HasStaticInitializer) {
Douglas Gregor728d00b2011-10-10 14:49:18 +00002878 // Normal initializer.
Richard Smith9ba0fec2015-06-30 01:28:56 +00002879 ExprResult Init = ParseCXXMemberInitializer(
2880 ThisDecl, DeclaratorInfo.isDeclarationOfFunction(), EqualLoc);
David Majnemer23252a32013-08-01 04:22:55 +00002881
Douglas Gregor728d00b2011-10-10 14:49:18 +00002882 if (Init.isInvalid())
Alexey Bataevee6507d2013-11-18 08:17:37 +00002883 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
Douglas Gregor728d00b2011-10-10 14:49:18 +00002884 else if (ThisDecl)
Richard Smith3beb7c62017-01-12 02:27:38 +00002885 Actions.AddInitializerToDecl(ThisDecl, Init.get(), EqualLoc.isInvalid());
David Majnemer23252a32013-08-01 04:22:55 +00002886 } else if (ThisDecl && DS.getStorageClassSpec() == DeclSpec::SCS_static)
Douglas Gregor728d00b2011-10-10 14:49:18 +00002887 // No initializer.
Richard Smith3beb7c62017-01-12 02:27:38 +00002888 Actions.ActOnUninitializedDecl(ThisDecl);
David Majnemer23252a32013-08-01 04:22:55 +00002889
Douglas Gregor728d00b2011-10-10 14:49:18 +00002890 if (ThisDecl) {
David Majnemer23252a32013-08-01 04:22:55 +00002891 if (!ThisDecl->isInvalidDecl()) {
2892 // Set the Decl for any late parsed attributes
2893 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i)
2894 CommonLateParsedAttrs[i]->addDecl(ThisDecl);
2895
2896 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i)
2897 LateParsedAttrs[i]->addDecl(ThisDecl);
2898 }
Douglas Gregor728d00b2011-10-10 14:49:18 +00002899 Actions.FinalizeDeclaration(ThisDecl);
2900 DeclsInGroup.push_back(ThisDecl);
David Majnemer23252a32013-08-01 04:22:55 +00002901
2902 if (DeclaratorInfo.isFunctionDeclarator() &&
2903 DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2904 DeclSpec::SCS_typedef)
2905 HandleMemberFunctionDeclDelays(DeclaratorInfo, ThisDecl);
Douglas Gregor728d00b2011-10-10 14:49:18 +00002906 }
David Majnemer23252a32013-08-01 04:22:55 +00002907 LateParsedAttrs.clear();
Douglas Gregor728d00b2011-10-10 14:49:18 +00002908
2909 DeclaratorInfo.complete(ThisDecl);
Richard Smith938f40b2011-06-11 17:19:42 +00002910
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002911 // If we don't have a comma, it is either the end of the list (a ';')
2912 // or an error, bail out.
Alp Toker094e5212014-01-05 03:27:11 +00002913 SourceLocation CommaLoc;
2914 if (!TryConsumeToken(tok::comma, CommaLoc))
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002915 break;
Mike Stump11289f42009-09-09 15:08:12 +00002916
Richard Smithc8a79032012-01-09 22:31:44 +00002917 if (Tok.isAtStartOfLine() &&
Faisal Vali421b2d12017-12-29 05:41:00 +00002918 !MightBeDeclarator(DeclaratorContext::MemberContext)) {
Richard Smithc8a79032012-01-09 22:31:44 +00002919 // This comma was followed by a line-break and something which can't be
2920 // the start of a declarator. The comma was probably a typo for a
2921 // semicolon.
2922 Diag(CommaLoc, diag::err_expected_semi_declaration)
2923 << FixItHint::CreateReplacement(CommaLoc, ";");
2924 ExpectSemi = false;
2925 break;
2926 }
Mike Stump11289f42009-09-09 15:08:12 +00002927
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002928 // Parse the next declarator.
2929 DeclaratorInfo.clear();
Nico Weber24b2a822011-01-28 06:07:34 +00002930 VS.clear();
Nico Weberf56c85b2015-01-17 02:26:40 +00002931 BitfieldSize = ExprResult(/*Invalid=*/false);
Richard Smith9ba0fec2015-06-30 01:28:56 +00002932 EqualLoc = PureSpecLoc = SourceLocation();
Richard Smith8d06f422012-01-12 23:53:29 +00002933 DeclaratorInfo.setCommaLoc(CommaLoc);
Mike Stump11289f42009-09-09 15:08:12 +00002934
Richard Smith72553fc2014-01-23 23:53:27 +00002935 // GNU attributes are allowed before the second and subsequent declarator.
John McCall53fa7142010-12-24 02:08:15 +00002936 MaybeParseGNUAttributes(DeclaratorInfo);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002937
Nico Weberd89e6f72015-01-16 19:34:13 +00002938 if (ParseCXXMemberDeclaratorBeforeInitializer(
2939 DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs))
2940 break;
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002941 }
2942
Richard Smithc8a79032012-01-09 22:31:44 +00002943 if (ExpectSemi &&
2944 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list)) {
Chris Lattner916dbf12010-02-02 00:43:15 +00002945 // Skip to end of block or statement.
Alexey Bataevee6507d2013-11-18 08:17:37 +00002946 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Chris Lattner916dbf12010-02-02 00:43:15 +00002947 // If we stopped at a ';', eat it.
Alp Toker35d87032013-12-30 23:29:50 +00002948 TryConsumeToken(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002949 return nullptr;
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002950 }
2951
Alexey Bataev05c25d62015-07-31 08:42:25 +00002952 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002953}
2954
Richard Smith9ba0fec2015-06-30 01:28:56 +00002955/// ParseCXXMemberInitializer - Parse the brace-or-equal-initializer.
2956/// Also detect and reject any attempted defaulted/deleted function definition.
2957/// The location of the '=', if any, will be placed in EqualLoc.
Richard Smith938f40b2011-06-11 17:19:42 +00002958///
Richard Smith9ba0fec2015-06-30 01:28:56 +00002959/// This does not check for a pure-specifier; that's handled elsewhere.
Sebastian Redleef474c2012-02-22 10:50:08 +00002960///
Richard Smith938f40b2011-06-11 17:19:42 +00002961/// brace-or-equal-initializer:
2962/// '=' initializer-expression
Sebastian Redleef474c2012-02-22 10:50:08 +00002963/// braced-init-list
2964///
Richard Smith938f40b2011-06-11 17:19:42 +00002965/// initializer-clause:
2966/// assignment-expression
Sebastian Redleef474c2012-02-22 10:50:08 +00002967/// braced-init-list
2968///
Richard Smithda35e962013-11-09 04:52:51 +00002969/// defaulted/deleted function-definition:
Richard Smith938f40b2011-06-11 17:19:42 +00002970/// '=' 'default'
2971/// '=' 'delete'
2972///
2973/// Prior to C++0x, the assignment-expression in an initializer-clause must
2974/// be a constant-expression.
Douglas Gregor926410d2012-02-21 02:22:07 +00002975ExprResult Parser::ParseCXXMemberInitializer(Decl *D, bool IsFunction,
Richard Smith938f40b2011-06-11 17:19:42 +00002976 SourceLocation &EqualLoc) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002977 assert(Tok.isOneOf(tok::equal, tok::l_brace)
Richard Smith938f40b2011-06-11 17:19:42 +00002978 && "Data member initializer not starting with '=' or '{'");
2979
Faisal Valid143a0c2017-04-01 21:30:49 +00002980 EnterExpressionEvaluationContext Context(
2981 Actions, Sema::ExpressionEvaluationContext::PotentiallyEvaluated, D);
Alp Toker094e5212014-01-05 03:27:11 +00002982 if (TryConsumeToken(tok::equal, EqualLoc)) {
Richard Smith938f40b2011-06-11 17:19:42 +00002983 if (Tok.is(tok::kw_delete)) {
2984 // In principle, an initializer of '= delete p;' is legal, but it will
2985 // never type-check. It's better to diagnose it as an ill-formed expression
2986 // than as an ill-formed deleted non-function member.
2987 // An initializer of '= delete p, foo' will never be parsed, because
2988 // a top-level comma always ends the initializer expression.
2989 const Token &Next = NextToken();
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002990 if (IsFunction || Next.isOneOf(tok::semi, tok::comma, tok::eof)) {
Richard Smith938f40b2011-06-11 17:19:42 +00002991 if (IsFunction)
2992 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2993 << 1 /* delete */;
2994 else
2995 Diag(ConsumeToken(), diag::err_deleted_non_function);
Richard Smithedcb26e2014-06-11 00:49:52 +00002996 return ExprError();
Richard Smith938f40b2011-06-11 17:19:42 +00002997 }
2998 } else if (Tok.is(tok::kw_default)) {
Richard Smith938f40b2011-06-11 17:19:42 +00002999 if (IsFunction)
3000 Diag(Tok, diag::err_default_delete_in_multiple_declaration)
3001 << 0 /* default */;
3002 else
Richard Smithd052a5782019-10-22 17:44:08 -07003003 Diag(ConsumeToken(), diag::err_default_special_members)
3004 << getLangOpts().CPlusPlus2a;
Richard Smithedcb26e2014-06-11 00:49:52 +00003005 return ExprError();
Richard Smith938f40b2011-06-11 17:19:42 +00003006 }
David Majnemer87ff66c2014-12-13 11:34:16 +00003007 }
3008 if (const auto *PD = dyn_cast_or_null<MSPropertyDecl>(D)) {
3009 Diag(Tok, diag::err_ms_property_initializer) << PD;
3010 return ExprError();
Sebastian Redleef474c2012-02-22 10:50:08 +00003011 }
3012 return ParseInitializer();
Richard Smith938f40b2011-06-11 17:19:42 +00003013}
3014
Richard Smith65ebb4a2015-03-26 04:09:53 +00003015void Parser::SkipCXXMemberSpecification(SourceLocation RecordLoc,
3016 SourceLocation AttrFixitLoc,
Faisal Vali090da2d2018-01-01 18:23:28 +00003017 unsigned TagType, Decl *TagDecl) {
Richard Smith65ebb4a2015-03-26 04:09:53 +00003018 // Skip the optional 'final' keyword.
3019 if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
3020 assert(isCXX11FinalKeyword() && "not a class definition");
3021 ConsumeToken();
3022
3023 // Diagnose any C++11 attributes after 'final' keyword.
3024 // We deliberately discard these attributes.
3025 ParsedAttributesWithRange Attrs(AttrFactory);
3026 CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
3027
3028 // This can only happen if we had malformed misplaced attributes;
3029 // we only get called if there is a colon or left-brace after the
3030 // attributes.
3031 if (Tok.isNot(tok::colon) && Tok.isNot(tok::l_brace))
3032 return;
3033 }
3034
3035 // Skip the base clauses. This requires actually parsing them, because
3036 // otherwise we can't be sure where they end (a left brace may appear
3037 // within a template argument).
3038 if (Tok.is(tok::colon)) {
3039 // Enter the scope of the class so that we can correctly parse its bases.
3040 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
3041 ParsingClassDefinition ParsingDef(*this, TagDecl, /*NonNestedClass*/ true,
3042 TagType == DeclSpec::TST_interface);
Richard Smith0f192e82015-06-11 22:48:25 +00003043 auto OldContext =
3044 Actions.ActOnTagStartSkippedDefinition(getCurScope(), TagDecl);
Richard Smith65ebb4a2015-03-26 04:09:53 +00003045
3046 // Parse the bases but don't attach them to the class.
3047 ParseBaseClause(nullptr);
3048
Richard Smith0f192e82015-06-11 22:48:25 +00003049 Actions.ActOnTagFinishSkippedDefinition(OldContext);
Richard Smith65ebb4a2015-03-26 04:09:53 +00003050
3051 if (!Tok.is(tok::l_brace)) {
3052 Diag(PP.getLocForEndOfToken(PrevTokLocation),
3053 diag::err_expected_lbrace_after_base_specifiers);
3054 return;
3055 }
3056 }
3057
3058 // Skip the body.
3059 assert(Tok.is(tok::l_brace));
3060 BalancedDelimiterTracker T(*this, tok::l_brace);
3061 T.consumeOpen();
3062 T.skipToEnd();
Richard Smith04c6c1f2015-07-01 18:56:50 +00003063
3064 // Parse and discard any trailing attributes.
3065 ParsedAttributes Attrs(AttrFactory);
3066 if (Tok.is(tok::kw___attribute))
3067 MaybeParseGNUAttributes(Attrs);
Richard Smith65ebb4a2015-03-26 04:09:53 +00003068}
3069
Alexey Bataev05c25d62015-07-31 08:42:25 +00003070Parser::DeclGroupPtrTy Parser::ParseCXXClassMemberDeclarationWithPragmas(
3071 AccessSpecifier &AS, ParsedAttributesWithRange &AccessAttrs,
3072 DeclSpec::TST TagType, Decl *TagDecl) {
Richard Smithbf5bcf22018-06-26 23:20:26 +00003073 ParenBraceBracketBalancer BalancerRAIIObj(*this);
3074
Richard Smithb55f7582017-01-28 01:12:10 +00003075 switch (Tok.getKind()) {
3076 case tok::kw___if_exists:
3077 case tok::kw___if_not_exists:
Erich Keanec480f302018-07-12 21:09:05 +00003078 ParseMicrosoftIfExistsClassDeclaration(TagType, AccessAttrs, AS);
David Blaikie0403cb12016-01-15 23:43:25 +00003079 return nullptr;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003080
Richard Smithb55f7582017-01-28 01:12:10 +00003081 case tok::semi:
3082 // Check for extraneous top-level semicolon.
Alexey Bataev05c25d62015-07-31 08:42:25 +00003083 ConsumeExtraSemi(InsideStruct, TagType);
David Blaikie0403cb12016-01-15 23:43:25 +00003084 return nullptr;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003085
Richard Smithb55f7582017-01-28 01:12:10 +00003086 // Handle pragmas that can appear as member declarations.
3087 case tok::annot_pragma_vis:
Alexey Bataev05c25d62015-07-31 08:42:25 +00003088 HandlePragmaVisibility();
David Blaikie0403cb12016-01-15 23:43:25 +00003089 return nullptr;
Richard Smithb55f7582017-01-28 01:12:10 +00003090 case tok::annot_pragma_pack:
Alexey Bataev05c25d62015-07-31 08:42:25 +00003091 HandlePragmaPack();
David Blaikie0403cb12016-01-15 23:43:25 +00003092 return nullptr;
Richard Smithb55f7582017-01-28 01:12:10 +00003093 case tok::annot_pragma_align:
Alexey Bataev05c25d62015-07-31 08:42:25 +00003094 HandlePragmaAlign();
David Blaikie0403cb12016-01-15 23:43:25 +00003095 return nullptr;
Richard Smithb55f7582017-01-28 01:12:10 +00003096 case tok::annot_pragma_ms_pointers_to_members:
Alexey Bataev05c25d62015-07-31 08:42:25 +00003097 HandlePragmaMSPointersToMembers();
David Blaikie0403cb12016-01-15 23:43:25 +00003098 return nullptr;
Richard Smithb55f7582017-01-28 01:12:10 +00003099 case tok::annot_pragma_ms_pragma:
Alexey Bataev05c25d62015-07-31 08:42:25 +00003100 HandlePragmaMSPragma();
David Blaikie0403cb12016-01-15 23:43:25 +00003101 return nullptr;
Richard Smithb55f7582017-01-28 01:12:10 +00003102 case tok::annot_pragma_ms_vtordisp:
Alexey Bataev3d42f342015-11-20 07:02:57 +00003103 HandlePragmaMSVtorDisp();
David Blaikie0403cb12016-01-15 23:43:25 +00003104 return nullptr;
Richard Smithb256d302017-01-28 01:20:57 +00003105 case tok::annot_pragma_dump:
3106 HandlePragmaDump();
3107 return nullptr;
Alexey Bataev3d42f342015-11-20 07:02:57 +00003108
Richard Smithb55f7582017-01-28 01:12:10 +00003109 case tok::kw_namespace:
3110 // If we see a namespace here, a close brace was missing somewhere.
Alexey Bataev05c25d62015-07-31 08:42:25 +00003111 DiagnoseUnexpectedNamespace(cast<NamedDecl>(TagDecl));
David Blaikie0403cb12016-01-15 23:43:25 +00003112 return nullptr;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003113
Anastasia Stulova948e37c2019-03-25 11:54:02 +00003114 case tok::kw_private:
3115 // FIXME: We don't accept GNU attributes on access specifiers in OpenCL mode
3116 // yet.
3117 if (getLangOpts().OpenCL && !NextToken().is(tok::colon))
3118 return ParseCXXClassMemberDeclaration(AS, AccessAttrs);
3119 LLVM_FALLTHROUGH;
Richard Smithb55f7582017-01-28 01:12:10 +00003120 case tok::kw_public:
Anastasia Stulova948e37c2019-03-25 11:54:02 +00003121 case tok::kw_protected: {
Richard Smithb55f7582017-01-28 01:12:10 +00003122 AccessSpecifier NewAS = getAccessSpecifierIfPresent();
3123 assert(NewAS != AS_none);
Alexey Bataev05c25d62015-07-31 08:42:25 +00003124 // Current token is a C++ access specifier.
3125 AS = NewAS;
3126 SourceLocation ASLoc = Tok.getLocation();
3127 unsigned TokLength = Tok.getLength();
3128 ConsumeToken();
3129 AccessAttrs.clear();
3130 MaybeParseGNUAttributes(AccessAttrs);
3131
3132 SourceLocation EndLoc;
3133 if (TryConsumeToken(tok::colon, EndLoc)) {
3134 } else if (TryConsumeToken(tok::semi, EndLoc)) {
3135 Diag(EndLoc, diag::err_expected)
3136 << tok::colon << FixItHint::CreateReplacement(EndLoc, ":");
3137 } else {
3138 EndLoc = ASLoc.getLocWithOffset(TokLength);
3139 Diag(EndLoc, diag::err_expected)
3140 << tok::colon << FixItHint::CreateInsertion(EndLoc, ":");
3141 }
3142
3143 // The Microsoft extension __interface does not permit non-public
3144 // access specifiers.
3145 if (TagType == DeclSpec::TST_interface && AS != AS_public) {
3146 Diag(ASLoc, diag::err_access_specifier_interface) << (AS == AS_protected);
3147 }
3148
Erich Keanec480f302018-07-12 21:09:05 +00003149 if (Actions.ActOnAccessSpecifier(NewAS, ASLoc, EndLoc, AccessAttrs)) {
Alexey Bataev05c25d62015-07-31 08:42:25 +00003150 // found another attribute than only annotations
3151 AccessAttrs.clear();
3152 }
3153
David Blaikie0403cb12016-01-15 23:43:25 +00003154 return nullptr;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003155 }
3156
Richard Smithb55f7582017-01-28 01:12:10 +00003157 case tok::annot_pragma_openmp:
Alexey Bataevc972f6f2020-01-07 13:39:18 -05003158 return ParseOpenMPDeclarativeDirectiveWithExtDecl(
3159 AS, AccessAttrs, /*Delayed=*/true, TagType, TagDecl);
Alexey Bataev05c25d62015-07-31 08:42:25 +00003160
Richard Smithb55f7582017-01-28 01:12:10 +00003161 default:
Serge Pavlov037861b2019-08-04 10:08:51 +00003162 if (tok::isPragmaAnnotation(Tok.getKind())) {
3163 Diag(Tok.getLocation(), diag::err_pragma_misplaced_in_decl)
3164 << DeclSpec::getSpecifierName(TagType,
3165 Actions.getASTContext().getPrintingPolicy());
3166 ConsumeAnnotationToken();
3167 return nullptr;
3168 }
Erich Keanec480f302018-07-12 21:09:05 +00003169 return ParseCXXClassMemberDeclaration(AS, AccessAttrs);
Richard Smithb55f7582017-01-28 01:12:10 +00003170 }
Alexey Bataev05c25d62015-07-31 08:42:25 +00003171}
3172
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003173/// ParseCXXMemberSpecification - Parse the class definition.
3174///
3175/// member-specification:
3176/// member-declaration member-specification[opt]
3177/// access-specifier ':' member-specification[opt]
3178///
Joao Matose9a3ed42012-08-31 22:18:20 +00003179void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc,
Michael Han309af292013-01-07 16:57:11 +00003180 SourceLocation AttrFixitLoc,
Richard Smith4c96e992013-02-19 23:47:15 +00003181 ParsedAttributesWithRange &Attrs,
Faisal Vali090da2d2018-01-01 18:23:28 +00003182 unsigned TagType, Decl *TagDecl) {
Joao Matose9a3ed42012-08-31 22:18:20 +00003183 assert((TagType == DeclSpec::TST_struct ||
Faisal Vali090da2d2018-01-01 18:23:28 +00003184 TagType == DeclSpec::TST_interface ||
3185 TagType == DeclSpec::TST_union ||
3186 TagType == DeclSpec::TST_class) && "Invalid TagType!");
Joao Matose9a3ed42012-08-31 22:18:20 +00003187
Anton Afanasyevd880de22019-03-30 08:42:48 +00003188 llvm::TimeTraceScope TimeScope("ParseClass", [&]() {
3189 if (auto *TD = dyn_cast_or_null<NamedDecl>(TagDecl))
3190 return TD->getQualifiedNameAsString();
3191 return std::string("<anonymous>");
3192 });
3193
Jordan Rose1e879d82018-03-23 00:07:18 +00003194 PrettyDeclStackTraceEntry CrashInfo(Actions.Context, TagDecl, RecordLoc,
John McCallfaf5fb42010-08-26 23:41:50 +00003195 "parsing struct/union/class body");
Mike Stump11289f42009-09-09 15:08:12 +00003196
Douglas Gregoredf8f392010-01-16 20:52:59 +00003197 // Determine whether this is a non-nested class. Note that local
3198 // classes are *not* considered to be nested classes.
3199 bool NonNestedClass = true;
3200 if (!ClassStack.empty()) {
Douglas Gregor0be31a22010-07-02 17:43:08 +00003201 for (const Scope *S = getCurScope(); S; S = S->getParent()) {
Douglas Gregoredf8f392010-01-16 20:52:59 +00003202 if (S->isClassScope()) {
3203 // We're inside a class scope, so this is a nested class.
3204 NonNestedClass = false;
John McCalldb632ac2012-09-25 07:32:39 +00003205
3206 // The Microsoft extension __interface does not permit nested classes.
3207 if (getCurrentClass().IsInterface) {
3208 Diag(RecordLoc, diag::err_invalid_member_in_interface)
3209 << /*ErrorType=*/6
3210 << (isa<NamedDecl>(TagDecl)
3211 ? cast<NamedDecl>(TagDecl)->getQualifiedNameAsString()
David Blaikieabe1a392014-04-02 05:58:29 +00003212 : "(anonymous)");
John McCalldb632ac2012-09-25 07:32:39 +00003213 }
Douglas Gregoredf8f392010-01-16 20:52:59 +00003214 break;
3215 }
3216
Serge Pavlovd9c0bcf2015-07-14 10:02:10 +00003217 if ((S->getFlags() & Scope::FnScope))
3218 // If we're in a function or function template then this is a local
3219 // class rather than a nested class.
3220 break;
Douglas Gregoredf8f392010-01-16 20:52:59 +00003221 }
3222 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003223
3224 // Enter a scope for the class.
Douglas Gregor658b9552009-01-09 22:42:13 +00003225 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003226
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003227 // Note that we are parsing a new (potentially-nested) class definition.
John McCalldb632ac2012-09-25 07:32:39 +00003228 ParsingClassDefinition ParsingDef(*this, TagDecl, NonNestedClass,
3229 TagType == DeclSpec::TST_interface);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003230
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003231 if (TagDecl)
Douglas Gregor0be31a22010-07-02 17:43:08 +00003232 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
John McCall2d814c32009-12-19 21:48:58 +00003233
Anders Carlssonf9eb63b2011-03-25 14:46:08 +00003234 SourceLocation FinalLoc;
David Majnemera5433082013-10-18 00:33:31 +00003235 bool IsFinalSpelledSealed = false;
Anders Carlssonf9eb63b2011-03-25 14:46:08 +00003236
3237 // Parse the optional 'final' keyword.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003238 if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
David Majnemera5433082013-10-18 00:33:31 +00003239 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier(Tok);
3240 assert((Specifier == VirtSpecifiers::VS_Final ||
Fangrui Song6907ce22018-07-30 19:24:48 +00003241 Specifier == VirtSpecifiers::VS_GNU_Final ||
David Majnemera5433082013-10-18 00:33:31 +00003242 Specifier == VirtSpecifiers::VS_Sealed) &&
3243 "not a class definition");
Richard Smithda261112011-10-15 04:21:46 +00003244 FinalLoc = ConsumeToken();
David Majnemera5433082013-10-18 00:33:31 +00003245 IsFinalSpelledSealed = Specifier == VirtSpecifiers::VS_Sealed;
Anders Carlssonf9eb63b2011-03-25 14:46:08 +00003246
David Majnemera5433082013-10-18 00:33:31 +00003247 if (TagType == DeclSpec::TST_interface)
John McCalldb632ac2012-09-25 07:32:39 +00003248 Diag(FinalLoc, diag::err_override_control_interface)
David Majnemera5433082013-10-18 00:33:31 +00003249 << VirtSpecifiers::getSpecifierName(Specifier);
3250 else if (Specifier == VirtSpecifiers::VS_Final)
3251 Diag(FinalLoc, getLangOpts().CPlusPlus11
3252 ? diag::warn_cxx98_compat_override_control_keyword
3253 : diag::ext_override_control_keyword)
3254 << VirtSpecifiers::getSpecifierName(Specifier);
3255 else if (Specifier == VirtSpecifiers::VS_Sealed)
3256 Diag(FinalLoc, diag::ext_ms_sealed_keyword);
Andrey Bokhanko276055b2016-07-29 10:42:48 +00003257 else if (Specifier == VirtSpecifiers::VS_GNU_Final)
3258 Diag(FinalLoc, diag::ext_warn_gnu_final);
Michael Han9407e502012-11-26 22:54:45 +00003259
Michael Han309af292013-01-07 16:57:11 +00003260 // Parse any C++11 attributes after 'final' keyword.
3261 // These attributes are not allowed to appear here,
3262 // and the only possible place for them to appertain
3263 // to the class would be between class-key and class-name.
Richard Smith4c96e992013-02-19 23:47:15 +00003264 CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
Nico Weber4b4be842014-12-29 06:56:50 +00003265
3266 // ParseClassSpecifier() does only a superficial check for attributes before
3267 // deciding to call this method. For example, for
3268 // `class C final alignas ([l) {` it will decide that this looks like a
3269 // misplaced attribute since it sees `alignas '(' ')'`. But the actual
3270 // attribute parsing code will try to parse the '[' as a constexpr lambda
3271 // and consume enough tokens that the alignas parsing code will eat the
3272 // opening '{'. So bail out if the next token isn't one we expect.
Nico Weber36de3a22014-12-29 21:56:22 +00003273 if (!Tok.is(tok::colon) && !Tok.is(tok::l_brace)) {
3274 if (TagDecl)
3275 Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
Nico Weber4b4be842014-12-29 06:56:50 +00003276 return;
Nico Weber36de3a22014-12-29 21:56:22 +00003277 }
Anders Carlssonf9eb63b2011-03-25 14:46:08 +00003278 }
Anders Carlsson4b63d0e2011-01-22 16:56:46 +00003279
John McCall2d814c32009-12-19 21:48:58 +00003280 if (Tok.is(tok::colon)) {
Erik Verbruggen6524c052017-10-24 13:46:58 +00003281 ParseScope InheritanceScope(this, getCurScope()->getFlags() |
3282 Scope::ClassInheritanceScope);
3283
John McCall2d814c32009-12-19 21:48:58 +00003284 ParseBaseClause(TagDecl);
John McCall2d814c32009-12-19 21:48:58 +00003285 if (!Tok.is(tok::l_brace)) {
Ismail Pazarbasi129c44c2014-09-25 21:13:02 +00003286 bool SuggestFixIt = false;
3287 SourceLocation BraceLoc = PP.getLocForEndOfToken(PrevTokLocation);
3288 if (Tok.isAtStartOfLine()) {
3289 switch (Tok.getKind()) {
3290 case tok::kw_private:
3291 case tok::kw_protected:
3292 case tok::kw_public:
3293 SuggestFixIt = NextToken().getKind() == tok::colon;
3294 break;
3295 case tok::kw_static_assert:
3296 case tok::r_brace:
3297 case tok::kw_using:
3298 // base-clause can have simple-template-id; 'template' can't be there
3299 case tok::kw_template:
3300 SuggestFixIt = true;
3301 break;
3302 case tok::identifier:
3303 SuggestFixIt = isConstructorDeclarator(true);
3304 break;
3305 default:
3306 SuggestFixIt = isCXXSimpleDeclaration(/*AllowForRangeDecl=*/false);
3307 break;
3308 }
3309 }
3310 DiagnosticBuilder LBraceDiag =
3311 Diag(BraceLoc, diag::err_expected_lbrace_after_base_specifiers);
3312 if (SuggestFixIt) {
3313 LBraceDiag << FixItHint::CreateInsertion(BraceLoc, " {");
3314 // Try recovering from missing { after base-clause.
Ilya Biryukov929af672019-05-17 09:32:05 +00003315 PP.EnterToken(Tok, /*IsReinject*/true);
Ismail Pazarbasi129c44c2014-09-25 21:13:02 +00003316 Tok.setKind(tok::l_brace);
3317 } else {
3318 if (TagDecl)
3319 Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
3320 return;
3321 }
John McCall2d814c32009-12-19 21:48:58 +00003322 }
3323 }
3324
3325 assert(Tok.is(tok::l_brace));
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003326 BalancedDelimiterTracker T(*this, tok::l_brace);
3327 T.consumeOpen();
John McCall2d814c32009-12-19 21:48:58 +00003328
John McCall08bede42010-05-28 08:11:17 +00003329 if (TagDecl)
Anders Carlsson30f29442011-03-25 14:31:08 +00003330 Actions.ActOnStartCXXMemberDeclarations(getCurScope(), TagDecl, FinalLoc,
David Majnemera5433082013-10-18 00:33:31 +00003331 IsFinalSpelledSealed,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003332 T.getOpenLocation());
John McCall1c7e6ec2009-12-20 07:58:13 +00003333
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003334 // C++ 11p3: Members of a class defined with the keyword class are private
3335 // by default. Members of a class defined with the keywords struct or union
3336 // are public by default.
3337 AccessSpecifier CurAS;
3338 if (TagType == DeclSpec::TST_class)
3339 CurAS = AS_private;
3340 else
3341 CurAS = AS_public;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003342 ParsedAttributesWithRange AccessAttrs(AttrFactory);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003343
Douglas Gregor9377c822010-06-21 22:31:09 +00003344 if (TagDecl) {
3345 // While we still have something to read, read the member-declarations.
Richard Smith752ada82015-11-17 23:32:01 +00003346 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
3347 Tok.isNot(tok::eof)) {
Douglas Gregor9377c822010-06-21 22:31:09 +00003348 // Each iteration of this loop reads one member-declaration.
Alexey Bataev05c25d62015-07-31 08:42:25 +00003349 ParseCXXClassMemberDeclarationWithPragmas(
3350 CurAS, AccessAttrs, static_cast<DeclSpec::TST>(TagType), TagDecl);
Serge Pavlovc4e04a22015-09-19 05:32:57 +00003351 }
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003352 T.consumeClose();
Douglas Gregor9377c822010-06-21 22:31:09 +00003353 } else {
Alexey Bataevee6507d2013-11-18 08:17:37 +00003354 SkipUntil(tok::r_brace);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003355 }
Mike Stump11289f42009-09-09 15:08:12 +00003356
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003357 // If attributes exist after class contents, parse them.
John McCall084e83d2011-03-24 11:26:52 +00003358 ParsedAttributes attrs(AttrFactory);
John McCall53fa7142010-12-24 02:08:15 +00003359 MaybeParseGNUAttributes(attrs);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003360
John McCall08bede42010-05-28 08:11:17 +00003361 if (TagDecl)
Douglas Gregor0be31a22010-07-02 17:43:08 +00003362 Actions.ActOnFinishCXXMemberSpecification(getCurScope(), RecordLoc, TagDecl,
Erich Keanec480f302018-07-12 21:09:05 +00003363 T.getOpenLocation(),
3364 T.getCloseLocation(), attrs);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003365
Douglas Gregor433e0532012-04-16 18:27:27 +00003366 // C++11 [class.mem]p2:
3367 // Within the class member-specification, the class is regarded as complete
Richard Smith0b3a4622014-11-13 20:01:57 +00003368 // within function bodies, default arguments, exception-specifications, and
Douglas Gregor433e0532012-04-16 18:27:27 +00003369 // brace-or-equal-initializers for non-static data members (including such
3370 // things in nested classes).
Douglas Gregor9377c822010-06-21 22:31:09 +00003371 if (TagDecl && NonNestedClass) {
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003372 // We are not inside a nested class. This class and its nested classes
Douglas Gregor4d87df52008-12-16 21:30:33 +00003373 // are complete and we can parse the delayed portions of method
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00003374 // declarations and the lexed inline method definitions, along with any
3375 // delayed attributes.
Douglas Gregor428119e2010-06-16 23:45:56 +00003376 SourceLocation SavedPrevTokLocation = PrevTokLocation;
Alexey Bataevc972f6f2020-01-07 13:39:18 -05003377 ParseLexedPragmas(getCurrentClass());
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00003378 ParseLexedAttributes(getCurrentClass());
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003379 ParseLexedMethodDeclarations(getCurrentClass());
Richard Smith84973e52012-04-21 18:42:51 +00003380
3381 // We've finished with all pending member declarations.
3382 Actions.ActOnFinishCXXMemberDecls();
3383
Richard Smith938f40b2011-06-11 17:19:42 +00003384 ParseLexedMemberInitializers(getCurrentClass());
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003385 ParseLexedMethodDefs(getCurrentClass());
Douglas Gregor428119e2010-06-16 23:45:56 +00003386 PrevTokLocation = SavedPrevTokLocation;
Reid Klecknerbba3cb92015-03-17 19:00:50 +00003387
3388 // We've finished parsing everything, including default argument
3389 // initializers.
Hans Wennborg92ce2af2019-12-02 16:25:23 +01003390 Actions.ActOnFinishCXXNonNestedClass();
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003391 }
3392
John McCall08bede42010-05-28 08:11:17 +00003393 if (TagDecl)
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00003394 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getRange());
John McCall2ff380a2010-03-17 00:38:33 +00003395
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003396 // Leave the class scope.
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003397 ParsingDef.Pop();
Douglas Gregor7307d6c2008-12-10 06:34:36 +00003398 ClassScope.Exit();
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003399}
Douglas Gregore8381c02008-11-05 04:29:56 +00003400
Richard Smith2ac43ad2013-11-15 23:00:02 +00003401void Parser::DiagnoseUnexpectedNamespace(NamedDecl *D) {
Richard Smithda35e962013-11-09 04:52:51 +00003402 assert(Tok.is(tok::kw_namespace));
3403
3404 // FIXME: Suggest where the close brace should have gone by looking
3405 // at indentation changes within the definition body.
Richard Smith2ac43ad2013-11-15 23:00:02 +00003406 Diag(D->getLocation(),
3407 diag::err_missing_end_of_definition) << D;
Richard Smithda35e962013-11-09 04:52:51 +00003408 Diag(Tok.getLocation(),
Richard Smith2ac43ad2013-11-15 23:00:02 +00003409 diag::note_missing_end_of_definition_before) << D;
Richard Smithda35e962013-11-09 04:52:51 +00003410
3411 // Push '};' onto the token stream to recover.
Ilya Biryukov929af672019-05-17 09:32:05 +00003412 PP.EnterToken(Tok, /*IsReinject*/ true);
Richard Smithda35e962013-11-09 04:52:51 +00003413
3414 Tok.startToken();
3415 Tok.setLocation(PP.getLocForEndOfToken(PrevTokLocation));
3416 Tok.setKind(tok::semi);
Ilya Biryukov929af672019-05-17 09:32:05 +00003417 PP.EnterToken(Tok, /*IsReinject*/ true);
Richard Smithda35e962013-11-09 04:52:51 +00003418
3419 Tok.setKind(tok::r_brace);
3420}
3421
Douglas Gregore8381c02008-11-05 04:29:56 +00003422/// ParseConstructorInitializer - Parse a C++ constructor initializer,
3423/// which explicitly initializes the members or base classes of a
3424/// class (C++ [class.base.init]). For example, the three initializers
3425/// after the ':' in the Derived constructor below:
3426///
3427/// @code
3428/// class Base { };
3429/// class Derived : Base {
3430/// int x;
3431/// float f;
3432/// public:
3433/// Derived(float f) : Base(), x(17), f(f) { }
3434/// };
3435/// @endcode
3436///
Mike Stump11289f42009-09-09 15:08:12 +00003437/// [C++] ctor-initializer:
3438/// ':' mem-initializer-list
Douglas Gregore8381c02008-11-05 04:29:56 +00003439///
Mike Stump11289f42009-09-09 15:08:12 +00003440/// [C++] mem-initializer-list:
Douglas Gregor44e7df62011-01-04 00:32:56 +00003441/// mem-initializer ...[opt]
3442/// mem-initializer ...[opt] , mem-initializer-list
John McCall48871652010-08-21 09:40:31 +00003443void Parser::ParseConstructorInitializer(Decl *ConstructorDecl) {
Nico Weber3b00fdc2015-03-07 19:52:39 +00003444 assert(Tok.is(tok::colon) &&
3445 "Constructor initializer always starts with ':'");
Douglas Gregore8381c02008-11-05 04:29:56 +00003446
Nico Weber3b00fdc2015-03-07 19:52:39 +00003447 // Poison the SEH identifiers so they are flagged as illegal in constructor
3448 // initializers.
John Wiegley1c0675e2011-04-28 01:08:34 +00003449 PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
Douglas Gregore8381c02008-11-05 04:29:56 +00003450 SourceLocation ColonLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +00003451
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003452 SmallVector<CXXCtorInitializer*, 4> MemInitializers;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003453 bool AnyErrors = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003454
Douglas Gregore8381c02008-11-05 04:29:56 +00003455 do {
Douglas Gregoreaeeca92010-08-28 00:00:50 +00003456 if (Tok.is(tok::code_completion)) {
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00003457 Actions.CodeCompleteConstructorInitializer(ConstructorDecl,
3458 MemInitializers);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00003459 return cutOffParsing();
Douglas Gregoreaeeca92010-08-28 00:00:50 +00003460 }
Alexey Bataev79de17d2016-01-20 05:25:51 +00003461
3462 MemInitResult MemInit = ParseMemInitializer(ConstructorDecl);
3463 if (!MemInit.isInvalid())
3464 MemInitializers.push_back(MemInit.get());
3465 else
3466 AnyErrors = true;
3467
Douglas Gregore8381c02008-11-05 04:29:56 +00003468 if (Tok.is(tok::comma))
3469 ConsumeToken();
3470 else if (Tok.is(tok::l_brace))
3471 break;
Alexey Bataev79de17d2016-01-20 05:25:51 +00003472 // If the previous initializer was valid and the next token looks like a
3473 // base or member initializer, assume that we're just missing a comma.
3474 else if (!MemInit.isInvalid() &&
3475 Tok.isOneOf(tok::identifier, tok::coloncolon)) {
Douglas Gregorce66d022010-09-07 14:51:08 +00003476 SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation);
3477 Diag(Loc, diag::err_ctor_init_missing_comma)
3478 << FixItHint::CreateInsertion(Loc, ", ");
3479 } else {
Douglas Gregore8381c02008-11-05 04:29:56 +00003480 // Skip over garbage, until we get to '{'. Don't eat the '{'.
Alexey Bataev79de17d2016-01-20 05:25:51 +00003481 if (!MemInit.isInvalid())
3482 Diag(Tok.getLocation(), diag::err_expected_either) << tok::l_brace
3483 << tok::comma;
Alexey Bataevee6507d2013-11-18 08:17:37 +00003484 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
Douglas Gregore8381c02008-11-05 04:29:56 +00003485 break;
3486 }
3487 } while (true);
3488
David Blaikie3fc2f912013-01-17 05:26:25 +00003489 Actions.ActOnMemInitializers(ConstructorDecl, ColonLoc, MemInitializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003490 AnyErrors);
Douglas Gregore8381c02008-11-05 04:29:56 +00003491}
3492
3493/// ParseMemInitializer - Parse a C++ member initializer, which is
3494/// part of a constructor initializer that explicitly initializes one
3495/// member or base class (C++ [class.base.init]). See
3496/// ParseConstructorInitializer for an example.
3497///
3498/// [C++] mem-initializer:
3499/// mem-initializer-id '(' expression-list[opt] ')'
Sebastian Redl3da34892011-06-05 12:23:16 +00003500/// [C++0x] mem-initializer-id braced-init-list
Mike Stump11289f42009-09-09 15:08:12 +00003501///
Douglas Gregore8381c02008-11-05 04:29:56 +00003502/// [C++] mem-initializer-id:
3503/// '::'[opt] nested-name-specifier[opt] class-name
3504/// identifier
Craig Topper9ad7e262014-10-31 06:57:07 +00003505MemInitResult Parser::ParseMemInitializer(Decl *ConstructorDecl) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00003506 // parse '::'[opt] nested-name-specifier[opt]
3507 CXXScopeSpec SS;
Haojian Wu0dd0b102020-03-19 09:12:29 +01003508 if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
3509 /*ObjectHadErrors=*/false,
3510 /*EnteringContext=*/false))
Richard Smithb23c5e82019-05-09 03:31:27 +00003511 return true;
Richard Smithaf3b3252017-05-18 19:21:48 +00003512
3513 // : identifier
3514 IdentifierInfo *II = nullptr;
3515 SourceLocation IdLoc = Tok.getLocation();
3516 // : declype(...)
3517 DeclSpec DS(AttrFactory);
3518 // : template_name<...>
John McCallba7bf592010-08-24 05:47:05 +00003519 ParsedType TemplateTypeTy;
Richard Smithaf3b3252017-05-18 19:21:48 +00003520
3521 if (Tok.is(tok::identifier)) {
3522 // Get the identifier. This may be a member name or a class name,
3523 // but we'll let the semantic analysis determine which it is.
3524 II = Tok.getIdentifierInfo();
3525 ConsumeToken();
3526 } else if (Tok.is(tok::annot_decltype)) {
3527 // Get the decltype expression, if there is one.
3528 // Uses of decltype will already have been converted to annot_decltype by
3529 // ParseOptionalCXXScopeSpecifier at this point.
3530 // FIXME: Can we get here with a scope specifier?
3531 ParseDecltypeSpecifier(DS);
3532 } else {
3533 TemplateIdAnnotation *TemplateId = Tok.is(tok::annot_template_id)
3534 ? takeTemplateIdAnnotation(Tok)
3535 : nullptr;
3536 if (TemplateId && (TemplateId->Kind == TNK_Type_template ||
Richard Smithb23c5e82019-05-09 03:31:27 +00003537 TemplateId->Kind == TNK_Dependent_template_name ||
3538 TemplateId->Kind == TNK_Undeclared_template)) {
Richard Smitha42fd842020-01-17 15:42:11 -08003539 AnnotateTemplateIdTokenAsType(SS, /*IsClassName*/true);
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00003540 assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
John McCallba7bf592010-08-24 05:47:05 +00003541 TemplateTypeTy = getTypeAnnotation(Tok);
Richard Smithaf3b3252017-05-18 19:21:48 +00003542 ConsumeAnnotationToken();
Richard Smithb23c5e82019-05-09 03:31:27 +00003543 if (!TemplateTypeTy)
3544 return true;
Richard Smithaf3b3252017-05-18 19:21:48 +00003545 } else {
3546 Diag(Tok, diag::err_expected_member_or_base_name);
3547 return true;
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00003548 }
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00003549 }
Douglas Gregore8381c02008-11-05 04:29:56 +00003550
3551 // Parse the '('.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003552 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
Richard Smith5d164bc2011-10-15 05:09:34 +00003553 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
3554
Kadir Cetinkaya84774c32018-09-11 15:02:18 +00003555 // FIXME: Add support for signature help inside initializer lists.
Sebastian Redla74948d2011-09-24 17:48:25 +00003556 ExprResult InitList = ParseBraceInitializer();
3557 if (InitList.isInvalid())
3558 return true;
3559
3560 SourceLocation EllipsisLoc;
Alp Toker094e5212014-01-05 03:27:11 +00003561 TryConsumeToken(tok::ellipsis, EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00003562
3563 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
Fangrui Song6907ce22018-07-30 19:24:48 +00003564 TemplateTypeTy, DS, IdLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003565 InitList.get(), EllipsisLoc);
Sebastian Redl3da34892011-06-05 12:23:16 +00003566 } else if(Tok.is(tok::l_paren)) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003567 BalancedDelimiterTracker T(*this, tok::l_paren);
3568 T.consumeOpen();
Douglas Gregore8381c02008-11-05 04:29:56 +00003569
Sebastian Redl3da34892011-06-05 12:23:16 +00003570 // Parse the optional expression-list.
Benjamin Kramerf0623432012-08-23 22:51:59 +00003571 ExprVector ArgExprs;
Sebastian Redl3da34892011-06-05 12:23:16 +00003572 CommaLocsTy CommaLocs;
Ilya Biryukovff2a9972019-02-26 11:01:50 +00003573 auto RunSignatureHelp = [&] {
3574 QualType PreferredType = Actions.ProduceCtorInitMemberSignatureHelp(
3575 getCurScope(), ConstructorDecl, SS, TemplateTypeTy, ArgExprs, II,
3576 T.getOpenLocation());
3577 CalledSignatureHelp = true;
3578 return PreferredType;
3579 };
Kadir Cetinkaya84774c32018-09-11 15:02:18 +00003580 if (Tok.isNot(tok::r_paren) &&
3581 ParseExpressionList(ArgExprs, CommaLocs, [&] {
Ilya Biryukovff2a9972019-02-26 11:01:50 +00003582 PreferredType.enterFunctionArgument(Tok.getLocation(),
3583 RunSignatureHelp);
Kadir Cetinkaya84774c32018-09-11 15:02:18 +00003584 })) {
Ilya Biryukovff2a9972019-02-26 11:01:50 +00003585 if (PP.isCodeCompletionReached() && !CalledSignatureHelp)
3586 RunSignatureHelp();
Alexey Bataevee6507d2013-11-18 08:17:37 +00003587 SkipUntil(tok::r_paren, StopAtSemi);
Sebastian Redl3da34892011-06-05 12:23:16 +00003588 return true;
3589 }
3590
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003591 T.consumeClose();
Sebastian Redl3da34892011-06-05 12:23:16 +00003592
3593 SourceLocation EllipsisLoc;
Alp Toker97650562014-01-10 11:19:30 +00003594 TryConsumeToken(tok::ellipsis, EllipsisLoc);
Sebastian Redl3da34892011-06-05 12:23:16 +00003595
3596 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
David Blaikie186a8892012-01-24 06:03:59 +00003597 TemplateTypeTy, DS, IdLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00003598 T.getOpenLocation(), ArgExprs,
3599 T.getCloseLocation(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00003600 }
3601
Alp Tokerec543272013-12-24 09:48:30 +00003602 if (getLangOpts().CPlusPlus11)
3603 return Diag(Tok, diag::err_expected_either) << tok::l_paren << tok::l_brace;
3604 else
3605 return Diag(Tok, diag::err_expected) << tok::l_paren;
Douglas Gregore8381c02008-11-05 04:29:56 +00003606}
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003607
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003608/// Parse a C++ exception-specification if present (C++0x [except.spec]).
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003609///
Douglas Gregor356513d2008-12-01 18:00:20 +00003610/// exception-specification:
Sebastian Redl965b0e32011-03-05 14:45:16 +00003611/// dynamic-exception-specification
3612/// noexcept-specification
3613///
3614/// noexcept-specification:
3615/// 'noexcept'
3616/// 'noexcept' '(' constant-expression ')'
3617ExceptionSpecificationType
Richard Smith0b3a4622014-11-13 20:01:57 +00003618Parser::tryParseExceptionSpecification(bool Delayed,
Douglas Gregor433e0532012-04-16 18:27:27 +00003619 SourceRange &SpecificationRange,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003620 SmallVectorImpl<ParsedType> &DynamicExceptions,
3621 SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
Richard Smith0b3a4622014-11-13 20:01:57 +00003622 ExprResult &NoexceptExpr,
3623 CachedTokens *&ExceptionSpecTokens) {
Sebastian Redl965b0e32011-03-05 14:45:16 +00003624 ExceptionSpecificationType Result = EST_None;
Hans Wennborgdcfba332015-10-06 23:40:43 +00003625 ExceptionSpecTokens = nullptr;
Fangrui Song6907ce22018-07-30 19:24:48 +00003626
Richard Smith0b3a4622014-11-13 20:01:57 +00003627 // Handle delayed parsing of exception-specifications.
3628 if (Delayed) {
3629 if (Tok.isNot(tok::kw_throw) && Tok.isNot(tok::kw_noexcept))
3630 return EST_None;
Sebastian Redl965b0e32011-03-05 14:45:16 +00003631
Richard Smith0b3a4622014-11-13 20:01:57 +00003632 // Consume and cache the starting token.
3633 bool IsNoexcept = Tok.is(tok::kw_noexcept);
3634 Token StartTok = Tok;
3635 SpecificationRange = SourceRange(ConsumeToken());
3636
3637 // Check for a '('.
3638 if (!Tok.is(tok::l_paren)) {
3639 // If this is a bare 'noexcept', we're done.
3640 if (IsNoexcept) {
3641 Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
Hans Wennborgdcfba332015-10-06 23:40:43 +00003642 NoexceptExpr = nullptr;
Richard Smith0b3a4622014-11-13 20:01:57 +00003643 return EST_BasicNoexcept;
3644 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003645
Richard Smith0b3a4622014-11-13 20:01:57 +00003646 Diag(Tok, diag::err_expected_lparen_after) << "throw";
3647 return EST_DynamicNone;
3648 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003649
Richard Smith0b3a4622014-11-13 20:01:57 +00003650 // Cache the tokens for the exception-specification.
3651 ExceptionSpecTokens = new CachedTokens;
3652 ExceptionSpecTokens->push_back(StartTok); // 'throw' or 'noexcept'
3653 ExceptionSpecTokens->push_back(Tok); // '('
3654 SpecificationRange.setEnd(ConsumeParen()); // '('
Richard Smithb1c217e2015-01-13 02:24:58 +00003655
3656 ConsumeAndStoreUntil(tok::r_paren, *ExceptionSpecTokens,
3657 /*StopAtSemi=*/true,
3658 /*ConsumeFinalToken=*/true);
Aaron Ballman580ccaf2016-01-12 21:04:22 +00003659 SpecificationRange.setEnd(ExceptionSpecTokens->back().getLocation());
3660
Richard Smith0b3a4622014-11-13 20:01:57 +00003661 return EST_Unparsed;
3662 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003663
Sebastian Redl965b0e32011-03-05 14:45:16 +00003664 // See if there's a dynamic specification.
3665 if (Tok.is(tok::kw_throw)) {
3666 Result = ParseDynamicExceptionSpecification(SpecificationRange,
3667 DynamicExceptions,
3668 DynamicExceptionRanges);
3669 assert(DynamicExceptions.size() == DynamicExceptionRanges.size() &&
3670 "Produced different number of exception types and ranges.");
3671 }
3672
3673 // If there's no noexcept specification, we're done.
3674 if (Tok.isNot(tok::kw_noexcept))
3675 return Result;
3676
Richard Smithb15c11c2011-10-17 23:06:20 +00003677 Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
3678
Sebastian Redl965b0e32011-03-05 14:45:16 +00003679 // If we already had a dynamic specification, parse the noexcept for,
3680 // recovery, but emit a diagnostic and don't store the results.
3681 SourceRange NoexceptRange;
3682 ExceptionSpecificationType NoexceptType = EST_None;
3683
3684 SourceLocation KeywordLoc = ConsumeToken();
3685 if (Tok.is(tok::l_paren)) {
3686 // There is an argument.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003687 BalancedDelimiterTracker T(*this, tok::l_paren);
3688 T.consumeOpen();
Sebastian Redl965b0e32011-03-05 14:45:16 +00003689 NoexceptExpr = ParseConstantExpression();
Serge Pavlov3739f5e72015-06-29 17:50:19 +00003690 T.consumeClose();
Serge Pavlov3739f5e72015-06-29 17:50:19 +00003691 if (!NoexceptExpr.isInvalid()) {
Richard Smitheaf11ad2018-05-03 03:58:32 +00003692 NoexceptExpr = Actions.ActOnNoexceptSpec(KeywordLoc, NoexceptExpr.get(),
3693 NoexceptType);
Serge Pavlov3739f5e72015-06-29 17:50:19 +00003694 NoexceptRange = SourceRange(KeywordLoc, T.getCloseLocation());
3695 } else {
Malcolm Parsonsa3220ce2017-01-12 16:11:28 +00003696 NoexceptType = EST_BasicNoexcept;
Serge Pavlov3739f5e72015-06-29 17:50:19 +00003697 }
Sebastian Redl965b0e32011-03-05 14:45:16 +00003698 } else {
3699 // There is no argument.
3700 NoexceptType = EST_BasicNoexcept;
3701 NoexceptRange = SourceRange(KeywordLoc, KeywordLoc);
3702 }
3703
3704 if (Result == EST_None) {
3705 SpecificationRange = NoexceptRange;
3706 Result = NoexceptType;
3707
3708 // If there's a dynamic specification after a noexcept specification,
3709 // parse that and ignore the results.
3710 if (Tok.is(tok::kw_throw)) {
3711 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
3712 ParseDynamicExceptionSpecification(NoexceptRange, DynamicExceptions,
3713 DynamicExceptionRanges);
3714 }
3715 } else {
3716 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
3717 }
3718
3719 return Result;
3720}
3721
Richard Smith8ca78a12013-06-13 02:02:51 +00003722static void diagnoseDynamicExceptionSpecification(
Craig Toppere335f252015-10-04 04:53:55 +00003723 Parser &P, SourceRange Range, bool IsNoexcept) {
Richard Smith8ca78a12013-06-13 02:02:51 +00003724 if (P.getLangOpts().CPlusPlus11) {
3725 const char *Replacement = IsNoexcept ? "noexcept" : "noexcept(false)";
Richard Smith82da19d2016-12-08 02:49:07 +00003726 P.Diag(Range.getBegin(),
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003727 P.getLangOpts().CPlusPlus17 && !IsNoexcept
Richard Smith82da19d2016-12-08 02:49:07 +00003728 ? diag::ext_dynamic_exception_spec
3729 : diag::warn_exception_spec_deprecated)
3730 << Range;
Richard Smith8ca78a12013-06-13 02:02:51 +00003731 P.Diag(Range.getBegin(), diag::note_exception_spec_deprecated)
3732 << Replacement << FixItHint::CreateReplacement(Range, Replacement);
3733 }
3734}
3735
Sebastian Redl965b0e32011-03-05 14:45:16 +00003736/// ParseDynamicExceptionSpecification - Parse a C++
3737/// dynamic-exception-specification (C++ [except.spec]).
3738///
3739/// dynamic-exception-specification:
Douglas Gregor356513d2008-12-01 18:00:20 +00003740/// 'throw' '(' type-id-list [opt] ')'
3741/// [MS] 'throw' '(' '...' ')'
Mike Stump11289f42009-09-09 15:08:12 +00003742///
Douglas Gregor356513d2008-12-01 18:00:20 +00003743/// type-id-list:
Douglas Gregor830837d2010-12-20 23:57:46 +00003744/// type-id ... [opt]
3745/// type-id-list ',' type-id ... [opt]
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003746///
Sebastian Redl965b0e32011-03-05 14:45:16 +00003747ExceptionSpecificationType Parser::ParseDynamicExceptionSpecification(
3748 SourceRange &SpecificationRange,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003749 SmallVectorImpl<ParsedType> &Exceptions,
3750 SmallVectorImpl<SourceRange> &Ranges) {
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003751 assert(Tok.is(tok::kw_throw) && "expected throw");
Mike Stump11289f42009-09-09 15:08:12 +00003752
Sebastian Redl965b0e32011-03-05 14:45:16 +00003753 SpecificationRange.setBegin(ConsumeToken());
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003754 BalancedDelimiterTracker T(*this, tok::l_paren);
3755 if (T.consumeOpen()) {
Sebastian Redl965b0e32011-03-05 14:45:16 +00003756 Diag(Tok, diag::err_expected_lparen_after) << "throw";
3757 SpecificationRange.setEnd(SpecificationRange.getBegin());
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003758 return EST_DynamicNone;
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003759 }
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003760
Douglas Gregor356513d2008-12-01 18:00:20 +00003761 // Parse throw(...), a Microsoft extension that means "this function
3762 // can throw anything".
3763 if (Tok.is(tok::ellipsis)) {
3764 SourceLocation EllipsisLoc = ConsumeToken();
David Blaikiebbafb8a2012-03-11 07:00:24 +00003765 if (!getLangOpts().MicrosoftExt)
Douglas Gregor356513d2008-12-01 18:00:20 +00003766 Diag(EllipsisLoc, diag::ext_ellipsis_exception_spec);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003767 T.consumeClose();
3768 SpecificationRange.setEnd(T.getCloseLocation());
Richard Smith8ca78a12013-06-13 02:02:51 +00003769 diagnoseDynamicExceptionSpecification(*this, SpecificationRange, false);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003770 return EST_MSAny;
Douglas Gregor356513d2008-12-01 18:00:20 +00003771 }
3772
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003773 // Parse the sequence of type-ids.
Sebastian Redld6434562009-05-29 18:02:33 +00003774 SourceRange Range;
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003775 while (Tok.isNot(tok::r_paren)) {
Sebastian Redld6434562009-05-29 18:02:33 +00003776 TypeResult Res(ParseTypeName(&Range));
Sebastian Redl965b0e32011-03-05 14:45:16 +00003777
Douglas Gregor830837d2010-12-20 23:57:46 +00003778 if (Tok.is(tok::ellipsis)) {
3779 // C++0x [temp.variadic]p5:
Fangrui Song6907ce22018-07-30 19:24:48 +00003780 // - In a dynamic-exception-specification (15.4); the pattern is a
Douglas Gregor830837d2010-12-20 23:57:46 +00003781 // type-id.
3782 SourceLocation Ellipsis = ConsumeToken();
Sebastian Redl965b0e32011-03-05 14:45:16 +00003783 Range.setEnd(Ellipsis);
Douglas Gregor830837d2010-12-20 23:57:46 +00003784 if (!Res.isInvalid())
3785 Res = Actions.ActOnPackExpansion(Res.get(), Ellipsis);
3786 }
Sebastian Redl965b0e32011-03-05 14:45:16 +00003787
Sebastian Redld6434562009-05-29 18:02:33 +00003788 if (!Res.isInvalid()) {
Sebastian Redl2b9cacb2009-04-29 17:30:04 +00003789 Exceptions.push_back(Res.get());
Sebastian Redld6434562009-05-29 18:02:33 +00003790 Ranges.push_back(Range);
3791 }
Alp Toker97650562014-01-10 11:19:30 +00003792
3793 if (!TryConsumeToken(tok::comma))
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003794 break;
3795 }
3796
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003797 T.consumeClose();
3798 SpecificationRange.setEnd(T.getCloseLocation());
Richard Smith8ca78a12013-06-13 02:02:51 +00003799 diagnoseDynamicExceptionSpecification(*this, SpecificationRange,
3800 Exceptions.empty());
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003801 return Exceptions.empty() ? EST_DynamicNone : EST_Dynamic;
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003802}
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003803
Douglas Gregor7fb25412010-10-01 18:44:50 +00003804/// ParseTrailingReturnType - Parse a trailing return type on a new-style
3805/// function declaration.
Richard Smithe303e352018-02-02 22:24:54 +00003806TypeResult Parser::ParseTrailingReturnType(SourceRange &Range,
3807 bool MayBeFollowedByDirectInit) {
Douglas Gregor7fb25412010-10-01 18:44:50 +00003808 assert(Tok.is(tok::arrow) && "expected arrow");
3809
3810 ConsumeToken();
3811
Richard Smithe303e352018-02-02 22:24:54 +00003812 return ParseTypeName(&Range, MayBeFollowedByDirectInit
3813 ? DeclaratorContext::TrailingReturnVarContext
3814 : DeclaratorContext::TrailingReturnContext);
Douglas Gregor7fb25412010-10-01 18:44:50 +00003815}
3816
Saar Razb65b1f32020-01-09 15:07:51 +02003817/// Parse a requires-clause as part of a function declaration.
3818void Parser::ParseTrailingRequiresClause(Declarator &D) {
3819 assert(Tok.is(tok::kw_requires) && "expected requires");
3820
3821 SourceLocation RequiresKWLoc = ConsumeToken();
3822
3823 ExprResult TrailingRequiresClause;
3824 ParseScope ParamScope(this,
3825 Scope::DeclScope |
3826 Scope::FunctionDeclarationScope |
3827 Scope::FunctionPrototypeScope);
3828
3829 Actions.ActOnStartTrailingRequiresClause(getCurScope(), D);
3830
3831 llvm::Optional<Sema::CXXThisScopeRAII> ThisScope;
3832 InitCXXThisScopeForDeclaratorIfRelevant(D, D.getDeclSpec(), ThisScope);
3833
3834 TrailingRequiresClause =
3835 ParseConstraintLogicalOrExpression(/*IsTrailingRequiresClause=*/true);
3836
3837 TrailingRequiresClause =
3838 Actions.ActOnFinishTrailingRequiresClause(TrailingRequiresClause);
3839
3840 if (!D.isDeclarationOfFunction()) {
3841 Diag(RequiresKWLoc,
3842 diag::err_requires_clause_on_declarator_not_declaring_a_function);
3843 return;
3844 }
3845
3846 if (TrailingRequiresClause.isInvalid())
3847 SkipUntil({tok::l_brace, tok::arrow, tok::kw_try, tok::comma, tok::colon},
3848 StopAtSemi | StopBeforeMatch);
3849 else
3850 D.setTrailingRequiresClause(TrailingRequiresClause.get());
3851
3852 // Did the user swap the trailing return type and requires clause?
3853 if (D.isFunctionDeclarator() && Tok.is(tok::arrow) &&
3854 D.getDeclSpec().getTypeSpecType() == TST_auto) {
3855 SourceLocation ArrowLoc = Tok.getLocation();
3856 SourceRange Range;
3857 TypeResult TrailingReturnType =
3858 ParseTrailingReturnType(Range, /*MayBeFollowedByDirectInit=*/false);
3859
3860 if (!TrailingReturnType.isInvalid()) {
3861 Diag(ArrowLoc,
3862 diag::err_requires_clause_must_appear_after_trailing_return)
3863 << Range;
3864 auto &FunctionChunk = D.getFunctionTypeInfo();
3865 FunctionChunk.HasTrailingReturnType = TrailingReturnType.isUsable();
3866 FunctionChunk.TrailingReturnType = TrailingReturnType.get();
3867 } else
3868 SkipUntil({tok::equal, tok::l_brace, tok::arrow, tok::kw_try, tok::comma},
3869 StopAtSemi | StopBeforeMatch);
3870 }
3871}
3872
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003873/// We have just started parsing the definition of a new class,
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003874/// so push that class onto our stack of classes that is currently
3875/// being parsed.
John McCallc1465822011-02-14 07:13:47 +00003876Sema::ParsingClassState
John McCalldb632ac2012-09-25 07:32:39 +00003877Parser::PushParsingClass(Decl *ClassDecl, bool NonNestedClass,
3878 bool IsInterface) {
Douglas Gregoredf8f392010-01-16 20:52:59 +00003879 assert((NonNestedClass || !ClassStack.empty()) &&
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003880 "Nested class without outer class");
John McCalldb632ac2012-09-25 07:32:39 +00003881 ClassStack.push(new ParsingClass(ClassDecl, NonNestedClass, IsInterface));
John McCallc1465822011-02-14 07:13:47 +00003882 return Actions.PushParsingClass();
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003883}
3884
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003885/// Deallocate the given parsed class and all of its nested
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003886/// classes.
3887void Parser::DeallocateParsedClasses(Parser::ParsingClass *Class) {
Douglas Gregorefc46952010-10-12 16:25:54 +00003888 for (unsigned I = 0, N = Class->LateParsedDeclarations.size(); I != N; ++I)
3889 delete Class->LateParsedDeclarations[I];
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003890 delete Class;
3891}
3892
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003893/// Pop the top class of the stack of classes that are
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003894/// currently being parsed.
3895///
3896/// This routine should be called when we have finished parsing the
3897/// definition of a class, but have not yet popped the Scope
3898/// associated with the class's definition.
John McCallc1465822011-02-14 07:13:47 +00003899void Parser::PopParsingClass(Sema::ParsingClassState state) {
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003900 assert(!ClassStack.empty() && "Mismatched push/pop for class parsing");
Mike Stump11289f42009-09-09 15:08:12 +00003901
John McCallc1465822011-02-14 07:13:47 +00003902 Actions.PopParsingClass(state);
3903
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003904 ParsingClass *Victim = ClassStack.top();
3905 ClassStack.pop();
3906 if (Victim->TopLevelClass) {
3907 // Deallocate all of the nested classes of this class,
3908 // recursively: we don't need to keep any of this information.
3909 DeallocateParsedClasses(Victim);
3910 return;
Mike Stump11289f42009-09-09 15:08:12 +00003911 }
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003912 assert(!ClassStack.empty() && "Missing top-level class?");
3913
Douglas Gregorefc46952010-10-12 16:25:54 +00003914 if (Victim->LateParsedDeclarations.empty()) {
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003915 // The victim is a nested class, but we will not need to perform
3916 // any processing after the definition of this class since it has
3917 // no members whose handling was delayed. Therefore, we can just
3918 // remove this nested class.
Douglas Gregorefc46952010-10-12 16:25:54 +00003919 DeallocateParsedClasses(Victim);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003920 return;
3921 }
3922
3923 // This nested class has some members that will need to be processed
3924 // after the top-level class is completely defined. Therefore, add
3925 // it to the list of nested classes within its parent.
Douglas Gregor0be31a22010-07-02 17:43:08 +00003926 assert(getCurScope()->isClassScope() && "Nested class outside of class scope?");
Douglas Gregorefc46952010-10-12 16:25:54 +00003927 ClassStack.top()->LateParsedDeclarations.push_back(new LateParsedClass(this, Victim));
Douglas Gregor0be31a22010-07-02 17:43:08 +00003928 Victim->TemplateScope = getCurScope()->getParent()->isTemplateParamScope();
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003929}
Alexis Hunt96d5c762009-11-21 08:43:09 +00003930
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003931/// Try to parse an 'identifier' which appears within an attribute-token.
Richard Smith3dff2512012-04-10 03:25:07 +00003932///
3933/// \return the parsed identifier on success, and 0 if the next token is not an
3934/// attribute-token.
3935///
3936/// C++11 [dcl.attr.grammar]p3:
3937/// If a keyword or an alternative token that satisfies the syntactic
3938/// requirements of an identifier is contained in an attribute-token,
3939/// it is considered an identifier.
3940IdentifierInfo *Parser::TryParseCXX11AttributeIdentifier(SourceLocation &Loc) {
3941 switch (Tok.getKind()) {
3942 default:
3943 // Identifiers and keywords have identifier info attached.
David Majnemerd5271992015-01-09 18:09:39 +00003944 if (!Tok.isAnnotation()) {
3945 if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
3946 Loc = ConsumeToken();
3947 return II;
3948 }
Richard Smith3dff2512012-04-10 03:25:07 +00003949 }
Craig Topper161e4db2014-05-21 06:02:52 +00003950 return nullptr;
Richard Smith3dff2512012-04-10 03:25:07 +00003951
Aaron Ballmanc44c17422018-11-09 17:19:45 +00003952 case tok::numeric_constant: {
3953 // If we got a numeric constant, check to see if it comes from a macro that
3954 // corresponds to the predefined __clang__ macro. If it does, warn the user
3955 // and recover by pretending they said _Clang instead.
3956 if (Tok.getLocation().isMacroID()) {
3957 SmallString<8> ExpansionBuf;
3958 SourceLocation ExpansionLoc =
3959 PP.getSourceManager().getExpansionLoc(Tok.getLocation());
3960 StringRef Spelling = PP.getSpelling(ExpansionLoc, ExpansionBuf);
3961 if (Spelling == "__clang__") {
3962 SourceRange TokRange(
3963 ExpansionLoc,
3964 PP.getSourceManager().getExpansionLoc(Tok.getEndLoc()));
3965 Diag(Tok, diag::warn_wrong_clang_attr_namespace)
3966 << FixItHint::CreateReplacement(TokRange, "_Clang");
3967 Loc = ConsumeToken();
3968 return &PP.getIdentifierTable().get("_Clang");
3969 }
3970 }
3971 return nullptr;
3972 }
3973
Richard Smith3dff2512012-04-10 03:25:07 +00003974 case tok::ampamp: // 'and'
3975 case tok::pipe: // 'bitor'
3976 case tok::pipepipe: // 'or'
3977 case tok::caret: // 'xor'
3978 case tok::tilde: // 'compl'
3979 case tok::amp: // 'bitand'
3980 case tok::ampequal: // 'and_eq'
3981 case tok::pipeequal: // 'or_eq'
3982 case tok::caretequal: // 'xor_eq'
3983 case tok::exclaim: // 'not'
3984 case tok::exclaimequal: // 'not_eq'
3985 // Alternative tokens do not have identifier info, but their spelling
3986 // starts with an alphabetical character.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003987 SmallString<8> SpellingBuf;
Benjamin Kramer60be5632015-03-29 19:25:07 +00003988 SourceLocation SpellingLoc =
3989 PP.getSourceManager().getSpellingLoc(Tok.getLocation());
3990 StringRef Spelling = PP.getSpelling(SpellingLoc, SpellingBuf);
Jordan Rosea7d03842013-02-08 22:30:41 +00003991 if (isLetter(Spelling[0])) {
Richard Smith3dff2512012-04-10 03:25:07 +00003992 Loc = ConsumeToken();
Benjamin Kramer5c17f9c2012-04-22 20:43:30 +00003993 return &PP.getIdentifierTable().get(Spelling);
Richard Smith3dff2512012-04-10 03:25:07 +00003994 }
Craig Topper161e4db2014-05-21 06:02:52 +00003995 return nullptr;
Richard Smith3dff2512012-04-10 03:25:07 +00003996 }
3997}
3998
Michael Han23214e52012-10-03 01:56:22 +00003999static bool IsBuiltInOrStandardCXX11Attribute(IdentifierInfo *AttrName,
Aaron Ballman606093a2017-10-15 15:01:42 +00004000 IdentifierInfo *ScopeName) {
Erich Keane6a24e802019-09-13 17:39:31 +00004001 switch (
4002 ParsedAttr::getParsedKind(AttrName, ScopeName, ParsedAttr::AS_CXX11)) {
Erich Keanee891aa92018-07-13 15:07:47 +00004003 case ParsedAttr::AT_CarriesDependency:
4004 case ParsedAttr::AT_Deprecated:
4005 case ParsedAttr::AT_FallThrough:
4006 case ParsedAttr::AT_CXX11NoReturn:
Richard Smith78b239e2019-06-20 20:44:45 +00004007 case ParsedAttr::AT_NoUniqueAddress:
Michael Han23214e52012-10-03 01:56:22 +00004008 return true;
Erich Keanee891aa92018-07-13 15:07:47 +00004009 case ParsedAttr::AT_WarnUnusedResult:
Aaron Ballmane7964782016-03-07 22:44:55 +00004010 return !ScopeName && AttrName->getName().equals("nodiscard");
Erich Keanee891aa92018-07-13 15:07:47 +00004011 case ParsedAttr::AT_Unused:
Nico Weberac03bce2016-08-23 19:59:55 +00004012 return !ScopeName && AttrName->getName().equals("maybe_unused");
Michael Han23214e52012-10-03 01:56:22 +00004013 default:
4014 return false;
4015 }
4016}
4017
Aaron Ballmanb8e20392014-03-31 17:32:39 +00004018/// ParseCXX11AttributeArgs -- Parse a C++11 attribute-argument-clause.
4019///
4020/// [C++11] attribute-argument-clause:
4021/// '(' balanced-token-seq ')'
4022///
4023/// [C++11] balanced-token-seq:
4024/// balanced-token
4025/// balanced-token-seq balanced-token
4026///
4027/// [C++11] balanced-token:
4028/// '(' balanced-token-seq ')'
4029/// '[' balanced-token-seq ']'
4030/// '{' balanced-token-seq '}'
4031/// any token but '(', ')', '[', ']', '{', or '}'
4032bool Parser::ParseCXX11AttributeArgs(IdentifierInfo *AttrName,
4033 SourceLocation AttrNameLoc,
4034 ParsedAttributes &Attrs,
4035 SourceLocation *EndLoc,
4036 IdentifierInfo *ScopeName,
4037 SourceLocation ScopeLoc) {
4038 assert(Tok.is(tok::l_paren) && "Not a C++11 attribute argument list");
Aaron Ballman35f94212014-04-14 16:03:22 +00004039 SourceLocation LParenLoc = Tok.getLocation();
Aaron Ballman606093a2017-10-15 15:01:42 +00004040 const LangOptions &LO = getLangOpts();
Erich Keanee891aa92018-07-13 15:07:47 +00004041 ParsedAttr::Syntax Syntax =
4042 LO.CPlusPlus ? ParsedAttr::AS_CXX11 : ParsedAttr::AS_C2x;
Aaron Ballmanb8e20392014-03-31 17:32:39 +00004043
4044 // If the attribute isn't known, we will not attempt to parse any
4045 // arguments.
Aaron Ballman606093a2017-10-15 15:01:42 +00004046 if (!hasAttribute(LO.CPlusPlus ? AttrSyntax::CXX : AttrSyntax::C, ScopeName,
4047 AttrName, getTargetInfo(), getLangOpts())) {
Aaron Ballmanb8e20392014-03-31 17:32:39 +00004048 // Eat the left paren, then skip to the ending right paren.
4049 ConsumeParen();
4050 SkipUntil(tok::r_paren);
Aaron Ballmanc44c17422018-11-09 17:19:45 +00004051 return false;
4052 }
4053
4054 if (ScopeName && (ScopeName->isStr("gnu") || ScopeName->isStr("__gnu__"))) {
4055 // GNU-scoped attributes have some special cases to handle GNU-specific
4056 // behaviors.
4057 ParseGNUAttributeArgs(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
Aaron Ballman606093a2017-10-15 15:01:42 +00004058 ScopeLoc, Syntax, nullptr);
Alex Lorenzd5d27e12017-03-01 18:06:25 +00004059 return true;
4060 }
4061
4062 unsigned NumArgs;
4063 // Some Clang-scoped attributes have some special parsing behavior.
Aaron Ballmanc44c17422018-11-09 17:19:45 +00004064 if (ScopeName && (ScopeName->isStr("clang") || ScopeName->isStr("_Clang")))
4065 NumArgs = ParseClangAttributeArgs(AttrName, AttrNameLoc, Attrs, EndLoc,
4066 ScopeName, ScopeLoc, Syntax);
Alex Lorenzd5d27e12017-03-01 18:06:25 +00004067 else
4068 NumArgs =
Aaron Ballman35f94212014-04-14 16:03:22 +00004069 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc,
Aaron Ballman606093a2017-10-15 15:01:42 +00004070 ScopeName, ScopeLoc, Syntax);
Alex Lorenzd5d27e12017-03-01 18:06:25 +00004071
Erich Keanec480f302018-07-12 21:09:05 +00004072 if (!Attrs.empty() &&
4073 IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName)) {
Michael Krusedc5ce722018-08-03 01:21:16 +00004074 ParsedAttr &Attr = Attrs.back();
Alex Lorenzd5d27e12017-03-01 18:06:25 +00004075 // If the attribute is a standard or built-in attribute and we are
4076 // parsing an argument list, we need to determine whether this attribute
4077 // was allowed to have an argument list (such as [[deprecated]]), and how
4078 // many arguments were parsed (so we can diagnose on [[deprecated()]]).
Erich Keanec480f302018-07-12 21:09:05 +00004079 if (Attr.getMaxArgs() && !NumArgs) {
Alex Lorenzd5d27e12017-03-01 18:06:25 +00004080 // The attribute was allowed to have arguments, but none were provided
4081 // even though the attribute parsed successfully. This is an error.
4082 Diag(LParenLoc, diag::err_attribute_requires_arguments) << AttrName;
Erich Keanec480f302018-07-12 21:09:05 +00004083 Attr.setInvalid(true);
4084 } else if (!Attr.getMaxArgs()) {
Alex Lorenzd5d27e12017-03-01 18:06:25 +00004085 // The attribute parsed successfully, but was not allowed to have any
4086 // arguments. It doesn't matter whether any were provided -- the
4087 // presence of the argument list (even if empty) is diagnosed.
4088 Diag(LParenLoc, diag::err_cxx11_attribute_forbids_arguments)
4089 << AttrName
4090 << FixItHint::CreateRemoval(SourceRange(LParenLoc, *EndLoc));
Erich Keanec480f302018-07-12 21:09:05 +00004091 Attr.setInvalid(true);
Aaron Ballman35f94212014-04-14 16:03:22 +00004092 }
4093 }
Aaron Ballmanb8e20392014-03-31 17:32:39 +00004094 return true;
4095}
4096
Aaron Ballman606093a2017-10-15 15:01:42 +00004097/// ParseCXX11AttributeSpecifier - Parse a C++11 or C2x attribute-specifier.
Alexis Hunt96d5c762009-11-21 08:43:09 +00004098///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004099/// [C++11] attribute-specifier:
Alexis Hunt96d5c762009-11-21 08:43:09 +00004100/// '[' '[' attribute-list ']' ']'
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00004101/// alignment-specifier
Alexis Hunt96d5c762009-11-21 08:43:09 +00004102///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004103/// [C++11] attribute-list:
Alexis Hunt96d5c762009-11-21 08:43:09 +00004104/// attribute[opt]
4105/// attribute-list ',' attribute[opt]
Richard Smith3dff2512012-04-10 03:25:07 +00004106/// attribute '...'
4107/// attribute-list ',' attribute '...'
Alexis Hunt96d5c762009-11-21 08:43:09 +00004108///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004109/// [C++11] attribute:
Alexis Hunt96d5c762009-11-21 08:43:09 +00004110/// attribute-token attribute-argument-clause[opt]
4111///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004112/// [C++11] attribute-token:
Alexis Hunt96d5c762009-11-21 08:43:09 +00004113/// identifier
4114/// attribute-scoped-token
4115///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004116/// [C++11] attribute-scoped-token:
Alexis Hunt96d5c762009-11-21 08:43:09 +00004117/// attribute-namespace '::' identifier
4118///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004119/// [C++11] attribute-namespace:
Alexis Hunt96d5c762009-11-21 08:43:09 +00004120/// identifier
Richard Smith3dff2512012-04-10 03:25:07 +00004121void Parser::ParseCXX11AttributeSpecifier(ParsedAttributes &attrs,
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004122 SourceLocation *endLoc) {
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00004123 if (Tok.is(tok::kw_alignas)) {
Richard Smithf679b5b2011-10-14 20:48:27 +00004124 Diag(Tok.getLocation(), diag::warn_cxx98_compat_alignas);
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00004125 ParseAlignmentSpecifier(attrs, endLoc);
4126 return;
4127 }
4128
Aaron Ballman606093a2017-10-15 15:01:42 +00004129 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square) &&
4130 "Not a double square bracket attribute list");
Alexis Hunt96d5c762009-11-21 08:43:09 +00004131
Richard Smithf679b5b2011-10-14 20:48:27 +00004132 Diag(Tok.getLocation(), diag::warn_cxx98_compat_attribute);
4133
Alexis Hunt96d5c762009-11-21 08:43:09 +00004134 ConsumeBracket();
4135 ConsumeBracket();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004136
Richard Smithb7d7a042016-06-24 12:15:12 +00004137 SourceLocation CommonScopeLoc;
4138 IdentifierInfo *CommonScopeName = nullptr;
4139 if (Tok.is(tok::kw_using)) {
Aaron Ballmanc351fba2017-12-04 20:27:34 +00004140 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
Richard Smithb7d7a042016-06-24 12:15:12 +00004141 ? diag::warn_cxx14_compat_using_attribute_ns
4142 : diag::ext_using_attribute_ns);
4143 ConsumeToken();
4144
4145 CommonScopeName = TryParseCXX11AttributeIdentifier(CommonScopeLoc);
4146 if (!CommonScopeName) {
4147 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
4148 SkipUntil(tok::r_square, tok::colon, StopBeforeMatch);
4149 }
4150 if (!TryConsumeToken(tok::colon) && CommonScopeName)
4151 Diag(Tok.getLocation(), diag::err_expected) << tok::colon;
4152 }
4153
Richard Smith10876ef2013-01-17 01:30:42 +00004154 llvm::SmallDenseMap<IdentifierInfo*, SourceLocation, 4> SeenAttrs;
4155
Richard Smith3dff2512012-04-10 03:25:07 +00004156 while (Tok.isNot(tok::r_square)) {
Alexis Hunt96d5c762009-11-21 08:43:09 +00004157 // attribute not present
Alp Toker97650562014-01-10 11:19:30 +00004158 if (TryConsumeToken(tok::comma))
Alexis Hunt96d5c762009-11-21 08:43:09 +00004159 continue;
Alexis Hunt96d5c762009-11-21 08:43:09 +00004160
Richard Smith3dff2512012-04-10 03:25:07 +00004161 SourceLocation ScopeLoc, AttrLoc;
Craig Topper161e4db2014-05-21 06:02:52 +00004162 IdentifierInfo *ScopeName = nullptr, *AttrName = nullptr;
Richard Smith3dff2512012-04-10 03:25:07 +00004163
4164 AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
4165 if (!AttrName)
4166 // Break out to the "expected ']'" diagnostic.
4167 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004168
Alexis Hunt96d5c762009-11-21 08:43:09 +00004169 // scoped attribute
Alp Toker97650562014-01-10 11:19:30 +00004170 if (TryConsumeToken(tok::coloncolon)) {
Richard Smith3dff2512012-04-10 03:25:07 +00004171 ScopeName = AttrName;
4172 ScopeLoc = AttrLoc;
4173
4174 AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
4175 if (!AttrName) {
Alp Tokerec543272013-12-24 09:48:30 +00004176 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
Alexey Bataevee6507d2013-11-18 08:17:37 +00004177 SkipUntil(tok::r_square, tok::comma, StopAtSemi | StopBeforeMatch);
Alexis Hunt96d5c762009-11-21 08:43:09 +00004178 continue;
4179 }
Alexis Hunt96d5c762009-11-21 08:43:09 +00004180 }
4181
Richard Smithb7d7a042016-06-24 12:15:12 +00004182 if (CommonScopeName) {
4183 if (ScopeName) {
4184 Diag(ScopeLoc, diag::err_using_attribute_ns_conflict)
4185 << SourceRange(CommonScopeLoc);
4186 } else {
4187 ScopeName = CommonScopeName;
4188 ScopeLoc = CommonScopeLoc;
4189 }
4190 }
4191
Aaron Ballmanb8e20392014-03-31 17:32:39 +00004192 bool StandardAttr = IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName);
Alexis Hunt96d5c762009-11-21 08:43:09 +00004193 bool AttrParsed = false;
Alexis Hunt96d5c762009-11-21 08:43:09 +00004194
Richard Smith10876ef2013-01-17 01:30:42 +00004195 if (StandardAttr &&
4196 !SeenAttrs.insert(std::make_pair(AttrName, AttrLoc)).second)
4197 Diag(AttrLoc, diag::err_cxx11_attribute_repeated)
Aaron Ballmanb8e20392014-03-31 17:32:39 +00004198 << AttrName << SourceRange(SeenAttrs[AttrName]);
Richard Smith10876ef2013-01-17 01:30:42 +00004199
Michael Han23214e52012-10-03 01:56:22 +00004200 // Parse attribute arguments
Aaron Ballman35f94212014-04-14 16:03:22 +00004201 if (Tok.is(tok::l_paren))
Aaron Ballmanb8e20392014-03-31 17:32:39 +00004202 AttrParsed = ParseCXX11AttributeArgs(AttrName, AttrLoc, attrs, endLoc,
4203 ScopeName, ScopeLoc);
Michael Han23214e52012-10-03 01:56:22 +00004204
4205 if (!AttrParsed)
Aaron Ballman606093a2017-10-15 15:01:42 +00004206 attrs.addNew(
4207 AttrName,
4208 SourceRange(ScopeLoc.isValid() ? ScopeLoc : AttrLoc, AttrLoc),
4209 ScopeName, ScopeLoc, nullptr, 0,
Erich Keanee891aa92018-07-13 15:07:47 +00004210 getLangOpts().CPlusPlus ? ParsedAttr::AS_CXX11 : ParsedAttr::AS_C2x);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004211
Alp Toker97650562014-01-10 11:19:30 +00004212 if (TryConsumeToken(tok::ellipsis))
Michael Han23214e52012-10-03 01:56:22 +00004213 Diag(Tok, diag::err_cxx11_attribute_forbids_ellipsis)
Richard Trieub4025802018-03-28 04:16:13 +00004214 << AttrName;
Alexis Hunt96d5c762009-11-21 08:43:09 +00004215 }
4216
Alp Toker383d2c42014-01-01 03:08:43 +00004217 if (ExpectAndConsume(tok::r_square))
Alexey Bataevee6507d2013-11-18 08:17:37 +00004218 SkipUntil(tok::r_square);
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004219 if (endLoc)
4220 *endLoc = Tok.getLocation();
Alp Toker383d2c42014-01-01 03:08:43 +00004221 if (ExpectAndConsume(tok::r_square))
Alexey Bataevee6507d2013-11-18 08:17:37 +00004222 SkipUntil(tok::r_square);
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004223}
Alexis Hunt96d5c762009-11-21 08:43:09 +00004224
Aaron Ballman606093a2017-10-15 15:01:42 +00004225/// ParseCXX11Attributes - Parse a C++11 or C2x attribute-specifier-seq.
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004226///
4227/// attribute-specifier-seq:
4228/// attribute-specifier-seq[opt] attribute-specifier
Richard Smith3dff2512012-04-10 03:25:07 +00004229void Parser::ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004230 SourceLocation *endLoc) {
Aaron Ballman606093a2017-10-15 15:01:42 +00004231 assert(standardAttributesAllowed());
Richard Smith4cabd042013-02-22 09:15:49 +00004232
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004233 SourceLocation StartLoc = Tok.getLocation(), Loc;
4234 if (!endLoc)
4235 endLoc = &Loc;
4236
Douglas Gregor6f981002011-10-07 20:35:25 +00004237 do {
Richard Smith3dff2512012-04-10 03:25:07 +00004238 ParseCXX11AttributeSpecifier(attrs, endLoc);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004239 } while (isCXX11AttributeSpecifier());
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004240
4241 attrs.Range = SourceRange(StartLoc, *endLoc);
Alexis Hunt96d5c762009-11-21 08:43:09 +00004242}
4243
Richard Smithc2c8bb82013-10-15 01:34:54 +00004244void Parser::DiagnoseAndSkipCXX11Attributes() {
Richard Smithc2c8bb82013-10-15 01:34:54 +00004245 // Start and end location of an attribute or an attribute list.
4246 SourceLocation StartLoc = Tok.getLocation();
Richard Smith955bf012014-06-19 11:42:00 +00004247 SourceLocation EndLoc = SkipCXX11Attributes();
4248
4249 if (EndLoc.isValid()) {
4250 SourceRange Range(StartLoc, EndLoc);
4251 Diag(StartLoc, diag::err_attributes_not_allowed)
4252 << Range;
4253 }
4254}
4255
4256SourceLocation Parser::SkipCXX11Attributes() {
Richard Smithc2c8bb82013-10-15 01:34:54 +00004257 SourceLocation EndLoc;
4258
Richard Smith955bf012014-06-19 11:42:00 +00004259 if (!isCXX11AttributeSpecifier())
4260 return EndLoc;
4261
Richard Smithc2c8bb82013-10-15 01:34:54 +00004262 do {
4263 if (Tok.is(tok::l_square)) {
4264 BalancedDelimiterTracker T(*this, tok::l_square);
4265 T.consumeOpen();
4266 T.skipToEnd();
4267 EndLoc = T.getCloseLocation();
4268 } else {
4269 assert(Tok.is(tok::kw_alignas) && "not an attribute specifier");
4270 ConsumeToken();
4271 BalancedDelimiterTracker T(*this, tok::l_paren);
4272 if (!T.consumeOpen())
4273 T.skipToEnd();
4274 EndLoc = T.getCloseLocation();
4275 }
4276 } while (isCXX11AttributeSpecifier());
4277
Richard Smith955bf012014-06-19 11:42:00 +00004278 return EndLoc;
Richard Smithc2c8bb82013-10-15 01:34:54 +00004279}
4280
Nico Weber05e1dad2016-09-03 03:25:22 +00004281/// Parse uuid() attribute when it appears in a [] Microsoft attribute.
4282void Parser::ParseMicrosoftUuidAttributeArgs(ParsedAttributes &Attrs) {
4283 assert(Tok.is(tok::identifier) && "Not a Microsoft attribute list");
4284 IdentifierInfo *UuidIdent = Tok.getIdentifierInfo();
4285 assert(UuidIdent->getName() == "uuid" && "Not a Microsoft attribute list");
4286
4287 SourceLocation UuidLoc = Tok.getLocation();
4288 ConsumeToken();
4289
4290 // Ignore the left paren location for now.
4291 BalancedDelimiterTracker T(*this, tok::l_paren);
4292 if (T.consumeOpen()) {
4293 Diag(Tok, diag::err_expected) << tok::l_paren;
4294 return;
4295 }
4296
4297 ArgsVector ArgExprs;
4298 if (Tok.is(tok::string_literal)) {
4299 // Easy case: uuid("...") -- quoted string.
4300 ExprResult StringResult = ParseStringLiteralExpression();
4301 if (StringResult.isInvalid())
4302 return;
4303 ArgExprs.push_back(StringResult.get());
4304 } else {
4305 // something like uuid({000000A0-0000-0000-C000-000000000049}) -- no
4306 // quotes in the parens. Just append the spelling of all tokens encountered
4307 // until the closing paren.
4308
4309 SmallString<42> StrBuffer; // 2 "", 36 bytes UUID, 2 optional {}, 1 nul
4310 StrBuffer += "\"";
4311
4312 // Since none of C++'s keywords match [a-f]+, accepting just tok::l_brace,
4313 // tok::r_brace, tok::minus, tok::identifier (think C000) and
4314 // tok::numeric_constant (0000) should be enough. But the spelling of the
4315 // uuid argument is checked later anyways, so there's no harm in accepting
4316 // almost anything here.
4317 // cl is very strict about whitespace in this form and errors out if any
4318 // is present, so check the space flags on the tokens.
4319 SourceLocation StartLoc = Tok.getLocation();
4320 while (Tok.isNot(tok::r_paren)) {
4321 if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
4322 Diag(Tok, diag::err_attribute_uuid_malformed_guid);
4323 SkipUntil(tok::r_paren, StopAtSemi);
4324 return;
4325 }
4326 SmallString<16> SpellingBuffer;
4327 SpellingBuffer.resize(Tok.getLength() + 1);
4328 bool Invalid = false;
4329 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
4330 if (Invalid) {
4331 SkipUntil(tok::r_paren, StopAtSemi);
4332 return;
4333 }
4334 StrBuffer += TokSpelling;
4335 ConsumeAnyToken();
4336 }
4337 StrBuffer += "\"";
4338
4339 if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
4340 Diag(Tok, diag::err_attribute_uuid_malformed_guid);
4341 ConsumeParen();
4342 return;
4343 }
4344
4345 // Pretend the user wrote the appropriate string literal here.
4346 // ActOnStringLiteral() copies the string data into the literal, so it's
4347 // ok that the Token points to StrBuffer.
4348 Token Toks[1];
4349 Toks[0].startToken();
4350 Toks[0].setKind(tok::string_literal);
4351 Toks[0].setLocation(StartLoc);
4352 Toks[0].setLiteralData(StrBuffer.data());
4353 Toks[0].setLength(StrBuffer.size());
4354 StringLiteral *UuidString =
4355 cast<StringLiteral>(Actions.ActOnStringLiteral(Toks, nullptr).get());
4356 ArgExprs.push_back(UuidString);
4357 }
4358
4359 if (!T.consumeClose()) {
Nico Weber05e1dad2016-09-03 03:25:22 +00004360 Attrs.addNew(UuidIdent, SourceRange(UuidLoc, T.getCloseLocation()), nullptr,
4361 SourceLocation(), ArgExprs.data(), ArgExprs.size(),
Erich Keanee891aa92018-07-13 15:07:47 +00004362 ParsedAttr::AS_Microsoft);
Nico Weber05e1dad2016-09-03 03:25:22 +00004363 }
4364}
4365
David Majnemere4752e752015-07-08 05:55:00 +00004366/// ParseMicrosoftAttributes - Parse Microsoft attributes [Attr]
Francois Pichetc2bc5ac2010-10-11 12:59:39 +00004367///
4368/// [MS] ms-attribute:
4369/// '[' token-seq ']'
4370///
4371/// [MS] ms-attribute-seq:
4372/// ms-attribute[opt]
4373/// ms-attribute ms-attribute-seq
John McCall53fa7142010-12-24 02:08:15 +00004374void Parser::ParseMicrosoftAttributes(ParsedAttributes &attrs,
4375 SourceLocation *endLoc) {
Francois Pichetc2bc5ac2010-10-11 12:59:39 +00004376 assert(Tok.is(tok::l_square) && "Not a Microsoft attribute list");
4377
Saleem Abdulrasool425efcf2015-06-15 20:57:04 +00004378 do {
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004379 // FIXME: If this is actually a C++11 attribute, parse it as one.
Saleem Abdulrasool425efcf2015-06-15 20:57:04 +00004380 BalancedDelimiterTracker T(*this, tok::l_square);
4381 T.consumeOpen();
Nico Weber05e1dad2016-09-03 03:25:22 +00004382
4383 // Skip most ms attributes except for a whitelist.
4384 while (true) {
4385 SkipUntil(tok::r_square, tok::identifier, StopAtSemi | StopBeforeMatch);
4386 if (Tok.isNot(tok::identifier)) // ']', but also eof
4387 break;
4388 if (Tok.getIdentifierInfo()->getName() == "uuid")
4389 ParseMicrosoftUuidAttributeArgs(attrs);
4390 else
4391 ConsumeToken();
4392 }
4393
Saleem Abdulrasool425efcf2015-06-15 20:57:04 +00004394 T.consumeClose();
4395 if (endLoc)
4396 *endLoc = T.getCloseLocation();
4397 } while (Tok.is(tok::l_square));
Francois Pichetc2bc5ac2010-10-11 12:59:39 +00004398}
Francois Pichet8f981d52011-05-25 10:19:49 +00004399
Erich Keanec480f302018-07-12 21:09:05 +00004400void Parser::ParseMicrosoftIfExistsClassDeclaration(
4401 DeclSpec::TST TagType, ParsedAttributes &AccessAttrs,
4402 AccessSpecifier &CurAS) {
Douglas Gregor43edb322011-10-24 22:31:10 +00004403 IfExistsCondition Result;
Francois Pichet8f981d52011-05-25 10:19:49 +00004404 if (ParseMicrosoftIfExistsCondition(Result))
4405 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00004406
Douglas Gregor43edb322011-10-24 22:31:10 +00004407 BalancedDelimiterTracker Braces(*this, tok::l_brace);
4408 if (Braces.consumeOpen()) {
Alp Tokerec543272013-12-24 09:48:30 +00004409 Diag(Tok, diag::err_expected) << tok::l_brace;
Francois Pichet8f981d52011-05-25 10:19:49 +00004410 return;
4411 }
Francois Pichet8f981d52011-05-25 10:19:49 +00004412
Douglas Gregor43edb322011-10-24 22:31:10 +00004413 switch (Result.Behavior) {
4414 case IEB_Parse:
4415 // Parse the declarations below.
4416 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00004417
Douglas Gregor43edb322011-10-24 22:31:10 +00004418 case IEB_Dependent:
4419 Diag(Result.KeywordLoc, diag::warn_microsoft_dependent_exists)
4420 << Result.IsIfExists;
4421 // Fall through to skip.
Galina Kistanovad819d5b2017-06-01 21:19:06 +00004422 LLVM_FALLTHROUGH;
Fangrui Song6907ce22018-07-30 19:24:48 +00004423
Douglas Gregor43edb322011-10-24 22:31:10 +00004424 case IEB_Skip:
4425 Braces.skipToEnd();
Francois Pichet8f981d52011-05-25 10:19:49 +00004426 return;
4427 }
4428
Richard Smith34f30512013-11-23 04:06:09 +00004429 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
Francois Pichet8f981d52011-05-25 10:19:49 +00004430 // __if_exists, __if_not_exists can nest.
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00004431 if (Tok.isOneOf(tok::kw___if_exists, tok::kw___if_not_exists)) {
Serge Pavlov0c503192019-08-01 11:46:28 +00004432 ParseMicrosoftIfExistsClassDeclaration(TagType,
Erich Keanec480f302018-07-12 21:09:05 +00004433 AccessAttrs, CurAS);
Francois Pichet8f981d52011-05-25 10:19:49 +00004434 continue;
4435 }
4436
4437 // Check for extraneous top-level semicolon.
4438 if (Tok.is(tok::semi)) {
Richard Smith87f5dc52012-07-23 05:45:25 +00004439 ConsumeExtraSemi(InsideStruct, TagType);
Francois Pichet8f981d52011-05-25 10:19:49 +00004440 continue;
4441 }
4442
4443 AccessSpecifier AS = getAccessSpecifierIfPresent();
4444 if (AS != AS_none) {
4445 // Current token is a C++ access specifier.
4446 CurAS = AS;
4447 SourceLocation ASLoc = Tok.getLocation();
4448 ConsumeToken();
4449 if (Tok.is(tok::colon))
Erich Keanec480f302018-07-12 21:09:05 +00004450 Actions.ActOnAccessSpecifier(AS, ASLoc, Tok.getLocation(),
4451 ParsedAttributesView{});
Francois Pichet8f981d52011-05-25 10:19:49 +00004452 else
Alp Toker35d87032013-12-30 23:29:50 +00004453 Diag(Tok, diag::err_expected) << tok::colon;
Francois Pichet8f981d52011-05-25 10:19:49 +00004454 ConsumeToken();
4455 continue;
4456 }
4457
4458 // Parse all the comma separated declarators.
Erich Keanec480f302018-07-12 21:09:05 +00004459 ParseCXXClassMemberDeclaration(CurAS, AccessAttrs);
Francois Pichet8f981d52011-05-25 10:19:49 +00004460 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004461
Douglas Gregor43edb322011-10-24 22:31:10 +00004462 Braces.consumeClose();
Francois Pichet8f981d52011-05-25 10:19:49 +00004463}