blob: 0d5bb2e97d466dd3d3d495a486f0ceb2cfe3fd56 [file] [log] [blame]
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00001//===--- ParseCXXInlineMethods.cpp - C++ class inline methods parsing------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements parsing for C++ class inline methods.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Parse/Parser.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "RAIIObjectsForParser.h"
16#include "clang/AST/DeclTemplate.h"
17#include "clang/Parse/ParseDiagnostic.h"
John McCall8b0666c2010-08-20 18:27:03 +000018#include "clang/Sema/DeclSpec.h"
19#include "clang/Sema/Scope.h"
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +000020using namespace clang;
21
Sebastian Redla7b98a72009-04-26 20:35:05 +000022/// ParseCXXInlineMethodDef - We parsed and verified that the specified
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +000023/// Declarator is a well formed C++ inline method definition. Now lex its body
24/// and store its tokens for parsing after the C++ class is complete.
Rafael Espindolac2453dd2013-01-08 21:00:12 +000025NamedDecl *Parser::ParseCXXInlineMethodDef(AccessSpecifier AS,
Erik Verbruggenca98f2a2011-10-13 09:41:32 +000026 AttributeList *AccessAttrs,
27 ParsingDeclarator &D,
Douglas Gregor5d1b4e32011-11-07 20:56:01 +000028 const ParsedTemplateInfo &TemplateInfo,
29 const VirtSpecifiers& VS,
30 FunctionDefinitionKind DefinitionKind,
31 ExprResult& Init) {
Abramo Bagnara924a8f32010-12-10 16:29:40 +000032 assert(D.isFunctionDeclarator() && "This isn't a function declarator!");
Alexis Hunt5a7fa252011-05-12 06:15:49 +000033 assert((Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try) ||
34 Tok.is(tok::equal)) &&
35 "Current token not a '{', ':', '=', or 'try'!");
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +000036
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000037 MultiTemplateParamsArg TemplateParams(
Craig Topper161e4db2014-05-21 06:02:52 +000038 TemplateInfo.TemplateParams ? TemplateInfo.TemplateParams->data()
39 : nullptr,
Nico Weber77c76c52014-05-10 17:43:15 +000040 TemplateInfo.TemplateParams ? TemplateInfo.TemplateParams->size() : 0);
Alexis Hunt1deb9722010-04-14 23:07:37 +000041
Rafael Espindolac2453dd2013-01-08 21:00:12 +000042 NamedDecl *FnD;
Douglas Gregor5d1b4e32011-11-07 20:56:01 +000043 D.setFunctionDefinitionKind(DefinitionKind);
John McCall07e91c02009-08-06 02:15:43 +000044 if (D.getDeclSpec().isFriendSpecified())
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000045 FnD = Actions.ActOnFriendFunctionDecl(getCurScope(), D,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000046 TemplateParams);
Douglas Gregor728d00b2011-10-10 14:49:18 +000047 else {
Douglas Gregor0be31a22010-07-02 17:43:08 +000048 FnD = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS, D,
Craig Topper161e4db2014-05-21 06:02:52 +000049 TemplateParams, nullptr,
Richard Smith2b013182012-06-10 03:12:00 +000050 VS, ICIS_NoInit);
Douglas Gregor728d00b2011-10-10 14:49:18 +000051 if (FnD) {
Richard Smithf8a75c32013-08-29 00:47:48 +000052 Actions.ProcessDeclAttributeList(getCurScope(), FnD, AccessAttrs);
Richard Smith74aeef52013-04-26 16:15:35 +000053 bool TypeSpecContainsAuto = D.getDeclSpec().containsPlaceholderType();
Douglas Gregor50cefbf2011-10-17 17:09:53 +000054 if (Init.isUsable())
Larisse Voufo39a1e502013-08-06 01:03:05 +000055 Actions.AddInitializerToDecl(FnD, Init.get(), false,
Douglas Gregor728d00b2011-10-10 14:49:18 +000056 TypeSpecContainsAuto);
57 else
58 Actions.ActOnUninitializedDecl(FnD, TypeSpecContainsAuto);
59 }
Nico Weber24b2a822011-01-28 06:07:34 +000060 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +000061
Douglas Gregor433e0532012-04-16 18:27:27 +000062 HandleMemberFunctionDeclDelays(D, FnD);
Eli Friedman3af2a772009-07-22 21:45:50 +000063
John McCallc1465822011-02-14 07:13:47 +000064 D.complete(FnD);
65
Alp Tokera3ebe6e2013-12-17 14:12:37 +000066 if (TryConsumeToken(tok::equal)) {
Richard Smith1c704732011-11-10 09:08:44 +000067 if (!FnD) {
68 SkipUntil(tok::semi);
Craig Topper161e4db2014-05-21 06:02:52 +000069 return nullptr;
Richard Smith1c704732011-11-10 09:08:44 +000070 }
71
Alexis Hunt5a7fa252011-05-12 06:15:49 +000072 bool Delete = false;
73 SourceLocation KWLoc;
Alp Tokera3ebe6e2013-12-17 14:12:37 +000074 if (TryConsumeToken(tok::kw_delete, KWLoc)) {
75 Diag(KWLoc, getLangOpts().CPlusPlus11
76 ? diag::warn_cxx98_compat_deleted_function
77 : diag::ext_deleted_function);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000078 Actions.SetDeclDeleted(FnD, KWLoc);
79 Delete = true;
Alp Tokera3ebe6e2013-12-17 14:12:37 +000080 } else if (TryConsumeToken(tok::kw_default, KWLoc)) {
81 Diag(KWLoc, getLangOpts().CPlusPlus11
82 ? diag::warn_cxx98_compat_defaulted_function
83 : diag::ext_defaulted_function);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000084 Actions.SetDeclDefaulted(FnD, KWLoc);
85 } else {
86 llvm_unreachable("function definition after = not 'delete' or 'default'");
87 }
88
89 if (Tok.is(tok::comma)) {
90 Diag(KWLoc, diag::err_default_delete_in_multiple_declaration)
91 << Delete;
92 SkipUntil(tok::semi);
Alp Toker383d2c42014-01-01 03:08:43 +000093 } else if (ExpectAndConsume(tok::semi, diag::err_expected_after,
94 Delete ? "delete" : "default")) {
95 SkipUntil(tok::semi);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000096 }
97
98 return FnD;
99 }
Faisal Valib96570332013-11-01 02:01:01 +0000100
Francois Pichet1c229c02011-04-22 22:18:13 +0000101 // In delayed template parsing mode, if we are within a class template
102 // or if we are about to parse function member template then consume
103 // the tokens and store them for parsing at the end of the translation unit.
David Majnemer90b17292013-09-14 05:46:42 +0000104 if (getLangOpts().DelayedTemplateParsing &&
105 DefinitionKind == FDK_Definition &&
Alp Tokera2794f92014-01-22 07:29:52 +0000106 !D.getDeclSpec().isConstexprSpecified() &&
107 !(FnD && FnD->getAsFunction() &&
Alp Toker314cc812014-01-25 16:55:45 +0000108 FnD->getAsFunction()->getReturnType()->getContainedAutoType()) &&
Francois Pichet1c229c02011-04-22 22:18:13 +0000109 ((Actions.CurContext->isDependentContext() ||
David Majnemer90b17292013-09-14 05:46:42 +0000110 (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
111 TemplateInfo.Kind != ParsedTemplateInfo::ExplicitSpecialization)) &&
112 !Actions.IsInsideALocalClassWithinATemplateFunction())) {
Francois Pichet1c229c02011-04-22 22:18:13 +0000113
Richard Smithe40f2ba2013-08-07 21:41:30 +0000114 CachedTokens Toks;
115 LexTemplateFunctionForLateParsing(Toks);
Francois Pichet1c229c02011-04-22 22:18:13 +0000116
Richard Smithe40f2ba2013-08-07 21:41:30 +0000117 if (FnD) {
Alp Tokera2794f92014-01-22 07:29:52 +0000118 FunctionDecl *FD = FnD->getAsFunction();
Chandler Carruthbc0f9ae2011-04-25 07:09:43 +0000119 Actions.CheckForFunctionRedefinition(FD);
Richard Smithe40f2ba2013-08-07 21:41:30 +0000120 Actions.MarkAsLateParsedTemplate(FD, FnD, Toks);
Francois Pichet1c229c02011-04-22 22:18:13 +0000121 }
122
123 return FnD;
124 }
125
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000126 // Consume the tokens and store them for later parsing.
127
Douglas Gregorefc46952010-10-12 16:25:54 +0000128 LexedMethod* LM = new LexedMethod(this, FnD);
129 getCurrentClass().LateParsedDeclarations.push_back(LM);
130 LM->TemplateScope = getCurScope()->isTemplateParamScope();
131 CachedTokens &Toks = LM->Toks;
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000132
Sebastian Redla7b98a72009-04-26 20:35:05 +0000133 tok::TokenKind kind = Tok.getKind();
Sebastian Redl0d164012011-09-30 08:32:17 +0000134 // Consume everything up to (and including) the left brace of the
135 // function body.
136 if (ConsumeAndStoreFunctionPrologue(Toks)) {
137 // We didn't find the left-brace we expected after the
Eli Friedman7cd4a9b2012-02-22 04:49:04 +0000138 // constructor initializer; we already printed an error, and it's likely
139 // impossible to recover, so don't try to parse this method later.
Richard Smithcde3fd82013-07-04 00:13:48 +0000140 // Skip over the rest of the decl and back to somewhere that looks
141 // reasonable.
142 SkipMalformedDecl();
Eli Friedman7cd4a9b2012-02-22 04:49:04 +0000143 delete getCurrentClass().LateParsedDeclarations.back();
144 getCurrentClass().LateParsedDeclarations.pop_back();
145 return FnD;
Douglas Gregore8381c02008-11-05 04:29:56 +0000146 } else {
Sebastian Redl0d164012011-09-30 08:32:17 +0000147 // Consume everything up to (and including) the matching right brace.
148 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
Douglas Gregore8381c02008-11-05 04:29:56 +0000149 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000150
Sebastian Redla7b98a72009-04-26 20:35:05 +0000151 // If we're in a function-try-block, we need to store all the catch blocks.
152 if (kind == tok::kw_try) {
153 while (Tok.is(tok::kw_catch)) {
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000154 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
155 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
Sebastian Redla7b98a72009-04-26 20:35:05 +0000156 }
157 }
158
Stephen Lin9354fc52013-06-23 07:37:13 +0000159 if (FnD) {
160 // If this is a friend function, mark that it's late-parsed so that
161 // it's still known to be a definition even before we attach the
162 // parsed body. Sema needs to treat friend function definitions
163 // differently during template instantiation, and it's possible for
164 // the containing class to be instantiated before all its member
165 // function definitions are parsed.
166 //
167 // If you remove this, you can remove the code that clears the flag
168 // after parsing the member.
169 if (D.getDeclSpec().isFriendSpecified()) {
Alp Tokera2794f92014-01-22 07:29:52 +0000170 FunctionDecl *FD = FnD->getAsFunction();
Alp Toker19bff322013-10-18 05:54:24 +0000171 Actions.CheckForFunctionRedefinition(FD);
172 FD->setLateTemplateParsed(true);
Stephen Lin9354fc52013-06-23 07:37:13 +0000173 }
174 } else {
Douglas Gregor6ca64102011-04-14 23:19:27 +0000175 // If semantic analysis could not build a function declaration,
176 // just throw away the late-parsed declaration.
177 delete getCurrentClass().LateParsedDeclarations.back();
178 getCurrentClass().LateParsedDeclarations.pop_back();
179 }
180
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000181 return FnD;
182}
183
Richard Smith938f40b2011-06-11 17:19:42 +0000184/// ParseCXXNonStaticMemberInitializer - We parsed and verified that the
185/// specified Declarator is a well formed C++ non-static data member
186/// declaration. Now lex its initializer and store its tokens for parsing
187/// after the class is complete.
188void Parser::ParseCXXNonStaticMemberInitializer(Decl *VarD) {
189 assert((Tok.is(tok::l_brace) || Tok.is(tok::equal)) &&
190 "Current token not a '{' or '='!");
191
192 LateParsedMemberInitializer *MI =
193 new LateParsedMemberInitializer(this, VarD);
194 getCurrentClass().LateParsedDeclarations.push_back(MI);
195 CachedTokens &Toks = MI->Toks;
196
197 tok::TokenKind kind = Tok.getKind();
198 if (kind == tok::equal) {
199 Toks.push_back(Tok);
Douglas Gregor0cf55e92012-03-08 01:00:17 +0000200 ConsumeToken();
Richard Smith938f40b2011-06-11 17:19:42 +0000201 }
202
203 if (kind == tok::l_brace) {
204 // Begin by storing the '{' token.
205 Toks.push_back(Tok);
206 ConsumeBrace();
207
208 // Consume everything up to (and including) the matching right brace.
209 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/true);
210 } else {
211 // Consume everything up to (but excluding) the comma or semicolon.
Richard Smith1fff95c2013-09-12 23:28:08 +0000212 ConsumeAndStoreInitializer(Toks, CIK_DefaultInitializer);
Richard Smith938f40b2011-06-11 17:19:42 +0000213 }
214
215 // Store an artificial EOF token to ensure that we don't run off the end of
216 // the initializer when we come to parse it.
217 Token Eof;
218 Eof.startToken();
219 Eof.setKind(tok::eof);
220 Eof.setLocation(Tok.getLocation());
David Majnemerce1d3012014-12-19 02:13:56 +0000221 Eof.setEofData(VarD);
Richard Smith938f40b2011-06-11 17:19:42 +0000222 Toks.push_back(Eof);
223}
224
Douglas Gregorefc46952010-10-12 16:25:54 +0000225Parser::LateParsedDeclaration::~LateParsedDeclaration() {}
226void Parser::LateParsedDeclaration::ParseLexedMethodDeclarations() {}
Richard Smith938f40b2011-06-11 17:19:42 +0000227void Parser::LateParsedDeclaration::ParseLexedMemberInitializers() {}
Douglas Gregorefc46952010-10-12 16:25:54 +0000228void Parser::LateParsedDeclaration::ParseLexedMethodDefs() {}
229
230Parser::LateParsedClass::LateParsedClass(Parser *P, ParsingClass *C)
231 : Self(P), Class(C) {}
232
233Parser::LateParsedClass::~LateParsedClass() {
234 Self->DeallocateParsedClasses(Class);
235}
236
237void Parser::LateParsedClass::ParseLexedMethodDeclarations() {
238 Self->ParseLexedMethodDeclarations(*Class);
239}
240
Richard Smith938f40b2011-06-11 17:19:42 +0000241void Parser::LateParsedClass::ParseLexedMemberInitializers() {
242 Self->ParseLexedMemberInitializers(*Class);
243}
244
Douglas Gregorefc46952010-10-12 16:25:54 +0000245void Parser::LateParsedClass::ParseLexedMethodDefs() {
246 Self->ParseLexedMethodDefs(*Class);
247}
248
249void Parser::LateParsedMethodDeclaration::ParseLexedMethodDeclarations() {
250 Self->ParseLexedMethodDeclaration(*this);
251}
252
253void Parser::LexedMethod::ParseLexedMethodDefs() {
254 Self->ParseLexedMethodDef(*this);
255}
256
Richard Smith938f40b2011-06-11 17:19:42 +0000257void Parser::LateParsedMemberInitializer::ParseLexedMemberInitializers() {
258 Self->ParseLexedMemberInitializer(*this);
259}
260
Douglas Gregor4d87df52008-12-16 21:30:33 +0000261/// ParseLexedMethodDeclarations - We finished parsing the member
262/// specification of a top (non-nested) C++ class. Now go over the
263/// stack of method declarations with some parts for which parsing was
264/// delayed (such as default arguments) and parse them.
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000265void Parser::ParseLexedMethodDeclarations(ParsingClass &Class) {
266 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
Nico Weber77c76c52014-05-10 17:43:15 +0000267 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
268 HasTemplateScope);
Richard Smithc8378952013-04-29 11:55:38 +0000269 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
270 if (HasTemplateScope) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000271 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
Richard Smithc8378952013-04-29 11:55:38 +0000272 ++CurTemplateDepthTracker;
273 }
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000274
John McCall6df5fef2009-12-19 10:49:29 +0000275 // The current scope is still active if we're the top-level class.
276 // Otherwise we'll need to push and enter a new scope.
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000277 bool HasClassScope = !Class.TopLevelClass;
Alexis Hunt1deb9722010-04-14 23:07:37 +0000278 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope,
279 HasClassScope);
John McCall6df5fef2009-12-19 10:49:29 +0000280 if (HasClassScope)
Nico Weber77c76c52014-05-10 17:43:15 +0000281 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(),
282 Class.TagOrTemplate);
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000283
Douglas Gregorefc46952010-10-12 16:25:54 +0000284 for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
285 Class.LateParsedDeclarations[i]->ParseLexedMethodDeclarations();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000286 }
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000287
John McCall6df5fef2009-12-19 10:49:29 +0000288 if (HasClassScope)
Nico Weber77c76c52014-05-10 17:43:15 +0000289 Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(),
290 Class.TagOrTemplate);
Douglas Gregor4d87df52008-12-16 21:30:33 +0000291}
292
Douglas Gregorefc46952010-10-12 16:25:54 +0000293void Parser::ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM) {
294 // If this is a member template, introduce the template parameter scope.
295 ParseScope TemplateScope(this, Scope::TemplateParamScope, LM.TemplateScope);
Richard Smithc8378952013-04-29 11:55:38 +0000296 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
297 if (LM.TemplateScope) {
Douglas Gregorefc46952010-10-12 16:25:54 +0000298 Actions.ActOnReenterTemplateScope(getCurScope(), LM.Method);
Richard Smithc8378952013-04-29 11:55:38 +0000299 ++CurTemplateDepthTracker;
300 }
Douglas Gregorefc46952010-10-12 16:25:54 +0000301 // Start the delayed C++ method declaration
302 Actions.ActOnStartDelayedCXXMethodDeclaration(getCurScope(), LM.Method);
303
304 // Introduce the parameters into scope and parse their default
305 // arguments.
Richard Smithe233fbf2013-01-28 22:42:45 +0000306 ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
307 Scope::FunctionDeclarationScope | Scope::DeclScope);
Douglas Gregorefc46952010-10-12 16:25:54 +0000308 for (unsigned I = 0, N = LM.DefaultArgs.size(); I != N; ++I) {
309 // Introduce the parameter into scope.
Nico Weber77c76c52014-05-10 17:43:15 +0000310 Actions.ActOnDelayedCXXMethodParameter(getCurScope(),
Douglas Gregor7fcbd902012-02-21 00:37:24 +0000311 LM.DefaultArgs[I].Param);
Douglas Gregorefc46952010-10-12 16:25:54 +0000312
313 if (CachedTokens *Toks = LM.DefaultArgs[I].Toks) {
314 // Save the current token position.
315 SourceLocation origLoc = Tok.getLocation();
316
317 // Parse the default argument from its saved token stream.
318 Toks->push_back(Tok); // So that the current token doesn't get lost
319 PP.EnterTokenStream(&Toks->front(), Toks->size(), true, false);
320
321 // Consume the previously-pushed token.
322 ConsumeAnyToken();
323
324 // Consume the '='.
325 assert(Tok.is(tok::equal) && "Default argument not starting with '='");
326 SourceLocation EqualLoc = ConsumeToken();
327
328 // The argument isn't actually potentially evaluated unless it is
329 // used.
330 EnterExpressionEvaluationContext Eval(Actions,
Douglas Gregor7fcbd902012-02-21 00:37:24 +0000331 Sema::PotentiallyEvaluatedIfUsed,
332 LM.DefaultArgs[I].Param);
Douglas Gregorefc46952010-10-12 16:25:54 +0000333
Sebastian Redldb63af22012-03-14 15:54:00 +0000334 ExprResult DefArgResult;
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000335 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
Sebastian Redl6db0b1b2012-03-20 21:24:03 +0000336 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
Sebastian Redldb63af22012-03-14 15:54:00 +0000337 DefArgResult = ParseBraceInitializer();
Sebastian Redl6db0b1b2012-03-20 21:24:03 +0000338 } else
Sebastian Redldb63af22012-03-14 15:54:00 +0000339 DefArgResult = ParseAssignmentExpression();
David Majnemerbba12342015-01-12 06:51:15 +0000340 bool DefArgTokenFound =
341 Tok.is(tok::eof) && Tok.getEofData() == LM.DefaultArgs[I].Param;
342 if (DefArgTokenFound)
343 ConsumeAnyToken();
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000344 DefArgResult = Actions.CorrectDelayedTyposInExpr(DefArgResult);
David Majnemerbba12342015-01-12 06:51:15 +0000345 if (DefArgResult.isInvalid()) {
Serge Pavlovb4b35782014-07-22 01:54:49 +0000346 Actions.ActOnParamDefaultArgumentError(LM.DefaultArgs[I].Param,
347 EqualLoc);
David Majnemerbba12342015-01-12 06:51:15 +0000348 } else {
349 if (!DefArgTokenFound) {
Richard Smith1fff95c2013-09-12 23:28:08 +0000350 // The last two tokens are the terminator and the saved value of
351 // Tok; the last token in the default argument is the one before
352 // those.
353 assert(Toks->size() >= 3 && "expected a token in default arg");
354 Diag(Tok.getLocation(), diag::err_default_arg_unparsed)
355 << SourceRange(Tok.getLocation(),
356 (*Toks)[Toks->size() - 3].getLocation());
357 }
Douglas Gregorefc46952010-10-12 16:25:54 +0000358 Actions.ActOnParamDefaultArgument(LM.DefaultArgs[I].Param, EqualLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000359 DefArgResult.get());
Douglas Gregorefc46952010-10-12 16:25:54 +0000360 }
361
362 assert(!PP.getSourceManager().isBeforeInTranslationUnit(origLoc,
363 Tok.getLocation()) &&
364 "ParseAssignmentExpression went over the default arg tokens!");
365 // There could be leftover tokens (e.g. because of an error).
366 // Skip through until we reach the original token position.
David Majnemer06b7d002015-01-12 05:17:40 +0000367 while (Tok.getLocation() != origLoc) {
368 if (Tok.is(tok::eof) && Tok.getEofData() != LM.DefaultArgs[I].Param)
369 break;
Douglas Gregorefc46952010-10-12 16:25:54 +0000370 ConsumeAnyToken();
David Majnemer06b7d002015-01-12 05:17:40 +0000371 }
Douglas Gregorefc46952010-10-12 16:25:54 +0000372
373 delete Toks;
Craig Topper161e4db2014-05-21 06:02:52 +0000374 LM.DefaultArgs[I].Toks = nullptr;
Douglas Gregorefc46952010-10-12 16:25:54 +0000375 }
376 }
Douglas Gregor433e0532012-04-16 18:27:27 +0000377
Richard Smith0b3a4622014-11-13 20:01:57 +0000378 // Parse a delayed exception-specification, if there is one.
379 if (CachedTokens *Toks = LM.ExceptionSpecTokens) {
380 // Save the current token position.
381 SourceLocation origLoc = Tok.getLocation();
382
383 // Parse the default argument from its saved token stream.
384 Toks->push_back(Tok); // So that the current token doesn't get lost
385 PP.EnterTokenStream(&Toks->front(), Toks->size(), true, false);
386
387 // Consume the previously-pushed token.
388 ConsumeAnyToken();
389
390 // C++11 [expr.prim.general]p3:
391 // If a declaration declares a member function or member function
392 // template of a class X, the expression this is a prvalue of type
393 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
394 // and the end of the function-definition, member-declarator, or
395 // declarator.
396 CXXMethodDecl *Method;
397 if (FunctionTemplateDecl *FunTmpl
398 = dyn_cast<FunctionTemplateDecl>(LM.Method))
399 Method = cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
400 else
401 Method = cast<CXXMethodDecl>(LM.Method);
402
403 Sema::CXXThisScopeRAII ThisScope(Actions, Method->getParent(),
404 Method->getTypeQualifiers(),
405 getLangOpts().CPlusPlus11);
406
407 // Parse the exception-specification.
408 SourceRange SpecificationRange;
409 SmallVector<ParsedType, 4> DynamicExceptions;
410 SmallVector<SourceRange, 4> DynamicExceptionRanges;
411 ExprResult NoexceptExpr;
412 CachedTokens *ExceptionSpecTokens;
413
414 ExceptionSpecificationType EST
415 = tryParseExceptionSpecification(/*Delayed=*/false, SpecificationRange,
416 DynamicExceptions,
417 DynamicExceptionRanges, NoexceptExpr,
418 ExceptionSpecTokens);
419
420 // Clean up the remaining tokens.
421 if (Tok.is(tok::cxx_exceptspec_end))
422 ConsumeToken();
423 else if (EST != EST_None)
424 Diag(Tok.getLocation(), diag::err_except_spec_unparsed);
425
426 // Attach the exception-specification to the method.
Richard Smith3ef3e892014-11-20 22:32:11 +0000427 Actions.actOnDelayedExceptionSpecification(LM.Method, EST,
428 SpecificationRange,
429 DynamicExceptions,
430 DynamicExceptionRanges,
431 NoexceptExpr.isUsable()?
432 NoexceptExpr.get() : nullptr);
Richard Smith0b3a4622014-11-13 20:01:57 +0000433
434 assert(!PP.getSourceManager().isBeforeInTranslationUnit(origLoc,
435 Tok.getLocation()) &&
436 "tryParseExceptionSpecification went over the exception tokens!");
437
438 // There could be leftover tokens (e.g. because of an error).
439 // Skip through until we reach the original token position.
440 while (Tok.getLocation() != origLoc && Tok.isNot(tok::eof))
441 ConsumeAnyToken();
442
443 delete Toks;
444 LM.ExceptionSpecTokens = nullptr;
445 }
446
Douglas Gregorefc46952010-10-12 16:25:54 +0000447 PrototypeScope.Exit();
448
449 // Finish the delayed C++ method declaration.
450 Actions.ActOnFinishDelayedCXXMethodDeclaration(getCurScope(), LM.Method);
451}
452
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000453/// ParseLexedMethodDefs - We finished parsing the member specification of a top
454/// (non-nested) C++ class. Now go over the stack of lexed methods that were
455/// collected during its parsing and parse them all.
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000456void Parser::ParseLexedMethodDefs(ParsingClass &Class) {
457 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
Douglas Gregorefc46952010-10-12 16:25:54 +0000458 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope, HasTemplateScope);
Richard Smithc8378952013-04-29 11:55:38 +0000459 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
460 if (HasTemplateScope) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000461 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
Richard Smithc8378952013-04-29 11:55:38 +0000462 ++CurTemplateDepthTracker;
463 }
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000464 bool HasClassScope = !Class.TopLevelClass;
465 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope,
466 HasClassScope);
467
Douglas Gregorefc46952010-10-12 16:25:54 +0000468 for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
469 Class.LateParsedDeclarations[i]->ParseLexedMethodDefs();
470 }
471}
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000472
Douglas Gregorefc46952010-10-12 16:25:54 +0000473void Parser::ParseLexedMethodDef(LexedMethod &LM) {
474 // If this is a member template, introduce the template parameter scope.
475 ParseScope TemplateScope(this, Scope::TemplateParamScope, LM.TemplateScope);
Richard Smithc8378952013-04-29 11:55:38 +0000476 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
477 if (LM.TemplateScope) {
Douglas Gregorefc46952010-10-12 16:25:54 +0000478 Actions.ActOnReenterTemplateScope(getCurScope(), LM.D);
Richard Smithc8378952013-04-29 11:55:38 +0000479 ++CurTemplateDepthTracker;
480 }
Douglas Gregorefc46952010-10-12 16:25:54 +0000481 // Save the current token position.
482 SourceLocation origLoc = Tok.getLocation();
Argyrios Kyrtzidis02041972010-03-31 00:38:09 +0000483
Douglas Gregorefc46952010-10-12 16:25:54 +0000484 assert(!LM.Toks.empty() && "Empty body!");
485 // Append the current token at the end of the new token stream so that it
486 // doesn't get lost.
487 LM.Toks.push_back(Tok);
488 PP.EnterTokenStream(LM.Toks.data(), LM.Toks.size(), true, false);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000489
Douglas Gregorefc46952010-10-12 16:25:54 +0000490 // Consume the previously pushed token.
Argyrios Kyrtzidisc36633c2013-03-27 23:58:17 +0000491 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
Douglas Gregorefc46952010-10-12 16:25:54 +0000492 assert((Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try))
493 && "Inline method not starting with '{', ':' or 'try'");
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000494
Douglas Gregorefc46952010-10-12 16:25:54 +0000495 // Parse the method body. Function body parsing code is similar enough
496 // to be re-used for method bodies as well.
497 ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope);
498 Actions.ActOnStartOfFunctionDef(getCurScope(), LM.D);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000499
Douglas Gregorefc46952010-10-12 16:25:54 +0000500 if (Tok.is(tok::kw_try)) {
Douglas Gregora0ff0c32011-03-16 17:05:57 +0000501 ParseFunctionTryBlock(LM.D, FnScope);
Douglas Gregorefc46952010-10-12 16:25:54 +0000502 assert(!PP.getSourceManager().isBeforeInTranslationUnit(origLoc,
503 Tok.getLocation()) &&
504 "ParseFunctionTryBlock went over the cached tokens!");
505 // There could be leftover tokens (e.g. because of an error).
506 // Skip through until we reach the original token position.
507 while (Tok.getLocation() != origLoc && Tok.isNot(tok::eof))
508 ConsumeAnyToken();
509 return;
510 }
511 if (Tok.is(tok::colon)) {
512 ParseConstructorInitializer(LM.D);
513
514 // Error recovery.
515 if (!Tok.is(tok::l_brace)) {
Douglas Gregora0ff0c32011-03-16 17:05:57 +0000516 FnScope.Exit();
Craig Topper161e4db2014-05-21 06:02:52 +0000517 Actions.ActOnFinishFunctionBody(LM.D, nullptr);
Matt Beaumont-Gayd0457922011-09-23 22:39:23 +0000518 while (Tok.getLocation() != origLoc && Tok.isNot(tok::eof))
519 ConsumeAnyToken();
Douglas Gregorefc46952010-10-12 16:25:54 +0000520 return;
521 }
522 } else
523 Actions.ActOnDefaultCtorInitializers(LM.D);
524
Richard Smithc8378952013-04-29 11:55:38 +0000525 assert((Actions.getDiagnostics().hasErrorOccurred() ||
526 !isa<FunctionTemplateDecl>(LM.D) ||
527 cast<FunctionTemplateDecl>(LM.D)->getTemplateParameters()->getDepth()
528 < TemplateParameterDepth) &&
529 "TemplateParameterDepth should be greater than the depth of "
530 "current template being instantiated!");
531
Douglas Gregora0ff0c32011-03-16 17:05:57 +0000532 ParseFunctionStatementBody(LM.D, FnScope);
Douglas Gregorefc46952010-10-12 16:25:54 +0000533
John McCalle68672f2013-03-14 05:13:41 +0000534 // Clear the late-template-parsed bit if we set it before.
Alp Tokera2794f92014-01-22 07:29:52 +0000535 if (LM.D)
536 LM.D->getAsFunction()->setLateTemplateParsed(false);
John McCalle68672f2013-03-14 05:13:41 +0000537
Douglas Gregorefc46952010-10-12 16:25:54 +0000538 if (Tok.getLocation() != origLoc) {
539 // Due to parsing error, we either went over the cached tokens or
540 // there are still cached tokens left. If it's the latter case skip the
541 // leftover tokens.
542 // Since this is an uncommon situation that should be avoided, use the
543 // expensive isBeforeInTranslationUnit call.
544 if (PP.getSourceManager().isBeforeInTranslationUnit(Tok.getLocation(),
545 origLoc))
Argyrios Kyrtzidise1224c82010-06-19 19:58:34 +0000546 while (Tok.getLocation() != origLoc && Tok.isNot(tok::eof))
Argyrios Kyrtzidise9b76af2010-06-17 10:52:22 +0000547 ConsumeAnyToken();
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000548 }
Hans Wennborga926d842014-05-23 20:37:38 +0000549
550 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(LM.D))
551 Actions.ActOnFinishInlineMethodDef(MD);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000552}
553
Richard Smith938f40b2011-06-11 17:19:42 +0000554/// ParseLexedMemberInitializers - We finished parsing the member specification
555/// of a top (non-nested) C++ class. Now go over the stack of lexed data member
556/// initializers that were collected during its parsing and parse them all.
557void Parser::ParseLexedMemberInitializers(ParsingClass &Class) {
558 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
559 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
560 HasTemplateScope);
Richard Smithc8378952013-04-29 11:55:38 +0000561 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
562 if (HasTemplateScope) {
Richard Smith938f40b2011-06-11 17:19:42 +0000563 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
Richard Smithc8378952013-04-29 11:55:38 +0000564 ++CurTemplateDepthTracker;
565 }
Douglas Gregor3024f072012-04-16 07:05:22 +0000566 // Set or update the scope flags.
Richard Smith938f40b2011-06-11 17:19:42 +0000567 bool AlreadyHasClassScope = Class.TopLevelClass;
Douglas Gregor3024f072012-04-16 07:05:22 +0000568 unsigned ScopeFlags = Scope::ClassScope|Scope::DeclScope;
Richard Smith938f40b2011-06-11 17:19:42 +0000569 ParseScope ClassScope(this, ScopeFlags, !AlreadyHasClassScope);
570 ParseScopeFlags ClassScopeFlags(this, ScopeFlags, AlreadyHasClassScope);
571
572 if (!AlreadyHasClassScope)
573 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(),
574 Class.TagOrTemplate);
575
Benjamin Kramer1d373c62012-05-17 12:01:52 +0000576 if (!Class.LateParsedDeclarations.empty()) {
Douglas Gregor3024f072012-04-16 07:05:22 +0000577 // C++11 [expr.prim.general]p4:
578 // Otherwise, if a member-declarator declares a non-static data member
579 // (9.2) of a class X, the expression this is a prvalue of type "pointer
580 // to X" within the optional brace-or-equal-initializer. It shall not
581 // appear elsewhere in the member-declarator.
582 Sema::CXXThisScopeRAII ThisScope(Actions, Class.TagOrTemplate,
583 /*TypeQuals=*/(unsigned)0);
Richard Smith938f40b2011-06-11 17:19:42 +0000584
Douglas Gregor3024f072012-04-16 07:05:22 +0000585 for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
586 Class.LateParsedDeclarations[i]->ParseLexedMemberInitializers();
587 }
588 }
589
Richard Smith938f40b2011-06-11 17:19:42 +0000590 if (!AlreadyHasClassScope)
591 Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(),
592 Class.TagOrTemplate);
593
594 Actions.ActOnFinishDelayedMemberInitializers(Class.TagOrTemplate);
595}
596
597void Parser::ParseLexedMemberInitializer(LateParsedMemberInitializer &MI) {
Richard Smith1a526fd2011-09-29 19:42:27 +0000598 if (!MI.Field || MI.Field->isInvalidDecl())
Richard Smith938f40b2011-06-11 17:19:42 +0000599 return;
600
601 // Append the current token at the end of the new token stream so that it
602 // doesn't get lost.
603 MI.Toks.push_back(Tok);
604 PP.EnterTokenStream(MI.Toks.data(), MI.Toks.size(), true, false);
605
606 // Consume the previously pushed token.
Argyrios Kyrtzidisc36633c2013-03-27 23:58:17 +0000607 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
Richard Smith938f40b2011-06-11 17:19:42 +0000608
609 SourceLocation EqualLoc;
Richard Smith2b013182012-06-10 03:12:00 +0000610
Richard Smith74108172014-01-17 03:11:34 +0000611 Actions.ActOnStartCXXInClassMemberInitializer();
612
Douglas Gregor926410d2012-02-21 02:22:07 +0000613 ExprResult Init = ParseCXXMemberInitializer(MI.Field, /*IsFunction=*/false,
614 EqualLoc);
Richard Smith938f40b2011-06-11 17:19:42 +0000615
Richard Smith74108172014-01-17 03:11:34 +0000616 Actions.ActOnFinishCXXInClassMemberInitializer(MI.Field, EqualLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000617 Init.get());
Richard Smith938f40b2011-06-11 17:19:42 +0000618
619 // The next token should be our artificial terminating EOF token.
620 if (Tok.isNot(tok::eof)) {
Richard Smith95e1fb02014-08-27 03:23:12 +0000621 if (!Init.isInvalid()) {
622 SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
623 if (!EndLoc.isValid())
624 EndLoc = Tok.getLocation();
625 // No fixit; we can't recover as if there were a semicolon here.
626 Diag(EndLoc, diag::err_expected_semi_decl_list);
627 }
Richard Smith938f40b2011-06-11 17:19:42 +0000628
629 // Consume tokens until we hit the artificial EOF.
630 while (Tok.isNot(tok::eof))
631 ConsumeAnyToken();
632 }
David Majnemer2d3663e2014-12-18 09:57:31 +0000633 // Make sure this is *our* artificial EOF token.
David Majnemerce1d3012014-12-19 02:13:56 +0000634 if (Tok.getEofData() == MI.Field)
David Majnemer2d3663e2014-12-18 09:57:31 +0000635 ConsumeAnyToken();
Richard Smith938f40b2011-06-11 17:19:42 +0000636}
637
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000638/// ConsumeAndStoreUntil - Consume and store the token at the passed token
Douglas Gregor4d87df52008-12-16 21:30:33 +0000639/// container until the token 'T' is reached (which gets
Mike Stump11289f42009-09-09 15:08:12 +0000640/// consumed/stored too, if ConsumeFinalToken).
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000641/// If StopAtSemi is true, then we will stop early at a ';' character.
Douglas Gregor4d87df52008-12-16 21:30:33 +0000642/// Returns true if token 'T1' or 'T2' was found.
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000643/// NOTE: This is a specialized version of Parser::SkipUntil.
Douglas Gregor4d87df52008-12-16 21:30:33 +0000644bool Parser::ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
645 CachedTokens &Toks,
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000646 bool StopAtSemi, bool ConsumeFinalToken) {
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000647 // We always want this function to consume at least one token if the first
648 // token isn't T and if not at EOF.
649 bool isFirstTokenConsumed = true;
650 while (1) {
651 // If we found one of the tokens, stop and return true.
Douglas Gregor4d87df52008-12-16 21:30:33 +0000652 if (Tok.is(T1) || Tok.is(T2)) {
653 if (ConsumeFinalToken) {
654 Toks.push_back(Tok);
655 ConsumeAnyToken();
656 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000657 return true;
658 }
659
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000660 switch (Tok.getKind()) {
661 case tok::eof:
Richard Smith34f30512013-11-23 04:06:09 +0000662 case tok::annot_module_begin:
663 case tok::annot_module_end:
664 case tok::annot_module_include:
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000665 // Ran out of tokens.
666 return false;
667
668 case tok::l_paren:
669 // Recursively consume properly-nested parens.
670 Toks.push_back(Tok);
671 ConsumeParen();
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000672 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000673 break;
674 case tok::l_square:
675 // Recursively consume properly-nested square brackets.
676 Toks.push_back(Tok);
677 ConsumeBracket();
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000678 ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000679 break;
680 case tok::l_brace:
681 // Recursively consume properly-nested braces.
682 Toks.push_back(Tok);
683 ConsumeBrace();
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000684 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000685 break;
686
687 // Okay, we found a ']' or '}' or ')', which we think should be balanced.
688 // Since the user wasn't looking for this token (if they were, it would
689 // already be handled), this isn't balanced. If there is a LHS token at a
690 // higher level, we will assume that this matches the unbalanced token
691 // and return it. Otherwise, this is a spurious RHS token, which we skip.
692 case tok::r_paren:
693 if (ParenCount && !isFirstTokenConsumed)
694 return false; // Matches something.
695 Toks.push_back(Tok);
696 ConsumeParen();
697 break;
698 case tok::r_square:
699 if (BracketCount && !isFirstTokenConsumed)
700 return false; // Matches something.
701 Toks.push_back(Tok);
702 ConsumeBracket();
703 break;
704 case tok::r_brace:
705 if (BraceCount && !isFirstTokenConsumed)
706 return false; // Matches something.
707 Toks.push_back(Tok);
708 ConsumeBrace();
709 break;
710
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000711 case tok::code_completion:
712 Toks.push_back(Tok);
713 ConsumeCodeCompletionToken();
714 break;
715
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000716 case tok::string_literal:
717 case tok::wide_string_literal:
Douglas Gregorfb65e592011-07-27 05:40:30 +0000718 case tok::utf8_string_literal:
719 case tok::utf16_string_literal:
720 case tok::utf32_string_literal:
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000721 Toks.push_back(Tok);
722 ConsumeStringToken();
723 break;
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000724 case tok::semi:
725 if (StopAtSemi)
726 return false;
727 // FALL THROUGH.
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000728 default:
729 // consume this token.
730 Toks.push_back(Tok);
731 ConsumeToken();
732 break;
733 }
734 isFirstTokenConsumed = false;
735 }
736}
Sebastian Redla74948d2011-09-24 17:48:25 +0000737
738/// \brief Consume tokens and store them in the passed token container until
739/// we've passed the try keyword and constructor initializers and have consumed
Sebastian Redl0d164012011-09-30 08:32:17 +0000740/// the opening brace of the function body. The opening brace will be consumed
741/// if and only if there was no error.
Sebastian Redla74948d2011-09-24 17:48:25 +0000742///
Richard Smithcde3fd82013-07-04 00:13:48 +0000743/// \return True on error.
Sebastian Redl0d164012011-09-30 08:32:17 +0000744bool Parser::ConsumeAndStoreFunctionPrologue(CachedTokens &Toks) {
Sebastian Redla74948d2011-09-24 17:48:25 +0000745 if (Tok.is(tok::kw_try)) {
746 Toks.push_back(Tok);
747 ConsumeToken();
748 }
Richard Smithcde3fd82013-07-04 00:13:48 +0000749
750 if (Tok.isNot(tok::colon)) {
751 // Easy case, just a function body.
752
753 // Grab any remaining garbage to be diagnosed later. We stop when we reach a
754 // brace: an opening one is the function body, while a closing one probably
755 // means we've reached the end of the class.
756 ConsumeAndStoreUntil(tok::l_brace, tok::r_brace, Toks,
757 /*StopAtSemi=*/true,
758 /*ConsumeFinalToken=*/false);
759 if (Tok.isNot(tok::l_brace))
Alp Tokerec543272013-12-24 09:48:30 +0000760 return Diag(Tok.getLocation(), diag::err_expected) << tok::l_brace;
Richard Smithcde3fd82013-07-04 00:13:48 +0000761
Sebastian Redla74948d2011-09-24 17:48:25 +0000762 Toks.push_back(Tok);
Richard Smithcde3fd82013-07-04 00:13:48 +0000763 ConsumeBrace();
764 return false;
Eli Friedman7cd4a9b2012-02-22 04:49:04 +0000765 }
Sebastian Redl0d164012011-09-30 08:32:17 +0000766
767 Toks.push_back(Tok);
Richard Smithcde3fd82013-07-04 00:13:48 +0000768 ConsumeToken();
769
770 // We can't reliably skip over a mem-initializer-id, because it could be
771 // a template-id involving not-yet-declared names. Given:
772 //
773 // S ( ) : a < b < c > ( e )
774 //
775 // 'e' might be an initializer or part of a template argument, depending
776 // on whether 'b' is a template.
777
778 // Track whether we might be inside a template argument. We can give
779 // significantly better diagnostics if we know that we're not.
780 bool MightBeTemplateArgument = false;
781
782 while (true) {
783 // Skip over the mem-initializer-id, if possible.
784 if (Tok.is(tok::kw_decltype)) {
785 Toks.push_back(Tok);
786 SourceLocation OpenLoc = ConsumeToken();
787 if (Tok.isNot(tok::l_paren))
788 return Diag(Tok.getLocation(), diag::err_expected_lparen_after)
789 << "decltype";
790 Toks.push_back(Tok);
791 ConsumeParen();
792 if (!ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/true)) {
Alp Tokerec543272013-12-24 09:48:30 +0000793 Diag(Tok.getLocation(), diag::err_expected) << tok::r_paren;
794 Diag(OpenLoc, diag::note_matching) << tok::l_paren;
Richard Smithcde3fd82013-07-04 00:13:48 +0000795 return true;
796 }
797 }
798 do {
799 // Walk over a component of a nested-name-specifier.
800 if (Tok.is(tok::coloncolon)) {
801 Toks.push_back(Tok);
802 ConsumeToken();
803
804 if (Tok.is(tok::kw_template)) {
805 Toks.push_back(Tok);
806 ConsumeToken();
807 }
808 }
809
810 if (Tok.is(tok::identifier) || Tok.is(tok::kw_template)) {
811 Toks.push_back(Tok);
812 ConsumeToken();
813 } else if (Tok.is(tok::code_completion)) {
814 Toks.push_back(Tok);
815 ConsumeCodeCompletionToken();
816 // Consume the rest of the initializers permissively.
817 // FIXME: We should be able to perform code-completion here even if
818 // there isn't a subsequent '{' token.
819 MightBeTemplateArgument = true;
820 break;
821 } else {
822 break;
823 }
824 } while (Tok.is(tok::coloncolon));
825
826 if (Tok.is(tok::less))
827 MightBeTemplateArgument = true;
828
829 if (MightBeTemplateArgument) {
830 // We may be inside a template argument list. Grab up to the start of the
831 // next parenthesized initializer or braced-init-list. This *might* be the
832 // initializer, or it might be a subexpression in the template argument
833 // list.
834 // FIXME: Count angle brackets, and clear MightBeTemplateArgument
835 // if all angles are closed.
836 if (!ConsumeAndStoreUntil(tok::l_paren, tok::l_brace, Toks,
837 /*StopAtSemi=*/true,
838 /*ConsumeFinalToken=*/false)) {
839 // We're not just missing the initializer, we're also missing the
840 // function body!
Alp Tokerec543272013-12-24 09:48:30 +0000841 return Diag(Tok.getLocation(), diag::err_expected) << tok::l_brace;
Richard Smithcde3fd82013-07-04 00:13:48 +0000842 }
843 } else if (Tok.isNot(tok::l_paren) && Tok.isNot(tok::l_brace)) {
844 // We found something weird in a mem-initializer-id.
Alp Tokerec543272013-12-24 09:48:30 +0000845 if (getLangOpts().CPlusPlus11)
846 return Diag(Tok.getLocation(), diag::err_expected_either)
847 << tok::l_paren << tok::l_brace;
848 else
849 return Diag(Tok.getLocation(), diag::err_expected) << tok::l_paren;
Richard Smithcde3fd82013-07-04 00:13:48 +0000850 }
851
852 tok::TokenKind kind = Tok.getKind();
853 Toks.push_back(Tok);
854 bool IsLParen = (kind == tok::l_paren);
855 SourceLocation OpenLoc = Tok.getLocation();
856
857 if (IsLParen) {
858 ConsumeParen();
859 } else {
860 assert(kind == tok::l_brace && "Must be left paren or brace here.");
861 ConsumeBrace();
862 // In C++03, this has to be the start of the function body, which
863 // means the initializer is malformed; we'll diagnose it later.
864 if (!getLangOpts().CPlusPlus11)
865 return false;
866 }
867
868 // Grab the initializer (or the subexpression of the template argument).
869 // FIXME: If we support lambdas here, we'll need to set StopAtSemi to false
870 // if we might be inside the braces of a lambda-expression.
Alp Tokerec543272013-12-24 09:48:30 +0000871 tok::TokenKind CloseKind = IsLParen ? tok::r_paren : tok::r_brace;
872 if (!ConsumeAndStoreUntil(CloseKind, Toks, /*StopAtSemi=*/true)) {
873 Diag(Tok, diag::err_expected) << CloseKind;
874 Diag(OpenLoc, diag::note_matching) << kind;
Richard Smithcde3fd82013-07-04 00:13:48 +0000875 return true;
876 }
877
878 // Grab pack ellipsis, if present.
879 if (Tok.is(tok::ellipsis)) {
880 Toks.push_back(Tok);
881 ConsumeToken();
882 }
883
884 // If we know we just consumed a mem-initializer, we must have ',' or '{'
885 // next.
886 if (Tok.is(tok::comma)) {
887 Toks.push_back(Tok);
888 ConsumeToken();
889 } else if (Tok.is(tok::l_brace)) {
890 // This is the function body if the ')' or '}' is immediately followed by
891 // a '{'. That cannot happen within a template argument, apart from the
892 // case where a template argument contains a compound literal:
893 //
894 // S ( ) : a < b < c > ( d ) { }
895 // // End of declaration, or still inside the template argument?
896 //
897 // ... and the case where the template argument contains a lambda:
898 //
899 // S ( ) : a < 0 && b < c > ( d ) + [ ] ( ) { return 0; }
900 // ( ) > ( ) { }
901 //
902 // FIXME: Disambiguate these cases. Note that the latter case is probably
903 // going to be made ill-formed by core issue 1607.
904 Toks.push_back(Tok);
905 ConsumeBrace();
906 return false;
907 } else if (!MightBeTemplateArgument) {
Alp Tokerec543272013-12-24 09:48:30 +0000908 return Diag(Tok.getLocation(), diag::err_expected_either) << tok::l_brace
909 << tok::comma;
Richard Smithcde3fd82013-07-04 00:13:48 +0000910 }
911 }
Sebastian Redla74948d2011-09-24 17:48:25 +0000912}
Richard Smith1fff95c2013-09-12 23:28:08 +0000913
914/// \brief Consume and store tokens from the '?' to the ':' in a conditional
915/// expression.
916bool Parser::ConsumeAndStoreConditional(CachedTokens &Toks) {
917 // Consume '?'.
918 assert(Tok.is(tok::question));
919 Toks.push_back(Tok);
920 ConsumeToken();
921
922 while (Tok.isNot(tok::colon)) {
Nico Weber77c76c52014-05-10 17:43:15 +0000923 if (!ConsumeAndStoreUntil(tok::question, tok::colon, Toks,
924 /*StopAtSemi=*/true,
925 /*ConsumeFinalToken=*/false))
Richard Smith1fff95c2013-09-12 23:28:08 +0000926 return false;
927
928 // If we found a nested conditional, consume it.
929 if (Tok.is(tok::question) && !ConsumeAndStoreConditional(Toks))
930 return false;
931 }
932
933 // Consume ':'.
934 Toks.push_back(Tok);
935 ConsumeToken();
936 return true;
937}
938
939/// \brief A tentative parsing action that can also revert token annotations.
940class Parser::UnannotatedTentativeParsingAction : public TentativeParsingAction {
941public:
942 explicit UnannotatedTentativeParsingAction(Parser &Self,
943 tok::TokenKind EndKind)
944 : TentativeParsingAction(Self), Self(Self), EndKind(EndKind) {
945 // Stash away the old token stream, so we can restore it once the
946 // tentative parse is complete.
947 TentativeParsingAction Inner(Self);
948 Self.ConsumeAndStoreUntil(EndKind, Toks, true, /*ConsumeFinalToken*/false);
949 Inner.Revert();
950 }
951
952 void RevertAnnotations() {
953 Revert();
954
955 // Put back the original tokens.
Alexey Bataevee6507d2013-11-18 08:17:37 +0000956 Self.SkipUntil(EndKind, StopAtSemi | StopBeforeMatch);
Richard Smith1fff95c2013-09-12 23:28:08 +0000957 if (Toks.size()) {
958 Token *Buffer = new Token[Toks.size()];
959 std::copy(Toks.begin() + 1, Toks.end(), Buffer);
960 Buffer[Toks.size() - 1] = Self.Tok;
961 Self.PP.EnterTokenStream(Buffer, Toks.size(), true, /*Owned*/true);
962
963 Self.Tok = Toks.front();
964 }
965 }
966
967private:
968 Parser &Self;
969 CachedTokens Toks;
970 tok::TokenKind EndKind;
971};
972
973/// ConsumeAndStoreInitializer - Consume and store the token at the passed token
974/// container until the end of the current initializer expression (either a
975/// default argument or an in-class initializer for a non-static data member).
Richard Smith95e1fb02014-08-27 03:23:12 +0000976///
977/// Returns \c true if we reached the end of something initializer-shaped,
978/// \c false if we bailed out.
Richard Smith1fff95c2013-09-12 23:28:08 +0000979bool Parser::ConsumeAndStoreInitializer(CachedTokens &Toks,
980 CachedInitKind CIK) {
981 // We always want this function to consume at least one token if not at EOF.
Richard Smith95e1fb02014-08-27 03:23:12 +0000982 bool IsFirstToken = true;
Richard Smith1fff95c2013-09-12 23:28:08 +0000983
984 // Number of possible unclosed <s we've seen so far. These might be templates,
985 // and might not, but if there were none of them (or we know for sure that
986 // we're within a template), we can avoid a tentative parse.
987 unsigned AngleCount = 0;
988 unsigned KnownTemplateCount = 0;
989
990 while (1) {
991 switch (Tok.getKind()) {
992 case tok::comma:
993 // If we might be in a template, perform a tentative parse to check.
994 if (!AngleCount)
995 // Not a template argument: this is the end of the initializer.
996 return true;
997 if (KnownTemplateCount)
998 goto consume_token;
999
1000 // We hit a comma inside angle brackets. This is the hard case. The
1001 // rule we follow is:
1002 // * For a default argument, if the tokens after the comma form a
1003 // syntactically-valid parameter-declaration-clause, in which each
1004 // parameter has an initializer, then this comma ends the default
1005 // argument.
1006 // * For a default initializer, if the tokens after the comma form a
1007 // syntactically-valid init-declarator-list, then this comma ends
1008 // the default initializer.
1009 {
1010 UnannotatedTentativeParsingAction PA(*this,
1011 CIK == CIK_DefaultInitializer
1012 ? tok::semi : tok::r_paren);
1013 Sema::TentativeAnalysisScope Scope(Actions);
1014
Richard Smithee390432014-05-16 01:56:53 +00001015 TPResult Result = TPResult::Error;
Richard Smith1fff95c2013-09-12 23:28:08 +00001016 ConsumeToken();
1017 switch (CIK) {
1018 case CIK_DefaultInitializer:
1019 Result = TryParseInitDeclaratorList();
1020 // If we parsed a complete, ambiguous init-declarator-list, this
1021 // is only syntactically-valid if it's followed by a semicolon.
Richard Smithee390432014-05-16 01:56:53 +00001022 if (Result == TPResult::Ambiguous && Tok.isNot(tok::semi))
1023 Result = TPResult::False;
Richard Smith1fff95c2013-09-12 23:28:08 +00001024 break;
1025
1026 case CIK_DefaultArgument:
1027 bool InvalidAsDeclaration = false;
1028 Result = TryParseParameterDeclarationClause(
Nico Weberc29c4832014-12-28 23:24:02 +00001029 &InvalidAsDeclaration, /*VersusTemplateArgument=*/true);
Richard Smith1fff95c2013-09-12 23:28:08 +00001030 // If this is an expression or a declaration with a missing
1031 // 'typename', assume it's not a declaration.
Richard Smithee390432014-05-16 01:56:53 +00001032 if (Result == TPResult::Ambiguous && InvalidAsDeclaration)
1033 Result = TPResult::False;
Richard Smith1fff95c2013-09-12 23:28:08 +00001034 break;
1035 }
1036
1037 // If what follows could be a declaration, it is a declaration.
Richard Smithee390432014-05-16 01:56:53 +00001038 if (Result != TPResult::False && Result != TPResult::Error) {
Richard Smith1fff95c2013-09-12 23:28:08 +00001039 PA.Revert();
1040 return true;
1041 }
1042
1043 // In the uncommon case that we decide the following tokens are part
1044 // of a template argument, revert any annotations we've performed in
1045 // those tokens. We're not going to look them up until we've parsed
1046 // the rest of the class, and that might add more declarations.
1047 PA.RevertAnnotations();
1048 }
1049
1050 // Keep going. We know we're inside a template argument list now.
1051 ++KnownTemplateCount;
1052 goto consume_token;
1053
1054 case tok::eof:
Richard Smith34f30512013-11-23 04:06:09 +00001055 case tok::annot_module_begin:
1056 case tok::annot_module_end:
1057 case tok::annot_module_include:
Richard Smith1fff95c2013-09-12 23:28:08 +00001058 // Ran out of tokens.
1059 return false;
1060
1061 case tok::less:
1062 // FIXME: A '<' can only start a template-id if it's preceded by an
1063 // identifier, an operator-function-id, or a literal-operator-id.
1064 ++AngleCount;
1065 goto consume_token;
1066
1067 case tok::question:
1068 // In 'a ? b : c', 'b' can contain an unparenthesized comma. If it does,
1069 // that is *never* the end of the initializer. Skip to the ':'.
1070 if (!ConsumeAndStoreConditional(Toks))
1071 return false;
1072 break;
1073
1074 case tok::greatergreatergreater:
1075 if (!getLangOpts().CPlusPlus11)
1076 goto consume_token;
1077 if (AngleCount) --AngleCount;
1078 if (KnownTemplateCount) --KnownTemplateCount;
1079 // Fall through.
1080 case tok::greatergreater:
1081 if (!getLangOpts().CPlusPlus11)
1082 goto consume_token;
1083 if (AngleCount) --AngleCount;
1084 if (KnownTemplateCount) --KnownTemplateCount;
1085 // Fall through.
1086 case tok::greater:
1087 if (AngleCount) --AngleCount;
1088 if (KnownTemplateCount) --KnownTemplateCount;
1089 goto consume_token;
1090
1091 case tok::kw_template:
1092 // 'template' identifier '<' is known to start a template argument list,
1093 // and can be used to disambiguate the parse.
1094 // FIXME: Support all forms of 'template' unqualified-id '<'.
1095 Toks.push_back(Tok);
1096 ConsumeToken();
1097 if (Tok.is(tok::identifier)) {
1098 Toks.push_back(Tok);
1099 ConsumeToken();
1100 if (Tok.is(tok::less)) {
Richard Smith93033572014-07-27 05:38:12 +00001101 ++AngleCount;
Richard Smith1fff95c2013-09-12 23:28:08 +00001102 ++KnownTemplateCount;
1103 Toks.push_back(Tok);
1104 ConsumeToken();
1105 }
1106 }
1107 break;
1108
1109 case tok::kw_operator:
1110 // If 'operator' precedes other punctuation, that punctuation loses
1111 // its special behavior.
1112 Toks.push_back(Tok);
1113 ConsumeToken();
1114 switch (Tok.getKind()) {
1115 case tok::comma:
1116 case tok::greatergreatergreater:
1117 case tok::greatergreater:
1118 case tok::greater:
1119 case tok::less:
1120 Toks.push_back(Tok);
1121 ConsumeToken();
1122 break;
1123 default:
1124 break;
1125 }
1126 break;
1127
1128 case tok::l_paren:
1129 // Recursively consume properly-nested parens.
1130 Toks.push_back(Tok);
1131 ConsumeParen();
1132 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
1133 break;
1134 case tok::l_square:
1135 // Recursively consume properly-nested square brackets.
1136 Toks.push_back(Tok);
1137 ConsumeBracket();
1138 ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false);
1139 break;
1140 case tok::l_brace:
1141 // Recursively consume properly-nested braces.
1142 Toks.push_back(Tok);
1143 ConsumeBrace();
1144 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1145 break;
1146
1147 // Okay, we found a ']' or '}' or ')', which we think should be balanced.
1148 // Since the user wasn't looking for this token (if they were, it would
1149 // already be handled), this isn't balanced. If there is a LHS token at a
1150 // higher level, we will assume that this matches the unbalanced token
Richard Smith95e1fb02014-08-27 03:23:12 +00001151 // and return it. Otherwise, this is a spurious RHS token, which we
1152 // consume and pass on to downstream code to diagnose.
Richard Smith1fff95c2013-09-12 23:28:08 +00001153 case tok::r_paren:
1154 if (CIK == CIK_DefaultArgument)
1155 return true; // End of the default argument.
Richard Smith95e1fb02014-08-27 03:23:12 +00001156 if (ParenCount && !IsFirstToken)
1157 return false;
1158 Toks.push_back(Tok);
1159 ConsumeParen();
1160 continue;
Richard Smith1fff95c2013-09-12 23:28:08 +00001161 case tok::r_square:
Richard Smith95e1fb02014-08-27 03:23:12 +00001162 if (BracketCount && !IsFirstToken)
1163 return false;
1164 Toks.push_back(Tok);
1165 ConsumeBracket();
1166 continue;
Richard Smith1fff95c2013-09-12 23:28:08 +00001167 case tok::r_brace:
Richard Smith95e1fb02014-08-27 03:23:12 +00001168 if (BraceCount && !IsFirstToken)
1169 return false;
1170 Toks.push_back(Tok);
1171 ConsumeBrace();
1172 continue;
Richard Smith1fff95c2013-09-12 23:28:08 +00001173
1174 case tok::code_completion:
1175 Toks.push_back(Tok);
1176 ConsumeCodeCompletionToken();
1177 break;
1178
1179 case tok::string_literal:
1180 case tok::wide_string_literal:
1181 case tok::utf8_string_literal:
1182 case tok::utf16_string_literal:
1183 case tok::utf32_string_literal:
1184 Toks.push_back(Tok);
1185 ConsumeStringToken();
1186 break;
1187 case tok::semi:
1188 if (CIK == CIK_DefaultInitializer)
1189 return true; // End of the default initializer.
1190 // FALL THROUGH.
1191 default:
1192 consume_token:
1193 Toks.push_back(Tok);
1194 ConsumeToken();
1195 break;
1196 }
Richard Smith95e1fb02014-08-27 03:23:12 +00001197 IsFirstToken = false;
Richard Smith1fff95c2013-09-12 23:28:08 +00001198 }
1199}