Roslyn scripting: Line number information for run time exceptions

后端 未结 1 1656
我寻月下人不归
我寻月下人不归 2021-02-11 00:37

I am messing around with the Roslyn scripting stuff (using the Microsoft.CodeAnalysis.CSharp.Scripting nuget package), and I wonder if there is a way to add line nu

1条回答
  •  日久生厌
    2021-02-11 01:27

    I got something working by emitting an (in-memory) assembly with debug information.

    Example code:

    var code = @"
    var a = 0;
    var b = 1 / a;
    ";
    
    var script = CSharpScript.Create(code);
    var compilation = script.GetCompilation();
    var ilstream = new MemoryStream();
    var pdbstream = new MemoryStream();
    compilation.Emit(ilstream, pdbstream);
    
    var assembly = Assembly.Load(ilstream.GetBuffer(), pdbstream.GetBuffer());
    var type = assembly.GetType("Submission#0");
    var factory = type.GetMethod("");
    var submissionArray = new object[2];
    Task task = (Task)factory.Invoke(null, new object[] { submissionArray });
    
    try
    {
        await task;
    }
    catch (DivideByZeroException dbze)
    {
        Console.WriteLine(dbze.StackTrace);
    }
    
    
    

    The output is (notice the :line 3 in the stack trace):

       at Submission#0.<>d__0.MoveNext() in :line 3
    --- End of stack trace from previous location where exception was thrown ---
       at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
       at UnitTests.ExploreRoslyn.d__13.MoveNext() in D:\dev\misc\netmockery\UnitTests\ExploreRoslyn.cs:line 151
    

    Now obviously this is a bit of a hack, and I'm not really happy with the hardcoded script engine implementation details (Submission#0, ), plus I don't really know what I'm doing. There should be (and maybe there is?) a better way.

    Update

    Created issue https://github.com/dotnet/roslyn/issues/13482 in the Roslyn issue tracker.

    0 讨论(0)
    提交回复
    热议问题