Chapter156:.NETCompilerPlatform (Roslyn)

No Comments

Section156.1:Semanticmodel

ASemanticModeloffersadeeperlevelofinterpretationandinsightofcodecomparetoasyntaxtree.Where syntaxtreescantellthenamesofvariables,semanticmodelsalsogivethetypeandallreferences.Syntaxtrees notice method calls, but semantic models give references to the precise location the method is declared (after overload resolution has been applied.)

varworkspace=Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.Create(); varsln=awaitworkspace.OpenSolutionAsync(solutionFilePath);

varproject=sln.Projects.First();

varcompilation=awaitproject.GetCompilationAsync();

foreach(varsyntaxTreeincompilation.SyntaxTrees)

{

varroot=awaitsyntaxTree.GetRootAsync();

vardeclaredIdentifiers=root.DescendantNodes()

.Where(an=>anisVariableDeclaratorSyntax)

.Cast<VariableDeclaratorSyntax>();

foreach(vardiindeclaredIdentifiers)

{

Console.WriteLine(di.Identifier);

//=>”root”

varvariableSymbol=compilation

.GetSemanticModel(syntaxTree)

.GetDeclaredSymbol(di)asILocalSymbol;

Console.WriteLine(variableSymbol.Type);

//=>“Microsoft.CodeAnalysis.SyntaxNode”

varreferences=awaitSymbolFinder.FindReferencesAsync(variableSymbol,sln); foreach(varreferenceinreferences)

{

foreach(varlocinreference.Locations)

{

Console.WriteLine(loc.Location.SourceSpan);

//=>”[1375..1379)”

}

}

}

}

This outputs a list of local variables using a syntax tree. Then it consults the semantic model to get the full type name and find all references of every variable.

Section156.2:Syntaxtree

ASyntaxTreeisanimmutabledatastructurerepresentingtheprogramasatreeofnames,commandsandmarks (as previously configured in the editor.)

Forexample,assumeaMicrosoft.CodeAnalysis.Compilationinstancenamedcompilationhasbeenconfigured.

Therearemultiplewaystolistthenamesofeveryvariabledeclaredintheloadedcode.Todosonaively,takeall piecesofsyntaxineverydocument(theDescendantNodesmethod)anduseLinqtoselectnodesthatdescribe variable declaration:

foreach(varsyntaxTreeincompilation.SyntaxTrees)

{

varroot=awaitsyntaxTree.GetRootAsync();

vardeclaredIdentifiers=root.DescendantNodes()

.Where(an=>anisVariableDeclaratorSyntax)

.Cast<VariableDeclaratorSyntax>()

.Select(vd=>vd.Identifier);

foreach(vardiindeclaredIdentifiers)

{

Console.WriteLine(di);

}

}

EverytypeofC#constructwithacorrespondingtypewillexistinthesyntaxtree.Toquicklyfindspecifictypes,use the SyntaxVisualizerwindow from Visual Studio. This will interpret the current opened document as a Roslynsyntax tree.

Section156.3:CreateworkspacefromMSBuildproject

FirstobtaintheMicrosoft.CodeAnalysis.CSharp.Workspacesnugetbeforecontinuing.

varworkspace=Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.Create(); varproject=awaitworkspace.OpenProjectAsync(projectFilePath);

varcompilation=awaitproject.GetCompilationAsync();

foreach(vardiagnosticincompilation.GetDiagnostics()

.Where(d=>d.Severity==Microsoft.CodeAnalysis.DiagnosticSeverity.Error))

{

Console.WriteLine(diagnostic);

}

To load existing code to the workspace, compile and report errors. Afterwards the code will be located in memory. From here, both the syntactic and semantic side will be available to work with.

About us and this blog

We are a digital marketing company with a focus on helping our customers achieve great results across several key areas.

Request a free quote

We offer professional SEO services that help websites increase their organic search score drastically in order to compete for the highest rankings even when it comes to highly competitive keywords.

Subscribe to our newsletter!

More from our blog

See all posts

Leave a Comment