blob: ab1f97d31a6905f6d76634b3205b72abe6c4a007 [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,
Eli Bendersky41842222015-03-23 23:49:41 +000029 const VirtSpecifiers& VS,
Richard Smith9ba0fec2015-06-30 01:28:56 +000030 SourceLocation PureSpecLoc) {
Abramo Bagnara924a8f32010-12-10 16:29:40 +000031 assert(D.isFunctionDeclarator() && "This isn't a function declarator!");
Daniel Marjamakie59f8d72015-06-18 10:59:26 +000032 assert(Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try, tok::equal) &&
Alexis Hunt5a7fa252011-05-12 06:15:49 +000033 "Current token not a '{', ':', '=', or 'try'!");
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +000034
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000035 MultiTemplateParamsArg TemplateParams(
Craig Topper161e4db2014-05-21 06:02:52 +000036 TemplateInfo.TemplateParams ? TemplateInfo.TemplateParams->data()
37 : nullptr,
Nico Weber77c76c52014-05-10 17:43:15 +000038 TemplateInfo.TemplateParams ? TemplateInfo.TemplateParams->size() : 0);
Alexis Hunt1deb9722010-04-14 23:07:37 +000039
Rafael Espindolac2453dd2013-01-08 21:00:12 +000040 NamedDecl *FnD;
John McCall07e91c02009-08-06 02:15:43 +000041 if (D.getDeclSpec().isFriendSpecified())
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000042 FnD = Actions.ActOnFriendFunctionDecl(getCurScope(), D,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000043 TemplateParams);
Douglas Gregor728d00b2011-10-10 14:49:18 +000044 else {
Douglas Gregor0be31a22010-07-02 17:43:08 +000045 FnD = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS, D,
Craig Topper161e4db2014-05-21 06:02:52 +000046 TemplateParams, nullptr,
Richard Smith2b013182012-06-10 03:12:00 +000047 VS, ICIS_NoInit);
Douglas Gregor728d00b2011-10-10 14:49:18 +000048 if (FnD) {
Richard Smithf8a75c32013-08-29 00:47:48 +000049 Actions.ProcessDeclAttributeList(getCurScope(), FnD, AccessAttrs);
Richard Smith9ba0fec2015-06-30 01:28:56 +000050 if (PureSpecLoc.isValid())
51 Actions.ActOnPureSpecifier(FnD, PureSpecLoc);
Douglas Gregor728d00b2011-10-10 14:49:18 +000052 }
Nico Weber24b2a822011-01-28 06:07:34 +000053 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +000054
Douglas Gregor433e0532012-04-16 18:27:27 +000055 HandleMemberFunctionDeclDelays(D, FnD);
Eli Friedman3af2a772009-07-22 21:45:50 +000056
John McCallc1465822011-02-14 07:13:47 +000057 D.complete(FnD);
58
Alp Tokera3ebe6e2013-12-17 14:12:37 +000059 if (TryConsumeToken(tok::equal)) {
Richard Smith1c704732011-11-10 09:08:44 +000060 if (!FnD) {
61 SkipUntil(tok::semi);
Craig Topper161e4db2014-05-21 06:02:52 +000062 return nullptr;
Richard Smith1c704732011-11-10 09:08:44 +000063 }
64
Alexis Hunt5a7fa252011-05-12 06:15:49 +000065 bool Delete = false;
66 SourceLocation KWLoc;
Eli Bendersky5f4d76e2015-03-23 21:43:28 +000067 SourceLocation KWEndLoc = Tok.getEndLoc().getLocWithOffset(-1);
Alp Tokera3ebe6e2013-12-17 14:12:37 +000068 if (TryConsumeToken(tok::kw_delete, KWLoc)) {
69 Diag(KWLoc, getLangOpts().CPlusPlus11
70 ? diag::warn_cxx98_compat_deleted_function
71 : diag::ext_deleted_function);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000072 Actions.SetDeclDeleted(FnD, KWLoc);
73 Delete = true;
Eli Bendersky5f4d76e2015-03-23 21:43:28 +000074 if (auto *DeclAsFunction = dyn_cast<FunctionDecl>(FnD)) {
75 DeclAsFunction->setRangeEnd(KWEndLoc);
76 }
Alp Tokera3ebe6e2013-12-17 14:12:37 +000077 } else if (TryConsumeToken(tok::kw_default, KWLoc)) {
78 Diag(KWLoc, getLangOpts().CPlusPlus11
79 ? diag::warn_cxx98_compat_defaulted_function
80 : diag::ext_defaulted_function);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000081 Actions.SetDeclDefaulted(FnD, KWLoc);
Eli Bendersky5f4d76e2015-03-23 21:43:28 +000082 if (auto *DeclAsFunction = dyn_cast<FunctionDecl>(FnD)) {
83 DeclAsFunction->setRangeEnd(KWEndLoc);
84 }
Alexis Hunt5a7fa252011-05-12 06:15:49 +000085 } 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 }
Eli Bendersky41842222015-03-23 23:49:41 +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 &&
Eli Bendersky41842222015-03-23 23:49:41 +0000105 D.getFunctionDefinitionKind() == 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) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000189 assert(Tok.isOneOf(tok::l_brace, tok::equal) &&
Richard Smith938f40b2011-06-11 17:19:42 +0000190 "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
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000225Parser::LateParsedDeclaration::~LateParsedDeclaration() {}
Douglas Gregorefc46952010-10-12 16:25:54 +0000226void 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) {
Nathan Sidwell5bb231c2015-02-19 14:03:22 +0000309 auto Param = cast<ParmVarDecl>(LM.DefaultArgs[I].Param);
Douglas Gregorefc46952010-10-12 16:25:54 +0000310 // Introduce the parameter into scope.
Nathan Sidwell5bb231c2015-02-19 14:03:22 +0000311 bool HasUnparsed = Param->hasUnparsedDefaultArg();
Nathan Sidwell55d53fe2015-01-30 14:21:35 +0000312 Actions.ActOnDelayedCXXMethodParameter(getCurScope(), Param);
Douglas Gregorefc46952010-10-12 16:25:54 +0000313 if (CachedTokens *Toks = LM.DefaultArgs[I].Toks) {
David Majnemer7cceba52015-01-13 04:20:57 +0000314 // Mark the end of the default argument so that we know when to stop when
315 // we parse it later on.
316 Token LastDefaultArgToken = Toks->back();
317 Token DefArgEnd;
318 DefArgEnd.startToken();
319 DefArgEnd.setKind(tok::eof);
David Majnemera8f2f1d2015-03-19 00:10:23 +0000320 DefArgEnd.setLocation(LastDefaultArgToken.getEndLoc());
Nathan Sidwell55d53fe2015-01-30 14:21:35 +0000321 DefArgEnd.setEofData(Param);
David Majnemer7cceba52015-01-13 04:20:57 +0000322 Toks->push_back(DefArgEnd);
Douglas Gregorefc46952010-10-12 16:25:54 +0000323
324 // Parse the default argument from its saved token stream.
325 Toks->push_back(Tok); // So that the current token doesn't get lost
326 PP.EnterTokenStream(&Toks->front(), Toks->size(), true, false);
327
328 // Consume the previously-pushed token.
329 ConsumeAnyToken();
330
331 // Consume the '='.
332 assert(Tok.is(tok::equal) && "Default argument not starting with '='");
333 SourceLocation EqualLoc = ConsumeToken();
334
335 // The argument isn't actually potentially evaluated unless it is
336 // used.
337 EnterExpressionEvaluationContext Eval(Actions,
Douglas Gregor7fcbd902012-02-21 00:37:24 +0000338 Sema::PotentiallyEvaluatedIfUsed,
Nathan Sidwell55d53fe2015-01-30 14:21:35 +0000339 Param);
Douglas Gregorefc46952010-10-12 16:25:54 +0000340
Sebastian Redldb63af22012-03-14 15:54:00 +0000341 ExprResult DefArgResult;
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000342 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
Sebastian Redl6db0b1b2012-03-20 21:24:03 +0000343 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
Sebastian Redldb63af22012-03-14 15:54:00 +0000344 DefArgResult = ParseBraceInitializer();
Sebastian Redl6db0b1b2012-03-20 21:24:03 +0000345 } else
Sebastian Redldb63af22012-03-14 15:54:00 +0000346 DefArgResult = ParseAssignmentExpression();
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000347 DefArgResult = Actions.CorrectDelayedTyposInExpr(DefArgResult);
David Majnemerbba12342015-01-12 06:51:15 +0000348 if (DefArgResult.isInvalid()) {
Nathan Sidwell55d53fe2015-01-30 14:21:35 +0000349 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
David Majnemerbba12342015-01-12 06:51:15 +0000350 } else {
Nathan Sidwell55d53fe2015-01-30 14:21:35 +0000351 if (Tok.isNot(tok::eof) || Tok.getEofData() != Param) {
Richard Smith1fff95c2013-09-12 23:28:08 +0000352 // The last two tokens are the terminator and the saved value of
353 // Tok; the last token in the default argument is the one before
354 // those.
355 assert(Toks->size() >= 3 && "expected a token in default arg");
356 Diag(Tok.getLocation(), diag::err_default_arg_unparsed)
357 << SourceRange(Tok.getLocation(),
358 (*Toks)[Toks->size() - 3].getLocation());
359 }
Nathan Sidwell55d53fe2015-01-30 14:21:35 +0000360 Actions.ActOnParamDefaultArgument(Param, EqualLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000361 DefArgResult.get());
Douglas Gregorefc46952010-10-12 16:25:54 +0000362 }
363
Douglas Gregorefc46952010-10-12 16:25:54 +0000364 // There could be leftover tokens (e.g. because of an error).
David Majnemer7cceba52015-01-13 04:20:57 +0000365 // Skip through until we reach the 'end of default argument' token.
366 while (Tok.isNot(tok::eof))
Douglas Gregorefc46952010-10-12 16:25:54 +0000367 ConsumeAnyToken();
David Majnemer7cceba52015-01-13 04:20:57 +0000368
Nathan Sidwell55d53fe2015-01-30 14:21:35 +0000369 if (Tok.is(tok::eof) && Tok.getEofData() == Param)
David Majnemer7cceba52015-01-13 04:20:57 +0000370 ConsumeAnyToken();
Douglas Gregorefc46952010-10-12 16:25:54 +0000371
372 delete Toks;
Craig Topper161e4db2014-05-21 06:02:52 +0000373 LM.DefaultArgs[I].Toks = nullptr;
Nathan Sidwell5bb231c2015-02-19 14:03:22 +0000374 } else if (HasUnparsed) {
375 assert(Param->hasInheritedDefaultArg());
376 FunctionDecl *Old = cast<FunctionDecl>(LM.Method)->getPreviousDecl();
377 ParmVarDecl *OldParam = Old->getParamDecl(I);
378 assert (!OldParam->hasUnparsedDefaultArg());
379 if (OldParam->hasUninstantiatedDefaultArg())
380 Param->setUninstantiatedDefaultArg(
381 Param->getUninstantiatedDefaultArg());
382 else
383 Param->setDefaultArg(OldParam->getInit());
Douglas Gregorefc46952010-10-12 16:25:54 +0000384 }
385 }
Douglas Gregor433e0532012-04-16 18:27:27 +0000386
Richard Smith0b3a4622014-11-13 20:01:57 +0000387 // Parse a delayed exception-specification, if there is one.
388 if (CachedTokens *Toks = LM.ExceptionSpecTokens) {
David Majnemer7cceba52015-01-13 04:20:57 +0000389 // Add the 'stop' token.
390 Token LastExceptionSpecToken = Toks->back();
391 Token ExceptionSpecEnd;
392 ExceptionSpecEnd.startToken();
393 ExceptionSpecEnd.setKind(tok::eof);
David Majnemera8f2f1d2015-03-19 00:10:23 +0000394 ExceptionSpecEnd.setLocation(LastExceptionSpecToken.getEndLoc());
David Majnemer7cceba52015-01-13 04:20:57 +0000395 ExceptionSpecEnd.setEofData(LM.Method);
396 Toks->push_back(ExceptionSpecEnd);
Richard Smith0b3a4622014-11-13 20:01:57 +0000397
398 // Parse the default argument from its saved token stream.
399 Toks->push_back(Tok); // So that the current token doesn't get lost
400 PP.EnterTokenStream(&Toks->front(), Toks->size(), true, false);
401
402 // Consume the previously-pushed token.
403 ConsumeAnyToken();
404
405 // C++11 [expr.prim.general]p3:
406 // If a declaration declares a member function or member function
407 // template of a class X, the expression this is a prvalue of type
408 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
409 // and the end of the function-definition, member-declarator, or
410 // declarator.
411 CXXMethodDecl *Method;
412 if (FunctionTemplateDecl *FunTmpl
413 = dyn_cast<FunctionTemplateDecl>(LM.Method))
414 Method = cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
415 else
416 Method = cast<CXXMethodDecl>(LM.Method);
417
418 Sema::CXXThisScopeRAII ThisScope(Actions, Method->getParent(),
419 Method->getTypeQualifiers(),
420 getLangOpts().CPlusPlus11);
421
422 // Parse the exception-specification.
423 SourceRange SpecificationRange;
424 SmallVector<ParsedType, 4> DynamicExceptions;
425 SmallVector<SourceRange, 4> DynamicExceptionRanges;
426 ExprResult NoexceptExpr;
427 CachedTokens *ExceptionSpecTokens;
428
429 ExceptionSpecificationType EST
430 = tryParseExceptionSpecification(/*Delayed=*/false, SpecificationRange,
431 DynamicExceptions,
432 DynamicExceptionRanges, NoexceptExpr,
433 ExceptionSpecTokens);
434
David Majnemer7cceba52015-01-13 04:20:57 +0000435 if (Tok.isNot(tok::eof) || Tok.getEofData() != LM.Method)
Richard Smith0b3a4622014-11-13 20:01:57 +0000436 Diag(Tok.getLocation(), diag::err_except_spec_unparsed);
437
438 // Attach the exception-specification to the method.
Richard Smith3ef3e892014-11-20 22:32:11 +0000439 Actions.actOnDelayedExceptionSpecification(LM.Method, EST,
440 SpecificationRange,
441 DynamicExceptions,
442 DynamicExceptionRanges,
443 NoexceptExpr.isUsable()?
444 NoexceptExpr.get() : nullptr);
Richard Smith0b3a4622014-11-13 20:01:57 +0000445
Richard Smith0b3a4622014-11-13 20:01:57 +0000446 // There could be leftover tokens (e.g. because of an error).
447 // Skip through until we reach the original token position.
David Majnemer7cceba52015-01-13 04:20:57 +0000448 while (Tok.isNot(tok::eof))
Richard Smith0b3a4622014-11-13 20:01:57 +0000449 ConsumeAnyToken();
David Majnemer7cceba52015-01-13 04:20:57 +0000450
451 // Clean up the remaining EOF token.
452 if (Tok.is(tok::eof) && Tok.getEofData() == LM.Method)
453 ConsumeAnyToken();
Richard Smith0b3a4622014-11-13 20:01:57 +0000454
455 delete Toks;
456 LM.ExceptionSpecTokens = nullptr;
457 }
458
Douglas Gregorefc46952010-10-12 16:25:54 +0000459 PrototypeScope.Exit();
460
461 // Finish the delayed C++ method declaration.
462 Actions.ActOnFinishDelayedCXXMethodDeclaration(getCurScope(), LM.Method);
463}
464
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000465/// ParseLexedMethodDefs - We finished parsing the member specification of a top
466/// (non-nested) C++ class. Now go over the stack of lexed methods that were
467/// collected during its parsing and parse them all.
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000468void Parser::ParseLexedMethodDefs(ParsingClass &Class) {
469 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
Douglas Gregorefc46952010-10-12 16:25:54 +0000470 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope, HasTemplateScope);
Richard Smithc8378952013-04-29 11:55:38 +0000471 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
472 if (HasTemplateScope) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000473 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
Richard Smithc8378952013-04-29 11:55:38 +0000474 ++CurTemplateDepthTracker;
475 }
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000476 bool HasClassScope = !Class.TopLevelClass;
477 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope,
478 HasClassScope);
479
Douglas Gregorefc46952010-10-12 16:25:54 +0000480 for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
481 Class.LateParsedDeclarations[i]->ParseLexedMethodDefs();
482 }
483}
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000484
Douglas Gregorefc46952010-10-12 16:25:54 +0000485void Parser::ParseLexedMethodDef(LexedMethod &LM) {
486 // If this is a member template, introduce the template parameter scope.
487 ParseScope TemplateScope(this, Scope::TemplateParamScope, LM.TemplateScope);
Richard Smithc8378952013-04-29 11:55:38 +0000488 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
489 if (LM.TemplateScope) {
Douglas Gregorefc46952010-10-12 16:25:54 +0000490 Actions.ActOnReenterTemplateScope(getCurScope(), LM.D);
Richard Smithc8378952013-04-29 11:55:38 +0000491 ++CurTemplateDepthTracker;
492 }
Argyrios Kyrtzidis02041972010-03-31 00:38:09 +0000493
Douglas Gregorefc46952010-10-12 16:25:54 +0000494 assert(!LM.Toks.empty() && "Empty body!");
David Majnemera7ea1b12015-01-13 05:06:20 +0000495 Token LastBodyToken = LM.Toks.back();
496 Token BodyEnd;
497 BodyEnd.startToken();
498 BodyEnd.setKind(tok::eof);
David Majnemera8f2f1d2015-03-19 00:10:23 +0000499 BodyEnd.setLocation(LastBodyToken.getEndLoc());
David Majnemera7ea1b12015-01-13 05:06:20 +0000500 BodyEnd.setEofData(LM.D);
501 LM.Toks.push_back(BodyEnd);
Douglas Gregorefc46952010-10-12 16:25:54 +0000502 // Append the current token at the end of the new token stream so that it
503 // doesn't get lost.
504 LM.Toks.push_back(Tok);
505 PP.EnterTokenStream(LM.Toks.data(), LM.Toks.size(), true, false);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000506
Douglas Gregorefc46952010-10-12 16:25:54 +0000507 // Consume the previously pushed token.
Argyrios Kyrtzidisc36633c2013-03-27 23:58:17 +0000508 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000509 assert(Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try)
Douglas Gregorefc46952010-10-12 16:25:54 +0000510 && "Inline method not starting with '{', ':' or 'try'");
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000511
Douglas Gregorefc46952010-10-12 16:25:54 +0000512 // Parse the method body. Function body parsing code is similar enough
513 // to be re-used for method bodies as well.
514 ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope);
515 Actions.ActOnStartOfFunctionDef(getCurScope(), LM.D);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000516
Douglas Gregorefc46952010-10-12 16:25:54 +0000517 if (Tok.is(tok::kw_try)) {
Douglas Gregora0ff0c32011-03-16 17:05:57 +0000518 ParseFunctionTryBlock(LM.D, FnScope);
David Majnemera7ea1b12015-01-13 05:06:20 +0000519
520 while (Tok.isNot(tok::eof))
521 ConsumeAnyToken();
522
523 if (Tok.is(tok::eof) && Tok.getEofData() == LM.D)
Douglas Gregorefc46952010-10-12 16:25:54 +0000524 ConsumeAnyToken();
525 return;
526 }
527 if (Tok.is(tok::colon)) {
528 ParseConstructorInitializer(LM.D);
529
530 // Error recovery.
531 if (!Tok.is(tok::l_brace)) {
Douglas Gregora0ff0c32011-03-16 17:05:57 +0000532 FnScope.Exit();
Craig Topper161e4db2014-05-21 06:02:52 +0000533 Actions.ActOnFinishFunctionBody(LM.D, nullptr);
David Majnemera7ea1b12015-01-13 05:06:20 +0000534
535 while (Tok.isNot(tok::eof))
536 ConsumeAnyToken();
537
538 if (Tok.is(tok::eof) && Tok.getEofData() == LM.D)
Matt Beaumont-Gayd0457922011-09-23 22:39:23 +0000539 ConsumeAnyToken();
Douglas Gregorefc46952010-10-12 16:25:54 +0000540 return;
541 }
542 } else
543 Actions.ActOnDefaultCtorInitializers(LM.D);
544
Richard Smithc8378952013-04-29 11:55:38 +0000545 assert((Actions.getDiagnostics().hasErrorOccurred() ||
546 !isa<FunctionTemplateDecl>(LM.D) ||
547 cast<FunctionTemplateDecl>(LM.D)->getTemplateParameters()->getDepth()
548 < TemplateParameterDepth) &&
549 "TemplateParameterDepth should be greater than the depth of "
550 "current template being instantiated!");
551
Douglas Gregora0ff0c32011-03-16 17:05:57 +0000552 ParseFunctionStatementBody(LM.D, FnScope);
Douglas Gregorefc46952010-10-12 16:25:54 +0000553
John McCalle68672f2013-03-14 05:13:41 +0000554 // Clear the late-template-parsed bit if we set it before.
Alp Tokera2794f92014-01-22 07:29:52 +0000555 if (LM.D)
556 LM.D->getAsFunction()->setLateTemplateParsed(false);
John McCalle68672f2013-03-14 05:13:41 +0000557
David Majnemera7ea1b12015-01-13 05:06:20 +0000558 while (Tok.isNot(tok::eof))
559 ConsumeAnyToken();
560
561 if (Tok.is(tok::eof) && Tok.getEofData() == LM.D)
562 ConsumeAnyToken();
Hans Wennborga926d842014-05-23 20:37:38 +0000563
564 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(LM.D))
565 Actions.ActOnFinishInlineMethodDef(MD);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000566}
567
Richard Smith938f40b2011-06-11 17:19:42 +0000568/// ParseLexedMemberInitializers - We finished parsing the member specification
569/// of a top (non-nested) C++ class. Now go over the stack of lexed data member
570/// initializers that were collected during its parsing and parse them all.
571void Parser::ParseLexedMemberInitializers(ParsingClass &Class) {
572 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
573 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
574 HasTemplateScope);
Richard Smithc8378952013-04-29 11:55:38 +0000575 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
576 if (HasTemplateScope) {
Richard Smith938f40b2011-06-11 17:19:42 +0000577 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
Richard Smithc8378952013-04-29 11:55:38 +0000578 ++CurTemplateDepthTracker;
579 }
Douglas Gregor3024f072012-04-16 07:05:22 +0000580 // Set or update the scope flags.
Richard Smith938f40b2011-06-11 17:19:42 +0000581 bool AlreadyHasClassScope = Class.TopLevelClass;
Douglas Gregor3024f072012-04-16 07:05:22 +0000582 unsigned ScopeFlags = Scope::ClassScope|Scope::DeclScope;
Richard Smith938f40b2011-06-11 17:19:42 +0000583 ParseScope ClassScope(this, ScopeFlags, !AlreadyHasClassScope);
584 ParseScopeFlags ClassScopeFlags(this, ScopeFlags, AlreadyHasClassScope);
585
586 if (!AlreadyHasClassScope)
587 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(),
588 Class.TagOrTemplate);
589
Benjamin Kramer1d373c62012-05-17 12:01:52 +0000590 if (!Class.LateParsedDeclarations.empty()) {
Douglas Gregor3024f072012-04-16 07:05:22 +0000591 // C++11 [expr.prim.general]p4:
592 // Otherwise, if a member-declarator declares a non-static data member
593 // (9.2) of a class X, the expression this is a prvalue of type "pointer
594 // to X" within the optional brace-or-equal-initializer. It shall not
595 // appear elsewhere in the member-declarator.
596 Sema::CXXThisScopeRAII ThisScope(Actions, Class.TagOrTemplate,
597 /*TypeQuals=*/(unsigned)0);
Richard Smith938f40b2011-06-11 17:19:42 +0000598
Douglas Gregor3024f072012-04-16 07:05:22 +0000599 for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
600 Class.LateParsedDeclarations[i]->ParseLexedMemberInitializers();
601 }
602 }
603
Richard Smith938f40b2011-06-11 17:19:42 +0000604 if (!AlreadyHasClassScope)
605 Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(),
606 Class.TagOrTemplate);
607
608 Actions.ActOnFinishDelayedMemberInitializers(Class.TagOrTemplate);
609}
610
611void Parser::ParseLexedMemberInitializer(LateParsedMemberInitializer &MI) {
Richard Smith1a526fd2011-09-29 19:42:27 +0000612 if (!MI.Field || MI.Field->isInvalidDecl())
Richard Smith938f40b2011-06-11 17:19:42 +0000613 return;
614
615 // Append the current token at the end of the new token stream so that it
616 // doesn't get lost.
617 MI.Toks.push_back(Tok);
618 PP.EnterTokenStream(MI.Toks.data(), MI.Toks.size(), true, false);
619
620 // Consume the previously pushed token.
Argyrios Kyrtzidisc36633c2013-03-27 23:58:17 +0000621 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
Richard Smith938f40b2011-06-11 17:19:42 +0000622
623 SourceLocation EqualLoc;
Richard Smith2b013182012-06-10 03:12:00 +0000624
Richard Smith74108172014-01-17 03:11:34 +0000625 Actions.ActOnStartCXXInClassMemberInitializer();
626
Douglas Gregor926410d2012-02-21 02:22:07 +0000627 ExprResult Init = ParseCXXMemberInitializer(MI.Field, /*IsFunction=*/false,
628 EqualLoc);
Richard Smith938f40b2011-06-11 17:19:42 +0000629
Richard Smith74108172014-01-17 03:11:34 +0000630 Actions.ActOnFinishCXXInClassMemberInitializer(MI.Field, EqualLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000631 Init.get());
Richard Smith938f40b2011-06-11 17:19:42 +0000632
633 // The next token should be our artificial terminating EOF token.
634 if (Tok.isNot(tok::eof)) {
Richard Smith95e1fb02014-08-27 03:23:12 +0000635 if (!Init.isInvalid()) {
636 SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
637 if (!EndLoc.isValid())
638 EndLoc = Tok.getLocation();
639 // No fixit; we can't recover as if there were a semicolon here.
640 Diag(EndLoc, diag::err_expected_semi_decl_list);
641 }
Richard Smith938f40b2011-06-11 17:19:42 +0000642
643 // Consume tokens until we hit the artificial EOF.
644 while (Tok.isNot(tok::eof))
645 ConsumeAnyToken();
646 }
David Majnemer2d3663e2014-12-18 09:57:31 +0000647 // Make sure this is *our* artificial EOF token.
David Majnemerce1d3012014-12-19 02:13:56 +0000648 if (Tok.getEofData() == MI.Field)
David Majnemer2d3663e2014-12-18 09:57:31 +0000649 ConsumeAnyToken();
Richard Smith938f40b2011-06-11 17:19:42 +0000650}
651
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000652/// ConsumeAndStoreUntil - Consume and store the token at the passed token
Douglas Gregor4d87df52008-12-16 21:30:33 +0000653/// container until the token 'T' is reached (which gets
Mike Stump11289f42009-09-09 15:08:12 +0000654/// consumed/stored too, if ConsumeFinalToken).
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000655/// If StopAtSemi is true, then we will stop early at a ';' character.
Douglas Gregor4d87df52008-12-16 21:30:33 +0000656/// Returns true if token 'T1' or 'T2' was found.
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000657/// NOTE: This is a specialized version of Parser::SkipUntil.
Douglas Gregor4d87df52008-12-16 21:30:33 +0000658bool Parser::ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
659 CachedTokens &Toks,
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000660 bool StopAtSemi, bool ConsumeFinalToken) {
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000661 // We always want this function to consume at least one token if the first
662 // token isn't T and if not at EOF.
663 bool isFirstTokenConsumed = true;
664 while (1) {
665 // If we found one of the tokens, stop and return true.
Douglas Gregor4d87df52008-12-16 21:30:33 +0000666 if (Tok.is(T1) || Tok.is(T2)) {
667 if (ConsumeFinalToken) {
668 Toks.push_back(Tok);
669 ConsumeAnyToken();
670 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000671 return true;
672 }
673
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000674 switch (Tok.getKind()) {
675 case tok::eof:
Richard Smith34f30512013-11-23 04:06:09 +0000676 case tok::annot_module_begin:
677 case tok::annot_module_end:
678 case tok::annot_module_include:
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000679 // Ran out of tokens.
680 return false;
681
682 case tok::l_paren:
683 // Recursively consume properly-nested parens.
684 Toks.push_back(Tok);
685 ConsumeParen();
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000686 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000687 break;
688 case tok::l_square:
689 // Recursively consume properly-nested square brackets.
690 Toks.push_back(Tok);
691 ConsumeBracket();
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000692 ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000693 break;
694 case tok::l_brace:
695 // Recursively consume properly-nested braces.
696 Toks.push_back(Tok);
697 ConsumeBrace();
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000698 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000699 break;
700
701 // Okay, we found a ']' or '}' or ')', which we think should be balanced.
702 // Since the user wasn't looking for this token (if they were, it would
703 // already be handled), this isn't balanced. If there is a LHS token at a
704 // higher level, we will assume that this matches the unbalanced token
705 // and return it. Otherwise, this is a spurious RHS token, which we skip.
706 case tok::r_paren:
707 if (ParenCount && !isFirstTokenConsumed)
708 return false; // Matches something.
709 Toks.push_back(Tok);
710 ConsumeParen();
711 break;
712 case tok::r_square:
713 if (BracketCount && !isFirstTokenConsumed)
714 return false; // Matches something.
715 Toks.push_back(Tok);
716 ConsumeBracket();
717 break;
718 case tok::r_brace:
719 if (BraceCount && !isFirstTokenConsumed)
720 return false; // Matches something.
721 Toks.push_back(Tok);
722 ConsumeBrace();
723 break;
724
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000725 case tok::code_completion:
726 Toks.push_back(Tok);
727 ConsumeCodeCompletionToken();
728 break;
729
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000730 case tok::string_literal:
731 case tok::wide_string_literal:
Douglas Gregorfb65e592011-07-27 05:40:30 +0000732 case tok::utf8_string_literal:
733 case tok::utf16_string_literal:
734 case tok::utf32_string_literal:
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000735 Toks.push_back(Tok);
736 ConsumeStringToken();
737 break;
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000738 case tok::semi:
739 if (StopAtSemi)
740 return false;
741 // FALL THROUGH.
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000742 default:
743 // consume this token.
744 Toks.push_back(Tok);
745 ConsumeToken();
746 break;
747 }
748 isFirstTokenConsumed = false;
749 }
750}
Sebastian Redla74948d2011-09-24 17:48:25 +0000751
752/// \brief Consume tokens and store them in the passed token container until
753/// we've passed the try keyword and constructor initializers and have consumed
Sebastian Redl0d164012011-09-30 08:32:17 +0000754/// the opening brace of the function body. The opening brace will be consumed
755/// if and only if there was no error.
Sebastian Redla74948d2011-09-24 17:48:25 +0000756///
Richard Smithcde3fd82013-07-04 00:13:48 +0000757/// \return True on error.
Sebastian Redl0d164012011-09-30 08:32:17 +0000758bool Parser::ConsumeAndStoreFunctionPrologue(CachedTokens &Toks) {
Sebastian Redla74948d2011-09-24 17:48:25 +0000759 if (Tok.is(tok::kw_try)) {
760 Toks.push_back(Tok);
761 ConsumeToken();
762 }
Richard Smithcde3fd82013-07-04 00:13:48 +0000763
764 if (Tok.isNot(tok::colon)) {
765 // Easy case, just a function body.
766
767 // Grab any remaining garbage to be diagnosed later. We stop when we reach a
768 // brace: an opening one is the function body, while a closing one probably
769 // means we've reached the end of the class.
770 ConsumeAndStoreUntil(tok::l_brace, tok::r_brace, Toks,
771 /*StopAtSemi=*/true,
772 /*ConsumeFinalToken=*/false);
773 if (Tok.isNot(tok::l_brace))
Alp Tokerec543272013-12-24 09:48:30 +0000774 return Diag(Tok.getLocation(), diag::err_expected) << tok::l_brace;
Richard Smithcde3fd82013-07-04 00:13:48 +0000775
Sebastian Redla74948d2011-09-24 17:48:25 +0000776 Toks.push_back(Tok);
Richard Smithcde3fd82013-07-04 00:13:48 +0000777 ConsumeBrace();
778 return false;
Eli Friedman7cd4a9b2012-02-22 04:49:04 +0000779 }
Sebastian Redl0d164012011-09-30 08:32:17 +0000780
781 Toks.push_back(Tok);
Richard Smithcde3fd82013-07-04 00:13:48 +0000782 ConsumeToken();
783
784 // We can't reliably skip over a mem-initializer-id, because it could be
785 // a template-id involving not-yet-declared names. Given:
786 //
787 // S ( ) : a < b < c > ( e )
788 //
789 // 'e' might be an initializer or part of a template argument, depending
790 // on whether 'b' is a template.
791
792 // Track whether we might be inside a template argument. We can give
793 // significantly better diagnostics if we know that we're not.
794 bool MightBeTemplateArgument = false;
795
796 while (true) {
797 // Skip over the mem-initializer-id, if possible.
798 if (Tok.is(tok::kw_decltype)) {
799 Toks.push_back(Tok);
800 SourceLocation OpenLoc = ConsumeToken();
801 if (Tok.isNot(tok::l_paren))
802 return Diag(Tok.getLocation(), diag::err_expected_lparen_after)
803 << "decltype";
804 Toks.push_back(Tok);
805 ConsumeParen();
806 if (!ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/true)) {
Alp Tokerec543272013-12-24 09:48:30 +0000807 Diag(Tok.getLocation(), diag::err_expected) << tok::r_paren;
808 Diag(OpenLoc, diag::note_matching) << tok::l_paren;
Richard Smithcde3fd82013-07-04 00:13:48 +0000809 return true;
810 }
811 }
812 do {
813 // Walk over a component of a nested-name-specifier.
814 if (Tok.is(tok::coloncolon)) {
815 Toks.push_back(Tok);
816 ConsumeToken();
817
818 if (Tok.is(tok::kw_template)) {
819 Toks.push_back(Tok);
820 ConsumeToken();
821 }
822 }
823
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000824 if (Tok.isOneOf(tok::identifier, tok::kw_template)) {
Richard Smithcde3fd82013-07-04 00:13:48 +0000825 Toks.push_back(Tok);
826 ConsumeToken();
827 } else if (Tok.is(tok::code_completion)) {
828 Toks.push_back(Tok);
829 ConsumeCodeCompletionToken();
830 // Consume the rest of the initializers permissively.
831 // FIXME: We should be able to perform code-completion here even if
832 // there isn't a subsequent '{' token.
833 MightBeTemplateArgument = true;
834 break;
835 } else {
836 break;
837 }
838 } while (Tok.is(tok::coloncolon));
839
840 if (Tok.is(tok::less))
841 MightBeTemplateArgument = true;
842
843 if (MightBeTemplateArgument) {
844 // We may be inside a template argument list. Grab up to the start of the
845 // next parenthesized initializer or braced-init-list. This *might* be the
846 // initializer, or it might be a subexpression in the template argument
847 // list.
848 // FIXME: Count angle brackets, and clear MightBeTemplateArgument
849 // if all angles are closed.
850 if (!ConsumeAndStoreUntil(tok::l_paren, tok::l_brace, Toks,
851 /*StopAtSemi=*/true,
852 /*ConsumeFinalToken=*/false)) {
853 // We're not just missing the initializer, we're also missing the
854 // function body!
Alp Tokerec543272013-12-24 09:48:30 +0000855 return Diag(Tok.getLocation(), diag::err_expected) << tok::l_brace;
Richard Smithcde3fd82013-07-04 00:13:48 +0000856 }
857 } else if (Tok.isNot(tok::l_paren) && Tok.isNot(tok::l_brace)) {
858 // We found something weird in a mem-initializer-id.
Alp Tokerec543272013-12-24 09:48:30 +0000859 if (getLangOpts().CPlusPlus11)
860 return Diag(Tok.getLocation(), diag::err_expected_either)
861 << tok::l_paren << tok::l_brace;
862 else
863 return Diag(Tok.getLocation(), diag::err_expected) << tok::l_paren;
Richard Smithcde3fd82013-07-04 00:13:48 +0000864 }
865
866 tok::TokenKind kind = Tok.getKind();
867 Toks.push_back(Tok);
868 bool IsLParen = (kind == tok::l_paren);
869 SourceLocation OpenLoc = Tok.getLocation();
870
871 if (IsLParen) {
872 ConsumeParen();
873 } else {
874 assert(kind == tok::l_brace && "Must be left paren or brace here.");
875 ConsumeBrace();
876 // In C++03, this has to be the start of the function body, which
877 // means the initializer is malformed; we'll diagnose it later.
878 if (!getLangOpts().CPlusPlus11)
879 return false;
880 }
881
882 // Grab the initializer (or the subexpression of the template argument).
883 // FIXME: If we support lambdas here, we'll need to set StopAtSemi to false
884 // if we might be inside the braces of a lambda-expression.
Alp Tokerec543272013-12-24 09:48:30 +0000885 tok::TokenKind CloseKind = IsLParen ? tok::r_paren : tok::r_brace;
886 if (!ConsumeAndStoreUntil(CloseKind, Toks, /*StopAtSemi=*/true)) {
887 Diag(Tok, diag::err_expected) << CloseKind;
888 Diag(OpenLoc, diag::note_matching) << kind;
Richard Smithcde3fd82013-07-04 00:13:48 +0000889 return true;
890 }
891
892 // Grab pack ellipsis, if present.
893 if (Tok.is(tok::ellipsis)) {
894 Toks.push_back(Tok);
895 ConsumeToken();
896 }
897
898 // If we know we just consumed a mem-initializer, we must have ',' or '{'
899 // next.
900 if (Tok.is(tok::comma)) {
901 Toks.push_back(Tok);
902 ConsumeToken();
903 } else if (Tok.is(tok::l_brace)) {
904 // This is the function body if the ')' or '}' is immediately followed by
905 // a '{'. That cannot happen within a template argument, apart from the
906 // case where a template argument contains a compound literal:
907 //
908 // S ( ) : a < b < c > ( d ) { }
909 // // End of declaration, or still inside the template argument?
910 //
911 // ... and the case where the template argument contains a lambda:
912 //
913 // S ( ) : a < 0 && b < c > ( d ) + [ ] ( ) { return 0; }
914 // ( ) > ( ) { }
915 //
916 // FIXME: Disambiguate these cases. Note that the latter case is probably
917 // going to be made ill-formed by core issue 1607.
918 Toks.push_back(Tok);
919 ConsumeBrace();
920 return false;
921 } else if (!MightBeTemplateArgument) {
Alp Tokerec543272013-12-24 09:48:30 +0000922 return Diag(Tok.getLocation(), diag::err_expected_either) << tok::l_brace
923 << tok::comma;
Richard Smithcde3fd82013-07-04 00:13:48 +0000924 }
925 }
Sebastian Redla74948d2011-09-24 17:48:25 +0000926}
Richard Smith1fff95c2013-09-12 23:28:08 +0000927
928/// \brief Consume and store tokens from the '?' to the ':' in a conditional
929/// expression.
930bool Parser::ConsumeAndStoreConditional(CachedTokens &Toks) {
931 // Consume '?'.
932 assert(Tok.is(tok::question));
933 Toks.push_back(Tok);
934 ConsumeToken();
935
936 while (Tok.isNot(tok::colon)) {
Nico Weber77c76c52014-05-10 17:43:15 +0000937 if (!ConsumeAndStoreUntil(tok::question, tok::colon, Toks,
938 /*StopAtSemi=*/true,
939 /*ConsumeFinalToken=*/false))
Richard Smith1fff95c2013-09-12 23:28:08 +0000940 return false;
941
942 // If we found a nested conditional, consume it.
943 if (Tok.is(tok::question) && !ConsumeAndStoreConditional(Toks))
944 return false;
945 }
946
947 // Consume ':'.
948 Toks.push_back(Tok);
949 ConsumeToken();
950 return true;
951}
952
953/// \brief A tentative parsing action that can also revert token annotations.
954class Parser::UnannotatedTentativeParsingAction : public TentativeParsingAction {
955public:
956 explicit UnannotatedTentativeParsingAction(Parser &Self,
957 tok::TokenKind EndKind)
958 : TentativeParsingAction(Self), Self(Self), EndKind(EndKind) {
959 // Stash away the old token stream, so we can restore it once the
960 // tentative parse is complete.
961 TentativeParsingAction Inner(Self);
962 Self.ConsumeAndStoreUntil(EndKind, Toks, true, /*ConsumeFinalToken*/false);
963 Inner.Revert();
964 }
965
966 void RevertAnnotations() {
967 Revert();
968
969 // Put back the original tokens.
Alexey Bataevee6507d2013-11-18 08:17:37 +0000970 Self.SkipUntil(EndKind, StopAtSemi | StopBeforeMatch);
Richard Smith1fff95c2013-09-12 23:28:08 +0000971 if (Toks.size()) {
972 Token *Buffer = new Token[Toks.size()];
973 std::copy(Toks.begin() + 1, Toks.end(), Buffer);
974 Buffer[Toks.size() - 1] = Self.Tok;
975 Self.PP.EnterTokenStream(Buffer, Toks.size(), true, /*Owned*/true);
976
977 Self.Tok = Toks.front();
978 }
979 }
980
981private:
982 Parser &Self;
983 CachedTokens Toks;
984 tok::TokenKind EndKind;
985};
986
987/// ConsumeAndStoreInitializer - Consume and store the token at the passed token
988/// container until the end of the current initializer expression (either a
989/// default argument or an in-class initializer for a non-static data member).
Richard Smith95e1fb02014-08-27 03:23:12 +0000990///
991/// Returns \c true if we reached the end of something initializer-shaped,
992/// \c false if we bailed out.
Richard Smith1fff95c2013-09-12 23:28:08 +0000993bool Parser::ConsumeAndStoreInitializer(CachedTokens &Toks,
994 CachedInitKind CIK) {
995 // We always want this function to consume at least one token if not at EOF.
Richard Smith95e1fb02014-08-27 03:23:12 +0000996 bool IsFirstToken = true;
Richard Smith1fff95c2013-09-12 23:28:08 +0000997
998 // Number of possible unclosed <s we've seen so far. These might be templates,
999 // and might not, but if there were none of them (or we know for sure that
1000 // we're within a template), we can avoid a tentative parse.
1001 unsigned AngleCount = 0;
1002 unsigned KnownTemplateCount = 0;
1003
1004 while (1) {
1005 switch (Tok.getKind()) {
1006 case tok::comma:
1007 // If we might be in a template, perform a tentative parse to check.
1008 if (!AngleCount)
1009 // Not a template argument: this is the end of the initializer.
1010 return true;
1011 if (KnownTemplateCount)
1012 goto consume_token;
1013
1014 // We hit a comma inside angle brackets. This is the hard case. The
1015 // rule we follow is:
1016 // * For a default argument, if the tokens after the comma form a
1017 // syntactically-valid parameter-declaration-clause, in which each
1018 // parameter has an initializer, then this comma ends the default
1019 // argument.
1020 // * For a default initializer, if the tokens after the comma form a
1021 // syntactically-valid init-declarator-list, then this comma ends
1022 // the default initializer.
1023 {
1024 UnannotatedTentativeParsingAction PA(*this,
1025 CIK == CIK_DefaultInitializer
1026 ? tok::semi : tok::r_paren);
1027 Sema::TentativeAnalysisScope Scope(Actions);
1028
Richard Smithee390432014-05-16 01:56:53 +00001029 TPResult Result = TPResult::Error;
Richard Smith1fff95c2013-09-12 23:28:08 +00001030 ConsumeToken();
1031 switch (CIK) {
1032 case CIK_DefaultInitializer:
1033 Result = TryParseInitDeclaratorList();
1034 // If we parsed a complete, ambiguous init-declarator-list, this
1035 // is only syntactically-valid if it's followed by a semicolon.
Richard Smithee390432014-05-16 01:56:53 +00001036 if (Result == TPResult::Ambiguous && Tok.isNot(tok::semi))
1037 Result = TPResult::False;
Richard Smith1fff95c2013-09-12 23:28:08 +00001038 break;
1039
1040 case CIK_DefaultArgument:
1041 bool InvalidAsDeclaration = false;
1042 Result = TryParseParameterDeclarationClause(
Nico Weberc29c4832014-12-28 23:24:02 +00001043 &InvalidAsDeclaration, /*VersusTemplateArgument=*/true);
Richard Smith1fff95c2013-09-12 23:28:08 +00001044 // If this is an expression or a declaration with a missing
1045 // 'typename', assume it's not a declaration.
Richard Smithee390432014-05-16 01:56:53 +00001046 if (Result == TPResult::Ambiguous && InvalidAsDeclaration)
1047 Result = TPResult::False;
Richard Smith1fff95c2013-09-12 23:28:08 +00001048 break;
1049 }
1050
1051 // If what follows could be a declaration, it is a declaration.
Richard Smithee390432014-05-16 01:56:53 +00001052 if (Result != TPResult::False && Result != TPResult::Error) {
Richard Smith1fff95c2013-09-12 23:28:08 +00001053 PA.Revert();
1054 return true;
1055 }
1056
1057 // In the uncommon case that we decide the following tokens are part
1058 // of a template argument, revert any annotations we've performed in
1059 // those tokens. We're not going to look them up until we've parsed
1060 // the rest of the class, and that might add more declarations.
1061 PA.RevertAnnotations();
1062 }
1063
1064 // Keep going. We know we're inside a template argument list now.
1065 ++KnownTemplateCount;
1066 goto consume_token;
1067
1068 case tok::eof:
Richard Smith34f30512013-11-23 04:06:09 +00001069 case tok::annot_module_begin:
1070 case tok::annot_module_end:
1071 case tok::annot_module_include:
Richard Smith1fff95c2013-09-12 23:28:08 +00001072 // Ran out of tokens.
1073 return false;
1074
1075 case tok::less:
1076 // FIXME: A '<' can only start a template-id if it's preceded by an
1077 // identifier, an operator-function-id, or a literal-operator-id.
1078 ++AngleCount;
1079 goto consume_token;
1080
1081 case tok::question:
1082 // In 'a ? b : c', 'b' can contain an unparenthesized comma. If it does,
1083 // that is *never* the end of the initializer. Skip to the ':'.
1084 if (!ConsumeAndStoreConditional(Toks))
1085 return false;
1086 break;
1087
1088 case tok::greatergreatergreater:
1089 if (!getLangOpts().CPlusPlus11)
1090 goto consume_token;
1091 if (AngleCount) --AngleCount;
1092 if (KnownTemplateCount) --KnownTemplateCount;
1093 // Fall through.
1094 case tok::greatergreater:
1095 if (!getLangOpts().CPlusPlus11)
1096 goto consume_token;
1097 if (AngleCount) --AngleCount;
1098 if (KnownTemplateCount) --KnownTemplateCount;
1099 // Fall through.
1100 case tok::greater:
1101 if (AngleCount) --AngleCount;
1102 if (KnownTemplateCount) --KnownTemplateCount;
1103 goto consume_token;
1104
1105 case tok::kw_template:
1106 // 'template' identifier '<' is known to start a template argument list,
1107 // and can be used to disambiguate the parse.
1108 // FIXME: Support all forms of 'template' unqualified-id '<'.
1109 Toks.push_back(Tok);
1110 ConsumeToken();
1111 if (Tok.is(tok::identifier)) {
1112 Toks.push_back(Tok);
1113 ConsumeToken();
1114 if (Tok.is(tok::less)) {
Richard Smith93033572014-07-27 05:38:12 +00001115 ++AngleCount;
Richard Smith1fff95c2013-09-12 23:28:08 +00001116 ++KnownTemplateCount;
1117 Toks.push_back(Tok);
1118 ConsumeToken();
1119 }
1120 }
1121 break;
1122
1123 case tok::kw_operator:
1124 // If 'operator' precedes other punctuation, that punctuation loses
1125 // its special behavior.
1126 Toks.push_back(Tok);
1127 ConsumeToken();
1128 switch (Tok.getKind()) {
1129 case tok::comma:
1130 case tok::greatergreatergreater:
1131 case tok::greatergreater:
1132 case tok::greater:
1133 case tok::less:
1134 Toks.push_back(Tok);
1135 ConsumeToken();
1136 break;
1137 default:
1138 break;
1139 }
1140 break;
1141
1142 case tok::l_paren:
1143 // Recursively consume properly-nested parens.
1144 Toks.push_back(Tok);
1145 ConsumeParen();
1146 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
1147 break;
1148 case tok::l_square:
1149 // Recursively consume properly-nested square brackets.
1150 Toks.push_back(Tok);
1151 ConsumeBracket();
1152 ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false);
1153 break;
1154 case tok::l_brace:
1155 // Recursively consume properly-nested braces.
1156 Toks.push_back(Tok);
1157 ConsumeBrace();
1158 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1159 break;
1160
1161 // Okay, we found a ']' or '}' or ')', which we think should be balanced.
1162 // Since the user wasn't looking for this token (if they were, it would
1163 // already be handled), this isn't balanced. If there is a LHS token at a
1164 // higher level, we will assume that this matches the unbalanced token
Richard Smith95e1fb02014-08-27 03:23:12 +00001165 // and return it. Otherwise, this is a spurious RHS token, which we
1166 // consume and pass on to downstream code to diagnose.
Richard Smith1fff95c2013-09-12 23:28:08 +00001167 case tok::r_paren:
1168 if (CIK == CIK_DefaultArgument)
1169 return true; // End of the default argument.
Richard Smith95e1fb02014-08-27 03:23:12 +00001170 if (ParenCount && !IsFirstToken)
1171 return false;
1172 Toks.push_back(Tok);
1173 ConsumeParen();
1174 continue;
Richard Smith1fff95c2013-09-12 23:28:08 +00001175 case tok::r_square:
Richard Smith95e1fb02014-08-27 03:23:12 +00001176 if (BracketCount && !IsFirstToken)
1177 return false;
1178 Toks.push_back(Tok);
1179 ConsumeBracket();
1180 continue;
Richard Smith1fff95c2013-09-12 23:28:08 +00001181 case tok::r_brace:
Richard Smith95e1fb02014-08-27 03:23:12 +00001182 if (BraceCount && !IsFirstToken)
1183 return false;
1184 Toks.push_back(Tok);
1185 ConsumeBrace();
1186 continue;
Richard Smith1fff95c2013-09-12 23:28:08 +00001187
1188 case tok::code_completion:
1189 Toks.push_back(Tok);
1190 ConsumeCodeCompletionToken();
1191 break;
1192
1193 case tok::string_literal:
1194 case tok::wide_string_literal:
1195 case tok::utf8_string_literal:
1196 case tok::utf16_string_literal:
1197 case tok::utf32_string_literal:
1198 Toks.push_back(Tok);
1199 ConsumeStringToken();
1200 break;
1201 case tok::semi:
1202 if (CIK == CIK_DefaultInitializer)
1203 return true; // End of the default initializer.
1204 // FALL THROUGH.
1205 default:
1206 consume_token:
1207 Toks.push_back(Tok);
1208 ConsumeToken();
1209 break;
1210 }
Richard Smith95e1fb02014-08-27 03:23:12 +00001211 IsFirstToken = false;
Richard Smith1fff95c2013-09-12 23:28:08 +00001212 }
1213}