blob: 8469fb96911addf631d87b6adcbf643b9be98f1f [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());
221 Toks.push_back(Eof);
222}
223
Douglas Gregorefc46952010-10-12 16:25:54 +0000224Parser::LateParsedDeclaration::~LateParsedDeclaration() {}
225void Parser::LateParsedDeclaration::ParseLexedMethodDeclarations() {}
Richard Smith938f40b2011-06-11 17:19:42 +0000226void Parser::LateParsedDeclaration::ParseLexedMemberInitializers() {}
Douglas Gregorefc46952010-10-12 16:25:54 +0000227void Parser::LateParsedDeclaration::ParseLexedMethodDefs() {}
228
229Parser::LateParsedClass::LateParsedClass(Parser *P, ParsingClass *C)
230 : Self(P), Class(C) {}
231
232Parser::LateParsedClass::~LateParsedClass() {
233 Self->DeallocateParsedClasses(Class);
234}
235
236void Parser::LateParsedClass::ParseLexedMethodDeclarations() {
237 Self->ParseLexedMethodDeclarations(*Class);
238}
239
Richard Smith938f40b2011-06-11 17:19:42 +0000240void Parser::LateParsedClass::ParseLexedMemberInitializers() {
241 Self->ParseLexedMemberInitializers(*Class);
242}
243
Douglas Gregorefc46952010-10-12 16:25:54 +0000244void Parser::LateParsedClass::ParseLexedMethodDefs() {
245 Self->ParseLexedMethodDefs(*Class);
246}
247
248void Parser::LateParsedMethodDeclaration::ParseLexedMethodDeclarations() {
249 Self->ParseLexedMethodDeclaration(*this);
250}
251
252void Parser::LexedMethod::ParseLexedMethodDefs() {
253 Self->ParseLexedMethodDef(*this);
254}
255
Richard Smith938f40b2011-06-11 17:19:42 +0000256void Parser::LateParsedMemberInitializer::ParseLexedMemberInitializers() {
257 Self->ParseLexedMemberInitializer(*this);
258}
259
Douglas Gregor4d87df52008-12-16 21:30:33 +0000260/// ParseLexedMethodDeclarations - We finished parsing the member
261/// specification of a top (non-nested) C++ class. Now go over the
262/// stack of method declarations with some parts for which parsing was
263/// delayed (such as default arguments) and parse them.
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000264void Parser::ParseLexedMethodDeclarations(ParsingClass &Class) {
265 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
Nico Weber77c76c52014-05-10 17:43:15 +0000266 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
267 HasTemplateScope);
Richard Smithc8378952013-04-29 11:55:38 +0000268 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
269 if (HasTemplateScope) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000270 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
Richard Smithc8378952013-04-29 11:55:38 +0000271 ++CurTemplateDepthTracker;
272 }
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000273
John McCall6df5fef2009-12-19 10:49:29 +0000274 // The current scope is still active if we're the top-level class.
275 // Otherwise we'll need to push and enter a new scope.
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000276 bool HasClassScope = !Class.TopLevelClass;
Alexis Hunt1deb9722010-04-14 23:07:37 +0000277 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope,
278 HasClassScope);
John McCall6df5fef2009-12-19 10:49:29 +0000279 if (HasClassScope)
Nico Weber77c76c52014-05-10 17:43:15 +0000280 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(),
281 Class.TagOrTemplate);
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000282
Douglas Gregorefc46952010-10-12 16:25:54 +0000283 for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
284 Class.LateParsedDeclarations[i]->ParseLexedMethodDeclarations();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000285 }
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000286
John McCall6df5fef2009-12-19 10:49:29 +0000287 if (HasClassScope)
Nico Weber77c76c52014-05-10 17:43:15 +0000288 Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(),
289 Class.TagOrTemplate);
Douglas Gregor4d87df52008-12-16 21:30:33 +0000290}
291
Douglas Gregorefc46952010-10-12 16:25:54 +0000292void Parser::ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM) {
293 // If this is a member template, introduce the template parameter scope.
294 ParseScope TemplateScope(this, Scope::TemplateParamScope, LM.TemplateScope);
Richard Smithc8378952013-04-29 11:55:38 +0000295 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
296 if (LM.TemplateScope) {
Douglas Gregorefc46952010-10-12 16:25:54 +0000297 Actions.ActOnReenterTemplateScope(getCurScope(), LM.Method);
Richard Smithc8378952013-04-29 11:55:38 +0000298 ++CurTemplateDepthTracker;
299 }
Douglas Gregorefc46952010-10-12 16:25:54 +0000300 // Start the delayed C++ method declaration
301 Actions.ActOnStartDelayedCXXMethodDeclaration(getCurScope(), LM.Method);
302
303 // Introduce the parameters into scope and parse their default
304 // arguments.
Richard Smithe233fbf2013-01-28 22:42:45 +0000305 ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
306 Scope::FunctionDeclarationScope | Scope::DeclScope);
Douglas Gregorefc46952010-10-12 16:25:54 +0000307 for (unsigned I = 0, N = LM.DefaultArgs.size(); I != N; ++I) {
308 // Introduce the parameter into scope.
Nico Weber77c76c52014-05-10 17:43:15 +0000309 Actions.ActOnDelayedCXXMethodParameter(getCurScope(),
Douglas Gregor7fcbd902012-02-21 00:37:24 +0000310 LM.DefaultArgs[I].Param);
Douglas Gregorefc46952010-10-12 16:25:54 +0000311
312 if (CachedTokens *Toks = LM.DefaultArgs[I].Toks) {
313 // Save the current token position.
314 SourceLocation origLoc = Tok.getLocation();
315
316 // Parse the default argument from its saved token stream.
317 Toks->push_back(Tok); // So that the current token doesn't get lost
318 PP.EnterTokenStream(&Toks->front(), Toks->size(), true, false);
319
320 // Consume the previously-pushed token.
321 ConsumeAnyToken();
322
323 // Consume the '='.
324 assert(Tok.is(tok::equal) && "Default argument not starting with '='");
325 SourceLocation EqualLoc = ConsumeToken();
326
327 // The argument isn't actually potentially evaluated unless it is
328 // used.
329 EnterExpressionEvaluationContext Eval(Actions,
Douglas Gregor7fcbd902012-02-21 00:37:24 +0000330 Sema::PotentiallyEvaluatedIfUsed,
331 LM.DefaultArgs[I].Param);
Douglas Gregorefc46952010-10-12 16:25:54 +0000332
Sebastian Redldb63af22012-03-14 15:54:00 +0000333 ExprResult DefArgResult;
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000334 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
Sebastian Redl6db0b1b2012-03-20 21:24:03 +0000335 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
Sebastian Redldb63af22012-03-14 15:54:00 +0000336 DefArgResult = ParseBraceInitializer();
Sebastian Redl6db0b1b2012-03-20 21:24:03 +0000337 } else
Sebastian Redldb63af22012-03-14 15:54:00 +0000338 DefArgResult = ParseAssignmentExpression();
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000339 DefArgResult = Actions.CorrectDelayedTyposInExpr(DefArgResult);
Douglas Gregorefc46952010-10-12 16:25:54 +0000340 if (DefArgResult.isInvalid())
Serge Pavlovb4b35782014-07-22 01:54:49 +0000341 Actions.ActOnParamDefaultArgumentError(LM.DefaultArgs[I].Param,
342 EqualLoc);
Douglas Gregorefc46952010-10-12 16:25:54 +0000343 else {
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000344 if (!TryConsumeToken(tok::cxx_defaultarg_end)) {
Richard Smith1fff95c2013-09-12 23:28:08 +0000345 // The last two tokens are the terminator and the saved value of
346 // Tok; the last token in the default argument is the one before
347 // those.
348 assert(Toks->size() >= 3 && "expected a token in default arg");
349 Diag(Tok.getLocation(), diag::err_default_arg_unparsed)
350 << SourceRange(Tok.getLocation(),
351 (*Toks)[Toks->size() - 3].getLocation());
352 }
Douglas Gregorefc46952010-10-12 16:25:54 +0000353 Actions.ActOnParamDefaultArgument(LM.DefaultArgs[I].Param, EqualLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000354 DefArgResult.get());
Douglas Gregorefc46952010-10-12 16:25:54 +0000355 }
356
357 assert(!PP.getSourceManager().isBeforeInTranslationUnit(origLoc,
358 Tok.getLocation()) &&
359 "ParseAssignmentExpression went over the default arg tokens!");
360 // There could be leftover tokens (e.g. because of an error).
361 // Skip through until we reach the original token position.
362 while (Tok.getLocation() != origLoc && Tok.isNot(tok::eof))
363 ConsumeAnyToken();
364
365 delete Toks;
Craig Topper161e4db2014-05-21 06:02:52 +0000366 LM.DefaultArgs[I].Toks = nullptr;
Douglas Gregorefc46952010-10-12 16:25:54 +0000367 }
368 }
Douglas Gregor433e0532012-04-16 18:27:27 +0000369
Richard Smith0b3a4622014-11-13 20:01:57 +0000370 // Parse a delayed exception-specification, if there is one.
371 if (CachedTokens *Toks = LM.ExceptionSpecTokens) {
372 // Save the current token position.
373 SourceLocation origLoc = Tok.getLocation();
374
375 // Parse the default argument from its saved token stream.
376 Toks->push_back(Tok); // So that the current token doesn't get lost
377 PP.EnterTokenStream(&Toks->front(), Toks->size(), true, false);
378
379 // Consume the previously-pushed token.
380 ConsumeAnyToken();
381
382 // C++11 [expr.prim.general]p3:
383 // If a declaration declares a member function or member function
384 // template of a class X, the expression this is a prvalue of type
385 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
386 // and the end of the function-definition, member-declarator, or
387 // declarator.
388 CXXMethodDecl *Method;
389 if (FunctionTemplateDecl *FunTmpl
390 = dyn_cast<FunctionTemplateDecl>(LM.Method))
391 Method = cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
392 else
393 Method = cast<CXXMethodDecl>(LM.Method);
394
395 Sema::CXXThisScopeRAII ThisScope(Actions, Method->getParent(),
396 Method->getTypeQualifiers(),
397 getLangOpts().CPlusPlus11);
398
399 // Parse the exception-specification.
400 SourceRange SpecificationRange;
401 SmallVector<ParsedType, 4> DynamicExceptions;
402 SmallVector<SourceRange, 4> DynamicExceptionRanges;
403 ExprResult NoexceptExpr;
404 CachedTokens *ExceptionSpecTokens;
405
406 ExceptionSpecificationType EST
407 = tryParseExceptionSpecification(/*Delayed=*/false, SpecificationRange,
408 DynamicExceptions,
409 DynamicExceptionRanges, NoexceptExpr,
410 ExceptionSpecTokens);
411
412 // Clean up the remaining tokens.
413 if (Tok.is(tok::cxx_exceptspec_end))
414 ConsumeToken();
415 else if (EST != EST_None)
416 Diag(Tok.getLocation(), diag::err_except_spec_unparsed);
417
418 // Attach the exception-specification to the method.
419 if (EST != EST_None)
420 Actions.actOnDelayedExceptionSpecification(LM.Method, EST,
421 SpecificationRange,
422 DynamicExceptions,
423 DynamicExceptionRanges,
424 NoexceptExpr.isUsable()?
425 NoexceptExpr.get() : nullptr);
426
427 assert(!PP.getSourceManager().isBeforeInTranslationUnit(origLoc,
428 Tok.getLocation()) &&
429 "tryParseExceptionSpecification went over the exception tokens!");
430
431 // There could be leftover tokens (e.g. because of an error).
432 // Skip through until we reach the original token position.
433 while (Tok.getLocation() != origLoc && Tok.isNot(tok::eof))
434 ConsumeAnyToken();
435
436 delete Toks;
437 LM.ExceptionSpecTokens = nullptr;
438 }
439
Douglas Gregorefc46952010-10-12 16:25:54 +0000440 PrototypeScope.Exit();
441
442 // Finish the delayed C++ method declaration.
443 Actions.ActOnFinishDelayedCXXMethodDeclaration(getCurScope(), LM.Method);
444}
445
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000446/// ParseLexedMethodDefs - We finished parsing the member specification of a top
447/// (non-nested) C++ class. Now go over the stack of lexed methods that were
448/// collected during its parsing and parse them all.
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000449void Parser::ParseLexedMethodDefs(ParsingClass &Class) {
450 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
Douglas Gregorefc46952010-10-12 16:25:54 +0000451 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope, HasTemplateScope);
Richard Smithc8378952013-04-29 11:55:38 +0000452 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
453 if (HasTemplateScope) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000454 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
Richard Smithc8378952013-04-29 11:55:38 +0000455 ++CurTemplateDepthTracker;
456 }
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000457 bool HasClassScope = !Class.TopLevelClass;
458 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope,
459 HasClassScope);
460
Douglas Gregorefc46952010-10-12 16:25:54 +0000461 for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
462 Class.LateParsedDeclarations[i]->ParseLexedMethodDefs();
463 }
464}
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000465
Douglas Gregorefc46952010-10-12 16:25:54 +0000466void Parser::ParseLexedMethodDef(LexedMethod &LM) {
467 // If this is a member template, introduce the template parameter scope.
468 ParseScope TemplateScope(this, Scope::TemplateParamScope, LM.TemplateScope);
Richard Smithc8378952013-04-29 11:55:38 +0000469 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
470 if (LM.TemplateScope) {
Douglas Gregorefc46952010-10-12 16:25:54 +0000471 Actions.ActOnReenterTemplateScope(getCurScope(), LM.D);
Richard Smithc8378952013-04-29 11:55:38 +0000472 ++CurTemplateDepthTracker;
473 }
Douglas Gregorefc46952010-10-12 16:25:54 +0000474 // Save the current token position.
475 SourceLocation origLoc = Tok.getLocation();
Argyrios Kyrtzidis02041972010-03-31 00:38:09 +0000476
Douglas Gregorefc46952010-10-12 16:25:54 +0000477 assert(!LM.Toks.empty() && "Empty body!");
478 // Append the current token at the end of the new token stream so that it
479 // doesn't get lost.
480 LM.Toks.push_back(Tok);
481 PP.EnterTokenStream(LM.Toks.data(), LM.Toks.size(), true, false);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000482
Douglas Gregorefc46952010-10-12 16:25:54 +0000483 // Consume the previously pushed token.
Argyrios Kyrtzidisc36633c2013-03-27 23:58:17 +0000484 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
Douglas Gregorefc46952010-10-12 16:25:54 +0000485 assert((Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try))
486 && "Inline method not starting with '{', ':' or 'try'");
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000487
Douglas Gregorefc46952010-10-12 16:25:54 +0000488 // Parse the method body. Function body parsing code is similar enough
489 // to be re-used for method bodies as well.
490 ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope);
491 Actions.ActOnStartOfFunctionDef(getCurScope(), LM.D);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000492
Douglas Gregorefc46952010-10-12 16:25:54 +0000493 if (Tok.is(tok::kw_try)) {
Douglas Gregora0ff0c32011-03-16 17:05:57 +0000494 ParseFunctionTryBlock(LM.D, FnScope);
Douglas Gregorefc46952010-10-12 16:25:54 +0000495 assert(!PP.getSourceManager().isBeforeInTranslationUnit(origLoc,
496 Tok.getLocation()) &&
497 "ParseFunctionTryBlock went over the cached tokens!");
498 // There could be leftover tokens (e.g. because of an error).
499 // Skip through until we reach the original token position.
500 while (Tok.getLocation() != origLoc && Tok.isNot(tok::eof))
501 ConsumeAnyToken();
502 return;
503 }
504 if (Tok.is(tok::colon)) {
505 ParseConstructorInitializer(LM.D);
506
507 // Error recovery.
508 if (!Tok.is(tok::l_brace)) {
Douglas Gregora0ff0c32011-03-16 17:05:57 +0000509 FnScope.Exit();
Craig Topper161e4db2014-05-21 06:02:52 +0000510 Actions.ActOnFinishFunctionBody(LM.D, nullptr);
Matt Beaumont-Gayd0457922011-09-23 22:39:23 +0000511 while (Tok.getLocation() != origLoc && Tok.isNot(tok::eof))
512 ConsumeAnyToken();
Douglas Gregorefc46952010-10-12 16:25:54 +0000513 return;
514 }
515 } else
516 Actions.ActOnDefaultCtorInitializers(LM.D);
517
Richard Smithc8378952013-04-29 11:55:38 +0000518 assert((Actions.getDiagnostics().hasErrorOccurred() ||
519 !isa<FunctionTemplateDecl>(LM.D) ||
520 cast<FunctionTemplateDecl>(LM.D)->getTemplateParameters()->getDepth()
521 < TemplateParameterDepth) &&
522 "TemplateParameterDepth should be greater than the depth of "
523 "current template being instantiated!");
524
Douglas Gregora0ff0c32011-03-16 17:05:57 +0000525 ParseFunctionStatementBody(LM.D, FnScope);
Douglas Gregorefc46952010-10-12 16:25:54 +0000526
John McCalle68672f2013-03-14 05:13:41 +0000527 // Clear the late-template-parsed bit if we set it before.
Alp Tokera2794f92014-01-22 07:29:52 +0000528 if (LM.D)
529 LM.D->getAsFunction()->setLateTemplateParsed(false);
John McCalle68672f2013-03-14 05:13:41 +0000530
Douglas Gregorefc46952010-10-12 16:25:54 +0000531 if (Tok.getLocation() != origLoc) {
532 // Due to parsing error, we either went over the cached tokens or
533 // there are still cached tokens left. If it's the latter case skip the
534 // leftover tokens.
535 // Since this is an uncommon situation that should be avoided, use the
536 // expensive isBeforeInTranslationUnit call.
537 if (PP.getSourceManager().isBeforeInTranslationUnit(Tok.getLocation(),
538 origLoc))
Argyrios Kyrtzidise1224c82010-06-19 19:58:34 +0000539 while (Tok.getLocation() != origLoc && Tok.isNot(tok::eof))
Argyrios Kyrtzidise9b76af2010-06-17 10:52:22 +0000540 ConsumeAnyToken();
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000541 }
Hans Wennborga926d842014-05-23 20:37:38 +0000542
543 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(LM.D))
544 Actions.ActOnFinishInlineMethodDef(MD);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000545}
546
Richard Smith938f40b2011-06-11 17:19:42 +0000547/// ParseLexedMemberInitializers - We finished parsing the member specification
548/// of a top (non-nested) C++ class. Now go over the stack of lexed data member
549/// initializers that were collected during its parsing and parse them all.
550void Parser::ParseLexedMemberInitializers(ParsingClass &Class) {
551 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
552 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
553 HasTemplateScope);
Richard Smithc8378952013-04-29 11:55:38 +0000554 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
555 if (HasTemplateScope) {
Richard Smith938f40b2011-06-11 17:19:42 +0000556 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
Richard Smithc8378952013-04-29 11:55:38 +0000557 ++CurTemplateDepthTracker;
558 }
Douglas Gregor3024f072012-04-16 07:05:22 +0000559 // Set or update the scope flags.
Richard Smith938f40b2011-06-11 17:19:42 +0000560 bool AlreadyHasClassScope = Class.TopLevelClass;
Douglas Gregor3024f072012-04-16 07:05:22 +0000561 unsigned ScopeFlags = Scope::ClassScope|Scope::DeclScope;
Richard Smith938f40b2011-06-11 17:19:42 +0000562 ParseScope ClassScope(this, ScopeFlags, !AlreadyHasClassScope);
563 ParseScopeFlags ClassScopeFlags(this, ScopeFlags, AlreadyHasClassScope);
564
565 if (!AlreadyHasClassScope)
566 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(),
567 Class.TagOrTemplate);
568
Benjamin Kramer1d373c62012-05-17 12:01:52 +0000569 if (!Class.LateParsedDeclarations.empty()) {
Douglas Gregor3024f072012-04-16 07:05:22 +0000570 // C++11 [expr.prim.general]p4:
571 // Otherwise, if a member-declarator declares a non-static data member
572 // (9.2) of a class X, the expression this is a prvalue of type "pointer
573 // to X" within the optional brace-or-equal-initializer. It shall not
574 // appear elsewhere in the member-declarator.
575 Sema::CXXThisScopeRAII ThisScope(Actions, Class.TagOrTemplate,
576 /*TypeQuals=*/(unsigned)0);
Richard Smith938f40b2011-06-11 17:19:42 +0000577
Douglas Gregor3024f072012-04-16 07:05:22 +0000578 for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
579 Class.LateParsedDeclarations[i]->ParseLexedMemberInitializers();
580 }
581 }
582
Richard Smith938f40b2011-06-11 17:19:42 +0000583 if (!AlreadyHasClassScope)
584 Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(),
585 Class.TagOrTemplate);
586
587 Actions.ActOnFinishDelayedMemberInitializers(Class.TagOrTemplate);
588}
589
590void Parser::ParseLexedMemberInitializer(LateParsedMemberInitializer &MI) {
Richard Smith1a526fd2011-09-29 19:42:27 +0000591 if (!MI.Field || MI.Field->isInvalidDecl())
Richard Smith938f40b2011-06-11 17:19:42 +0000592 return;
593
594 // Append the current token at the end of the new token stream so that it
595 // doesn't get lost.
596 MI.Toks.push_back(Tok);
597 PP.EnterTokenStream(MI.Toks.data(), MI.Toks.size(), true, false);
598
599 // Consume the previously pushed token.
Argyrios Kyrtzidisc36633c2013-03-27 23:58:17 +0000600 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
Richard Smith938f40b2011-06-11 17:19:42 +0000601
602 SourceLocation EqualLoc;
Richard Smith2b013182012-06-10 03:12:00 +0000603
Richard Smith74108172014-01-17 03:11:34 +0000604 Actions.ActOnStartCXXInClassMemberInitializer();
605
Douglas Gregor926410d2012-02-21 02:22:07 +0000606 ExprResult Init = ParseCXXMemberInitializer(MI.Field, /*IsFunction=*/false,
607 EqualLoc);
Richard Smith938f40b2011-06-11 17:19:42 +0000608
Richard Smith74108172014-01-17 03:11:34 +0000609 Actions.ActOnFinishCXXInClassMemberInitializer(MI.Field, EqualLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000610 Init.get());
Richard Smith938f40b2011-06-11 17:19:42 +0000611
612 // The next token should be our artificial terminating EOF token.
613 if (Tok.isNot(tok::eof)) {
Richard Smith95e1fb02014-08-27 03:23:12 +0000614 if (!Init.isInvalid()) {
615 SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
616 if (!EndLoc.isValid())
617 EndLoc = Tok.getLocation();
618 // No fixit; we can't recover as if there were a semicolon here.
619 Diag(EndLoc, diag::err_expected_semi_decl_list);
620 }
Richard Smith938f40b2011-06-11 17:19:42 +0000621
622 // Consume tokens until we hit the artificial EOF.
623 while (Tok.isNot(tok::eof))
624 ConsumeAnyToken();
625 }
626 ConsumeAnyToken();
627}
628
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000629/// ConsumeAndStoreUntil - Consume and store the token at the passed token
Douglas Gregor4d87df52008-12-16 21:30:33 +0000630/// container until the token 'T' is reached (which gets
Mike Stump11289f42009-09-09 15:08:12 +0000631/// consumed/stored too, if ConsumeFinalToken).
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000632/// If StopAtSemi is true, then we will stop early at a ';' character.
Douglas Gregor4d87df52008-12-16 21:30:33 +0000633/// Returns true if token 'T1' or 'T2' was found.
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000634/// NOTE: This is a specialized version of Parser::SkipUntil.
Douglas Gregor4d87df52008-12-16 21:30:33 +0000635bool Parser::ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
636 CachedTokens &Toks,
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000637 bool StopAtSemi, bool ConsumeFinalToken) {
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000638 // We always want this function to consume at least one token if the first
639 // token isn't T and if not at EOF.
640 bool isFirstTokenConsumed = true;
641 while (1) {
642 // If we found one of the tokens, stop and return true.
Douglas Gregor4d87df52008-12-16 21:30:33 +0000643 if (Tok.is(T1) || Tok.is(T2)) {
644 if (ConsumeFinalToken) {
645 Toks.push_back(Tok);
646 ConsumeAnyToken();
647 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000648 return true;
649 }
650
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000651 switch (Tok.getKind()) {
652 case tok::eof:
Richard Smith34f30512013-11-23 04:06:09 +0000653 case tok::annot_module_begin:
654 case tok::annot_module_end:
655 case tok::annot_module_include:
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000656 // Ran out of tokens.
657 return false;
658
659 case tok::l_paren:
660 // Recursively consume properly-nested parens.
661 Toks.push_back(Tok);
662 ConsumeParen();
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000663 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000664 break;
665 case tok::l_square:
666 // Recursively consume properly-nested square brackets.
667 Toks.push_back(Tok);
668 ConsumeBracket();
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000669 ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000670 break;
671 case tok::l_brace:
672 // Recursively consume properly-nested braces.
673 Toks.push_back(Tok);
674 ConsumeBrace();
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000675 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000676 break;
677
678 // Okay, we found a ']' or '}' or ')', which we think should be balanced.
679 // Since the user wasn't looking for this token (if they were, it would
680 // already be handled), this isn't balanced. If there is a LHS token at a
681 // higher level, we will assume that this matches the unbalanced token
682 // and return it. Otherwise, this is a spurious RHS token, which we skip.
683 case tok::r_paren:
684 if (ParenCount && !isFirstTokenConsumed)
685 return false; // Matches something.
686 Toks.push_back(Tok);
687 ConsumeParen();
688 break;
689 case tok::r_square:
690 if (BracketCount && !isFirstTokenConsumed)
691 return false; // Matches something.
692 Toks.push_back(Tok);
693 ConsumeBracket();
694 break;
695 case tok::r_brace:
696 if (BraceCount && !isFirstTokenConsumed)
697 return false; // Matches something.
698 Toks.push_back(Tok);
699 ConsumeBrace();
700 break;
701
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000702 case tok::code_completion:
703 Toks.push_back(Tok);
704 ConsumeCodeCompletionToken();
705 break;
706
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000707 case tok::string_literal:
708 case tok::wide_string_literal:
Douglas Gregorfb65e592011-07-27 05:40:30 +0000709 case tok::utf8_string_literal:
710 case tok::utf16_string_literal:
711 case tok::utf32_string_literal:
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000712 Toks.push_back(Tok);
713 ConsumeStringToken();
714 break;
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000715 case tok::semi:
716 if (StopAtSemi)
717 return false;
718 // FALL THROUGH.
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000719 default:
720 // consume this token.
721 Toks.push_back(Tok);
722 ConsumeToken();
723 break;
724 }
725 isFirstTokenConsumed = false;
726 }
727}
Sebastian Redla74948d2011-09-24 17:48:25 +0000728
729/// \brief Consume tokens and store them in the passed token container until
730/// we've passed the try keyword and constructor initializers and have consumed
Sebastian Redl0d164012011-09-30 08:32:17 +0000731/// the opening brace of the function body. The opening brace will be consumed
732/// if and only if there was no error.
Sebastian Redla74948d2011-09-24 17:48:25 +0000733///
Richard Smithcde3fd82013-07-04 00:13:48 +0000734/// \return True on error.
Sebastian Redl0d164012011-09-30 08:32:17 +0000735bool Parser::ConsumeAndStoreFunctionPrologue(CachedTokens &Toks) {
Sebastian Redla74948d2011-09-24 17:48:25 +0000736 if (Tok.is(tok::kw_try)) {
737 Toks.push_back(Tok);
738 ConsumeToken();
739 }
Richard Smithcde3fd82013-07-04 00:13:48 +0000740
741 if (Tok.isNot(tok::colon)) {
742 // Easy case, just a function body.
743
744 // Grab any remaining garbage to be diagnosed later. We stop when we reach a
745 // brace: an opening one is the function body, while a closing one probably
746 // means we've reached the end of the class.
747 ConsumeAndStoreUntil(tok::l_brace, tok::r_brace, Toks,
748 /*StopAtSemi=*/true,
749 /*ConsumeFinalToken=*/false);
750 if (Tok.isNot(tok::l_brace))
Alp Tokerec543272013-12-24 09:48:30 +0000751 return Diag(Tok.getLocation(), diag::err_expected) << tok::l_brace;
Richard Smithcde3fd82013-07-04 00:13:48 +0000752
Sebastian Redla74948d2011-09-24 17:48:25 +0000753 Toks.push_back(Tok);
Richard Smithcde3fd82013-07-04 00:13:48 +0000754 ConsumeBrace();
755 return false;
Eli Friedman7cd4a9b2012-02-22 04:49:04 +0000756 }
Sebastian Redl0d164012011-09-30 08:32:17 +0000757
758 Toks.push_back(Tok);
Richard Smithcde3fd82013-07-04 00:13:48 +0000759 ConsumeToken();
760
761 // We can't reliably skip over a mem-initializer-id, because it could be
762 // a template-id involving not-yet-declared names. Given:
763 //
764 // S ( ) : a < b < c > ( e )
765 //
766 // 'e' might be an initializer or part of a template argument, depending
767 // on whether 'b' is a template.
768
769 // Track whether we might be inside a template argument. We can give
770 // significantly better diagnostics if we know that we're not.
771 bool MightBeTemplateArgument = false;
772
773 while (true) {
774 // Skip over the mem-initializer-id, if possible.
775 if (Tok.is(tok::kw_decltype)) {
776 Toks.push_back(Tok);
777 SourceLocation OpenLoc = ConsumeToken();
778 if (Tok.isNot(tok::l_paren))
779 return Diag(Tok.getLocation(), diag::err_expected_lparen_after)
780 << "decltype";
781 Toks.push_back(Tok);
782 ConsumeParen();
783 if (!ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/true)) {
Alp Tokerec543272013-12-24 09:48:30 +0000784 Diag(Tok.getLocation(), diag::err_expected) << tok::r_paren;
785 Diag(OpenLoc, diag::note_matching) << tok::l_paren;
Richard Smithcde3fd82013-07-04 00:13:48 +0000786 return true;
787 }
788 }
789 do {
790 // Walk over a component of a nested-name-specifier.
791 if (Tok.is(tok::coloncolon)) {
792 Toks.push_back(Tok);
793 ConsumeToken();
794
795 if (Tok.is(tok::kw_template)) {
796 Toks.push_back(Tok);
797 ConsumeToken();
798 }
799 }
800
801 if (Tok.is(tok::identifier) || Tok.is(tok::kw_template)) {
802 Toks.push_back(Tok);
803 ConsumeToken();
804 } else if (Tok.is(tok::code_completion)) {
805 Toks.push_back(Tok);
806 ConsumeCodeCompletionToken();
807 // Consume the rest of the initializers permissively.
808 // FIXME: We should be able to perform code-completion here even if
809 // there isn't a subsequent '{' token.
810 MightBeTemplateArgument = true;
811 break;
812 } else {
813 break;
814 }
815 } while (Tok.is(tok::coloncolon));
816
817 if (Tok.is(tok::less))
818 MightBeTemplateArgument = true;
819
820 if (MightBeTemplateArgument) {
821 // We may be inside a template argument list. Grab up to the start of the
822 // next parenthesized initializer or braced-init-list. This *might* be the
823 // initializer, or it might be a subexpression in the template argument
824 // list.
825 // FIXME: Count angle brackets, and clear MightBeTemplateArgument
826 // if all angles are closed.
827 if (!ConsumeAndStoreUntil(tok::l_paren, tok::l_brace, Toks,
828 /*StopAtSemi=*/true,
829 /*ConsumeFinalToken=*/false)) {
830 // We're not just missing the initializer, we're also missing the
831 // function body!
Alp Tokerec543272013-12-24 09:48:30 +0000832 return Diag(Tok.getLocation(), diag::err_expected) << tok::l_brace;
Richard Smithcde3fd82013-07-04 00:13:48 +0000833 }
834 } else if (Tok.isNot(tok::l_paren) && Tok.isNot(tok::l_brace)) {
835 // We found something weird in a mem-initializer-id.
Alp Tokerec543272013-12-24 09:48:30 +0000836 if (getLangOpts().CPlusPlus11)
837 return Diag(Tok.getLocation(), diag::err_expected_either)
838 << tok::l_paren << tok::l_brace;
839 else
840 return Diag(Tok.getLocation(), diag::err_expected) << tok::l_paren;
Richard Smithcde3fd82013-07-04 00:13:48 +0000841 }
842
843 tok::TokenKind kind = Tok.getKind();
844 Toks.push_back(Tok);
845 bool IsLParen = (kind == tok::l_paren);
846 SourceLocation OpenLoc = Tok.getLocation();
847
848 if (IsLParen) {
849 ConsumeParen();
850 } else {
851 assert(kind == tok::l_brace && "Must be left paren or brace here.");
852 ConsumeBrace();
853 // In C++03, this has to be the start of the function body, which
854 // means the initializer is malformed; we'll diagnose it later.
855 if (!getLangOpts().CPlusPlus11)
856 return false;
857 }
858
859 // Grab the initializer (or the subexpression of the template argument).
860 // FIXME: If we support lambdas here, we'll need to set StopAtSemi to false
861 // if we might be inside the braces of a lambda-expression.
Alp Tokerec543272013-12-24 09:48:30 +0000862 tok::TokenKind CloseKind = IsLParen ? tok::r_paren : tok::r_brace;
863 if (!ConsumeAndStoreUntil(CloseKind, Toks, /*StopAtSemi=*/true)) {
864 Diag(Tok, diag::err_expected) << CloseKind;
865 Diag(OpenLoc, diag::note_matching) << kind;
Richard Smithcde3fd82013-07-04 00:13:48 +0000866 return true;
867 }
868
869 // Grab pack ellipsis, if present.
870 if (Tok.is(tok::ellipsis)) {
871 Toks.push_back(Tok);
872 ConsumeToken();
873 }
874
875 // If we know we just consumed a mem-initializer, we must have ',' or '{'
876 // next.
877 if (Tok.is(tok::comma)) {
878 Toks.push_back(Tok);
879 ConsumeToken();
880 } else if (Tok.is(tok::l_brace)) {
881 // This is the function body if the ')' or '}' is immediately followed by
882 // a '{'. That cannot happen within a template argument, apart from the
883 // case where a template argument contains a compound literal:
884 //
885 // S ( ) : a < b < c > ( d ) { }
886 // // End of declaration, or still inside the template argument?
887 //
888 // ... and the case where the template argument contains a lambda:
889 //
890 // S ( ) : a < 0 && b < c > ( d ) + [ ] ( ) { return 0; }
891 // ( ) > ( ) { }
892 //
893 // FIXME: Disambiguate these cases. Note that the latter case is probably
894 // going to be made ill-formed by core issue 1607.
895 Toks.push_back(Tok);
896 ConsumeBrace();
897 return false;
898 } else if (!MightBeTemplateArgument) {
Alp Tokerec543272013-12-24 09:48:30 +0000899 return Diag(Tok.getLocation(), diag::err_expected_either) << tok::l_brace
900 << tok::comma;
Richard Smithcde3fd82013-07-04 00:13:48 +0000901 }
902 }
Sebastian Redla74948d2011-09-24 17:48:25 +0000903}
Richard Smith1fff95c2013-09-12 23:28:08 +0000904
905/// \brief Consume and store tokens from the '?' to the ':' in a conditional
906/// expression.
907bool Parser::ConsumeAndStoreConditional(CachedTokens &Toks) {
908 // Consume '?'.
909 assert(Tok.is(tok::question));
910 Toks.push_back(Tok);
911 ConsumeToken();
912
913 while (Tok.isNot(tok::colon)) {
Nico Weber77c76c52014-05-10 17:43:15 +0000914 if (!ConsumeAndStoreUntil(tok::question, tok::colon, Toks,
915 /*StopAtSemi=*/true,
916 /*ConsumeFinalToken=*/false))
Richard Smith1fff95c2013-09-12 23:28:08 +0000917 return false;
918
919 // If we found a nested conditional, consume it.
920 if (Tok.is(tok::question) && !ConsumeAndStoreConditional(Toks))
921 return false;
922 }
923
924 // Consume ':'.
925 Toks.push_back(Tok);
926 ConsumeToken();
927 return true;
928}
929
930/// \brief A tentative parsing action that can also revert token annotations.
931class Parser::UnannotatedTentativeParsingAction : public TentativeParsingAction {
932public:
933 explicit UnannotatedTentativeParsingAction(Parser &Self,
934 tok::TokenKind EndKind)
935 : TentativeParsingAction(Self), Self(Self), EndKind(EndKind) {
936 // Stash away the old token stream, so we can restore it once the
937 // tentative parse is complete.
938 TentativeParsingAction Inner(Self);
939 Self.ConsumeAndStoreUntil(EndKind, Toks, true, /*ConsumeFinalToken*/false);
940 Inner.Revert();
941 }
942
943 void RevertAnnotations() {
944 Revert();
945
946 // Put back the original tokens.
Alexey Bataevee6507d2013-11-18 08:17:37 +0000947 Self.SkipUntil(EndKind, StopAtSemi | StopBeforeMatch);
Richard Smith1fff95c2013-09-12 23:28:08 +0000948 if (Toks.size()) {
949 Token *Buffer = new Token[Toks.size()];
950 std::copy(Toks.begin() + 1, Toks.end(), Buffer);
951 Buffer[Toks.size() - 1] = Self.Tok;
952 Self.PP.EnterTokenStream(Buffer, Toks.size(), true, /*Owned*/true);
953
954 Self.Tok = Toks.front();
955 }
956 }
957
958private:
959 Parser &Self;
960 CachedTokens Toks;
961 tok::TokenKind EndKind;
962};
963
964/// ConsumeAndStoreInitializer - Consume and store the token at the passed token
965/// container until the end of the current initializer expression (either a
966/// default argument or an in-class initializer for a non-static data member).
Richard Smith95e1fb02014-08-27 03:23:12 +0000967///
968/// Returns \c true if we reached the end of something initializer-shaped,
969/// \c false if we bailed out.
Richard Smith1fff95c2013-09-12 23:28:08 +0000970bool Parser::ConsumeAndStoreInitializer(CachedTokens &Toks,
971 CachedInitKind CIK) {
972 // We always want this function to consume at least one token if not at EOF.
Richard Smith95e1fb02014-08-27 03:23:12 +0000973 bool IsFirstToken = true;
Richard Smith1fff95c2013-09-12 23:28:08 +0000974
975 // Number of possible unclosed <s we've seen so far. These might be templates,
976 // and might not, but if there were none of them (or we know for sure that
977 // we're within a template), we can avoid a tentative parse.
978 unsigned AngleCount = 0;
979 unsigned KnownTemplateCount = 0;
980
981 while (1) {
982 switch (Tok.getKind()) {
983 case tok::comma:
984 // If we might be in a template, perform a tentative parse to check.
985 if (!AngleCount)
986 // Not a template argument: this is the end of the initializer.
987 return true;
988 if (KnownTemplateCount)
989 goto consume_token;
990
991 // We hit a comma inside angle brackets. This is the hard case. The
992 // rule we follow is:
993 // * For a default argument, if the tokens after the comma form a
994 // syntactically-valid parameter-declaration-clause, in which each
995 // parameter has an initializer, then this comma ends the default
996 // argument.
997 // * For a default initializer, if the tokens after the comma form a
998 // syntactically-valid init-declarator-list, then this comma ends
999 // the default initializer.
1000 {
1001 UnannotatedTentativeParsingAction PA(*this,
1002 CIK == CIK_DefaultInitializer
1003 ? tok::semi : tok::r_paren);
1004 Sema::TentativeAnalysisScope Scope(Actions);
1005
Richard Smithee390432014-05-16 01:56:53 +00001006 TPResult Result = TPResult::Error;
Richard Smith1fff95c2013-09-12 23:28:08 +00001007 ConsumeToken();
1008 switch (CIK) {
1009 case CIK_DefaultInitializer:
1010 Result = TryParseInitDeclaratorList();
1011 // If we parsed a complete, ambiguous init-declarator-list, this
1012 // is only syntactically-valid if it's followed by a semicolon.
Richard Smithee390432014-05-16 01:56:53 +00001013 if (Result == TPResult::Ambiguous && Tok.isNot(tok::semi))
1014 Result = TPResult::False;
Richard Smith1fff95c2013-09-12 23:28:08 +00001015 break;
1016
1017 case CIK_DefaultArgument:
1018 bool InvalidAsDeclaration = false;
1019 Result = TryParseParameterDeclarationClause(
1020 &InvalidAsDeclaration, /*VersusTemplateArgument*/true);
1021 // If this is an expression or a declaration with a missing
1022 // 'typename', assume it's not a declaration.
Richard Smithee390432014-05-16 01:56:53 +00001023 if (Result == TPResult::Ambiguous && InvalidAsDeclaration)
1024 Result = TPResult::False;
Richard Smith1fff95c2013-09-12 23:28:08 +00001025 break;
1026 }
1027
1028 // If what follows could be a declaration, it is a declaration.
Richard Smithee390432014-05-16 01:56:53 +00001029 if (Result != TPResult::False && Result != TPResult::Error) {
Richard Smith1fff95c2013-09-12 23:28:08 +00001030 PA.Revert();
1031 return true;
1032 }
1033
1034 // In the uncommon case that we decide the following tokens are part
1035 // of a template argument, revert any annotations we've performed in
1036 // those tokens. We're not going to look them up until we've parsed
1037 // the rest of the class, and that might add more declarations.
1038 PA.RevertAnnotations();
1039 }
1040
1041 // Keep going. We know we're inside a template argument list now.
1042 ++KnownTemplateCount;
1043 goto consume_token;
1044
1045 case tok::eof:
Richard Smith34f30512013-11-23 04:06:09 +00001046 case tok::annot_module_begin:
1047 case tok::annot_module_end:
1048 case tok::annot_module_include:
Richard Smith1fff95c2013-09-12 23:28:08 +00001049 // Ran out of tokens.
1050 return false;
1051
1052 case tok::less:
1053 // FIXME: A '<' can only start a template-id if it's preceded by an
1054 // identifier, an operator-function-id, or a literal-operator-id.
1055 ++AngleCount;
1056 goto consume_token;
1057
1058 case tok::question:
1059 // In 'a ? b : c', 'b' can contain an unparenthesized comma. If it does,
1060 // that is *never* the end of the initializer. Skip to the ':'.
1061 if (!ConsumeAndStoreConditional(Toks))
1062 return false;
1063 break;
1064
1065 case tok::greatergreatergreater:
1066 if (!getLangOpts().CPlusPlus11)
1067 goto consume_token;
1068 if (AngleCount) --AngleCount;
1069 if (KnownTemplateCount) --KnownTemplateCount;
1070 // Fall through.
1071 case tok::greatergreater:
1072 if (!getLangOpts().CPlusPlus11)
1073 goto consume_token;
1074 if (AngleCount) --AngleCount;
1075 if (KnownTemplateCount) --KnownTemplateCount;
1076 // Fall through.
1077 case tok::greater:
1078 if (AngleCount) --AngleCount;
1079 if (KnownTemplateCount) --KnownTemplateCount;
1080 goto consume_token;
1081
1082 case tok::kw_template:
1083 // 'template' identifier '<' is known to start a template argument list,
1084 // and can be used to disambiguate the parse.
1085 // FIXME: Support all forms of 'template' unqualified-id '<'.
1086 Toks.push_back(Tok);
1087 ConsumeToken();
1088 if (Tok.is(tok::identifier)) {
1089 Toks.push_back(Tok);
1090 ConsumeToken();
1091 if (Tok.is(tok::less)) {
Richard Smith93033572014-07-27 05:38:12 +00001092 ++AngleCount;
Richard Smith1fff95c2013-09-12 23:28:08 +00001093 ++KnownTemplateCount;
1094 Toks.push_back(Tok);
1095 ConsumeToken();
1096 }
1097 }
1098 break;
1099
1100 case tok::kw_operator:
1101 // If 'operator' precedes other punctuation, that punctuation loses
1102 // its special behavior.
1103 Toks.push_back(Tok);
1104 ConsumeToken();
1105 switch (Tok.getKind()) {
1106 case tok::comma:
1107 case tok::greatergreatergreater:
1108 case tok::greatergreater:
1109 case tok::greater:
1110 case tok::less:
1111 Toks.push_back(Tok);
1112 ConsumeToken();
1113 break;
1114 default:
1115 break;
1116 }
1117 break;
1118
1119 case tok::l_paren:
1120 // Recursively consume properly-nested parens.
1121 Toks.push_back(Tok);
1122 ConsumeParen();
1123 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
1124 break;
1125 case tok::l_square:
1126 // Recursively consume properly-nested square brackets.
1127 Toks.push_back(Tok);
1128 ConsumeBracket();
1129 ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false);
1130 break;
1131 case tok::l_brace:
1132 // Recursively consume properly-nested braces.
1133 Toks.push_back(Tok);
1134 ConsumeBrace();
1135 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1136 break;
1137
1138 // Okay, we found a ']' or '}' or ')', which we think should be balanced.
1139 // Since the user wasn't looking for this token (if they were, it would
1140 // already be handled), this isn't balanced. If there is a LHS token at a
1141 // higher level, we will assume that this matches the unbalanced token
Richard Smith95e1fb02014-08-27 03:23:12 +00001142 // and return it. Otherwise, this is a spurious RHS token, which we
1143 // consume and pass on to downstream code to diagnose.
Richard Smith1fff95c2013-09-12 23:28:08 +00001144 case tok::r_paren:
1145 if (CIK == CIK_DefaultArgument)
1146 return true; // End of the default argument.
Richard Smith95e1fb02014-08-27 03:23:12 +00001147 if (ParenCount && !IsFirstToken)
1148 return false;
1149 Toks.push_back(Tok);
1150 ConsumeParen();
1151 continue;
Richard Smith1fff95c2013-09-12 23:28:08 +00001152 case tok::r_square:
Richard Smith95e1fb02014-08-27 03:23:12 +00001153 if (BracketCount && !IsFirstToken)
1154 return false;
1155 Toks.push_back(Tok);
1156 ConsumeBracket();
1157 continue;
Richard Smith1fff95c2013-09-12 23:28:08 +00001158 case tok::r_brace:
Richard Smith95e1fb02014-08-27 03:23:12 +00001159 if (BraceCount && !IsFirstToken)
1160 return false;
1161 Toks.push_back(Tok);
1162 ConsumeBrace();
1163 continue;
Richard Smith1fff95c2013-09-12 23:28:08 +00001164
1165 case tok::code_completion:
1166 Toks.push_back(Tok);
1167 ConsumeCodeCompletionToken();
1168 break;
1169
1170 case tok::string_literal:
1171 case tok::wide_string_literal:
1172 case tok::utf8_string_literal:
1173 case tok::utf16_string_literal:
1174 case tok::utf32_string_literal:
1175 Toks.push_back(Tok);
1176 ConsumeStringToken();
1177 break;
1178 case tok::semi:
1179 if (CIK == CIK_DefaultInitializer)
1180 return true; // End of the default initializer.
1181 // FALL THROUGH.
1182 default:
1183 consume_token:
1184 Toks.push_back(Tok);
1185 ConsumeToken();
1186 break;
1187 }
Richard Smith95e1fb02014-08-27 03:23:12 +00001188 IsFirstToken = false;
Richard Smith1fff95c2013-09-12 23:28:08 +00001189 }
1190}