blob: ed05eff8e1236da0285cbfc32cdb7316408b79b9 [file] [log] [blame]
Douglas Gregor03dd13c2012-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"
18#include "clang/AST/ExprCXX.h"
19using namespace clang;
20using namespace sema;
21
22void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
23 Declarator &ParamInfo,
24 Scope *CurScope) {
25 DeclContext *DC = CurContext;
26 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
27 DC = DC->getParent();
28
29 // Start constructing the lambda class.
30 CXXRecordDecl *Class = CXXRecordDecl::Create(Context, TTK_Class, DC,
31 Intro.Range.getBegin(),
Douglas Gregorfbf19a02012-02-09 02:20:38 +000032 /*IdLoc=*/Intro.Range.getBegin(),
Douglas Gregor03dd13c2012-02-08 21:18:48 +000033 /*Id=*/0);
34 Class->startDefinition();
Douglas Gregor9c702202012-02-10 07:45:31 +000035 Class->makeLambda();
Douglas Gregor03dd13c2012-02-08 21:18:48 +000036 CurContext->addDecl(Class);
37
38 // Build the call operator; we don't really have all the relevant information
39 // at this point, but we need something to attach child declarations to.
40 QualType MethodTy;
41 TypeSourceInfo *MethodTyInfo;
42 bool ExplicitParams = true;
43 SourceLocation EndLoc;
44 if (ParamInfo.getNumTypeObjects() == 0) {
45 // C++11 [expr.prim.lambda]p4:
46 // If a lambda-expression does not include a lambda-declarator, it is as
47 // if the lambda-declarator were ().
48 FunctionProtoType::ExtProtoInfo EPI;
Richard Smith5e580292012-02-10 09:58:53 +000049 EPI.HasTrailingReturn = true;
Douglas Gregor03dd13c2012-02-08 21:18:48 +000050 EPI.TypeQuals |= DeclSpec::TQ_const;
51 MethodTy = Context.getFunctionType(Context.DependentTy,
52 /*Args=*/0, /*NumArgs=*/0, EPI);
53 MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy);
54 ExplicitParams = false;
55 EndLoc = Intro.Range.getEnd();
56 } else {
57 assert(ParamInfo.isFunctionDeclarator() &&
58 "lambda-declarator is a function");
59 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo();
60
61 // C++11 [expr.prim.lambda]p5:
62 // This function call operator is declared const (9.3.1) if and only if
63 // the lambda-expression's parameter-declaration-clause is not followed
64 // by mutable. It is neither virtual nor declared volatile. [...]
65 if (!FTI.hasMutableQualifier())
66 FTI.TypeQuals |= DeclSpec::TQ_const;
67
68 // C++11 [expr.prim.lambda]p5:
69 // [...] Default arguments (8.3.6) shall not be specified in the
70 // parameter-declaration-clause of a lambda-declarator.
71 CheckExtraCXXDefaultArguments(ParamInfo);
72
73 MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope);
74 // FIXME: Can these asserts actually fail?
75 assert(MethodTyInfo && "no type from lambda-declarator");
76 MethodTy = MethodTyInfo->getType();
77 assert(!MethodTy.isNull() && "no type from lambda declarator");
78 EndLoc = ParamInfo.getSourceRange().getEnd();
79 }
80
81 // C++11 [expr.prim.lambda]p5:
82 // The closure type for a lambda-expression has a public inline function
83 // call operator (13.5.4) whose parameters and return type are described by
84 // the lambda-expression's parameter-declaration-clause and
85 // trailing-return-type respectively.
86 DeclarationName MethodName
87 = Context.DeclarationNames.getCXXOperatorName(OO_Call);
88 DeclarationNameLoc MethodNameLoc;
89 MethodNameLoc.CXXOperatorName.BeginOpNameLoc
90 = Intro.Range.getBegin().getRawEncoding();
91 MethodNameLoc.CXXOperatorName.EndOpNameLoc
92 = Intro.Range.getEnd().getRawEncoding();
93 CXXMethodDecl *Method
94 = CXXMethodDecl::Create(Context, Class, EndLoc,
95 DeclarationNameInfo(MethodName,
96 Intro.Range.getBegin(),
97 MethodNameLoc),
98 MethodTy, MethodTyInfo,
99 /*isStatic=*/false,
100 SC_None,
101 /*isInline=*/true,
102 /*isConstExpr=*/false,
103 EndLoc);
104 Method->setAccess(AS_public);
105 Class->addDecl(Method);
Douglas Gregor12695102012-02-10 08:36:38 +0000106
107 // Temporarily set the lexical declaration context to the current
108 // context, so that the Scope stack matches the lexical nesting.
109 Method->setLexicalDeclContext(DC);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +0000110
111 // Attributes on the lambda apply to the method.
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000112 ProcessDeclAttributes(CurScope, Method, ParamInfo);
113
Douglas Gregor8c50e7c2012-02-09 00:47:04 +0000114 // Introduce the function call operator as the current declaration context.
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000115 PushDeclContext(CurScope, Method);
116
117 // Introduce the lambda scope.
118 PushLambdaScope(Class, Method);
119 LambdaScopeInfo *LSI = getCurLambda();
120 if (Intro.Default == LCD_ByCopy)
121 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
122 else if (Intro.Default == LCD_ByRef)
123 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
124 LSI->IntroducerRange = Intro.Range;
125 LSI->ExplicitParams = ExplicitParams;
126 LSI->Mutable = (Method->getTypeQualifiers() & Qualifiers::Const) == 0;
127
128 // Handle explicit captures.
129 for (llvm::SmallVector<LambdaCapture, 4>::const_iterator
130 C = Intro.Captures.begin(),
131 E = Intro.Captures.end();
132 C != E; ++C) {
133 if (C->Kind == LCK_This) {
134 // C++11 [expr.prim.lambda]p8:
135 // An identifier or this shall not appear more than once in a
136 // lambda-capture.
137 if (LSI->isCXXThisCaptured()) {
138 Diag(C->Loc, diag::err_capture_more_than_once)
139 << "'this'"
140 << SourceRange(LSI->getCXXThisCapture().getLocation());
141 continue;
142 }
143
144 // C++11 [expr.prim.lambda]p8:
145 // If a lambda-capture includes a capture-default that is =, the
146 // lambda-capture shall not contain this [...].
147 if (Intro.Default == LCD_ByCopy) {
148 Diag(C->Loc, diag::err_this_capture_with_copy_default);
149 continue;
150 }
151
152 // C++11 [expr.prim.lambda]p12:
153 // If this is captured by a local lambda expression, its nearest
154 // enclosing function shall be a non-static member function.
155 QualType ThisCaptureType = getCurrentThisType();
156 if (ThisCaptureType.isNull()) {
157 Diag(C->Loc, diag::err_this_capture) << true;
158 continue;
159 }
160
161 CheckCXXThisCapture(C->Loc, /*Explicit=*/true);
162 continue;
163 }
164
165 assert(C->Id && "missing identifier for capture");
166
167 // C++11 [expr.prim.lambda]p8:
168 // If a lambda-capture includes a capture-default that is &, the
169 // identifiers in the lambda-capture shall not be preceded by &.
170 // If a lambda-capture includes a capture-default that is =, [...]
171 // each identifier it contains shall be preceded by &.
172 if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
173 Diag(C->Loc, diag::err_reference_capture_with_reference_default);
174 continue;
175 } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
176 Diag(C->Loc, diag::err_copy_capture_with_copy_default);
177 continue;
178 }
179
180 DeclarationNameInfo Name(C->Id, C->Loc);
181 LookupResult R(*this, Name, LookupOrdinaryName);
182 LookupName(R, CurScope);
183 if (R.isAmbiguous())
184 continue;
185 if (R.empty()) {
186 // FIXME: Disable corrections that would add qualification?
187 CXXScopeSpec ScopeSpec;
188 DeclFilterCCC<VarDecl> Validator;
189 if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
190 continue;
191 }
192
193 // C++11 [expr.prim.lambda]p10:
194 // The identifiers in a capture-list are looked up using the usual rules
195 // for unqualified name lookup (3.4.1); each such lookup shall find a
196 // variable with automatic storage duration declared in the reaching
197 // scope of the local lambda expression.
198 // FIXME: Check reaching scope.
199 VarDecl *Var = R.getAsSingle<VarDecl>();
200 if (!Var) {
201 Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
202 continue;
203 }
204
205 if (!Var->hasLocalStorage()) {
206 Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
207 Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
208 continue;
209 }
210
211 // C++11 [expr.prim.lambda]p8:
212 // An identifier or this shall not appear more than once in a
213 // lambda-capture.
214 if (LSI->isCaptured(Var)) {
215 Diag(C->Loc, diag::err_capture_more_than_once)
216 << C->Id
217 << SourceRange(LSI->getCapture(Var).getLocation());
218 continue;
219 }
220
221 TryCaptureKind Kind = C->Kind == LCK_ByRef ? TryCapture_ExplicitByRef :
222 TryCapture_ExplicitByVal;
223 TryCaptureVar(Var, C->Loc, Kind);
224 }
225 LSI->finishedExplicitCaptures();
226
227 // Set the parameters on the decl, if specified.
228 if (isa<FunctionProtoTypeLoc>(MethodTyInfo->getTypeLoc())) {
229 FunctionProtoTypeLoc Proto =
230 cast<FunctionProtoTypeLoc>(MethodTyInfo->getTypeLoc());
231 Method->setParams(Proto.getParams());
232 CheckParmsForFunctionDef(Method->param_begin(),
233 Method->param_end(),
234 /*CheckParameterNames=*/false);
235
236 // Introduce our parameters into the function scope
237 for (unsigned p = 0, NumParams = Method->getNumParams(); p < NumParams; ++p) {
238 ParmVarDecl *Param = Method->getParamDecl(p);
239 Param->setOwningFunction(Method);
240
241 // If this has an identifier, add it to the scope stack.
242 if (Param->getIdentifier()) {
243 CheckShadow(CurScope, Param);
244
245 PushOnScopeChains(Param, CurScope);
246 }
247 }
248 }
249
250 const FunctionType *Fn = MethodTy->getAs<FunctionType>();
251 QualType RetTy = Fn->getResultType();
252 if (RetTy != Context.DependentTy) {
253 LSI->ReturnType = RetTy;
254 } else {
255 LSI->HasImplicitReturnType = true;
256 }
257
258 // FIXME: Check return type is complete, !isObjCObjectType
259
Douglas Gregor8c50e7c2012-02-09 00:47:04 +0000260 // Enter a new evaluation context to insulate the block from any
261 // cleanups from the enclosing full-expression.
262 PushExpressionEvaluationContext(PotentiallyEvaluated);
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000263}
264
265void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope) {
266 // Leave the expression-evaluation context.
267 DiscardCleanupsInEvaluationContext();
268 PopExpressionEvaluationContext();
269
270 // Leave the context of the lambda.
271 PopDeclContext();
Douglas Gregorab23d9a2012-02-09 01:28:42 +0000272
273 // Finalize the lambda.
274 LambdaScopeInfo *LSI = getCurLambda();
275 CXXRecordDecl *Class = LSI->Lambda;
276 Class->setInvalidDecl();
277 SmallVector<Decl*, 4> Fields(Class->field_begin(), Class->field_end());
278 ActOnFields(0, Class->getLocation(), Class, Fields,
279 SourceLocation(), SourceLocation(), 0);
280 CheckCompletedCXXClass(Class);
281
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000282 PopFunctionScopeInfo();
283}
284
285ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc,
286 Stmt *Body, Scope *CurScope) {
287 // Leave the expression-evaluation context.
288 DiscardCleanupsInEvaluationContext();
289 PopExpressionEvaluationContext();
290
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000291 // Collect information from the lambda scope.
292 llvm::SmallVector<LambdaExpr::Capture, 4> Captures;
293 llvm::SmallVector<Expr *, 4> CaptureInits;
294 LambdaCaptureDefault CaptureDefault;
295 CXXRecordDecl *Class;
Douglas Gregor12695102012-02-10 08:36:38 +0000296 CXXMethodDecl *CallOperator;
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000297 SourceRange IntroducerRange;
298 bool ExplicitParams;
Douglas Gregor8c50e7c2012-02-09 00:47:04 +0000299 bool LambdaExprNeedsCleanups;
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000300 {
301 LambdaScopeInfo *LSI = getCurLambda();
Douglas Gregor12695102012-02-10 08:36:38 +0000302 CallOperator = LSI->CallOperator;
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000303 Class = LSI->Lambda;
304 IntroducerRange = LSI->IntroducerRange;
305 ExplicitParams = LSI->ExplicitParams;
Douglas Gregor8c50e7c2012-02-09 00:47:04 +0000306 LambdaExprNeedsCleanups = LSI->ExprNeedsCleanups;
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000307
308 // Translate captures.
309 for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) {
310 LambdaScopeInfo::Capture From = LSI->Captures[I];
311 assert(!From.isBlockCapture() && "Cannot capture __block variables");
312 bool IsImplicit = I >= LSI->NumExplicitCaptures;
313
314 // Handle 'this' capture.
315 if (From.isThisCapture()) {
316 Captures.push_back(LambdaExpr::Capture(From.getLocation(),
317 IsImplicit,
318 LCK_This));
319 CaptureInits.push_back(new (Context) CXXThisExpr(From.getLocation(),
320 getCurrentThisType(),
321 /*isImplicit=*/true));
322 continue;
323 }
324
325 VarDecl *Var = From.getVariable();
326 // FIXME: Handle pack expansions.
327 LambdaCaptureKind Kind = From.isCopyCapture()? LCK_ByCopy : LCK_ByRef;
328 Captures.push_back(LambdaExpr::Capture(From.getLocation(), IsImplicit,
329 Kind, Var));
330 CaptureInits.push_back(From.getCopyExpr());
331 }
332
333 switch (LSI->ImpCaptureStyle) {
334 case CapturingScopeInfo::ImpCap_None:
335 CaptureDefault = LCD_None;
336 break;
337
338 case CapturingScopeInfo::ImpCap_LambdaByval:
339 CaptureDefault = LCD_ByCopy;
340 break;
341
342 case CapturingScopeInfo::ImpCap_LambdaByref:
343 CaptureDefault = LCD_ByRef;
344 break;
345
346 case CapturingScopeInfo::ImpCap_Block:
347 llvm_unreachable("block capture in lambda");
348 break;
349 }
350
Douglas Gregor73456262012-02-09 10:18:50 +0000351 // C++11 [expr.prim.lambda]p4:
352 // If a lambda-expression does not include a
353 // trailing-return-type, it is as if the trailing-return-type
354 // denotes the following type:
355 // FIXME: Assumes current resolution to core issue 975.
356 if (LSI->HasImplicitReturnType) {
357 // - if there are no return statements in the
358 // compound-statement, or all return statements return
359 // either an expression of type void or no expression or
360 // braced-init-list, the type void;
361 if (LSI->ReturnType.isNull()) {
362 LSI->ReturnType = Context.VoidTy;
363 } else {
364 // C++11 [expr.prim.lambda]p4:
365 // - if the compound-statement is of the form
366 //
367 // { attribute-specifier-seq[opt] return expression ; }
368 //
369 // the type of the returned expression after
370 // lvalue-to-rvalue conversion (4.1), array-to-pointer
371 // conver- sion (4.2), and function-to-pointer conversion
372 // (4.3);
373 //
374 // Since we're accepting the resolution to a post-C++11 core
375 // issue with a non-trivial extension, provide a warning (by
376 // default).
377 CompoundStmt *CompoundBody = cast<CompoundStmt>(Body);
378 if (!(CompoundBody->size() == 1 &&
379 isa<ReturnStmt>(*CompoundBody->body_begin())) &&
380 !Context.hasSameType(LSI->ReturnType, Context.VoidTy))
381 Diag(IntroducerRange.getBegin(),
382 diag::ext_lambda_implies_void_return);
383 }
384
385 // Create a function type with the inferred return type.
386 const FunctionProtoType *Proto
387 = CallOperator->getType()->getAs<FunctionProtoType>();
388 QualType FunctionTy
389 = Context.getFunctionType(LSI->ReturnType,
390 Proto->arg_type_begin(),
391 Proto->getNumArgs(),
392 Proto->getExtProtoInfo());
393 CallOperator->setType(FunctionTy);
394 }
395
Douglas Gregor8c50e7c2012-02-09 00:47:04 +0000396 // Finalize the lambda class.
397 SmallVector<Decl*, 4> Fields(Class->field_begin(), Class->field_end());
398 ActOnFields(0, Class->getLocation(), Class, Fields,
399 SourceLocation(), SourceLocation(), 0);
400 CheckCompletedCXXClass(Class);
401
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000402 // C++ [expr.prim.lambda]p7:
403 // The lambda-expression's compound-statement yields the
404 // function-body (8.4) of the function call operator [...].
Douglas Gregor410d6af2012-02-09 08:52:43 +0000405 ActOnFinishFunctionBody(CallOperator, Body, /*IsInstantation=*/false);
406 CallOperator->setLexicalDeclContext(Class);
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000407 }
408
Douglas Gregor8c50e7c2012-02-09 00:47:04 +0000409 if (LambdaExprNeedsCleanups)
410 ExprNeedsCleanups = true;
411
Douglas Gregor89625492012-02-09 08:14:43 +0000412 LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange,
413 CaptureDefault, Captures,
414 ExplicitParams, CaptureInits,
415 Body->getLocEnd());
Douglas Gregor9c702202012-02-10 07:45:31 +0000416 Class->setLambda(Lambda);
Douglas Gregor89625492012-02-09 08:14:43 +0000417
418 // C++11 [expr.prim.lambda]p2:
419 // A lambda-expression shall not appear in an unevaluated operand
420 // (Clause 5).
421 switch (ExprEvalContexts.back().Context) {
422 case Unevaluated:
423 // We don't actually diagnose this case immediately, because we
424 // could be within a context where we might find out later that
425 // the expression is potentially evaluated (e.g., for typeid).
426 ExprEvalContexts.back().Lambdas.push_back(Lambda);
427 break;
428
429 case ConstantEvaluated:
430 case PotentiallyEvaluated:
431 case PotentiallyEvaluatedIfUsed:
432 break;
433 }
434
Douglas Gregor12695102012-02-10 08:36:38 +0000435 // C++11 [expr.prim.lambda]p6:
436 // The closure type for a lambda-expression with no lambda-capture
437 // has a public non-virtual non-explicit const conversion function
438 // to pointer to function having the same parameter and return
439 // types as the closure type's function call operator.
440 if (Captures.empty() && CaptureDefault == LCD_None) {
441 const FunctionProtoType *Proto
442 = CallOperator->getType()->getAs<FunctionProtoType>();
443 QualType FunctionPtrTy;
444 {
445 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
446 ExtInfo.TypeQuals = 0;
447 QualType FunctionTy
448 = Context.getFunctionType(Proto->getResultType(),
449 Proto->arg_type_begin(),
450 Proto->getNumArgs(),
451 ExtInfo);
452 FunctionPtrTy = Context.getPointerType(FunctionTy);
453 }
454
455 FunctionProtoType::ExtProtoInfo ExtInfo;
456 ExtInfo.TypeQuals = Qualifiers::Const;
457 QualType ConvTy = Context.getFunctionType(FunctionPtrTy, 0, 0, ExtInfo);
458
459 SourceLocation Loc = IntroducerRange.getBegin();
460 DeclarationName Name
461 = Context.DeclarationNames.getCXXConversionFunctionName(
462 Context.getCanonicalType(FunctionPtrTy));
463 DeclarationNameLoc NameLoc;
464 NameLoc.NamedType.TInfo = Context.getTrivialTypeSourceInfo(FunctionPtrTy,
465 Loc);
466 CXXConversionDecl *Conversion
467 = CXXConversionDecl::Create(Context, Class, Loc,
468 DeclarationNameInfo(Name, Loc, NameLoc),
469 ConvTy,
470 Context.getTrivialTypeSourceInfo(ConvTy, Loc),
471 /*isInline=*/false, /*isExplicit=*/false,
472 /*isConstexpr=*/false, Body->getLocEnd());
473 Conversion->setAccess(AS_public);
474 Conversion->setImplicit(true);
475 Class->addDecl(Conversion);
476 }
477
Douglas Gregor8c50e7c2012-02-09 00:47:04 +0000478 return MaybeBindToTemporary(Lambda);
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000479}