blob: 9a69bec167972284bbc7f930d897305f1fc12013 [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 }
Faisal Valib96570332013-11-01 02:01:01 +0000112
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 &&
Faisal Valib96570332013-11-01 02:01:01 +0000118 !D.getDeclSpec().isConstexprSpecified() &&
119 !(FnD && getFunctionDecl(FnD) &&
120 getFunctionDecl(FnD)->getResultType()->getContainedAutoType()) &&
Francois Pichet1c229c02011-04-22 22:18:13 +0000121 ((Actions.CurContext->isDependentContext() ||
David Majnemer90b17292013-09-14 05:46:42 +0000122 (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
123 TemplateInfo.Kind != ParsedTemplateInfo::ExplicitSpecialization)) &&
124 !Actions.IsInsideALocalClassWithinATemplateFunction())) {
Francois Pichet1c229c02011-04-22 22:18:13 +0000125
Richard Smithe40f2ba2013-08-07 21:41:30 +0000126 CachedTokens Toks;
127 LexTemplateFunctionForLateParsing(Toks);
Francois Pichet1c229c02011-04-22 22:18:13 +0000128
Richard Smithe40f2ba2013-08-07 21:41:30 +0000129 if (FnD) {
John McCalle68672f2013-03-14 05:13:41 +0000130 FunctionDecl *FD = getFunctionDecl(FnD);
Chandler Carruthbc0f9ae2011-04-25 07:09:43 +0000131 Actions.CheckForFunctionRedefinition(FD);
Richard Smithe40f2ba2013-08-07 21:41:30 +0000132 Actions.MarkAsLateParsedTemplate(FD, FnD, Toks);
Francois Pichet1c229c02011-04-22 22:18:13 +0000133 }
134
135 return FnD;
136 }
137
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000138 // Consume the tokens and store them for later parsing.
139
Douglas Gregorefc46952010-10-12 16:25:54 +0000140 LexedMethod* LM = new LexedMethod(this, FnD);
141 getCurrentClass().LateParsedDeclarations.push_back(LM);
142 LM->TemplateScope = getCurScope()->isTemplateParamScope();
143 CachedTokens &Toks = LM->Toks;
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000144
Sebastian Redla7b98a72009-04-26 20:35:05 +0000145 tok::TokenKind kind = Tok.getKind();
Sebastian Redl0d164012011-09-30 08:32:17 +0000146 // Consume everything up to (and including) the left brace of the
147 // function body.
148 if (ConsumeAndStoreFunctionPrologue(Toks)) {
149 // We didn't find the left-brace we expected after the
Eli Friedman7cd4a9b2012-02-22 04:49:04 +0000150 // constructor initializer; we already printed an error, and it's likely
151 // impossible to recover, so don't try to parse this method later.
Richard Smithcde3fd82013-07-04 00:13:48 +0000152 // Skip over the rest of the decl and back to somewhere that looks
153 // reasonable.
154 SkipMalformedDecl();
Eli Friedman7cd4a9b2012-02-22 04:49:04 +0000155 delete getCurrentClass().LateParsedDeclarations.back();
156 getCurrentClass().LateParsedDeclarations.pop_back();
157 return FnD;
Douglas Gregore8381c02008-11-05 04:29:56 +0000158 } else {
Sebastian Redl0d164012011-09-30 08:32:17 +0000159 // Consume everything up to (and including) the matching right brace.
160 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
Douglas Gregore8381c02008-11-05 04:29:56 +0000161 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000162
Sebastian Redla7b98a72009-04-26 20:35:05 +0000163 // If we're in a function-try-block, we need to store all the catch blocks.
164 if (kind == tok::kw_try) {
165 while (Tok.is(tok::kw_catch)) {
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000166 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
167 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
Sebastian Redla7b98a72009-04-26 20:35:05 +0000168 }
169 }
170
Stephen Lin9354fc52013-06-23 07:37:13 +0000171 if (FnD) {
172 // If this is a friend function, mark that it's late-parsed so that
173 // it's still known to be a definition even before we attach the
174 // parsed body. Sema needs to treat friend function definitions
175 // differently during template instantiation, and it's possible for
176 // the containing class to be instantiated before all its member
177 // function definitions are parsed.
178 //
179 // If you remove this, you can remove the code that clears the flag
180 // after parsing the member.
181 if (D.getDeclSpec().isFriendSpecified()) {
Alp Toker19bff322013-10-18 05:54:24 +0000182 FunctionDecl *FD = getFunctionDecl(FnD);
183 Actions.CheckForFunctionRedefinition(FD);
184 FD->setLateTemplateParsed(true);
Stephen Lin9354fc52013-06-23 07:37:13 +0000185 }
186 } else {
Douglas Gregor6ca64102011-04-14 23:19:27 +0000187 // If semantic analysis could not build a function declaration,
188 // just throw away the late-parsed declaration.
189 delete getCurrentClass().LateParsedDeclarations.back();
190 getCurrentClass().LateParsedDeclarations.pop_back();
191 }
192
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000193 return FnD;
194}
195
Richard Smith938f40b2011-06-11 17:19:42 +0000196/// ParseCXXNonStaticMemberInitializer - We parsed and verified that the
197/// specified Declarator is a well formed C++ non-static data member
198/// declaration. Now lex its initializer and store its tokens for parsing
199/// after the class is complete.
200void Parser::ParseCXXNonStaticMemberInitializer(Decl *VarD) {
201 assert((Tok.is(tok::l_brace) || Tok.is(tok::equal)) &&
202 "Current token not a '{' or '='!");
203
204 LateParsedMemberInitializer *MI =
205 new LateParsedMemberInitializer(this, VarD);
206 getCurrentClass().LateParsedDeclarations.push_back(MI);
207 CachedTokens &Toks = MI->Toks;
208
209 tok::TokenKind kind = Tok.getKind();
210 if (kind == tok::equal) {
211 Toks.push_back(Tok);
Douglas Gregor0cf55e92012-03-08 01:00:17 +0000212 ConsumeToken();
Richard Smith938f40b2011-06-11 17:19:42 +0000213 }
214
215 if (kind == tok::l_brace) {
216 // Begin by storing the '{' token.
217 Toks.push_back(Tok);
218 ConsumeBrace();
219
220 // Consume everything up to (and including) the matching right brace.
221 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/true);
222 } else {
223 // Consume everything up to (but excluding) the comma or semicolon.
Richard Smith1fff95c2013-09-12 23:28:08 +0000224 ConsumeAndStoreInitializer(Toks, CIK_DefaultInitializer);
Richard Smith938f40b2011-06-11 17:19:42 +0000225 }
226
227 // Store an artificial EOF token to ensure that we don't run off the end of
228 // the initializer when we come to parse it.
229 Token Eof;
230 Eof.startToken();
231 Eof.setKind(tok::eof);
232 Eof.setLocation(Tok.getLocation());
233 Toks.push_back(Eof);
234}
235
Douglas Gregorefc46952010-10-12 16:25:54 +0000236Parser::LateParsedDeclaration::~LateParsedDeclaration() {}
237void Parser::LateParsedDeclaration::ParseLexedMethodDeclarations() {}
Richard Smith938f40b2011-06-11 17:19:42 +0000238void Parser::LateParsedDeclaration::ParseLexedMemberInitializers() {}
Douglas Gregorefc46952010-10-12 16:25:54 +0000239void Parser::LateParsedDeclaration::ParseLexedMethodDefs() {}
240
241Parser::LateParsedClass::LateParsedClass(Parser *P, ParsingClass *C)
242 : Self(P), Class(C) {}
243
244Parser::LateParsedClass::~LateParsedClass() {
245 Self->DeallocateParsedClasses(Class);
246}
247
248void Parser::LateParsedClass::ParseLexedMethodDeclarations() {
249 Self->ParseLexedMethodDeclarations(*Class);
250}
251
Richard Smith938f40b2011-06-11 17:19:42 +0000252void Parser::LateParsedClass::ParseLexedMemberInitializers() {
253 Self->ParseLexedMemberInitializers(*Class);
254}
255
Douglas Gregorefc46952010-10-12 16:25:54 +0000256void Parser::LateParsedClass::ParseLexedMethodDefs() {
257 Self->ParseLexedMethodDefs(*Class);
258}
259
260void Parser::LateParsedMethodDeclaration::ParseLexedMethodDeclarations() {
261 Self->ParseLexedMethodDeclaration(*this);
262}
263
264void Parser::LexedMethod::ParseLexedMethodDefs() {
265 Self->ParseLexedMethodDef(*this);
266}
267
Richard Smith938f40b2011-06-11 17:19:42 +0000268void Parser::LateParsedMemberInitializer::ParseLexedMemberInitializers() {
269 Self->ParseLexedMemberInitializer(*this);
270}
271
Douglas Gregor4d87df52008-12-16 21:30:33 +0000272/// ParseLexedMethodDeclarations - We finished parsing the member
273/// specification of a top (non-nested) C++ class. Now go over the
274/// stack of method declarations with some parts for which parsing was
275/// delayed (such as default arguments) and parse them.
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000276void Parser::ParseLexedMethodDeclarations(ParsingClass &Class) {
277 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
Douglas Gregorefc46952010-10-12 16:25:54 +0000278 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope, HasTemplateScope);
Richard Smithc8378952013-04-29 11:55:38 +0000279 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
280 if (HasTemplateScope) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000281 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
Richard Smithc8378952013-04-29 11:55:38 +0000282 ++CurTemplateDepthTracker;
283 }
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000284
John McCall6df5fef2009-12-19 10:49:29 +0000285 // The current scope is still active if we're the top-level class.
286 // Otherwise we'll need to push and enter a new scope.
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000287 bool HasClassScope = !Class.TopLevelClass;
Alexis Hunt1deb9722010-04-14 23:07:37 +0000288 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope,
289 HasClassScope);
John McCall6df5fef2009-12-19 10:49:29 +0000290 if (HasClassScope)
Douglas Gregor0be31a22010-07-02 17:43:08 +0000291 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(), Class.TagOrTemplate);
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000292
Douglas Gregorefc46952010-10-12 16:25:54 +0000293 for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
294 Class.LateParsedDeclarations[i]->ParseLexedMethodDeclarations();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000295 }
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000296
John McCall6df5fef2009-12-19 10:49:29 +0000297 if (HasClassScope)
Douglas Gregor0be31a22010-07-02 17:43:08 +0000298 Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(), Class.TagOrTemplate);
Douglas Gregor4d87df52008-12-16 21:30:33 +0000299}
300
Douglas Gregorefc46952010-10-12 16:25:54 +0000301void Parser::ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM) {
302 // If this is a member template, introduce the template parameter scope.
303 ParseScope TemplateScope(this, Scope::TemplateParamScope, LM.TemplateScope);
Richard Smithc8378952013-04-29 11:55:38 +0000304 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
305 if (LM.TemplateScope) {
Douglas Gregorefc46952010-10-12 16:25:54 +0000306 Actions.ActOnReenterTemplateScope(getCurScope(), LM.Method);
Richard Smithc8378952013-04-29 11:55:38 +0000307 ++CurTemplateDepthTracker;
308 }
Douglas Gregorefc46952010-10-12 16:25:54 +0000309 // Start the delayed C++ method declaration
310 Actions.ActOnStartDelayedCXXMethodDeclaration(getCurScope(), LM.Method);
311
312 // Introduce the parameters into scope and parse their default
313 // arguments.
Richard Smithe233fbf2013-01-28 22:42:45 +0000314 ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
315 Scope::FunctionDeclarationScope | Scope::DeclScope);
Douglas Gregorefc46952010-10-12 16:25:54 +0000316 for (unsigned I = 0, N = LM.DefaultArgs.size(); I != N; ++I) {
317 // Introduce the parameter into scope.
Douglas Gregor7fcbd902012-02-21 00:37:24 +0000318 Actions.ActOnDelayedCXXMethodParameter(getCurScope(),
319 LM.DefaultArgs[I].Param);
Douglas Gregorefc46952010-10-12 16:25:54 +0000320
321 if (CachedTokens *Toks = LM.DefaultArgs[I].Toks) {
322 // Save the current token position.
323 SourceLocation origLoc = Tok.getLocation();
324
325 // Parse the default argument from its saved token stream.
326 Toks->push_back(Tok); // So that the current token doesn't get lost
327 PP.EnterTokenStream(&Toks->front(), Toks->size(), true, false);
328
329 // Consume the previously-pushed token.
330 ConsumeAnyToken();
331
332 // Consume the '='.
333 assert(Tok.is(tok::equal) && "Default argument not starting with '='");
334 SourceLocation EqualLoc = ConsumeToken();
335
336 // The argument isn't actually potentially evaluated unless it is
337 // used.
338 EnterExpressionEvaluationContext Eval(Actions,
Douglas Gregor7fcbd902012-02-21 00:37:24 +0000339 Sema::PotentiallyEvaluatedIfUsed,
340 LM.DefaultArgs[I].Param);
Douglas Gregorefc46952010-10-12 16:25:54 +0000341
Sebastian Redldb63af22012-03-14 15:54:00 +0000342 ExprResult DefArgResult;
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000343 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
Sebastian Redl6db0b1b2012-03-20 21:24:03 +0000344 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
Sebastian Redldb63af22012-03-14 15:54:00 +0000345 DefArgResult = ParseBraceInitializer();
Sebastian Redl6db0b1b2012-03-20 21:24:03 +0000346 } else
Sebastian Redldb63af22012-03-14 15:54:00 +0000347 DefArgResult = ParseAssignmentExpression();
Douglas Gregorefc46952010-10-12 16:25:54 +0000348 if (DefArgResult.isInvalid())
349 Actions.ActOnParamDefaultArgumentError(LM.DefaultArgs[I].Param);
350 else {
351 if (Tok.is(tok::cxx_defaultarg_end))
352 ConsumeToken();
Richard Smith1fff95c2013-09-12 23:28:08 +0000353 else {
354 // The last two tokens are the terminator and the saved value of
355 // Tok; the last token in the default argument is the one before
356 // those.
357 assert(Toks->size() >= 3 && "expected a token in default arg");
358 Diag(Tok.getLocation(), diag::err_default_arg_unparsed)
359 << SourceRange(Tok.getLocation(),
360 (*Toks)[Toks->size() - 3].getLocation());
361 }
Douglas Gregorefc46952010-10-12 16:25:54 +0000362 Actions.ActOnParamDefaultArgument(LM.DefaultArgs[I].Param, EqualLoc,
363 DefArgResult.take());
364 }
365
366 assert(!PP.getSourceManager().isBeforeInTranslationUnit(origLoc,
367 Tok.getLocation()) &&
368 "ParseAssignmentExpression went over the default arg tokens!");
369 // There could be leftover tokens (e.g. because of an error).
370 // Skip through until we reach the original token position.
371 while (Tok.getLocation() != origLoc && Tok.isNot(tok::eof))
372 ConsumeAnyToken();
373
374 delete Toks;
375 LM.DefaultArgs[I].Toks = 0;
376 }
377 }
Douglas Gregor433e0532012-04-16 18:27:27 +0000378
Douglas Gregorefc46952010-10-12 16:25:54 +0000379 PrototypeScope.Exit();
380
381 // Finish the delayed C++ method declaration.
382 Actions.ActOnFinishDelayedCXXMethodDeclaration(getCurScope(), LM.Method);
383}
384
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000385/// ParseLexedMethodDefs - We finished parsing the member specification of a top
386/// (non-nested) C++ class. Now go over the stack of lexed methods that were
387/// collected during its parsing and parse them all.
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000388void Parser::ParseLexedMethodDefs(ParsingClass &Class) {
389 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
Douglas Gregorefc46952010-10-12 16:25:54 +0000390 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope, HasTemplateScope);
Richard Smithc8378952013-04-29 11:55:38 +0000391 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
392 if (HasTemplateScope) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000393 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
Richard Smithc8378952013-04-29 11:55:38 +0000394 ++CurTemplateDepthTracker;
395 }
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000396 bool HasClassScope = !Class.TopLevelClass;
397 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope,
398 HasClassScope);
399
Douglas Gregorefc46952010-10-12 16:25:54 +0000400 for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
401 Class.LateParsedDeclarations[i]->ParseLexedMethodDefs();
402 }
403}
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000404
Douglas Gregorefc46952010-10-12 16:25:54 +0000405void Parser::ParseLexedMethodDef(LexedMethod &LM) {
406 // If this is a member template, introduce the template parameter scope.
407 ParseScope TemplateScope(this, Scope::TemplateParamScope, LM.TemplateScope);
Richard Smithc8378952013-04-29 11:55:38 +0000408 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
409 if (LM.TemplateScope) {
Douglas Gregorefc46952010-10-12 16:25:54 +0000410 Actions.ActOnReenterTemplateScope(getCurScope(), LM.D);
Richard Smithc8378952013-04-29 11:55:38 +0000411 ++CurTemplateDepthTracker;
412 }
Douglas Gregorefc46952010-10-12 16:25:54 +0000413 // Save the current token position.
414 SourceLocation origLoc = Tok.getLocation();
Argyrios Kyrtzidis02041972010-03-31 00:38:09 +0000415
Douglas Gregorefc46952010-10-12 16:25:54 +0000416 assert(!LM.Toks.empty() && "Empty body!");
417 // Append the current token at the end of the new token stream so that it
418 // doesn't get lost.
419 LM.Toks.push_back(Tok);
420 PP.EnterTokenStream(LM.Toks.data(), LM.Toks.size(), true, false);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000421
Douglas Gregorefc46952010-10-12 16:25:54 +0000422 // Consume the previously pushed token.
Argyrios Kyrtzidisc36633c2013-03-27 23:58:17 +0000423 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
Douglas Gregorefc46952010-10-12 16:25:54 +0000424 assert((Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try))
425 && "Inline method not starting with '{', ':' or 'try'");
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000426
Douglas Gregorefc46952010-10-12 16:25:54 +0000427 // Parse the method body. Function body parsing code is similar enough
428 // to be re-used for method bodies as well.
429 ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope);
430 Actions.ActOnStartOfFunctionDef(getCurScope(), LM.D);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000431
Douglas Gregorefc46952010-10-12 16:25:54 +0000432 if (Tok.is(tok::kw_try)) {
Douglas Gregora0ff0c32011-03-16 17:05:57 +0000433 ParseFunctionTryBlock(LM.D, FnScope);
Douglas Gregorefc46952010-10-12 16:25:54 +0000434 assert(!PP.getSourceManager().isBeforeInTranslationUnit(origLoc,
435 Tok.getLocation()) &&
436 "ParseFunctionTryBlock went over the cached tokens!");
437 // There could be leftover tokens (e.g. because of an error).
438 // Skip through until we reach the original token position.
439 while (Tok.getLocation() != origLoc && Tok.isNot(tok::eof))
440 ConsumeAnyToken();
441 return;
442 }
443 if (Tok.is(tok::colon)) {
444 ParseConstructorInitializer(LM.D);
445
446 // Error recovery.
447 if (!Tok.is(tok::l_brace)) {
Douglas Gregora0ff0c32011-03-16 17:05:57 +0000448 FnScope.Exit();
Douglas Gregorefc46952010-10-12 16:25:54 +0000449 Actions.ActOnFinishFunctionBody(LM.D, 0);
Matt Beaumont-Gayd0457922011-09-23 22:39:23 +0000450 while (Tok.getLocation() != origLoc && Tok.isNot(tok::eof))
451 ConsumeAnyToken();
Douglas Gregorefc46952010-10-12 16:25:54 +0000452 return;
453 }
454 } else
455 Actions.ActOnDefaultCtorInitializers(LM.D);
456
Richard Smithc8378952013-04-29 11:55:38 +0000457 assert((Actions.getDiagnostics().hasErrorOccurred() ||
458 !isa<FunctionTemplateDecl>(LM.D) ||
459 cast<FunctionTemplateDecl>(LM.D)->getTemplateParameters()->getDepth()
460 < TemplateParameterDepth) &&
461 "TemplateParameterDepth should be greater than the depth of "
462 "current template being instantiated!");
463
Douglas Gregora0ff0c32011-03-16 17:05:57 +0000464 ParseFunctionStatementBody(LM.D, FnScope);
Douglas Gregorefc46952010-10-12 16:25:54 +0000465
John McCalle68672f2013-03-14 05:13:41 +0000466 // Clear the late-template-parsed bit if we set it before.
467 if (LM.D) getFunctionDecl(LM.D)->setLateTemplateParsed(false);
468
Douglas Gregorefc46952010-10-12 16:25:54 +0000469 if (Tok.getLocation() != origLoc) {
470 // Due to parsing error, we either went over the cached tokens or
471 // there are still cached tokens left. If it's the latter case skip the
472 // leftover tokens.
473 // Since this is an uncommon situation that should be avoided, use the
474 // expensive isBeforeInTranslationUnit call.
475 if (PP.getSourceManager().isBeforeInTranslationUnit(Tok.getLocation(),
476 origLoc))
Argyrios Kyrtzidise1224c82010-06-19 19:58:34 +0000477 while (Tok.getLocation() != origLoc && Tok.isNot(tok::eof))
Argyrios Kyrtzidise9b76af2010-06-17 10:52:22 +0000478 ConsumeAnyToken();
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000479 }
480}
481
Richard Smith938f40b2011-06-11 17:19:42 +0000482/// ParseLexedMemberInitializers - We finished parsing the member specification
483/// of a top (non-nested) C++ class. Now go over the stack of lexed data member
484/// initializers that were collected during its parsing and parse them all.
485void Parser::ParseLexedMemberInitializers(ParsingClass &Class) {
486 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
487 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
488 HasTemplateScope);
Richard Smithc8378952013-04-29 11:55:38 +0000489 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
490 if (HasTemplateScope) {
Richard Smith938f40b2011-06-11 17:19:42 +0000491 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
Richard Smithc8378952013-04-29 11:55:38 +0000492 ++CurTemplateDepthTracker;
493 }
Douglas Gregor3024f072012-04-16 07:05:22 +0000494 // Set or update the scope flags.
Richard Smith938f40b2011-06-11 17:19:42 +0000495 bool AlreadyHasClassScope = Class.TopLevelClass;
Douglas Gregor3024f072012-04-16 07:05:22 +0000496 unsigned ScopeFlags = Scope::ClassScope|Scope::DeclScope;
Richard Smith938f40b2011-06-11 17:19:42 +0000497 ParseScope ClassScope(this, ScopeFlags, !AlreadyHasClassScope);
498 ParseScopeFlags ClassScopeFlags(this, ScopeFlags, AlreadyHasClassScope);
499
500 if (!AlreadyHasClassScope)
501 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(),
502 Class.TagOrTemplate);
503
Benjamin Kramer1d373c62012-05-17 12:01:52 +0000504 if (!Class.LateParsedDeclarations.empty()) {
Douglas Gregor3024f072012-04-16 07:05:22 +0000505 // C++11 [expr.prim.general]p4:
506 // Otherwise, if a member-declarator declares a non-static data member
507 // (9.2) of a class X, the expression this is a prvalue of type "pointer
508 // to X" within the optional brace-or-equal-initializer. It shall not
509 // appear elsewhere in the member-declarator.
510 Sema::CXXThisScopeRAII ThisScope(Actions, Class.TagOrTemplate,
511 /*TypeQuals=*/(unsigned)0);
Richard Smith938f40b2011-06-11 17:19:42 +0000512
Douglas Gregor3024f072012-04-16 07:05:22 +0000513 for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
514 Class.LateParsedDeclarations[i]->ParseLexedMemberInitializers();
515 }
516 }
517
Richard Smith938f40b2011-06-11 17:19:42 +0000518 if (!AlreadyHasClassScope)
519 Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(),
520 Class.TagOrTemplate);
521
522 Actions.ActOnFinishDelayedMemberInitializers(Class.TagOrTemplate);
523}
524
525void Parser::ParseLexedMemberInitializer(LateParsedMemberInitializer &MI) {
Richard Smith1a526fd2011-09-29 19:42:27 +0000526 if (!MI.Field || MI.Field->isInvalidDecl())
Richard Smith938f40b2011-06-11 17:19:42 +0000527 return;
528
529 // Append the current token at the end of the new token stream so that it
530 // doesn't get lost.
531 MI.Toks.push_back(Tok);
532 PP.EnterTokenStream(MI.Toks.data(), MI.Toks.size(), true, false);
533
534 // Consume the previously pushed token.
Argyrios Kyrtzidisc36633c2013-03-27 23:58:17 +0000535 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
Richard Smith938f40b2011-06-11 17:19:42 +0000536
537 SourceLocation EqualLoc;
Richard Smith2b013182012-06-10 03:12:00 +0000538
Douglas Gregor926410d2012-02-21 02:22:07 +0000539 ExprResult Init = ParseCXXMemberInitializer(MI.Field, /*IsFunction=*/false,
540 EqualLoc);
Richard Smith938f40b2011-06-11 17:19:42 +0000541
542 Actions.ActOnCXXInClassMemberInitializer(MI.Field, EqualLoc, Init.release());
543
544 // The next token should be our artificial terminating EOF token.
545 if (Tok.isNot(tok::eof)) {
546 SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
547 if (!EndLoc.isValid())
548 EndLoc = Tok.getLocation();
549 // No fixit; we can't recover as if there were a semicolon here.
550 Diag(EndLoc, diag::err_expected_semi_decl_list);
551
552 // Consume tokens until we hit the artificial EOF.
553 while (Tok.isNot(tok::eof))
554 ConsumeAnyToken();
555 }
556 ConsumeAnyToken();
557}
558
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000559/// ConsumeAndStoreUntil - Consume and store the token at the passed token
Douglas Gregor4d87df52008-12-16 21:30:33 +0000560/// container until the token 'T' is reached (which gets
Mike Stump11289f42009-09-09 15:08:12 +0000561/// consumed/stored too, if ConsumeFinalToken).
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000562/// If StopAtSemi is true, then we will stop early at a ';' character.
Douglas Gregor4d87df52008-12-16 21:30:33 +0000563/// Returns true if token 'T1' or 'T2' was found.
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000564/// NOTE: This is a specialized version of Parser::SkipUntil.
Douglas Gregor4d87df52008-12-16 21:30:33 +0000565bool Parser::ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
566 CachedTokens &Toks,
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000567 bool StopAtSemi, bool ConsumeFinalToken) {
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000568 // We always want this function to consume at least one token if the first
569 // token isn't T and if not at EOF.
570 bool isFirstTokenConsumed = true;
571 while (1) {
572 // If we found one of the tokens, stop and return true.
Douglas Gregor4d87df52008-12-16 21:30:33 +0000573 if (Tok.is(T1) || Tok.is(T2)) {
574 if (ConsumeFinalToken) {
575 Toks.push_back(Tok);
576 ConsumeAnyToken();
577 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000578 return true;
579 }
580
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000581 switch (Tok.getKind()) {
582 case tok::eof:
Richard Smith34f30512013-11-23 04:06:09 +0000583 case tok::annot_module_begin:
584 case tok::annot_module_end:
585 case tok::annot_module_include:
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000586 // Ran out of tokens.
587 return false;
588
589 case tok::l_paren:
590 // Recursively consume properly-nested parens.
591 Toks.push_back(Tok);
592 ConsumeParen();
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000593 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000594 break;
595 case tok::l_square:
596 // Recursively consume properly-nested square brackets.
597 Toks.push_back(Tok);
598 ConsumeBracket();
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000599 ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000600 break;
601 case tok::l_brace:
602 // Recursively consume properly-nested braces.
603 Toks.push_back(Tok);
604 ConsumeBrace();
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000605 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000606 break;
607
608 // Okay, we found a ']' or '}' or ')', which we think should be balanced.
609 // Since the user wasn't looking for this token (if they were, it would
610 // already be handled), this isn't balanced. If there is a LHS token at a
611 // higher level, we will assume that this matches the unbalanced token
612 // and return it. Otherwise, this is a spurious RHS token, which we skip.
613 case tok::r_paren:
614 if (ParenCount && !isFirstTokenConsumed)
615 return false; // Matches something.
616 Toks.push_back(Tok);
617 ConsumeParen();
618 break;
619 case tok::r_square:
620 if (BracketCount && !isFirstTokenConsumed)
621 return false; // Matches something.
622 Toks.push_back(Tok);
623 ConsumeBracket();
624 break;
625 case tok::r_brace:
626 if (BraceCount && !isFirstTokenConsumed)
627 return false; // Matches something.
628 Toks.push_back(Tok);
629 ConsumeBrace();
630 break;
631
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000632 case tok::code_completion:
633 Toks.push_back(Tok);
634 ConsumeCodeCompletionToken();
635 break;
636
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000637 case tok::string_literal:
638 case tok::wide_string_literal:
Douglas Gregorfb65e592011-07-27 05:40:30 +0000639 case tok::utf8_string_literal:
640 case tok::utf16_string_literal:
641 case tok::utf32_string_literal:
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000642 Toks.push_back(Tok);
643 ConsumeStringToken();
644 break;
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000645 case tok::semi:
646 if (StopAtSemi)
647 return false;
648 // FALL THROUGH.
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000649 default:
650 // consume this token.
651 Toks.push_back(Tok);
652 ConsumeToken();
653 break;
654 }
655 isFirstTokenConsumed = false;
656 }
657}
Sebastian Redla74948d2011-09-24 17:48:25 +0000658
659/// \brief Consume tokens and store them in the passed token container until
660/// we've passed the try keyword and constructor initializers and have consumed
Sebastian Redl0d164012011-09-30 08:32:17 +0000661/// the opening brace of the function body. The opening brace will be consumed
662/// if and only if there was no error.
Sebastian Redla74948d2011-09-24 17:48:25 +0000663///
Richard Smithcde3fd82013-07-04 00:13:48 +0000664/// \return True on error.
Sebastian Redl0d164012011-09-30 08:32:17 +0000665bool Parser::ConsumeAndStoreFunctionPrologue(CachedTokens &Toks) {
Sebastian Redla74948d2011-09-24 17:48:25 +0000666 if (Tok.is(tok::kw_try)) {
667 Toks.push_back(Tok);
668 ConsumeToken();
669 }
Richard Smithcde3fd82013-07-04 00:13:48 +0000670
671 if (Tok.isNot(tok::colon)) {
672 // Easy case, just a function body.
673
674 // Grab any remaining garbage to be diagnosed later. We stop when we reach a
675 // brace: an opening one is the function body, while a closing one probably
676 // means we've reached the end of the class.
677 ConsumeAndStoreUntil(tok::l_brace, tok::r_brace, Toks,
678 /*StopAtSemi=*/true,
679 /*ConsumeFinalToken=*/false);
680 if (Tok.isNot(tok::l_brace))
681 return Diag(Tok.getLocation(), diag::err_expected_lbrace);
682
Sebastian Redla74948d2011-09-24 17:48:25 +0000683 Toks.push_back(Tok);
Richard Smithcde3fd82013-07-04 00:13:48 +0000684 ConsumeBrace();
685 return false;
Eli Friedman7cd4a9b2012-02-22 04:49:04 +0000686 }
Sebastian Redl0d164012011-09-30 08:32:17 +0000687
688 Toks.push_back(Tok);
Richard Smithcde3fd82013-07-04 00:13:48 +0000689 ConsumeToken();
690
691 // We can't reliably skip over a mem-initializer-id, because it could be
692 // a template-id involving not-yet-declared names. Given:
693 //
694 // S ( ) : a < b < c > ( e )
695 //
696 // 'e' might be an initializer or part of a template argument, depending
697 // on whether 'b' is a template.
698
699 // Track whether we might be inside a template argument. We can give
700 // significantly better diagnostics if we know that we're not.
701 bool MightBeTemplateArgument = false;
702
703 while (true) {
704 // Skip over the mem-initializer-id, if possible.
705 if (Tok.is(tok::kw_decltype)) {
706 Toks.push_back(Tok);
707 SourceLocation OpenLoc = ConsumeToken();
708 if (Tok.isNot(tok::l_paren))
709 return Diag(Tok.getLocation(), diag::err_expected_lparen_after)
710 << "decltype";
711 Toks.push_back(Tok);
712 ConsumeParen();
713 if (!ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/true)) {
714 Diag(Tok.getLocation(), diag::err_expected_rparen);
715 Diag(OpenLoc, diag::note_matching) << "(";
716 return true;
717 }
718 }
719 do {
720 // Walk over a component of a nested-name-specifier.
721 if (Tok.is(tok::coloncolon)) {
722 Toks.push_back(Tok);
723 ConsumeToken();
724
725 if (Tok.is(tok::kw_template)) {
726 Toks.push_back(Tok);
727 ConsumeToken();
728 }
729 }
730
731 if (Tok.is(tok::identifier) || Tok.is(tok::kw_template)) {
732 Toks.push_back(Tok);
733 ConsumeToken();
734 } else if (Tok.is(tok::code_completion)) {
735 Toks.push_back(Tok);
736 ConsumeCodeCompletionToken();
737 // Consume the rest of the initializers permissively.
738 // FIXME: We should be able to perform code-completion here even if
739 // there isn't a subsequent '{' token.
740 MightBeTemplateArgument = true;
741 break;
742 } else {
743 break;
744 }
745 } while (Tok.is(tok::coloncolon));
746
747 if (Tok.is(tok::less))
748 MightBeTemplateArgument = true;
749
750 if (MightBeTemplateArgument) {
751 // We may be inside a template argument list. Grab up to the start of the
752 // next parenthesized initializer or braced-init-list. This *might* be the
753 // initializer, or it might be a subexpression in the template argument
754 // list.
755 // FIXME: Count angle brackets, and clear MightBeTemplateArgument
756 // if all angles are closed.
757 if (!ConsumeAndStoreUntil(tok::l_paren, tok::l_brace, Toks,
758 /*StopAtSemi=*/true,
759 /*ConsumeFinalToken=*/false)) {
760 // We're not just missing the initializer, we're also missing the
761 // function body!
762 return Diag(Tok.getLocation(), diag::err_expected_lbrace);
763 }
764 } else if (Tok.isNot(tok::l_paren) && Tok.isNot(tok::l_brace)) {
765 // We found something weird in a mem-initializer-id.
766 return Diag(Tok.getLocation(), getLangOpts().CPlusPlus11
767 ? diag::err_expected_lparen_or_lbrace
768 : diag::err_expected_lparen);
769 }
770
771 tok::TokenKind kind = Tok.getKind();
772 Toks.push_back(Tok);
773 bool IsLParen = (kind == tok::l_paren);
774 SourceLocation OpenLoc = Tok.getLocation();
775
776 if (IsLParen) {
777 ConsumeParen();
778 } else {
779 assert(kind == tok::l_brace && "Must be left paren or brace here.");
780 ConsumeBrace();
781 // In C++03, this has to be the start of the function body, which
782 // means the initializer is malformed; we'll diagnose it later.
783 if (!getLangOpts().CPlusPlus11)
784 return false;
785 }
786
787 // Grab the initializer (or the subexpression of the template argument).
788 // FIXME: If we support lambdas here, we'll need to set StopAtSemi to false
789 // if we might be inside the braces of a lambda-expression.
790 if (!ConsumeAndStoreUntil(IsLParen ? tok::r_paren : tok::r_brace,
791 Toks, /*StopAtSemi=*/true)) {
792 Diag(Tok, IsLParen ? diag::err_expected_rparen :
793 diag::err_expected_rbrace);
794 Diag(OpenLoc, diag::note_matching) << (IsLParen ? "(" : "{");
795 return true;
796 }
797
798 // Grab pack ellipsis, if present.
799 if (Tok.is(tok::ellipsis)) {
800 Toks.push_back(Tok);
801 ConsumeToken();
802 }
803
804 // If we know we just consumed a mem-initializer, we must have ',' or '{'
805 // next.
806 if (Tok.is(tok::comma)) {
807 Toks.push_back(Tok);
808 ConsumeToken();
809 } else if (Tok.is(tok::l_brace)) {
810 // This is the function body if the ')' or '}' is immediately followed by
811 // a '{'. That cannot happen within a template argument, apart from the
812 // case where a template argument contains a compound literal:
813 //
814 // S ( ) : a < b < c > ( d ) { }
815 // // End of declaration, or still inside the template argument?
816 //
817 // ... and the case where the template argument contains a lambda:
818 //
819 // S ( ) : a < 0 && b < c > ( d ) + [ ] ( ) { return 0; }
820 // ( ) > ( ) { }
821 //
822 // FIXME: Disambiguate these cases. Note that the latter case is probably
823 // going to be made ill-formed by core issue 1607.
824 Toks.push_back(Tok);
825 ConsumeBrace();
826 return false;
827 } else if (!MightBeTemplateArgument) {
828 return Diag(Tok.getLocation(), diag::err_expected_lbrace_or_comma);
829 }
830 }
Sebastian Redla74948d2011-09-24 17:48:25 +0000831}
Richard Smith1fff95c2013-09-12 23:28:08 +0000832
833/// \brief Consume and store tokens from the '?' to the ':' in a conditional
834/// expression.
835bool Parser::ConsumeAndStoreConditional(CachedTokens &Toks) {
836 // Consume '?'.
837 assert(Tok.is(tok::question));
838 Toks.push_back(Tok);
839 ConsumeToken();
840
841 while (Tok.isNot(tok::colon)) {
842 if (!ConsumeAndStoreUntil(tok::question, tok::colon, Toks, /*StopAtSemi*/true,
843 /*ConsumeFinalToken*/false))
844 return false;
845
846 // If we found a nested conditional, consume it.
847 if (Tok.is(tok::question) && !ConsumeAndStoreConditional(Toks))
848 return false;
849 }
850
851 // Consume ':'.
852 Toks.push_back(Tok);
853 ConsumeToken();
854 return true;
855}
856
857/// \brief A tentative parsing action that can also revert token annotations.
858class Parser::UnannotatedTentativeParsingAction : public TentativeParsingAction {
859public:
860 explicit UnannotatedTentativeParsingAction(Parser &Self,
861 tok::TokenKind EndKind)
862 : TentativeParsingAction(Self), Self(Self), EndKind(EndKind) {
863 // Stash away the old token stream, so we can restore it once the
864 // tentative parse is complete.
865 TentativeParsingAction Inner(Self);
866 Self.ConsumeAndStoreUntil(EndKind, Toks, true, /*ConsumeFinalToken*/false);
867 Inner.Revert();
868 }
869
870 void RevertAnnotations() {
871 Revert();
872
873 // Put back the original tokens.
Alexey Bataevee6507d2013-11-18 08:17:37 +0000874 Self.SkipUntil(EndKind, StopAtSemi | StopBeforeMatch);
Richard Smith1fff95c2013-09-12 23:28:08 +0000875 if (Toks.size()) {
876 Token *Buffer = new Token[Toks.size()];
877 std::copy(Toks.begin() + 1, Toks.end(), Buffer);
878 Buffer[Toks.size() - 1] = Self.Tok;
879 Self.PP.EnterTokenStream(Buffer, Toks.size(), true, /*Owned*/true);
880
881 Self.Tok = Toks.front();
882 }
883 }
884
885private:
886 Parser &Self;
887 CachedTokens Toks;
888 tok::TokenKind EndKind;
889};
890
891/// ConsumeAndStoreInitializer - Consume and store the token at the passed token
892/// container until the end of the current initializer expression (either a
893/// default argument or an in-class initializer for a non-static data member).
894/// The final token is not consumed.
895bool Parser::ConsumeAndStoreInitializer(CachedTokens &Toks,
896 CachedInitKind CIK) {
897 // We always want this function to consume at least one token if not at EOF.
898 bool IsFirstTokenConsumed = true;
899
900 // Number of possible unclosed <s we've seen so far. These might be templates,
901 // and might not, but if there were none of them (or we know for sure that
902 // we're within a template), we can avoid a tentative parse.
903 unsigned AngleCount = 0;
904 unsigned KnownTemplateCount = 0;
905
906 while (1) {
907 switch (Tok.getKind()) {
908 case tok::comma:
909 // If we might be in a template, perform a tentative parse to check.
910 if (!AngleCount)
911 // Not a template argument: this is the end of the initializer.
912 return true;
913 if (KnownTemplateCount)
914 goto consume_token;
915
916 // We hit a comma inside angle brackets. This is the hard case. The
917 // rule we follow is:
918 // * For a default argument, if the tokens after the comma form a
919 // syntactically-valid parameter-declaration-clause, in which each
920 // parameter has an initializer, then this comma ends the default
921 // argument.
922 // * For a default initializer, if the tokens after the comma form a
923 // syntactically-valid init-declarator-list, then this comma ends
924 // the default initializer.
925 {
926 UnannotatedTentativeParsingAction PA(*this,
927 CIK == CIK_DefaultInitializer
928 ? tok::semi : tok::r_paren);
929 Sema::TentativeAnalysisScope Scope(Actions);
930
931 TPResult Result = TPResult::Error();
932 ConsumeToken();
933 switch (CIK) {
934 case CIK_DefaultInitializer:
935 Result = TryParseInitDeclaratorList();
936 // If we parsed a complete, ambiguous init-declarator-list, this
937 // is only syntactically-valid if it's followed by a semicolon.
938 if (Result == TPResult::Ambiguous() && Tok.isNot(tok::semi))
939 Result = TPResult::False();
940 break;
941
942 case CIK_DefaultArgument:
943 bool InvalidAsDeclaration = false;
944 Result = TryParseParameterDeclarationClause(
945 &InvalidAsDeclaration, /*VersusTemplateArgument*/true);
946 // If this is an expression or a declaration with a missing
947 // 'typename', assume it's not a declaration.
948 if (Result == TPResult::Ambiguous() && InvalidAsDeclaration)
949 Result = TPResult::False();
950 break;
951 }
952
953 // If what follows could be a declaration, it is a declaration.
954 if (Result != TPResult::False() && Result != TPResult::Error()) {
955 PA.Revert();
956 return true;
957 }
958
959 // In the uncommon case that we decide the following tokens are part
960 // of a template argument, revert any annotations we've performed in
961 // those tokens. We're not going to look them up until we've parsed
962 // the rest of the class, and that might add more declarations.
963 PA.RevertAnnotations();
964 }
965
966 // Keep going. We know we're inside a template argument list now.
967 ++KnownTemplateCount;
968 goto consume_token;
969
970 case tok::eof:
Richard Smith34f30512013-11-23 04:06:09 +0000971 case tok::annot_module_begin:
972 case tok::annot_module_end:
973 case tok::annot_module_include:
Richard Smith1fff95c2013-09-12 23:28:08 +0000974 // Ran out of tokens.
975 return false;
976
977 case tok::less:
978 // FIXME: A '<' can only start a template-id if it's preceded by an
979 // identifier, an operator-function-id, or a literal-operator-id.
980 ++AngleCount;
981 goto consume_token;
982
983 case tok::question:
984 // In 'a ? b : c', 'b' can contain an unparenthesized comma. If it does,
985 // that is *never* the end of the initializer. Skip to the ':'.
986 if (!ConsumeAndStoreConditional(Toks))
987 return false;
988 break;
989
990 case tok::greatergreatergreater:
991 if (!getLangOpts().CPlusPlus11)
992 goto consume_token;
993 if (AngleCount) --AngleCount;
994 if (KnownTemplateCount) --KnownTemplateCount;
995 // Fall through.
996 case tok::greatergreater:
997 if (!getLangOpts().CPlusPlus11)
998 goto consume_token;
999 if (AngleCount) --AngleCount;
1000 if (KnownTemplateCount) --KnownTemplateCount;
1001 // Fall through.
1002 case tok::greater:
1003 if (AngleCount) --AngleCount;
1004 if (KnownTemplateCount) --KnownTemplateCount;
1005 goto consume_token;
1006
1007 case tok::kw_template:
1008 // 'template' identifier '<' is known to start a template argument list,
1009 // and can be used to disambiguate the parse.
1010 // FIXME: Support all forms of 'template' unqualified-id '<'.
1011 Toks.push_back(Tok);
1012 ConsumeToken();
1013 if (Tok.is(tok::identifier)) {
1014 Toks.push_back(Tok);
1015 ConsumeToken();
1016 if (Tok.is(tok::less)) {
1017 ++KnownTemplateCount;
1018 Toks.push_back(Tok);
1019 ConsumeToken();
1020 }
1021 }
1022 break;
1023
1024 case tok::kw_operator:
1025 // If 'operator' precedes other punctuation, that punctuation loses
1026 // its special behavior.
1027 Toks.push_back(Tok);
1028 ConsumeToken();
1029 switch (Tok.getKind()) {
1030 case tok::comma:
1031 case tok::greatergreatergreater:
1032 case tok::greatergreater:
1033 case tok::greater:
1034 case tok::less:
1035 Toks.push_back(Tok);
1036 ConsumeToken();
1037 break;
1038 default:
1039 break;
1040 }
1041 break;
1042
1043 case tok::l_paren:
1044 // Recursively consume properly-nested parens.
1045 Toks.push_back(Tok);
1046 ConsumeParen();
1047 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
1048 break;
1049 case tok::l_square:
1050 // Recursively consume properly-nested square brackets.
1051 Toks.push_back(Tok);
1052 ConsumeBracket();
1053 ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false);
1054 break;
1055 case tok::l_brace:
1056 // Recursively consume properly-nested braces.
1057 Toks.push_back(Tok);
1058 ConsumeBrace();
1059 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1060 break;
1061
1062 // Okay, we found a ']' or '}' or ')', which we think should be balanced.
1063 // Since the user wasn't looking for this token (if they were, it would
1064 // already be handled), this isn't balanced. If there is a LHS token at a
1065 // higher level, we will assume that this matches the unbalanced token
1066 // and return it. Otherwise, this is a spurious RHS token, which we skip.
1067 case tok::r_paren:
1068 if (CIK == CIK_DefaultArgument)
1069 return true; // End of the default argument.
1070 if (ParenCount && !IsFirstTokenConsumed)
1071 return false; // Matches something.
1072 goto consume_token;
1073 case tok::r_square:
1074 if (BracketCount && !IsFirstTokenConsumed)
1075 return false; // Matches something.
1076 goto consume_token;
1077 case tok::r_brace:
1078 if (BraceCount && !IsFirstTokenConsumed)
1079 return false; // Matches something.
1080 goto consume_token;
1081
1082 case tok::code_completion:
1083 Toks.push_back(Tok);
1084 ConsumeCodeCompletionToken();
1085 break;
1086
1087 case tok::string_literal:
1088 case tok::wide_string_literal:
1089 case tok::utf8_string_literal:
1090 case tok::utf16_string_literal:
1091 case tok::utf32_string_literal:
1092 Toks.push_back(Tok);
1093 ConsumeStringToken();
1094 break;
1095 case tok::semi:
1096 if (CIK == CIK_DefaultInitializer)
1097 return true; // End of the default initializer.
1098 // FALL THROUGH.
1099 default:
1100 consume_token:
1101 Toks.push_back(Tok);
1102 ConsumeToken();
1103 break;
1104 }
1105 IsFirstTokenConsumed = false;
1106 }
1107}