blob: 8d82d03d8309289d2885dd7ed6709eb285fe8d9a [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
John McCalle68672f2013-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 Redla7b98a72009-04-26 20:35:05 +000029/// ParseCXXInlineMethodDef - We parsed and verified that the specified
Argyrios Kyrtzidis7bbb20e2008-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 Espindolac2453dd2013-01-08 21:00:12 +000032NamedDecl *Parser::ParseCXXInlineMethodDef(AccessSpecifier AS,
Erik Verbruggenca98f2a2011-10-13 09:41:32 +000033 AttributeList *AccessAttrs,
34 ParsingDeclarator &D,
Douglas Gregor5d1b4e32011-11-07 20:56:01 +000035 const ParsedTemplateInfo &TemplateInfo,
36 const VirtSpecifiers& VS,
37 FunctionDefinitionKind DefinitionKind,
38 ExprResult& Init) {
Abramo Bagnara924a8f32010-12-10 16:29:40 +000039 assert(D.isFunctionDeclarator() && "This isn't a function declarator!");
Alexis Hunt5a7fa252011-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 Kyrtzidis7bbb20e2008-06-24 22:12:16 +000043
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000044 MultiTemplateParamsArg TemplateParams(
Alexis Hunt1deb9722010-04-14 23:07:37 +000045 TemplateInfo.TemplateParams ? TemplateInfo.TemplateParams->data() : 0,
46 TemplateInfo.TemplateParams ? TemplateInfo.TemplateParams->size() : 0);
47
Rafael Espindolac2453dd2013-01-08 21:00:12 +000048 NamedDecl *FnD;
Douglas Gregor5d1b4e32011-11-07 20:56:01 +000049 D.setFunctionDefinitionKind(DefinitionKind);
John McCall07e91c02009-08-06 02:15:43 +000050 if (D.getDeclSpec().isFriendSpecified())
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000051 FnD = Actions.ActOnFriendFunctionDecl(getCurScope(), D,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000052 TemplateParams);
Douglas Gregor728d00b2011-10-10 14:49:18 +000053 else {
Douglas Gregor0be31a22010-07-02 17:43:08 +000054 FnD = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS, D,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000055 TemplateParams, 0,
Richard Smith2b013182012-06-10 03:12:00 +000056 VS, ICIS_NoInit);
Douglas Gregor728d00b2011-10-10 14:49:18 +000057 if (FnD) {
Richard Smithf8a75c32013-08-29 00:47:48 +000058 Actions.ProcessDeclAttributeList(getCurScope(), FnD, AccessAttrs);
Richard Smith74aeef52013-04-26 16:15:35 +000059 bool TypeSpecContainsAuto = D.getDeclSpec().containsPlaceholderType();
Douglas Gregor50cefbf2011-10-17 17:09:53 +000060 if (Init.isUsable())
Larisse Voufo39a1e502013-08-06 01:03:05 +000061 Actions.AddInitializerToDecl(FnD, Init.get(), false,
Douglas Gregor728d00b2011-10-10 14:49:18 +000062 TypeSpecContainsAuto);
63 else
64 Actions.ActOnUninitializedDecl(FnD, TypeSpecContainsAuto);
65 }
Nico Weber24b2a822011-01-28 06:07:34 +000066 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +000067
Douglas Gregor433e0532012-04-16 18:27:27 +000068 HandleMemberFunctionDeclDelays(D, FnD);
Eli Friedman3af2a772009-07-22 21:45:50 +000069
John McCallc1465822011-02-14 07:13:47 +000070 D.complete(FnD);
71
Alexis Hunt5a7fa252011-05-12 06:15:49 +000072 if (Tok.is(tok::equal)) {
73 ConsumeToken();
74
Richard Smith1c704732011-11-10 09:08:44 +000075 if (!FnD) {
76 SkipUntil(tok::semi);
77 return 0;
78 }
79
Alexis Hunt5a7fa252011-05-12 06:15:49 +000080 bool Delete = false;
81 SourceLocation KWLoc;
82 if (Tok.is(tok::kw_delete)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000083 Diag(Tok, getLangOpts().CPlusPlus11 ?
Richard Smith5d164bc2011-10-15 05:09:34 +000084 diag::warn_cxx98_compat_deleted_function :
Richard Smithe4345902011-12-29 21:57:33 +000085 diag::ext_deleted_function);
Alexis Hunt5a7fa252011-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 Smith2bf7fdb2013-01-02 11:42:31 +000091 Diag(Tok, getLangOpts().CPlusPlus11 ?
Richard Smith5d164bc2011-10-15 05:09:34 +000092 diag::warn_cxx98_compat_defaulted_function :
Richard Smithe4345902011-12-29 21:57:33 +000093 diag::ext_defaulted_function);
Alexis Hunt5a7fa252011-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 Pichet1c229c02011-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 Majnemer90b17292013-09-14 05:46:42 +0000116 if (getLangOpts().DelayedTemplateParsing &&
117 DefinitionKind == FDK_Definition &&
Francois Pichet1c229c02011-04-22 22:18:13 +0000118 ((Actions.CurContext->isDependentContext() ||
David Majnemer90b17292013-09-14 05:46:42 +0000119 (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
120 TemplateInfo.Kind != ParsedTemplateInfo::ExplicitSpecialization)) &&
121 !Actions.IsInsideALocalClassWithinATemplateFunction())) {
Francois Pichet1c229c02011-04-22 22:18:13 +0000122
Richard Smithe40f2ba2013-08-07 21:41:30 +0000123 CachedTokens Toks;
124 LexTemplateFunctionForLateParsing(Toks);
Francois Pichet1c229c02011-04-22 22:18:13 +0000125
Richard Smithe40f2ba2013-08-07 21:41:30 +0000126 if (FnD) {
John McCalle68672f2013-03-14 05:13:41 +0000127 FunctionDecl *FD = getFunctionDecl(FnD);
Chandler Carruthbc0f9ae2011-04-25 07:09:43 +0000128 Actions.CheckForFunctionRedefinition(FD);
Richard Smithe40f2ba2013-08-07 21:41:30 +0000129 Actions.MarkAsLateParsedTemplate(FD, FnD, Toks);
Francois Pichet1c229c02011-04-22 22:18:13 +0000130 }
131
132 return FnD;
133 }
134
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000135 // Consume the tokens and store them for later parsing.
136
Douglas Gregorefc46952010-10-12 16:25:54 +0000137 LexedMethod* LM = new LexedMethod(this, FnD);
138 getCurrentClass().LateParsedDeclarations.push_back(LM);
139 LM->TemplateScope = getCurScope()->isTemplateParamScope();
140 CachedTokens &Toks = LM->Toks;
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000141
Sebastian Redla7b98a72009-04-26 20:35:05 +0000142 tok::TokenKind kind = Tok.getKind();
Sebastian Redl0d164012011-09-30 08:32:17 +0000143 // Consume everything up to (and including) the left brace of the
144 // function body.
145 if (ConsumeAndStoreFunctionPrologue(Toks)) {
146 // We didn't find the left-brace we expected after the
Eli Friedman7cd4a9b2012-02-22 04:49:04 +0000147 // constructor initializer; we already printed an error, and it's likely
148 // impossible to recover, so don't try to parse this method later.
Richard Smithcde3fd82013-07-04 00:13:48 +0000149 // Skip over the rest of the decl and back to somewhere that looks
150 // reasonable.
151 SkipMalformedDecl();
Eli Friedman7cd4a9b2012-02-22 04:49:04 +0000152 delete getCurrentClass().LateParsedDeclarations.back();
153 getCurrentClass().LateParsedDeclarations.pop_back();
154 return FnD;
Douglas Gregore8381c02008-11-05 04:29:56 +0000155 } else {
Sebastian Redl0d164012011-09-30 08:32:17 +0000156 // Consume everything up to (and including) the matching right brace.
157 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
Douglas Gregore8381c02008-11-05 04:29:56 +0000158 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000159
Sebastian Redla7b98a72009-04-26 20:35:05 +0000160 // If we're in a function-try-block, we need to store all the catch blocks.
161 if (kind == tok::kw_try) {
162 while (Tok.is(tok::kw_catch)) {
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000163 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
164 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
Sebastian Redla7b98a72009-04-26 20:35:05 +0000165 }
166 }
167
Stephen Lin9354fc52013-06-23 07:37:13 +0000168 if (FnD) {
169 // If this is a friend function, mark that it's late-parsed so that
170 // it's still known to be a definition even before we attach the
171 // parsed body. Sema needs to treat friend function definitions
172 // differently during template instantiation, and it's possible for
173 // the containing class to be instantiated before all its member
174 // function definitions are parsed.
175 //
176 // If you remove this, you can remove the code that clears the flag
177 // after parsing the member.
178 if (D.getDeclSpec().isFriendSpecified()) {
179 getFunctionDecl(FnD)->setLateTemplateParsed(true);
180 }
181 } else {
Douglas Gregor6ca64102011-04-14 23:19:27 +0000182 // If semantic analysis could not build a function declaration,
183 // just throw away the late-parsed declaration.
184 delete getCurrentClass().LateParsedDeclarations.back();
185 getCurrentClass().LateParsedDeclarations.pop_back();
186 }
187
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000188 return FnD;
189}
190
Richard Smith938f40b2011-06-11 17:19:42 +0000191/// ParseCXXNonStaticMemberInitializer - We parsed and verified that the
192/// specified Declarator is a well formed C++ non-static data member
193/// declaration. Now lex its initializer and store its tokens for parsing
194/// after the class is complete.
195void Parser::ParseCXXNonStaticMemberInitializer(Decl *VarD) {
196 assert((Tok.is(tok::l_brace) || Tok.is(tok::equal)) &&
197 "Current token not a '{' or '='!");
198
199 LateParsedMemberInitializer *MI =
200 new LateParsedMemberInitializer(this, VarD);
201 getCurrentClass().LateParsedDeclarations.push_back(MI);
202 CachedTokens &Toks = MI->Toks;
203
204 tok::TokenKind kind = Tok.getKind();
205 if (kind == tok::equal) {
206 Toks.push_back(Tok);
Douglas Gregor0cf55e92012-03-08 01:00:17 +0000207 ConsumeToken();
Richard Smith938f40b2011-06-11 17:19:42 +0000208 }
209
210 if (kind == tok::l_brace) {
211 // Begin by storing the '{' token.
212 Toks.push_back(Tok);
213 ConsumeBrace();
214
215 // Consume everything up to (and including) the matching right brace.
216 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/true);
217 } else {
218 // Consume everything up to (but excluding) the comma or semicolon.
Richard Smith1fff95c2013-09-12 23:28:08 +0000219 ConsumeAndStoreInitializer(Toks, CIK_DefaultInitializer);
Richard Smith938f40b2011-06-11 17:19:42 +0000220 }
221
222 // Store an artificial EOF token to ensure that we don't run off the end of
223 // the initializer when we come to parse it.
224 Token Eof;
225 Eof.startToken();
226 Eof.setKind(tok::eof);
227 Eof.setLocation(Tok.getLocation());
228 Toks.push_back(Eof);
229}
230
Douglas Gregorefc46952010-10-12 16:25:54 +0000231Parser::LateParsedDeclaration::~LateParsedDeclaration() {}
232void Parser::LateParsedDeclaration::ParseLexedMethodDeclarations() {}
Richard Smith938f40b2011-06-11 17:19:42 +0000233void Parser::LateParsedDeclaration::ParseLexedMemberInitializers() {}
Douglas Gregorefc46952010-10-12 16:25:54 +0000234void Parser::LateParsedDeclaration::ParseLexedMethodDefs() {}
235
236Parser::LateParsedClass::LateParsedClass(Parser *P, ParsingClass *C)
237 : Self(P), Class(C) {}
238
239Parser::LateParsedClass::~LateParsedClass() {
240 Self->DeallocateParsedClasses(Class);
241}
242
243void Parser::LateParsedClass::ParseLexedMethodDeclarations() {
244 Self->ParseLexedMethodDeclarations(*Class);
245}
246
Richard Smith938f40b2011-06-11 17:19:42 +0000247void Parser::LateParsedClass::ParseLexedMemberInitializers() {
248 Self->ParseLexedMemberInitializers(*Class);
249}
250
Douglas Gregorefc46952010-10-12 16:25:54 +0000251void Parser::LateParsedClass::ParseLexedMethodDefs() {
252 Self->ParseLexedMethodDefs(*Class);
253}
254
255void Parser::LateParsedMethodDeclaration::ParseLexedMethodDeclarations() {
256 Self->ParseLexedMethodDeclaration(*this);
257}
258
259void Parser::LexedMethod::ParseLexedMethodDefs() {
260 Self->ParseLexedMethodDef(*this);
261}
262
Richard Smith938f40b2011-06-11 17:19:42 +0000263void Parser::LateParsedMemberInitializer::ParseLexedMemberInitializers() {
264 Self->ParseLexedMemberInitializer(*this);
265}
266
Douglas Gregor4d87df52008-12-16 21:30:33 +0000267/// ParseLexedMethodDeclarations - We finished parsing the member
268/// specification of a top (non-nested) C++ class. Now go over the
269/// stack of method declarations with some parts for which parsing was
270/// delayed (such as default arguments) and parse them.
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000271void Parser::ParseLexedMethodDeclarations(ParsingClass &Class) {
272 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
Douglas Gregorefc46952010-10-12 16:25:54 +0000273 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope, HasTemplateScope);
Richard Smithc8378952013-04-29 11:55:38 +0000274 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
275 if (HasTemplateScope) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000276 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
Richard Smithc8378952013-04-29 11:55:38 +0000277 ++CurTemplateDepthTracker;
278 }
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000279
John McCall6df5fef2009-12-19 10:49:29 +0000280 // The current scope is still active if we're the top-level class.
281 // Otherwise we'll need to push and enter a new scope.
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000282 bool HasClassScope = !Class.TopLevelClass;
Alexis Hunt1deb9722010-04-14 23:07:37 +0000283 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope,
284 HasClassScope);
John McCall6df5fef2009-12-19 10:49:29 +0000285 if (HasClassScope)
Douglas Gregor0be31a22010-07-02 17:43:08 +0000286 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(), Class.TagOrTemplate);
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000287
Douglas Gregorefc46952010-10-12 16:25:54 +0000288 for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
289 Class.LateParsedDeclarations[i]->ParseLexedMethodDeclarations();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000290 }
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000291
John McCall6df5fef2009-12-19 10:49:29 +0000292 if (HasClassScope)
Douglas Gregor0be31a22010-07-02 17:43:08 +0000293 Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(), Class.TagOrTemplate);
Douglas Gregor4d87df52008-12-16 21:30:33 +0000294}
295
Douglas Gregorefc46952010-10-12 16:25:54 +0000296void Parser::ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM) {
297 // If this is a member template, introduce the template parameter scope.
298 ParseScope TemplateScope(this, Scope::TemplateParamScope, LM.TemplateScope);
Richard Smithc8378952013-04-29 11:55:38 +0000299 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
300 if (LM.TemplateScope) {
Douglas Gregorefc46952010-10-12 16:25:54 +0000301 Actions.ActOnReenterTemplateScope(getCurScope(), LM.Method);
Richard Smithc8378952013-04-29 11:55:38 +0000302 ++CurTemplateDepthTracker;
303 }
Douglas Gregorefc46952010-10-12 16:25:54 +0000304 // Start the delayed C++ method declaration
305 Actions.ActOnStartDelayedCXXMethodDeclaration(getCurScope(), LM.Method);
306
307 // Introduce the parameters into scope and parse their default
308 // arguments.
Richard Smithe233fbf2013-01-28 22:42:45 +0000309 ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
310 Scope::FunctionDeclarationScope | Scope::DeclScope);
Douglas Gregorefc46952010-10-12 16:25:54 +0000311 for (unsigned I = 0, N = LM.DefaultArgs.size(); I != N; ++I) {
312 // Introduce the parameter into scope.
Douglas Gregor7fcbd902012-02-21 00:37:24 +0000313 Actions.ActOnDelayedCXXMethodParameter(getCurScope(),
314 LM.DefaultArgs[I].Param);
Douglas Gregorefc46952010-10-12 16:25:54 +0000315
316 if (CachedTokens *Toks = LM.DefaultArgs[I].Toks) {
317 // Save the current token position.
318 SourceLocation origLoc = Tok.getLocation();
319
320 // Parse the default argument from its saved token stream.
321 Toks->push_back(Tok); // So that the current token doesn't get lost
322 PP.EnterTokenStream(&Toks->front(), Toks->size(), true, false);
323
324 // Consume the previously-pushed token.
325 ConsumeAnyToken();
326
327 // Consume the '='.
328 assert(Tok.is(tok::equal) && "Default argument not starting with '='");
329 SourceLocation EqualLoc = ConsumeToken();
330
331 // The argument isn't actually potentially evaluated unless it is
332 // used.
333 EnterExpressionEvaluationContext Eval(Actions,
Douglas Gregor7fcbd902012-02-21 00:37:24 +0000334 Sema::PotentiallyEvaluatedIfUsed,
335 LM.DefaultArgs[I].Param);
Douglas Gregorefc46952010-10-12 16:25:54 +0000336
Sebastian Redldb63af22012-03-14 15:54:00 +0000337 ExprResult DefArgResult;
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000338 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
Sebastian Redl6db0b1b2012-03-20 21:24:03 +0000339 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
Sebastian Redldb63af22012-03-14 15:54:00 +0000340 DefArgResult = ParseBraceInitializer();
Sebastian Redl6db0b1b2012-03-20 21:24:03 +0000341 } else
Sebastian Redldb63af22012-03-14 15:54:00 +0000342 DefArgResult = ParseAssignmentExpression();
Douglas Gregorefc46952010-10-12 16:25:54 +0000343 if (DefArgResult.isInvalid())
344 Actions.ActOnParamDefaultArgumentError(LM.DefaultArgs[I].Param);
345 else {
346 if (Tok.is(tok::cxx_defaultarg_end))
347 ConsumeToken();
Richard Smith1fff95c2013-09-12 23:28:08 +0000348 else {
349 // The last two tokens are the terminator and the saved value of
350 // Tok; the last token in the default argument is the one before
351 // those.
352 assert(Toks->size() >= 3 && "expected a token in default arg");
353 Diag(Tok.getLocation(), diag::err_default_arg_unparsed)
354 << SourceRange(Tok.getLocation(),
355 (*Toks)[Toks->size() - 3].getLocation());
356 }
Douglas Gregorefc46952010-10-12 16:25:54 +0000357 Actions.ActOnParamDefaultArgument(LM.DefaultArgs[I].Param, EqualLoc,
358 DefArgResult.take());
359 }
360
361 assert(!PP.getSourceManager().isBeforeInTranslationUnit(origLoc,
362 Tok.getLocation()) &&
363 "ParseAssignmentExpression went over the default arg tokens!");
364 // There could be leftover tokens (e.g. because of an error).
365 // Skip through until we reach the original token position.
366 while (Tok.getLocation() != origLoc && Tok.isNot(tok::eof))
367 ConsumeAnyToken();
368
369 delete Toks;
370 LM.DefaultArgs[I].Toks = 0;
371 }
372 }
Douglas Gregor433e0532012-04-16 18:27:27 +0000373
Douglas Gregorefc46952010-10-12 16:25:54 +0000374 PrototypeScope.Exit();
375
376 // Finish the delayed C++ method declaration.
377 Actions.ActOnFinishDelayedCXXMethodDeclaration(getCurScope(), LM.Method);
378}
379
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000380/// ParseLexedMethodDefs - We finished parsing the member specification of a top
381/// (non-nested) C++ class. Now go over the stack of lexed methods that were
382/// collected during its parsing and parse them all.
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000383void Parser::ParseLexedMethodDefs(ParsingClass &Class) {
384 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
Douglas Gregorefc46952010-10-12 16:25:54 +0000385 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope, HasTemplateScope);
Richard Smithc8378952013-04-29 11:55:38 +0000386 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
387 if (HasTemplateScope) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000388 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
Richard Smithc8378952013-04-29 11:55:38 +0000389 ++CurTemplateDepthTracker;
390 }
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000391 bool HasClassScope = !Class.TopLevelClass;
392 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope,
393 HasClassScope);
394
Douglas Gregorefc46952010-10-12 16:25:54 +0000395 for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
396 Class.LateParsedDeclarations[i]->ParseLexedMethodDefs();
397 }
398}
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000399
Douglas Gregorefc46952010-10-12 16:25:54 +0000400void Parser::ParseLexedMethodDef(LexedMethod &LM) {
401 // If this is a member template, introduce the template parameter scope.
402 ParseScope TemplateScope(this, Scope::TemplateParamScope, LM.TemplateScope);
Richard Smithc8378952013-04-29 11:55:38 +0000403 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
404 if (LM.TemplateScope) {
Douglas Gregorefc46952010-10-12 16:25:54 +0000405 Actions.ActOnReenterTemplateScope(getCurScope(), LM.D);
Richard Smithc8378952013-04-29 11:55:38 +0000406 ++CurTemplateDepthTracker;
407 }
Douglas Gregorefc46952010-10-12 16:25:54 +0000408 // Save the current token position.
409 SourceLocation origLoc = Tok.getLocation();
Argyrios Kyrtzidis02041972010-03-31 00:38:09 +0000410
Douglas Gregorefc46952010-10-12 16:25:54 +0000411 assert(!LM.Toks.empty() && "Empty body!");
412 // Append the current token at the end of the new token stream so that it
413 // doesn't get lost.
414 LM.Toks.push_back(Tok);
415 PP.EnterTokenStream(LM.Toks.data(), LM.Toks.size(), true, false);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000416
Douglas Gregorefc46952010-10-12 16:25:54 +0000417 // Consume the previously pushed token.
Argyrios Kyrtzidisc36633c2013-03-27 23:58:17 +0000418 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
Douglas Gregorefc46952010-10-12 16:25:54 +0000419 assert((Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try))
420 && "Inline method not starting with '{', ':' or 'try'");
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000421
Douglas Gregorefc46952010-10-12 16:25:54 +0000422 // Parse the method body. Function body parsing code is similar enough
423 // to be re-used for method bodies as well.
424 ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope);
425 Actions.ActOnStartOfFunctionDef(getCurScope(), LM.D);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000426
Douglas Gregorefc46952010-10-12 16:25:54 +0000427 if (Tok.is(tok::kw_try)) {
Douglas Gregora0ff0c32011-03-16 17:05:57 +0000428 ParseFunctionTryBlock(LM.D, FnScope);
Douglas Gregorefc46952010-10-12 16:25:54 +0000429 assert(!PP.getSourceManager().isBeforeInTranslationUnit(origLoc,
430 Tok.getLocation()) &&
431 "ParseFunctionTryBlock went over the cached tokens!");
432 // There could be leftover tokens (e.g. because of an error).
433 // Skip through until we reach the original token position.
434 while (Tok.getLocation() != origLoc && Tok.isNot(tok::eof))
435 ConsumeAnyToken();
436 return;
437 }
438 if (Tok.is(tok::colon)) {
439 ParseConstructorInitializer(LM.D);
440
441 // Error recovery.
442 if (!Tok.is(tok::l_brace)) {
Douglas Gregora0ff0c32011-03-16 17:05:57 +0000443 FnScope.Exit();
Douglas Gregorefc46952010-10-12 16:25:54 +0000444 Actions.ActOnFinishFunctionBody(LM.D, 0);
Matt Beaumont-Gayd0457922011-09-23 22:39:23 +0000445 while (Tok.getLocation() != origLoc && Tok.isNot(tok::eof))
446 ConsumeAnyToken();
Douglas Gregorefc46952010-10-12 16:25:54 +0000447 return;
448 }
449 } else
450 Actions.ActOnDefaultCtorInitializers(LM.D);
451
Richard Smithc8378952013-04-29 11:55:38 +0000452 assert((Actions.getDiagnostics().hasErrorOccurred() ||
453 !isa<FunctionTemplateDecl>(LM.D) ||
454 cast<FunctionTemplateDecl>(LM.D)->getTemplateParameters()->getDepth()
455 < TemplateParameterDepth) &&
456 "TemplateParameterDepth should be greater than the depth of "
457 "current template being instantiated!");
458
Douglas Gregora0ff0c32011-03-16 17:05:57 +0000459 ParseFunctionStatementBody(LM.D, FnScope);
Douglas Gregorefc46952010-10-12 16:25:54 +0000460
John McCalle68672f2013-03-14 05:13:41 +0000461 // Clear the late-template-parsed bit if we set it before.
462 if (LM.D) getFunctionDecl(LM.D)->setLateTemplateParsed(false);
463
Douglas Gregorefc46952010-10-12 16:25:54 +0000464 if (Tok.getLocation() != origLoc) {
465 // Due to parsing error, we either went over the cached tokens or
466 // there are still cached tokens left. If it's the latter case skip the
467 // leftover tokens.
468 // Since this is an uncommon situation that should be avoided, use the
469 // expensive isBeforeInTranslationUnit call.
470 if (PP.getSourceManager().isBeforeInTranslationUnit(Tok.getLocation(),
471 origLoc))
Argyrios Kyrtzidise1224c82010-06-19 19:58:34 +0000472 while (Tok.getLocation() != origLoc && Tok.isNot(tok::eof))
Argyrios Kyrtzidise9b76af2010-06-17 10:52:22 +0000473 ConsumeAnyToken();
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000474 }
475}
476
Richard Smith938f40b2011-06-11 17:19:42 +0000477/// ParseLexedMemberInitializers - We finished parsing the member specification
478/// of a top (non-nested) C++ class. Now go over the stack of lexed data member
479/// initializers that were collected during its parsing and parse them all.
480void Parser::ParseLexedMemberInitializers(ParsingClass &Class) {
481 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
482 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
483 HasTemplateScope);
Richard Smithc8378952013-04-29 11:55:38 +0000484 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
485 if (HasTemplateScope) {
Richard Smith938f40b2011-06-11 17:19:42 +0000486 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
Richard Smithc8378952013-04-29 11:55:38 +0000487 ++CurTemplateDepthTracker;
488 }
Douglas Gregor3024f072012-04-16 07:05:22 +0000489 // Set or update the scope flags.
Richard Smith938f40b2011-06-11 17:19:42 +0000490 bool AlreadyHasClassScope = Class.TopLevelClass;
Douglas Gregor3024f072012-04-16 07:05:22 +0000491 unsigned ScopeFlags = Scope::ClassScope|Scope::DeclScope;
Richard Smith938f40b2011-06-11 17:19:42 +0000492 ParseScope ClassScope(this, ScopeFlags, !AlreadyHasClassScope);
493 ParseScopeFlags ClassScopeFlags(this, ScopeFlags, AlreadyHasClassScope);
494
495 if (!AlreadyHasClassScope)
496 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(),
497 Class.TagOrTemplate);
498
Benjamin Kramer1d373c62012-05-17 12:01:52 +0000499 if (!Class.LateParsedDeclarations.empty()) {
Douglas Gregor3024f072012-04-16 07:05:22 +0000500 // C++11 [expr.prim.general]p4:
501 // Otherwise, if a member-declarator declares a non-static data member
502 // (9.2) of a class X, the expression this is a prvalue of type "pointer
503 // to X" within the optional brace-or-equal-initializer. It shall not
504 // appear elsewhere in the member-declarator.
505 Sema::CXXThisScopeRAII ThisScope(Actions, Class.TagOrTemplate,
506 /*TypeQuals=*/(unsigned)0);
Richard Smith938f40b2011-06-11 17:19:42 +0000507
Douglas Gregor3024f072012-04-16 07:05:22 +0000508 for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
509 Class.LateParsedDeclarations[i]->ParseLexedMemberInitializers();
510 }
511 }
512
Richard Smith938f40b2011-06-11 17:19:42 +0000513 if (!AlreadyHasClassScope)
514 Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(),
515 Class.TagOrTemplate);
516
517 Actions.ActOnFinishDelayedMemberInitializers(Class.TagOrTemplate);
518}
519
520void Parser::ParseLexedMemberInitializer(LateParsedMemberInitializer &MI) {
Richard Smith1a526fd2011-09-29 19:42:27 +0000521 if (!MI.Field || MI.Field->isInvalidDecl())
Richard Smith938f40b2011-06-11 17:19:42 +0000522 return;
523
524 // Append the current token at the end of the new token stream so that it
525 // doesn't get lost.
526 MI.Toks.push_back(Tok);
527 PP.EnterTokenStream(MI.Toks.data(), MI.Toks.size(), true, false);
528
529 // Consume the previously pushed token.
Argyrios Kyrtzidisc36633c2013-03-27 23:58:17 +0000530 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
Richard Smith938f40b2011-06-11 17:19:42 +0000531
532 SourceLocation EqualLoc;
Richard Smith2b013182012-06-10 03:12:00 +0000533
Douglas Gregor926410d2012-02-21 02:22:07 +0000534 ExprResult Init = ParseCXXMemberInitializer(MI.Field, /*IsFunction=*/false,
535 EqualLoc);
Richard Smith938f40b2011-06-11 17:19:42 +0000536
537 Actions.ActOnCXXInClassMemberInitializer(MI.Field, EqualLoc, Init.release());
538
539 // The next token should be our artificial terminating EOF token.
540 if (Tok.isNot(tok::eof)) {
541 SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
542 if (!EndLoc.isValid())
543 EndLoc = Tok.getLocation();
544 // No fixit; we can't recover as if there were a semicolon here.
545 Diag(EndLoc, diag::err_expected_semi_decl_list);
546
547 // Consume tokens until we hit the artificial EOF.
548 while (Tok.isNot(tok::eof))
549 ConsumeAnyToken();
550 }
551 ConsumeAnyToken();
552}
553
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000554/// ConsumeAndStoreUntil - Consume and store the token at the passed token
Douglas Gregor4d87df52008-12-16 21:30:33 +0000555/// container until the token 'T' is reached (which gets
Mike Stump11289f42009-09-09 15:08:12 +0000556/// consumed/stored too, if ConsumeFinalToken).
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000557/// If StopAtSemi is true, then we will stop early at a ';' character.
Douglas Gregor4d87df52008-12-16 21:30:33 +0000558/// Returns true if token 'T1' or 'T2' was found.
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000559/// NOTE: This is a specialized version of Parser::SkipUntil.
Douglas Gregor4d87df52008-12-16 21:30:33 +0000560bool Parser::ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
561 CachedTokens &Toks,
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000562 bool StopAtSemi, bool ConsumeFinalToken) {
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000563 // We always want this function to consume at least one token if the first
564 // token isn't T and if not at EOF.
565 bool isFirstTokenConsumed = true;
566 while (1) {
567 // If we found one of the tokens, stop and return true.
Douglas Gregor4d87df52008-12-16 21:30:33 +0000568 if (Tok.is(T1) || Tok.is(T2)) {
569 if (ConsumeFinalToken) {
570 Toks.push_back(Tok);
571 ConsumeAnyToken();
572 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000573 return true;
574 }
575
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000576 switch (Tok.getKind()) {
577 case tok::eof:
578 // 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))
673 return Diag(Tok.getLocation(), diag::err_expected_lbrace);
674
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)) {
706 Diag(Tok.getLocation(), diag::err_expected_rparen);
707 Diag(OpenLoc, diag::note_matching) << "(";
708 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!
754 return Diag(Tok.getLocation(), diag::err_expected_lbrace);
755 }
756 } else if (Tok.isNot(tok::l_paren) && Tok.isNot(tok::l_brace)) {
757 // We found something weird in a mem-initializer-id.
758 return Diag(Tok.getLocation(), getLangOpts().CPlusPlus11
759 ? diag::err_expected_lparen_or_lbrace
760 : diag::err_expected_lparen);
761 }
762
763 tok::TokenKind kind = Tok.getKind();
764 Toks.push_back(Tok);
765 bool IsLParen = (kind == tok::l_paren);
766 SourceLocation OpenLoc = Tok.getLocation();
767
768 if (IsLParen) {
769 ConsumeParen();
770 } else {
771 assert(kind == tok::l_brace && "Must be left paren or brace here.");
772 ConsumeBrace();
773 // In C++03, this has to be the start of the function body, which
774 // means the initializer is malformed; we'll diagnose it later.
775 if (!getLangOpts().CPlusPlus11)
776 return false;
777 }
778
779 // Grab the initializer (or the subexpression of the template argument).
780 // FIXME: If we support lambdas here, we'll need to set StopAtSemi to false
781 // if we might be inside the braces of a lambda-expression.
782 if (!ConsumeAndStoreUntil(IsLParen ? tok::r_paren : tok::r_brace,
783 Toks, /*StopAtSemi=*/true)) {
784 Diag(Tok, IsLParen ? diag::err_expected_rparen :
785 diag::err_expected_rbrace);
786 Diag(OpenLoc, diag::note_matching) << (IsLParen ? "(" : "{");
787 return true;
788 }
789
790 // Grab pack ellipsis, if present.
791 if (Tok.is(tok::ellipsis)) {
792 Toks.push_back(Tok);
793 ConsumeToken();
794 }
795
796 // If we know we just consumed a mem-initializer, we must have ',' or '{'
797 // next.
798 if (Tok.is(tok::comma)) {
799 Toks.push_back(Tok);
800 ConsumeToken();
801 } else if (Tok.is(tok::l_brace)) {
802 // This is the function body if the ')' or '}' is immediately followed by
803 // a '{'. That cannot happen within a template argument, apart from the
804 // case where a template argument contains a compound literal:
805 //
806 // S ( ) : a < b < c > ( d ) { }
807 // // End of declaration, or still inside the template argument?
808 //
809 // ... and the case where the template argument contains a lambda:
810 //
811 // S ( ) : a < 0 && b < c > ( d ) + [ ] ( ) { return 0; }
812 // ( ) > ( ) { }
813 //
814 // FIXME: Disambiguate these cases. Note that the latter case is probably
815 // going to be made ill-formed by core issue 1607.
816 Toks.push_back(Tok);
817 ConsumeBrace();
818 return false;
819 } else if (!MightBeTemplateArgument) {
820 return Diag(Tok.getLocation(), diag::err_expected_lbrace_or_comma);
821 }
822 }
Sebastian Redla74948d2011-09-24 17:48:25 +0000823}
Richard Smith1fff95c2013-09-12 23:28:08 +0000824
825/// \brief Consume and store tokens from the '?' to the ':' in a conditional
826/// expression.
827bool Parser::ConsumeAndStoreConditional(CachedTokens &Toks) {
828 // Consume '?'.
829 assert(Tok.is(tok::question));
830 Toks.push_back(Tok);
831 ConsumeToken();
832
833 while (Tok.isNot(tok::colon)) {
834 if (!ConsumeAndStoreUntil(tok::question, tok::colon, Toks, /*StopAtSemi*/true,
835 /*ConsumeFinalToken*/false))
836 return false;
837
838 // If we found a nested conditional, consume it.
839 if (Tok.is(tok::question) && !ConsumeAndStoreConditional(Toks))
840 return false;
841 }
842
843 // Consume ':'.
844 Toks.push_back(Tok);
845 ConsumeToken();
846 return true;
847}
848
849/// \brief A tentative parsing action that can also revert token annotations.
850class Parser::UnannotatedTentativeParsingAction : public TentativeParsingAction {
851public:
852 explicit UnannotatedTentativeParsingAction(Parser &Self,
853 tok::TokenKind EndKind)
854 : TentativeParsingAction(Self), Self(Self), EndKind(EndKind) {
855 // Stash away the old token stream, so we can restore it once the
856 // tentative parse is complete.
857 TentativeParsingAction Inner(Self);
858 Self.ConsumeAndStoreUntil(EndKind, Toks, true, /*ConsumeFinalToken*/false);
859 Inner.Revert();
860 }
861
862 void RevertAnnotations() {
863 Revert();
864
865 // Put back the original tokens.
866 Self.SkipUntil(EndKind, true, /*DontConsume*/true);
867 if (Toks.size()) {
868 Token *Buffer = new Token[Toks.size()];
869 std::copy(Toks.begin() + 1, Toks.end(), Buffer);
870 Buffer[Toks.size() - 1] = Self.Tok;
871 Self.PP.EnterTokenStream(Buffer, Toks.size(), true, /*Owned*/true);
872
873 Self.Tok = Toks.front();
874 }
875 }
876
877private:
878 Parser &Self;
879 CachedTokens Toks;
880 tok::TokenKind EndKind;
881};
882
883/// ConsumeAndStoreInitializer - Consume and store the token at the passed token
884/// container until the end of the current initializer expression (either a
885/// default argument or an in-class initializer for a non-static data member).
886/// The final token is not consumed.
887bool Parser::ConsumeAndStoreInitializer(CachedTokens &Toks,
888 CachedInitKind CIK) {
889 // We always want this function to consume at least one token if not at EOF.
890 bool IsFirstTokenConsumed = true;
891
892 // Number of possible unclosed <s we've seen so far. These might be templates,
893 // and might not, but if there were none of them (or we know for sure that
894 // we're within a template), we can avoid a tentative parse.
895 unsigned AngleCount = 0;
896 unsigned KnownTemplateCount = 0;
897
898 while (1) {
899 switch (Tok.getKind()) {
900 case tok::comma:
901 // If we might be in a template, perform a tentative parse to check.
902 if (!AngleCount)
903 // Not a template argument: this is the end of the initializer.
904 return true;
905 if (KnownTemplateCount)
906 goto consume_token;
907
908 // We hit a comma inside angle brackets. This is the hard case. The
909 // rule we follow is:
910 // * For a default argument, if the tokens after the comma form a
911 // syntactically-valid parameter-declaration-clause, in which each
912 // parameter has an initializer, then this comma ends the default
913 // argument.
914 // * For a default initializer, if the tokens after the comma form a
915 // syntactically-valid init-declarator-list, then this comma ends
916 // the default initializer.
917 {
918 UnannotatedTentativeParsingAction PA(*this,
919 CIK == CIK_DefaultInitializer
920 ? tok::semi : tok::r_paren);
921 Sema::TentativeAnalysisScope Scope(Actions);
922
923 TPResult Result = TPResult::Error();
924 ConsumeToken();
925 switch (CIK) {
926 case CIK_DefaultInitializer:
927 Result = TryParseInitDeclaratorList();
928 // If we parsed a complete, ambiguous init-declarator-list, this
929 // is only syntactically-valid if it's followed by a semicolon.
930 if (Result == TPResult::Ambiguous() && Tok.isNot(tok::semi))
931 Result = TPResult::False();
932 break;
933
934 case CIK_DefaultArgument:
935 bool InvalidAsDeclaration = false;
936 Result = TryParseParameterDeclarationClause(
937 &InvalidAsDeclaration, /*VersusTemplateArgument*/true);
938 // If this is an expression or a declaration with a missing
939 // 'typename', assume it's not a declaration.
940 if (Result == TPResult::Ambiguous() && InvalidAsDeclaration)
941 Result = TPResult::False();
942 break;
943 }
944
945 // If what follows could be a declaration, it is a declaration.
946 if (Result != TPResult::False() && Result != TPResult::Error()) {
947 PA.Revert();
948 return true;
949 }
950
951 // In the uncommon case that we decide the following tokens are part
952 // of a template argument, revert any annotations we've performed in
953 // those tokens. We're not going to look them up until we've parsed
954 // the rest of the class, and that might add more declarations.
955 PA.RevertAnnotations();
956 }
957
958 // Keep going. We know we're inside a template argument list now.
959 ++KnownTemplateCount;
960 goto consume_token;
961
962 case tok::eof:
963 // Ran out of tokens.
964 return false;
965
966 case tok::less:
967 // FIXME: A '<' can only start a template-id if it's preceded by an
968 // identifier, an operator-function-id, or a literal-operator-id.
969 ++AngleCount;
970 goto consume_token;
971
972 case tok::question:
973 // In 'a ? b : c', 'b' can contain an unparenthesized comma. If it does,
974 // that is *never* the end of the initializer. Skip to the ':'.
975 if (!ConsumeAndStoreConditional(Toks))
976 return false;
977 break;
978
979 case tok::greatergreatergreater:
980 if (!getLangOpts().CPlusPlus11)
981 goto consume_token;
982 if (AngleCount) --AngleCount;
983 if (KnownTemplateCount) --KnownTemplateCount;
984 // Fall through.
985 case tok::greatergreater:
986 if (!getLangOpts().CPlusPlus11)
987 goto consume_token;
988 if (AngleCount) --AngleCount;
989 if (KnownTemplateCount) --KnownTemplateCount;
990 // Fall through.
991 case tok::greater:
992 if (AngleCount) --AngleCount;
993 if (KnownTemplateCount) --KnownTemplateCount;
994 goto consume_token;
995
996 case tok::kw_template:
997 // 'template' identifier '<' is known to start a template argument list,
998 // and can be used to disambiguate the parse.
999 // FIXME: Support all forms of 'template' unqualified-id '<'.
1000 Toks.push_back(Tok);
1001 ConsumeToken();
1002 if (Tok.is(tok::identifier)) {
1003 Toks.push_back(Tok);
1004 ConsumeToken();
1005 if (Tok.is(tok::less)) {
1006 ++KnownTemplateCount;
1007 Toks.push_back(Tok);
1008 ConsumeToken();
1009 }
1010 }
1011 break;
1012
1013 case tok::kw_operator:
1014 // If 'operator' precedes other punctuation, that punctuation loses
1015 // its special behavior.
1016 Toks.push_back(Tok);
1017 ConsumeToken();
1018 switch (Tok.getKind()) {
1019 case tok::comma:
1020 case tok::greatergreatergreater:
1021 case tok::greatergreater:
1022 case tok::greater:
1023 case tok::less:
1024 Toks.push_back(Tok);
1025 ConsumeToken();
1026 break;
1027 default:
1028 break;
1029 }
1030 break;
1031
1032 case tok::l_paren:
1033 // Recursively consume properly-nested parens.
1034 Toks.push_back(Tok);
1035 ConsumeParen();
1036 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
1037 break;
1038 case tok::l_square:
1039 // Recursively consume properly-nested square brackets.
1040 Toks.push_back(Tok);
1041 ConsumeBracket();
1042 ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false);
1043 break;
1044 case tok::l_brace:
1045 // Recursively consume properly-nested braces.
1046 Toks.push_back(Tok);
1047 ConsumeBrace();
1048 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1049 break;
1050
1051 // Okay, we found a ']' or '}' or ')', which we think should be balanced.
1052 // Since the user wasn't looking for this token (if they were, it would
1053 // already be handled), this isn't balanced. If there is a LHS token at a
1054 // higher level, we will assume that this matches the unbalanced token
1055 // and return it. Otherwise, this is a spurious RHS token, which we skip.
1056 case tok::r_paren:
1057 if (CIK == CIK_DefaultArgument)
1058 return true; // End of the default argument.
1059 if (ParenCount && !IsFirstTokenConsumed)
1060 return false; // Matches something.
1061 goto consume_token;
1062 case tok::r_square:
1063 if (BracketCount && !IsFirstTokenConsumed)
1064 return false; // Matches something.
1065 goto consume_token;
1066 case tok::r_brace:
1067 if (BraceCount && !IsFirstTokenConsumed)
1068 return false; // Matches something.
1069 goto consume_token;
1070
1071 case tok::code_completion:
1072 Toks.push_back(Tok);
1073 ConsumeCodeCompletionToken();
1074 break;
1075
1076 case tok::string_literal:
1077 case tok::wide_string_literal:
1078 case tok::utf8_string_literal:
1079 case tok::utf16_string_literal:
1080 case tok::utf32_string_literal:
1081 Toks.push_back(Tok);
1082 ConsumeStringToken();
1083 break;
1084 case tok::semi:
1085 if (CIK == CIK_DefaultInitializer)
1086 return true; // End of the default initializer.
1087 // FALL THROUGH.
1088 default:
1089 consume_token:
1090 Toks.push_back(Tok);
1091 ConsumeToken();
1092 break;
1093 }
1094 IsFirstTokenConsumed = false;
1095 }
1096}