Bug 32135

Summary: C# 6 string interpolation and lambdas miscompilation
Product: [Mono] Compilers Reporter: nsf <no.smile.face>
Component: C#Assignee: Marek Safar <masafa>
Status: RESOLVED FIXED    
Severity: normal CC: mono-bugs+mono
Priority: ---    
Version: 4.0.0   
Target Milestone: ---   
Hardware: PC   
OS: Linux   
Tags: Is this bug a regression?: ---
Last known good build:

Description nsf 2015-07-20 06:08:32 UTC
Mono versions:
--------------------------------------------------
[nsf @ ~]$ mcs --version
Mono C# compiler version 4.0.1.0
[nsf @ ~]$ mono --version
Mono JIT compiler version 4.0.1 (tarball Wed Jun 10 09:11:17 UTC 2015)
Copyright (C) 2002-2014 Novell, Inc, Xamarin Inc and Contributors. www.mono-project.com
        TLS:           __thread
        SIGSEGV:       altstack
        Notifications: epoll
        Architecture:  amd64
        Disabled:      none
        Misc:          softdebug
        LLVM:          supported, not enabled.
        GC:            sgen
--------------------------------------------------


Given this code:
--------------------------------------------------
using System;

class App {
        static Action a;

        static void Do(Action cb) {
                cb();
        }

        static void SetupOK() {
                int number = 0;
                Do(() => {
                        a = () => Console.WriteLine(string.Format("Number: {0}", ++number));
                });
        }

        static void SetupBAD() {
                int number = 0;
                Do(() => {
                        a = () => Console.WriteLine($"Number: {++number}");
                });
        }

        static void Main() {
                SetupOK();
                a();
                SetupBAD();
                a();
        }
}
--------------------------------------------------

SetupOK works fine, SetupBAD produces wrong code. I guess it has something to do with the way compiler captures variables in this nested lambda case with C# 6's string interpolation.

Miscompiled code dies with the following exception:

Unhandled Exception:
System.InvalidProgramException: Invalid IL code in App:<SetupBAD>m__1 (): IL_0005: ldloc.0
Comment 1 Marek Safar 2015-07-20 13:33:43 UTC
Fixed in master and Mono 4.2