blob: 07e32b7e42c4ba3e3e84bd3e4ac12ee062bfe615 [file] [log] [blame]
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00001//===--- ParseCXXInlineMethods.cpp - C++ class inline methods parsing------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements parsing for C++ class inline methods.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Parse/Parser.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "RAIIObjectsForParser.h"
16#include "clang/AST/DeclTemplate.h"
17#include "clang/Parse/ParseDiagnostic.h"
John McCall8b0666c2010-08-20 18:27:03 +000018#include "clang/Sema/DeclSpec.h"
19#include "clang/Sema/Scope.h"
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +000020using namespace clang;
21
Sebastian Redla7b98a72009-04-26 20:35:05 +000022/// ParseCXXInlineMethodDef - We parsed and verified that the specified
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +000023/// Declarator is a well formed C++ inline method definition. Now lex its body
24/// and store its tokens for parsing after the C++ class is complete.
Rafael Espindolac2453dd2013-01-08 21:00:12 +000025NamedDecl *Parser::ParseCXXInlineMethodDef(AccessSpecifier AS,
Erik Verbruggenca98f2a2011-10-13 09:41:32 +000026 AttributeList *AccessAttrs,
27 ParsingDeclarator &D,
Douglas Gregor5d1b4e32011-11-07 20:56:01 +000028 const ParsedTemplateInfo &TemplateInfo,
Eli Bendersky41842222015-03-23 23:49:41 +000029 const VirtSpecifiers& VS,
Richard Smith9ba0fec2015-06-30 01:28:56 +000030 SourceLocation PureSpecLoc) {
Abramo Bagnara924a8f32010-12-10 16:29:40 +000031 assert(D.isFunctionDeclarator() && "This isn't a function declarator!");
Daniel Marjamakie59f8d72015-06-18 10:59:26 +000032 assert(Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try, tok::equal) &&
Alexis Hunt5a7fa252011-05-12 06:15:49 +000033 "Current token not a '{', ':', '=', or 'try'!");
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +000034
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000035 MultiTemplateParamsArg TemplateParams(
Craig Topper161e4db2014-05-21 06:02:52 +000036 TemplateInfo.TemplateParams ? TemplateInfo.TemplateParams->data()
37 : nullptr,
Nico Weber77c76c52014-05-10 17:43:15 +000038 TemplateInfo.TemplateParams ? TemplateInfo.TemplateParams->size() : 0);
Alexis Hunt1deb9722010-04-14 23:07:37 +000039
Rafael Espindolac2453dd2013-01-08 21:00:12 +000040 NamedDecl *FnD;
John McCall07e91c02009-08-06 02:15:43 +000041 if (D.getDeclSpec().isFriendSpecified())
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000042 FnD = Actions.ActOnFriendFunctionDecl(getCurScope(), D,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000043 TemplateParams);
Douglas Gregor728d00b2011-10-10 14:49:18 +000044 else {
Douglas Gregor0be31a22010-07-02 17:43:08 +000045 FnD = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS, D,
Craig Topper161e4db2014-05-21 06:02:52 +000046 TemplateParams, nullptr,
Richard Smith2b013182012-06-10 03:12:00 +000047 VS, ICIS_NoInit);
Douglas Gregor728d00b2011-10-10 14:49:18 +000048 if (FnD) {
Richard Smithf8a75c32013-08-29 00:47:48 +000049 Actions.ProcessDeclAttributeList(getCurScope(), FnD, AccessAttrs);
Richard Smith9ba0fec2015-06-30 01:28:56 +000050 if (PureSpecLoc.isValid())
51 Actions.ActOnPureSpecifier(FnD, PureSpecLoc);
Douglas Gregor728d00b2011-10-10 14:49:18 +000052 }
Nico Weber24b2a822011-01-28 06:07:34 +000053 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +000054
Reid Klecknerbde5ede2016-02-19 01:15:08 +000055 if (FnD)
56 HandleMemberFunctionDeclDelays(D, FnD);
Eli Friedman3af2a772009-07-22 21:45:50 +000057
John McCallc1465822011-02-14 07:13:47 +000058 D.complete(FnD);
59
Alp Tokera3ebe6e2013-12-17 14:12:37 +000060 if (TryConsumeToken(tok::equal)) {
Richard Smith1c704732011-11-10 09:08:44 +000061 if (!FnD) {
62 SkipUntil(tok::semi);
Craig Topper161e4db2014-05-21 06:02:52 +000063 return nullptr;
Richard Smith1c704732011-11-10 09:08:44 +000064 }
65
Alexis Hunt5a7fa252011-05-12 06:15:49 +000066 bool Delete = false;
67 SourceLocation KWLoc;
Eli Bendersky5f4d76e2015-03-23 21:43:28 +000068 SourceLocation KWEndLoc = Tok.getEndLoc().getLocWithOffset(-1);
Alp Tokera3ebe6e2013-12-17 14:12:37 +000069 if (TryConsumeToken(tok::kw_delete, KWLoc)) {
70 Diag(KWLoc, getLangOpts().CPlusPlus11
Craig Topper54a6a682015-11-14 18:16:08 +000071 ? diag::warn_cxx98_compat_defaulted_deleted_function
72 : diag::ext_defaulted_deleted_function)
73 << 1 /* deleted */;
Alexis Hunt5a7fa252011-05-12 06:15:49 +000074 Actions.SetDeclDeleted(FnD, KWLoc);
75 Delete = true;
Eli Bendersky5f4d76e2015-03-23 21:43:28 +000076 if (auto *DeclAsFunction = dyn_cast<FunctionDecl>(FnD)) {
77 DeclAsFunction->setRangeEnd(KWEndLoc);
78 }
Alp Tokera3ebe6e2013-12-17 14:12:37 +000079 } else if (TryConsumeToken(tok::kw_default, KWLoc)) {
80 Diag(KWLoc, getLangOpts().CPlusPlus11
Craig Topper54a6a682015-11-14 18:16:08 +000081 ? diag::warn_cxx98_compat_defaulted_deleted_function
82 : diag::ext_defaulted_deleted_function)
83 << 0 /* defaulted */;
Alexis Hunt5a7fa252011-05-12 06:15:49 +000084 Actions.SetDeclDefaulted(FnD, KWLoc);
Eli Bendersky5f4d76e2015-03-23 21:43:28 +000085 if (auto *DeclAsFunction = dyn_cast<FunctionDecl>(FnD)) {
86 DeclAsFunction->setRangeEnd(KWEndLoc);
87 }
Alexis Hunt5a7fa252011-05-12 06:15:49 +000088 } else {
89 llvm_unreachable("function definition after = not 'delete' or 'default'");
90 }
91
92 if (Tok.is(tok::comma)) {
93 Diag(KWLoc, diag::err_default_delete_in_multiple_declaration)
94 << Delete;
95 SkipUntil(tok::semi);
Alp Toker383d2c42014-01-01 03:08:43 +000096 } else if (ExpectAndConsume(tok::semi, diag::err_expected_after,
97 Delete ? "delete" : "default")) {
98 SkipUntil(tok::semi);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000099 }
100
101 return FnD;
102 }
Eli Bendersky41842222015-03-23 23:49:41 +0000103
Francois Pichet1c229c02011-04-22 22:18:13 +0000104 // In delayed template parsing mode, if we are within a class template
105 // or if we are about to parse function member template then consume
106 // the tokens and store them for parsing at the end of the translation unit.
David Majnemer90b17292013-09-14 05:46:42 +0000107 if (getLangOpts().DelayedTemplateParsing &&
Eli Bendersky41842222015-03-23 23:49:41 +0000108 D.getFunctionDefinitionKind() == FDK_Definition &&
Alp Tokera2794f92014-01-22 07:29:52 +0000109 !D.getDeclSpec().isConstexprSpecified() &&
110 !(FnD && FnD->getAsFunction() &&
Alp Toker314cc812014-01-25 16:55:45 +0000111 FnD->getAsFunction()->getReturnType()->getContainedAutoType()) &&
Francois Pichet1c229c02011-04-22 22:18:13 +0000112 ((Actions.CurContext->isDependentContext() ||
David Majnemer90b17292013-09-14 05:46:42 +0000113 (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
114 TemplateInfo.Kind != ParsedTemplateInfo::ExplicitSpecialization)) &&
115 !Actions.IsInsideALocalClassWithinATemplateFunction())) {
Francois Pichet1c229c02011-04-22 22:18:13 +0000116
Richard Smithe40f2ba2013-08-07 21:41:30 +0000117 CachedTokens Toks;
118 LexTemplateFunctionForLateParsing(Toks);
Francois Pichet1c229c02011-04-22 22:18:13 +0000119
Richard Smithe40f2ba2013-08-07 21:41:30 +0000120 if (FnD) {
Alp Tokera2794f92014-01-22 07:29:52 +0000121 FunctionDecl *FD = FnD->getAsFunction();
Chandler Carruthbc0f9ae2011-04-25 07:09:43 +0000122 Actions.CheckForFunctionRedefinition(FD);
Richard Smithe40f2ba2013-08-07 21:41:30 +0000123 Actions.MarkAsLateParsedTemplate(FD, FnD, Toks);
Francois Pichet1c229c02011-04-22 22:18:13 +0000124 }
125
126 return FnD;
127 }
128
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000129 // Consume the tokens and store them for later parsing.
130
Douglas Gregorefc46952010-10-12 16:25:54 +0000131 LexedMethod* LM = new LexedMethod(this, FnD);
132 getCurrentClass().LateParsedDeclarations.push_back(LM);
133 LM->TemplateScope = getCurScope()->isTemplateParamScope();
134 CachedTokens &Toks = LM->Toks;
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000135
Sebastian Redla7b98a72009-04-26 20:35:05 +0000136 tok::TokenKind kind = Tok.getKind();
Sebastian Redl0d164012011-09-30 08:32:17 +0000137 // Consume everything up to (and including) the left brace of the
138 // function body.
139 if (ConsumeAndStoreFunctionPrologue(Toks)) {
140 // We didn't find the left-brace we expected after the
Eli Friedman7cd4a9b2012-02-22 04:49:04 +0000141 // constructor initializer; we already printed an error, and it's likely
142 // impossible to recover, so don't try to parse this method later.
Richard Smithcde3fd82013-07-04 00:13:48 +0000143 // Skip over the rest of the decl and back to somewhere that looks
144 // reasonable.
145 SkipMalformedDecl();
Eli Friedman7cd4a9b2012-02-22 04:49:04 +0000146 delete getCurrentClass().LateParsedDeclarations.back();
147 getCurrentClass().LateParsedDeclarations.pop_back();
148 return FnD;
Douglas Gregore8381c02008-11-05 04:29:56 +0000149 } else {
Sebastian Redl0d164012011-09-30 08:32:17 +0000150 // Consume everything up to (and including) the matching right brace.
151 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
Douglas Gregore8381c02008-11-05 04:29:56 +0000152 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000153
Sebastian Redla7b98a72009-04-26 20:35:05 +0000154 // If we're in a function-try-block, we need to store all the catch blocks.
155 if (kind == tok::kw_try) {
156 while (Tok.is(tok::kw_catch)) {
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000157 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
158 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
Sebastian Redla7b98a72009-04-26 20:35:05 +0000159 }
160 }
161
Stephen Lin9354fc52013-06-23 07:37:13 +0000162 if (FnD) {
163 // If this is a friend function, mark that it's late-parsed so that
164 // it's still known to be a definition even before we attach the
165 // parsed body. Sema needs to treat friend function definitions
166 // differently during template instantiation, and it's possible for
167 // the containing class to be instantiated before all its member
168 // function definitions are parsed.
169 //
170 // If you remove this, you can remove the code that clears the flag
171 // after parsing the member.
172 if (D.getDeclSpec().isFriendSpecified()) {
Alp Tokera2794f92014-01-22 07:29:52 +0000173 FunctionDecl *FD = FnD->getAsFunction();
Alp Toker19bff322013-10-18 05:54:24 +0000174 Actions.CheckForFunctionRedefinition(FD);
175 FD->setLateTemplateParsed(true);
Stephen Lin9354fc52013-06-23 07:37:13 +0000176 }
177 } else {
Douglas Gregor6ca64102011-04-14 23:19:27 +0000178 // If semantic analysis could not build a function declaration,
179 // just throw away the late-parsed declaration.
180 delete getCurrentClass().LateParsedDeclarations.back();
181 getCurrentClass().LateParsedDeclarations.pop_back();
182 }
183
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000184 return FnD;
185}
186
Richard Smith938f40b2011-06-11 17:19:42 +0000187/// ParseCXXNonStaticMemberInitializer - We parsed and verified that the
188/// specified Declarator is a well formed C++ non-static data member
189/// declaration. Now lex its initializer and store its tokens for parsing
190/// after the class is complete.
191void Parser::ParseCXXNonStaticMemberInitializer(Decl *VarD) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000192 assert(Tok.isOneOf(tok::l_brace, tok::equal) &&
Richard Smith938f40b2011-06-11 17:19:42 +0000193 "Current token not a '{' or '='!");
194
195 LateParsedMemberInitializer *MI =
196 new LateParsedMemberInitializer(this, VarD);
197 getCurrentClass().LateParsedDeclarations.push_back(MI);
198 CachedTokens &Toks = MI->Toks;
199
200 tok::TokenKind kind = Tok.getKind();
201 if (kind == tok::equal) {
202 Toks.push_back(Tok);
Douglas Gregor0cf55e92012-03-08 01:00:17 +0000203 ConsumeToken();
Richard Smith938f40b2011-06-11 17:19:42 +0000204 }
205
206 if (kind == tok::l_brace) {
207 // Begin by storing the '{' token.
208 Toks.push_back(Tok);
209 ConsumeBrace();
210
211 // Consume everything up to (and including) the matching right brace.
212 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/true);
213 } else {
214 // Consume everything up to (but excluding) the comma or semicolon.
Richard Smith1fff95c2013-09-12 23:28:08 +0000215 ConsumeAndStoreInitializer(Toks, CIK_DefaultInitializer);
Richard Smith938f40b2011-06-11 17:19:42 +0000216 }
217
218 // Store an artificial EOF token to ensure that we don't run off the end of
219 // the initializer when we come to parse it.
220 Token Eof;
221 Eof.startToken();
222 Eof.setKind(tok::eof);
223 Eof.setLocation(Tok.getLocation());
David Majnemerce1d3012014-12-19 02:13:56 +0000224 Eof.setEofData(VarD);
Richard Smith938f40b2011-06-11 17:19:42 +0000225 Toks.push_back(Eof);
226}
227
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000228Parser::LateParsedDeclaration::~LateParsedDeclaration() {}
Douglas Gregorefc46952010-10-12 16:25:54 +0000229void Parser::LateParsedDeclaration::ParseLexedMethodDeclarations() {}
Richard Smith938f40b2011-06-11 17:19:42 +0000230void Parser::LateParsedDeclaration::ParseLexedMemberInitializers() {}
Douglas Gregorefc46952010-10-12 16:25:54 +0000231void Parser::LateParsedDeclaration::ParseLexedMethodDefs() {}
232
233Parser::LateParsedClass::LateParsedClass(Parser *P, ParsingClass *C)
234 : Self(P), Class(C) {}
235
236Parser::LateParsedClass::~LateParsedClass() {
237 Self->DeallocateParsedClasses(Class);
238}
239
240void Parser::LateParsedClass::ParseLexedMethodDeclarations() {
241 Self->ParseLexedMethodDeclarations(*Class);
242}
243
Richard Smith938f40b2011-06-11 17:19:42 +0000244void Parser::LateParsedClass::ParseLexedMemberInitializers() {
245 Self->ParseLexedMemberInitializers(*Class);
246}
247
Douglas Gregorefc46952010-10-12 16:25:54 +0000248void Parser::LateParsedClass::ParseLexedMethodDefs() {
249 Self->ParseLexedMethodDefs(*Class);
250}
251
252void Parser::LateParsedMethodDeclaration::ParseLexedMethodDeclarations() {
253 Self->ParseLexedMethodDeclaration(*this);
254}
255
256void Parser::LexedMethod::ParseLexedMethodDefs() {
257 Self->ParseLexedMethodDef(*this);
258}
259
Richard Smith938f40b2011-06-11 17:19:42 +0000260void Parser::LateParsedMemberInitializer::ParseLexedMemberInitializers() {
261 Self->ParseLexedMemberInitializer(*this);
262}
263
Douglas Gregor4d87df52008-12-16 21:30:33 +0000264/// ParseLexedMethodDeclarations - We finished parsing the member
265/// specification of a top (non-nested) C++ class. Now go over the
266/// stack of method declarations with some parts for which parsing was
267/// delayed (such as default arguments) and parse them.
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000268void Parser::ParseLexedMethodDeclarations(ParsingClass &Class) {
269 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
Nico Weber77c76c52014-05-10 17:43:15 +0000270 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
271 HasTemplateScope);
Richard Smithc8378952013-04-29 11:55:38 +0000272 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
273 if (HasTemplateScope) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000274 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
Richard Smithc8378952013-04-29 11:55:38 +0000275 ++CurTemplateDepthTracker;
276 }
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000277
John McCall6df5fef2009-12-19 10:49:29 +0000278 // The current scope is still active if we're the top-level class.
279 // Otherwise we'll need to push and enter a new scope.
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000280 bool HasClassScope = !Class.TopLevelClass;
Alexis Hunt1deb9722010-04-14 23:07:37 +0000281 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope,
282 HasClassScope);
John McCall6df5fef2009-12-19 10:49:29 +0000283 if (HasClassScope)
Nico Weber77c76c52014-05-10 17:43:15 +0000284 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(),
285 Class.TagOrTemplate);
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000286
Douglas Gregorefc46952010-10-12 16:25:54 +0000287 for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
288 Class.LateParsedDeclarations[i]->ParseLexedMethodDeclarations();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000289 }
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000290
John McCall6df5fef2009-12-19 10:49:29 +0000291 if (HasClassScope)
Nico Weber77c76c52014-05-10 17:43:15 +0000292 Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(),
293 Class.TagOrTemplate);
Douglas Gregor4d87df52008-12-16 21:30:33 +0000294}
295
Douglas Gregorefc46952010-10-12 16:25:54 +0000296void Parser::ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM) {
297 // If this is a member template, introduce the template parameter scope.
298 ParseScope TemplateScope(this, Scope::TemplateParamScope, LM.TemplateScope);
Richard Smithc8378952013-04-29 11:55:38 +0000299 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
300 if (LM.TemplateScope) {
Douglas Gregorefc46952010-10-12 16:25:54 +0000301 Actions.ActOnReenterTemplateScope(getCurScope(), LM.Method);
Richard Smithc8378952013-04-29 11:55:38 +0000302 ++CurTemplateDepthTracker;
303 }
Douglas Gregorefc46952010-10-12 16:25:54 +0000304 // Start the delayed C++ method declaration
305 Actions.ActOnStartDelayedCXXMethodDeclaration(getCurScope(), LM.Method);
306
307 // Introduce the parameters into scope and parse their default
308 // arguments.
Richard Smithe233fbf2013-01-28 22:42:45 +0000309 ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
310 Scope::FunctionDeclarationScope | Scope::DeclScope);
Douglas Gregorefc46952010-10-12 16:25:54 +0000311 for (unsigned I = 0, N = LM.DefaultArgs.size(); I != N; ++I) {
Nathan Sidwell5bb231c2015-02-19 14:03:22 +0000312 auto Param = cast<ParmVarDecl>(LM.DefaultArgs[I].Param);
Douglas Gregorefc46952010-10-12 16:25:54 +0000313 // Introduce the parameter into scope.
Nathan Sidwell5bb231c2015-02-19 14:03:22 +0000314 bool HasUnparsed = Param->hasUnparsedDefaultArg();
Nathan Sidwell55d53fe2015-01-30 14:21:35 +0000315 Actions.ActOnDelayedCXXMethodParameter(getCurScope(), Param);
Douglas Gregorefc46952010-10-12 16:25:54 +0000316 if (CachedTokens *Toks = LM.DefaultArgs[I].Toks) {
David Majnemer7cceba52015-01-13 04:20:57 +0000317 // Mark the end of the default argument so that we know when to stop when
318 // we parse it later on.
319 Token LastDefaultArgToken = Toks->back();
320 Token DefArgEnd;
321 DefArgEnd.startToken();
322 DefArgEnd.setKind(tok::eof);
David Majnemera8f2f1d2015-03-19 00:10:23 +0000323 DefArgEnd.setLocation(LastDefaultArgToken.getEndLoc());
Nathan Sidwell55d53fe2015-01-30 14:21:35 +0000324 DefArgEnd.setEofData(Param);
David Majnemer7cceba52015-01-13 04:20:57 +0000325 Toks->push_back(DefArgEnd);
Douglas Gregorefc46952010-10-12 16:25:54 +0000326
327 // Parse the default argument from its saved token stream.
328 Toks->push_back(Tok); // So that the current token doesn't get lost
David Blaikie2eabcc92016-02-09 18:52:09 +0000329 PP.EnterTokenStream(*Toks, true);
Douglas Gregorefc46952010-10-12 16:25:54 +0000330
331 // Consume the previously-pushed token.
332 ConsumeAnyToken();
333
334 // Consume the '='.
335 assert(Tok.is(tok::equal) && "Default argument not starting with '='");
336 SourceLocation EqualLoc = ConsumeToken();
337
338 // The argument isn't actually potentially evaluated unless it is
339 // used.
340 EnterExpressionEvaluationContext Eval(Actions,
Douglas Gregor7fcbd902012-02-21 00:37:24 +0000341 Sema::PotentiallyEvaluatedIfUsed,
Nathan Sidwell55d53fe2015-01-30 14:21:35 +0000342 Param);
Douglas Gregorefc46952010-10-12 16:25:54 +0000343
Sebastian Redldb63af22012-03-14 15:54:00 +0000344 ExprResult DefArgResult;
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000345 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
Sebastian Redl6db0b1b2012-03-20 21:24:03 +0000346 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
Sebastian Redldb63af22012-03-14 15:54:00 +0000347 DefArgResult = ParseBraceInitializer();
Sebastian Redl6db0b1b2012-03-20 21:24:03 +0000348 } else
Sebastian Redldb63af22012-03-14 15:54:00 +0000349 DefArgResult = ParseAssignmentExpression();
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000350 DefArgResult = Actions.CorrectDelayedTyposInExpr(DefArgResult);
David Majnemerbba12342015-01-12 06:51:15 +0000351 if (DefArgResult.isInvalid()) {
Nathan Sidwell55d53fe2015-01-30 14:21:35 +0000352 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
David Majnemerbba12342015-01-12 06:51:15 +0000353 } else {
Nathan Sidwell55d53fe2015-01-30 14:21:35 +0000354 if (Tok.isNot(tok::eof) || Tok.getEofData() != Param) {
Richard Smith1fff95c2013-09-12 23:28:08 +0000355 // The last two tokens are the terminator and the saved value of
356 // Tok; the last token in the default argument is the one before
357 // those.
358 assert(Toks->size() >= 3 && "expected a token in default arg");
359 Diag(Tok.getLocation(), diag::err_default_arg_unparsed)
360 << SourceRange(Tok.getLocation(),
361 (*Toks)[Toks->size() - 3].getLocation());
362 }
Nathan Sidwell55d53fe2015-01-30 14:21:35 +0000363 Actions.ActOnParamDefaultArgument(Param, EqualLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000364 DefArgResult.get());
Douglas Gregorefc46952010-10-12 16:25:54 +0000365 }
366
Douglas Gregorefc46952010-10-12 16:25:54 +0000367 // There could be leftover tokens (e.g. because of an error).
David Majnemer7cceba52015-01-13 04:20:57 +0000368 // Skip through until we reach the 'end of default argument' token.
369 while (Tok.isNot(tok::eof))
Douglas Gregorefc46952010-10-12 16:25:54 +0000370 ConsumeAnyToken();
David Majnemer7cceba52015-01-13 04:20:57 +0000371
Nathan Sidwell55d53fe2015-01-30 14:21:35 +0000372 if (Tok.is(tok::eof) && Tok.getEofData() == Param)
David Majnemer7cceba52015-01-13 04:20:57 +0000373 ConsumeAnyToken();
Douglas Gregorefc46952010-10-12 16:25:54 +0000374
375 delete Toks;
Craig Topper161e4db2014-05-21 06:02:52 +0000376 LM.DefaultArgs[I].Toks = nullptr;
Nathan Sidwell5bb231c2015-02-19 14:03:22 +0000377 } else if (HasUnparsed) {
378 assert(Param->hasInheritedDefaultArg());
379 FunctionDecl *Old = cast<FunctionDecl>(LM.Method)->getPreviousDecl();
380 ParmVarDecl *OldParam = Old->getParamDecl(I);
381 assert (!OldParam->hasUnparsedDefaultArg());
382 if (OldParam->hasUninstantiatedDefaultArg())
383 Param->setUninstantiatedDefaultArg(
384 Param->getUninstantiatedDefaultArg());
385 else
386 Param->setDefaultArg(OldParam->getInit());
Douglas Gregorefc46952010-10-12 16:25:54 +0000387 }
388 }
Douglas Gregor433e0532012-04-16 18:27:27 +0000389
Richard Smith0b3a4622014-11-13 20:01:57 +0000390 // Parse a delayed exception-specification, if there is one.
391 if (CachedTokens *Toks = LM.ExceptionSpecTokens) {
David Majnemer7cceba52015-01-13 04:20:57 +0000392 // Add the 'stop' token.
393 Token LastExceptionSpecToken = Toks->back();
394 Token ExceptionSpecEnd;
395 ExceptionSpecEnd.startToken();
396 ExceptionSpecEnd.setKind(tok::eof);
David Majnemera8f2f1d2015-03-19 00:10:23 +0000397 ExceptionSpecEnd.setLocation(LastExceptionSpecToken.getEndLoc());
David Majnemer7cceba52015-01-13 04:20:57 +0000398 ExceptionSpecEnd.setEofData(LM.Method);
399 Toks->push_back(ExceptionSpecEnd);
Richard Smith0b3a4622014-11-13 20:01:57 +0000400
401 // Parse the default argument from its saved token stream.
402 Toks->push_back(Tok); // So that the current token doesn't get lost
David Blaikie2eabcc92016-02-09 18:52:09 +0000403 PP.EnterTokenStream(*Toks, true);
Richard Smith0b3a4622014-11-13 20:01:57 +0000404
405 // Consume the previously-pushed token.
406 ConsumeAnyToken();
407
408 // C++11 [expr.prim.general]p3:
409 // If a declaration declares a member function or member function
410 // template of a class X, the expression this is a prvalue of type
411 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
412 // and the end of the function-definition, member-declarator, or
413 // declarator.
414 CXXMethodDecl *Method;
415 if (FunctionTemplateDecl *FunTmpl
416 = dyn_cast<FunctionTemplateDecl>(LM.Method))
417 Method = cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
418 else
419 Method = cast<CXXMethodDecl>(LM.Method);
420
421 Sema::CXXThisScopeRAII ThisScope(Actions, Method->getParent(),
422 Method->getTypeQualifiers(),
423 getLangOpts().CPlusPlus11);
424
425 // Parse the exception-specification.
426 SourceRange SpecificationRange;
427 SmallVector<ParsedType, 4> DynamicExceptions;
428 SmallVector<SourceRange, 4> DynamicExceptionRanges;
429 ExprResult NoexceptExpr;
430 CachedTokens *ExceptionSpecTokens;
431
432 ExceptionSpecificationType EST
433 = tryParseExceptionSpecification(/*Delayed=*/false, SpecificationRange,
434 DynamicExceptions,
435 DynamicExceptionRanges, NoexceptExpr,
436 ExceptionSpecTokens);
437
David Majnemer7cceba52015-01-13 04:20:57 +0000438 if (Tok.isNot(tok::eof) || Tok.getEofData() != LM.Method)
Richard Smith0b3a4622014-11-13 20:01:57 +0000439 Diag(Tok.getLocation(), diag::err_except_spec_unparsed);
440
441 // Attach the exception-specification to the method.
Richard Smith3ef3e892014-11-20 22:32:11 +0000442 Actions.actOnDelayedExceptionSpecification(LM.Method, EST,
443 SpecificationRange,
444 DynamicExceptions,
445 DynamicExceptionRanges,
446 NoexceptExpr.isUsable()?
447 NoexceptExpr.get() : nullptr);
Richard Smith0b3a4622014-11-13 20:01:57 +0000448
Richard Smith0b3a4622014-11-13 20:01:57 +0000449 // There could be leftover tokens (e.g. because of an error).
450 // Skip through until we reach the original token position.
David Majnemer7cceba52015-01-13 04:20:57 +0000451 while (Tok.isNot(tok::eof))
Richard Smith0b3a4622014-11-13 20:01:57 +0000452 ConsumeAnyToken();
David Majnemer7cceba52015-01-13 04:20:57 +0000453
454 // Clean up the remaining EOF token.
455 if (Tok.is(tok::eof) && Tok.getEofData() == LM.Method)
456 ConsumeAnyToken();
Richard Smith0b3a4622014-11-13 20:01:57 +0000457
458 delete Toks;
459 LM.ExceptionSpecTokens = nullptr;
460 }
461
Douglas Gregorefc46952010-10-12 16:25:54 +0000462 PrototypeScope.Exit();
463
464 // Finish the delayed C++ method declaration.
465 Actions.ActOnFinishDelayedCXXMethodDeclaration(getCurScope(), LM.Method);
466}
467
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000468/// ParseLexedMethodDefs - We finished parsing the member specification of a top
469/// (non-nested) C++ class. Now go over the stack of lexed methods that were
470/// collected during its parsing and parse them all.
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000471void Parser::ParseLexedMethodDefs(ParsingClass &Class) {
472 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
Douglas Gregorefc46952010-10-12 16:25:54 +0000473 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope, HasTemplateScope);
Richard Smithc8378952013-04-29 11:55:38 +0000474 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
475 if (HasTemplateScope) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000476 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
Richard Smithc8378952013-04-29 11:55:38 +0000477 ++CurTemplateDepthTracker;
478 }
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000479 bool HasClassScope = !Class.TopLevelClass;
480 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope,
481 HasClassScope);
482
Douglas Gregorefc46952010-10-12 16:25:54 +0000483 for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
484 Class.LateParsedDeclarations[i]->ParseLexedMethodDefs();
485 }
486}
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000487
Douglas Gregorefc46952010-10-12 16:25:54 +0000488void Parser::ParseLexedMethodDef(LexedMethod &LM) {
489 // If this is a member template, introduce the template parameter scope.
490 ParseScope TemplateScope(this, Scope::TemplateParamScope, LM.TemplateScope);
Richard Smithc8378952013-04-29 11:55:38 +0000491 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
492 if (LM.TemplateScope) {
Douglas Gregorefc46952010-10-12 16:25:54 +0000493 Actions.ActOnReenterTemplateScope(getCurScope(), LM.D);
Richard Smithc8378952013-04-29 11:55:38 +0000494 ++CurTemplateDepthTracker;
495 }
Argyrios Kyrtzidis02041972010-03-31 00:38:09 +0000496
Douglas Gregorefc46952010-10-12 16:25:54 +0000497 assert(!LM.Toks.empty() && "Empty body!");
David Majnemera7ea1b12015-01-13 05:06:20 +0000498 Token LastBodyToken = LM.Toks.back();
499 Token BodyEnd;
500 BodyEnd.startToken();
501 BodyEnd.setKind(tok::eof);
David Majnemera8f2f1d2015-03-19 00:10:23 +0000502 BodyEnd.setLocation(LastBodyToken.getEndLoc());
David Majnemera7ea1b12015-01-13 05:06:20 +0000503 BodyEnd.setEofData(LM.D);
504 LM.Toks.push_back(BodyEnd);
Douglas Gregorefc46952010-10-12 16:25:54 +0000505 // Append the current token at the end of the new token stream so that it
506 // doesn't get lost.
507 LM.Toks.push_back(Tok);
David Blaikie2eabcc92016-02-09 18:52:09 +0000508 PP.EnterTokenStream(LM.Toks, true);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000509
Douglas Gregorefc46952010-10-12 16:25:54 +0000510 // Consume the previously pushed token.
Argyrios Kyrtzidisc36633c2013-03-27 23:58:17 +0000511 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000512 assert(Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try)
Douglas Gregorefc46952010-10-12 16:25:54 +0000513 && "Inline method not starting with '{', ':' or 'try'");
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000514
Douglas Gregorefc46952010-10-12 16:25:54 +0000515 // Parse the method body. Function body parsing code is similar enough
516 // to be re-used for method bodies as well.
517 ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope);
518 Actions.ActOnStartOfFunctionDef(getCurScope(), LM.D);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000519
Douglas Gregorefc46952010-10-12 16:25:54 +0000520 if (Tok.is(tok::kw_try)) {
Douglas Gregora0ff0c32011-03-16 17:05:57 +0000521 ParseFunctionTryBlock(LM.D, FnScope);
David Majnemera7ea1b12015-01-13 05:06:20 +0000522
523 while (Tok.isNot(tok::eof))
524 ConsumeAnyToken();
525
526 if (Tok.is(tok::eof) && Tok.getEofData() == LM.D)
Douglas Gregorefc46952010-10-12 16:25:54 +0000527 ConsumeAnyToken();
528 return;
529 }
530 if (Tok.is(tok::colon)) {
531 ParseConstructorInitializer(LM.D);
532
533 // Error recovery.
534 if (!Tok.is(tok::l_brace)) {
Douglas Gregora0ff0c32011-03-16 17:05:57 +0000535 FnScope.Exit();
Craig Topper161e4db2014-05-21 06:02:52 +0000536 Actions.ActOnFinishFunctionBody(LM.D, nullptr);
David Majnemera7ea1b12015-01-13 05:06:20 +0000537
538 while (Tok.isNot(tok::eof))
539 ConsumeAnyToken();
540
541 if (Tok.is(tok::eof) && Tok.getEofData() == LM.D)
Matt Beaumont-Gayd0457922011-09-23 22:39:23 +0000542 ConsumeAnyToken();
Douglas Gregorefc46952010-10-12 16:25:54 +0000543 return;
544 }
545 } else
546 Actions.ActOnDefaultCtorInitializers(LM.D);
547
Richard Smithc8378952013-04-29 11:55:38 +0000548 assert((Actions.getDiagnostics().hasErrorOccurred() ||
549 !isa<FunctionTemplateDecl>(LM.D) ||
550 cast<FunctionTemplateDecl>(LM.D)->getTemplateParameters()->getDepth()
551 < TemplateParameterDepth) &&
552 "TemplateParameterDepth should be greater than the depth of "
553 "current template being instantiated!");
554
Douglas Gregora0ff0c32011-03-16 17:05:57 +0000555 ParseFunctionStatementBody(LM.D, FnScope);
Douglas Gregorefc46952010-10-12 16:25:54 +0000556
John McCalle68672f2013-03-14 05:13:41 +0000557 // Clear the late-template-parsed bit if we set it before.
Alp Tokera2794f92014-01-22 07:29:52 +0000558 if (LM.D)
559 LM.D->getAsFunction()->setLateTemplateParsed(false);
John McCalle68672f2013-03-14 05:13:41 +0000560
David Majnemera7ea1b12015-01-13 05:06:20 +0000561 while (Tok.isNot(tok::eof))
562 ConsumeAnyToken();
563
564 if (Tok.is(tok::eof) && Tok.getEofData() == LM.D)
565 ConsumeAnyToken();
Hans Wennborga926d842014-05-23 20:37:38 +0000566
567 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(LM.D))
568 Actions.ActOnFinishInlineMethodDef(MD);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000569}
570
Richard Smith938f40b2011-06-11 17:19:42 +0000571/// ParseLexedMemberInitializers - We finished parsing the member specification
572/// of a top (non-nested) C++ class. Now go over the stack of lexed data member
573/// initializers that were collected during its parsing and parse them all.
574void Parser::ParseLexedMemberInitializers(ParsingClass &Class) {
575 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
576 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
577 HasTemplateScope);
Richard Smithc8378952013-04-29 11:55:38 +0000578 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
579 if (HasTemplateScope) {
Richard Smith938f40b2011-06-11 17:19:42 +0000580 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
Richard Smithc8378952013-04-29 11:55:38 +0000581 ++CurTemplateDepthTracker;
582 }
Douglas Gregor3024f072012-04-16 07:05:22 +0000583 // Set or update the scope flags.
Richard Smith938f40b2011-06-11 17:19:42 +0000584 bool AlreadyHasClassScope = Class.TopLevelClass;
Douglas Gregor3024f072012-04-16 07:05:22 +0000585 unsigned ScopeFlags = Scope::ClassScope|Scope::DeclScope;
Richard Smith938f40b2011-06-11 17:19:42 +0000586 ParseScope ClassScope(this, ScopeFlags, !AlreadyHasClassScope);
587 ParseScopeFlags ClassScopeFlags(this, ScopeFlags, AlreadyHasClassScope);
588
589 if (!AlreadyHasClassScope)
590 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(),
591 Class.TagOrTemplate);
592
Benjamin Kramer1d373c62012-05-17 12:01:52 +0000593 if (!Class.LateParsedDeclarations.empty()) {
Douglas Gregor3024f072012-04-16 07:05:22 +0000594 // C++11 [expr.prim.general]p4:
595 // Otherwise, if a member-declarator declares a non-static data member
596 // (9.2) of a class X, the expression this is a prvalue of type "pointer
597 // to X" within the optional brace-or-equal-initializer. It shall not
598 // appear elsewhere in the member-declarator.
599 Sema::CXXThisScopeRAII ThisScope(Actions, Class.TagOrTemplate,
600 /*TypeQuals=*/(unsigned)0);
Richard Smith938f40b2011-06-11 17:19:42 +0000601
Douglas Gregor3024f072012-04-16 07:05:22 +0000602 for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
603 Class.LateParsedDeclarations[i]->ParseLexedMemberInitializers();
604 }
605 }
606
Richard Smith938f40b2011-06-11 17:19:42 +0000607 if (!AlreadyHasClassScope)
608 Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(),
609 Class.TagOrTemplate);
610
611 Actions.ActOnFinishDelayedMemberInitializers(Class.TagOrTemplate);
612}
613
614void Parser::ParseLexedMemberInitializer(LateParsedMemberInitializer &MI) {
Richard Smith1a526fd2011-09-29 19:42:27 +0000615 if (!MI.Field || MI.Field->isInvalidDecl())
Richard Smith938f40b2011-06-11 17:19:42 +0000616 return;
617
618 // Append the current token at the end of the new token stream so that it
619 // doesn't get lost.
620 MI.Toks.push_back(Tok);
David Blaikie2eabcc92016-02-09 18:52:09 +0000621 PP.EnterTokenStream(MI.Toks, true);
Richard Smith938f40b2011-06-11 17:19:42 +0000622
623 // Consume the previously pushed token.
Argyrios Kyrtzidisc36633c2013-03-27 23:58:17 +0000624 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
Richard Smith938f40b2011-06-11 17:19:42 +0000625
626 SourceLocation EqualLoc;
Richard Smith2b013182012-06-10 03:12:00 +0000627
Richard Smith74108172014-01-17 03:11:34 +0000628 Actions.ActOnStartCXXInClassMemberInitializer();
629
Douglas Gregor926410d2012-02-21 02:22:07 +0000630 ExprResult Init = ParseCXXMemberInitializer(MI.Field, /*IsFunction=*/false,
631 EqualLoc);
Richard Smith938f40b2011-06-11 17:19:42 +0000632
Richard Smith74108172014-01-17 03:11:34 +0000633 Actions.ActOnFinishCXXInClassMemberInitializer(MI.Field, EqualLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000634 Init.get());
Richard Smith938f40b2011-06-11 17:19:42 +0000635
636 // The next token should be our artificial terminating EOF token.
637 if (Tok.isNot(tok::eof)) {
Richard Smith95e1fb02014-08-27 03:23:12 +0000638 if (!Init.isInvalid()) {
639 SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
640 if (!EndLoc.isValid())
641 EndLoc = Tok.getLocation();
642 // No fixit; we can't recover as if there were a semicolon here.
643 Diag(EndLoc, diag::err_expected_semi_decl_list);
644 }
Richard Smith938f40b2011-06-11 17:19:42 +0000645
646 // Consume tokens until we hit the artificial EOF.
647 while (Tok.isNot(tok::eof))
648 ConsumeAnyToken();
649 }
David Majnemer2d3663e2014-12-18 09:57:31 +0000650 // Make sure this is *our* artificial EOF token.
David Majnemerce1d3012014-12-19 02:13:56 +0000651 if (Tok.getEofData() == MI.Field)
David Majnemer2d3663e2014-12-18 09:57:31 +0000652 ConsumeAnyToken();
Richard Smith938f40b2011-06-11 17:19:42 +0000653}
654
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000655/// ConsumeAndStoreUntil - Consume and store the token at the passed token
Douglas Gregor4d87df52008-12-16 21:30:33 +0000656/// container until the token 'T' is reached (which gets
Mike Stump11289f42009-09-09 15:08:12 +0000657/// consumed/stored too, if ConsumeFinalToken).
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000658/// If StopAtSemi is true, then we will stop early at a ';' character.
Douglas Gregor4d87df52008-12-16 21:30:33 +0000659/// Returns true if token 'T1' or 'T2' was found.
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000660/// NOTE: This is a specialized version of Parser::SkipUntil.
Douglas Gregor4d87df52008-12-16 21:30:33 +0000661bool Parser::ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
662 CachedTokens &Toks,
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000663 bool StopAtSemi, bool ConsumeFinalToken) {
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000664 // We always want this function to consume at least one token if the first
665 // token isn't T and if not at EOF.
666 bool isFirstTokenConsumed = true;
667 while (1) {
668 // If we found one of the tokens, stop and return true.
Douglas Gregor4d87df52008-12-16 21:30:33 +0000669 if (Tok.is(T1) || Tok.is(T2)) {
670 if (ConsumeFinalToken) {
671 Toks.push_back(Tok);
672 ConsumeAnyToken();
673 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000674 return true;
675 }
676
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000677 switch (Tok.getKind()) {
678 case tok::eof:
Richard Smith34f30512013-11-23 04:06:09 +0000679 case tok::annot_module_begin:
680 case tok::annot_module_end:
681 case tok::annot_module_include:
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000682 // Ran out of tokens.
683 return false;
684
685 case tok::l_paren:
686 // Recursively consume properly-nested parens.
687 Toks.push_back(Tok);
688 ConsumeParen();
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000689 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000690 break;
691 case tok::l_square:
692 // Recursively consume properly-nested square brackets.
693 Toks.push_back(Tok);
694 ConsumeBracket();
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000695 ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000696 break;
697 case tok::l_brace:
698 // Recursively consume properly-nested braces.
699 Toks.push_back(Tok);
700 ConsumeBrace();
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000701 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000702 break;
703
704 // Okay, we found a ']' or '}' or ')', which we think should be balanced.
705 // Since the user wasn't looking for this token (if they were, it would
706 // already be handled), this isn't balanced. If there is a LHS token at a
707 // higher level, we will assume that this matches the unbalanced token
708 // and return it. Otherwise, this is a spurious RHS token, which we skip.
709 case tok::r_paren:
710 if (ParenCount && !isFirstTokenConsumed)
711 return false; // Matches something.
712 Toks.push_back(Tok);
713 ConsumeParen();
714 break;
715 case tok::r_square:
716 if (BracketCount && !isFirstTokenConsumed)
717 return false; // Matches something.
718 Toks.push_back(Tok);
719 ConsumeBracket();
720 break;
721 case tok::r_brace:
722 if (BraceCount && !isFirstTokenConsumed)
723 return false; // Matches something.
724 Toks.push_back(Tok);
725 ConsumeBrace();
726 break;
727
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000728 case tok::code_completion:
729 Toks.push_back(Tok);
730 ConsumeCodeCompletionToken();
731 break;
732
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000733 case tok::string_literal:
734 case tok::wide_string_literal:
Douglas Gregorfb65e592011-07-27 05:40:30 +0000735 case tok::utf8_string_literal:
736 case tok::utf16_string_literal:
737 case tok::utf32_string_literal:
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000738 Toks.push_back(Tok);
739 ConsumeStringToken();
740 break;
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000741 case tok::semi:
742 if (StopAtSemi)
743 return false;
744 // FALL THROUGH.
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000745 default:
746 // consume this token.
747 Toks.push_back(Tok);
748 ConsumeToken();
749 break;
750 }
751 isFirstTokenConsumed = false;
752 }
753}
Sebastian Redla74948d2011-09-24 17:48:25 +0000754
755/// \brief Consume tokens and store them in the passed token container until
756/// we've passed the try keyword and constructor initializers and have consumed
Sebastian Redl0d164012011-09-30 08:32:17 +0000757/// the opening brace of the function body. The opening brace will be consumed
758/// if and only if there was no error.
Sebastian Redla74948d2011-09-24 17:48:25 +0000759///
Richard Smithcde3fd82013-07-04 00:13:48 +0000760/// \return True on error.
Sebastian Redl0d164012011-09-30 08:32:17 +0000761bool Parser::ConsumeAndStoreFunctionPrologue(CachedTokens &Toks) {
Sebastian Redla74948d2011-09-24 17:48:25 +0000762 if (Tok.is(tok::kw_try)) {
763 Toks.push_back(Tok);
764 ConsumeToken();
765 }
Richard Smithcde3fd82013-07-04 00:13:48 +0000766
767 if (Tok.isNot(tok::colon)) {
768 // Easy case, just a function body.
769
770 // Grab any remaining garbage to be diagnosed later. We stop when we reach a
771 // brace: an opening one is the function body, while a closing one probably
772 // means we've reached the end of the class.
773 ConsumeAndStoreUntil(tok::l_brace, tok::r_brace, Toks,
774 /*StopAtSemi=*/true,
775 /*ConsumeFinalToken=*/false);
776 if (Tok.isNot(tok::l_brace))
Alp Tokerec543272013-12-24 09:48:30 +0000777 return Diag(Tok.getLocation(), diag::err_expected) << tok::l_brace;
Richard Smithcde3fd82013-07-04 00:13:48 +0000778
Sebastian Redla74948d2011-09-24 17:48:25 +0000779 Toks.push_back(Tok);
Richard Smithcde3fd82013-07-04 00:13:48 +0000780 ConsumeBrace();
781 return false;
Eli Friedman7cd4a9b2012-02-22 04:49:04 +0000782 }
Sebastian Redl0d164012011-09-30 08:32:17 +0000783
784 Toks.push_back(Tok);
Richard Smithcde3fd82013-07-04 00:13:48 +0000785 ConsumeToken();
786
787 // We can't reliably skip over a mem-initializer-id, because it could be
788 // a template-id involving not-yet-declared names. Given:
789 //
790 // S ( ) : a < b < c > ( e )
791 //
792 // 'e' might be an initializer or part of a template argument, depending
793 // on whether 'b' is a template.
794
795 // Track whether we might be inside a template argument. We can give
796 // significantly better diagnostics if we know that we're not.
797 bool MightBeTemplateArgument = false;
798
799 while (true) {
800 // Skip over the mem-initializer-id, if possible.
801 if (Tok.is(tok::kw_decltype)) {
802 Toks.push_back(Tok);
803 SourceLocation OpenLoc = ConsumeToken();
804 if (Tok.isNot(tok::l_paren))
805 return Diag(Tok.getLocation(), diag::err_expected_lparen_after)
806 << "decltype";
807 Toks.push_back(Tok);
808 ConsumeParen();
809 if (!ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/true)) {
Alp Tokerec543272013-12-24 09:48:30 +0000810 Diag(Tok.getLocation(), diag::err_expected) << tok::r_paren;
811 Diag(OpenLoc, diag::note_matching) << tok::l_paren;
Richard Smithcde3fd82013-07-04 00:13:48 +0000812 return true;
813 }
814 }
815 do {
816 // Walk over a component of a nested-name-specifier.
817 if (Tok.is(tok::coloncolon)) {
818 Toks.push_back(Tok);
819 ConsumeToken();
820
821 if (Tok.is(tok::kw_template)) {
822 Toks.push_back(Tok);
823 ConsumeToken();
824 }
825 }
826
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000827 if (Tok.isOneOf(tok::identifier, tok::kw_template)) {
Richard Smithcde3fd82013-07-04 00:13:48 +0000828 Toks.push_back(Tok);
829 ConsumeToken();
830 } else if (Tok.is(tok::code_completion)) {
831 Toks.push_back(Tok);
832 ConsumeCodeCompletionToken();
833 // Consume the rest of the initializers permissively.
834 // FIXME: We should be able to perform code-completion here even if
835 // there isn't a subsequent '{' token.
836 MightBeTemplateArgument = true;
837 break;
838 } else {
839 break;
840 }
841 } while (Tok.is(tok::coloncolon));
842
843 if (Tok.is(tok::less))
844 MightBeTemplateArgument = true;
845
846 if (MightBeTemplateArgument) {
847 // We may be inside a template argument list. Grab up to the start of the
848 // next parenthesized initializer or braced-init-list. This *might* be the
849 // initializer, or it might be a subexpression in the template argument
850 // list.
851 // FIXME: Count angle brackets, and clear MightBeTemplateArgument
852 // if all angles are closed.
853 if (!ConsumeAndStoreUntil(tok::l_paren, tok::l_brace, Toks,
854 /*StopAtSemi=*/true,
855 /*ConsumeFinalToken=*/false)) {
856 // We're not just missing the initializer, we're also missing the
857 // function body!
Alp Tokerec543272013-12-24 09:48:30 +0000858 return Diag(Tok.getLocation(), diag::err_expected) << tok::l_brace;
Richard Smithcde3fd82013-07-04 00:13:48 +0000859 }
860 } else if (Tok.isNot(tok::l_paren) && Tok.isNot(tok::l_brace)) {
861 // We found something weird in a mem-initializer-id.
Alp Tokerec543272013-12-24 09:48:30 +0000862 if (getLangOpts().CPlusPlus11)
863 return Diag(Tok.getLocation(), diag::err_expected_either)
864 << tok::l_paren << tok::l_brace;
865 else
866 return Diag(Tok.getLocation(), diag::err_expected) << tok::l_paren;
Richard Smithcde3fd82013-07-04 00:13:48 +0000867 }
868
869 tok::TokenKind kind = Tok.getKind();
870 Toks.push_back(Tok);
871 bool IsLParen = (kind == tok::l_paren);
872 SourceLocation OpenLoc = Tok.getLocation();
873
874 if (IsLParen) {
875 ConsumeParen();
876 } else {
877 assert(kind == tok::l_brace && "Must be left paren or brace here.");
878 ConsumeBrace();
879 // In C++03, this has to be the start of the function body, which
880 // means the initializer is malformed; we'll diagnose it later.
881 if (!getLangOpts().CPlusPlus11)
882 return false;
883 }
884
885 // Grab the initializer (or the subexpression of the template argument).
886 // FIXME: If we support lambdas here, we'll need to set StopAtSemi to false
887 // if we might be inside the braces of a lambda-expression.
Alp Tokerec543272013-12-24 09:48:30 +0000888 tok::TokenKind CloseKind = IsLParen ? tok::r_paren : tok::r_brace;
889 if (!ConsumeAndStoreUntil(CloseKind, Toks, /*StopAtSemi=*/true)) {
890 Diag(Tok, diag::err_expected) << CloseKind;
891 Diag(OpenLoc, diag::note_matching) << kind;
Richard Smithcde3fd82013-07-04 00:13:48 +0000892 return true;
893 }
894
895 // Grab pack ellipsis, if present.
896 if (Tok.is(tok::ellipsis)) {
897 Toks.push_back(Tok);
898 ConsumeToken();
899 }
900
901 // If we know we just consumed a mem-initializer, we must have ',' or '{'
902 // next.
903 if (Tok.is(tok::comma)) {
904 Toks.push_back(Tok);
905 ConsumeToken();
906 } else if (Tok.is(tok::l_brace)) {
907 // This is the function body if the ')' or '}' is immediately followed by
908 // a '{'. That cannot happen within a template argument, apart from the
909 // case where a template argument contains a compound literal:
910 //
911 // S ( ) : a < b < c > ( d ) { }
912 // // End of declaration, or still inside the template argument?
913 //
914 // ... and the case where the template argument contains a lambda:
915 //
916 // S ( ) : a < 0 && b < c > ( d ) + [ ] ( ) { return 0; }
917 // ( ) > ( ) { }
918 //
919 // FIXME: Disambiguate these cases. Note that the latter case is probably
920 // going to be made ill-formed by core issue 1607.
921 Toks.push_back(Tok);
922 ConsumeBrace();
923 return false;
924 } else if (!MightBeTemplateArgument) {
Alp Tokerec543272013-12-24 09:48:30 +0000925 return Diag(Tok.getLocation(), diag::err_expected_either) << tok::l_brace
926 << tok::comma;
Richard Smithcde3fd82013-07-04 00:13:48 +0000927 }
928 }
Sebastian Redla74948d2011-09-24 17:48:25 +0000929}
Richard Smith1fff95c2013-09-12 23:28:08 +0000930
931/// \brief Consume and store tokens from the '?' to the ':' in a conditional
932/// expression.
933bool Parser::ConsumeAndStoreConditional(CachedTokens &Toks) {
934 // Consume '?'.
935 assert(Tok.is(tok::question));
936 Toks.push_back(Tok);
937 ConsumeToken();
938
939 while (Tok.isNot(tok::colon)) {
Nico Weber77c76c52014-05-10 17:43:15 +0000940 if (!ConsumeAndStoreUntil(tok::question, tok::colon, Toks,
941 /*StopAtSemi=*/true,
942 /*ConsumeFinalToken=*/false))
Richard Smith1fff95c2013-09-12 23:28:08 +0000943 return false;
944
945 // If we found a nested conditional, consume it.
946 if (Tok.is(tok::question) && !ConsumeAndStoreConditional(Toks))
947 return false;
948 }
949
950 // Consume ':'.
951 Toks.push_back(Tok);
952 ConsumeToken();
953 return true;
954}
955
956/// \brief A tentative parsing action that can also revert token annotations.
957class Parser::UnannotatedTentativeParsingAction : public TentativeParsingAction {
958public:
959 explicit UnannotatedTentativeParsingAction(Parser &Self,
960 tok::TokenKind EndKind)
961 : TentativeParsingAction(Self), Self(Self), EndKind(EndKind) {
962 // Stash away the old token stream, so we can restore it once the
963 // tentative parse is complete.
964 TentativeParsingAction Inner(Self);
965 Self.ConsumeAndStoreUntil(EndKind, Toks, true, /*ConsumeFinalToken*/false);
966 Inner.Revert();
967 }
968
969 void RevertAnnotations() {
970 Revert();
971
972 // Put back the original tokens.
Alexey Bataevee6507d2013-11-18 08:17:37 +0000973 Self.SkipUntil(EndKind, StopAtSemi | StopBeforeMatch);
Richard Smith1fff95c2013-09-12 23:28:08 +0000974 if (Toks.size()) {
David Blaikie2eabcc92016-02-09 18:52:09 +0000975 auto Buffer = llvm::make_unique<Token[]>(Toks.size());
976 std::copy(Toks.begin() + 1, Toks.end(), Buffer.get());
Richard Smith1fff95c2013-09-12 23:28:08 +0000977 Buffer[Toks.size() - 1] = Self.Tok;
David Blaikie2eabcc92016-02-09 18:52:09 +0000978 Self.PP.EnterTokenStream(std::move(Buffer), Toks.size(), true);
Richard Smith1fff95c2013-09-12 23:28:08 +0000979
980 Self.Tok = Toks.front();
981 }
982 }
983
984private:
985 Parser &Self;
986 CachedTokens Toks;
987 tok::TokenKind EndKind;
988};
989
990/// ConsumeAndStoreInitializer - Consume and store the token at the passed token
991/// container until the end of the current initializer expression (either a
992/// default argument or an in-class initializer for a non-static data member).
Richard Smith95e1fb02014-08-27 03:23:12 +0000993///
994/// Returns \c true if we reached the end of something initializer-shaped,
995/// \c false if we bailed out.
Richard Smith1fff95c2013-09-12 23:28:08 +0000996bool Parser::ConsumeAndStoreInitializer(CachedTokens &Toks,
997 CachedInitKind CIK) {
998 // We always want this function to consume at least one token if not at EOF.
Richard Smith95e1fb02014-08-27 03:23:12 +0000999 bool IsFirstToken = true;
Richard Smith1fff95c2013-09-12 23:28:08 +00001000
1001 // Number of possible unclosed <s we've seen so far. These might be templates,
1002 // and might not, but if there were none of them (or we know for sure that
1003 // we're within a template), we can avoid a tentative parse.
1004 unsigned AngleCount = 0;
1005 unsigned KnownTemplateCount = 0;
1006
1007 while (1) {
1008 switch (Tok.getKind()) {
1009 case tok::comma:
1010 // If we might be in a template, perform a tentative parse to check.
1011 if (!AngleCount)
1012 // Not a template argument: this is the end of the initializer.
1013 return true;
1014 if (KnownTemplateCount)
1015 goto consume_token;
1016
1017 // We hit a comma inside angle brackets. This is the hard case. The
1018 // rule we follow is:
1019 // * For a default argument, if the tokens after the comma form a
1020 // syntactically-valid parameter-declaration-clause, in which each
1021 // parameter has an initializer, then this comma ends the default
1022 // argument.
1023 // * For a default initializer, if the tokens after the comma form a
1024 // syntactically-valid init-declarator-list, then this comma ends
1025 // the default initializer.
1026 {
1027 UnannotatedTentativeParsingAction PA(*this,
1028 CIK == CIK_DefaultInitializer
1029 ? tok::semi : tok::r_paren);
1030 Sema::TentativeAnalysisScope Scope(Actions);
1031
Richard Smithee390432014-05-16 01:56:53 +00001032 TPResult Result = TPResult::Error;
Richard Smith1fff95c2013-09-12 23:28:08 +00001033 ConsumeToken();
1034 switch (CIK) {
1035 case CIK_DefaultInitializer:
1036 Result = TryParseInitDeclaratorList();
1037 // If we parsed a complete, ambiguous init-declarator-list, this
1038 // is only syntactically-valid if it's followed by a semicolon.
Richard Smithee390432014-05-16 01:56:53 +00001039 if (Result == TPResult::Ambiguous && Tok.isNot(tok::semi))
1040 Result = TPResult::False;
Richard Smith1fff95c2013-09-12 23:28:08 +00001041 break;
1042
1043 case CIK_DefaultArgument:
1044 bool InvalidAsDeclaration = false;
1045 Result = TryParseParameterDeclarationClause(
Nico Weberc29c4832014-12-28 23:24:02 +00001046 &InvalidAsDeclaration, /*VersusTemplateArgument=*/true);
Richard Smith1fff95c2013-09-12 23:28:08 +00001047 // If this is an expression or a declaration with a missing
1048 // 'typename', assume it's not a declaration.
Richard Smithee390432014-05-16 01:56:53 +00001049 if (Result == TPResult::Ambiguous && InvalidAsDeclaration)
1050 Result = TPResult::False;
Richard Smith1fff95c2013-09-12 23:28:08 +00001051 break;
1052 }
1053
1054 // If what follows could be a declaration, it is a declaration.
Richard Smithee390432014-05-16 01:56:53 +00001055 if (Result != TPResult::False && Result != TPResult::Error) {
Richard Smith1fff95c2013-09-12 23:28:08 +00001056 PA.Revert();
1057 return true;
1058 }
1059
1060 // In the uncommon case that we decide the following tokens are part
1061 // of a template argument, revert any annotations we've performed in
1062 // those tokens. We're not going to look them up until we've parsed
1063 // the rest of the class, and that might add more declarations.
1064 PA.RevertAnnotations();
1065 }
1066
1067 // Keep going. We know we're inside a template argument list now.
1068 ++KnownTemplateCount;
1069 goto consume_token;
1070
1071 case tok::eof:
Richard Smith34f30512013-11-23 04:06:09 +00001072 case tok::annot_module_begin:
1073 case tok::annot_module_end:
1074 case tok::annot_module_include:
Richard Smith1fff95c2013-09-12 23:28:08 +00001075 // Ran out of tokens.
1076 return false;
1077
1078 case tok::less:
1079 // FIXME: A '<' can only start a template-id if it's preceded by an
1080 // identifier, an operator-function-id, or a literal-operator-id.
1081 ++AngleCount;
1082 goto consume_token;
1083
1084 case tok::question:
1085 // In 'a ? b : c', 'b' can contain an unparenthesized comma. If it does,
1086 // that is *never* the end of the initializer. Skip to the ':'.
1087 if (!ConsumeAndStoreConditional(Toks))
1088 return false;
1089 break;
1090
1091 case tok::greatergreatergreater:
1092 if (!getLangOpts().CPlusPlus11)
1093 goto consume_token;
1094 if (AngleCount) --AngleCount;
1095 if (KnownTemplateCount) --KnownTemplateCount;
1096 // Fall through.
1097 case tok::greatergreater:
1098 if (!getLangOpts().CPlusPlus11)
1099 goto consume_token;
1100 if (AngleCount) --AngleCount;
1101 if (KnownTemplateCount) --KnownTemplateCount;
1102 // Fall through.
1103 case tok::greater:
1104 if (AngleCount) --AngleCount;
1105 if (KnownTemplateCount) --KnownTemplateCount;
1106 goto consume_token;
1107
1108 case tok::kw_template:
1109 // 'template' identifier '<' is known to start a template argument list,
1110 // and can be used to disambiguate the parse.
1111 // FIXME: Support all forms of 'template' unqualified-id '<'.
1112 Toks.push_back(Tok);
1113 ConsumeToken();
1114 if (Tok.is(tok::identifier)) {
1115 Toks.push_back(Tok);
1116 ConsumeToken();
1117 if (Tok.is(tok::less)) {
Richard Smith93033572014-07-27 05:38:12 +00001118 ++AngleCount;
Richard Smith1fff95c2013-09-12 23:28:08 +00001119 ++KnownTemplateCount;
1120 Toks.push_back(Tok);
1121 ConsumeToken();
1122 }
1123 }
1124 break;
1125
1126 case tok::kw_operator:
1127 // If 'operator' precedes other punctuation, that punctuation loses
1128 // its special behavior.
1129 Toks.push_back(Tok);
1130 ConsumeToken();
1131 switch (Tok.getKind()) {
1132 case tok::comma:
1133 case tok::greatergreatergreater:
1134 case tok::greatergreater:
1135 case tok::greater:
1136 case tok::less:
1137 Toks.push_back(Tok);
1138 ConsumeToken();
1139 break;
1140 default:
1141 break;
1142 }
1143 break;
1144
1145 case tok::l_paren:
1146 // Recursively consume properly-nested parens.
1147 Toks.push_back(Tok);
1148 ConsumeParen();
1149 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
1150 break;
1151 case tok::l_square:
1152 // Recursively consume properly-nested square brackets.
1153 Toks.push_back(Tok);
1154 ConsumeBracket();
1155 ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false);
1156 break;
1157 case tok::l_brace:
1158 // Recursively consume properly-nested braces.
1159 Toks.push_back(Tok);
1160 ConsumeBrace();
1161 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1162 break;
1163
1164 // Okay, we found a ']' or '}' or ')', which we think should be balanced.
1165 // Since the user wasn't looking for this token (if they were, it would
1166 // already be handled), this isn't balanced. If there is a LHS token at a
1167 // higher level, we will assume that this matches the unbalanced token
Richard Smith95e1fb02014-08-27 03:23:12 +00001168 // and return it. Otherwise, this is a spurious RHS token, which we
1169 // consume and pass on to downstream code to diagnose.
Richard Smith1fff95c2013-09-12 23:28:08 +00001170 case tok::r_paren:
1171 if (CIK == CIK_DefaultArgument)
1172 return true; // End of the default argument.
Richard Smith95e1fb02014-08-27 03:23:12 +00001173 if (ParenCount && !IsFirstToken)
1174 return false;
1175 Toks.push_back(Tok);
1176 ConsumeParen();
1177 continue;
Richard Smith1fff95c2013-09-12 23:28:08 +00001178 case tok::r_square:
Richard Smith95e1fb02014-08-27 03:23:12 +00001179 if (BracketCount && !IsFirstToken)
1180 return false;
1181 Toks.push_back(Tok);
1182 ConsumeBracket();
1183 continue;
Richard Smith1fff95c2013-09-12 23:28:08 +00001184 case tok::r_brace:
Richard Smith95e1fb02014-08-27 03:23:12 +00001185 if (BraceCount && !IsFirstToken)
1186 return false;
1187 Toks.push_back(Tok);
1188 ConsumeBrace();
1189 continue;
Richard Smith1fff95c2013-09-12 23:28:08 +00001190
1191 case tok::code_completion:
1192 Toks.push_back(Tok);
1193 ConsumeCodeCompletionToken();
1194 break;
1195
1196 case tok::string_literal:
1197 case tok::wide_string_literal:
1198 case tok::utf8_string_literal:
1199 case tok::utf16_string_literal:
1200 case tok::utf32_string_literal:
1201 Toks.push_back(Tok);
1202 ConsumeStringToken();
1203 break;
1204 case tok::semi:
1205 if (CIK == CIK_DefaultInitializer)
1206 return true; // End of the default initializer.
1207 // FALL THROUGH.
1208 default:
1209 consume_token:
1210 Toks.push_back(Tok);
1211 ConsumeToken();
1212 break;
1213 }
Richard Smith95e1fb02014-08-27 03:23:12 +00001214 IsFirstToken = false;
Richard Smith1fff95c2013-09-12 23:28:08 +00001215 }
1216}