blob: 89ef35c88bb211f440dc5eb1bd7ad8caf8a86bc8 [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
Douglas Gregor433e0532012-04-16 18:27:27 +000055 HandleMemberFunctionDeclDelays(D, FnD);
Eli Friedman3af2a772009-07-22 21:45:50 +000056
John McCallc1465822011-02-14 07:13:47 +000057 D.complete(FnD);
58
Alp Tokera3ebe6e2013-12-17 14:12:37 +000059 if (TryConsumeToken(tok::equal)) {
Richard Smith1c704732011-11-10 09:08:44 +000060 if (!FnD) {
61 SkipUntil(tok::semi);
Craig Topper161e4db2014-05-21 06:02:52 +000062 return nullptr;
Richard Smith1c704732011-11-10 09:08:44 +000063 }
64
Alexis Hunt5a7fa252011-05-12 06:15:49 +000065 bool Delete = false;
66 SourceLocation KWLoc;
Eli Bendersky5f4d76e2015-03-23 21:43:28 +000067 SourceLocation KWEndLoc = Tok.getEndLoc().getLocWithOffset(-1);
Alp Tokera3ebe6e2013-12-17 14:12:37 +000068 if (TryConsumeToken(tok::kw_delete, KWLoc)) {
69 Diag(KWLoc, getLangOpts().CPlusPlus11
Craig Topper54a6a682015-11-14 18:16:08 +000070 ? diag::warn_cxx98_compat_defaulted_deleted_function
71 : diag::ext_defaulted_deleted_function)
72 << 1 /* deleted */;
Alexis Hunt5a7fa252011-05-12 06:15:49 +000073 Actions.SetDeclDeleted(FnD, KWLoc);
74 Delete = true;
Eli Bendersky5f4d76e2015-03-23 21:43:28 +000075 if (auto *DeclAsFunction = dyn_cast<FunctionDecl>(FnD)) {
76 DeclAsFunction->setRangeEnd(KWEndLoc);
77 }
Alp Tokera3ebe6e2013-12-17 14:12:37 +000078 } else if (TryConsumeToken(tok::kw_default, KWLoc)) {
79 Diag(KWLoc, getLangOpts().CPlusPlus11
Craig Topper54a6a682015-11-14 18:16:08 +000080 ? diag::warn_cxx98_compat_defaulted_deleted_function
81 : diag::ext_defaulted_deleted_function)
82 << 0 /* defaulted */;
Alexis Hunt5a7fa252011-05-12 06:15:49 +000083 Actions.SetDeclDefaulted(FnD, KWLoc);
Eli Bendersky5f4d76e2015-03-23 21:43:28 +000084 if (auto *DeclAsFunction = dyn_cast<FunctionDecl>(FnD)) {
85 DeclAsFunction->setRangeEnd(KWEndLoc);
86 }
Alexis Hunt5a7fa252011-05-12 06:15:49 +000087 } else {
88 llvm_unreachable("function definition after = not 'delete' or 'default'");
89 }
90
91 if (Tok.is(tok::comma)) {
92 Diag(KWLoc, diag::err_default_delete_in_multiple_declaration)
93 << Delete;
94 SkipUntil(tok::semi);
Alp Toker383d2c42014-01-01 03:08:43 +000095 } else if (ExpectAndConsume(tok::semi, diag::err_expected_after,
96 Delete ? "delete" : "default")) {
97 SkipUntil(tok::semi);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000098 }
99
100 return FnD;
101 }
Eli Bendersky41842222015-03-23 23:49:41 +0000102
Francois Pichet1c229c02011-04-22 22:18:13 +0000103 // In delayed template parsing mode, if we are within a class template
104 // or if we are about to parse function member template then consume
105 // the tokens and store them for parsing at the end of the translation unit.
David Majnemer90b17292013-09-14 05:46:42 +0000106 if (getLangOpts().DelayedTemplateParsing &&
Eli Bendersky41842222015-03-23 23:49:41 +0000107 D.getFunctionDefinitionKind() == FDK_Definition &&
Alp Tokera2794f92014-01-22 07:29:52 +0000108 !D.getDeclSpec().isConstexprSpecified() &&
109 !(FnD && FnD->getAsFunction() &&
Alp Toker314cc812014-01-25 16:55:45 +0000110 FnD->getAsFunction()->getReturnType()->getContainedAutoType()) &&
Francois Pichet1c229c02011-04-22 22:18:13 +0000111 ((Actions.CurContext->isDependentContext() ||
David Majnemer90b17292013-09-14 05:46:42 +0000112 (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
113 TemplateInfo.Kind != ParsedTemplateInfo::ExplicitSpecialization)) &&
114 !Actions.IsInsideALocalClassWithinATemplateFunction())) {
Francois Pichet1c229c02011-04-22 22:18:13 +0000115
Richard Smithe40f2ba2013-08-07 21:41:30 +0000116 CachedTokens Toks;
117 LexTemplateFunctionForLateParsing(Toks);
Francois Pichet1c229c02011-04-22 22:18:13 +0000118
Richard Smithe40f2ba2013-08-07 21:41:30 +0000119 if (FnD) {
Alp Tokera2794f92014-01-22 07:29:52 +0000120 FunctionDecl *FD = FnD->getAsFunction();
Chandler Carruthbc0f9ae2011-04-25 07:09:43 +0000121 Actions.CheckForFunctionRedefinition(FD);
Richard Smithe40f2ba2013-08-07 21:41:30 +0000122 Actions.MarkAsLateParsedTemplate(FD, FnD, Toks);
Francois Pichet1c229c02011-04-22 22:18:13 +0000123 }
124
125 return FnD;
126 }
127
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000128 // Consume the tokens and store them for later parsing.
129
Douglas Gregorefc46952010-10-12 16:25:54 +0000130 LexedMethod* LM = new LexedMethod(this, FnD);
131 getCurrentClass().LateParsedDeclarations.push_back(LM);
132 LM->TemplateScope = getCurScope()->isTemplateParamScope();
133 CachedTokens &Toks = LM->Toks;
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000134
Sebastian Redla7b98a72009-04-26 20:35:05 +0000135 tok::TokenKind kind = Tok.getKind();
Sebastian Redl0d164012011-09-30 08:32:17 +0000136 // Consume everything up to (and including) the left brace of the
137 // function body.
138 if (ConsumeAndStoreFunctionPrologue(Toks)) {
139 // We didn't find the left-brace we expected after the
Eli Friedman7cd4a9b2012-02-22 04:49:04 +0000140 // constructor initializer; we already printed an error, and it's likely
141 // impossible to recover, so don't try to parse this method later.
Richard Smithcde3fd82013-07-04 00:13:48 +0000142 // Skip over the rest of the decl and back to somewhere that looks
143 // reasonable.
144 SkipMalformedDecl();
Eli Friedman7cd4a9b2012-02-22 04:49:04 +0000145 delete getCurrentClass().LateParsedDeclarations.back();
146 getCurrentClass().LateParsedDeclarations.pop_back();
147 return FnD;
Douglas Gregore8381c02008-11-05 04:29:56 +0000148 } else {
Sebastian Redl0d164012011-09-30 08:32:17 +0000149 // Consume everything up to (and including) the matching right brace.
150 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
Douglas Gregore8381c02008-11-05 04:29:56 +0000151 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000152
Sebastian Redla7b98a72009-04-26 20:35:05 +0000153 // If we're in a function-try-block, we need to store all the catch blocks.
154 if (kind == tok::kw_try) {
155 while (Tok.is(tok::kw_catch)) {
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000156 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
157 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
Sebastian Redla7b98a72009-04-26 20:35:05 +0000158 }
159 }
160
Stephen Lin9354fc52013-06-23 07:37:13 +0000161 if (FnD) {
162 // If this is a friend function, mark that it's late-parsed so that
163 // it's still known to be a definition even before we attach the
164 // parsed body. Sema needs to treat friend function definitions
165 // differently during template instantiation, and it's possible for
166 // the containing class to be instantiated before all its member
167 // function definitions are parsed.
168 //
169 // If you remove this, you can remove the code that clears the flag
170 // after parsing the member.
171 if (D.getDeclSpec().isFriendSpecified()) {
Alp Tokera2794f92014-01-22 07:29:52 +0000172 FunctionDecl *FD = FnD->getAsFunction();
Alp Toker19bff322013-10-18 05:54:24 +0000173 Actions.CheckForFunctionRedefinition(FD);
174 FD->setLateTemplateParsed(true);
Stephen Lin9354fc52013-06-23 07:37:13 +0000175 }
176 } else {
Douglas Gregor6ca64102011-04-14 23:19:27 +0000177 // If semantic analysis could not build a function declaration,
178 // just throw away the late-parsed declaration.
179 delete getCurrentClass().LateParsedDeclarations.back();
180 getCurrentClass().LateParsedDeclarations.pop_back();
181 }
182
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000183 return FnD;
184}
185
Richard Smith938f40b2011-06-11 17:19:42 +0000186/// ParseCXXNonStaticMemberInitializer - We parsed and verified that the
187/// specified Declarator is a well formed C++ non-static data member
188/// declaration. Now lex its initializer and store its tokens for parsing
189/// after the class is complete.
190void Parser::ParseCXXNonStaticMemberInitializer(Decl *VarD) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000191 assert(Tok.isOneOf(tok::l_brace, tok::equal) &&
Richard Smith938f40b2011-06-11 17:19:42 +0000192 "Current token not a '{' or '='!");
193
194 LateParsedMemberInitializer *MI =
195 new LateParsedMemberInitializer(this, VarD);
196 getCurrentClass().LateParsedDeclarations.push_back(MI);
197 CachedTokens &Toks = MI->Toks;
198
199 tok::TokenKind kind = Tok.getKind();
200 if (kind == tok::equal) {
201 Toks.push_back(Tok);
Douglas Gregor0cf55e92012-03-08 01:00:17 +0000202 ConsumeToken();
Richard Smith938f40b2011-06-11 17:19:42 +0000203 }
204
205 if (kind == tok::l_brace) {
206 // Begin by storing the '{' token.
207 Toks.push_back(Tok);
208 ConsumeBrace();
209
210 // Consume everything up to (and including) the matching right brace.
211 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/true);
212 } else {
213 // Consume everything up to (but excluding) the comma or semicolon.
Richard Smith1fff95c2013-09-12 23:28:08 +0000214 ConsumeAndStoreInitializer(Toks, CIK_DefaultInitializer);
Richard Smith938f40b2011-06-11 17:19:42 +0000215 }
216
217 // Store an artificial EOF token to ensure that we don't run off the end of
218 // the initializer when we come to parse it.
219 Token Eof;
220 Eof.startToken();
221 Eof.setKind(tok::eof);
222 Eof.setLocation(Tok.getLocation());
David Majnemerce1d3012014-12-19 02:13:56 +0000223 Eof.setEofData(VarD);
Richard Smith938f40b2011-06-11 17:19:42 +0000224 Toks.push_back(Eof);
225}
226
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000227Parser::LateParsedDeclaration::~LateParsedDeclaration() {}
Douglas Gregorefc46952010-10-12 16:25:54 +0000228void Parser::LateParsedDeclaration::ParseLexedMethodDeclarations() {}
Richard Smith938f40b2011-06-11 17:19:42 +0000229void Parser::LateParsedDeclaration::ParseLexedMemberInitializers() {}
Douglas Gregorefc46952010-10-12 16:25:54 +0000230void Parser::LateParsedDeclaration::ParseLexedMethodDefs() {}
231
232Parser::LateParsedClass::LateParsedClass(Parser *P, ParsingClass *C)
233 : Self(P), Class(C) {}
234
235Parser::LateParsedClass::~LateParsedClass() {
236 Self->DeallocateParsedClasses(Class);
237}
238
239void Parser::LateParsedClass::ParseLexedMethodDeclarations() {
240 Self->ParseLexedMethodDeclarations(*Class);
241}
242
Richard Smith938f40b2011-06-11 17:19:42 +0000243void Parser::LateParsedClass::ParseLexedMemberInitializers() {
244 Self->ParseLexedMemberInitializers(*Class);
245}
246
Douglas Gregorefc46952010-10-12 16:25:54 +0000247void Parser::LateParsedClass::ParseLexedMethodDefs() {
248 Self->ParseLexedMethodDefs(*Class);
249}
250
251void Parser::LateParsedMethodDeclaration::ParseLexedMethodDeclarations() {
252 Self->ParseLexedMethodDeclaration(*this);
253}
254
255void Parser::LexedMethod::ParseLexedMethodDefs() {
256 Self->ParseLexedMethodDef(*this);
257}
258
Richard Smith938f40b2011-06-11 17:19:42 +0000259void Parser::LateParsedMemberInitializer::ParseLexedMemberInitializers() {
260 Self->ParseLexedMemberInitializer(*this);
261}
262
Douglas Gregor4d87df52008-12-16 21:30:33 +0000263/// ParseLexedMethodDeclarations - We finished parsing the member
264/// specification of a top (non-nested) C++ class. Now go over the
265/// stack of method declarations with some parts for which parsing was
266/// delayed (such as default arguments) and parse them.
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000267void Parser::ParseLexedMethodDeclarations(ParsingClass &Class) {
268 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
Nico Weber77c76c52014-05-10 17:43:15 +0000269 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
270 HasTemplateScope);
Richard Smithc8378952013-04-29 11:55:38 +0000271 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
272 if (HasTemplateScope) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000273 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
Richard Smithc8378952013-04-29 11:55:38 +0000274 ++CurTemplateDepthTracker;
275 }
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000276
John McCall6df5fef2009-12-19 10:49:29 +0000277 // The current scope is still active if we're the top-level class.
278 // Otherwise we'll need to push and enter a new scope.
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000279 bool HasClassScope = !Class.TopLevelClass;
Alexis Hunt1deb9722010-04-14 23:07:37 +0000280 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope,
281 HasClassScope);
John McCall6df5fef2009-12-19 10:49:29 +0000282 if (HasClassScope)
Nico Weber77c76c52014-05-10 17:43:15 +0000283 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(),
284 Class.TagOrTemplate);
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000285
Douglas Gregorefc46952010-10-12 16:25:54 +0000286 for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
287 Class.LateParsedDeclarations[i]->ParseLexedMethodDeclarations();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000288 }
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000289
John McCall6df5fef2009-12-19 10:49:29 +0000290 if (HasClassScope)
Nico Weber77c76c52014-05-10 17:43:15 +0000291 Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(),
292 Class.TagOrTemplate);
Douglas Gregor4d87df52008-12-16 21:30:33 +0000293}
294
Douglas Gregorefc46952010-10-12 16:25:54 +0000295void Parser::ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM) {
296 // If this is a member template, introduce the template parameter scope.
297 ParseScope TemplateScope(this, Scope::TemplateParamScope, LM.TemplateScope);
Richard Smithc8378952013-04-29 11:55:38 +0000298 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
299 if (LM.TemplateScope) {
Douglas Gregorefc46952010-10-12 16:25:54 +0000300 Actions.ActOnReenterTemplateScope(getCurScope(), LM.Method);
Richard Smithc8378952013-04-29 11:55:38 +0000301 ++CurTemplateDepthTracker;
302 }
Douglas Gregorefc46952010-10-12 16:25:54 +0000303 // Start the delayed C++ method declaration
304 Actions.ActOnStartDelayedCXXMethodDeclaration(getCurScope(), LM.Method);
305
306 // Introduce the parameters into scope and parse their default
307 // arguments.
Richard Smithe233fbf2013-01-28 22:42:45 +0000308 ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
309 Scope::FunctionDeclarationScope | Scope::DeclScope);
Douglas Gregorefc46952010-10-12 16:25:54 +0000310 for (unsigned I = 0, N = LM.DefaultArgs.size(); I != N; ++I) {
Nathan Sidwell5bb231c2015-02-19 14:03:22 +0000311 auto Param = cast<ParmVarDecl>(LM.DefaultArgs[I].Param);
Douglas Gregorefc46952010-10-12 16:25:54 +0000312 // Introduce the parameter into scope.
Nathan Sidwell5bb231c2015-02-19 14:03:22 +0000313 bool HasUnparsed = Param->hasUnparsedDefaultArg();
Nathan Sidwell55d53fe2015-01-30 14:21:35 +0000314 Actions.ActOnDelayedCXXMethodParameter(getCurScope(), Param);
Douglas Gregorefc46952010-10-12 16:25:54 +0000315 if (CachedTokens *Toks = LM.DefaultArgs[I].Toks) {
David Majnemer7cceba52015-01-13 04:20:57 +0000316 // Mark the end of the default argument so that we know when to stop when
317 // we parse it later on.
318 Token LastDefaultArgToken = Toks->back();
319 Token DefArgEnd;
320 DefArgEnd.startToken();
321 DefArgEnd.setKind(tok::eof);
David Majnemera8f2f1d2015-03-19 00:10:23 +0000322 DefArgEnd.setLocation(LastDefaultArgToken.getEndLoc());
Nathan Sidwell55d53fe2015-01-30 14:21:35 +0000323 DefArgEnd.setEofData(Param);
David Majnemer7cceba52015-01-13 04:20:57 +0000324 Toks->push_back(DefArgEnd);
Douglas Gregorefc46952010-10-12 16:25:54 +0000325
326 // Parse the default argument from its saved token stream.
327 Toks->push_back(Tok); // So that the current token doesn't get lost
David Blaikie2eabcc92016-02-09 18:52:09 +0000328 PP.EnterTokenStream(*Toks, true);
Douglas Gregorefc46952010-10-12 16:25:54 +0000329
330 // Consume the previously-pushed token.
331 ConsumeAnyToken();
332
333 // Consume the '='.
334 assert(Tok.is(tok::equal) && "Default argument not starting with '='");
335 SourceLocation EqualLoc = ConsumeToken();
336
337 // The argument isn't actually potentially evaluated unless it is
338 // used.
339 EnterExpressionEvaluationContext Eval(Actions,
Douglas Gregor7fcbd902012-02-21 00:37:24 +0000340 Sema::PotentiallyEvaluatedIfUsed,
Nathan Sidwell55d53fe2015-01-30 14:21:35 +0000341 Param);
Douglas Gregorefc46952010-10-12 16:25:54 +0000342
Sebastian Redldb63af22012-03-14 15:54:00 +0000343 ExprResult DefArgResult;
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000344 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
Sebastian Redl6db0b1b2012-03-20 21:24:03 +0000345 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
Sebastian Redldb63af22012-03-14 15:54:00 +0000346 DefArgResult = ParseBraceInitializer();
Sebastian Redl6db0b1b2012-03-20 21:24:03 +0000347 } else
Sebastian Redldb63af22012-03-14 15:54:00 +0000348 DefArgResult = ParseAssignmentExpression();
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000349 DefArgResult = Actions.CorrectDelayedTyposInExpr(DefArgResult);
David Majnemerbba12342015-01-12 06:51:15 +0000350 if (DefArgResult.isInvalid()) {
Nathan Sidwell55d53fe2015-01-30 14:21:35 +0000351 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
David Majnemerbba12342015-01-12 06:51:15 +0000352 } else {
Nathan Sidwell55d53fe2015-01-30 14:21:35 +0000353 if (Tok.isNot(tok::eof) || Tok.getEofData() != Param) {
Richard Smith1fff95c2013-09-12 23:28:08 +0000354 // The last two tokens are the terminator and the saved value of
355 // Tok; the last token in the default argument is the one before
356 // those.
357 assert(Toks->size() >= 3 && "expected a token in default arg");
358 Diag(Tok.getLocation(), diag::err_default_arg_unparsed)
359 << SourceRange(Tok.getLocation(),
360 (*Toks)[Toks->size() - 3].getLocation());
361 }
Nathan Sidwell55d53fe2015-01-30 14:21:35 +0000362 Actions.ActOnParamDefaultArgument(Param, EqualLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000363 DefArgResult.get());
Douglas Gregorefc46952010-10-12 16:25:54 +0000364 }
365
Douglas Gregorefc46952010-10-12 16:25:54 +0000366 // There could be leftover tokens (e.g. because of an error).
David Majnemer7cceba52015-01-13 04:20:57 +0000367 // Skip through until we reach the 'end of default argument' token.
368 while (Tok.isNot(tok::eof))
Douglas Gregorefc46952010-10-12 16:25:54 +0000369 ConsumeAnyToken();
David Majnemer7cceba52015-01-13 04:20:57 +0000370
Nathan Sidwell55d53fe2015-01-30 14:21:35 +0000371 if (Tok.is(tok::eof) && Tok.getEofData() == Param)
David Majnemer7cceba52015-01-13 04:20:57 +0000372 ConsumeAnyToken();
Douglas Gregorefc46952010-10-12 16:25:54 +0000373
374 delete Toks;
Craig Topper161e4db2014-05-21 06:02:52 +0000375 LM.DefaultArgs[I].Toks = nullptr;
Nathan Sidwell5bb231c2015-02-19 14:03:22 +0000376 } else if (HasUnparsed) {
377 assert(Param->hasInheritedDefaultArg());
378 FunctionDecl *Old = cast<FunctionDecl>(LM.Method)->getPreviousDecl();
379 ParmVarDecl *OldParam = Old->getParamDecl(I);
380 assert (!OldParam->hasUnparsedDefaultArg());
381 if (OldParam->hasUninstantiatedDefaultArg())
382 Param->setUninstantiatedDefaultArg(
383 Param->getUninstantiatedDefaultArg());
384 else
385 Param->setDefaultArg(OldParam->getInit());
Douglas Gregorefc46952010-10-12 16:25:54 +0000386 }
387 }
Douglas Gregor433e0532012-04-16 18:27:27 +0000388
Richard Smith0b3a4622014-11-13 20:01:57 +0000389 // Parse a delayed exception-specification, if there is one.
390 if (CachedTokens *Toks = LM.ExceptionSpecTokens) {
David Majnemer7cceba52015-01-13 04:20:57 +0000391 // Add the 'stop' token.
392 Token LastExceptionSpecToken = Toks->back();
393 Token ExceptionSpecEnd;
394 ExceptionSpecEnd.startToken();
395 ExceptionSpecEnd.setKind(tok::eof);
David Majnemera8f2f1d2015-03-19 00:10:23 +0000396 ExceptionSpecEnd.setLocation(LastExceptionSpecToken.getEndLoc());
David Majnemer7cceba52015-01-13 04:20:57 +0000397 ExceptionSpecEnd.setEofData(LM.Method);
398 Toks->push_back(ExceptionSpecEnd);
Richard Smith0b3a4622014-11-13 20:01:57 +0000399
400 // Parse the default argument from its saved token stream.
401 Toks->push_back(Tok); // So that the current token doesn't get lost
David Blaikie2eabcc92016-02-09 18:52:09 +0000402 PP.EnterTokenStream(*Toks, true);
Richard Smith0b3a4622014-11-13 20:01:57 +0000403
404 // Consume the previously-pushed token.
405 ConsumeAnyToken();
406
407 // C++11 [expr.prim.general]p3:
408 // If a declaration declares a member function or member function
409 // template of a class X, the expression this is a prvalue of type
410 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
411 // and the end of the function-definition, member-declarator, or
412 // declarator.
413 CXXMethodDecl *Method;
414 if (FunctionTemplateDecl *FunTmpl
415 = dyn_cast<FunctionTemplateDecl>(LM.Method))
416 Method = cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
417 else
418 Method = cast<CXXMethodDecl>(LM.Method);
419
420 Sema::CXXThisScopeRAII ThisScope(Actions, Method->getParent(),
421 Method->getTypeQualifiers(),
422 getLangOpts().CPlusPlus11);
423
424 // Parse the exception-specification.
425 SourceRange SpecificationRange;
426 SmallVector<ParsedType, 4> DynamicExceptions;
427 SmallVector<SourceRange, 4> DynamicExceptionRanges;
428 ExprResult NoexceptExpr;
429 CachedTokens *ExceptionSpecTokens;
430
431 ExceptionSpecificationType EST
432 = tryParseExceptionSpecification(/*Delayed=*/false, SpecificationRange,
433 DynamicExceptions,
434 DynamicExceptionRanges, NoexceptExpr,
435 ExceptionSpecTokens);
436
David Majnemer7cceba52015-01-13 04:20:57 +0000437 if (Tok.isNot(tok::eof) || Tok.getEofData() != LM.Method)
Richard Smith0b3a4622014-11-13 20:01:57 +0000438 Diag(Tok.getLocation(), diag::err_except_spec_unparsed);
439
440 // Attach the exception-specification to the method.
Richard Smith3ef3e892014-11-20 22:32:11 +0000441 Actions.actOnDelayedExceptionSpecification(LM.Method, EST,
442 SpecificationRange,
443 DynamicExceptions,
444 DynamicExceptionRanges,
445 NoexceptExpr.isUsable()?
446 NoexceptExpr.get() : nullptr);
Richard Smith0b3a4622014-11-13 20:01:57 +0000447
Richard Smith0b3a4622014-11-13 20:01:57 +0000448 // There could be leftover tokens (e.g. because of an error).
449 // Skip through until we reach the original token position.
David Majnemer7cceba52015-01-13 04:20:57 +0000450 while (Tok.isNot(tok::eof))
Richard Smith0b3a4622014-11-13 20:01:57 +0000451 ConsumeAnyToken();
David Majnemer7cceba52015-01-13 04:20:57 +0000452
453 // Clean up the remaining EOF token.
454 if (Tok.is(tok::eof) && Tok.getEofData() == LM.Method)
455 ConsumeAnyToken();
Richard Smith0b3a4622014-11-13 20:01:57 +0000456
457 delete Toks;
458 LM.ExceptionSpecTokens = nullptr;
459 }
460
Douglas Gregorefc46952010-10-12 16:25:54 +0000461 PrototypeScope.Exit();
462
463 // Finish the delayed C++ method declaration.
464 Actions.ActOnFinishDelayedCXXMethodDeclaration(getCurScope(), LM.Method);
465}
466
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000467/// ParseLexedMethodDefs - We finished parsing the member specification of a top
468/// (non-nested) C++ class. Now go over the stack of lexed methods that were
469/// collected during its parsing and parse them all.
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000470void Parser::ParseLexedMethodDefs(ParsingClass &Class) {
471 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
Douglas Gregorefc46952010-10-12 16:25:54 +0000472 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope, HasTemplateScope);
Richard Smithc8378952013-04-29 11:55:38 +0000473 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
474 if (HasTemplateScope) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000475 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
Richard Smithc8378952013-04-29 11:55:38 +0000476 ++CurTemplateDepthTracker;
477 }
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000478 bool HasClassScope = !Class.TopLevelClass;
479 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope,
480 HasClassScope);
481
Douglas Gregorefc46952010-10-12 16:25:54 +0000482 for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
483 Class.LateParsedDeclarations[i]->ParseLexedMethodDefs();
484 }
485}
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000486
Douglas Gregorefc46952010-10-12 16:25:54 +0000487void Parser::ParseLexedMethodDef(LexedMethod &LM) {
488 // If this is a member template, introduce the template parameter scope.
489 ParseScope TemplateScope(this, Scope::TemplateParamScope, LM.TemplateScope);
Richard Smithc8378952013-04-29 11:55:38 +0000490 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
491 if (LM.TemplateScope) {
Douglas Gregorefc46952010-10-12 16:25:54 +0000492 Actions.ActOnReenterTemplateScope(getCurScope(), LM.D);
Richard Smithc8378952013-04-29 11:55:38 +0000493 ++CurTemplateDepthTracker;
494 }
Argyrios Kyrtzidis02041972010-03-31 00:38:09 +0000495
Douglas Gregorefc46952010-10-12 16:25:54 +0000496 assert(!LM.Toks.empty() && "Empty body!");
David Majnemera7ea1b12015-01-13 05:06:20 +0000497 Token LastBodyToken = LM.Toks.back();
498 Token BodyEnd;
499 BodyEnd.startToken();
500 BodyEnd.setKind(tok::eof);
David Majnemera8f2f1d2015-03-19 00:10:23 +0000501 BodyEnd.setLocation(LastBodyToken.getEndLoc());
David Majnemera7ea1b12015-01-13 05:06:20 +0000502 BodyEnd.setEofData(LM.D);
503 LM.Toks.push_back(BodyEnd);
Douglas Gregorefc46952010-10-12 16:25:54 +0000504 // Append the current token at the end of the new token stream so that it
505 // doesn't get lost.
506 LM.Toks.push_back(Tok);
David Blaikie2eabcc92016-02-09 18:52:09 +0000507 PP.EnterTokenStream(LM.Toks, true);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000508
Douglas Gregorefc46952010-10-12 16:25:54 +0000509 // Consume the previously pushed token.
Argyrios Kyrtzidisc36633c2013-03-27 23:58:17 +0000510 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000511 assert(Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try)
Douglas Gregorefc46952010-10-12 16:25:54 +0000512 && "Inline method not starting with '{', ':' or 'try'");
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000513
Douglas Gregorefc46952010-10-12 16:25:54 +0000514 // Parse the method body. Function body parsing code is similar enough
515 // to be re-used for method bodies as well.
516 ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope);
517 Actions.ActOnStartOfFunctionDef(getCurScope(), LM.D);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000518
Douglas Gregorefc46952010-10-12 16:25:54 +0000519 if (Tok.is(tok::kw_try)) {
Douglas Gregora0ff0c32011-03-16 17:05:57 +0000520 ParseFunctionTryBlock(LM.D, FnScope);
David Majnemera7ea1b12015-01-13 05:06:20 +0000521
522 while (Tok.isNot(tok::eof))
523 ConsumeAnyToken();
524
525 if (Tok.is(tok::eof) && Tok.getEofData() == LM.D)
Douglas Gregorefc46952010-10-12 16:25:54 +0000526 ConsumeAnyToken();
527 return;
528 }
529 if (Tok.is(tok::colon)) {
530 ParseConstructorInitializer(LM.D);
531
532 // Error recovery.
533 if (!Tok.is(tok::l_brace)) {
Douglas Gregora0ff0c32011-03-16 17:05:57 +0000534 FnScope.Exit();
Craig Topper161e4db2014-05-21 06:02:52 +0000535 Actions.ActOnFinishFunctionBody(LM.D, nullptr);
David Majnemera7ea1b12015-01-13 05:06:20 +0000536
537 while (Tok.isNot(tok::eof))
538 ConsumeAnyToken();
539
540 if (Tok.is(tok::eof) && Tok.getEofData() == LM.D)
Matt Beaumont-Gayd0457922011-09-23 22:39:23 +0000541 ConsumeAnyToken();
Douglas Gregorefc46952010-10-12 16:25:54 +0000542 return;
543 }
544 } else
545 Actions.ActOnDefaultCtorInitializers(LM.D);
546
Richard Smithc8378952013-04-29 11:55:38 +0000547 assert((Actions.getDiagnostics().hasErrorOccurred() ||
548 !isa<FunctionTemplateDecl>(LM.D) ||
549 cast<FunctionTemplateDecl>(LM.D)->getTemplateParameters()->getDepth()
550 < TemplateParameterDepth) &&
551 "TemplateParameterDepth should be greater than the depth of "
552 "current template being instantiated!");
553
Douglas Gregora0ff0c32011-03-16 17:05:57 +0000554 ParseFunctionStatementBody(LM.D, FnScope);
Douglas Gregorefc46952010-10-12 16:25:54 +0000555
John McCalle68672f2013-03-14 05:13:41 +0000556 // Clear the late-template-parsed bit if we set it before.
Alp Tokera2794f92014-01-22 07:29:52 +0000557 if (LM.D)
558 LM.D->getAsFunction()->setLateTemplateParsed(false);
John McCalle68672f2013-03-14 05:13:41 +0000559
David Majnemera7ea1b12015-01-13 05:06:20 +0000560 while (Tok.isNot(tok::eof))
561 ConsumeAnyToken();
562
563 if (Tok.is(tok::eof) && Tok.getEofData() == LM.D)
564 ConsumeAnyToken();
Hans Wennborga926d842014-05-23 20:37:38 +0000565
566 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(LM.D))
567 Actions.ActOnFinishInlineMethodDef(MD);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000568}
569
Richard Smith938f40b2011-06-11 17:19:42 +0000570/// ParseLexedMemberInitializers - We finished parsing the member specification
571/// of a top (non-nested) C++ class. Now go over the stack of lexed data member
572/// initializers that were collected during its parsing and parse them all.
573void Parser::ParseLexedMemberInitializers(ParsingClass &Class) {
574 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
575 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
576 HasTemplateScope);
Richard Smithc8378952013-04-29 11:55:38 +0000577 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
578 if (HasTemplateScope) {
Richard Smith938f40b2011-06-11 17:19:42 +0000579 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
Richard Smithc8378952013-04-29 11:55:38 +0000580 ++CurTemplateDepthTracker;
581 }
Douglas Gregor3024f072012-04-16 07:05:22 +0000582 // Set or update the scope flags.
Richard Smith938f40b2011-06-11 17:19:42 +0000583 bool AlreadyHasClassScope = Class.TopLevelClass;
Douglas Gregor3024f072012-04-16 07:05:22 +0000584 unsigned ScopeFlags = Scope::ClassScope|Scope::DeclScope;
Richard Smith938f40b2011-06-11 17:19:42 +0000585 ParseScope ClassScope(this, ScopeFlags, !AlreadyHasClassScope);
586 ParseScopeFlags ClassScopeFlags(this, ScopeFlags, AlreadyHasClassScope);
587
588 if (!AlreadyHasClassScope)
589 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(),
590 Class.TagOrTemplate);
591
Benjamin Kramer1d373c62012-05-17 12:01:52 +0000592 if (!Class.LateParsedDeclarations.empty()) {
Douglas Gregor3024f072012-04-16 07:05:22 +0000593 // C++11 [expr.prim.general]p4:
594 // Otherwise, if a member-declarator declares a non-static data member
595 // (9.2) of a class X, the expression this is a prvalue of type "pointer
596 // to X" within the optional brace-or-equal-initializer. It shall not
597 // appear elsewhere in the member-declarator.
598 Sema::CXXThisScopeRAII ThisScope(Actions, Class.TagOrTemplate,
599 /*TypeQuals=*/(unsigned)0);
Richard Smith938f40b2011-06-11 17:19:42 +0000600
Douglas Gregor3024f072012-04-16 07:05:22 +0000601 for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
602 Class.LateParsedDeclarations[i]->ParseLexedMemberInitializers();
603 }
604 }
605
Richard Smith938f40b2011-06-11 17:19:42 +0000606 if (!AlreadyHasClassScope)
607 Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(),
608 Class.TagOrTemplate);
609
610 Actions.ActOnFinishDelayedMemberInitializers(Class.TagOrTemplate);
611}
612
613void Parser::ParseLexedMemberInitializer(LateParsedMemberInitializer &MI) {
Richard Smith1a526fd2011-09-29 19:42:27 +0000614 if (!MI.Field || MI.Field->isInvalidDecl())
Richard Smith938f40b2011-06-11 17:19:42 +0000615 return;
616
617 // Append the current token at the end of the new token stream so that it
618 // doesn't get lost.
619 MI.Toks.push_back(Tok);
David Blaikie2eabcc92016-02-09 18:52:09 +0000620 PP.EnterTokenStream(MI.Toks, true);
Richard Smith938f40b2011-06-11 17:19:42 +0000621
622 // Consume the previously pushed token.
Argyrios Kyrtzidisc36633c2013-03-27 23:58:17 +0000623 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
Richard Smith938f40b2011-06-11 17:19:42 +0000624
625 SourceLocation EqualLoc;
Richard Smith2b013182012-06-10 03:12:00 +0000626
Richard Smith74108172014-01-17 03:11:34 +0000627 Actions.ActOnStartCXXInClassMemberInitializer();
628
Douglas Gregor926410d2012-02-21 02:22:07 +0000629 ExprResult Init = ParseCXXMemberInitializer(MI.Field, /*IsFunction=*/false,
630 EqualLoc);
Richard Smith938f40b2011-06-11 17:19:42 +0000631
Richard Smith74108172014-01-17 03:11:34 +0000632 Actions.ActOnFinishCXXInClassMemberInitializer(MI.Field, EqualLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000633 Init.get());
Richard Smith938f40b2011-06-11 17:19:42 +0000634
635 // The next token should be our artificial terminating EOF token.
636 if (Tok.isNot(tok::eof)) {
Richard Smith95e1fb02014-08-27 03:23:12 +0000637 if (!Init.isInvalid()) {
638 SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
639 if (!EndLoc.isValid())
640 EndLoc = Tok.getLocation();
641 // No fixit; we can't recover as if there were a semicolon here.
642 Diag(EndLoc, diag::err_expected_semi_decl_list);
643 }
Richard Smith938f40b2011-06-11 17:19:42 +0000644
645 // Consume tokens until we hit the artificial EOF.
646 while (Tok.isNot(tok::eof))
647 ConsumeAnyToken();
648 }
David Majnemer2d3663e2014-12-18 09:57:31 +0000649 // Make sure this is *our* artificial EOF token.
David Majnemerce1d3012014-12-19 02:13:56 +0000650 if (Tok.getEofData() == MI.Field)
David Majnemer2d3663e2014-12-18 09:57:31 +0000651 ConsumeAnyToken();
Richard Smith938f40b2011-06-11 17:19:42 +0000652}
653
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000654/// ConsumeAndStoreUntil - Consume and store the token at the passed token
Douglas Gregor4d87df52008-12-16 21:30:33 +0000655/// container until the token 'T' is reached (which gets
Mike Stump11289f42009-09-09 15:08:12 +0000656/// consumed/stored too, if ConsumeFinalToken).
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000657/// If StopAtSemi is true, then we will stop early at a ';' character.
Douglas Gregor4d87df52008-12-16 21:30:33 +0000658/// Returns true if token 'T1' or 'T2' was found.
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000659/// NOTE: This is a specialized version of Parser::SkipUntil.
Douglas Gregor4d87df52008-12-16 21:30:33 +0000660bool Parser::ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
661 CachedTokens &Toks,
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000662 bool StopAtSemi, bool ConsumeFinalToken) {
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000663 // We always want this function to consume at least one token if the first
664 // token isn't T and if not at EOF.
665 bool isFirstTokenConsumed = true;
666 while (1) {
667 // If we found one of the tokens, stop and return true.
Douglas Gregor4d87df52008-12-16 21:30:33 +0000668 if (Tok.is(T1) || Tok.is(T2)) {
669 if (ConsumeFinalToken) {
670 Toks.push_back(Tok);
671 ConsumeAnyToken();
672 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000673 return true;
674 }
675
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000676 switch (Tok.getKind()) {
677 case tok::eof:
Richard Smith34f30512013-11-23 04:06:09 +0000678 case tok::annot_module_begin:
679 case tok::annot_module_end:
680 case tok::annot_module_include:
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000681 // Ran out of tokens.
682 return false;
683
684 case tok::l_paren:
685 // Recursively consume properly-nested parens.
686 Toks.push_back(Tok);
687 ConsumeParen();
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000688 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000689 break;
690 case tok::l_square:
691 // Recursively consume properly-nested square brackets.
692 Toks.push_back(Tok);
693 ConsumeBracket();
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000694 ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000695 break;
696 case tok::l_brace:
697 // Recursively consume properly-nested braces.
698 Toks.push_back(Tok);
699 ConsumeBrace();
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000700 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000701 break;
702
703 // Okay, we found a ']' or '}' or ')', which we think should be balanced.
704 // Since the user wasn't looking for this token (if they were, it would
705 // already be handled), this isn't balanced. If there is a LHS token at a
706 // higher level, we will assume that this matches the unbalanced token
707 // and return it. Otherwise, this is a spurious RHS token, which we skip.
708 case tok::r_paren:
709 if (ParenCount && !isFirstTokenConsumed)
710 return false; // Matches something.
711 Toks.push_back(Tok);
712 ConsumeParen();
713 break;
714 case tok::r_square:
715 if (BracketCount && !isFirstTokenConsumed)
716 return false; // Matches something.
717 Toks.push_back(Tok);
718 ConsumeBracket();
719 break;
720 case tok::r_brace:
721 if (BraceCount && !isFirstTokenConsumed)
722 return false; // Matches something.
723 Toks.push_back(Tok);
724 ConsumeBrace();
725 break;
726
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000727 case tok::code_completion:
728 Toks.push_back(Tok);
729 ConsumeCodeCompletionToken();
730 break;
731
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000732 case tok::string_literal:
733 case tok::wide_string_literal:
Douglas Gregorfb65e592011-07-27 05:40:30 +0000734 case tok::utf8_string_literal:
735 case tok::utf16_string_literal:
736 case tok::utf32_string_literal:
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000737 Toks.push_back(Tok);
738 ConsumeStringToken();
739 break;
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000740 case tok::semi:
741 if (StopAtSemi)
742 return false;
743 // FALL THROUGH.
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000744 default:
745 // consume this token.
746 Toks.push_back(Tok);
747 ConsumeToken();
748 break;
749 }
750 isFirstTokenConsumed = false;
751 }
752}
Sebastian Redla74948d2011-09-24 17:48:25 +0000753
754/// \brief Consume tokens and store them in the passed token container until
755/// we've passed the try keyword and constructor initializers and have consumed
Sebastian Redl0d164012011-09-30 08:32:17 +0000756/// the opening brace of the function body. The opening brace will be consumed
757/// if and only if there was no error.
Sebastian Redla74948d2011-09-24 17:48:25 +0000758///
Richard Smithcde3fd82013-07-04 00:13:48 +0000759/// \return True on error.
Sebastian Redl0d164012011-09-30 08:32:17 +0000760bool Parser::ConsumeAndStoreFunctionPrologue(CachedTokens &Toks) {
Sebastian Redla74948d2011-09-24 17:48:25 +0000761 if (Tok.is(tok::kw_try)) {
762 Toks.push_back(Tok);
763 ConsumeToken();
764 }
Richard Smithcde3fd82013-07-04 00:13:48 +0000765
766 if (Tok.isNot(tok::colon)) {
767 // Easy case, just a function body.
768
769 // Grab any remaining garbage to be diagnosed later. We stop when we reach a
770 // brace: an opening one is the function body, while a closing one probably
771 // means we've reached the end of the class.
772 ConsumeAndStoreUntil(tok::l_brace, tok::r_brace, Toks,
773 /*StopAtSemi=*/true,
774 /*ConsumeFinalToken=*/false);
775 if (Tok.isNot(tok::l_brace))
Alp Tokerec543272013-12-24 09:48:30 +0000776 return Diag(Tok.getLocation(), diag::err_expected) << tok::l_brace;
Richard Smithcde3fd82013-07-04 00:13:48 +0000777
Sebastian Redla74948d2011-09-24 17:48:25 +0000778 Toks.push_back(Tok);
Richard Smithcde3fd82013-07-04 00:13:48 +0000779 ConsumeBrace();
780 return false;
Eli Friedman7cd4a9b2012-02-22 04:49:04 +0000781 }
Sebastian Redl0d164012011-09-30 08:32:17 +0000782
783 Toks.push_back(Tok);
Richard Smithcde3fd82013-07-04 00:13:48 +0000784 ConsumeToken();
785
786 // We can't reliably skip over a mem-initializer-id, because it could be
787 // a template-id involving not-yet-declared names. Given:
788 //
789 // S ( ) : a < b < c > ( e )
790 //
791 // 'e' might be an initializer or part of a template argument, depending
792 // on whether 'b' is a template.
793
794 // Track whether we might be inside a template argument. We can give
795 // significantly better diagnostics if we know that we're not.
796 bool MightBeTemplateArgument = false;
797
798 while (true) {
799 // Skip over the mem-initializer-id, if possible.
800 if (Tok.is(tok::kw_decltype)) {
801 Toks.push_back(Tok);
802 SourceLocation OpenLoc = ConsumeToken();
803 if (Tok.isNot(tok::l_paren))
804 return Diag(Tok.getLocation(), diag::err_expected_lparen_after)
805 << "decltype";
806 Toks.push_back(Tok);
807 ConsumeParen();
808 if (!ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/true)) {
Alp Tokerec543272013-12-24 09:48:30 +0000809 Diag(Tok.getLocation(), diag::err_expected) << tok::r_paren;
810 Diag(OpenLoc, diag::note_matching) << tok::l_paren;
Richard Smithcde3fd82013-07-04 00:13:48 +0000811 return true;
812 }
813 }
814 do {
815 // Walk over a component of a nested-name-specifier.
816 if (Tok.is(tok::coloncolon)) {
817 Toks.push_back(Tok);
818 ConsumeToken();
819
820 if (Tok.is(tok::kw_template)) {
821 Toks.push_back(Tok);
822 ConsumeToken();
823 }
824 }
825
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000826 if (Tok.isOneOf(tok::identifier, tok::kw_template)) {
Richard Smithcde3fd82013-07-04 00:13:48 +0000827 Toks.push_back(Tok);
828 ConsumeToken();
829 } else if (Tok.is(tok::code_completion)) {
830 Toks.push_back(Tok);
831 ConsumeCodeCompletionToken();
832 // Consume the rest of the initializers permissively.
833 // FIXME: We should be able to perform code-completion here even if
834 // there isn't a subsequent '{' token.
835 MightBeTemplateArgument = true;
836 break;
837 } else {
838 break;
839 }
840 } while (Tok.is(tok::coloncolon));
841
842 if (Tok.is(tok::less))
843 MightBeTemplateArgument = true;
844
845 if (MightBeTemplateArgument) {
846 // We may be inside a template argument list. Grab up to the start of the
847 // next parenthesized initializer or braced-init-list. This *might* be the
848 // initializer, or it might be a subexpression in the template argument
849 // list.
850 // FIXME: Count angle brackets, and clear MightBeTemplateArgument
851 // if all angles are closed.
852 if (!ConsumeAndStoreUntil(tok::l_paren, tok::l_brace, Toks,
853 /*StopAtSemi=*/true,
854 /*ConsumeFinalToken=*/false)) {
855 // We're not just missing the initializer, we're also missing the
856 // function body!
Alp Tokerec543272013-12-24 09:48:30 +0000857 return Diag(Tok.getLocation(), diag::err_expected) << tok::l_brace;
Richard Smithcde3fd82013-07-04 00:13:48 +0000858 }
859 } else if (Tok.isNot(tok::l_paren) && Tok.isNot(tok::l_brace)) {
860 // We found something weird in a mem-initializer-id.
Alp Tokerec543272013-12-24 09:48:30 +0000861 if (getLangOpts().CPlusPlus11)
862 return Diag(Tok.getLocation(), diag::err_expected_either)
863 << tok::l_paren << tok::l_brace;
864 else
865 return Diag(Tok.getLocation(), diag::err_expected) << tok::l_paren;
Richard Smithcde3fd82013-07-04 00:13:48 +0000866 }
867
868 tok::TokenKind kind = Tok.getKind();
869 Toks.push_back(Tok);
870 bool IsLParen = (kind == tok::l_paren);
871 SourceLocation OpenLoc = Tok.getLocation();
872
873 if (IsLParen) {
874 ConsumeParen();
875 } else {
876 assert(kind == tok::l_brace && "Must be left paren or brace here.");
877 ConsumeBrace();
878 // In C++03, this has to be the start of the function body, which
879 // means the initializer is malformed; we'll diagnose it later.
880 if (!getLangOpts().CPlusPlus11)
881 return false;
882 }
883
884 // Grab the initializer (or the subexpression of the template argument).
885 // FIXME: If we support lambdas here, we'll need to set StopAtSemi to false
886 // if we might be inside the braces of a lambda-expression.
Alp Tokerec543272013-12-24 09:48:30 +0000887 tok::TokenKind CloseKind = IsLParen ? tok::r_paren : tok::r_brace;
888 if (!ConsumeAndStoreUntil(CloseKind, Toks, /*StopAtSemi=*/true)) {
889 Diag(Tok, diag::err_expected) << CloseKind;
890 Diag(OpenLoc, diag::note_matching) << kind;
Richard Smithcde3fd82013-07-04 00:13:48 +0000891 return true;
892 }
893
894 // Grab pack ellipsis, if present.
895 if (Tok.is(tok::ellipsis)) {
896 Toks.push_back(Tok);
897 ConsumeToken();
898 }
899
900 // If we know we just consumed a mem-initializer, we must have ',' or '{'
901 // next.
902 if (Tok.is(tok::comma)) {
903 Toks.push_back(Tok);
904 ConsumeToken();
905 } else if (Tok.is(tok::l_brace)) {
906 // This is the function body if the ')' or '}' is immediately followed by
907 // a '{'. That cannot happen within a template argument, apart from the
908 // case where a template argument contains a compound literal:
909 //
910 // S ( ) : a < b < c > ( d ) { }
911 // // End of declaration, or still inside the template argument?
912 //
913 // ... and the case where the template argument contains a lambda:
914 //
915 // S ( ) : a < 0 && b < c > ( d ) + [ ] ( ) { return 0; }
916 // ( ) > ( ) { }
917 //
918 // FIXME: Disambiguate these cases. Note that the latter case is probably
919 // going to be made ill-formed by core issue 1607.
920 Toks.push_back(Tok);
921 ConsumeBrace();
922 return false;
923 } else if (!MightBeTemplateArgument) {
Alp Tokerec543272013-12-24 09:48:30 +0000924 return Diag(Tok.getLocation(), diag::err_expected_either) << tok::l_brace
925 << tok::comma;
Richard Smithcde3fd82013-07-04 00:13:48 +0000926 }
927 }
Sebastian Redla74948d2011-09-24 17:48:25 +0000928}
Richard Smith1fff95c2013-09-12 23:28:08 +0000929
930/// \brief Consume and store tokens from the '?' to the ':' in a conditional
931/// expression.
932bool Parser::ConsumeAndStoreConditional(CachedTokens &Toks) {
933 // Consume '?'.
934 assert(Tok.is(tok::question));
935 Toks.push_back(Tok);
936 ConsumeToken();
937
938 while (Tok.isNot(tok::colon)) {
Nico Weber77c76c52014-05-10 17:43:15 +0000939 if (!ConsumeAndStoreUntil(tok::question, tok::colon, Toks,
940 /*StopAtSemi=*/true,
941 /*ConsumeFinalToken=*/false))
Richard Smith1fff95c2013-09-12 23:28:08 +0000942 return false;
943
944 // If we found a nested conditional, consume it.
945 if (Tok.is(tok::question) && !ConsumeAndStoreConditional(Toks))
946 return false;
947 }
948
949 // Consume ':'.
950 Toks.push_back(Tok);
951 ConsumeToken();
952 return true;
953}
954
955/// \brief A tentative parsing action that can also revert token annotations.
956class Parser::UnannotatedTentativeParsingAction : public TentativeParsingAction {
957public:
958 explicit UnannotatedTentativeParsingAction(Parser &Self,
959 tok::TokenKind EndKind)
960 : TentativeParsingAction(Self), Self(Self), EndKind(EndKind) {
961 // Stash away the old token stream, so we can restore it once the
962 // tentative parse is complete.
963 TentativeParsingAction Inner(Self);
964 Self.ConsumeAndStoreUntil(EndKind, Toks, true, /*ConsumeFinalToken*/false);
965 Inner.Revert();
966 }
967
968 void RevertAnnotations() {
969 Revert();
970
971 // Put back the original tokens.
Alexey Bataevee6507d2013-11-18 08:17:37 +0000972 Self.SkipUntil(EndKind, StopAtSemi | StopBeforeMatch);
Richard Smith1fff95c2013-09-12 23:28:08 +0000973 if (Toks.size()) {
David Blaikie2eabcc92016-02-09 18:52:09 +0000974 auto Buffer = llvm::make_unique<Token[]>(Toks.size());
975 std::copy(Toks.begin() + 1, Toks.end(), Buffer.get());
Richard Smith1fff95c2013-09-12 23:28:08 +0000976 Buffer[Toks.size() - 1] = Self.Tok;
David Blaikie2eabcc92016-02-09 18:52:09 +0000977 Self.PP.EnterTokenStream(std::move(Buffer), Toks.size(), true);
Richard Smith1fff95c2013-09-12 23:28:08 +0000978
979 Self.Tok = Toks.front();
980 }
981 }
982
983private:
984 Parser &Self;
985 CachedTokens Toks;
986 tok::TokenKind EndKind;
987};
988
989/// ConsumeAndStoreInitializer - Consume and store the token at the passed token
990/// container until the end of the current initializer expression (either a
991/// default argument or an in-class initializer for a non-static data member).
Richard Smith95e1fb02014-08-27 03:23:12 +0000992///
993/// Returns \c true if we reached the end of something initializer-shaped,
994/// \c false if we bailed out.
Richard Smith1fff95c2013-09-12 23:28:08 +0000995bool Parser::ConsumeAndStoreInitializer(CachedTokens &Toks,
996 CachedInitKind CIK) {
997 // We always want this function to consume at least one token if not at EOF.
Richard Smith95e1fb02014-08-27 03:23:12 +0000998 bool IsFirstToken = true;
Richard Smith1fff95c2013-09-12 23:28:08 +0000999
1000 // Number of possible unclosed <s we've seen so far. These might be templates,
1001 // and might not, but if there were none of them (or we know for sure that
1002 // we're within a template), we can avoid a tentative parse.
1003 unsigned AngleCount = 0;
1004 unsigned KnownTemplateCount = 0;
1005
1006 while (1) {
1007 switch (Tok.getKind()) {
1008 case tok::comma:
1009 // If we might be in a template, perform a tentative parse to check.
1010 if (!AngleCount)
1011 // Not a template argument: this is the end of the initializer.
1012 return true;
1013 if (KnownTemplateCount)
1014 goto consume_token;
1015
1016 // We hit a comma inside angle brackets. This is the hard case. The
1017 // rule we follow is:
1018 // * For a default argument, if the tokens after the comma form a
1019 // syntactically-valid parameter-declaration-clause, in which each
1020 // parameter has an initializer, then this comma ends the default
1021 // argument.
1022 // * For a default initializer, if the tokens after the comma form a
1023 // syntactically-valid init-declarator-list, then this comma ends
1024 // the default initializer.
1025 {
1026 UnannotatedTentativeParsingAction PA(*this,
1027 CIK == CIK_DefaultInitializer
1028 ? tok::semi : tok::r_paren);
1029 Sema::TentativeAnalysisScope Scope(Actions);
1030
Richard Smithee390432014-05-16 01:56:53 +00001031 TPResult Result = TPResult::Error;
Richard Smith1fff95c2013-09-12 23:28:08 +00001032 ConsumeToken();
1033 switch (CIK) {
1034 case CIK_DefaultInitializer:
1035 Result = TryParseInitDeclaratorList();
1036 // If we parsed a complete, ambiguous init-declarator-list, this
1037 // is only syntactically-valid if it's followed by a semicolon.
Richard Smithee390432014-05-16 01:56:53 +00001038 if (Result == TPResult::Ambiguous && Tok.isNot(tok::semi))
1039 Result = TPResult::False;
Richard Smith1fff95c2013-09-12 23:28:08 +00001040 break;
1041
1042 case CIK_DefaultArgument:
1043 bool InvalidAsDeclaration = false;
1044 Result = TryParseParameterDeclarationClause(
Nico Weberc29c4832014-12-28 23:24:02 +00001045 &InvalidAsDeclaration, /*VersusTemplateArgument=*/true);
Richard Smith1fff95c2013-09-12 23:28:08 +00001046 // If this is an expression or a declaration with a missing
1047 // 'typename', assume it's not a declaration.
Richard Smithee390432014-05-16 01:56:53 +00001048 if (Result == TPResult::Ambiguous && InvalidAsDeclaration)
1049 Result = TPResult::False;
Richard Smith1fff95c2013-09-12 23:28:08 +00001050 break;
1051 }
1052
1053 // If what follows could be a declaration, it is a declaration.
Richard Smithee390432014-05-16 01:56:53 +00001054 if (Result != TPResult::False && Result != TPResult::Error) {
Richard Smith1fff95c2013-09-12 23:28:08 +00001055 PA.Revert();
1056 return true;
1057 }
1058
1059 // In the uncommon case that we decide the following tokens are part
1060 // of a template argument, revert any annotations we've performed in
1061 // those tokens. We're not going to look them up until we've parsed
1062 // the rest of the class, and that might add more declarations.
1063 PA.RevertAnnotations();
1064 }
1065
1066 // Keep going. We know we're inside a template argument list now.
1067 ++KnownTemplateCount;
1068 goto consume_token;
1069
1070 case tok::eof:
Richard Smith34f30512013-11-23 04:06:09 +00001071 case tok::annot_module_begin:
1072 case tok::annot_module_end:
1073 case tok::annot_module_include:
Richard Smith1fff95c2013-09-12 23:28:08 +00001074 // Ran out of tokens.
1075 return false;
1076
1077 case tok::less:
1078 // FIXME: A '<' can only start a template-id if it's preceded by an
1079 // identifier, an operator-function-id, or a literal-operator-id.
1080 ++AngleCount;
1081 goto consume_token;
1082
1083 case tok::question:
1084 // In 'a ? b : c', 'b' can contain an unparenthesized comma. If it does,
1085 // that is *never* the end of the initializer. Skip to the ':'.
1086 if (!ConsumeAndStoreConditional(Toks))
1087 return false;
1088 break;
1089
1090 case tok::greatergreatergreater:
1091 if (!getLangOpts().CPlusPlus11)
1092 goto consume_token;
1093 if (AngleCount) --AngleCount;
1094 if (KnownTemplateCount) --KnownTemplateCount;
1095 // Fall through.
1096 case tok::greatergreater:
1097 if (!getLangOpts().CPlusPlus11)
1098 goto consume_token;
1099 if (AngleCount) --AngleCount;
1100 if (KnownTemplateCount) --KnownTemplateCount;
1101 // Fall through.
1102 case tok::greater:
1103 if (AngleCount) --AngleCount;
1104 if (KnownTemplateCount) --KnownTemplateCount;
1105 goto consume_token;
1106
1107 case tok::kw_template:
1108 // 'template' identifier '<' is known to start a template argument list,
1109 // and can be used to disambiguate the parse.
1110 // FIXME: Support all forms of 'template' unqualified-id '<'.
1111 Toks.push_back(Tok);
1112 ConsumeToken();
1113 if (Tok.is(tok::identifier)) {
1114 Toks.push_back(Tok);
1115 ConsumeToken();
1116 if (Tok.is(tok::less)) {
Richard Smith93033572014-07-27 05:38:12 +00001117 ++AngleCount;
Richard Smith1fff95c2013-09-12 23:28:08 +00001118 ++KnownTemplateCount;
1119 Toks.push_back(Tok);
1120 ConsumeToken();
1121 }
1122 }
1123 break;
1124
1125 case tok::kw_operator:
1126 // If 'operator' precedes other punctuation, that punctuation loses
1127 // its special behavior.
1128 Toks.push_back(Tok);
1129 ConsumeToken();
1130 switch (Tok.getKind()) {
1131 case tok::comma:
1132 case tok::greatergreatergreater:
1133 case tok::greatergreater:
1134 case tok::greater:
1135 case tok::less:
1136 Toks.push_back(Tok);
1137 ConsumeToken();
1138 break;
1139 default:
1140 break;
1141 }
1142 break;
1143
1144 case tok::l_paren:
1145 // Recursively consume properly-nested parens.
1146 Toks.push_back(Tok);
1147 ConsumeParen();
1148 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
1149 break;
1150 case tok::l_square:
1151 // Recursively consume properly-nested square brackets.
1152 Toks.push_back(Tok);
1153 ConsumeBracket();
1154 ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false);
1155 break;
1156 case tok::l_brace:
1157 // Recursively consume properly-nested braces.
1158 Toks.push_back(Tok);
1159 ConsumeBrace();
1160 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1161 break;
1162
1163 // Okay, we found a ']' or '}' or ')', which we think should be balanced.
1164 // Since the user wasn't looking for this token (if they were, it would
1165 // already be handled), this isn't balanced. If there is a LHS token at a
1166 // higher level, we will assume that this matches the unbalanced token
Richard Smith95e1fb02014-08-27 03:23:12 +00001167 // and return it. Otherwise, this is a spurious RHS token, which we
1168 // consume and pass on to downstream code to diagnose.
Richard Smith1fff95c2013-09-12 23:28:08 +00001169 case tok::r_paren:
1170 if (CIK == CIK_DefaultArgument)
1171 return true; // End of the default argument.
Richard Smith95e1fb02014-08-27 03:23:12 +00001172 if (ParenCount && !IsFirstToken)
1173 return false;
1174 Toks.push_back(Tok);
1175 ConsumeParen();
1176 continue;
Richard Smith1fff95c2013-09-12 23:28:08 +00001177 case tok::r_square:
Richard Smith95e1fb02014-08-27 03:23:12 +00001178 if (BracketCount && !IsFirstToken)
1179 return false;
1180 Toks.push_back(Tok);
1181 ConsumeBracket();
1182 continue;
Richard Smith1fff95c2013-09-12 23:28:08 +00001183 case tok::r_brace:
Richard Smith95e1fb02014-08-27 03:23:12 +00001184 if (BraceCount && !IsFirstToken)
1185 return false;
1186 Toks.push_back(Tok);
1187 ConsumeBrace();
1188 continue;
Richard Smith1fff95c2013-09-12 23:28:08 +00001189
1190 case tok::code_completion:
1191 Toks.push_back(Tok);
1192 ConsumeCodeCompletionToken();
1193 break;
1194
1195 case tok::string_literal:
1196 case tok::wide_string_literal:
1197 case tok::utf8_string_literal:
1198 case tok::utf16_string_literal:
1199 case tok::utf32_string_literal:
1200 Toks.push_back(Tok);
1201 ConsumeStringToken();
1202 break;
1203 case tok::semi:
1204 if (CIK == CIK_DefaultInitializer)
1205 return true; // End of the default initializer.
1206 // FALL THROUGH.
1207 default:
1208 consume_token:
1209 Toks.push_back(Tok);
1210 ConsumeToken();
1211 break;
1212 }
Richard Smith95e1fb02014-08-27 03:23:12 +00001213 IsFirstToken = false;
Richard Smith1fff95c2013-09-12 23:28:08 +00001214 }
1215}