blob: 5da70d025e561ea791cd30a0361ebc1fd6b5659c [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,
Douglas Gregor5d1b4e32011-11-07 20:56:01 +000030 ExprResult& Init) {
Abramo Bagnara924a8f32010-12-10 16:29:40 +000031 assert(D.isFunctionDeclarator() && "This isn't a function declarator!");
Alexis Hunt5a7fa252011-05-12 06:15:49 +000032 assert((Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try) ||
33 Tok.is(tok::equal)) &&
34 "Current token not a '{', ':', '=', or 'try'!");
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +000035
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000036 MultiTemplateParamsArg TemplateParams(
Craig Topper161e4db2014-05-21 06:02:52 +000037 TemplateInfo.TemplateParams ? TemplateInfo.TemplateParams->data()
38 : nullptr,
Nico Weber77c76c52014-05-10 17:43:15 +000039 TemplateInfo.TemplateParams ? TemplateInfo.TemplateParams->size() : 0);
Alexis Hunt1deb9722010-04-14 23:07:37 +000040
Rafael Espindolac2453dd2013-01-08 21:00:12 +000041 NamedDecl *FnD;
John McCall07e91c02009-08-06 02:15:43 +000042 if (D.getDeclSpec().isFriendSpecified())
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000043 FnD = Actions.ActOnFriendFunctionDecl(getCurScope(), D,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000044 TemplateParams);
Douglas Gregor728d00b2011-10-10 14:49:18 +000045 else {
Douglas Gregor0be31a22010-07-02 17:43:08 +000046 FnD = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS, D,
Craig Topper161e4db2014-05-21 06:02:52 +000047 TemplateParams, nullptr,
Richard Smith2b013182012-06-10 03:12:00 +000048 VS, ICIS_NoInit);
Douglas Gregor728d00b2011-10-10 14:49:18 +000049 if (FnD) {
Richard Smithf8a75c32013-08-29 00:47:48 +000050 Actions.ProcessDeclAttributeList(getCurScope(), FnD, AccessAttrs);
Richard Smith74aeef52013-04-26 16:15:35 +000051 bool TypeSpecContainsAuto = D.getDeclSpec().containsPlaceholderType();
Douglas Gregor50cefbf2011-10-17 17:09:53 +000052 if (Init.isUsable())
Larisse Voufo39a1e502013-08-06 01:03:05 +000053 Actions.AddInitializerToDecl(FnD, Init.get(), false,
Douglas Gregor728d00b2011-10-10 14:49:18 +000054 TypeSpecContainsAuto);
55 else
56 Actions.ActOnUninitializedDecl(FnD, TypeSpecContainsAuto);
57 }
Nico Weber24b2a822011-01-28 06:07:34 +000058 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +000059
Douglas Gregor433e0532012-04-16 18:27:27 +000060 HandleMemberFunctionDeclDelays(D, FnD);
Eli Friedman3af2a772009-07-22 21:45:50 +000061
John McCallc1465822011-02-14 07:13:47 +000062 D.complete(FnD);
63
Alp Tokera3ebe6e2013-12-17 14:12:37 +000064 if (TryConsumeToken(tok::equal)) {
Richard Smith1c704732011-11-10 09:08:44 +000065 if (!FnD) {
66 SkipUntil(tok::semi);
Craig Topper161e4db2014-05-21 06:02:52 +000067 return nullptr;
Richard Smith1c704732011-11-10 09:08:44 +000068 }
69
Alexis Hunt5a7fa252011-05-12 06:15:49 +000070 bool Delete = false;
71 SourceLocation KWLoc;
Eli Bendersky5f4d76e2015-03-23 21:43:28 +000072 SourceLocation KWEndLoc = Tok.getEndLoc().getLocWithOffset(-1);
Alp Tokera3ebe6e2013-12-17 14:12:37 +000073 if (TryConsumeToken(tok::kw_delete, KWLoc)) {
74 Diag(KWLoc, getLangOpts().CPlusPlus11
75 ? diag::warn_cxx98_compat_deleted_function
76 : diag::ext_deleted_function);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000077 Actions.SetDeclDeleted(FnD, KWLoc);
78 Delete = true;
Eli Bendersky5f4d76e2015-03-23 21:43:28 +000079 if (auto *DeclAsFunction = dyn_cast<FunctionDecl>(FnD)) {
80 DeclAsFunction->setRangeEnd(KWEndLoc);
81 }
Alp Tokera3ebe6e2013-12-17 14:12:37 +000082 } else if (TryConsumeToken(tok::kw_default, KWLoc)) {
83 Diag(KWLoc, getLangOpts().CPlusPlus11
84 ? diag::warn_cxx98_compat_defaulted_function
85 : diag::ext_defaulted_function);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000086 Actions.SetDeclDefaulted(FnD, KWLoc);
Eli Bendersky5f4d76e2015-03-23 21:43:28 +000087 if (auto *DeclAsFunction = dyn_cast<FunctionDecl>(FnD)) {
88 DeclAsFunction->setRangeEnd(KWEndLoc);
89 }
Alexis Hunt5a7fa252011-05-12 06:15:49 +000090 } else {
91 llvm_unreachable("function definition after = not 'delete' or 'default'");
92 }
93
94 if (Tok.is(tok::comma)) {
95 Diag(KWLoc, diag::err_default_delete_in_multiple_declaration)
96 << Delete;
97 SkipUntil(tok::semi);
Alp Toker383d2c42014-01-01 03:08:43 +000098 } else if (ExpectAndConsume(tok::semi, diag::err_expected_after,
99 Delete ? "delete" : "default")) {
100 SkipUntil(tok::semi);
Alexis Hunt5a7fa252011-05-12 06:15:49 +0000101 }
102
103 return FnD;
104 }
Eli Bendersky41842222015-03-23 23:49:41 +0000105
Francois Pichet1c229c02011-04-22 22:18:13 +0000106 // In delayed template parsing mode, if we are within a class template
107 // or if we are about to parse function member template then consume
108 // the tokens and store them for parsing at the end of the translation unit.
David Majnemer90b17292013-09-14 05:46:42 +0000109 if (getLangOpts().DelayedTemplateParsing &&
Eli Bendersky41842222015-03-23 23:49:41 +0000110 D.getFunctionDefinitionKind() == FDK_Definition &&
Alp Tokera2794f92014-01-22 07:29:52 +0000111 !D.getDeclSpec().isConstexprSpecified() &&
112 !(FnD && FnD->getAsFunction() &&
Alp Toker314cc812014-01-25 16:55:45 +0000113 FnD->getAsFunction()->getReturnType()->getContainedAutoType()) &&
Francois Pichet1c229c02011-04-22 22:18:13 +0000114 ((Actions.CurContext->isDependentContext() ||
David Majnemer90b17292013-09-14 05:46:42 +0000115 (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
116 TemplateInfo.Kind != ParsedTemplateInfo::ExplicitSpecialization)) &&
117 !Actions.IsInsideALocalClassWithinATemplateFunction())) {
Francois Pichet1c229c02011-04-22 22:18:13 +0000118
Richard Smithe40f2ba2013-08-07 21:41:30 +0000119 CachedTokens Toks;
120 LexTemplateFunctionForLateParsing(Toks);
Francois Pichet1c229c02011-04-22 22:18:13 +0000121
Richard Smithe40f2ba2013-08-07 21:41:30 +0000122 if (FnD) {
Alp Tokera2794f92014-01-22 07:29:52 +0000123 FunctionDecl *FD = FnD->getAsFunction();
Chandler Carruthbc0f9ae2011-04-25 07:09:43 +0000124 Actions.CheckForFunctionRedefinition(FD);
Richard Smithe40f2ba2013-08-07 21:41:30 +0000125 Actions.MarkAsLateParsedTemplate(FD, FnD, Toks);
Francois Pichet1c229c02011-04-22 22:18:13 +0000126 }
127
128 return FnD;
129 }
130
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000131 // Consume the tokens and store them for later parsing.
132
Douglas Gregorefc46952010-10-12 16:25:54 +0000133 LexedMethod* LM = new LexedMethod(this, FnD);
134 getCurrentClass().LateParsedDeclarations.push_back(LM);
135 LM->TemplateScope = getCurScope()->isTemplateParamScope();
136 CachedTokens &Toks = LM->Toks;
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000137
Sebastian Redla7b98a72009-04-26 20:35:05 +0000138 tok::TokenKind kind = Tok.getKind();
Sebastian Redl0d164012011-09-30 08:32:17 +0000139 // Consume everything up to (and including) the left brace of the
140 // function body.
141 if (ConsumeAndStoreFunctionPrologue(Toks)) {
142 // We didn't find the left-brace we expected after the
Eli Friedman7cd4a9b2012-02-22 04:49:04 +0000143 // constructor initializer; we already printed an error, and it's likely
144 // impossible to recover, so don't try to parse this method later.
Richard Smithcde3fd82013-07-04 00:13:48 +0000145 // Skip over the rest of the decl and back to somewhere that looks
146 // reasonable.
147 SkipMalformedDecl();
Eli Friedman7cd4a9b2012-02-22 04:49:04 +0000148 delete getCurrentClass().LateParsedDeclarations.back();
149 getCurrentClass().LateParsedDeclarations.pop_back();
150 return FnD;
Douglas Gregore8381c02008-11-05 04:29:56 +0000151 } else {
Sebastian Redl0d164012011-09-30 08:32:17 +0000152 // Consume everything up to (and including) the matching right brace.
153 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
Douglas Gregore8381c02008-11-05 04:29:56 +0000154 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000155
Sebastian Redla7b98a72009-04-26 20:35:05 +0000156 // If we're in a function-try-block, we need to store all the catch blocks.
157 if (kind == tok::kw_try) {
158 while (Tok.is(tok::kw_catch)) {
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000159 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
160 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
Sebastian Redla7b98a72009-04-26 20:35:05 +0000161 }
162 }
163
Stephen Lin9354fc52013-06-23 07:37:13 +0000164 if (FnD) {
165 // If this is a friend function, mark that it's late-parsed so that
166 // it's still known to be a definition even before we attach the
167 // parsed body. Sema needs to treat friend function definitions
168 // differently during template instantiation, and it's possible for
169 // the containing class to be instantiated before all its member
170 // function definitions are parsed.
171 //
172 // If you remove this, you can remove the code that clears the flag
173 // after parsing the member.
174 if (D.getDeclSpec().isFriendSpecified()) {
Alp Tokera2794f92014-01-22 07:29:52 +0000175 FunctionDecl *FD = FnD->getAsFunction();
Alp Toker19bff322013-10-18 05:54:24 +0000176 Actions.CheckForFunctionRedefinition(FD);
177 FD->setLateTemplateParsed(true);
Stephen Lin9354fc52013-06-23 07:37:13 +0000178 }
179 } else {
Douglas Gregor6ca64102011-04-14 23:19:27 +0000180 // If semantic analysis could not build a function declaration,
181 // just throw away the late-parsed declaration.
182 delete getCurrentClass().LateParsedDeclarations.back();
183 getCurrentClass().LateParsedDeclarations.pop_back();
184 }
185
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000186 return FnD;
187}
188
Richard Smith938f40b2011-06-11 17:19:42 +0000189/// ParseCXXNonStaticMemberInitializer - We parsed and verified that the
190/// specified Declarator is a well formed C++ non-static data member
191/// declaration. Now lex its initializer and store its tokens for parsing
192/// after the class is complete.
193void Parser::ParseCXXNonStaticMemberInitializer(Decl *VarD) {
194 assert((Tok.is(tok::l_brace) || Tok.is(tok::equal)) &&
195 "Current token not a '{' or '='!");
196
197 LateParsedMemberInitializer *MI =
198 new LateParsedMemberInitializer(this, VarD);
199 getCurrentClass().LateParsedDeclarations.push_back(MI);
200 CachedTokens &Toks = MI->Toks;
201
202 tok::TokenKind kind = Tok.getKind();
203 if (kind == tok::equal) {
204 Toks.push_back(Tok);
Douglas Gregor0cf55e92012-03-08 01:00:17 +0000205 ConsumeToken();
Richard Smith938f40b2011-06-11 17:19:42 +0000206 }
207
208 if (kind == tok::l_brace) {
209 // Begin by storing the '{' token.
210 Toks.push_back(Tok);
211 ConsumeBrace();
212
213 // Consume everything up to (and including) the matching right brace.
214 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/true);
215 } else {
216 // Consume everything up to (but excluding) the comma or semicolon.
Richard Smith1fff95c2013-09-12 23:28:08 +0000217 ConsumeAndStoreInitializer(Toks, CIK_DefaultInitializer);
Richard Smith938f40b2011-06-11 17:19:42 +0000218 }
219
220 // Store an artificial EOF token to ensure that we don't run off the end of
221 // the initializer when we come to parse it.
222 Token Eof;
223 Eof.startToken();
224 Eof.setKind(tok::eof);
225 Eof.setLocation(Tok.getLocation());
David Majnemerce1d3012014-12-19 02:13:56 +0000226 Eof.setEofData(VarD);
Richard Smith938f40b2011-06-11 17:19:42 +0000227 Toks.push_back(Eof);
228}
229
Douglas Gregorefc46952010-10-12 16:25:54 +0000230Parser::LateParsedDeclaration::~LateParsedDeclaration() {}
231void Parser::LateParsedDeclaration::ParseLexedMethodDeclarations() {}
Richard Smith938f40b2011-06-11 17:19:42 +0000232void Parser::LateParsedDeclaration::ParseLexedMemberInitializers() {}
Douglas Gregorefc46952010-10-12 16:25:54 +0000233void Parser::LateParsedDeclaration::ParseLexedMethodDefs() {}
234
235Parser::LateParsedClass::LateParsedClass(Parser *P, ParsingClass *C)
236 : Self(P), Class(C) {}
237
238Parser::LateParsedClass::~LateParsedClass() {
239 Self->DeallocateParsedClasses(Class);
240}
241
242void Parser::LateParsedClass::ParseLexedMethodDeclarations() {
243 Self->ParseLexedMethodDeclarations(*Class);
244}
245
Richard Smith938f40b2011-06-11 17:19:42 +0000246void Parser::LateParsedClass::ParseLexedMemberInitializers() {
247 Self->ParseLexedMemberInitializers(*Class);
248}
249
Douglas Gregorefc46952010-10-12 16:25:54 +0000250void Parser::LateParsedClass::ParseLexedMethodDefs() {
251 Self->ParseLexedMethodDefs(*Class);
252}
253
254void Parser::LateParsedMethodDeclaration::ParseLexedMethodDeclarations() {
255 Self->ParseLexedMethodDeclaration(*this);
256}
257
258void Parser::LexedMethod::ParseLexedMethodDefs() {
259 Self->ParseLexedMethodDef(*this);
260}
261
Richard Smith938f40b2011-06-11 17:19:42 +0000262void Parser::LateParsedMemberInitializer::ParseLexedMemberInitializers() {
263 Self->ParseLexedMemberInitializer(*this);
264}
265
Douglas Gregor4d87df52008-12-16 21:30:33 +0000266/// ParseLexedMethodDeclarations - We finished parsing the member
267/// specification of a top (non-nested) C++ class. Now go over the
268/// stack of method declarations with some parts for which parsing was
269/// delayed (such as default arguments) and parse them.
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000270void Parser::ParseLexedMethodDeclarations(ParsingClass &Class) {
271 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
Nico Weber77c76c52014-05-10 17:43:15 +0000272 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
273 HasTemplateScope);
Richard Smithc8378952013-04-29 11:55:38 +0000274 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
275 if (HasTemplateScope) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000276 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
Richard Smithc8378952013-04-29 11:55:38 +0000277 ++CurTemplateDepthTracker;
278 }
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000279
John McCall6df5fef2009-12-19 10:49:29 +0000280 // The current scope is still active if we're the top-level class.
281 // Otherwise we'll need to push and enter a new scope.
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000282 bool HasClassScope = !Class.TopLevelClass;
Alexis Hunt1deb9722010-04-14 23:07:37 +0000283 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope,
284 HasClassScope);
John McCall6df5fef2009-12-19 10:49:29 +0000285 if (HasClassScope)
Nico Weber77c76c52014-05-10 17:43:15 +0000286 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(),
287 Class.TagOrTemplate);
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000288
Douglas Gregorefc46952010-10-12 16:25:54 +0000289 for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
290 Class.LateParsedDeclarations[i]->ParseLexedMethodDeclarations();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000291 }
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000292
John McCall6df5fef2009-12-19 10:49:29 +0000293 if (HasClassScope)
Nico Weber77c76c52014-05-10 17:43:15 +0000294 Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(),
295 Class.TagOrTemplate);
Douglas Gregor4d87df52008-12-16 21:30:33 +0000296}
297
Douglas Gregorefc46952010-10-12 16:25:54 +0000298void Parser::ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM) {
299 // If this is a member template, introduce the template parameter scope.
300 ParseScope TemplateScope(this, Scope::TemplateParamScope, LM.TemplateScope);
Richard Smithc8378952013-04-29 11:55:38 +0000301 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
302 if (LM.TemplateScope) {
Douglas Gregorefc46952010-10-12 16:25:54 +0000303 Actions.ActOnReenterTemplateScope(getCurScope(), LM.Method);
Richard Smithc8378952013-04-29 11:55:38 +0000304 ++CurTemplateDepthTracker;
305 }
Douglas Gregorefc46952010-10-12 16:25:54 +0000306 // Start the delayed C++ method declaration
307 Actions.ActOnStartDelayedCXXMethodDeclaration(getCurScope(), LM.Method);
308
309 // Introduce the parameters into scope and parse their default
310 // arguments.
Richard Smithe233fbf2013-01-28 22:42:45 +0000311 ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
312 Scope::FunctionDeclarationScope | Scope::DeclScope);
Douglas Gregorefc46952010-10-12 16:25:54 +0000313 for (unsigned I = 0, N = LM.DefaultArgs.size(); I != N; ++I) {
Nathan Sidwell5bb231c2015-02-19 14:03:22 +0000314 auto Param = cast<ParmVarDecl>(LM.DefaultArgs[I].Param);
Douglas Gregorefc46952010-10-12 16:25:54 +0000315 // Introduce the parameter into scope.
Nathan Sidwell5bb231c2015-02-19 14:03:22 +0000316 bool HasUnparsed = Param->hasUnparsedDefaultArg();
Nathan Sidwell55d53fe2015-01-30 14:21:35 +0000317 Actions.ActOnDelayedCXXMethodParameter(getCurScope(), Param);
Douglas Gregorefc46952010-10-12 16:25:54 +0000318 if (CachedTokens *Toks = LM.DefaultArgs[I].Toks) {
David Majnemer7cceba52015-01-13 04:20:57 +0000319 // Mark the end of the default argument so that we know when to stop when
320 // we parse it later on.
321 Token LastDefaultArgToken = Toks->back();
322 Token DefArgEnd;
323 DefArgEnd.startToken();
324 DefArgEnd.setKind(tok::eof);
David Majnemera8f2f1d2015-03-19 00:10:23 +0000325 DefArgEnd.setLocation(LastDefaultArgToken.getEndLoc());
Nathan Sidwell55d53fe2015-01-30 14:21:35 +0000326 DefArgEnd.setEofData(Param);
David Majnemer7cceba52015-01-13 04:20:57 +0000327 Toks->push_back(DefArgEnd);
Douglas Gregorefc46952010-10-12 16:25:54 +0000328
329 // Parse the default argument from its saved token stream.
330 Toks->push_back(Tok); // So that the current token doesn't get lost
331 PP.EnterTokenStream(&Toks->front(), Toks->size(), true, false);
332
333 // Consume the previously-pushed token.
334 ConsumeAnyToken();
335
336 // Consume the '='.
337 assert(Tok.is(tok::equal) && "Default argument not starting with '='");
338 SourceLocation EqualLoc = ConsumeToken();
339
340 // The argument isn't actually potentially evaluated unless it is
341 // used.
342 EnterExpressionEvaluationContext Eval(Actions,
Douglas Gregor7fcbd902012-02-21 00:37:24 +0000343 Sema::PotentiallyEvaluatedIfUsed,
Nathan Sidwell55d53fe2015-01-30 14:21:35 +0000344 Param);
Douglas Gregorefc46952010-10-12 16:25:54 +0000345
Sebastian Redldb63af22012-03-14 15:54:00 +0000346 ExprResult DefArgResult;
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000347 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
Sebastian Redl6db0b1b2012-03-20 21:24:03 +0000348 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
Sebastian Redldb63af22012-03-14 15:54:00 +0000349 DefArgResult = ParseBraceInitializer();
Sebastian Redl6db0b1b2012-03-20 21:24:03 +0000350 } else
Sebastian Redldb63af22012-03-14 15:54:00 +0000351 DefArgResult = ParseAssignmentExpression();
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000352 DefArgResult = Actions.CorrectDelayedTyposInExpr(DefArgResult);
David Majnemerbba12342015-01-12 06:51:15 +0000353 if (DefArgResult.isInvalid()) {
Nathan Sidwell55d53fe2015-01-30 14:21:35 +0000354 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
David Majnemerbba12342015-01-12 06:51:15 +0000355 } else {
Nathan Sidwell55d53fe2015-01-30 14:21:35 +0000356 if (Tok.isNot(tok::eof) || Tok.getEofData() != Param) {
Richard Smith1fff95c2013-09-12 23:28:08 +0000357 // The last two tokens are the terminator and the saved value of
358 // Tok; the last token in the default argument is the one before
359 // those.
360 assert(Toks->size() >= 3 && "expected a token in default arg");
361 Diag(Tok.getLocation(), diag::err_default_arg_unparsed)
362 << SourceRange(Tok.getLocation(),
363 (*Toks)[Toks->size() - 3].getLocation());
364 }
Nathan Sidwell55d53fe2015-01-30 14:21:35 +0000365 Actions.ActOnParamDefaultArgument(Param, EqualLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000366 DefArgResult.get());
Douglas Gregorefc46952010-10-12 16:25:54 +0000367 }
368
Douglas Gregorefc46952010-10-12 16:25:54 +0000369 // There could be leftover tokens (e.g. because of an error).
David Majnemer7cceba52015-01-13 04:20:57 +0000370 // Skip through until we reach the 'end of default argument' token.
371 while (Tok.isNot(tok::eof))
Douglas Gregorefc46952010-10-12 16:25:54 +0000372 ConsumeAnyToken();
David Majnemer7cceba52015-01-13 04:20:57 +0000373
Nathan Sidwell55d53fe2015-01-30 14:21:35 +0000374 if (Tok.is(tok::eof) && Tok.getEofData() == Param)
David Majnemer7cceba52015-01-13 04:20:57 +0000375 ConsumeAnyToken();
Douglas Gregorefc46952010-10-12 16:25:54 +0000376
377 delete Toks;
Craig Topper161e4db2014-05-21 06:02:52 +0000378 LM.DefaultArgs[I].Toks = nullptr;
Nathan Sidwell5bb231c2015-02-19 14:03:22 +0000379 } else if (HasUnparsed) {
380 assert(Param->hasInheritedDefaultArg());
381 FunctionDecl *Old = cast<FunctionDecl>(LM.Method)->getPreviousDecl();
382 ParmVarDecl *OldParam = Old->getParamDecl(I);
383 assert (!OldParam->hasUnparsedDefaultArg());
384 if (OldParam->hasUninstantiatedDefaultArg())
385 Param->setUninstantiatedDefaultArg(
386 Param->getUninstantiatedDefaultArg());
387 else
388 Param->setDefaultArg(OldParam->getInit());
Douglas Gregorefc46952010-10-12 16:25:54 +0000389 }
390 }
Douglas Gregor433e0532012-04-16 18:27:27 +0000391
Richard Smith0b3a4622014-11-13 20:01:57 +0000392 // Parse a delayed exception-specification, if there is one.
393 if (CachedTokens *Toks = LM.ExceptionSpecTokens) {
David Majnemer7cceba52015-01-13 04:20:57 +0000394 // Add the 'stop' token.
395 Token LastExceptionSpecToken = Toks->back();
396 Token ExceptionSpecEnd;
397 ExceptionSpecEnd.startToken();
398 ExceptionSpecEnd.setKind(tok::eof);
David Majnemera8f2f1d2015-03-19 00:10:23 +0000399 ExceptionSpecEnd.setLocation(LastExceptionSpecToken.getEndLoc());
David Majnemer7cceba52015-01-13 04:20:57 +0000400 ExceptionSpecEnd.setEofData(LM.Method);
401 Toks->push_back(ExceptionSpecEnd);
Richard Smith0b3a4622014-11-13 20:01:57 +0000402
403 // Parse the default argument from its saved token stream.
404 Toks->push_back(Tok); // So that the current token doesn't get lost
405 PP.EnterTokenStream(&Toks->front(), Toks->size(), true, false);
406
407 // Consume the previously-pushed token.
408 ConsumeAnyToken();
409
410 // C++11 [expr.prim.general]p3:
411 // If a declaration declares a member function or member function
412 // template of a class X, the expression this is a prvalue of type
413 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
414 // and the end of the function-definition, member-declarator, or
415 // declarator.
416 CXXMethodDecl *Method;
417 if (FunctionTemplateDecl *FunTmpl
418 = dyn_cast<FunctionTemplateDecl>(LM.Method))
419 Method = cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
420 else
421 Method = cast<CXXMethodDecl>(LM.Method);
422
423 Sema::CXXThisScopeRAII ThisScope(Actions, Method->getParent(),
424 Method->getTypeQualifiers(),
425 getLangOpts().CPlusPlus11);
426
427 // Parse the exception-specification.
428 SourceRange SpecificationRange;
429 SmallVector<ParsedType, 4> DynamicExceptions;
430 SmallVector<SourceRange, 4> DynamicExceptionRanges;
431 ExprResult NoexceptExpr;
432 CachedTokens *ExceptionSpecTokens;
433
434 ExceptionSpecificationType EST
435 = tryParseExceptionSpecification(/*Delayed=*/false, SpecificationRange,
436 DynamicExceptions,
437 DynamicExceptionRanges, NoexceptExpr,
438 ExceptionSpecTokens);
439
David Majnemer7cceba52015-01-13 04:20:57 +0000440 if (Tok.isNot(tok::eof) || Tok.getEofData() != LM.Method)
Richard Smith0b3a4622014-11-13 20:01:57 +0000441 Diag(Tok.getLocation(), diag::err_except_spec_unparsed);
442
443 // Attach the exception-specification to the method.
Richard Smith3ef3e892014-11-20 22:32:11 +0000444 Actions.actOnDelayedExceptionSpecification(LM.Method, EST,
445 SpecificationRange,
446 DynamicExceptions,
447 DynamicExceptionRanges,
448 NoexceptExpr.isUsable()?
449 NoexceptExpr.get() : nullptr);
Richard Smith0b3a4622014-11-13 20:01:57 +0000450
Richard Smith0b3a4622014-11-13 20:01:57 +0000451 // There could be leftover tokens (e.g. because of an error).
452 // Skip through until we reach the original token position.
David Majnemer7cceba52015-01-13 04:20:57 +0000453 while (Tok.isNot(tok::eof))
Richard Smith0b3a4622014-11-13 20:01:57 +0000454 ConsumeAnyToken();
David Majnemer7cceba52015-01-13 04:20:57 +0000455
456 // Clean up the remaining EOF token.
457 if (Tok.is(tok::eof) && Tok.getEofData() == LM.Method)
458 ConsumeAnyToken();
Richard Smith0b3a4622014-11-13 20:01:57 +0000459
460 delete Toks;
461 LM.ExceptionSpecTokens = nullptr;
462 }
463
Douglas Gregorefc46952010-10-12 16:25:54 +0000464 PrototypeScope.Exit();
465
466 // Finish the delayed C++ method declaration.
467 Actions.ActOnFinishDelayedCXXMethodDeclaration(getCurScope(), LM.Method);
468}
469
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000470/// ParseLexedMethodDefs - We finished parsing the member specification of a top
471/// (non-nested) C++ class. Now go over the stack of lexed methods that were
472/// collected during its parsing and parse them all.
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000473void Parser::ParseLexedMethodDefs(ParsingClass &Class) {
474 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
Douglas Gregorefc46952010-10-12 16:25:54 +0000475 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope, HasTemplateScope);
Richard Smithc8378952013-04-29 11:55:38 +0000476 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
477 if (HasTemplateScope) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000478 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
Richard Smithc8378952013-04-29 11:55:38 +0000479 ++CurTemplateDepthTracker;
480 }
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000481 bool HasClassScope = !Class.TopLevelClass;
482 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope,
483 HasClassScope);
484
Douglas Gregorefc46952010-10-12 16:25:54 +0000485 for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
486 Class.LateParsedDeclarations[i]->ParseLexedMethodDefs();
487 }
488}
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000489
Douglas Gregorefc46952010-10-12 16:25:54 +0000490void Parser::ParseLexedMethodDef(LexedMethod &LM) {
491 // If this is a member template, introduce the template parameter scope.
492 ParseScope TemplateScope(this, Scope::TemplateParamScope, LM.TemplateScope);
Richard Smithc8378952013-04-29 11:55:38 +0000493 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
494 if (LM.TemplateScope) {
Douglas Gregorefc46952010-10-12 16:25:54 +0000495 Actions.ActOnReenterTemplateScope(getCurScope(), LM.D);
Richard Smithc8378952013-04-29 11:55:38 +0000496 ++CurTemplateDepthTracker;
497 }
Argyrios Kyrtzidis02041972010-03-31 00:38:09 +0000498
Douglas Gregorefc46952010-10-12 16:25:54 +0000499 assert(!LM.Toks.empty() && "Empty body!");
David Majnemera7ea1b12015-01-13 05:06:20 +0000500 Token LastBodyToken = LM.Toks.back();
501 Token BodyEnd;
502 BodyEnd.startToken();
503 BodyEnd.setKind(tok::eof);
David Majnemera8f2f1d2015-03-19 00:10:23 +0000504 BodyEnd.setLocation(LastBodyToken.getEndLoc());
David Majnemera7ea1b12015-01-13 05:06:20 +0000505 BodyEnd.setEofData(LM.D);
506 LM.Toks.push_back(BodyEnd);
Douglas Gregorefc46952010-10-12 16:25:54 +0000507 // Append the current token at the end of the new token stream so that it
508 // doesn't get lost.
509 LM.Toks.push_back(Tok);
510 PP.EnterTokenStream(LM.Toks.data(), LM.Toks.size(), true, false);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000511
Douglas Gregorefc46952010-10-12 16:25:54 +0000512 // Consume the previously pushed token.
Argyrios Kyrtzidisc36633c2013-03-27 23:58:17 +0000513 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
Douglas Gregorefc46952010-10-12 16:25:54 +0000514 assert((Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try))
515 && "Inline method not starting with '{', ':' or 'try'");
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000516
Douglas Gregorefc46952010-10-12 16:25:54 +0000517 // Parse the method body. Function body parsing code is similar enough
518 // to be re-used for method bodies as well.
519 ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope);
520 Actions.ActOnStartOfFunctionDef(getCurScope(), LM.D);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000521
Douglas Gregorefc46952010-10-12 16:25:54 +0000522 if (Tok.is(tok::kw_try)) {
Douglas Gregora0ff0c32011-03-16 17:05:57 +0000523 ParseFunctionTryBlock(LM.D, FnScope);
David Majnemera7ea1b12015-01-13 05:06:20 +0000524
525 while (Tok.isNot(tok::eof))
526 ConsumeAnyToken();
527
528 if (Tok.is(tok::eof) && Tok.getEofData() == LM.D)
Douglas Gregorefc46952010-10-12 16:25:54 +0000529 ConsumeAnyToken();
530 return;
531 }
532 if (Tok.is(tok::colon)) {
533 ParseConstructorInitializer(LM.D);
534
535 // Error recovery.
536 if (!Tok.is(tok::l_brace)) {
Douglas Gregora0ff0c32011-03-16 17:05:57 +0000537 FnScope.Exit();
Craig Topper161e4db2014-05-21 06:02:52 +0000538 Actions.ActOnFinishFunctionBody(LM.D, nullptr);
David Majnemera7ea1b12015-01-13 05:06:20 +0000539
540 while (Tok.isNot(tok::eof))
541 ConsumeAnyToken();
542
543 if (Tok.is(tok::eof) && Tok.getEofData() == LM.D)
Matt Beaumont-Gayd0457922011-09-23 22:39:23 +0000544 ConsumeAnyToken();
Douglas Gregorefc46952010-10-12 16:25:54 +0000545 return;
546 }
547 } else
548 Actions.ActOnDefaultCtorInitializers(LM.D);
549
Richard Smithc8378952013-04-29 11:55:38 +0000550 assert((Actions.getDiagnostics().hasErrorOccurred() ||
551 !isa<FunctionTemplateDecl>(LM.D) ||
552 cast<FunctionTemplateDecl>(LM.D)->getTemplateParameters()->getDepth()
553 < TemplateParameterDepth) &&
554 "TemplateParameterDepth should be greater than the depth of "
555 "current template being instantiated!");
556
Douglas Gregora0ff0c32011-03-16 17:05:57 +0000557 ParseFunctionStatementBody(LM.D, FnScope);
Douglas Gregorefc46952010-10-12 16:25:54 +0000558
John McCalle68672f2013-03-14 05:13:41 +0000559 // Clear the late-template-parsed bit if we set it before.
Alp Tokera2794f92014-01-22 07:29:52 +0000560 if (LM.D)
561 LM.D->getAsFunction()->setLateTemplateParsed(false);
John McCalle68672f2013-03-14 05:13:41 +0000562
David Majnemera7ea1b12015-01-13 05:06:20 +0000563 while (Tok.isNot(tok::eof))
564 ConsumeAnyToken();
565
566 if (Tok.is(tok::eof) && Tok.getEofData() == LM.D)
567 ConsumeAnyToken();
Hans Wennborga926d842014-05-23 20:37:38 +0000568
569 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(LM.D))
570 Actions.ActOnFinishInlineMethodDef(MD);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000571}
572
Richard Smith938f40b2011-06-11 17:19:42 +0000573/// ParseLexedMemberInitializers - We finished parsing the member specification
574/// of a top (non-nested) C++ class. Now go over the stack of lexed data member
575/// initializers that were collected during its parsing and parse them all.
576void Parser::ParseLexedMemberInitializers(ParsingClass &Class) {
577 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
578 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
579 HasTemplateScope);
Richard Smithc8378952013-04-29 11:55:38 +0000580 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
581 if (HasTemplateScope) {
Richard Smith938f40b2011-06-11 17:19:42 +0000582 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
Richard Smithc8378952013-04-29 11:55:38 +0000583 ++CurTemplateDepthTracker;
584 }
Douglas Gregor3024f072012-04-16 07:05:22 +0000585 // Set or update the scope flags.
Richard Smith938f40b2011-06-11 17:19:42 +0000586 bool AlreadyHasClassScope = Class.TopLevelClass;
Douglas Gregor3024f072012-04-16 07:05:22 +0000587 unsigned ScopeFlags = Scope::ClassScope|Scope::DeclScope;
Richard Smith938f40b2011-06-11 17:19:42 +0000588 ParseScope ClassScope(this, ScopeFlags, !AlreadyHasClassScope);
589 ParseScopeFlags ClassScopeFlags(this, ScopeFlags, AlreadyHasClassScope);
590
591 if (!AlreadyHasClassScope)
592 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(),
593 Class.TagOrTemplate);
594
Benjamin Kramer1d373c62012-05-17 12:01:52 +0000595 if (!Class.LateParsedDeclarations.empty()) {
Douglas Gregor3024f072012-04-16 07:05:22 +0000596 // C++11 [expr.prim.general]p4:
597 // Otherwise, if a member-declarator declares a non-static data member
598 // (9.2) of a class X, the expression this is a prvalue of type "pointer
599 // to X" within the optional brace-or-equal-initializer. It shall not
600 // appear elsewhere in the member-declarator.
601 Sema::CXXThisScopeRAII ThisScope(Actions, Class.TagOrTemplate,
602 /*TypeQuals=*/(unsigned)0);
Richard Smith938f40b2011-06-11 17:19:42 +0000603
Douglas Gregor3024f072012-04-16 07:05:22 +0000604 for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
605 Class.LateParsedDeclarations[i]->ParseLexedMemberInitializers();
606 }
607 }
608
Richard Smith938f40b2011-06-11 17:19:42 +0000609 if (!AlreadyHasClassScope)
610 Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(),
611 Class.TagOrTemplate);
612
613 Actions.ActOnFinishDelayedMemberInitializers(Class.TagOrTemplate);
614}
615
616void Parser::ParseLexedMemberInitializer(LateParsedMemberInitializer &MI) {
Richard Smith1a526fd2011-09-29 19:42:27 +0000617 if (!MI.Field || MI.Field->isInvalidDecl())
Richard Smith938f40b2011-06-11 17:19:42 +0000618 return;
619
620 // Append the current token at the end of the new token stream so that it
621 // doesn't get lost.
622 MI.Toks.push_back(Tok);
623 PP.EnterTokenStream(MI.Toks.data(), MI.Toks.size(), true, false);
624
625 // Consume the previously pushed token.
Argyrios Kyrtzidisc36633c2013-03-27 23:58:17 +0000626 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
Richard Smith938f40b2011-06-11 17:19:42 +0000627
628 SourceLocation EqualLoc;
Richard Smith2b013182012-06-10 03:12:00 +0000629
Richard Smith74108172014-01-17 03:11:34 +0000630 Actions.ActOnStartCXXInClassMemberInitializer();
631
Douglas Gregor926410d2012-02-21 02:22:07 +0000632 ExprResult Init = ParseCXXMemberInitializer(MI.Field, /*IsFunction=*/false,
633 EqualLoc);
Richard Smith938f40b2011-06-11 17:19:42 +0000634
Richard Smith74108172014-01-17 03:11:34 +0000635 Actions.ActOnFinishCXXInClassMemberInitializer(MI.Field, EqualLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000636 Init.get());
Richard Smith938f40b2011-06-11 17:19:42 +0000637
638 // The next token should be our artificial terminating EOF token.
639 if (Tok.isNot(tok::eof)) {
Richard Smith95e1fb02014-08-27 03:23:12 +0000640 if (!Init.isInvalid()) {
641 SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
642 if (!EndLoc.isValid())
643 EndLoc = Tok.getLocation();
644 // No fixit; we can't recover as if there were a semicolon here.
645 Diag(EndLoc, diag::err_expected_semi_decl_list);
646 }
Richard Smith938f40b2011-06-11 17:19:42 +0000647
648 // Consume tokens until we hit the artificial EOF.
649 while (Tok.isNot(tok::eof))
650 ConsumeAnyToken();
651 }
David Majnemer2d3663e2014-12-18 09:57:31 +0000652 // Make sure this is *our* artificial EOF token.
David Majnemerce1d3012014-12-19 02:13:56 +0000653 if (Tok.getEofData() == MI.Field)
David Majnemer2d3663e2014-12-18 09:57:31 +0000654 ConsumeAnyToken();
Richard Smith938f40b2011-06-11 17:19:42 +0000655}
656
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000657/// ConsumeAndStoreUntil - Consume and store the token at the passed token
Douglas Gregor4d87df52008-12-16 21:30:33 +0000658/// container until the token 'T' is reached (which gets
Mike Stump11289f42009-09-09 15:08:12 +0000659/// consumed/stored too, if ConsumeFinalToken).
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000660/// If StopAtSemi is true, then we will stop early at a ';' character.
Douglas Gregor4d87df52008-12-16 21:30:33 +0000661/// Returns true if token 'T1' or 'T2' was found.
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000662/// NOTE: This is a specialized version of Parser::SkipUntil.
Douglas Gregor4d87df52008-12-16 21:30:33 +0000663bool Parser::ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
664 CachedTokens &Toks,
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000665 bool StopAtSemi, bool ConsumeFinalToken) {
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000666 // We always want this function to consume at least one token if the first
667 // token isn't T and if not at EOF.
668 bool isFirstTokenConsumed = true;
669 while (1) {
670 // If we found one of the tokens, stop and return true.
Douglas Gregor4d87df52008-12-16 21:30:33 +0000671 if (Tok.is(T1) || Tok.is(T2)) {
672 if (ConsumeFinalToken) {
673 Toks.push_back(Tok);
674 ConsumeAnyToken();
675 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000676 return true;
677 }
678
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000679 switch (Tok.getKind()) {
680 case tok::eof:
Richard Smith34f30512013-11-23 04:06:09 +0000681 case tok::annot_module_begin:
682 case tok::annot_module_end:
683 case tok::annot_module_include:
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000684 // Ran out of tokens.
685 return false;
686
687 case tok::l_paren:
688 // Recursively consume properly-nested parens.
689 Toks.push_back(Tok);
690 ConsumeParen();
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000691 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000692 break;
693 case tok::l_square:
694 // Recursively consume properly-nested square brackets.
695 Toks.push_back(Tok);
696 ConsumeBracket();
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000697 ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000698 break;
699 case tok::l_brace:
700 // Recursively consume properly-nested braces.
701 Toks.push_back(Tok);
702 ConsumeBrace();
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000703 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000704 break;
705
706 // Okay, we found a ']' or '}' or ')', which we think should be balanced.
707 // Since the user wasn't looking for this token (if they were, it would
708 // already be handled), this isn't balanced. If there is a LHS token at a
709 // higher level, we will assume that this matches the unbalanced token
710 // and return it. Otherwise, this is a spurious RHS token, which we skip.
711 case tok::r_paren:
712 if (ParenCount && !isFirstTokenConsumed)
713 return false; // Matches something.
714 Toks.push_back(Tok);
715 ConsumeParen();
716 break;
717 case tok::r_square:
718 if (BracketCount && !isFirstTokenConsumed)
719 return false; // Matches something.
720 Toks.push_back(Tok);
721 ConsumeBracket();
722 break;
723 case tok::r_brace:
724 if (BraceCount && !isFirstTokenConsumed)
725 return false; // Matches something.
726 Toks.push_back(Tok);
727 ConsumeBrace();
728 break;
729
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000730 case tok::code_completion:
731 Toks.push_back(Tok);
732 ConsumeCodeCompletionToken();
733 break;
734
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000735 case tok::string_literal:
736 case tok::wide_string_literal:
Douglas Gregorfb65e592011-07-27 05:40:30 +0000737 case tok::utf8_string_literal:
738 case tok::utf16_string_literal:
739 case tok::utf32_string_literal:
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000740 Toks.push_back(Tok);
741 ConsumeStringToken();
742 break;
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000743 case tok::semi:
744 if (StopAtSemi)
745 return false;
746 // FALL THROUGH.
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000747 default:
748 // consume this token.
749 Toks.push_back(Tok);
750 ConsumeToken();
751 break;
752 }
753 isFirstTokenConsumed = false;
754 }
755}
Sebastian Redla74948d2011-09-24 17:48:25 +0000756
757/// \brief Consume tokens and store them in the passed token container until
758/// we've passed the try keyword and constructor initializers and have consumed
Sebastian Redl0d164012011-09-30 08:32:17 +0000759/// the opening brace of the function body. The opening brace will be consumed
760/// if and only if there was no error.
Sebastian Redla74948d2011-09-24 17:48:25 +0000761///
Richard Smithcde3fd82013-07-04 00:13:48 +0000762/// \return True on error.
Sebastian Redl0d164012011-09-30 08:32:17 +0000763bool Parser::ConsumeAndStoreFunctionPrologue(CachedTokens &Toks) {
Sebastian Redla74948d2011-09-24 17:48:25 +0000764 if (Tok.is(tok::kw_try)) {
765 Toks.push_back(Tok);
766 ConsumeToken();
767 }
Richard Smithcde3fd82013-07-04 00:13:48 +0000768
769 if (Tok.isNot(tok::colon)) {
770 // Easy case, just a function body.
771
772 // Grab any remaining garbage to be diagnosed later. We stop when we reach a
773 // brace: an opening one is the function body, while a closing one probably
774 // means we've reached the end of the class.
775 ConsumeAndStoreUntil(tok::l_brace, tok::r_brace, Toks,
776 /*StopAtSemi=*/true,
777 /*ConsumeFinalToken=*/false);
778 if (Tok.isNot(tok::l_brace))
Alp Tokerec543272013-12-24 09:48:30 +0000779 return Diag(Tok.getLocation(), diag::err_expected) << tok::l_brace;
Richard Smithcde3fd82013-07-04 00:13:48 +0000780
Sebastian Redla74948d2011-09-24 17:48:25 +0000781 Toks.push_back(Tok);
Richard Smithcde3fd82013-07-04 00:13:48 +0000782 ConsumeBrace();
783 return false;
Eli Friedman7cd4a9b2012-02-22 04:49:04 +0000784 }
Sebastian Redl0d164012011-09-30 08:32:17 +0000785
786 Toks.push_back(Tok);
Richard Smithcde3fd82013-07-04 00:13:48 +0000787 ConsumeToken();
788
789 // We can't reliably skip over a mem-initializer-id, because it could be
790 // a template-id involving not-yet-declared names. Given:
791 //
792 // S ( ) : a < b < c > ( e )
793 //
794 // 'e' might be an initializer or part of a template argument, depending
795 // on whether 'b' is a template.
796
797 // Track whether we might be inside a template argument. We can give
798 // significantly better diagnostics if we know that we're not.
799 bool MightBeTemplateArgument = false;
800
801 while (true) {
802 // Skip over the mem-initializer-id, if possible.
803 if (Tok.is(tok::kw_decltype)) {
804 Toks.push_back(Tok);
805 SourceLocation OpenLoc = ConsumeToken();
806 if (Tok.isNot(tok::l_paren))
807 return Diag(Tok.getLocation(), diag::err_expected_lparen_after)
808 << "decltype";
809 Toks.push_back(Tok);
810 ConsumeParen();
811 if (!ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/true)) {
Alp Tokerec543272013-12-24 09:48:30 +0000812 Diag(Tok.getLocation(), diag::err_expected) << tok::r_paren;
813 Diag(OpenLoc, diag::note_matching) << tok::l_paren;
Richard Smithcde3fd82013-07-04 00:13:48 +0000814 return true;
815 }
816 }
817 do {
818 // Walk over a component of a nested-name-specifier.
819 if (Tok.is(tok::coloncolon)) {
820 Toks.push_back(Tok);
821 ConsumeToken();
822
823 if (Tok.is(tok::kw_template)) {
824 Toks.push_back(Tok);
825 ConsumeToken();
826 }
827 }
828
829 if (Tok.is(tok::identifier) || Tok.is(tok::kw_template)) {
830 Toks.push_back(Tok);
831 ConsumeToken();
832 } else if (Tok.is(tok::code_completion)) {
833 Toks.push_back(Tok);
834 ConsumeCodeCompletionToken();
835 // Consume the rest of the initializers permissively.
836 // FIXME: We should be able to perform code-completion here even if
837 // there isn't a subsequent '{' token.
838 MightBeTemplateArgument = true;
839 break;
840 } else {
841 break;
842 }
843 } while (Tok.is(tok::coloncolon));
844
845 if (Tok.is(tok::less))
846 MightBeTemplateArgument = true;
847
848 if (MightBeTemplateArgument) {
849 // We may be inside a template argument list. Grab up to the start of the
850 // next parenthesized initializer or braced-init-list. This *might* be the
851 // initializer, or it might be a subexpression in the template argument
852 // list.
853 // FIXME: Count angle brackets, and clear MightBeTemplateArgument
854 // if all angles are closed.
855 if (!ConsumeAndStoreUntil(tok::l_paren, tok::l_brace, Toks,
856 /*StopAtSemi=*/true,
857 /*ConsumeFinalToken=*/false)) {
858 // We're not just missing the initializer, we're also missing the
859 // function body!
Alp Tokerec543272013-12-24 09:48:30 +0000860 return Diag(Tok.getLocation(), diag::err_expected) << tok::l_brace;
Richard Smithcde3fd82013-07-04 00:13:48 +0000861 }
862 } else if (Tok.isNot(tok::l_paren) && Tok.isNot(tok::l_brace)) {
863 // We found something weird in a mem-initializer-id.
Alp Tokerec543272013-12-24 09:48:30 +0000864 if (getLangOpts().CPlusPlus11)
865 return Diag(Tok.getLocation(), diag::err_expected_either)
866 << tok::l_paren << tok::l_brace;
867 else
868 return Diag(Tok.getLocation(), diag::err_expected) << tok::l_paren;
Richard Smithcde3fd82013-07-04 00:13:48 +0000869 }
870
871 tok::TokenKind kind = Tok.getKind();
872 Toks.push_back(Tok);
873 bool IsLParen = (kind == tok::l_paren);
874 SourceLocation OpenLoc = Tok.getLocation();
875
876 if (IsLParen) {
877 ConsumeParen();
878 } else {
879 assert(kind == tok::l_brace && "Must be left paren or brace here.");
880 ConsumeBrace();
881 // In C++03, this has to be the start of the function body, which
882 // means the initializer is malformed; we'll diagnose it later.
883 if (!getLangOpts().CPlusPlus11)
884 return false;
885 }
886
887 // Grab the initializer (or the subexpression of the template argument).
888 // FIXME: If we support lambdas here, we'll need to set StopAtSemi to false
889 // if we might be inside the braces of a lambda-expression.
Alp Tokerec543272013-12-24 09:48:30 +0000890 tok::TokenKind CloseKind = IsLParen ? tok::r_paren : tok::r_brace;
891 if (!ConsumeAndStoreUntil(CloseKind, Toks, /*StopAtSemi=*/true)) {
892 Diag(Tok, diag::err_expected) << CloseKind;
893 Diag(OpenLoc, diag::note_matching) << kind;
Richard Smithcde3fd82013-07-04 00:13:48 +0000894 return true;
895 }
896
897 // Grab pack ellipsis, if present.
898 if (Tok.is(tok::ellipsis)) {
899 Toks.push_back(Tok);
900 ConsumeToken();
901 }
902
903 // If we know we just consumed a mem-initializer, we must have ',' or '{'
904 // next.
905 if (Tok.is(tok::comma)) {
906 Toks.push_back(Tok);
907 ConsumeToken();
908 } else if (Tok.is(tok::l_brace)) {
909 // This is the function body if the ')' or '}' is immediately followed by
910 // a '{'. That cannot happen within a template argument, apart from the
911 // case where a template argument contains a compound literal:
912 //
913 // S ( ) : a < b < c > ( d ) { }
914 // // End of declaration, or still inside the template argument?
915 //
916 // ... and the case where the template argument contains a lambda:
917 //
918 // S ( ) : a < 0 && b < c > ( d ) + [ ] ( ) { return 0; }
919 // ( ) > ( ) { }
920 //
921 // FIXME: Disambiguate these cases. Note that the latter case is probably
922 // going to be made ill-formed by core issue 1607.
923 Toks.push_back(Tok);
924 ConsumeBrace();
925 return false;
926 } else if (!MightBeTemplateArgument) {
Alp Tokerec543272013-12-24 09:48:30 +0000927 return Diag(Tok.getLocation(), diag::err_expected_either) << tok::l_brace
928 << tok::comma;
Richard Smithcde3fd82013-07-04 00:13:48 +0000929 }
930 }
Sebastian Redla74948d2011-09-24 17:48:25 +0000931}
Richard Smith1fff95c2013-09-12 23:28:08 +0000932
933/// \brief Consume and store tokens from the '?' to the ':' in a conditional
934/// expression.
935bool Parser::ConsumeAndStoreConditional(CachedTokens &Toks) {
936 // Consume '?'.
937 assert(Tok.is(tok::question));
938 Toks.push_back(Tok);
939 ConsumeToken();
940
941 while (Tok.isNot(tok::colon)) {
Nico Weber77c76c52014-05-10 17:43:15 +0000942 if (!ConsumeAndStoreUntil(tok::question, tok::colon, Toks,
943 /*StopAtSemi=*/true,
944 /*ConsumeFinalToken=*/false))
Richard Smith1fff95c2013-09-12 23:28:08 +0000945 return false;
946
947 // If we found a nested conditional, consume it.
948 if (Tok.is(tok::question) && !ConsumeAndStoreConditional(Toks))
949 return false;
950 }
951
952 // Consume ':'.
953 Toks.push_back(Tok);
954 ConsumeToken();
955 return true;
956}
957
958/// \brief A tentative parsing action that can also revert token annotations.
959class Parser::UnannotatedTentativeParsingAction : public TentativeParsingAction {
960public:
961 explicit UnannotatedTentativeParsingAction(Parser &Self,
962 tok::TokenKind EndKind)
963 : TentativeParsingAction(Self), Self(Self), EndKind(EndKind) {
964 // Stash away the old token stream, so we can restore it once the
965 // tentative parse is complete.
966 TentativeParsingAction Inner(Self);
967 Self.ConsumeAndStoreUntil(EndKind, Toks, true, /*ConsumeFinalToken*/false);
968 Inner.Revert();
969 }
970
971 void RevertAnnotations() {
972 Revert();
973
974 // Put back the original tokens.
Alexey Bataevee6507d2013-11-18 08:17:37 +0000975 Self.SkipUntil(EndKind, StopAtSemi | StopBeforeMatch);
Richard Smith1fff95c2013-09-12 23:28:08 +0000976 if (Toks.size()) {
977 Token *Buffer = new Token[Toks.size()];
978 std::copy(Toks.begin() + 1, Toks.end(), Buffer);
979 Buffer[Toks.size() - 1] = Self.Tok;
980 Self.PP.EnterTokenStream(Buffer, Toks.size(), true, /*Owned*/true);
981
982 Self.Tok = Toks.front();
983 }
984 }
985
986private:
987 Parser &Self;
988 CachedTokens Toks;
989 tok::TokenKind EndKind;
990};
991
992/// ConsumeAndStoreInitializer - Consume and store the token at the passed token
993/// container until the end of the current initializer expression (either a
994/// default argument or an in-class initializer for a non-static data member).
Richard Smith95e1fb02014-08-27 03:23:12 +0000995///
996/// Returns \c true if we reached the end of something initializer-shaped,
997/// \c false if we bailed out.
Richard Smith1fff95c2013-09-12 23:28:08 +0000998bool Parser::ConsumeAndStoreInitializer(CachedTokens &Toks,
999 CachedInitKind CIK) {
1000 // We always want this function to consume at least one token if not at EOF.
Richard Smith95e1fb02014-08-27 03:23:12 +00001001 bool IsFirstToken = true;
Richard Smith1fff95c2013-09-12 23:28:08 +00001002
1003 // Number of possible unclosed <s we've seen so far. These might be templates,
1004 // and might not, but if there were none of them (or we know for sure that
1005 // we're within a template), we can avoid a tentative parse.
1006 unsigned AngleCount = 0;
1007 unsigned KnownTemplateCount = 0;
1008
1009 while (1) {
1010 switch (Tok.getKind()) {
1011 case tok::comma:
1012 // If we might be in a template, perform a tentative parse to check.
1013 if (!AngleCount)
1014 // Not a template argument: this is the end of the initializer.
1015 return true;
1016 if (KnownTemplateCount)
1017 goto consume_token;
1018
1019 // We hit a comma inside angle brackets. This is the hard case. The
1020 // rule we follow is:
1021 // * For a default argument, if the tokens after the comma form a
1022 // syntactically-valid parameter-declaration-clause, in which each
1023 // parameter has an initializer, then this comma ends the default
1024 // argument.
1025 // * For a default initializer, if the tokens after the comma form a
1026 // syntactically-valid init-declarator-list, then this comma ends
1027 // the default initializer.
1028 {
1029 UnannotatedTentativeParsingAction PA(*this,
1030 CIK == CIK_DefaultInitializer
1031 ? tok::semi : tok::r_paren);
1032 Sema::TentativeAnalysisScope Scope(Actions);
1033
Richard Smithee390432014-05-16 01:56:53 +00001034 TPResult Result = TPResult::Error;
Richard Smith1fff95c2013-09-12 23:28:08 +00001035 ConsumeToken();
1036 switch (CIK) {
1037 case CIK_DefaultInitializer:
1038 Result = TryParseInitDeclaratorList();
1039 // If we parsed a complete, ambiguous init-declarator-list, this
1040 // is only syntactically-valid if it's followed by a semicolon.
Richard Smithee390432014-05-16 01:56:53 +00001041 if (Result == TPResult::Ambiguous && Tok.isNot(tok::semi))
1042 Result = TPResult::False;
Richard Smith1fff95c2013-09-12 23:28:08 +00001043 break;
1044
1045 case CIK_DefaultArgument:
1046 bool InvalidAsDeclaration = false;
1047 Result = TryParseParameterDeclarationClause(
Nico Weberc29c4832014-12-28 23:24:02 +00001048 &InvalidAsDeclaration, /*VersusTemplateArgument=*/true);
Richard Smith1fff95c2013-09-12 23:28:08 +00001049 // If this is an expression or a declaration with a missing
1050 // 'typename', assume it's not a declaration.
Richard Smithee390432014-05-16 01:56:53 +00001051 if (Result == TPResult::Ambiguous && InvalidAsDeclaration)
1052 Result = TPResult::False;
Richard Smith1fff95c2013-09-12 23:28:08 +00001053 break;
1054 }
1055
1056 // If what follows could be a declaration, it is a declaration.
Richard Smithee390432014-05-16 01:56:53 +00001057 if (Result != TPResult::False && Result != TPResult::Error) {
Richard Smith1fff95c2013-09-12 23:28:08 +00001058 PA.Revert();
1059 return true;
1060 }
1061
1062 // In the uncommon case that we decide the following tokens are part
1063 // of a template argument, revert any annotations we've performed in
1064 // those tokens. We're not going to look them up until we've parsed
1065 // the rest of the class, and that might add more declarations.
1066 PA.RevertAnnotations();
1067 }
1068
1069 // Keep going. We know we're inside a template argument list now.
1070 ++KnownTemplateCount;
1071 goto consume_token;
1072
1073 case tok::eof:
Richard Smith34f30512013-11-23 04:06:09 +00001074 case tok::annot_module_begin:
1075 case tok::annot_module_end:
1076 case tok::annot_module_include:
Richard Smith1fff95c2013-09-12 23:28:08 +00001077 // Ran out of tokens.
1078 return false;
1079
1080 case tok::less:
1081 // FIXME: A '<' can only start a template-id if it's preceded by an
1082 // identifier, an operator-function-id, or a literal-operator-id.
1083 ++AngleCount;
1084 goto consume_token;
1085
1086 case tok::question:
1087 // In 'a ? b : c', 'b' can contain an unparenthesized comma. If it does,
1088 // that is *never* the end of the initializer. Skip to the ':'.
1089 if (!ConsumeAndStoreConditional(Toks))
1090 return false;
1091 break;
1092
1093 case tok::greatergreatergreater:
1094 if (!getLangOpts().CPlusPlus11)
1095 goto consume_token;
1096 if (AngleCount) --AngleCount;
1097 if (KnownTemplateCount) --KnownTemplateCount;
1098 // Fall through.
1099 case tok::greatergreater:
1100 if (!getLangOpts().CPlusPlus11)
1101 goto consume_token;
1102 if (AngleCount) --AngleCount;
1103 if (KnownTemplateCount) --KnownTemplateCount;
1104 // Fall through.
1105 case tok::greater:
1106 if (AngleCount) --AngleCount;
1107 if (KnownTemplateCount) --KnownTemplateCount;
1108 goto consume_token;
1109
1110 case tok::kw_template:
1111 // 'template' identifier '<' is known to start a template argument list,
1112 // and can be used to disambiguate the parse.
1113 // FIXME: Support all forms of 'template' unqualified-id '<'.
1114 Toks.push_back(Tok);
1115 ConsumeToken();
1116 if (Tok.is(tok::identifier)) {
1117 Toks.push_back(Tok);
1118 ConsumeToken();
1119 if (Tok.is(tok::less)) {
Richard Smith93033572014-07-27 05:38:12 +00001120 ++AngleCount;
Richard Smith1fff95c2013-09-12 23:28:08 +00001121 ++KnownTemplateCount;
1122 Toks.push_back(Tok);
1123 ConsumeToken();
1124 }
1125 }
1126 break;
1127
1128 case tok::kw_operator:
1129 // If 'operator' precedes other punctuation, that punctuation loses
1130 // its special behavior.
1131 Toks.push_back(Tok);
1132 ConsumeToken();
1133 switch (Tok.getKind()) {
1134 case tok::comma:
1135 case tok::greatergreatergreater:
1136 case tok::greatergreater:
1137 case tok::greater:
1138 case tok::less:
1139 Toks.push_back(Tok);
1140 ConsumeToken();
1141 break;
1142 default:
1143 break;
1144 }
1145 break;
1146
1147 case tok::l_paren:
1148 // Recursively consume properly-nested parens.
1149 Toks.push_back(Tok);
1150 ConsumeParen();
1151 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
1152 break;
1153 case tok::l_square:
1154 // Recursively consume properly-nested square brackets.
1155 Toks.push_back(Tok);
1156 ConsumeBracket();
1157 ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false);
1158 break;
1159 case tok::l_brace:
1160 // Recursively consume properly-nested braces.
1161 Toks.push_back(Tok);
1162 ConsumeBrace();
1163 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1164 break;
1165
1166 // Okay, we found a ']' or '}' or ')', which we think should be balanced.
1167 // Since the user wasn't looking for this token (if they were, it would
1168 // already be handled), this isn't balanced. If there is a LHS token at a
1169 // higher level, we will assume that this matches the unbalanced token
Richard Smith95e1fb02014-08-27 03:23:12 +00001170 // and return it. Otherwise, this is a spurious RHS token, which we
1171 // consume and pass on to downstream code to diagnose.
Richard Smith1fff95c2013-09-12 23:28:08 +00001172 case tok::r_paren:
1173 if (CIK == CIK_DefaultArgument)
1174 return true; // End of the default argument.
Richard Smith95e1fb02014-08-27 03:23:12 +00001175 if (ParenCount && !IsFirstToken)
1176 return false;
1177 Toks.push_back(Tok);
1178 ConsumeParen();
1179 continue;
Richard Smith1fff95c2013-09-12 23:28:08 +00001180 case tok::r_square:
Richard Smith95e1fb02014-08-27 03:23:12 +00001181 if (BracketCount && !IsFirstToken)
1182 return false;
1183 Toks.push_back(Tok);
1184 ConsumeBracket();
1185 continue;
Richard Smith1fff95c2013-09-12 23:28:08 +00001186 case tok::r_brace:
Richard Smith95e1fb02014-08-27 03:23:12 +00001187 if (BraceCount && !IsFirstToken)
1188 return false;
1189 Toks.push_back(Tok);
1190 ConsumeBrace();
1191 continue;
Richard Smith1fff95c2013-09-12 23:28:08 +00001192
1193 case tok::code_completion:
1194 Toks.push_back(Tok);
1195 ConsumeCodeCompletionToken();
1196 break;
1197
1198 case tok::string_literal:
1199 case tok::wide_string_literal:
1200 case tok::utf8_string_literal:
1201 case tok::utf16_string_literal:
1202 case tok::utf32_string_literal:
1203 Toks.push_back(Tok);
1204 ConsumeStringToken();
1205 break;
1206 case tok::semi:
1207 if (CIK == CIK_DefaultInitializer)
1208 return true; // End of the default initializer.
1209 // FALL THROUGH.
1210 default:
1211 consume_token:
1212 Toks.push_back(Tok);
1213 ConsumeToken();
1214 break;
1215 }
Richard Smith95e1fb02014-08-27 03:23:12 +00001216 IsFirstToken = false;
Richard Smith1fff95c2013-09-12 23:28:08 +00001217 }
1218}