blob: 528e903ae761669ab30e8f2689ac98aac71587f3 [file] [log] [blame]
Hans Wennborgdcfba332015-10-06 23:40:43 +00001//===--- ParseDeclCXX.cpp - C++ Declaration Parsing -------------*- C++ -*-===//
Chris Lattnera5235172007-08-25 06:57:03 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnera5235172007-08-25 06:57:03 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the C++ Declaration portions of the Parser interfaces.
11//
12//===----------------------------------------------------------------------===//
13
Douglas Gregor423984d2008-04-14 00:13:42 +000014#include "clang/Parse/Parser.h"
Erik Verbruggen888d52a2014-01-15 09:15:43 +000015#include "clang/AST/ASTContext.h"
Chandler Carruth757fcd62014-03-04 10:05:20 +000016#include "clang/AST/DeclTemplate.h"
Jordan Rose1e879d82018-03-23 00:07:18 +000017#include "clang/AST/PrettyDeclStackTrace.h"
Aaron Ballmanb8e20392014-03-31 17:32:39 +000018#include "clang/Basic/Attributes.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000019#include "clang/Basic/CharInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/Basic/OperatorKinds.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000021#include "clang/Basic/TargetInfo.h"
Chris Lattner60f36222009-01-29 05:15:15 +000022#include "clang/Parse/ParseDiagnostic.h"
Vassil Vassilev11ad3392017-03-23 15:11:07 +000023#include "clang/Parse/RAIIObjectsForParser.h"
John McCall8b0666c2010-08-20 18:27:03 +000024#include "clang/Sema/DeclSpec.h"
John McCall8b0666c2010-08-20 18:27:03 +000025#include "clang/Sema/ParsedTemplate.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "clang/Sema/Scope.h"
John McCalldb632ac2012-09-25 07:32:39 +000027#include "clang/Sema/SemaDiagnostic.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000028#include "llvm/ADT/SmallString.h"
Hans Wennborgdcfba332015-10-06 23:40:43 +000029
Chris Lattnera5235172007-08-25 06:57:03 +000030using namespace clang;
31
32/// ParseNamespace - We know that the current token is a namespace keyword. This
Sebastian Redl67667942010-08-27 23:12:46 +000033/// may either be a top level namespace or a block-level namespace alias. If
34/// there was an inline keyword, it has already been parsed.
Chris Lattnera5235172007-08-25 06:57:03 +000035///
Erich Keane53f391d2018-11-12 17:19:48 +000036/// namespace-definition: [C++: namespace.def]
Chris Lattnera5235172007-08-25 06:57:03 +000037/// named-namespace-definition
38/// unnamed-namespace-definition
Erich Keane53f391d2018-11-12 17:19:48 +000039/// nested-namespace-definition
40///
41/// named-namespace-definition:
Erich Keanede6480a32018-11-13 15:48:08 +000042/// 'inline'[opt] 'namespace' attributes[opt] identifier '{'
43/// namespace-body '}'
Chris Lattnera5235172007-08-25 06:57:03 +000044///
45/// unnamed-namespace-definition:
Sebastian Redl67667942010-08-27 23:12:46 +000046/// 'inline'[opt] 'namespace' attributes[opt] '{' namespace-body '}'
Chris Lattnera5235172007-08-25 06:57:03 +000047///
Erich Keane53f391d2018-11-12 17:19:48 +000048/// nested-namespace-definition:
Erich Keanede6480a32018-11-13 15:48:08 +000049/// 'namespace' enclosing-namespace-specifier '::' 'inline'[opt]
50/// identifier '{' namespace-body '}'
Chris Lattnera5235172007-08-25 06:57:03 +000051///
Erich Keane53f391d2018-11-12 17:19:48 +000052/// enclosing-namespace-specifier:
53/// identifier
54/// enclosing-namespace-specifier '::' 'inline'[opt] identifier
Mike Stump11289f42009-09-09 15:08:12 +000055///
Chris Lattnera5235172007-08-25 06:57:03 +000056/// namespace-alias-definition: [C++ 7.3.2: namespace.alias]
57/// 'namespace' identifier '=' qualified-namespace-specifier ';'
58///
Faisal Vali421b2d12017-12-29 05:41:00 +000059Parser::DeclGroupPtrTy Parser::ParseNamespace(DeclaratorContext Context,
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +000060 SourceLocation &DeclEnd,
61 SourceLocation InlineLoc) {
Chris Lattner76c72282007-10-09 17:33:22 +000062 assert(Tok.is(tok::kw_namespace) && "Not a namespace!");
Chris Lattnera5235172007-08-25 06:57:03 +000063 SourceLocation NamespaceLoc = ConsumeToken(); // eat the 'namespace'.
Fariborz Jahanian4bf82622011-08-22 17:59:19 +000064 ObjCDeclContextSwitch ObjCDC(*this);
Fangrui Song6907ce22018-07-30 19:24:48 +000065
Douglas Gregor7e90c6d2009-09-18 19:03:04 +000066 if (Tok.is(tok::code_completion)) {
Douglas Gregor0be31a22010-07-02 17:43:08 +000067 Actions.CodeCompleteNamespaceDecl(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +000068 cutOffParsing();
David Blaikie0403cb12016-01-15 23:43:25 +000069 return nullptr;
Douglas Gregor7e90c6d2009-09-18 19:03:04 +000070 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000071
Chris Lattnera5235172007-08-25 06:57:03 +000072 SourceLocation IdentLoc;
Craig Topper161e4db2014-05-21 06:02:52 +000073 IdentifierInfo *Ident = nullptr;
Erich Keane53f391d2018-11-12 17:19:48 +000074 InnerNamespaceInfoList ExtraNSs;
75 SourceLocation FirstNestedInlineLoc;
Douglas Gregor6b6bba42009-06-17 19:49:00 +000076
Aaron Ballman730476b2014-11-08 15:33:35 +000077 ParsedAttributesWithRange attrs(AttrFactory);
78 SourceLocation attrLoc;
79 if (getLangOpts().CPlusPlus11 && isCXX11AttributeSpecifier()) {
Aaron Ballmanc351fba2017-12-04 20:27:34 +000080 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
Richard Smith40e202f2017-10-14 00:56:24 +000081 ? diag::warn_cxx14_compat_ns_enum_attribute
82 : diag::ext_ns_enum_attribute)
83 << 0 /*namespace*/;
Aaron Ballman730476b2014-11-08 15:33:35 +000084 attrLoc = Tok.getLocation();
85 ParseCXX11Attributes(attrs);
86 }
Mike Stump11289f42009-09-09 15:08:12 +000087
Chris Lattner76c72282007-10-09 17:33:22 +000088 if (Tok.is(tok::identifier)) {
Chris Lattnera5235172007-08-25 06:57:03 +000089 Ident = Tok.getIdentifierInfo();
90 IdentLoc = ConsumeToken(); // eat the identifier.
Erich Keane53f391d2018-11-12 17:19:48 +000091 while (Tok.is(tok::coloncolon) &&
92 (NextToken().is(tok::identifier) ||
93 (NextToken().is(tok::kw_inline) &&
94 GetLookAheadToken(2).is(tok::identifier)))) {
95
96 InnerNamespaceInfo Info;
97 Info.NamespaceLoc = ConsumeToken();
98
99 if (Tok.is(tok::kw_inline)) {
100 Info.InlineLoc = ConsumeToken();
101 if (FirstNestedInlineLoc.isInvalid())
102 FirstNestedInlineLoc = Info.InlineLoc;
103 }
104
105 Info.Ident = Tok.getIdentifierInfo();
106 Info.IdentLoc = ConsumeToken();
107
108 ExtraNSs.push_back(Info);
Richard Trieu61384cb2011-05-26 20:11:09 +0000109 }
Chris Lattnera5235172007-08-25 06:57:03 +0000110 }
Mike Stump11289f42009-09-09 15:08:12 +0000111
Aaron Ballmanc0ae7df2014-11-08 17:07:15 +0000112 // A nested namespace definition cannot have attributes.
Erich Keane53f391d2018-11-12 17:19:48 +0000113 if (!ExtraNSs.empty() && attrLoc.isValid())
Aaron Ballmanc0ae7df2014-11-08 17:07:15 +0000114 Diag(attrLoc, diag::err_unexpected_nested_namespace_attribute);
115
Chris Lattnera5235172007-08-25 06:57:03 +0000116 // Read label attributes, if present.
Douglas Gregor6b6bba42009-06-17 19:49:00 +0000117 if (Tok.is(tok::kw___attribute)) {
Aaron Ballman730476b2014-11-08 15:33:35 +0000118 attrLoc = Tok.getLocation();
John McCall53fa7142010-12-24 02:08:15 +0000119 ParseGNUAttributes(attrs);
Douglas Gregor6b6bba42009-06-17 19:49:00 +0000120 }
Mike Stump11289f42009-09-09 15:08:12 +0000121
Douglas Gregor6b6bba42009-06-17 19:49:00 +0000122 if (Tok.is(tok::equal)) {
Craig Topper161e4db2014-05-21 06:02:52 +0000123 if (!Ident) {
Alp Tokerec543272013-12-24 09:48:30 +0000124 Diag(Tok, diag::err_expected) << tok::identifier;
Nico Weber729f1e22012-10-27 23:44:27 +0000125 // Skip to end of the definition and eat the ';'.
126 SkipUntil(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +0000127 return nullptr;
Nico Weber729f1e22012-10-27 23:44:27 +0000128 }
Aaron Ballman730476b2014-11-08 15:33:35 +0000129 if (attrLoc.isValid())
130 Diag(attrLoc, diag::err_unexpected_namespace_attributes_alias);
Sebastian Redl67667942010-08-27 23:12:46 +0000131 if (InlineLoc.isValid())
132 Diag(InlineLoc, diag::err_inline_namespace_alias)
133 << FixItHint::CreateRemoval(InlineLoc);
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +0000134 Decl *NSAlias = ParseNamespaceAlias(NamespaceLoc, IdentLoc, Ident, DeclEnd);
135 return Actions.ConvertDeclToDeclGroup(NSAlias);
136}
Mike Stump11289f42009-09-09 15:08:12 +0000137
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000138 BalancedDelimiterTracker T(*this, tok::l_brace);
139 if (T.consumeOpen()) {
Alp Tokerec543272013-12-24 09:48:30 +0000140 if (Ident)
141 Diag(Tok, diag::err_expected) << tok::l_brace;
142 else
143 Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace;
David Blaikie0403cb12016-01-15 23:43:25 +0000144 return nullptr;
Chris Lattnera5235172007-08-25 06:57:03 +0000145 }
Mike Stump11289f42009-09-09 15:08:12 +0000146
Fangrui Song6907ce22018-07-30 19:24:48 +0000147 if (getCurScope()->isClassScope() || getCurScope()->isTemplateParamScope() ||
148 getCurScope()->isInObjcMethodScope() || getCurScope()->getBlockParent() ||
Douglas Gregor0be31a22010-07-02 17:43:08 +0000149 getCurScope()->getFnParent()) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000150 Diag(T.getOpenLocation(), diag::err_namespace_nonnamespace_scope);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000151 SkipUntil(tok::r_brace);
David Blaikie0403cb12016-01-15 23:43:25 +0000152 return nullptr;
Douglas Gregor05cfc292010-05-14 05:08:22 +0000153 }
154
Erich Keane53f391d2018-11-12 17:19:48 +0000155 if (ExtraNSs.empty()) {
Richard Smith13307f52014-11-08 05:37:34 +0000156 // Normal namespace definition, not a nested-namespace-definition.
157 } else if (InlineLoc.isValid()) {
158 Diag(InlineLoc, diag::err_inline_nested_namespace_definition);
Erich Keane53f391d2018-11-12 17:19:48 +0000159 } else if (getLangOpts().CPlusPlus2a) {
160 Diag(ExtraNSs[0].NamespaceLoc,
Richard Smith13307f52014-11-08 05:37:34 +0000161 diag::warn_cxx14_compat_nested_namespace_definition);
Erich Keane53f391d2018-11-12 17:19:48 +0000162 if (FirstNestedInlineLoc.isValid())
163 Diag(FirstNestedInlineLoc,
164 diag::warn_cxx17_compat_inline_nested_namespace_definition);
165 } else if (getLangOpts().CPlusPlus17) {
166 Diag(ExtraNSs[0].NamespaceLoc,
167 diag::warn_cxx14_compat_nested_namespace_definition);
168 if (FirstNestedInlineLoc.isValid())
169 Diag(FirstNestedInlineLoc, diag::ext_inline_nested_namespace_definition);
Richard Smith13307f52014-11-08 05:37:34 +0000170 } else {
Richard Trieu61384cb2011-05-26 20:11:09 +0000171 TentativeParsingAction TPA(*this);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000172 SkipUntil(tok::r_brace, StopBeforeMatch);
Richard Trieu61384cb2011-05-26 20:11:09 +0000173 Token rBraceToken = Tok;
174 TPA.Revert();
175
176 if (!rBraceToken.is(tok::r_brace)) {
Erich Keane53f391d2018-11-12 17:19:48 +0000177 Diag(ExtraNSs[0].NamespaceLoc, diag::ext_nested_namespace_definition)
178 << SourceRange(ExtraNSs.front().NamespaceLoc,
179 ExtraNSs.back().IdentLoc);
Richard Trieu61384cb2011-05-26 20:11:09 +0000180 } else {
Benjamin Kramerf546f412011-05-26 21:32:30 +0000181 std::string NamespaceFix;
Erich Keane53f391d2018-11-12 17:19:48 +0000182 for (const auto &ExtraNS : ExtraNSs) {
Erich Keanea946acd2018-11-12 21:08:41 +0000183 NamespaceFix += " { ";
184 if (ExtraNS.InlineLoc.isValid())
185 NamespaceFix += "inline ";
186 NamespaceFix += "namespace ";
Erich Keane53f391d2018-11-12 17:19:48 +0000187 NamespaceFix += ExtraNS.Ident->getName();
Richard Trieu61384cb2011-05-26 20:11:09 +0000188 }
Benjamin Kramerf546f412011-05-26 21:32:30 +0000189
Richard Trieu61384cb2011-05-26 20:11:09 +0000190 std::string RBraces;
Erich Keane53f391d2018-11-12 17:19:48 +0000191 for (unsigned i = 0, e = ExtraNSs.size(); i != e; ++i)
Richard Trieu61384cb2011-05-26 20:11:09 +0000192 RBraces += "} ";
Benjamin Kramerf546f412011-05-26 21:32:30 +0000193
Erich Keane53f391d2018-11-12 17:19:48 +0000194 Diag(ExtraNSs[0].NamespaceLoc, diag::ext_nested_namespace_definition)
195 << FixItHint::CreateReplacement(
196 SourceRange(ExtraNSs.front().NamespaceLoc,
197 ExtraNSs.back().IdentLoc),
198 NamespaceFix)
Richard Trieu61384cb2011-05-26 20:11:09 +0000199 << FixItHint::CreateInsertion(rBraceToken.getLocation(), RBraces);
200 }
Erich Keane53f391d2018-11-12 17:19:48 +0000201
202 // Warn about nested inline namespaces.
203 if (FirstNestedInlineLoc.isValid())
204 Diag(FirstNestedInlineLoc, diag::ext_inline_nested_namespace_definition);
Richard Trieu61384cb2011-05-26 20:11:09 +0000205 }
206
Sebastian Redl5a5f2c72010-08-31 00:36:45 +0000207 // If we're still good, complain about inline namespaces in non-C++0x now.
Richard Smith5d164bc2011-10-15 05:09:34 +0000208 if (InlineLoc.isValid())
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000209 Diag(InlineLoc, getLangOpts().CPlusPlus11 ?
Richard Smith5d164bc2011-10-15 05:09:34 +0000210 diag::warn_cxx98_compat_inline_namespace : diag::ext_inline_namespace);
Sebastian Redl5a5f2c72010-08-31 00:36:45 +0000211
Chris Lattner4de55aa2009-03-29 14:02:43 +0000212 // Enter a scope for the namespace.
213 ParseScope NamespaceScope(this, Scope::DeclScope);
214
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +0000215 UsingDirectiveDecl *ImplicitUsingDirectiveDecl = nullptr;
Erich Keanec480f302018-07-12 21:09:05 +0000216 Decl *NamespcDecl = Actions.ActOnStartNamespaceDef(
217 getCurScope(), InlineLoc, NamespaceLoc, IdentLoc, Ident,
218 T.getOpenLocation(), attrs, ImplicitUsingDirectiveDecl);
Chris Lattner4de55aa2009-03-29 14:02:43 +0000219
Jordan Rose1e879d82018-03-23 00:07:18 +0000220 PrettyDeclStackTraceEntry CrashInfo(Actions.Context, NamespcDecl,
221 NamespaceLoc, "parsing namespace");
Mike Stump11289f42009-09-09 15:08:12 +0000222
Fangrui Song6907ce22018-07-30 19:24:48 +0000223 // Parse the contents of the namespace. This includes parsing recovery on
Richard Trieu61384cb2011-05-26 20:11:09 +0000224 // any improperly nested namespaces.
Erich Keane53f391d2018-11-12 17:19:48 +0000225 ParseInnerNamespace(ExtraNSs, 0, InlineLoc, attrs, T);
Mike Stump11289f42009-09-09 15:08:12 +0000226
Chris Lattner4de55aa2009-03-29 14:02:43 +0000227 // Leave the namespace scope.
228 NamespaceScope.Exit();
229
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000230 DeclEnd = T.getCloseLocation();
231 Actions.ActOnFinishNamespaceDef(NamespcDecl, DeclEnd);
Fangrui Song6907ce22018-07-30 19:24:48 +0000232
233 return Actions.ConvertDeclToDeclGroup(NamespcDecl,
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +0000234 ImplicitUsingDirectiveDecl);
Chris Lattnera5235172007-08-25 06:57:03 +0000235}
Chris Lattner38376f12008-01-12 07:05:38 +0000236
Richard Trieu61384cb2011-05-26 20:11:09 +0000237/// ParseInnerNamespace - Parse the contents of a namespace.
Erich Keane53f391d2018-11-12 17:19:48 +0000238void Parser::ParseInnerNamespace(const InnerNamespaceInfoList &InnerNSs,
Richard Smith13307f52014-11-08 05:37:34 +0000239 unsigned int index, SourceLocation &InlineLoc,
240 ParsedAttributes &attrs,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000241 BalancedDelimiterTracker &Tracker) {
Erich Keane53f391d2018-11-12 17:19:48 +0000242 if (index == InnerNSs.size()) {
Richard Smith752ada82015-11-17 23:32:01 +0000243 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
244 Tok.isNot(tok::eof)) {
Richard Trieu61384cb2011-05-26 20:11:09 +0000245 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +0000246 MaybeParseCXX11Attributes(attrs);
Richard Trieu61384cb2011-05-26 20:11:09 +0000247 ParseExternalDeclaration(attrs);
248 }
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000249
250 // The caller is what called check -- we are simply calling
251 // the close for it.
252 Tracker.consumeClose();
Richard Trieu61384cb2011-05-26 20:11:09 +0000253
254 return;
255 }
256
Richard Smith13307f52014-11-08 05:37:34 +0000257 // Handle a nested namespace definition.
258 // FIXME: Preserve the source information through to the AST rather than
259 // desugaring it here.
Richard Trieu61384cb2011-05-26 20:11:09 +0000260 ParseScope NamespaceScope(this, Scope::DeclScope);
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +0000261 UsingDirectiveDecl *ImplicitUsingDirectiveDecl = nullptr;
Erich Keanec480f302018-07-12 21:09:05 +0000262 Decl *NamespcDecl = Actions.ActOnStartNamespaceDef(
Erich Keane53f391d2018-11-12 17:19:48 +0000263 getCurScope(), InnerNSs[index].InlineLoc, InnerNSs[index].NamespaceLoc,
264 InnerNSs[index].IdentLoc, InnerNSs[index].Ident,
265 Tracker.getOpenLocation(), attrs, ImplicitUsingDirectiveDecl);
Fangrui Song6907ce22018-07-30 19:24:48 +0000266 assert(!ImplicitUsingDirectiveDecl &&
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +0000267 "nested namespace definition cannot define anonymous namespace");
Richard Trieu61384cb2011-05-26 20:11:09 +0000268
Erich Keanede6480a32018-11-13 15:48:08 +0000269 ParseInnerNamespace(InnerNSs, ++index, InlineLoc, attrs, Tracker);
Richard Trieu61384cb2011-05-26 20:11:09 +0000270
271 NamespaceScope.Exit();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000272 Actions.ActOnFinishNamespaceDef(NamespcDecl, Tracker.getCloseLocation());
Richard Trieu61384cb2011-05-26 20:11:09 +0000273}
274
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000275/// ParseNamespaceAlias - Parse the part after the '=' in a namespace
276/// alias definition.
277///
John McCall48871652010-08-21 09:40:31 +0000278Decl *Parser::ParseNamespaceAlias(SourceLocation NamespaceLoc,
John McCall084e83d2011-03-24 11:26:52 +0000279 SourceLocation AliasLoc,
280 IdentifierInfo *Alias,
281 SourceLocation &DeclEnd) {
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000282 assert(Tok.is(tok::equal) && "Not equal token");
Mike Stump11289f42009-09-09 15:08:12 +0000283
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000284 ConsumeToken(); // eat the '='.
Mike Stump11289f42009-09-09 15:08:12 +0000285
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000286 if (Tok.is(tok::code_completion)) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000287 Actions.CodeCompleteNamespaceAliasDecl(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000288 cutOffParsing();
Craig Topper161e4db2014-05-21 06:02:52 +0000289 return nullptr;
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000290 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000291
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000292 CXXScopeSpec SS;
293 // Parse (optional) nested-name-specifier.
Matthias Gehredc01bb42017-03-17 21:41:20 +0000294 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false,
295 /*MayBePseudoDestructor=*/nullptr,
296 /*IsTypename=*/false,
297 /*LastII=*/nullptr,
298 /*OnlyNamespace=*/true);
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000299
Matthias Gehredc01bb42017-03-17 21:41:20 +0000300 if (Tok.isNot(tok::identifier)) {
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000301 Diag(Tok, diag::err_expected_namespace_name);
302 // Skip to end of the definition and eat the ';'.
303 SkipUntil(tok::semi);
Craig Topper161e4db2014-05-21 06:02:52 +0000304 return nullptr;
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000305 }
306
Matthias Gehredc01bb42017-03-17 21:41:20 +0000307 if (SS.isInvalid()) {
308 // Diagnostics have been emitted in ParseOptionalCXXScopeSpecifier.
309 // Skip to end of the definition and eat the ';'.
310 SkipUntil(tok::semi);
311 return nullptr;
312 }
313
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000314 // Parse identifier.
Anders Carlsson47952ae2009-03-28 22:53:22 +0000315 IdentifierInfo *Ident = Tok.getIdentifierInfo();
316 SourceLocation IdentLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000317
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000318 // Eat the ';'.
Chris Lattner49836b42009-04-02 04:16:50 +0000319 DeclEnd = Tok.getLocation();
Alp Toker383d2c42014-01-01 03:08:43 +0000320 if (ExpectAndConsume(tok::semi, diag::err_expected_semi_after_namespace_name))
321 SkipUntil(tok::semi);
Mike Stump11289f42009-09-09 15:08:12 +0000322
Craig Topperff354282015-11-14 18:16:00 +0000323 return Actions.ActOnNamespaceAliasDef(getCurScope(), NamespaceLoc, AliasLoc,
324 Alias, SS, IdentLoc, Ident);
Anders Carlsson1894f0d42009-03-28 04:07:16 +0000325}
326
Chris Lattner38376f12008-01-12 07:05:38 +0000327/// ParseLinkage - We know that the current token is a string_literal
328/// and just before that, that extern was seen.
329///
330/// linkage-specification: [C++ 7.5p2: dcl.link]
331/// 'extern' string-literal '{' declaration-seq[opt] '}'
332/// 'extern' string-literal declaration
333///
Faisal Vali421b2d12017-12-29 05:41:00 +0000334Decl *Parser::ParseLinkage(ParsingDeclSpec &DS, DeclaratorContext Context) {
Richard Smith4ee696d2014-02-17 23:25:27 +0000335 assert(isTokenStringLiteral() && "Not a string literal!");
336 ExprResult Lang = ParseStringLiteralExpression(false);
Chris Lattner38376f12008-01-12 07:05:38 +0000337
Douglas Gregor07665a62009-01-05 19:45:36 +0000338 ParseScope LinkageScope(this, Scope::DeclScope);
Richard Smith4ee696d2014-02-17 23:25:27 +0000339 Decl *LinkageSpec =
340 Lang.isInvalid()
Craig Topper161e4db2014-05-21 06:02:52 +0000341 ? nullptr
Richard Smith4ee696d2014-02-17 23:25:27 +0000342 : Actions.ActOnStartLinkageSpecification(
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000343 getCurScope(), DS.getSourceRange().getBegin(), Lang.get(),
Richard Smith4ee696d2014-02-17 23:25:27 +0000344 Tok.is(tok::l_brace) ? Tok.getLocation() : SourceLocation());
Douglas Gregor07665a62009-01-05 19:45:36 +0000345
John McCall084e83d2011-03-24 11:26:52 +0000346 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +0000347 MaybeParseCXX11Attributes(attrs);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000348
Douglas Gregor07665a62009-01-05 19:45:36 +0000349 if (Tok.isNot(tok::l_brace)) {
Abramo Bagnara4d423992011-05-01 16:25:54 +0000350 // Reset the source range in DS, as the leading "extern"
351 // does not really belong to the inner declaration ...
352 DS.SetRangeStart(SourceLocation());
353 DS.SetRangeEnd(SourceLocation());
354 // ... but anyway remember that such an "extern" was seen.
Abramo Bagnaraed5b6892010-07-30 16:47:02 +0000355 DS.setExternInLinkageSpec(true);
John McCall53fa7142010-12-24 02:08:15 +0000356 ParseExternalDeclaration(attrs, &DS);
Richard Smith4ee696d2014-02-17 23:25:27 +0000357 return LinkageSpec ? Actions.ActOnFinishLinkageSpecification(
358 getCurScope(), LinkageSpec, SourceLocation())
Craig Topper161e4db2014-05-21 06:02:52 +0000359 : nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000360 }
Douglas Gregor29ff7d02008-12-16 22:23:02 +0000361
Douglas Gregorb65a9132010-02-07 08:38:28 +0000362 DS.abort();
363
John McCall53fa7142010-12-24 02:08:15 +0000364 ProhibitAttributes(attrs);
Alexis Hunt96d5c762009-11-21 08:43:09 +0000365
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000366 BalancedDelimiterTracker T(*this, tok::l_brace);
367 T.consumeOpen();
Richard Smith77944862014-03-02 05:58:18 +0000368
369 unsigned NestedModules = 0;
370 while (true) {
371 switch (Tok.getKind()) {
372 case tok::annot_module_begin:
373 ++NestedModules;
374 ParseTopLevelDecl();
375 continue;
376
377 case tok::annot_module_end:
378 if (!NestedModules)
379 break;
380 --NestedModules;
381 ParseTopLevelDecl();
382 continue;
383
384 case tok::annot_module_include:
385 ParseTopLevelDecl();
386 continue;
387
388 case tok::eof:
389 break;
390
391 case tok::r_brace:
392 if (!NestedModules)
393 break;
Reid Kleckner4dc0b1a2018-11-01 19:54:45 +0000394 LLVM_FALLTHROUGH;
Richard Smith77944862014-03-02 05:58:18 +0000395 default:
396 ParsedAttributesWithRange attrs(AttrFactory);
397 MaybeParseCXX11Attributes(attrs);
Richard Smith77944862014-03-02 05:58:18 +0000398 ParseExternalDeclaration(attrs);
399 continue;
400 }
401
402 break;
Chris Lattner38376f12008-01-12 07:05:38 +0000403 }
404
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000405 T.consumeClose();
Richard Smith4ee696d2014-02-17 23:25:27 +0000406 return LinkageSpec ? Actions.ActOnFinishLinkageSpecification(
407 getCurScope(), LinkageSpec, T.getCloseLocation())
Craig Topper161e4db2014-05-21 06:02:52 +0000408 : nullptr;
Chris Lattner38376f12008-01-12 07:05:38 +0000409}
Douglas Gregor556877c2008-04-13 21:30:24 +0000410
Richard Smith8df390f2016-09-08 23:14:54 +0000411/// Parse a C++ Modules TS export-declaration.
412///
413/// export-declaration:
414/// 'export' declaration
415/// 'export' '{' declaration-seq[opt] '}'
416///
417Decl *Parser::ParseExportDeclaration() {
418 assert(Tok.is(tok::kw_export));
419 SourceLocation ExportLoc = ConsumeToken();
420
421 ParseScope ExportScope(this, Scope::DeclScope);
422 Decl *ExportDecl = Actions.ActOnStartExportDecl(
423 getCurScope(), ExportLoc,
424 Tok.is(tok::l_brace) ? Tok.getLocation() : SourceLocation());
425
426 if (Tok.isNot(tok::l_brace)) {
427 // FIXME: Factor out a ParseExternalDeclarationWithAttrs.
428 ParsedAttributesWithRange Attrs(AttrFactory);
429 MaybeParseCXX11Attributes(Attrs);
430 MaybeParseMicrosoftAttributes(Attrs);
431 ParseExternalDeclaration(Attrs);
432 return Actions.ActOnFinishExportDecl(getCurScope(), ExportDecl,
433 SourceLocation());
434 }
435
436 BalancedDelimiterTracker T(*this, tok::l_brace);
437 T.consumeOpen();
438
439 // The Modules TS draft says "An export-declaration shall declare at least one
440 // entity", but the intent is that it shall contain at least one declaration.
441 if (Tok.is(tok::r_brace))
442 Diag(ExportLoc, diag::err_export_empty)
443 << SourceRange(ExportLoc, Tok.getLocation());
444
445 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
446 Tok.isNot(tok::eof)) {
447 ParsedAttributesWithRange Attrs(AttrFactory);
448 MaybeParseCXX11Attributes(Attrs);
449 MaybeParseMicrosoftAttributes(Attrs);
450 ParseExternalDeclaration(Attrs);
451 }
452
453 T.consumeClose();
454 return Actions.ActOnFinishExportDecl(getCurScope(), ExportDecl,
455 T.getCloseLocation());
456}
457
Douglas Gregord7c4d982008-12-30 03:27:21 +0000458/// ParseUsingDirectiveOrDeclaration - Parse C++ using using-declaration or
459/// using-directive. Assumes that current token is 'using'.
Richard Smith6f1daa42016-12-16 00:58:48 +0000460Parser::DeclGroupPtrTy
Faisal Vali421b2d12017-12-29 05:41:00 +0000461Parser::ParseUsingDirectiveOrDeclaration(DeclaratorContext Context,
John McCall9b72f892010-11-10 02:40:36 +0000462 const ParsedTemplateInfo &TemplateInfo,
Richard Smith6f1daa42016-12-16 00:58:48 +0000463 SourceLocation &DeclEnd,
464 ParsedAttributesWithRange &attrs) {
Douglas Gregord7c4d982008-12-30 03:27:21 +0000465 assert(Tok.is(tok::kw_using) && "Not using token");
Fariborz Jahanian4bf82622011-08-22 17:59:19 +0000466 ObjCDeclContextSwitch ObjCDC(*this);
Fangrui Song6907ce22018-07-30 19:24:48 +0000467
Douglas Gregord7c4d982008-12-30 03:27:21 +0000468 // Eat 'using'.
469 SourceLocation UsingLoc = ConsumeToken();
470
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000471 if (Tok.is(tok::code_completion)) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000472 Actions.CodeCompleteUsing(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000473 cutOffParsing();
Craig Topper161e4db2014-05-21 06:02:52 +0000474 return nullptr;
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000475 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000476
John McCall9b72f892010-11-10 02:40:36 +0000477 // 'using namespace' means this is a using-directive.
478 if (Tok.is(tok::kw_namespace)) {
479 // Template parameters are always an error here.
480 if (TemplateInfo.Kind) {
481 SourceRange R = TemplateInfo.getSourceRange();
Craig Topper54a6a682015-11-14 18:16:08 +0000482 Diag(UsingLoc, diag::err_templated_using_directive_declaration)
483 << 0 /* directive */ << R << FixItHint::CreateRemoval(R);
John McCall9b72f892010-11-10 02:40:36 +0000484 }
Alexis Hunt96d5c762009-11-21 08:43:09 +0000485
Richard Smith6f1daa42016-12-16 00:58:48 +0000486 Decl *UsingDir = ParseUsingDirective(Context, UsingLoc, DeclEnd, attrs);
487 return Actions.ConvertDeclToDeclGroup(UsingDir);
John McCall9b72f892010-11-10 02:40:36 +0000488 }
489
Richard Smithdda56e42011-04-15 14:24:37 +0000490 // Otherwise, it must be a using-declaration or an alias-declaration.
John McCall9b72f892010-11-10 02:40:36 +0000491
492 // Using declarations can't have attributes.
John McCall53fa7142010-12-24 02:08:15 +0000493 ProhibitAttributes(attrs);
Chris Lattner9b01ca12009-01-06 06:55:51 +0000494
Fariborz Jahanian4bf82622011-08-22 17:59:19 +0000495 return ParseUsingDeclaration(Context, TemplateInfo, UsingLoc, DeclEnd,
Richard Smith6f1daa42016-12-16 00:58:48 +0000496 AS_none);
Douglas Gregord7c4d982008-12-30 03:27:21 +0000497}
498
499/// ParseUsingDirective - Parse C++ using-directive, assumes
500/// that current token is 'namespace' and 'using' was already parsed.
501///
502/// using-directive: [C++ 7.3.p4: namespace.udir]
503/// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
504/// namespace-name ;
505/// [GNU] using-directive:
506/// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
507/// namespace-name attributes[opt] ;
508///
Faisal Vali421b2d12017-12-29 05:41:00 +0000509Decl *Parser::ParseUsingDirective(DeclaratorContext Context,
John McCall9b72f892010-11-10 02:40:36 +0000510 SourceLocation UsingLoc,
511 SourceLocation &DeclEnd,
John McCall53fa7142010-12-24 02:08:15 +0000512 ParsedAttributes &attrs) {
Douglas Gregord7c4d982008-12-30 03:27:21 +0000513 assert(Tok.is(tok::kw_namespace) && "Not 'namespace' token");
514
515 // Eat 'namespace'.
516 SourceLocation NamespcLoc = ConsumeToken();
517
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000518 if (Tok.is(tok::code_completion)) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000519 Actions.CodeCompleteUsingDirective(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000520 cutOffParsing();
Craig Topper161e4db2014-05-21 06:02:52 +0000521 return nullptr;
Douglas Gregor7e90c6d2009-09-18 19:03:04 +0000522 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000523
Douglas Gregord7c4d982008-12-30 03:27:21 +0000524 CXXScopeSpec SS;
525 // Parse (optional) nested-name-specifier.
Matthias Gehredc01bb42017-03-17 21:41:20 +0000526 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false,
527 /*MayBePseudoDestructor=*/nullptr,
528 /*IsTypename=*/false,
529 /*LastII=*/nullptr,
530 /*OnlyNamespace=*/true);
Douglas Gregord7c4d982008-12-30 03:27:21 +0000531
Craig Topper161e4db2014-05-21 06:02:52 +0000532 IdentifierInfo *NamespcName = nullptr;
Douglas Gregord7c4d982008-12-30 03:27:21 +0000533 SourceLocation IdentLoc = SourceLocation();
534
535 // Parse namespace-name.
Matthias Gehredc01bb42017-03-17 21:41:20 +0000536 if (Tok.isNot(tok::identifier)) {
Douglas Gregord7c4d982008-12-30 03:27:21 +0000537 Diag(Tok, diag::err_expected_namespace_name);
538 // If there was invalid namespace name, skip to end of decl, and eat ';'.
539 SkipUntil(tok::semi);
540 // FIXME: Are there cases, when we would like to call ActOnUsingDirective?
Craig Topper161e4db2014-05-21 06:02:52 +0000541 return nullptr;
Douglas Gregord7c4d982008-12-30 03:27:21 +0000542 }
Mike Stump11289f42009-09-09 15:08:12 +0000543
Matthias Gehredc01bb42017-03-17 21:41:20 +0000544 if (SS.isInvalid()) {
545 // Diagnostics have been emitted in ParseOptionalCXXScopeSpecifier.
546 // Skip to end of the definition and eat the ';'.
547 SkipUntil(tok::semi);
548 return nullptr;
549 }
550
Chris Lattnerce1da2c2009-01-06 07:27:21 +0000551 // Parse identifier.
552 NamespcName = Tok.getIdentifierInfo();
553 IdentLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000554
Chris Lattnerce1da2c2009-01-06 07:27:21 +0000555 // Parse (optional) attributes (most likely GNU strong-using extension).
Alexis Hunt96d5c762009-11-21 08:43:09 +0000556 bool GNUAttr = false;
557 if (Tok.is(tok::kw___attribute)) {
558 GNUAttr = true;
John McCall53fa7142010-12-24 02:08:15 +0000559 ParseGNUAttributes(attrs);
Alexis Hunt96d5c762009-11-21 08:43:09 +0000560 }
Mike Stump11289f42009-09-09 15:08:12 +0000561
Chris Lattnerce1da2c2009-01-06 07:27:21 +0000562 // Eat ';'.
Chris Lattner49836b42009-04-02 04:16:50 +0000563 DeclEnd = Tok.getLocation();
Alp Toker383d2c42014-01-01 03:08:43 +0000564 if (ExpectAndConsume(tok::semi,
565 GNUAttr ? diag::err_expected_semi_after_attribute_list
566 : diag::err_expected_semi_after_namespace_name))
567 SkipUntil(tok::semi);
Douglas Gregord7c4d982008-12-30 03:27:21 +0000568
Douglas Gregor0be31a22010-07-02 17:43:08 +0000569 return Actions.ActOnUsingDirective(getCurScope(), UsingLoc, NamespcLoc, SS,
Erich Keanec480f302018-07-12 21:09:05 +0000570 IdentLoc, NamespcName, attrs);
Douglas Gregord7c4d982008-12-30 03:27:21 +0000571}
572
Richard Smith6f1daa42016-12-16 00:58:48 +0000573/// Parse a using-declarator (or the identifier in a C++11 alias-declaration).
Douglas Gregord7c4d982008-12-30 03:27:21 +0000574///
Richard Smith6f1daa42016-12-16 00:58:48 +0000575/// using-declarator:
576/// 'typename'[opt] nested-name-specifier unqualified-id
Douglas Gregord7c4d982008-12-30 03:27:21 +0000577///
Faisal Vali421b2d12017-12-29 05:41:00 +0000578bool Parser::ParseUsingDeclarator(DeclaratorContext Context,
579 UsingDeclarator &D) {
Richard Smith6f1daa42016-12-16 00:58:48 +0000580 D.clear();
Douglas Gregorfec52632009-06-20 00:51:54 +0000581
582 // Ignore optional 'typename'.
Douglas Gregor220f4272009-11-04 16:30:06 +0000583 // FIXME: This is wrong; we should parse this as a typename-specifier.
Richard Smith6f1daa42016-12-16 00:58:48 +0000584 TryConsumeToken(tok::kw_typename, D.TypenameLoc);
Douglas Gregorfec52632009-06-20 00:51:54 +0000585
Nikola Smiljanic67860242014-09-26 00:28:20 +0000586 if (Tok.is(tok::kw___super)) {
587 Diag(Tok.getLocation(), diag::err_super_in_using_declaration);
Richard Smith6f1daa42016-12-16 00:58:48 +0000588 return true;
Nikola Smiljanic67860242014-09-26 00:28:20 +0000589 }
590
Douglas Gregorfec52632009-06-20 00:51:54 +0000591 // Parse nested-name-specifier.
Craig Topper161e4db2014-05-21 06:02:52 +0000592 IdentifierInfo *LastII = nullptr;
Richard Smith6f1daa42016-12-16 00:58:48 +0000593 ParseOptionalCXXScopeSpecifier(D.SS, nullptr, /*EnteringContext=*/false,
Craig Topper161e4db2014-05-21 06:02:52 +0000594 /*MayBePseudoDtor=*/nullptr,
595 /*IsTypename=*/false,
Richard Smith7447af42013-03-26 01:15:19 +0000596 /*LastII=*/&LastII);
Richard Smith6f1daa42016-12-16 00:58:48 +0000597 if (D.SS.isInvalid())
598 return true;
Richard Smith7447af42013-03-26 01:15:19 +0000599
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000600 // Parse the unqualified-id. We allow parsing of both constructor and
Douglas Gregor220f4272009-11-04 16:30:06 +0000601 // destructor names and allow the action module to diagnose any semantic
602 // errors.
Richard Smith7447af42013-03-26 01:15:19 +0000603 //
604 // C++11 [class.qual]p2:
605 // [...] in a using-declaration that is a member-declaration, if the name
606 // specified after the nested-name-specifier is the same as the identifier
607 // or the simple-template-id's template-name in the last component of the
608 // nested-name-specifier, the name is [...] considered to name the
609 // constructor.
Faisal Vali421b2d12017-12-29 05:41:00 +0000610 if (getLangOpts().CPlusPlus11 &&
611 Context == DeclaratorContext::MemberContext &&
Richard Smith151c4562016-12-20 21:35:28 +0000612 Tok.is(tok::identifier) &&
613 (NextToken().is(tok::semi) || NextToken().is(tok::comma) ||
614 NextToken().is(tok::ellipsis)) &&
Richard Smith6f1daa42016-12-16 00:58:48 +0000615 D.SS.isNotEmpty() && LastII == Tok.getIdentifierInfo() &&
616 !D.SS.getScopeRep()->getAsNamespace() &&
617 !D.SS.getScopeRep()->getAsNamespaceAlias()) {
Richard Smith7447af42013-03-26 01:15:19 +0000618 SourceLocation IdLoc = ConsumeToken();
Richard Smith6f1daa42016-12-16 00:58:48 +0000619 ParsedType Type =
620 Actions.getInheritingConstructorName(D.SS, IdLoc, *LastII);
621 D.Name.setConstructorName(Type, IdLoc, IdLoc);
622 } else {
623 if (ParseUnqualifiedId(
624 D.SS, /*EnteringContext=*/false,
625 /*AllowDestructorName=*/true,
626 /*AllowConstructorName=*/!(Tok.is(tok::identifier) &&
627 NextToken().is(tok::equal)),
Richard Smith35845152017-02-07 01:37:30 +0000628 /*AllowDeductionGuide=*/false,
Richard Smithc08b6932018-04-27 02:00:13 +0000629 nullptr, nullptr, D.Name))
Richard Smith6f1daa42016-12-16 00:58:48 +0000630 return true;
Douglas Gregorfec52632009-06-20 00:51:54 +0000631 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000632
Richard Smith151c4562016-12-20 21:35:28 +0000633 if (TryConsumeToken(tok::ellipsis, D.EllipsisLoc))
Aaron Ballmanc351fba2017-12-04 20:27:34 +0000634 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17 ?
Richard Smithb115e5d2017-08-13 23:37:29 +0000635 diag::warn_cxx17_compat_using_declaration_pack :
Richard Smith151c4562016-12-20 21:35:28 +0000636 diag::ext_using_declaration_pack);
Richard Smith6f1daa42016-12-16 00:58:48 +0000637
638 return false;
639}
640
641/// ParseUsingDeclaration - Parse C++ using-declaration or alias-declaration.
642/// Assumes that 'using' was already seen.
643///
644/// using-declaration: [C++ 7.3.p3: namespace.udecl]
645/// 'using' using-declarator-list[opt] ;
646///
647/// using-declarator-list: [C++1z]
648/// using-declarator '...'[opt]
649/// using-declarator-list ',' using-declarator '...'[opt]
650///
651/// using-declarator-list: [C++98-14]
652/// using-declarator
653///
654/// alias-declaration: C++11 [dcl.dcl]p1
655/// 'using' identifier attribute-specifier-seq[opt] = type-id ;
656///
657Parser::DeclGroupPtrTy
Faisal Vali421b2d12017-12-29 05:41:00 +0000658Parser::ParseUsingDeclaration(DeclaratorContext Context,
Richard Smith6f1daa42016-12-16 00:58:48 +0000659 const ParsedTemplateInfo &TemplateInfo,
660 SourceLocation UsingLoc, SourceLocation &DeclEnd,
661 AccessSpecifier AS) {
662 // Check for misplaced attributes before the identifier in an
663 // alias-declaration.
664 ParsedAttributesWithRange MisplacedAttrs(AttrFactory);
665 MaybeParseCXX11Attributes(MisplacedAttrs);
666
667 UsingDeclarator D;
668 bool InvalidDeclarator = ParseUsingDeclarator(Context, D);
669
Richard Smithc2c8bb82013-10-15 01:34:54 +0000670 ParsedAttributesWithRange Attrs(AttrFactory);
Richard Smith37a45dd2013-10-24 01:21:09 +0000671 MaybeParseGNUAttributes(Attrs);
Richard Smith54ecd982013-02-20 19:22:51 +0000672 MaybeParseCXX11Attributes(Attrs);
Richard Smithdda56e42011-04-15 14:24:37 +0000673
674 // Maybe this is an alias-declaration.
Richard Smith6f1daa42016-12-16 00:58:48 +0000675 if (Tok.is(tok::equal)) {
676 if (InvalidDeclarator) {
677 SkipUntil(tok::semi);
678 return nullptr;
679 }
680
Richard Smithc2c8bb82013-10-15 01:34:54 +0000681 // If we had any misplaced attributes from earlier, this is where they
682 // should have been written.
683 if (MisplacedAttrs.Range.isValid()) {
684 Diag(MisplacedAttrs.Range.getBegin(), diag::err_attributes_not_allowed)
685 << FixItHint::CreateInsertionFromRange(
686 Tok.getLocation(),
687 CharSourceRange::getTokenRange(MisplacedAttrs.Range))
688 << FixItHint::CreateRemoval(MisplacedAttrs.Range);
689 Attrs.takeAllFrom(MisplacedAttrs);
690 }
691
Richard Smith6f1daa42016-12-16 00:58:48 +0000692 Decl *DeclFromDeclSpec = nullptr;
693 Decl *AD = ParseAliasDeclarationAfterDeclarator(
694 TemplateInfo, UsingLoc, D, DeclEnd, AS, Attrs, &DeclFromDeclSpec);
695 return Actions.ConvertDeclToDeclGroup(AD, DeclFromDeclSpec);
Alexis Hunt6aa9bee2012-06-23 05:07:58 +0000696 }
Mike Stump11289f42009-09-09 15:08:12 +0000697
Richard Smith6f1daa42016-12-16 00:58:48 +0000698 // C++11 attributes are not allowed on a using-declaration, but GNU ones
699 // are.
700 ProhibitAttributes(MisplacedAttrs);
701 ProhibitAttributes(Attrs);
Douglas Gregorfec52632009-06-20 00:51:54 +0000702
John McCall9b72f892010-11-10 02:40:36 +0000703 // Diagnose an attempt to declare a templated using-declaration.
Richard Smith810ad3e2013-01-29 10:02:16 +0000704 // In C++11, alias-declarations can be templates:
Richard Smithdda56e42011-04-15 14:24:37 +0000705 // template <...> using id = type;
Richard Smith6f1daa42016-12-16 00:58:48 +0000706 if (TemplateInfo.Kind) {
John McCall9b72f892010-11-10 02:40:36 +0000707 SourceRange R = TemplateInfo.getSourceRange();
Craig Topper54a6a682015-11-14 18:16:08 +0000708 Diag(UsingLoc, diag::err_templated_using_directive_declaration)
709 << 1 /* declaration */ << R << FixItHint::CreateRemoval(R);
John McCall9b72f892010-11-10 02:40:36 +0000710
711 // Unfortunately, we have to bail out instead of recovering by
712 // ignoring the parameters, just in case the nested name specifier
713 // depends on the parameters.
Craig Topper161e4db2014-05-21 06:02:52 +0000714 return nullptr;
John McCall9b72f892010-11-10 02:40:36 +0000715 }
716
Richard Smith6f1daa42016-12-16 00:58:48 +0000717 SmallVector<Decl *, 8> DeclsInGroup;
718 while (true) {
719 // Parse (optional) attributes (most likely GNU strong-using extension).
720 MaybeParseGNUAttributes(Attrs);
721
722 if (InvalidDeclarator)
723 SkipUntil(tok::comma, tok::semi, StopBeforeMatch);
724 else {
725 // "typename" keyword is allowed for identifiers only,
726 // because it may be a type definition.
727 if (D.TypenameLoc.isValid() &&
Faisal Vali2ab8c152017-12-30 04:15:27 +0000728 D.Name.getKind() != UnqualifiedIdKind::IK_Identifier) {
Richard Smith6f1daa42016-12-16 00:58:48 +0000729 Diag(D.Name.getSourceRange().getBegin(),
730 diag::err_typename_identifiers_only)
731 << FixItHint::CreateRemoval(SourceRange(D.TypenameLoc));
732 // Proceed parsing, but discard the typename keyword.
733 D.TypenameLoc = SourceLocation();
734 }
735
Richard Smith151c4562016-12-20 21:35:28 +0000736 Decl *UD = Actions.ActOnUsingDeclaration(getCurScope(), AS, UsingLoc,
737 D.TypenameLoc, D.SS, D.Name,
Erich Keanec480f302018-07-12 21:09:05 +0000738 D.EllipsisLoc, Attrs);
Richard Smith6f1daa42016-12-16 00:58:48 +0000739 if (UD)
740 DeclsInGroup.push_back(UD);
741 }
742
743 if (!TryConsumeToken(tok::comma))
744 break;
745
746 // Parse another using-declarator.
747 Attrs.clear();
748 InvalidDeclarator = ParseUsingDeclarator(Context, D);
Douglas Gregor882a61a2011-09-26 14:30:28 +0000749 }
750
Richard Smith6f1daa42016-12-16 00:58:48 +0000751 if (DeclsInGroup.size() > 1)
Aaron Ballmanc351fba2017-12-04 20:27:34 +0000752 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17 ?
Richard Smithb115e5d2017-08-13 23:37:29 +0000753 diag::warn_cxx17_compat_multi_using_declaration :
Richard Smith6f1daa42016-12-16 00:58:48 +0000754 diag::ext_multi_using_declaration);
755
756 // Eat ';'.
757 DeclEnd = Tok.getLocation();
758 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
759 !Attrs.empty() ? "attributes list"
760 : "using declaration"))
761 SkipUntil(tok::semi);
762
Richard Smith3beb7c62017-01-12 02:27:38 +0000763 return Actions.BuildDeclaratorGroup(DeclsInGroup);
Richard Smith6f1daa42016-12-16 00:58:48 +0000764}
765
Richard Smith6f1daa42016-12-16 00:58:48 +0000766Decl *Parser::ParseAliasDeclarationAfterDeclarator(
767 const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc,
768 UsingDeclarator &D, SourceLocation &DeclEnd, AccessSpecifier AS,
769 ParsedAttributes &Attrs, Decl **OwnedType) {
770 if (ExpectAndConsume(tok::equal)) {
771 SkipUntil(tok::semi);
772 return nullptr;
773 }
774
775 Diag(Tok.getLocation(), getLangOpts().CPlusPlus11 ?
776 diag::warn_cxx98_compat_alias_declaration :
777 diag::ext_alias_declaration);
778
779 // Type alias templates cannot be specialized.
780 int SpecKind = -1;
781 if (TemplateInfo.Kind == ParsedTemplateInfo::Template &&
Faisal Vali2ab8c152017-12-30 04:15:27 +0000782 D.Name.getKind() == UnqualifiedIdKind::IK_TemplateId)
Richard Smith6f1daa42016-12-16 00:58:48 +0000783 SpecKind = 0;
784 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization)
785 SpecKind = 1;
786 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
787 SpecKind = 2;
788 if (SpecKind != -1) {
789 SourceRange Range;
790 if (SpecKind == 0)
791 Range = SourceRange(D.Name.TemplateId->LAngleLoc,
792 D.Name.TemplateId->RAngleLoc);
793 else
794 Range = TemplateInfo.getSourceRange();
795 Diag(Range.getBegin(), diag::err_alias_declaration_specialization)
796 << SpecKind << Range;
797 SkipUntil(tok::semi);
798 return nullptr;
799 }
800
801 // Name must be an identifier.
Faisal Vali2ab8c152017-12-30 04:15:27 +0000802 if (D.Name.getKind() != UnqualifiedIdKind::IK_Identifier) {
Richard Smith6f1daa42016-12-16 00:58:48 +0000803 Diag(D.Name.StartLocation, diag::err_alias_declaration_not_identifier);
804 // No removal fixit: can't recover from this.
805 SkipUntil(tok::semi);
806 return nullptr;
807 } else if (D.TypenameLoc.isValid())
808 Diag(D.TypenameLoc, diag::err_alias_declaration_not_identifier)
809 << FixItHint::CreateRemoval(SourceRange(
810 D.TypenameLoc,
811 D.SS.isNotEmpty() ? D.SS.getEndLoc() : D.TypenameLoc));
812 else if (D.SS.isNotEmpty())
813 Diag(D.SS.getBeginLoc(), diag::err_alias_declaration_not_identifier)
814 << FixItHint::CreateRemoval(D.SS.getRange());
Richard Smith151c4562016-12-20 21:35:28 +0000815 if (D.EllipsisLoc.isValid())
816 Diag(D.EllipsisLoc, diag::err_alias_declaration_pack_expansion)
817 << FixItHint::CreateRemoval(SourceRange(D.EllipsisLoc));
Richard Smith6f1daa42016-12-16 00:58:48 +0000818
819 Decl *DeclFromDeclSpec = nullptr;
Faisal Vali421b2d12017-12-29 05:41:00 +0000820 TypeResult TypeAlias = ParseTypeName(
821 nullptr,
822 TemplateInfo.Kind ? DeclaratorContext::AliasTemplateContext
823 : DeclaratorContext::AliasDeclContext,
824 AS, &DeclFromDeclSpec, &Attrs);
Richard Smith6f1daa42016-12-16 00:58:48 +0000825 if (OwnedType)
826 *OwnedType = DeclFromDeclSpec;
827
828 // Eat ';'.
829 DeclEnd = Tok.getLocation();
830 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
831 !Attrs.empty() ? "attributes list"
832 : "alias declaration"))
833 SkipUntil(tok::semi);
834
835 TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
836 MultiTemplateParamsArg TemplateParamsArg(
837 TemplateParams ? TemplateParams->data() : nullptr,
838 TemplateParams ? TemplateParams->size() : 0);
839 return Actions.ActOnAliasDeclaration(getCurScope(), AS, TemplateParamsArg,
Erich Keanec480f302018-07-12 21:09:05 +0000840 UsingLoc, D.Name, Attrs, TypeAlias,
841 DeclFromDeclSpec);
Douglas Gregord7c4d982008-12-30 03:27:21 +0000842}
843
Benjamin Kramere56f3932011-12-23 17:00:35 +0000844/// ParseStaticAssertDeclaration - Parse C++0x or C11 static_assert-declaration.
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000845///
Peter Collingbourne3d9cbdc2011-04-15 00:35:57 +0000846/// [C++0x] static_assert-declaration:
847/// static_assert ( constant-expression , string-literal ) ;
848///
Benjamin Kramere56f3932011-12-23 17:00:35 +0000849/// [C11] static_assert-declaration:
Peter Collingbourne3d9cbdc2011-04-15 00:35:57 +0000850/// _Static_assert ( constant-expression , string-literal ) ;
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000851///
John McCall48871652010-08-21 09:40:31 +0000852Decl *Parser::ParseStaticAssertDeclaration(SourceLocation &DeclEnd){
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000853 assert(Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert) &&
Peter Collingbourne3d9cbdc2011-04-15 00:35:57 +0000854 "Not a static_assert declaration");
855
David Blaikiebbafb8a2012-03-11 07:00:24 +0000856 if (Tok.is(tok::kw__Static_assert) && !getLangOpts().C11)
Benjamin Kramere56f3932011-12-23 17:00:35 +0000857 Diag(Tok, diag::ext_c11_static_assert);
Richard Smithb15c11c2011-10-17 23:06:20 +0000858 if (Tok.is(tok::kw_static_assert))
859 Diag(Tok, diag::warn_cxx98_compat_static_assert);
Peter Collingbourne3d9cbdc2011-04-15 00:35:57 +0000860
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000861 SourceLocation StaticAssertLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000862
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000863 BalancedDelimiterTracker T(*this, tok::l_paren);
864 if (T.consumeOpen()) {
Alp Tokerec543272013-12-24 09:48:30 +0000865 Diag(Tok, diag::err_expected) << tok::l_paren;
Richard Smith76965712012-09-13 19:12:50 +0000866 SkipMalformedDecl();
Craig Topper161e4db2014-05-21 06:02:52 +0000867 return nullptr;
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000868 }
Mike Stump11289f42009-09-09 15:08:12 +0000869
Richard Smithb3018062017-06-06 01:34:24 +0000870 EnterExpressionEvaluationContext ConstantEvaluated(
871 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
872 ExprResult AssertExpr(ParseConstantExpressionInExprEvalContext());
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000873 if (AssertExpr.isInvalid()) {
Richard Smith76965712012-09-13 19:12:50 +0000874 SkipMalformedDecl();
Craig Topper161e4db2014-05-21 06:02:52 +0000875 return nullptr;
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000876 }
Mike Stump11289f42009-09-09 15:08:12 +0000877
Richard Smith085a64f2014-06-20 19:57:12 +0000878 ExprResult AssertMessage;
879 if (Tok.is(tok::r_paren)) {
Aaron Ballmanc351fba2017-12-04 20:27:34 +0000880 Diag(Tok, getLangOpts().CPlusPlus17
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000881 ? diag::warn_cxx14_compat_static_assert_no_message
Richard Smith085a64f2014-06-20 19:57:12 +0000882 : diag::ext_static_assert_no_message)
Aaron Ballmanc351fba2017-12-04 20:27:34 +0000883 << (getLangOpts().CPlusPlus17
Richard Smith085a64f2014-06-20 19:57:12 +0000884 ? FixItHint()
885 : FixItHint::CreateInsertion(Tok.getLocation(), ", \"\""));
886 } else {
887 if (ExpectAndConsume(tok::comma)) {
888 SkipUntil(tok::semi);
889 return nullptr;
890 }
Anders Carlssonb4cf3ad2009-03-13 23:29:20 +0000891
Richard Smith085a64f2014-06-20 19:57:12 +0000892 if (!isTokenStringLiteral()) {
893 Diag(Tok, diag::err_expected_string_literal)
894 << /*Source='static_assert'*/1;
895 SkipMalformedDecl();
896 return nullptr;
897 }
Mike Stump11289f42009-09-09 15:08:12 +0000898
Richard Smith085a64f2014-06-20 19:57:12 +0000899 AssertMessage = ParseStringLiteralExpression();
900 if (AssertMessage.isInvalid()) {
901 SkipMalformedDecl();
902 return nullptr;
903 }
Richard Smithd67aea22012-03-06 03:21:47 +0000904 }
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000905
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000906 T.consumeClose();
Mike Stump11289f42009-09-09 15:08:12 +0000907
Chris Lattner49836b42009-04-02 04:16:50 +0000908 DeclEnd = Tok.getLocation();
Douglas Gregor45d6bdf2010-09-07 15:23:11 +0000909 ExpectAndConsumeSemi(diag::err_expected_semi_after_static_assert);
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000910
John McCallb268a282010-08-23 23:25:46 +0000911 return Actions.ActOnStaticAssertDeclaration(StaticAssertLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000912 AssertExpr.get(),
913 AssertMessage.get(),
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000914 T.getCloseLocation());
Anders Carlssonf24fcff62009-03-11 16:27:10 +0000915}
916
Richard Smith74aeef52013-04-26 16:15:35 +0000917/// ParseDecltypeSpecifier - Parse a C++11 decltype specifier.
Anders Carlsson74948d02009-06-24 17:47:40 +0000918///
919/// 'decltype' ( expression )
Richard Smith74aeef52013-04-26 16:15:35 +0000920/// 'decltype' ( 'auto' ) [C++1y]
Anders Carlsson74948d02009-06-24 17:47:40 +0000921///
David Blaikie15a430a2011-12-04 05:04:18 +0000922SourceLocation Parser::ParseDecltypeSpecifier(DeclSpec &DS) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000923 assert(Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)
David Blaikie15a430a2011-12-04 05:04:18 +0000924 && "Not a decltype specifier");
Fangrui Song6907ce22018-07-30 19:24:48 +0000925
David Blaikie15a430a2011-12-04 05:04:18 +0000926 ExprResult Result;
927 SourceLocation StartLoc = Tok.getLocation();
928 SourceLocation EndLoc;
929
930 if (Tok.is(tok::annot_decltype)) {
931 Result = getExprAnnotation(Tok);
932 EndLoc = Tok.getAnnotationEndLoc();
Richard Smithaf3b3252017-05-18 19:21:48 +0000933 ConsumeAnnotationToken();
David Blaikie15a430a2011-12-04 05:04:18 +0000934 if (Result.isInvalid()) {
935 DS.SetTypeSpecError();
936 return EndLoc;
937 }
938 } else {
Richard Smith324df552012-02-24 22:30:04 +0000939 if (Tok.getIdentifierInfo()->isStr("decltype"))
940 Diag(Tok, diag::warn_cxx98_compat_decltype);
Richard Smithfd3da932012-02-24 18:10:23 +0000941
David Blaikie15a430a2011-12-04 05:04:18 +0000942 ConsumeToken();
943
944 BalancedDelimiterTracker T(*this, tok::l_paren);
945 if (T.expectAndConsume(diag::err_expected_lparen_after,
946 "decltype", tok::r_paren)) {
947 DS.SetTypeSpecError();
948 return T.getOpenLocation() == Tok.getLocation() ?
949 StartLoc : T.getOpenLocation();
950 }
951
Richard Smith74aeef52013-04-26 16:15:35 +0000952 // Check for C++1y 'decltype(auto)'.
953 if (Tok.is(tok::kw_auto)) {
954 // No need to disambiguate here: an expression can't start with 'auto',
955 // because the typename-specifier in a function-style cast operation can't
956 // be 'auto'.
957 Diag(Tok.getLocation(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000958 getLangOpts().CPlusPlus14
Richard Smith74aeef52013-04-26 16:15:35 +0000959 ? diag::warn_cxx11_compat_decltype_auto_type_specifier
960 : diag::ext_decltype_auto_type_specifier);
961 ConsumeToken();
962 } else {
963 // Parse the expression
David Blaikie15a430a2011-12-04 05:04:18 +0000964
Richard Smith74aeef52013-04-26 16:15:35 +0000965 // C++11 [dcl.type.simple]p4:
966 // The operand of the decltype specifier is an unevaluated operand.
Faisal Valid143a0c2017-04-01 21:30:49 +0000967 EnterExpressionEvaluationContext Unevaluated(
968 Actions, Sema::ExpressionEvaluationContext::Unevaluated, nullptr,
Nicolas Lesserb6d5c582018-07-12 18:45:41 +0000969 Sema::ExpressionEvaluationContextRecord::EK_Decltype);
Kaelyn Takata5cc85352015-04-10 19:16:46 +0000970 Result =
971 Actions.CorrectDelayedTyposInExpr(ParseExpression(), [](Expr *E) {
972 return E->hasPlaceholderType() ? ExprError() : E;
973 });
Richard Smith74aeef52013-04-26 16:15:35 +0000974 if (Result.isInvalid()) {
975 DS.SetTypeSpecError();
Alexey Bataevee6507d2013-11-18 08:17:37 +0000976 if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch)) {
Richard Smith74aeef52013-04-26 16:15:35 +0000977 EndLoc = ConsumeParen();
Argyrios Kyrtzidisc38395a2012-10-26 22:53:44 +0000978 } else {
Richard Smith74aeef52013-04-26 16:15:35 +0000979 if (PP.isBacktrackEnabled() && Tok.is(tok::semi)) {
980 // Backtrack to get the location of the last token before the semi.
981 PP.RevertCachedTokens(2);
982 ConsumeToken(); // the semi.
983 EndLoc = ConsumeAnyToken();
984 assert(Tok.is(tok::semi));
985 } else {
986 EndLoc = Tok.getLocation();
987 }
Argyrios Kyrtzidisc38395a2012-10-26 22:53:44 +0000988 }
Richard Smith74aeef52013-04-26 16:15:35 +0000989 return EndLoc;
Argyrios Kyrtzidisc38395a2012-10-26 22:53:44 +0000990 }
Richard Smith74aeef52013-04-26 16:15:35 +0000991
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000992 Result = Actions.ActOnDecltypeExpression(Result.get());
David Blaikie15a430a2011-12-04 05:04:18 +0000993 }
994
995 // Match the ')'
996 T.consumeClose();
997 if (T.getCloseLocation().isInvalid()) {
998 DS.SetTypeSpecError();
999 // FIXME: this should return the location of the last token
1000 // that was consumed (by "consumeClose()")
1001 return T.getCloseLocation();
1002 }
1003
Richard Smithfd555f62012-02-22 02:04:18 +00001004 if (Result.isInvalid()) {
1005 DS.SetTypeSpecError();
1006 return T.getCloseLocation();
1007 }
1008
David Blaikie15a430a2011-12-04 05:04:18 +00001009 EndLoc = T.getCloseLocation();
Anders Carlsson74948d02009-06-24 17:47:40 +00001010 }
Richard Smith74aeef52013-04-26 16:15:35 +00001011 assert(!Result.isInvalid());
Mike Stump11289f42009-09-09 15:08:12 +00001012
Craig Topper161e4db2014-05-21 06:02:52 +00001013 const char *PrevSpec = nullptr;
John McCall49bfce42009-08-03 20:12:06 +00001014 unsigned DiagID;
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001015 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
Anders Carlsson74948d02009-06-24 17:47:40 +00001016 // Check for duplicate type specifiers (e.g. "int decltype(a)").
Richard Smith74aeef52013-04-26 16:15:35 +00001017 if (Result.get()
1018 ? DS.SetTypeSpecType(DeclSpec::TST_decltype, StartLoc, PrevSpec,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001019 DiagID, Result.get(), Policy)
Richard Smith74aeef52013-04-26 16:15:35 +00001020 : DS.SetTypeSpecType(DeclSpec::TST_decltype_auto, StartLoc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001021 DiagID, Policy)) {
John McCall49bfce42009-08-03 20:12:06 +00001022 Diag(StartLoc, DiagID) << PrevSpec;
David Blaikie15a430a2011-12-04 05:04:18 +00001023 DS.SetTypeSpecError();
1024 }
1025 return EndLoc;
1026}
1027
Fangrui Song6907ce22018-07-30 19:24:48 +00001028void Parser::AnnotateExistingDecltypeSpecifier(const DeclSpec& DS,
David Blaikie15a430a2011-12-04 05:04:18 +00001029 SourceLocation StartLoc,
1030 SourceLocation EndLoc) {
1031 // make sure we have a token we can turn into an annotation token
1032 if (PP.isBacktrackEnabled())
1033 PP.RevertCachedTokens(1);
1034 else
1035 PP.EnterToken(Tok);
1036
1037 Tok.setKind(tok::annot_decltype);
Faisal Vali090da2d2018-01-01 18:23:28 +00001038 setExprAnnotation(Tok,
1039 DS.getTypeSpecType() == TST_decltype ? DS.getRepAsExpr() :
1040 DS.getTypeSpecType() == TST_decltype_auto ? ExprResult() :
1041 ExprError());
David Blaikie15a430a2011-12-04 05:04:18 +00001042 Tok.setAnnotationEndLoc(EndLoc);
1043 Tok.setLocation(StartLoc);
1044 PP.AnnotateCachedTokens(Tok);
Anders Carlsson74948d02009-06-24 17:47:40 +00001045}
1046
Alexis Hunt4a257072011-05-19 05:37:45 +00001047void Parser::ParseUnderlyingTypeSpecifier(DeclSpec &DS) {
1048 assert(Tok.is(tok::kw___underlying_type) &&
1049 "Not an underlying type specifier");
1050
1051 SourceLocation StartLoc = ConsumeToken();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001052 BalancedDelimiterTracker T(*this, tok::l_paren);
1053 if (T.expectAndConsume(diag::err_expected_lparen_after,
1054 "__underlying_type", tok::r_paren)) {
Alexis Hunt4a257072011-05-19 05:37:45 +00001055 return;
1056 }
1057
1058 TypeResult Result = ParseTypeName();
1059 if (Result.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00001060 SkipUntil(tok::r_paren, StopAtSemi);
Alexis Hunt4a257072011-05-19 05:37:45 +00001061 return;
1062 }
1063
1064 // Match the ')'
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001065 T.consumeClose();
1066 if (T.getCloseLocation().isInvalid())
Alexis Hunt4a257072011-05-19 05:37:45 +00001067 return;
1068
Craig Topper161e4db2014-05-21 06:02:52 +00001069 const char *PrevSpec = nullptr;
Alexis Hunt4a257072011-05-19 05:37:45 +00001070 unsigned DiagID;
Alexis Hunte852b102011-05-24 22:41:36 +00001071 if (DS.SetTypeSpecType(DeclSpec::TST_underlyingType, StartLoc, PrevSpec,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001072 DiagID, Result.get(),
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001073 Actions.getASTContext().getPrintingPolicy()))
Alexis Hunt4a257072011-05-19 05:37:45 +00001074 Diag(StartLoc, DiagID) << PrevSpec;
Enea Zaffanellaa90af722013-07-06 18:54:58 +00001075 DS.setTypeofParensRange(T.getRange());
Alexis Hunt4a257072011-05-19 05:37:45 +00001076}
1077
David Blaikie00ee7a082011-10-25 15:01:20 +00001078/// ParseBaseTypeSpecifier - Parse a C++ base-type-specifier which is either a
Fangrui Song6907ce22018-07-30 19:24:48 +00001079/// class name or decltype-specifier. Note that we only check that the result
1080/// names a type; semantic analysis will need to verify that the type names a
1081/// class. The result is either a type or null, depending on whether a type
David Blaikie00ee7a082011-10-25 15:01:20 +00001082/// name was found.
Douglas Gregor831c93f2008-11-05 20:51:48 +00001083///
Richard Smith4c96e992013-02-19 23:47:15 +00001084/// base-type-specifier: [C++11 class.derived]
David Blaikie00ee7a082011-10-25 15:01:20 +00001085/// class-or-decltype
Richard Smith4c96e992013-02-19 23:47:15 +00001086/// class-or-decltype: [C++11 class.derived]
David Blaikie00ee7a082011-10-25 15:01:20 +00001087/// nested-name-specifier[opt] class-name
1088/// decltype-specifier
Richard Smith4c96e992013-02-19 23:47:15 +00001089/// class-name: [C++ class.name]
Douglas Gregor831c93f2008-11-05 20:51:48 +00001090/// identifier
Douglas Gregord54dfb82009-02-25 23:52:28 +00001091/// simple-template-id
Mike Stump11289f42009-09-09 15:08:12 +00001092///
Richard Smith4c96e992013-02-19 23:47:15 +00001093/// In C++98, instead of base-type-specifier, we have:
1094///
1095/// ::[opt] nested-name-specifier[opt] class-name
Craig Topper9ad7e262014-10-31 06:57:07 +00001096TypeResult Parser::ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
1097 SourceLocation &EndLocation) {
David Blaikiedd58d4c2011-10-25 18:46:41 +00001098 // Ignore attempts to use typename
1099 if (Tok.is(tok::kw_typename)) {
1100 Diag(Tok, diag::err_expected_class_name_not_template)
1101 << FixItHint::CreateRemoval(Tok.getLocation());
1102 ConsumeToken();
1103 }
1104
David Blaikieafa155f2011-10-25 18:17:58 +00001105 // Parse optional nested-name-specifier
1106 CXXScopeSpec SS;
David Blaikieefdccaa2016-01-15 23:43:34 +00001107 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false);
David Blaikieafa155f2011-10-25 18:17:58 +00001108
1109 BaseLoc = Tok.getLocation();
1110
David Blaikie1cd50022011-10-25 17:10:12 +00001111 // Parse decltype-specifier
Fangrui Song6907ce22018-07-30 19:24:48 +00001112 // tok == kw_decltype is just error recovery, it can only happen when SS
David Blaikie15a430a2011-12-04 05:04:18 +00001113 // isn't empty
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001114 if (Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)) {
David Blaikieafa155f2011-10-25 18:17:58 +00001115 if (SS.isNotEmpty())
1116 Diag(SS.getBeginLoc(), diag::err_unexpected_scope_on_base_decltype)
1117 << FixItHint::CreateRemoval(SS.getRange());
David Blaikie1cd50022011-10-25 17:10:12 +00001118 // Fake up a Declarator to use with ActOnTypeName.
1119 DeclSpec DS(AttrFactory);
1120
David Blaikie7491e732011-12-08 04:53:15 +00001121 EndLocation = ParseDecltypeSpecifier(DS);
David Blaikie1cd50022011-10-25 17:10:12 +00001122
Faisal Vali421b2d12017-12-29 05:41:00 +00001123 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
David Blaikie1cd50022011-10-25 17:10:12 +00001124 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
1125 }
1126
Douglas Gregord54dfb82009-02-25 23:52:28 +00001127 // Check whether we have a template-id that names a type.
1128 if (Tok.is(tok::annot_template_id)) {
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00001129 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregor46c59612010-01-12 17:52:59 +00001130 if (TemplateId->Kind == TNK_Type_template ||
1131 TemplateId->Kind == TNK_Dependent_template_name) {
Richard Smith62559bd2017-02-01 21:36:38 +00001132 AnnotateTemplateIdTokenAsType(/*IsClassName*/true);
Douglas Gregord54dfb82009-02-25 23:52:28 +00001133
1134 assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
John McCallba7bf592010-08-24 05:47:05 +00001135 ParsedType Type = getTypeAnnotation(Tok);
Douglas Gregord54dfb82009-02-25 23:52:28 +00001136 EndLocation = Tok.getAnnotationEndLoc();
Richard Smithaf3b3252017-05-18 19:21:48 +00001137 ConsumeAnnotationToken();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001138
1139 if (Type)
1140 return Type;
1141 return true;
Douglas Gregord54dfb82009-02-25 23:52:28 +00001142 }
1143
1144 // Fall through to produce an error below.
1145 }
1146
Douglas Gregor831c93f2008-11-05 20:51:48 +00001147 if (Tok.isNot(tok::identifier)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00001148 Diag(Tok, diag::err_expected_class_name);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001149 return true;
Douglas Gregor831c93f2008-11-05 20:51:48 +00001150 }
1151
Douglas Gregor18473f32010-01-12 21:28:44 +00001152 IdentifierInfo *Id = Tok.getIdentifierInfo();
1153 SourceLocation IdLoc = ConsumeToken();
1154
1155 if (Tok.is(tok::less)) {
1156 // It looks the user intended to write a template-id here, but the
1157 // template-name was wrong. Try to fix that.
1158 TemplateNameKind TNK = TNK_Type_template;
1159 TemplateTy Template;
Douglas Gregor0be31a22010-07-02 17:43:08 +00001160 if (!Actions.DiagnoseUnknownTemplateName(*Id, IdLoc, getCurScope(),
Douglas Gregore7c20652011-03-02 00:47:37 +00001161 &SS, Template, TNK)) {
Douglas Gregor18473f32010-01-12 21:28:44 +00001162 Diag(IdLoc, diag::err_unknown_template_name)
1163 << Id;
1164 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001165
Serge Pavlovb716b3c2013-08-10 05:54:47 +00001166 if (!Template) {
1167 TemplateArgList TemplateArgs;
1168 SourceLocation LAngleLoc, RAngleLoc;
Richard Smith9a420f92017-05-10 21:47:30 +00001169 ParseTemplateIdAfterTemplateName(true, LAngleLoc, TemplateArgs,
1170 RAngleLoc);
Douglas Gregor18473f32010-01-12 21:28:44 +00001171 return true;
Serge Pavlovb716b3c2013-08-10 05:54:47 +00001172 }
Douglas Gregor18473f32010-01-12 21:28:44 +00001173
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001174 // Form the template name
Douglas Gregor18473f32010-01-12 21:28:44 +00001175 UnqualifiedId TemplateName;
1176 TemplateName.setIdentifier(Id, IdLoc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001177
Douglas Gregor18473f32010-01-12 21:28:44 +00001178 // Parse the full template-id, then turn it into a type.
Abramo Bagnara7945c982012-01-27 09:46:47 +00001179 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
Richard Smith62559bd2017-02-01 21:36:38 +00001180 TemplateName))
Douglas Gregor18473f32010-01-12 21:28:44 +00001181 return true;
Richard Smith62559bd2017-02-01 21:36:38 +00001182 if (TNK == TNK_Type_template || TNK == TNK_Dependent_template_name)
1183 AnnotateTemplateIdTokenAsType(/*IsClassName*/true);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001184
Douglas Gregor18473f32010-01-12 21:28:44 +00001185 // If we didn't end up with a typename token, there's nothing more we
1186 // can do.
1187 if (Tok.isNot(tok::annot_typename))
1188 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001189
Douglas Gregor18473f32010-01-12 21:28:44 +00001190 // Retrieve the type from the annotation token, consume that token, and
1191 // return.
1192 EndLocation = Tok.getAnnotationEndLoc();
John McCallba7bf592010-08-24 05:47:05 +00001193 ParsedType Type = getTypeAnnotation(Tok);
Richard Smithaf3b3252017-05-18 19:21:48 +00001194 ConsumeAnnotationToken();
Douglas Gregor18473f32010-01-12 21:28:44 +00001195 return Type;
1196 }
1197
Douglas Gregor831c93f2008-11-05 20:51:48 +00001198 // We have an identifier; check whether it is actually a type.
Craig Topper161e4db2014-05-21 06:02:52 +00001199 IdentifierInfo *CorrectedII = nullptr;
Richard Smith600b5262017-01-26 20:40:47 +00001200 ParsedType Type = Actions.getTypeName(
Richard Smith62559bd2017-02-01 21:36:38 +00001201 *Id, IdLoc, getCurScope(), &SS, /*IsClassName=*/true, false, nullptr,
Richard Smith600b5262017-01-26 20:40:47 +00001202 /*IsCtorOrDtorName=*/false,
1203 /*NonTrivialTypeSourceInfo=*/true,
1204 /*IsClassTemplateDeductionContext*/ false, &CorrectedII);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001205 if (!Type) {
Douglas Gregorfe17d252010-02-16 19:09:40 +00001206 Diag(IdLoc, diag::err_expected_class_name);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001207 return true;
Douglas Gregor831c93f2008-11-05 20:51:48 +00001208 }
1209
1210 // Consume the identifier.
Douglas Gregor18473f32010-01-12 21:28:44 +00001211 EndLocation = IdLoc;
Nick Lewycky19b9f952010-07-26 16:56:01 +00001212
1213 // Fake up a Declarator to use with ActOnTypeName.
John McCall084e83d2011-03-24 11:26:52 +00001214 DeclSpec DS(AttrFactory);
Nick Lewycky19b9f952010-07-26 16:56:01 +00001215 DS.SetRangeStart(IdLoc);
1216 DS.SetRangeEnd(EndLocation);
Douglas Gregore7c20652011-03-02 00:47:37 +00001217 DS.getTypeSpecScope() = SS;
Nick Lewycky19b9f952010-07-26 16:56:01 +00001218
Craig Topper161e4db2014-05-21 06:02:52 +00001219 const char *PrevSpec = nullptr;
Nick Lewycky19b9f952010-07-26 16:56:01 +00001220 unsigned DiagID;
Faisal Vali090da2d2018-01-01 18:23:28 +00001221 DS.SetTypeSpecType(TST_typename, IdLoc, PrevSpec, DiagID, Type,
1222 Actions.getASTContext().getPrintingPolicy());
Nick Lewycky19b9f952010-07-26 16:56:01 +00001223
Faisal Vali421b2d12017-12-29 05:41:00 +00001224 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
Nick Lewycky19b9f952010-07-26 16:56:01 +00001225 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
Douglas Gregor831c93f2008-11-05 20:51:48 +00001226}
1227
John McCall8d32c052012-05-22 21:28:12 +00001228void Parser::ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001229 while (Tok.isOneOf(tok::kw___single_inheritance,
1230 tok::kw___multiple_inheritance,
1231 tok::kw___virtual_inheritance)) {
John McCall8d32c052012-05-22 21:28:12 +00001232 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
1233 SourceLocation AttrNameLoc = ConsumeToken();
Craig Topper161e4db2014-05-21 06:02:52 +00001234 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
Erich Keanee891aa92018-07-13 15:07:47 +00001235 ParsedAttr::AS_Keyword);
John McCall8d32c052012-05-22 21:28:12 +00001236 }
1237}
1238
Richard Smith369b9f92012-06-25 21:37:02 +00001239/// Determine whether the following tokens are valid after a type-specifier
1240/// which could be a standalone declaration. This will conservatively return
1241/// true if there's any doubt, and is appropriate for insert-';' fixits.
Richard Smith200f47c2012-07-02 19:14:01 +00001242bool Parser::isValidAfterTypeSpecifier(bool CouldBeBitfield) {
Richard Smith369b9f92012-06-25 21:37:02 +00001243 // This switch enumerates the valid "follow" set for type-specifiers.
1244 switch (Tok.getKind()) {
1245 default: break;
1246 case tok::semi: // struct foo {...} ;
1247 case tok::star: // struct foo {...} * P;
1248 case tok::amp: // struct foo {...} & R = ...
Richard Smith1ac67d12013-01-19 03:48:05 +00001249 case tok::ampamp: // struct foo {...} && R = ...
Richard Smith369b9f92012-06-25 21:37:02 +00001250 case tok::identifier: // struct foo {...} V ;
1251 case tok::r_paren: //(struct foo {...} ) {4}
1252 case tok::annot_cxxscope: // struct foo {...} a:: b;
1253 case tok::annot_typename: // struct foo {...} a ::b;
1254 case tok::annot_template_id: // struct foo {...} a<int> ::b;
1255 case tok::l_paren: // struct foo {...} ( x);
1256 case tok::comma: // __builtin_offsetof(struct foo{...} ,
Richard Smith1ac67d12013-01-19 03:48:05 +00001257 case tok::kw_operator: // struct foo operator ++() {...}
Alp Tokerd3f79c52013-11-24 20:24:54 +00001258 case tok::kw___declspec: // struct foo {...} __declspec(...)
Richard Smith843f18f2014-08-13 02:13:15 +00001259 case tok::l_square: // void f(struct f [ 3])
1260 case tok::ellipsis: // void f(struct f ... [Ns])
Abramo Bagnara152eb392014-08-16 08:29:27 +00001261 // FIXME: we should emit semantic diagnostic when declaration
1262 // attribute is in type attribute position.
1263 case tok::kw___attribute: // struct foo __attribute__((used)) x;
David Majnemer15b311c2016-06-14 03:20:28 +00001264 case tok::annot_pragma_pack: // struct foo {...} _Pragma(pack(pop));
1265 // struct foo {...} _Pragma(section(...));
1266 case tok::annot_pragma_ms_pragma:
1267 // struct foo {...} _Pragma(vtordisp(pop));
1268 case tok::annot_pragma_ms_vtordisp:
1269 // struct foo {...} _Pragma(pointers_to_members(...));
1270 case tok::annot_pragma_ms_pointers_to_members:
Richard Smith369b9f92012-06-25 21:37:02 +00001271 return true;
Richard Smith200f47c2012-07-02 19:14:01 +00001272 case tok::colon:
1273 return CouldBeBitfield; // enum E { ... } : 2;
Reid Klecknercfa91552016-03-21 16:08:49 +00001274 // Microsoft compatibility
1275 case tok::kw___cdecl: // struct foo {...} __cdecl x;
1276 case tok::kw___fastcall: // struct foo {...} __fastcall x;
1277 case tok::kw___stdcall: // struct foo {...} __stdcall x;
1278 case tok::kw___thiscall: // struct foo {...} __thiscall x;
1279 case tok::kw___vectorcall: // struct foo {...} __vectorcall x;
1280 // We will diagnose these calling-convention specifiers on non-function
1281 // declarations later, so claim they are valid after a type specifier.
1282 return getLangOpts().MicrosoftExt;
Richard Smith369b9f92012-06-25 21:37:02 +00001283 // Type qualifiers
1284 case tok::kw_const: // struct foo {...} const x;
1285 case tok::kw_volatile: // struct foo {...} volatile x;
1286 case tok::kw_restrict: // struct foo {...} restrict x;
Richard Smith843f18f2014-08-13 02:13:15 +00001287 case tok::kw__Atomic: // struct foo {...} _Atomic x;
Nico Rieck3e1ee832014-12-04 23:30:25 +00001288 case tok::kw___unaligned: // struct foo {...} __unaligned *x;
Richard Smith1ac67d12013-01-19 03:48:05 +00001289 // Function specifiers
1290 // Note, no 'explicit'. An explicit function must be either a conversion
1291 // operator or a constructor. Either way, it can't have a return type.
1292 case tok::kw_inline: // struct foo inline f();
1293 case tok::kw_virtual: // struct foo virtual f();
1294 case tok::kw_friend: // struct foo friend f();
Richard Smith369b9f92012-06-25 21:37:02 +00001295 // Storage-class specifiers
1296 case tok::kw_static: // struct foo {...} static x;
1297 case tok::kw_extern: // struct foo {...} extern x;
1298 case tok::kw_typedef: // struct foo {...} typedef x;
1299 case tok::kw_register: // struct foo {...} register x;
1300 case tok::kw_auto: // struct foo {...} auto x;
1301 case tok::kw_mutable: // struct foo {...} mutable x;
Richard Smith1ac67d12013-01-19 03:48:05 +00001302 case tok::kw_thread_local: // struct foo {...} thread_local x;
Richard Smith369b9f92012-06-25 21:37:02 +00001303 case tok::kw_constexpr: // struct foo {...} constexpr x;
1304 // As shown above, type qualifiers and storage class specifiers absolutely
1305 // can occur after class specifiers according to the grammar. However,
1306 // almost no one actually writes code like this. If we see one of these,
1307 // it is much more likely that someone missed a semi colon and the
1308 // type/storage class specifier we're seeing is part of the *next*
1309 // intended declaration, as in:
1310 //
1311 // struct foo { ... }
1312 // typedef int X;
1313 //
1314 // We'd really like to emit a missing semicolon error instead of emitting
1315 // an error on the 'int' saying that you can't have two type specifiers in
1316 // the same declaration of X. Because of this, we look ahead past this
1317 // token to see if it's a type specifier. If so, we know the code is
1318 // otherwise invalid, so we can produce the expected semi error.
1319 if (!isKnownToBeTypeSpecifier(NextToken()))
1320 return true;
1321 break;
1322 case tok::r_brace: // struct bar { struct foo {...} }
1323 // Missing ';' at end of struct is accepted as an extension in C mode.
1324 if (!getLangOpts().CPlusPlus)
1325 return true;
1326 break;
Richard Smith52c5b872013-01-29 04:13:32 +00001327 case tok::greater:
1328 // template<class T = class X>
1329 return getLangOpts().CPlusPlus;
Richard Smith369b9f92012-06-25 21:37:02 +00001330 }
1331 return false;
1332}
1333
Douglas Gregor556877c2008-04-13 21:30:24 +00001334/// ParseClassSpecifier - Parse a C++ class-specifier [C++ class] or
1335/// elaborated-type-specifier [C++ dcl.type.elab]; we can't tell which
1336/// until we reach the start of a definition or see a token that
Richard Smithc5b05522012-03-12 07:56:15 +00001337/// cannot start a definition.
Douglas Gregor556877c2008-04-13 21:30:24 +00001338///
1339/// class-specifier: [C++ class]
1340/// class-head '{' member-specification[opt] '}'
1341/// class-head '{' member-specification[opt] '}' attributes[opt]
1342/// class-head:
1343/// class-key identifier[opt] base-clause[opt]
1344/// class-key nested-name-specifier identifier base-clause[opt]
1345/// class-key nested-name-specifier[opt] simple-template-id
1346/// base-clause[opt]
1347/// [GNU] class-key attributes[opt] identifier[opt] base-clause[opt]
Mike Stump11289f42009-09-09 15:08:12 +00001348/// [GNU] class-key attributes[opt] nested-name-specifier
Douglas Gregor556877c2008-04-13 21:30:24 +00001349/// identifier base-clause[opt]
Mike Stump11289f42009-09-09 15:08:12 +00001350/// [GNU] class-key attributes[opt] nested-name-specifier[opt]
Douglas Gregor556877c2008-04-13 21:30:24 +00001351/// simple-template-id base-clause[opt]
1352/// class-key:
1353/// 'class'
1354/// 'struct'
1355/// 'union'
1356///
1357/// elaborated-type-specifier: [C++ dcl.type.elab]
Mike Stump11289f42009-09-09 15:08:12 +00001358/// class-key ::[opt] nested-name-specifier[opt] identifier
1359/// class-key ::[opt] nested-name-specifier[opt] 'template'[opt]
1360/// simple-template-id
Douglas Gregor556877c2008-04-13 21:30:24 +00001361///
1362/// Note that the C++ class-specifier and elaborated-type-specifier,
1363/// together, subsume the C99 struct-or-union-specifier:
1364///
1365/// struct-or-union-specifier: [C99 6.7.2.1]
1366/// struct-or-union identifier[opt] '{' struct-contents '}'
1367/// struct-or-union identifier
1368/// [GNU] struct-or-union attributes[opt] identifier[opt] '{' struct-contents
1369/// '}' attributes[opt]
1370/// [GNU] struct-or-union attributes[opt] identifier
1371/// struct-or-union:
1372/// 'struct'
1373/// 'union'
Chris Lattnerffaa0e62009-04-12 21:49:30 +00001374void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind,
1375 SourceLocation StartLoc, DeclSpec &DS,
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001376 const ParsedTemplateInfo &TemplateInfo,
Fangrui Song6907ce22018-07-30 19:24:48 +00001377 AccessSpecifier AS,
1378 bool EnteringContext, DeclSpecContext DSC,
Bill Wendling44426052012-12-20 19:22:21 +00001379 ParsedAttributesWithRange &Attributes) {
Joao Matose9a3ed42012-08-31 22:18:20 +00001380 DeclSpec::TST TagType;
1381 if (TagTokKind == tok::kw_struct)
1382 TagType = DeclSpec::TST_struct;
1383 else if (TagTokKind == tok::kw___interface)
1384 TagType = DeclSpec::TST_interface;
1385 else if (TagTokKind == tok::kw_class)
1386 TagType = DeclSpec::TST_class;
1387 else {
Chris Lattnerffaa0e62009-04-12 21:49:30 +00001388 assert(TagTokKind == tok::kw_union && "Not a class specifier");
1389 TagType = DeclSpec::TST_union;
1390 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001391
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00001392 if (Tok.is(tok::code_completion)) {
1393 // Code completion for a struct, class, or union name.
Douglas Gregor0be31a22010-07-02 17:43:08 +00001394 Actions.CodeCompleteTag(getCurScope(), TagType);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001395 return cutOffParsing();
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00001396 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001397
Chandler Carruth2d69ec72010-06-28 08:39:25 +00001398 // C++03 [temp.explicit] 14.7.2/8:
1399 // The usual access checking rules do not apply to names used to specify
1400 // explicit instantiations.
1401 //
1402 // As an extension we do not perform access checking on the names used to
1403 // specify explicit specializations either. This is important to allow
1404 // specializing traits classes for private types.
John McCall6347b682012-05-07 06:16:58 +00001405 //
1406 // Note that we don't suppress if this turns out to be an elaborated
1407 // type specifier.
1408 bool shouldDelayDiagsInTag =
1409 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
1410 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
1411 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
Chandler Carruth2d69ec72010-06-28 08:39:25 +00001412
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001413 ParsedAttributesWithRange attrs(AttrFactory);
Douglas Gregor556877c2008-04-13 21:30:24 +00001414 // If attributes exist after tag, parse them.
Richard Smith37a45dd2013-10-24 01:21:09 +00001415 MaybeParseGNUAttributes(attrs);
Aaron Ballman068aa512015-05-20 20:58:33 +00001416 MaybeParseMicrosoftDeclSpecs(attrs);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001417
John McCall8d32c052012-05-22 21:28:12 +00001418 // Parse inheritance specifiers.
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001419 if (Tok.isOneOf(tok::kw___single_inheritance,
1420 tok::kw___multiple_inheritance,
1421 tok::kw___virtual_inheritance))
Richard Smith37a45dd2013-10-24 01:21:09 +00001422 ParseMicrosoftInheritanceClassAttributes(attrs);
John McCall8d32c052012-05-22 21:28:12 +00001423
Alexis Hunt96d5c762009-11-21 08:43:09 +00001424 // If C++0x attributes exist here, parse them.
1425 // FIXME: Are we consistent with the ordering of parsing of different
1426 // styles of attributes?
Richard Smith89645bc2013-01-02 12:01:23 +00001427 MaybeParseCXX11Attributes(attrs);
Mike Stump11289f42009-09-09 15:08:12 +00001428
Michael Han309af292013-01-07 16:57:11 +00001429 // Source location used by FIXIT to insert misplaced
1430 // C++11 attributes
1431 SourceLocation AttrFixitLoc = Tok.getLocation();
1432
Nico Weber7c3c5be2014-09-23 04:09:56 +00001433 if (TagType == DeclSpec::TST_struct &&
David Majnemer86330af2014-12-29 02:14:26 +00001434 Tok.isNot(tok::identifier) &&
1435 !Tok.isAnnotation() &&
Nico Weber7c3c5be2014-09-23 04:09:56 +00001436 Tok.getIdentifierInfo() &&
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001437 Tok.isOneOf(tok::kw___is_abstract,
Eric Fiselier07360662017-04-12 22:12:15 +00001438 tok::kw___is_aggregate,
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001439 tok::kw___is_arithmetic,
1440 tok::kw___is_array,
David Majnemerb3d96882016-05-23 17:21:55 +00001441 tok::kw___is_assignable,
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001442 tok::kw___is_base_of,
1443 tok::kw___is_class,
1444 tok::kw___is_complete_type,
1445 tok::kw___is_compound,
1446 tok::kw___is_const,
1447 tok::kw___is_constructible,
1448 tok::kw___is_convertible,
1449 tok::kw___is_convertible_to,
1450 tok::kw___is_destructible,
1451 tok::kw___is_empty,
1452 tok::kw___is_enum,
1453 tok::kw___is_floating_point,
1454 tok::kw___is_final,
1455 tok::kw___is_function,
1456 tok::kw___is_fundamental,
1457 tok::kw___is_integral,
1458 tok::kw___is_interface_class,
1459 tok::kw___is_literal,
1460 tok::kw___is_lvalue_expr,
1461 tok::kw___is_lvalue_reference,
1462 tok::kw___is_member_function_pointer,
1463 tok::kw___is_member_object_pointer,
1464 tok::kw___is_member_pointer,
1465 tok::kw___is_nothrow_assignable,
1466 tok::kw___is_nothrow_constructible,
1467 tok::kw___is_nothrow_destructible,
1468 tok::kw___is_object,
1469 tok::kw___is_pod,
1470 tok::kw___is_pointer,
1471 tok::kw___is_polymorphic,
1472 tok::kw___is_reference,
1473 tok::kw___is_rvalue_expr,
1474 tok::kw___is_rvalue_reference,
1475 tok::kw___is_same,
1476 tok::kw___is_scalar,
1477 tok::kw___is_sealed,
1478 tok::kw___is_signed,
1479 tok::kw___is_standard_layout,
1480 tok::kw___is_trivial,
1481 tok::kw___is_trivially_assignable,
1482 tok::kw___is_trivially_constructible,
1483 tok::kw___is_trivially_copyable,
1484 tok::kw___is_union,
1485 tok::kw___is_unsigned,
1486 tok::kw___is_void,
1487 tok::kw___is_volatile))
Nico Weber7c3c5be2014-09-23 04:09:56 +00001488 // GNU libstdc++ 4.2 and libc++ use certain intrinsic names as the
1489 // name of struct templates, but some are keywords in GCC >= 4.3
1490 // and Clang. Therefore, when we see the token sequence "struct
1491 // X", make X into a normal identifier rather than a keyword, to
1492 // allow libstdc++ 4.2 and libc++ to work properly.
1493 TryKeywordIdentFallback(true);
Mike Stump11289f42009-09-09 15:08:12 +00001494
David Majnemer51fd8a02015-07-22 23:46:18 +00001495 struct PreserveAtomicIdentifierInfoRAII {
1496 PreserveAtomicIdentifierInfoRAII(Token &Tok, bool Enabled)
1497 : AtomicII(nullptr) {
1498 if (!Enabled)
1499 return;
1500 assert(Tok.is(tok::kw__Atomic));
1501 AtomicII = Tok.getIdentifierInfo();
1502 AtomicII->revertTokenIDToIdentifier();
1503 Tok.setKind(tok::identifier);
1504 }
1505 ~PreserveAtomicIdentifierInfoRAII() {
1506 if (!AtomicII)
1507 return;
1508 AtomicII->revertIdentifierToTokenID(tok::kw__Atomic);
1509 }
1510 IdentifierInfo *AtomicII;
1511 };
1512
1513 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
1514 // implementation for VS2013 uses _Atomic as an identifier for one of the
1515 // classes in <atomic>. When we are parsing 'struct _Atomic', don't consider
1516 // '_Atomic' to be a keyword. We are careful to undo this so that clang can
1517 // use '_Atomic' in its own header files.
1518 bool ShouldChangeAtomicToIdentifier = getLangOpts().MSVCCompat &&
1519 Tok.is(tok::kw__Atomic) &&
1520 TagType == DeclSpec::TST_struct;
1521 PreserveAtomicIdentifierInfoRAII AtomicTokenGuard(
1522 Tok, ShouldChangeAtomicToIdentifier);
1523
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001524 // Parse the (optional) nested-name-specifier.
John McCall9dab4e62009-12-12 11:40:51 +00001525 CXXScopeSpec &SS = DS.getTypeSpecScope();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001526 if (getLangOpts().CPlusPlus) {
Serge Pavlov458ea762014-07-16 05:16:52 +00001527 // "FOO : BAR" is not a potential typo for "FOO::BAR". In this context it
1528 // is a base-specifier-list.
Chris Lattnerd5c1c9d2009-12-10 00:32:41 +00001529 ColonProtectionRAIIObject X(*this);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001530
Nico Webercfaa4cd2015-02-15 07:26:13 +00001531 CXXScopeSpec Spec;
1532 bool HasValidSpec = true;
David Blaikieefdccaa2016-01-15 23:43:34 +00001533 if (ParseOptionalCXXScopeSpecifier(Spec, nullptr, EnteringContext)) {
John McCall413021a2010-07-30 06:26:29 +00001534 DS.SetTypeSpecError();
Nico Webercfaa4cd2015-02-15 07:26:13 +00001535 HasValidSpec = false;
1536 }
1537 if (Spec.isSet())
1538 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::annot_template_id)) {
Alp Tokerec543272013-12-24 09:48:30 +00001539 Diag(Tok, diag::err_expected) << tok::identifier;
Nico Webercfaa4cd2015-02-15 07:26:13 +00001540 HasValidSpec = false;
1541 }
1542 if (HasValidSpec)
1543 SS = Spec;
Chris Lattnerd5c1c9d2009-12-10 00:32:41 +00001544 }
Douglas Gregor67a65642009-02-17 23:15:12 +00001545
Douglas Gregor916462b2009-10-30 21:46:58 +00001546 TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
1547
Douglas Gregor67a65642009-02-17 23:15:12 +00001548 // Parse the (optional) class name or simple-template-id.
Craig Topper161e4db2014-05-21 06:02:52 +00001549 IdentifierInfo *Name = nullptr;
Douglas Gregor556877c2008-04-13 21:30:24 +00001550 SourceLocation NameLoc;
Craig Topper161e4db2014-05-21 06:02:52 +00001551 TemplateIdAnnotation *TemplateId = nullptr;
Douglas Gregor556877c2008-04-13 21:30:24 +00001552 if (Tok.is(tok::identifier)) {
1553 Name = Tok.getIdentifierInfo();
1554 NameLoc = ConsumeToken();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001555
David Blaikiebbafb8a2012-03-11 07:00:24 +00001556 if (Tok.is(tok::less) && getLangOpts().CPlusPlus) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001557 // The name was supposed to refer to a template, but didn't.
Douglas Gregor916462b2009-10-30 21:46:58 +00001558 // Eat the template argument list and try to continue parsing this as
1559 // a class (or template thereof).
1560 TemplateArgList TemplateArgs;
Douglas Gregor916462b2009-10-30 21:46:58 +00001561 SourceLocation LAngleLoc, RAngleLoc;
Richard Smith9a420f92017-05-10 21:47:30 +00001562 if (ParseTemplateIdAfterTemplateName(true, LAngleLoc, TemplateArgs,
1563 RAngleLoc)) {
Douglas Gregor916462b2009-10-30 21:46:58 +00001564 // We couldn't parse the template argument list at all, so don't
1565 // try to give any location information for the list.
1566 LAngleLoc = RAngleLoc = SourceLocation();
1567 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001568
Douglas Gregor916462b2009-10-30 21:46:58 +00001569 Diag(NameLoc, diag::err_explicit_spec_non_template)
Alp Toker01d65e12014-01-06 12:54:41 +00001570 << (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
1571 << TagTokKind << Name << SourceRange(LAngleLoc, RAngleLoc);
Joao Matose9a3ed42012-08-31 22:18:20 +00001572
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001573 // Strip off the last template parameter list if it was empty, since
Douglas Gregor1d0015f2009-10-30 22:09:44 +00001574 // we've removed its template argument list.
1575 if (TemplateParams && TemplateInfo.LastParameterListWasEmpty) {
Hubert Tong97b06632016-04-13 18:41:03 +00001576 if (TemplateParams->size() > 1) {
Douglas Gregor1d0015f2009-10-30 22:09:44 +00001577 TemplateParams->pop_back();
1578 } else {
Craig Topper161e4db2014-05-21 06:02:52 +00001579 TemplateParams = nullptr;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001580 const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind
Douglas Gregor1d0015f2009-10-30 22:09:44 +00001581 = ParsedTemplateInfo::NonTemplate;
1582 }
1583 } else if (TemplateInfo.Kind
1584 == ParsedTemplateInfo::ExplicitInstantiation) {
1585 // Pretend this is just a forward declaration.
Craig Topper161e4db2014-05-21 06:02:52 +00001586 TemplateParams = nullptr;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001587 const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind
Douglas Gregor916462b2009-10-30 21:46:58 +00001588 = ParsedTemplateInfo::NonTemplate;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001589 const_cast<ParsedTemplateInfo&>(TemplateInfo).TemplateLoc
Douglas Gregor1d0015f2009-10-30 22:09:44 +00001590 = SourceLocation();
1591 const_cast<ParsedTemplateInfo&>(TemplateInfo).ExternLoc
1592 = SourceLocation();
Douglas Gregor916462b2009-10-30 21:46:58 +00001593 }
Douglas Gregor916462b2009-10-30 21:46:58 +00001594 }
Douglas Gregor7f741122009-02-25 19:37:18 +00001595 } else if (Tok.is(tok::annot_template_id)) {
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00001596 TemplateId = takeTemplateIdAnnotation(Tok);
Richard Smithaf3b3252017-05-18 19:21:48 +00001597 NameLoc = ConsumeAnnotationToken();
Douglas Gregor67a65642009-02-17 23:15:12 +00001598
Douglas Gregore7c20652011-03-02 00:47:37 +00001599 if (TemplateId->Kind != TNK_Type_template &&
1600 TemplateId->Kind != TNK_Dependent_template_name) {
Douglas Gregor7f741122009-02-25 19:37:18 +00001601 // The template-name in the simple-template-id refers to
1602 // something other than a class template. Give an appropriate
1603 // error message and skip to the ';'.
1604 SourceRange Range(NameLoc);
1605 if (SS.isNotEmpty())
1606 Range.setBegin(SS.getBeginLoc());
Douglas Gregor67a65642009-02-17 23:15:12 +00001607
Richard Smith72bfbd82013-12-04 00:28:23 +00001608 // FIXME: Name may be null here.
Douglas Gregor7f741122009-02-25 19:37:18 +00001609 Diag(TemplateId->LAngleLoc, diag::err_template_spec_syntax_non_template)
Richard Trieu30f93852013-06-19 22:25:01 +00001610 << TemplateId->Name << static_cast<int>(TemplateId->Kind) << Range;
Mike Stump11289f42009-09-09 15:08:12 +00001611
Douglas Gregor7f741122009-02-25 19:37:18 +00001612 DS.SetTypeSpecError();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001613 SkipUntil(tok::semi, StopBeforeMatch);
Douglas Gregor7f741122009-02-25 19:37:18 +00001614 return;
Douglas Gregor67a65642009-02-17 23:15:12 +00001615 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001616 }
1617
Richard Smithbfdb1082012-03-12 08:56:40 +00001618 // There are four options here.
1619 // - If we are in a trailing return type, this is always just a reference,
1620 // and we must not try to parse a definition. For instance,
1621 // [] () -> struct S { };
1622 // does not define a type.
1623 // - If we have 'struct foo {...', 'struct foo :...',
1624 // 'struct foo final :' or 'struct foo final {', then this is a definition.
1625 // - If we have 'struct foo;', then this is either a forward declaration
1626 // or a friend declaration, which have to be treated differently.
1627 // - Otherwise we have something like 'struct foo xyz', a reference.
Michael Han9407e502012-11-26 22:54:45 +00001628 //
1629 // We also detect these erroneous cases to provide better diagnostic for
1630 // C++11 attributes parsing.
1631 // - attributes follow class name:
1632 // struct foo [[]] {};
1633 // - attributes appear before or after 'final':
1634 // struct foo [[]] final [[]] {};
1635 //
Richard Smithc5b05522012-03-12 07:56:15 +00001636 // However, in type-specifier-seq's, things look like declarations but are
1637 // just references, e.g.
1638 // new struct s;
Sebastian Redl2b372722010-02-03 21:21:43 +00001639 // or
Richard Smithc5b05522012-03-12 07:56:15 +00001640 // &T::operator struct s;
Faisal Vali7db85c52017-12-31 00:06:40 +00001641 // For these, DSC is DeclSpecContext::DSC_type_specifier or
1642 // DeclSpecContext::DSC_alias_declaration.
Michael Han9407e502012-11-26 22:54:45 +00001643
1644 // If there are attributes after class name, parse them.
Richard Smith89645bc2013-01-02 12:01:23 +00001645 MaybeParseCXX11Attributes(Attributes);
Michael Han9407e502012-11-26 22:54:45 +00001646
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001647 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
John McCallfaf5fb42010-08-26 23:41:50 +00001648 Sema::TagUseKind TUK;
Faisal Vali7db85c52017-12-31 00:06:40 +00001649 if (DSC == DeclSpecContext::DSC_trailing)
Richard Smithbfdb1082012-03-12 08:56:40 +00001650 TUK = Sema::TUK_Reference;
1651 else if (Tok.is(tok::l_brace) ||
1652 (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
Richard Smith89645bc2013-01-02 12:01:23 +00001653 (isCXX11FinalKeyword() &&
David Blaikie9933a5a2012-03-12 15:39:49 +00001654 (NextToken().is(tok::l_brace) || NextToken().is(tok::colon)))) {
Douglas Gregor3dad8422009-09-26 06:47:28 +00001655 if (DS.isFriendSpecified()) {
1656 // C++ [class.friend]p2:
1657 // A class shall not be defined in a friend declaration.
Richard Smith0f8ee222012-01-10 01:33:14 +00001658 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
Douglas Gregor3dad8422009-09-26 06:47:28 +00001659 << SourceRange(DS.getFriendSpecLoc());
1660
1661 // Skip everything up to the semicolon, so that this looks like a proper
1662 // friend class (or template thereof) declaration.
Alexey Bataevee6507d2013-11-18 08:17:37 +00001663 SkipUntil(tok::semi, StopBeforeMatch);
John McCallfaf5fb42010-08-26 23:41:50 +00001664 TUK = Sema::TUK_Friend;
Douglas Gregor3dad8422009-09-26 06:47:28 +00001665 } else {
1666 // Okay, this is a class definition.
John McCallfaf5fb42010-08-26 23:41:50 +00001667 TUK = Sema::TUK_Definition;
Douglas Gregor3dad8422009-09-26 06:47:28 +00001668 }
Richard Smith434516c2013-02-22 06:46:23 +00001669 } else if (isCXX11FinalKeyword() && (NextToken().is(tok::l_square) ||
1670 NextToken().is(tok::kw_alignas))) {
Michael Han9407e502012-11-26 22:54:45 +00001671 // We can't tell if this is a definition or reference
1672 // until we skipped the 'final' and C++11 attribute specifiers.
1673 TentativeParsingAction PA(*this);
1674
1675 // Skip the 'final' keyword.
1676 ConsumeToken();
1677
1678 // Skip C++11 attribute specifiers.
1679 while (true) {
1680 if (Tok.is(tok::l_square) && NextToken().is(tok::l_square)) {
1681 ConsumeBracket();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001682 if (!SkipUntil(tok::r_square, StopAtSemi))
Michael Han9407e502012-11-26 22:54:45 +00001683 break;
Richard Smith434516c2013-02-22 06:46:23 +00001684 } else if (Tok.is(tok::kw_alignas) && NextToken().is(tok::l_paren)) {
Michael Han9407e502012-11-26 22:54:45 +00001685 ConsumeToken();
1686 ConsumeParen();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001687 if (!SkipUntil(tok::r_paren, StopAtSemi))
Michael Han9407e502012-11-26 22:54:45 +00001688 break;
1689 } else {
1690 break;
1691 }
1692 }
1693
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001694 if (Tok.isOneOf(tok::l_brace, tok::colon))
Michael Han9407e502012-11-26 22:54:45 +00001695 TUK = Sema::TUK_Definition;
1696 else
1697 TUK = Sema::TUK_Reference;
1698
1699 PA.Revert();
Richard Smith649c7b062014-01-08 00:56:48 +00001700 } else if (!isTypeSpecifier(DSC) &&
Richard Smith369b9f92012-06-25 21:37:02 +00001701 (Tok.is(tok::semi) ||
Richard Smith200f47c2012-07-02 19:14:01 +00001702 (Tok.isAtStartOfLine() && !isValidAfterTypeSpecifier(false)))) {
John McCallfaf5fb42010-08-26 23:41:50 +00001703 TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
Joao Matose9a3ed42012-08-31 22:18:20 +00001704 if (Tok.isNot(tok::semi)) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001705 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
Joao Matose9a3ed42012-08-31 22:18:20 +00001706 // A semicolon was missing after this declaration. Diagnose and recover.
Alp Toker383d2c42014-01-01 03:08:43 +00001707 ExpectAndConsume(tok::semi, diag::err_expected_after,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001708 DeclSpec::getSpecifierName(TagType, PPol));
Joao Matose9a3ed42012-08-31 22:18:20 +00001709 PP.EnterToken(Tok);
1710 Tok.setKind(tok::semi);
1711 }
Richard Smith369b9f92012-06-25 21:37:02 +00001712 } else
John McCallfaf5fb42010-08-26 23:41:50 +00001713 TUK = Sema::TUK_Reference;
Douglas Gregor556877c2008-04-13 21:30:24 +00001714
Michael Han9407e502012-11-26 22:54:45 +00001715 // Forbid misplaced attributes. In cases of a reference, we pass attributes
1716 // to caller to handle.
Michael Han309af292013-01-07 16:57:11 +00001717 if (TUK != Sema::TUK_Reference) {
1718 // If this is not a reference, then the only possible
1719 // valid place for C++11 attributes to appear here
1720 // is between class-key and class-name. If there are
1721 // any attributes after class-name, we try a fixit to move
1722 // them to the right place.
1723 SourceRange AttrRange = Attributes.Range;
1724 if (AttrRange.isValid()) {
1725 Diag(AttrRange.getBegin(), diag::err_attributes_not_allowed)
1726 << AttrRange
1727 << FixItHint::CreateInsertionFromRange(AttrFixitLoc,
1728 CharSourceRange(AttrRange, true))
1729 << FixItHint::CreateRemoval(AttrRange);
1730
1731 // Recover by adding misplaced attributes to the attribute list
1732 // of the class so they can be applied on the class later.
1733 attrs.takeAllFrom(Attributes);
1734 }
1735 }
Michael Han9407e502012-11-26 22:54:45 +00001736
John McCall6347b682012-05-07 06:16:58 +00001737 // If this is an elaborated type specifier, and we delayed
1738 // diagnostics before, just merge them into the current pool.
1739 if (shouldDelayDiagsInTag) {
1740 diagsFromTag.done();
1741 if (TUK == Sema::TUK_Reference)
1742 diagsFromTag.redelay();
1743 }
1744
John McCall413021a2010-07-30 06:26:29 +00001745 if (!Name && !TemplateId && (DS.getTypeSpecType() == DeclSpec::TST_error ||
John McCallfaf5fb42010-08-26 23:41:50 +00001746 TUK != Sema::TUK_Definition)) {
John McCall413021a2010-07-30 06:26:29 +00001747 if (DS.getTypeSpecType() != DeclSpec::TST_error) {
1748 // We have a declaration or reference to an anonymous class.
1749 Diag(StartLoc, diag::err_anon_type_definition)
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001750 << DeclSpec::getSpecifierName(TagType, Policy);
John McCall413021a2010-07-30 06:26:29 +00001751 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001752
David Majnemer3252fd02013-12-05 01:36:53 +00001753 // If we are parsing a definition and stop at a base-clause, continue on
1754 // until the semicolon. Continuing from the comma will just trick us into
1755 // thinking we are seeing a variable declaration.
1756 if (TUK == Sema::TUK_Definition && Tok.is(tok::colon))
1757 SkipUntil(tok::semi, StopBeforeMatch);
1758 else
1759 SkipUntil(tok::comma, StopAtSemi);
Douglas Gregor556877c2008-04-13 21:30:24 +00001760 return;
1761 }
1762
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001763 // Create the tag portion of the class or class template.
John McCall48871652010-08-21 09:40:31 +00001764 DeclResult TagOrTempResult = true; // invalid
1765 TypeResult TypeResult = true; // invalid
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001766
Douglas Gregord6ab8742009-05-28 23:31:59 +00001767 bool Owned = false;
Richard Smithd9ba2242015-05-07 03:54:19 +00001768 Sema::SkipBodyInfo SkipBody;
John McCall06f6fe8d2009-09-04 01:14:41 +00001769 if (TemplateId) {
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001770 // Explicit specialization, class template partial specialization,
1771 // or explicit instantiation.
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00001772 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregor7f741122009-02-25 19:37:18 +00001773 TemplateId->NumArgs);
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001774 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
John McCallfaf5fb42010-08-26 23:41:50 +00001775 TUK == Sema::TUK_Declaration) {
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001776 // This is an explicit instantiation of a class template.
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001777 ProhibitAttributes(attrs);
1778
Erich Keanec480f302018-07-12 21:09:05 +00001779 TagOrTempResult = Actions.ActOnExplicitInstantiation(
1780 getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc,
1781 TagType, StartLoc, SS, TemplateId->Template,
1782 TemplateId->TemplateNameLoc, TemplateId->LAngleLoc, TemplateArgsPtr,
1783 TemplateId->RAngleLoc, attrs);
John McCallb7c5c272010-04-14 00:24:33 +00001784
Erich Keanec480f302018-07-12 21:09:05 +00001785 // Friend template-ids are treated as references unless
1786 // they have template headers, in which case they're ill-formed
1787 // (FIXME: "template <class T> friend class A<T>::B<int>;").
1788 // We diagnose this error in ActOnClassTemplateSpecialization.
John McCallfaf5fb42010-08-26 23:41:50 +00001789 } else if (TUK == Sema::TUK_Reference ||
1790 (TUK == Sema::TUK_Friend &&
John McCallb7c5c272010-04-14 00:24:33 +00001791 TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate)) {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001792 ProhibitAttributes(attrs);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00001793 TypeResult = Actions.ActOnTagTemplateIdType(TUK, TagType, StartLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00001794 TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00001795 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00001796 TemplateId->Template,
1797 TemplateId->TemplateNameLoc,
1798 TemplateId->LAngleLoc,
1799 TemplateArgsPtr,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00001800 TemplateId->RAngleLoc);
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001801 } else {
1802 // This is an explicit specialization or a class template
1803 // partial specialization.
1804 TemplateParameterLists FakedParamLists;
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001805 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1806 // This looks like an explicit instantiation, because we have
1807 // something like
1808 //
1809 // template class Foo<X>
1810 //
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001811 // but it actually has a definition. Most likely, this was
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001812 // meant to be an explicit specialization, but the user forgot
1813 // the '<>' after 'template'.
Richard Smith003c5e12013-11-08 19:03:29 +00001814 // It this is friend declaration however, since it cannot have a
1815 // template header, it is most likely that the user meant to
1816 // remove the 'template' keyword.
Larisse Voufob9bbaba2013-06-22 13:56:11 +00001817 assert((TUK == Sema::TUK_Definition || TUK == Sema::TUK_Friend) &&
Richard Smith003c5e12013-11-08 19:03:29 +00001818 "Expected a definition here");
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001819
Richard Smith003c5e12013-11-08 19:03:29 +00001820 if (TUK == Sema::TUK_Friend) {
1821 Diag(DS.getFriendSpecLoc(), diag::err_friend_explicit_instantiation);
Craig Topper161e4db2014-05-21 06:02:52 +00001822 TemplateParams = nullptr;
Richard Smith003c5e12013-11-08 19:03:29 +00001823 } else {
1824 SourceLocation LAngleLoc =
1825 PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
1826 Diag(TemplateId->TemplateNameLoc,
1827 diag::err_explicit_instantiation_with_definition)
1828 << SourceRange(TemplateInfo.TemplateLoc)
1829 << FixItHint::CreateInsertion(LAngleLoc, "<>");
1830
1831 // Create a fake template parameter list that contains only
1832 // "template<>", so that we treat this construct as a class
1833 // template specialization.
1834 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
Craig Topper96225a52015-12-24 23:58:25 +00001835 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
Hubert Tongf608c052016-04-29 18:05:37 +00001836 LAngleLoc, nullptr));
Richard Smith003c5e12013-11-08 19:03:29 +00001837 TemplateParams = &FakedParamLists;
1838 }
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001839 }
1840
1841 // Build the class template specialization.
Richard Smith4b55a9c2014-04-17 03:29:33 +00001842 TagOrTempResult = Actions.ActOnClassTemplateSpecialization(
1843 getCurScope(), TagType, TUK, StartLoc, DS.getModulePrivateSpecLoc(),
Erich Keanec480f302018-07-12 21:09:05 +00001844 *TemplateId, attrs,
Craig Topper161e4db2014-05-21 06:02:52 +00001845 MultiTemplateParamsArg(TemplateParams ? &(*TemplateParams)[0]
1846 : nullptr,
Richard Smithc7e6ff02015-05-18 20:36:47 +00001847 TemplateParams ? TemplateParams->size() : 0),
1848 &SkipBody);
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001849 }
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001850 } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
John McCallfaf5fb42010-08-26 23:41:50 +00001851 TUK == Sema::TUK_Declaration) {
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001852 // Explicit instantiation of a member of a class template
1853 // specialization, e.g.,
1854 //
1855 // template struct Outer<int>::Inner;
1856 //
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001857 ProhibitAttributes(attrs);
1858
Erich Keanec480f302018-07-12 21:09:05 +00001859 TagOrTempResult = Actions.ActOnExplicitInstantiation(
1860 getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc,
1861 TagType, StartLoc, SS, Name, NameLoc, attrs);
John McCallace48cd2010-10-19 01:40:49 +00001862 } else if (TUK == Sema::TUK_Friend &&
1863 TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate) {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001864 ProhibitAttributes(attrs);
1865
Erich Keanec480f302018-07-12 21:09:05 +00001866 TagOrTempResult = Actions.ActOnTemplatedFriendTag(
1867 getCurScope(), DS.getFriendSpecLoc(), TagType, StartLoc, SS, Name,
1868 NameLoc, attrs,
1869 MultiTemplateParamsArg(TemplateParams ? &(*TemplateParams)[0] : nullptr,
1870 TemplateParams ? TemplateParams->size() : 0));
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001871 } else {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001872 if (TUK != Sema::TUK_Declaration && TUK != Sema::TUK_Definition)
1873 ProhibitAttributes(attrs);
Richard Smith003c5e12013-11-08 19:03:29 +00001874
Larisse Voufo725de3e2013-06-21 00:08:46 +00001875 if (TUK == Sema::TUK_Definition &&
1876 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1877 // If the declarator-id is not a template-id, issue a diagnostic and
1878 // recover by ignoring the 'template' keyword.
1879 Diag(Tok, diag::err_template_defn_explicit_instantiation)
1880 << 1 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
Craig Topper161e4db2014-05-21 06:02:52 +00001881 TemplateParams = nullptr;
Larisse Voufo725de3e2013-06-21 00:08:46 +00001882 }
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001883
John McCall7f41d982009-09-11 04:59:25 +00001884 bool IsDependent = false;
1885
John McCall32723e92010-10-19 18:40:57 +00001886 // Don't pass down template parameter lists if this is just a tag
1887 // reference. For example, we don't need the template parameters here:
1888 // template <class T> class A *makeA(T t);
1889 MultiTemplateParamsArg TParams;
1890 if (TUK != Sema::TUK_Reference && TemplateParams)
1891 TParams =
1892 MultiTemplateParamsArg(&(*TemplateParams)[0], TemplateParams->size());
1893
Nico Weber32a0fc72016-09-03 03:01:32 +00001894 stripTypeAttributesOffDeclSpec(attrs, DS, TUK);
David Majnemer936b4112015-04-19 07:53:29 +00001895
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001896 // Declaration or definition of a class type
Faisal Vali7db85c52017-12-31 00:06:40 +00001897 TagOrTempResult = Actions.ActOnTag(
Erich Keanec480f302018-07-12 21:09:05 +00001898 getCurScope(), TagType, TUK, StartLoc, SS, Name, NameLoc, attrs, AS,
1899 DS.getModulePrivateSpecLoc(), TParams, Owned, IsDependent,
1900 SourceLocation(), false, clang::TypeResult(),
Faisal Vali7db85c52017-12-31 00:06:40 +00001901 DSC == DeclSpecContext::DSC_type_specifier,
1902 DSC == DeclSpecContext::DSC_template_param ||
1903 DSC == DeclSpecContext::DSC_template_type_arg,
1904 &SkipBody);
John McCall7f41d982009-09-11 04:59:25 +00001905
1906 // If ActOnTag said the type was dependent, try again with the
1907 // less common call.
John McCallace48cd2010-10-19 01:40:49 +00001908 if (IsDependent) {
1909 assert(TUK == Sema::TUK_Reference || TUK == Sema::TUK_Friend);
Douglas Gregor0be31a22010-07-02 17:43:08 +00001910 TypeResult = Actions.ActOnDependentTag(getCurScope(), TagType, TUK,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001911 SS, Name, StartLoc, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +00001912 }
Douglas Gregor2ec748c2009-05-14 00:28:11 +00001913 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001914
Douglas Gregor556877c2008-04-13 21:30:24 +00001915 // If there is a body, parse it and inform the actions module.
John McCallfaf5fb42010-08-26 23:41:50 +00001916 if (TUK == Sema::TUK_Definition) {
John McCall2d814c32009-12-19 21:48:58 +00001917 assert(Tok.is(tok::l_brace) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00001918 (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
Richard Smith89645bc2013-01-02 12:01:23 +00001919 isCXX11FinalKeyword());
Richard Smithd9ba2242015-05-07 03:54:19 +00001920 if (SkipBody.ShouldSkip)
Richard Smith65ebb4a2015-03-26 04:09:53 +00001921 SkipCXXMemberSpecification(StartLoc, AttrFixitLoc, TagType,
1922 TagOrTempResult.get());
1923 else if (getLangOpts().CPlusPlus)
Michael Han309af292013-01-07 16:57:11 +00001924 ParseCXXMemberSpecification(StartLoc, AttrFixitLoc, attrs, TagType,
1925 TagOrTempResult.get());
Bruno Cardoso Lopesdf0ee342017-07-01 00:06:47 +00001926 else {
1927 Decl *D =
1928 SkipBody.CheckSameAsPrevious ? SkipBody.New : TagOrTempResult.get();
1929 // Parse the definition body.
1930 ParseStructUnionBody(StartLoc, TagType, D);
1931 if (SkipBody.CheckSameAsPrevious &&
1932 !Actions.ActOnDuplicateDefinition(DS, TagOrTempResult.get(),
1933 SkipBody)) {
1934 DS.SetTypeSpecError();
1935 return;
1936 }
1937 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001938 }
1939
Erich Keane2fe684b2017-02-28 20:44:39 +00001940 if (!TagOrTempResult.isInvalid())
Hiroshi Inoue939d9322017-06-30 05:40:31 +00001941 // Delayed processing of attributes.
Erich Keanec480f302018-07-12 21:09:05 +00001942 Actions.ProcessDeclAttributeDelayed(TagOrTempResult.get(), attrs);
Erich Keane2fe684b2017-02-28 20:44:39 +00001943
Craig Topper161e4db2014-05-21 06:02:52 +00001944 const char *PrevSpec = nullptr;
John McCallba7bf592010-08-24 05:47:05 +00001945 unsigned DiagID;
1946 bool Result;
John McCall7f41d982009-09-11 04:59:25 +00001947 if (!TypeResult.isInvalid()) {
Abramo Bagnara9875a3c2011-03-16 20:16:18 +00001948 Result = DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
1949 NameLoc.isValid() ? NameLoc : StartLoc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001950 PrevSpec, DiagID, TypeResult.get(), Policy);
John McCall7f41d982009-09-11 04:59:25 +00001951 } else if (!TagOrTempResult.isInvalid()) {
Abramo Bagnara9875a3c2011-03-16 20:16:18 +00001952 Result = DS.SetTypeSpecType(TagType, StartLoc,
1953 NameLoc.isValid() ? NameLoc : StartLoc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001954 PrevSpec, DiagID, TagOrTempResult.get(), Owned,
1955 Policy);
John McCall7f41d982009-09-11 04:59:25 +00001956 } else {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001957 DS.SetTypeSpecError();
Anders Carlssonf83c9fa2009-05-11 22:27:47 +00001958 return;
1959 }
Mike Stump11289f42009-09-09 15:08:12 +00001960
John McCallba7bf592010-08-24 05:47:05 +00001961 if (Result)
John McCall49bfce42009-08-03 20:12:06 +00001962 Diag(StartLoc, DiagID) << PrevSpec;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001963
Chris Lattnercf251412010-02-02 01:23:29 +00001964 // At this point, we've successfully parsed a class-specifier in 'definition'
1965 // form (e.g. "struct foo { int x; }". While we could just return here, we're
1966 // going to look at what comes after it to improve error recovery. If an
1967 // impossible token occurs next, we assume that the programmer forgot a ; at
1968 // the end of the declaration and recover that way.
1969 //
Richard Smith369b9f92012-06-25 21:37:02 +00001970 // Also enforce C++ [temp]p3:
1971 // In a template-declaration which defines a class, no declarator
1972 // is permitted.
Richard Smith843f18f2014-08-13 02:13:15 +00001973 //
1974 // After a type-specifier, we don't expect a semicolon. This only happens in
1975 // C, since definitions are not permitted in this context in C++.
Joao Matose9a3ed42012-08-31 22:18:20 +00001976 if (TUK == Sema::TUK_Definition &&
Richard Smith843f18f2014-08-13 02:13:15 +00001977 (getLangOpts().CPlusPlus || !isTypeSpecifier(DSC)) &&
Joao Matose9a3ed42012-08-31 22:18:20 +00001978 (TemplateInfo.Kind || !isValidAfterTypeSpecifier(false))) {
Argyrios Kyrtzidise6f69132012-12-17 20:10:43 +00001979 if (Tok.isNot(tok::semi)) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001980 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
Alp Toker383d2c42014-01-01 03:08:43 +00001981 ExpectAndConsume(tok::semi, diag::err_expected_after,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001982 DeclSpec::getSpecifierName(TagType, PPol));
Argyrios Kyrtzidise6f69132012-12-17 20:10:43 +00001983 // Push this token back into the preprocessor and change our current token
1984 // to ';' so that the rest of the code recovers as though there were an
1985 // ';' after the definition.
1986 PP.EnterToken(Tok);
1987 Tok.setKind(tok::semi);
1988 }
Chris Lattnercf251412010-02-02 01:23:29 +00001989 }
Douglas Gregor556877c2008-04-13 21:30:24 +00001990}
1991
Mike Stump11289f42009-09-09 15:08:12 +00001992/// ParseBaseClause - Parse the base-clause of a C++ class [C++ class.derived].
Douglas Gregor556877c2008-04-13 21:30:24 +00001993///
1994/// base-clause : [C++ class.derived]
1995/// ':' base-specifier-list
1996/// base-specifier-list:
1997/// base-specifier '...'[opt]
1998/// base-specifier-list ',' base-specifier '...'[opt]
John McCall48871652010-08-21 09:40:31 +00001999void Parser::ParseBaseClause(Decl *ClassDecl) {
Douglas Gregor556877c2008-04-13 21:30:24 +00002000 assert(Tok.is(tok::colon) && "Not a base clause");
2001 ConsumeToken();
2002
Douglas Gregor29a92472008-10-22 17:49:05 +00002003 // Build up an array of parsed base specifiers.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002004 SmallVector<CXXBaseSpecifier *, 8> BaseInfo;
Douglas Gregor29a92472008-10-22 17:49:05 +00002005
Douglas Gregor556877c2008-04-13 21:30:24 +00002006 while (true) {
2007 // Parse a base-specifier.
Douglas Gregor29a92472008-10-22 17:49:05 +00002008 BaseResult Result = ParseBaseSpecifier(ClassDecl);
Douglas Gregorf8298252009-01-26 22:44:13 +00002009 if (Result.isInvalid()) {
Douglas Gregor556877c2008-04-13 21:30:24 +00002010 // Skip the rest of this base specifier, up until the comma or
2011 // opening brace.
Alexey Bataevee6507d2013-11-18 08:17:37 +00002012 SkipUntil(tok::comma, tok::l_brace, StopAtSemi | StopBeforeMatch);
Douglas Gregor29a92472008-10-22 17:49:05 +00002013 } else {
2014 // Add this to our array of base specifiers.
Douglas Gregorf8298252009-01-26 22:44:13 +00002015 BaseInfo.push_back(Result.get());
Douglas Gregor556877c2008-04-13 21:30:24 +00002016 }
2017
2018 // If the next token is a comma, consume it and keep reading
2019 // base-specifiers.
Alp Toker97650562014-01-10 11:19:30 +00002020 if (!TryConsumeToken(tok::comma))
2021 break;
Douglas Gregor556877c2008-04-13 21:30:24 +00002022 }
Douglas Gregor29a92472008-10-22 17:49:05 +00002023
2024 // Attach the base specifiers
Craig Topperaa700cb2015-12-27 21:55:19 +00002025 Actions.ActOnBaseSpecifiers(ClassDecl, BaseInfo);
Douglas Gregor556877c2008-04-13 21:30:24 +00002026}
2027
2028/// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is
2029/// one entry in the base class list of a class specifier, for example:
2030/// class foo : public bar, virtual private baz {
2031/// 'public bar' and 'virtual private baz' are each base-specifiers.
2032///
2033/// base-specifier: [C++ class.derived]
Richard Smith4c96e992013-02-19 23:47:15 +00002034/// attribute-specifier-seq[opt] base-type-specifier
2035/// attribute-specifier-seq[opt] 'virtual' access-specifier[opt]
2036/// base-type-specifier
2037/// attribute-specifier-seq[opt] access-specifier 'virtual'[opt]
2038/// base-type-specifier
Craig Topper9ad7e262014-10-31 06:57:07 +00002039BaseResult Parser::ParseBaseSpecifier(Decl *ClassDecl) {
Douglas Gregor556877c2008-04-13 21:30:24 +00002040 bool IsVirtual = false;
2041 SourceLocation StartLoc = Tok.getLocation();
2042
Richard Smith4c96e992013-02-19 23:47:15 +00002043 ParsedAttributesWithRange Attributes(AttrFactory);
2044 MaybeParseCXX11Attributes(Attributes);
2045
Douglas Gregor556877c2008-04-13 21:30:24 +00002046 // Parse the 'virtual' keyword.
Alp Toker97650562014-01-10 11:19:30 +00002047 if (TryConsumeToken(tok::kw_virtual))
Douglas Gregor556877c2008-04-13 21:30:24 +00002048 IsVirtual = true;
Douglas Gregor556877c2008-04-13 21:30:24 +00002049
Richard Smith4c96e992013-02-19 23:47:15 +00002050 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2051
Douglas Gregor556877c2008-04-13 21:30:24 +00002052 // Parse an (optional) access specifier.
2053 AccessSpecifier Access = getAccessSpecifierIfPresent();
John McCall553c0792010-01-23 00:46:32 +00002054 if (Access != AS_none)
Douglas Gregor556877c2008-04-13 21:30:24 +00002055 ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +00002056
Richard Smith4c96e992013-02-19 23:47:15 +00002057 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2058
Douglas Gregor556877c2008-04-13 21:30:24 +00002059 // Parse the 'virtual' keyword (again!), in case it came after the
2060 // access specifier.
2061 if (Tok.is(tok::kw_virtual)) {
2062 SourceLocation VirtualLoc = ConsumeToken();
2063 if (IsVirtual) {
2064 // Complain about duplicate 'virtual'
Chris Lattner6d29c102008-11-18 07:48:38 +00002065 Diag(VirtualLoc, diag::err_dup_virtual)
Douglas Gregora771f462010-03-31 17:46:05 +00002066 << FixItHint::CreateRemoval(VirtualLoc);
Douglas Gregor556877c2008-04-13 21:30:24 +00002067 }
2068
2069 IsVirtual = true;
2070 }
2071
Richard Smith4c96e992013-02-19 23:47:15 +00002072 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2073
Douglas Gregor831c93f2008-11-05 20:51:48 +00002074 // Parse the class-name.
David Majnemer51fd8a02015-07-22 23:46:18 +00002075
2076 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
2077 // implementation for VS2013 uses _Atomic as an identifier for one of the
2078 // classes in <atomic>. Treat '_Atomic' to be an identifier when we are
2079 // parsing the class-name for a base specifier.
2080 if (getLangOpts().MSVCCompat && Tok.is(tok::kw__Atomic) &&
2081 NextToken().is(tok::less))
2082 Tok.setKind(tok::identifier);
2083
Douglas Gregord54dfb82009-02-25 23:52:28 +00002084 SourceLocation EndLocation;
David Blaikie1cd50022011-10-25 17:10:12 +00002085 SourceLocation BaseLoc;
2086 TypeResult BaseType = ParseBaseTypeSpecifier(BaseLoc, EndLocation);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00002087 if (BaseType.isInvalid())
Douglas Gregor831c93f2008-11-05 20:51:48 +00002088 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002089
Fangrui Song6907ce22018-07-30 19:24:48 +00002090 // Parse the optional ellipsis (for a pack expansion). The ellipsis is
Douglas Gregor752a5952011-01-03 22:36:02 +00002091 // actually part of the base-specifier-list grammar productions, but we
2092 // parse it here for convenience.
2093 SourceLocation EllipsisLoc;
Alp Toker97650562014-01-10 11:19:30 +00002094 TryConsumeToken(tok::ellipsis, EllipsisLoc);
2095
Mike Stump11289f42009-09-09 15:08:12 +00002096 // Find the complete source range for the base-specifier.
Douglas Gregord54dfb82009-02-25 23:52:28 +00002097 SourceRange Range(StartLoc, EndLocation);
Mike Stump11289f42009-09-09 15:08:12 +00002098
Douglas Gregor556877c2008-04-13 21:30:24 +00002099 // Notify semantic analysis that we have parsed a complete
2100 // base-specifier.
Richard Smith4c96e992013-02-19 23:47:15 +00002101 return Actions.ActOnBaseSpecifier(ClassDecl, Range, Attributes, IsVirtual,
2102 Access, BaseType.get(), BaseLoc,
2103 EllipsisLoc);
Douglas Gregor556877c2008-04-13 21:30:24 +00002104}
2105
2106/// getAccessSpecifierIfPresent - Determine whether the next token is
2107/// a C++ access-specifier.
2108///
2109/// access-specifier: [C++ class.derived]
2110/// 'private'
2111/// 'protected'
2112/// 'public'
Mike Stump11289f42009-09-09 15:08:12 +00002113AccessSpecifier Parser::getAccessSpecifierIfPresent() const {
Douglas Gregor556877c2008-04-13 21:30:24 +00002114 switch (Tok.getKind()) {
2115 default: return AS_none;
2116 case tok::kw_private: return AS_private;
2117 case tok::kw_protected: return AS_protected;
2118 case tok::kw_public: return AS_public;
2119 }
2120}
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002121
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002122/// If the given declarator has any parts for which parsing has to be
Richard Smith0b3a4622014-11-13 20:01:57 +00002123/// delayed, e.g., default arguments or an exception-specification, create a
2124/// late-parsed method declaration record to handle the parsing at the end of
2125/// the class definition.
Douglas Gregor433e0532012-04-16 18:27:27 +00002126void Parser::HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
2127 Decl *ThisDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00002128 DeclaratorChunk::FunctionTypeInfo &FTI
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002129 = DeclaratorInfo.getFunctionTypeInfo();
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002130 // If there was a late-parsed exception-specification, we'll need a
2131 // late parse
2132 bool NeedLateParse = FTI.getExceptionSpecType() == EST_Unparsed;
Douglas Gregor433e0532012-04-16 18:27:27 +00002133
Nathan Sidwell5bb231c2015-02-19 14:03:22 +00002134 if (!NeedLateParse) {
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002135 // Look ahead to see if there are any default args
Nathan Sidwell5bb231c2015-02-19 14:03:22 +00002136 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx) {
2137 auto Param = cast<ParmVarDecl>(FTI.Params[ParamIdx].Param);
2138 if (Param->hasUnparsedDefaultArg()) {
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002139 NeedLateParse = true;
2140 break;
2141 }
Nathan Sidwell5bb231c2015-02-19 14:03:22 +00002142 }
2143 }
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002144
2145 if (NeedLateParse) {
Richard Smith0b3a4622014-11-13 20:01:57 +00002146 // Push this method onto the stack of late-parsed method
2147 // declarations.
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002148 auto LateMethod = new LateParsedMethodDeclaration(this, ThisDecl);
Richard Smith0b3a4622014-11-13 20:01:57 +00002149 getCurrentClass().LateParsedDeclarations.push_back(LateMethod);
2150 LateMethod->TemplateScope = getCurScope()->isTemplateParamScope();
2151
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002152 // Stash the exception-specification tokens in the late-pased method.
Richard Smith0b3a4622014-11-13 20:01:57 +00002153 LateMethod->ExceptionSpecTokens = FTI.ExceptionSpecTokens;
Hans Wennborgdcfba332015-10-06 23:40:43 +00002154 FTI.ExceptionSpecTokens = nullptr;
Richard Smith0b3a4622014-11-13 20:01:57 +00002155
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002156 // Push tokens for each parameter. Those that do not have
2157 // defaults will be NULL.
Richard Smith0b3a4622014-11-13 20:01:57 +00002158 LateMethod->DefaultArgs.reserve(FTI.NumParams);
Nathan Sidwelld5b9a1d2015-01-25 00:25:44 +00002159 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx)
Alp Tokerc5350722014-02-26 22:27:52 +00002160 LateMethod->DefaultArgs.push_back(LateParsedDefaultArgument(
Malcolm Parsonsca9d8342016-11-17 21:00:09 +00002161 FTI.Params[ParamIdx].Param,
2162 std::move(FTI.Params[ParamIdx].DefaultArgTokens)));
Eli Friedman3af2a772009-07-22 21:45:50 +00002163 }
2164}
2165
Richard Smith89645bc2013-01-02 12:01:23 +00002166/// isCXX11VirtSpecifier - Determine whether the given token is a C++11
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002167/// virt-specifier.
2168///
2169/// virt-specifier:
2170/// override
2171/// final
Andrey Bokhanko276055b2016-07-29 10:42:48 +00002172/// __final
Richard Smith89645bc2013-01-02 12:01:23 +00002173VirtSpecifiers::Specifier Parser::isCXX11VirtSpecifier(const Token &Tok) const {
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002174 if (!getLangOpts().CPlusPlus || Tok.isNot(tok::identifier))
Anders Carlsson4b63d0e2011-01-22 16:56:46 +00002175 return VirtSpecifiers::VS_None;
2176
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002177 IdentifierInfo *II = Tok.getIdentifierInfo();
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002178
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002179 // Initialize the contextual keywords.
2180 if (!Ident_final) {
2181 Ident_final = &PP.getIdentifierTable().get("final");
Andrey Bokhanko276055b2016-07-29 10:42:48 +00002182 if (getLangOpts().GNUKeywords)
2183 Ident_GNU_final = &PP.getIdentifierTable().get("__final");
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002184 if (getLangOpts().MicrosoftExt)
2185 Ident_sealed = &PP.getIdentifierTable().get("sealed");
2186 Ident_override = &PP.getIdentifierTable().get("override");
Anders Carlsson56104902011-01-17 03:05:47 +00002187 }
2188
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002189 if (II == Ident_override)
2190 return VirtSpecifiers::VS_Override;
2191
2192 if (II == Ident_sealed)
2193 return VirtSpecifiers::VS_Sealed;
2194
2195 if (II == Ident_final)
2196 return VirtSpecifiers::VS_Final;
2197
Andrey Bokhanko276055b2016-07-29 10:42:48 +00002198 if (II == Ident_GNU_final)
2199 return VirtSpecifiers::VS_GNU_Final;
2200
Anders Carlsson56104902011-01-17 03:05:47 +00002201 return VirtSpecifiers::VS_None;
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002202}
2203
Richard Smith89645bc2013-01-02 12:01:23 +00002204/// ParseOptionalCXX11VirtSpecifierSeq - Parse a virt-specifier-seq.
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002205///
2206/// virt-specifier-seq:
2207/// virt-specifier
2208/// virt-specifier-seq virt-specifier
Richard Smith89645bc2013-01-02 12:01:23 +00002209void Parser::ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS,
Richard Smith3d1a94c2014-08-12 00:22:39 +00002210 bool IsInterface,
2211 SourceLocation FriendLoc) {
Anders Carlsson56104902011-01-17 03:05:47 +00002212 while (true) {
Richard Smith89645bc2013-01-02 12:01:23 +00002213 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
Anders Carlsson56104902011-01-17 03:05:47 +00002214 if (Specifier == VirtSpecifiers::VS_None)
2215 return;
2216
Richard Smith3d1a94c2014-08-12 00:22:39 +00002217 if (FriendLoc.isValid()) {
2218 Diag(Tok.getLocation(), diag::err_friend_decl_spec)
2219 << VirtSpecifiers::getSpecifierName(Specifier)
2220 << FixItHint::CreateRemoval(Tok.getLocation())
2221 << SourceRange(FriendLoc, FriendLoc);
2222 ConsumeToken();
2223 continue;
2224 }
2225
Anders Carlsson56104902011-01-17 03:05:47 +00002226 // C++ [class.mem]p8:
2227 // A virt-specifier-seq shall contain at most one of each virt-specifier.
Craig Topper161e4db2014-05-21 06:02:52 +00002228 const char *PrevSpec = nullptr;
Anders Carlssonf2ca3892011-01-22 15:58:16 +00002229 if (VS.SetSpecifier(Specifier, Tok.getLocation(), PrevSpec))
Anders Carlsson56104902011-01-17 03:05:47 +00002230 Diag(Tok.getLocation(), diag::err_duplicate_virt_specifier)
2231 << PrevSpec
2232 << FixItHint::CreateRemoval(Tok.getLocation());
2233
David Majnemera5433082013-10-18 00:33:31 +00002234 if (IsInterface && (Specifier == VirtSpecifiers::VS_Final ||
2235 Specifier == VirtSpecifiers::VS_Sealed)) {
John McCalldb632ac2012-09-25 07:32:39 +00002236 Diag(Tok.getLocation(), diag::err_override_control_interface)
2237 << VirtSpecifiers::getSpecifierName(Specifier);
David Majnemera5433082013-10-18 00:33:31 +00002238 } else if (Specifier == VirtSpecifiers::VS_Sealed) {
2239 Diag(Tok.getLocation(), diag::ext_ms_sealed_keyword);
Andrey Bokhanko276055b2016-07-29 10:42:48 +00002240 } else if (Specifier == VirtSpecifiers::VS_GNU_Final) {
2241 Diag(Tok.getLocation(), diag::ext_warn_gnu_final);
John McCalldb632ac2012-09-25 07:32:39 +00002242 } else {
David Majnemera5433082013-10-18 00:33:31 +00002243 Diag(Tok.getLocation(),
2244 getLangOpts().CPlusPlus11
2245 ? diag::warn_cxx98_compat_override_control_keyword
2246 : diag::ext_override_control_keyword)
2247 << VirtSpecifiers::getSpecifierName(Specifier);
John McCalldb632ac2012-09-25 07:32:39 +00002248 }
Anders Carlsson56104902011-01-17 03:05:47 +00002249 ConsumeToken();
2250 }
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002251}
2252
Richard Smith89645bc2013-01-02 12:01:23 +00002253/// isCXX11FinalKeyword - Determine whether the next token is a C++11
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002254/// 'final' or Microsoft 'sealed' contextual keyword.
Richard Smith89645bc2013-01-02 12:01:23 +00002255bool Parser::isCXX11FinalKeyword() const {
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002256 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
2257 return Specifier == VirtSpecifiers::VS_Final ||
Fangrui Song6907ce22018-07-30 19:24:48 +00002258 Specifier == VirtSpecifiers::VS_GNU_Final ||
Alp Tokerbb4b86a2014-01-09 00:13:52 +00002259 Specifier == VirtSpecifiers::VS_Sealed;
Anders Carlsson4b63d0e2011-01-22 16:56:46 +00002260}
2261
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002262/// Parse a C++ member-declarator up to, but not including, the optional
Richard Smith72553fc2014-01-23 23:53:27 +00002263/// brace-or-equal-initializer or pure-specifier.
Nico Weberd89e6f72015-01-16 19:34:13 +00002264bool Parser::ParseCXXMemberDeclaratorBeforeInitializer(
Richard Smith72553fc2014-01-23 23:53:27 +00002265 Declarator &DeclaratorInfo, VirtSpecifiers &VS, ExprResult &BitfieldSize,
2266 LateParsedAttrList &LateParsedAttrs) {
2267 // member-declarator:
2268 // declarator pure-specifier[opt]
2269 // declarator brace-or-equal-initializer[opt]
2270 // identifier[opt] ':' constant-expression
Serge Pavlov458ea762014-07-16 05:16:52 +00002271 if (Tok.isNot(tok::colon))
Richard Smith72553fc2014-01-23 23:53:27 +00002272 ParseDeclarator(DeclaratorInfo);
Richard Smith3d1a94c2014-08-12 00:22:39 +00002273 else
2274 DeclaratorInfo.SetIdentifier(nullptr, Tok.getLocation());
Richard Smith72553fc2014-01-23 23:53:27 +00002275
2276 if (!DeclaratorInfo.isFunctionDeclarator() && TryConsumeToken(tok::colon)) {
Richard Smith3d1a94c2014-08-12 00:22:39 +00002277 assert(DeclaratorInfo.isPastIdentifier() &&
2278 "don't know where identifier would go yet?");
Richard Smith72553fc2014-01-23 23:53:27 +00002279 BitfieldSize = ParseConstantExpression();
2280 if (BitfieldSize.isInvalid())
2281 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002282 } else {
Richard Smith3d1a94c2014-08-12 00:22:39 +00002283 ParseOptionalCXX11VirtSpecifierSeq(
2284 VS, getCurrentClass().IsInterface,
2285 DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002286 if (!VS.isUnset())
2287 MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo, VS);
2288 }
Richard Smith72553fc2014-01-23 23:53:27 +00002289
2290 // If a simple-asm-expr is present, parse it.
2291 if (Tok.is(tok::kw_asm)) {
2292 SourceLocation Loc;
2293 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
2294 if (AsmLabel.isInvalid())
2295 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2296
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002297 DeclaratorInfo.setAsmLabel(AsmLabel.get());
Richard Smith72553fc2014-01-23 23:53:27 +00002298 DeclaratorInfo.SetRangeEnd(Loc);
2299 }
2300
2301 // If attributes exist after the declarator, but before an '{', parse them.
2302 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
Richard Smith4b5a9492014-01-24 22:34:35 +00002303
2304 // For compatibility with code written to older Clang, also accept a
2305 // virt-specifier *after* the GNU attributes.
Aaron Ballman5d153e32014-08-04 17:03:51 +00002306 if (BitfieldSize.isUnset() && VS.isUnset()) {
Richard Smith3d1a94c2014-08-12 00:22:39 +00002307 ParseOptionalCXX11VirtSpecifierSeq(
2308 VS, getCurrentClass().IsInterface,
2309 DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
Aaron Ballman5d153e32014-08-04 17:03:51 +00002310 if (!VS.isUnset()) {
2311 // If we saw any GNU-style attributes that are known to GCC followed by a
2312 // virt-specifier, issue a GCC-compat warning.
Erich Keanee891aa92018-07-13 15:07:47 +00002313 for (const ParsedAttr &AL : DeclaratorInfo.getAttributes())
Erich Keanec480f302018-07-12 21:09:05 +00002314 if (AL.isKnownToGCC() && !AL.isCXX11Attribute())
2315 Diag(AL.getLoc(), diag::warn_gcc_attribute_location);
2316
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002317 MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo, VS);
Aaron Ballman5d153e32014-08-04 17:03:51 +00002318 }
2319 }
Nico Weberd89e6f72015-01-16 19:34:13 +00002320
2321 // If this has neither a name nor a bit width, something has gone seriously
2322 // wrong. Skip until the semi-colon or }.
2323 if (!DeclaratorInfo.hasName() && BitfieldSize.isUnset()) {
2324 // If so, skip until the semi-colon or a }.
2325 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2326 return true;
2327 }
2328 return false;
Richard Smith72553fc2014-01-23 23:53:27 +00002329}
2330
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002331/// Look for declaration specifiers possibly occurring after C++11
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002332/// virt-specifier-seq and diagnose them.
2333void Parser::MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(
2334 Declarator &D,
2335 VirtSpecifiers &VS) {
2336 DeclSpec DS(AttrFactory);
2337
2338 // GNU-style and C++11 attributes are not allowed here, but they will be
2339 // handled by the caller. Diagnose everything else.
Alex Lorenz8f4d3992017-02-13 23:19:40 +00002340 ParseTypeQualifierListOpt(
2341 DS, AR_NoAttributesParsed, false,
2342 /*IdentifierRequired=*/false, llvm::function_ref<void()>([&]() {
2343 Actions.CodeCompleteFunctionQualifiers(DS, D, &VS);
2344 }));
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002345 D.ExtendWithDeclSpec(DS);
2346
2347 if (D.isFunctionDeclarator()) {
Ehsan Akhgaric07d1e22015-03-25 00:53:33 +00002348 auto &Function = D.getFunctionTypeInfo();
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002349 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
2350 auto DeclSpecCheck = [&] (DeclSpec::TQ TypeQual,
2351 const char *FixItName,
2352 SourceLocation SpecLoc,
2353 unsigned* QualifierLoc) {
2354 FixItHint Insertion;
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002355 if (DS.getTypeQualifiers() & TypeQual) {
2356 if (!(Function.TypeQuals & TypeQual)) {
2357 std::string Name(FixItName);
2358 Name += " ";
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00002359 Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), Name);
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002360 Function.TypeQuals |= TypeQual;
2361 *QualifierLoc = SpecLoc.getRawEncoding();
2362 }
2363 Diag(SpecLoc, diag::err_declspec_after_virtspec)
2364 << FixItName
2365 << VirtSpecifiers::getSpecifierName(VS.getLastSpecifier())
2366 << FixItHint::CreateRemoval(SpecLoc)
2367 << Insertion;
2368 }
2369 };
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002370 DeclSpecCheck(DeclSpec::TQ_const, "const", DS.getConstSpecLoc(),
2371 &Function.ConstQualifierLoc);
2372 DeclSpecCheck(DeclSpec::TQ_volatile, "volatile", DS.getVolatileSpecLoc(),
2373 &Function.VolatileQualifierLoc);
2374 DeclSpecCheck(DeclSpec::TQ_restrict, "restrict", DS.getRestrictSpecLoc(),
2375 &Function.RestrictQualifierLoc);
2376 }
Ehsan Akhgaric07d1e22015-03-25 00:53:33 +00002377
2378 // Parse ref-qualifiers.
2379 bool RefQualifierIsLValueRef = true;
2380 SourceLocation RefQualifierLoc;
2381 if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc)) {
2382 const char *Name = (RefQualifierIsLValueRef ? "& " : "&& ");
2383 FixItHint Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), Name);
2384 Function.RefQualifierIsLValueRef = RefQualifierIsLValueRef;
2385 Function.RefQualifierLoc = RefQualifierLoc.getRawEncoding();
2386
2387 Diag(RefQualifierLoc, diag::err_declspec_after_virtspec)
2388 << (RefQualifierIsLValueRef ? "&" : "&&")
2389 << VirtSpecifiers::getSpecifierName(VS.getLastSpecifier())
2390 << FixItHint::CreateRemoval(RefQualifierLoc)
2391 << Insertion;
2392 D.SetRangeEnd(RefQualifierLoc);
2393 }
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00002394 }
2395}
2396
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002397/// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration.
2398///
2399/// member-declaration:
2400/// decl-specifier-seq[opt] member-declarator-list[opt] ';'
2401/// function-definition ';'[opt]
2402/// ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO]
2403/// using-declaration [TODO]
Anders Carlssonf24fcff62009-03-11 16:27:10 +00002404/// [C++0x] static_assert-declaration
Anders Carlssondfbbdf62009-03-26 00:52:18 +00002405/// template-declaration
Chris Lattnerd19c1c02008-12-18 01:12:00 +00002406/// [GNU] '__extension__' member-declaration
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002407///
2408/// member-declarator-list:
2409/// member-declarator
2410/// member-declarator-list ',' member-declarator
2411///
2412/// member-declarator:
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002413/// declarator virt-specifier-seq[opt] pure-specifier[opt]
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002414/// declarator constant-initializer[opt]
Richard Smith938f40b2011-06-11 17:19:42 +00002415/// [C++11] declarator brace-or-equal-initializer[opt]
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002416/// identifier[opt] ':' constant-expression
2417///
Anders Carlsson11fdbbc2011-01-16 23:56:42 +00002418/// virt-specifier-seq:
2419/// virt-specifier
2420/// virt-specifier-seq virt-specifier
2421///
2422/// virt-specifier:
2423/// override
2424/// final
David Majnemera5433082013-10-18 00:33:31 +00002425/// [MS] sealed
Fangrui Song6907ce22018-07-30 19:24:48 +00002426///
Sebastian Redl42e92c42009-04-12 17:16:29 +00002427/// pure-specifier:
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002428/// '= 0'
2429///
2430/// constant-initializer:
2431/// '=' constant-expression
2432///
Alexey Bataev05c25d62015-07-31 08:42:25 +00002433Parser::DeclGroupPtrTy
2434Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS,
Erich Keanec480f302018-07-12 21:09:05 +00002435 ParsedAttributes &AccessAttrs,
John McCall796c2a52010-07-16 08:13:16 +00002436 const ParsedTemplateInfo &TemplateInfo,
2437 ParsingDeclRAIIObject *TemplateDiags) {
Douglas Gregor23c84762011-04-14 17:21:19 +00002438 if (Tok.is(tok::at)) {
Erik Pilkingtonfa983902018-10-30 20:31:30 +00002439 if (getLangOpts().ObjC && NextToken().isObjCAtKeyword(tok::objc_defs))
Douglas Gregor23c84762011-04-14 17:21:19 +00002440 Diag(Tok, diag::err_at_defs_cxx);
2441 else
2442 Diag(Tok, diag::err_at_in_class);
Richard Smithda35e962013-11-09 04:52:51 +00002443
Douglas Gregor23c84762011-04-14 17:21:19 +00002444 ConsumeToken();
Alexey Bataevee6507d2013-11-18 08:17:37 +00002445 SkipUntil(tok::r_brace, StopAtSemi);
David Blaikie0403cb12016-01-15 23:43:25 +00002446 return nullptr;
Douglas Gregor23c84762011-04-14 17:21:19 +00002447 }
Richard Smithda35e962013-11-09 04:52:51 +00002448
Serge Pavlov458ea762014-07-16 05:16:52 +00002449 // Turn on colon protection early, while parsing declspec, although there is
2450 // nothing to protect there. It prevents from false errors if error recovery
2451 // incorrectly determines where the declspec ends, as in the example:
2452 // struct A { enum class B { C }; };
2453 // const int C = 4;
2454 // struct D { A::B : C; };
2455 ColonProtectionRAIIObject X(*this);
2456
John McCalla0097262009-12-11 02:10:03 +00002457 // Access declarations.
Richard Smith45855df2012-05-09 08:23:23 +00002458 bool MalformedTypeSpec = false;
John McCalla0097262009-12-11 02:10:03 +00002459 if (!TemplateInfo.Kind &&
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002460 Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw___super)) {
Richard Smith45855df2012-05-09 08:23:23 +00002461 if (TryAnnotateCXXScopeToken())
2462 MalformedTypeSpec = true;
2463
2464 bool isAccessDecl;
2465 if (Tok.isNot(tok::annot_cxxscope))
2466 isAccessDecl = false;
2467 else if (NextToken().is(tok::identifier))
John McCalla0097262009-12-11 02:10:03 +00002468 isAccessDecl = GetLookAheadToken(2).is(tok::semi);
2469 else
2470 isAccessDecl = NextToken().is(tok::kw_operator);
2471
2472 if (isAccessDecl) {
2473 // Collect the scope specifier token we annotated earlier.
2474 CXXScopeSpec SS;
David Blaikieefdccaa2016-01-15 23:43:34 +00002475 ParseOptionalCXXScopeSpecifier(SS, nullptr,
Douglas Gregordf593fb2011-11-07 17:33:42 +00002476 /*EnteringContext=*/false);
John McCalla0097262009-12-11 02:10:03 +00002477
Nico Weberef03e702014-09-10 00:59:37 +00002478 if (SS.isInvalid()) {
2479 SkipUntil(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002480 return nullptr;
Nico Weberef03e702014-09-10 00:59:37 +00002481 }
2482
John McCalla0097262009-12-11 02:10:03 +00002483 // Try to parse an unqualified-id.
Abramo Bagnara7945c982012-01-27 09:46:47 +00002484 SourceLocation TemplateKWLoc;
John McCalla0097262009-12-11 02:10:03 +00002485 UnqualifiedId Name;
Richard Smith35845152017-02-07 01:37:30 +00002486 if (ParseUnqualifiedId(SS, false, true, true, false, nullptr,
Richard Smithc08b6932018-04-27 02:00:13 +00002487 &TemplateKWLoc, Name)) {
John McCalla0097262009-12-11 02:10:03 +00002488 SkipUntil(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002489 return nullptr;
John McCalla0097262009-12-11 02:10:03 +00002490 }
2491
2492 // TODO: recover from mistakenly-qualified operator declarations.
Alp Toker383d2c42014-01-01 03:08:43 +00002493 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
2494 "access declaration")) {
2495 SkipUntil(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002496 return nullptr;
Alp Toker383d2c42014-01-01 03:08:43 +00002497 }
John McCalla0097262009-12-11 02:10:03 +00002498
Richard Smithc08b6932018-04-27 02:00:13 +00002499 // FIXME: We should do something with the 'template' keyword here.
Alexey Bataev05c25d62015-07-31 08:42:25 +00002500 return DeclGroupPtrTy::make(DeclGroupRef(Actions.ActOnUsingDeclaration(
Richard Smith151c4562016-12-20 21:35:28 +00002501 getCurScope(), AS, /*UsingLoc*/ SourceLocation(),
2502 /*TypenameLoc*/ SourceLocation(), SS, Name,
Erich Keanec480f302018-07-12 21:09:05 +00002503 /*EllipsisLoc*/ SourceLocation(),
2504 /*AttrList*/ ParsedAttributesView())));
John McCalla0097262009-12-11 02:10:03 +00002505 }
2506 }
2507
Aaron Ballmane7c544d2014-08-04 20:28:35 +00002508 // static_assert-declaration. A templated static_assert declaration is
2509 // diagnosed in Parser::ParseSingleDeclarationAfterTemplate.
2510 if (!TemplateInfo.Kind &&
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002511 Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert)) {
Chris Lattner49836b42009-04-02 04:16:50 +00002512 SourceLocation DeclEnd;
Alexey Bataev05c25d62015-07-31 08:42:25 +00002513 return DeclGroupPtrTy::make(
2514 DeclGroupRef(ParseStaticAssertDeclaration(DeclEnd)));
Chris Lattner5bbb3c82009-03-29 16:50:03 +00002515 }
Mike Stump11289f42009-09-09 15:08:12 +00002516
Chris Lattner5bbb3c82009-03-29 16:50:03 +00002517 if (Tok.is(tok::kw_template)) {
Mike Stump11289f42009-09-09 15:08:12 +00002518 assert(!TemplateInfo.TemplateParams &&
Douglas Gregor3447e762009-08-20 22:52:58 +00002519 "Nested template improperly parsed?");
Richard Smith3af70092017-02-09 22:14:25 +00002520 ObjCDeclContextSwitch ObjCDC(*this);
Chris Lattner49836b42009-04-02 04:16:50 +00002521 SourceLocation DeclEnd;
Alexey Bataev05c25d62015-07-31 08:42:25 +00002522 return DeclGroupPtrTy::make(
Richard Smith3af70092017-02-09 22:14:25 +00002523 DeclGroupRef(ParseTemplateDeclarationOrSpecialization(
Erich Keanec480f302018-07-12 21:09:05 +00002524 DeclaratorContext::MemberContext, DeclEnd, AccessAttrs, AS)));
Chris Lattner5bbb3c82009-03-29 16:50:03 +00002525 }
Anders Carlssondfbbdf62009-03-26 00:52:18 +00002526
Chris Lattnerd19c1c02008-12-18 01:12:00 +00002527 // Handle: member-declaration ::= '__extension__' member-declaration
2528 if (Tok.is(tok::kw___extension__)) {
2529 // __extension__ silences extension warnings in the subexpression.
2530 ExtensionRAIIObject O(Diags); // Use RAII to do this.
2531 ConsumeToken();
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00002532 return ParseCXXClassMemberDeclaration(AS, AccessAttrs,
2533 TemplateInfo, TemplateDiags);
Chris Lattnerd19c1c02008-12-18 01:12:00 +00002534 }
Douglas Gregorfec52632009-06-20 00:51:54 +00002535
John McCall084e83d2011-03-24 11:26:52 +00002536 ParsedAttributesWithRange attrs(AttrFactory);
Erich Keanec480f302018-07-12 21:09:05 +00002537 ParsedAttributesViewWithRange FnAttrs;
Richard Smith89645bc2013-01-02 12:01:23 +00002538 // Optional C++11 attribute-specifier
2539 MaybeParseCXX11Attributes(attrs);
Michael Handdc016d2012-11-28 23:17:40 +00002540 // We need to keep these attributes for future diagnostic
2541 // before they are taken over by declaration specifier.
Erich Keanec480f302018-07-12 21:09:05 +00002542 FnAttrs.addAll(attrs.begin(), attrs.end());
Michael Handdc016d2012-11-28 23:17:40 +00002543 FnAttrs.Range = attrs.Range;
2544
John McCall53fa7142010-12-24 02:08:15 +00002545 MaybeParseMicrosoftAttributes(attrs);
Alexis Hunt96d5c762009-11-21 08:43:09 +00002546
Douglas Gregorfec52632009-06-20 00:51:54 +00002547 if (Tok.is(tok::kw_using)) {
John McCall53fa7142010-12-24 02:08:15 +00002548 ProhibitAttributes(attrs);
Mike Stump11289f42009-09-09 15:08:12 +00002549
Douglas Gregorfec52632009-06-20 00:51:54 +00002550 // Eat 'using'.
2551 SourceLocation UsingLoc = ConsumeToken();
2552
2553 if (Tok.is(tok::kw_namespace)) {
2554 Diag(UsingLoc, diag::err_using_namespace_in_class);
Alexey Bataevee6507d2013-11-18 08:17:37 +00002555 SkipUntil(tok::semi, StopBeforeMatch);
David Blaikie0403cb12016-01-15 23:43:25 +00002556 return nullptr;
Douglas Gregorfec52632009-06-20 00:51:54 +00002557 }
Alexey Bataev05c25d62015-07-31 08:42:25 +00002558 SourceLocation DeclEnd;
2559 // Otherwise, it must be a using-declaration or an alias-declaration.
Faisal Vali421b2d12017-12-29 05:41:00 +00002560 return ParseUsingDeclaration(DeclaratorContext::MemberContext, TemplateInfo,
Richard Smith6f1daa42016-12-16 00:58:48 +00002561 UsingLoc, DeclEnd, AS);
Douglas Gregorfec52632009-06-20 00:51:54 +00002562 }
2563
DeLesley Hutchinsbd2ee132012-03-02 22:12:59 +00002564 // Hold late-parsed attributes so we can attach a Decl to them later.
2565 LateParsedAttrList CommonLateParsedAttrs;
2566
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002567 // decl-specifier-seq:
2568 // Parse the common declaration-specifiers piece.
John McCall796c2a52010-07-16 08:13:16 +00002569 ParsingDeclSpec DS(*this, TemplateDiags);
John McCall53fa7142010-12-24 02:08:15 +00002570 DS.takeAttributesFrom(attrs);
Richard Smith45855df2012-05-09 08:23:23 +00002571 if (MalformedTypeSpec)
2572 DS.SetTypeSpecError();
Richard Smith72553fc2014-01-23 23:53:27 +00002573
Faisal Valia534f072018-04-26 00:42:40 +00002574 ParseDeclarationSpecifiers(DS, TemplateInfo, AS, DeclSpecContext::DSC_class,
2575 &CommonLateParsedAttrs);
Serge Pavlov458ea762014-07-16 05:16:52 +00002576
2577 // Turn off colon protection that was set for declspec.
2578 X.restore();
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002579
Richard Smith404dfb42013-11-19 22:47:36 +00002580 // If we had a free-standing type definition with a missing semicolon, we
2581 // may get this far before the problem becomes obvious.
2582 if (DS.hasTagDefinition() &&
2583 TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate &&
Faisal Vali7db85c52017-12-31 00:06:40 +00002584 DiagnoseMissingSemiAfterTagDefinition(DS, AS, DeclSpecContext::DSC_class,
Richard Smith404dfb42013-11-19 22:47:36 +00002585 &CommonLateParsedAttrs))
David Blaikie0403cb12016-01-15 23:43:25 +00002586 return nullptr;
Richard Smith404dfb42013-11-19 22:47:36 +00002587
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002588 MultiTemplateParamsArg TemplateParams(
Craig Topper161e4db2014-05-21 06:02:52 +00002589 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->data()
2590 : nullptr,
John McCall11083da2009-09-16 22:47:08 +00002591 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->size() : 0);
2592
Alp Toker35d87032013-12-30 23:29:50 +00002593 if (TryConsumeToken(tok::semi)) {
Michael Handdc016d2012-11-28 23:17:40 +00002594 if (DS.isFriendSpecified())
2595 ProhibitAttributes(FnAttrs);
2596
Nico Weber7b837f52016-01-28 19:25:00 +00002597 RecordDecl *AnonRecord = nullptr;
2598 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(
2599 getCurScope(), AS, DS, TemplateParams, false, AnonRecord);
John McCall796c2a52010-07-16 08:13:16 +00002600 DS.complete(TheDecl);
Nico Weber7b837f52016-01-28 19:25:00 +00002601 if (AnonRecord) {
2602 Decl* decls[] = {AnonRecord, TheDecl};
Richard Smith3beb7c62017-01-12 02:27:38 +00002603 return Actions.BuildDeclaratorGroup(decls);
Nico Weber7b837f52016-01-28 19:25:00 +00002604 }
2605 return Actions.ConvertDeclToDeclGroup(TheDecl);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002606 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002607
Faisal Vali421b2d12017-12-29 05:41:00 +00002608 ParsingDeclarator DeclaratorInfo(*this, DS, DeclaratorContext::MemberContext);
Nico Weber24b2a822011-01-28 06:07:34 +00002609 VirtSpecifiers VS;
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002610
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002611 // Hold late-parsed attributes so we can attach a Decl to them later.
2612 LateParsedAttrList LateParsedAttrs;
2613
Douglas Gregor50cefbf2011-10-17 17:09:53 +00002614 SourceLocation EqualLoc;
Richard Smith9ba0fec2015-06-30 01:28:56 +00002615 SourceLocation PureSpecLoc;
2616
Yaron Keren180c1672015-06-30 07:35:19 +00002617 auto TryConsumePureSpecifier = [&] (bool AllowDefinition) {
Richard Smith9ba0fec2015-06-30 01:28:56 +00002618 if (Tok.isNot(tok::equal))
2619 return false;
2620
2621 auto &Zero = NextToken();
2622 SmallString<8> Buffer;
2623 if (Zero.isNot(tok::numeric_constant) || Zero.getLength() != 1 ||
2624 PP.getSpelling(Zero, Buffer) != "0")
2625 return false;
2626
2627 auto &After = GetLookAheadToken(2);
2628 if (!After.isOneOf(tok::semi, tok::comma) &&
2629 !(AllowDefinition &&
2630 After.isOneOf(tok::l_brace, tok::colon, tok::kw_try)))
2631 return false;
2632
2633 EqualLoc = ConsumeToken();
2634 PureSpecLoc = ConsumeToken();
2635 return true;
2636 };
Chris Lattner17c3b1f2009-12-10 01:59:24 +00002637
Richard Smith72553fc2014-01-23 23:53:27 +00002638 SmallVector<Decl *, 8> DeclsInGroup;
2639 ExprResult BitfieldSize;
2640 bool ExpectSemi = true;
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002641
Richard Smith72553fc2014-01-23 23:53:27 +00002642 // Parse the first declarator.
Nico Weberd89e6f72015-01-16 19:34:13 +00002643 if (ParseCXXMemberDeclaratorBeforeInitializer(
2644 DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs)) {
Richard Smith72553fc2014-01-23 23:53:27 +00002645 TryConsumeToken(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002646 return nullptr;
Richard Smith72553fc2014-01-23 23:53:27 +00002647 }
John Thompson5bc5cbe2009-11-25 22:58:06 +00002648
Richard Smith72553fc2014-01-23 23:53:27 +00002649 // Check for a member function definition.
Richard Smith4b5a9492014-01-24 22:34:35 +00002650 if (BitfieldSize.isUnset()) {
Richard Smith72553fc2014-01-23 23:53:27 +00002651 // MSVC permits pure specifier on inline functions defined at class scope.
Francois Pichet3abc9b82011-05-11 02:14:46 +00002652 // Hence check for =0 before checking for function definition.
Richard Smith9ba0fec2015-06-30 01:28:56 +00002653 if (getLangOpts().MicrosoftExt && DeclaratorInfo.isDeclarationOfFunction())
2654 TryConsumePureSpecifier(/*AllowDefinition*/ true);
Francois Pichet3abc9b82011-05-11 02:14:46 +00002655
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00002656 FunctionDefinitionKind DefinitionKind = FDK_Declaration;
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002657 // function-definition:
Richard Smith938f40b2011-06-11 17:19:42 +00002658 //
2659 // In C++11, a non-function declarator followed by an open brace is a
2660 // braced-init-list for an in-class member initialization, not an
2661 // erroneous function definition.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002662 if (Tok.is(tok::l_brace) && !getLangOpts().CPlusPlus11) {
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00002663 DefinitionKind = FDK_Definition;
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002664 } else if (DeclaratorInfo.isFunctionDeclarator()) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002665 if (Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try)) {
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00002666 DefinitionKind = FDK_Definition;
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002667 } else if (Tok.is(tok::equal)) {
2668 const Token &KW = NextToken();
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00002669 if (KW.is(tok::kw_default))
2670 DefinitionKind = FDK_Defaulted;
2671 else if (KW.is(tok::kw_delete))
2672 DefinitionKind = FDK_Deleted;
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002673 }
2674 }
Eli Bendersky41842222015-03-23 23:49:41 +00002675 DeclaratorInfo.setFunctionDefinitionKind(DefinitionKind);
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002676
Fangrui Song6907ce22018-07-30 19:24:48 +00002677 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
Michael Handdc016d2012-11-28 23:17:40 +00002678 // to a friend declaration, that declaration shall be a definition.
Fangrui Song6907ce22018-07-30 19:24:48 +00002679 if (DeclaratorInfo.isFunctionDeclarator() &&
Michael Handdc016d2012-11-28 23:17:40 +00002680 DefinitionKind != FDK_Definition && DS.isFriendSpecified()) {
2681 // Diagnose attributes that appear before decl specifier:
2682 // [[]] friend int foo();
2683 ProhibitAttributes(FnAttrs);
2684 }
2685
Nico Webera7f137d2015-01-16 19:35:01 +00002686 if (DefinitionKind != FDK_Declaration) {
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002687 if (!DeclaratorInfo.isFunctionDeclarator()) {
Richard Trieu0d730542012-01-21 02:59:18 +00002688 Diag(DeclaratorInfo.getIdentifierLoc(), diag::err_func_def_no_params);
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002689 ConsumeBrace();
Alexey Bataevee6507d2013-11-18 08:17:37 +00002690 SkipUntil(tok::r_brace);
Michael Handdc016d2012-11-28 23:17:40 +00002691
Douglas Gregor8a4db832011-01-19 16:41:58 +00002692 // Consume the optional ';'
Alp Toker35d87032013-12-30 23:29:50 +00002693 TryConsumeToken(tok::semi);
2694
David Blaikie0403cb12016-01-15 23:43:25 +00002695 return nullptr;
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002696 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002697
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002698 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
Richard Trieu0d730542012-01-21 02:59:18 +00002699 Diag(DeclaratorInfo.getIdentifierLoc(),
2700 diag::err_function_declared_typedef);
Douglas Gregor8a4db832011-01-19 16:41:58 +00002701
Richard Smith2603b092012-11-15 22:54:20 +00002702 // Recover by treating the 'typedef' as spurious.
2703 DS.ClearStorageClassSpecs();
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002704 }
2705
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002706 Decl *FunDecl =
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00002707 ParseCXXInlineMethodDef(AS, AccessAttrs, DeclaratorInfo, TemplateInfo,
Richard Smith9ba0fec2015-06-30 01:28:56 +00002708 VS, PureSpecLoc);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002709
David Majnemer23252a32013-08-01 04:22:55 +00002710 if (FunDecl) {
2711 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i) {
2712 CommonLateParsedAttrs[i]->addDecl(FunDecl);
2713 }
2714 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i) {
2715 LateParsedAttrs[i]->addDecl(FunDecl);
2716 }
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002717 }
2718 LateParsedAttrs.clear();
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002719
2720 // Consume the ';' - it's optional unless we have a delete or default
Richard Trieu2f7dc462012-05-16 19:04:59 +00002721 if (Tok.is(tok::semi))
Richard Smith87f5dc52012-07-23 05:45:25 +00002722 ConsumeExtraSemi(AfterMemberFunctionDefinition);
Douglas Gregor8a4db832011-01-19 16:41:58 +00002723
Alexey Bataev05c25d62015-07-31 08:42:25 +00002724 return DeclGroupPtrTy::make(DeclGroupRef(FunDecl));
Argyrios Kyrtzidisf4ebe9e2008-06-28 08:10:48 +00002725 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002726 }
2727
2728 // member-declarator-list:
2729 // member-declarator
2730 // member-declarator-list ',' member-declarator
2731
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002732 while (1) {
Richard Smith2b013182012-06-10 03:12:00 +00002733 InClassInitStyle HasInClassInit = ICIS_NoInit;
Richard Smith9ba0fec2015-06-30 01:28:56 +00002734 bool HasStaticInitializer = false;
2735 if (Tok.isOneOf(tok::equal, tok::l_brace) && PureSpecLoc.isInvalid()) {
Richard Smith6b8e3c02017-08-28 00:28:14 +00002736 if (DeclaratorInfo.isDeclarationOfFunction()) {
Richard Smith9ba0fec2015-06-30 01:28:56 +00002737 // It's a pure-specifier.
2738 if (!TryConsumePureSpecifier(/*AllowFunctionDefinition*/ false))
2739 // Parse it as an expression so that Sema can diagnose it.
2740 HasStaticInitializer = true;
2741 } else if (DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2742 DeclSpec::SCS_static &&
2743 DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2744 DeclSpec::SCS_typedef &&
2745 !DS.isFriendSpecified()) {
2746 // It's a default member initializer.
Richard Smith6b8e3c02017-08-28 00:28:14 +00002747 if (BitfieldSize.get())
2748 Diag(Tok, getLangOpts().CPlusPlus2a
2749 ? diag::warn_cxx17_compat_bitfield_member_init
2750 : diag::ext_bitfield_member_init);
Richard Smith9ba0fec2015-06-30 01:28:56 +00002751 HasInClassInit = Tok.is(tok::equal) ? ICIS_CopyInit : ICIS_ListInit;
Richard Smith938f40b2011-06-11 17:19:42 +00002752 } else {
Richard Smith9ba0fec2015-06-30 01:28:56 +00002753 HasStaticInitializer = true;
Richard Smith938f40b2011-06-11 17:19:42 +00002754 }
2755 }
2756
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002757 // NOTE: If Sema is the Action module and declarator is an instance field,
Chris Lattner5bbb3c82009-03-29 16:50:03 +00002758 // this call will *not* return the created decl; It will return null.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002759 // See Sema::ActOnCXXMemberDeclarator for details.
John McCall07e91c02009-08-06 02:15:43 +00002760
Craig Topper161e4db2014-05-21 06:02:52 +00002761 NamedDecl *ThisDecl = nullptr;
John McCall07e91c02009-08-06 02:15:43 +00002762 if (DS.isFriendSpecified()) {
Richard Smith72553fc2014-01-23 23:53:27 +00002763 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
Michael Handdc016d2012-11-28 23:17:40 +00002764 // to a friend declaration, that declaration shall be a definition.
2765 //
Richard Smith72553fc2014-01-23 23:53:27 +00002766 // Diagnose attributes that appear in a friend member function declarator:
2767 // friend int foo [[]] ();
Michael Handdc016d2012-11-28 23:17:40 +00002768 SmallVector<SourceRange, 4> Ranges;
2769 DeclaratorInfo.getCXX11AttributeRanges(Ranges);
Richard Smith72553fc2014-01-23 23:53:27 +00002770 for (SmallVectorImpl<SourceRange>::iterator I = Ranges.begin(),
2771 E = Ranges.end(); I != E; ++I)
2772 Diag((*I).getBegin(), diag::err_attributes_not_allowed) << *I;
Michael Handdc016d2012-11-28 23:17:40 +00002773
Douglas Gregor0be31a22010-07-02 17:43:08 +00002774 ThisDecl = Actions.ActOnFriendFunctionDecl(getCurScope(), DeclaratorInfo,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002775 TemplateParams);
Douglas Gregor3447e762009-08-20 22:52:58 +00002776 } else {
Douglas Gregor0be31a22010-07-02 17:43:08 +00002777 ThisDecl = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS,
John McCall07e91c02009-08-06 02:15:43 +00002778 DeclaratorInfo,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002779 TemplateParams,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002780 BitfieldSize.get(),
Richard Smith2b013182012-06-10 03:12:00 +00002781 VS, HasInClassInit);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002782
2783 if (VarTemplateDecl *VT =
Craig Topper161e4db2014-05-21 06:02:52 +00002784 ThisDecl ? dyn_cast<VarTemplateDecl>(ThisDecl) : nullptr)
Larisse Voufo39a1e502013-08-06 01:03:05 +00002785 // Re-direct this decl to refer to the templated decl so that we can
2786 // initialize it.
2787 ThisDecl = VT->getTemplatedDecl();
2788
Erich Keanec480f302018-07-12 21:09:05 +00002789 if (ThisDecl)
Richard Smithf8a75c32013-08-29 00:47:48 +00002790 Actions.ProcessDeclAttributeList(getCurScope(), ThisDecl, AccessAttrs);
Douglas Gregor3447e762009-08-20 22:52:58 +00002791 }
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00002792
Richard Smith9ba0fec2015-06-30 01:28:56 +00002793 // Error recovery might have converted a non-static member into a static
2794 // member.
David Blaikie35506f82013-01-30 01:22:18 +00002795 if (HasInClassInit != ICIS_NoInit &&
Richard Smith9ba0fec2015-06-30 01:28:56 +00002796 DeclaratorInfo.getDeclSpec().getStorageClassSpec() ==
2797 DeclSpec::SCS_static) {
2798 HasInClassInit = ICIS_NoInit;
2799 HasStaticInitializer = true;
2800 }
2801
2802 if (ThisDecl && PureSpecLoc.isValid())
2803 Actions.ActOnPureSpecifier(ThisDecl, PureSpecLoc);
2804
2805 // Handle the initializer.
2806 if (HasInClassInit != ICIS_NoInit) {
Douglas Gregor728d00b2011-10-10 14:49:18 +00002807 // The initializer was deferred; parse it and cache the tokens.
David Majnemer23252a32013-08-01 04:22:55 +00002808 Diag(Tok, getLangOpts().CPlusPlus11
2809 ? diag::warn_cxx98_compat_nonstatic_member_init
2810 : diag::ext_nonstatic_member_init);
Richard Smith5d164bc2011-10-15 05:09:34 +00002811
Richard Smith938f40b2011-06-11 17:19:42 +00002812 if (DeclaratorInfo.isArrayOfUnknownBound()) {
Richard Smith2b013182012-06-10 03:12:00 +00002813 // C++11 [dcl.array]p3: An array bound may also be omitted when the
2814 // declarator is followed by an initializer.
Richard Smith938f40b2011-06-11 17:19:42 +00002815 //
2816 // A brace-or-equal-initializer for a member-declarator is not an
David Blaikiecdd91db2012-02-14 09:00:46 +00002817 // initializer in the grammar, so this is ill-formed.
Richard Smith938f40b2011-06-11 17:19:42 +00002818 Diag(Tok, diag::err_incomplete_array_member_init);
Alexey Bataevee6507d2013-11-18 08:17:37 +00002819 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
David Majnemer23252a32013-08-01 04:22:55 +00002820
2821 // Avoid later warnings about a class member of incomplete type.
David Blaikiecdd91db2012-02-14 09:00:46 +00002822 if (ThisDecl)
David Blaikiecdd91db2012-02-14 09:00:46 +00002823 ThisDecl->setInvalidDecl();
Richard Smith938f40b2011-06-11 17:19:42 +00002824 } else
2825 ParseCXXNonStaticMemberInitializer(ThisDecl);
Richard Smith9ba0fec2015-06-30 01:28:56 +00002826 } else if (HasStaticInitializer) {
Douglas Gregor728d00b2011-10-10 14:49:18 +00002827 // Normal initializer.
Richard Smith9ba0fec2015-06-30 01:28:56 +00002828 ExprResult Init = ParseCXXMemberInitializer(
2829 ThisDecl, DeclaratorInfo.isDeclarationOfFunction(), EqualLoc);
David Majnemer23252a32013-08-01 04:22:55 +00002830
Douglas Gregor728d00b2011-10-10 14:49:18 +00002831 if (Init.isInvalid())
Alexey Bataevee6507d2013-11-18 08:17:37 +00002832 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
Douglas Gregor728d00b2011-10-10 14:49:18 +00002833 else if (ThisDecl)
Richard Smith3beb7c62017-01-12 02:27:38 +00002834 Actions.AddInitializerToDecl(ThisDecl, Init.get(), EqualLoc.isInvalid());
David Majnemer23252a32013-08-01 04:22:55 +00002835 } else if (ThisDecl && DS.getStorageClassSpec() == DeclSpec::SCS_static)
Douglas Gregor728d00b2011-10-10 14:49:18 +00002836 // No initializer.
Richard Smith3beb7c62017-01-12 02:27:38 +00002837 Actions.ActOnUninitializedDecl(ThisDecl);
David Majnemer23252a32013-08-01 04:22:55 +00002838
Douglas Gregor728d00b2011-10-10 14:49:18 +00002839 if (ThisDecl) {
David Majnemer23252a32013-08-01 04:22:55 +00002840 if (!ThisDecl->isInvalidDecl()) {
2841 // Set the Decl for any late parsed attributes
2842 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i)
2843 CommonLateParsedAttrs[i]->addDecl(ThisDecl);
2844
2845 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i)
2846 LateParsedAttrs[i]->addDecl(ThisDecl);
2847 }
Douglas Gregor728d00b2011-10-10 14:49:18 +00002848 Actions.FinalizeDeclaration(ThisDecl);
2849 DeclsInGroup.push_back(ThisDecl);
David Majnemer23252a32013-08-01 04:22:55 +00002850
2851 if (DeclaratorInfo.isFunctionDeclarator() &&
2852 DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2853 DeclSpec::SCS_typedef)
2854 HandleMemberFunctionDeclDelays(DeclaratorInfo, ThisDecl);
Douglas Gregor728d00b2011-10-10 14:49:18 +00002855 }
David Majnemer23252a32013-08-01 04:22:55 +00002856 LateParsedAttrs.clear();
Douglas Gregor728d00b2011-10-10 14:49:18 +00002857
2858 DeclaratorInfo.complete(ThisDecl);
Richard Smith938f40b2011-06-11 17:19:42 +00002859
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002860 // If we don't have a comma, it is either the end of the list (a ';')
2861 // or an error, bail out.
Alp Toker094e5212014-01-05 03:27:11 +00002862 SourceLocation CommaLoc;
2863 if (!TryConsumeToken(tok::comma, CommaLoc))
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002864 break;
Mike Stump11289f42009-09-09 15:08:12 +00002865
Richard Smithc8a79032012-01-09 22:31:44 +00002866 if (Tok.isAtStartOfLine() &&
Faisal Vali421b2d12017-12-29 05:41:00 +00002867 !MightBeDeclarator(DeclaratorContext::MemberContext)) {
Richard Smithc8a79032012-01-09 22:31:44 +00002868 // This comma was followed by a line-break and something which can't be
2869 // the start of a declarator. The comma was probably a typo for a
2870 // semicolon.
2871 Diag(CommaLoc, diag::err_expected_semi_declaration)
2872 << FixItHint::CreateReplacement(CommaLoc, ";");
2873 ExpectSemi = false;
2874 break;
2875 }
Mike Stump11289f42009-09-09 15:08:12 +00002876
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002877 // Parse the next declarator.
2878 DeclaratorInfo.clear();
Nico Weber24b2a822011-01-28 06:07:34 +00002879 VS.clear();
Nico Weberf56c85b2015-01-17 02:26:40 +00002880 BitfieldSize = ExprResult(/*Invalid=*/false);
Richard Smith9ba0fec2015-06-30 01:28:56 +00002881 EqualLoc = PureSpecLoc = SourceLocation();
Richard Smith8d06f422012-01-12 23:53:29 +00002882 DeclaratorInfo.setCommaLoc(CommaLoc);
Mike Stump11289f42009-09-09 15:08:12 +00002883
Richard Smith72553fc2014-01-23 23:53:27 +00002884 // GNU attributes are allowed before the second and subsequent declarator.
John McCall53fa7142010-12-24 02:08:15 +00002885 MaybeParseGNUAttributes(DeclaratorInfo);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002886
Nico Weberd89e6f72015-01-16 19:34:13 +00002887 if (ParseCXXMemberDeclaratorBeforeInitializer(
2888 DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs))
2889 break;
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002890 }
2891
Richard Smithc8a79032012-01-09 22:31:44 +00002892 if (ExpectSemi &&
2893 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list)) {
Chris Lattner916dbf12010-02-02 00:43:15 +00002894 // Skip to end of block or statement.
Alexey Bataevee6507d2013-11-18 08:17:37 +00002895 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Chris Lattner916dbf12010-02-02 00:43:15 +00002896 // If we stopped at a ';', eat it.
Alp Toker35d87032013-12-30 23:29:50 +00002897 TryConsumeToken(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002898 return nullptr;
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002899 }
2900
Alexey Bataev05c25d62015-07-31 08:42:25 +00002901 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00002902}
2903
Richard Smith9ba0fec2015-06-30 01:28:56 +00002904/// ParseCXXMemberInitializer - Parse the brace-or-equal-initializer.
2905/// Also detect and reject any attempted defaulted/deleted function definition.
2906/// The location of the '=', if any, will be placed in EqualLoc.
Richard Smith938f40b2011-06-11 17:19:42 +00002907///
Richard Smith9ba0fec2015-06-30 01:28:56 +00002908/// This does not check for a pure-specifier; that's handled elsewhere.
Sebastian Redleef474c2012-02-22 10:50:08 +00002909///
Richard Smith938f40b2011-06-11 17:19:42 +00002910/// brace-or-equal-initializer:
2911/// '=' initializer-expression
Sebastian Redleef474c2012-02-22 10:50:08 +00002912/// braced-init-list
2913///
Richard Smith938f40b2011-06-11 17:19:42 +00002914/// initializer-clause:
2915/// assignment-expression
Sebastian Redleef474c2012-02-22 10:50:08 +00002916/// braced-init-list
2917///
Richard Smithda35e962013-11-09 04:52:51 +00002918/// defaulted/deleted function-definition:
Richard Smith938f40b2011-06-11 17:19:42 +00002919/// '=' 'default'
2920/// '=' 'delete'
2921///
2922/// Prior to C++0x, the assignment-expression in an initializer-clause must
2923/// be a constant-expression.
Douglas Gregor926410d2012-02-21 02:22:07 +00002924ExprResult Parser::ParseCXXMemberInitializer(Decl *D, bool IsFunction,
Richard Smith938f40b2011-06-11 17:19:42 +00002925 SourceLocation &EqualLoc) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002926 assert(Tok.isOneOf(tok::equal, tok::l_brace)
Richard Smith938f40b2011-06-11 17:19:42 +00002927 && "Data member initializer not starting with '=' or '{'");
2928
Faisal Valid143a0c2017-04-01 21:30:49 +00002929 EnterExpressionEvaluationContext Context(
2930 Actions, Sema::ExpressionEvaluationContext::PotentiallyEvaluated, D);
Alp Toker094e5212014-01-05 03:27:11 +00002931 if (TryConsumeToken(tok::equal, EqualLoc)) {
Richard Smith938f40b2011-06-11 17:19:42 +00002932 if (Tok.is(tok::kw_delete)) {
2933 // In principle, an initializer of '= delete p;' is legal, but it will
2934 // never type-check. It's better to diagnose it as an ill-formed expression
2935 // than as an ill-formed deleted non-function member.
2936 // An initializer of '= delete p, foo' will never be parsed, because
2937 // a top-level comma always ends the initializer expression.
2938 const Token &Next = NextToken();
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002939 if (IsFunction || Next.isOneOf(tok::semi, tok::comma, tok::eof)) {
Richard Smith938f40b2011-06-11 17:19:42 +00002940 if (IsFunction)
2941 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2942 << 1 /* delete */;
2943 else
2944 Diag(ConsumeToken(), diag::err_deleted_non_function);
Richard Smithedcb26e2014-06-11 00:49:52 +00002945 return ExprError();
Richard Smith938f40b2011-06-11 17:19:42 +00002946 }
2947 } else if (Tok.is(tok::kw_default)) {
Richard Smith938f40b2011-06-11 17:19:42 +00002948 if (IsFunction)
2949 Diag(Tok, diag::err_default_delete_in_multiple_declaration)
2950 << 0 /* default */;
2951 else
2952 Diag(ConsumeToken(), diag::err_default_special_members);
Richard Smithedcb26e2014-06-11 00:49:52 +00002953 return ExprError();
Richard Smith938f40b2011-06-11 17:19:42 +00002954 }
David Majnemer87ff66c2014-12-13 11:34:16 +00002955 }
2956 if (const auto *PD = dyn_cast_or_null<MSPropertyDecl>(D)) {
2957 Diag(Tok, diag::err_ms_property_initializer) << PD;
2958 return ExprError();
Sebastian Redleef474c2012-02-22 10:50:08 +00002959 }
2960 return ParseInitializer();
Richard Smith938f40b2011-06-11 17:19:42 +00002961}
2962
Richard Smith65ebb4a2015-03-26 04:09:53 +00002963void Parser::SkipCXXMemberSpecification(SourceLocation RecordLoc,
2964 SourceLocation AttrFixitLoc,
Faisal Vali090da2d2018-01-01 18:23:28 +00002965 unsigned TagType, Decl *TagDecl) {
Richard Smith65ebb4a2015-03-26 04:09:53 +00002966 // Skip the optional 'final' keyword.
2967 if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
2968 assert(isCXX11FinalKeyword() && "not a class definition");
2969 ConsumeToken();
2970
2971 // Diagnose any C++11 attributes after 'final' keyword.
2972 // We deliberately discard these attributes.
2973 ParsedAttributesWithRange Attrs(AttrFactory);
2974 CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
2975
2976 // This can only happen if we had malformed misplaced attributes;
2977 // we only get called if there is a colon or left-brace after the
2978 // attributes.
2979 if (Tok.isNot(tok::colon) && Tok.isNot(tok::l_brace))
2980 return;
2981 }
2982
2983 // Skip the base clauses. This requires actually parsing them, because
2984 // otherwise we can't be sure where they end (a left brace may appear
2985 // within a template argument).
2986 if (Tok.is(tok::colon)) {
2987 // Enter the scope of the class so that we can correctly parse its bases.
2988 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
2989 ParsingClassDefinition ParsingDef(*this, TagDecl, /*NonNestedClass*/ true,
2990 TagType == DeclSpec::TST_interface);
Richard Smith0f192e82015-06-11 22:48:25 +00002991 auto OldContext =
2992 Actions.ActOnTagStartSkippedDefinition(getCurScope(), TagDecl);
Richard Smith65ebb4a2015-03-26 04:09:53 +00002993
2994 // Parse the bases but don't attach them to the class.
2995 ParseBaseClause(nullptr);
2996
Richard Smith0f192e82015-06-11 22:48:25 +00002997 Actions.ActOnTagFinishSkippedDefinition(OldContext);
Richard Smith65ebb4a2015-03-26 04:09:53 +00002998
2999 if (!Tok.is(tok::l_brace)) {
3000 Diag(PP.getLocForEndOfToken(PrevTokLocation),
3001 diag::err_expected_lbrace_after_base_specifiers);
3002 return;
3003 }
3004 }
3005
3006 // Skip the body.
3007 assert(Tok.is(tok::l_brace));
3008 BalancedDelimiterTracker T(*this, tok::l_brace);
3009 T.consumeOpen();
3010 T.skipToEnd();
Richard Smith04c6c1f2015-07-01 18:56:50 +00003011
3012 // Parse and discard any trailing attributes.
3013 ParsedAttributes Attrs(AttrFactory);
3014 if (Tok.is(tok::kw___attribute))
3015 MaybeParseGNUAttributes(Attrs);
Richard Smith65ebb4a2015-03-26 04:09:53 +00003016}
3017
Alexey Bataev05c25d62015-07-31 08:42:25 +00003018Parser::DeclGroupPtrTy Parser::ParseCXXClassMemberDeclarationWithPragmas(
3019 AccessSpecifier &AS, ParsedAttributesWithRange &AccessAttrs,
3020 DeclSpec::TST TagType, Decl *TagDecl) {
Richard Smithbf5bcf22018-06-26 23:20:26 +00003021 ParenBraceBracketBalancer BalancerRAIIObj(*this);
3022
Richard Smithb55f7582017-01-28 01:12:10 +00003023 switch (Tok.getKind()) {
3024 case tok::kw___if_exists:
3025 case tok::kw___if_not_exists:
Erich Keanec480f302018-07-12 21:09:05 +00003026 ParseMicrosoftIfExistsClassDeclaration(TagType, AccessAttrs, AS);
David Blaikie0403cb12016-01-15 23:43:25 +00003027 return nullptr;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003028
Richard Smithb55f7582017-01-28 01:12:10 +00003029 case tok::semi:
3030 // Check for extraneous top-level semicolon.
Alexey Bataev05c25d62015-07-31 08:42:25 +00003031 ConsumeExtraSemi(InsideStruct, TagType);
David Blaikie0403cb12016-01-15 23:43:25 +00003032 return nullptr;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003033
Richard Smithb55f7582017-01-28 01:12:10 +00003034 // Handle pragmas that can appear as member declarations.
3035 case tok::annot_pragma_vis:
Alexey Bataev05c25d62015-07-31 08:42:25 +00003036 HandlePragmaVisibility();
David Blaikie0403cb12016-01-15 23:43:25 +00003037 return nullptr;
Richard Smithb55f7582017-01-28 01:12:10 +00003038 case tok::annot_pragma_pack:
Alexey Bataev05c25d62015-07-31 08:42:25 +00003039 HandlePragmaPack();
David Blaikie0403cb12016-01-15 23:43:25 +00003040 return nullptr;
Richard Smithb55f7582017-01-28 01:12:10 +00003041 case tok::annot_pragma_align:
Alexey Bataev05c25d62015-07-31 08:42:25 +00003042 HandlePragmaAlign();
David Blaikie0403cb12016-01-15 23:43:25 +00003043 return nullptr;
Richard Smithb55f7582017-01-28 01:12:10 +00003044 case tok::annot_pragma_ms_pointers_to_members:
Alexey Bataev05c25d62015-07-31 08:42:25 +00003045 HandlePragmaMSPointersToMembers();
David Blaikie0403cb12016-01-15 23:43:25 +00003046 return nullptr;
Richard Smithb55f7582017-01-28 01:12:10 +00003047 case tok::annot_pragma_ms_pragma:
Alexey Bataev05c25d62015-07-31 08:42:25 +00003048 HandlePragmaMSPragma();
David Blaikie0403cb12016-01-15 23:43:25 +00003049 return nullptr;
Richard Smithb55f7582017-01-28 01:12:10 +00003050 case tok::annot_pragma_ms_vtordisp:
Alexey Bataev3d42f342015-11-20 07:02:57 +00003051 HandlePragmaMSVtorDisp();
David Blaikie0403cb12016-01-15 23:43:25 +00003052 return nullptr;
Richard Smithb256d302017-01-28 01:20:57 +00003053 case tok::annot_pragma_dump:
3054 HandlePragmaDump();
3055 return nullptr;
Alexey Bataev3d42f342015-11-20 07:02:57 +00003056
Richard Smithb55f7582017-01-28 01:12:10 +00003057 case tok::kw_namespace:
3058 // If we see a namespace here, a close brace was missing somewhere.
Alexey Bataev05c25d62015-07-31 08:42:25 +00003059 DiagnoseUnexpectedNamespace(cast<NamedDecl>(TagDecl));
David Blaikie0403cb12016-01-15 23:43:25 +00003060 return nullptr;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003061
Richard Smithb55f7582017-01-28 01:12:10 +00003062 case tok::kw_public:
3063 case tok::kw_protected:
3064 case tok::kw_private: {
3065 AccessSpecifier NewAS = getAccessSpecifierIfPresent();
3066 assert(NewAS != AS_none);
Alexey Bataev05c25d62015-07-31 08:42:25 +00003067 // Current token is a C++ access specifier.
3068 AS = NewAS;
3069 SourceLocation ASLoc = Tok.getLocation();
3070 unsigned TokLength = Tok.getLength();
3071 ConsumeToken();
3072 AccessAttrs.clear();
3073 MaybeParseGNUAttributes(AccessAttrs);
3074
3075 SourceLocation EndLoc;
3076 if (TryConsumeToken(tok::colon, EndLoc)) {
3077 } else if (TryConsumeToken(tok::semi, EndLoc)) {
3078 Diag(EndLoc, diag::err_expected)
3079 << tok::colon << FixItHint::CreateReplacement(EndLoc, ":");
3080 } else {
3081 EndLoc = ASLoc.getLocWithOffset(TokLength);
3082 Diag(EndLoc, diag::err_expected)
3083 << tok::colon << FixItHint::CreateInsertion(EndLoc, ":");
3084 }
3085
3086 // The Microsoft extension __interface does not permit non-public
3087 // access specifiers.
3088 if (TagType == DeclSpec::TST_interface && AS != AS_public) {
3089 Diag(ASLoc, diag::err_access_specifier_interface) << (AS == AS_protected);
3090 }
3091
Erich Keanec480f302018-07-12 21:09:05 +00003092 if (Actions.ActOnAccessSpecifier(NewAS, ASLoc, EndLoc, AccessAttrs)) {
Alexey Bataev05c25d62015-07-31 08:42:25 +00003093 // found another attribute than only annotations
3094 AccessAttrs.clear();
3095 }
3096
David Blaikie0403cb12016-01-15 23:43:25 +00003097 return nullptr;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003098 }
3099
Richard Smithb55f7582017-01-28 01:12:10 +00003100 case tok::annot_pragma_openmp:
Alexey Bataev587e1de2016-03-30 10:43:55 +00003101 return ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, AccessAttrs, TagType,
3102 TagDecl);
Alexey Bataev05c25d62015-07-31 08:42:25 +00003103
Richard Smithb55f7582017-01-28 01:12:10 +00003104 default:
Erich Keanec480f302018-07-12 21:09:05 +00003105 return ParseCXXClassMemberDeclaration(AS, AccessAttrs);
Richard Smithb55f7582017-01-28 01:12:10 +00003106 }
Alexey Bataev05c25d62015-07-31 08:42:25 +00003107}
3108
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003109/// ParseCXXMemberSpecification - Parse the class definition.
3110///
3111/// member-specification:
3112/// member-declaration member-specification[opt]
3113/// access-specifier ':' member-specification[opt]
3114///
Joao Matose9a3ed42012-08-31 22:18:20 +00003115void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc,
Michael Han309af292013-01-07 16:57:11 +00003116 SourceLocation AttrFixitLoc,
Richard Smith4c96e992013-02-19 23:47:15 +00003117 ParsedAttributesWithRange &Attrs,
Faisal Vali090da2d2018-01-01 18:23:28 +00003118 unsigned TagType, Decl *TagDecl) {
Joao Matose9a3ed42012-08-31 22:18:20 +00003119 assert((TagType == DeclSpec::TST_struct ||
Faisal Vali090da2d2018-01-01 18:23:28 +00003120 TagType == DeclSpec::TST_interface ||
3121 TagType == DeclSpec::TST_union ||
3122 TagType == DeclSpec::TST_class) && "Invalid TagType!");
Joao Matose9a3ed42012-08-31 22:18:20 +00003123
Jordan Rose1e879d82018-03-23 00:07:18 +00003124 PrettyDeclStackTraceEntry CrashInfo(Actions.Context, TagDecl, RecordLoc,
John McCallfaf5fb42010-08-26 23:41:50 +00003125 "parsing struct/union/class body");
Mike Stump11289f42009-09-09 15:08:12 +00003126
Douglas Gregoredf8f392010-01-16 20:52:59 +00003127 // Determine whether this is a non-nested class. Note that local
3128 // classes are *not* considered to be nested classes.
3129 bool NonNestedClass = true;
3130 if (!ClassStack.empty()) {
Douglas Gregor0be31a22010-07-02 17:43:08 +00003131 for (const Scope *S = getCurScope(); S; S = S->getParent()) {
Douglas Gregoredf8f392010-01-16 20:52:59 +00003132 if (S->isClassScope()) {
3133 // We're inside a class scope, so this is a nested class.
3134 NonNestedClass = false;
John McCalldb632ac2012-09-25 07:32:39 +00003135
3136 // The Microsoft extension __interface does not permit nested classes.
3137 if (getCurrentClass().IsInterface) {
3138 Diag(RecordLoc, diag::err_invalid_member_in_interface)
3139 << /*ErrorType=*/6
3140 << (isa<NamedDecl>(TagDecl)
3141 ? cast<NamedDecl>(TagDecl)->getQualifiedNameAsString()
David Blaikieabe1a392014-04-02 05:58:29 +00003142 : "(anonymous)");
John McCalldb632ac2012-09-25 07:32:39 +00003143 }
Douglas Gregoredf8f392010-01-16 20:52:59 +00003144 break;
3145 }
3146
Serge Pavlovd9c0bcf2015-07-14 10:02:10 +00003147 if ((S->getFlags() & Scope::FnScope))
3148 // If we're in a function or function template then this is a local
3149 // class rather than a nested class.
3150 break;
Douglas Gregoredf8f392010-01-16 20:52:59 +00003151 }
3152 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003153
3154 // Enter a scope for the class.
Douglas Gregor658b9552009-01-09 22:42:13 +00003155 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003156
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003157 // Note that we are parsing a new (potentially-nested) class definition.
John McCalldb632ac2012-09-25 07:32:39 +00003158 ParsingClassDefinition ParsingDef(*this, TagDecl, NonNestedClass,
3159 TagType == DeclSpec::TST_interface);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003160
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003161 if (TagDecl)
Douglas Gregor0be31a22010-07-02 17:43:08 +00003162 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
John McCall2d814c32009-12-19 21:48:58 +00003163
Anders Carlssonf9eb63b2011-03-25 14:46:08 +00003164 SourceLocation FinalLoc;
David Majnemera5433082013-10-18 00:33:31 +00003165 bool IsFinalSpelledSealed = false;
Anders Carlssonf9eb63b2011-03-25 14:46:08 +00003166
3167 // Parse the optional 'final' keyword.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003168 if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
David Majnemera5433082013-10-18 00:33:31 +00003169 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier(Tok);
3170 assert((Specifier == VirtSpecifiers::VS_Final ||
Fangrui Song6907ce22018-07-30 19:24:48 +00003171 Specifier == VirtSpecifiers::VS_GNU_Final ||
David Majnemera5433082013-10-18 00:33:31 +00003172 Specifier == VirtSpecifiers::VS_Sealed) &&
3173 "not a class definition");
Richard Smithda261112011-10-15 04:21:46 +00003174 FinalLoc = ConsumeToken();
David Majnemera5433082013-10-18 00:33:31 +00003175 IsFinalSpelledSealed = Specifier == VirtSpecifiers::VS_Sealed;
Anders Carlssonf9eb63b2011-03-25 14:46:08 +00003176
David Majnemera5433082013-10-18 00:33:31 +00003177 if (TagType == DeclSpec::TST_interface)
John McCalldb632ac2012-09-25 07:32:39 +00003178 Diag(FinalLoc, diag::err_override_control_interface)
David Majnemera5433082013-10-18 00:33:31 +00003179 << VirtSpecifiers::getSpecifierName(Specifier);
3180 else if (Specifier == VirtSpecifiers::VS_Final)
3181 Diag(FinalLoc, getLangOpts().CPlusPlus11
3182 ? diag::warn_cxx98_compat_override_control_keyword
3183 : diag::ext_override_control_keyword)
3184 << VirtSpecifiers::getSpecifierName(Specifier);
3185 else if (Specifier == VirtSpecifiers::VS_Sealed)
3186 Diag(FinalLoc, diag::ext_ms_sealed_keyword);
Andrey Bokhanko276055b2016-07-29 10:42:48 +00003187 else if (Specifier == VirtSpecifiers::VS_GNU_Final)
3188 Diag(FinalLoc, diag::ext_warn_gnu_final);
Michael Han9407e502012-11-26 22:54:45 +00003189
Michael Han309af292013-01-07 16:57:11 +00003190 // Parse any C++11 attributes after 'final' keyword.
3191 // These attributes are not allowed to appear here,
3192 // and the only possible place for them to appertain
3193 // to the class would be between class-key and class-name.
Richard Smith4c96e992013-02-19 23:47:15 +00003194 CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
Nico Weber4b4be842014-12-29 06:56:50 +00003195
3196 // ParseClassSpecifier() does only a superficial check for attributes before
3197 // deciding to call this method. For example, for
3198 // `class C final alignas ([l) {` it will decide that this looks like a
3199 // misplaced attribute since it sees `alignas '(' ')'`. But the actual
3200 // attribute parsing code will try to parse the '[' as a constexpr lambda
3201 // and consume enough tokens that the alignas parsing code will eat the
3202 // opening '{'. So bail out if the next token isn't one we expect.
Nico Weber36de3a22014-12-29 21:56:22 +00003203 if (!Tok.is(tok::colon) && !Tok.is(tok::l_brace)) {
3204 if (TagDecl)
3205 Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
Nico Weber4b4be842014-12-29 06:56:50 +00003206 return;
Nico Weber36de3a22014-12-29 21:56:22 +00003207 }
Anders Carlssonf9eb63b2011-03-25 14:46:08 +00003208 }
Anders Carlsson4b63d0e2011-01-22 16:56:46 +00003209
John McCall2d814c32009-12-19 21:48:58 +00003210 if (Tok.is(tok::colon)) {
Erik Verbruggen6524c052017-10-24 13:46:58 +00003211 ParseScope InheritanceScope(this, getCurScope()->getFlags() |
3212 Scope::ClassInheritanceScope);
3213
John McCall2d814c32009-12-19 21:48:58 +00003214 ParseBaseClause(TagDecl);
John McCall2d814c32009-12-19 21:48:58 +00003215 if (!Tok.is(tok::l_brace)) {
Ismail Pazarbasi129c44c2014-09-25 21:13:02 +00003216 bool SuggestFixIt = false;
3217 SourceLocation BraceLoc = PP.getLocForEndOfToken(PrevTokLocation);
3218 if (Tok.isAtStartOfLine()) {
3219 switch (Tok.getKind()) {
3220 case tok::kw_private:
3221 case tok::kw_protected:
3222 case tok::kw_public:
3223 SuggestFixIt = NextToken().getKind() == tok::colon;
3224 break;
3225 case tok::kw_static_assert:
3226 case tok::r_brace:
3227 case tok::kw_using:
3228 // base-clause can have simple-template-id; 'template' can't be there
3229 case tok::kw_template:
3230 SuggestFixIt = true;
3231 break;
3232 case tok::identifier:
3233 SuggestFixIt = isConstructorDeclarator(true);
3234 break;
3235 default:
3236 SuggestFixIt = isCXXSimpleDeclaration(/*AllowForRangeDecl=*/false);
3237 break;
3238 }
3239 }
3240 DiagnosticBuilder LBraceDiag =
3241 Diag(BraceLoc, diag::err_expected_lbrace_after_base_specifiers);
3242 if (SuggestFixIt) {
3243 LBraceDiag << FixItHint::CreateInsertion(BraceLoc, " {");
3244 // Try recovering from missing { after base-clause.
3245 PP.EnterToken(Tok);
3246 Tok.setKind(tok::l_brace);
3247 } else {
3248 if (TagDecl)
3249 Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
3250 return;
3251 }
John McCall2d814c32009-12-19 21:48:58 +00003252 }
3253 }
3254
3255 assert(Tok.is(tok::l_brace));
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003256 BalancedDelimiterTracker T(*this, tok::l_brace);
3257 T.consumeOpen();
John McCall2d814c32009-12-19 21:48:58 +00003258
John McCall08bede42010-05-28 08:11:17 +00003259 if (TagDecl)
Anders Carlsson30f29442011-03-25 14:31:08 +00003260 Actions.ActOnStartCXXMemberDeclarations(getCurScope(), TagDecl, FinalLoc,
David Majnemera5433082013-10-18 00:33:31 +00003261 IsFinalSpelledSealed,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003262 T.getOpenLocation());
John McCall1c7e6ec2009-12-20 07:58:13 +00003263
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003264 // C++ 11p3: Members of a class defined with the keyword class are private
3265 // by default. Members of a class defined with the keywords struct or union
3266 // are public by default.
3267 AccessSpecifier CurAS;
3268 if (TagType == DeclSpec::TST_class)
3269 CurAS = AS_private;
3270 else
3271 CurAS = AS_public;
Alexey Bataev05c25d62015-07-31 08:42:25 +00003272 ParsedAttributesWithRange AccessAttrs(AttrFactory);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003273
Douglas Gregor9377c822010-06-21 22:31:09 +00003274 if (TagDecl) {
3275 // While we still have something to read, read the member-declarations.
Richard Smith752ada82015-11-17 23:32:01 +00003276 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
3277 Tok.isNot(tok::eof)) {
Douglas Gregor9377c822010-06-21 22:31:09 +00003278 // Each iteration of this loop reads one member-declaration.
Alexey Bataev05c25d62015-07-31 08:42:25 +00003279 ParseCXXClassMemberDeclarationWithPragmas(
3280 CurAS, AccessAttrs, static_cast<DeclSpec::TST>(TagType), TagDecl);
Serge Pavlovc4e04a22015-09-19 05:32:57 +00003281 }
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003282 T.consumeClose();
Douglas Gregor9377c822010-06-21 22:31:09 +00003283 } else {
Alexey Bataevee6507d2013-11-18 08:17:37 +00003284 SkipUntil(tok::r_brace);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003285 }
Mike Stump11289f42009-09-09 15:08:12 +00003286
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003287 // If attributes exist after class contents, parse them.
John McCall084e83d2011-03-24 11:26:52 +00003288 ParsedAttributes attrs(AttrFactory);
John McCall53fa7142010-12-24 02:08:15 +00003289 MaybeParseGNUAttributes(attrs);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003290
John McCall08bede42010-05-28 08:11:17 +00003291 if (TagDecl)
Douglas Gregor0be31a22010-07-02 17:43:08 +00003292 Actions.ActOnFinishCXXMemberSpecification(getCurScope(), RecordLoc, TagDecl,
Erich Keanec480f302018-07-12 21:09:05 +00003293 T.getOpenLocation(),
3294 T.getCloseLocation(), attrs);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003295
Douglas Gregor433e0532012-04-16 18:27:27 +00003296 // C++11 [class.mem]p2:
3297 // Within the class member-specification, the class is regarded as complete
Richard Smith0b3a4622014-11-13 20:01:57 +00003298 // within function bodies, default arguments, exception-specifications, and
Douglas Gregor433e0532012-04-16 18:27:27 +00003299 // brace-or-equal-initializers for non-static data members (including such
3300 // things in nested classes).
Douglas Gregor9377c822010-06-21 22:31:09 +00003301 if (TagDecl && NonNestedClass) {
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003302 // We are not inside a nested class. This class and its nested classes
Douglas Gregor4d87df52008-12-16 21:30:33 +00003303 // are complete and we can parse the delayed portions of method
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00003304 // declarations and the lexed inline method definitions, along with any
3305 // delayed attributes.
Douglas Gregor428119e2010-06-16 23:45:56 +00003306 SourceLocation SavedPrevTokLocation = PrevTokLocation;
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00003307 ParseLexedAttributes(getCurrentClass());
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003308 ParseLexedMethodDeclarations(getCurrentClass());
Richard Smith84973e52012-04-21 18:42:51 +00003309
3310 // We've finished with all pending member declarations.
3311 Actions.ActOnFinishCXXMemberDecls();
3312
Richard Smith938f40b2011-06-11 17:19:42 +00003313 ParseLexedMemberInitializers(getCurrentClass());
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003314 ParseLexedMethodDefs(getCurrentClass());
Douglas Gregor428119e2010-06-16 23:45:56 +00003315 PrevTokLocation = SavedPrevTokLocation;
Reid Klecknerbba3cb92015-03-17 19:00:50 +00003316
3317 // We've finished parsing everything, including default argument
3318 // initializers.
Hans Wennborg99000c22015-08-15 01:18:16 +00003319 Actions.ActOnFinishCXXNonNestedClass(TagDecl);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003320 }
3321
John McCall08bede42010-05-28 08:11:17 +00003322 if (TagDecl)
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00003323 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getRange());
John McCall2ff380a2010-03-17 00:38:33 +00003324
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003325 // Leave the class scope.
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003326 ParsingDef.Pop();
Douglas Gregor7307d6c2008-12-10 06:34:36 +00003327 ClassScope.Exit();
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00003328}
Douglas Gregore8381c02008-11-05 04:29:56 +00003329
Richard Smith2ac43ad2013-11-15 23:00:02 +00003330void Parser::DiagnoseUnexpectedNamespace(NamedDecl *D) {
Richard Smithda35e962013-11-09 04:52:51 +00003331 assert(Tok.is(tok::kw_namespace));
3332
3333 // FIXME: Suggest where the close brace should have gone by looking
3334 // at indentation changes within the definition body.
Richard Smith2ac43ad2013-11-15 23:00:02 +00003335 Diag(D->getLocation(),
3336 diag::err_missing_end_of_definition) << D;
Richard Smithda35e962013-11-09 04:52:51 +00003337 Diag(Tok.getLocation(),
Richard Smith2ac43ad2013-11-15 23:00:02 +00003338 diag::note_missing_end_of_definition_before) << D;
Richard Smithda35e962013-11-09 04:52:51 +00003339
3340 // Push '};' onto the token stream to recover.
3341 PP.EnterToken(Tok);
3342
3343 Tok.startToken();
3344 Tok.setLocation(PP.getLocForEndOfToken(PrevTokLocation));
3345 Tok.setKind(tok::semi);
3346 PP.EnterToken(Tok);
3347
3348 Tok.setKind(tok::r_brace);
3349}
3350
Douglas Gregore8381c02008-11-05 04:29:56 +00003351/// ParseConstructorInitializer - Parse a C++ constructor initializer,
3352/// which explicitly initializes the members or base classes of a
3353/// class (C++ [class.base.init]). For example, the three initializers
3354/// after the ':' in the Derived constructor below:
3355///
3356/// @code
3357/// class Base { };
3358/// class Derived : Base {
3359/// int x;
3360/// float f;
3361/// public:
3362/// Derived(float f) : Base(), x(17), f(f) { }
3363/// };
3364/// @endcode
3365///
Mike Stump11289f42009-09-09 15:08:12 +00003366/// [C++] ctor-initializer:
3367/// ':' mem-initializer-list
Douglas Gregore8381c02008-11-05 04:29:56 +00003368///
Mike Stump11289f42009-09-09 15:08:12 +00003369/// [C++] mem-initializer-list:
Douglas Gregor44e7df62011-01-04 00:32:56 +00003370/// mem-initializer ...[opt]
3371/// mem-initializer ...[opt] , mem-initializer-list
John McCall48871652010-08-21 09:40:31 +00003372void Parser::ParseConstructorInitializer(Decl *ConstructorDecl) {
Nico Weber3b00fdc2015-03-07 19:52:39 +00003373 assert(Tok.is(tok::colon) &&
3374 "Constructor initializer always starts with ':'");
Douglas Gregore8381c02008-11-05 04:29:56 +00003375
Nico Weber3b00fdc2015-03-07 19:52:39 +00003376 // Poison the SEH identifiers so they are flagged as illegal in constructor
3377 // initializers.
John Wiegley1c0675e2011-04-28 01:08:34 +00003378 PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
Douglas Gregore8381c02008-11-05 04:29:56 +00003379 SourceLocation ColonLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +00003380
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003381 SmallVector<CXXCtorInitializer*, 4> MemInitializers;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003382 bool AnyErrors = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003383
Douglas Gregore8381c02008-11-05 04:29:56 +00003384 do {
Douglas Gregoreaeeca92010-08-28 00:00:50 +00003385 if (Tok.is(tok::code_completion)) {
Dmitri Gribenko27cb3dd02013-06-23 22:58:02 +00003386 Actions.CodeCompleteConstructorInitializer(ConstructorDecl,
3387 MemInitializers);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00003388 return cutOffParsing();
Douglas Gregoreaeeca92010-08-28 00:00:50 +00003389 }
Alexey Bataev79de17d2016-01-20 05:25:51 +00003390
3391 MemInitResult MemInit = ParseMemInitializer(ConstructorDecl);
3392 if (!MemInit.isInvalid())
3393 MemInitializers.push_back(MemInit.get());
3394 else
3395 AnyErrors = true;
3396
Douglas Gregore8381c02008-11-05 04:29:56 +00003397 if (Tok.is(tok::comma))
3398 ConsumeToken();
3399 else if (Tok.is(tok::l_brace))
3400 break;
Alexey Bataev79de17d2016-01-20 05:25:51 +00003401 // If the previous initializer was valid and the next token looks like a
3402 // base or member initializer, assume that we're just missing a comma.
3403 else if (!MemInit.isInvalid() &&
3404 Tok.isOneOf(tok::identifier, tok::coloncolon)) {
Douglas Gregorce66d022010-09-07 14:51:08 +00003405 SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation);
3406 Diag(Loc, diag::err_ctor_init_missing_comma)
3407 << FixItHint::CreateInsertion(Loc, ", ");
3408 } else {
Douglas Gregore8381c02008-11-05 04:29:56 +00003409 // Skip over garbage, until we get to '{'. Don't eat the '{'.
Alexey Bataev79de17d2016-01-20 05:25:51 +00003410 if (!MemInit.isInvalid())
3411 Diag(Tok.getLocation(), diag::err_expected_either) << tok::l_brace
3412 << tok::comma;
Alexey Bataevee6507d2013-11-18 08:17:37 +00003413 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
Douglas Gregore8381c02008-11-05 04:29:56 +00003414 break;
3415 }
3416 } while (true);
3417
David Blaikie3fc2f912013-01-17 05:26:25 +00003418 Actions.ActOnMemInitializers(ConstructorDecl, ColonLoc, MemInitializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003419 AnyErrors);
Douglas Gregore8381c02008-11-05 04:29:56 +00003420}
3421
3422/// ParseMemInitializer - Parse a C++ member initializer, which is
3423/// part of a constructor initializer that explicitly initializes one
3424/// member or base class (C++ [class.base.init]). See
3425/// ParseConstructorInitializer for an example.
3426///
3427/// [C++] mem-initializer:
3428/// mem-initializer-id '(' expression-list[opt] ')'
Sebastian Redl3da34892011-06-05 12:23:16 +00003429/// [C++0x] mem-initializer-id braced-init-list
Mike Stump11289f42009-09-09 15:08:12 +00003430///
Douglas Gregore8381c02008-11-05 04:29:56 +00003431/// [C++] mem-initializer-id:
3432/// '::'[opt] nested-name-specifier[opt] class-name
3433/// identifier
Craig Topper9ad7e262014-10-31 06:57:07 +00003434MemInitResult Parser::ParseMemInitializer(Decl *ConstructorDecl) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00003435 // parse '::'[opt] nested-name-specifier[opt]
3436 CXXScopeSpec SS;
David Blaikieefdccaa2016-01-15 23:43:34 +00003437 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false);
Richard Smithaf3b3252017-05-18 19:21:48 +00003438
3439 // : identifier
3440 IdentifierInfo *II = nullptr;
3441 SourceLocation IdLoc = Tok.getLocation();
3442 // : declype(...)
3443 DeclSpec DS(AttrFactory);
3444 // : template_name<...>
John McCallba7bf592010-08-24 05:47:05 +00003445 ParsedType TemplateTypeTy;
Richard Smithaf3b3252017-05-18 19:21:48 +00003446
3447 if (Tok.is(tok::identifier)) {
3448 // Get the identifier. This may be a member name or a class name,
3449 // but we'll let the semantic analysis determine which it is.
3450 II = Tok.getIdentifierInfo();
3451 ConsumeToken();
3452 } else if (Tok.is(tok::annot_decltype)) {
3453 // Get the decltype expression, if there is one.
3454 // Uses of decltype will already have been converted to annot_decltype by
3455 // ParseOptionalCXXScopeSpecifier at this point.
3456 // FIXME: Can we get here with a scope specifier?
3457 ParseDecltypeSpecifier(DS);
3458 } else {
3459 TemplateIdAnnotation *TemplateId = Tok.is(tok::annot_template_id)
3460 ? takeTemplateIdAnnotation(Tok)
3461 : nullptr;
3462 if (TemplateId && (TemplateId->Kind == TNK_Type_template ||
3463 TemplateId->Kind == TNK_Dependent_template_name)) {
Richard Smith62559bd2017-02-01 21:36:38 +00003464 AnnotateTemplateIdTokenAsType(/*IsClassName*/true);
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00003465 assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
John McCallba7bf592010-08-24 05:47:05 +00003466 TemplateTypeTy = getTypeAnnotation(Tok);
Richard Smithaf3b3252017-05-18 19:21:48 +00003467 ConsumeAnnotationToken();
3468 } else {
3469 Diag(Tok, diag::err_expected_member_or_base_name);
3470 return true;
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00003471 }
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00003472 }
Douglas Gregore8381c02008-11-05 04:29:56 +00003473
3474 // Parse the '('.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003475 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
Richard Smith5d164bc2011-10-15 05:09:34 +00003476 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
3477
Kadir Cetinkaya84774c32018-09-11 15:02:18 +00003478 // FIXME: Add support for signature help inside initializer lists.
Sebastian Redla74948d2011-09-24 17:48:25 +00003479 ExprResult InitList = ParseBraceInitializer();
3480 if (InitList.isInvalid())
3481 return true;
3482
3483 SourceLocation EllipsisLoc;
Alp Toker094e5212014-01-05 03:27:11 +00003484 TryConsumeToken(tok::ellipsis, EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00003485
3486 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
Fangrui Song6907ce22018-07-30 19:24:48 +00003487 TemplateTypeTy, DS, IdLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003488 InitList.get(), EllipsisLoc);
Sebastian Redl3da34892011-06-05 12:23:16 +00003489 } else if(Tok.is(tok::l_paren)) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003490 BalancedDelimiterTracker T(*this, tok::l_paren);
3491 T.consumeOpen();
Douglas Gregore8381c02008-11-05 04:29:56 +00003492
Sebastian Redl3da34892011-06-05 12:23:16 +00003493 // Parse the optional expression-list.
Benjamin Kramerf0623432012-08-23 22:51:59 +00003494 ExprVector ArgExprs;
Sebastian Redl3da34892011-06-05 12:23:16 +00003495 CommaLocsTy CommaLocs;
Kadir Cetinkaya84774c32018-09-11 15:02:18 +00003496 if (Tok.isNot(tok::r_paren) &&
3497 ParseExpressionList(ArgExprs, CommaLocs, [&] {
3498 QualType PreferredType = Actions.ProduceCtorInitMemberSignatureHelp(
3499 getCurScope(), ConstructorDecl, SS, TemplateTypeTy, ArgExprs, II,
3500 T.getOpenLocation());
3501 CalledSignatureHelp = true;
3502 Actions.CodeCompleteExpression(getCurScope(), PreferredType);
3503 })) {
3504 if (PP.isCodeCompletionReached() && !CalledSignatureHelp) {
3505 Actions.ProduceCtorInitMemberSignatureHelp(
3506 getCurScope(), ConstructorDecl, SS, TemplateTypeTy, ArgExprs, II,
3507 T.getOpenLocation());
3508 CalledSignatureHelp = true;
3509 }
Alexey Bataevee6507d2013-11-18 08:17:37 +00003510 SkipUntil(tok::r_paren, StopAtSemi);
Sebastian Redl3da34892011-06-05 12:23:16 +00003511 return true;
3512 }
3513
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003514 T.consumeClose();
Sebastian Redl3da34892011-06-05 12:23:16 +00003515
3516 SourceLocation EllipsisLoc;
Alp Toker97650562014-01-10 11:19:30 +00003517 TryConsumeToken(tok::ellipsis, EllipsisLoc);
Sebastian Redl3da34892011-06-05 12:23:16 +00003518
3519 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
David Blaikie186a8892012-01-24 06:03:59 +00003520 TemplateTypeTy, DS, IdLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00003521 T.getOpenLocation(), ArgExprs,
3522 T.getCloseLocation(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00003523 }
3524
Alp Tokerec543272013-12-24 09:48:30 +00003525 if (getLangOpts().CPlusPlus11)
3526 return Diag(Tok, diag::err_expected_either) << tok::l_paren << tok::l_brace;
3527 else
3528 return Diag(Tok, diag::err_expected) << tok::l_paren;
Douglas Gregore8381c02008-11-05 04:29:56 +00003529}
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003530
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003531/// Parse a C++ exception-specification if present (C++0x [except.spec]).
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003532///
Douglas Gregor356513d2008-12-01 18:00:20 +00003533/// exception-specification:
Sebastian Redl965b0e32011-03-05 14:45:16 +00003534/// dynamic-exception-specification
3535/// noexcept-specification
3536///
3537/// noexcept-specification:
3538/// 'noexcept'
3539/// 'noexcept' '(' constant-expression ')'
3540ExceptionSpecificationType
Richard Smith0b3a4622014-11-13 20:01:57 +00003541Parser::tryParseExceptionSpecification(bool Delayed,
Douglas Gregor433e0532012-04-16 18:27:27 +00003542 SourceRange &SpecificationRange,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003543 SmallVectorImpl<ParsedType> &DynamicExceptions,
3544 SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
Richard Smith0b3a4622014-11-13 20:01:57 +00003545 ExprResult &NoexceptExpr,
3546 CachedTokens *&ExceptionSpecTokens) {
Sebastian Redl965b0e32011-03-05 14:45:16 +00003547 ExceptionSpecificationType Result = EST_None;
Hans Wennborgdcfba332015-10-06 23:40:43 +00003548 ExceptionSpecTokens = nullptr;
Fangrui Song6907ce22018-07-30 19:24:48 +00003549
Richard Smith0b3a4622014-11-13 20:01:57 +00003550 // Handle delayed parsing of exception-specifications.
3551 if (Delayed) {
3552 if (Tok.isNot(tok::kw_throw) && Tok.isNot(tok::kw_noexcept))
3553 return EST_None;
Sebastian Redl965b0e32011-03-05 14:45:16 +00003554
Richard Smith0b3a4622014-11-13 20:01:57 +00003555 // Consume and cache the starting token.
3556 bool IsNoexcept = Tok.is(tok::kw_noexcept);
3557 Token StartTok = Tok;
3558 SpecificationRange = SourceRange(ConsumeToken());
3559
3560 // Check for a '('.
3561 if (!Tok.is(tok::l_paren)) {
3562 // If this is a bare 'noexcept', we're done.
3563 if (IsNoexcept) {
3564 Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
Hans Wennborgdcfba332015-10-06 23:40:43 +00003565 NoexceptExpr = nullptr;
Richard Smith0b3a4622014-11-13 20:01:57 +00003566 return EST_BasicNoexcept;
3567 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003568
Richard Smith0b3a4622014-11-13 20:01:57 +00003569 Diag(Tok, diag::err_expected_lparen_after) << "throw";
3570 return EST_DynamicNone;
3571 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003572
Richard Smith0b3a4622014-11-13 20:01:57 +00003573 // Cache the tokens for the exception-specification.
3574 ExceptionSpecTokens = new CachedTokens;
3575 ExceptionSpecTokens->push_back(StartTok); // 'throw' or 'noexcept'
3576 ExceptionSpecTokens->push_back(Tok); // '('
3577 SpecificationRange.setEnd(ConsumeParen()); // '('
Richard Smithb1c217e2015-01-13 02:24:58 +00003578
3579 ConsumeAndStoreUntil(tok::r_paren, *ExceptionSpecTokens,
3580 /*StopAtSemi=*/true,
3581 /*ConsumeFinalToken=*/true);
Aaron Ballman580ccaf2016-01-12 21:04:22 +00003582 SpecificationRange.setEnd(ExceptionSpecTokens->back().getLocation());
3583
Richard Smith0b3a4622014-11-13 20:01:57 +00003584 return EST_Unparsed;
3585 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003586
Sebastian Redl965b0e32011-03-05 14:45:16 +00003587 // See if there's a dynamic specification.
3588 if (Tok.is(tok::kw_throw)) {
3589 Result = ParseDynamicExceptionSpecification(SpecificationRange,
3590 DynamicExceptions,
3591 DynamicExceptionRanges);
3592 assert(DynamicExceptions.size() == DynamicExceptionRanges.size() &&
3593 "Produced different number of exception types and ranges.");
3594 }
3595
3596 // If there's no noexcept specification, we're done.
3597 if (Tok.isNot(tok::kw_noexcept))
3598 return Result;
3599
Richard Smithb15c11c2011-10-17 23:06:20 +00003600 Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
3601
Sebastian Redl965b0e32011-03-05 14:45:16 +00003602 // If we already had a dynamic specification, parse the noexcept for,
3603 // recovery, but emit a diagnostic and don't store the results.
3604 SourceRange NoexceptRange;
3605 ExceptionSpecificationType NoexceptType = EST_None;
3606
3607 SourceLocation KeywordLoc = ConsumeToken();
3608 if (Tok.is(tok::l_paren)) {
3609 // There is an argument.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003610 BalancedDelimiterTracker T(*this, tok::l_paren);
3611 T.consumeOpen();
Sebastian Redl965b0e32011-03-05 14:45:16 +00003612 NoexceptExpr = ParseConstantExpression();
Serge Pavlov3739f5e72015-06-29 17:50:19 +00003613 T.consumeClose();
Serge Pavlov3739f5e72015-06-29 17:50:19 +00003614 if (!NoexceptExpr.isInvalid()) {
Richard Smitheaf11ad2018-05-03 03:58:32 +00003615 NoexceptExpr = Actions.ActOnNoexceptSpec(KeywordLoc, NoexceptExpr.get(),
3616 NoexceptType);
Serge Pavlov3739f5e72015-06-29 17:50:19 +00003617 NoexceptRange = SourceRange(KeywordLoc, T.getCloseLocation());
3618 } else {
Malcolm Parsonsa3220ce2017-01-12 16:11:28 +00003619 NoexceptType = EST_BasicNoexcept;
Serge Pavlov3739f5e72015-06-29 17:50:19 +00003620 }
Sebastian Redl965b0e32011-03-05 14:45:16 +00003621 } else {
3622 // There is no argument.
3623 NoexceptType = EST_BasicNoexcept;
3624 NoexceptRange = SourceRange(KeywordLoc, KeywordLoc);
3625 }
3626
3627 if (Result == EST_None) {
3628 SpecificationRange = NoexceptRange;
3629 Result = NoexceptType;
3630
3631 // If there's a dynamic specification after a noexcept specification,
3632 // parse that and ignore the results.
3633 if (Tok.is(tok::kw_throw)) {
3634 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
3635 ParseDynamicExceptionSpecification(NoexceptRange, DynamicExceptions,
3636 DynamicExceptionRanges);
3637 }
3638 } else {
3639 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
3640 }
3641
3642 return Result;
3643}
3644
Richard Smith8ca78a12013-06-13 02:02:51 +00003645static void diagnoseDynamicExceptionSpecification(
Craig Toppere335f252015-10-04 04:53:55 +00003646 Parser &P, SourceRange Range, bool IsNoexcept) {
Richard Smith8ca78a12013-06-13 02:02:51 +00003647 if (P.getLangOpts().CPlusPlus11) {
3648 const char *Replacement = IsNoexcept ? "noexcept" : "noexcept(false)";
Richard Smith82da19d2016-12-08 02:49:07 +00003649 P.Diag(Range.getBegin(),
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003650 P.getLangOpts().CPlusPlus17 && !IsNoexcept
Richard Smith82da19d2016-12-08 02:49:07 +00003651 ? diag::ext_dynamic_exception_spec
3652 : diag::warn_exception_spec_deprecated)
3653 << Range;
Richard Smith8ca78a12013-06-13 02:02:51 +00003654 P.Diag(Range.getBegin(), diag::note_exception_spec_deprecated)
3655 << Replacement << FixItHint::CreateReplacement(Range, Replacement);
3656 }
3657}
3658
Sebastian Redl965b0e32011-03-05 14:45:16 +00003659/// ParseDynamicExceptionSpecification - Parse a C++
3660/// dynamic-exception-specification (C++ [except.spec]).
3661///
3662/// dynamic-exception-specification:
Douglas Gregor356513d2008-12-01 18:00:20 +00003663/// 'throw' '(' type-id-list [opt] ')'
3664/// [MS] 'throw' '(' '...' ')'
Mike Stump11289f42009-09-09 15:08:12 +00003665///
Douglas Gregor356513d2008-12-01 18:00:20 +00003666/// type-id-list:
Douglas Gregor830837d2010-12-20 23:57:46 +00003667/// type-id ... [opt]
3668/// type-id-list ',' type-id ... [opt]
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003669///
Sebastian Redl965b0e32011-03-05 14:45:16 +00003670ExceptionSpecificationType Parser::ParseDynamicExceptionSpecification(
3671 SourceRange &SpecificationRange,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003672 SmallVectorImpl<ParsedType> &Exceptions,
3673 SmallVectorImpl<SourceRange> &Ranges) {
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003674 assert(Tok.is(tok::kw_throw) && "expected throw");
Mike Stump11289f42009-09-09 15:08:12 +00003675
Sebastian Redl965b0e32011-03-05 14:45:16 +00003676 SpecificationRange.setBegin(ConsumeToken());
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003677 BalancedDelimiterTracker T(*this, tok::l_paren);
3678 if (T.consumeOpen()) {
Sebastian Redl965b0e32011-03-05 14:45:16 +00003679 Diag(Tok, diag::err_expected_lparen_after) << "throw";
3680 SpecificationRange.setEnd(SpecificationRange.getBegin());
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003681 return EST_DynamicNone;
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003682 }
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003683
Douglas Gregor356513d2008-12-01 18:00:20 +00003684 // Parse throw(...), a Microsoft extension that means "this function
3685 // can throw anything".
3686 if (Tok.is(tok::ellipsis)) {
3687 SourceLocation EllipsisLoc = ConsumeToken();
David Blaikiebbafb8a2012-03-11 07:00:24 +00003688 if (!getLangOpts().MicrosoftExt)
Douglas Gregor356513d2008-12-01 18:00:20 +00003689 Diag(EllipsisLoc, diag::ext_ellipsis_exception_spec);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003690 T.consumeClose();
3691 SpecificationRange.setEnd(T.getCloseLocation());
Richard Smith8ca78a12013-06-13 02:02:51 +00003692 diagnoseDynamicExceptionSpecification(*this, SpecificationRange, false);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003693 return EST_MSAny;
Douglas Gregor356513d2008-12-01 18:00:20 +00003694 }
3695
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003696 // Parse the sequence of type-ids.
Sebastian Redld6434562009-05-29 18:02:33 +00003697 SourceRange Range;
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003698 while (Tok.isNot(tok::r_paren)) {
Sebastian Redld6434562009-05-29 18:02:33 +00003699 TypeResult Res(ParseTypeName(&Range));
Sebastian Redl965b0e32011-03-05 14:45:16 +00003700
Douglas Gregor830837d2010-12-20 23:57:46 +00003701 if (Tok.is(tok::ellipsis)) {
3702 // C++0x [temp.variadic]p5:
Fangrui Song6907ce22018-07-30 19:24:48 +00003703 // - In a dynamic-exception-specification (15.4); the pattern is a
Douglas Gregor830837d2010-12-20 23:57:46 +00003704 // type-id.
3705 SourceLocation Ellipsis = ConsumeToken();
Sebastian Redl965b0e32011-03-05 14:45:16 +00003706 Range.setEnd(Ellipsis);
Douglas Gregor830837d2010-12-20 23:57:46 +00003707 if (!Res.isInvalid())
3708 Res = Actions.ActOnPackExpansion(Res.get(), Ellipsis);
3709 }
Sebastian Redl965b0e32011-03-05 14:45:16 +00003710
Sebastian Redld6434562009-05-29 18:02:33 +00003711 if (!Res.isInvalid()) {
Sebastian Redl2b9cacb2009-04-29 17:30:04 +00003712 Exceptions.push_back(Res.get());
Sebastian Redld6434562009-05-29 18:02:33 +00003713 Ranges.push_back(Range);
3714 }
Alp Toker97650562014-01-10 11:19:30 +00003715
3716 if (!TryConsumeToken(tok::comma))
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003717 break;
3718 }
3719
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003720 T.consumeClose();
3721 SpecificationRange.setEnd(T.getCloseLocation());
Richard Smith8ca78a12013-06-13 02:02:51 +00003722 diagnoseDynamicExceptionSpecification(*this, SpecificationRange,
3723 Exceptions.empty());
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003724 return Exceptions.empty() ? EST_DynamicNone : EST_Dynamic;
Douglas Gregor2afd0be2008-11-25 03:22:00 +00003725}
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003726
Douglas Gregor7fb25412010-10-01 18:44:50 +00003727/// ParseTrailingReturnType - Parse a trailing return type on a new-style
3728/// function declaration.
Richard Smithe303e352018-02-02 22:24:54 +00003729TypeResult Parser::ParseTrailingReturnType(SourceRange &Range,
3730 bool MayBeFollowedByDirectInit) {
Douglas Gregor7fb25412010-10-01 18:44:50 +00003731 assert(Tok.is(tok::arrow) && "expected arrow");
3732
3733 ConsumeToken();
3734
Richard Smithe303e352018-02-02 22:24:54 +00003735 return ParseTypeName(&Range, MayBeFollowedByDirectInit
3736 ? DeclaratorContext::TrailingReturnVarContext
3737 : DeclaratorContext::TrailingReturnContext);
Douglas Gregor7fb25412010-10-01 18:44:50 +00003738}
3739
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003740/// We have just started parsing the definition of a new class,
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003741/// so push that class onto our stack of classes that is currently
3742/// being parsed.
John McCallc1465822011-02-14 07:13:47 +00003743Sema::ParsingClassState
John McCalldb632ac2012-09-25 07:32:39 +00003744Parser::PushParsingClass(Decl *ClassDecl, bool NonNestedClass,
3745 bool IsInterface) {
Douglas Gregoredf8f392010-01-16 20:52:59 +00003746 assert((NonNestedClass || !ClassStack.empty()) &&
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003747 "Nested class without outer class");
John McCalldb632ac2012-09-25 07:32:39 +00003748 ClassStack.push(new ParsingClass(ClassDecl, NonNestedClass, IsInterface));
John McCallc1465822011-02-14 07:13:47 +00003749 return Actions.PushParsingClass();
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003750}
3751
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003752/// Deallocate the given parsed class and all of its nested
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003753/// classes.
3754void Parser::DeallocateParsedClasses(Parser::ParsingClass *Class) {
Douglas Gregorefc46952010-10-12 16:25:54 +00003755 for (unsigned I = 0, N = Class->LateParsedDeclarations.size(); I != N; ++I)
3756 delete Class->LateParsedDeclarations[I];
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003757 delete Class;
3758}
3759
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003760/// Pop the top class of the stack of classes that are
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003761/// currently being parsed.
3762///
3763/// This routine should be called when we have finished parsing the
3764/// definition of a class, but have not yet popped the Scope
3765/// associated with the class's definition.
John McCallc1465822011-02-14 07:13:47 +00003766void Parser::PopParsingClass(Sema::ParsingClassState state) {
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003767 assert(!ClassStack.empty() && "Mismatched push/pop for class parsing");
Mike Stump11289f42009-09-09 15:08:12 +00003768
John McCallc1465822011-02-14 07:13:47 +00003769 Actions.PopParsingClass(state);
3770
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003771 ParsingClass *Victim = ClassStack.top();
3772 ClassStack.pop();
3773 if (Victim->TopLevelClass) {
3774 // Deallocate all of the nested classes of this class,
3775 // recursively: we don't need to keep any of this information.
3776 DeallocateParsedClasses(Victim);
3777 return;
Mike Stump11289f42009-09-09 15:08:12 +00003778 }
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003779 assert(!ClassStack.empty() && "Missing top-level class?");
3780
Douglas Gregorefc46952010-10-12 16:25:54 +00003781 if (Victim->LateParsedDeclarations.empty()) {
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003782 // The victim is a nested class, but we will not need to perform
3783 // any processing after the definition of this class since it has
3784 // no members whose handling was delayed. Therefore, we can just
3785 // remove this nested class.
Douglas Gregorefc46952010-10-12 16:25:54 +00003786 DeallocateParsedClasses(Victim);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003787 return;
3788 }
3789
3790 // This nested class has some members that will need to be processed
3791 // after the top-level class is completely defined. Therefore, add
3792 // it to the list of nested classes within its parent.
Douglas Gregor0be31a22010-07-02 17:43:08 +00003793 assert(getCurScope()->isClassScope() && "Nested class outside of class scope?");
Douglas Gregorefc46952010-10-12 16:25:54 +00003794 ClassStack.top()->LateParsedDeclarations.push_back(new LateParsedClass(this, Victim));
Douglas Gregor0be31a22010-07-02 17:43:08 +00003795 Victim->TemplateScope = getCurScope()->getParent()->isTemplateParamScope();
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003796}
Alexis Hunt96d5c762009-11-21 08:43:09 +00003797
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003798/// Try to parse an 'identifier' which appears within an attribute-token.
Richard Smith3dff2512012-04-10 03:25:07 +00003799///
3800/// \return the parsed identifier on success, and 0 if the next token is not an
3801/// attribute-token.
3802///
3803/// C++11 [dcl.attr.grammar]p3:
3804/// If a keyword or an alternative token that satisfies the syntactic
3805/// requirements of an identifier is contained in an attribute-token,
3806/// it is considered an identifier.
3807IdentifierInfo *Parser::TryParseCXX11AttributeIdentifier(SourceLocation &Loc) {
3808 switch (Tok.getKind()) {
3809 default:
3810 // Identifiers and keywords have identifier info attached.
David Majnemerd5271992015-01-09 18:09:39 +00003811 if (!Tok.isAnnotation()) {
3812 if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
3813 Loc = ConsumeToken();
3814 return II;
3815 }
Richard Smith3dff2512012-04-10 03:25:07 +00003816 }
Craig Topper161e4db2014-05-21 06:02:52 +00003817 return nullptr;
Richard Smith3dff2512012-04-10 03:25:07 +00003818
Aaron Ballmanc44c17422018-11-09 17:19:45 +00003819 case tok::numeric_constant: {
3820 // If we got a numeric constant, check to see if it comes from a macro that
3821 // corresponds to the predefined __clang__ macro. If it does, warn the user
3822 // and recover by pretending they said _Clang instead.
3823 if (Tok.getLocation().isMacroID()) {
3824 SmallString<8> ExpansionBuf;
3825 SourceLocation ExpansionLoc =
3826 PP.getSourceManager().getExpansionLoc(Tok.getLocation());
3827 StringRef Spelling = PP.getSpelling(ExpansionLoc, ExpansionBuf);
3828 if (Spelling == "__clang__") {
3829 SourceRange TokRange(
3830 ExpansionLoc,
3831 PP.getSourceManager().getExpansionLoc(Tok.getEndLoc()));
3832 Diag(Tok, diag::warn_wrong_clang_attr_namespace)
3833 << FixItHint::CreateReplacement(TokRange, "_Clang");
3834 Loc = ConsumeToken();
3835 return &PP.getIdentifierTable().get("_Clang");
3836 }
3837 }
3838 return nullptr;
3839 }
3840
Richard Smith3dff2512012-04-10 03:25:07 +00003841 case tok::ampamp: // 'and'
3842 case tok::pipe: // 'bitor'
3843 case tok::pipepipe: // 'or'
3844 case tok::caret: // 'xor'
3845 case tok::tilde: // 'compl'
3846 case tok::amp: // 'bitand'
3847 case tok::ampequal: // 'and_eq'
3848 case tok::pipeequal: // 'or_eq'
3849 case tok::caretequal: // 'xor_eq'
3850 case tok::exclaim: // 'not'
3851 case tok::exclaimequal: // 'not_eq'
3852 // Alternative tokens do not have identifier info, but their spelling
3853 // starts with an alphabetical character.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003854 SmallString<8> SpellingBuf;
Benjamin Kramer60be5632015-03-29 19:25:07 +00003855 SourceLocation SpellingLoc =
3856 PP.getSourceManager().getSpellingLoc(Tok.getLocation());
3857 StringRef Spelling = PP.getSpelling(SpellingLoc, SpellingBuf);
Jordan Rosea7d03842013-02-08 22:30:41 +00003858 if (isLetter(Spelling[0])) {
Richard Smith3dff2512012-04-10 03:25:07 +00003859 Loc = ConsumeToken();
Benjamin Kramer5c17f9c2012-04-22 20:43:30 +00003860 return &PP.getIdentifierTable().get(Spelling);
Richard Smith3dff2512012-04-10 03:25:07 +00003861 }
Craig Topper161e4db2014-05-21 06:02:52 +00003862 return nullptr;
Richard Smith3dff2512012-04-10 03:25:07 +00003863 }
3864}
3865
Michael Han23214e52012-10-03 01:56:22 +00003866static bool IsBuiltInOrStandardCXX11Attribute(IdentifierInfo *AttrName,
Aaron Ballman606093a2017-10-15 15:01:42 +00003867 IdentifierInfo *ScopeName) {
Erich Keanee891aa92018-07-13 15:07:47 +00003868 switch (ParsedAttr::getKind(AttrName, ScopeName, ParsedAttr::AS_CXX11)) {
3869 case ParsedAttr::AT_CarriesDependency:
3870 case ParsedAttr::AT_Deprecated:
3871 case ParsedAttr::AT_FallThrough:
3872 case ParsedAttr::AT_CXX11NoReturn:
Michael Han23214e52012-10-03 01:56:22 +00003873 return true;
Erich Keanee891aa92018-07-13 15:07:47 +00003874 case ParsedAttr::AT_WarnUnusedResult:
Aaron Ballmane7964782016-03-07 22:44:55 +00003875 return !ScopeName && AttrName->getName().equals("nodiscard");
Erich Keanee891aa92018-07-13 15:07:47 +00003876 case ParsedAttr::AT_Unused:
Nico Weberac03bce2016-08-23 19:59:55 +00003877 return !ScopeName && AttrName->getName().equals("maybe_unused");
Michael Han23214e52012-10-03 01:56:22 +00003878 default:
3879 return false;
3880 }
3881}
3882
Aaron Ballmanb8e20392014-03-31 17:32:39 +00003883/// ParseCXX11AttributeArgs -- Parse a C++11 attribute-argument-clause.
3884///
3885/// [C++11] attribute-argument-clause:
3886/// '(' balanced-token-seq ')'
3887///
3888/// [C++11] balanced-token-seq:
3889/// balanced-token
3890/// balanced-token-seq balanced-token
3891///
3892/// [C++11] balanced-token:
3893/// '(' balanced-token-seq ')'
3894/// '[' balanced-token-seq ']'
3895/// '{' balanced-token-seq '}'
3896/// any token but '(', ')', '[', ']', '{', or '}'
3897bool Parser::ParseCXX11AttributeArgs(IdentifierInfo *AttrName,
3898 SourceLocation AttrNameLoc,
3899 ParsedAttributes &Attrs,
3900 SourceLocation *EndLoc,
3901 IdentifierInfo *ScopeName,
3902 SourceLocation ScopeLoc) {
3903 assert(Tok.is(tok::l_paren) && "Not a C++11 attribute argument list");
Aaron Ballman35f94212014-04-14 16:03:22 +00003904 SourceLocation LParenLoc = Tok.getLocation();
Aaron Ballman606093a2017-10-15 15:01:42 +00003905 const LangOptions &LO = getLangOpts();
Erich Keanee891aa92018-07-13 15:07:47 +00003906 ParsedAttr::Syntax Syntax =
3907 LO.CPlusPlus ? ParsedAttr::AS_CXX11 : ParsedAttr::AS_C2x;
Aaron Ballmanb8e20392014-03-31 17:32:39 +00003908
3909 // If the attribute isn't known, we will not attempt to parse any
3910 // arguments.
Aaron Ballman606093a2017-10-15 15:01:42 +00003911 if (!hasAttribute(LO.CPlusPlus ? AttrSyntax::CXX : AttrSyntax::C, ScopeName,
3912 AttrName, getTargetInfo(), getLangOpts())) {
Aaron Ballmanb8e20392014-03-31 17:32:39 +00003913 // Eat the left paren, then skip to the ending right paren.
3914 ConsumeParen();
3915 SkipUntil(tok::r_paren);
Aaron Ballmanc44c17422018-11-09 17:19:45 +00003916 return false;
3917 }
3918
3919 if (ScopeName && (ScopeName->isStr("gnu") || ScopeName->isStr("__gnu__"))) {
3920 // GNU-scoped attributes have some special cases to handle GNU-specific
3921 // behaviors.
3922 ParseGNUAttributeArgs(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
Aaron Ballman606093a2017-10-15 15:01:42 +00003923 ScopeLoc, Syntax, nullptr);
Alex Lorenzd5d27e12017-03-01 18:06:25 +00003924 return true;
3925 }
3926
3927 unsigned NumArgs;
3928 // Some Clang-scoped attributes have some special parsing behavior.
Aaron Ballmanc44c17422018-11-09 17:19:45 +00003929 if (ScopeName && (ScopeName->isStr("clang") || ScopeName->isStr("_Clang")))
3930 NumArgs = ParseClangAttributeArgs(AttrName, AttrNameLoc, Attrs, EndLoc,
3931 ScopeName, ScopeLoc, Syntax);
Alex Lorenzd5d27e12017-03-01 18:06:25 +00003932 else
3933 NumArgs =
Aaron Ballman35f94212014-04-14 16:03:22 +00003934 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc,
Aaron Ballman606093a2017-10-15 15:01:42 +00003935 ScopeName, ScopeLoc, Syntax);
Alex Lorenzd5d27e12017-03-01 18:06:25 +00003936
Erich Keanec480f302018-07-12 21:09:05 +00003937 if (!Attrs.empty() &&
3938 IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName)) {
Michael Krusedc5ce722018-08-03 01:21:16 +00003939 ParsedAttr &Attr = Attrs.back();
Alex Lorenzd5d27e12017-03-01 18:06:25 +00003940 // If the attribute is a standard or built-in attribute and we are
3941 // parsing an argument list, we need to determine whether this attribute
3942 // was allowed to have an argument list (such as [[deprecated]]), and how
3943 // many arguments were parsed (so we can diagnose on [[deprecated()]]).
Erich Keanec480f302018-07-12 21:09:05 +00003944 if (Attr.getMaxArgs() && !NumArgs) {
Alex Lorenzd5d27e12017-03-01 18:06:25 +00003945 // The attribute was allowed to have arguments, but none were provided
3946 // even though the attribute parsed successfully. This is an error.
3947 Diag(LParenLoc, diag::err_attribute_requires_arguments) << AttrName;
Erich Keanec480f302018-07-12 21:09:05 +00003948 Attr.setInvalid(true);
3949 } else if (!Attr.getMaxArgs()) {
Alex Lorenzd5d27e12017-03-01 18:06:25 +00003950 // The attribute parsed successfully, but was not allowed to have any
3951 // arguments. It doesn't matter whether any were provided -- the
3952 // presence of the argument list (even if empty) is diagnosed.
3953 Diag(LParenLoc, diag::err_cxx11_attribute_forbids_arguments)
3954 << AttrName
3955 << FixItHint::CreateRemoval(SourceRange(LParenLoc, *EndLoc));
Erich Keanec480f302018-07-12 21:09:05 +00003956 Attr.setInvalid(true);
Aaron Ballman35f94212014-04-14 16:03:22 +00003957 }
3958 }
Aaron Ballmanb8e20392014-03-31 17:32:39 +00003959 return true;
3960}
3961
Aaron Ballman606093a2017-10-15 15:01:42 +00003962/// ParseCXX11AttributeSpecifier - Parse a C++11 or C2x attribute-specifier.
Alexis Hunt96d5c762009-11-21 08:43:09 +00003963///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003964/// [C++11] attribute-specifier:
Alexis Hunt96d5c762009-11-21 08:43:09 +00003965/// '[' '[' attribute-list ']' ']'
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00003966/// alignment-specifier
Alexis Hunt96d5c762009-11-21 08:43:09 +00003967///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003968/// [C++11] attribute-list:
Alexis Hunt96d5c762009-11-21 08:43:09 +00003969/// attribute[opt]
3970/// attribute-list ',' attribute[opt]
Richard Smith3dff2512012-04-10 03:25:07 +00003971/// attribute '...'
3972/// attribute-list ',' attribute '...'
Alexis Hunt96d5c762009-11-21 08:43:09 +00003973///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003974/// [C++11] attribute:
Alexis Hunt96d5c762009-11-21 08:43:09 +00003975/// attribute-token attribute-argument-clause[opt]
3976///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003977/// [C++11] attribute-token:
Alexis Hunt96d5c762009-11-21 08:43:09 +00003978/// identifier
3979/// attribute-scoped-token
3980///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003981/// [C++11] attribute-scoped-token:
Alexis Hunt96d5c762009-11-21 08:43:09 +00003982/// attribute-namespace '::' identifier
3983///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003984/// [C++11] attribute-namespace:
Alexis Hunt96d5c762009-11-21 08:43:09 +00003985/// identifier
Richard Smith3dff2512012-04-10 03:25:07 +00003986void Parser::ParseCXX11AttributeSpecifier(ParsedAttributes &attrs,
Peter Collingbourne49eedec2011-09-29 18:04:05 +00003987 SourceLocation *endLoc) {
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00003988 if (Tok.is(tok::kw_alignas)) {
Richard Smithf679b5b2011-10-14 20:48:27 +00003989 Diag(Tok.getLocation(), diag::warn_cxx98_compat_alignas);
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00003990 ParseAlignmentSpecifier(attrs, endLoc);
3991 return;
3992 }
3993
Aaron Ballman606093a2017-10-15 15:01:42 +00003994 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square) &&
3995 "Not a double square bracket attribute list");
Alexis Hunt96d5c762009-11-21 08:43:09 +00003996
Richard Smithf679b5b2011-10-14 20:48:27 +00003997 Diag(Tok.getLocation(), diag::warn_cxx98_compat_attribute);
3998
Alexis Hunt96d5c762009-11-21 08:43:09 +00003999 ConsumeBracket();
4000 ConsumeBracket();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004001
Richard Smithb7d7a042016-06-24 12:15:12 +00004002 SourceLocation CommonScopeLoc;
4003 IdentifierInfo *CommonScopeName = nullptr;
4004 if (Tok.is(tok::kw_using)) {
Aaron Ballmanc351fba2017-12-04 20:27:34 +00004005 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
Richard Smithb7d7a042016-06-24 12:15:12 +00004006 ? diag::warn_cxx14_compat_using_attribute_ns
4007 : diag::ext_using_attribute_ns);
4008 ConsumeToken();
4009
4010 CommonScopeName = TryParseCXX11AttributeIdentifier(CommonScopeLoc);
4011 if (!CommonScopeName) {
4012 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
4013 SkipUntil(tok::r_square, tok::colon, StopBeforeMatch);
4014 }
4015 if (!TryConsumeToken(tok::colon) && CommonScopeName)
4016 Diag(Tok.getLocation(), diag::err_expected) << tok::colon;
4017 }
4018
Richard Smith10876ef2013-01-17 01:30:42 +00004019 llvm::SmallDenseMap<IdentifierInfo*, SourceLocation, 4> SeenAttrs;
4020
Richard Smith3dff2512012-04-10 03:25:07 +00004021 while (Tok.isNot(tok::r_square)) {
Alexis Hunt96d5c762009-11-21 08:43:09 +00004022 // attribute not present
Alp Toker97650562014-01-10 11:19:30 +00004023 if (TryConsumeToken(tok::comma))
Alexis Hunt96d5c762009-11-21 08:43:09 +00004024 continue;
Alexis Hunt96d5c762009-11-21 08:43:09 +00004025
Richard Smith3dff2512012-04-10 03:25:07 +00004026 SourceLocation ScopeLoc, AttrLoc;
Craig Topper161e4db2014-05-21 06:02:52 +00004027 IdentifierInfo *ScopeName = nullptr, *AttrName = nullptr;
Richard Smith3dff2512012-04-10 03:25:07 +00004028
4029 AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
4030 if (!AttrName)
4031 // Break out to the "expected ']'" diagnostic.
4032 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004033
Alexis Hunt96d5c762009-11-21 08:43:09 +00004034 // scoped attribute
Alp Toker97650562014-01-10 11:19:30 +00004035 if (TryConsumeToken(tok::coloncolon)) {
Richard Smith3dff2512012-04-10 03:25:07 +00004036 ScopeName = AttrName;
4037 ScopeLoc = AttrLoc;
4038
4039 AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
4040 if (!AttrName) {
Alp Tokerec543272013-12-24 09:48:30 +00004041 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
Alexey Bataevee6507d2013-11-18 08:17:37 +00004042 SkipUntil(tok::r_square, tok::comma, StopAtSemi | StopBeforeMatch);
Alexis Hunt96d5c762009-11-21 08:43:09 +00004043 continue;
4044 }
Alexis Hunt96d5c762009-11-21 08:43:09 +00004045 }
4046
Richard Smithb7d7a042016-06-24 12:15:12 +00004047 if (CommonScopeName) {
4048 if (ScopeName) {
4049 Diag(ScopeLoc, diag::err_using_attribute_ns_conflict)
4050 << SourceRange(CommonScopeLoc);
4051 } else {
4052 ScopeName = CommonScopeName;
4053 ScopeLoc = CommonScopeLoc;
4054 }
4055 }
4056
Aaron Ballmanb8e20392014-03-31 17:32:39 +00004057 bool StandardAttr = IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName);
Alexis Hunt96d5c762009-11-21 08:43:09 +00004058 bool AttrParsed = false;
Alexis Hunt96d5c762009-11-21 08:43:09 +00004059
Richard Smith10876ef2013-01-17 01:30:42 +00004060 if (StandardAttr &&
4061 !SeenAttrs.insert(std::make_pair(AttrName, AttrLoc)).second)
4062 Diag(AttrLoc, diag::err_cxx11_attribute_repeated)
Aaron Ballmanb8e20392014-03-31 17:32:39 +00004063 << AttrName << SourceRange(SeenAttrs[AttrName]);
Richard Smith10876ef2013-01-17 01:30:42 +00004064
Michael Han23214e52012-10-03 01:56:22 +00004065 // Parse attribute arguments
Aaron Ballman35f94212014-04-14 16:03:22 +00004066 if (Tok.is(tok::l_paren))
Aaron Ballmanb8e20392014-03-31 17:32:39 +00004067 AttrParsed = ParseCXX11AttributeArgs(AttrName, AttrLoc, attrs, endLoc,
4068 ScopeName, ScopeLoc);
Michael Han23214e52012-10-03 01:56:22 +00004069
4070 if (!AttrParsed)
Aaron Ballman606093a2017-10-15 15:01:42 +00004071 attrs.addNew(
4072 AttrName,
4073 SourceRange(ScopeLoc.isValid() ? ScopeLoc : AttrLoc, AttrLoc),
4074 ScopeName, ScopeLoc, nullptr, 0,
Erich Keanee891aa92018-07-13 15:07:47 +00004075 getLangOpts().CPlusPlus ? ParsedAttr::AS_CXX11 : ParsedAttr::AS_C2x);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004076
Alp Toker97650562014-01-10 11:19:30 +00004077 if (TryConsumeToken(tok::ellipsis))
Michael Han23214e52012-10-03 01:56:22 +00004078 Diag(Tok, diag::err_cxx11_attribute_forbids_ellipsis)
Richard Trieub4025802018-03-28 04:16:13 +00004079 << AttrName;
Alexis Hunt96d5c762009-11-21 08:43:09 +00004080 }
4081
Alp Toker383d2c42014-01-01 03:08:43 +00004082 if (ExpectAndConsume(tok::r_square))
Alexey Bataevee6507d2013-11-18 08:17:37 +00004083 SkipUntil(tok::r_square);
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004084 if (endLoc)
4085 *endLoc = Tok.getLocation();
Alp Toker383d2c42014-01-01 03:08:43 +00004086 if (ExpectAndConsume(tok::r_square))
Alexey Bataevee6507d2013-11-18 08:17:37 +00004087 SkipUntil(tok::r_square);
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004088}
Alexis Hunt96d5c762009-11-21 08:43:09 +00004089
Aaron Ballman606093a2017-10-15 15:01:42 +00004090/// ParseCXX11Attributes - Parse a C++11 or C2x attribute-specifier-seq.
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004091///
4092/// attribute-specifier-seq:
4093/// attribute-specifier-seq[opt] attribute-specifier
Richard Smith3dff2512012-04-10 03:25:07 +00004094void Parser::ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004095 SourceLocation *endLoc) {
Aaron Ballman606093a2017-10-15 15:01:42 +00004096 assert(standardAttributesAllowed());
Richard Smith4cabd042013-02-22 09:15:49 +00004097
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004098 SourceLocation StartLoc = Tok.getLocation(), Loc;
4099 if (!endLoc)
4100 endLoc = &Loc;
4101
Douglas Gregor6f981002011-10-07 20:35:25 +00004102 do {
Richard Smith3dff2512012-04-10 03:25:07 +00004103 ParseCXX11AttributeSpecifier(attrs, endLoc);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004104 } while (isCXX11AttributeSpecifier());
Peter Collingbourne49eedec2011-09-29 18:04:05 +00004105
4106 attrs.Range = SourceRange(StartLoc, *endLoc);
Alexis Hunt96d5c762009-11-21 08:43:09 +00004107}
4108
Richard Smithc2c8bb82013-10-15 01:34:54 +00004109void Parser::DiagnoseAndSkipCXX11Attributes() {
Richard Smithc2c8bb82013-10-15 01:34:54 +00004110 // Start and end location of an attribute or an attribute list.
4111 SourceLocation StartLoc = Tok.getLocation();
Richard Smith955bf012014-06-19 11:42:00 +00004112 SourceLocation EndLoc = SkipCXX11Attributes();
4113
4114 if (EndLoc.isValid()) {
4115 SourceRange Range(StartLoc, EndLoc);
4116 Diag(StartLoc, diag::err_attributes_not_allowed)
4117 << Range;
4118 }
4119}
4120
4121SourceLocation Parser::SkipCXX11Attributes() {
Richard Smithc2c8bb82013-10-15 01:34:54 +00004122 SourceLocation EndLoc;
4123
Richard Smith955bf012014-06-19 11:42:00 +00004124 if (!isCXX11AttributeSpecifier())
4125 return EndLoc;
4126
Richard Smithc2c8bb82013-10-15 01:34:54 +00004127 do {
4128 if (Tok.is(tok::l_square)) {
4129 BalancedDelimiterTracker T(*this, tok::l_square);
4130 T.consumeOpen();
4131 T.skipToEnd();
4132 EndLoc = T.getCloseLocation();
4133 } else {
4134 assert(Tok.is(tok::kw_alignas) && "not an attribute specifier");
4135 ConsumeToken();
4136 BalancedDelimiterTracker T(*this, tok::l_paren);
4137 if (!T.consumeOpen())
4138 T.skipToEnd();
4139 EndLoc = T.getCloseLocation();
4140 }
4141 } while (isCXX11AttributeSpecifier());
4142
Richard Smith955bf012014-06-19 11:42:00 +00004143 return EndLoc;
Richard Smithc2c8bb82013-10-15 01:34:54 +00004144}
4145
Nico Weber05e1dad2016-09-03 03:25:22 +00004146/// Parse uuid() attribute when it appears in a [] Microsoft attribute.
4147void Parser::ParseMicrosoftUuidAttributeArgs(ParsedAttributes &Attrs) {
4148 assert(Tok.is(tok::identifier) && "Not a Microsoft attribute list");
4149 IdentifierInfo *UuidIdent = Tok.getIdentifierInfo();
4150 assert(UuidIdent->getName() == "uuid" && "Not a Microsoft attribute list");
4151
4152 SourceLocation UuidLoc = Tok.getLocation();
4153 ConsumeToken();
4154
4155 // Ignore the left paren location for now.
4156 BalancedDelimiterTracker T(*this, tok::l_paren);
4157 if (T.consumeOpen()) {
4158 Diag(Tok, diag::err_expected) << tok::l_paren;
4159 return;
4160 }
4161
4162 ArgsVector ArgExprs;
4163 if (Tok.is(tok::string_literal)) {
4164 // Easy case: uuid("...") -- quoted string.
4165 ExprResult StringResult = ParseStringLiteralExpression();
4166 if (StringResult.isInvalid())
4167 return;
4168 ArgExprs.push_back(StringResult.get());
4169 } else {
4170 // something like uuid({000000A0-0000-0000-C000-000000000049}) -- no
4171 // quotes in the parens. Just append the spelling of all tokens encountered
4172 // until the closing paren.
4173
4174 SmallString<42> StrBuffer; // 2 "", 36 bytes UUID, 2 optional {}, 1 nul
4175 StrBuffer += "\"";
4176
4177 // Since none of C++'s keywords match [a-f]+, accepting just tok::l_brace,
4178 // tok::r_brace, tok::minus, tok::identifier (think C000) and
4179 // tok::numeric_constant (0000) should be enough. But the spelling of the
4180 // uuid argument is checked later anyways, so there's no harm in accepting
4181 // almost anything here.
4182 // cl is very strict about whitespace in this form and errors out if any
4183 // is present, so check the space flags on the tokens.
4184 SourceLocation StartLoc = Tok.getLocation();
4185 while (Tok.isNot(tok::r_paren)) {
4186 if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
4187 Diag(Tok, diag::err_attribute_uuid_malformed_guid);
4188 SkipUntil(tok::r_paren, StopAtSemi);
4189 return;
4190 }
4191 SmallString<16> SpellingBuffer;
4192 SpellingBuffer.resize(Tok.getLength() + 1);
4193 bool Invalid = false;
4194 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
4195 if (Invalid) {
4196 SkipUntil(tok::r_paren, StopAtSemi);
4197 return;
4198 }
4199 StrBuffer += TokSpelling;
4200 ConsumeAnyToken();
4201 }
4202 StrBuffer += "\"";
4203
4204 if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
4205 Diag(Tok, diag::err_attribute_uuid_malformed_guid);
4206 ConsumeParen();
4207 return;
4208 }
4209
4210 // Pretend the user wrote the appropriate string literal here.
4211 // ActOnStringLiteral() copies the string data into the literal, so it's
4212 // ok that the Token points to StrBuffer.
4213 Token Toks[1];
4214 Toks[0].startToken();
4215 Toks[0].setKind(tok::string_literal);
4216 Toks[0].setLocation(StartLoc);
4217 Toks[0].setLiteralData(StrBuffer.data());
4218 Toks[0].setLength(StrBuffer.size());
4219 StringLiteral *UuidString =
4220 cast<StringLiteral>(Actions.ActOnStringLiteral(Toks, nullptr).get());
4221 ArgExprs.push_back(UuidString);
4222 }
4223
4224 if (!T.consumeClose()) {
Nico Weber05e1dad2016-09-03 03:25:22 +00004225 Attrs.addNew(UuidIdent, SourceRange(UuidLoc, T.getCloseLocation()), nullptr,
4226 SourceLocation(), ArgExprs.data(), ArgExprs.size(),
Erich Keanee891aa92018-07-13 15:07:47 +00004227 ParsedAttr::AS_Microsoft);
Nico Weber05e1dad2016-09-03 03:25:22 +00004228 }
4229}
4230
David Majnemere4752e752015-07-08 05:55:00 +00004231/// ParseMicrosoftAttributes - Parse Microsoft attributes [Attr]
Francois Pichetc2bc5ac2010-10-11 12:59:39 +00004232///
4233/// [MS] ms-attribute:
4234/// '[' token-seq ']'
4235///
4236/// [MS] ms-attribute-seq:
4237/// ms-attribute[opt]
4238/// ms-attribute ms-attribute-seq
John McCall53fa7142010-12-24 02:08:15 +00004239void Parser::ParseMicrosoftAttributes(ParsedAttributes &attrs,
4240 SourceLocation *endLoc) {
Francois Pichetc2bc5ac2010-10-11 12:59:39 +00004241 assert(Tok.is(tok::l_square) && "Not a Microsoft attribute list");
4242
Saleem Abdulrasool425efcf2015-06-15 20:57:04 +00004243 do {
Richard Smith7bdcc4a2012-04-10 01:32:12 +00004244 // FIXME: If this is actually a C++11 attribute, parse it as one.
Saleem Abdulrasool425efcf2015-06-15 20:57:04 +00004245 BalancedDelimiterTracker T(*this, tok::l_square);
4246 T.consumeOpen();
Nico Weber05e1dad2016-09-03 03:25:22 +00004247
4248 // Skip most ms attributes except for a whitelist.
4249 while (true) {
4250 SkipUntil(tok::r_square, tok::identifier, StopAtSemi | StopBeforeMatch);
4251 if (Tok.isNot(tok::identifier)) // ']', but also eof
4252 break;
4253 if (Tok.getIdentifierInfo()->getName() == "uuid")
4254 ParseMicrosoftUuidAttributeArgs(attrs);
4255 else
4256 ConsumeToken();
4257 }
4258
Saleem Abdulrasool425efcf2015-06-15 20:57:04 +00004259 T.consumeClose();
4260 if (endLoc)
4261 *endLoc = T.getCloseLocation();
4262 } while (Tok.is(tok::l_square));
Francois Pichetc2bc5ac2010-10-11 12:59:39 +00004263}
Francois Pichet8f981d52011-05-25 10:19:49 +00004264
Erich Keanec480f302018-07-12 21:09:05 +00004265void Parser::ParseMicrosoftIfExistsClassDeclaration(
4266 DeclSpec::TST TagType, ParsedAttributes &AccessAttrs,
4267 AccessSpecifier &CurAS) {
Douglas Gregor43edb322011-10-24 22:31:10 +00004268 IfExistsCondition Result;
Francois Pichet8f981d52011-05-25 10:19:49 +00004269 if (ParseMicrosoftIfExistsCondition(Result))
4270 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00004271
Douglas Gregor43edb322011-10-24 22:31:10 +00004272 BalancedDelimiterTracker Braces(*this, tok::l_brace);
4273 if (Braces.consumeOpen()) {
Alp Tokerec543272013-12-24 09:48:30 +00004274 Diag(Tok, diag::err_expected) << tok::l_brace;
Francois Pichet8f981d52011-05-25 10:19:49 +00004275 return;
4276 }
Francois Pichet8f981d52011-05-25 10:19:49 +00004277
Douglas Gregor43edb322011-10-24 22:31:10 +00004278 switch (Result.Behavior) {
4279 case IEB_Parse:
4280 // Parse the declarations below.
4281 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00004282
Douglas Gregor43edb322011-10-24 22:31:10 +00004283 case IEB_Dependent:
4284 Diag(Result.KeywordLoc, diag::warn_microsoft_dependent_exists)
4285 << Result.IsIfExists;
4286 // Fall through to skip.
Galina Kistanovad819d5b2017-06-01 21:19:06 +00004287 LLVM_FALLTHROUGH;
Fangrui Song6907ce22018-07-30 19:24:48 +00004288
Douglas Gregor43edb322011-10-24 22:31:10 +00004289 case IEB_Skip:
4290 Braces.skipToEnd();
Francois Pichet8f981d52011-05-25 10:19:49 +00004291 return;
4292 }
4293
Richard Smith34f30512013-11-23 04:06:09 +00004294 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
Francois Pichet8f981d52011-05-25 10:19:49 +00004295 // __if_exists, __if_not_exists can nest.
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00004296 if (Tok.isOneOf(tok::kw___if_exists, tok::kw___if_not_exists)) {
Erich Keanec480f302018-07-12 21:09:05 +00004297 ParseMicrosoftIfExistsClassDeclaration((DeclSpec::TST)TagType,
4298 AccessAttrs, CurAS);
Francois Pichet8f981d52011-05-25 10:19:49 +00004299 continue;
4300 }
4301
4302 // Check for extraneous top-level semicolon.
4303 if (Tok.is(tok::semi)) {
Richard Smith87f5dc52012-07-23 05:45:25 +00004304 ConsumeExtraSemi(InsideStruct, TagType);
Francois Pichet8f981d52011-05-25 10:19:49 +00004305 continue;
4306 }
4307
4308 AccessSpecifier AS = getAccessSpecifierIfPresent();
4309 if (AS != AS_none) {
4310 // Current token is a C++ access specifier.
4311 CurAS = AS;
4312 SourceLocation ASLoc = Tok.getLocation();
4313 ConsumeToken();
4314 if (Tok.is(tok::colon))
Erich Keanec480f302018-07-12 21:09:05 +00004315 Actions.ActOnAccessSpecifier(AS, ASLoc, Tok.getLocation(),
4316 ParsedAttributesView{});
Francois Pichet8f981d52011-05-25 10:19:49 +00004317 else
Alp Toker35d87032013-12-30 23:29:50 +00004318 Diag(Tok, diag::err_expected) << tok::colon;
Francois Pichet8f981d52011-05-25 10:19:49 +00004319 ConsumeToken();
4320 continue;
4321 }
4322
4323 // Parse all the comma separated declarators.
Erich Keanec480f302018-07-12 21:09:05 +00004324 ParseCXXClassMemberDeclaration(CurAS, AccessAttrs);
Francois Pichet8f981d52011-05-25 10:19:49 +00004325 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004326
Douglas Gregor43edb322011-10-24 22:31:10 +00004327 Braces.consumeClose();
Francois Pichet8f981d52011-05-25 10:19:49 +00004328}