Roslyn fluent syntax to create expression tree for multiline lambda

.net c# expression-trees metaprogramming roslyn

Question

I am writing a Roslyn-based custom tool that tries to eradicate CS0834 by rewriting given multi-line lambdas into Expression trees at build time.

Edit: At this time, I am only targeting anonymous multiline lambdas.

For example:

    // Will produce CS0834 if Bar takes Expression<Action<...>>
    Foo.Bar((int x) => { ... });

to

    Foo.Bar(Expression.Lambda<Action<int>>(
        Expression.Block(
            ...
            ),
        Expression.Parameter(typeof(int))));

So that will compile correctly. While I can figure out the Expression.(blah) syntax required to convert the given code, doing it using Roslyn is another matter altogether. Perhaps I just don't know the Roslyn Syntax.(blah) API well enough to translate this raw lambda

    (int index, float[] a, float[] b) =>
    {
        var sum = 0f;
        for (int i = 0; i < index; i++)
            sum += a[i];

        b[index] = sum;
    });

Could someone help me write the Roslyn Syntax.(blah) syntax that will generate an expression tree that looks like the one below?

    Expression<Action<int, float[], float[]>> action = 
        Expression.Lambda(
            Expression.Block(
                Expression.Assign(sumParameter, Expression.Constant(0)),
                Expression.Loop(...) // The for loop here
                )
            );

Once I have a starting point - I ought to be able to figure out or at least get started translating simple cases in this project.

Many thanks, your help is much appreciated.

Accepted Answer

We have a tool called Quoter that will generate Syntax.* API calls for any C# program.

You can view it live at roslynquoter.azurewebsites.net.

If you figure out the logic to generate the Expression.* calls, you can easily generate code that generates it.

Update: the tool is now open-source! https://github.com/KirillOsenkov/RoslynQuoter



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why