blob: 4cf87e5d9ace7391a0e827de96e7cd3a38b6984f [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,
29 const VirtSpecifiers& VS,
30 FunctionDefinitionKind DefinitionKind,
31 ExprResult& Init) {
Abramo Bagnara924a8f32010-12-10 16:29:40 +000032 assert(D.isFunctionDeclarator() && "This isn't a function declarator!");
Alexis Hunt5a7fa252011-05-12 06:15:49 +000033 assert((Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try) ||
34 Tok.is(tok::equal)) &&
35 "Current token not a '{', ':', '=', or 'try'!");
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +000036
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000037 MultiTemplateParamsArg TemplateParams(
Alexis Hunt1deb9722010-04-14 23:07:37 +000038 TemplateInfo.TemplateParams ? TemplateInfo.TemplateParams->data() : 0,
39 TemplateInfo.TemplateParams ? TemplateInfo.TemplateParams->size() : 0);
40
Rafael Espindolac2453dd2013-01-08 21:00:12 +000041 NamedDecl *FnD;
Douglas Gregor5d1b4e32011-11-07 20:56:01 +000042 D.setFunctionDefinitionKind(DefinitionKind);
John McCall07e91c02009-08-06 02:15:43 +000043 if (D.getDeclSpec().isFriendSpecified())
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000044 FnD = Actions.ActOnFriendFunctionDecl(getCurScope(), D,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000045 TemplateParams);
Douglas Gregor728d00b2011-10-10 14:49:18 +000046 else {
Douglas Gregor0be31a22010-07-02 17:43:08 +000047 FnD = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS, D,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000048 TemplateParams, 0,
Richard Smith2b013182012-06-10 03:12:00 +000049 VS, ICIS_NoInit);
Douglas Gregor728d00b2011-10-10 14:49:18 +000050 if (FnD) {
Richard Smithf8a75c32013-08-29 00:47:48 +000051 Actions.ProcessDeclAttributeList(getCurScope(), FnD, AccessAttrs);
Richard Smith74aeef52013-04-26 16:15:35 +000052 bool TypeSpecContainsAuto = D.getDeclSpec().containsPlaceholderType();
Douglas Gregor50cefbf2011-10-17 17:09:53 +000053 if (Init.isUsable())
Larisse Voufo39a1e502013-08-06 01:03:05 +000054 Actions.AddInitializerToDecl(FnD, Init.get(), false,
Douglas Gregor728d00b2011-10-10 14:49:18 +000055 TypeSpecContainsAuto);
56 else
57 Actions.ActOnUninitializedDecl(FnD, TypeSpecContainsAuto);
58 }
Nico Weber24b2a822011-01-28 06:07:34 +000059 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +000060
Douglas Gregor433e0532012-04-16 18:27:27 +000061 HandleMemberFunctionDeclDelays(D, FnD);
Eli Friedman3af2a772009-07-22 21:45:50 +000062
John McCallc1465822011-02-14 07:13:47 +000063 D.complete(FnD);
64
Alp Tokera3ebe6e2013-12-17 14:12:37 +000065 if (TryConsumeToken(tok::equal)) {
Richard Smith1c704732011-11-10 09:08:44 +000066 if (!FnD) {
67 SkipUntil(tok::semi);
68 return 0;
69 }
70
Alexis Hunt5a7fa252011-05-12 06:15:49 +000071 bool Delete = false;
72 SourceLocation KWLoc;
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;
Alp Tokera3ebe6e2013-12-17 14:12:37 +000079 } else if (TryConsumeToken(tok::kw_default, KWLoc)) {
80 Diag(KWLoc, getLangOpts().CPlusPlus11
81 ? diag::warn_cxx98_compat_defaulted_function
82 : diag::ext_defaulted_function);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000083 Actions.SetDeclDefaulted(FnD, KWLoc);
84 } else {
85 llvm_unreachable("function definition after = not 'delete' or 'default'");
86 }
87
88 if (Tok.is(tok::comma)) {
89 Diag(KWLoc, diag::err_default_delete_in_multiple_declaration)
90 << Delete;
91 SkipUntil(tok::semi);
Alp Toker383d2c42014-01-01 03:08:43 +000092 } else if (ExpectAndConsume(tok::semi, diag::err_expected_after,
93 Delete ? "delete" : "default")) {
94 SkipUntil(tok::semi);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000095 }
96
97 return FnD;
98 }
Faisal Valib96570332013-11-01 02:01:01 +000099
Francois Pichet1c229c02011-04-22 22:18:13 +0000100 // In delayed template parsing mode, if we are within a class template
101 // or if we are about to parse function member template then consume
102 // the tokens and store them for parsing at the end of the translation unit.
David Majnemer90b17292013-09-14 05:46:42 +0000103 if (getLangOpts().DelayedTemplateParsing &&
104 DefinitionKind == FDK_Definition &&
Alp Tokera2794f92014-01-22 07:29:52 +0000105 !D.getDeclSpec().isConstexprSpecified() &&
106 !(FnD && FnD->getAsFunction() &&
Alp Toker314cc812014-01-25 16:55:45 +0000107 FnD->getAsFunction()->getReturnType()->getContainedAutoType()) &&
Francois Pichet1c229c02011-04-22 22:18:13 +0000108 ((Actions.CurContext->isDependentContext() ||
David Majnemer90b17292013-09-14 05:46:42 +0000109 (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
110 TemplateInfo.Kind != ParsedTemplateInfo::ExplicitSpecialization)) &&
111 !Actions.IsInsideALocalClassWithinATemplateFunction())) {
Francois Pichet1c229c02011-04-22 22:18:13 +0000112
Richard Smithe40f2ba2013-08-07 21:41:30 +0000113 CachedTokens Toks;
114 LexTemplateFunctionForLateParsing(Toks);
Francois Pichet1c229c02011-04-22 22:18:13 +0000115
Richard Smithe40f2ba2013-08-07 21:41:30 +0000116 if (FnD) {
Alp Tokera2794f92014-01-22 07:29:52 +0000117 FunctionDecl *FD = FnD->getAsFunction();
Chandler Carruthbc0f9ae2011-04-25 07:09:43 +0000118 Actions.CheckForFunctionRedefinition(FD);
Richard Smithe40f2ba2013-08-07 21:41:30 +0000119 Actions.MarkAsLateParsedTemplate(FD, FnD, Toks);
Francois Pichet1c229c02011-04-22 22:18:13 +0000120 }
121
122 return FnD;
123 }
124
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000125 // Consume the tokens and store them for later parsing.
126
Douglas Gregorefc46952010-10-12 16:25:54 +0000127 LexedMethod* LM = new LexedMethod(this, FnD);
128 getCurrentClass().LateParsedDeclarations.push_back(LM);
129 LM->TemplateScope = getCurScope()->isTemplateParamScope();
130 CachedTokens &Toks = LM->Toks;
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000131
Sebastian Redla7b98a72009-04-26 20:35:05 +0000132 tok::TokenKind kind = Tok.getKind();
Sebastian Redl0d164012011-09-30 08:32:17 +0000133 // Consume everything up to (and including) the left brace of the
134 // function body.
135 if (ConsumeAndStoreFunctionPrologue(Toks)) {
136 // We didn't find the left-brace we expected after the
Eli Friedman7cd4a9b2012-02-22 04:49:04 +0000137 // constructor initializer; we already printed an error, and it's likely
138 // impossible to recover, so don't try to parse this method later.
Richard Smithcde3fd82013-07-04 00:13:48 +0000139 // Skip over the rest of the decl and back to somewhere that looks
140 // reasonable.
141 SkipMalformedDecl();
Eli Friedman7cd4a9b2012-02-22 04:49:04 +0000142 delete getCurrentClass().LateParsedDeclarations.back();
143 getCurrentClass().LateParsedDeclarations.pop_back();
144 return FnD;
Douglas Gregore8381c02008-11-05 04:29:56 +0000145 } else {
Sebastian Redl0d164012011-09-30 08:32:17 +0000146 // Consume everything up to (and including) the matching right brace.
147 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
Douglas Gregore8381c02008-11-05 04:29:56 +0000148 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000149
Sebastian Redla7b98a72009-04-26 20:35:05 +0000150 // If we're in a function-try-block, we need to store all the catch blocks.
151 if (kind == tok::kw_try) {
152 while (Tok.is(tok::kw_catch)) {
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000153 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
154 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
Sebastian Redla7b98a72009-04-26 20:35:05 +0000155 }
156 }
157
Stephen Lin9354fc52013-06-23 07:37:13 +0000158 if (FnD) {
159 // If this is a friend function, mark that it's late-parsed so that
160 // it's still known to be a definition even before we attach the
161 // parsed body. Sema needs to treat friend function definitions
162 // differently during template instantiation, and it's possible for
163 // the containing class to be instantiated before all its member
164 // function definitions are parsed.
165 //
166 // If you remove this, you can remove the code that clears the flag
167 // after parsing the member.
168 if (D.getDeclSpec().isFriendSpecified()) {
Alp Tokera2794f92014-01-22 07:29:52 +0000169 FunctionDecl *FD = FnD->getAsFunction();
Alp Toker19bff322013-10-18 05:54:24 +0000170 Actions.CheckForFunctionRedefinition(FD);
171 FD->setLateTemplateParsed(true);
Stephen Lin9354fc52013-06-23 07:37:13 +0000172 }
173 } else {
Douglas Gregor6ca64102011-04-14 23:19:27 +0000174 // If semantic analysis could not build a function declaration,
175 // just throw away the late-parsed declaration.
176 delete getCurrentClass().LateParsedDeclarations.back();
177 getCurrentClass().LateParsedDeclarations.pop_back();
178 }
179
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000180 return FnD;
181}
182
Richard Smith938f40b2011-06-11 17:19:42 +0000183/// ParseCXXNonStaticMemberInitializer - We parsed and verified that the
184/// specified Declarator is a well formed C++ non-static data member
185/// declaration. Now lex its initializer and store its tokens for parsing
186/// after the class is complete.
187void Parser::ParseCXXNonStaticMemberInitializer(Decl *VarD) {
188 assert((Tok.is(tok::l_brace) || Tok.is(tok::equal)) &&
189 "Current token not a '{' or '='!");
190
191 LateParsedMemberInitializer *MI =
192 new LateParsedMemberInitializer(this, VarD);
193 getCurrentClass().LateParsedDeclarations.push_back(MI);
194 CachedTokens &Toks = MI->Toks;
195
196 tok::TokenKind kind = Tok.getKind();
197 if (kind == tok::equal) {
198 Toks.push_back(Tok);
Douglas Gregor0cf55e92012-03-08 01:00:17 +0000199 ConsumeToken();
Richard Smith938f40b2011-06-11 17:19:42 +0000200 }
201
202 if (kind == tok::l_brace) {
203 // Begin by storing the '{' token.
204 Toks.push_back(Tok);
205 ConsumeBrace();
206
207 // Consume everything up to (and including) the matching right brace.
208 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/true);
209 } else {
210 // Consume everything up to (but excluding) the comma or semicolon.
Richard Smith1fff95c2013-09-12 23:28:08 +0000211 ConsumeAndStoreInitializer(Toks, CIK_DefaultInitializer);
Richard Smith938f40b2011-06-11 17:19:42 +0000212 }
213
214 // Store an artificial EOF token to ensure that we don't run off the end of
215 // the initializer when we come to parse it.
216 Token Eof;
217 Eof.startToken();
218 Eof.setKind(tok::eof);
219 Eof.setLocation(Tok.getLocation());
220 Toks.push_back(Eof);
221}
222
Douglas Gregorefc46952010-10-12 16:25:54 +0000223Parser::LateParsedDeclaration::~LateParsedDeclaration() {}
224void Parser::LateParsedDeclaration::ParseLexedMethodDeclarations() {}
Richard Smith938f40b2011-06-11 17:19:42 +0000225void Parser::LateParsedDeclaration::ParseLexedMemberInitializers() {}
Douglas Gregorefc46952010-10-12 16:25:54 +0000226void Parser::LateParsedDeclaration::ParseLexedMethodDefs() {}
227
228Parser::LateParsedClass::LateParsedClass(Parser *P, ParsingClass *C)
229 : Self(P), Class(C) {}
230
231Parser::LateParsedClass::~LateParsedClass() {
232 Self->DeallocateParsedClasses(Class);
233}
234
235void Parser::LateParsedClass::ParseLexedMethodDeclarations() {
236 Self->ParseLexedMethodDeclarations(*Class);
237}
238
Richard Smith938f40b2011-06-11 17:19:42 +0000239void Parser::LateParsedClass::ParseLexedMemberInitializers() {
240 Self->ParseLexedMemberInitializers(*Class);
241}
242
Douglas Gregorefc46952010-10-12 16:25:54 +0000243void Parser::LateParsedClass::ParseLexedMethodDefs() {
244 Self->ParseLexedMethodDefs(*Class);
245}
246
247void Parser::LateParsedMethodDeclaration::ParseLexedMethodDeclarations() {
248 Self->ParseLexedMethodDeclaration(*this);
249}
250
251void Parser::LexedMethod::ParseLexedMethodDefs() {
252 Self->ParseLexedMethodDef(*this);
253}
254
Richard Smith938f40b2011-06-11 17:19:42 +0000255void Parser::LateParsedMemberInitializer::ParseLexedMemberInitializers() {
256 Self->ParseLexedMemberInitializer(*this);
257}
258
Douglas Gregor4d87df52008-12-16 21:30:33 +0000259/// ParseLexedMethodDeclarations - We finished parsing the member
260/// specification of a top (non-nested) C++ class. Now go over the
261/// stack of method declarations with some parts for which parsing was
262/// delayed (such as default arguments) and parse them.
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000263void Parser::ParseLexedMethodDeclarations(ParsingClass &Class) {
264 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
Douglas Gregorefc46952010-10-12 16:25:54 +0000265 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope, HasTemplateScope);
Richard Smithc8378952013-04-29 11:55:38 +0000266 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
267 if (HasTemplateScope) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000268 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
Richard Smithc8378952013-04-29 11:55:38 +0000269 ++CurTemplateDepthTracker;
270 }
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000271
John McCall6df5fef2009-12-19 10:49:29 +0000272 // The current scope is still active if we're the top-level class.
273 // Otherwise we'll need to push and enter a new scope.
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000274 bool HasClassScope = !Class.TopLevelClass;
Alexis Hunt1deb9722010-04-14 23:07:37 +0000275 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope,
276 HasClassScope);
John McCall6df5fef2009-12-19 10:49:29 +0000277 if (HasClassScope)
Douglas Gregor0be31a22010-07-02 17:43:08 +0000278 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(), Class.TagOrTemplate);
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000279
Douglas Gregorefc46952010-10-12 16:25:54 +0000280 for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
281 Class.LateParsedDeclarations[i]->ParseLexedMethodDeclarations();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000282 }
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000283
John McCall6df5fef2009-12-19 10:49:29 +0000284 if (HasClassScope)
Douglas Gregor0be31a22010-07-02 17:43:08 +0000285 Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(), Class.TagOrTemplate);
Douglas Gregor4d87df52008-12-16 21:30:33 +0000286}
287
Douglas Gregorefc46952010-10-12 16:25:54 +0000288void Parser::ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM) {
289 // If this is a member template, introduce the template parameter scope.
290 ParseScope TemplateScope(this, Scope::TemplateParamScope, LM.TemplateScope);
Richard Smithc8378952013-04-29 11:55:38 +0000291 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
292 if (LM.TemplateScope) {
Douglas Gregorefc46952010-10-12 16:25:54 +0000293 Actions.ActOnReenterTemplateScope(getCurScope(), LM.Method);
Richard Smithc8378952013-04-29 11:55:38 +0000294 ++CurTemplateDepthTracker;
295 }
Douglas Gregorefc46952010-10-12 16:25:54 +0000296 // Start the delayed C++ method declaration
297 Actions.ActOnStartDelayedCXXMethodDeclaration(getCurScope(), LM.Method);
298
299 // Introduce the parameters into scope and parse their default
300 // arguments.
Richard Smithe233fbf2013-01-28 22:42:45 +0000301 ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
302 Scope::FunctionDeclarationScope | Scope::DeclScope);
Douglas Gregorefc46952010-10-12 16:25:54 +0000303 for (unsigned I = 0, N = LM.DefaultArgs.size(); I != N; ++I) {
304 // Introduce the parameter into scope.
Douglas Gregor7fcbd902012-02-21 00:37:24 +0000305 Actions.ActOnDelayedCXXMethodParameter(getCurScope(),
306 LM.DefaultArgs[I].Param);
Douglas Gregorefc46952010-10-12 16:25:54 +0000307
308 if (CachedTokens *Toks = LM.DefaultArgs[I].Toks) {
309 // Save the current token position.
310 SourceLocation origLoc = Tok.getLocation();
311
312 // Parse the default argument from its saved token stream.
313 Toks->push_back(Tok); // So that the current token doesn't get lost
314 PP.EnterTokenStream(&Toks->front(), Toks->size(), true, false);
315
316 // Consume the previously-pushed token.
317 ConsumeAnyToken();
318
319 // Consume the '='.
320 assert(Tok.is(tok::equal) && "Default argument not starting with '='");
321 SourceLocation EqualLoc = ConsumeToken();
322
323 // The argument isn't actually potentially evaluated unless it is
324 // used.
325 EnterExpressionEvaluationContext Eval(Actions,
Douglas Gregor7fcbd902012-02-21 00:37:24 +0000326 Sema::PotentiallyEvaluatedIfUsed,
327 LM.DefaultArgs[I].Param);
Douglas Gregorefc46952010-10-12 16:25:54 +0000328
Sebastian Redldb63af22012-03-14 15:54:00 +0000329 ExprResult DefArgResult;
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000330 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
Sebastian Redl6db0b1b2012-03-20 21:24:03 +0000331 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
Sebastian Redldb63af22012-03-14 15:54:00 +0000332 DefArgResult = ParseBraceInitializer();
Sebastian Redl6db0b1b2012-03-20 21:24:03 +0000333 } else
Sebastian Redldb63af22012-03-14 15:54:00 +0000334 DefArgResult = ParseAssignmentExpression();
Douglas Gregorefc46952010-10-12 16:25:54 +0000335 if (DefArgResult.isInvalid())
336 Actions.ActOnParamDefaultArgumentError(LM.DefaultArgs[I].Param);
337 else {
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000338 if (!TryConsumeToken(tok::cxx_defaultarg_end)) {
Richard Smith1fff95c2013-09-12 23:28:08 +0000339 // The last two tokens are the terminator and the saved value of
340 // Tok; the last token in the default argument is the one before
341 // those.
342 assert(Toks->size() >= 3 && "expected a token in default arg");
343 Diag(Tok.getLocation(), diag::err_default_arg_unparsed)
344 << SourceRange(Tok.getLocation(),
345 (*Toks)[Toks->size() - 3].getLocation());
346 }
Douglas Gregorefc46952010-10-12 16:25:54 +0000347 Actions.ActOnParamDefaultArgument(LM.DefaultArgs[I].Param, EqualLoc,
348 DefArgResult.take());
349 }
350
351 assert(!PP.getSourceManager().isBeforeInTranslationUnit(origLoc,
352 Tok.getLocation()) &&
353 "ParseAssignmentExpression went over the default arg tokens!");
354 // There could be leftover tokens (e.g. because of an error).
355 // Skip through until we reach the original token position.
356 while (Tok.getLocation() != origLoc && Tok.isNot(tok::eof))
357 ConsumeAnyToken();
358
359 delete Toks;
360 LM.DefaultArgs[I].Toks = 0;
361 }
362 }
Douglas Gregor433e0532012-04-16 18:27:27 +0000363
Douglas Gregorefc46952010-10-12 16:25:54 +0000364 PrototypeScope.Exit();
365
366 // Finish the delayed C++ method declaration.
367 Actions.ActOnFinishDelayedCXXMethodDeclaration(getCurScope(), LM.Method);
368}
369
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000370/// ParseLexedMethodDefs - We finished parsing the member specification of a top
371/// (non-nested) C++ class. Now go over the stack of lexed methods that were
372/// collected during its parsing and parse them all.
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000373void Parser::ParseLexedMethodDefs(ParsingClass &Class) {
374 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
Douglas Gregorefc46952010-10-12 16:25:54 +0000375 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope, HasTemplateScope);
Richard Smithc8378952013-04-29 11:55:38 +0000376 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
377 if (HasTemplateScope) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000378 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
Richard Smithc8378952013-04-29 11:55:38 +0000379 ++CurTemplateDepthTracker;
380 }
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000381 bool HasClassScope = !Class.TopLevelClass;
382 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope,
383 HasClassScope);
384
Douglas Gregorefc46952010-10-12 16:25:54 +0000385 for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
386 Class.LateParsedDeclarations[i]->ParseLexedMethodDefs();
387 }
388}
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000389
Douglas Gregorefc46952010-10-12 16:25:54 +0000390void Parser::ParseLexedMethodDef(LexedMethod &LM) {
391 // If this is a member template, introduce the template parameter scope.
392 ParseScope TemplateScope(this, Scope::TemplateParamScope, LM.TemplateScope);
Richard Smithc8378952013-04-29 11:55:38 +0000393 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
394 if (LM.TemplateScope) {
Douglas Gregorefc46952010-10-12 16:25:54 +0000395 Actions.ActOnReenterTemplateScope(getCurScope(), LM.D);
Richard Smithc8378952013-04-29 11:55:38 +0000396 ++CurTemplateDepthTracker;
397 }
Douglas Gregorefc46952010-10-12 16:25:54 +0000398 // Save the current token position.
399 SourceLocation origLoc = Tok.getLocation();
Argyrios Kyrtzidis02041972010-03-31 00:38:09 +0000400
Douglas Gregorefc46952010-10-12 16:25:54 +0000401 assert(!LM.Toks.empty() && "Empty body!");
402 // Append the current token at the end of the new token stream so that it
403 // doesn't get lost.
404 LM.Toks.push_back(Tok);
405 PP.EnterTokenStream(LM.Toks.data(), LM.Toks.size(), true, false);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000406
Douglas Gregorefc46952010-10-12 16:25:54 +0000407 // Consume the previously pushed token.
Argyrios Kyrtzidisc36633c2013-03-27 23:58:17 +0000408 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
Douglas Gregorefc46952010-10-12 16:25:54 +0000409 assert((Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try))
410 && "Inline method not starting with '{', ':' or 'try'");
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000411
Douglas Gregorefc46952010-10-12 16:25:54 +0000412 // Parse the method body. Function body parsing code is similar enough
413 // to be re-used for method bodies as well.
414 ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope);
415 Actions.ActOnStartOfFunctionDef(getCurScope(), LM.D);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000416
Douglas Gregorefc46952010-10-12 16:25:54 +0000417 if (Tok.is(tok::kw_try)) {
Douglas Gregora0ff0c32011-03-16 17:05:57 +0000418 ParseFunctionTryBlock(LM.D, FnScope);
Douglas Gregorefc46952010-10-12 16:25:54 +0000419 assert(!PP.getSourceManager().isBeforeInTranslationUnit(origLoc,
420 Tok.getLocation()) &&
421 "ParseFunctionTryBlock went over the cached tokens!");
422 // There could be leftover tokens (e.g. because of an error).
423 // Skip through until we reach the original token position.
424 while (Tok.getLocation() != origLoc && Tok.isNot(tok::eof))
425 ConsumeAnyToken();
426 return;
427 }
428 if (Tok.is(tok::colon)) {
429 ParseConstructorInitializer(LM.D);
430
431 // Error recovery.
432 if (!Tok.is(tok::l_brace)) {
Douglas Gregora0ff0c32011-03-16 17:05:57 +0000433 FnScope.Exit();
Douglas Gregorefc46952010-10-12 16:25:54 +0000434 Actions.ActOnFinishFunctionBody(LM.D, 0);
Matt Beaumont-Gayd0457922011-09-23 22:39:23 +0000435 while (Tok.getLocation() != origLoc && Tok.isNot(tok::eof))
436 ConsumeAnyToken();
Douglas Gregorefc46952010-10-12 16:25:54 +0000437 return;
438 }
439 } else
440 Actions.ActOnDefaultCtorInitializers(LM.D);
441
Richard Smithc8378952013-04-29 11:55:38 +0000442 assert((Actions.getDiagnostics().hasErrorOccurred() ||
443 !isa<FunctionTemplateDecl>(LM.D) ||
444 cast<FunctionTemplateDecl>(LM.D)->getTemplateParameters()->getDepth()
445 < TemplateParameterDepth) &&
446 "TemplateParameterDepth should be greater than the depth of "
447 "current template being instantiated!");
448
Douglas Gregora0ff0c32011-03-16 17:05:57 +0000449 ParseFunctionStatementBody(LM.D, FnScope);
Douglas Gregorefc46952010-10-12 16:25:54 +0000450
John McCalle68672f2013-03-14 05:13:41 +0000451 // Clear the late-template-parsed bit if we set it before.
Alp Tokera2794f92014-01-22 07:29:52 +0000452 if (LM.D)
453 LM.D->getAsFunction()->setLateTemplateParsed(false);
John McCalle68672f2013-03-14 05:13:41 +0000454
Douglas Gregorefc46952010-10-12 16:25:54 +0000455 if (Tok.getLocation() != origLoc) {
456 // Due to parsing error, we either went over the cached tokens or
457 // there are still cached tokens left. If it's the latter case skip the
458 // leftover tokens.
459 // Since this is an uncommon situation that should be avoided, use the
460 // expensive isBeforeInTranslationUnit call.
461 if (PP.getSourceManager().isBeforeInTranslationUnit(Tok.getLocation(),
462 origLoc))
Argyrios Kyrtzidise1224c82010-06-19 19:58:34 +0000463 while (Tok.getLocation() != origLoc && Tok.isNot(tok::eof))
Argyrios Kyrtzidise9b76af2010-06-17 10:52:22 +0000464 ConsumeAnyToken();
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000465 }
466}
467
Richard Smith938f40b2011-06-11 17:19:42 +0000468/// ParseLexedMemberInitializers - We finished parsing the member specification
469/// of a top (non-nested) C++ class. Now go over the stack of lexed data member
470/// initializers that were collected during its parsing and parse them all.
471void Parser::ParseLexedMemberInitializers(ParsingClass &Class) {
472 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
473 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
474 HasTemplateScope);
Richard Smithc8378952013-04-29 11:55:38 +0000475 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
476 if (HasTemplateScope) {
Richard Smith938f40b2011-06-11 17:19:42 +0000477 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
Richard Smithc8378952013-04-29 11:55:38 +0000478 ++CurTemplateDepthTracker;
479 }
Douglas Gregor3024f072012-04-16 07:05:22 +0000480 // Set or update the scope flags.
Richard Smith938f40b2011-06-11 17:19:42 +0000481 bool AlreadyHasClassScope = Class.TopLevelClass;
Douglas Gregor3024f072012-04-16 07:05:22 +0000482 unsigned ScopeFlags = Scope::ClassScope|Scope::DeclScope;
Richard Smith938f40b2011-06-11 17:19:42 +0000483 ParseScope ClassScope(this, ScopeFlags, !AlreadyHasClassScope);
484 ParseScopeFlags ClassScopeFlags(this, ScopeFlags, AlreadyHasClassScope);
485
486 if (!AlreadyHasClassScope)
487 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(),
488 Class.TagOrTemplate);
489
Benjamin Kramer1d373c62012-05-17 12:01:52 +0000490 if (!Class.LateParsedDeclarations.empty()) {
Douglas Gregor3024f072012-04-16 07:05:22 +0000491 // C++11 [expr.prim.general]p4:
492 // Otherwise, if a member-declarator declares a non-static data member
493 // (9.2) of a class X, the expression this is a prvalue of type "pointer
494 // to X" within the optional brace-or-equal-initializer. It shall not
495 // appear elsewhere in the member-declarator.
496 Sema::CXXThisScopeRAII ThisScope(Actions, Class.TagOrTemplate,
497 /*TypeQuals=*/(unsigned)0);
Richard Smith938f40b2011-06-11 17:19:42 +0000498
Douglas Gregor3024f072012-04-16 07:05:22 +0000499 for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
500 Class.LateParsedDeclarations[i]->ParseLexedMemberInitializers();
501 }
502 }
503
Richard Smith938f40b2011-06-11 17:19:42 +0000504 if (!AlreadyHasClassScope)
505 Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(),
506 Class.TagOrTemplate);
507
508 Actions.ActOnFinishDelayedMemberInitializers(Class.TagOrTemplate);
509}
510
511void Parser::ParseLexedMemberInitializer(LateParsedMemberInitializer &MI) {
Richard Smith1a526fd2011-09-29 19:42:27 +0000512 if (!MI.Field || MI.Field->isInvalidDecl())
Richard Smith938f40b2011-06-11 17:19:42 +0000513 return;
514
515 // Append the current token at the end of the new token stream so that it
516 // doesn't get lost.
517 MI.Toks.push_back(Tok);
518 PP.EnterTokenStream(MI.Toks.data(), MI.Toks.size(), true, false);
519
520 // Consume the previously pushed token.
Argyrios Kyrtzidisc36633c2013-03-27 23:58:17 +0000521 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
Richard Smith938f40b2011-06-11 17:19:42 +0000522
523 SourceLocation EqualLoc;
Richard Smith2b013182012-06-10 03:12:00 +0000524
Richard Smith74108172014-01-17 03:11:34 +0000525 Actions.ActOnStartCXXInClassMemberInitializer();
526
Douglas Gregor926410d2012-02-21 02:22:07 +0000527 ExprResult Init = ParseCXXMemberInitializer(MI.Field, /*IsFunction=*/false,
528 EqualLoc);
Richard Smith938f40b2011-06-11 17:19:42 +0000529
Richard Smith74108172014-01-17 03:11:34 +0000530 Actions.ActOnFinishCXXInClassMemberInitializer(MI.Field, EqualLoc,
531 Init.release());
Richard Smith938f40b2011-06-11 17:19:42 +0000532
533 // The next token should be our artificial terminating EOF token.
534 if (Tok.isNot(tok::eof)) {
535 SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
536 if (!EndLoc.isValid())
537 EndLoc = Tok.getLocation();
538 // No fixit; we can't recover as if there were a semicolon here.
539 Diag(EndLoc, diag::err_expected_semi_decl_list);
540
541 // Consume tokens until we hit the artificial EOF.
542 while (Tok.isNot(tok::eof))
543 ConsumeAnyToken();
544 }
545 ConsumeAnyToken();
546}
547
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000548/// ConsumeAndStoreUntil - Consume and store the token at the passed token
Douglas Gregor4d87df52008-12-16 21:30:33 +0000549/// container until the token 'T' is reached (which gets
Mike Stump11289f42009-09-09 15:08:12 +0000550/// consumed/stored too, if ConsumeFinalToken).
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000551/// If StopAtSemi is true, then we will stop early at a ';' character.
Douglas Gregor4d87df52008-12-16 21:30:33 +0000552/// Returns true if token 'T1' or 'T2' was found.
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000553/// NOTE: This is a specialized version of Parser::SkipUntil.
Douglas Gregor4d87df52008-12-16 21:30:33 +0000554bool Parser::ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
555 CachedTokens &Toks,
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000556 bool StopAtSemi, bool ConsumeFinalToken) {
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000557 // We always want this function to consume at least one token if the first
558 // token isn't T and if not at EOF.
559 bool isFirstTokenConsumed = true;
560 while (1) {
561 // If we found one of the tokens, stop and return true.
Douglas Gregor4d87df52008-12-16 21:30:33 +0000562 if (Tok.is(T1) || Tok.is(T2)) {
563 if (ConsumeFinalToken) {
564 Toks.push_back(Tok);
565 ConsumeAnyToken();
566 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000567 return true;
568 }
569
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000570 switch (Tok.getKind()) {
571 case tok::eof:
Richard Smith34f30512013-11-23 04:06:09 +0000572 case tok::annot_module_begin:
573 case tok::annot_module_end:
574 case tok::annot_module_include:
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000575 // Ran out of tokens.
576 return false;
577
578 case tok::l_paren:
579 // Recursively consume properly-nested parens.
580 Toks.push_back(Tok);
581 ConsumeParen();
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000582 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000583 break;
584 case tok::l_square:
585 // Recursively consume properly-nested square brackets.
586 Toks.push_back(Tok);
587 ConsumeBracket();
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000588 ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000589 break;
590 case tok::l_brace:
591 // Recursively consume properly-nested braces.
592 Toks.push_back(Tok);
593 ConsumeBrace();
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000594 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000595 break;
596
597 // Okay, we found a ']' or '}' or ')', which we think should be balanced.
598 // Since the user wasn't looking for this token (if they were, it would
599 // already be handled), this isn't balanced. If there is a LHS token at a
600 // higher level, we will assume that this matches the unbalanced token
601 // and return it. Otherwise, this is a spurious RHS token, which we skip.
602 case tok::r_paren:
603 if (ParenCount && !isFirstTokenConsumed)
604 return false; // Matches something.
605 Toks.push_back(Tok);
606 ConsumeParen();
607 break;
608 case tok::r_square:
609 if (BracketCount && !isFirstTokenConsumed)
610 return false; // Matches something.
611 Toks.push_back(Tok);
612 ConsumeBracket();
613 break;
614 case tok::r_brace:
615 if (BraceCount && !isFirstTokenConsumed)
616 return false; // Matches something.
617 Toks.push_back(Tok);
618 ConsumeBrace();
619 break;
620
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000621 case tok::code_completion:
622 Toks.push_back(Tok);
623 ConsumeCodeCompletionToken();
624 break;
625
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000626 case tok::string_literal:
627 case tok::wide_string_literal:
Douglas Gregorfb65e592011-07-27 05:40:30 +0000628 case tok::utf8_string_literal:
629 case tok::utf16_string_literal:
630 case tok::utf32_string_literal:
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000631 Toks.push_back(Tok);
632 ConsumeStringToken();
633 break;
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000634 case tok::semi:
635 if (StopAtSemi)
636 return false;
637 // FALL THROUGH.
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000638 default:
639 // consume this token.
640 Toks.push_back(Tok);
641 ConsumeToken();
642 break;
643 }
644 isFirstTokenConsumed = false;
645 }
646}
Sebastian Redla74948d2011-09-24 17:48:25 +0000647
648/// \brief Consume tokens and store them in the passed token container until
649/// we've passed the try keyword and constructor initializers and have consumed
Sebastian Redl0d164012011-09-30 08:32:17 +0000650/// the opening brace of the function body. The opening brace will be consumed
651/// if and only if there was no error.
Sebastian Redla74948d2011-09-24 17:48:25 +0000652///
Richard Smithcde3fd82013-07-04 00:13:48 +0000653/// \return True on error.
Sebastian Redl0d164012011-09-30 08:32:17 +0000654bool Parser::ConsumeAndStoreFunctionPrologue(CachedTokens &Toks) {
Sebastian Redla74948d2011-09-24 17:48:25 +0000655 if (Tok.is(tok::kw_try)) {
656 Toks.push_back(Tok);
657 ConsumeToken();
658 }
Richard Smithcde3fd82013-07-04 00:13:48 +0000659
660 if (Tok.isNot(tok::colon)) {
661 // Easy case, just a function body.
662
663 // Grab any remaining garbage to be diagnosed later. We stop when we reach a
664 // brace: an opening one is the function body, while a closing one probably
665 // means we've reached the end of the class.
666 ConsumeAndStoreUntil(tok::l_brace, tok::r_brace, Toks,
667 /*StopAtSemi=*/true,
668 /*ConsumeFinalToken=*/false);
669 if (Tok.isNot(tok::l_brace))
Alp Tokerec543272013-12-24 09:48:30 +0000670 return Diag(Tok.getLocation(), diag::err_expected) << tok::l_brace;
Richard Smithcde3fd82013-07-04 00:13:48 +0000671
Sebastian Redla74948d2011-09-24 17:48:25 +0000672 Toks.push_back(Tok);
Richard Smithcde3fd82013-07-04 00:13:48 +0000673 ConsumeBrace();
674 return false;
Eli Friedman7cd4a9b2012-02-22 04:49:04 +0000675 }
Sebastian Redl0d164012011-09-30 08:32:17 +0000676
677 Toks.push_back(Tok);
Richard Smithcde3fd82013-07-04 00:13:48 +0000678 ConsumeToken();
679
680 // We can't reliably skip over a mem-initializer-id, because it could be
681 // a template-id involving not-yet-declared names. Given:
682 //
683 // S ( ) : a < b < c > ( e )
684 //
685 // 'e' might be an initializer or part of a template argument, depending
686 // on whether 'b' is a template.
687
688 // Track whether we might be inside a template argument. We can give
689 // significantly better diagnostics if we know that we're not.
690 bool MightBeTemplateArgument = false;
691
692 while (true) {
693 // Skip over the mem-initializer-id, if possible.
694 if (Tok.is(tok::kw_decltype)) {
695 Toks.push_back(Tok);
696 SourceLocation OpenLoc = ConsumeToken();
697 if (Tok.isNot(tok::l_paren))
698 return Diag(Tok.getLocation(), diag::err_expected_lparen_after)
699 << "decltype";
700 Toks.push_back(Tok);
701 ConsumeParen();
702 if (!ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/true)) {
Alp Tokerec543272013-12-24 09:48:30 +0000703 Diag(Tok.getLocation(), diag::err_expected) << tok::r_paren;
704 Diag(OpenLoc, diag::note_matching) << tok::l_paren;
Richard Smithcde3fd82013-07-04 00:13:48 +0000705 return true;
706 }
707 }
708 do {
709 // Walk over a component of a nested-name-specifier.
710 if (Tok.is(tok::coloncolon)) {
711 Toks.push_back(Tok);
712 ConsumeToken();
713
714 if (Tok.is(tok::kw_template)) {
715 Toks.push_back(Tok);
716 ConsumeToken();
717 }
718 }
719
720 if (Tok.is(tok::identifier) || Tok.is(tok::kw_template)) {
721 Toks.push_back(Tok);
722 ConsumeToken();
723 } else if (Tok.is(tok::code_completion)) {
724 Toks.push_back(Tok);
725 ConsumeCodeCompletionToken();
726 // Consume the rest of the initializers permissively.
727 // FIXME: We should be able to perform code-completion here even if
728 // there isn't a subsequent '{' token.
729 MightBeTemplateArgument = true;
730 break;
731 } else {
732 break;
733 }
734 } while (Tok.is(tok::coloncolon));
735
736 if (Tok.is(tok::less))
737 MightBeTemplateArgument = true;
738
739 if (MightBeTemplateArgument) {
740 // We may be inside a template argument list. Grab up to the start of the
741 // next parenthesized initializer or braced-init-list. This *might* be the
742 // initializer, or it might be a subexpression in the template argument
743 // list.
744 // FIXME: Count angle brackets, and clear MightBeTemplateArgument
745 // if all angles are closed.
746 if (!ConsumeAndStoreUntil(tok::l_paren, tok::l_brace, Toks,
747 /*StopAtSemi=*/true,
748 /*ConsumeFinalToken=*/false)) {
749 // We're not just missing the initializer, we're also missing the
750 // function body!
Alp Tokerec543272013-12-24 09:48:30 +0000751 return Diag(Tok.getLocation(), diag::err_expected) << tok::l_brace;
Richard Smithcde3fd82013-07-04 00:13:48 +0000752 }
753 } else if (Tok.isNot(tok::l_paren) && Tok.isNot(tok::l_brace)) {
754 // We found something weird in a mem-initializer-id.
Alp Tokerec543272013-12-24 09:48:30 +0000755 if (getLangOpts().CPlusPlus11)
756 return Diag(Tok.getLocation(), diag::err_expected_either)
757 << tok::l_paren << tok::l_brace;
758 else
759 return Diag(Tok.getLocation(), diag::err_expected) << tok::l_paren;
Richard Smithcde3fd82013-07-04 00:13:48 +0000760 }
761
762 tok::TokenKind kind = Tok.getKind();
763 Toks.push_back(Tok);
764 bool IsLParen = (kind == tok::l_paren);
765 SourceLocation OpenLoc = Tok.getLocation();
766
767 if (IsLParen) {
768 ConsumeParen();
769 } else {
770 assert(kind == tok::l_brace && "Must be left paren or brace here.");
771 ConsumeBrace();
772 // In C++03, this has to be the start of the function body, which
773 // means the initializer is malformed; we'll diagnose it later.
774 if (!getLangOpts().CPlusPlus11)
775 return false;
776 }
777
778 // Grab the initializer (or the subexpression of the template argument).
779 // FIXME: If we support lambdas here, we'll need to set StopAtSemi to false
780 // if we might be inside the braces of a lambda-expression.
Alp Tokerec543272013-12-24 09:48:30 +0000781 tok::TokenKind CloseKind = IsLParen ? tok::r_paren : tok::r_brace;
782 if (!ConsumeAndStoreUntil(CloseKind, Toks, /*StopAtSemi=*/true)) {
783 Diag(Tok, diag::err_expected) << CloseKind;
784 Diag(OpenLoc, diag::note_matching) << kind;
Richard Smithcde3fd82013-07-04 00:13:48 +0000785 return true;
786 }
787
788 // Grab pack ellipsis, if present.
789 if (Tok.is(tok::ellipsis)) {
790 Toks.push_back(Tok);
791 ConsumeToken();
792 }
793
794 // If we know we just consumed a mem-initializer, we must have ',' or '{'
795 // next.
796 if (Tok.is(tok::comma)) {
797 Toks.push_back(Tok);
798 ConsumeToken();
799 } else if (Tok.is(tok::l_brace)) {
800 // This is the function body if the ')' or '}' is immediately followed by
801 // a '{'. That cannot happen within a template argument, apart from the
802 // case where a template argument contains a compound literal:
803 //
804 // S ( ) : a < b < c > ( d ) { }
805 // // End of declaration, or still inside the template argument?
806 //
807 // ... and the case where the template argument contains a lambda:
808 //
809 // S ( ) : a < 0 && b < c > ( d ) + [ ] ( ) { return 0; }
810 // ( ) > ( ) { }
811 //
812 // FIXME: Disambiguate these cases. Note that the latter case is probably
813 // going to be made ill-formed by core issue 1607.
814 Toks.push_back(Tok);
815 ConsumeBrace();
816 return false;
817 } else if (!MightBeTemplateArgument) {
Alp Tokerec543272013-12-24 09:48:30 +0000818 return Diag(Tok.getLocation(), diag::err_expected_either) << tok::l_brace
819 << tok::comma;
Richard Smithcde3fd82013-07-04 00:13:48 +0000820 }
821 }
Sebastian Redla74948d2011-09-24 17:48:25 +0000822}
Richard Smith1fff95c2013-09-12 23:28:08 +0000823
824/// \brief Consume and store tokens from the '?' to the ':' in a conditional
825/// expression.
826bool Parser::ConsumeAndStoreConditional(CachedTokens &Toks) {
827 // Consume '?'.
828 assert(Tok.is(tok::question));
829 Toks.push_back(Tok);
830 ConsumeToken();
831
832 while (Tok.isNot(tok::colon)) {
833 if (!ConsumeAndStoreUntil(tok::question, tok::colon, Toks, /*StopAtSemi*/true,
834 /*ConsumeFinalToken*/false))
835 return false;
836
837 // If we found a nested conditional, consume it.
838 if (Tok.is(tok::question) && !ConsumeAndStoreConditional(Toks))
839 return false;
840 }
841
842 // Consume ':'.
843 Toks.push_back(Tok);
844 ConsumeToken();
845 return true;
846}
847
848/// \brief A tentative parsing action that can also revert token annotations.
849class Parser::UnannotatedTentativeParsingAction : public TentativeParsingAction {
850public:
851 explicit UnannotatedTentativeParsingAction(Parser &Self,
852 tok::TokenKind EndKind)
853 : TentativeParsingAction(Self), Self(Self), EndKind(EndKind) {
854 // Stash away the old token stream, so we can restore it once the
855 // tentative parse is complete.
856 TentativeParsingAction Inner(Self);
857 Self.ConsumeAndStoreUntil(EndKind, Toks, true, /*ConsumeFinalToken*/false);
858 Inner.Revert();
859 }
860
861 void RevertAnnotations() {
862 Revert();
863
864 // Put back the original tokens.
Alexey Bataevee6507d2013-11-18 08:17:37 +0000865 Self.SkipUntil(EndKind, StopAtSemi | StopBeforeMatch);
Richard Smith1fff95c2013-09-12 23:28:08 +0000866 if (Toks.size()) {
867 Token *Buffer = new Token[Toks.size()];
868 std::copy(Toks.begin() + 1, Toks.end(), Buffer);
869 Buffer[Toks.size() - 1] = Self.Tok;
870 Self.PP.EnterTokenStream(Buffer, Toks.size(), true, /*Owned*/true);
871
872 Self.Tok = Toks.front();
873 }
874 }
875
876private:
877 Parser &Self;
878 CachedTokens Toks;
879 tok::TokenKind EndKind;
880};
881
882/// ConsumeAndStoreInitializer - Consume and store the token at the passed token
883/// container until the end of the current initializer expression (either a
884/// default argument or an in-class initializer for a non-static data member).
885/// The final token is not consumed.
886bool Parser::ConsumeAndStoreInitializer(CachedTokens &Toks,
887 CachedInitKind CIK) {
888 // We always want this function to consume at least one token if not at EOF.
889 bool IsFirstTokenConsumed = true;
890
891 // Number of possible unclosed <s we've seen so far. These might be templates,
892 // and might not, but if there were none of them (or we know for sure that
893 // we're within a template), we can avoid a tentative parse.
894 unsigned AngleCount = 0;
895 unsigned KnownTemplateCount = 0;
896
897 while (1) {
898 switch (Tok.getKind()) {
899 case tok::comma:
900 // If we might be in a template, perform a tentative parse to check.
901 if (!AngleCount)
902 // Not a template argument: this is the end of the initializer.
903 return true;
904 if (KnownTemplateCount)
905 goto consume_token;
906
907 // We hit a comma inside angle brackets. This is the hard case. The
908 // rule we follow is:
909 // * For a default argument, if the tokens after the comma form a
910 // syntactically-valid parameter-declaration-clause, in which each
911 // parameter has an initializer, then this comma ends the default
912 // argument.
913 // * For a default initializer, if the tokens after the comma form a
914 // syntactically-valid init-declarator-list, then this comma ends
915 // the default initializer.
916 {
917 UnannotatedTentativeParsingAction PA(*this,
918 CIK == CIK_DefaultInitializer
919 ? tok::semi : tok::r_paren);
920 Sema::TentativeAnalysisScope Scope(Actions);
921
922 TPResult Result = TPResult::Error();
923 ConsumeToken();
924 switch (CIK) {
925 case CIK_DefaultInitializer:
926 Result = TryParseInitDeclaratorList();
927 // If we parsed a complete, ambiguous init-declarator-list, this
928 // is only syntactically-valid if it's followed by a semicolon.
929 if (Result == TPResult::Ambiguous() && Tok.isNot(tok::semi))
930 Result = TPResult::False();
931 break;
932
933 case CIK_DefaultArgument:
934 bool InvalidAsDeclaration = false;
935 Result = TryParseParameterDeclarationClause(
936 &InvalidAsDeclaration, /*VersusTemplateArgument*/true);
937 // If this is an expression or a declaration with a missing
938 // 'typename', assume it's not a declaration.
939 if (Result == TPResult::Ambiguous() && InvalidAsDeclaration)
940 Result = TPResult::False();
941 break;
942 }
943
944 // If what follows could be a declaration, it is a declaration.
945 if (Result != TPResult::False() && Result != TPResult::Error()) {
946 PA.Revert();
947 return true;
948 }
949
950 // In the uncommon case that we decide the following tokens are part
951 // of a template argument, revert any annotations we've performed in
952 // those tokens. We're not going to look them up until we've parsed
953 // the rest of the class, and that might add more declarations.
954 PA.RevertAnnotations();
955 }
956
957 // Keep going. We know we're inside a template argument list now.
958 ++KnownTemplateCount;
959 goto consume_token;
960
961 case tok::eof:
Richard Smith34f30512013-11-23 04:06:09 +0000962 case tok::annot_module_begin:
963 case tok::annot_module_end:
964 case tok::annot_module_include:
Richard Smith1fff95c2013-09-12 23:28:08 +0000965 // Ran out of tokens.
966 return false;
967
968 case tok::less:
969 // FIXME: A '<' can only start a template-id if it's preceded by an
970 // identifier, an operator-function-id, or a literal-operator-id.
971 ++AngleCount;
972 goto consume_token;
973
974 case tok::question:
975 // In 'a ? b : c', 'b' can contain an unparenthesized comma. If it does,
976 // that is *never* the end of the initializer. Skip to the ':'.
977 if (!ConsumeAndStoreConditional(Toks))
978 return false;
979 break;
980
981 case tok::greatergreatergreater:
982 if (!getLangOpts().CPlusPlus11)
983 goto consume_token;
984 if (AngleCount) --AngleCount;
985 if (KnownTemplateCount) --KnownTemplateCount;
986 // Fall through.
987 case tok::greatergreater:
988 if (!getLangOpts().CPlusPlus11)
989 goto consume_token;
990 if (AngleCount) --AngleCount;
991 if (KnownTemplateCount) --KnownTemplateCount;
992 // Fall through.
993 case tok::greater:
994 if (AngleCount) --AngleCount;
995 if (KnownTemplateCount) --KnownTemplateCount;
996 goto consume_token;
997
998 case tok::kw_template:
999 // 'template' identifier '<' is known to start a template argument list,
1000 // and can be used to disambiguate the parse.
1001 // FIXME: Support all forms of 'template' unqualified-id '<'.
1002 Toks.push_back(Tok);
1003 ConsumeToken();
1004 if (Tok.is(tok::identifier)) {
1005 Toks.push_back(Tok);
1006 ConsumeToken();
1007 if (Tok.is(tok::less)) {
1008 ++KnownTemplateCount;
1009 Toks.push_back(Tok);
1010 ConsumeToken();
1011 }
1012 }
1013 break;
1014
1015 case tok::kw_operator:
1016 // If 'operator' precedes other punctuation, that punctuation loses
1017 // its special behavior.
1018 Toks.push_back(Tok);
1019 ConsumeToken();
1020 switch (Tok.getKind()) {
1021 case tok::comma:
1022 case tok::greatergreatergreater:
1023 case tok::greatergreater:
1024 case tok::greater:
1025 case tok::less:
1026 Toks.push_back(Tok);
1027 ConsumeToken();
1028 break;
1029 default:
1030 break;
1031 }
1032 break;
1033
1034 case tok::l_paren:
1035 // Recursively consume properly-nested parens.
1036 Toks.push_back(Tok);
1037 ConsumeParen();
1038 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
1039 break;
1040 case tok::l_square:
1041 // Recursively consume properly-nested square brackets.
1042 Toks.push_back(Tok);
1043 ConsumeBracket();
1044 ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false);
1045 break;
1046 case tok::l_brace:
1047 // Recursively consume properly-nested braces.
1048 Toks.push_back(Tok);
1049 ConsumeBrace();
1050 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1051 break;
1052
1053 // Okay, we found a ']' or '}' or ')', which we think should be balanced.
1054 // Since the user wasn't looking for this token (if they were, it would
1055 // already be handled), this isn't balanced. If there is a LHS token at a
1056 // higher level, we will assume that this matches the unbalanced token
1057 // and return it. Otherwise, this is a spurious RHS token, which we skip.
1058 case tok::r_paren:
1059 if (CIK == CIK_DefaultArgument)
1060 return true; // End of the default argument.
1061 if (ParenCount && !IsFirstTokenConsumed)
1062 return false; // Matches something.
1063 goto consume_token;
1064 case tok::r_square:
1065 if (BracketCount && !IsFirstTokenConsumed)
1066 return false; // Matches something.
1067 goto consume_token;
1068 case tok::r_brace:
1069 if (BraceCount && !IsFirstTokenConsumed)
1070 return false; // Matches something.
1071 goto consume_token;
1072
1073 case tok::code_completion:
1074 Toks.push_back(Tok);
1075 ConsumeCodeCompletionToken();
1076 break;
1077
1078 case tok::string_literal:
1079 case tok::wide_string_literal:
1080 case tok::utf8_string_literal:
1081 case tok::utf16_string_literal:
1082 case tok::utf32_string_literal:
1083 Toks.push_back(Tok);
1084 ConsumeStringToken();
1085 break;
1086 case tok::semi:
1087 if (CIK == CIK_DefaultInitializer)
1088 return true; // End of the default initializer.
1089 // FALL THROUGH.
1090 default:
1091 consume_token:
1092 Toks.push_back(Tok);
1093 ConsumeToken();
1094 break;
1095 }
1096 IsFirstTokenConsumed = false;
1097 }
1098}