LambdaRewriter.cs 75.6 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
using Roslyn.Utilities;
15 16
using System.Linq;
using Microsoft.CodeAnalysis.Collections;
P
Pilchie 已提交
17 18 19 20 21 22 23 24

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 已提交
25
    /// The entry point is the public method <see cref="Rewrite"/>.  It operates as follows:
P
Pilchie 已提交
26 27 28
    /// 
    /// 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
29
    /// have captured variables.  The result of this analysis is left in <see cref="_analysis"/>.
P
Pilchie 已提交
30 31
    /// 
    /// Then we make a frame, or compiler-generated class, represented by an instance of
T
TomasMatousek 已提交
32
    /// <see cref="LambdaFrame"/> for each scope with captured variables.  The generated frames are kept
33
    /// in <see cref="_frames"/>.  Each frame is given a single field for each captured
34
    /// variable in the corresponding scope.  These are maintained in <see cref="MethodToClassRewriter.proxies"/>.
P
Pilchie 已提交
35
    /// 
36
    /// Next, we walk and rewrite the input bound tree, keeping track of the following:
37 38 39
    /// (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 已提交
40
    /// (4) The symbol that is used to access the innermost frame pointer (it could be a local variable or "this" parameter)
41 42 43 44 45 46 47
    ///
    /// Lastly, we visit the top-level method and each of the lowered methods
    /// to rewrite references (e.g., calls and delegate conversions) to local
    /// functions. We visit references to local functions separately from
    /// lambdas because we may see the reference before we lower the target
    /// local function. Lambdas, on the other hand, are always convertible as
    /// they are being lowered.
P
Pilchie 已提交
48 49 50 51 52 53 54
    /// 
    /// 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.
    /// 
55 56
    /// In addition, the rewriting deposits into <see cref="TypeCompilationState.SynthesizedMethods"/>
    /// a (<see cref="MethodSymbol"/>, <see cref="BoundStatement"/>) pair for each generated method.
P
Pilchie 已提交
57
    /// 
T
TomasMatousek 已提交
58
    /// <see cref="Rewrite"/> produces its output in two forms.  First, it returns a new bound statement
P
Pilchie 已提交
59
    /// for the caller to use for the body of the original method.  Second, it returns a collection of
T
TomasMatousek 已提交
60
    /// (<see cref="MethodSymbol"/>, <see cref="BoundStatement"/>) pairs for additional methods that the lambda rewriter produced.
P
Pilchie 已提交
61 62 63 64 65
    /// 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>
66
    internal sealed partial class LambdaRewriter : MethodToClassRewriter
P
Pilchie 已提交
67
    {
68 69
        private readonly Analysis _analysis;
        private readonly MethodSymbol _topLevelMethod;
70
        private readonly MethodSymbol _substitutedSourceMethod;
71
        private readonly int _topLevelMethodOrdinal;
P
Pilchie 已提交
72

73 74
        // lambda frame for static lambdas. 
        // initialized lazily and could be null if there are no static lambdas
75
        private LambdaFrame _lazyStaticLambdaFrame;
76

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

80
        // A mapping from every local function to its lowered method
E
Evan Hauck 已提交
81 82
        private struct MappedLocalFunction
        {
83
            public readonly SynthesizedLambdaMethod Symbol;
E
Evan Hauck 已提交
84
            public readonly ClosureKind ClosureKind;
85
            public MappedLocalFunction(SynthesizedLambdaMethod symbol, ClosureKind closureKind)
E
Evan Hauck 已提交
86 87 88 89 90
            {
                Symbol = symbol;
                ClosureKind = closureKind;
            }
        }
91

E
Evan Hauck 已提交
92
        private readonly Dictionary<LocalFunctionSymbol, MappedLocalFunction> _localFunctionMap = new Dictionary<LocalFunctionSymbol, MappedLocalFunction>();
E
Evan Hauck 已提交
93

P
Pilchie 已提交
94
        // for each block with lifted (captured) variables, the corresponding frame type
95
        private readonly Dictionary<BoundNode, LambdaFrame> _frames = new Dictionary<BoundNode, LambdaFrame>();
P
Pilchie 已提交
96 97 98

        // 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.
99
        private readonly Dictionary<NamedTypeSymbol, Symbol> _framePointers = new Dictionary<NamedTypeSymbol, Symbol>();
P
Pilchie 已提交
100

101 102 103
        // 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.
104
        private readonly bool _assignLocals;
105

P
Pilchie 已提交
106
        // The current method or lambda being processed.
107
        private MethodSymbol _currentMethod;
P
Pilchie 已提交
108 109

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

112
        private readonly ArrayBuilder<LambdaDebugInfo> _lambdaDebugInfoBuilder;
113

114
        // ID dispenser for field names of frame references
115
        private int _synthesizedFieldNameIdDispenser;
116

P
Pilchie 已提交
117
        // The symbol (field or local) holding the innermost frame
118
        private Symbol _innermostFramePointer;
P
Pilchie 已提交
119 120

        // The mapping of type parameters for the current lambda body
121
        private TypeMap _currentLambdaBodyTypeMap;
P
Pilchie 已提交
122 123

        // The current set of type parameters (mapped from the enclosing method's type parameters)
124
        private ImmutableArray<TypeParameterSymbol> _currentTypeParameters;
P
Pilchie 已提交
125 126 127

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

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

        // Set to true while translating code inside of an expression lambda.
134
        private bool _inExpressionLambda;
P
Pilchie 已提交
135 136 137 138

        // 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.
139
        private ArrayBuilder<LocalSymbol> _addedLocals;
P
Pilchie 已提交
140 141 142

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

145 146 147 148 149 150
        /// <summary>
        /// Temporary bag for methods synthesized by the rewriting. Added to
        /// <see cref="TypeCompilationState.SynthesizedMethods"/> at the end of rewriting.
        /// </summary>
        private ArrayBuilder<TypeCompilationState.MethodWithBody> _synthesizedMethods;

P
Pilchie 已提交
151 152 153
        private LambdaRewriter(
            Analysis analysis,
            NamedTypeSymbol thisType,
T
TomasMatousek 已提交
154
            ParameterSymbol thisParameterOpt,
P
Pilchie 已提交
155
            MethodSymbol method,
156
            int methodOrdinal,
157
            MethodSymbol substitutedSourceMethod,
158
            ArrayBuilder<LambdaDebugInfo> lambdaDebugInfoBuilder,
159
            VariableSlotAllocator slotAllocatorOpt,
P
Pilchie 已提交
160 161
            TypeCompilationState compilationState,
            DiagnosticBag diagnostics,
162
            bool assignLocals)
163
            : base(slotAllocatorOpt, compilationState, diagnostics)
P
Pilchie 已提交
164
        {
T
TomasMatousek 已提交
165 166 167 168 169 170
            Debug.Assert(analysis != null);
            Debug.Assert(thisType != null);
            Debug.Assert(method != null);
            Debug.Assert(compilationState != null);
            Debug.Assert(diagnostics != null);

171
            _topLevelMethod = method;
172
            _substitutedSourceMethod = substitutedSourceMethod;
173 174 175 176 177 178 179 180 181 182 183
            _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 已提交
184 185
        }

186 187
        protected override bool NeedsProxy(Symbol localOrParameter)
        {
E
Evan Hauck 已提交
188 189
            Debug.Assert(localOrParameter is LocalSymbol || localOrParameter is ParameterSymbol ||
                (localOrParameter as MethodSymbol)?.MethodKind == MethodKind.LocalFunction);
E
Evan Hauck 已提交
190
            return _analysis.CapturedVariables.ContainsKey(localOrParameter);
191 192
        }

P
Pilchie 已提交
193 194 195 196 197 198
        /// <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>
199
        /// <param name="loweredBody">The bound node to be rewritten</param>
P
Pilchie 已提交
200 201 202
        /// <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>
203
        /// <param name="methodOrdinal">Index of the method symbol in its containing type member list.</param>
204
        /// <param name="substitutedSourceMethod">If this is non-null, then <paramref name="method"/> will be treated as this for uses of parent symbols. For use in EE.</param>
205 206
        /// <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>
207
        /// <param name="slotAllocatorOpt">Slot allocator.</param>
P
Pilchie 已提交
208 209
        /// <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>
210
        /// <param name="assignLocals">The rewritten tree should include assignments of the original locals to the lifted proxies</param>
P
Pilchie 已提交
211
        public static BoundStatement Rewrite(
212
            BoundStatement loweredBody,
P
Pilchie 已提交
213 214 215
            NamedTypeSymbol thisType,
            ParameterSymbol thisParameter,
            MethodSymbol method,
216
            int methodOrdinal,
217
            MethodSymbol substitutedSourceMethod,
218 219
            ArrayBuilder<LambdaDebugInfo> lambdaDebugInfoBuilder,
            ArrayBuilder<ClosureDebugInfo> closureDebugInfoBuilder,
220
            VariableSlotAllocator slotAllocatorOpt,
P
Pilchie 已提交
221 222
            TypeCompilationState compilationState,
            DiagnosticBag diagnostics,
223
            bool assignLocals)
P
Pilchie 已提交
224 225 226
        {
            Debug.Assert((object)thisType != null);
            Debug.Assert(((object)thisParameter == null) || (thisParameter.Type == thisType));
227 228 229 230 231 232 233 234 235
            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;
236
                //   var b = false && (from z in new X(y) select f(z + y))
237 238
                return loweredBody;
            }
P
Pilchie 已提交
239

240
            CheckLocalsDefined(loweredBody);
241 242 243 244 245
            var rewriter = new LambdaRewriter(
                analysis,
                thisType,
                thisParameter,
                method,
246
                methodOrdinal,
247
                substitutedSourceMethod,
248
                lambdaDebugInfoBuilder,
249
                slotAllocatorOpt,
250 251
                compilationState,
                diagnostics,
252
                assignLocals);
253

P
Pilchie 已提交
254
            analysis.ComputeLambdaScopesAndFrameCaptures();
255
            rewriter.MakeFrames(closureDebugInfoBuilder);
256 257 258 259 260 261 262 263 264 265 266 267

            // First, lower everything but references (calls, delegate conversions)
            // to local functions
            var body = rewriter.AddStatementsIfNeeded(
                (BoundStatement)rewriter.Visit(loweredBody));

            // Now lower the references
            if (rewriter._localFunctionMap.Count != 0)
            {
                body = rewriter.RewriteLocalFunctionReferences(body);
            }

268 269 270 271 272 273 274 275 276 277 278 279 280 281
            // Add the completed methods to the compilation state
            if (rewriter._synthesizedMethods != null)
            {
                if (compilationState.SynthesizedMethods == null)
                {
                    compilationState.SynthesizedMethods = rewriter._synthesizedMethods;
                }
                else
                {
                    compilationState.SynthesizedMethods.AddRange(rewriter._synthesizedMethods);
                    rewriter._synthesizedMethods.Free();
                }
            }

P
Pilchie 已提交
282
            CheckLocalsDefined(body);
283

P
Pilchie 已提交
284 285 286
            return body;
        }

287
        private BoundStatement AddStatementsIfNeeded(BoundStatement body)
P
Pilchie 已提交
288
        {
289
            if (_addedLocals != null)
P
Pilchie 已提交
290
            {
291
                _addedStatements.Add(body);
292
                body = new BoundBlock(body.Syntax, _addedLocals.ToImmutableAndFree(), _addedStatements.ToImmutableAndFree()) { WasCompilerGenerated = true };
293 294
                _addedLocals = null;
                _addedStatements = null;
P
Pilchie 已提交
295 296 297
            }
            else
            {
298
                Debug.Assert(_addedStatements == null);
P
Pilchie 已提交
299 300 301 302 303 304 305
            }

            return body;
        }

        protected override TypeMap TypeMap
        {
306
            get { return _currentLambdaBodyTypeMap; }
P
Pilchie 已提交
307 308 309 310
        }

        protected override MethodSymbol CurrentMethod
        {
311
            get { return _currentMethod; }
P
Pilchie 已提交
312 313 314 315
        }

        protected override NamedTypeSymbol ContainingType
        {
316
            get { return _topLevelMethod.ContainingType; }
P
Pilchie 已提交
317 318 319 320 321 322 323 324 325 326 327
        }

        /// <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>
328
        private void MakeFrames(ArrayBuilder<ClosureDebugInfo> closureDebugInfo)
P
Pilchie 已提交
329
        {
330
            var closures = _analysis.CapturedVariablesByLambda.Keys;
P
Pilchie 已提交
331

332
            foreach (var closure in closures)
P
Pilchie 已提交
333
            {
334
                var capturedVars = _analysis.CapturedVariablesByLambda[closure];
P
pgavlin 已提交
335

336 337
                if (closure.MethodKind == MethodKind.LocalFunction &&
                    OnlyCapturesThis((LocalFunctionSymbol)closure, capturedVars))
P
Pilchie 已提交
338 339 340 341
                {
                    continue;
                }

342
                foreach (var captured in capturedVars)
P
Pilchie 已提交
343
                {
344 345 346 347 348 349 350
                    BoundNode scope;
                    if (!_analysis.VariableScope.TryGetValue(captured, out scope))
                    {
                        continue;
                    }

                    LambdaFrame frame = GetFrameForScope(scope, closureDebugInfo);
E
Evan Hauck 已提交
351

352
                    if (captured.Kind != SymbolKind.Method && !proxies.ContainsKey(captured))
P
Pilchie 已提交
353
                    {
354 355 356 357 358
                        var hoistedField = LambdaCapturedVariable.Create(frame, captured, ref _synthesizedFieldNameIdDispenser);
                        proxies.Add(captured, new CapturedToFrameSymbolReplacement(hoistedField, isReusable: false));
                        CompilationState.ModuleBuilderOpt.AddSynthesizedDefinition(frame, hoistedField);

                        if (hoistedField.Type.IsRestrictedType())
359
                        {
360 361 362 363 364
                            foreach (CSharpSyntaxNode syntax in _analysis.CapturedVariables[captured])
                            {
                                // CS4013: Instance of type '{0}' cannot be used inside an anonymous function, query expression, iterator block or async method
                                this.Diagnostics.Add(ErrorCode.ERR_SpecialByRefInLambda, syntax.Location, hoistedField.Type);
                            }
365
                        }
P
Pilchie 已提交
366 367 368 369 370
                    }
                }
            }
        }

371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 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 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443

        private SmallDictionary<LocalFunctionSymbol, bool> _onlyCapturesThisMemoTable;
        /// <summary>
        /// Helper for determining whether a local function transitively
        /// only captures this (only captures this or other local functions
        /// which only capture this).
        /// </summary>
        private bool OnlyCapturesThis<T>(
            LocalFunctionSymbol closure,
            T capturedVars, 
            PooledHashSet<LocalFunctionSymbol> localFuncsInProgress = null)
            where T : IEnumerable<Symbol>
        {
            bool result = false;
            if (_onlyCapturesThisMemoTable?.TryGetValue(closure, out result) == true)
            {
                return result;
            }

            result = true;
            foreach (var captured in capturedVars)
            {
                var param = captured as ParameterSymbol;
                if (param != null && param.IsThis)
                {
                    continue;
                }

                var localFunc = captured as LocalFunctionSymbol;
                if (localFunc != null)
                {
                    bool freePool = false;
                    if (localFuncsInProgress == null)
                    {
                        localFuncsInProgress = PooledHashSet<LocalFunctionSymbol>.GetInstance();
                        freePool = true;
                    }
                    else if (localFuncsInProgress.Contains(localFunc))
                    {
                        continue;
                    }

                    localFuncsInProgress.Add(localFunc);
                    bool transitivelyTrue = OnlyCapturesThis(
                          localFunc,
                          _analysis.CapturedVariablesByLambda[localFunc],
                          localFuncsInProgress);

                    if (freePool)
                    {
                        localFuncsInProgress.Free();
                        localFuncsInProgress = null;
                    }

                    if (transitivelyTrue)
                    {
                        continue;
                    }
                }

                result = false;
                break;
            }

            if (_onlyCapturesThisMemoTable == null)
            {
                _onlyCapturesThisMemoTable = new SmallDictionary<LocalFunctionSymbol, bool>();
            }

            _onlyCapturesThisMemoTable[closure] = result;
            return result;
        }

444
        private LambdaFrame GetFrameForScope(BoundNode scope, ArrayBuilder<ClosureDebugInfo> closureDebugInfo)
445 446
        {
            LambdaFrame frame;
447
            if (!_frames.TryGetValue(scope, out frame))
448
            {
449 450 451
                var syntax = scope.Syntax;
                Debug.Assert(syntax != null);

452 453
                DebugId methodId = GetTopLevelMethodId();
                DebugId closureId = GetClosureId(syntax, closureDebugInfo);
454

E
Evan Hauck 已提交
455
                var canBeStruct = !_analysis.ScopesThatCantBeStructs.Contains(scope);
456

E
Evan Hauck 已提交
457
                var containingMethod = _analysis.ScopeOwner[scope];
458 459 460 461
                if (_substitutedSourceMethod != null && containingMethod == _topLevelMethod)
                {
                    containingMethod = _substitutedSourceMethod;
                }
E
Evan Hauck 已提交
462
                frame = new LambdaFrame(_topLevelMethod, containingMethod, canBeStruct, syntax, methodId, closureId);
463
                _frames.Add(scope, frame);
464

465
                CompilationState.ModuleBuilderOpt.AddSynthesizedDefinition(this.ContainingType, frame);
466 467
                if (frame.Constructor != null)
                {
468 469 470 471 472 473
                    AddSynthesizedMethod(
                        frame.Constructor,
                        FlowAnalysisPass.AppendImplicitReturn(
                            MethodCompiler.BindMethodBody(frame.Constructor, CompilationState, null),
                            frame.Constructor));
                }
474 475 476 477 478
            }

            return frame;
        }

E
Evan Hauck 已提交
479
        private LambdaFrame GetStaticFrame(DiagnosticBag diagnostics, IBoundLambdaOrFunction lambda)
480
        {
481
            if (_lazyStaticLambdaFrame == null)
482
            {
483
                var isNonGeneric = !_topLevelMethod.IsGenericMethod;
484 485
                if (isNonGeneric)
                {
486
                    _lazyStaticLambdaFrame = CompilationState.StaticLambdaFrame;
487 488
                }

489
                if (_lazyStaticLambdaFrame == null)
490
                {
491
                    DebugId methodId;
492 493
                    if (isNonGeneric)
                    {
494
                        methodId = new DebugId(DebugId.UndefinedOrdinal, CompilationState.ModuleBuilderOpt.CurrentGenerationOrdinal);
495 496 497
                    }
                    else
                    {
498
                        methodId = GetTopLevelMethodId();
499
                    }
500

E
Evan Hauck 已提交
501
                    DebugId closureId = default(DebugId);
E
Evan Hauck 已提交
502
                    // using _topLevelMethod as containing member because the static frame does not have generic parameters, except for the top level method's
503
                    var containingMethod = isNonGeneric ? null : (_substitutedSourceMethod ?? _topLevelMethod);
E
Evan Hauck 已提交
504
                    _lazyStaticLambdaFrame = new LambdaFrame(_topLevelMethod, containingMethod, isStruct: false, scopeSyntaxOpt: null, methodId: methodId, closureId: closureId);
505

506
                    // non-generic static lambdas can share the frame
507
                    if (isNonGeneric)
508
                    {
509
                        CompilationState.StaticLambdaFrame = _lazyStaticLambdaFrame;
510 511
                    }

512
                    var frame = _lazyStaticLambdaFrame;
513 514 515 516

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

517
                    // add its ctor (note Constructor can be null if TypeKind.Struct is passed in to LambdaFrame.ctor, but Class is passed in above)
518
                    AddSynthesizedMethod(
519
                        frame.Constructor,
520 521 522
                        FlowAnalysisPass.AppendImplicitReturn(
                            MethodCompiler.BindMethodBody(frame.Constructor, CompilationState, null),
                            frame.Constructor));
523

524
                    // associate the frame with the first lambda that caused it to exist. 
C
Charles Stoner 已提交
525
                    // we need to associate this with some syntax.
526 527
                    // unfortunately either containing method or containing class could be synthetic
                    // therefore could have no syntax.
528
                    SyntaxNode syntax = lambda.Syntax;
529 530 531 532 533 534 535 536

                    // 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)),
537
                            new BoundReturnStatement(syntax, RefKind.None, null));
538

539
                    AddSynthesizedMethod(frame.StaticConstructor, body);
540 541 542
                }
            }

543
            return _lazyStaticLambdaFrame;
544 545
        }

P
Pilchie 已提交
546 547 548 549 550 551
        /// <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>
552
        private BoundExpression FrameOfType(SyntaxNode syntax, NamedTypeSymbol frameType)
P
Pilchie 已提交
553 554 555 556 557 558 559 560 561 562 563 564 565 566
        {
            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>
567
        protected override BoundExpression FramePointer(SyntaxNode syntax, NamedTypeSymbol frameClass)
P
Pilchie 已提交
568 569 570 571
        {
            Debug.Assert(frameClass.IsDefinition);

            // If in an instance method of the right type, we can just return the "this" pointer.
572
            if ((object)_currentFrameThis != null && _currentFrameThis.Type == frameClass)
P
Pilchie 已提交
573 574 575 576
            {
                return new BoundThisReference(syntax, frameClass);
            }

577 578 579 580 581 582 583 584 585 586 587 588 589 590 591
            // If the current method has by-ref struct closure parameters, and one of them is correct, use it.
            var lambda = _currentMethod as SynthesizedLambdaMethod;
            if (lambda != null)
            {
                var start = lambda.ParameterCount - lambda.ExtraSynthesizedParameterCount;
                for (var i = start; i < lambda.ParameterCount; i++)
                {
                    var potentialParameter = lambda.Parameters[i];
                    if (potentialParameter.Type.OriginalDefinition == frameClass)
                    {
                        return new BoundParameter(syntax, potentialParameter);
                    }
                }
            }

P
Pilchie 已提交
592
            // Otherwise we need to return the value from a frame pointer local variable...
593
            Symbol framePointer = _framePointers[frameClass];
P
Pilchie 已提交
594 595 596 597 598 599 600 601 602
            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));
            }

603
            var localFrame = (LocalSymbol)framePointer;
P
Pilchie 已提交
604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623
            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>
624
        private BoundNode IntroduceFrame(BoundNode node, LambdaFrame frame, Func<ArrayBuilder<BoundExpression>, ArrayBuilder<LocalSymbol>, BoundNode> F)
P
Pilchie 已提交
625
        {
N
Neal Gafter 已提交
626
            var frameTypeParameters = ImmutableArray.Create(StaticCast<TypeSymbol>.From(_currentTypeParameters).SelectAsArray(TypeMap.TypeSymbolAsTypeWithModifiers), 0, frame.Arity);
E
Evan Hauck 已提交
627
            NamedTypeSymbol frameType = frame.ConstructIfGeneric(frameTypeParameters);
628 629

            Debug.Assert(frame.ScopeSyntaxOpt != null);
630
            LocalSymbol framePointer = new SynthesizedLocal(_topLevelMethod, frameType, SynthesizedLocalKind.LambdaDisplayClass, frame.ScopeSyntaxOpt);
P
Pilchie 已提交
631

632
            SyntaxNode syntax = node.Syntax;
P
Pilchie 已提交
633 634 635 636 637

            // assign new frame to the frame variable

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

638 639 640 641 642 643 644 645
            BoundExpression newFrame;
            if (frame.Constructor == null)
            {
                Debug.Assert(frame.TypeKind == TypeKind.Struct);
                newFrame = new BoundDefaultOperator(syntax: syntax, type: frameType);
            }
            else
            {
646 647
                MethodSymbol constructor = frame.Constructor.AsMember(frameType);
                Debug.Assert(frameType == constructor.ContainingType);
648
                newFrame = new BoundObjectCreationExpression(
P
Pilchie 已提交
649 650
                syntax: syntax,
                constructor: constructor);
651
            }
P
Pilchie 已提交
652 653 654 655 656 657 658

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

            CapturedSymbolReplacement oldInnermostFrameProxy = null;
659
            if ((object)_innermostFramePointer != null)
P
Pilchie 已提交
660
            {
661
                proxies.TryGetValue(_innermostFramePointer, out oldInnermostFrameProxy);
E
Evan Hauck 已提交
662
                if (_analysis.NeedsParentFrame.Contains(node))
P
Pilchie 已提交
663
                {
664
                    var capturedFrame = LambdaCapturedVariable.Create(frame, _innermostFramePointer, ref _synthesizedFieldNameIdDispenser);
P
Pilchie 已提交
665 666 667 668 669
                    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);

670
                    if (_currentMethod.MethodKind == MethodKind.Constructor && capturedFrame.Type == _currentMethod.ContainingType && !_seenBaseCall)
P
Pilchie 已提交
671 672 673 674 675
                    {
                        // 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
676 677
                        Debug.Assert(_thisProxyInitDeferred == null);
                        _thisProxyInitDeferred = assignment;
P
Pilchie 已提交
678 679 680 681 682 683 684 685
                    }
                    else
                    {
                        prologue.Add(assignment);
                    }

                    if (CompilationState.Emitting)
                    {
E
Evan Hauck 已提交
686
                        Debug.Assert(capturedFrame.Type.IsReferenceType); // Make sure we're not accidentally capturing a struct by value
T
TomasMatousek 已提交
687
                        CompilationState.ModuleBuilderOpt.AddSynthesizedDefinition(frame, capturedFrame);
P
Pilchie 已提交
688 689
                    }

690
                    proxies[_innermostFramePointer] = new CapturedToFrameSymbolReplacement(capturedFrame, isReusable: false);
P
Pilchie 已提交
691 692 693 694
                }
            }

            // Capture any parameters of this block.  This would typically occur
695
            // at the top level of a method or lambda with captured parameters.
P
Pilchie 已提交
696
            // TODO: speed up the following by computing it in analysis.
E
Evan Hauck 已提交
697
            foreach (var variable in _analysis.CapturedVariables.Keys)
P
Pilchie 已提交
698 699
            {
                BoundNode varNode;
E
Evan Hauck 已提交
700
                if (!_analysis.VariableScope.TryGetValue(variable, out varNode) || varNode != node)
P
Pilchie 已提交
701 702 703 704
                {
                    continue;
                }

705
                InitVariableProxy(syntax, variable, framePointer, prologue);
P
Pilchie 已提交
706 707
            }

708 709
            Symbol oldInnermostFramePointer = _innermostFramePointer;
            _innermostFramePointer = framePointer;
P
Pilchie 已提交
710 711
            var addedLocals = ArrayBuilder<LocalSymbol>.GetInstance();
            addedLocals.Add(framePointer);
712
            _framePointers.Add(frame, framePointer);
P
Pilchie 已提交
713 714 715

            var result = F(prologue, addedLocals);

716
            _innermostFramePointer = oldInnermostFramePointer;
P
Pilchie 已提交
717

718
            if ((object)_innermostFramePointer != null)
P
Pilchie 已提交
719 720 721
            {
                if (oldInnermostFrameProxy != null)
                {
722
                    proxies[_innermostFramePointer] = oldInnermostFrameProxy;
P
Pilchie 已提交
723 724 725
                }
                else
                {
726
                    proxies.Remove(_innermostFramePointer);
P
Pilchie 已提交
727 728 729 730 731 732
                }
            }

            return result;
        }

733
        private void InitVariableProxy(SyntaxNode syntax, Symbol symbol, LocalSymbol framePointer, ArrayBuilder<BoundExpression> prologue)
P
Pilchie 已提交
734 735
        {
            CapturedSymbolReplacement proxy;
736
            if (proxies.TryGetValue(symbol, out proxy))
P
Pilchie 已提交
737
            {
738 739
                BoundExpression value;
                switch (symbol.Kind)
740
                {
741 742 743
                    case SymbolKind.Parameter:
                        var parameter = (ParameterSymbol)symbol;
                        ParameterSymbol parameterToUse;
744
                        if (!_parameterMap.TryGetValue(parameter, out parameterToUse))
745 746
                        {
                            parameterToUse = parameter;
747
                        }
748 749

                        value = new BoundParameter(syntax, parameterToUse);
750
                        break;
751

752
                    case SymbolKind.Local:
753
                        if (!_assignLocals)
754 755 756
                        {
                            return;
                        }
757

758 759 760 761 762 763 764 765
                        var local = (LocalSymbol)symbol;
                        LocalSymbol localToUse;
                        if (!localMap.TryGetValue(local, out localToUse))
                        {
                            localToUse = local;
                        }

                        value = new BoundLocal(syntax, localToUse, null, localToUse.Type);
766
                        break;
E
Evan Hauck 已提交
767

768 769 770
                    default:
                        throw ExceptionUtilities.UnexpectedValue(symbol.Kind);
                }
P
Pilchie 已提交
771

E
Evan Hauck 已提交
772 773 774
                var left = proxy.Replacement(syntax, frameType1 => new BoundLocal(syntax, framePointer, null, framePointer.Type));
                var assignToProxy = new BoundAssignmentOperator(syntax, left, value, value.Type);
                prologue.Add(assignToProxy);
P
Pilchie 已提交
775 776 777 778 779
            }
        }

        #region Visit Methods

780 781 782
        protected override BoundNode VisitUnhoistedParameter(BoundParameter node)
        {
            ParameterSymbol replacementParameter;
783
            if (_parameterMap.TryGetValue(node.ParameterSymbol, out replacementParameter))
784 785 786 787 788 789 790
            {
                return new BoundParameter(node.Syntax, replacementParameter, replacementParameter.Type, node.HasErrors);
            }

            return base.VisitUnhoistedParameter(node);
        }

P
Pilchie 已提交
791 792 793 794 795 796 797 798 799 800 801 802
        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?

803
            return (_currentMethod == _topLevelMethod || _topLevelMethod.ThisParameter == null ?
804 805
                node :
                FramePointer(node.Syntax, (NamedTypeSymbol)node.Type));
P
Pilchie 已提交
806 807 808 809
        }

        public override BoundNode VisitBaseReference(BoundBaseReference node)
        {
810
            return (!_currentMethod.IsStatic && _currentMethod.ContainingType == _topLevelMethod.ContainingType)
P
Pilchie 已提交
811
                ? node
812
                : FramePointer(node.Syntax, _topLevelMethod.ContainingType); // technically, not the correct static type
P
Pilchie 已提交
813
        }
814

E
Evan Hauck 已提交
815
        private void RemapLambdaOrLocalFunction(
816
            SyntaxNode syntax,
E
Evan Hauck 已提交
817 818 819 820 821 822
            MethodSymbol originalMethod,
            ImmutableArray<TypeSymbol> typeArgumentsOpt,
            ClosureKind closureKind,
            ref MethodSymbol synthesizedMethod,
            out BoundExpression receiver,
            out NamedTypeSymbol constructedFrame)
E
Evan Hauck 已提交
823
        {
E
Evan Hauck 已提交
824 825
            var translatedLambdaContainer = synthesizedMethod.ContainingType;
            var containerAsFrame = translatedLambdaContainer as LambdaFrame;
826

827
            // All of _currentTypeParameters might not be preserved here due to recursively calling upwards in the chain of local functions/lambdas
E
Evan Hauck 已提交
828
            Debug.Assert((typeArgumentsOpt.IsDefault && !originalMethod.IsGenericMethod) || (typeArgumentsOpt.Length == originalMethod.Arity));
829
            var totalTypeArgumentCount = (containerAsFrame?.Arity ?? 0) + synthesizedMethod.Arity;
E
Evan Hauck 已提交
830 831
            var realTypeArguments = ImmutableArray.Create(StaticCast<TypeSymbol>.From(_currentTypeParameters), 0, totalTypeArgumentCount - originalMethod.Arity);
            if (!typeArgumentsOpt.IsDefault)
832
            {
E
Evan Hauck 已提交
833
                realTypeArguments = realTypeArguments.Concat(typeArgumentsOpt);
834 835
            }

E
Evan Hauck 已提交
836 837 838 839 840 841 842 843 844 845
            if (containerAsFrame != null && containerAsFrame.Arity != 0)
            {
                var containerTypeArguments = ImmutableArray.Create(realTypeArguments, 0, containerAsFrame.Arity);
                realTypeArguments = ImmutableArray.Create(realTypeArguments, containerAsFrame.Arity, realTypeArguments.Length - containerAsFrame.Arity);
                constructedFrame = containerAsFrame.Construct(containerTypeArguments);
            }
            else
            {
                constructedFrame = translatedLambdaContainer;
            }
E
Evan Hauck 已提交
846 847 848

            // for instance lambdas, receiver is the frame
            // for static lambdas, get the singleton receiver
849
            if (closureKind == ClosureKind.Singleton)
E
Evan Hauck 已提交
850 851 852 853
            {
                var field = containerAsFrame.SingletonCache.AsMember(constructedFrame);
                receiver = new BoundFieldAccess(syntax, null, field, constantValueOpt: null);
            }
854 855 856 857 858 859 860 861
            else if (closureKind == ClosureKind.Static)
            {
                receiver = null;
            }
            else // ThisOnly and General
            {
                receiver = FrameOfType(syntax, constructedFrame);
            }
862

E
Evan Hauck 已提交
863 864 865 866 867 868
            synthesizedMethod = synthesizedMethod.AsMember(constructedFrame);
            if (synthesizedMethod.IsGenericMethod)
            {
                synthesizedMethod = synthesizedMethod.Construct(StaticCast<TypeSymbol>.From(realTypeArguments));
            }
            else
E
Evan Hauck 已提交
869
            {
E
Evan Hauck 已提交
870
                Debug.Assert(realTypeArguments.Length == 0);
E
Evan Hauck 已提交
871
            }
872
        }
P
Pilchie 已提交
873

874 875 876 877 878 879 880 881
        /// <remarks>
        /// This pass doesn't rewrite the local function calls themselves
        /// because we may encounter a call to a local function that has yet
        /// to be lowered. Here we just want to make sure we lower the
        /// arguments as they may contain references to captured variables.
        /// The final lowering of the call will be in the
        /// <see cref="LocalFunctionReferenceRewriter" />
        /// </remarks>
P
Pilchie 已提交
882 883
        public override BoundNode VisitCall(BoundCall node)
        {
E
Evan Hauck 已提交
884 885
            if (node.Method.MethodKind == MethodKind.LocalFunction)
            {
886 887
                var rewrittenArguments = this.VisitList(node.Arguments);

888
                var withArguments = node.Update(
889 890 891 892 893 894 895 896 897 898 899
                    node.ReceiverOpt,
                    node.Method,
                    rewrittenArguments,
                    node.ArgumentNamesOpt,
                    node.ArgumentRefKindsOpt,
                    node.IsDelegateCall,
                    node.Expanded,
                    node.InvokedAsExtensionMethod,
                    node.ArgsToParamsOpt,
                    node.ResultKind,
                    node.Type);
900 901

                return PartiallyLowerLocalFunctionReference(withArguments);
E
Evan Hauck 已提交
902
            }
903

E
Evan Hauck 已提交
904
            var visited = base.VisitCall(node);
P
Pilchie 已提交
905 906 907 908 909 910 911 912
            if (visited.Kind != BoundKind.Call)
            {
                return visited;
            }

            var rewritten = (BoundCall)visited;

            // Check if we need to init the 'this' proxy in a ctor call
913
            if (!_seenBaseCall)
P
Pilchie 已提交
914
            {
915 916
                _seenBaseCall = _currentMethod == _topLevelMethod && node.IsConstructorInitializer();
                if (_seenBaseCall && _thisProxyInitDeferred != null)
P
Pilchie 已提交
917 918 919 920 921 922 923
                {
                    // 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),
924
                        value: _thisProxyInitDeferred,
P
Pilchie 已提交
925 926 927 928 929 930 931
                        type: rewritten.Type);
                }
            }

            return rewritten;
        }

932 933 934 935 936 937 938 939 940 941 942
        private PartiallyLoweredLocalFunctionReference PartiallyLowerLocalFunctionReference(
            BoundExpression underlyingNode)
        {
            Debug.Assert(underlyingNode.Kind == BoundKind.Call ||
                         underlyingNode.Kind == BoundKind.DelegateCreationExpression ||
                         underlyingNode.Kind == BoundKind.Conversion);
            return new PartiallyLoweredLocalFunctionReference(
                                underlyingNode,
                                new Dictionary<Symbol, CapturedSymbolReplacement>(proxies));
        }

P
Pilchie 已提交
943 944
        private BoundSequence RewriteSequence(BoundSequence node, ArrayBuilder<BoundExpression> prologue, ArrayBuilder<LocalSymbol> newLocals)
        {
945
            RewriteLocals(node.Locals, newLocals);
P
Pilchie 已提交
946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962

            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.
963
            if (_frames.TryGetValue(node, out frame))
P
Pilchie 已提交
964 965 966 967 968 969 970 971 972 973
            {
                return IntroduceFrame(node, frame, (ArrayBuilder<BoundExpression> prologue, ArrayBuilder<LocalSymbol> newLocals) =>
                    RewriteBlock(node, prologue, newLocals));
            }
            else
            {
                return RewriteBlock(node, ArrayBuilder<BoundExpression>.GetInstance(), ArrayBuilder<LocalSymbol>.GetInstance());
            }
        }

974
        private BoundBlock RewriteBlock(BoundBlock node, ArrayBuilder<BoundExpression> prologue, ArrayBuilder<LocalSymbol> newLocals)
P
Pilchie 已提交
975
        {
976
            RewriteLocals(node.Locals, newLocals);
P
Pilchie 已提交
977 978 979

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

980 981 982 983 984 985 986
            if (prologue.Count > 0)
            {
                newStatements.Add(new BoundSequencePoint(null, null) { WasCompilerGenerated = true });
            }

            InsertAndFreePrologue(newStatements, prologue);

P
Pilchie 已提交
987 988 989 990 991 992 993 994 995 996
            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.
E
Evan Hauck 已提交
997
            return node.Update(newLocals.ToImmutableAndFree(), node.LocalFunctions, newStatements.ToImmutableAndFree());
P
Pilchie 已提交
998 999 1000 1001 1002 1003
        }

        public override BoundNode VisitCatchBlock(BoundCatchBlock node)
        {
            // Test if this frame has captured variables and requires the introduction of a closure class.
            LambdaFrame frame;
1004
            if (_frames.TryGetValue(node, out frame))
P
Pilchie 已提交
1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018
            {
                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)
        {
1019 1020
            RewriteLocals(node.Locals, newLocals);
            var rewrittenCatchLocals = newLocals.ToImmutableAndFree();
P
Pilchie 已提交
1021 1022 1023

            // If exception variable got lifted, IntroduceFrame will give us frame init prologue.
            // It needs to run before the exception variable is accessed.
1024
            // To ensure that, we will make exception variable a sequence that performs prologue as its side-effects.
P
Pilchie 已提交
1025
            BoundExpression rewrittenExceptionSource = null;
1026
            var rewrittenFilter = (BoundExpression)this.Visit(node.ExceptionFilterOpt);
P
Pilchie 已提交
1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
            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);
                }
            }
1040 1041 1042 1043 1044 1045 1046 1047 1048 1049
            else if (prologue.Count > 0)
            {
                Debug.Assert(rewrittenFilter != null);
                rewrittenFilter = new BoundSequence(
                    rewrittenFilter.Syntax,
                    ImmutableArray.Create<LocalSymbol>(),
                    prologue.ToImmutable(),
                    rewrittenFilter,
                    rewrittenFilter.Type);
            }
P
Pilchie 已提交
1050

1051
            // done with this.
P
Pilchie 已提交
1052 1053 1054 1055 1056 1057 1058 1059
            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(
1060
                rewrittenCatchLocals,
P
Pilchie 已提交
1061 1062 1063
                rewrittenExceptionSource,
                exceptionTypeOpt,
                rewrittenFilter,
1064 1065
                rewrittenBlock,
                node.IsSynthesizedAsyncCatchAll);
P
Pilchie 已提交
1066 1067 1068 1069 1070 1071
        }

        public override BoundNode VisitSequence(BoundSequence node)
        {
            LambdaFrame frame;
            // Test if this frame has captured variables and requires the introduction of a closure class.
1072
            if (_frames.TryGetValue(node, out frame))
P
Pilchie 已提交
1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
            {
                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.
1090
            if (_frames.TryGetValue(node, out frame))
P
Pilchie 已提交
1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101
            {
                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));
                    }

1102
                    return new BoundBlock(node.Syntax, newLocals.ToImmutableAndFree(), newStatements.ToImmutableAndFree(), node.HasErrors);
P
Pilchie 已提交
1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114
                });
            }
            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.
1115
            if (_frames.TryGetValue(node, out frame))
P
Pilchie 已提交
1116 1117 1118 1119 1120 1121 1122
            {
                return IntroduceFrame(node, frame, (ArrayBuilder<BoundExpression> prologue, ArrayBuilder<LocalSymbol> newLocals) =>
                {
                    var newStatements = ArrayBuilder<BoundStatement>.GetInstance();
                    InsertAndFreePrologue(newStatements, prologue);
                    newStatements.Add((BoundStatement)base.VisitSwitchStatement(node));

1123
                    return new BoundBlock(node.Syntax, newLocals.ToImmutableAndFree(), newStatements.ToImmutableAndFree(), node.HasErrors);
P
Pilchie 已提交
1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139
                });
            }
            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);
            }
1140 1141

            if (node.MethodOpt?.MethodKind == MethodKind.LocalFunction)
P
Pilchie 已提交
1142
            {
1143
                return PartiallyLowerLocalFunctionReference(node);
P
Pilchie 已提交
1144
            }
1145
            return base.VisitDelegateCreationExpression(node);
P
Pilchie 已提交
1146 1147 1148 1149 1150 1151 1152
        }

        public override BoundNode VisitConversion(BoundConversion conversion)
        {
            if (conversion.ConversionKind == ConversionKind.AnonymousFunction)
            {
                var result = (BoundExpression)RewriteLambdaConversion((BoundLambda)conversion.Operand);
1153 1154 1155 1156

                if (_inExpressionLambda && conversion.ExplicitCastInCode)
                {
                    result = new BoundConversion(
1157 1158
                        syntax: conversion.Syntax,
                        operand: result,
V
VSadov 已提交
1159
                        conversion: conversion.Conversion,
1160 1161 1162 1163
                        isBaseConversion: false,
                        @checked: false,
                        explicitCastInCode: true,
                        constantValueOpt: conversion.ConstantValueOpt,
1164 1165 1166 1167
                        type: conversion.Type);
                }

                return result;
P
Pilchie 已提交
1168
            }
1169 1170 1171

            if (conversion.ConversionKind == ConversionKind.MethodGroup &&
                conversion.SymbolOpt?.MethodKind == MethodKind.LocalFunction)
P
Pilchie 已提交
1172
            {
1173
                return PartiallyLowerLocalFunctionReference(conversion);
P
Pilchie 已提交
1174
            }
1175
            return base.VisitConversion(conversion);
P
Pilchie 已提交
1176 1177
        }

1178 1179
        public override BoundNode VisitLocalFunctionStatement(BoundLocalFunctionStatement node)
        {
E
Evan Hauck 已提交
1180
            ClosureKind closureKind;
1181 1182
            NamedTypeSymbol translatedLambdaContainer;
            LambdaFrame containerAsFrame;
E
Evan Hauck 已提交
1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193
            BoundNode lambdaScope;
            DebugId topLevelMethodId;
            DebugId lambdaId;
            RewriteLambdaOrLocalFunction(
                node,
                out closureKind,
                out translatedLambdaContainer,
                out containerAsFrame,
                out lambdaScope,
                out topLevelMethodId,
                out lambdaId);
1194 1195 1196 1197

            return new BoundNoOpStatement(node.Syntax, NoOpStatementFlavor.Default);
        }

1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218
        private DebugId GetTopLevelMethodId()
        {
            return slotAllocatorOpt?.MethodId ?? new DebugId(_topLevelMethodOrdinal, CompilationState.ModuleBuilderOpt.CurrentGenerationOrdinal);
        }

        private DebugId GetClosureId(SyntaxNode syntax, ArrayBuilder<ClosureDebugInfo> closureDebugInfo)
        {
            Debug.Assert(syntax != null);

            DebugId closureId;
            DebugId previousClosureId;
            if (slotAllocatorOpt != null && slotAllocatorOpt.TryGetPreviousClosure(syntax, out previousClosureId))
            {
                closureId = previousClosureId;
            }
            else
            {
                closureId = new DebugId(closureDebugInfo.Count, CompilationState.ModuleBuilderOpt.CurrentGenerationOrdinal);
            }

            int syntaxOffset = _topLevelMethod.CalculateLocalSyntaxOffset(syntax.SpanStart, syntax.SyntaxTree);
T
Tomas Matousek 已提交
1219
            closureDebugInfo.Add(new ClosureDebugInfo(syntaxOffset, closureId));
1220 1221 1222 1223 1224

            return closureId;
        }

        private DebugId GetLambdaId(SyntaxNode syntax, ClosureKind closureKind, int closureOrdinal)
1225 1226 1227 1228 1229
        {
            Debug.Assert(syntax != null);

            SyntaxNode lambdaOrLambdaBodySyntax;
            var anonymousFunction = syntax as AnonymousFunctionExpressionSyntax;
1230
            var localFunction = syntax as LocalFunctionStatementSyntax;
1231 1232
            bool isLambdaBody;

1233 1234 1235
            if (anonymousFunction != null)
            {
                lambdaOrLambdaBodySyntax = anonymousFunction.Body;
1236
                isLambdaBody = true;
1237
            }
1238 1239 1240 1241 1242
            else if (localFunction != null)
            {
                lambdaOrLambdaBodySyntax = (SyntaxNode)localFunction.Body ?? localFunction.ExpressionBody;
                isLambdaBody = true;
            }
1243
            else if (LambdaUtilities.IsQueryPairLambda(syntax))
1244 1245 1246
            {
                // "pair" query lambdas
                lambdaOrLambdaBodySyntax = syntax;
1247
                isLambdaBody = false;
1248
                Debug.Assert(closureKind == ClosureKind.Singleton);
1249 1250 1251 1252 1253
            }
            else
            {
                // query lambdas
                lambdaOrLambdaBodySyntax = syntax;
1254
                isLambdaBody = true;
1255 1256
            }

1257
            Debug.Assert(!isLambdaBody || LambdaUtilities.IsLambdaBody(lambdaOrLambdaBodySyntax));
1258

1259
            // determine lambda ordinal and calculate syntax offset
1260

1261 1262 1263
            DebugId lambdaId;
            DebugId previousLambdaId;
            if (slotAllocatorOpt != null && slotAllocatorOpt.TryGetPreviousLambda(lambdaOrLambdaBodySyntax, isLambdaBody, out previousLambdaId))
1264
            {
1265
                lambdaId = previousLambdaId;
1266 1267 1268
            }
            else
            {
1269
                lambdaId = new DebugId(_lambdaDebugInfoBuilder.Count, CompilationState.ModuleBuilderOpt.CurrentGenerationOrdinal);
1270
            }
1271 1272

            int syntaxOffset = _topLevelMethod.CalculateLocalSyntaxOffset(lambdaOrLambdaBodySyntax.SpanStart, lambdaOrLambdaBodySyntax.SyntaxTree);
T
Tomas Matousek 已提交
1273
            _lambdaDebugInfoBuilder.Add(new LambdaDebugInfo(syntaxOffset, lambdaId, closureOrdinal));
1274
            return lambdaId;
1275 1276
        }

E
Evan Hauck 已提交
1277 1278 1279 1280 1281 1282 1283 1284
        private SynthesizedLambdaMethod RewriteLambdaOrLocalFunction(
            IBoundLambdaOrFunction node,
            out ClosureKind closureKind,
            out NamedTypeSymbol translatedLambdaContainer,
            out LambdaFrame containerAsFrame,
            out BoundNode lambdaScope,
            out DebugId topLevelMethodId,
            out DebugId lambdaId)
P
Pilchie 已提交
1285
        {
1286
            ImmutableArray<TypeSymbol> structClosures;
1287
            int closureOrdinal;
E
Evan Hauck 已提交
1288
            if (_analysis.LambdaScopes.TryGetValue(node.Symbol, out lambdaScope))
P
Pilchie 已提交
1289
            {
1290 1291 1292 1293 1294
                containerAsFrame = _frames[lambdaScope];
                var structClosureParamBuilder = ArrayBuilder<TypeSymbol>.GetInstance();
                while (containerAsFrame != null && containerAsFrame.IsValueType)
                {
                    structClosureParamBuilder.Add(containerAsFrame);
E
Evan Hauck 已提交
1295
                    if (this._analysis.NeedsParentFrame.Contains(lambdaScope))
1296
                    {
E
Evan Hauck 已提交
1297 1298 1299 1300 1301 1302 1303
                        var found = false;
                        while (this._analysis.ScopeParent.TryGetValue(lambdaScope, out lambdaScope))
                        {
                            if (_frames.TryGetValue(lambdaScope, out containerAsFrame))
                            {
                                found = true;
                                break;
1304
                            }
E
Evan Hauck 已提交
1305 1306 1307 1308 1309
                        }
                        if (found)
                        {
                            continue;
                        }
1310
                    }
E
Evan Hauck 已提交
1311 1312 1313
                    // can happen when scope no longer needs parent frame, or we're at the outermost level and the "parent frame" is top level "this".
                    lambdaScope = null;
                    containerAsFrame = null;
1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324
                }
                // Reverse it because we're going from inner to outer, and parameters are in order of outer to inner
                structClosureParamBuilder.ReverseContents();
                structClosures = structClosureParamBuilder.ToImmutableAndFree();
                if (containerAsFrame == null)
                {
                    closureKind = ClosureKind.Static; // not exactly... but we've rewritten the receiver to be a by-ref parameter
                    translatedLambdaContainer = _topLevelMethod.ContainingType;
                    closureOrdinal = LambdaDebugInfo.StaticClosureOrdinal;
                }
                else
1325 1326
                {
                    closureKind = ClosureKind.General;
1327
                    translatedLambdaContainer = containerAsFrame;
1328 1329
                    closureOrdinal = containerAsFrame.ClosureOrdinal;
                }
P
Pilchie 已提交
1330
            }
E
Evan Hauck 已提交
1331
            else if (_analysis.CapturedVariablesByLambda[node.Symbol].Count == 0)
1332
            {
1333
                if (_analysis.MethodsConvertedToDelegates.Contains(node.Symbol))
1334 1335
                {
                    translatedLambdaContainer = containerAsFrame = GetStaticFrame(Diagnostics, node);
1336 1337 1338 1339 1340 1341 1342
                    closureKind = ClosureKind.Singleton;
                    closureOrdinal = LambdaDebugInfo.StaticClosureOrdinal;
                }
                else
                {
                    containerAsFrame = null;
                    translatedLambdaContainer = _topLevelMethod.ContainingType;
1343 1344 1345
                    closureKind = ClosureKind.Static;
                    closureOrdinal = LambdaDebugInfo.StaticClosureOrdinal;
                }
1346
                structClosures = default(ImmutableArray<TypeSymbol>);
1347
            }
P
Pilchie 已提交
1348 1349
            else
            {
1350
                containerAsFrame = null;
1351
                translatedLambdaContainer = _topLevelMethod.ContainingType;
1352
                closureKind = ClosureKind.ThisOnly;
1353
                closureOrdinal = LambdaDebugInfo.ThisOnlyClosureOrdinal;
1354
                structClosures = default(ImmutableArray<TypeSymbol>);
P
Pilchie 已提交
1355 1356 1357
            }

            // Move the body of the lambda to a freshly generated synthetic method on its frame.
E
Evan Hauck 已提交
1358 1359
            topLevelMethodId = GetTopLevelMethodId();
            lambdaId = GetLambdaId(node.Syntax, closureKind, closureOrdinal);
1360

1361
            var synthesizedMethod = new SynthesizedLambdaMethod(translatedLambdaContainer, structClosures, closureKind, _topLevelMethod, topLevelMethodId, node, lambdaId);
1362
            CompilationState.ModuleBuilderOpt.AddSynthesizedDefinition(translatedLambdaContainer, synthesizedMethod);
P
Pilchie 已提交
1363

1364
            foreach (var parameter in node.Symbol.Parameters)
P
Pilchie 已提交
1365
            {
1366
                _parameterMap.Add(parameter, synthesizedMethod.Parameters[parameter.Ordinal]);
P
Pilchie 已提交
1367 1368
            }

E
Evan Hauck 已提交
1369 1370
            if (node is BoundLocalFunctionStatement)
            {
E
Evan Hauck 已提交
1371
                _localFunctionMap[((BoundLocalFunctionStatement)node).Symbol] = new MappedLocalFunction(synthesizedMethod, closureKind);
E
Evan Hauck 已提交
1372 1373
            }

P
Pilchie 已提交
1374
            // rewrite the lambda body as the generated method's body
1375 1376 1377 1378 1379 1380 1381 1382 1383
            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 已提交
1384 1385 1386

            // switch to the generated method

1387
            _currentMethod = synthesizedMethod;
1388
            if (closureKind == ClosureKind.Static || closureKind == ClosureKind.Singleton)
P
Pilchie 已提交
1389 1390
            {
                // no link from a static lambda to its container
1391
                _innermostFramePointer = _currentFrameThis = null;
P
Pilchie 已提交
1392 1393 1394
            }
            else
            {
1395 1396 1397
                _currentFrameThis = synthesizedMethod.ThisParameter;
                _innermostFramePointer = null;
                _framePointers.TryGetValue(translatedLambdaContainer, out _innermostFramePointer);
P
Pilchie 已提交
1398 1399
            }

E
Evan Hauck 已提交
1400
            _currentTypeParameters = containerAsFrame?.TypeParameters.Concat(synthesizedMethod.TypeParameters) ?? synthesizedMethod.TypeParameters;
E
Evan Hauck 已提交
1401
            _currentLambdaBodyTypeMap = synthesizedMethod.TypeMap;
P
Pilchie 已提交
1402 1403 1404

            var body = AddStatementsIfNeeded((BoundStatement)VisitBlock(node.Body));
            CheckLocalsDefined(body);
1405
            AddSynthesizedMethod(synthesizedMethod, body);
P
Pilchie 已提交
1406 1407 1408

            // return to the old method

1409 1410 1411 1412 1413 1414 1415
            _currentMethod = oldMethod;
            _currentFrameThis = oldFrameThis;
            _currentTypeParameters = oldTypeParameters;
            _innermostFramePointer = oldInnermostFramePointer;
            _currentLambdaBodyTypeMap = oldTypeMap;
            _addedLocals = oldAddedLocals;
            _addedStatements = oldAddedStatements;
P
Pilchie 已提交
1416

E
Evan Hauck 已提交
1417
            return synthesizedMethod;
1418
        }
E
Evan Hauck 已提交
1419

1420 1421 1422
        private void AddSynthesizedMethod(MethodSymbol method, BoundStatement body)
        {
            if (_synthesizedMethods == null)
1423
            {
1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435
                _synthesizedMethods = ArrayBuilder<TypeCompilationState.MethodWithBody>.GetInstance();
            }

            _synthesizedMethods.Add(
                new TypeCompilationState.MethodWithBody(
                    method,
                    body,
                    CompilationState.CurrentImportChain));
        }

        private BoundNode RewriteLambdaConversion(BoundLambda node)
        {
E
Evan Hauck 已提交
1436 1437 1438 1439 1440 1441 1442 1443
            var wasInExpressionLambda = _inExpressionLambda;
            _inExpressionLambda = _inExpressionLambda || node.Type.IsExpressionTree();

            if (_inExpressionLambda)
            {
                var newType = VisitType(node.Type);
                var newBody = (BoundBlock)Visit(node.Body);
                node = node.Update(node.Symbol, newBody, node.Diagnostics, node.Binder, newType);
1444
                var result0 = wasInExpressionLambda ? node : ExpressionLambdaRewriter.RewriteLambda(node, CompilationState, TypeMap, RecursionDepth, Diagnostics);
E
Evan Hauck 已提交
1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463
                _inExpressionLambda = wasInExpressionLambda;
                return result0;
            }

            ClosureKind closureKind;
            NamedTypeSymbol translatedLambdaContainer;
            LambdaFrame containerAsFrame;
            BoundNode lambdaScope;
            DebugId topLevelMethodId;
            DebugId lambdaId;
            SynthesizedLambdaMethod synthesizedMethod = RewriteLambdaOrLocalFunction(
                node,
                out closureKind,
                out translatedLambdaContainer,
                out containerAsFrame,
                out lambdaScope,
                out topLevelMethodId,
                out lambdaId);

E
Evan Hauck 已提交
1464
            MethodSymbol referencedMethod = synthesizedMethod;
1465
            BoundExpression receiver;
E
Evan Hauck 已提交
1466 1467
            NamedTypeSymbol constructedFrame;
            RemapLambdaOrLocalFunction(node.Syntax, node.Symbol, default(ImmutableArray<TypeSymbol>), closureKind, ref referencedMethod, out receiver, out constructedFrame);
1468

E
Evan Hauck 已提交
1469
            // Rewrite the lambda expression (and the enclosing anonymous method conversion) as a delegate creation expression
1470

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

1473 1474
            // static lambdas are emitted as instance methods on a singleton receiver
            // delegates invoke dispatch is optimized for instance delegates so 
1475
            // it is preferable to emit lambdas as instance methods even when lambdas 
1476
            // do not capture anything
P
Pilchie 已提交
1477 1478 1479 1480
            BoundExpression result = new BoundDelegateCreationExpression(
                node.Syntax,
                receiver,
                referencedMethod,
1481
                isExtensionMethod: false,
P
Pilchie 已提交
1482 1483 1484 1485 1486
                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.
1487
            var shouldCacheForStaticMethod = closureKind == ClosureKind.Singleton &&
1488
                _currentMethod.MethodKind != MethodKind.StaticConstructor &&
P
Pilchie 已提交
1489 1490 1491 1492 1493
                !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 &&
E
Evan Hauck 已提交
1494
                lambdaScope != _analysis.ScopeParent[node.Body] &&
P
Pilchie 已提交
1495 1496 1497 1498
                InLoopOrLambda(node.Syntax, lambdaScope.Syntax);

            if (shouldCacheForStaticMethod || shouldCacheInLoop)
            {
1499
                // replace the expression "new Delegate(frame.M)" with "frame.cache ?? (frame.cache = new Delegate(frame.M));
1500
                var F = new SyntheticBoundNodeFactory(_currentMethod, node.Syntax, CompilationState, Diagnostics);
P
Pilchie 已提交
1501 1502
                try
                {
T
TomasMatousek 已提交
1503
                    BoundExpression cache;
1504
                    if (shouldCacheForStaticMethod || shouldCacheInLoop && (object)containerAsFrame != null)
P
Pilchie 已提交
1505
                    {
1506 1507 1508
                        // Since the cache variable will be in a container with possibly alpha-rewritten generic parameters, we need to
                        // substitute the original type according to the type map for that container. That substituted type may be
                        // different from the local variable `type`, which has the node's type substituted for the current container.
1509
                        var cacheVariableType = containerAsFrame.TypeMap.SubstituteType(node.Type).Type;
1510

1511
                        var cacheVariableName = GeneratedNames.MakeLambdaCacheFieldName(
1512 1513
                            // 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.
1514 1515
                            (closureKind == ClosureKind.General) ? -1 : topLevelMethodId.Ordinal,
                            topLevelMethodId.Generation,
1516 1517
                            lambdaId.Ordinal,
                            lambdaId.Generation);
1518

1519
                        var cacheField = new SynthesizedLambdaCacheFieldSymbol(translatedLambdaContainer, cacheVariableType, cacheVariableName, _topLevelMethod, isReadOnly: false, isStatic: closureKind == ClosureKind.Singleton);
T
TomasMatousek 已提交
1520
                        CompilationState.ModuleBuilderOpt.AddSynthesizedDefinition(translatedLambdaContainer, cacheField);
T
TomasMatousek 已提交
1521
                        cache = F.Field(receiver, cacheField.AsMember(constructedFrame)); //NOTE: the field was added to the unconstructed frame type.
P
Pilchie 已提交
1522 1523 1524 1525
                    }
                    else
                    {
                        // the lambda captures at most the "this" of the enclosing method.  We cache its delegate in a local variable.
1526
                        var cacheLocal = F.SynthesizedLocal(type, kind: SynthesizedLocalKind.CachedAnonymousMethodDelegate);
1527 1528 1529
                        if (_addedLocals == null) _addedLocals = ArrayBuilder<LocalSymbol>.GetInstance();
                        _addedLocals.Add(cacheLocal);
                        if (_addedStatements == null) _addedStatements = ArrayBuilder<BoundStatement>.GetInstance();
T
TomasMatousek 已提交
1530
                        cache = F.Local(cacheLocal);
1531
                        _addedStatements.Add(F.Assignment(cache, F.Null(type)));
P
Pilchie 已提交
1532 1533
                    }

T
TomasMatousek 已提交
1534
                    result = F.Coalesce(cache, F.AssignmentExpression(cache, result));
P
Pilchie 已提交
1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577
                }
                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)
            {
1578
                switch (curSyntax.Kind())
P
Pilchie 已提交
1579 1580 1581
                {
                    case SyntaxKind.ForStatement:
                    case SyntaxKind.ForEachStatement:
1582
                    case SyntaxKind.ForEachComponentStatement:
P
Pilchie 已提交
1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601
                    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;
        }

E
Evan Hauck 已提交
1602
        #endregion
P
Pilchie 已提交
1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692

#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
    }
}