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