c# - Finding everywhere an enum is converted to string -
i'm trying find everywhere in solution specific enum converted string, whether or not tostring() explicitly called. (these being replaced conversion using enum descriptions improve obfuscation.)
example: i'd find code such string str = "value: " + someenum.somevalue;
i've tried replacing enum wrapper class containing implicit conversions enum type , overriding tostring() in wrapper class, when try searching uses of tostring() override gives me list of places in solution tostring() called on (and called explicitly). search done resharper in visual studio.
is there way find these enum-to-string conversions? going through entire solution manually doesn't sound fun.
the trick in roslyn use semanticmodel.gettypeinfo()
, check convertedtype
find these sort of implicit conversions.
a complete example:
using system; using system.collections.generic; using system.linq; using system.text; using roslyn.compilers; using roslyn.compilers.csharp; using roslyn.services; using roslyn.services.csharp; using roslyn.compilers.common; class program { static void main(string[] args) { var code = @"enum e { v } class { static void main() { string s = ""value: "" + e.v; } }"; var doc = solution.create(solutionid.createnewid()) .addcsharpproject("foo", "foo") .addmetadatareference(metadatafilereference.createassemblyreference("mscorlib")) .adddocument("doc.cs", code); var stringtype = doc.project.getcompilation().getspecialtype(specialtype.system_string); var e = doc.project.getcompilation().globalnamespace.gettypemembers("e").single(); var v = e.getmembers("v").single(); var refs = v.findreferences(doc.project.solution); var tostrings = referencedlocation in refs r in referencedlocation.locations let node = getnode(doc, r.location) let convertedtype = doc.getsemanticmodel().gettypeinfo(getnode(doc, r.location)).convertedtype convertedtype.equals(stringtype) select r.location; foreach (var loc in tostrings) { console.writeline(loc); } } static commonsyntaxnode getnode(idocument doc, commonlocation loc) { return loc.sourcetree.getroot().findtoken(loc.sourcespan.start).parent.parent.parent; } }
Comments
Post a Comment