Question

I am working on implementing different source code transformations with Roslyn. (the code context will be a standalone command line util and not a VS CodeAction)

The most trivial way to do this to have CSharpSyntaxRewriter implementation and when visiting the particular nodes apply the changes on the fly. However this approach may or may not have sideeffects leading to erratic result. When changing the tree we are changing the semantic model too, so the previously got semanticmodel may invalidated. Not going into the details its kinda similar thing like changing a List while enumerating on that without notifiyng the enumerator about this.

(Yes I know the tree is immutable, but this is the whole point: the visitor will change it, when an overloaded method returns with a replacement node instead of the original.)

So I got this idea: We must do the transformation in 2 passes: First collects the changes, and the second actually applies the changes.

  • The first pass is obviously a CSharpSyntaxRewriter (visitor) what is actually does not rewrite anything just produces a change list. (maybe some lower base visitor class will do better than a rewriter, as actually will not rewritten anything in this pass)
  • The second pass is the change list applier what applies the changes collected in the first pass.

The next interesting idea, that the second pass does not have to manipulate the tree itself: It can manipulate the original source text directly (the first pass can build a change list with exact source code locations, as Span information is available for every node and token.)

Sorry for this long explanation, now the question:

I do not want to reinvent the wheel: Is there any source code manipulation infrastructure already implemented in Roslyn (to have a change list, (based on Spans for example) and Apply(...) it on a source code?

Thx in advance

Was it helpful?

Solution

Found exactly what was described:

The SourceText class has a WithChanges(...) method what returns with the new SourceText instance transformad by applied changes. The changes are in the form of a list of TextChange, which is basically a thin wrapper around TextSpan, containing the span itself and the replacement text.

Thanks anyone who spent time with this.

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