blob: 863a09e89d34c3586eef488b3882143273029b1d [file] [log] [blame]
Argyrios Kyrtzidis4cc18a42008-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 Carruth55fc8732012-12-04 09:13:33 +000015#include "RAIIObjectsForParser.h"
16#include "clang/AST/DeclTemplate.h"
17#include "clang/Parse/ParseDiagnostic.h"
John McCall19510852010-08-20 18:27:03 +000018#include "clang/Sema/DeclSpec.h"
19#include "clang/Sema/Scope.h"
Argyrios Kyrtzidis4cc18a42008-06-24 22:12:16 +000020using namespace clang;
21
John McCalle34db6b2013-03-14 05:13:41 +000022/// Get the FunctionDecl for a function or function template decl.
23static FunctionDecl *getFunctionDecl(Decl *D) {
24 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(D))
25 return fn;
26 return cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
27}
28
Sebastian Redld3a413d2009-04-26 20:35:05 +000029/// ParseCXXInlineMethodDef - We parsed and verified that the specified
Argyrios Kyrtzidis4cc18a42008-06-24 22:12:16 +000030/// Declarator is a well formed C++ inline method definition. Now lex its body
31/// and store its tokens for parsing after the C++ class is complete.
Rafael Espindola0777cf52013-01-08 21:00:12 +000032NamedDecl *Parser::ParseCXXInlineMethodDef(AccessSpecifier AS,
Erik Verbruggen5f1c8222011-10-13 09:41:32 +000033 AttributeList *AccessAttrs,
34 ParsingDeclarator &D,
Douglas Gregor45fa5602011-11-07 20:56:01 +000035 const ParsedTemplateInfo &TemplateInfo,
36 const VirtSpecifiers& VS,
37 FunctionDefinitionKind DefinitionKind,
38 ExprResult& Init) {
Abramo Bagnara075f8f12010-12-10 16:29:40 +000039 assert(D.isFunctionDeclarator() && "This isn't a function declarator!");
Sean Hunte4246a62011-05-12 06:15:49 +000040 assert((Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try) ||
41 Tok.is(tok::equal)) &&
42 "Current token not a '{', ':', '=', or 'try'!");
Argyrios Kyrtzidis4cc18a42008-06-24 22:12:16 +000043
Benjamin Kramer5354e772012-08-23 23:38:35 +000044 MultiTemplateParamsArg TemplateParams(
Sean Hunt4cd84942010-04-14 23:07:37 +000045 TemplateInfo.TemplateParams ? TemplateInfo.TemplateParams->data() : 0,
46 TemplateInfo.TemplateParams ? TemplateInfo.TemplateParams->size() : 0);
47
Rafael Espindola0777cf52013-01-08 21:00:12 +000048 NamedDecl *FnD;
Douglas Gregor45fa5602011-11-07 20:56:01 +000049 D.setFunctionDefinitionKind(DefinitionKind);
John McCall67d1a672009-08-06 02:15:43 +000050 if (D.getDeclSpec().isFriendSpecified())
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000051 FnD = Actions.ActOnFriendFunctionDecl(getCurScope(), D,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000052 TemplateParams);
Douglas Gregor147545d2011-10-10 14:49:18 +000053 else {
Douglas Gregor23c94db2010-07-02 17:43:08 +000054 FnD = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS, D,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000055 TemplateParams, 0,
Richard Smithca523302012-06-10 03:12:00 +000056 VS, ICIS_NoInit);
Douglas Gregor147545d2011-10-10 14:49:18 +000057 if (FnD) {
Richard Smith4a97b8e2013-08-29 00:47:48 +000058 Actions.ProcessDeclAttributeList(getCurScope(), FnD, AccessAttrs);
Richard Smitha2c36462013-04-26 16:15:35 +000059 bool TypeSpecContainsAuto = D.getDeclSpec().containsPlaceholderType();
Douglas Gregora2b4e5d2011-10-17 17:09:53 +000060 if (Init.isUsable())
Larisse Voufoef4579c2013-08-06 01:03:05 +000061 Actions.AddInitializerToDecl(FnD, Init.get(), false,
Douglas Gregor147545d2011-10-10 14:49:18 +000062 TypeSpecContainsAuto);
63 else
64 Actions.ActOnUninitializedDecl(FnD, TypeSpecContainsAuto);
65 }
Nico Weber48673472011-01-28 06:07:34 +000066 }
Argyrios Kyrtzidis4cc18a42008-06-24 22:12:16 +000067
Douglas Gregor74e2fc32012-04-16 18:27:27 +000068 HandleMemberFunctionDeclDelays(D, FnD);
Eli Friedmand33133c2009-07-22 21:45:50 +000069
John McCalleee1d542011-02-14 07:13:47 +000070 D.complete(FnD);
71
Sean Hunte4246a62011-05-12 06:15:49 +000072 if (Tok.is(tok::equal)) {
73 ConsumeToken();
74
Richard Smithc430ef42011-11-10 09:08:44 +000075 if (!FnD) {
76 SkipUntil(tok::semi);
77 return 0;
78 }
79
Sean Hunte4246a62011-05-12 06:15:49 +000080 bool Delete = false;
81 SourceLocation KWLoc;
82 if (Tok.is(tok::kw_delete)) {
Richard Smith80ad52f2013-01-02 11:42:31 +000083 Diag(Tok, getLangOpts().CPlusPlus11 ?
Richard Smith7fe62082011-10-15 05:09:34 +000084 diag::warn_cxx98_compat_deleted_function :
Richard Smithd7c56e12011-12-29 21:57:33 +000085 diag::ext_deleted_function);
Sean Hunte4246a62011-05-12 06:15:49 +000086
87 KWLoc = ConsumeToken();
88 Actions.SetDeclDeleted(FnD, KWLoc);
89 Delete = true;
90 } else if (Tok.is(tok::kw_default)) {
Richard Smith80ad52f2013-01-02 11:42:31 +000091 Diag(Tok, getLangOpts().CPlusPlus11 ?
Richard Smith7fe62082011-10-15 05:09:34 +000092 diag::warn_cxx98_compat_defaulted_function :
Richard Smithd7c56e12011-12-29 21:57:33 +000093 diag::ext_defaulted_function);
Sean Hunte4246a62011-05-12 06:15:49 +000094
95 KWLoc = ConsumeToken();
96 Actions.SetDeclDefaulted(FnD, KWLoc);
97 } else {
98 llvm_unreachable("function definition after = not 'delete' or 'default'");
99 }
100
101 if (Tok.is(tok::comma)) {
102 Diag(KWLoc, diag::err_default_delete_in_multiple_declaration)
103 << Delete;
104 SkipUntil(tok::semi);
105 } else {
106 ExpectAndConsume(tok::semi, diag::err_expected_semi_after,
107 Delete ? "delete" : "default", tok::semi);
108 }
109
110 return FnD;
111 }
112
Francois Pichet8387e2a2011-04-22 22:18:13 +0000113 // In delayed template parsing mode, if we are within a class template
114 // or if we are about to parse function member template then consume
115 // the tokens and store them for parsing at the end of the translation unit.
David Majnemerabcfa612013-09-14 05:46:42 +0000116 if (getLangOpts().DelayedTemplateParsing &&
117 DefinitionKind == FDK_Definition &&
David Majnemer645526c2013-10-23 21:31:20 +0000118 !D.getDeclSpec().isConstexprSpecified() &&
Francois Pichet8387e2a2011-04-22 22:18:13 +0000119 ((Actions.CurContext->isDependentContext() ||
David Majnemerabcfa612013-09-14 05:46:42 +0000120 (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
121 TemplateInfo.Kind != ParsedTemplateInfo::ExplicitSpecialization)) &&
122 !Actions.IsInsideALocalClassWithinATemplateFunction())) {
Francois Pichet8387e2a2011-04-22 22:18:13 +0000123
Richard Smithac32d902013-08-07 21:41:30 +0000124 CachedTokens Toks;
125 LexTemplateFunctionForLateParsing(Toks);
Francois Pichet8387e2a2011-04-22 22:18:13 +0000126
Richard Smithac32d902013-08-07 21:41:30 +0000127 if (FnD) {
John McCalle34db6b2013-03-14 05:13:41 +0000128 FunctionDecl *FD = getFunctionDecl(FnD);
Chandler Carruth81542fd2011-04-25 07:09:43 +0000129 Actions.CheckForFunctionRedefinition(FD);
Richard Smithac32d902013-08-07 21:41:30 +0000130 Actions.MarkAsLateParsedTemplate(FD, FnD, Toks);
Francois Pichet8387e2a2011-04-22 22:18:13 +0000131 }
132
133 return FnD;
134 }
135
Argyrios Kyrtzidis4cc18a42008-06-24 22:12:16 +0000136 // Consume the tokens and store them for later parsing.
137
Douglas Gregord54eb442010-10-12 16:25:54 +0000138 LexedMethod* LM = new LexedMethod(this, FnD);
139 getCurrentClass().LateParsedDeclarations.push_back(LM);
140 LM->TemplateScope = getCurScope()->isTemplateParamScope();
141 CachedTokens &Toks = LM->Toks;
Argyrios Kyrtzidis4cc18a42008-06-24 22:12:16 +0000142
Sebastian Redld3a413d2009-04-26 20:35:05 +0000143 tok::TokenKind kind = Tok.getKind();
Sebastian Redla891a322011-09-30 08:32:17 +0000144 // Consume everything up to (and including) the left brace of the
145 // function body.
146 if (ConsumeAndStoreFunctionPrologue(Toks)) {
147 // We didn't find the left-brace we expected after the
Eli Friedmane9ee3822012-02-22 04:49:04 +0000148 // constructor initializer; we already printed an error, and it's likely
149 // impossible to recover, so don't try to parse this method later.
Richard Smith54ca0692013-07-04 00:13:48 +0000150 // Skip over the rest of the decl and back to somewhere that looks
151 // reasonable.
152 SkipMalformedDecl();
Eli Friedmane9ee3822012-02-22 04:49:04 +0000153 delete getCurrentClass().LateParsedDeclarations.back();
154 getCurrentClass().LateParsedDeclarations.pop_back();
155 return FnD;
Douglas Gregor7ad83902008-11-05 04:29:56 +0000156 } else {
Sebastian Redla891a322011-09-30 08:32:17 +0000157 // Consume everything up to (and including) the matching right brace.
158 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000159 }
Argyrios Kyrtzidis4cc18a42008-06-24 22:12:16 +0000160
Sebastian Redld3a413d2009-04-26 20:35:05 +0000161 // If we're in a function-try-block, we need to store all the catch blocks.
162 if (kind == tok::kw_try) {
163 while (Tok.is(tok::kw_catch)) {
Argyrios Kyrtzidis14b91622010-04-23 21:20:12 +0000164 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
165 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
Sebastian Redld3a413d2009-04-26 20:35:05 +0000166 }
167 }
168
Stephen Lin319957c2013-06-23 07:37:13 +0000169 if (FnD) {
170 // If this is a friend function, mark that it's late-parsed so that
171 // it's still known to be a definition even before we attach the
172 // parsed body. Sema needs to treat friend function definitions
173 // differently during template instantiation, and it's possible for
174 // the containing class to be instantiated before all its member
175 // function definitions are parsed.
176 //
177 // If you remove this, you can remove the code that clears the flag
178 // after parsing the member.
179 if (D.getDeclSpec().isFriendSpecified()) {
Alp Toker530fa4f2013-10-18 05:54:24 +0000180 FunctionDecl *FD = getFunctionDecl(FnD);
181 Actions.CheckForFunctionRedefinition(FD);
182 FD->setLateTemplateParsed(true);
Stephen Lin319957c2013-06-23 07:37:13 +0000183 }
184 } else {
Douglas Gregor87f10642011-04-14 23:19:27 +0000185 // If semantic analysis could not build a function declaration,
186 // just throw away the late-parsed declaration.
187 delete getCurrentClass().LateParsedDeclarations.back();
188 getCurrentClass().LateParsedDeclarations.pop_back();
189 }
190
Argyrios Kyrtzidis4cc18a42008-06-24 22:12:16 +0000191 return FnD;
192}
193
Richard Smith7a614d82011-06-11 17:19:42 +0000194/// ParseCXXNonStaticMemberInitializer - We parsed and verified that the
195/// specified Declarator is a well formed C++ non-static data member
196/// declaration. Now lex its initializer and store its tokens for parsing
197/// after the class is complete.
198void Parser::ParseCXXNonStaticMemberInitializer(Decl *VarD) {
199 assert((Tok.is(tok::l_brace) || Tok.is(tok::equal)) &&
200 "Current token not a '{' or '='!");
201
202 LateParsedMemberInitializer *MI =
203 new LateParsedMemberInitializer(this, VarD);
204 getCurrentClass().LateParsedDeclarations.push_back(MI);
205 CachedTokens &Toks = MI->Toks;
206
207 tok::TokenKind kind = Tok.getKind();
208 if (kind == tok::equal) {
209 Toks.push_back(Tok);
Douglas Gregord78ef5b2012-03-08 01:00:17 +0000210 ConsumeToken();
Richard Smith7a614d82011-06-11 17:19:42 +0000211 }
212
213 if (kind == tok::l_brace) {
214 // Begin by storing the '{' token.
215 Toks.push_back(Tok);
216 ConsumeBrace();
217
218 // Consume everything up to (and including) the matching right brace.
219 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/true);
220 } else {
221 // Consume everything up to (but excluding) the comma or semicolon.
Richard Smith9bd3cdc2013-09-12 23:28:08 +0000222 ConsumeAndStoreInitializer(Toks, CIK_DefaultInitializer);
Richard Smith7a614d82011-06-11 17:19:42 +0000223 }
224
225 // Store an artificial EOF token to ensure that we don't run off the end of
226 // the initializer when we come to parse it.
227 Token Eof;
228 Eof.startToken();
229 Eof.setKind(tok::eof);
230 Eof.setLocation(Tok.getLocation());
231 Toks.push_back(Eof);
232}
233
Douglas Gregord54eb442010-10-12 16:25:54 +0000234Parser::LateParsedDeclaration::~LateParsedDeclaration() {}
235void Parser::LateParsedDeclaration::ParseLexedMethodDeclarations() {}
Richard Smith7a614d82011-06-11 17:19:42 +0000236void Parser::LateParsedDeclaration::ParseLexedMemberInitializers() {}
Douglas Gregord54eb442010-10-12 16:25:54 +0000237void Parser::LateParsedDeclaration::ParseLexedMethodDefs() {}
238
239Parser::LateParsedClass::LateParsedClass(Parser *P, ParsingClass *C)
240 : Self(P), Class(C) {}
241
242Parser::LateParsedClass::~LateParsedClass() {
243 Self->DeallocateParsedClasses(Class);
244}
245
246void Parser::LateParsedClass::ParseLexedMethodDeclarations() {
247 Self->ParseLexedMethodDeclarations(*Class);
248}
249
Richard Smith7a614d82011-06-11 17:19:42 +0000250void Parser::LateParsedClass::ParseLexedMemberInitializers() {
251 Self->ParseLexedMemberInitializers(*Class);
252}
253
Douglas Gregord54eb442010-10-12 16:25:54 +0000254void Parser::LateParsedClass::ParseLexedMethodDefs() {
255 Self->ParseLexedMethodDefs(*Class);
256}
257
258void Parser::LateParsedMethodDeclaration::ParseLexedMethodDeclarations() {
259 Self->ParseLexedMethodDeclaration(*this);
260}
261
262void Parser::LexedMethod::ParseLexedMethodDefs() {
263 Self->ParseLexedMethodDef(*this);
264}
265
Richard Smith7a614d82011-06-11 17:19:42 +0000266void Parser::LateParsedMemberInitializer::ParseLexedMemberInitializers() {
267 Self->ParseLexedMemberInitializer(*this);
268}
269
Douglas Gregor72b505b2008-12-16 21:30:33 +0000270/// ParseLexedMethodDeclarations - We finished parsing the member
271/// specification of a top (non-nested) C++ class. Now go over the
272/// stack of method declarations with some parts for which parsing was
273/// delayed (such as default arguments) and parse them.
Douglas Gregor6569d682009-05-27 23:11:45 +0000274void Parser::ParseLexedMethodDeclarations(ParsingClass &Class) {
275 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
Douglas Gregord54eb442010-10-12 16:25:54 +0000276 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope, HasTemplateScope);
Richard Smith098b8142013-04-29 11:55:38 +0000277 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
278 if (HasTemplateScope) {
Douglas Gregor23c94db2010-07-02 17:43:08 +0000279 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
Richard Smith098b8142013-04-29 11:55:38 +0000280 ++CurTemplateDepthTracker;
281 }
Douglas Gregor6569d682009-05-27 23:11:45 +0000282
John McCall7a1dc562009-12-19 10:49:29 +0000283 // The current scope is still active if we're the top-level class.
284 // Otherwise we'll need to push and enter a new scope.
Douglas Gregor6569d682009-05-27 23:11:45 +0000285 bool HasClassScope = !Class.TopLevelClass;
Sean Hunt4cd84942010-04-14 23:07:37 +0000286 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope,
287 HasClassScope);
John McCall7a1dc562009-12-19 10:49:29 +0000288 if (HasClassScope)
Douglas Gregor23c94db2010-07-02 17:43:08 +0000289 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(), Class.TagOrTemplate);
Douglas Gregor6569d682009-05-27 23:11:45 +0000290
Douglas Gregord54eb442010-10-12 16:25:54 +0000291 for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
292 Class.LateParsedDeclarations[i]->ParseLexedMethodDeclarations();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000293 }
Douglas Gregor6569d682009-05-27 23:11:45 +0000294
John McCall7a1dc562009-12-19 10:49:29 +0000295 if (HasClassScope)
Douglas Gregor23c94db2010-07-02 17:43:08 +0000296 Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(), Class.TagOrTemplate);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000297}
298
Douglas Gregord54eb442010-10-12 16:25:54 +0000299void Parser::ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM) {
300 // If this is a member template, introduce the template parameter scope.
301 ParseScope TemplateScope(this, Scope::TemplateParamScope, LM.TemplateScope);
Richard Smith098b8142013-04-29 11:55:38 +0000302 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
303 if (LM.TemplateScope) {
Douglas Gregord54eb442010-10-12 16:25:54 +0000304 Actions.ActOnReenterTemplateScope(getCurScope(), LM.Method);
Richard Smith098b8142013-04-29 11:55:38 +0000305 ++CurTemplateDepthTracker;
306 }
Douglas Gregord54eb442010-10-12 16:25:54 +0000307 // Start the delayed C++ method declaration
308 Actions.ActOnStartDelayedCXXMethodDeclaration(getCurScope(), LM.Method);
309
310 // Introduce the parameters into scope and parse their default
311 // arguments.
Richard Smith3a2b7a12013-01-28 22:42:45 +0000312 ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
313 Scope::FunctionDeclarationScope | Scope::DeclScope);
Douglas Gregord54eb442010-10-12 16:25:54 +0000314 for (unsigned I = 0, N = LM.DefaultArgs.size(); I != N; ++I) {
315 // Introduce the parameter into scope.
Douglas Gregorccc1b5e2012-02-21 00:37:24 +0000316 Actions.ActOnDelayedCXXMethodParameter(getCurScope(),
317 LM.DefaultArgs[I].Param);
Douglas Gregord54eb442010-10-12 16:25:54 +0000318
319 if (CachedTokens *Toks = LM.DefaultArgs[I].Toks) {
320 // Save the current token position.
321 SourceLocation origLoc = Tok.getLocation();
322
323 // Parse the default argument from its saved token stream.
324 Toks->push_back(Tok); // So that the current token doesn't get lost
325 PP.EnterTokenStream(&Toks->front(), Toks->size(), true, false);
326
327 // Consume the previously-pushed token.
328 ConsumeAnyToken();
329
330 // Consume the '='.
331 assert(Tok.is(tok::equal) && "Default argument not starting with '='");
332 SourceLocation EqualLoc = ConsumeToken();
333
334 // The argument isn't actually potentially evaluated unless it is
335 // used.
336 EnterExpressionEvaluationContext Eval(Actions,
Douglas Gregorccc1b5e2012-02-21 00:37:24 +0000337 Sema::PotentiallyEvaluatedIfUsed,
338 LM.DefaultArgs[I].Param);
Douglas Gregord54eb442010-10-12 16:25:54 +0000339
Sebastian Redl84407ba2012-03-14 15:54:00 +0000340 ExprResult DefArgResult;
Richard Smith80ad52f2013-01-02 11:42:31 +0000341 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
Sebastian Redlca893712012-03-20 21:24:03 +0000342 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
Sebastian Redl84407ba2012-03-14 15:54:00 +0000343 DefArgResult = ParseBraceInitializer();
Sebastian Redlca893712012-03-20 21:24:03 +0000344 } else
Sebastian Redl84407ba2012-03-14 15:54:00 +0000345 DefArgResult = ParseAssignmentExpression();
Douglas Gregord54eb442010-10-12 16:25:54 +0000346 if (DefArgResult.isInvalid())
347 Actions.ActOnParamDefaultArgumentError(LM.DefaultArgs[I].Param);
348 else {
349 if (Tok.is(tok::cxx_defaultarg_end))
350 ConsumeToken();
Richard Smith9bd3cdc2013-09-12 23:28:08 +0000351 else {
352 // The last two tokens are the terminator and the saved value of
353 // Tok; the last token in the default argument is the one before
354 // those.
355 assert(Toks->size() >= 3 && "expected a token in default arg");
356 Diag(Tok.getLocation(), diag::err_default_arg_unparsed)
357 << SourceRange(Tok.getLocation(),
358 (*Toks)[Toks->size() - 3].getLocation());
359 }
Douglas Gregord54eb442010-10-12 16:25:54 +0000360 Actions.ActOnParamDefaultArgument(LM.DefaultArgs[I].Param, EqualLoc,
361 DefArgResult.take());
362 }
363
364 assert(!PP.getSourceManager().isBeforeInTranslationUnit(origLoc,
365 Tok.getLocation()) &&
366 "ParseAssignmentExpression went over the default arg tokens!");
367 // There could be leftover tokens (e.g. because of an error).
368 // Skip through until we reach the original token position.
369 while (Tok.getLocation() != origLoc && Tok.isNot(tok::eof))
370 ConsumeAnyToken();
371
372 delete Toks;
373 LM.DefaultArgs[I].Toks = 0;
374 }
375 }
Douglas Gregor74e2fc32012-04-16 18:27:27 +0000376
Douglas Gregord54eb442010-10-12 16:25:54 +0000377 PrototypeScope.Exit();
378
379 // Finish the delayed C++ method declaration.
380 Actions.ActOnFinishDelayedCXXMethodDeclaration(getCurScope(), LM.Method);
381}
382
Argyrios Kyrtzidis4cc18a42008-06-24 22:12:16 +0000383/// ParseLexedMethodDefs - We finished parsing the member specification of a top
384/// (non-nested) C++ class. Now go over the stack of lexed methods that were
385/// collected during its parsing and parse them all.
Douglas Gregor6569d682009-05-27 23:11:45 +0000386void Parser::ParseLexedMethodDefs(ParsingClass &Class) {
387 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
Douglas Gregord54eb442010-10-12 16:25:54 +0000388 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope, HasTemplateScope);
Richard Smith098b8142013-04-29 11:55:38 +0000389 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
390 if (HasTemplateScope) {
Douglas Gregor23c94db2010-07-02 17:43:08 +0000391 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
Richard Smith098b8142013-04-29 11:55:38 +0000392 ++CurTemplateDepthTracker;
393 }
Douglas Gregor6569d682009-05-27 23:11:45 +0000394 bool HasClassScope = !Class.TopLevelClass;
395 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope,
396 HasClassScope);
397
Douglas Gregord54eb442010-10-12 16:25:54 +0000398 for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
399 Class.LateParsedDeclarations[i]->ParseLexedMethodDefs();
400 }
401}
Argyrios Kyrtzidis4cc18a42008-06-24 22:12:16 +0000402
Douglas Gregord54eb442010-10-12 16:25:54 +0000403void Parser::ParseLexedMethodDef(LexedMethod &LM) {
404 // If this is a member template, introduce the template parameter scope.
405 ParseScope TemplateScope(this, Scope::TemplateParamScope, LM.TemplateScope);
Richard Smith098b8142013-04-29 11:55:38 +0000406 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
407 if (LM.TemplateScope) {
Douglas Gregord54eb442010-10-12 16:25:54 +0000408 Actions.ActOnReenterTemplateScope(getCurScope(), LM.D);
Richard Smith098b8142013-04-29 11:55:38 +0000409 ++CurTemplateDepthTracker;
410 }
Douglas Gregord54eb442010-10-12 16:25:54 +0000411 // Save the current token position.
412 SourceLocation origLoc = Tok.getLocation();
Argyrios Kyrtzidisc50a5e02010-03-31 00:38:09 +0000413
Douglas Gregord54eb442010-10-12 16:25:54 +0000414 assert(!LM.Toks.empty() && "Empty body!");
415 // Append the current token at the end of the new token stream so that it
416 // doesn't get lost.
417 LM.Toks.push_back(Tok);
418 PP.EnterTokenStream(LM.Toks.data(), LM.Toks.size(), true, false);
Argyrios Kyrtzidis4cc18a42008-06-24 22:12:16 +0000419
Douglas Gregord54eb442010-10-12 16:25:54 +0000420 // Consume the previously pushed token.
Argyrios Kyrtzidisab2d09b2013-03-27 23:58:17 +0000421 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
Douglas Gregord54eb442010-10-12 16:25:54 +0000422 assert((Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try))
423 && "Inline method not starting with '{', ':' or 'try'");
Argyrios Kyrtzidis4cc18a42008-06-24 22:12:16 +0000424
Douglas Gregord54eb442010-10-12 16:25:54 +0000425 // Parse the method body. Function body parsing code is similar enough
426 // to be re-used for method bodies as well.
427 ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope);
428 Actions.ActOnStartOfFunctionDef(getCurScope(), LM.D);
Argyrios Kyrtzidis4cc18a42008-06-24 22:12:16 +0000429
Douglas Gregord54eb442010-10-12 16:25:54 +0000430 if (Tok.is(tok::kw_try)) {
Douglas Gregorc9977d02011-03-16 17:05:57 +0000431 ParseFunctionTryBlock(LM.D, FnScope);
Douglas Gregord54eb442010-10-12 16:25:54 +0000432 assert(!PP.getSourceManager().isBeforeInTranslationUnit(origLoc,
433 Tok.getLocation()) &&
434 "ParseFunctionTryBlock went over the cached tokens!");
435 // There could be leftover tokens (e.g. because of an error).
436 // Skip through until we reach the original token position.
437 while (Tok.getLocation() != origLoc && Tok.isNot(tok::eof))
438 ConsumeAnyToken();
439 return;
440 }
441 if (Tok.is(tok::colon)) {
442 ParseConstructorInitializer(LM.D);
443
444 // Error recovery.
445 if (!Tok.is(tok::l_brace)) {
Douglas Gregorc9977d02011-03-16 17:05:57 +0000446 FnScope.Exit();
Douglas Gregord54eb442010-10-12 16:25:54 +0000447 Actions.ActOnFinishFunctionBody(LM.D, 0);
Matt Beaumont-Gay10904522011-09-23 22:39:23 +0000448 while (Tok.getLocation() != origLoc && Tok.isNot(tok::eof))
449 ConsumeAnyToken();
Douglas Gregord54eb442010-10-12 16:25:54 +0000450 return;
451 }
452 } else
453 Actions.ActOnDefaultCtorInitializers(LM.D);
454
Richard Smith098b8142013-04-29 11:55:38 +0000455 assert((Actions.getDiagnostics().hasErrorOccurred() ||
456 !isa<FunctionTemplateDecl>(LM.D) ||
457 cast<FunctionTemplateDecl>(LM.D)->getTemplateParameters()->getDepth()
458 < TemplateParameterDepth) &&
459 "TemplateParameterDepth should be greater than the depth of "
460 "current template being instantiated!");
461
Douglas Gregorc9977d02011-03-16 17:05:57 +0000462 ParseFunctionStatementBody(LM.D, FnScope);
Douglas Gregord54eb442010-10-12 16:25:54 +0000463
John McCalle34db6b2013-03-14 05:13:41 +0000464 // Clear the late-template-parsed bit if we set it before.
465 if (LM.D) getFunctionDecl(LM.D)->setLateTemplateParsed(false);
466
Douglas Gregord54eb442010-10-12 16:25:54 +0000467 if (Tok.getLocation() != origLoc) {
468 // Due to parsing error, we either went over the cached tokens or
469 // there are still cached tokens left. If it's the latter case skip the
470 // leftover tokens.
471 // Since this is an uncommon situation that should be avoided, use the
472 // expensive isBeforeInTranslationUnit call.
473 if (PP.getSourceManager().isBeforeInTranslationUnit(Tok.getLocation(),
474 origLoc))
Argyrios Kyrtzidis8f9359f2010-06-19 19:58:34 +0000475 while (Tok.getLocation() != origLoc && Tok.isNot(tok::eof))
Argyrios Kyrtzidis7558cd02010-06-17 10:52:22 +0000476 ConsumeAnyToken();
Argyrios Kyrtzidis4cc18a42008-06-24 22:12:16 +0000477 }
478}
479
Richard Smith7a614d82011-06-11 17:19:42 +0000480/// ParseLexedMemberInitializers - We finished parsing the member specification
481/// of a top (non-nested) C++ class. Now go over the stack of lexed data member
482/// initializers that were collected during its parsing and parse them all.
483void Parser::ParseLexedMemberInitializers(ParsingClass &Class) {
484 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
485 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
486 HasTemplateScope);
Richard Smith098b8142013-04-29 11:55:38 +0000487 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
488 if (HasTemplateScope) {
Richard Smith7a614d82011-06-11 17:19:42 +0000489 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
Richard Smith098b8142013-04-29 11:55:38 +0000490 ++CurTemplateDepthTracker;
491 }
Douglas Gregorcefc3af2012-04-16 07:05:22 +0000492 // Set or update the scope flags.
Richard Smith7a614d82011-06-11 17:19:42 +0000493 bool AlreadyHasClassScope = Class.TopLevelClass;
Douglas Gregorcefc3af2012-04-16 07:05:22 +0000494 unsigned ScopeFlags = Scope::ClassScope|Scope::DeclScope;
Richard Smith7a614d82011-06-11 17:19:42 +0000495 ParseScope ClassScope(this, ScopeFlags, !AlreadyHasClassScope);
496 ParseScopeFlags ClassScopeFlags(this, ScopeFlags, AlreadyHasClassScope);
497
498 if (!AlreadyHasClassScope)
499 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(),
500 Class.TagOrTemplate);
501
Benjamin Kramer268efba2012-05-17 12:01:52 +0000502 if (!Class.LateParsedDeclarations.empty()) {
Douglas Gregorcefc3af2012-04-16 07:05:22 +0000503 // C++11 [expr.prim.general]p4:
504 // Otherwise, if a member-declarator declares a non-static data member
505 // (9.2) of a class X, the expression this is a prvalue of type "pointer
506 // to X" within the optional brace-or-equal-initializer. It shall not
507 // appear elsewhere in the member-declarator.
508 Sema::CXXThisScopeRAII ThisScope(Actions, Class.TagOrTemplate,
509 /*TypeQuals=*/(unsigned)0);
Richard Smith7a614d82011-06-11 17:19:42 +0000510
Douglas Gregorcefc3af2012-04-16 07:05:22 +0000511 for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
512 Class.LateParsedDeclarations[i]->ParseLexedMemberInitializers();
513 }
514 }
515
Richard Smith7a614d82011-06-11 17:19:42 +0000516 if (!AlreadyHasClassScope)
517 Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(),
518 Class.TagOrTemplate);
519
520 Actions.ActOnFinishDelayedMemberInitializers(Class.TagOrTemplate);
521}
522
523void Parser::ParseLexedMemberInitializer(LateParsedMemberInitializer &MI) {
Richard Smith1991b712011-09-29 19:42:27 +0000524 if (!MI.Field || MI.Field->isInvalidDecl())
Richard Smith7a614d82011-06-11 17:19:42 +0000525 return;
526
527 // Append the current token at the end of the new token stream so that it
528 // doesn't get lost.
529 MI.Toks.push_back(Tok);
530 PP.EnterTokenStream(MI.Toks.data(), MI.Toks.size(), true, false);
531
532 // Consume the previously pushed token.
Argyrios Kyrtzidisab2d09b2013-03-27 23:58:17 +0000533 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
Richard Smith7a614d82011-06-11 17:19:42 +0000534
535 SourceLocation EqualLoc;
Richard Smithca523302012-06-10 03:12:00 +0000536
Douglas Gregor552e2992012-02-21 02:22:07 +0000537 ExprResult Init = ParseCXXMemberInitializer(MI.Field, /*IsFunction=*/false,
538 EqualLoc);
Richard Smith7a614d82011-06-11 17:19:42 +0000539
540 Actions.ActOnCXXInClassMemberInitializer(MI.Field, EqualLoc, Init.release());
541
542 // The next token should be our artificial terminating EOF token.
543 if (Tok.isNot(tok::eof)) {
544 SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
545 if (!EndLoc.isValid())
546 EndLoc = Tok.getLocation();
547 // No fixit; we can't recover as if there were a semicolon here.
548 Diag(EndLoc, diag::err_expected_semi_decl_list);
549
550 // Consume tokens until we hit the artificial EOF.
551 while (Tok.isNot(tok::eof))
552 ConsumeAnyToken();
553 }
554 ConsumeAnyToken();
555}
556
Argyrios Kyrtzidis4cc18a42008-06-24 22:12:16 +0000557/// ConsumeAndStoreUntil - Consume and store the token at the passed token
Douglas Gregor72b505b2008-12-16 21:30:33 +0000558/// container until the token 'T' is reached (which gets
Mike Stump1eb44332009-09-09 15:08:12 +0000559/// consumed/stored too, if ConsumeFinalToken).
Argyrios Kyrtzidis14b91622010-04-23 21:20:12 +0000560/// If StopAtSemi is true, then we will stop early at a ';' character.
Douglas Gregor72b505b2008-12-16 21:30:33 +0000561/// Returns true if token 'T1' or 'T2' was found.
Argyrios Kyrtzidis4cc18a42008-06-24 22:12:16 +0000562/// NOTE: This is a specialized version of Parser::SkipUntil.
Douglas Gregor72b505b2008-12-16 21:30:33 +0000563bool Parser::ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
564 CachedTokens &Toks,
Argyrios Kyrtzidis14b91622010-04-23 21:20:12 +0000565 bool StopAtSemi, bool ConsumeFinalToken) {
Argyrios Kyrtzidis4cc18a42008-06-24 22:12:16 +0000566 // We always want this function to consume at least one token if the first
567 // token isn't T and if not at EOF.
568 bool isFirstTokenConsumed = true;
569 while (1) {
570 // If we found one of the tokens, stop and return true.
Douglas Gregor72b505b2008-12-16 21:30:33 +0000571 if (Tok.is(T1) || Tok.is(T2)) {
572 if (ConsumeFinalToken) {
573 Toks.push_back(Tok);
574 ConsumeAnyToken();
575 }
Argyrios Kyrtzidis4cc18a42008-06-24 22:12:16 +0000576 return true;
577 }
578
Argyrios Kyrtzidis4cc18a42008-06-24 22:12:16 +0000579 switch (Tok.getKind()) {
580 case tok::eof:
581 // Ran out of tokens.
582 return false;
583
584 case tok::l_paren:
585 // Recursively consume properly-nested parens.
586 Toks.push_back(Tok);
587 ConsumeParen();
Argyrios Kyrtzidis14b91622010-04-23 21:20:12 +0000588 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
Argyrios Kyrtzidis4cc18a42008-06-24 22:12:16 +0000589 break;
590 case tok::l_square:
591 // Recursively consume properly-nested square brackets.
592 Toks.push_back(Tok);
593 ConsumeBracket();
Argyrios Kyrtzidis14b91622010-04-23 21:20:12 +0000594 ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false);
Argyrios Kyrtzidis4cc18a42008-06-24 22:12:16 +0000595 break;
596 case tok::l_brace:
597 // Recursively consume properly-nested braces.
598 Toks.push_back(Tok);
599 ConsumeBrace();
Argyrios Kyrtzidis14b91622010-04-23 21:20:12 +0000600 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
Argyrios Kyrtzidis4cc18a42008-06-24 22:12:16 +0000601 break;
602
603 // Okay, we found a ']' or '}' or ')', which we think should be balanced.
604 // Since the user wasn't looking for this token (if they were, it would
605 // already be handled), this isn't balanced. If there is a LHS token at a
606 // higher level, we will assume that this matches the unbalanced token
607 // and return it. Otherwise, this is a spurious RHS token, which we skip.
608 case tok::r_paren:
609 if (ParenCount && !isFirstTokenConsumed)
610 return false; // Matches something.
611 Toks.push_back(Tok);
612 ConsumeParen();
613 break;
614 case tok::r_square:
615 if (BracketCount && !isFirstTokenConsumed)
616 return false; // Matches something.
617 Toks.push_back(Tok);
618 ConsumeBracket();
619 break;
620 case tok::r_brace:
621 if (BraceCount && !isFirstTokenConsumed)
622 return false; // Matches something.
623 Toks.push_back(Tok);
624 ConsumeBrace();
625 break;
626
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000627 case tok::code_completion:
628 Toks.push_back(Tok);
629 ConsumeCodeCompletionToken();
630 break;
631
Argyrios Kyrtzidis4cc18a42008-06-24 22:12:16 +0000632 case tok::string_literal:
633 case tok::wide_string_literal:
Douglas Gregor5cee1192011-07-27 05:40:30 +0000634 case tok::utf8_string_literal:
635 case tok::utf16_string_literal:
636 case tok::utf32_string_literal:
Argyrios Kyrtzidis4cc18a42008-06-24 22:12:16 +0000637 Toks.push_back(Tok);
638 ConsumeStringToken();
639 break;
Argyrios Kyrtzidis14b91622010-04-23 21:20:12 +0000640 case tok::semi:
641 if (StopAtSemi)
642 return false;
643 // FALL THROUGH.
Argyrios Kyrtzidis4cc18a42008-06-24 22:12:16 +0000644 default:
645 // consume this token.
646 Toks.push_back(Tok);
647 ConsumeToken();
648 break;
649 }
650 isFirstTokenConsumed = false;
651 }
652}
Sebastian Redl6df65482011-09-24 17:48:25 +0000653
654/// \brief Consume tokens and store them in the passed token container until
655/// we've passed the try keyword and constructor initializers and have consumed
Sebastian Redla891a322011-09-30 08:32:17 +0000656/// the opening brace of the function body. The opening brace will be consumed
657/// if and only if there was no error.
Sebastian Redl6df65482011-09-24 17:48:25 +0000658///
Richard Smith54ca0692013-07-04 00:13:48 +0000659/// \return True on error.
Sebastian Redla891a322011-09-30 08:32:17 +0000660bool Parser::ConsumeAndStoreFunctionPrologue(CachedTokens &Toks) {
Sebastian Redl6df65482011-09-24 17:48:25 +0000661 if (Tok.is(tok::kw_try)) {
662 Toks.push_back(Tok);
663 ConsumeToken();
664 }
Richard Smith54ca0692013-07-04 00:13:48 +0000665
666 if (Tok.isNot(tok::colon)) {
667 // Easy case, just a function body.
668
669 // Grab any remaining garbage to be diagnosed later. We stop when we reach a
670 // brace: an opening one is the function body, while a closing one probably
671 // means we've reached the end of the class.
672 ConsumeAndStoreUntil(tok::l_brace, tok::r_brace, Toks,
673 /*StopAtSemi=*/true,
674 /*ConsumeFinalToken=*/false);
675 if (Tok.isNot(tok::l_brace))
676 return Diag(Tok.getLocation(), diag::err_expected_lbrace);
677
Sebastian Redl6df65482011-09-24 17:48:25 +0000678 Toks.push_back(Tok);
Richard Smith54ca0692013-07-04 00:13:48 +0000679 ConsumeBrace();
680 return false;
Eli Friedmane9ee3822012-02-22 04:49:04 +0000681 }
Sebastian Redla891a322011-09-30 08:32:17 +0000682
683 Toks.push_back(Tok);
Richard Smith54ca0692013-07-04 00:13:48 +0000684 ConsumeToken();
685
686 // We can't reliably skip over a mem-initializer-id, because it could be
687 // a template-id involving not-yet-declared names. Given:
688 //
689 // S ( ) : a < b < c > ( e )
690 //
691 // 'e' might be an initializer or part of a template argument, depending
692 // on whether 'b' is a template.
693
694 // Track whether we might be inside a template argument. We can give
695 // significantly better diagnostics if we know that we're not.
696 bool MightBeTemplateArgument = false;
697
698 while (true) {
699 // Skip over the mem-initializer-id, if possible.
700 if (Tok.is(tok::kw_decltype)) {
701 Toks.push_back(Tok);
702 SourceLocation OpenLoc = ConsumeToken();
703 if (Tok.isNot(tok::l_paren))
704 return Diag(Tok.getLocation(), diag::err_expected_lparen_after)
705 << "decltype";
706 Toks.push_back(Tok);
707 ConsumeParen();
708 if (!ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/true)) {
709 Diag(Tok.getLocation(), diag::err_expected_rparen);
710 Diag(OpenLoc, diag::note_matching) << "(";
711 return true;
712 }
713 }
714 do {
715 // Walk over a component of a nested-name-specifier.
716 if (Tok.is(tok::coloncolon)) {
717 Toks.push_back(Tok);
718 ConsumeToken();
719
720 if (Tok.is(tok::kw_template)) {
721 Toks.push_back(Tok);
722 ConsumeToken();
723 }
724 }
725
726 if (Tok.is(tok::identifier) || Tok.is(tok::kw_template)) {
727 Toks.push_back(Tok);
728 ConsumeToken();
729 } else if (Tok.is(tok::code_completion)) {
730 Toks.push_back(Tok);
731 ConsumeCodeCompletionToken();
732 // Consume the rest of the initializers permissively.
733 // FIXME: We should be able to perform code-completion here even if
734 // there isn't a subsequent '{' token.
735 MightBeTemplateArgument = true;
736 break;
737 } else {
738 break;
739 }
740 } while (Tok.is(tok::coloncolon));
741
742 if (Tok.is(tok::less))
743 MightBeTemplateArgument = true;
744
745 if (MightBeTemplateArgument) {
746 // We may be inside a template argument list. Grab up to the start of the
747 // next parenthesized initializer or braced-init-list. This *might* be the
748 // initializer, or it might be a subexpression in the template argument
749 // list.
750 // FIXME: Count angle brackets, and clear MightBeTemplateArgument
751 // if all angles are closed.
752 if (!ConsumeAndStoreUntil(tok::l_paren, tok::l_brace, Toks,
753 /*StopAtSemi=*/true,
754 /*ConsumeFinalToken=*/false)) {
755 // We're not just missing the initializer, we're also missing the
756 // function body!
757 return Diag(Tok.getLocation(), diag::err_expected_lbrace);
758 }
759 } else if (Tok.isNot(tok::l_paren) && Tok.isNot(tok::l_brace)) {
760 // We found something weird in a mem-initializer-id.
761 return Diag(Tok.getLocation(), getLangOpts().CPlusPlus11
762 ? diag::err_expected_lparen_or_lbrace
763 : diag::err_expected_lparen);
764 }
765
766 tok::TokenKind kind = Tok.getKind();
767 Toks.push_back(Tok);
768 bool IsLParen = (kind == tok::l_paren);
769 SourceLocation OpenLoc = Tok.getLocation();
770
771 if (IsLParen) {
772 ConsumeParen();
773 } else {
774 assert(kind == tok::l_brace && "Must be left paren or brace here.");
775 ConsumeBrace();
776 // In C++03, this has to be the start of the function body, which
777 // means the initializer is malformed; we'll diagnose it later.
778 if (!getLangOpts().CPlusPlus11)
779 return false;
780 }
781
782 // Grab the initializer (or the subexpression of the template argument).
783 // FIXME: If we support lambdas here, we'll need to set StopAtSemi to false
784 // if we might be inside the braces of a lambda-expression.
785 if (!ConsumeAndStoreUntil(IsLParen ? tok::r_paren : tok::r_brace,
786 Toks, /*StopAtSemi=*/true)) {
787 Diag(Tok, IsLParen ? diag::err_expected_rparen :
788 diag::err_expected_rbrace);
789 Diag(OpenLoc, diag::note_matching) << (IsLParen ? "(" : "{");
790 return true;
791 }
792
793 // Grab pack ellipsis, if present.
794 if (Tok.is(tok::ellipsis)) {
795 Toks.push_back(Tok);
796 ConsumeToken();
797 }
798
799 // If we know we just consumed a mem-initializer, we must have ',' or '{'
800 // next.
801 if (Tok.is(tok::comma)) {
802 Toks.push_back(Tok);
803 ConsumeToken();
804 } else if (Tok.is(tok::l_brace)) {
805 // This is the function body if the ')' or '}' is immediately followed by
806 // a '{'. That cannot happen within a template argument, apart from the
807 // case where a template argument contains a compound literal:
808 //
809 // S ( ) : a < b < c > ( d ) { }
810 // // End of declaration, or still inside the template argument?
811 //
812 // ... and the case where the template argument contains a lambda:
813 //
814 // S ( ) : a < 0 && b < c > ( d ) + [ ] ( ) { return 0; }
815 // ( ) > ( ) { }
816 //
817 // FIXME: Disambiguate these cases. Note that the latter case is probably
818 // going to be made ill-formed by core issue 1607.
819 Toks.push_back(Tok);
820 ConsumeBrace();
821 return false;
822 } else if (!MightBeTemplateArgument) {
823 return Diag(Tok.getLocation(), diag::err_expected_lbrace_or_comma);
824 }
825 }
Sebastian Redl6df65482011-09-24 17:48:25 +0000826}
Richard Smith9bd3cdc2013-09-12 23:28:08 +0000827
828/// \brief Consume and store tokens from the '?' to the ':' in a conditional
829/// expression.
830bool Parser::ConsumeAndStoreConditional(CachedTokens &Toks) {
831 // Consume '?'.
832 assert(Tok.is(tok::question));
833 Toks.push_back(Tok);
834 ConsumeToken();
835
836 while (Tok.isNot(tok::colon)) {
837 if (!ConsumeAndStoreUntil(tok::question, tok::colon, Toks, /*StopAtSemi*/true,
838 /*ConsumeFinalToken*/false))
839 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.
869 Self.SkipUntil(EndKind, true, /*DontConsume*/true);
870 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:
966 // Ran out of tokens.
967 return false;
968
969 case tok::less:
970 // FIXME: A '<' can only start a template-id if it's preceded by an
971 // identifier, an operator-function-id, or a literal-operator-id.
972 ++AngleCount;
973 goto consume_token;
974
975 case tok::question:
976 // In 'a ? b : c', 'b' can contain an unparenthesized comma. If it does,
977 // that is *never* the end of the initializer. Skip to the ':'.
978 if (!ConsumeAndStoreConditional(Toks))
979 return false;
980 break;
981
982 case tok::greatergreatergreater:
983 if (!getLangOpts().CPlusPlus11)
984 goto consume_token;
985 if (AngleCount) --AngleCount;
986 if (KnownTemplateCount) --KnownTemplateCount;
987 // Fall through.
988 case tok::greatergreater:
989 if (!getLangOpts().CPlusPlus11)
990 goto consume_token;
991 if (AngleCount) --AngleCount;
992 if (KnownTemplateCount) --KnownTemplateCount;
993 // Fall through.
994 case tok::greater:
995 if (AngleCount) --AngleCount;
996 if (KnownTemplateCount) --KnownTemplateCount;
997 goto consume_token;
998
999 case tok::kw_template:
1000 // 'template' identifier '<' is known to start a template argument list,
1001 // and can be used to disambiguate the parse.
1002 // FIXME: Support all forms of 'template' unqualified-id '<'.
1003 Toks.push_back(Tok);
1004 ConsumeToken();
1005 if (Tok.is(tok::identifier)) {
1006 Toks.push_back(Tok);
1007 ConsumeToken();
1008 if (Tok.is(tok::less)) {
1009 ++KnownTemplateCount;
1010 Toks.push_back(Tok);
1011 ConsumeToken();
1012 }
1013 }
1014 break;
1015
1016 case tok::kw_operator:
1017 // If 'operator' precedes other punctuation, that punctuation loses
1018 // its special behavior.
1019 Toks.push_back(Tok);
1020 ConsumeToken();
1021 switch (Tok.getKind()) {
1022 case tok::comma:
1023 case tok::greatergreatergreater:
1024 case tok::greatergreater:
1025 case tok::greater:
1026 case tok::less:
1027 Toks.push_back(Tok);
1028 ConsumeToken();
1029 break;
1030 default:
1031 break;
1032 }
1033 break;
1034
1035 case tok::l_paren:
1036 // Recursively consume properly-nested parens.
1037 Toks.push_back(Tok);
1038 ConsumeParen();
1039 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
1040 break;
1041 case tok::l_square:
1042 // Recursively consume properly-nested square brackets.
1043 Toks.push_back(Tok);
1044 ConsumeBracket();
1045 ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false);
1046 break;
1047 case tok::l_brace:
1048 // Recursively consume properly-nested braces.
1049 Toks.push_back(Tok);
1050 ConsumeBrace();
1051 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1052 break;
1053
1054 // Okay, we found a ']' or '}' or ')', which we think should be balanced.
1055 // Since the user wasn't looking for this token (if they were, it would
1056 // already be handled), this isn't balanced. If there is a LHS token at a
1057 // higher level, we will assume that this matches the unbalanced token
1058 // and return it. Otherwise, this is a spurious RHS token, which we skip.
1059 case tok::r_paren:
1060 if (CIK == CIK_DefaultArgument)
1061 return true; // End of the default argument.
1062 if (ParenCount && !IsFirstTokenConsumed)
1063 return false; // Matches something.
1064 goto consume_token;
1065 case tok::r_square:
1066 if (BracketCount && !IsFirstTokenConsumed)
1067 return false; // Matches something.
1068 goto consume_token;
1069 case tok::r_brace:
1070 if (BraceCount && !IsFirstTokenConsumed)
1071 return false; // Matches something.
1072 goto consume_token;
1073
1074 case tok::code_completion:
1075 Toks.push_back(Tok);
1076 ConsumeCodeCompletionToken();
1077 break;
1078
1079 case tok::string_literal:
1080 case tok::wide_string_literal:
1081 case tok::utf8_string_literal:
1082 case tok::utf16_string_literal:
1083 case tok::utf32_string_literal:
1084 Toks.push_back(Tok);
1085 ConsumeStringToken();
1086 break;
1087 case tok::semi:
1088 if (CIK == CIK_DefaultInitializer)
1089 return true; // End of the default initializer.
1090 // FALL THROUGH.
1091 default:
1092 consume_token:
1093 Toks.push_back(Tok);
1094 ConsumeToken();
1095 break;
1096 }
1097 IsFirstTokenConsumed = false;
1098 }
1099}