c# - Get a list of referenced Types within a project with Roslyn -
i want list of used types in project, example:
var x = 1; var y = x.tostring().gettype();
the code should return system.int32
, system.string
, system.type
.
what have freaking slow... each file (syntax tree), following:
var root = await syntaxtree.getrootasync(); var nodes = root.descendantnodes(n => true); if (nodes != null) { var syntaxnodes = nodes syntaxnode[] ?? nodes.toarray(); // identifiernamesyntax: // - var keyword // - identifiers of kind (including type names) var namedtypes = syntaxnodes .oftype<identifiernamesyntax>() .select(id => this.compilation .getsemanticmodel(id.syntaxtree) .getsymbolinfo(id) .symbol) .oftype<inamedtypesymbol>() .toarray(); // add found types list this.addrange(namedtypes); // expressionsyntax: // - method calls // - property uses // - field uses // - kinds of composite expressions var expressionsyntaxs = syntaxnodes .oftype<expressionsyntax>() .tolist(); var typesymbols = new list<itypesymbol>(); (int index = 0; index < expressionsyntaxs.count; index++) { expressionsyntax ma = expressionsyntaxs[index]; typesymbols.add(this.compilation .getsemanticmodel(ma.syntaxtree) .gettypeinfo(ma) .type); } var expressiontypes = typesymbols .oftype<inamedtypesymbol>() .toarray(); // add found types list this.addrange(expressiontypes); }
motivation:
i making tool analyses project, , tells .net framework versions support given project (e.g. portable .net frameworks).
i hoped faster match set of used types set of available types framework, before compiling.
with small files code fast enough, , total amount of time less of compiling every possible framework... large files unacceptable.
is there way list of types in way acceptable?
so, i've learnt lesson: never assume immutable structure going cache of it's calculations because 2 calls return same result.
it true when method pure, return same structurally, doesn't have same instance.
my assumption lead me error: thinking this.compilation.getsemanticmodel(id.syntaxtree)
return same instance of semantic model given syntaxtree
... it's not true.
i changed code following, , blazing fast:
var root = await syntaxtree.getrootasync(); var nodes = root.descendantnodes(n => true); var st = root.syntaxtree; var sm = this.compilation.getsemanticmodel(st); if (nodes != null) { var syntaxnodes = nodes syntaxnode[] ?? nodes.toarray(); // identifiernamesyntax: // - var keyword // - identifiers of kind (including type names) var namedtypes = syntaxnodes .oftype<identifiernamesyntax>() .select(id => sm.getsymbolinfo(id).symbol) .oftype<inamedtypesymbol>() .toarray(); this.add(namedtypes); // expressionsyntax: // - method calls // - property uses // - field uses // - kinds of composite expressions var expressiontypes = syntaxnodes .oftype<expressionsyntax>() .select(ma => sm.gettypeinfo(ma).type) .oftype<inamedtypesymbol>() .toarray(); this.add(expressiontypes); }
Comments
Post a Comment