LambdaRewriter.cs 59.2 KB
Newer Older
1
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.
P
Pilchie 已提交
2 3 4 5

#if DEBUG
//#define CHECK_LOCALS // define CHECK_LOCALS to help debug some rewriting problems that would otherwise cause code-gen failures

6
#endif
P
Pilchie 已提交
7 8 9 10
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
11
using Microsoft.CodeAnalysis.CodeGen;
P
Pilchie 已提交
12
using Microsoft.CodeAnalysis.CSharp.Symbols;
13
using Microsoft.CodeAnalysis.CSharp.Syntax;
P
Pilchie 已提交
14 15 16 17 18 19 20 21 22
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.CSharp
{
    /// <summary>
    /// The rewriter for removing lambda expressions from method bodies and introducing closure classes
    /// as containers for captured variables along the lines of the example in section 6.5.3 of the
    /// C# language specification.
    /// 
T
TomasMatousek 已提交
23
    /// The entry point is the public method <see cref="Rewrite"/>.  It operates as follows:
P
Pilchie 已提交
24 25 26
    /// 
    /// First, an analysis of the whole method body is performed that determines which variables are
    /// captured, what their scopes are, and what the nesting relationship is between scopes that
27
    /// have captured variables.  The result of this analysis is left in <see cref="_analysis"/>.
P
Pilchie 已提交
28 29
    /// 
    /// Then we make a frame, or compiler-generated class, represented by an instance of
T
TomasMatousek 已提交
30
    /// <see cref="LambdaFrame"/> for each scope with captured variables.  The generated frames are kept
31
    /// in <see cref="_frames"/>.  Each frame is given a single field for each captured
T
TomasMatousek 已提交
32
    /// variable in the corresponding scope.  These are are maintained in <see cref="MethodToClassRewriter.proxies"/>.
P
Pilchie 已提交
33 34
    /// 
    /// Finally, we walk and rewrite the input bound tree, keeping track of the following:
35 36 37
    /// (1) The current set of active frame pointers, in <see cref="_framePointers"/>
    /// (2) The current method being processed (this changes within a lambda's body), in <see cref="_currentMethod"/>
    /// (3) The "this" symbol for the current method in <see cref="_currentFrameThis"/>, and
P
Pilchie 已提交
38 39 40 41 42 43 44 45
    /// (4) The symbol that is used to access the innermost frame pointer (it could be a local variable or "this" parameter)
    /// 
    /// There are a few key transformations done in the rewriting.
    /// (1) Lambda expressions are turned into delegate creation expressions, and the body of the lambda is
    ///     moved into a new, compiler-generated method of a selected frame class.
    /// (2) On entry to a scope with captured variables, we create a frame object and store it in a local variable.
    /// (3) References to captured variables are transformed into references to fields of a frame class.
    /// 
T
TomasMatousek 已提交
46
    /// In addition, the rewriting deposits into <see cref="TypeCompilationState.SynthesizedMethods"/> a (<see cref="MethodSymbol"/>, <see cref="BoundStatement"/>)
P
Pilchie 已提交
47 48
    /// pair for each generated method.
    /// 
T
TomasMatousek 已提交
49
    /// <see cref="Rewrite"/> produces its output in two forms.  First, it returns a new bound statement
P
Pilchie 已提交
50
    /// for the caller to use for the body of the original method.  Second, it returns a collection of
T
TomasMatousek 已提交
51
    /// (<see cref="MethodSymbol"/>, <see cref="BoundStatement"/>) pairs for additional methods that the lambda rewriter produced.
P
Pilchie 已提交
52 53 54 55 56
    /// These additional methods contain the bodies of the lambdas moved into ordinary methods of their
    /// respective frame classes, and the caller is responsible for processing them just as it does with
    /// the returned bound node.  For example, the caller will typically perform iterator method and
    /// asynchronous method transformations, and emit IL instructions into an assembly.
    /// </summary>
57
    internal sealed partial class LambdaRewriter : MethodToClassRewriter
P
Pilchie 已提交
58
    {
59 60 61
        private readonly Analysis _analysis;
        private readonly MethodSymbol _topLevelMethod;
        private readonly int _topLevelMethodOrdinal;
P
Pilchie 已提交
62

63 64
        // lambda frame for static lambdas. 
        // initialized lazily and could be null if there are no static lambdas
65
        private LambdaFrame _lazyStaticLambdaFrame;
66

67
        // A mapping from every lambda parameter to its corresponding method's parameter.
68
        private readonly Dictionary<ParameterSymbol, ParameterSymbol> _parameterMap = new Dictionary<ParameterSymbol, ParameterSymbol>();
69

P
Pilchie 已提交
70
        // for each block with lifted (captured) variables, the corresponding frame type
71
        private readonly Dictionary<BoundNode, LambdaFrame> _frames = new Dictionary<BoundNode, LambdaFrame>();
P
Pilchie 已提交
72 73 74

        // the current set of frame pointers in scope.  Each is either a local variable (where introduced),
        // or the "this" parameter when at the top level.  Keys in this map are never constructed types.
75
        private readonly Dictionary<NamedTypeSymbol, Symbol> _framePointers = new Dictionary<NamedTypeSymbol, Symbol>();
P
Pilchie 已提交
76

77 78 79
        // True if the rewritten tree should include assignments of the
        // original locals to the lifted proxies. This is only useful for the
        // expression evaluator where the original locals are left as is.
80
        private readonly bool _assignLocals;
81

P
Pilchie 已提交
82
        // The current method or lambda being processed.
83
        private MethodSymbol _currentMethod;
P
Pilchie 已提交
84 85

        // The "this" symbol for the current method.
86
        private ParameterSymbol _currentFrameThis;
P
Pilchie 已提交
87

88
        private ArrayBuilder<LambdaDebugInfo> _lambdaDebugInfoBuilder;
89

90
        // ID dispenser for field names of frame references
91
        private int _synthesizedFieldNameIdDispenser;
92

P
Pilchie 已提交
93
        // The symbol (field or local) holding the innermost frame
94
        private Symbol _innermostFramePointer;
P
Pilchie 已提交
95 96

        // The mapping of type parameters for the current lambda body
97
        private TypeMap _currentLambdaBodyTypeMap;
P
Pilchie 已提交
98 99

        // The current set of type parameters (mapped from the enclosing method's type parameters)
100
        private ImmutableArray<TypeParameterSymbol> _currentTypeParameters;
P
Pilchie 已提交
101 102 103

        // Initialization for the proxy of the upper frame if it needs to be deferred.
        // Such situation happens when lifting this in a ctor.
104
        private BoundExpression _thisProxyInitDeferred;
P
Pilchie 已提交
105 106

        // Set to true once we've seen the base (or self) constructor invocation in a constructor
107
        private bool _seenBaseCall;
P
Pilchie 已提交
108 109

        // Set to true while translating code inside of an expression lambda.
110
        private bool _inExpressionLambda;
P
Pilchie 已提交
111 112 113 114

        // When a lambda captures only 'this' of the enclosing method, we cache it in a local
        // variable.  This is the set of such local variables that must be added to the enclosing
        // method's top-level block.
115
        private ArrayBuilder<LocalSymbol> _addedLocals;
P
Pilchie 已提交
116 117 118

        // Similarly, this is the set of statements that must be added to the enclosing method's
        // top-level block initializing those variables to null.
119
        private ArrayBuilder<BoundStatement> _addedStatements;
P
Pilchie 已提交
120 121 122 123

        private LambdaRewriter(
            Analysis analysis,
            NamedTypeSymbol thisType,
T
TomasMatousek 已提交
124
            ParameterSymbol thisParameterOpt,
P
Pilchie 已提交
125
            MethodSymbol method,
126
            int methodOrdinal,
127
            ArrayBuilder<LambdaDebugInfo> lambdaDebugInfoBuilder,
128
            VariableSlotAllocator slotAllocatorOpt,
P
Pilchie 已提交
129 130
            TypeCompilationState compilationState,
            DiagnosticBag diagnostics,
131
            bool assignLocals)
132
            : base(slotAllocatorOpt, compilationState, diagnostics)
P
Pilchie 已提交
133
        {
T
TomasMatousek 已提交
134 135 136 137 138 139
            Debug.Assert(analysis != null);
            Debug.Assert(thisType != null);
            Debug.Assert(method != null);
            Debug.Assert(compilationState != null);
            Debug.Assert(diagnostics != null);

140 141 142 143 144 145 146 147 148 149 150 151
            _topLevelMethod = method;
            _topLevelMethodOrdinal = methodOrdinal;
            _lambdaDebugInfoBuilder = lambdaDebugInfoBuilder;
            _currentMethod = method;
            _analysis = analysis;
            _assignLocals = assignLocals;
            _currentTypeParameters = method.TypeParameters;
            _currentLambdaBodyTypeMap = TypeMap.Empty;
            _innermostFramePointer = _currentFrameThis = thisParameterOpt;
            _framePointers[thisType] = thisParameterOpt;
            _seenBaseCall = method.MethodKind != MethodKind.Constructor; // only used for ctors
            _synthesizedFieldNameIdDispenser = 1;
P
Pilchie 已提交
152 153
        }

154 155 156
        protected override bool NeedsProxy(Symbol localOrParameter)
        {
            Debug.Assert(localOrParameter is LocalSymbol || localOrParameter is ParameterSymbol);
157
            return _analysis.capturedVariables.ContainsKey(localOrParameter);
158 159
        }

P
Pilchie 已提交
160 161 162 163 164 165
        /// <summary>
        /// Rewrite the given node to eliminate lambda expressions.  Also returned are the method symbols and their
        /// bound bodies for the extracted lambda bodies. These would typically be emitted by the caller such as
        /// MethodBodyCompiler.  See this class' documentation
        /// for a more thorough explanation of the algorithm and its use by clients.
        /// </summary>
166
        /// <param name="loweredBody">The bound node to be rewritten</param>
P
Pilchie 已提交
167 168 169
        /// <param name="thisType">The type of the top-most frame</param>
        /// <param name="thisParameter">The "this" parameter in the top-most frame, or null if static method</param>
        /// <param name="method">The containing method of the node to be rewritten</param>
170
        /// <param name="methodOrdinal">Index of the method symbol in its containing type member list.</param>
171 172
        /// <param name="lambdaDebugInfoBuilder">Information on lambdas defined in <paramref name="method"/> needed for debugging.</param>
        /// <param name="closureDebugInfoBuilder">Information on closures defined in <paramref name="method"/> needed for debugging.</param>
173
        /// <param name="slotAllocatorOpt">Slot allocator.</param>
P
Pilchie 已提交
174 175
        /// <param name="compilationState">The caller's buffer into which we produce additional methods to be emitted by the caller</param>
        /// <param name="diagnostics">Diagnostic bag for diagnostics</param>
176
        /// <param name="assignLocals">The rewritten tree should include assignments of the original locals to the lifted proxies</param>
P
Pilchie 已提交
177
        public static BoundStatement Rewrite(
178
            BoundStatement loweredBody,
P
Pilchie 已提交
179 180 181
            NamedTypeSymbol thisType,
            ParameterSymbol thisParameter,
            MethodSymbol method,
182
            int methodOrdinal,
183 184
            ArrayBuilder<LambdaDebugInfo> lambdaDebugInfoBuilder,
            ArrayBuilder<ClosureDebugInfo> closureDebugInfoBuilder,
185
            VariableSlotAllocator slotAllocatorOpt,
P
Pilchie 已提交
186 187
            TypeCompilationState compilationState,
            DiagnosticBag diagnostics,
188
            bool assignLocals)
P
Pilchie 已提交
189 190 191
        {
            Debug.Assert((object)thisType != null);
            Debug.Assert(((object)thisParameter == null) || (thisParameter.Type == thisType));
192 193 194 195 196 197 198 199 200 201 202 203
            Debug.Assert(compilationState.ModuleBuilderOpt != null);

            var analysis = Analysis.Analyze(loweredBody, method);
            if (!analysis.SeenLambda)
            {
                // Unreachable anonymous functions are ignored by the analyzer.
                // No closures or lambda methods are generated.
                // E.g. 
                //   int y = 0;
                //   var b = false && from z in new X(y) select f(z + y)
                return loweredBody;
            }
P
Pilchie 已提交
204

205
            CheckLocalsDefined(loweredBody);
206 207 208 209 210
            var rewriter = new LambdaRewriter(
                analysis,
                thisType,
                thisParameter,
                method,
211
                methodOrdinal,
212
                lambdaDebugInfoBuilder,
213
                slotAllocatorOpt,
214 215 216
                compilationState,
                diagnostics,
                assignLocals);
217

P
Pilchie 已提交
218
            analysis.ComputeLambdaScopesAndFrameCaptures();
219 220
            rewriter.MakeFrames(closureDebugInfoBuilder);
            var body = rewriter.AddStatementsIfNeeded((BoundStatement)rewriter.Visit(loweredBody));
P
Pilchie 已提交
221
            CheckLocalsDefined(body);
222

P
Pilchie 已提交
223 224 225
            return body;
        }

226
        private BoundStatement AddStatementsIfNeeded(BoundStatement body)
P
Pilchie 已提交
227
        {
228
            if (_addedLocals != null)
P
Pilchie 已提交
229
            {
230 231 232 233
                _addedStatements.Add(body);
                body = new BoundBlock(body.Syntax, _addedLocals.ToImmutableAndFree(), _addedStatements.ToImmutableAndFree()) { WasCompilerGenerated = true };
                _addedLocals = null;
                _addedStatements = null;
P
Pilchie 已提交
234 235 236
            }
            else
            {
237
                Debug.Assert(_addedStatements == null);
P
Pilchie 已提交
238 239 240 241 242 243 244
            }

            return body;
        }

        protected override TypeMap TypeMap
        {
245
            get { return _currentLambdaBodyTypeMap; }
P
Pilchie 已提交
246 247 248 249
        }

        protected override MethodSymbol CurrentMethod
        {
250
            get { return _currentMethod; }
P
Pilchie 已提交
251 252 253 254
        }

        protected override NamedTypeSymbol ContainingType
        {
255
            get { return _topLevelMethod.ContainingType; }
P
Pilchie 已提交
256 257 258 259 260 261 262 263 264 265 266
        }

        /// <summary>
        /// Check that the top-level node is well-defined, in the sense that all
        /// locals that are used are defined in some enclosing scope.
        /// </summary>
        static partial void CheckLocalsDefined(BoundNode node);

        /// <summary>
        /// Create the frame types.
        /// </summary>
267
        private void MakeFrames(ArrayBuilder<ClosureDebugInfo> closureDebugInfo)
P
Pilchie 已提交
268 269 270
        {
            NamedTypeSymbol containingType = this.ContainingType;

271
            foreach (var kvp in _analysis.capturedVariables)
P
Pilchie 已提交
272
            {
P
pgavlin 已提交
273 274
                var captured = kvp.Key;

275
                BoundNode scope;
276
                if (!_analysis.variableScope.TryGetValue(captured, out scope))
P
Pilchie 已提交
277 278 279 280
                {
                    continue;
                }

281
                LambdaFrame frame = GetFrameForScope(scope, closureDebugInfo);
P
Pilchie 已提交
282

283
                var hoistedField = LambdaCapturedVariable.Create(frame, captured, ref _synthesizedFieldNameIdDispenser);
284
                proxies.Add(captured, new CapturedToFrameSymbolReplacement(hoistedField, isReusable: false));
285
                CompilationState.ModuleBuilderOpt.AddSynthesizedDefinition(frame, hoistedField);
P
Pilchie 已提交
286

287
                if (hoistedField.Type.IsRestrictedType())
P
Pilchie 已提交
288
                {
P
pgavlin 已提交
289
                    foreach (CSharpSyntaxNode syntax in kvp.Value)
P
Pilchie 已提交
290 291
                    {
                        // CS4013: Instance of type '{0}' cannot be used inside an anonymous function, query expression, iterator block or async method
292
                        this.Diagnostics.Add(ErrorCode.ERR_SpecialByRefInLambda, syntax.Location, hoistedField.Type);
P
Pilchie 已提交
293 294 295 296 297
                    }
                }
            }
        }

298
        private LambdaFrame GetFrameForScope(BoundNode scope, ArrayBuilder<ClosureDebugInfo> closureDebugInfo)
299 300
        {
            LambdaFrame frame;
301
            if (!_frames.TryGetValue(scope, out frame))
302
            {
303 304 305 306
                var syntax = scope.Syntax;
                Debug.Assert(syntax != null);

                int closureOrdinal = closureDebugInfo.Count;
307
                int syntaxOffset = _topLevelMethod.CalculateLocalSyntaxOffset(syntax.SpanStart, syntax.SyntaxTree);
308 309
                closureDebugInfo.Add(new ClosureDebugInfo(syntaxOffset));

310
                var methodId = new MethodDebugId(_topLevelMethodOrdinal, CompilationState.ModuleBuilderOpt.CurrentGenerationOrdinal);
311

312 313
                frame = new LambdaFrame(slotAllocatorOpt, _topLevelMethod, methodId, syntax, closureOrdinal);
                _frames.Add(scope, frame);
314

315 316 317 318 319
                CompilationState.ModuleBuilderOpt.AddSynthesizedDefinition(this.ContainingType, frame);
                CompilationState.AddSynthesizedMethod(
                    frame.Constructor,
                    FlowAnalysisPass.AppendImplicitReturn(MethodCompiler.BindMethodBody(frame.Constructor, CompilationState, null),
                    frame.Constructor));
320 321 322 323 324 325 326
            }

            return frame;
        }

        private LambdaFrame GetStaticFrame(DiagnosticBag diagnostics, BoundNode lambda)
        {
327
            if (_lazyStaticLambdaFrame == null)
328
            {
329
                var isNonGeneric = !_topLevelMethod.IsGenericMethod;
330 331
                if (isNonGeneric)
                {
332
                    _lazyStaticLambdaFrame = CompilationState.staticLambdaFrame;
333 334
                }

335
                if (_lazyStaticLambdaFrame == null)
336
                {
337 338 339 340 341 342 343
                    MethodDebugId methodId;
                    if (isNonGeneric)
                    {
                        methodId = new MethodDebugId(MethodDebugId.UndefinedOrdinal, CompilationState.ModuleBuilderOpt.CurrentGenerationOrdinal);
                    }
                    else
                    {
344
                        methodId = slotAllocatorOpt?.PreviousMethodId ?? new MethodDebugId(_topLevelMethodOrdinal, CompilationState.ModuleBuilderOpt.CurrentGenerationOrdinal);
345
                    }
346

347
                    _lazyStaticLambdaFrame = new LambdaFrame(slotAllocatorOpt, _topLevelMethod, methodId, scopeSyntaxOpt: null, closureOrdinal: -1);
348 349

                    // nongeneric static lambdas can share the frame
350
                    if (isNonGeneric)
351
                    {
352
                        CompilationState.staticLambdaFrame = _lazyStaticLambdaFrame;
353 354
                    }

355
                    var frame = _lazyStaticLambdaFrame;
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381

                    // add frame type
                    CompilationState.ModuleBuilderOpt.AddSynthesizedDefinition(this.ContainingType, frame);

                    // add its ctor
                    CompilationState.AddSynthesizedMethod(
                        frame.Constructor,
                        FlowAnalysisPass.AppendImplicitReturn(MethodCompiler.BindMethodBody(frame.Constructor, CompilationState, null),
                        frame.Constructor));

                    // associate the frame with the the first lambda that caused it to exist. 
                    // we need to associate this with somme syntax.
                    // unfortunately either containing method or containing class could be synthetic
                    // therefore could have no syntax.
                    CSharpSyntaxNode syntax = lambda.Syntax;

                    // add cctor
                    // Frame.inst = new Frame()
                    var F = new SyntheticBoundNodeFactory(frame.StaticConstructor, syntax, CompilationState, diagnostics);
                    var body = F.Block(
                            F.Assignment(
                                F.Field(null, frame.SingletonCache),
                                F.New(frame.Constructor)),
                            F.Return());

                    CompilationState.AddSynthesizedMethod(frame.StaticConstructor, body);
382 383 384
                }
            }

385
            return _lazyStaticLambdaFrame;
386 387
        }

P
Pilchie 已提交
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
        /// <summary>
        /// Produce a bound expression representing a pointer to a frame of a particular frame type.
        /// </summary>
        /// <param name="syntax">The syntax to attach to the bound nodes produced</param>
        /// <param name="frameType">The type of frame to be returned</param>
        /// <returns>A bound node that computes the pointer to the required frame</returns>
        private BoundExpression FrameOfType(CSharpSyntaxNode syntax, NamedTypeSymbol frameType)
        {
            BoundExpression result = FramePointer(syntax, frameType.OriginalDefinition);
            Debug.Assert(result.Type == frameType);
            return result;
        }

        /// <summary>
        /// Produce a bound expression representing a pointer to a frame of a particular frame class.
        /// Note that for generic frames, the frameClass parameter is the generic definition, but
        /// the resulting expression will be constructed with the current type parameters.
        /// </summary>
        /// <param name="syntax">The syntax to attach to the bound nodes produced</param>
        /// <param name="frameClass">The class type of frame to be returned</param>
        /// <returns>A bound node that computes the pointer to the required frame</returns>
        protected override BoundExpression FramePointer(CSharpSyntaxNode syntax, NamedTypeSymbol frameClass)
        {
            Debug.Assert(frameClass.IsDefinition);

            // If in an instance method of the right type, we can just return the "this" pointer.
414
            if ((object)_currentFrameThis != null && _currentFrameThis.Type == frameClass)
P
Pilchie 已提交
415 416 417 418 419
            {
                return new BoundThisReference(syntax, frameClass);
            }

            // Otherwise we need to return the value from a frame pointer local variable...
420
            Symbol framePointer = _framePointers[frameClass];
P
Pilchie 已提交
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452
            CapturedSymbolReplacement proxyField;
            if (proxies.TryGetValue(framePointer, out proxyField))
            {
                // However, frame pointer local variables themselves can be "captured".  In that case
                // the inner frames contain pointers to the enclosing frames.  That is, nested
                // frame pointers are organized in a linked list.
                return proxyField.Replacement(syntax, frameType => FramePointer(syntax, frameType));
            }

            var localFrame = framePointer as LocalSymbol;
            return new BoundLocal(syntax, localFrame, null, localFrame.Type);
        }

        private static void InsertAndFreePrologue(ArrayBuilder<BoundStatement> result, ArrayBuilder<BoundExpression> prologue)
        {
            foreach (var expr in prologue)
            {
                result.Add(new BoundExpressionStatement(expr.Syntax, expr));
            }

            prologue.Free();
        }

        /// <summary>
        /// Introduce a frame around the translation of the given node.
        /// </summary>
        /// <param name="node">The node whose translation should be translated to contain a frame</param>
        /// <param name="frame">The frame for the translated node</param>
        /// <param name="F">A function that computes the translation of the node.  It receives lists of added statements and added symbols</param>
        /// <returns>The translated statement, as returned from F</returns>
        private T IntroduceFrame<T>(BoundNode node, LambdaFrame frame, Func<ArrayBuilder<BoundExpression>, ArrayBuilder<LocalSymbol>, T> F)
        {
453
            NamedTypeSymbol frameType = frame.ConstructIfGeneric(StaticCast<TypeSymbol>.From(_currentTypeParameters));
454 455

            Debug.Assert(frame.ScopeSyntaxOpt != null);
456
            LocalSymbol framePointer = new SynthesizedLocal(_topLevelMethod, frameType, SynthesizedLocalKind.LambdaDisplayClass, frame.ScopeSyntaxOpt);
P
Pilchie 已提交
457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475

            CSharpSyntaxNode syntax = node.Syntax;

            // assign new frame to the frame variable

            var prologue = ArrayBuilder<BoundExpression>.GetInstance();

            MethodSymbol constructor = frame.Constructor.AsMember(frameType);
            Debug.Assert(frameType == constructor.ContainingType);
            var newFrame = new BoundObjectCreationExpression(
                syntax: syntax,
                constructor: constructor);

            prologue.Add(new BoundAssignmentOperator(syntax,
                new BoundLocal(syntax, framePointer, null, frameType),
                newFrame,
                frameType));

            CapturedSymbolReplacement oldInnermostFrameProxy = null;
476
            if ((object)_innermostFramePointer != null)
P
Pilchie 已提交
477
            {
478 479
                proxies.TryGetValue(_innermostFramePointer, out oldInnermostFrameProxy);
                if (_analysis.needsParentFrame.Contains(node))
P
Pilchie 已提交
480
                {
481
                    var capturedFrame = LambdaCapturedVariable.Create(frame, _innermostFramePointer, ref _synthesizedFieldNameIdDispenser);
P
Pilchie 已提交
482 483 484 485 486
                    FieldSymbol frameParent = capturedFrame.AsMember(frameType);
                    BoundExpression left = new BoundFieldAccess(syntax, new BoundLocal(syntax, framePointer, null, frameType), frameParent, null);
                    BoundExpression right = FrameOfType(syntax, frameParent.Type as NamedTypeSymbol);
                    BoundExpression assignment = new BoundAssignmentOperator(syntax, left, right, left.Type);

487
                    if (_currentMethod.MethodKind == MethodKind.Constructor && capturedFrame.Type == _currentMethod.ContainingType && !_seenBaseCall)
P
Pilchie 已提交
488 489 490 491 492
                    {
                        // Containing method is a constructor 
                        // Initialization statement for the "this" proxy must be inserted
                        // after the constructor initializer statement block
                        // This insertion will be done by the delegate F
493 494
                        Debug.Assert(_thisProxyInitDeferred == null);
                        _thisProxyInitDeferred = assignment;
P
Pilchie 已提交
495 496 497 498 499 500 501 502
                    }
                    else
                    {
                        prologue.Add(assignment);
                    }

                    if (CompilationState.Emitting)
                    {
T
TomasMatousek 已提交
503
                        CompilationState.ModuleBuilderOpt.AddSynthesizedDefinition(frame, capturedFrame);
P
Pilchie 已提交
504 505
                    }

506
                    proxies[_innermostFramePointer] = new CapturedToFrameSymbolReplacement(capturedFrame, isReusable: false);
P
Pilchie 已提交
507 508 509 510
                }
            }

            // Capture any parameters of this block.  This would typically occur
511
            // at the top level of a method or lambda with captured parameters.
P
Pilchie 已提交
512
            // TODO: speed up the following by computing it in analysis.
513
            foreach (var variable in _analysis.capturedVariables.Keys)
P
Pilchie 已提交
514 515
            {
                BoundNode varNode;
516
                if (!_analysis.variableScope.TryGetValue(variable, out varNode) || varNode != node)
P
Pilchie 已提交
517 518 519 520
                {
                    continue;
                }

521
                InitVariableProxy(syntax, variable, framePointer, prologue);
P
Pilchie 已提交
522 523
            }

524
            Symbol oldInnermostFramePointer = _innermostFramePointer;
P
Pilchie 已提交
525

526
            _innermostFramePointer = framePointer;
P
Pilchie 已提交
527 528
            var addedLocals = ArrayBuilder<LocalSymbol>.GetInstance();
            addedLocals.Add(framePointer);
529
            _framePointers.Add(frame, framePointer);
P
Pilchie 已提交
530 531 532

            var result = F(prologue, addedLocals);

533 534
            _framePointers.Remove(frame);
            _innermostFramePointer = oldInnermostFramePointer;
P
Pilchie 已提交
535

536
            if ((object)_innermostFramePointer != null)
P
Pilchie 已提交
537 538 539
            {
                if (oldInnermostFrameProxy != null)
                {
540
                    proxies[_innermostFramePointer] = oldInnermostFrameProxy;
P
Pilchie 已提交
541 542 543
                }
                else
                {
544
                    proxies.Remove(_innermostFramePointer);
P
Pilchie 已提交
545 546 547 548 549 550
                }
            }

            return result;
        }

551
        private void InitVariableProxy(CSharpSyntaxNode syntax, Symbol symbol, LocalSymbol framePointer, ArrayBuilder<BoundExpression> prologue)
P
Pilchie 已提交
552 553
        {
            CapturedSymbolReplacement proxy;
554
            if (proxies.TryGetValue(symbol, out proxy))
P
Pilchie 已提交
555
            {
556 557
                BoundExpression value;
                switch (symbol.Kind)
558
                {
559 560 561
                    case SymbolKind.Parameter:
                        var parameter = (ParameterSymbol)symbol;
                        ParameterSymbol parameterToUse;
562
                        if (!_parameterMap.TryGetValue(parameter, out parameterToUse))
563 564
                        {
                            parameterToUse = parameter;
565
                        }
566 567

                        value = new BoundParameter(syntax, parameterToUse);
568
                        break;
569

570
                    case SymbolKind.Local:
571
                        if (!_assignLocals)
572 573 574
                        {
                            return;
                        }
575

576 577 578 579 580 581 582 583
                        var local = (LocalSymbol)symbol;
                        LocalSymbol localToUse;
                        if (!localMap.TryGetValue(local, out localToUse))
                        {
                            localToUse = local;
                        }

                        value = new BoundLocal(syntax, localToUse, null, localToUse.Type);
584
                        break;
585

586 587 588
                    default:
                        throw ExceptionUtilities.UnexpectedValue(symbol.Kind);
                }
P
Pilchie 已提交
589

590
                var left = proxy.Replacement(syntax, frameType1 => new BoundLocal(syntax, framePointer, null, framePointer.Type));
591
                var assignToProxy = new BoundAssignmentOperator(syntax, left, value, value.Type);
P
Pilchie 已提交
592 593 594 595 596 597
                prologue.Add(assignToProxy);
            }
        }

        #region Visit Methods

598 599 600
        protected override BoundNode VisitUnhoistedParameter(BoundParameter node)
        {
            ParameterSymbol replacementParameter;
601
            if (_parameterMap.TryGetValue(node.ParameterSymbol, out replacementParameter))
602 603 604 605 606 607 608
            {
                return new BoundParameter(node.Syntax, replacementParameter, replacementParameter.Type, node.HasErrors);
            }

            return base.VisitUnhoistedParameter(node);
        }

P
Pilchie 已提交
609 610 611 612 613 614 615 616 617 618 619 620
        public override BoundNode VisitThisReference(BoundThisReference node)
        {
            // "topLevelMethod.ThisParameter == null" can occur in a delegate creation expression because the method group
            // in the argument can have a "this" receiver even when "this"
            // is not captured because a static method is selected.  But we do preserve
            // the method group and its receiver in the bound tree.
            // No need to capture "this" in such case.

            // TODO: Why don't we drop "this" while lowering if method is static? 
            //       Actually, considering that method group expression does not evaluate to a particular value 
            //       why do we have it in the lowered tree at all?

621
            return (_currentMethod == _topLevelMethod || _topLevelMethod.ThisParameter == null ?
622 623
                node :
                FramePointer(node.Syntax, (NamedTypeSymbol)node.Type));
P
Pilchie 已提交
624 625 626 627
        }

        public override BoundNode VisitBaseReference(BoundBaseReference node)
        {
628
            return (_currentMethod.ContainingType == _topLevelMethod.ContainingType)
P
Pilchie 已提交
629
                ? node
630
                : FramePointer(node.Syntax, _topLevelMethod.ContainingType); // technically, not the correct static type
P
Pilchie 已提交
631 632 633 634 635 636 637 638 639 640 641 642 643
        }

        public override BoundNode VisitCall(BoundCall node)
        {
            var visited = base.VisitCall(node);
            if (visited.Kind != BoundKind.Call)
            {
                return visited;
            }

            var rewritten = (BoundCall)visited;

            // Check if we need to init the 'this' proxy in a ctor call
644
            if (!_seenBaseCall)
P
Pilchie 已提交
645
            {
646 647
                _seenBaseCall = _currentMethod == _topLevelMethod && node.IsConstructorInitializer();
                if (_seenBaseCall && _thisProxyInitDeferred != null)
P
Pilchie 已提交
648 649 650 651 652 653 654
                {
                    // Insert the this proxy assignment after the ctor call.
                    // Create bound sequence: { ctor call, thisProxyInitDeferred }
                    return new BoundSequence(
                        syntax: node.Syntax,
                        locals: ImmutableArray<LocalSymbol>.Empty,
                        sideEffects: ImmutableArray.Create<BoundExpression>(rewritten),
655
                        value: _thisProxyInitDeferred,
P
Pilchie 已提交
656 657 658 659 660 661 662 663 664
                        type: rewritten.Type);
                }
            }

            return rewritten;
        }

        private BoundSequence RewriteSequence(BoundSequence node, ArrayBuilder<BoundExpression> prologue, ArrayBuilder<LocalSymbol> newLocals)
        {
665
            RewriteLocals(node.Locals, newLocals);
P
Pilchie 已提交
666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682

            foreach (var expr in node.SideEffects)
            {
                var replacement = (BoundExpression)this.Visit(expr);
                if (replacement != null) prologue.Add(replacement);
            }

            var newValue = (BoundExpression)this.Visit(node.Value);
            var newType = this.VisitType(node.Type);

            return node.Update(newLocals.ToImmutableAndFree(), prologue.ToImmutableAndFree(), newValue, newType);
        }

        public override BoundNode VisitBlock(BoundBlock node)
        {
            LambdaFrame frame;
            // Test if this frame has captured variables and requires the introduction of a closure class.
683
            if (_frames.TryGetValue(node, out frame))
P
Pilchie 已提交
684 685 686 687 688 689 690 691 692 693
            {
                return IntroduceFrame(node, frame, (ArrayBuilder<BoundExpression> prologue, ArrayBuilder<LocalSymbol> newLocals) =>
                    RewriteBlock(node, prologue, newLocals));
            }
            else
            {
                return RewriteBlock(node, ArrayBuilder<BoundExpression>.GetInstance(), ArrayBuilder<LocalSymbol>.GetInstance());
            }
        }

694
        private BoundBlock RewriteBlock(BoundBlock node, ArrayBuilder<BoundExpression> prologue, ArrayBuilder<LocalSymbol> newLocals)
P
Pilchie 已提交
695
        {
696
            RewriteLocals(node.Locals, newLocals);
P
Pilchie 已提交
697 698 699

            var newStatements = ArrayBuilder<BoundStatement>.GetInstance();

700
            if (prologue.Count > 0)
P
Pilchie 已提交
701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723
            {
                newStatements.Add(new BoundSequencePoint(null, null) { WasCompilerGenerated = true });
            }

            InsertAndFreePrologue(newStatements, prologue);

            foreach (var statement in node.Statements)
            {
                var replacement = (BoundStatement)this.Visit(statement);
                if (replacement != null)
                {
                    newStatements.Add(replacement);
                }
            }

            // TODO: we may not need to update if there was nothing to rewrite.
            return node.Update(newLocals.ToImmutableAndFree(), newStatements.ToImmutableAndFree());
        }

        public override BoundNode VisitCatchBlock(BoundCatchBlock node)
        {
            // Test if this frame has captured variables and requires the introduction of a closure class.
            LambdaFrame frame;
724
            if (_frames.TryGetValue(node, out frame))
P
Pilchie 已提交
725 726 727 728 729 730 731 732 733 734 735 736 737 738
            {
                return IntroduceFrame(node, frame, (ArrayBuilder<BoundExpression> prologue, ArrayBuilder<LocalSymbol> newLocals) =>
                {
                    return RewriteCatch(node, prologue, newLocals);
                });
            }
            else
            {
                return RewriteCatch(node, ArrayBuilder<BoundExpression>.GetInstance(), ArrayBuilder<LocalSymbol>.GetInstance());
            }
        }

        private BoundNode RewriteCatch(BoundCatchBlock node, ArrayBuilder<BoundExpression> prologue, ArrayBuilder<LocalSymbol> newLocals)
        {
739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760
            LocalSymbol newLocal;
            if ((object)node.LocalOpt != null && TryRewriteLocal(node.LocalOpt, out newLocal))
            {
                newLocals.Add(newLocal);
            }

            LocalSymbol rewrittenCatchLocal;

            if (newLocals.Count > 0)
            {
                // If the original LocalOpt was lifted into a closure,
                // the newLocals will contain a frame reference. In this case, 
                // instead of an actual local, catch will own the frame reference.

                Debug.Assert((object)node.LocalOpt != null && newLocals.Count == 1);
                rewrittenCatchLocal = newLocals[0];
            }
            else
            {
                Debug.Assert((object)node.LocalOpt == null);
                rewrittenCatchLocal = null;
            }
P
Pilchie 已提交
761 762 763 764 765

            // If exception variable got lifted, IntroduceFrame will give us frame init prologue.
            // It needs to run before the exception variable is accessed.
            // To ensure that, we will make exception variable a sequence that performs prologue as its its sideeffecs.
            BoundExpression rewrittenExceptionSource = null;
766
            var rewrittenFilter = (BoundExpression)this.Visit(node.ExceptionFilterOpt);
P
Pilchie 已提交
767 768 769 770 771 772 773 774 775 776 777 778 779
            if (node.ExceptionSourceOpt != null)
            {
                rewrittenExceptionSource = (BoundExpression)Visit(node.ExceptionSourceOpt);
                if (prologue.Count > 0)
                {
                    rewrittenExceptionSource = new BoundSequence(
                        rewrittenExceptionSource.Syntax,
                        ImmutableArray.Create<LocalSymbol>(),
                        prologue.ToImmutable(),
                        rewrittenExceptionSource,
                        rewrittenExceptionSource.Type);
                }
            }
780 781 782 783 784 785 786 787 788 789
            else if (prologue.Count > 0)
            {
                Debug.Assert(rewrittenFilter != null);
                rewrittenFilter = new BoundSequence(
                    rewrittenFilter.Syntax,
                    ImmutableArray.Create<LocalSymbol>(),
                    prologue.ToImmutable(),
                    rewrittenFilter,
                    rewrittenFilter.Type);
            }
P
Pilchie 已提交
790

791
            // done with this.
792
            newLocals.Free();
P
Pilchie 已提交
793 794 795 796 797 798 799 800
            prologue.Free();

            // rewrite filter and body
            // NOTE: this will proxy all accesses to exception local if that got lifted.
            var exceptionTypeOpt = this.VisitType(node.ExceptionTypeOpt);
            var rewrittenBlock = (BoundBlock)this.Visit(node.Body);

            return node.Update(
801
                rewrittenCatchLocal,
P
Pilchie 已提交
802 803 804
                rewrittenExceptionSource,
                exceptionTypeOpt,
                rewrittenFilter,
805 806
                rewrittenBlock,
                node.IsSynthesizedAsyncCatchAll);
P
Pilchie 已提交
807 808 809 810 811 812
        }

        public override BoundNode VisitSequence(BoundSequence node)
        {
            LambdaFrame frame;
            // Test if this frame has captured variables and requires the introduction of a closure class.
813
            if (_frames.TryGetValue(node, out frame))
P
Pilchie 已提交
814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830
            {
                return IntroduceFrame(node, frame, (ArrayBuilder<BoundExpression> prologue, ArrayBuilder<LocalSymbol> newLocals) =>
                {
                    return RewriteSequence(node, prologue, newLocals);
                });
            }
            else
            {
                return RewriteSequence(node, ArrayBuilder<BoundExpression>.GetInstance(), ArrayBuilder<LocalSymbol>.GetInstance());
            }
        }

        public override BoundNode VisitStatementList(BoundStatementList node)
        {
            LambdaFrame frame;
            // Test if this frame has captured variables and requires the introduction of a closure class.
            // That can occur for a BoundStatementList if it is the body of a method with captured parameters.
831
            if (_frames.TryGetValue(node, out frame))
P
Pilchie 已提交
832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855
            {
                return IntroduceFrame(node, frame, (ArrayBuilder<BoundExpression> prologue, ArrayBuilder<LocalSymbol> newLocals) =>
                {
                    var newStatements = ArrayBuilder<BoundStatement>.GetInstance();
                    InsertAndFreePrologue(newStatements, prologue);

                    foreach (var s in node.Statements)
                    {
                        newStatements.Add((BoundStatement)this.Visit(s));
                    }

                    return new BoundBlock(node.Syntax, newLocals.ToImmutableAndFree(), newStatements.ToImmutableAndFree(), node.HasErrors);
                });
            }
            else
            {
                return base.VisitStatementList(node);
            }
        }

        public override BoundNode VisitSwitchStatement(BoundSwitchStatement node)
        {
            LambdaFrame frame;
            // Test if this frame has captured variables and requires the introduction of a closure class.
856
            if (_frames.TryGetValue(node, out frame))
P
Pilchie 已提交
857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891
            {
                return IntroduceFrame(node, frame, (ArrayBuilder<BoundExpression> prologue, ArrayBuilder<LocalSymbol> newLocals) =>
                {
                    var newStatements = ArrayBuilder<BoundStatement>.GetInstance();
                    InsertAndFreePrologue(newStatements, prologue);
                    newStatements.Add((BoundStatement)base.VisitSwitchStatement(node));

                    return new BoundBlock(node.Syntax, newLocals.ToImmutableAndFree(), newStatements.ToImmutableAndFree(), node.HasErrors);
                });
            }
            else
            {
                return base.VisitSwitchStatement(node);
            }
        }

        public override BoundNode VisitDelegateCreationExpression(BoundDelegateCreationExpression node)
        {
            // A delegate creation expression of the form "new Action( ()=>{} )" is treated exactly like
            // (Action)(()=>{})
            if (node.Argument.Kind == BoundKind.Lambda)
            {
                return RewriteLambdaConversion((BoundLambda)node.Argument);
            }
            else
            {
                return base.VisitDelegateCreationExpression(node);
            }
        }

        public override BoundNode VisitConversion(BoundConversion conversion)
        {
            if (conversion.ConversionKind == ConversionKind.AnonymousFunction)
            {
                var result = (BoundExpression)RewriteLambdaConversion((BoundLambda)conversion.Operand);
892
                return _inExpressionLambda && conversion.ExplicitCastInCode
893 894 895 896 897 898 899 900 901 902 903 904 905
                    ? new BoundConversion(
                        syntax: conversion.Syntax,
                        operand: result,
                        conversionKind: conversion.ConversionKind,
                        resultKind: conversion.ResultKind,
                        isBaseConversion: false,
                        symbolOpt: null,
                        @checked: false,
                        explicitCastInCode: true,
                        isExtensionMethod: false,
                        isArrayIndex: false,
                        constantValueOpt: conversion.ConstantValueOpt,
                        type: conversion.Type)
P
Pilchie 已提交
906 907 908 909 910 911 912 913
                    : result;
            }
            else
            {
                return base.VisitConversion(conversion);
            }
        }

914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937
        private void GetLambdaId(SyntaxNode syntax, ClosureKind closureKind, int closureOrdinal, out MethodDebugId topLevelMethodId, out int lambdaOrdinal)
        {
            Debug.Assert(syntax != null);

            SyntaxNode lambdaOrLambdaBodySyntax;
            var anonymousFunction = syntax as AnonymousFunctionExpressionSyntax;
            if (anonymousFunction != null)
            {
                lambdaOrLambdaBodySyntax = anonymousFunction.Body;
            }
            else if (SyntaxFacts.IsQueryPairLambda(syntax))
            {
                // "pair" query lambdas
                lambdaOrLambdaBodySyntax = syntax;
                Debug.Assert(closureKind == ClosureKind.Static);
            }
            else
            {
                // query lambdas
                Debug.Assert(SyntaxFacts.IsLambdaBody(syntax));
                lambdaOrLambdaBodySyntax = syntax;
            }

            // determine lambda ordinal and calculate syntax offset:
938 939 940
            lambdaOrdinal = _lambdaDebugInfoBuilder.Count;
            int syntaxOffset = _topLevelMethod.CalculateLocalSyntaxOffset(lambdaOrLambdaBodySyntax.SpanStart, lambdaOrLambdaBodySyntax.SyntaxTree);
            _lambdaDebugInfoBuilder.Add(new LambdaDebugInfo(syntaxOffset, closureOrdinal));
941 942

            int previousLambdaOrdinal;
943
            if (slotAllocatorOpt != null &&
944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962
                slotAllocatorOpt.TryGetPreviousLambda(
                    lambdaOrLambdaBodySyntax,
                    !SyntaxFacts.IsQueryPairLambda(lambdaOrLambdaBodySyntax),
                    out previousLambdaOrdinal))
            {
                topLevelMethodId = slotAllocatorOpt.PreviousMethodId;
                lambdaOrdinal = previousLambdaOrdinal;
            }
            else
            {
                // If we haven't found existing closure in the previous generation, use the current generation method ordinal.
                // That is, don't try to reuse previous generation method ordinal as that might create name conflict. 
                // E.g. 
                //     Gen0                    Gen1
                //                             F() { new lambda } // ordinal 0
                //     G() { } // ordinal 0    G() { new lambda } // ordinal 1
                //
                // In the example above G is updated and F is added. 
                // G's ordinal in Gen0 is 0. If we used that ordinal for updated G's new lambda it would conflict with F's ordinal.
963
                topLevelMethodId = new MethodDebugId(_topLevelMethodOrdinal, CompilationState.ModuleBuilderOpt.CurrentGenerationOrdinal);
964 965 966
            }
        }

P
Pilchie 已提交
967 968
        private BoundNode RewriteLambdaConversion(BoundLambda node)
        {
969 970
            var wasInExpressionLambda = _inExpressionLambda;
            _inExpressionLambda = _inExpressionLambda || node.Type.IsExpressionTree();
P
Pilchie 已提交
971

972
            if (_inExpressionLambda)
P
Pilchie 已提交
973 974 975 976
            {
                var newType = VisitType(node.Type);
                var newBody = (BoundBlock)Visit(node.Body);
                node = node.Update(node.Symbol, newBody, node.Diagnostics, node.Binder, newType);
977
                var result0 = wasInExpressionLambda ? node : ExpressionLambdaRewriter.RewriteLambda(node, CompilationState, TypeMap, Diagnostics);
978
                _inExpressionLambda = wasInExpressionLambda;
P
Pilchie 已提交
979 980 981 982 983
                return result0;
            }

            NamedTypeSymbol translatedLambdaContainer;
            BoundNode lambdaScope = null;
984
            LambdaFrame containerAsFrame;
985

986
            int closureOrdinal;
987
            ClosureKind closureKind;
988
            if (_analysis.lambdaScopes.TryGetValue(node.Symbol, out lambdaScope))
P
Pilchie 已提交
989
            {
990
                translatedLambdaContainer = containerAsFrame = _frames[lambdaScope];
991
                closureKind = ClosureKind.General;
992
                closureOrdinal = containerAsFrame.ClosureOrdinal;
P
Pilchie 已提交
993
            }
994
            else if (_analysis.capturedVariablesByLambda[node.Symbol].Count == 0)
995
            {
996
                translatedLambdaContainer = containerAsFrame = GetStaticFrame(Diagnostics, node);
997
                closureKind = ClosureKind.Static;
998
                closureOrdinal = LambdaDebugInfo.StaticClosureOrdinal;
999
            }
P
Pilchie 已提交
1000 1001
            else
            {
1002
                containerAsFrame = null;
1003
                translatedLambdaContainer = _topLevelMethod.ContainingType;
1004
                closureKind = ClosureKind.ThisOnly;
1005
                closureOrdinal = LambdaDebugInfo.ThisOnlyClosureOrdinal;
P
Pilchie 已提交
1006 1007 1008
            }

            // Move the body of the lambda to a freshly generated synthetic method on its frame.
1009 1010 1011 1012 1013
            MethodDebugId topLevelMethodId;
            int lambdaOrdinal;

            GetLambdaId(node.Syntax, closureKind, closureOrdinal, out topLevelMethodId, out lambdaOrdinal);

1014
            var synthesizedMethod = new SynthesizedLambdaMethod(translatedLambdaContainer, closureKind, _topLevelMethod, topLevelMethodId, node, lambdaOrdinal);
1015
            CompilationState.ModuleBuilderOpt.AddSynthesizedDefinition(translatedLambdaContainer, synthesizedMethod);
P
Pilchie 已提交
1016

1017
            foreach (var parameter in node.Symbol.Parameters)
P
Pilchie 已提交
1018
            {
1019
                _parameterMap.Add(parameter, synthesizedMethod.Parameters[parameter.Ordinal]);
P
Pilchie 已提交
1020 1021 1022
            }

            // rewrite the lambda body as the generated method's body
1023 1024 1025 1026 1027 1028 1029 1030 1031
            var oldMethod = _currentMethod;
            var oldFrameThis = _currentFrameThis;
            var oldTypeParameters = _currentTypeParameters;
            var oldInnermostFramePointer = _innermostFramePointer;
            var oldTypeMap = _currentLambdaBodyTypeMap;
            var oldAddedStatements = _addedStatements;
            var oldAddedLocals = _addedLocals;
            _addedStatements = null;
            _addedLocals = null;
P
Pilchie 已提交
1032 1033 1034

            // switch to the generated method

1035
            _currentMethod = synthesizedMethod;
1036
            if (closureKind == ClosureKind.Static)
P
Pilchie 已提交
1037 1038
            {
                // no link from a static lambda to its container
1039
                _innermostFramePointer = _currentFrameThis = null;
P
Pilchie 已提交
1040 1041 1042
            }
            else
            {
1043 1044 1045
                _currentFrameThis = synthesizedMethod.ThisParameter;
                _innermostFramePointer = null;
                _framePointers.TryGetValue(translatedLambdaContainer, out _innermostFramePointer);
P
Pilchie 已提交
1046 1047
            }

1048
            if ((object)containerAsFrame != null)
P
Pilchie 已提交
1049
            {
1050 1051
                _currentTypeParameters = translatedLambdaContainer.TypeParameters;
                _currentLambdaBodyTypeMap = ((LambdaFrame)translatedLambdaContainer).TypeMap;
P
Pilchie 已提交
1052 1053 1054
            }
            else
            {
1055 1056
                _currentTypeParameters = synthesizedMethod.TypeParameters;
                _currentLambdaBodyTypeMap = new TypeMap(_topLevelMethod.TypeParameters, _currentTypeParameters);
P
Pilchie 已提交
1057 1058 1059 1060
            }

            var body = AddStatementsIfNeeded((BoundStatement)VisitBlock(node.Body));
            CheckLocalsDefined(body);
T
TomasMatousek 已提交
1061
            CompilationState.AddSynthesizedMethod(synthesizedMethod, body);
P
Pilchie 已提交
1062 1063 1064

            // return to the old method

1065 1066 1067 1068 1069 1070 1071
            _currentMethod = oldMethod;
            _currentFrameThis = oldFrameThis;
            _currentTypeParameters = oldTypeParameters;
            _innermostFramePointer = oldInnermostFramePointer;
            _currentLambdaBodyTypeMap = oldTypeMap;
            _addedLocals = oldAddedLocals;
            _addedStatements = oldAddedStatements;
P
Pilchie 已提交
1072 1073

            // Rewrite the lambda expression (and the enclosing anonymous method conversion) as a delegate creation expression
1074
            NamedTypeSymbol constructedFrame = (object)containerAsFrame != null ?
1075
                translatedLambdaContainer.ConstructIfGeneric(StaticCast<TypeSymbol>.From(_currentTypeParameters)) :
1076
                translatedLambdaContainer;
1077 1078

            // for instance lambdas, receiver is the frame
1079 1080
            // for static lambdas, get the singleton receiver 
            BoundExpression receiver;
1081
            if (closureKind != ClosureKind.Static)
1082 1083 1084 1085 1086 1087 1088 1089
            {
                receiver = FrameOfType(node.Syntax, constructedFrame);
            }
            else
            {
                var field = containerAsFrame.SingletonCache.AsMember(constructedFrame);
                receiver = new BoundFieldAccess(node.Syntax, null, field, constantValueOpt: null);
            }
1090

T
TomasMatousek 已提交
1091
            MethodSymbol referencedMethod = synthesizedMethod.AsMember(constructedFrame);
1092 1093
            if (referencedMethod.IsGenericMethod)
            {
1094
                referencedMethod = referencedMethod.Construct(StaticCast<TypeSymbol>.From(_currentTypeParameters));
1095 1096
            }

P
Pilchie 已提交
1097
            TypeSymbol type = this.VisitType(node.Type);
1098

1099 1100 1101 1102
            // static lambdas are emitted as instance methods on a singleton receiver
            // delegates invoke dispatch is optimized for instance delegates so 
            // it is preferrable to emit lambdas as instance methods even when lambdas 
            // do not capture anything
P
Pilchie 已提交
1103 1104 1105 1106
            BoundExpression result = new BoundDelegateCreationExpression(
                node.Syntax,
                receiver,
                referencedMethod,
1107
                isExtensionMethod: false,
P
Pilchie 已提交
1108 1109 1110 1111 1112
                type: type);

            // if the block containing the lambda is not the innermost block,
            // or the lambda is static, then the lambda object should be cached in its frame.
            // NOTE: we are not caching static lambdas in static ctors - cannot reuse such cache.
1113
            var shouldCacheForStaticMethod = closureKind == ClosureKind.Static &&
1114
                _currentMethod.MethodKind != MethodKind.StaticConstructor &&
P
Pilchie 已提交
1115 1116 1117 1118 1119
                !referencedMethod.IsGenericMethod;

            // NOTE: We require "lambdaScope != null". 
            //       We do not want to introduce a field into an actual user's class (not a synthetic frame).
            var shouldCacheInLoop = lambdaScope != null &&
1120
                lambdaScope != _analysis.scopeParent[node.Body] &&
P
Pilchie 已提交
1121 1122 1123 1124
                InLoopOrLambda(node.Syntax, lambdaScope.Syntax);

            if (shouldCacheForStaticMethod || shouldCacheInLoop)
            {
1125
                // replace the expression "new Delegate(frame.M)" with "frame.cache ?? (frame.cache = new Delegate(frame.M));
1126
                var F = new SyntheticBoundNodeFactory(_currentMethod, node.Syntax, CompilationState, Diagnostics);
P
Pilchie 已提交
1127 1128
                try
                {
T
TomasMatousek 已提交
1129
                    BoundExpression cache;
1130
                    if (shouldCacheForStaticMethod || shouldCacheInLoop && (object)containerAsFrame != null)
P
Pilchie 已提交
1131
                    {
1132
                        var cacheVariableType = containerAsFrame?.TypeMap.SubstituteType(type) ?? translatedLambdaContainer;
1133

1134 1135
                        // If we are generating the field into a display class created exclusively for the lambda the lambdaOrdinal itself is unique already, 
                        // no need to include the top-level method ordinal in the field name.
1136

1137
                        var cacheVariableName = GeneratedNames.MakeLambdaCacheFieldName(
1138 1139
                            (closureKind == ClosureKind.General) ? -1 : topLevelMethodId.Ordinal,
                            topLevelMethodId.Generation,
1140
                            lambdaOrdinal);
1141

1142
                        var cacheField = new SynthesizedLambdaCacheFieldSymbol(translatedLambdaContainer, cacheVariableType, cacheVariableName, _topLevelMethod, isReadOnly: false, isStatic: closureKind == ClosureKind.Static);
T
TomasMatousek 已提交
1143
                        CompilationState.ModuleBuilderOpt.AddSynthesizedDefinition(translatedLambdaContainer, cacheField);
T
TomasMatousek 已提交
1144
                        cache = F.Field(receiver, cacheField.AsMember(constructedFrame)); //NOTE: the field was added to the unconstructed frame type.
P
Pilchie 已提交
1145 1146 1147 1148
                    }
                    else
                    {
                        // the lambda captures at most the "this" of the enclosing method.  We cache its delegate in a local variable.
1149
                        var cacheLocal = F.SynthesizedLocal(type, kind: SynthesizedLocalKind.CachedAnonymousMethodDelegate);
1150 1151 1152
                        if (_addedLocals == null) _addedLocals = ArrayBuilder<LocalSymbol>.GetInstance();
                        _addedLocals.Add(cacheLocal);
                        if (_addedStatements == null) _addedStatements = ArrayBuilder<BoundStatement>.GetInstance();
T
TomasMatousek 已提交
1153
                        cache = F.Local(cacheLocal);
1154
                        _addedStatements.Add(F.Assignment(cache, F.Null(type)));
P
Pilchie 已提交
1155 1156
                    }

T
TomasMatousek 已提交
1157
                    result = F.Coalesce(cache, F.AssignmentExpression(cache, result));
P
Pilchie 已提交
1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200
                }
                catch (SyntheticBoundNodeFactory.MissingPredefinedMember ex)
                {
                    Diagnostics.Add(ex.Diagnostic);
                    return new BoundBadExpression(F.Syntax, LookupResultKind.Empty, ImmutableArray<Symbol>.Empty, ImmutableArray.Create<BoundNode>(node), node.Type);
                }
            }

            return result;
        }

        // This helper checks syntactically whether there is a loop or lambda expression
        // between given lambda syntax and the syntax that corresponds to its closure.
        // we use this heuristic as a hint that the lambda delegate may be created 
        // multiple times with same closure.
        // In such cases it makes sense to cache the delegate.
        //
        // Examples:
        //            int x = 123;
        //            for (int i = 1; i< 10; i++)
        //            {
        //                if (i< 2)
        //                {
        //                    arr[i].Execute(arg => arg + x);  // delegate should be cached
        //                }
        //            }

        //            for (int i = 1; i< 10; i++)
        //            {
        //                var val = i;
        //                if (i< 2)
        //                {
        //                    int y = i + i;
        //                    System.Console.WriteLine(y);
        //                    arr[i].Execute(arg => arg + val);  // delegate should NOT be cached (closure created inside the loop)
        //                }
        //            }
        //
        private static bool InLoopOrLambda(SyntaxNode lambdaSyntax, SyntaxNode scopeSyntax)
        {
            var curSyntax = lambdaSyntax.Parent;
            while (curSyntax != null && curSyntax != scopeSyntax)
            {
1201
                switch (curSyntax.Kind())
P
Pilchie 已提交
1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314
                {
                    case SyntaxKind.ForStatement:
                    case SyntaxKind.ForEachStatement:
                    case SyntaxKind.WhileStatement:
                    case SyntaxKind.DoStatement:
                    case SyntaxKind.SimpleLambdaExpression:
                    case SyntaxKind.ParenthesizedLambdaExpression:
                        return true;
                }

                curSyntax = curSyntax.Parent;
            }

            return false;
        }

        public override BoundNode VisitLambda(BoundLambda node)
        {
            // these nodes have been handled in the context of the enclosing anonymous method conversion.
            throw ExceptionUtilities.Unreachable;
        }

        #endregion

#if CHECK_LOCALS
        /// <summary>
        /// Ensure that local variables are always in scope where used in bound trees
        /// </summary>
        /// <param name="node"></param>
        static partial void CheckLocalsDefined(BoundNode node)
        {
            LocalsDefinedScanner.INSTANCE.Visit(node);
        }

        class LocalsDefinedScanner : BoundTreeWalker
        {
            internal static LocalsDefinedScanner INSTANCE = new LocalsDefinedScanner();

            HashSet<Symbol> localsDefined = new HashSet<Symbol>();

            public override BoundNode VisitLocal(BoundLocal node)
            {
                Debug.Assert(node.LocalSymbol.IsConst || localsDefined.Contains(node.LocalSymbol));
                return base.VisitLocal(node);
            }

            public override BoundNode VisitSequence(BoundSequence node)
            {
                try
                {
                    if (!node.Locals.IsNullOrEmpty)
                        foreach (var l in node.Locals)
                            localsDefined.Add(l);
                    return base.VisitSequence(node);
                }
                finally
                {
                    if (!node.Locals.IsNullOrEmpty)
                        foreach (var l in node.Locals)
                            localsDefined.Remove(l);
                }
            }

            public override BoundNode VisitCatchBlock(BoundCatchBlock node)
            {
                try
                {
                    if ((object)node.LocalOpt != null) localsDefined.Add(node.LocalOpt);
                    return base.VisitCatchBlock(node);
                }
                finally
                {
                    if ((object)node.LocalOpt != null) localsDefined.Remove(node.LocalOpt);
                }
            }

            public override BoundNode VisitSwitchStatement(BoundSwitchStatement node)
            {
                try
                {
                    if (!node.LocalsOpt.IsNullOrEmpty)
                        foreach (var l in node.LocalsOpt)
                            localsDefined.Add(l);
                    return base.VisitSwitchStatement(node);
                }
                finally
                {
                    if (!node.LocalsOpt.IsNullOrEmpty)
                        foreach (var l in node.LocalsOpt)
                            localsDefined.Remove(l);
                }
            }

            public override BoundNode VisitBlock(BoundBlock node)
            {
                try
                {
                    if (!node.LocalsOpt.IsNullOrEmpty)
                        foreach (var l in node.LocalsOpt)
                            localsDefined.Add(l);
                    return base.VisitBlock(node);
                }
                finally
                {
                    if (!node.LocalsOpt.IsNullOrEmpty)
                        foreach (var l in node.LocalsOpt)
                            localsDefined.Remove(l);
                }
            }
        }
#endif
    }
}