blob: 595b16e97a9b7d64e567e28cb39a86071b414227 [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(
Nico Weber77c76c52014-05-10 17:43:15 +000038 TemplateInfo.TemplateParams ? TemplateInfo.TemplateParams->data() : 0,
39 TemplateInfo.TemplateParams ? TemplateInfo.TemplateParams->size() : 0);
Alexis Hunt1deb9722010-04-14 23:07:37 +000040
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;
Nico Weber77c76c52014-05-10 17:43:15 +0000265 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
266 HasTemplateScope);
Richard Smithc8378952013-04-29 11:55:38 +0000267 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
268 if (HasTemplateScope) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000269 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
Richard Smithc8378952013-04-29 11:55:38 +0000270 ++CurTemplateDepthTracker;
271 }
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000272
John McCall6df5fef2009-12-19 10:49:29 +0000273 // The current scope is still active if we're the top-level class.
274 // Otherwise we'll need to push and enter a new scope.
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000275 bool HasClassScope = !Class.TopLevelClass;
Alexis Hunt1deb9722010-04-14 23:07:37 +0000276 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope,
277 HasClassScope);
John McCall6df5fef2009-12-19 10:49:29 +0000278 if (HasClassScope)
Nico Weber77c76c52014-05-10 17:43:15 +0000279 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(),
280 Class.TagOrTemplate);
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000281
Douglas Gregorefc46952010-10-12 16:25:54 +0000282 for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
283 Class.LateParsedDeclarations[i]->ParseLexedMethodDeclarations();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000284 }
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000285
John McCall6df5fef2009-12-19 10:49:29 +0000286 if (HasClassScope)
Nico Weber77c76c52014-05-10 17:43:15 +0000287 Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(),
288 Class.TagOrTemplate);
Douglas Gregor4d87df52008-12-16 21:30:33 +0000289}
290
Douglas Gregorefc46952010-10-12 16:25:54 +0000291void Parser::ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM) {
292 // If this is a member template, introduce the template parameter scope.
293 ParseScope TemplateScope(this, Scope::TemplateParamScope, LM.TemplateScope);
Richard Smithc8378952013-04-29 11:55:38 +0000294 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
295 if (LM.TemplateScope) {
Douglas Gregorefc46952010-10-12 16:25:54 +0000296 Actions.ActOnReenterTemplateScope(getCurScope(), LM.Method);
Richard Smithc8378952013-04-29 11:55:38 +0000297 ++CurTemplateDepthTracker;
298 }
Douglas Gregorefc46952010-10-12 16:25:54 +0000299 // Start the delayed C++ method declaration
300 Actions.ActOnStartDelayedCXXMethodDeclaration(getCurScope(), LM.Method);
301
302 // Introduce the parameters into scope and parse their default
303 // arguments.
Richard Smithe233fbf2013-01-28 22:42:45 +0000304 ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
305 Scope::FunctionDeclarationScope | Scope::DeclScope);
Douglas Gregorefc46952010-10-12 16:25:54 +0000306 for (unsigned I = 0, N = LM.DefaultArgs.size(); I != N; ++I) {
307 // Introduce the parameter into scope.
Nico Weber77c76c52014-05-10 17:43:15 +0000308 Actions.ActOnDelayedCXXMethodParameter(getCurScope(),
Douglas Gregor7fcbd902012-02-21 00:37:24 +0000309 LM.DefaultArgs[I].Param);
Douglas Gregorefc46952010-10-12 16:25:54 +0000310
311 if (CachedTokens *Toks = LM.DefaultArgs[I].Toks) {
312 // Save the current token position.
313 SourceLocation origLoc = Tok.getLocation();
314
315 // Parse the default argument from its saved token stream.
316 Toks->push_back(Tok); // So that the current token doesn't get lost
317 PP.EnterTokenStream(&Toks->front(), Toks->size(), true, false);
318
319 // Consume the previously-pushed token.
320 ConsumeAnyToken();
321
322 // Consume the '='.
323 assert(Tok.is(tok::equal) && "Default argument not starting with '='");
324 SourceLocation EqualLoc = ConsumeToken();
325
326 // The argument isn't actually potentially evaluated unless it is
327 // used.
328 EnterExpressionEvaluationContext Eval(Actions,
Douglas Gregor7fcbd902012-02-21 00:37:24 +0000329 Sema::PotentiallyEvaluatedIfUsed,
330 LM.DefaultArgs[I].Param);
Douglas Gregorefc46952010-10-12 16:25:54 +0000331
Sebastian Redldb63af22012-03-14 15:54:00 +0000332 ExprResult DefArgResult;
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000333 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
Sebastian Redl6db0b1b2012-03-20 21:24:03 +0000334 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
Sebastian Redldb63af22012-03-14 15:54:00 +0000335 DefArgResult = ParseBraceInitializer();
Sebastian Redl6db0b1b2012-03-20 21:24:03 +0000336 } else
Sebastian Redldb63af22012-03-14 15:54:00 +0000337 DefArgResult = ParseAssignmentExpression();
Douglas Gregorefc46952010-10-12 16:25:54 +0000338 if (DefArgResult.isInvalid())
339 Actions.ActOnParamDefaultArgumentError(LM.DefaultArgs[I].Param);
340 else {
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000341 if (!TryConsumeToken(tok::cxx_defaultarg_end)) {
Richard Smith1fff95c2013-09-12 23:28:08 +0000342 // The last two tokens are the terminator and the saved value of
343 // Tok; the last token in the default argument is the one before
344 // those.
345 assert(Toks->size() >= 3 && "expected a token in default arg");
346 Diag(Tok.getLocation(), diag::err_default_arg_unparsed)
347 << SourceRange(Tok.getLocation(),
348 (*Toks)[Toks->size() - 3].getLocation());
349 }
Douglas Gregorefc46952010-10-12 16:25:54 +0000350 Actions.ActOnParamDefaultArgument(LM.DefaultArgs[I].Param, EqualLoc,
351 DefArgResult.take());
352 }
353
354 assert(!PP.getSourceManager().isBeforeInTranslationUnit(origLoc,
355 Tok.getLocation()) &&
356 "ParseAssignmentExpression went over the default arg tokens!");
357 // There could be leftover tokens (e.g. because of an error).
358 // Skip through until we reach the original token position.
359 while (Tok.getLocation() != origLoc && Tok.isNot(tok::eof))
360 ConsumeAnyToken();
361
362 delete Toks;
363 LM.DefaultArgs[I].Toks = 0;
364 }
365 }
Douglas Gregor433e0532012-04-16 18:27:27 +0000366
Douglas Gregorefc46952010-10-12 16:25:54 +0000367 PrototypeScope.Exit();
368
369 // Finish the delayed C++ method declaration.
370 Actions.ActOnFinishDelayedCXXMethodDeclaration(getCurScope(), LM.Method);
371}
372
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000373/// ParseLexedMethodDefs - We finished parsing the member specification of a top
374/// (non-nested) C++ class. Now go over the stack of lexed methods that were
375/// collected during its parsing and parse them all.
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000376void Parser::ParseLexedMethodDefs(ParsingClass &Class) {
377 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
Douglas Gregorefc46952010-10-12 16:25:54 +0000378 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope, HasTemplateScope);
Richard Smithc8378952013-04-29 11:55:38 +0000379 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
380 if (HasTemplateScope) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000381 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
Richard Smithc8378952013-04-29 11:55:38 +0000382 ++CurTemplateDepthTracker;
383 }
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000384 bool HasClassScope = !Class.TopLevelClass;
385 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope,
386 HasClassScope);
387
Douglas Gregorefc46952010-10-12 16:25:54 +0000388 for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
389 Class.LateParsedDeclarations[i]->ParseLexedMethodDefs();
390 }
391}
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000392
Douglas Gregorefc46952010-10-12 16:25:54 +0000393void Parser::ParseLexedMethodDef(LexedMethod &LM) {
394 // If this is a member template, introduce the template parameter scope.
395 ParseScope TemplateScope(this, Scope::TemplateParamScope, LM.TemplateScope);
Richard Smithc8378952013-04-29 11:55:38 +0000396 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
397 if (LM.TemplateScope) {
Douglas Gregorefc46952010-10-12 16:25:54 +0000398 Actions.ActOnReenterTemplateScope(getCurScope(), LM.D);
Richard Smithc8378952013-04-29 11:55:38 +0000399 ++CurTemplateDepthTracker;
400 }
Douglas Gregorefc46952010-10-12 16:25:54 +0000401 // Save the current token position.
402 SourceLocation origLoc = Tok.getLocation();
Argyrios Kyrtzidis02041972010-03-31 00:38:09 +0000403
Douglas Gregorefc46952010-10-12 16:25:54 +0000404 assert(!LM.Toks.empty() && "Empty body!");
405 // Append the current token at the end of the new token stream so that it
406 // doesn't get lost.
407 LM.Toks.push_back(Tok);
408 PP.EnterTokenStream(LM.Toks.data(), LM.Toks.size(), true, false);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000409
Douglas Gregorefc46952010-10-12 16:25:54 +0000410 // Consume the previously pushed token.
Argyrios Kyrtzidisc36633c2013-03-27 23:58:17 +0000411 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
Douglas Gregorefc46952010-10-12 16:25:54 +0000412 assert((Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try))
413 && "Inline method not starting with '{', ':' or 'try'");
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000414
Douglas Gregorefc46952010-10-12 16:25:54 +0000415 // Parse the method body. Function body parsing code is similar enough
416 // to be re-used for method bodies as well.
417 ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope);
418 Actions.ActOnStartOfFunctionDef(getCurScope(), LM.D);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000419
Douglas Gregorefc46952010-10-12 16:25:54 +0000420 if (Tok.is(tok::kw_try)) {
Douglas Gregora0ff0c32011-03-16 17:05:57 +0000421 ParseFunctionTryBlock(LM.D, FnScope);
Douglas Gregorefc46952010-10-12 16:25:54 +0000422 assert(!PP.getSourceManager().isBeforeInTranslationUnit(origLoc,
423 Tok.getLocation()) &&
424 "ParseFunctionTryBlock went over the cached tokens!");
425 // There could be leftover tokens (e.g. because of an error).
426 // Skip through until we reach the original token position.
427 while (Tok.getLocation() != origLoc && Tok.isNot(tok::eof))
428 ConsumeAnyToken();
429 return;
430 }
431 if (Tok.is(tok::colon)) {
432 ParseConstructorInitializer(LM.D);
433
434 // Error recovery.
435 if (!Tok.is(tok::l_brace)) {
Douglas Gregora0ff0c32011-03-16 17:05:57 +0000436 FnScope.Exit();
Douglas Gregorefc46952010-10-12 16:25:54 +0000437 Actions.ActOnFinishFunctionBody(LM.D, 0);
Matt Beaumont-Gayd0457922011-09-23 22:39:23 +0000438 while (Tok.getLocation() != origLoc && Tok.isNot(tok::eof))
439 ConsumeAnyToken();
Douglas Gregorefc46952010-10-12 16:25:54 +0000440 return;
441 }
442 } else
443 Actions.ActOnDefaultCtorInitializers(LM.D);
444
Richard Smithc8378952013-04-29 11:55:38 +0000445 assert((Actions.getDiagnostics().hasErrorOccurred() ||
446 !isa<FunctionTemplateDecl>(LM.D) ||
447 cast<FunctionTemplateDecl>(LM.D)->getTemplateParameters()->getDepth()
448 < TemplateParameterDepth) &&
449 "TemplateParameterDepth should be greater than the depth of "
450 "current template being instantiated!");
451
Douglas Gregora0ff0c32011-03-16 17:05:57 +0000452 ParseFunctionStatementBody(LM.D, FnScope);
Douglas Gregorefc46952010-10-12 16:25:54 +0000453
John McCalle68672f2013-03-14 05:13:41 +0000454 // Clear the late-template-parsed bit if we set it before.
Alp Tokera2794f92014-01-22 07:29:52 +0000455 if (LM.D)
456 LM.D->getAsFunction()->setLateTemplateParsed(false);
John McCalle68672f2013-03-14 05:13:41 +0000457
Douglas Gregorefc46952010-10-12 16:25:54 +0000458 if (Tok.getLocation() != origLoc) {
459 // Due to parsing error, we either went over the cached tokens or
460 // there are still cached tokens left. If it's the latter case skip the
461 // leftover tokens.
462 // Since this is an uncommon situation that should be avoided, use the
463 // expensive isBeforeInTranslationUnit call.
464 if (PP.getSourceManager().isBeforeInTranslationUnit(Tok.getLocation(),
465 origLoc))
Argyrios Kyrtzidise1224c82010-06-19 19:58:34 +0000466 while (Tok.getLocation() != origLoc && Tok.isNot(tok::eof))
Argyrios Kyrtzidise9b76af2010-06-17 10:52:22 +0000467 ConsumeAnyToken();
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000468 }
469}
470
Richard Smith938f40b2011-06-11 17:19:42 +0000471/// ParseLexedMemberInitializers - We finished parsing the member specification
472/// of a top (non-nested) C++ class. Now go over the stack of lexed data member
473/// initializers that were collected during its parsing and parse them all.
474void Parser::ParseLexedMemberInitializers(ParsingClass &Class) {
475 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
476 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
477 HasTemplateScope);
Richard Smithc8378952013-04-29 11:55:38 +0000478 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
479 if (HasTemplateScope) {
Richard Smith938f40b2011-06-11 17:19:42 +0000480 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
Richard Smithc8378952013-04-29 11:55:38 +0000481 ++CurTemplateDepthTracker;
482 }
Douglas Gregor3024f072012-04-16 07:05:22 +0000483 // Set or update the scope flags.
Richard Smith938f40b2011-06-11 17:19:42 +0000484 bool AlreadyHasClassScope = Class.TopLevelClass;
Douglas Gregor3024f072012-04-16 07:05:22 +0000485 unsigned ScopeFlags = Scope::ClassScope|Scope::DeclScope;
Richard Smith938f40b2011-06-11 17:19:42 +0000486 ParseScope ClassScope(this, ScopeFlags, !AlreadyHasClassScope);
487 ParseScopeFlags ClassScopeFlags(this, ScopeFlags, AlreadyHasClassScope);
488
489 if (!AlreadyHasClassScope)
490 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(),
491 Class.TagOrTemplate);
492
Benjamin Kramer1d373c62012-05-17 12:01:52 +0000493 if (!Class.LateParsedDeclarations.empty()) {
Douglas Gregor3024f072012-04-16 07:05:22 +0000494 // C++11 [expr.prim.general]p4:
495 // Otherwise, if a member-declarator declares a non-static data member
496 // (9.2) of a class X, the expression this is a prvalue of type "pointer
497 // to X" within the optional brace-or-equal-initializer. It shall not
498 // appear elsewhere in the member-declarator.
499 Sema::CXXThisScopeRAII ThisScope(Actions, Class.TagOrTemplate,
500 /*TypeQuals=*/(unsigned)0);
Richard Smith938f40b2011-06-11 17:19:42 +0000501
Douglas Gregor3024f072012-04-16 07:05:22 +0000502 for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
503 Class.LateParsedDeclarations[i]->ParseLexedMemberInitializers();
504 }
505 }
506
Richard Smith938f40b2011-06-11 17:19:42 +0000507 if (!AlreadyHasClassScope)
508 Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(),
509 Class.TagOrTemplate);
510
511 Actions.ActOnFinishDelayedMemberInitializers(Class.TagOrTemplate);
512}
513
514void Parser::ParseLexedMemberInitializer(LateParsedMemberInitializer &MI) {
Richard Smith1a526fd2011-09-29 19:42:27 +0000515 if (!MI.Field || MI.Field->isInvalidDecl())
Richard Smith938f40b2011-06-11 17:19:42 +0000516 return;
517
518 // Append the current token at the end of the new token stream so that it
519 // doesn't get lost.
520 MI.Toks.push_back(Tok);
521 PP.EnterTokenStream(MI.Toks.data(), MI.Toks.size(), true, false);
522
523 // Consume the previously pushed token.
Argyrios Kyrtzidisc36633c2013-03-27 23:58:17 +0000524 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
Richard Smith938f40b2011-06-11 17:19:42 +0000525
526 SourceLocation EqualLoc;
Richard Smith2b013182012-06-10 03:12:00 +0000527
Richard Smith74108172014-01-17 03:11:34 +0000528 Actions.ActOnStartCXXInClassMemberInitializer();
529
Douglas Gregor926410d2012-02-21 02:22:07 +0000530 ExprResult Init = ParseCXXMemberInitializer(MI.Field, /*IsFunction=*/false,
531 EqualLoc);
Richard Smith938f40b2011-06-11 17:19:42 +0000532
Richard Smith74108172014-01-17 03:11:34 +0000533 Actions.ActOnFinishCXXInClassMemberInitializer(MI.Field, EqualLoc,
534 Init.release());
Richard Smith938f40b2011-06-11 17:19:42 +0000535
536 // The next token should be our artificial terminating EOF token.
537 if (Tok.isNot(tok::eof)) {
538 SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
539 if (!EndLoc.isValid())
540 EndLoc = Tok.getLocation();
541 // No fixit; we can't recover as if there were a semicolon here.
542 Diag(EndLoc, diag::err_expected_semi_decl_list);
543
544 // Consume tokens until we hit the artificial EOF.
545 while (Tok.isNot(tok::eof))
546 ConsumeAnyToken();
547 }
548 ConsumeAnyToken();
549}
550
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000551/// ConsumeAndStoreUntil - Consume and store the token at the passed token
Douglas Gregor4d87df52008-12-16 21:30:33 +0000552/// container until the token 'T' is reached (which gets
Mike Stump11289f42009-09-09 15:08:12 +0000553/// consumed/stored too, if ConsumeFinalToken).
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000554/// If StopAtSemi is true, then we will stop early at a ';' character.
Douglas Gregor4d87df52008-12-16 21:30:33 +0000555/// Returns true if token 'T1' or 'T2' was found.
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000556/// NOTE: This is a specialized version of Parser::SkipUntil.
Douglas Gregor4d87df52008-12-16 21:30:33 +0000557bool Parser::ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
558 CachedTokens &Toks,
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000559 bool StopAtSemi, bool ConsumeFinalToken) {
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000560 // We always want this function to consume at least one token if the first
561 // token isn't T and if not at EOF.
562 bool isFirstTokenConsumed = true;
563 while (1) {
564 // If we found one of the tokens, stop and return true.
Douglas Gregor4d87df52008-12-16 21:30:33 +0000565 if (Tok.is(T1) || Tok.is(T2)) {
566 if (ConsumeFinalToken) {
567 Toks.push_back(Tok);
568 ConsumeAnyToken();
569 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000570 return true;
571 }
572
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000573 switch (Tok.getKind()) {
574 case tok::eof:
Richard Smith34f30512013-11-23 04:06:09 +0000575 case tok::annot_module_begin:
576 case tok::annot_module_end:
577 case tok::annot_module_include:
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000578 // Ran out of tokens.
579 return false;
580
581 case tok::l_paren:
582 // Recursively consume properly-nested parens.
583 Toks.push_back(Tok);
584 ConsumeParen();
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000585 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000586 break;
587 case tok::l_square:
588 // Recursively consume properly-nested square brackets.
589 Toks.push_back(Tok);
590 ConsumeBracket();
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000591 ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000592 break;
593 case tok::l_brace:
594 // Recursively consume properly-nested braces.
595 Toks.push_back(Tok);
596 ConsumeBrace();
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000597 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000598 break;
599
600 // Okay, we found a ']' or '}' or ')', which we think should be balanced.
601 // Since the user wasn't looking for this token (if they were, it would
602 // already be handled), this isn't balanced. If there is a LHS token at a
603 // higher level, we will assume that this matches the unbalanced token
604 // and return it. Otherwise, this is a spurious RHS token, which we skip.
605 case tok::r_paren:
606 if (ParenCount && !isFirstTokenConsumed)
607 return false; // Matches something.
608 Toks.push_back(Tok);
609 ConsumeParen();
610 break;
611 case tok::r_square:
612 if (BracketCount && !isFirstTokenConsumed)
613 return false; // Matches something.
614 Toks.push_back(Tok);
615 ConsumeBracket();
616 break;
617 case tok::r_brace:
618 if (BraceCount && !isFirstTokenConsumed)
619 return false; // Matches something.
620 Toks.push_back(Tok);
621 ConsumeBrace();
622 break;
623
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000624 case tok::code_completion:
625 Toks.push_back(Tok);
626 ConsumeCodeCompletionToken();
627 break;
628
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000629 case tok::string_literal:
630 case tok::wide_string_literal:
Douglas Gregorfb65e592011-07-27 05:40:30 +0000631 case tok::utf8_string_literal:
632 case tok::utf16_string_literal:
633 case tok::utf32_string_literal:
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000634 Toks.push_back(Tok);
635 ConsumeStringToken();
636 break;
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000637 case tok::semi:
638 if (StopAtSemi)
639 return false;
640 // FALL THROUGH.
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000641 default:
642 // consume this token.
643 Toks.push_back(Tok);
644 ConsumeToken();
645 break;
646 }
647 isFirstTokenConsumed = false;
648 }
649}
Sebastian Redla74948d2011-09-24 17:48:25 +0000650
651/// \brief Consume tokens and store them in the passed token container until
652/// we've passed the try keyword and constructor initializers and have consumed
Sebastian Redl0d164012011-09-30 08:32:17 +0000653/// the opening brace of the function body. The opening brace will be consumed
654/// if and only if there was no error.
Sebastian Redla74948d2011-09-24 17:48:25 +0000655///
Richard Smithcde3fd82013-07-04 00:13:48 +0000656/// \return True on error.
Sebastian Redl0d164012011-09-30 08:32:17 +0000657bool Parser::ConsumeAndStoreFunctionPrologue(CachedTokens &Toks) {
Sebastian Redla74948d2011-09-24 17:48:25 +0000658 if (Tok.is(tok::kw_try)) {
659 Toks.push_back(Tok);
660 ConsumeToken();
661 }
Richard Smithcde3fd82013-07-04 00:13:48 +0000662
663 if (Tok.isNot(tok::colon)) {
664 // Easy case, just a function body.
665
666 // Grab any remaining garbage to be diagnosed later. We stop when we reach a
667 // brace: an opening one is the function body, while a closing one probably
668 // means we've reached the end of the class.
669 ConsumeAndStoreUntil(tok::l_brace, tok::r_brace, Toks,
670 /*StopAtSemi=*/true,
671 /*ConsumeFinalToken=*/false);
672 if (Tok.isNot(tok::l_brace))
Alp Tokerec543272013-12-24 09:48:30 +0000673 return Diag(Tok.getLocation(), diag::err_expected) << tok::l_brace;
Richard Smithcde3fd82013-07-04 00:13:48 +0000674
Sebastian Redla74948d2011-09-24 17:48:25 +0000675 Toks.push_back(Tok);
Richard Smithcde3fd82013-07-04 00:13:48 +0000676 ConsumeBrace();
677 return false;
Eli Friedman7cd4a9b2012-02-22 04:49:04 +0000678 }
Sebastian Redl0d164012011-09-30 08:32:17 +0000679
680 Toks.push_back(Tok);
Richard Smithcde3fd82013-07-04 00:13:48 +0000681 ConsumeToken();
682
683 // We can't reliably skip over a mem-initializer-id, because it could be
684 // a template-id involving not-yet-declared names. Given:
685 //
686 // S ( ) : a < b < c > ( e )
687 //
688 // 'e' might be an initializer or part of a template argument, depending
689 // on whether 'b' is a template.
690
691 // Track whether we might be inside a template argument. We can give
692 // significantly better diagnostics if we know that we're not.
693 bool MightBeTemplateArgument = false;
694
695 while (true) {
696 // Skip over the mem-initializer-id, if possible.
697 if (Tok.is(tok::kw_decltype)) {
698 Toks.push_back(Tok);
699 SourceLocation OpenLoc = ConsumeToken();
700 if (Tok.isNot(tok::l_paren))
701 return Diag(Tok.getLocation(), diag::err_expected_lparen_after)
702 << "decltype";
703 Toks.push_back(Tok);
704 ConsumeParen();
705 if (!ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/true)) {
Alp Tokerec543272013-12-24 09:48:30 +0000706 Diag(Tok.getLocation(), diag::err_expected) << tok::r_paren;
707 Diag(OpenLoc, diag::note_matching) << tok::l_paren;
Richard Smithcde3fd82013-07-04 00:13:48 +0000708 return true;
709 }
710 }
711 do {
712 // Walk over a component of a nested-name-specifier.
713 if (Tok.is(tok::coloncolon)) {
714 Toks.push_back(Tok);
715 ConsumeToken();
716
717 if (Tok.is(tok::kw_template)) {
718 Toks.push_back(Tok);
719 ConsumeToken();
720 }
721 }
722
723 if (Tok.is(tok::identifier) || Tok.is(tok::kw_template)) {
724 Toks.push_back(Tok);
725 ConsumeToken();
726 } else if (Tok.is(tok::code_completion)) {
727 Toks.push_back(Tok);
728 ConsumeCodeCompletionToken();
729 // Consume the rest of the initializers permissively.
730 // FIXME: We should be able to perform code-completion here even if
731 // there isn't a subsequent '{' token.
732 MightBeTemplateArgument = true;
733 break;
734 } else {
735 break;
736 }
737 } while (Tok.is(tok::coloncolon));
738
739 if (Tok.is(tok::less))
740 MightBeTemplateArgument = true;
741
742 if (MightBeTemplateArgument) {
743 // We may be inside a template argument list. Grab up to the start of the
744 // next parenthesized initializer or braced-init-list. This *might* be the
745 // initializer, or it might be a subexpression in the template argument
746 // list.
747 // FIXME: Count angle brackets, and clear MightBeTemplateArgument
748 // if all angles are closed.
749 if (!ConsumeAndStoreUntil(tok::l_paren, tok::l_brace, Toks,
750 /*StopAtSemi=*/true,
751 /*ConsumeFinalToken=*/false)) {
752 // We're not just missing the initializer, we're also missing the
753 // function body!
Alp Tokerec543272013-12-24 09:48:30 +0000754 return Diag(Tok.getLocation(), diag::err_expected) << tok::l_brace;
Richard Smithcde3fd82013-07-04 00:13:48 +0000755 }
756 } else if (Tok.isNot(tok::l_paren) && Tok.isNot(tok::l_brace)) {
757 // We found something weird in a mem-initializer-id.
Alp Tokerec543272013-12-24 09:48:30 +0000758 if (getLangOpts().CPlusPlus11)
759 return Diag(Tok.getLocation(), diag::err_expected_either)
760 << tok::l_paren << tok::l_brace;
761 else
762 return Diag(Tok.getLocation(), diag::err_expected) << tok::l_paren;
Richard Smithcde3fd82013-07-04 00:13:48 +0000763 }
764
765 tok::TokenKind kind = Tok.getKind();
766 Toks.push_back(Tok);
767 bool IsLParen = (kind == tok::l_paren);
768 SourceLocation OpenLoc = Tok.getLocation();
769
770 if (IsLParen) {
771 ConsumeParen();
772 } else {
773 assert(kind == tok::l_brace && "Must be left paren or brace here.");
774 ConsumeBrace();
775 // In C++03, this has to be the start of the function body, which
776 // means the initializer is malformed; we'll diagnose it later.
777 if (!getLangOpts().CPlusPlus11)
778 return false;
779 }
780
781 // Grab the initializer (or the subexpression of the template argument).
782 // FIXME: If we support lambdas here, we'll need to set StopAtSemi to false
783 // if we might be inside the braces of a lambda-expression.
Alp Tokerec543272013-12-24 09:48:30 +0000784 tok::TokenKind CloseKind = IsLParen ? tok::r_paren : tok::r_brace;
785 if (!ConsumeAndStoreUntil(CloseKind, Toks, /*StopAtSemi=*/true)) {
786 Diag(Tok, diag::err_expected) << CloseKind;
787 Diag(OpenLoc, diag::note_matching) << kind;
Richard Smithcde3fd82013-07-04 00:13:48 +0000788 return true;
789 }
790
791 // Grab pack ellipsis, if present.
792 if (Tok.is(tok::ellipsis)) {
793 Toks.push_back(Tok);
794 ConsumeToken();
795 }
796
797 // If we know we just consumed a mem-initializer, we must have ',' or '{'
798 // next.
799 if (Tok.is(tok::comma)) {
800 Toks.push_back(Tok);
801 ConsumeToken();
802 } else if (Tok.is(tok::l_brace)) {
803 // This is the function body if the ')' or '}' is immediately followed by
804 // a '{'. That cannot happen within a template argument, apart from the
805 // case where a template argument contains a compound literal:
806 //
807 // S ( ) : a < b < c > ( d ) { }
808 // // End of declaration, or still inside the template argument?
809 //
810 // ... and the case where the template argument contains a lambda:
811 //
812 // S ( ) : a < 0 && b < c > ( d ) + [ ] ( ) { return 0; }
813 // ( ) > ( ) { }
814 //
815 // FIXME: Disambiguate these cases. Note that the latter case is probably
816 // going to be made ill-formed by core issue 1607.
817 Toks.push_back(Tok);
818 ConsumeBrace();
819 return false;
820 } else if (!MightBeTemplateArgument) {
Alp Tokerec543272013-12-24 09:48:30 +0000821 return Diag(Tok.getLocation(), diag::err_expected_either) << tok::l_brace
822 << tok::comma;
Richard Smithcde3fd82013-07-04 00:13:48 +0000823 }
824 }
Sebastian Redla74948d2011-09-24 17:48:25 +0000825}
Richard Smith1fff95c2013-09-12 23:28:08 +0000826
827/// \brief Consume and store tokens from the '?' to the ':' in a conditional
828/// expression.
829bool Parser::ConsumeAndStoreConditional(CachedTokens &Toks) {
830 // Consume '?'.
831 assert(Tok.is(tok::question));
832 Toks.push_back(Tok);
833 ConsumeToken();
834
835 while (Tok.isNot(tok::colon)) {
Nico Weber77c76c52014-05-10 17:43:15 +0000836 if (!ConsumeAndStoreUntil(tok::question, tok::colon, Toks,
837 /*StopAtSemi=*/true,
838 /*ConsumeFinalToken=*/false))
Richard Smith1fff95c2013-09-12 23:28:08 +0000839 return false;
840
841 // If we found a nested conditional, consume it.
842 if (Tok.is(tok::question) && !ConsumeAndStoreConditional(Toks))
843 return false;
844 }
845
846 // Consume ':'.
847 Toks.push_back(Tok);
848 ConsumeToken();
849 return true;
850}
851
852/// \brief A tentative parsing action that can also revert token annotations.
853class Parser::UnannotatedTentativeParsingAction : public TentativeParsingAction {
854public:
855 explicit UnannotatedTentativeParsingAction(Parser &Self,
856 tok::TokenKind EndKind)
857 : TentativeParsingAction(Self), Self(Self), EndKind(EndKind) {
858 // Stash away the old token stream, so we can restore it once the
859 // tentative parse is complete.
860 TentativeParsingAction Inner(Self);
861 Self.ConsumeAndStoreUntil(EndKind, Toks, true, /*ConsumeFinalToken*/false);
862 Inner.Revert();
863 }
864
865 void RevertAnnotations() {
866 Revert();
867
868 // Put back the original tokens.
Alexey Bataevee6507d2013-11-18 08:17:37 +0000869 Self.SkipUntil(EndKind, StopAtSemi | StopBeforeMatch);
Richard Smith1fff95c2013-09-12 23:28:08 +0000870 if (Toks.size()) {
871 Token *Buffer = new Token[Toks.size()];
872 std::copy(Toks.begin() + 1, Toks.end(), Buffer);
873 Buffer[Toks.size() - 1] = Self.Tok;
874 Self.PP.EnterTokenStream(Buffer, Toks.size(), true, /*Owned*/true);
875
876 Self.Tok = Toks.front();
877 }
878 }
879
880private:
881 Parser &Self;
882 CachedTokens Toks;
883 tok::TokenKind EndKind;
884};
885
886/// ConsumeAndStoreInitializer - Consume and store the token at the passed token
887/// container until the end of the current initializer expression (either a
888/// default argument or an in-class initializer for a non-static data member).
889/// The final token is not consumed.
890bool Parser::ConsumeAndStoreInitializer(CachedTokens &Toks,
891 CachedInitKind CIK) {
892 // We always want this function to consume at least one token if not at EOF.
893 bool IsFirstTokenConsumed = true;
894
895 // Number of possible unclosed <s we've seen so far. These might be templates,
896 // and might not, but if there were none of them (or we know for sure that
897 // we're within a template), we can avoid a tentative parse.
898 unsigned AngleCount = 0;
899 unsigned KnownTemplateCount = 0;
900
901 while (1) {
902 switch (Tok.getKind()) {
903 case tok::comma:
904 // If we might be in a template, perform a tentative parse to check.
905 if (!AngleCount)
906 // Not a template argument: this is the end of the initializer.
907 return true;
908 if (KnownTemplateCount)
909 goto consume_token;
910
911 // We hit a comma inside angle brackets. This is the hard case. The
912 // rule we follow is:
913 // * For a default argument, if the tokens after the comma form a
914 // syntactically-valid parameter-declaration-clause, in which each
915 // parameter has an initializer, then this comma ends the default
916 // argument.
917 // * For a default initializer, if the tokens after the comma form a
918 // syntactically-valid init-declarator-list, then this comma ends
919 // the default initializer.
920 {
921 UnannotatedTentativeParsingAction PA(*this,
922 CIK == CIK_DefaultInitializer
923 ? tok::semi : tok::r_paren);
924 Sema::TentativeAnalysisScope Scope(Actions);
925
926 TPResult Result = TPResult::Error();
927 ConsumeToken();
928 switch (CIK) {
929 case CIK_DefaultInitializer:
930 Result = TryParseInitDeclaratorList();
931 // If we parsed a complete, ambiguous init-declarator-list, this
932 // is only syntactically-valid if it's followed by a semicolon.
933 if (Result == TPResult::Ambiguous() && Tok.isNot(tok::semi))
934 Result = TPResult::False();
935 break;
936
937 case CIK_DefaultArgument:
938 bool InvalidAsDeclaration = false;
939 Result = TryParseParameterDeclarationClause(
940 &InvalidAsDeclaration, /*VersusTemplateArgument*/true);
941 // If this is an expression or a declaration with a missing
942 // 'typename', assume it's not a declaration.
943 if (Result == TPResult::Ambiguous() && InvalidAsDeclaration)
944 Result = TPResult::False();
945 break;
946 }
947
948 // If what follows could be a declaration, it is a declaration.
949 if (Result != TPResult::False() && Result != TPResult::Error()) {
950 PA.Revert();
951 return true;
952 }
953
954 // In the uncommon case that we decide the following tokens are part
955 // of a template argument, revert any annotations we've performed in
956 // those tokens. We're not going to look them up until we've parsed
957 // the rest of the class, and that might add more declarations.
958 PA.RevertAnnotations();
959 }
960
961 // Keep going. We know we're inside a template argument list now.
962 ++KnownTemplateCount;
963 goto consume_token;
964
965 case tok::eof:
Richard Smith34f30512013-11-23 04:06:09 +0000966 case tok::annot_module_begin:
967 case tok::annot_module_end:
968 case tok::annot_module_include:
Richard Smith1fff95c2013-09-12 23:28:08 +0000969 // Ran out of tokens.
970 return false;
971
972 case tok::less:
973 // FIXME: A '<' can only start a template-id if it's preceded by an
974 // identifier, an operator-function-id, or a literal-operator-id.
975 ++AngleCount;
976 goto consume_token;
977
978 case tok::question:
979 // In 'a ? b : c', 'b' can contain an unparenthesized comma. If it does,
980 // that is *never* the end of the initializer. Skip to the ':'.
981 if (!ConsumeAndStoreConditional(Toks))
982 return false;
983 break;
984
985 case tok::greatergreatergreater:
986 if (!getLangOpts().CPlusPlus11)
987 goto consume_token;
988 if (AngleCount) --AngleCount;
989 if (KnownTemplateCount) --KnownTemplateCount;
990 // Fall through.
991 case tok::greatergreater:
992 if (!getLangOpts().CPlusPlus11)
993 goto consume_token;
994 if (AngleCount) --AngleCount;
995 if (KnownTemplateCount) --KnownTemplateCount;
996 // Fall through.
997 case tok::greater:
998 if (AngleCount) --AngleCount;
999 if (KnownTemplateCount) --KnownTemplateCount;
1000 goto consume_token;
1001
1002 case tok::kw_template:
1003 // 'template' identifier '<' is known to start a template argument list,
1004 // and can be used to disambiguate the parse.
1005 // FIXME: Support all forms of 'template' unqualified-id '<'.
1006 Toks.push_back(Tok);
1007 ConsumeToken();
1008 if (Tok.is(tok::identifier)) {
1009 Toks.push_back(Tok);
1010 ConsumeToken();
1011 if (Tok.is(tok::less)) {
1012 ++KnownTemplateCount;
1013 Toks.push_back(Tok);
1014 ConsumeToken();
1015 }
1016 }
1017 break;
1018
1019 case tok::kw_operator:
1020 // If 'operator' precedes other punctuation, that punctuation loses
1021 // its special behavior.
1022 Toks.push_back(Tok);
1023 ConsumeToken();
1024 switch (Tok.getKind()) {
1025 case tok::comma:
1026 case tok::greatergreatergreater:
1027 case tok::greatergreater:
1028 case tok::greater:
1029 case tok::less:
1030 Toks.push_back(Tok);
1031 ConsumeToken();
1032 break;
1033 default:
1034 break;
1035 }
1036 break;
1037
1038 case tok::l_paren:
1039 // Recursively consume properly-nested parens.
1040 Toks.push_back(Tok);
1041 ConsumeParen();
1042 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
1043 break;
1044 case tok::l_square:
1045 // Recursively consume properly-nested square brackets.
1046 Toks.push_back(Tok);
1047 ConsumeBracket();
1048 ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false);
1049 break;
1050 case tok::l_brace:
1051 // Recursively consume properly-nested braces.
1052 Toks.push_back(Tok);
1053 ConsumeBrace();
1054 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1055 break;
1056
1057 // Okay, we found a ']' or '}' or ')', which we think should be balanced.
1058 // Since the user wasn't looking for this token (if they were, it would
1059 // already be handled), this isn't balanced. If there is a LHS token at a
1060 // higher level, we will assume that this matches the unbalanced token
1061 // and return it. Otherwise, this is a spurious RHS token, which we skip.
1062 case tok::r_paren:
1063 if (CIK == CIK_DefaultArgument)
1064 return true; // End of the default argument.
1065 if (ParenCount && !IsFirstTokenConsumed)
1066 return false; // Matches something.
1067 goto consume_token;
1068 case tok::r_square:
1069 if (BracketCount && !IsFirstTokenConsumed)
1070 return false; // Matches something.
1071 goto consume_token;
1072 case tok::r_brace:
1073 if (BraceCount && !IsFirstTokenConsumed)
1074 return false; // Matches something.
1075 goto consume_token;
1076
1077 case tok::code_completion:
1078 Toks.push_back(Tok);
1079 ConsumeCodeCompletionToken();
1080 break;
1081
1082 case tok::string_literal:
1083 case tok::wide_string_literal:
1084 case tok::utf8_string_literal:
1085 case tok::utf16_string_literal:
1086 case tok::utf32_string_literal:
1087 Toks.push_back(Tok);
1088 ConsumeStringToken();
1089 break;
1090 case tok::semi:
1091 if (CIK == CIK_DefaultInitializer)
1092 return true; // End of the default initializer.
1093 // FALL THROUGH.
1094 default:
1095 consume_token:
1096 Toks.push_back(Tok);
1097 ConsumeToken();
1098 break;
1099 }
1100 IsFirstTokenConsumed = false;
1101 }
1102}