How to view assembly content without source code in Roslyn

Roslyn lets you get CSharpCompilation

from source:

// Getting the AST node
 var tree = (CSharpSyntaxTree)CSharpSyntaxTree.ParseText("my code");

// Loading the semantic model
CSharpCompilation compilation = CSharpCompilation.Create("Compilation", new[] { tree });

      

Then I get SemanticModel

:

var sm = compilation.GetSemanticModel(tree);

      

I usually try to get characters like this:

sm.GetSymbolInfo(node);

      

No source code

What if I don't have the source code?

  • How can I get CSharpCompilation

    without source code but only from DLL?
  • How can I list all symbols in a DLL and get all the information about those types?

Is Roslyn capable of this?

+3


source to share


3 answers


Roslyn is not meant to read assemblies, reflection libraries like System.Reflection, Mono.Cecil, System.Reflection.Metadata or IKVM.Reflection will most likely be better suited for this.

If you really want to do this, you can get the symbol for the assembly by creating a dummy compilation that references the assembly and then using GetAssemblyOrModuleSymbol

. For example, to write all types in an assembly in the console, you can use code like this:



var reference = MetadataReference.CreateFromFile(dllPath);
var compilation = CSharpCompilation.Create(null).AddReferences(reference);

var assemblySymbol = (IAssemblySymbol)compilation.GetAssemblyOrModuleSymbol(reference);

Write(assemblySymbol.GlobalNamespace);

void Write(INamespaceOrTypeSymbol symbol)
{
    if (symbol is ITypeSymbol)
        Console.WriteLine(symbol);

    foreach (var memberSymbol in symbol.GetMembers().OfType<INamespaceOrTypeSymbol>())
    {
        Write(memberSymbol);
    }
}

      

+5


source


Roslyn is a compiler. It takes the source code and builds it.



To test assemblies you need to use reflection .

+1


source


The NDepend tool offers a code model that can only be built from assemblies . No PDB or source code, but more information can be provided if PDB and source code are available. More explanation on NDepend parsing inputs here .

The code model can then be explored using C # LINQ queries . Around 150 predefined code rules are written with such a predefined LINQ query.

The generated code model offers many objects : code metrics, dependencies, diff from baseline, state variability, technical debt score ...

Disclaimer: I am working for NDepend

+1


source







All Articles