blob: 34ccb2d3dd6ab68fe7228eef3227cd4d82c48a39 [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 Gregordfca6f52012-02-13 22:00:16 +0000369ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
370 Scope *CurScope, bool IsInstantiation) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000371 // Leave the expression-evaluation context.
372 DiscardCleanupsInEvaluationContext();
373 PopExpressionEvaluationContext();
374
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000375 // Collect information from the lambda scope.
376 llvm::SmallVector<LambdaExpr::Capture, 4> Captures;
377 llvm::SmallVector<Expr *, 4> CaptureInits;
378 LambdaCaptureDefault CaptureDefault;
379 CXXRecordDecl *Class;
Douglas Gregoref7d78b2012-02-10 08:36:38 +0000380 CXXMethodDecl *CallOperator;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000381 SourceRange IntroducerRange;
382 bool ExplicitParams;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000383 bool ExplicitResultType;
Douglas Gregor503384f2012-02-09 00:47:04 +0000384 bool LambdaExprNeedsCleanups;
Douglas Gregor9daa7bf2012-02-13 16:35:30 +0000385 llvm::SmallVector<VarDecl *, 4> ArrayIndexVars;
386 llvm::SmallVector<unsigned, 4> ArrayIndexStarts;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000387 {
388 LambdaScopeInfo *LSI = getCurLambda();
Douglas Gregoref7d78b2012-02-10 08:36:38 +0000389 CallOperator = LSI->CallOperator;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000390 Class = LSI->Lambda;
391 IntroducerRange = LSI->IntroducerRange;
392 ExplicitParams = LSI->ExplicitParams;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000393 ExplicitResultType = !LSI->HasImplicitReturnType;
Douglas Gregor503384f2012-02-09 00:47:04 +0000394 LambdaExprNeedsCleanups = LSI->ExprNeedsCleanups;
Douglas Gregor9daa7bf2012-02-13 16:35:30 +0000395 ArrayIndexVars.swap(LSI->ArrayIndexVars);
396 ArrayIndexStarts.swap(LSI->ArrayIndexStarts);
397
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000398 // Translate captures.
399 for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) {
400 LambdaScopeInfo::Capture From = LSI->Captures[I];
401 assert(!From.isBlockCapture() && "Cannot capture __block variables");
402 bool IsImplicit = I >= LSI->NumExplicitCaptures;
403
404 // Handle 'this' capture.
405 if (From.isThisCapture()) {
406 Captures.push_back(LambdaExpr::Capture(From.getLocation(),
407 IsImplicit,
408 LCK_This));
409 CaptureInits.push_back(new (Context) CXXThisExpr(From.getLocation(),
410 getCurrentThisType(),
411 /*isImplicit=*/true));
412 continue;
413 }
414
415 VarDecl *Var = From.getVariable();
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000416 LambdaCaptureKind Kind = From.isCopyCapture()? LCK_ByCopy : LCK_ByRef;
417 Captures.push_back(LambdaExpr::Capture(From.getLocation(), IsImplicit,
Douglas Gregora7365242012-02-14 19:27:52 +0000418 Kind, Var, From.getEllipsisLoc()));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000419 CaptureInits.push_back(From.getCopyExpr());
420 }
421
422 switch (LSI->ImpCaptureStyle) {
423 case CapturingScopeInfo::ImpCap_None:
424 CaptureDefault = LCD_None;
425 break;
426
427 case CapturingScopeInfo::ImpCap_LambdaByval:
428 CaptureDefault = LCD_ByCopy;
429 break;
430
431 case CapturingScopeInfo::ImpCap_LambdaByref:
432 CaptureDefault = LCD_ByRef;
433 break;
434
435 case CapturingScopeInfo::ImpCap_Block:
436 llvm_unreachable("block capture in lambda");
437 break;
438 }
439
Douglas Gregor54042f12012-02-09 10:18:50 +0000440 // C++11 [expr.prim.lambda]p4:
441 // If a lambda-expression does not include a
442 // trailing-return-type, it is as if the trailing-return-type
443 // denotes the following type:
444 // FIXME: Assumes current resolution to core issue 975.
445 if (LSI->HasImplicitReturnType) {
446 // - if there are no return statements in the
447 // compound-statement, or all return statements return
448 // either an expression of type void or no expression or
449 // braced-init-list, the type void;
450 if (LSI->ReturnType.isNull()) {
451 LSI->ReturnType = Context.VoidTy;
452 } else {
453 // C++11 [expr.prim.lambda]p4:
454 // - if the compound-statement is of the form
455 //
456 // { attribute-specifier-seq[opt] return expression ; }
457 //
458 // the type of the returned expression after
459 // lvalue-to-rvalue conversion (4.1), array-to-pointer
460 // conver- sion (4.2), and function-to-pointer conversion
461 // (4.3);
462 //
463 // Since we're accepting the resolution to a post-C++11 core
464 // issue with a non-trivial extension, provide a warning (by
465 // default).
466 CompoundStmt *CompoundBody = cast<CompoundStmt>(Body);
467 if (!(CompoundBody->size() == 1 &&
468 isa<ReturnStmt>(*CompoundBody->body_begin())) &&
469 !Context.hasSameType(LSI->ReturnType, Context.VoidTy))
470 Diag(IntroducerRange.getBegin(),
471 diag::ext_lambda_implies_void_return);
472 }
473
474 // Create a function type with the inferred return type.
475 const FunctionProtoType *Proto
476 = CallOperator->getType()->getAs<FunctionProtoType>();
477 QualType FunctionTy
478 = Context.getFunctionType(LSI->ReturnType,
479 Proto->arg_type_begin(),
480 Proto->getNumArgs(),
481 Proto->getExtProtoInfo());
482 CallOperator->setType(FunctionTy);
483 }
484
Douglas Gregor215e4e12012-02-12 17:34:23 +0000485 // C++ [expr.prim.lambda]p7:
486 // The lambda-expression's compound-statement yields the
487 // function-body (8.4) of the function call operator [...].
Douglas Gregordfca6f52012-02-13 22:00:16 +0000488 ActOnFinishFunctionBody(CallOperator, Body, IsInstantiation);
Douglas Gregor215e4e12012-02-12 17:34:23 +0000489 CallOperator->setLexicalDeclContext(Class);
490 Class->addDecl(CallOperator);
491
Douglas Gregorb5559712012-02-10 16:13:20 +0000492 // C++11 [expr.prim.lambda]p6:
493 // The closure type for a lambda-expression with no lambda-capture
494 // has a public non-virtual non-explicit const conversion function
495 // to pointer to function having the same parameter and return
496 // types as the closure type's function call operator.
497 if (Captures.empty() && CaptureDefault == LCD_None) {
498 const FunctionProtoType *Proto
499 = CallOperator->getType()->getAs<FunctionProtoType>();
500 QualType FunctionPtrTy;
501 {
502 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
503 ExtInfo.TypeQuals = 0;
504 QualType FunctionTy
505 = Context.getFunctionType(Proto->getResultType(),
506 Proto->arg_type_begin(),
507 Proto->getNumArgs(),
508 ExtInfo);
509 FunctionPtrTy = Context.getPointerType(FunctionTy);
510 }
511
512 FunctionProtoType::ExtProtoInfo ExtInfo;
513 ExtInfo.TypeQuals = Qualifiers::Const;
514 QualType ConvTy = Context.getFunctionType(FunctionPtrTy, 0, 0, ExtInfo);
515
516 SourceLocation Loc = IntroducerRange.getBegin();
517 DeclarationName Name
518 = Context.DeclarationNames.getCXXConversionFunctionName(
519 Context.getCanonicalType(FunctionPtrTy));
520 DeclarationNameLoc NameLoc;
521 NameLoc.NamedType.TInfo = Context.getTrivialTypeSourceInfo(FunctionPtrTy,
522 Loc);
523 CXXConversionDecl *Conversion
524 = CXXConversionDecl::Create(Context, Class, Loc,
525 DeclarationNameInfo(Name, Loc, NameLoc),
526 ConvTy,
527 Context.getTrivialTypeSourceInfo(ConvTy,
528 Loc),
529 /*isInline=*/false, /*isExplicit=*/false,
530 /*isConstexpr=*/false, Body->getLocEnd());
531 Conversion->setAccess(AS_public);
532 Conversion->setImplicit(true);
533 Class->addDecl(Conversion);
534 }
Douglas Gregor503384f2012-02-09 00:47:04 +0000535
Douglas Gregorb5559712012-02-10 16:13:20 +0000536 // Finalize the lambda class.
537 SmallVector<Decl*, 4> Fields(Class->field_begin(), Class->field_end());
Douglas Gregorb5559712012-02-10 16:13:20 +0000538 ActOnFields(0, Class->getLocation(), Class, Fields,
539 SourceLocation(), SourceLocation(), 0);
540 CheckCompletedCXXClass(Class);
541
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000542 }
543
Douglas Gregor503384f2012-02-09 00:47:04 +0000544 if (LambdaExprNeedsCleanups)
545 ExprNeedsCleanups = true;
546
Douglas Gregore2c59132012-02-09 08:14:43 +0000547 LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange,
548 CaptureDefault, Captures,
Douglas Gregordfca6f52012-02-13 22:00:16 +0000549 ExplicitParams, ExplicitResultType,
550 CaptureInits, ArrayIndexVars,
551 ArrayIndexStarts, Body->getLocEnd());
Douglas Gregore2c59132012-02-09 08:14:43 +0000552
553 // C++11 [expr.prim.lambda]p2:
554 // A lambda-expression shall not appear in an unevaluated operand
555 // (Clause 5).
Douglas Gregord5387e82012-02-14 00:00:48 +0000556 if (!CurContext->isDependentContext()) {
557 switch (ExprEvalContexts.back().Context) {
558 case Unevaluated:
559 // We don't actually diagnose this case immediately, because we
560 // could be within a context where we might find out later that
561 // the expression is potentially evaluated (e.g., for typeid).
562 ExprEvalContexts.back().Lambdas.push_back(Lambda);
563 break;
Douglas Gregore2c59132012-02-09 08:14:43 +0000564
Douglas Gregord5387e82012-02-14 00:00:48 +0000565 case ConstantEvaluated:
566 case PotentiallyEvaluated:
567 case PotentiallyEvaluatedIfUsed:
568 break;
569 }
Douglas Gregore2c59132012-02-09 08:14:43 +0000570 }
Douglas Gregord5387e82012-02-14 00:00:48 +0000571
Douglas Gregor503384f2012-02-09 00:47:04 +0000572 return MaybeBindToTemporary(Lambda);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000573}