Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get dependencies between classes in Roslyn

I am successfully getting dependencies between projects with Roslyn, and now I would like to get dependencies between classes, similar to the Code Map feature in Visual Studio Enterprise.

Here is my code, the "?????" part is where I imagine I could get something. I am very new to the Roslyn API, though, and I don't know how to proceed from there on.

        Solution solution = MSBuildWorkspace.Create()
            .OpenSolutionAsync(Path.Combine(repoRootFolder, "MySolution.sln"))
            .Result;

        ProjectDependencyGraph projdeps = solution.GetProjectDependencyGraph();

        Digraph graph = new Digraph();

        foreach (ProjectId projectId in projdeps.GetTopologicallySortedProjects())
        {
            string projName = solution.GetProject(projectId).Name;
            var projDeps = projdeps.GetProjectsThatThisProjectDirectlyDependsOn(projectId);
            foreach (ProjectId depId in projDeps)
            {
                Project dep = solution.GetProject(depId);

                Compilation compilation = dep.GetCompilationAsync().Result;

                foreach (var syntree in compilation.SyntaxTrees)
                {
                    foreach (var classNode in syntree.GetRoot().DescendantNodes().OfType<ClassDeclarationSyntax>())
                    {
                        var classesThisClassNodeReferences = ?????????
                    }
                }

                string depName = dep.Name;

                graph.Dependencies.Add(new Dependency
                {
                    Source = projName,
                    Target = depName
                });
            }
        }
like image 452
heltonbiker Avatar asked Aug 30 '16 18:08

heltonbiker


1 Answers

I'm not sure about your requirements, but you can probably go for checking all descendant SyntaxNodes of the class and get the corresponding symbol, and it's type, and then collect these types. Something like the following:

var semantic = compilation.GetSemanticModel(syntree);
var typesForCurrentClass = classNode.DescendantNodes().Select(n => 
  semantic.GetTypeInfo(n).Type);

Note that there can be multiple typesForCurrentClass for a given class symbol because of partial classes.

like image 97
Tamas Avatar answered Oct 04 '22 19:10

Tamas