blob: 8b8a083a0667895cce8e7ed8e2dd7dbfe04803c3 [file] [log] [blame]
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001//===--- SemaLambda.cpp - Semantic Analysis for C++11 Lambdas -------------===//
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 semantic analysis for C++ lambda expressions.
11//
12//===----------------------------------------------------------------------===//
13#include "clang/Sema/DeclSpec.h"
14#include "clang/Sema/Initialization.h"
15#include "clang/Sema/Lookup.h"
16#include "clang/Sema/ScopeInfo.h"
17#include "clang/Sema/SemaInternal.h"
Douglas Gregor3ac109c2012-02-10 17:46:20 +000018#include "clang/Lex/Preprocessor.h"
Douglas Gregore2a7ad02012-02-08 21:18:48 +000019#include "clang/AST/ExprCXX.h"
20using namespace clang;
21using namespace sema;
22
Douglas Gregordfca6f52012-02-13 22:00:16 +000023CXXRecordDecl *Sema::createLambdaClosureType(SourceRange IntroducerRange) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +000024 DeclContext *DC = CurContext;
25 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
26 DC = DC->getParent();
Douglas Gregordfca6f52012-02-13 22:00:16 +000027
Douglas Gregore2a7ad02012-02-08 21:18:48 +000028 // Start constructing the lambda class.
Douglas Gregorda8962a2012-02-13 15:44:47 +000029 CXXRecordDecl *Class = CXXRecordDecl::CreateLambda(Context, DC,
Douglas Gregordfca6f52012-02-13 22:00:16 +000030 IntroducerRange.getBegin());
Douglas Gregore2a7ad02012-02-08 21:18:48 +000031 CurContext->addDecl(Class);
Douglas Gregordfca6f52012-02-13 22:00:16 +000032
33 return Class;
34}
Douglas Gregore2a7ad02012-02-08 21:18:48 +000035
Douglas Gregordfca6f52012-02-13 22:00:16 +000036CXXMethodDecl *Sema::startLambdaDefinition(CXXRecordDecl *Class,
37 SourceRange IntroducerRange,
38 TypeSourceInfo *MethodType,
39 SourceLocation EndLoc) {
40 // C++11 [expr.prim.lambda]p5:
41 // The closure type for a lambda-expression has a public inline function
42 // call operator (13.5.4) whose parameters and return type are described by
43 // the lambda-expression's parameter-declaration-clause and
44 // trailing-return-type respectively.
45 DeclarationName MethodName
46 = Context.DeclarationNames.getCXXOperatorName(OO_Call);
47 DeclarationNameLoc MethodNameLoc;
48 MethodNameLoc.CXXOperatorName.BeginOpNameLoc
49 = IntroducerRange.getBegin().getRawEncoding();
50 MethodNameLoc.CXXOperatorName.EndOpNameLoc
51 = IntroducerRange.getEnd().getRawEncoding();
52 CXXMethodDecl *Method
53 = CXXMethodDecl::Create(Context, Class, EndLoc,
54 DeclarationNameInfo(MethodName,
55 IntroducerRange.getBegin(),
56 MethodNameLoc),
57 MethodType->getType(), MethodType,
58 /*isStatic=*/false,
59 SC_None,
60 /*isInline=*/true,
61 /*isConstExpr=*/false,
62 EndLoc);
63 Method->setAccess(AS_public);
64
65 // Temporarily set the lexical declaration context to the current
66 // context, so that the Scope stack matches the lexical nesting.
67 Method->setLexicalDeclContext(Class->getDeclContext());
68
69 return Method;
70}
71
72LambdaScopeInfo *Sema::enterLambdaScope(CXXMethodDecl *CallOperator,
73 SourceRange IntroducerRange,
74 LambdaCaptureDefault CaptureDefault,
75 bool ExplicitParams,
76 bool ExplicitResultType,
77 bool Mutable) {
78 PushLambdaScope(CallOperator->getParent(), CallOperator);
79 LambdaScopeInfo *LSI = getCurLambda();
80 if (CaptureDefault == LCD_ByCopy)
81 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
82 else if (CaptureDefault == LCD_ByRef)
83 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
84 LSI->IntroducerRange = IntroducerRange;
85 LSI->ExplicitParams = ExplicitParams;
86 LSI->Mutable = Mutable;
87
88 if (ExplicitResultType) {
89 LSI->ReturnType = CallOperator->getResultType();
Douglas Gregor53393f22012-02-14 21:20:44 +000090
91 if (!LSI->ReturnType->isDependentType() &&
92 !LSI->ReturnType->isVoidType()) {
93 if (RequireCompleteType(CallOperator->getLocStart(), LSI->ReturnType,
94 diag::err_lambda_incomplete_result)) {
95 // Do nothing.
96 } else if (LSI->ReturnType->isObjCObjectOrInterfaceType()) {
97 Diag(CallOperator->getLocStart(), diag::err_lambda_objc_object_result)
98 << LSI->ReturnType;
99 }
100 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000101 } else {
102 LSI->HasImplicitReturnType = true;
103 }
104
105 return LSI;
106}
107
108void Sema::finishLambdaExplicitCaptures(LambdaScopeInfo *LSI) {
109 LSI->finishedExplicitCaptures();
110}
111
112void Sema::addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope,
113 llvm::ArrayRef<ParmVarDecl *> Params) {
114 CallOperator->setParams(Params);
115 CheckParmsForFunctionDef(const_cast<ParmVarDecl **>(Params.begin()),
116 const_cast<ParmVarDecl **>(Params.end()),
117 /*CheckParameterNames=*/false);
118
119 // Introduce our parameters into the function scope
120 for (unsigned p = 0, NumParams = CallOperator->getNumParams();
121 p < NumParams; ++p) {
122 ParmVarDecl *Param = CallOperator->getParamDecl(p);
123 Param->setOwningFunction(CallOperator);
124
125 // If this has an identifier, add it to the scope stack.
126 if (CurScope && Param->getIdentifier()) {
127 CheckShadow(CurScope, Param);
128
129 PushOnScopeChains(Param, CurScope);
130 }
131 }
132}
133
134void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
135 Declarator &ParamInfo,
136 Scope *CurScope) {
137 CXXRecordDecl *Class = createLambdaClosureType(Intro.Range);
138
139 // Determine the signature of the call operator.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000140 TypeSourceInfo *MethodTyInfo;
141 bool ExplicitParams = true;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000142 bool ExplicitResultType = true;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000143 SourceLocation EndLoc;
144 if (ParamInfo.getNumTypeObjects() == 0) {
145 // C++11 [expr.prim.lambda]p4:
146 // If a lambda-expression does not include a lambda-declarator, it is as
147 // if the lambda-declarator were ().
148 FunctionProtoType::ExtProtoInfo EPI;
Richard Smitheefb3d52012-02-10 09:58:53 +0000149 EPI.HasTrailingReturn = true;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000150 EPI.TypeQuals |= DeclSpec::TQ_const;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000151 QualType MethodTy = Context.getFunctionType(Context.DependentTy,
152 /*Args=*/0, /*NumArgs=*/0, EPI);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000153 MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy);
154 ExplicitParams = false;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000155 ExplicitResultType = false;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000156 EndLoc = Intro.Range.getEnd();
157 } else {
158 assert(ParamInfo.isFunctionDeclarator() &&
159 "lambda-declarator is a function");
160 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo();
161
162 // C++11 [expr.prim.lambda]p5:
163 // This function call operator is declared const (9.3.1) if and only if
164 // the lambda-expression's parameter-declaration-clause is not followed
165 // by mutable. It is neither virtual nor declared volatile. [...]
166 if (!FTI.hasMutableQualifier())
167 FTI.TypeQuals |= DeclSpec::TQ_const;
168
169 // C++11 [expr.prim.lambda]p5:
170 // [...] Default arguments (8.3.6) shall not be specified in the
171 // parameter-declaration-clause of a lambda-declarator.
172 CheckExtraCXXDefaultArguments(ParamInfo);
173
174 MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000175 assert(MethodTyInfo && "no type from lambda-declarator");
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000176 EndLoc = ParamInfo.getSourceRange().getEnd();
Douglas Gregordfca6f52012-02-13 22:00:16 +0000177
178 ExplicitResultType
179 = MethodTyInfo->getType()->getAs<FunctionType>()->getResultType()
180 != Context.DependentTy;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000181 }
182
Douglas Gregordfca6f52012-02-13 22:00:16 +0000183 CXXMethodDecl *Method = startLambdaDefinition(Class, Intro.Range,
184 MethodTyInfo, EndLoc);
185
Douglas Gregor503384f2012-02-09 00:47:04 +0000186 // Attributes on the lambda apply to the method.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000187 ProcessDeclAttributes(CurScope, Method, ParamInfo);
188
Douglas Gregor503384f2012-02-09 00:47:04 +0000189 // Introduce the function call operator as the current declaration context.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000190 PushDeclContext(CurScope, Method);
191
192 // Introduce the lambda scope.
Douglas Gregordfca6f52012-02-13 22:00:16 +0000193 LambdaScopeInfo *LSI
194 = enterLambdaScope(Method, Intro.Range, Intro.Default, ExplicitParams,
195 ExplicitResultType,
196 (Method->getTypeQualifiers() & Qualifiers::Const) == 0);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000197
198 // Handle explicit captures.
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000199 SourceLocation PrevCaptureLoc
200 = Intro.Default == LCD_None? Intro.Range.getBegin() : Intro.DefaultLoc;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000201 for (llvm::SmallVector<LambdaCapture, 4>::const_iterator
202 C = Intro.Captures.begin(),
203 E = Intro.Captures.end();
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000204 C != E;
205 PrevCaptureLoc = C->Loc, ++C) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000206 if (C->Kind == LCK_This) {
207 // C++11 [expr.prim.lambda]p8:
208 // An identifier or this shall not appear more than once in a
209 // lambda-capture.
210 if (LSI->isCXXThisCaptured()) {
211 Diag(C->Loc, diag::err_capture_more_than_once)
212 << "'this'"
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000213 << SourceRange(LSI->getCXXThisCapture().getLocation())
214 << FixItHint::CreateRemoval(
215 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000216 continue;
217 }
218
219 // C++11 [expr.prim.lambda]p8:
220 // If a lambda-capture includes a capture-default that is =, the
221 // lambda-capture shall not contain this [...].
222 if (Intro.Default == LCD_ByCopy) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000223 Diag(C->Loc, diag::err_this_capture_with_copy_default)
224 << FixItHint::CreateRemoval(
225 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000226 continue;
227 }
228
229 // C++11 [expr.prim.lambda]p12:
230 // If this is captured by a local lambda expression, its nearest
231 // enclosing function shall be a non-static member function.
232 QualType ThisCaptureType = getCurrentThisType();
233 if (ThisCaptureType.isNull()) {
234 Diag(C->Loc, diag::err_this_capture) << true;
235 continue;
236 }
237
238 CheckCXXThisCapture(C->Loc, /*Explicit=*/true);
239 continue;
240 }
241
242 assert(C->Id && "missing identifier for capture");
243
244 // C++11 [expr.prim.lambda]p8:
245 // If a lambda-capture includes a capture-default that is &, the
246 // identifiers in the lambda-capture shall not be preceded by &.
247 // If a lambda-capture includes a capture-default that is =, [...]
248 // each identifier it contains shall be preceded by &.
249 if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000250 Diag(C->Loc, diag::err_reference_capture_with_reference_default)
251 << FixItHint::CreateRemoval(
252 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000253 continue;
254 } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000255 Diag(C->Loc, diag::err_copy_capture_with_copy_default)
256 << FixItHint::CreateRemoval(
257 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000258 continue;
259 }
260
261 DeclarationNameInfo Name(C->Id, C->Loc);
262 LookupResult R(*this, Name, LookupOrdinaryName);
263 LookupName(R, CurScope);
264 if (R.isAmbiguous())
265 continue;
266 if (R.empty()) {
267 // FIXME: Disable corrections that would add qualification?
268 CXXScopeSpec ScopeSpec;
269 DeclFilterCCC<VarDecl> Validator;
270 if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
271 continue;
272 }
273
274 // C++11 [expr.prim.lambda]p10:
275 // The identifiers in a capture-list are looked up using the usual rules
276 // for unqualified name lookup (3.4.1); each such lookup shall find a
277 // variable with automatic storage duration declared in the reaching
278 // scope of the local lambda expression.
Douglas Gregor53393f22012-02-14 21:20:44 +0000279 //
280 // Note that the 'reaching scope' check happens in TryCaptureVar.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000281 VarDecl *Var = R.getAsSingle<VarDecl>();
282 if (!Var) {
283 Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
284 continue;
285 }
286
287 if (!Var->hasLocalStorage()) {
288 Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
289 Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
290 continue;
291 }
292
293 // C++11 [expr.prim.lambda]p8:
294 // An identifier or this shall not appear more than once in a
295 // lambda-capture.
296 if (LSI->isCaptured(Var)) {
297 Diag(C->Loc, diag::err_capture_more_than_once)
298 << C->Id
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000299 << SourceRange(LSI->getCapture(Var).getLocation())
300 << FixItHint::CreateRemoval(
301 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000302 continue;
303 }
304
Douglas Gregora7365242012-02-14 19:27:52 +0000305 // C++11 [expr.prim.lambda]p23:
306 // A capture followed by an ellipsis is a pack expansion (14.5.3).
307 SourceLocation EllipsisLoc;
308 if (C->EllipsisLoc.isValid()) {
309 if (Var->isParameterPack()) {
310 EllipsisLoc = C->EllipsisLoc;
311 } else {
312 Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
313 << SourceRange(C->Loc);
314
315 // Just ignore the ellipsis.
316 }
317 } else if (Var->isParameterPack()) {
318 Diag(C->Loc, diag::err_lambda_unexpanded_pack);
319 continue;
320 }
321
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000322 TryCaptureKind Kind = C->Kind == LCK_ByRef ? TryCapture_ExplicitByRef :
323 TryCapture_ExplicitByVal;
Douglas Gregora7365242012-02-14 19:27:52 +0000324 TryCaptureVar(Var, C->Loc, Kind, EllipsisLoc);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000325 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000326 finishLambdaExplicitCaptures(LSI);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000327
328 // Set the parameters on the decl, if specified.
329 if (isa<FunctionProtoTypeLoc>(MethodTyInfo->getTypeLoc())) {
Douglas Gregordfca6f52012-02-13 22:00:16 +0000330 FunctionProtoTypeLoc Proto
331 = cast<FunctionProtoTypeLoc>(MethodTyInfo->getTypeLoc());
332 addLambdaParameters(Method, CurScope, Proto.getParams());
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000333 }
334
Douglas Gregordfca6f52012-02-13 22:00:16 +0000335 // Enter a new evaluation context to insulate the lambda from any
Douglas Gregor503384f2012-02-09 00:47:04 +0000336 // cleanups from the enclosing full-expression.
337 PushExpressionEvaluationContext(PotentiallyEvaluated);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000338}
339
Douglas Gregordfca6f52012-02-13 22:00:16 +0000340void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
341 bool IsInstantiation) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000342 // Leave the expression-evaluation context.
343 DiscardCleanupsInEvaluationContext();
344 PopExpressionEvaluationContext();
345
346 // Leave the context of the lambda.
Douglas Gregordfca6f52012-02-13 22:00:16 +0000347 if (!IsInstantiation)
348 PopDeclContext();
Douglas Gregor630d5ff2012-02-09 01:28:42 +0000349
350 // Finalize the lambda.
351 LambdaScopeInfo *LSI = getCurLambda();
352 CXXRecordDecl *Class = LSI->Lambda;
353 Class->setInvalidDecl();
354 SmallVector<Decl*, 4> Fields(Class->field_begin(), Class->field_end());
355 ActOnFields(0, Class->getLocation(), Class, Fields,
356 SourceLocation(), SourceLocation(), 0);
357 CheckCompletedCXXClass(Class);
358
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000359 PopFunctionScopeInfo();
360}
361
Douglas Gregordfca6f52012-02-13 22:00:16 +0000362ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
363 Scope *CurScope, bool IsInstantiation) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000364 // Leave the expression-evaluation context.
365 DiscardCleanupsInEvaluationContext();
366 PopExpressionEvaluationContext();
367
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000368 // Collect information from the lambda scope.
369 llvm::SmallVector<LambdaExpr::Capture, 4> Captures;
370 llvm::SmallVector<Expr *, 4> CaptureInits;
371 LambdaCaptureDefault CaptureDefault;
372 CXXRecordDecl *Class;
Douglas Gregoref7d78b2012-02-10 08:36:38 +0000373 CXXMethodDecl *CallOperator;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000374 SourceRange IntroducerRange;
375 bool ExplicitParams;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000376 bool ExplicitResultType;
Douglas Gregor503384f2012-02-09 00:47:04 +0000377 bool LambdaExprNeedsCleanups;
Douglas Gregor9daa7bf2012-02-13 16:35:30 +0000378 llvm::SmallVector<VarDecl *, 4> ArrayIndexVars;
379 llvm::SmallVector<unsigned, 4> ArrayIndexStarts;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000380 {
381 LambdaScopeInfo *LSI = getCurLambda();
Douglas Gregoref7d78b2012-02-10 08:36:38 +0000382 CallOperator = LSI->CallOperator;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000383 Class = LSI->Lambda;
384 IntroducerRange = LSI->IntroducerRange;
385 ExplicitParams = LSI->ExplicitParams;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000386 ExplicitResultType = !LSI->HasImplicitReturnType;
Douglas Gregor503384f2012-02-09 00:47:04 +0000387 LambdaExprNeedsCleanups = LSI->ExprNeedsCleanups;
Douglas Gregor9daa7bf2012-02-13 16:35:30 +0000388 ArrayIndexVars.swap(LSI->ArrayIndexVars);
389 ArrayIndexStarts.swap(LSI->ArrayIndexStarts);
390
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000391 // Translate captures.
392 for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) {
393 LambdaScopeInfo::Capture From = LSI->Captures[I];
394 assert(!From.isBlockCapture() && "Cannot capture __block variables");
395 bool IsImplicit = I >= LSI->NumExplicitCaptures;
396
397 // Handle 'this' capture.
398 if (From.isThisCapture()) {
399 Captures.push_back(LambdaExpr::Capture(From.getLocation(),
400 IsImplicit,
401 LCK_This));
402 CaptureInits.push_back(new (Context) CXXThisExpr(From.getLocation(),
403 getCurrentThisType(),
404 /*isImplicit=*/true));
405 continue;
406 }
407
408 VarDecl *Var = From.getVariable();
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000409 LambdaCaptureKind Kind = From.isCopyCapture()? LCK_ByCopy : LCK_ByRef;
410 Captures.push_back(LambdaExpr::Capture(From.getLocation(), IsImplicit,
Douglas Gregora7365242012-02-14 19:27:52 +0000411 Kind, Var, From.getEllipsisLoc()));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000412 CaptureInits.push_back(From.getCopyExpr());
413 }
414
415 switch (LSI->ImpCaptureStyle) {
416 case CapturingScopeInfo::ImpCap_None:
417 CaptureDefault = LCD_None;
418 break;
419
420 case CapturingScopeInfo::ImpCap_LambdaByval:
421 CaptureDefault = LCD_ByCopy;
422 break;
423
424 case CapturingScopeInfo::ImpCap_LambdaByref:
425 CaptureDefault = LCD_ByRef;
426 break;
427
428 case CapturingScopeInfo::ImpCap_Block:
429 llvm_unreachable("block capture in lambda");
430 break;
431 }
432
Douglas Gregor54042f12012-02-09 10:18:50 +0000433 // C++11 [expr.prim.lambda]p4:
434 // If a lambda-expression does not include a
435 // trailing-return-type, it is as if the trailing-return-type
436 // denotes the following type:
437 // FIXME: Assumes current resolution to core issue 975.
438 if (LSI->HasImplicitReturnType) {
439 // - if there are no return statements in the
440 // compound-statement, or all return statements return
441 // either an expression of type void or no expression or
442 // braced-init-list, the type void;
443 if (LSI->ReturnType.isNull()) {
444 LSI->ReturnType = Context.VoidTy;
445 } else {
446 // C++11 [expr.prim.lambda]p4:
447 // - if the compound-statement is of the form
448 //
449 // { attribute-specifier-seq[opt] return expression ; }
450 //
451 // the type of the returned expression after
452 // lvalue-to-rvalue conversion (4.1), array-to-pointer
453 // conver- sion (4.2), and function-to-pointer conversion
454 // (4.3);
455 //
456 // Since we're accepting the resolution to a post-C++11 core
457 // issue with a non-trivial extension, provide a warning (by
458 // default).
459 CompoundStmt *CompoundBody = cast<CompoundStmt>(Body);
460 if (!(CompoundBody->size() == 1 &&
461 isa<ReturnStmt>(*CompoundBody->body_begin())) &&
462 !Context.hasSameType(LSI->ReturnType, Context.VoidTy))
463 Diag(IntroducerRange.getBegin(),
464 diag::ext_lambda_implies_void_return);
465 }
466
467 // Create a function type with the inferred return type.
468 const FunctionProtoType *Proto
469 = CallOperator->getType()->getAs<FunctionProtoType>();
470 QualType FunctionTy
471 = Context.getFunctionType(LSI->ReturnType,
472 Proto->arg_type_begin(),
473 Proto->getNumArgs(),
474 Proto->getExtProtoInfo());
475 CallOperator->setType(FunctionTy);
476 }
477
Douglas Gregor215e4e12012-02-12 17:34:23 +0000478 // C++ [expr.prim.lambda]p7:
479 // The lambda-expression's compound-statement yields the
480 // function-body (8.4) of the function call operator [...].
Douglas Gregordfca6f52012-02-13 22:00:16 +0000481 ActOnFinishFunctionBody(CallOperator, Body, IsInstantiation);
Douglas Gregor215e4e12012-02-12 17:34:23 +0000482 CallOperator->setLexicalDeclContext(Class);
483 Class->addDecl(CallOperator);
484
Douglas Gregorb5559712012-02-10 16:13:20 +0000485 // C++11 [expr.prim.lambda]p6:
486 // The closure type for a lambda-expression with no lambda-capture
487 // has a public non-virtual non-explicit const conversion function
488 // to pointer to function having the same parameter and return
489 // types as the closure type's function call operator.
490 if (Captures.empty() && CaptureDefault == LCD_None) {
491 const FunctionProtoType *Proto
492 = CallOperator->getType()->getAs<FunctionProtoType>();
493 QualType FunctionPtrTy;
494 {
495 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
496 ExtInfo.TypeQuals = 0;
497 QualType FunctionTy
498 = Context.getFunctionType(Proto->getResultType(),
499 Proto->arg_type_begin(),
500 Proto->getNumArgs(),
501 ExtInfo);
502 FunctionPtrTy = Context.getPointerType(FunctionTy);
503 }
504
505 FunctionProtoType::ExtProtoInfo ExtInfo;
506 ExtInfo.TypeQuals = Qualifiers::Const;
507 QualType ConvTy = Context.getFunctionType(FunctionPtrTy, 0, 0, ExtInfo);
508
509 SourceLocation Loc = IntroducerRange.getBegin();
510 DeclarationName Name
511 = Context.DeclarationNames.getCXXConversionFunctionName(
512 Context.getCanonicalType(FunctionPtrTy));
513 DeclarationNameLoc NameLoc;
514 NameLoc.NamedType.TInfo = Context.getTrivialTypeSourceInfo(FunctionPtrTy,
515 Loc);
516 CXXConversionDecl *Conversion
517 = CXXConversionDecl::Create(Context, Class, Loc,
518 DeclarationNameInfo(Name, Loc, NameLoc),
519 ConvTy,
520 Context.getTrivialTypeSourceInfo(ConvTy,
521 Loc),
522 /*isInline=*/false, /*isExplicit=*/false,
523 /*isConstexpr=*/false, Body->getLocEnd());
524 Conversion->setAccess(AS_public);
525 Conversion->setImplicit(true);
526 Class->addDecl(Conversion);
527 }
Douglas Gregor503384f2012-02-09 00:47:04 +0000528
Douglas Gregorb5559712012-02-10 16:13:20 +0000529 // Finalize the lambda class.
530 SmallVector<Decl*, 4> Fields(Class->field_begin(), Class->field_end());
Douglas Gregorb5559712012-02-10 16:13:20 +0000531 ActOnFields(0, Class->getLocation(), Class, Fields,
532 SourceLocation(), SourceLocation(), 0);
533 CheckCompletedCXXClass(Class);
534
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000535 }
536
Douglas Gregor503384f2012-02-09 00:47:04 +0000537 if (LambdaExprNeedsCleanups)
538 ExprNeedsCleanups = true;
539
Douglas Gregore2c59132012-02-09 08:14:43 +0000540 LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange,
541 CaptureDefault, Captures,
Douglas Gregordfca6f52012-02-13 22:00:16 +0000542 ExplicitParams, ExplicitResultType,
543 CaptureInits, ArrayIndexVars,
544 ArrayIndexStarts, Body->getLocEnd());
Douglas Gregore2c59132012-02-09 08:14:43 +0000545
546 // C++11 [expr.prim.lambda]p2:
547 // A lambda-expression shall not appear in an unevaluated operand
548 // (Clause 5).
Douglas Gregord5387e82012-02-14 00:00:48 +0000549 if (!CurContext->isDependentContext()) {
550 switch (ExprEvalContexts.back().Context) {
551 case Unevaluated:
552 // We don't actually diagnose this case immediately, because we
553 // could be within a context where we might find out later that
554 // the expression is potentially evaluated (e.g., for typeid).
555 ExprEvalContexts.back().Lambdas.push_back(Lambda);
556 break;
Douglas Gregore2c59132012-02-09 08:14:43 +0000557
Douglas Gregord5387e82012-02-14 00:00:48 +0000558 case ConstantEvaluated:
559 case PotentiallyEvaluated:
560 case PotentiallyEvaluatedIfUsed:
561 break;
562 }
Douglas Gregore2c59132012-02-09 08:14:43 +0000563 }
Douglas Gregord5387e82012-02-14 00:00:48 +0000564
Douglas Gregor503384f2012-02-09 00:47:04 +0000565 return MaybeBindToTemporary(Lambda);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000566}