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