Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Roslyn expose the compiler-generated yield transformations to the syntax trees?

Tags:

yield

roslyn

The yield operator is implemented under the hood by the compiler generating a class that implements a state machine adhering to IEnumerable and IEnumerator.

Given a Roslyn MethodDeclarationSyntax, it is possible to create the ClassDeclarationSyntax and generate a MoveNext method as the compiler usually does. This transformation is necessary if one is writing a cross-compiler that is to support the yield operator -- one would first want to rewrite C# code to not use the yield operator and then let the cross-compiler take it from there.

However, it is clear that since Roslyn can compile C# code end-to-end, it must have the logic to perform this transformation in some fashion, and implementing this algorithm myself is pretty non-trivial.

My question: is that logic exposed in such a way that it is possible to leverage it to transform a given MethodDeclarationSyntax into the corresponding ClassDeclarationSyntax iterator declaration? Or is it baked away at the Emit phase and thus unavailable when working among SyntaxNodes?

like image 371
Kirk Woll Avatar asked Oct 01 '22 21:10

Kirk Woll


1 Answers

The current Roslyn bits handles iterator methods as part of the code generation phase. Unfortunately, this phase is mostly opaque and uses an internal representation that is not exposed to the public API. The Roslyn.Compilers.CSharp.IteratorRewriter internal class is where this is implemented, if you're in a mind to dig deeper into this.

For now, you'll have to implement this by yourself. However, the Roslyn team has hinted to a near-future update to the public CTP with substantial API changes, so cross your fingers and maybe the next version will have this feature.

like image 154
Trillian Avatar answered Oct 05 '22 12:10

Trillian