blob: 6bab7988cf0bf92e5c17dfaf96f5da92231c781f [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()) {
Alp Toker19bff322013-10-18 05:54:24 +0000179 FunctionDecl *FD = getFunctionDecl(FnD);
180 Actions.CheckForFunctionRedefinition(FD);
181 FD->setLateTemplateParsed(true);
Stephen Lin9354fc52013-06-23 07:37:13 +0000182 }
183 } else {
Douglas Gregor6ca64102011-04-14 23:19:27 +0000184 // If semantic analysis could not build a function declaration,
185 // just throw away the late-parsed declaration.
186 delete getCurrentClass().LateParsedDeclarations.back();
187 getCurrentClass().LateParsedDeclarations.pop_back();
188 }
189
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000190 return FnD;
191}
192
Richard Smith938f40b2011-06-11 17:19:42 +0000193/// ParseCXXNonStaticMemberInitializer - We parsed and verified that the
194/// specified Declarator is a well formed C++ non-static data member
195/// declaration. Now lex its initializer and store its tokens for parsing
196/// after the class is complete.
197void Parser::ParseCXXNonStaticMemberInitializer(Decl *VarD) {
198 assert((Tok.is(tok::l_brace) || Tok.is(tok::equal)) &&
199 "Current token not a '{' or '='!");
200
201 LateParsedMemberInitializer *MI =
202 new LateParsedMemberInitializer(this, VarD);
203 getCurrentClass().LateParsedDeclarations.push_back(MI);
204 CachedTokens &Toks = MI->Toks;
205
206 tok::TokenKind kind = Tok.getKind();
207 if (kind == tok::equal) {
208 Toks.push_back(Tok);
Douglas Gregor0cf55e92012-03-08 01:00:17 +0000209 ConsumeToken();
Richard Smith938f40b2011-06-11 17:19:42 +0000210 }
211
212 if (kind == tok::l_brace) {
213 // Begin by storing the '{' token.
214 Toks.push_back(Tok);
215 ConsumeBrace();
216
217 // Consume everything up to (and including) the matching right brace.
218 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/true);
219 } else {
220 // Consume everything up to (but excluding) the comma or semicolon.
Richard Smith1fff95c2013-09-12 23:28:08 +0000221 ConsumeAndStoreInitializer(Toks, CIK_DefaultInitializer);
Richard Smith938f40b2011-06-11 17:19:42 +0000222 }
223
224 // Store an artificial EOF token to ensure that we don't run off the end of
225 // the initializer when we come to parse it.
226 Token Eof;
227 Eof.startToken();
228 Eof.setKind(tok::eof);
229 Eof.setLocation(Tok.getLocation());
230 Toks.push_back(Eof);
231}
232
Douglas Gregorefc46952010-10-12 16:25:54 +0000233Parser::LateParsedDeclaration::~LateParsedDeclaration() {}
234void Parser::LateParsedDeclaration::ParseLexedMethodDeclarations() {}
Richard Smith938f40b2011-06-11 17:19:42 +0000235void Parser::LateParsedDeclaration::ParseLexedMemberInitializers() {}
Douglas Gregorefc46952010-10-12 16:25:54 +0000236void Parser::LateParsedDeclaration::ParseLexedMethodDefs() {}
237
238Parser::LateParsedClass::LateParsedClass(Parser *P, ParsingClass *C)
239 : Self(P), Class(C) {}
240
241Parser::LateParsedClass::~LateParsedClass() {
242 Self->DeallocateParsedClasses(Class);
243}
244
245void Parser::LateParsedClass::ParseLexedMethodDeclarations() {
246 Self->ParseLexedMethodDeclarations(*Class);
247}
248
Richard Smith938f40b2011-06-11 17:19:42 +0000249void Parser::LateParsedClass::ParseLexedMemberInitializers() {
250 Self->ParseLexedMemberInitializers(*Class);
251}
252
Douglas Gregorefc46952010-10-12 16:25:54 +0000253void Parser::LateParsedClass::ParseLexedMethodDefs() {
254 Self->ParseLexedMethodDefs(*Class);
255}
256
257void Parser::LateParsedMethodDeclaration::ParseLexedMethodDeclarations() {
258 Self->ParseLexedMethodDeclaration(*this);
259}
260
261void Parser::LexedMethod::ParseLexedMethodDefs() {
262 Self->ParseLexedMethodDef(*this);
263}
264
Richard Smith938f40b2011-06-11 17:19:42 +0000265void Parser::LateParsedMemberInitializer::ParseLexedMemberInitializers() {
266 Self->ParseLexedMemberInitializer(*this);
267}
268
Douglas Gregor4d87df52008-12-16 21:30:33 +0000269/// ParseLexedMethodDeclarations - We finished parsing the member
270/// specification of a top (non-nested) C++ class. Now go over the
271/// stack of method declarations with some parts for which parsing was
272/// delayed (such as default arguments) and parse them.
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000273void Parser::ParseLexedMethodDeclarations(ParsingClass &Class) {
274 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
Douglas Gregorefc46952010-10-12 16:25:54 +0000275 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope, HasTemplateScope);
Richard Smithc8378952013-04-29 11:55:38 +0000276 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
277 if (HasTemplateScope) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000278 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
Richard Smithc8378952013-04-29 11:55:38 +0000279 ++CurTemplateDepthTracker;
280 }
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000281
John McCall6df5fef2009-12-19 10:49:29 +0000282 // The current scope is still active if we're the top-level class.
283 // Otherwise we'll need to push and enter a new scope.
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000284 bool HasClassScope = !Class.TopLevelClass;
Alexis Hunt1deb9722010-04-14 23:07:37 +0000285 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope,
286 HasClassScope);
John McCall6df5fef2009-12-19 10:49:29 +0000287 if (HasClassScope)
Douglas Gregor0be31a22010-07-02 17:43:08 +0000288 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(), Class.TagOrTemplate);
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000289
Douglas Gregorefc46952010-10-12 16:25:54 +0000290 for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
291 Class.LateParsedDeclarations[i]->ParseLexedMethodDeclarations();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000292 }
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000293
John McCall6df5fef2009-12-19 10:49:29 +0000294 if (HasClassScope)
Douglas Gregor0be31a22010-07-02 17:43:08 +0000295 Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(), Class.TagOrTemplate);
Douglas Gregor4d87df52008-12-16 21:30:33 +0000296}
297
Douglas Gregorefc46952010-10-12 16:25:54 +0000298void Parser::ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM) {
299 // If this is a member template, introduce the template parameter scope.
300 ParseScope TemplateScope(this, Scope::TemplateParamScope, LM.TemplateScope);
Richard Smithc8378952013-04-29 11:55:38 +0000301 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
302 if (LM.TemplateScope) {
Douglas Gregorefc46952010-10-12 16:25:54 +0000303 Actions.ActOnReenterTemplateScope(getCurScope(), LM.Method);
Richard Smithc8378952013-04-29 11:55:38 +0000304 ++CurTemplateDepthTracker;
305 }
Douglas Gregorefc46952010-10-12 16:25:54 +0000306 // Start the delayed C++ method declaration
307 Actions.ActOnStartDelayedCXXMethodDeclaration(getCurScope(), LM.Method);
308
309 // Introduce the parameters into scope and parse their default
310 // arguments.
Richard Smithe233fbf2013-01-28 22:42:45 +0000311 ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
312 Scope::FunctionDeclarationScope | Scope::DeclScope);
Douglas Gregorefc46952010-10-12 16:25:54 +0000313 for (unsigned I = 0, N = LM.DefaultArgs.size(); I != N; ++I) {
314 // Introduce the parameter into scope.
Douglas Gregor7fcbd902012-02-21 00:37:24 +0000315 Actions.ActOnDelayedCXXMethodParameter(getCurScope(),
316 LM.DefaultArgs[I].Param);
Douglas Gregorefc46952010-10-12 16:25:54 +0000317
318 if (CachedTokens *Toks = LM.DefaultArgs[I].Toks) {
319 // Save the current token position.
320 SourceLocation origLoc = Tok.getLocation();
321
322 // Parse the default argument from its saved token stream.
323 Toks->push_back(Tok); // So that the current token doesn't get lost
324 PP.EnterTokenStream(&Toks->front(), Toks->size(), true, false);
325
326 // Consume the previously-pushed token.
327 ConsumeAnyToken();
328
329 // Consume the '='.
330 assert(Tok.is(tok::equal) && "Default argument not starting with '='");
331 SourceLocation EqualLoc = ConsumeToken();
332
333 // The argument isn't actually potentially evaluated unless it is
334 // used.
335 EnterExpressionEvaluationContext Eval(Actions,
Douglas Gregor7fcbd902012-02-21 00:37:24 +0000336 Sema::PotentiallyEvaluatedIfUsed,
337 LM.DefaultArgs[I].Param);
Douglas Gregorefc46952010-10-12 16:25:54 +0000338
Sebastian Redldb63af22012-03-14 15:54:00 +0000339 ExprResult DefArgResult;
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000340 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
Sebastian Redl6db0b1b2012-03-20 21:24:03 +0000341 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
Sebastian Redldb63af22012-03-14 15:54:00 +0000342 DefArgResult = ParseBraceInitializer();
Sebastian Redl6db0b1b2012-03-20 21:24:03 +0000343 } else
Sebastian Redldb63af22012-03-14 15:54:00 +0000344 DefArgResult = ParseAssignmentExpression();
Douglas Gregorefc46952010-10-12 16:25:54 +0000345 if (DefArgResult.isInvalid())
346 Actions.ActOnParamDefaultArgumentError(LM.DefaultArgs[I].Param);
347 else {
348 if (Tok.is(tok::cxx_defaultarg_end))
349 ConsumeToken();
Richard Smith1fff95c2013-09-12 23:28:08 +0000350 else {
351 // The last two tokens are the terminator and the saved value of
352 // Tok; the last token in the default argument is the one before
353 // those.
354 assert(Toks->size() >= 3 && "expected a token in default arg");
355 Diag(Tok.getLocation(), diag::err_default_arg_unparsed)
356 << SourceRange(Tok.getLocation(),
357 (*Toks)[Toks->size() - 3].getLocation());
358 }
Douglas Gregorefc46952010-10-12 16:25:54 +0000359 Actions.ActOnParamDefaultArgument(LM.DefaultArgs[I].Param, EqualLoc,
360 DefArgResult.take());
361 }
362
363 assert(!PP.getSourceManager().isBeforeInTranslationUnit(origLoc,
364 Tok.getLocation()) &&
365 "ParseAssignmentExpression went over the default arg tokens!");
366 // There could be leftover tokens (e.g. because of an error).
367 // Skip through until we reach the original token position.
368 while (Tok.getLocation() != origLoc && Tok.isNot(tok::eof))
369 ConsumeAnyToken();
370
371 delete Toks;
372 LM.DefaultArgs[I].Toks = 0;
373 }
374 }
Douglas Gregor433e0532012-04-16 18:27:27 +0000375
Douglas Gregorefc46952010-10-12 16:25:54 +0000376 PrototypeScope.Exit();
377
378 // Finish the delayed C++ method declaration.
379 Actions.ActOnFinishDelayedCXXMethodDeclaration(getCurScope(), LM.Method);
380}
381
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000382/// ParseLexedMethodDefs - We finished parsing the member specification of a top
383/// (non-nested) C++ class. Now go over the stack of lexed methods that were
384/// collected during its parsing and parse them all.
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000385void Parser::ParseLexedMethodDefs(ParsingClass &Class) {
386 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
Douglas Gregorefc46952010-10-12 16:25:54 +0000387 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope, HasTemplateScope);
Richard Smithc8378952013-04-29 11:55:38 +0000388 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
389 if (HasTemplateScope) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000390 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
Richard Smithc8378952013-04-29 11:55:38 +0000391 ++CurTemplateDepthTracker;
392 }
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000393 bool HasClassScope = !Class.TopLevelClass;
394 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope,
395 HasClassScope);
396
Douglas Gregorefc46952010-10-12 16:25:54 +0000397 for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
398 Class.LateParsedDeclarations[i]->ParseLexedMethodDefs();
399 }
400}
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000401
Douglas Gregorefc46952010-10-12 16:25:54 +0000402void Parser::ParseLexedMethodDef(LexedMethod &LM) {
403 // If this is a member template, introduce the template parameter scope.
404 ParseScope TemplateScope(this, Scope::TemplateParamScope, LM.TemplateScope);
Richard Smithc8378952013-04-29 11:55:38 +0000405 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
406 if (LM.TemplateScope) {
Douglas Gregorefc46952010-10-12 16:25:54 +0000407 Actions.ActOnReenterTemplateScope(getCurScope(), LM.D);
Richard Smithc8378952013-04-29 11:55:38 +0000408 ++CurTemplateDepthTracker;
409 }
Douglas Gregorefc46952010-10-12 16:25:54 +0000410 // Save the current token position.
411 SourceLocation origLoc = Tok.getLocation();
Argyrios Kyrtzidis02041972010-03-31 00:38:09 +0000412
Douglas Gregorefc46952010-10-12 16:25:54 +0000413 assert(!LM.Toks.empty() && "Empty body!");
414 // Append the current token at the end of the new token stream so that it
415 // doesn't get lost.
416 LM.Toks.push_back(Tok);
417 PP.EnterTokenStream(LM.Toks.data(), LM.Toks.size(), true, false);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000418
Douglas Gregorefc46952010-10-12 16:25:54 +0000419 // Consume the previously pushed token.
Argyrios Kyrtzidisc36633c2013-03-27 23:58:17 +0000420 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
Douglas Gregorefc46952010-10-12 16:25:54 +0000421 assert((Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try))
422 && "Inline method not starting with '{', ':' or 'try'");
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000423
Douglas Gregorefc46952010-10-12 16:25:54 +0000424 // Parse the method body. Function body parsing code is similar enough
425 // to be re-used for method bodies as well.
426 ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope);
427 Actions.ActOnStartOfFunctionDef(getCurScope(), LM.D);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000428
Douglas Gregorefc46952010-10-12 16:25:54 +0000429 if (Tok.is(tok::kw_try)) {
Douglas Gregora0ff0c32011-03-16 17:05:57 +0000430 ParseFunctionTryBlock(LM.D, FnScope);
Douglas Gregorefc46952010-10-12 16:25:54 +0000431 assert(!PP.getSourceManager().isBeforeInTranslationUnit(origLoc,
432 Tok.getLocation()) &&
433 "ParseFunctionTryBlock went over the cached tokens!");
434 // There could be leftover tokens (e.g. because of an error).
435 // Skip through until we reach the original token position.
436 while (Tok.getLocation() != origLoc && Tok.isNot(tok::eof))
437 ConsumeAnyToken();
438 return;
439 }
440 if (Tok.is(tok::colon)) {
441 ParseConstructorInitializer(LM.D);
442
443 // Error recovery.
444 if (!Tok.is(tok::l_brace)) {
Douglas Gregora0ff0c32011-03-16 17:05:57 +0000445 FnScope.Exit();
Douglas Gregorefc46952010-10-12 16:25:54 +0000446 Actions.ActOnFinishFunctionBody(LM.D, 0);
Matt Beaumont-Gayd0457922011-09-23 22:39:23 +0000447 while (Tok.getLocation() != origLoc && Tok.isNot(tok::eof))
448 ConsumeAnyToken();
Douglas Gregorefc46952010-10-12 16:25:54 +0000449 return;
450 }
451 } else
452 Actions.ActOnDefaultCtorInitializers(LM.D);
453
Richard Smithc8378952013-04-29 11:55:38 +0000454 assert((Actions.getDiagnostics().hasErrorOccurred() ||
455 !isa<FunctionTemplateDecl>(LM.D) ||
456 cast<FunctionTemplateDecl>(LM.D)->getTemplateParameters()->getDepth()
457 < TemplateParameterDepth) &&
458 "TemplateParameterDepth should be greater than the depth of "
459 "current template being instantiated!");
460
Douglas Gregora0ff0c32011-03-16 17:05:57 +0000461 ParseFunctionStatementBody(LM.D, FnScope);
Douglas Gregorefc46952010-10-12 16:25:54 +0000462
John McCalle68672f2013-03-14 05:13:41 +0000463 // Clear the late-template-parsed bit if we set it before.
464 if (LM.D) getFunctionDecl(LM.D)->setLateTemplateParsed(false);
465
Douglas Gregorefc46952010-10-12 16:25:54 +0000466 if (Tok.getLocation() != origLoc) {
467 // Due to parsing error, we either went over the cached tokens or
468 // there are still cached tokens left. If it's the latter case skip the
469 // leftover tokens.
470 // Since this is an uncommon situation that should be avoided, use the
471 // expensive isBeforeInTranslationUnit call.
472 if (PP.getSourceManager().isBeforeInTranslationUnit(Tok.getLocation(),
473 origLoc))
Argyrios Kyrtzidise1224c82010-06-19 19:58:34 +0000474 while (Tok.getLocation() != origLoc && Tok.isNot(tok::eof))
Argyrios Kyrtzidise9b76af2010-06-17 10:52:22 +0000475 ConsumeAnyToken();
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000476 }
477}
478
Richard Smith938f40b2011-06-11 17:19:42 +0000479/// ParseLexedMemberInitializers - We finished parsing the member specification
480/// of a top (non-nested) C++ class. Now go over the stack of lexed data member
481/// initializers that were collected during its parsing and parse them all.
482void Parser::ParseLexedMemberInitializers(ParsingClass &Class) {
483 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
484 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
485 HasTemplateScope);
Richard Smithc8378952013-04-29 11:55:38 +0000486 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
487 if (HasTemplateScope) {
Richard Smith938f40b2011-06-11 17:19:42 +0000488 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
Richard Smithc8378952013-04-29 11:55:38 +0000489 ++CurTemplateDepthTracker;
490 }
Douglas Gregor3024f072012-04-16 07:05:22 +0000491 // Set or update the scope flags.
Richard Smith938f40b2011-06-11 17:19:42 +0000492 bool AlreadyHasClassScope = Class.TopLevelClass;
Douglas Gregor3024f072012-04-16 07:05:22 +0000493 unsigned ScopeFlags = Scope::ClassScope|Scope::DeclScope;
Richard Smith938f40b2011-06-11 17:19:42 +0000494 ParseScope ClassScope(this, ScopeFlags, !AlreadyHasClassScope);
495 ParseScopeFlags ClassScopeFlags(this, ScopeFlags, AlreadyHasClassScope);
496
497 if (!AlreadyHasClassScope)
498 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(),
499 Class.TagOrTemplate);
500
Benjamin Kramer1d373c62012-05-17 12:01:52 +0000501 if (!Class.LateParsedDeclarations.empty()) {
Douglas Gregor3024f072012-04-16 07:05:22 +0000502 // C++11 [expr.prim.general]p4:
503 // Otherwise, if a member-declarator declares a non-static data member
504 // (9.2) of a class X, the expression this is a prvalue of type "pointer
505 // to X" within the optional brace-or-equal-initializer. It shall not
506 // appear elsewhere in the member-declarator.
507 Sema::CXXThisScopeRAII ThisScope(Actions, Class.TagOrTemplate,
508 /*TypeQuals=*/(unsigned)0);
Richard Smith938f40b2011-06-11 17:19:42 +0000509
Douglas Gregor3024f072012-04-16 07:05:22 +0000510 for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
511 Class.LateParsedDeclarations[i]->ParseLexedMemberInitializers();
512 }
513 }
514
Richard Smith938f40b2011-06-11 17:19:42 +0000515 if (!AlreadyHasClassScope)
516 Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(),
517 Class.TagOrTemplate);
518
519 Actions.ActOnFinishDelayedMemberInitializers(Class.TagOrTemplate);
520}
521
522void Parser::ParseLexedMemberInitializer(LateParsedMemberInitializer &MI) {
Richard Smith1a526fd2011-09-29 19:42:27 +0000523 if (!MI.Field || MI.Field->isInvalidDecl())
Richard Smith938f40b2011-06-11 17:19:42 +0000524 return;
525
526 // Append the current token at the end of the new token stream so that it
527 // doesn't get lost.
528 MI.Toks.push_back(Tok);
529 PP.EnterTokenStream(MI.Toks.data(), MI.Toks.size(), true, false);
530
531 // Consume the previously pushed token.
Argyrios Kyrtzidisc36633c2013-03-27 23:58:17 +0000532 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
Richard Smith938f40b2011-06-11 17:19:42 +0000533
534 SourceLocation EqualLoc;
Richard Smith2b013182012-06-10 03:12:00 +0000535
Douglas Gregor926410d2012-02-21 02:22:07 +0000536 ExprResult Init = ParseCXXMemberInitializer(MI.Field, /*IsFunction=*/false,
537 EqualLoc);
Richard Smith938f40b2011-06-11 17:19:42 +0000538
539 Actions.ActOnCXXInClassMemberInitializer(MI.Field, EqualLoc, Init.release());
540
541 // The next token should be our artificial terminating EOF token.
542 if (Tok.isNot(tok::eof)) {
543 SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
544 if (!EndLoc.isValid())
545 EndLoc = Tok.getLocation();
546 // No fixit; we can't recover as if there were a semicolon here.
547 Diag(EndLoc, diag::err_expected_semi_decl_list);
548
549 // Consume tokens until we hit the artificial EOF.
550 while (Tok.isNot(tok::eof))
551 ConsumeAnyToken();
552 }
553 ConsumeAnyToken();
554}
555
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000556/// ConsumeAndStoreUntil - Consume and store the token at the passed token
Douglas Gregor4d87df52008-12-16 21:30:33 +0000557/// container until the token 'T' is reached (which gets
Mike Stump11289f42009-09-09 15:08:12 +0000558/// consumed/stored too, if ConsumeFinalToken).
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000559/// If StopAtSemi is true, then we will stop early at a ';' character.
Douglas Gregor4d87df52008-12-16 21:30:33 +0000560/// Returns true if token 'T1' or 'T2' was found.
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000561/// NOTE: This is a specialized version of Parser::SkipUntil.
Douglas Gregor4d87df52008-12-16 21:30:33 +0000562bool Parser::ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
563 CachedTokens &Toks,
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000564 bool StopAtSemi, bool ConsumeFinalToken) {
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000565 // We always want this function to consume at least one token if the first
566 // token isn't T and if not at EOF.
567 bool isFirstTokenConsumed = true;
568 while (1) {
569 // If we found one of the tokens, stop and return true.
Douglas Gregor4d87df52008-12-16 21:30:33 +0000570 if (Tok.is(T1) || Tok.is(T2)) {
571 if (ConsumeFinalToken) {
572 Toks.push_back(Tok);
573 ConsumeAnyToken();
574 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000575 return true;
576 }
577
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000578 switch (Tok.getKind()) {
579 case tok::eof:
580 // Ran out of tokens.
581 return false;
582
583 case tok::l_paren:
584 // Recursively consume properly-nested parens.
585 Toks.push_back(Tok);
586 ConsumeParen();
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000587 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000588 break;
589 case tok::l_square:
590 // Recursively consume properly-nested square brackets.
591 Toks.push_back(Tok);
592 ConsumeBracket();
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000593 ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000594 break;
595 case tok::l_brace:
596 // Recursively consume properly-nested braces.
597 Toks.push_back(Tok);
598 ConsumeBrace();
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000599 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000600 break;
601
602 // Okay, we found a ']' or '}' or ')', which we think should be balanced.
603 // Since the user wasn't looking for this token (if they were, it would
604 // already be handled), this isn't balanced. If there is a LHS token at a
605 // higher level, we will assume that this matches the unbalanced token
606 // and return it. Otherwise, this is a spurious RHS token, which we skip.
607 case tok::r_paren:
608 if (ParenCount && !isFirstTokenConsumed)
609 return false; // Matches something.
610 Toks.push_back(Tok);
611 ConsumeParen();
612 break;
613 case tok::r_square:
614 if (BracketCount && !isFirstTokenConsumed)
615 return false; // Matches something.
616 Toks.push_back(Tok);
617 ConsumeBracket();
618 break;
619 case tok::r_brace:
620 if (BraceCount && !isFirstTokenConsumed)
621 return false; // Matches something.
622 Toks.push_back(Tok);
623 ConsumeBrace();
624 break;
625
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000626 case tok::code_completion:
627 Toks.push_back(Tok);
628 ConsumeCodeCompletionToken();
629 break;
630
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000631 case tok::string_literal:
632 case tok::wide_string_literal:
Douglas Gregorfb65e592011-07-27 05:40:30 +0000633 case tok::utf8_string_literal:
634 case tok::utf16_string_literal:
635 case tok::utf32_string_literal:
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000636 Toks.push_back(Tok);
637 ConsumeStringToken();
638 break;
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000639 case tok::semi:
640 if (StopAtSemi)
641 return false;
642 // FALL THROUGH.
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000643 default:
644 // consume this token.
645 Toks.push_back(Tok);
646 ConsumeToken();
647 break;
648 }
649 isFirstTokenConsumed = false;
650 }
651}
Sebastian Redla74948d2011-09-24 17:48:25 +0000652
653/// \brief Consume tokens and store them in the passed token container until
654/// we've passed the try keyword and constructor initializers and have consumed
Sebastian Redl0d164012011-09-30 08:32:17 +0000655/// the opening brace of the function body. The opening brace will be consumed
656/// if and only if there was no error.
Sebastian Redla74948d2011-09-24 17:48:25 +0000657///
Richard Smithcde3fd82013-07-04 00:13:48 +0000658/// \return True on error.
Sebastian Redl0d164012011-09-30 08:32:17 +0000659bool Parser::ConsumeAndStoreFunctionPrologue(CachedTokens &Toks) {
Sebastian Redla74948d2011-09-24 17:48:25 +0000660 if (Tok.is(tok::kw_try)) {
661 Toks.push_back(Tok);
662 ConsumeToken();
663 }
Richard Smithcde3fd82013-07-04 00:13:48 +0000664
665 if (Tok.isNot(tok::colon)) {
666 // Easy case, just a function body.
667
668 // Grab any remaining garbage to be diagnosed later. We stop when we reach a
669 // brace: an opening one is the function body, while a closing one probably
670 // means we've reached the end of the class.
671 ConsumeAndStoreUntil(tok::l_brace, tok::r_brace, Toks,
672 /*StopAtSemi=*/true,
673 /*ConsumeFinalToken=*/false);
674 if (Tok.isNot(tok::l_brace))
675 return Diag(Tok.getLocation(), diag::err_expected_lbrace);
676
Sebastian Redla74948d2011-09-24 17:48:25 +0000677 Toks.push_back(Tok);
Richard Smithcde3fd82013-07-04 00:13:48 +0000678 ConsumeBrace();
679 return false;
Eli Friedman7cd4a9b2012-02-22 04:49:04 +0000680 }
Sebastian Redl0d164012011-09-30 08:32:17 +0000681
682 Toks.push_back(Tok);
Richard Smithcde3fd82013-07-04 00:13:48 +0000683 ConsumeToken();
684
685 // We can't reliably skip over a mem-initializer-id, because it could be
686 // a template-id involving not-yet-declared names. Given:
687 //
688 // S ( ) : a < b < c > ( e )
689 //
690 // 'e' might be an initializer or part of a template argument, depending
691 // on whether 'b' is a template.
692
693 // Track whether we might be inside a template argument. We can give
694 // significantly better diagnostics if we know that we're not.
695 bool MightBeTemplateArgument = false;
696
697 while (true) {
698 // Skip over the mem-initializer-id, if possible.
699 if (Tok.is(tok::kw_decltype)) {
700 Toks.push_back(Tok);
701 SourceLocation OpenLoc = ConsumeToken();
702 if (Tok.isNot(tok::l_paren))
703 return Diag(Tok.getLocation(), diag::err_expected_lparen_after)
704 << "decltype";
705 Toks.push_back(Tok);
706 ConsumeParen();
707 if (!ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/true)) {
708 Diag(Tok.getLocation(), diag::err_expected_rparen);
709 Diag(OpenLoc, diag::note_matching) << "(";
710 return true;
711 }
712 }
713 do {
714 // Walk over a component of a nested-name-specifier.
715 if (Tok.is(tok::coloncolon)) {
716 Toks.push_back(Tok);
717 ConsumeToken();
718
719 if (Tok.is(tok::kw_template)) {
720 Toks.push_back(Tok);
721 ConsumeToken();
722 }
723 }
724
725 if (Tok.is(tok::identifier) || Tok.is(tok::kw_template)) {
726 Toks.push_back(Tok);
727 ConsumeToken();
728 } else if (Tok.is(tok::code_completion)) {
729 Toks.push_back(Tok);
730 ConsumeCodeCompletionToken();
731 // Consume the rest of the initializers permissively.
732 // FIXME: We should be able to perform code-completion here even if
733 // there isn't a subsequent '{' token.
734 MightBeTemplateArgument = true;
735 break;
736 } else {
737 break;
738 }
739 } while (Tok.is(tok::coloncolon));
740
741 if (Tok.is(tok::less))
742 MightBeTemplateArgument = true;
743
744 if (MightBeTemplateArgument) {
745 // We may be inside a template argument list. Grab up to the start of the
746 // next parenthesized initializer or braced-init-list. This *might* be the
747 // initializer, or it might be a subexpression in the template argument
748 // list.
749 // FIXME: Count angle brackets, and clear MightBeTemplateArgument
750 // if all angles are closed.
751 if (!ConsumeAndStoreUntil(tok::l_paren, tok::l_brace, Toks,
752 /*StopAtSemi=*/true,
753 /*ConsumeFinalToken=*/false)) {
754 // We're not just missing the initializer, we're also missing the
755 // function body!
756 return Diag(Tok.getLocation(), diag::err_expected_lbrace);
757 }
758 } else if (Tok.isNot(tok::l_paren) && Tok.isNot(tok::l_brace)) {
759 // We found something weird in a mem-initializer-id.
760 return Diag(Tok.getLocation(), getLangOpts().CPlusPlus11
761 ? diag::err_expected_lparen_or_lbrace
762 : diag::err_expected_lparen);
763 }
764
765 tok::TokenKind kind = Tok.getKind();
766 Toks.push_back(Tok);
767 bool IsLParen = (kind == tok::l_paren);
768 SourceLocation OpenLoc = Tok.getLocation();
769
770 if (IsLParen) {
771 ConsumeParen();
772 } else {
773 assert(kind == tok::l_brace && "Must be left paren or brace here.");
774 ConsumeBrace();
775 // In C++03, this has to be the start of the function body, which
776 // means the initializer is malformed; we'll diagnose it later.
777 if (!getLangOpts().CPlusPlus11)
778 return false;
779 }
780
781 // Grab the initializer (or the subexpression of the template argument).
782 // FIXME: If we support lambdas here, we'll need to set StopAtSemi to false
783 // if we might be inside the braces of a lambda-expression.
784 if (!ConsumeAndStoreUntil(IsLParen ? tok::r_paren : tok::r_brace,
785 Toks, /*StopAtSemi=*/true)) {
786 Diag(Tok, IsLParen ? diag::err_expected_rparen :
787 diag::err_expected_rbrace);
788 Diag(OpenLoc, diag::note_matching) << (IsLParen ? "(" : "{");
789 return true;
790 }
791
792 // Grab pack ellipsis, if present.
793 if (Tok.is(tok::ellipsis)) {
794 Toks.push_back(Tok);
795 ConsumeToken();
796 }
797
798 // If we know we just consumed a mem-initializer, we must have ',' or '{'
799 // next.
800 if (Tok.is(tok::comma)) {
801 Toks.push_back(Tok);
802 ConsumeToken();
803 } else if (Tok.is(tok::l_brace)) {
804 // This is the function body if the ')' or '}' is immediately followed by
805 // a '{'. That cannot happen within a template argument, apart from the
806 // case where a template argument contains a compound literal:
807 //
808 // S ( ) : a < b < c > ( d ) { }
809 // // End of declaration, or still inside the template argument?
810 //
811 // ... and the case where the template argument contains a lambda:
812 //
813 // S ( ) : a < 0 && b < c > ( d ) + [ ] ( ) { return 0; }
814 // ( ) > ( ) { }
815 //
816 // FIXME: Disambiguate these cases. Note that the latter case is probably
817 // going to be made ill-formed by core issue 1607.
818 Toks.push_back(Tok);
819 ConsumeBrace();
820 return false;
821 } else if (!MightBeTemplateArgument) {
822 return Diag(Tok.getLocation(), diag::err_expected_lbrace_or_comma);
823 }
824 }
Sebastian Redla74948d2011-09-24 17:48:25 +0000825}
Richard Smith1fff95c2013-09-12 23:28:08 +0000826
827/// \brief Consume and store tokens from the '?' to the ':' in a conditional
828/// expression.
829bool Parser::ConsumeAndStoreConditional(CachedTokens &Toks) {
830 // Consume '?'.
831 assert(Tok.is(tok::question));
832 Toks.push_back(Tok);
833 ConsumeToken();
834
835 while (Tok.isNot(tok::colon)) {
836 if (!ConsumeAndStoreUntil(tok::question, tok::colon, Toks, /*StopAtSemi*/true,
837 /*ConsumeFinalToken*/false))
838 return false;
839
840 // If we found a nested conditional, consume it.
841 if (Tok.is(tok::question) && !ConsumeAndStoreConditional(Toks))
842 return false;
843 }
844
845 // Consume ':'.
846 Toks.push_back(Tok);
847 ConsumeToken();
848 return true;
849}
850
851/// \brief A tentative parsing action that can also revert token annotations.
852class Parser::UnannotatedTentativeParsingAction : public TentativeParsingAction {
853public:
854 explicit UnannotatedTentativeParsingAction(Parser &Self,
855 tok::TokenKind EndKind)
856 : TentativeParsingAction(Self), Self(Self), EndKind(EndKind) {
857 // Stash away the old token stream, so we can restore it once the
858 // tentative parse is complete.
859 TentativeParsingAction Inner(Self);
860 Self.ConsumeAndStoreUntil(EndKind, Toks, true, /*ConsumeFinalToken*/false);
861 Inner.Revert();
862 }
863
864 void RevertAnnotations() {
865 Revert();
866
867 // Put back the original tokens.
868 Self.SkipUntil(EndKind, true, /*DontConsume*/true);
869 if (Toks.size()) {
870 Token *Buffer = new Token[Toks.size()];
871 std::copy(Toks.begin() + 1, Toks.end(), Buffer);
872 Buffer[Toks.size() - 1] = Self.Tok;
873 Self.PP.EnterTokenStream(Buffer, Toks.size(), true, /*Owned*/true);
874
875 Self.Tok = Toks.front();
876 }
877 }
878
879private:
880 Parser &Self;
881 CachedTokens Toks;
882 tok::TokenKind EndKind;
883};
884
885/// ConsumeAndStoreInitializer - Consume and store the token at the passed token
886/// container until the end of the current initializer expression (either a
887/// default argument or an in-class initializer for a non-static data member).
888/// The final token is not consumed.
889bool Parser::ConsumeAndStoreInitializer(CachedTokens &Toks,
890 CachedInitKind CIK) {
891 // We always want this function to consume at least one token if not at EOF.
892 bool IsFirstTokenConsumed = true;
893
894 // Number of possible unclosed <s we've seen so far. These might be templates,
895 // and might not, but if there were none of them (or we know for sure that
896 // we're within a template), we can avoid a tentative parse.
897 unsigned AngleCount = 0;
898 unsigned KnownTemplateCount = 0;
899
900 while (1) {
901 switch (Tok.getKind()) {
902 case tok::comma:
903 // If we might be in a template, perform a tentative parse to check.
904 if (!AngleCount)
905 // Not a template argument: this is the end of the initializer.
906 return true;
907 if (KnownTemplateCount)
908 goto consume_token;
909
910 // We hit a comma inside angle brackets. This is the hard case. The
911 // rule we follow is:
912 // * For a default argument, if the tokens after the comma form a
913 // syntactically-valid parameter-declaration-clause, in which each
914 // parameter has an initializer, then this comma ends the default
915 // argument.
916 // * For a default initializer, if the tokens after the comma form a
917 // syntactically-valid init-declarator-list, then this comma ends
918 // the default initializer.
919 {
920 UnannotatedTentativeParsingAction PA(*this,
921 CIK == CIK_DefaultInitializer
922 ? tok::semi : tok::r_paren);
923 Sema::TentativeAnalysisScope Scope(Actions);
924
925 TPResult Result = TPResult::Error();
926 ConsumeToken();
927 switch (CIK) {
928 case CIK_DefaultInitializer:
929 Result = TryParseInitDeclaratorList();
930 // If we parsed a complete, ambiguous init-declarator-list, this
931 // is only syntactically-valid if it's followed by a semicolon.
932 if (Result == TPResult::Ambiguous() && Tok.isNot(tok::semi))
933 Result = TPResult::False();
934 break;
935
936 case CIK_DefaultArgument:
937 bool InvalidAsDeclaration = false;
938 Result = TryParseParameterDeclarationClause(
939 &InvalidAsDeclaration, /*VersusTemplateArgument*/true);
940 // If this is an expression or a declaration with a missing
941 // 'typename', assume it's not a declaration.
942 if (Result == TPResult::Ambiguous() && InvalidAsDeclaration)
943 Result = TPResult::False();
944 break;
945 }
946
947 // If what follows could be a declaration, it is a declaration.
948 if (Result != TPResult::False() && Result != TPResult::Error()) {
949 PA.Revert();
950 return true;
951 }
952
953 // In the uncommon case that we decide the following tokens are part
954 // of a template argument, revert any annotations we've performed in
955 // those tokens. We're not going to look them up until we've parsed
956 // the rest of the class, and that might add more declarations.
957 PA.RevertAnnotations();
958 }
959
960 // Keep going. We know we're inside a template argument list now.
961 ++KnownTemplateCount;
962 goto consume_token;
963
964 case tok::eof:
965 // Ran out of tokens.
966 return false;
967
968 case tok::less:
969 // FIXME: A '<' can only start a template-id if it's preceded by an
970 // identifier, an operator-function-id, or a literal-operator-id.
971 ++AngleCount;
972 goto consume_token;
973
974 case tok::question:
975 // In 'a ? b : c', 'b' can contain an unparenthesized comma. If it does,
976 // that is *never* the end of the initializer. Skip to the ':'.
977 if (!ConsumeAndStoreConditional(Toks))
978 return false;
979 break;
980
981 case tok::greatergreatergreater:
982 if (!getLangOpts().CPlusPlus11)
983 goto consume_token;
984 if (AngleCount) --AngleCount;
985 if (KnownTemplateCount) --KnownTemplateCount;
986 // Fall through.
987 case tok::greatergreater:
988 if (!getLangOpts().CPlusPlus11)
989 goto consume_token;
990 if (AngleCount) --AngleCount;
991 if (KnownTemplateCount) --KnownTemplateCount;
992 // Fall through.
993 case tok::greater:
994 if (AngleCount) --AngleCount;
995 if (KnownTemplateCount) --KnownTemplateCount;
996 goto consume_token;
997
998 case tok::kw_template:
999 // 'template' identifier '<' is known to start a template argument list,
1000 // and can be used to disambiguate the parse.
1001 // FIXME: Support all forms of 'template' unqualified-id '<'.
1002 Toks.push_back(Tok);
1003 ConsumeToken();
1004 if (Tok.is(tok::identifier)) {
1005 Toks.push_back(Tok);
1006 ConsumeToken();
1007 if (Tok.is(tok::less)) {
1008 ++KnownTemplateCount;
1009 Toks.push_back(Tok);
1010 ConsumeToken();
1011 }
1012 }
1013 break;
1014
1015 case tok::kw_operator:
1016 // If 'operator' precedes other punctuation, that punctuation loses
1017 // its special behavior.
1018 Toks.push_back(Tok);
1019 ConsumeToken();
1020 switch (Tok.getKind()) {
1021 case tok::comma:
1022 case tok::greatergreatergreater:
1023 case tok::greatergreater:
1024 case tok::greater:
1025 case tok::less:
1026 Toks.push_back(Tok);
1027 ConsumeToken();
1028 break;
1029 default:
1030 break;
1031 }
1032 break;
1033
1034 case tok::l_paren:
1035 // Recursively consume properly-nested parens.
1036 Toks.push_back(Tok);
1037 ConsumeParen();
1038 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
1039 break;
1040 case tok::l_square:
1041 // Recursively consume properly-nested square brackets.
1042 Toks.push_back(Tok);
1043 ConsumeBracket();
1044 ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false);
1045 break;
1046 case tok::l_brace:
1047 // Recursively consume properly-nested braces.
1048 Toks.push_back(Tok);
1049 ConsumeBrace();
1050 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1051 break;
1052
1053 // Okay, we found a ']' or '}' or ')', which we think should be balanced.
1054 // Since the user wasn't looking for this token (if they were, it would
1055 // already be handled), this isn't balanced. If there is a LHS token at a
1056 // higher level, we will assume that this matches the unbalanced token
1057 // and return it. Otherwise, this is a spurious RHS token, which we skip.
1058 case tok::r_paren:
1059 if (CIK == CIK_DefaultArgument)
1060 return true; // End of the default argument.
1061 if (ParenCount && !IsFirstTokenConsumed)
1062 return false; // Matches something.
1063 goto consume_token;
1064 case tok::r_square:
1065 if (BracketCount && !IsFirstTokenConsumed)
1066 return false; // Matches something.
1067 goto consume_token;
1068 case tok::r_brace:
1069 if (BraceCount && !IsFirstTokenConsumed)
1070 return false; // Matches something.
1071 goto consume_token;
1072
1073 case tok::code_completion:
1074 Toks.push_back(Tok);
1075 ConsumeCodeCompletionToken();
1076 break;
1077
1078 case tok::string_literal:
1079 case tok::wide_string_literal:
1080 case tok::utf8_string_literal:
1081 case tok::utf16_string_literal:
1082 case tok::utf32_string_literal:
1083 Toks.push_back(Tok);
1084 ConsumeStringToken();
1085 break;
1086 case tok::semi:
1087 if (CIK == CIK_DefaultInitializer)
1088 return true; // End of the default initializer.
1089 // FALL THROUGH.
1090 default:
1091 consume_token:
1092 Toks.push_back(Tok);
1093 ConsumeToken();
1094 break;
1095 }
1096 IsFirstTokenConsumed = false;
1097 }
1098}