[Question] How do I get all the INamedTypeSymbols in a given compilation? #6138

Closed
JoshVarty opened this Issue Oct 19, 2015 · 10 comments

Projects

None yet

5 participants

@JoshVarty
Member

I've been trying this for about 45 minutes now, but I can't seem to figure out how to get a list of all of the INamedTypeSymbol available in a given compilation. I tried digging through the Compilation.GetTypeByMetadataName stuff, but couldn't figure it out.

I tried using Compilation.GlobalNamespace.GetTypeMembers() and it seems to give me all the IModuleSymbols that are referenced by the current project. (I see mscorlib, System.Core etc.) I then tried getting the type members inside these modules, but they were either empty or contained PrivateImplementation stuff.

Is there an API to get access to all the INamedTypeSymbols available in a compilation?

@SLaks
Contributor
SLaks commented Oct 19, 2015

You need to recurse through all of the namespaces in the global namespace

@daveaglick
Contributor

Yep - I've found the easiest way to do the recursion is with a SymbolVisitor:

// Main code
CSharpCompilation compilation = CSharpCompilation.Create(...);
GetAllSymbolsVisitor visitor = new GetAllSymbolsVisitor();
visitor.Visit(compilation.Assembly.GlobalNamespace);

// Visitor
public class GetAllSymbolsVisitor : SymbolVisitor
{
    public override void VisitNamespace(INamespaceSymbol symbol)
    {
        Parallel.ForEach(symbol.GetMembers(), s => s.Accept(this));
    }

    public override void VisitNamedType(INamedTypeSymbol symbol)
    {
        // Do what you need to here (add to collection, etc.)
    }
}
@SLaks
Contributor
SLaks commented Oct 19, 2015

@daveaglick You can syntax-highlight that code by wrapping it in

```C#
@daveaglick
Contributor

@SLaks Holy cow - I had no idea I could force language highlighting. One of those simple little things I never picked up...thanks!

@SLaks
Contributor
SLaks commented Oct 19, 2015

Also, your visitor won't catch nested types.

@daveaglick
Contributor

Yeah, just left that out - there's actually a pretty full example here that does:
https://github.com/Wyamio/Wyam/blob/develop/Wyam.Modules.CodeAnalysis/AnalyzeSymbolVisitor.cs

@JoshVarty
Member

Thanks guys, that should be more than enough to get me started. :)

@JoshVarty JoshVarty closed this Oct 19, 2015
@daveaglick
Contributor

@drewnoakes Indeed it is! A casualty of refactoring, thanks for updating it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment