blob: feff7fb724aabc8e3627ffb12f766747e181637b [file] [log] [blame]
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00001//===--- ParseCXXInlineMethods.cpp - C++ class inline methods parsing------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements parsing for C++ class inline methods.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Parse/Parser.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "RAIIObjectsForParser.h"
16#include "clang/AST/DeclTemplate.h"
17#include "clang/Parse/ParseDiagnostic.h"
John McCall8b0666c2010-08-20 18:27:03 +000018#include "clang/Sema/DeclSpec.h"
19#include "clang/Sema/Scope.h"
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +000020using namespace clang;
21
John McCalle68672f2013-03-14 05:13:41 +000022/// Get the FunctionDecl for a function or function template decl.
23static FunctionDecl *getFunctionDecl(Decl *D) {
24 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(D))
25 return fn;
26 return cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
27}
28
Sebastian Redla7b98a72009-04-26 20:35:05 +000029/// ParseCXXInlineMethodDef - We parsed and verified that the specified
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +000030/// Declarator is a well formed C++ inline method definition. Now lex its body
31/// and store its tokens for parsing after the C++ class is complete.
Rafael Espindolac2453dd2013-01-08 21:00:12 +000032NamedDecl *Parser::ParseCXXInlineMethodDef(AccessSpecifier AS,
Erik Verbruggenca98f2a2011-10-13 09:41:32 +000033 AttributeList *AccessAttrs,
34 ParsingDeclarator &D,
Douglas Gregor5d1b4e32011-11-07 20:56:01 +000035 const ParsedTemplateInfo &TemplateInfo,
36 const VirtSpecifiers& VS,
37 FunctionDefinitionKind DefinitionKind,
38 ExprResult& Init) {
Abramo Bagnara924a8f32010-12-10 16:29:40 +000039 assert(D.isFunctionDeclarator() && "This isn't a function declarator!");
Alexis Hunt5a7fa252011-05-12 06:15:49 +000040 assert((Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try) ||
41 Tok.is(tok::equal)) &&
42 "Current token not a '{', ':', '=', or 'try'!");
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +000043
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000044 MultiTemplateParamsArg TemplateParams(
Alexis Hunt1deb9722010-04-14 23:07:37 +000045 TemplateInfo.TemplateParams ? TemplateInfo.TemplateParams->data() : 0,
46 TemplateInfo.TemplateParams ? TemplateInfo.TemplateParams->size() : 0);
47
Rafael Espindolac2453dd2013-01-08 21:00:12 +000048 NamedDecl *FnD;
Douglas Gregor5d1b4e32011-11-07 20:56:01 +000049 D.setFunctionDefinitionKind(DefinitionKind);
John McCall07e91c02009-08-06 02:15:43 +000050 if (D.getDeclSpec().isFriendSpecified())
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000051 FnD = Actions.ActOnFriendFunctionDecl(getCurScope(), D,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000052 TemplateParams);
Douglas Gregor728d00b2011-10-10 14:49:18 +000053 else {
Douglas Gregor0be31a22010-07-02 17:43:08 +000054 FnD = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS, D,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000055 TemplateParams, 0,
Richard Smith2b013182012-06-10 03:12:00 +000056 VS, ICIS_NoInit);
Douglas Gregor728d00b2011-10-10 14:49:18 +000057 if (FnD) {
Richard Smithf8a75c32013-08-29 00:47:48 +000058 Actions.ProcessDeclAttributeList(getCurScope(), FnD, AccessAttrs);
Richard Smith74aeef52013-04-26 16:15:35 +000059 bool TypeSpecContainsAuto = D.getDeclSpec().containsPlaceholderType();
Douglas Gregor50cefbf2011-10-17 17:09:53 +000060 if (Init.isUsable())
Larisse Voufo39a1e502013-08-06 01:03:05 +000061 Actions.AddInitializerToDecl(FnD, Init.get(), false,
Douglas Gregor728d00b2011-10-10 14:49:18 +000062 TypeSpecContainsAuto);
63 else
64 Actions.ActOnUninitializedDecl(FnD, TypeSpecContainsAuto);
65 }
Nico Weber24b2a822011-01-28 06:07:34 +000066 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +000067
Douglas Gregor433e0532012-04-16 18:27:27 +000068 HandleMemberFunctionDeclDelays(D, FnD);
Eli Friedman3af2a772009-07-22 21:45:50 +000069
John McCallc1465822011-02-14 07:13:47 +000070 D.complete(FnD);
71
Alp Tokera3ebe6e2013-12-17 14:12:37 +000072 if (TryConsumeToken(tok::equal)) {
Richard Smith1c704732011-11-10 09:08:44 +000073 if (!FnD) {
74 SkipUntil(tok::semi);
75 return 0;
76 }
77
Alexis Hunt5a7fa252011-05-12 06:15:49 +000078 bool Delete = false;
79 SourceLocation KWLoc;
Alp Tokera3ebe6e2013-12-17 14:12:37 +000080 if (TryConsumeToken(tok::kw_delete, KWLoc)) {
81 Diag(KWLoc, getLangOpts().CPlusPlus11
82 ? diag::warn_cxx98_compat_deleted_function
83 : diag::ext_deleted_function);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000084 Actions.SetDeclDeleted(FnD, KWLoc);
85 Delete = true;
Alp Tokera3ebe6e2013-12-17 14:12:37 +000086 } else if (TryConsumeToken(tok::kw_default, KWLoc)) {
87 Diag(KWLoc, getLangOpts().CPlusPlus11
88 ? diag::warn_cxx98_compat_defaulted_function
89 : diag::ext_defaulted_function);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000090 Actions.SetDeclDefaulted(FnD, KWLoc);
91 } else {
92 llvm_unreachable("function definition after = not 'delete' or 'default'");
93 }
94
95 if (Tok.is(tok::comma)) {
96 Diag(KWLoc, diag::err_default_delete_in_multiple_declaration)
97 << Delete;
98 SkipUntil(tok::semi);
Alp Toker383d2c42014-01-01 03:08:43 +000099 } else if (ExpectAndConsume(tok::semi, diag::err_expected_after,
100 Delete ? "delete" : "default")) {
101 SkipUntil(tok::semi);
Alexis Hunt5a7fa252011-05-12 06:15:49 +0000102 }
103
104 return FnD;
105 }
Faisal Valib96570332013-11-01 02:01:01 +0000106
Francois Pichet1c229c02011-04-22 22:18:13 +0000107 // In delayed template parsing mode, if we are within a class template
108 // or if we are about to parse function member template then consume
109 // the tokens and store them for parsing at the end of the translation unit.
David Majnemer90b17292013-09-14 05:46:42 +0000110 if (getLangOpts().DelayedTemplateParsing &&
111 DefinitionKind == FDK_Definition &&
Faisal Valib96570332013-11-01 02:01:01 +0000112 !D.getDeclSpec().isConstexprSpecified() &&
113 !(FnD && getFunctionDecl(FnD) &&
114 getFunctionDecl(FnD)->getResultType()->getContainedAutoType()) &&
Francois Pichet1c229c02011-04-22 22:18:13 +0000115 ((Actions.CurContext->isDependentContext() ||
David Majnemer90b17292013-09-14 05:46:42 +0000116 (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
117 TemplateInfo.Kind != ParsedTemplateInfo::ExplicitSpecialization)) &&
118 !Actions.IsInsideALocalClassWithinATemplateFunction())) {
Francois Pichet1c229c02011-04-22 22:18:13 +0000119
Richard Smithe40f2ba2013-08-07 21:41:30 +0000120 CachedTokens Toks;
121 LexTemplateFunctionForLateParsing(Toks);
Francois Pichet1c229c02011-04-22 22:18:13 +0000122
Richard Smithe40f2ba2013-08-07 21:41:30 +0000123 if (FnD) {
John McCalle68672f2013-03-14 05:13:41 +0000124 FunctionDecl *FD = getFunctionDecl(FnD);
Chandler Carruthbc0f9ae2011-04-25 07:09:43 +0000125 Actions.CheckForFunctionRedefinition(FD);
Richard Smithe40f2ba2013-08-07 21:41:30 +0000126 Actions.MarkAsLateParsedTemplate(FD, FnD, Toks);
Francois Pichet1c229c02011-04-22 22:18:13 +0000127 }
128
129 return FnD;
130 }
131
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000132 // Consume the tokens and store them for later parsing.
133
Douglas Gregorefc46952010-10-12 16:25:54 +0000134 LexedMethod* LM = new LexedMethod(this, FnD);
135 getCurrentClass().LateParsedDeclarations.push_back(LM);
136 LM->TemplateScope = getCurScope()->isTemplateParamScope();
137 CachedTokens &Toks = LM->Toks;
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000138
Sebastian Redla7b98a72009-04-26 20:35:05 +0000139 tok::TokenKind kind = Tok.getKind();
Sebastian Redl0d164012011-09-30 08:32:17 +0000140 // Consume everything up to (and including) the left brace of the
141 // function body.
142 if (ConsumeAndStoreFunctionPrologue(Toks)) {
143 // We didn't find the left-brace we expected after the
Eli Friedman7cd4a9b2012-02-22 04:49:04 +0000144 // constructor initializer; we already printed an error, and it's likely
145 // impossible to recover, so don't try to parse this method later.
Richard Smithcde3fd82013-07-04 00:13:48 +0000146 // Skip over the rest of the decl and back to somewhere that looks
147 // reasonable.
148 SkipMalformedDecl();
Eli Friedman7cd4a9b2012-02-22 04:49:04 +0000149 delete getCurrentClass().LateParsedDeclarations.back();
150 getCurrentClass().LateParsedDeclarations.pop_back();
151 return FnD;
Douglas Gregore8381c02008-11-05 04:29:56 +0000152 } else {
Sebastian Redl0d164012011-09-30 08:32:17 +0000153 // Consume everything up to (and including) the matching right brace.
154 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
Douglas Gregore8381c02008-11-05 04:29:56 +0000155 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000156
Sebastian Redla7b98a72009-04-26 20:35:05 +0000157 // If we're in a function-try-block, we need to store all the catch blocks.
158 if (kind == tok::kw_try) {
159 while (Tok.is(tok::kw_catch)) {
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000160 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
161 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
Sebastian Redla7b98a72009-04-26 20:35:05 +0000162 }
163 }
164
Stephen Lin9354fc52013-06-23 07:37:13 +0000165 if (FnD) {
166 // If this is a friend function, mark that it's late-parsed so that
167 // it's still known to be a definition even before we attach the
168 // parsed body. Sema needs to treat friend function definitions
169 // differently during template instantiation, and it's possible for
170 // the containing class to be instantiated before all its member
171 // function definitions are parsed.
172 //
173 // If you remove this, you can remove the code that clears the flag
174 // after parsing the member.
175 if (D.getDeclSpec().isFriendSpecified()) {
Alp Toker19bff322013-10-18 05:54:24 +0000176 FunctionDecl *FD = getFunctionDecl(FnD);
177 Actions.CheckForFunctionRedefinition(FD);
178 FD->setLateTemplateParsed(true);
Stephen Lin9354fc52013-06-23 07:37:13 +0000179 }
180 } else {
Douglas Gregor6ca64102011-04-14 23:19:27 +0000181 // If semantic analysis could not build a function declaration,
182 // just throw away the late-parsed declaration.
183 delete getCurrentClass().LateParsedDeclarations.back();
184 getCurrentClass().LateParsedDeclarations.pop_back();
185 }
186
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000187 return FnD;
188}
189
Richard Smith938f40b2011-06-11 17:19:42 +0000190/// ParseCXXNonStaticMemberInitializer - We parsed and verified that the
191/// specified Declarator is a well formed C++ non-static data member
192/// declaration. Now lex its initializer and store its tokens for parsing
193/// after the class is complete.
194void Parser::ParseCXXNonStaticMemberInitializer(Decl *VarD) {
195 assert((Tok.is(tok::l_brace) || Tok.is(tok::equal)) &&
196 "Current token not a '{' or '='!");
197
198 LateParsedMemberInitializer *MI =
199 new LateParsedMemberInitializer(this, VarD);
200 getCurrentClass().LateParsedDeclarations.push_back(MI);
201 CachedTokens &Toks = MI->Toks;
202
203 tok::TokenKind kind = Tok.getKind();
204 if (kind == tok::equal) {
205 Toks.push_back(Tok);
Douglas Gregor0cf55e92012-03-08 01:00:17 +0000206 ConsumeToken();
Richard Smith938f40b2011-06-11 17:19:42 +0000207 }
208
209 if (kind == tok::l_brace) {
210 // Begin by storing the '{' token.
211 Toks.push_back(Tok);
212 ConsumeBrace();
213
214 // Consume everything up to (and including) the matching right brace.
215 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/true);
216 } else {
217 // Consume everything up to (but excluding) the comma or semicolon.
Richard Smith1fff95c2013-09-12 23:28:08 +0000218 ConsumeAndStoreInitializer(Toks, CIK_DefaultInitializer);
Richard Smith938f40b2011-06-11 17:19:42 +0000219 }
220
221 // Store an artificial EOF token to ensure that we don't run off the end of
222 // the initializer when we come to parse it.
223 Token Eof;
224 Eof.startToken();
225 Eof.setKind(tok::eof);
226 Eof.setLocation(Tok.getLocation());
227 Toks.push_back(Eof);
228}
229
Douglas Gregorefc46952010-10-12 16:25:54 +0000230Parser::LateParsedDeclaration::~LateParsedDeclaration() {}
231void Parser::LateParsedDeclaration::ParseLexedMethodDeclarations() {}
Richard Smith938f40b2011-06-11 17:19:42 +0000232void Parser::LateParsedDeclaration::ParseLexedMemberInitializers() {}
Douglas Gregorefc46952010-10-12 16:25:54 +0000233void Parser::LateParsedDeclaration::ParseLexedMethodDefs() {}
234
235Parser::LateParsedClass::LateParsedClass(Parser *P, ParsingClass *C)
236 : Self(P), Class(C) {}
237
238Parser::LateParsedClass::~LateParsedClass() {
239 Self->DeallocateParsedClasses(Class);
240}
241
242void Parser::LateParsedClass::ParseLexedMethodDeclarations() {
243 Self->ParseLexedMethodDeclarations(*Class);
244}
245
Richard Smith938f40b2011-06-11 17:19:42 +0000246void Parser::LateParsedClass::ParseLexedMemberInitializers() {
247 Self->ParseLexedMemberInitializers(*Class);
248}
249
Douglas Gregorefc46952010-10-12 16:25:54 +0000250void Parser::LateParsedClass::ParseLexedMethodDefs() {
251 Self->ParseLexedMethodDefs(*Class);
252}
253
254void Parser::LateParsedMethodDeclaration::ParseLexedMethodDeclarations() {
255 Self->ParseLexedMethodDeclaration(*this);
256}
257
258void Parser::LexedMethod::ParseLexedMethodDefs() {
259 Self->ParseLexedMethodDef(*this);
260}
261
Richard Smith938f40b2011-06-11 17:19:42 +0000262void Parser::LateParsedMemberInitializer::ParseLexedMemberInitializers() {
263 Self->ParseLexedMemberInitializer(*this);
264}
265
Douglas Gregor4d87df52008-12-16 21:30:33 +0000266/// ParseLexedMethodDeclarations - We finished parsing the member
267/// specification of a top (non-nested) C++ class. Now go over the
268/// stack of method declarations with some parts for which parsing was
269/// delayed (such as default arguments) and parse them.
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000270void Parser::ParseLexedMethodDeclarations(ParsingClass &Class) {
271 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
Douglas Gregorefc46952010-10-12 16:25:54 +0000272 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope, HasTemplateScope);
Richard Smithc8378952013-04-29 11:55:38 +0000273 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
274 if (HasTemplateScope) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000275 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
Richard Smithc8378952013-04-29 11:55:38 +0000276 ++CurTemplateDepthTracker;
277 }
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000278
John McCall6df5fef2009-12-19 10:49:29 +0000279 // The current scope is still active if we're the top-level class.
280 // Otherwise we'll need to push and enter a new scope.
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000281 bool HasClassScope = !Class.TopLevelClass;
Alexis Hunt1deb9722010-04-14 23:07:37 +0000282 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope,
283 HasClassScope);
John McCall6df5fef2009-12-19 10:49:29 +0000284 if (HasClassScope)
Douglas Gregor0be31a22010-07-02 17:43:08 +0000285 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(), Class.TagOrTemplate);
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000286
Douglas Gregorefc46952010-10-12 16:25:54 +0000287 for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
288 Class.LateParsedDeclarations[i]->ParseLexedMethodDeclarations();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000289 }
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000290
John McCall6df5fef2009-12-19 10:49:29 +0000291 if (HasClassScope)
Douglas Gregor0be31a22010-07-02 17:43:08 +0000292 Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(), Class.TagOrTemplate);
Douglas Gregor4d87df52008-12-16 21:30:33 +0000293}
294
Douglas Gregorefc46952010-10-12 16:25:54 +0000295void Parser::ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM) {
296 // If this is a member template, introduce the template parameter scope.
297 ParseScope TemplateScope(this, Scope::TemplateParamScope, LM.TemplateScope);
Richard Smithc8378952013-04-29 11:55:38 +0000298 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
299 if (LM.TemplateScope) {
Douglas Gregorefc46952010-10-12 16:25:54 +0000300 Actions.ActOnReenterTemplateScope(getCurScope(), LM.Method);
Richard Smithc8378952013-04-29 11:55:38 +0000301 ++CurTemplateDepthTracker;
302 }
Douglas Gregorefc46952010-10-12 16:25:54 +0000303 // Start the delayed C++ method declaration
304 Actions.ActOnStartDelayedCXXMethodDeclaration(getCurScope(), LM.Method);
305
306 // Introduce the parameters into scope and parse their default
307 // arguments.
Richard Smithe233fbf2013-01-28 22:42:45 +0000308 ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
309 Scope::FunctionDeclarationScope | Scope::DeclScope);
Douglas Gregorefc46952010-10-12 16:25:54 +0000310 for (unsigned I = 0, N = LM.DefaultArgs.size(); I != N; ++I) {
311 // Introduce the parameter into scope.
Douglas Gregor7fcbd902012-02-21 00:37:24 +0000312 Actions.ActOnDelayedCXXMethodParameter(getCurScope(),
313 LM.DefaultArgs[I].Param);
Douglas Gregorefc46952010-10-12 16:25:54 +0000314
315 if (CachedTokens *Toks = LM.DefaultArgs[I].Toks) {
316 // Save the current token position.
317 SourceLocation origLoc = Tok.getLocation();
318
319 // Parse the default argument from its saved token stream.
320 Toks->push_back(Tok); // So that the current token doesn't get lost
321 PP.EnterTokenStream(&Toks->front(), Toks->size(), true, false);
322
323 // Consume the previously-pushed token.
324 ConsumeAnyToken();
325
326 // Consume the '='.
327 assert(Tok.is(tok::equal) && "Default argument not starting with '='");
328 SourceLocation EqualLoc = ConsumeToken();
329
330 // The argument isn't actually potentially evaluated unless it is
331 // used.
332 EnterExpressionEvaluationContext Eval(Actions,
Douglas Gregor7fcbd902012-02-21 00:37:24 +0000333 Sema::PotentiallyEvaluatedIfUsed,
334 LM.DefaultArgs[I].Param);
Douglas Gregorefc46952010-10-12 16:25:54 +0000335
Sebastian Redldb63af22012-03-14 15:54:00 +0000336 ExprResult DefArgResult;
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000337 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
Sebastian Redl6db0b1b2012-03-20 21:24:03 +0000338 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
Sebastian Redldb63af22012-03-14 15:54:00 +0000339 DefArgResult = ParseBraceInitializer();
Sebastian Redl6db0b1b2012-03-20 21:24:03 +0000340 } else
Sebastian Redldb63af22012-03-14 15:54:00 +0000341 DefArgResult = ParseAssignmentExpression();
Douglas Gregorefc46952010-10-12 16:25:54 +0000342 if (DefArgResult.isInvalid())
343 Actions.ActOnParamDefaultArgumentError(LM.DefaultArgs[I].Param);
344 else {
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000345 if (!TryConsumeToken(tok::cxx_defaultarg_end)) {
Richard Smith1fff95c2013-09-12 23:28:08 +0000346 // The last two tokens are the terminator and the saved value of
347 // Tok; the last token in the default argument is the one before
348 // those.
349 assert(Toks->size() >= 3 && "expected a token in default arg");
350 Diag(Tok.getLocation(), diag::err_default_arg_unparsed)
351 << SourceRange(Tok.getLocation(),
352 (*Toks)[Toks->size() - 3].getLocation());
353 }
Douglas Gregorefc46952010-10-12 16:25:54 +0000354 Actions.ActOnParamDefaultArgument(LM.DefaultArgs[I].Param, EqualLoc,
355 DefArgResult.take());
356 }
357
358 assert(!PP.getSourceManager().isBeforeInTranslationUnit(origLoc,
359 Tok.getLocation()) &&
360 "ParseAssignmentExpression went over the default arg tokens!");
361 // There could be leftover tokens (e.g. because of an error).
362 // Skip through until we reach the original token position.
363 while (Tok.getLocation() != origLoc && Tok.isNot(tok::eof))
364 ConsumeAnyToken();
365
366 delete Toks;
367 LM.DefaultArgs[I].Toks = 0;
368 }
369 }
Douglas Gregor433e0532012-04-16 18:27:27 +0000370
Douglas Gregorefc46952010-10-12 16:25:54 +0000371 PrototypeScope.Exit();
372
373 // Finish the delayed C++ method declaration.
374 Actions.ActOnFinishDelayedCXXMethodDeclaration(getCurScope(), LM.Method);
375}
376
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000377/// ParseLexedMethodDefs - We finished parsing the member specification of a top
378/// (non-nested) C++ class. Now go over the stack of lexed methods that were
379/// collected during its parsing and parse them all.
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000380void Parser::ParseLexedMethodDefs(ParsingClass &Class) {
381 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
Douglas Gregorefc46952010-10-12 16:25:54 +0000382 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope, HasTemplateScope);
Richard Smithc8378952013-04-29 11:55:38 +0000383 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
384 if (HasTemplateScope) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000385 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
Richard Smithc8378952013-04-29 11:55:38 +0000386 ++CurTemplateDepthTracker;
387 }
Douglas Gregore44a2ad2009-05-27 23:11:45 +0000388 bool HasClassScope = !Class.TopLevelClass;
389 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope,
390 HasClassScope);
391
Douglas Gregorefc46952010-10-12 16:25:54 +0000392 for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
393 Class.LateParsedDeclarations[i]->ParseLexedMethodDefs();
394 }
395}
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000396
Douglas Gregorefc46952010-10-12 16:25:54 +0000397void Parser::ParseLexedMethodDef(LexedMethod &LM) {
398 // If this is a member template, introduce the template parameter scope.
399 ParseScope TemplateScope(this, Scope::TemplateParamScope, LM.TemplateScope);
Richard Smithc8378952013-04-29 11:55:38 +0000400 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
401 if (LM.TemplateScope) {
Douglas Gregorefc46952010-10-12 16:25:54 +0000402 Actions.ActOnReenterTemplateScope(getCurScope(), LM.D);
Richard Smithc8378952013-04-29 11:55:38 +0000403 ++CurTemplateDepthTracker;
404 }
Douglas Gregorefc46952010-10-12 16:25:54 +0000405 // Save the current token position.
406 SourceLocation origLoc = Tok.getLocation();
Argyrios Kyrtzidis02041972010-03-31 00:38:09 +0000407
Douglas Gregorefc46952010-10-12 16:25:54 +0000408 assert(!LM.Toks.empty() && "Empty body!");
409 // Append the current token at the end of the new token stream so that it
410 // doesn't get lost.
411 LM.Toks.push_back(Tok);
412 PP.EnterTokenStream(LM.Toks.data(), LM.Toks.size(), true, false);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000413
Douglas Gregorefc46952010-10-12 16:25:54 +0000414 // Consume the previously pushed token.
Argyrios Kyrtzidisc36633c2013-03-27 23:58:17 +0000415 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
Douglas Gregorefc46952010-10-12 16:25:54 +0000416 assert((Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try))
417 && "Inline method not starting with '{', ':' or 'try'");
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000418
Douglas Gregorefc46952010-10-12 16:25:54 +0000419 // Parse the method body. Function body parsing code is similar enough
420 // to be re-used for method bodies as well.
421 ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope);
422 Actions.ActOnStartOfFunctionDef(getCurScope(), LM.D);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000423
Douglas Gregorefc46952010-10-12 16:25:54 +0000424 if (Tok.is(tok::kw_try)) {
Douglas Gregora0ff0c32011-03-16 17:05:57 +0000425 ParseFunctionTryBlock(LM.D, FnScope);
Douglas Gregorefc46952010-10-12 16:25:54 +0000426 assert(!PP.getSourceManager().isBeforeInTranslationUnit(origLoc,
427 Tok.getLocation()) &&
428 "ParseFunctionTryBlock went over the cached tokens!");
429 // There could be leftover tokens (e.g. because of an error).
430 // Skip through until we reach the original token position.
431 while (Tok.getLocation() != origLoc && Tok.isNot(tok::eof))
432 ConsumeAnyToken();
433 return;
434 }
435 if (Tok.is(tok::colon)) {
436 ParseConstructorInitializer(LM.D);
437
438 // Error recovery.
439 if (!Tok.is(tok::l_brace)) {
Douglas Gregora0ff0c32011-03-16 17:05:57 +0000440 FnScope.Exit();
Douglas Gregorefc46952010-10-12 16:25:54 +0000441 Actions.ActOnFinishFunctionBody(LM.D, 0);
Matt Beaumont-Gayd0457922011-09-23 22:39:23 +0000442 while (Tok.getLocation() != origLoc && Tok.isNot(tok::eof))
443 ConsumeAnyToken();
Douglas Gregorefc46952010-10-12 16:25:54 +0000444 return;
445 }
446 } else
447 Actions.ActOnDefaultCtorInitializers(LM.D);
448
Richard Smithc8378952013-04-29 11:55:38 +0000449 assert((Actions.getDiagnostics().hasErrorOccurred() ||
450 !isa<FunctionTemplateDecl>(LM.D) ||
451 cast<FunctionTemplateDecl>(LM.D)->getTemplateParameters()->getDepth()
452 < TemplateParameterDepth) &&
453 "TemplateParameterDepth should be greater than the depth of "
454 "current template being instantiated!");
455
Douglas Gregora0ff0c32011-03-16 17:05:57 +0000456 ParseFunctionStatementBody(LM.D, FnScope);
Douglas Gregorefc46952010-10-12 16:25:54 +0000457
John McCalle68672f2013-03-14 05:13:41 +0000458 // Clear the late-template-parsed bit if we set it before.
459 if (LM.D) getFunctionDecl(LM.D)->setLateTemplateParsed(false);
460
Douglas Gregorefc46952010-10-12 16:25:54 +0000461 if (Tok.getLocation() != origLoc) {
462 // Due to parsing error, we either went over the cached tokens or
463 // there are still cached tokens left. If it's the latter case skip the
464 // leftover tokens.
465 // Since this is an uncommon situation that should be avoided, use the
466 // expensive isBeforeInTranslationUnit call.
467 if (PP.getSourceManager().isBeforeInTranslationUnit(Tok.getLocation(),
468 origLoc))
Argyrios Kyrtzidise1224c82010-06-19 19:58:34 +0000469 while (Tok.getLocation() != origLoc && Tok.isNot(tok::eof))
Argyrios Kyrtzidise9b76af2010-06-17 10:52:22 +0000470 ConsumeAnyToken();
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000471 }
472}
473
Richard Smith938f40b2011-06-11 17:19:42 +0000474/// ParseLexedMemberInitializers - We finished parsing the member specification
475/// of a top (non-nested) C++ class. Now go over the stack of lexed data member
476/// initializers that were collected during its parsing and parse them all.
477void Parser::ParseLexedMemberInitializers(ParsingClass &Class) {
478 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
479 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
480 HasTemplateScope);
Richard Smithc8378952013-04-29 11:55:38 +0000481 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
482 if (HasTemplateScope) {
Richard Smith938f40b2011-06-11 17:19:42 +0000483 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
Richard Smithc8378952013-04-29 11:55:38 +0000484 ++CurTemplateDepthTracker;
485 }
Douglas Gregor3024f072012-04-16 07:05:22 +0000486 // Set or update the scope flags.
Richard Smith938f40b2011-06-11 17:19:42 +0000487 bool AlreadyHasClassScope = Class.TopLevelClass;
Douglas Gregor3024f072012-04-16 07:05:22 +0000488 unsigned ScopeFlags = Scope::ClassScope|Scope::DeclScope;
Richard Smith938f40b2011-06-11 17:19:42 +0000489 ParseScope ClassScope(this, ScopeFlags, !AlreadyHasClassScope);
490 ParseScopeFlags ClassScopeFlags(this, ScopeFlags, AlreadyHasClassScope);
491
492 if (!AlreadyHasClassScope)
493 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(),
494 Class.TagOrTemplate);
495
Benjamin Kramer1d373c62012-05-17 12:01:52 +0000496 if (!Class.LateParsedDeclarations.empty()) {
Douglas Gregor3024f072012-04-16 07:05:22 +0000497 // C++11 [expr.prim.general]p4:
498 // Otherwise, if a member-declarator declares a non-static data member
499 // (9.2) of a class X, the expression this is a prvalue of type "pointer
500 // to X" within the optional brace-or-equal-initializer. It shall not
501 // appear elsewhere in the member-declarator.
502 Sema::CXXThisScopeRAII ThisScope(Actions, Class.TagOrTemplate,
503 /*TypeQuals=*/(unsigned)0);
Richard Smith938f40b2011-06-11 17:19:42 +0000504
Douglas Gregor3024f072012-04-16 07:05:22 +0000505 for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) {
506 Class.LateParsedDeclarations[i]->ParseLexedMemberInitializers();
507 }
508 }
509
Richard Smith938f40b2011-06-11 17:19:42 +0000510 if (!AlreadyHasClassScope)
511 Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(),
512 Class.TagOrTemplate);
513
514 Actions.ActOnFinishDelayedMemberInitializers(Class.TagOrTemplate);
515}
516
517void Parser::ParseLexedMemberInitializer(LateParsedMemberInitializer &MI) {
Richard Smith1a526fd2011-09-29 19:42:27 +0000518 if (!MI.Field || MI.Field->isInvalidDecl())
Richard Smith938f40b2011-06-11 17:19:42 +0000519 return;
520
521 // Append the current token at the end of the new token stream so that it
522 // doesn't get lost.
523 MI.Toks.push_back(Tok);
524 PP.EnterTokenStream(MI.Toks.data(), MI.Toks.size(), true, false);
525
526 // Consume the previously pushed token.
Argyrios Kyrtzidisc36633c2013-03-27 23:58:17 +0000527 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
Richard Smith938f40b2011-06-11 17:19:42 +0000528
529 SourceLocation EqualLoc;
Richard Smith2b013182012-06-10 03:12:00 +0000530
Douglas Gregor926410d2012-02-21 02:22:07 +0000531 ExprResult Init = ParseCXXMemberInitializer(MI.Field, /*IsFunction=*/false,
532 EqualLoc);
Richard Smith938f40b2011-06-11 17:19:42 +0000533
534 Actions.ActOnCXXInClassMemberInitializer(MI.Field, EqualLoc, Init.release());
535
536 // The next token should be our artificial terminating EOF token.
537 if (Tok.isNot(tok::eof)) {
538 SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
539 if (!EndLoc.isValid())
540 EndLoc = Tok.getLocation();
541 // No fixit; we can't recover as if there were a semicolon here.
542 Diag(EndLoc, diag::err_expected_semi_decl_list);
543
544 // Consume tokens until we hit the artificial EOF.
545 while (Tok.isNot(tok::eof))
546 ConsumeAnyToken();
547 }
548 ConsumeAnyToken();
549}
550
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000551/// ConsumeAndStoreUntil - Consume and store the token at the passed token
Douglas Gregor4d87df52008-12-16 21:30:33 +0000552/// container until the token 'T' is reached (which gets
Mike Stump11289f42009-09-09 15:08:12 +0000553/// consumed/stored too, if ConsumeFinalToken).
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000554/// If StopAtSemi is true, then we will stop early at a ';' character.
Douglas Gregor4d87df52008-12-16 21:30:33 +0000555/// Returns true if token 'T1' or 'T2' was found.
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000556/// NOTE: This is a specialized version of Parser::SkipUntil.
Douglas Gregor4d87df52008-12-16 21:30:33 +0000557bool Parser::ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
558 CachedTokens &Toks,
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000559 bool StopAtSemi, bool ConsumeFinalToken) {
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000560 // We always want this function to consume at least one token if the first
561 // token isn't T and if not at EOF.
562 bool isFirstTokenConsumed = true;
563 while (1) {
564 // If we found one of the tokens, stop and return true.
Douglas Gregor4d87df52008-12-16 21:30:33 +0000565 if (Tok.is(T1) || Tok.is(T2)) {
566 if (ConsumeFinalToken) {
567 Toks.push_back(Tok);
568 ConsumeAnyToken();
569 }
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000570 return true;
571 }
572
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000573 switch (Tok.getKind()) {
574 case tok::eof:
Richard Smith34f30512013-11-23 04:06:09 +0000575 case tok::annot_module_begin:
576 case tok::annot_module_end:
577 case tok::annot_module_include:
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000578 // Ran out of tokens.
579 return false;
580
581 case tok::l_paren:
582 // Recursively consume properly-nested parens.
583 Toks.push_back(Tok);
584 ConsumeParen();
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000585 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000586 break;
587 case tok::l_square:
588 // Recursively consume properly-nested square brackets.
589 Toks.push_back(Tok);
590 ConsumeBracket();
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000591 ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000592 break;
593 case tok::l_brace:
594 // Recursively consume properly-nested braces.
595 Toks.push_back(Tok);
596 ConsumeBrace();
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000597 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000598 break;
599
600 // Okay, we found a ']' or '}' or ')', which we think should be balanced.
601 // Since the user wasn't looking for this token (if they were, it would
602 // already be handled), this isn't balanced. If there is a LHS token at a
603 // higher level, we will assume that this matches the unbalanced token
604 // and return it. Otherwise, this is a spurious RHS token, which we skip.
605 case tok::r_paren:
606 if (ParenCount && !isFirstTokenConsumed)
607 return false; // Matches something.
608 Toks.push_back(Tok);
609 ConsumeParen();
610 break;
611 case tok::r_square:
612 if (BracketCount && !isFirstTokenConsumed)
613 return false; // Matches something.
614 Toks.push_back(Tok);
615 ConsumeBracket();
616 break;
617 case tok::r_brace:
618 if (BraceCount && !isFirstTokenConsumed)
619 return false; // Matches something.
620 Toks.push_back(Tok);
621 ConsumeBrace();
622 break;
623
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000624 case tok::code_completion:
625 Toks.push_back(Tok);
626 ConsumeCodeCompletionToken();
627 break;
628
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000629 case tok::string_literal:
630 case tok::wide_string_literal:
Douglas Gregorfb65e592011-07-27 05:40:30 +0000631 case tok::utf8_string_literal:
632 case tok::utf16_string_literal:
633 case tok::utf32_string_literal:
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000634 Toks.push_back(Tok);
635 ConsumeStringToken();
636 break;
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +0000637 case tok::semi:
638 if (StopAtSemi)
639 return false;
640 // FALL THROUGH.
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +0000641 default:
642 // consume this token.
643 Toks.push_back(Tok);
644 ConsumeToken();
645 break;
646 }
647 isFirstTokenConsumed = false;
648 }
649}
Sebastian Redla74948d2011-09-24 17:48:25 +0000650
651/// \brief Consume tokens and store them in the passed token container until
652/// we've passed the try keyword and constructor initializers and have consumed
Sebastian Redl0d164012011-09-30 08:32:17 +0000653/// the opening brace of the function body. The opening brace will be consumed
654/// if and only if there was no error.
Sebastian Redla74948d2011-09-24 17:48:25 +0000655///
Richard Smithcde3fd82013-07-04 00:13:48 +0000656/// \return True on error.
Sebastian Redl0d164012011-09-30 08:32:17 +0000657bool Parser::ConsumeAndStoreFunctionPrologue(CachedTokens &Toks) {
Sebastian Redla74948d2011-09-24 17:48:25 +0000658 if (Tok.is(tok::kw_try)) {
659 Toks.push_back(Tok);
660 ConsumeToken();
661 }
Richard Smithcde3fd82013-07-04 00:13:48 +0000662
663 if (Tok.isNot(tok::colon)) {
664 // Easy case, just a function body.
665
666 // Grab any remaining garbage to be diagnosed later. We stop when we reach a
667 // brace: an opening one is the function body, while a closing one probably
668 // means we've reached the end of the class.
669 ConsumeAndStoreUntil(tok::l_brace, tok::r_brace, Toks,
670 /*StopAtSemi=*/true,
671 /*ConsumeFinalToken=*/false);
672 if (Tok.isNot(tok::l_brace))
Alp Tokerec543272013-12-24 09:48:30 +0000673 return Diag(Tok.getLocation(), diag::err_expected) << tok::l_brace;
Richard Smithcde3fd82013-07-04 00:13:48 +0000674
Sebastian Redla74948d2011-09-24 17:48:25 +0000675 Toks.push_back(Tok);
Richard Smithcde3fd82013-07-04 00:13:48 +0000676 ConsumeBrace();
677 return false;
Eli Friedman7cd4a9b2012-02-22 04:49:04 +0000678 }
Sebastian Redl0d164012011-09-30 08:32:17 +0000679
680 Toks.push_back(Tok);
Richard Smithcde3fd82013-07-04 00:13:48 +0000681 ConsumeToken();
682
683 // We can't reliably skip over a mem-initializer-id, because it could be
684 // a template-id involving not-yet-declared names. Given:
685 //
686 // S ( ) : a < b < c > ( e )
687 //
688 // 'e' might be an initializer or part of a template argument, depending
689 // on whether 'b' is a template.
690
691 // Track whether we might be inside a template argument. We can give
692 // significantly better diagnostics if we know that we're not.
693 bool MightBeTemplateArgument = false;
694
695 while (true) {
696 // Skip over the mem-initializer-id, if possible.
697 if (Tok.is(tok::kw_decltype)) {
698 Toks.push_back(Tok);
699 SourceLocation OpenLoc = ConsumeToken();
700 if (Tok.isNot(tok::l_paren))
701 return Diag(Tok.getLocation(), diag::err_expected_lparen_after)
702 << "decltype";
703 Toks.push_back(Tok);
704 ConsumeParen();
705 if (!ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/true)) {
Alp Tokerec543272013-12-24 09:48:30 +0000706 Diag(Tok.getLocation(), diag::err_expected) << tok::r_paren;
707 Diag(OpenLoc, diag::note_matching) << tok::l_paren;
Richard Smithcde3fd82013-07-04 00:13:48 +0000708 return true;
709 }
710 }
711 do {
712 // Walk over a component of a nested-name-specifier.
713 if (Tok.is(tok::coloncolon)) {
714 Toks.push_back(Tok);
715 ConsumeToken();
716
717 if (Tok.is(tok::kw_template)) {
718 Toks.push_back(Tok);
719 ConsumeToken();
720 }
721 }
722
723 if (Tok.is(tok::identifier) || Tok.is(tok::kw_template)) {
724 Toks.push_back(Tok);
725 ConsumeToken();
726 } else if (Tok.is(tok::code_completion)) {
727 Toks.push_back(Tok);
728 ConsumeCodeCompletionToken();
729 // Consume the rest of the initializers permissively.
730 // FIXME: We should be able to perform code-completion here even if
731 // there isn't a subsequent '{' token.
732 MightBeTemplateArgument = true;
733 break;
734 } else {
735 break;
736 }
737 } while (Tok.is(tok::coloncolon));
738
739 if (Tok.is(tok::less))
740 MightBeTemplateArgument = true;
741
742 if (MightBeTemplateArgument) {
743 // We may be inside a template argument list. Grab up to the start of the
744 // next parenthesized initializer or braced-init-list. This *might* be the
745 // initializer, or it might be a subexpression in the template argument
746 // list.
747 // FIXME: Count angle brackets, and clear MightBeTemplateArgument
748 // if all angles are closed.
749 if (!ConsumeAndStoreUntil(tok::l_paren, tok::l_brace, Toks,
750 /*StopAtSemi=*/true,
751 /*ConsumeFinalToken=*/false)) {
752 // We're not just missing the initializer, we're also missing the
753 // function body!
Alp Tokerec543272013-12-24 09:48:30 +0000754 return Diag(Tok.getLocation(), diag::err_expected) << tok::l_brace;
Richard Smithcde3fd82013-07-04 00:13:48 +0000755 }
756 } else if (Tok.isNot(tok::l_paren) && Tok.isNot(tok::l_brace)) {
757 // We found something weird in a mem-initializer-id.
Alp Tokerec543272013-12-24 09:48:30 +0000758 if (getLangOpts().CPlusPlus11)
759 return Diag(Tok.getLocation(), diag::err_expected_either)
760 << tok::l_paren << tok::l_brace;
761 else
762 return Diag(Tok.getLocation(), diag::err_expected) << tok::l_paren;
Richard Smithcde3fd82013-07-04 00:13:48 +0000763 }
764
765 tok::TokenKind kind = Tok.getKind();
766 Toks.push_back(Tok);
767 bool IsLParen = (kind == tok::l_paren);
768 SourceLocation OpenLoc = Tok.getLocation();
769
770 if (IsLParen) {
771 ConsumeParen();
772 } else {
773 assert(kind == tok::l_brace && "Must be left paren or brace here.");
774 ConsumeBrace();
775 // In C++03, this has to be the start of the function body, which
776 // means the initializer is malformed; we'll diagnose it later.
777 if (!getLangOpts().CPlusPlus11)
778 return false;
779 }
780
781 // Grab the initializer (or the subexpression of the template argument).
782 // FIXME: If we support lambdas here, we'll need to set StopAtSemi to false
783 // if we might be inside the braces of a lambda-expression.
Alp Tokerec543272013-12-24 09:48:30 +0000784 tok::TokenKind CloseKind = IsLParen ? tok::r_paren : tok::r_brace;
785 if (!ConsumeAndStoreUntil(CloseKind, Toks, /*StopAtSemi=*/true)) {
786 Diag(Tok, diag::err_expected) << CloseKind;
787 Diag(OpenLoc, diag::note_matching) << kind;
Richard Smithcde3fd82013-07-04 00:13:48 +0000788 return true;
789 }
790
791 // Grab pack ellipsis, if present.
792 if (Tok.is(tok::ellipsis)) {
793 Toks.push_back(Tok);
794 ConsumeToken();
795 }
796
797 // If we know we just consumed a mem-initializer, we must have ',' or '{'
798 // next.
799 if (Tok.is(tok::comma)) {
800 Toks.push_back(Tok);
801 ConsumeToken();
802 } else if (Tok.is(tok::l_brace)) {
803 // This is the function body if the ')' or '}' is immediately followed by
804 // a '{'. That cannot happen within a template argument, apart from the
805 // case where a template argument contains a compound literal:
806 //
807 // S ( ) : a < b < c > ( d ) { }
808 // // End of declaration, or still inside the template argument?
809 //
810 // ... and the case where the template argument contains a lambda:
811 //
812 // S ( ) : a < 0 && b < c > ( d ) + [ ] ( ) { return 0; }
813 // ( ) > ( ) { }
814 //
815 // FIXME: Disambiguate these cases. Note that the latter case is probably
816 // going to be made ill-formed by core issue 1607.
817 Toks.push_back(Tok);
818 ConsumeBrace();
819 return false;
820 } else if (!MightBeTemplateArgument) {
Alp Tokerec543272013-12-24 09:48:30 +0000821 return Diag(Tok.getLocation(), diag::err_expected_either) << tok::l_brace
822 << tok::comma;
Richard Smithcde3fd82013-07-04 00:13:48 +0000823 }
824 }
Sebastian Redla74948d2011-09-24 17:48:25 +0000825}
Richard Smith1fff95c2013-09-12 23:28:08 +0000826
827/// \brief Consume and store tokens from the '?' to the ':' in a conditional
828/// expression.
829bool Parser::ConsumeAndStoreConditional(CachedTokens &Toks) {
830 // Consume '?'.
831 assert(Tok.is(tok::question));
832 Toks.push_back(Tok);
833 ConsumeToken();
834
835 while (Tok.isNot(tok::colon)) {
836 if (!ConsumeAndStoreUntil(tok::question, tok::colon, Toks, /*StopAtSemi*/true,
837 /*ConsumeFinalToken*/false))
838 return false;
839
840 // If we found a nested conditional, consume it.
841 if (Tok.is(tok::question) && !ConsumeAndStoreConditional(Toks))
842 return false;
843 }
844
845 // Consume ':'.
846 Toks.push_back(Tok);
847 ConsumeToken();
848 return true;
849}
850
851/// \brief A tentative parsing action that can also revert token annotations.
852class Parser::UnannotatedTentativeParsingAction : public TentativeParsingAction {
853public:
854 explicit UnannotatedTentativeParsingAction(Parser &Self,
855 tok::TokenKind EndKind)
856 : TentativeParsingAction(Self), Self(Self), EndKind(EndKind) {
857 // Stash away the old token stream, so we can restore it once the
858 // tentative parse is complete.
859 TentativeParsingAction Inner(Self);
860 Self.ConsumeAndStoreUntil(EndKind, Toks, true, /*ConsumeFinalToken*/false);
861 Inner.Revert();
862 }
863
864 void RevertAnnotations() {
865 Revert();
866
867 // Put back the original tokens.
Alexey Bataevee6507d2013-11-18 08:17:37 +0000868 Self.SkipUntil(EndKind, StopAtSemi | StopBeforeMatch);
Richard Smith1fff95c2013-09-12 23:28:08 +0000869 if (Toks.size()) {
870 Token *Buffer = new Token[Toks.size()];
871 std::copy(Toks.begin() + 1, Toks.end(), Buffer);
872 Buffer[Toks.size() - 1] = Self.Tok;
873 Self.PP.EnterTokenStream(Buffer, Toks.size(), true, /*Owned*/true);
874
875 Self.Tok = Toks.front();
876 }
877 }
878
879private:
880 Parser &Self;
881 CachedTokens Toks;
882 tok::TokenKind EndKind;
883};
884
885/// ConsumeAndStoreInitializer - Consume and store the token at the passed token
886/// container until the end of the current initializer expression (either a
887/// default argument or an in-class initializer for a non-static data member).
888/// The final token is not consumed.
889bool Parser::ConsumeAndStoreInitializer(CachedTokens &Toks,
890 CachedInitKind CIK) {
891 // We always want this function to consume at least one token if not at EOF.
892 bool IsFirstTokenConsumed = true;
893
894 // Number of possible unclosed <s we've seen so far. These might be templates,
895 // and might not, but if there were none of them (or we know for sure that
896 // we're within a template), we can avoid a tentative parse.
897 unsigned AngleCount = 0;
898 unsigned KnownTemplateCount = 0;
899
900 while (1) {
901 switch (Tok.getKind()) {
902 case tok::comma:
903 // If we might be in a template, perform a tentative parse to check.
904 if (!AngleCount)
905 // Not a template argument: this is the end of the initializer.
906 return true;
907 if (KnownTemplateCount)
908 goto consume_token;
909
910 // We hit a comma inside angle brackets. This is the hard case. The
911 // rule we follow is:
912 // * For a default argument, if the tokens after the comma form a
913 // syntactically-valid parameter-declaration-clause, in which each
914 // parameter has an initializer, then this comma ends the default
915 // argument.
916 // * For a default initializer, if the tokens after the comma form a
917 // syntactically-valid init-declarator-list, then this comma ends
918 // the default initializer.
919 {
920 UnannotatedTentativeParsingAction PA(*this,
921 CIK == CIK_DefaultInitializer
922 ? tok::semi : tok::r_paren);
923 Sema::TentativeAnalysisScope Scope(Actions);
924
925 TPResult Result = TPResult::Error();
926 ConsumeToken();
927 switch (CIK) {
928 case CIK_DefaultInitializer:
929 Result = TryParseInitDeclaratorList();
930 // If we parsed a complete, ambiguous init-declarator-list, this
931 // is only syntactically-valid if it's followed by a semicolon.
932 if (Result == TPResult::Ambiguous() && Tok.isNot(tok::semi))
933 Result = TPResult::False();
934 break;
935
936 case CIK_DefaultArgument:
937 bool InvalidAsDeclaration = false;
938 Result = TryParseParameterDeclarationClause(
939 &InvalidAsDeclaration, /*VersusTemplateArgument*/true);
940 // If this is an expression or a declaration with a missing
941 // 'typename', assume it's not a declaration.
942 if (Result == TPResult::Ambiguous() && InvalidAsDeclaration)
943 Result = TPResult::False();
944 break;
945 }
946
947 // If what follows could be a declaration, it is a declaration.
948 if (Result != TPResult::False() && Result != TPResult::Error()) {
949 PA.Revert();
950 return true;
951 }
952
953 // In the uncommon case that we decide the following tokens are part
954 // of a template argument, revert any annotations we've performed in
955 // those tokens. We're not going to look them up until we've parsed
956 // the rest of the class, and that might add more declarations.
957 PA.RevertAnnotations();
958 }
959
960 // Keep going. We know we're inside a template argument list now.
961 ++KnownTemplateCount;
962 goto consume_token;
963
964 case tok::eof:
Richard Smith34f30512013-11-23 04:06:09 +0000965 case tok::annot_module_begin:
966 case tok::annot_module_end:
967 case tok::annot_module_include:
Richard Smith1fff95c2013-09-12 23:28:08 +0000968 // Ran out of tokens.
969 return false;
970
971 case tok::less:
972 // FIXME: A '<' can only start a template-id if it's preceded by an
973 // identifier, an operator-function-id, or a literal-operator-id.
974 ++AngleCount;
975 goto consume_token;
976
977 case tok::question:
978 // In 'a ? b : c', 'b' can contain an unparenthesized comma. If it does,
979 // that is *never* the end of the initializer. Skip to the ':'.
980 if (!ConsumeAndStoreConditional(Toks))
981 return false;
982 break;
983
984 case tok::greatergreatergreater:
985 if (!getLangOpts().CPlusPlus11)
986 goto consume_token;
987 if (AngleCount) --AngleCount;
988 if (KnownTemplateCount) --KnownTemplateCount;
989 // Fall through.
990 case tok::greatergreater:
991 if (!getLangOpts().CPlusPlus11)
992 goto consume_token;
993 if (AngleCount) --AngleCount;
994 if (KnownTemplateCount) --KnownTemplateCount;
995 // Fall through.
996 case tok::greater:
997 if (AngleCount) --AngleCount;
998 if (KnownTemplateCount) --KnownTemplateCount;
999 goto consume_token;
1000
1001 case tok::kw_template:
1002 // 'template' identifier '<' is known to start a template argument list,
1003 // and can be used to disambiguate the parse.
1004 // FIXME: Support all forms of 'template' unqualified-id '<'.
1005 Toks.push_back(Tok);
1006 ConsumeToken();
1007 if (Tok.is(tok::identifier)) {
1008 Toks.push_back(Tok);
1009 ConsumeToken();
1010 if (Tok.is(tok::less)) {
1011 ++KnownTemplateCount;
1012 Toks.push_back(Tok);
1013 ConsumeToken();
1014 }
1015 }
1016 break;
1017
1018 case tok::kw_operator:
1019 // If 'operator' precedes other punctuation, that punctuation loses
1020 // its special behavior.
1021 Toks.push_back(Tok);
1022 ConsumeToken();
1023 switch (Tok.getKind()) {
1024 case tok::comma:
1025 case tok::greatergreatergreater:
1026 case tok::greatergreater:
1027 case tok::greater:
1028 case tok::less:
1029 Toks.push_back(Tok);
1030 ConsumeToken();
1031 break;
1032 default:
1033 break;
1034 }
1035 break;
1036
1037 case tok::l_paren:
1038 // Recursively consume properly-nested parens.
1039 Toks.push_back(Tok);
1040 ConsumeParen();
1041 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
1042 break;
1043 case tok::l_square:
1044 // Recursively consume properly-nested square brackets.
1045 Toks.push_back(Tok);
1046 ConsumeBracket();
1047 ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false);
1048 break;
1049 case tok::l_brace:
1050 // Recursively consume properly-nested braces.
1051 Toks.push_back(Tok);
1052 ConsumeBrace();
1053 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1054 break;
1055
1056 // Okay, we found a ']' or '}' or ')', which we think should be balanced.
1057 // Since the user wasn't looking for this token (if they were, it would
1058 // already be handled), this isn't balanced. If there is a LHS token at a
1059 // higher level, we will assume that this matches the unbalanced token
1060 // and return it. Otherwise, this is a spurious RHS token, which we skip.
1061 case tok::r_paren:
1062 if (CIK == CIK_DefaultArgument)
1063 return true; // End of the default argument.
1064 if (ParenCount && !IsFirstTokenConsumed)
1065 return false; // Matches something.
1066 goto consume_token;
1067 case tok::r_square:
1068 if (BracketCount && !IsFirstTokenConsumed)
1069 return false; // Matches something.
1070 goto consume_token;
1071 case tok::r_brace:
1072 if (BraceCount && !IsFirstTokenConsumed)
1073 return false; // Matches something.
1074 goto consume_token;
1075
1076 case tok::code_completion:
1077 Toks.push_back(Tok);
1078 ConsumeCodeCompletionToken();
1079 break;
1080
1081 case tok::string_literal:
1082 case tok::wide_string_literal:
1083 case tok::utf8_string_literal:
1084 case tok::utf16_string_literal:
1085 case tok::utf32_string_literal:
1086 Toks.push_back(Tok);
1087 ConsumeStringToken();
1088 break;
1089 case tok::semi:
1090 if (CIK == CIK_DefaultInitializer)
1091 return true; // End of the default initializer.
1092 // FALL THROUGH.
1093 default:
1094 consume_token:
1095 Toks.push_back(Tok);
1096 ConsumeToken();
1097 break;
1098 }
1099 IsFirstTokenConsumed = false;
1100 }
1101}