SemaLambda.cpp revision b555971345750350c21d541afe135054c7402933
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.HasTrailingReturn = true;
50    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
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    // C++11 [expr.prim.lambda]p6:
396    //   The closure type for a lambda-expression with no lambda-capture
397    //   has a public non-virtual non-explicit const conversion function
398    //   to pointer to function having the same parameter and return
399    //   types as the closure type's function call operator.
400    if (Captures.empty() && CaptureDefault == LCD_None) {
401      const FunctionProtoType *Proto
402        = CallOperator->getType()->getAs<FunctionProtoType>();
403      QualType FunctionPtrTy;
404      {
405        FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
406        ExtInfo.TypeQuals = 0;
407        QualType FunctionTy
408          = Context.getFunctionType(Proto->getResultType(),
409                                    Proto->arg_type_begin(),
410                                    Proto->getNumArgs(),
411                                    ExtInfo);
412        FunctionPtrTy = Context.getPointerType(FunctionTy);
413      }
414
415      FunctionProtoType::ExtProtoInfo ExtInfo;
416      ExtInfo.TypeQuals = Qualifiers::Const;
417      QualType ConvTy = Context.getFunctionType(FunctionPtrTy, 0, 0, ExtInfo);
418
419      SourceLocation Loc = IntroducerRange.getBegin();
420      DeclarationName Name
421        = Context.DeclarationNames.getCXXConversionFunctionName(
422            Context.getCanonicalType(FunctionPtrTy));
423      DeclarationNameLoc NameLoc;
424      NameLoc.NamedType.TInfo = Context.getTrivialTypeSourceInfo(FunctionPtrTy,
425                                                                 Loc);
426      CXXConversionDecl *Conversion
427        = CXXConversionDecl::Create(Context, Class, Loc,
428                                    DeclarationNameInfo(Name, Loc, NameLoc),
429                                    ConvTy,
430                                    Context.getTrivialTypeSourceInfo(ConvTy,
431                                                                     Loc),
432                                    /*isInline=*/false, /*isExplicit=*/false,
433                                    /*isConstexpr=*/false, Body->getLocEnd());
434      Conversion->setAccess(AS_public);
435      Conversion->setImplicit(true);
436      Class->addDecl(Conversion);
437    }
438
439    // C++ [expr.prim.lambda]p7:
440    //   The lambda-expression's compound-statement yields the
441    //   function-body (8.4) of the function call operator [...].
442    ActOnFinishFunctionBody(CallOperator, Body, /*IsInstantation=*/false);
443
444    // Finalize the lambda class.
445    SmallVector<Decl*, 4> Fields(Class->field_begin(), Class->field_end());
446    CallOperator->setLexicalDeclContext(Class);
447    Class->addDecl(CallOperator);
448    ActOnFields(0, Class->getLocation(), Class, Fields,
449                SourceLocation(), SourceLocation(), 0);
450    CheckCompletedCXXClass(Class);
451
452  }
453
454  if (LambdaExprNeedsCleanups)
455    ExprNeedsCleanups = true;
456
457  LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange,
458                                          CaptureDefault, Captures,
459                                          ExplicitParams, CaptureInits,
460                                          Body->getLocEnd());
461  Class->setLambda(Lambda);
462
463  // C++11 [expr.prim.lambda]p2:
464  //   A lambda-expression shall not appear in an unevaluated operand
465  //   (Clause 5).
466  switch (ExprEvalContexts.back().Context) {
467  case Unevaluated:
468    // We don't actually diagnose this case immediately, because we
469    // could be within a context where we might find out later that
470    // the expression is potentially evaluated (e.g., for typeid).
471    ExprEvalContexts.back().Lambdas.push_back(Lambda);
472    break;
473
474  case ConstantEvaluated:
475  case PotentiallyEvaluated:
476  case PotentiallyEvaluatedIfUsed:
477    break;
478  }
479
480  return MaybeBindToTemporary(Lambda);
481}
482