blob: 9a137e1e7963d8a07ca55a88cacd069f3c9c9a91 [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,
Douglas Gregorc6889e72012-02-14 22:28:59 +000039 SourceLocation EndLoc,
40 llvm::ArrayRef<ParmVarDecl *> Params) {
Douglas Gregordfca6f52012-02-13 22:00:16 +000041 // C++11 [expr.prim.lambda]p5:
42 // The closure type for a lambda-expression has a public inline function
43 // call operator (13.5.4) whose parameters and return type are described by
44 // the lambda-expression's parameter-declaration-clause and
45 // trailing-return-type respectively.
46 DeclarationName MethodName
47 = Context.DeclarationNames.getCXXOperatorName(OO_Call);
48 DeclarationNameLoc MethodNameLoc;
49 MethodNameLoc.CXXOperatorName.BeginOpNameLoc
50 = IntroducerRange.getBegin().getRawEncoding();
51 MethodNameLoc.CXXOperatorName.EndOpNameLoc
52 = IntroducerRange.getEnd().getRawEncoding();
53 CXXMethodDecl *Method
54 = CXXMethodDecl::Create(Context, Class, EndLoc,
55 DeclarationNameInfo(MethodName,
56 IntroducerRange.getBegin(),
57 MethodNameLoc),
58 MethodType->getType(), MethodType,
59 /*isStatic=*/false,
60 SC_None,
61 /*isInline=*/true,
62 /*isConstExpr=*/false,
63 EndLoc);
64 Method->setAccess(AS_public);
65
66 // Temporarily set the lexical declaration context to the current
67 // context, so that the Scope stack matches the lexical nesting.
68 Method->setLexicalDeclContext(Class->getDeclContext());
69
Douglas Gregorc6889e72012-02-14 22:28:59 +000070 // Add parameters.
71 if (!Params.empty()) {
72 Method->setParams(Params);
73 CheckParmsForFunctionDef(const_cast<ParmVarDecl **>(Params.begin()),
74 const_cast<ParmVarDecl **>(Params.end()),
75 /*CheckParameterNames=*/false);
76
77 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
78 PEnd = Method->param_end();
79 P != PEnd; ++P)
80 (*P)->setOwningFunction(Method);
81 }
82
Douglas Gregordfca6f52012-02-13 22:00:16 +000083 return Method;
84}
85
86LambdaScopeInfo *Sema::enterLambdaScope(CXXMethodDecl *CallOperator,
87 SourceRange IntroducerRange,
88 LambdaCaptureDefault CaptureDefault,
89 bool ExplicitParams,
90 bool ExplicitResultType,
91 bool Mutable) {
92 PushLambdaScope(CallOperator->getParent(), CallOperator);
93 LambdaScopeInfo *LSI = getCurLambda();
94 if (CaptureDefault == LCD_ByCopy)
95 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
96 else if (CaptureDefault == LCD_ByRef)
97 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
98 LSI->IntroducerRange = IntroducerRange;
99 LSI->ExplicitParams = ExplicitParams;
100 LSI->Mutable = Mutable;
101
102 if (ExplicitResultType) {
103 LSI->ReturnType = CallOperator->getResultType();
Douglas Gregor53393f22012-02-14 21:20:44 +0000104
105 if (!LSI->ReturnType->isDependentType() &&
106 !LSI->ReturnType->isVoidType()) {
107 if (RequireCompleteType(CallOperator->getLocStart(), LSI->ReturnType,
108 diag::err_lambda_incomplete_result)) {
109 // Do nothing.
110 } else if (LSI->ReturnType->isObjCObjectOrInterfaceType()) {
111 Diag(CallOperator->getLocStart(), diag::err_lambda_objc_object_result)
112 << LSI->ReturnType;
113 }
114 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000115 } else {
116 LSI->HasImplicitReturnType = true;
117 }
118
119 return LSI;
120}
121
122void Sema::finishLambdaExplicitCaptures(LambdaScopeInfo *LSI) {
123 LSI->finishedExplicitCaptures();
124}
125
Douglas Gregorc6889e72012-02-14 22:28:59 +0000126void Sema::addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope) {
Douglas Gregordfca6f52012-02-13 22:00:16 +0000127 // Introduce our parameters into the function scope
128 for (unsigned p = 0, NumParams = CallOperator->getNumParams();
129 p < NumParams; ++p) {
130 ParmVarDecl *Param = CallOperator->getParamDecl(p);
Douglas Gregordfca6f52012-02-13 22:00:16 +0000131
132 // If this has an identifier, add it to the scope stack.
133 if (CurScope && Param->getIdentifier()) {
134 CheckShadow(CurScope, Param);
135
136 PushOnScopeChains(Param, CurScope);
137 }
138 }
139}
140
141void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
142 Declarator &ParamInfo,
143 Scope *CurScope) {
144 CXXRecordDecl *Class = createLambdaClosureType(Intro.Range);
145
146 // Determine the signature of the call operator.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000147 TypeSourceInfo *MethodTyInfo;
148 bool ExplicitParams = true;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000149 bool ExplicitResultType = true;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000150 SourceLocation EndLoc;
Douglas Gregorc6889e72012-02-14 22:28:59 +0000151 llvm::ArrayRef<ParmVarDecl *> Params;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000152 if (ParamInfo.getNumTypeObjects() == 0) {
153 // C++11 [expr.prim.lambda]p4:
154 // If a lambda-expression does not include a lambda-declarator, it is as
155 // if the lambda-declarator were ().
156 FunctionProtoType::ExtProtoInfo EPI;
Richard Smitheefb3d52012-02-10 09:58:53 +0000157 EPI.HasTrailingReturn = true;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000158 EPI.TypeQuals |= DeclSpec::TQ_const;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000159 QualType MethodTy = Context.getFunctionType(Context.DependentTy,
160 /*Args=*/0, /*NumArgs=*/0, EPI);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000161 MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy);
162 ExplicitParams = false;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000163 ExplicitResultType = false;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000164 EndLoc = Intro.Range.getEnd();
165 } else {
166 assert(ParamInfo.isFunctionDeclarator() &&
167 "lambda-declarator is a function");
168 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo();
169
170 // C++11 [expr.prim.lambda]p5:
171 // This function call operator is declared const (9.3.1) if and only if
172 // the lambda-expression's parameter-declaration-clause is not followed
173 // by mutable. It is neither virtual nor declared volatile. [...]
174 if (!FTI.hasMutableQualifier())
175 FTI.TypeQuals |= DeclSpec::TQ_const;
176
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000177 MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000178 assert(MethodTyInfo && "no type from lambda-declarator");
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000179 EndLoc = ParamInfo.getSourceRange().getEnd();
Douglas Gregordfca6f52012-02-13 22:00:16 +0000180
181 ExplicitResultType
182 = MethodTyInfo->getType()->getAs<FunctionType>()->getResultType()
183 != Context.DependentTy;
Douglas Gregorc6889e72012-02-14 22:28:59 +0000184
185 TypeLoc TL = MethodTyInfo->getTypeLoc();
186 FunctionProtoTypeLoc Proto = cast<FunctionProtoTypeLoc>(TL);
187 Params = llvm::ArrayRef<ParmVarDecl *>(Proto.getParmArray(),
188 Proto.getNumArgs());
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000189 }
190
Douglas Gregordfca6f52012-02-13 22:00:16 +0000191 CXXMethodDecl *Method = startLambdaDefinition(Class, Intro.Range,
Douglas Gregorc6889e72012-02-14 22:28:59 +0000192 MethodTyInfo, EndLoc, Params);
193
194 if (ExplicitParams)
195 CheckCXXDefaultArguments(Method);
Douglas Gregordfca6f52012-02-13 22:00:16 +0000196
Douglas Gregor503384f2012-02-09 00:47:04 +0000197 // Attributes on the lambda apply to the method.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000198 ProcessDeclAttributes(CurScope, Method, ParamInfo);
199
Douglas Gregor503384f2012-02-09 00:47:04 +0000200 // Introduce the function call operator as the current declaration context.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000201 PushDeclContext(CurScope, Method);
202
203 // Introduce the lambda scope.
Douglas Gregordfca6f52012-02-13 22:00:16 +0000204 LambdaScopeInfo *LSI
205 = enterLambdaScope(Method, Intro.Range, Intro.Default, ExplicitParams,
206 ExplicitResultType,
207 (Method->getTypeQualifiers() & Qualifiers::Const) == 0);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000208
209 // Handle explicit captures.
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000210 SourceLocation PrevCaptureLoc
211 = Intro.Default == LCD_None? Intro.Range.getBegin() : Intro.DefaultLoc;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000212 for (llvm::SmallVector<LambdaCapture, 4>::const_iterator
213 C = Intro.Captures.begin(),
214 E = Intro.Captures.end();
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000215 C != E;
216 PrevCaptureLoc = C->Loc, ++C) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000217 if (C->Kind == LCK_This) {
218 // C++11 [expr.prim.lambda]p8:
219 // An identifier or this shall not appear more than once in a
220 // lambda-capture.
221 if (LSI->isCXXThisCaptured()) {
222 Diag(C->Loc, diag::err_capture_more_than_once)
223 << "'this'"
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000224 << SourceRange(LSI->getCXXThisCapture().getLocation())
225 << FixItHint::CreateRemoval(
226 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000227 continue;
228 }
229
230 // C++11 [expr.prim.lambda]p8:
231 // If a lambda-capture includes a capture-default that is =, the
232 // lambda-capture shall not contain this [...].
233 if (Intro.Default == LCD_ByCopy) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000234 Diag(C->Loc, diag::err_this_capture_with_copy_default)
235 << FixItHint::CreateRemoval(
236 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000237 continue;
238 }
239
240 // C++11 [expr.prim.lambda]p12:
241 // If this is captured by a local lambda expression, its nearest
242 // enclosing function shall be a non-static member function.
243 QualType ThisCaptureType = getCurrentThisType();
244 if (ThisCaptureType.isNull()) {
245 Diag(C->Loc, diag::err_this_capture) << true;
246 continue;
247 }
248
249 CheckCXXThisCapture(C->Loc, /*Explicit=*/true);
250 continue;
251 }
252
253 assert(C->Id && "missing identifier for capture");
254
255 // C++11 [expr.prim.lambda]p8:
256 // If a lambda-capture includes a capture-default that is &, the
257 // identifiers in the lambda-capture shall not be preceded by &.
258 // If a lambda-capture includes a capture-default that is =, [...]
259 // each identifier it contains shall be preceded by &.
260 if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000261 Diag(C->Loc, diag::err_reference_capture_with_reference_default)
262 << FixItHint::CreateRemoval(
263 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000264 continue;
265 } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000266 Diag(C->Loc, diag::err_copy_capture_with_copy_default)
267 << FixItHint::CreateRemoval(
268 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000269 continue;
270 }
271
272 DeclarationNameInfo Name(C->Id, C->Loc);
273 LookupResult R(*this, Name, LookupOrdinaryName);
274 LookupName(R, CurScope);
275 if (R.isAmbiguous())
276 continue;
277 if (R.empty()) {
278 // FIXME: Disable corrections that would add qualification?
279 CXXScopeSpec ScopeSpec;
280 DeclFilterCCC<VarDecl> Validator;
281 if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
282 continue;
283 }
284
285 // C++11 [expr.prim.lambda]p10:
286 // The identifiers in a capture-list are looked up using the usual rules
287 // for unqualified name lookup (3.4.1); each such lookup shall find a
288 // variable with automatic storage duration declared in the reaching
289 // scope of the local lambda expression.
Douglas Gregor53393f22012-02-14 21:20:44 +0000290 //
291 // Note that the 'reaching scope' check happens in TryCaptureVar.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000292 VarDecl *Var = R.getAsSingle<VarDecl>();
293 if (!Var) {
294 Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
295 continue;
296 }
297
298 if (!Var->hasLocalStorage()) {
299 Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
300 Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
301 continue;
302 }
303
304 // C++11 [expr.prim.lambda]p8:
305 // An identifier or this shall not appear more than once in a
306 // lambda-capture.
307 if (LSI->isCaptured(Var)) {
308 Diag(C->Loc, diag::err_capture_more_than_once)
309 << C->Id
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000310 << SourceRange(LSI->getCapture(Var).getLocation())
311 << FixItHint::CreateRemoval(
312 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000313 continue;
314 }
315
Douglas Gregora7365242012-02-14 19:27:52 +0000316 // C++11 [expr.prim.lambda]p23:
317 // A capture followed by an ellipsis is a pack expansion (14.5.3).
318 SourceLocation EllipsisLoc;
319 if (C->EllipsisLoc.isValid()) {
320 if (Var->isParameterPack()) {
321 EllipsisLoc = C->EllipsisLoc;
322 } else {
323 Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
324 << SourceRange(C->Loc);
325
326 // Just ignore the ellipsis.
327 }
328 } else if (Var->isParameterPack()) {
329 Diag(C->Loc, diag::err_lambda_unexpanded_pack);
330 continue;
331 }
332
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000333 TryCaptureKind Kind = C->Kind == LCK_ByRef ? TryCapture_ExplicitByRef :
334 TryCapture_ExplicitByVal;
Douglas Gregora7365242012-02-14 19:27:52 +0000335 TryCaptureVar(Var, C->Loc, Kind, EllipsisLoc);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000336 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000337 finishLambdaExplicitCaptures(LSI);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000338
Douglas Gregorc6889e72012-02-14 22:28:59 +0000339 // Add lambda parameters into scope.
340 addLambdaParameters(Method, CurScope);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000341
Douglas Gregordfca6f52012-02-13 22:00:16 +0000342 // Enter a new evaluation context to insulate the lambda from any
Douglas Gregor503384f2012-02-09 00:47:04 +0000343 // cleanups from the enclosing full-expression.
344 PushExpressionEvaluationContext(PotentiallyEvaluated);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000345}
346
Douglas Gregordfca6f52012-02-13 22:00:16 +0000347void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
348 bool IsInstantiation) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000349 // Leave the expression-evaluation context.
350 DiscardCleanupsInEvaluationContext();
351 PopExpressionEvaluationContext();
352
353 // Leave the context of the lambda.
Douglas Gregordfca6f52012-02-13 22:00:16 +0000354 if (!IsInstantiation)
355 PopDeclContext();
Douglas Gregor630d5ff2012-02-09 01:28:42 +0000356
357 // Finalize the lambda.
358 LambdaScopeInfo *LSI = getCurLambda();
359 CXXRecordDecl *Class = LSI->Lambda;
360 Class->setInvalidDecl();
361 SmallVector<Decl*, 4> Fields(Class->field_begin(), Class->field_end());
362 ActOnFields(0, Class->getLocation(), Class, Fields,
363 SourceLocation(), SourceLocation(), 0);
364 CheckCompletedCXXClass(Class);
365
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000366 PopFunctionScopeInfo();
367}
368
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000369/// \brief Add a lambda's conversion to function pointer, as described in
370/// C++11 [expr.prim.lambda]p6.
371static void addFunctionPointerConversion(Sema &S,
372 SourceRange IntroducerRange,
373 CXXRecordDecl *Class,
374 CXXMethodDecl *CallOperator) {
375 const FunctionProtoType *Proto
376 = CallOperator->getType()->getAs<FunctionProtoType>();
377 QualType FunctionPtrTy;
378 {
379 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
380 ExtInfo.TypeQuals = 0;
381 QualType FunctionTy
382 = S.Context.getFunctionType(Proto->getResultType(),
383 Proto->arg_type_begin(),
384 Proto->getNumArgs(),
385 ExtInfo);
386 FunctionPtrTy = S.Context.getPointerType(FunctionTy);
387 }
388
389 FunctionProtoType::ExtProtoInfo ExtInfo;
390 ExtInfo.TypeQuals = Qualifiers::Const;
391 QualType ConvTy = S.Context.getFunctionType(FunctionPtrTy, 0, 0, ExtInfo);
392
393 SourceLocation Loc = IntroducerRange.getBegin();
394 DeclarationName Name
395 = S.Context.DeclarationNames.getCXXConversionFunctionName(
396 S.Context.getCanonicalType(FunctionPtrTy));
397 DeclarationNameLoc NameLoc;
398 NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(FunctionPtrTy,
399 Loc);
400 CXXConversionDecl *Conversion
401 = CXXConversionDecl::Create(S.Context, Class, Loc,
402 DeclarationNameInfo(Name, Loc, NameLoc),
403 ConvTy,
404 S.Context.getTrivialTypeSourceInfo(ConvTy,
405 Loc),
406 /*isInline=*/false, /*isExplicit=*/false,
407 /*isConstexpr=*/false,
408 CallOperator->getBody()->getLocEnd());
409 Conversion->setAccess(AS_public);
410 Conversion->setImplicit(true);
411 Class->addDecl(Conversion);
412}
413
Douglas Gregordfca6f52012-02-13 22:00:16 +0000414ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
415 Scope *CurScope, bool IsInstantiation) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000416 // Leave the expression-evaluation context.
417 DiscardCleanupsInEvaluationContext();
418 PopExpressionEvaluationContext();
419
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000420 // Collect information from the lambda scope.
421 llvm::SmallVector<LambdaExpr::Capture, 4> Captures;
422 llvm::SmallVector<Expr *, 4> CaptureInits;
423 LambdaCaptureDefault CaptureDefault;
424 CXXRecordDecl *Class;
Douglas Gregoref7d78b2012-02-10 08:36:38 +0000425 CXXMethodDecl *CallOperator;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000426 SourceRange IntroducerRange;
427 bool ExplicitParams;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000428 bool ExplicitResultType;
Douglas Gregor503384f2012-02-09 00:47:04 +0000429 bool LambdaExprNeedsCleanups;
Douglas Gregor9daa7bf2012-02-13 16:35:30 +0000430 llvm::SmallVector<VarDecl *, 4> ArrayIndexVars;
431 llvm::SmallVector<unsigned, 4> ArrayIndexStarts;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000432 {
433 LambdaScopeInfo *LSI = getCurLambda();
Douglas Gregoref7d78b2012-02-10 08:36:38 +0000434 CallOperator = LSI->CallOperator;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000435 Class = LSI->Lambda;
436 IntroducerRange = LSI->IntroducerRange;
437 ExplicitParams = LSI->ExplicitParams;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000438 ExplicitResultType = !LSI->HasImplicitReturnType;
Douglas Gregor503384f2012-02-09 00:47:04 +0000439 LambdaExprNeedsCleanups = LSI->ExprNeedsCleanups;
Douglas Gregor9daa7bf2012-02-13 16:35:30 +0000440 ArrayIndexVars.swap(LSI->ArrayIndexVars);
441 ArrayIndexStarts.swap(LSI->ArrayIndexStarts);
442
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000443 // Translate captures.
444 for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) {
445 LambdaScopeInfo::Capture From = LSI->Captures[I];
446 assert(!From.isBlockCapture() && "Cannot capture __block variables");
447 bool IsImplicit = I >= LSI->NumExplicitCaptures;
448
449 // Handle 'this' capture.
450 if (From.isThisCapture()) {
451 Captures.push_back(LambdaExpr::Capture(From.getLocation(),
452 IsImplicit,
453 LCK_This));
454 CaptureInits.push_back(new (Context) CXXThisExpr(From.getLocation(),
455 getCurrentThisType(),
456 /*isImplicit=*/true));
457 continue;
458 }
459
460 VarDecl *Var = From.getVariable();
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000461 LambdaCaptureKind Kind = From.isCopyCapture()? LCK_ByCopy : LCK_ByRef;
462 Captures.push_back(LambdaExpr::Capture(From.getLocation(), IsImplicit,
Douglas Gregora7365242012-02-14 19:27:52 +0000463 Kind, Var, From.getEllipsisLoc()));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000464 CaptureInits.push_back(From.getCopyExpr());
465 }
466
467 switch (LSI->ImpCaptureStyle) {
468 case CapturingScopeInfo::ImpCap_None:
469 CaptureDefault = LCD_None;
470 break;
471
472 case CapturingScopeInfo::ImpCap_LambdaByval:
473 CaptureDefault = LCD_ByCopy;
474 break;
475
476 case CapturingScopeInfo::ImpCap_LambdaByref:
477 CaptureDefault = LCD_ByRef;
478 break;
479
480 case CapturingScopeInfo::ImpCap_Block:
481 llvm_unreachable("block capture in lambda");
482 break;
483 }
484
Douglas Gregor54042f12012-02-09 10:18:50 +0000485 // C++11 [expr.prim.lambda]p4:
486 // If a lambda-expression does not include a
487 // trailing-return-type, it is as if the trailing-return-type
488 // denotes the following type:
489 // FIXME: Assumes current resolution to core issue 975.
490 if (LSI->HasImplicitReturnType) {
491 // - if there are no return statements in the
492 // compound-statement, or all return statements return
493 // either an expression of type void or no expression or
494 // braced-init-list, the type void;
495 if (LSI->ReturnType.isNull()) {
496 LSI->ReturnType = Context.VoidTy;
497 } else {
498 // C++11 [expr.prim.lambda]p4:
499 // - if the compound-statement is of the form
500 //
501 // { attribute-specifier-seq[opt] return expression ; }
502 //
503 // the type of the returned expression after
504 // lvalue-to-rvalue conversion (4.1), array-to-pointer
505 // conver- sion (4.2), and function-to-pointer conversion
506 // (4.3);
507 //
508 // Since we're accepting the resolution to a post-C++11 core
509 // issue with a non-trivial extension, provide a warning (by
510 // default).
511 CompoundStmt *CompoundBody = cast<CompoundStmt>(Body);
512 if (!(CompoundBody->size() == 1 &&
513 isa<ReturnStmt>(*CompoundBody->body_begin())) &&
514 !Context.hasSameType(LSI->ReturnType, Context.VoidTy))
515 Diag(IntroducerRange.getBegin(),
516 diag::ext_lambda_implies_void_return);
517 }
518
519 // Create a function type with the inferred return type.
520 const FunctionProtoType *Proto
521 = CallOperator->getType()->getAs<FunctionProtoType>();
522 QualType FunctionTy
523 = Context.getFunctionType(LSI->ReturnType,
524 Proto->arg_type_begin(),
525 Proto->getNumArgs(),
526 Proto->getExtProtoInfo());
527 CallOperator->setType(FunctionTy);
528 }
529
Douglas Gregor215e4e12012-02-12 17:34:23 +0000530 // C++ [expr.prim.lambda]p7:
531 // The lambda-expression's compound-statement yields the
532 // function-body (8.4) of the function call operator [...].
Douglas Gregordfca6f52012-02-13 22:00:16 +0000533 ActOnFinishFunctionBody(CallOperator, Body, IsInstantiation);
Douglas Gregor215e4e12012-02-12 17:34:23 +0000534 CallOperator->setLexicalDeclContext(Class);
535 Class->addDecl(CallOperator);
536
Douglas Gregorb5559712012-02-10 16:13:20 +0000537 // C++11 [expr.prim.lambda]p6:
538 // The closure type for a lambda-expression with no lambda-capture
539 // has a public non-virtual non-explicit const conversion function
540 // to pointer to function having the same parameter and return
541 // types as the closure type's function call operator.
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000542 if (Captures.empty() && CaptureDefault == LCD_None)
543 addFunctionPointerConversion(*this, IntroducerRange, Class,
544 CallOperator);
Douglas Gregor503384f2012-02-09 00:47:04 +0000545
Douglas Gregorb5559712012-02-10 16:13:20 +0000546 // Finalize the lambda class.
547 SmallVector<Decl*, 4> Fields(Class->field_begin(), Class->field_end());
Douglas Gregorb5559712012-02-10 16:13:20 +0000548 ActOnFields(0, Class->getLocation(), Class, Fields,
549 SourceLocation(), SourceLocation(), 0);
550 CheckCompletedCXXClass(Class);
551
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000552 }
553
Douglas Gregor503384f2012-02-09 00:47:04 +0000554 if (LambdaExprNeedsCleanups)
555 ExprNeedsCleanups = true;
556
Douglas Gregore2c59132012-02-09 08:14:43 +0000557 LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange,
558 CaptureDefault, Captures,
Douglas Gregordfca6f52012-02-13 22:00:16 +0000559 ExplicitParams, ExplicitResultType,
560 CaptureInits, ArrayIndexVars,
561 ArrayIndexStarts, Body->getLocEnd());
Douglas Gregore2c59132012-02-09 08:14:43 +0000562
563 // C++11 [expr.prim.lambda]p2:
564 // A lambda-expression shall not appear in an unevaluated operand
565 // (Clause 5).
Douglas Gregord5387e82012-02-14 00:00:48 +0000566 if (!CurContext->isDependentContext()) {
567 switch (ExprEvalContexts.back().Context) {
568 case Unevaluated:
569 // We don't actually diagnose this case immediately, because we
570 // could be within a context where we might find out later that
571 // the expression is potentially evaluated (e.g., for typeid).
572 ExprEvalContexts.back().Lambdas.push_back(Lambda);
573 break;
Douglas Gregore2c59132012-02-09 08:14:43 +0000574
Douglas Gregord5387e82012-02-14 00:00:48 +0000575 case ConstantEvaluated:
576 case PotentiallyEvaluated:
577 case PotentiallyEvaluatedIfUsed:
578 break;
579 }
Douglas Gregore2c59132012-02-09 08:14:43 +0000580 }
Douglas Gregord5387e82012-02-14 00:00:48 +0000581
Douglas Gregor503384f2012-02-09 00:47:04 +0000582 return MaybeBindToTemporary(Lambda);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000583}