Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get TypeSyntax from ITypeSymbol

Tags:

c#

roslyn

I'm experimenting a bit with the Roslyn-CTP.

Currently I'm trying to replace var with the concrete type.

var i=1;

should become:

int i=1;

Figuring out the inferred type is easy. But since this part happens in the semantic model I get a ITypeSymbol. The replacement happens in the syntax model, so I need a TypeSyntax. Since I don't want a bloated name (global::System.Int32), the conversion is context dependent (using, nested types etc.).

The Visual studio version that's part of Roslyn already has this functionality in its "Simplify type name" quickfix, but looking over the samples I couldn't find an easy way to do this conversion.


Based on Kevin Pilch-Bisson's answer I'm now using:

var location = document.GetSyntaxTree().GetLocation(node);
string name = variableType.ToMinimalDisplayString((Location)location, (SemanticModel)document.GetSemanticModel());

A location which ToMinimalDisplayString can be obtained from a CommonSyntaxTree.

An additional complication is that ToMinimalDisplayString requires the classes Location and SemanticModel, whereas document.GetSemanticModel() and CommonSyntaxTree.GetLocation only return an interface.
I worked around by simply casting to the classes, which seems to work for now.

Hmm it looks like the classes are C# specific, and the interfaces language independent.


I've uploaded a working version on github: https://github.com/CodesInChaos/Roslyn

It doesn't work for var in a foreach, but I suspect that's a limitation of the current Roslyn build.

like image 967
CodesInChaos Avatar asked Nov 22 '11 17:11

CodesInChaos


1 Answers

You can get the shortest legal string to represent a symbol at a given location using the ToMinimalDisplayString() extension method that applies to ISymbol (note: It's found in `Roslyn.Compilers.CSharp.SymbolDisplay.

Disclaimer: I work at Microsoft on the Roslyn team.

like image 94
Kevin Pilch Avatar answered Nov 03 '22 03:11

Kevin Pilch