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

StackOverflow https://stackoverflow.com/questions/21079903

  •  27-09-2022
  •  | 
  •  

Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top