When working with Roslyn, I will often have a node that is in the CompilationUnitSyntax but not the SemanticModel or vice-versa. (Or I can only pull the nodes out with operations of one or the other–For example if you need type info from a semantic model, the node querying on has to exist in the SemanticModel’s tree)
I can see why they did it for immutability and all that, but how the heck do you consistently go back and find the same token from one tree to another?? If you modify either tree, you have to retrieve the node you were working with somehow. What’s the best way to do it????
If you want to keep track of a single syntax node while you’re changing the tree, you can use
SyntaxAnnotation.To use it, create a new
SyntaxAnnotation(or a custom derived type, if you need to keep some additional information with that annotation) and then add it to a node by callingannotation.AddAnnotationTo(node)ornode.WithAdditionalAnnotations(annotation). Keep in mind that the node is still immutable, so you need to replace the original one with the annotated one in the tree.Then, after you perform some modifications to the tree, you can get the annotated node back by using something like
parentNode.GetAnnotatedNodesAndTokens(annotation).Single().AsNode(). (You can also get all nodes annotated by a specific derived type of annotation byparentNode.GetAnnotatedNodesAndTokens(typeof(CustomAnnotationType)).)