Search code examples
c#.net-coreroslyn

Get all types from compilation using Roslyn?


I'm trying to get all types by some criteria from Roslyn Compilation created by this code:

var syntaxTrees = new[] 
{ 
      CSharpSyntaxTree.ParseText(source, new CSharpParseOptions(LanguageVersion.Preview)) 
};

// Add some references
references.Add(MetadataReference.CreateFromFile(...));
            
// Create compilation
var options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);
var compilation = CSharpCompilation.Create(nameof(GeneratorRunner), syntaxTrees, references, options);

return compilation;

Then I'm using this code to seach for types

compilation.GetTypeByMetadataName("HomeCenter.Messages.Commands.Device.AdjustPowerLevelCommand");
compilation.GetSymbolsWithName(x => true, SymbolFilter.Type).ToList();

This works weird for me - GetSymbolsWithName returns only types defined in my sources but not in referenced assemblies but GetTypeByMetadataName is able to return information about type even when it is defined in reference assembly. The problem is I'm trying to search for all types in compilation so I don't know exact names. The question is how can I search in all types application have in sources but also in referenced assemblies? Also is there any other option for filtering opposite to name - I'm interested in all types that inherit from specific type so they can be named in all kind of ways.


Solution

  • If you want to start searching through all types, you can do Compilation.GlobalNamespace, which gives you a INamespaceSymbol that represents the "root" namespace of the hierarchy. From there you can call GetTypeMembers() to get types that are in that namespace, and GetNamespaceMembers() to get child namespaces. You'll have to do the recursion yourself, I don't think we have a helper for that.