blob: cd438f7437dffdc1c28c6905a5ff278ab241f8d2 [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;
Eli Bendersky5f4d76e2015-03-23 21:43:28 +000074 SourceLocation KWEndLoc = Tok.getEndLoc().getLocWithOffset(-1);
Alp Tokera3ebe6e2013-12-17 14:12:37 +000075 if (TryConsumeToken(tok::kw_delete, KWLoc)) {
76 Diag(KWLoc, getLangOpts().CPlusPlus11
77 ? diag::warn_cxx98_compat_deleted_function
78 : diag::ext_deleted_function);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000079 Actions.SetDeclDeleted(FnD, KWLoc);
80 Delete = true;
Eli Bendersky5f4d76e2015-03-23 21:43:28 +000081 if (auto *DeclAsFunction = dyn_cast<FunctionDecl>(FnD)) {
82 DeclAsFunction->setRangeEnd(KWEndLoc);
83 }
Alp Tokera3ebe6e2013-12-17 14:12:37 +000084 } else if (TryConsumeToken(tok::kw_default, KWLoc)) {
85 Diag(KWLoc, getLangOpts().CPlusPlus11
86 ? diag::warn_cxx98_compat_defaulted_function
87 : diag::ext_defaulted_function);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000088 Actions.SetDeclDefaulted(FnD, KWLoc);
Eli Bendersky5f4d76e2015-03-23 21:43:28 +000089 if (auto *DeclAsFunction = dyn_cast<FunctionDecl>(FnD)) {
90 DeclAsFunction->setRangeEnd(KWEndLoc);
91 }
Alexis Hunt5a7fa252011-05-12 06:15:49 +000092 } else {
93 llvm_unreachable("function definition after = not 'delete' or 'default'");
94 }
95
96 if (Tok.is(tok::comma)) {
97 Diag(KWLoc, diag::err_default_delete_in_multiple_declaration)
98 << Delete;
99 SkipUntil(tok::semi);
Alp Toker383d2c42014-01-01 03:08:43 +0000100 } else if (ExpectAndConsume(tok::semi, diag::err_expected_after,
101 Delete ? "delete" : "default")) {
102 SkipUntil(tok::semi);
Alexis Hunt5a7fa252011-05-12 06:15:49 +0000103 }
104
105 return FnD;
106 }
Faisal Valib96570332013-11-01 02:01:01 +0000107
Francois Pichet1c229c02011-04-22 22:18:13 +0000108 // In delayed template parsing mode, if we are within a class template
109 // or if we are about to parse function member template then consume
110 // the tokens and store them for parsing at the end of the translation unit.
David Majnemer90b17292013-09-14 05:46:42 +0000111 if (getLangOpts().DelayedTemplateParsing &&
112 DefinitionKind == FDK_Definition &&
Alp Tokera2794f92014-01-22 07:29:52 +0000113 !D.getDeclSpec().isConstexprSpecified() &&
114 !(FnD && FnD->getAsFunction() &&
Alp Toker314cc812014-01-25 16:55:45 +0000115 FnD->getAsFunction()->getReturnType()->getContainedAutoType()) &&
Francois Pichet1c229c02011-04-22 22:18:13 +0000116 ((Actions.CurContext->isDependentContext() ||
David Majnemer90b17292013-09-14 05:46:42 +0000117 (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
118 TemplateInfo.Kind != ParsedTemplateInfo::ExplicitSpecialization)) &&
119 !Actions.IsInsideALocalClassWithinATemplateFunction())) {
Francois Pichet1c229c02011-04-22 22:18:13 +0000120
Richard Smithe40f2ba2013-08-07 21:41:30 +0000121 CachedTokens Toks;
122 LexTemplateFunctionForLateParsing(Toks);
Francois Pichet1c229c02011-04-22 22:18:13 +0000123
Richard Smithe40f2ba2013-08-07 21:41:30 +0000124 if (FnD) {
Alp Tokera2794f92014-01-22 07:29:52 +0000125 FunctionDecl *FD = FnD->getAsFunction();
Chandler Carruthbc0f9ae2011-04-25 07:09:43 +0000126 Actions.CheckForFunctionRedefinition(FD);
Richard Smithe40f2ba2013-08-07 21:41:30 +0000127 Actions.MarkAsLateParsedTemplate(FD, FnD, Toks);
Francois Pichet1c229c02011-04-22 22:18:13 +0000128 }
129
130 return FnD;
131 }
132
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000133 // Consume the tokens and store them for later parsing.
134
Douglas Gregorefc46952010-10-12 16:25:54 +0000135 LexedMethod* LM = new LexedMethod(this, FnD);
136 getCurrentClass().LateParsedDeclarations.push_back(LM);
137 LM->TemplateScope = getCurScope()->isTemplateParamScope();
138 CachedTokens &Toks = LM->Toks;
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000139
Sebastian Redla7b98a72009-04-26 20:35:05 +0000140 tok::TokenKind kind = Tok.getKind();
Sebastian Redl0d164012011-09-30 08:32:17 +0000141 // Consume everything up to (and including) the left brace of the
142 // function body.
143 if (ConsumeAndStoreFunctionPrologue(Toks)) {
144 // We didn't find the left-brace we expected after the
Eli Friedman7cd4a9b2012-02-22 04:49:04 +0000145 // constructor initializer; we already printed an error, and it's likely
146 // impossible to recover, so don't try to parse this method later.
Richard Smithcde3fd82013-07-04 00:13:48 +0000147 // Skip over the rest of the decl and back to somewhere that looks
148 // reasonable.
149 SkipMalformedDecl();
Eli Friedman7cd4a9b2012-02-22 04:49:04 +0000150 delete getCurrentClass().LateParsedDeclarations.back();
151 getCurrentClass().LateParsedDeclarations.pop_back();
152 return FnD;
Douglas Gregore8381c02008-11-05 04:29:56 +0000153 } else {
Sebastian Redl0d164012011-09-30 08:32:17 +0000154 // Consume everything up to (and including) the matching right brace.
155 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
Douglas Gregore8381c02008-11-05 04:29:56 +0000156 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000157
Sebastian Redla7b98a72009-04-26 20:35:05 +0000158 // If we're in a function-try-block, we need to store all the catch blocks.
159 if (kind == tok::kw_try) {
160 while (Tok.is(tok::kw_catch)) {
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000161 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
162 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
Sebastian Redla7b98a72009-04-26 20:35:05 +0000163 }
164 }
165
Stephen Lin9354fc52013-06-23 07:37:13 +0000166 if (FnD) {
167 // If this is a friend function, mark that it's late-parsed so that
168 // it's still known to be a definition even before we attach the
169 // parsed body. Sema needs to treat friend function definitions
170 // differently during template instantiation, and it's possible for
171 // the containing class to be instantiated before all its member
172 // function definitions are parsed.
173 //
174 // If you remove this, you can remove the code that clears the flag
175 // after parsing the member.
176 if (D.getDeclSpec().isFriendSpecified()) {
Alp Tokera2794f92014-01-22 07:29:52 +0000177 FunctionDecl *FD = FnD->getAsFunction();
Alp Toker19bff322013-10-18 05:54:24 +0000178 Actions.CheckForFunctionRedefinition(FD);
179 FD->setLateTemplateParsed(true);
Stephen Lin9354fc52013-06-23 07:37:13 +0000180 }
181 } else {
Douglas Gregor6ca64102011-04-14 23:19:27 +0000182 // If semantic analysis could not build a function declaration,
183 // just throw away the late-parsed declaration.
184 delete getCurrentClass().LateParsedDeclarations.back();
185 getCurrentClass().LateParsedDeclarations.pop_back();
186 }
187
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000188 return FnD;
189}
190
Richard Smith938f40b2011-06-11 17:19:42 +0000191/// ParseCXXNonStaticMemberInitializer - We parsed and verified that the
192/// specified Declarator is a well formed C++ non-static data member
193/// declaration. Now lex its initializer and store its tokens for parsing
194/// after the class is complete.
195void Parser::ParseCXXNonStaticMemberInitializer(Decl *VarD) {
196 assert((Tok.is(tok::l_brace) || Tok.is(tok::equal)) &&
197 "Current token not a '{' or '='!");
198
199 LateParsedMemberInitializer *MI =
200 new LateParsedMemberInitializer(this, VarD);
201 getCurrentClass().LateParsedDeclarations.push_back(MI);
202 CachedTokens &Toks = MI->Toks;
203
204 tok::TokenKind kind = Tok.getKind();
205 if (kind == tok::equal) {
206 Toks.push_back(Tok);
Douglas Gregor0cf55e92012-03-08 01:00:17 +0000207 ConsumeToken();
Richard Smith938f40b2011-06-11 17:19:42 +0000208 }
209
210 if (kind == tok::l_brace) {
211 // Begin by storing the '{' token.
212 Toks.push_back(Tok);
213 ConsumeBrace();
214
215 // Consume everything up to (and including) the matching right brace.
216 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/true);
217 } else {
218 // Consume everything up to (but excluding) the comma or semicolon.
Richard Smith1fff95c2013-09-12 23:28:08 +0000219 ConsumeAndStoreInitializer(Toks, CIK_DefaultInitializer);
Richard Smith938f40b2011-06-11 17:19:42 +0000220 }
221
222 // Store an artificial EOF token to ensure that we don't run off the end of
223 // the initializer when we come to parse it.
224 Token Eof;
225 Eof.startToken();
226 Eof.setKind(tok::eof);
227 Eof.setLocation(Tok.getLocation());
David Majnemerce1d3012014-12-19 02:13:56 +0000228 Eof.setEofData(VarD);
Richard Smith938f40b2011-06-11 17:19:42 +0000229 Toks.push_back(Eof);
230}
231
Douglas Gregorefc46952010-10-12 16:25:54 +0000232Parser::LateParsedDeclaration::~LateParsedDeclaration() {}
233void Parser::LateParsedDeclaration::ParseLexedMethodDeclarations() {}
Richard Smith938f40b2011-06-11 17:19:42 +0000234void Parser::LateParsedDeclaration::ParseLexedMemberInitializers() {}
Douglas Gregorefc46952010-10-12 16:25:54 +0000235void Parser::LateParsedDeclaration::ParseLexedMethodDefs() {}
236
237Parser::LateParsedClass::LateParsedClass(Parser *P, ParsingClass *C)
238 : Self(P), Class(C) {}
239
240Parser::LateParsedClass::~LateParsedClass() {
241 Self->DeallocateParsedClasses(Class);
242}
243
244void Parser::LateParsedClass::ParseLexedMethodDeclarations() {
245 Self->ParseLexedMethodDeclarations(*Class);
246}
247
Richard Smith938f40b2011-06-11 17:19:42 +0000248void Parser::LateParsedClass::ParseLexedMemberInitializers() {
249 Self->ParseLexedMemberInitializers(*Class);
250}
251
Douglas Gregorefc46952010-10-12 16:25:54 +0000252void Parser::LateParsedClass::ParseLexedMethodDefs() {
253 Self->ParseLexedMethodDefs(*Class);
254}
255
256void Parser::LateParsedMethodDeclaration::ParseLexedMethodDeclarations() {
257 Self->ParseLexedMethodDeclaration(*this);
258}
259
260void Parser::LexedMethod::ParseLexedMethodDefs() {
261 Self->ParseLexedMethodDef(*this);
262}
263
Richard Smith938f40b2011-06-11 17:19:42 +0000264void Parser::LateParsedMemberInitializer::ParseLexedMemberInitializers() {
265 Self->ParseLexedMemberInitializer(*this);
266}
267
Douglas Gregor4d87df52008-12-16 21:30:33 +0000268/// ParseLexedMethodDeclarations - We finished parsing the member
269/// specification of a top (non-nested) C++ class. Now go over the
270/// stack of method declarations with some parts for which parsing was
271/// delayed (such as default arguments) and parse them.
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000272void Parser::ParseLexedMethodDeclarations(ParsingClass &Class) {
273 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
Nico Weber77c76c52014-05-10 17:43:15 +0000274 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
275 HasTemplateScope);
Richard Smithc8378952013-04-29 11:55:38 +0000276 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
277 if (HasTemplateScope) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000278 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
Richard Smithc8378952013-04-29 11:55:38 +0000279 ++CurTemplateDepthTracker;
280 }
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000281
John McCall6df5fef2009-12-19 10:49:29 +0000282 // The current scope is still active if we're the top-level class.
283 // Otherwise we'll need to push and enter a new scope.
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000284 bool HasClassScope = !Class.TopLevelClass;
Alexis Hunt1deb9722010-04-14 23:07:37 +0000285 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope,
286 HasClassScope);
John McCall6df5fef2009-12-19 10:49:29 +0000287 if (HasClassScope)
Nico Weber77c76c52014-05-10 17:43:15 +0000288 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(),
289 Class.TagOrTemplate);
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000290
Douglas Gregorefc46952010-10-12 16:25:54 +0000291 for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
292 Class.LateParsedDeclarations[i]->ParseLexedMethodDeclarations();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000293 }
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000294
John McCall6df5fef2009-12-19 10:49:29 +0000295 if (HasClassScope)
Nico Weber77c76c52014-05-10 17:43:15 +0000296 Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(),
297 Class.TagOrTemplate);
Douglas Gregor4d87df52008-12-16 21:30:33 +0000298}
299
Douglas Gregorefc46952010-10-12 16:25:54 +0000300void Parser::ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM) {
301 // If this is a member template, introduce the template parameter scope.
302 ParseScope TemplateScope(this, Scope::TemplateParamScope, LM.TemplateScope);
Richard Smithc8378952013-04-29 11:55:38 +0000303 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
304 if (LM.TemplateScope) {
Douglas Gregorefc46952010-10-12 16:25:54 +0000305 Actions.ActOnReenterTemplateScope(getCurScope(), LM.Method);
Richard Smithc8378952013-04-29 11:55:38 +0000306 ++CurTemplateDepthTracker;
307 }
Douglas Gregorefc46952010-10-12 16:25:54 +0000308 // Start the delayed C++ method declaration
309 Actions.ActOnStartDelayedCXXMethodDeclaration(getCurScope(), LM.Method);
310
311 // Introduce the parameters into scope and parse their default
312 // arguments.
Richard Smithe233fbf2013-01-28 22:42:45 +0000313 ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
314 Scope::FunctionDeclarationScope | Scope::DeclScope);
Douglas Gregorefc46952010-10-12 16:25:54 +0000315 for (unsigned I = 0, N = LM.DefaultArgs.size(); I != N; ++I) {
Nathan Sidwell5bb231c2015-02-19 14:03:22 +0000316 auto Param = cast<ParmVarDecl>(LM.DefaultArgs[I].Param);
Douglas Gregorefc46952010-10-12 16:25:54 +0000317 // Introduce the parameter into scope.
Nathan Sidwell5bb231c2015-02-19 14:03:22 +0000318 bool HasUnparsed = Param->hasUnparsedDefaultArg();
Nathan Sidwell55d53fe2015-01-30 14:21:35 +0000319 Actions.ActOnDelayedCXXMethodParameter(getCurScope(), Param);
Douglas Gregorefc46952010-10-12 16:25:54 +0000320 if (CachedTokens *Toks = LM.DefaultArgs[I].Toks) {
David Majnemer7cceba52015-01-13 04:20:57 +0000321 // Mark the end of the default argument so that we know when to stop when
322 // we parse it later on.
323 Token LastDefaultArgToken = Toks->back();
324 Token DefArgEnd;
325 DefArgEnd.startToken();
326 DefArgEnd.setKind(tok::eof);
David Majnemera8f2f1d2015-03-19 00:10:23 +0000327 DefArgEnd.setLocation(LastDefaultArgToken.getEndLoc());
Nathan Sidwell55d53fe2015-01-30 14:21:35 +0000328 DefArgEnd.setEofData(Param);
David Majnemer7cceba52015-01-13 04:20:57 +0000329 Toks->push_back(DefArgEnd);
Douglas Gregorefc46952010-10-12 16:25:54 +0000330
331 // Parse the default argument from its saved token stream.
332 Toks->push_back(Tok); // So that the current token doesn't get lost
333 PP.EnterTokenStream(&Toks->front(), Toks->size(), true, false);
334
335 // Consume the previously-pushed token.
336 ConsumeAnyToken();
337
338 // Consume the '='.
339 assert(Tok.is(tok::equal) && "Default argument not starting with '='");
340 SourceLocation EqualLoc = ConsumeToken();
341
342 // The argument isn't actually potentially evaluated unless it is
343 // used.
344 EnterExpressionEvaluationContext Eval(Actions,
Douglas Gregor7fcbd902012-02-21 00:37:24 +0000345 Sema::PotentiallyEvaluatedIfUsed,
Nathan Sidwell55d53fe2015-01-30 14:21:35 +0000346 Param);
Douglas Gregorefc46952010-10-12 16:25:54 +0000347
Sebastian Redldb63af22012-03-14 15:54:00 +0000348 ExprResult DefArgResult;
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000349 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
Sebastian Redl6db0b1b2012-03-20 21:24:03 +0000350 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
Sebastian Redldb63af22012-03-14 15:54:00 +0000351 DefArgResult = ParseBraceInitializer();
Sebastian Redl6db0b1b2012-03-20 21:24:03 +0000352 } else
Sebastian Redldb63af22012-03-14 15:54:00 +0000353 DefArgResult = ParseAssignmentExpression();
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000354 DefArgResult = Actions.CorrectDelayedTyposInExpr(DefArgResult);
David Majnemerbba12342015-01-12 06:51:15 +0000355 if (DefArgResult.isInvalid()) {
Nathan Sidwell55d53fe2015-01-30 14:21:35 +0000356 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
David Majnemerbba12342015-01-12 06:51:15 +0000357 } else {
Nathan Sidwell55d53fe2015-01-30 14:21:35 +0000358 if (Tok.isNot(tok::eof) || Tok.getEofData() != Param) {
Richard Smith1fff95c2013-09-12 23:28:08 +0000359 // The last two tokens are the terminator and the saved value of
360 // Tok; the last token in the default argument is the one before
361 // those.
362 assert(Toks->size() >= 3 && "expected a token in default arg");
363 Diag(Tok.getLocation(), diag::err_default_arg_unparsed)
364 << SourceRange(Tok.getLocation(),
365 (*Toks)[Toks->size() - 3].getLocation());
366 }
Nathan Sidwell55d53fe2015-01-30 14:21:35 +0000367 Actions.ActOnParamDefaultArgument(Param, EqualLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000368 DefArgResult.get());
Douglas Gregorefc46952010-10-12 16:25:54 +0000369 }
370
Douglas Gregorefc46952010-10-12 16:25:54 +0000371 // There could be leftover tokens (e.g. because of an error).
David Majnemer7cceba52015-01-13 04:20:57 +0000372 // Skip through until we reach the 'end of default argument' token.
373 while (Tok.isNot(tok::eof))
Douglas Gregorefc46952010-10-12 16:25:54 +0000374 ConsumeAnyToken();
David Majnemer7cceba52015-01-13 04:20:57 +0000375
Nathan Sidwell55d53fe2015-01-30 14:21:35 +0000376 if (Tok.is(tok::eof) && Tok.getEofData() == Param)
David Majnemer7cceba52015-01-13 04:20:57 +0000377 ConsumeAnyToken();
Douglas Gregorefc46952010-10-12 16:25:54 +0000378
379 delete Toks;
Craig Topper161e4db2014-05-21 06:02:52 +0000380 LM.DefaultArgs[I].Toks = nullptr;
Nathan Sidwell5bb231c2015-02-19 14:03:22 +0000381 } else if (HasUnparsed) {
382 assert(Param->hasInheritedDefaultArg());
383 FunctionDecl *Old = cast<FunctionDecl>(LM.Method)->getPreviousDecl();
384 ParmVarDecl *OldParam = Old->getParamDecl(I);
385 assert (!OldParam->hasUnparsedDefaultArg());
386 if (OldParam->hasUninstantiatedDefaultArg())
387 Param->setUninstantiatedDefaultArg(
388 Param->getUninstantiatedDefaultArg());
389 else
390 Param->setDefaultArg(OldParam->getInit());
Douglas Gregorefc46952010-10-12 16:25:54 +0000391 }
392 }
Douglas Gregor433e0532012-04-16 18:27:27 +0000393
Richard Smith0b3a4622014-11-13 20:01:57 +0000394 // Parse a delayed exception-specification, if there is one.
395 if (CachedTokens *Toks = LM.ExceptionSpecTokens) {
David Majnemer7cceba52015-01-13 04:20:57 +0000396 // Add the 'stop' token.
397 Token LastExceptionSpecToken = Toks->back();
398 Token ExceptionSpecEnd;
399 ExceptionSpecEnd.startToken();
400 ExceptionSpecEnd.setKind(tok::eof);
David Majnemera8f2f1d2015-03-19 00:10:23 +0000401 ExceptionSpecEnd.setLocation(LastExceptionSpecToken.getEndLoc());
David Majnemer7cceba52015-01-13 04:20:57 +0000402 ExceptionSpecEnd.setEofData(LM.Method);
403 Toks->push_back(ExceptionSpecEnd);
Richard Smith0b3a4622014-11-13 20:01:57 +0000404
405 // Parse the default argument from its saved token stream.
406 Toks->push_back(Tok); // So that the current token doesn't get lost
407 PP.EnterTokenStream(&Toks->front(), Toks->size(), true, false);
408
409 // Consume the previously-pushed token.
410 ConsumeAnyToken();
411
412 // C++11 [expr.prim.general]p3:
413 // If a declaration declares a member function or member function
414 // template of a class X, the expression this is a prvalue of type
415 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
416 // and the end of the function-definition, member-declarator, or
417 // declarator.
418 CXXMethodDecl *Method;
419 if (FunctionTemplateDecl *FunTmpl
420 = dyn_cast<FunctionTemplateDecl>(LM.Method))
421 Method = cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
422 else
423 Method = cast<CXXMethodDecl>(LM.Method);
424
425 Sema::CXXThisScopeRAII ThisScope(Actions, Method->getParent(),
426 Method->getTypeQualifiers(),
427 getLangOpts().CPlusPlus11);
428
429 // Parse the exception-specification.
430 SourceRange SpecificationRange;
431 SmallVector<ParsedType, 4> DynamicExceptions;
432 SmallVector<SourceRange, 4> DynamicExceptionRanges;
433 ExprResult NoexceptExpr;
434 CachedTokens *ExceptionSpecTokens;
435
436 ExceptionSpecificationType EST
437 = tryParseExceptionSpecification(/*Delayed=*/false, SpecificationRange,
438 DynamicExceptions,
439 DynamicExceptionRanges, NoexceptExpr,
440 ExceptionSpecTokens);
441
David Majnemer7cceba52015-01-13 04:20:57 +0000442 if (Tok.isNot(tok::eof) || Tok.getEofData() != LM.Method)
Richard Smith0b3a4622014-11-13 20:01:57 +0000443 Diag(Tok.getLocation(), diag::err_except_spec_unparsed);
444
445 // Attach the exception-specification to the method.
Richard Smith3ef3e892014-11-20 22:32:11 +0000446 Actions.actOnDelayedExceptionSpecification(LM.Method, EST,
447 SpecificationRange,
448 DynamicExceptions,
449 DynamicExceptionRanges,
450 NoexceptExpr.isUsable()?
451 NoexceptExpr.get() : nullptr);
Richard Smith0b3a4622014-11-13 20:01:57 +0000452
Richard Smith0b3a4622014-11-13 20:01:57 +0000453 // There could be leftover tokens (e.g. because of an error).
454 // Skip through until we reach the original token position.
David Majnemer7cceba52015-01-13 04:20:57 +0000455 while (Tok.isNot(tok::eof))
Richard Smith0b3a4622014-11-13 20:01:57 +0000456 ConsumeAnyToken();
David Majnemer7cceba52015-01-13 04:20:57 +0000457
458 // Clean up the remaining EOF token.
459 if (Tok.is(tok::eof) && Tok.getEofData() == LM.Method)
460 ConsumeAnyToken();
Richard Smith0b3a4622014-11-13 20:01:57 +0000461
462 delete Toks;
463 LM.ExceptionSpecTokens = nullptr;
464 }
465
Douglas Gregorefc46952010-10-12 16:25:54 +0000466 PrototypeScope.Exit();
467
468 // Finish the delayed C++ method declaration.
469 Actions.ActOnFinishDelayedCXXMethodDeclaration(getCurScope(), LM.Method);
470}
471
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000472/// ParseLexedMethodDefs - We finished parsing the member specification of a top
473/// (non-nested) C++ class. Now go over the stack of lexed methods that were
474/// collected during its parsing and parse them all.
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000475void Parser::ParseLexedMethodDefs(ParsingClass &Class) {
476 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
Douglas Gregorefc46952010-10-12 16:25:54 +0000477 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope, HasTemplateScope);
Richard Smithc8378952013-04-29 11:55:38 +0000478 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
479 if (HasTemplateScope) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000480 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
Richard Smithc8378952013-04-29 11:55:38 +0000481 ++CurTemplateDepthTracker;
482 }
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000483 bool HasClassScope = !Class.TopLevelClass;
484 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope,
485 HasClassScope);
486
Douglas Gregorefc46952010-10-12 16:25:54 +0000487 for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
488 Class.LateParsedDeclarations[i]->ParseLexedMethodDefs();
489 }
490}
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000491
Douglas Gregorefc46952010-10-12 16:25:54 +0000492void Parser::ParseLexedMethodDef(LexedMethod &LM) {
493 // If this is a member template, introduce the template parameter scope.
494 ParseScope TemplateScope(this, Scope::TemplateParamScope, LM.TemplateScope);
Richard Smithc8378952013-04-29 11:55:38 +0000495 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
496 if (LM.TemplateScope) {
Douglas Gregorefc46952010-10-12 16:25:54 +0000497 Actions.ActOnReenterTemplateScope(getCurScope(), LM.D);
Richard Smithc8378952013-04-29 11:55:38 +0000498 ++CurTemplateDepthTracker;
499 }
Argyrios Kyrtzidis02041972010-03-31 00:38:09 +0000500
Douglas Gregorefc46952010-10-12 16:25:54 +0000501 assert(!LM.Toks.empty() && "Empty body!");
David Majnemera7ea1b12015-01-13 05:06:20 +0000502 Token LastBodyToken = LM.Toks.back();
503 Token BodyEnd;
504 BodyEnd.startToken();
505 BodyEnd.setKind(tok::eof);
David Majnemera8f2f1d2015-03-19 00:10:23 +0000506 BodyEnd.setLocation(LastBodyToken.getEndLoc());
David Majnemera7ea1b12015-01-13 05:06:20 +0000507 BodyEnd.setEofData(LM.D);
508 LM.Toks.push_back(BodyEnd);
Douglas Gregorefc46952010-10-12 16:25:54 +0000509 // Append the current token at the end of the new token stream so that it
510 // doesn't get lost.
511 LM.Toks.push_back(Tok);
512 PP.EnterTokenStream(LM.Toks.data(), LM.Toks.size(), true, false);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000513
Douglas Gregorefc46952010-10-12 16:25:54 +0000514 // Consume the previously pushed token.
Argyrios Kyrtzidisc36633c2013-03-27 23:58:17 +0000515 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
Douglas Gregorefc46952010-10-12 16:25:54 +0000516 assert((Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try))
517 && "Inline method not starting with '{', ':' or 'try'");
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000518
Douglas Gregorefc46952010-10-12 16:25:54 +0000519 // Parse the method body. Function body parsing code is similar enough
520 // to be re-used for method bodies as well.
521 ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope);
522 Actions.ActOnStartOfFunctionDef(getCurScope(), LM.D);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000523
Douglas Gregorefc46952010-10-12 16:25:54 +0000524 if (Tok.is(tok::kw_try)) {
Douglas Gregora0ff0c32011-03-16 17:05:57 +0000525 ParseFunctionTryBlock(LM.D, FnScope);
David Majnemera7ea1b12015-01-13 05:06:20 +0000526
527 while (Tok.isNot(tok::eof))
528 ConsumeAnyToken();
529
530 if (Tok.is(tok::eof) && Tok.getEofData() == LM.D)
Douglas Gregorefc46952010-10-12 16:25:54 +0000531 ConsumeAnyToken();
532 return;
533 }
534 if (Tok.is(tok::colon)) {
535 ParseConstructorInitializer(LM.D);
536
537 // Error recovery.
538 if (!Tok.is(tok::l_brace)) {
Douglas Gregora0ff0c32011-03-16 17:05:57 +0000539 FnScope.Exit();
Craig Topper161e4db2014-05-21 06:02:52 +0000540 Actions.ActOnFinishFunctionBody(LM.D, nullptr);
David Majnemera7ea1b12015-01-13 05:06:20 +0000541
542 while (Tok.isNot(tok::eof))
543 ConsumeAnyToken();
544
545 if (Tok.is(tok::eof) && Tok.getEofData() == LM.D)
Matt Beaumont-Gayd0457922011-09-23 22:39:23 +0000546 ConsumeAnyToken();
Douglas Gregorefc46952010-10-12 16:25:54 +0000547 return;
548 }
549 } else
550 Actions.ActOnDefaultCtorInitializers(LM.D);
551
Richard Smithc8378952013-04-29 11:55:38 +0000552 assert((Actions.getDiagnostics().hasErrorOccurred() ||
553 !isa<FunctionTemplateDecl>(LM.D) ||
554 cast<FunctionTemplateDecl>(LM.D)->getTemplateParameters()->getDepth()
555 < TemplateParameterDepth) &&
556 "TemplateParameterDepth should be greater than the depth of "
557 "current template being instantiated!");
558
Douglas Gregora0ff0c32011-03-16 17:05:57 +0000559 ParseFunctionStatementBody(LM.D, FnScope);
Douglas Gregorefc46952010-10-12 16:25:54 +0000560
John McCalle68672f2013-03-14 05:13:41 +0000561 // Clear the late-template-parsed bit if we set it before.
Alp Tokera2794f92014-01-22 07:29:52 +0000562 if (LM.D)
563 LM.D->getAsFunction()->setLateTemplateParsed(false);
John McCalle68672f2013-03-14 05:13:41 +0000564
David Majnemera7ea1b12015-01-13 05:06:20 +0000565 while (Tok.isNot(tok::eof))
566 ConsumeAnyToken();
567
568 if (Tok.is(tok::eof) && Tok.getEofData() == LM.D)
569 ConsumeAnyToken();
Hans Wennborga926d842014-05-23 20:37:38 +0000570
571 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(LM.D))
572 Actions.ActOnFinishInlineMethodDef(MD);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000573}
574
Richard Smith938f40b2011-06-11 17:19:42 +0000575/// ParseLexedMemberInitializers - We finished parsing the member specification
576/// of a top (non-nested) C++ class. Now go over the stack of lexed data member
577/// initializers that were collected during its parsing and parse them all.
578void Parser::ParseLexedMemberInitializers(ParsingClass &Class) {
579 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
580 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
581 HasTemplateScope);
Richard Smithc8378952013-04-29 11:55:38 +0000582 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
583 if (HasTemplateScope) {
Richard Smith938f40b2011-06-11 17:19:42 +0000584 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
Richard Smithc8378952013-04-29 11:55:38 +0000585 ++CurTemplateDepthTracker;
586 }
Douglas Gregor3024f072012-04-16 07:05:22 +0000587 // Set or update the scope flags.
Richard Smith938f40b2011-06-11 17:19:42 +0000588 bool AlreadyHasClassScope = Class.TopLevelClass;
Douglas Gregor3024f072012-04-16 07:05:22 +0000589 unsigned ScopeFlags = Scope::ClassScope|Scope::DeclScope;
Richard Smith938f40b2011-06-11 17:19:42 +0000590 ParseScope ClassScope(this, ScopeFlags, !AlreadyHasClassScope);
591 ParseScopeFlags ClassScopeFlags(this, ScopeFlags, AlreadyHasClassScope);
592
593 if (!AlreadyHasClassScope)
594 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(),
595 Class.TagOrTemplate);
596
Benjamin Kramer1d373c62012-05-17 12:01:52 +0000597 if (!Class.LateParsedDeclarations.empty()) {
Douglas Gregor3024f072012-04-16 07:05:22 +0000598 // C++11 [expr.prim.general]p4:
599 // Otherwise, if a member-declarator declares a non-static data member
600 // (9.2) of a class X, the expression this is a prvalue of type "pointer
601 // to X" within the optional brace-or-equal-initializer. It shall not
602 // appear elsewhere in the member-declarator.
603 Sema::CXXThisScopeRAII ThisScope(Actions, Class.TagOrTemplate,
604 /*TypeQuals=*/(unsigned)0);
Richard Smith938f40b2011-06-11 17:19:42 +0000605
Douglas Gregor3024f072012-04-16 07:05:22 +0000606 for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
607 Class.LateParsedDeclarations[i]->ParseLexedMemberInitializers();
608 }
609 }
610
Richard Smith938f40b2011-06-11 17:19:42 +0000611 if (!AlreadyHasClassScope)
612 Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(),
613 Class.TagOrTemplate);
614
615 Actions.ActOnFinishDelayedMemberInitializers(Class.TagOrTemplate);
616}
617
618void Parser::ParseLexedMemberInitializer(LateParsedMemberInitializer &MI) {
Richard Smith1a526fd2011-09-29 19:42:27 +0000619 if (!MI.Field || MI.Field->isInvalidDecl())
Richard Smith938f40b2011-06-11 17:19:42 +0000620 return;
621
622 // Append the current token at the end of the new token stream so that it
623 // doesn't get lost.
624 MI.Toks.push_back(Tok);
625 PP.EnterTokenStream(MI.Toks.data(), MI.Toks.size(), true, false);
626
627 // Consume the previously pushed token.
Argyrios Kyrtzidisc36633c2013-03-27 23:58:17 +0000628 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
Richard Smith938f40b2011-06-11 17:19:42 +0000629
630 SourceLocation EqualLoc;
Richard Smith2b013182012-06-10 03:12:00 +0000631
Richard Smith74108172014-01-17 03:11:34 +0000632 Actions.ActOnStartCXXInClassMemberInitializer();
633
Douglas Gregor926410d2012-02-21 02:22:07 +0000634 ExprResult Init = ParseCXXMemberInitializer(MI.Field, /*IsFunction=*/false,
635 EqualLoc);
Richard Smith938f40b2011-06-11 17:19:42 +0000636
Richard Smith74108172014-01-17 03:11:34 +0000637 Actions.ActOnFinishCXXInClassMemberInitializer(MI.Field, EqualLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000638 Init.get());
Richard Smith938f40b2011-06-11 17:19:42 +0000639
640 // The next token should be our artificial terminating EOF token.
641 if (Tok.isNot(tok::eof)) {
Richard Smith95e1fb02014-08-27 03:23:12 +0000642 if (!Init.isInvalid()) {
643 SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
644 if (!EndLoc.isValid())
645 EndLoc = Tok.getLocation();
646 // No fixit; we can't recover as if there were a semicolon here.
647 Diag(EndLoc, diag::err_expected_semi_decl_list);
648 }
Richard Smith938f40b2011-06-11 17:19:42 +0000649
650 // Consume tokens until we hit the artificial EOF.
651 while (Tok.isNot(tok::eof))
652 ConsumeAnyToken();
653 }
David Majnemer2d3663e2014-12-18 09:57:31 +0000654 // Make sure this is *our* artificial EOF token.
David Majnemerce1d3012014-12-19 02:13:56 +0000655 if (Tok.getEofData() == MI.Field)
David Majnemer2d3663e2014-12-18 09:57:31 +0000656 ConsumeAnyToken();
Richard Smith938f40b2011-06-11 17:19:42 +0000657}
658
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000659/// ConsumeAndStoreUntil - Consume and store the token at the passed token
Douglas Gregor4d87df52008-12-16 21:30:33 +0000660/// container until the token 'T' is reached (which gets
Mike Stump11289f42009-09-09 15:08:12 +0000661/// consumed/stored too, if ConsumeFinalToken).
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000662/// If StopAtSemi is true, then we will stop early at a ';' character.
Douglas Gregor4d87df52008-12-16 21:30:33 +0000663/// Returns true if token 'T1' or 'T2' was found.
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000664/// NOTE: This is a specialized version of Parser::SkipUntil.
Douglas Gregor4d87df52008-12-16 21:30:33 +0000665bool Parser::ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
666 CachedTokens &Toks,
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000667 bool StopAtSemi, bool ConsumeFinalToken) {
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000668 // We always want this function to consume at least one token if the first
669 // token isn't T and if not at EOF.
670 bool isFirstTokenConsumed = true;
671 while (1) {
672 // If we found one of the tokens, stop and return true.
Douglas Gregor4d87df52008-12-16 21:30:33 +0000673 if (Tok.is(T1) || Tok.is(T2)) {
674 if (ConsumeFinalToken) {
675 Toks.push_back(Tok);
676 ConsumeAnyToken();
677 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000678 return true;
679 }
680
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000681 switch (Tok.getKind()) {
682 case tok::eof:
Richard Smith34f30512013-11-23 04:06:09 +0000683 case tok::annot_module_begin:
684 case tok::annot_module_end:
685 case tok::annot_module_include:
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000686 // Ran out of tokens.
687 return false;
688
689 case tok::l_paren:
690 // Recursively consume properly-nested parens.
691 Toks.push_back(Tok);
692 ConsumeParen();
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000693 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000694 break;
695 case tok::l_square:
696 // Recursively consume properly-nested square brackets.
697 Toks.push_back(Tok);
698 ConsumeBracket();
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000699 ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000700 break;
701 case tok::l_brace:
702 // Recursively consume properly-nested braces.
703 Toks.push_back(Tok);
704 ConsumeBrace();
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000705 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000706 break;
707
708 // Okay, we found a ']' or '}' or ')', which we think should be balanced.
709 // Since the user wasn't looking for this token (if they were, it would
710 // already be handled), this isn't balanced. If there is a LHS token at a
711 // higher level, we will assume that this matches the unbalanced token
712 // and return it. Otherwise, this is a spurious RHS token, which we skip.
713 case tok::r_paren:
714 if (ParenCount && !isFirstTokenConsumed)
715 return false; // Matches something.
716 Toks.push_back(Tok);
717 ConsumeParen();
718 break;
719 case tok::r_square:
720 if (BracketCount && !isFirstTokenConsumed)
721 return false; // Matches something.
722 Toks.push_back(Tok);
723 ConsumeBracket();
724 break;
725 case tok::r_brace:
726 if (BraceCount && !isFirstTokenConsumed)
727 return false; // Matches something.
728 Toks.push_back(Tok);
729 ConsumeBrace();
730 break;
731
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000732 case tok::code_completion:
733 Toks.push_back(Tok);
734 ConsumeCodeCompletionToken();
735 break;
736
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000737 case tok::string_literal:
738 case tok::wide_string_literal:
Douglas Gregorfb65e592011-07-27 05:40:30 +0000739 case tok::utf8_string_literal:
740 case tok::utf16_string_literal:
741 case tok::utf32_string_literal:
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000742 Toks.push_back(Tok);
743 ConsumeStringToken();
744 break;
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000745 case tok::semi:
746 if (StopAtSemi)
747 return false;
748 // FALL THROUGH.
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000749 default:
750 // consume this token.
751 Toks.push_back(Tok);
752 ConsumeToken();
753 break;
754 }
755 isFirstTokenConsumed = false;
756 }
757}
Sebastian Redla74948d2011-09-24 17:48:25 +0000758
759/// \brief Consume tokens and store them in the passed token container until
760/// we've passed the try keyword and constructor initializers and have consumed
Sebastian Redl0d164012011-09-30 08:32:17 +0000761/// the opening brace of the function body. The opening brace will be consumed
762/// if and only if there was no error.
Sebastian Redla74948d2011-09-24 17:48:25 +0000763///
Richard Smithcde3fd82013-07-04 00:13:48 +0000764/// \return True on error.
Sebastian Redl0d164012011-09-30 08:32:17 +0000765bool Parser::ConsumeAndStoreFunctionPrologue(CachedTokens &Toks) {
Sebastian Redla74948d2011-09-24 17:48:25 +0000766 if (Tok.is(tok::kw_try)) {
767 Toks.push_back(Tok);
768 ConsumeToken();
769 }
Richard Smithcde3fd82013-07-04 00:13:48 +0000770
771 if (Tok.isNot(tok::colon)) {
772 // Easy case, just a function body.
773
774 // Grab any remaining garbage to be diagnosed later. We stop when we reach a
775 // brace: an opening one is the function body, while a closing one probably
776 // means we've reached the end of the class.
777 ConsumeAndStoreUntil(tok::l_brace, tok::r_brace, Toks,
778 /*StopAtSemi=*/true,
779 /*ConsumeFinalToken=*/false);
780 if (Tok.isNot(tok::l_brace))
Alp Tokerec543272013-12-24 09:48:30 +0000781 return Diag(Tok.getLocation(), diag::err_expected) << tok::l_brace;
Richard Smithcde3fd82013-07-04 00:13:48 +0000782
Sebastian Redla74948d2011-09-24 17:48:25 +0000783 Toks.push_back(Tok);
Richard Smithcde3fd82013-07-04 00:13:48 +0000784 ConsumeBrace();
785 return false;
Eli Friedman7cd4a9b2012-02-22 04:49:04 +0000786 }
Sebastian Redl0d164012011-09-30 08:32:17 +0000787
788 Toks.push_back(Tok);
Richard Smithcde3fd82013-07-04 00:13:48 +0000789 ConsumeToken();
790
791 // We can't reliably skip over a mem-initializer-id, because it could be
792 // a template-id involving not-yet-declared names. Given:
793 //
794 // S ( ) : a < b < c > ( e )
795 //
796 // 'e' might be an initializer or part of a template argument, depending
797 // on whether 'b' is a template.
798
799 // Track whether we might be inside a template argument. We can give
800 // significantly better diagnostics if we know that we're not.
801 bool MightBeTemplateArgument = false;
802
803 while (true) {
804 // Skip over the mem-initializer-id, if possible.
805 if (Tok.is(tok::kw_decltype)) {
806 Toks.push_back(Tok);
807 SourceLocation OpenLoc = ConsumeToken();
808 if (Tok.isNot(tok::l_paren))
809 return Diag(Tok.getLocation(), diag::err_expected_lparen_after)
810 << "decltype";
811 Toks.push_back(Tok);
812 ConsumeParen();
813 if (!ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/true)) {
Alp Tokerec543272013-12-24 09:48:30 +0000814 Diag(Tok.getLocation(), diag::err_expected) << tok::r_paren;
815 Diag(OpenLoc, diag::note_matching) << tok::l_paren;
Richard Smithcde3fd82013-07-04 00:13:48 +0000816 return true;
817 }
818 }
819 do {
820 // Walk over a component of a nested-name-specifier.
821 if (Tok.is(tok::coloncolon)) {
822 Toks.push_back(Tok);
823 ConsumeToken();
824
825 if (Tok.is(tok::kw_template)) {
826 Toks.push_back(Tok);
827 ConsumeToken();
828 }
829 }
830
831 if (Tok.is(tok::identifier) || Tok.is(tok::kw_template)) {
832 Toks.push_back(Tok);
833 ConsumeToken();
834 } else if (Tok.is(tok::code_completion)) {
835 Toks.push_back(Tok);
836 ConsumeCodeCompletionToken();
837 // Consume the rest of the initializers permissively.
838 // FIXME: We should be able to perform code-completion here even if
839 // there isn't a subsequent '{' token.
840 MightBeTemplateArgument = true;
841 break;
842 } else {
843 break;
844 }
845 } while (Tok.is(tok::coloncolon));
846
847 if (Tok.is(tok::less))
848 MightBeTemplateArgument = true;
849
850 if (MightBeTemplateArgument) {
851 // We may be inside a template argument list. Grab up to the start of the
852 // next parenthesized initializer or braced-init-list. This *might* be the
853 // initializer, or it might be a subexpression in the template argument
854 // list.
855 // FIXME: Count angle brackets, and clear MightBeTemplateArgument
856 // if all angles are closed.
857 if (!ConsumeAndStoreUntil(tok::l_paren, tok::l_brace, Toks,
858 /*StopAtSemi=*/true,
859 /*ConsumeFinalToken=*/false)) {
860 // We're not just missing the initializer, we're also missing the
861 // function body!
Alp Tokerec543272013-12-24 09:48:30 +0000862 return Diag(Tok.getLocation(), diag::err_expected) << tok::l_brace;
Richard Smithcde3fd82013-07-04 00:13:48 +0000863 }
864 } else if (Tok.isNot(tok::l_paren) && Tok.isNot(tok::l_brace)) {
865 // We found something weird in a mem-initializer-id.
Alp Tokerec543272013-12-24 09:48:30 +0000866 if (getLangOpts().CPlusPlus11)
867 return Diag(Tok.getLocation(), diag::err_expected_either)
868 << tok::l_paren << tok::l_brace;
869 else
870 return Diag(Tok.getLocation(), diag::err_expected) << tok::l_paren;
Richard Smithcde3fd82013-07-04 00:13:48 +0000871 }
872
873 tok::TokenKind kind = Tok.getKind();
874 Toks.push_back(Tok);
875 bool IsLParen = (kind == tok::l_paren);
876 SourceLocation OpenLoc = Tok.getLocation();
877
878 if (IsLParen) {
879 ConsumeParen();
880 } else {
881 assert(kind == tok::l_brace && "Must be left paren or brace here.");
882 ConsumeBrace();
883 // In C++03, this has to be the start of the function body, which
884 // means the initializer is malformed; we'll diagnose it later.
885 if (!getLangOpts().CPlusPlus11)
886 return false;
887 }
888
889 // Grab the initializer (or the subexpression of the template argument).
890 // FIXME: If we support lambdas here, we'll need to set StopAtSemi to false
891 // if we might be inside the braces of a lambda-expression.
Alp Tokerec543272013-12-24 09:48:30 +0000892 tok::TokenKind CloseKind = IsLParen ? tok::r_paren : tok::r_brace;
893 if (!ConsumeAndStoreUntil(CloseKind, Toks, /*StopAtSemi=*/true)) {
894 Diag(Tok, diag::err_expected) << CloseKind;
895 Diag(OpenLoc, diag::note_matching) << kind;
Richard Smithcde3fd82013-07-04 00:13:48 +0000896 return true;
897 }
898
899 // Grab pack ellipsis, if present.
900 if (Tok.is(tok::ellipsis)) {
901 Toks.push_back(Tok);
902 ConsumeToken();
903 }
904
905 // If we know we just consumed a mem-initializer, we must have ',' or '{'
906 // next.
907 if (Tok.is(tok::comma)) {
908 Toks.push_back(Tok);
909 ConsumeToken();
910 } else if (Tok.is(tok::l_brace)) {
911 // This is the function body if the ')' or '}' is immediately followed by
912 // a '{'. That cannot happen within a template argument, apart from the
913 // case where a template argument contains a compound literal:
914 //
915 // S ( ) : a < b < c > ( d ) { }
916 // // End of declaration, or still inside the template argument?
917 //
918 // ... and the case where the template argument contains a lambda:
919 //
920 // S ( ) : a < 0 && b < c > ( d ) + [ ] ( ) { return 0; }
921 // ( ) > ( ) { }
922 //
923 // FIXME: Disambiguate these cases. Note that the latter case is probably
924 // going to be made ill-formed by core issue 1607.
925 Toks.push_back(Tok);
926 ConsumeBrace();
927 return false;
928 } else if (!MightBeTemplateArgument) {
Alp Tokerec543272013-12-24 09:48:30 +0000929 return Diag(Tok.getLocation(), diag::err_expected_either) << tok::l_brace
930 << tok::comma;
Richard Smithcde3fd82013-07-04 00:13:48 +0000931 }
932 }
Sebastian Redla74948d2011-09-24 17:48:25 +0000933}
Richard Smith1fff95c2013-09-12 23:28:08 +0000934
935/// \brief Consume and store tokens from the '?' to the ':' in a conditional
936/// expression.
937bool Parser::ConsumeAndStoreConditional(CachedTokens &Toks) {
938 // Consume '?'.
939 assert(Tok.is(tok::question));
940 Toks.push_back(Tok);
941 ConsumeToken();
942
943 while (Tok.isNot(tok::colon)) {
Nico Weber77c76c52014-05-10 17:43:15 +0000944 if (!ConsumeAndStoreUntil(tok::question, tok::colon, Toks,
945 /*StopAtSemi=*/true,
946 /*ConsumeFinalToken=*/false))
Richard Smith1fff95c2013-09-12 23:28:08 +0000947 return false;
948
949 // If we found a nested conditional, consume it.
950 if (Tok.is(tok::question) && !ConsumeAndStoreConditional(Toks))
951 return false;
952 }
953
954 // Consume ':'.
955 Toks.push_back(Tok);
956 ConsumeToken();
957 return true;
958}
959
960/// \brief A tentative parsing action that can also revert token annotations.
961class Parser::UnannotatedTentativeParsingAction : public TentativeParsingAction {
962public:
963 explicit UnannotatedTentativeParsingAction(Parser &Self,
964 tok::TokenKind EndKind)
965 : TentativeParsingAction(Self), Self(Self), EndKind(EndKind) {
966 // Stash away the old token stream, so we can restore it once the
967 // tentative parse is complete.
968 TentativeParsingAction Inner(Self);
969 Self.ConsumeAndStoreUntil(EndKind, Toks, true, /*ConsumeFinalToken*/false);
970 Inner.Revert();
971 }
972
973 void RevertAnnotations() {
974 Revert();
975
976 // Put back the original tokens.
Alexey Bataevee6507d2013-11-18 08:17:37 +0000977 Self.SkipUntil(EndKind, StopAtSemi | StopBeforeMatch);
Richard Smith1fff95c2013-09-12 23:28:08 +0000978 if (Toks.size()) {
979 Token *Buffer = new Token[Toks.size()];
980 std::copy(Toks.begin() + 1, Toks.end(), Buffer);
981 Buffer[Toks.size() - 1] = Self.Tok;
982 Self.PP.EnterTokenStream(Buffer, Toks.size(), true, /*Owned*/true);
983
984 Self.Tok = Toks.front();
985 }
986 }
987
988private:
989 Parser &Self;
990 CachedTokens Toks;
991 tok::TokenKind EndKind;
992};
993
994/// ConsumeAndStoreInitializer - Consume and store the token at the passed token
995/// container until the end of the current initializer expression (either a
996/// default argument or an in-class initializer for a non-static data member).
Richard Smith95e1fb02014-08-27 03:23:12 +0000997///
998/// Returns \c true if we reached the end of something initializer-shaped,
999/// \c false if we bailed out.
Richard Smith1fff95c2013-09-12 23:28:08 +00001000bool Parser::ConsumeAndStoreInitializer(CachedTokens &Toks,
1001 CachedInitKind CIK) {
1002 // We always want this function to consume at least one token if not at EOF.
Richard Smith95e1fb02014-08-27 03:23:12 +00001003 bool IsFirstToken = true;
Richard Smith1fff95c2013-09-12 23:28:08 +00001004
1005 // Number of possible unclosed <s we've seen so far. These might be templates,
1006 // and might not, but if there were none of them (or we know for sure that
1007 // we're within a template), we can avoid a tentative parse.
1008 unsigned AngleCount = 0;
1009 unsigned KnownTemplateCount = 0;
1010
1011 while (1) {
1012 switch (Tok.getKind()) {
1013 case tok::comma:
1014 // If we might be in a template, perform a tentative parse to check.
1015 if (!AngleCount)
1016 // Not a template argument: this is the end of the initializer.
1017 return true;
1018 if (KnownTemplateCount)
1019 goto consume_token;
1020
1021 // We hit a comma inside angle brackets. This is the hard case. The
1022 // rule we follow is:
1023 // * For a default argument, if the tokens after the comma form a
1024 // syntactically-valid parameter-declaration-clause, in which each
1025 // parameter has an initializer, then this comma ends the default
1026 // argument.
1027 // * For a default initializer, if the tokens after the comma form a
1028 // syntactically-valid init-declarator-list, then this comma ends
1029 // the default initializer.
1030 {
1031 UnannotatedTentativeParsingAction PA(*this,
1032 CIK == CIK_DefaultInitializer
1033 ? tok::semi : tok::r_paren);
1034 Sema::TentativeAnalysisScope Scope(Actions);
1035
Richard Smithee390432014-05-16 01:56:53 +00001036 TPResult Result = TPResult::Error;
Richard Smith1fff95c2013-09-12 23:28:08 +00001037 ConsumeToken();
1038 switch (CIK) {
1039 case CIK_DefaultInitializer:
1040 Result = TryParseInitDeclaratorList();
1041 // If we parsed a complete, ambiguous init-declarator-list, this
1042 // is only syntactically-valid if it's followed by a semicolon.
Richard Smithee390432014-05-16 01:56:53 +00001043 if (Result == TPResult::Ambiguous && Tok.isNot(tok::semi))
1044 Result = TPResult::False;
Richard Smith1fff95c2013-09-12 23:28:08 +00001045 break;
1046
1047 case CIK_DefaultArgument:
1048 bool InvalidAsDeclaration = false;
1049 Result = TryParseParameterDeclarationClause(
Nico Weberc29c4832014-12-28 23:24:02 +00001050 &InvalidAsDeclaration, /*VersusTemplateArgument=*/true);
Richard Smith1fff95c2013-09-12 23:28:08 +00001051 // If this is an expression or a declaration with a missing
1052 // 'typename', assume it's not a declaration.
Richard Smithee390432014-05-16 01:56:53 +00001053 if (Result == TPResult::Ambiguous && InvalidAsDeclaration)
1054 Result = TPResult::False;
Richard Smith1fff95c2013-09-12 23:28:08 +00001055 break;
1056 }
1057
1058 // If what follows could be a declaration, it is a declaration.
Richard Smithee390432014-05-16 01:56:53 +00001059 if (Result != TPResult::False && Result != TPResult::Error) {
Richard Smith1fff95c2013-09-12 23:28:08 +00001060 PA.Revert();
1061 return true;
1062 }
1063
1064 // In the uncommon case that we decide the following tokens are part
1065 // of a template argument, revert any annotations we've performed in
1066 // those tokens. We're not going to look them up until we've parsed
1067 // the rest of the class, and that might add more declarations.
1068 PA.RevertAnnotations();
1069 }
1070
1071 // Keep going. We know we're inside a template argument list now.
1072 ++KnownTemplateCount;
1073 goto consume_token;
1074
1075 case tok::eof:
Richard Smith34f30512013-11-23 04:06:09 +00001076 case tok::annot_module_begin:
1077 case tok::annot_module_end:
1078 case tok::annot_module_include:
Richard Smith1fff95c2013-09-12 23:28:08 +00001079 // Ran out of tokens.
1080 return false;
1081
1082 case tok::less:
1083 // FIXME: A '<' can only start a template-id if it's preceded by an
1084 // identifier, an operator-function-id, or a literal-operator-id.
1085 ++AngleCount;
1086 goto consume_token;
1087
1088 case tok::question:
1089 // In 'a ? b : c', 'b' can contain an unparenthesized comma. If it does,
1090 // that is *never* the end of the initializer. Skip to the ':'.
1091 if (!ConsumeAndStoreConditional(Toks))
1092 return false;
1093 break;
1094
1095 case tok::greatergreatergreater:
1096 if (!getLangOpts().CPlusPlus11)
1097 goto consume_token;
1098 if (AngleCount) --AngleCount;
1099 if (KnownTemplateCount) --KnownTemplateCount;
1100 // Fall through.
1101 case tok::greatergreater:
1102 if (!getLangOpts().CPlusPlus11)
1103 goto consume_token;
1104 if (AngleCount) --AngleCount;
1105 if (KnownTemplateCount) --KnownTemplateCount;
1106 // Fall through.
1107 case tok::greater:
1108 if (AngleCount) --AngleCount;
1109 if (KnownTemplateCount) --KnownTemplateCount;
1110 goto consume_token;
1111
1112 case tok::kw_template:
1113 // 'template' identifier '<' is known to start a template argument list,
1114 // and can be used to disambiguate the parse.
1115 // FIXME: Support all forms of 'template' unqualified-id '<'.
1116 Toks.push_back(Tok);
1117 ConsumeToken();
1118 if (Tok.is(tok::identifier)) {
1119 Toks.push_back(Tok);
1120 ConsumeToken();
1121 if (Tok.is(tok::less)) {
Richard Smith93033572014-07-27 05:38:12 +00001122 ++AngleCount;
Richard Smith1fff95c2013-09-12 23:28:08 +00001123 ++KnownTemplateCount;
1124 Toks.push_back(Tok);
1125 ConsumeToken();
1126 }
1127 }
1128 break;
1129
1130 case tok::kw_operator:
1131 // If 'operator' precedes other punctuation, that punctuation loses
1132 // its special behavior.
1133 Toks.push_back(Tok);
1134 ConsumeToken();
1135 switch (Tok.getKind()) {
1136 case tok::comma:
1137 case tok::greatergreatergreater:
1138 case tok::greatergreater:
1139 case tok::greater:
1140 case tok::less:
1141 Toks.push_back(Tok);
1142 ConsumeToken();
1143 break;
1144 default:
1145 break;
1146 }
1147 break;
1148
1149 case tok::l_paren:
1150 // Recursively consume properly-nested parens.
1151 Toks.push_back(Tok);
1152 ConsumeParen();
1153 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
1154 break;
1155 case tok::l_square:
1156 // Recursively consume properly-nested square brackets.
1157 Toks.push_back(Tok);
1158 ConsumeBracket();
1159 ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false);
1160 break;
1161 case tok::l_brace:
1162 // Recursively consume properly-nested braces.
1163 Toks.push_back(Tok);
1164 ConsumeBrace();
1165 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1166 break;
1167
1168 // Okay, we found a ']' or '}' or ')', which we think should be balanced.
1169 // Since the user wasn't looking for this token (if they were, it would
1170 // already be handled), this isn't balanced. If there is a LHS token at a
1171 // higher level, we will assume that this matches the unbalanced token
Richard Smith95e1fb02014-08-27 03:23:12 +00001172 // and return it. Otherwise, this is a spurious RHS token, which we
1173 // consume and pass on to downstream code to diagnose.
Richard Smith1fff95c2013-09-12 23:28:08 +00001174 case tok::r_paren:
1175 if (CIK == CIK_DefaultArgument)
1176 return true; // End of the default argument.
Richard Smith95e1fb02014-08-27 03:23:12 +00001177 if (ParenCount && !IsFirstToken)
1178 return false;
1179 Toks.push_back(Tok);
1180 ConsumeParen();
1181 continue;
Richard Smith1fff95c2013-09-12 23:28:08 +00001182 case tok::r_square:
Richard Smith95e1fb02014-08-27 03:23:12 +00001183 if (BracketCount && !IsFirstToken)
1184 return false;
1185 Toks.push_back(Tok);
1186 ConsumeBracket();
1187 continue;
Richard Smith1fff95c2013-09-12 23:28:08 +00001188 case tok::r_brace:
Richard Smith95e1fb02014-08-27 03:23:12 +00001189 if (BraceCount && !IsFirstToken)
1190 return false;
1191 Toks.push_back(Tok);
1192 ConsumeBrace();
1193 continue;
Richard Smith1fff95c2013-09-12 23:28:08 +00001194
1195 case tok::code_completion:
1196 Toks.push_back(Tok);
1197 ConsumeCodeCompletionToken();
1198 break;
1199
1200 case tok::string_literal:
1201 case tok::wide_string_literal:
1202 case tok::utf8_string_literal:
1203 case tok::utf16_string_literal:
1204 case tok::utf32_string_literal:
1205 Toks.push_back(Tok);
1206 ConsumeStringToken();
1207 break;
1208 case tok::semi:
1209 if (CIK == CIK_DefaultInitializer)
1210 return true; // End of the default initializer.
1211 // FALL THROUGH.
1212 default:
1213 consume_token:
1214 Toks.push_back(Tok);
1215 ConsumeToken();
1216 break;
1217 }
Richard Smith95e1fb02014-08-27 03:23:12 +00001218 IsFirstToken = false;
Richard Smith1fff95c2013-09-12 23:28:08 +00001219 }
1220}