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