Browse Source

Merge pull request #170 from EdHarvey/Analysis

Analyzer & Ux Enhancements
pull/172/merge
Daniel Grunwald 14 years ago
parent
commit
e04f6f77ed
  1. 110
      ILSpy/CSharpLanguage.cs
  2. 7
      ILSpy/ILSpy.csproj
  3. 5
      ILSpy/Images/Images.cs
  4. BIN
      ILSpy/Images/StaticClass.png
  5. 3
      ILSpy/Images/TypeIcon.cs
  6. 69
      ILSpy/Language.cs
  7. 43
      ILSpy/TreeNodes/Analyzer/AnalyzedEventAccessorTreeNode.cs
  8. 33
      ILSpy/TreeNodes/Analyzer/AnalyzedEventOverridesTreeNode.cs
  9. 17
      ILSpy/TreeNodes/Analyzer/AnalyzedEventTreeNode.cs
  10. 34
      ILSpy/TreeNodes/Analyzer/AnalyzedFieldAccessTreeNode.cs
  11. 4
      ILSpy/TreeNodes/Analyzer/AnalyzedInterfaceEventImplementedByTreeNode.cs
  12. 4
      ILSpy/TreeNodes/Analyzer/AnalyzedInterfaceMethodImplementedByTreeNode.cs
  13. 4
      ILSpy/TreeNodes/Analyzer/AnalyzedInterfacePropertyImplementedByTreeNode.cs
  14. 51
      ILSpy/TreeNodes/Analyzer/AnalyzedMethodOverridesTreeNode.cs
  15. 8
      ILSpy/TreeNodes/Analyzer/AnalyzedMethodTreeNode.cs
  16. 28
      ILSpy/TreeNodes/Analyzer/AnalyzedMethodUsedByTreeNode.cs
  17. 43
      ILSpy/TreeNodes/Analyzer/AnalyzedPropertyAccessorTreeNode.cs
  18. 40
      ILSpy/TreeNodes/Analyzer/AnalyzedPropertyOverridesTreeNode.cs
  19. 13
      ILSpy/TreeNodes/Analyzer/AnalyzedPropertyTreeNode.cs
  20. 4
      ILSpy/TreeNodes/Analyzer/AnalyzedTypeExposedByTreeNode.cs
  21. 4
      ILSpy/TreeNodes/Analyzer/AnalyzedTypeExtensionMethodsTreeNode.cs
  22. 4
      ILSpy/TreeNodes/Analyzer/AnalyzedTypeInstantiationsTreeNode.cs
  23. 151
      ILSpy/TreeNodes/Analyzer/AnalyzedVirtualMethodUsedByTreeNode.cs
  24. 63
      ILSpy/TreeNodes/Analyzer/Helpers.cs
  25. 89
      ILSpy/TreeNodes/Analyzer/ScopedWhereUsedAnalyzer.cs
  26. 15
      ILSpy/TreeNodes/TypeTreeNode.cs

110
ILSpy/CSharpLanguage.cs

@ -47,12 +47,12 @@ namespace ICSharpCode.ILSpy
string name = "C#"; string name = "C#";
bool showAllMembers = false; bool showAllMembers = false;
Predicate<IAstTransform> transformAbortCondition = null; Predicate<IAstTransform> transformAbortCondition = null;
public CSharpLanguage() public CSharpLanguage()
{ {
} }
#if DEBUG #if DEBUG
internal static IEnumerable<CSharpLanguage> GetDebugLanguages() internal static IEnumerable<CSharpLanguage> GetDebugLanguages()
{ {
DecompilerContext context = new DecompilerContext(ModuleDefinition.CreateModule("dummy", ModuleKind.Dll)); DecompilerContext context = new DecompilerContext(ModuleDefinition.CreateModule("dummy", ModuleKind.Dll));
@ -71,20 +71,23 @@ namespace ICSharpCode.ILSpy
showAllMembers = true showAllMembers = true
}; };
} }
#endif #endif
public override string Name { public override string Name
{
get { return name; } get { return name; }
} }
public override string FileExtension { public override string FileExtension
{
get { return ".cs"; } get { return ".cs"; }
} }
public override string ProjectFileExtension { public override string ProjectFileExtension
{
get { return ".csproj"; } get { return ".csproj"; }
} }
public override void DecompileMethod(MethodDefinition method, ITextOutput output, DecompilationOptions options) public override void DecompileMethod(MethodDefinition method, ITextOutput output, DecompilationOptions options)
{ {
WriteCommentLine(output, TypeToString(method.DeclaringType, includeNamespace: true)); WriteCommentLine(output, TypeToString(method.DeclaringType, includeNamespace: true));
@ -92,7 +95,7 @@ namespace ICSharpCode.ILSpy
codeDomBuilder.AddMethod(method); codeDomBuilder.AddMethod(method);
RunTransformsAndGenerateCode(codeDomBuilder, output, options); RunTransformsAndGenerateCode(codeDomBuilder, output, options);
} }
public override void DecompileProperty(PropertyDefinition property, ITextOutput output, DecompilationOptions options) public override void DecompileProperty(PropertyDefinition property, ITextOutput output, DecompilationOptions options)
{ {
WriteCommentLine(output, TypeToString(property.DeclaringType, includeNamespace: true)); WriteCommentLine(output, TypeToString(property.DeclaringType, includeNamespace: true));
@ -100,7 +103,7 @@ namespace ICSharpCode.ILSpy
codeDomBuilder.AddProperty(property); codeDomBuilder.AddProperty(property);
RunTransformsAndGenerateCode(codeDomBuilder, output, options); RunTransformsAndGenerateCode(codeDomBuilder, output, options);
} }
public override void DecompileField(FieldDefinition field, ITextOutput output, DecompilationOptions options) public override void DecompileField(FieldDefinition field, ITextOutput output, DecompilationOptions options)
{ {
WriteCommentLine(output, TypeToString(field.DeclaringType, includeNamespace: true)); WriteCommentLine(output, TypeToString(field.DeclaringType, includeNamespace: true));
@ -108,7 +111,7 @@ namespace ICSharpCode.ILSpy
codeDomBuilder.AddField(field); codeDomBuilder.AddField(field);
RunTransformsAndGenerateCode(codeDomBuilder, output, options); RunTransformsAndGenerateCode(codeDomBuilder, output, options);
} }
public override void DecompileEvent(EventDefinition ev, ITextOutput output, DecompilationOptions options) public override void DecompileEvent(EventDefinition ev, ITextOutput output, DecompilationOptions options)
{ {
WriteCommentLine(output, TypeToString(ev.DeclaringType, includeNamespace: true)); WriteCommentLine(output, TypeToString(ev.DeclaringType, includeNamespace: true));
@ -116,7 +119,7 @@ namespace ICSharpCode.ILSpy
codeDomBuilder.AddEvent(ev); codeDomBuilder.AddEvent(ev);
RunTransformsAndGenerateCode(codeDomBuilder, output, options); RunTransformsAndGenerateCode(codeDomBuilder, output, options);
} }
public override void DecompileType(TypeDefinition type, ITextOutput output, DecompilationOptions options) public override void DecompileType(TypeDefinition type, ITextOutput output, DecompilationOptions options)
{ {
AstBuilder codeDomBuilder = CreateAstBuilder(options, currentType: type); AstBuilder codeDomBuilder = CreateAstBuilder(options, currentType: type);
@ -131,7 +134,7 @@ namespace ICSharpCode.ILSpy
AddXmlDocTransform.Run(astBuilder.CompilationUnit); AddXmlDocTransform.Run(astBuilder.CompilationUnit);
astBuilder.GenerateCode(output); astBuilder.GenerateCode(output);
} }
public override void DecompileAssembly(LoadedAssembly assembly, ITextOutput output, DecompilationOptions options) public override void DecompileAssembly(LoadedAssembly assembly, ITextOutput output, DecompilationOptions options)
{ {
if (options.FullDecompilation && options.SaveAsProjectDirectory != null) { if (options.FullDecompilation && options.SaveAsProjectDirectory != null) {
@ -150,7 +153,7 @@ namespace ICSharpCode.ILSpy
} }
} }
} }
#region WriteProjectFile #region WriteProjectFile
void WriteProjectFile(TextWriter writer, IEnumerable<Tuple<string, string>> files, ModuleDefinition module) void WriteProjectFile(TextWriter writer, IEnumerable<Tuple<string, string>> files, ModuleDefinition module)
{ {
@ -178,20 +181,20 @@ namespace ICSharpCode.ILSpy
w.WriteStartElement("Project", ns); w.WriteStartElement("Project", ns);
w.WriteAttributeString("ToolsVersion", "4.0"); w.WriteAttributeString("ToolsVersion", "4.0");
w.WriteAttributeString("DefaultTargets", "Build"); w.WriteAttributeString("DefaultTargets", "Build");
w.WriteStartElement("PropertyGroup"); w.WriteStartElement("PropertyGroup");
w.WriteElementString("ProjectGuid", Guid.NewGuid().ToString().ToUpperInvariant()); w.WriteElementString("ProjectGuid", Guid.NewGuid().ToString().ToUpperInvariant());
w.WriteStartElement("Configuration"); w.WriteStartElement("Configuration");
w.WriteAttributeString("Condition", " '$(Configuration)' == '' "); w.WriteAttributeString("Condition", " '$(Configuration)' == '' ");
w.WriteValue("Debug"); w.WriteValue("Debug");
w.WriteEndElement(); // </Configuration> w.WriteEndElement(); // </Configuration>
w.WriteStartElement("Platform"); w.WriteStartElement("Platform");
w.WriteAttributeString("Condition", " '$(Platform)' == '' "); w.WriteAttributeString("Condition", " '$(Platform)' == '' ");
w.WriteValue(platformName); w.WriteValue(platformName);
w.WriteEndElement(); // </Platform> w.WriteEndElement(); // </Platform>
switch (module.Kind) { switch (module.Kind) {
case ModuleKind.Windows: case ModuleKind.Windows:
w.WriteElementString("OutputType", "WinExe"); w.WriteElementString("OutputType", "WinExe");
@ -203,7 +206,7 @@ namespace ICSharpCode.ILSpy
w.WriteElementString("OutputType", "Library"); w.WriteElementString("OutputType", "Library");
break; break;
} }
w.WriteElementString("AssemblyName", module.Assembly.Name.Name); w.WriteElementString("AssemblyName", module.Assembly.Name.Name);
switch (module.Runtime) { switch (module.Runtime) {
case TargetRuntime.Net_1_0: case TargetRuntime.Net_1_0:
@ -222,14 +225,14 @@ namespace ICSharpCode.ILSpy
break; break;
} }
w.WriteElementString("WarningLevel", "4"); w.WriteElementString("WarningLevel", "4");
w.WriteEndElement(); // </PropertyGroup> w.WriteEndElement(); // </PropertyGroup>
w.WriteStartElement("PropertyGroup"); // platform-specific w.WriteStartElement("PropertyGroup"); // platform-specific
w.WriteAttributeString("Condition", " '$(Platform)' == '" + platformName + "' "); w.WriteAttributeString("Condition", " '$(Platform)' == '" + platformName + "' ");
w.WriteElementString("PlatformTarget", platformName); w.WriteElementString("PlatformTarget", platformName);
w.WriteEndElement(); // </PropertyGroup> (platform-specific) w.WriteEndElement(); // </PropertyGroup> (platform-specific)
w.WriteStartElement("PropertyGroup"); // Debug w.WriteStartElement("PropertyGroup"); // Debug
w.WriteAttributeString("Condition", " '$(Configuration)' == 'Debug' "); w.WriteAttributeString("Condition", " '$(Configuration)' == 'Debug' ");
w.WriteElementString("OutputPath", "bin\\Debug\\"); w.WriteElementString("OutputPath", "bin\\Debug\\");
@ -237,7 +240,7 @@ namespace ICSharpCode.ILSpy
w.WriteElementString("DebugType", "full"); w.WriteElementString("DebugType", "full");
w.WriteElementString("Optimize", "false"); w.WriteElementString("Optimize", "false");
w.WriteEndElement(); // </PropertyGroup> (Debug) w.WriteEndElement(); // </PropertyGroup> (Debug)
w.WriteStartElement("PropertyGroup"); // Release w.WriteStartElement("PropertyGroup"); // Release
w.WriteAttributeString("Condition", " '$(Configuration)' == 'Release' "); w.WriteAttributeString("Condition", " '$(Configuration)' == 'Release' ");
w.WriteElementString("OutputPath", "bin\\Release\\"); w.WriteElementString("OutputPath", "bin\\Release\\");
@ -245,8 +248,8 @@ namespace ICSharpCode.ILSpy
w.WriteElementString("DebugType", "pdbonly"); w.WriteElementString("DebugType", "pdbonly");
w.WriteElementString("Optimize", "true"); w.WriteElementString("Optimize", "true");
w.WriteEndElement(); // </PropertyGroup> (Release) w.WriteEndElement(); // </PropertyGroup> (Release)
w.WriteStartElement("ItemGroup"); // References w.WriteStartElement("ItemGroup"); // References
foreach (AssemblyNameReference r in module.AssemblyReferences) { foreach (AssemblyNameReference r in module.AssemblyReferences) {
if (r.Name != "mscorlib") { if (r.Name != "mscorlib") {
@ -257,7 +260,7 @@ namespace ICSharpCode.ILSpy
} }
} }
w.WriteEndElement(); // </ItemGroup> (References) w.WriteEndElement(); // </ItemGroup> (References)
foreach (IGrouping<string, string> gr in (from f in files group f.Item2 by f.Item1 into g orderby g.Key select g)) { foreach (IGrouping<string, string> gr in (from f in files group f.Item2 by f.Item1 into g orderby g.Key select g)) {
w.WriteStartElement("ItemGroup"); w.WriteStartElement("ItemGroup");
foreach (string file in gr.OrderBy(f => f, StringComparer.OrdinalIgnoreCase)) { foreach (string file in gr.OrderBy(f => f, StringComparer.OrdinalIgnoreCase)) {
@ -267,16 +270,16 @@ namespace ICSharpCode.ILSpy
} }
w.WriteEndElement(); w.WriteEndElement();
} }
w.WriteStartElement("Import"); w.WriteStartElement("Import");
w.WriteAttributeString("Project", "$(MSBuildToolsPath)\\Microsoft.CSharp.targets"); w.WriteAttributeString("Project", "$(MSBuildToolsPath)\\Microsoft.CSharp.targets");
w.WriteEndElement(); w.WriteEndElement();
w.WriteEndDocument(); w.WriteEndDocument();
} }
} }
#endregion #endregion
#region WriteCodeFilesInProject #region WriteCodeFilesInProject
bool IncludeTypeWhenDecompilingProject(TypeDefinition type, DecompilationOptions options) bool IncludeTypeWhenDecompilingProject(TypeDefinition type, DecompilationOptions options)
{ {
@ -286,11 +289,11 @@ namespace ICSharpCode.ILSpy
return false; return false;
return true; return true;
} }
IEnumerable<Tuple<string, string>> WriteCodeFilesInProject(AssemblyDefinition assembly, DecompilationOptions options, HashSet<string> directories) IEnumerable<Tuple<string, string>> WriteCodeFilesInProject(AssemblyDefinition assembly, DecompilationOptions options, HashSet<string> directories)
{ {
var files = assembly.MainModule.Types.Where(t => IncludeTypeWhenDecompilingProject(t, options)).GroupBy( var files = assembly.MainModule.Types.Where(t => IncludeTypeWhenDecompilingProject(t, options)).GroupBy(
delegate (TypeDefinition type) { delegate(TypeDefinition type) {
string file = TextView.DecompilerTextView.CleanUpName(type.Name) + this.FileExtension; string file = TextView.DecompilerTextView.CleanUpName(type.Name) + this.FileExtension;
if (string.IsNullOrEmpty(type.Namespace)) { if (string.IsNullOrEmpty(type.Namespace)) {
return file; return file;
@ -305,7 +308,7 @@ namespace ICSharpCode.ILSpy
Parallel.ForEach( Parallel.ForEach(
files, files,
new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount }, new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount },
delegate (IGrouping<string, TypeDefinition> file) { delegate(IGrouping<string, TypeDefinition> file) {
using (StreamWriter w = new StreamWriter(Path.Combine(options.SaveAsProjectDirectory, file.Key))) { using (StreamWriter w = new StreamWriter(Path.Combine(options.SaveAsProjectDirectory, file.Key))) {
AstBuilder codeDomBuilder = CreateAstBuilder(options, currentModule: assembly.MainModule); AstBuilder codeDomBuilder = CreateAstBuilder(options, currentModule: assembly.MainModule);
foreach (TypeDefinition type in file) { foreach (TypeDefinition type in file) {
@ -319,7 +322,7 @@ namespace ICSharpCode.ILSpy
return files.Select(f => Tuple.Create("Compile", f.Key)); return files.Select(f => Tuple.Create("Compile", f.Key));
} }
#endregion #endregion
#region WriteResourceFilesInProject #region WriteResourceFilesInProject
IEnumerable<Tuple<string, string>> WriteResourceFilesInProject(LoadedAssembly assembly, DecompilationOptions options, HashSet<string> directories) IEnumerable<Tuple<string, string>> WriteResourceFilesInProject(LoadedAssembly assembly, DecompilationOptions options, HashSet<string> directories)
{ {
@ -333,7 +336,8 @@ namespace ICSharpCode.ILSpy
IEnumerable<DictionaryEntry> rs = null; IEnumerable<DictionaryEntry> rs = null;
try { try {
rs = new ResourceSet(s).Cast<DictionaryEntry>(); rs = new ResourceSet(s).Cast<DictionaryEntry>();
} catch (ArgumentException) { }
catch (ArgumentException) {
} }
if (rs != null && rs.All(e => e.Value is Stream)) { if (rs != null && rs.All(e => e.Value is Stream)) {
foreach (var pair in rs) { foreach (var pair in rs) {
@ -351,7 +355,8 @@ namespace ICSharpCode.ILSpy
string xaml = null; string xaml = null;
try { try {
xaml = decompiler.DecompileBaml(ms, assembly.FileName, new ConnectMethodDecompiler(assembly), new AssemblyResolver(assembly)); xaml = decompiler.DecompileBaml(ms, assembly.FileName, new ConnectMethodDecompiler(assembly), new AssemblyResolver(assembly));
} catch (XamlXmlWriterException) {} // ignore XAML writer exceptions }
catch (XamlXmlWriterException) { } // ignore XAML writer exceptions
if (xaml != null) { if (xaml != null) {
File.WriteAllText(Path.Combine(options.SaveAsProjectDirectory, Path.ChangeExtension(fileName, ".xaml")), xaml); File.WriteAllText(Path.Combine(options.SaveAsProjectDirectory, Path.ChangeExtension(fileName, ".xaml")), xaml);
yield return Tuple.Create("Page", Path.ChangeExtension(fileName, ".xaml")); yield return Tuple.Create("Page", Path.ChangeExtension(fileName, ".xaml"));
@ -372,12 +377,13 @@ namespace ICSharpCode.ILSpy
} }
yield return Tuple.Create("EmbeddedResource", fileName); yield return Tuple.Create("EmbeddedResource", fileName);
} }
} finally { }
finally {
if (bamlDecompilerAppDomain != null) if (bamlDecompilerAppDomain != null)
AppDomain.Unload(bamlDecompilerAppDomain); AppDomain.Unload(bamlDecompilerAppDomain);
} }
} }
string GetFileNameForResource(string fullName, HashSet<string> directories) string GetFileNameForResource(string fullName, HashSet<string> directories)
{ {
string[] splitName = fullName.Split('.'); string[] splitName = fullName.Split('.');
@ -393,7 +399,7 @@ namespace ICSharpCode.ILSpy
return fileName; return fileName;
} }
#endregion #endregion
AstBuilder CreateAstBuilder(DecompilationOptions options, ModuleDefinition currentModule = null, TypeDefinition currentType = null, bool isSingleMember = false) AstBuilder CreateAstBuilder(DecompilationOptions options, ModuleDefinition currentModule = null, TypeDefinition currentType = null, bool isSingleMember = false)
{ {
if (currentModule == null) if (currentModule == null)
@ -417,7 +423,7 @@ namespace ICSharpCode.ILSpy
if (includeNamespace) if (includeNamespace)
options |= ConvertTypeOptions.IncludeNamespace; options |= ConvertTypeOptions.IncludeNamespace;
AstType astType = AstBuilder.ConvertType(type, typeAttributes, options); AstType astType = AstBuilder.ConvertType(type, typeAttributes, options);
StringWriter w = new StringWriter(); StringWriter w = new StringWriter();
if (type.IsByReference) { if (type.IsByReference) {
ParameterDefinition pd = typeAttributes as ParameterDefinition; ParameterDefinition pd = typeAttributes as ParameterDefinition;
@ -425,11 +431,11 @@ namespace ICSharpCode.ILSpy
w.Write("out "); w.Write("out ");
else else
w.Write("ref "); w.Write("ref ");
if (astType is ComposedType && ((ComposedType)astType).PointerRank > 0) if (astType is ComposedType && ((ComposedType)astType).PointerRank > 0)
((ComposedType)astType).PointerRank--; ((ComposedType)astType).PointerRank--;
} }
astType.AcceptVisitor(new OutputVisitor(w, new CSharpFormattingOptions()), null); astType.AcceptVisitor(new OutputVisitor(w, new CSharpFormattingOptions()), null);
return w.ToString(); return w.ToString();
} }
@ -464,12 +470,20 @@ namespace ICSharpCode.ILSpy
} else } else
return property.Name; return property.Name;
} }
public override bool ShowMember(MemberReference member) public override bool ShowMember(MemberReference member)
{ {
return showAllMembers || !AstBuilder.MemberIsHidden(member, new DecompilationOptions().DecompilerSettings); return showAllMembers || !AstBuilder.MemberIsHidden(member, new DecompilationOptions().DecompilerSettings);
} }
public override MemberReference GetOriginalCodeLocation(MemberReference member)
{
if (showAllMembers || !DecompilerSettingsPanel.CurrentDecompilerSettings.AnonymousMethods)
return member;
else
return ICSharpCode.ILSpy.TreeNodes.Analyzer.Helpers.GetOriginalCodeLocation(member);
}
public override string GetTooltip(MemberReference member) public override string GetTooltip(MemberReference member)
{ {
MethodDefinition md = member as MethodDefinition; MethodDefinition md = member as MethodDefinition;
@ -490,12 +504,12 @@ namespace ICSharpCode.ILSpy
b.RunTransformations(); b.RunTransformations();
foreach (var attribute in b.CompilationUnit.Descendants.OfType<AttributeSection>()) foreach (var attribute in b.CompilationUnit.Descendants.OfType<AttributeSection>())
attribute.Remove(); attribute.Remove();
StringWriter w = new StringWriter(); StringWriter w = new StringWriter();
b.GenerateCode(new PlainTextOutput(w)); b.GenerateCode(new PlainTextOutput(w));
return Regex.Replace(w.ToString(), @"\s+", " ").TrimEnd(); return Regex.Replace(w.ToString(), @"\s+", " ").TrimEnd();
} }
return base.GetTooltip(member); return base.GetTooltip(member);
} }
} }

7
ILSpy/ILSpy.csproj

@ -144,21 +144,22 @@
<SubType>Code</SubType> <SubType>Code</SubType>
</Compile> </Compile>
<Compile Include="TreeNodes\Analyzer\AnalyzeContextMenuEntry.cs" /> <Compile Include="TreeNodes\Analyzer\AnalyzeContextMenuEntry.cs" />
<Compile Include="TreeNodes\Analyzer\AnalyzedEventAccessorsTreeNode.cs" />
<Compile Include="TreeNodes\Analyzer\AnalyzedEventOverridesTreeNode.cs" /> <Compile Include="TreeNodes\Analyzer\AnalyzedEventOverridesTreeNode.cs" />
<Compile Include="TreeNodes\Analyzer\AnalyzedEventTreeNode.cs" /> <Compile Include="TreeNodes\Analyzer\AnalyzedEventTreeNode.cs" />
<Compile Include="TreeNodes\Analyzer\AnalyzedInterfacePropertyImplementedByTreeNode.cs" /> <Compile Include="TreeNodes\Analyzer\AnalyzedInterfacePropertyImplementedByTreeNode.cs" />
<Compile Include="TreeNodes\Analyzer\AnalyzedInterfaceMethodImplementedByTreeNode.cs" /> <Compile Include="TreeNodes\Analyzer\AnalyzedInterfaceMethodImplementedByTreeNode.cs" />
<Compile Include="TreeNodes\Analyzer\AnalyzedInterfaceEventImplementedByTreeNode.cs" /> <Compile Include="TreeNodes\Analyzer\AnalyzedInterfaceEventImplementedByTreeNode.cs" />
<Compile Include="TreeNodes\Analyzer\AnalyzedPropertyAccessorTreeNode.cs" />
<Compile Include="TreeNodes\Analyzer\AnalyzedTypeExposedByTreeNode.cs" /> <Compile Include="TreeNodes\Analyzer\AnalyzedTypeExposedByTreeNode.cs" />
<Compile Include="TreeNodes\Analyzer\AnalyzedTypeExtensionMethodsTreeNode.cs" /> <Compile Include="TreeNodes\Analyzer\AnalyzedTypeExtensionMethodsTreeNode.cs" />
<Compile Include="TreeNodes\Analyzer\AnalyzedTypeInstantiationsTreeNode.cs" /> <Compile Include="TreeNodes\Analyzer\AnalyzedTypeInstantiationsTreeNode.cs" />
<Compile Include="TreeNodes\Analyzer\AnalyzedTypeTreeNode.cs" /> <Compile Include="TreeNodes\Analyzer\AnalyzedTypeTreeNode.cs" />
<Compile Include="TreeNodes\Analyzer\AnalyzedEventAccessorTreeNode.cs" />
<Compile Include="TreeNodes\Analyzer\AnalyzedVirtualMethodUsedByTreeNode.cs" />
<Compile Include="TreeNodes\Analyzer\Helpers.cs" /> <Compile Include="TreeNodes\Analyzer\Helpers.cs" />
<Compile Include="TreeNodes\Analyzer\ScopedWhereUsedAnalyzer.cs" /> <Compile Include="TreeNodes\Analyzer\ScopedWhereUsedAnalyzer.cs" />
<Compile Include="TreeNodes\IMemberTreeNode.cs" /> <Compile Include="TreeNodes\IMemberTreeNode.cs" />
<Compile Include="TreeNodes\XamlResourceNode.cs" /> <Compile Include="TreeNodes\XamlResourceNode.cs" />
<Compile Include="TreeNodes\Analyzer\AnalyzedPropertyAccessorsTreeNode.cs" />
<Compile Include="TreeNodes\Analyzer\AnalyzedPropertyOverridesTreeNode.cs" /> <Compile Include="TreeNodes\Analyzer\AnalyzedPropertyOverridesTreeNode.cs" />
<Compile Include="TreeNodes\Analyzer\AnalyzedPropertyTreeNode.cs" /> <Compile Include="TreeNodes\Analyzer\AnalyzedPropertyTreeNode.cs" />
<Compile Include="XmlDoc\AddXmlDocTransform.cs" /> <Compile Include="XmlDoc\AddXmlDocTransform.cs" />
@ -243,6 +244,7 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Resource Include="Images\Class.png" /> <Resource Include="Images\Class.png" />
<Resource Include="Images\StaticClass.png" />
<Resource Include="Images\Delegate.png" /> <Resource Include="Images\Delegate.png" />
<Resource Include="Images\Enum.png" /> <Resource Include="Images\Enum.png" />
<Resource Include="Images\Field.png" /> <Resource Include="Images\Field.png" />
@ -310,6 +312,5 @@
<Name>ICSharpCode.TreeView</Name> <Name>ICSharpCode.TreeView</Name>
</ProjectReference> </ProjectReference>
</ItemGroup> </ItemGroup>
<ItemGroup />
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.Targets" /> <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.Targets" />
</Project> </Project>

5
ILSpy/Images/Images.cs

@ -65,6 +65,7 @@ namespace ICSharpCode.ILSpy
public static readonly BitmapImage Interface = LoadBitmap("Interface"); public static readonly BitmapImage Interface = LoadBitmap("Interface");
public static readonly BitmapImage Delegate = LoadBitmap("Delegate"); public static readonly BitmapImage Delegate = LoadBitmap("Delegate");
public static readonly BitmapImage Enum = LoadBitmap("Enum"); public static readonly BitmapImage Enum = LoadBitmap("Enum");
public static readonly BitmapImage StaticClass = LoadBitmap("StaticClass");
public static readonly BitmapImage Field = LoadBitmap("Field"); public static readonly BitmapImage Field = LoadBitmap("Field");
@ -133,6 +134,7 @@ namespace ICSharpCode.ILSpy
PreloadPublicIconToCache(TypeIcon.Struct, Images.Struct); PreloadPublicIconToCache(TypeIcon.Struct, Images.Struct);
PreloadPublicIconToCache(TypeIcon.Interface, Images.Interface); PreloadPublicIconToCache(TypeIcon.Interface, Images.Interface);
PreloadPublicIconToCache(TypeIcon.Delegate, Images.Delegate); PreloadPublicIconToCache(TypeIcon.Delegate, Images.Delegate);
PreloadPublicIconToCache(TypeIcon.StaticClass, Images.StaticClass);
} }
protected override ImageSource GetBaseImage(TypeIcon icon) protected override ImageSource GetBaseImage(TypeIcon icon)
@ -154,6 +156,9 @@ namespace ICSharpCode.ILSpy
case TypeIcon.Delegate: case TypeIcon.Delegate:
baseImage = Images.Delegate; baseImage = Images.Delegate;
break; break;
case TypeIcon.StaticClass:
baseImage = Images.StaticClass;
break;
default: default:
throw new NotSupportedException(); throw new NotSupportedException();
} }

BIN
ILSpy/Images/StaticClass.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 569 B

3
ILSpy/Images/TypeIcon.cs

@ -26,6 +26,7 @@ namespace ICSharpCode.ILSpy
Enum, Enum,
Struct, Struct,
Interface, Interface,
Delegate Delegate,
StaticClass
} }
} }

69
ILSpy/Language.cs

@ -35,66 +35,69 @@ namespace ICSharpCode.ILSpy
/// Gets the name of the language (as shown in the UI) /// Gets the name of the language (as shown in the UI)
/// </summary> /// </summary>
public abstract string Name { get; } public abstract string Name { get; }
/// <summary> /// <summary>
/// Gets the file extension used by source code files in this language. /// Gets the file extension used by source code files in this language.
/// </summary> /// </summary>
public abstract string FileExtension { get; } public abstract string FileExtension { get; }
public virtual string ProjectFileExtension { public virtual string ProjectFileExtension
{
get { return null; } get { return null; }
} }
/// <summary> /// <summary>
/// Gets the syntax highlighting used for this language. /// Gets the syntax highlighting used for this language.
/// </summary> /// </summary>
public virtual ICSharpCode.AvalonEdit.Highlighting.IHighlightingDefinition SyntaxHighlighting { public virtual ICSharpCode.AvalonEdit.Highlighting.IHighlightingDefinition SyntaxHighlighting
get { {
get
{
return ICSharpCode.AvalonEdit.Highlighting.HighlightingManager.Instance.GetDefinitionByExtension(this.FileExtension); return ICSharpCode.AvalonEdit.Highlighting.HighlightingManager.Instance.GetDefinitionByExtension(this.FileExtension);
} }
} }
public virtual void DecompileMethod(MethodDefinition method, ITextOutput output, DecompilationOptions options) public virtual void DecompileMethod(MethodDefinition method, ITextOutput output, DecompilationOptions options)
{ {
WriteCommentLine(output, TypeToString(method.DeclaringType, true) + "." + method.Name); WriteCommentLine(output, TypeToString(method.DeclaringType, true) + "." + method.Name);
} }
public virtual void DecompileProperty(PropertyDefinition property, ITextOutput output, DecompilationOptions options) public virtual void DecompileProperty(PropertyDefinition property, ITextOutput output, DecompilationOptions options)
{ {
WriteCommentLine(output, TypeToString(property.DeclaringType, true) + "." + property.Name); WriteCommentLine(output, TypeToString(property.DeclaringType, true) + "." + property.Name);
} }
public virtual void DecompileField(FieldDefinition field, ITextOutput output, DecompilationOptions options) public virtual void DecompileField(FieldDefinition field, ITextOutput output, DecompilationOptions options)
{ {
WriteCommentLine(output, TypeToString(field.DeclaringType, true) + "." + field.Name); WriteCommentLine(output, TypeToString(field.DeclaringType, true) + "." + field.Name);
} }
public virtual void DecompileEvent(EventDefinition ev, ITextOutput output, DecompilationOptions options) public virtual void DecompileEvent(EventDefinition ev, ITextOutput output, DecompilationOptions options)
{ {
WriteCommentLine(output, TypeToString(ev.DeclaringType, true) + "." + ev.Name); WriteCommentLine(output, TypeToString(ev.DeclaringType, true) + "." + ev.Name);
} }
public virtual void DecompileType(TypeDefinition type, ITextOutput output, DecompilationOptions options) public virtual void DecompileType(TypeDefinition type, ITextOutput output, DecompilationOptions options)
{ {
WriteCommentLine(output, TypeToString(type, true)); WriteCommentLine(output, TypeToString(type, true));
} }
public virtual void DecompileNamespace(string nameSpace, IEnumerable<TypeDefinition> types, ITextOutput output, DecompilationOptions options) public virtual void DecompileNamespace(string nameSpace, IEnumerable<TypeDefinition> types, ITextOutput output, DecompilationOptions options)
{ {
WriteCommentLine(output, nameSpace); WriteCommentLine(output, nameSpace);
} }
public virtual void DecompileAssembly(LoadedAssembly assembly, ITextOutput output, DecompilationOptions options) public virtual void DecompileAssembly(LoadedAssembly assembly, ITextOutput output, DecompilationOptions options)
{ {
WriteCommentLine(output, assembly.FileName); WriteCommentLine(output, assembly.FileName);
WriteCommentLine(output, assembly.AssemblyDefinition.FullName); WriteCommentLine(output, assembly.AssemblyDefinition.FullName);
} }
public virtual void WriteCommentLine(ITextOutput output, string comment) public virtual void WriteCommentLine(ITextOutput output, string comment)
{ {
output.WriteLine("// " + comment); output.WriteLine("// " + comment);
} }
/// <summary> /// <summary>
/// Converts a type reference into a string. This method is used by the member tree node for parameter and return types. /// Converts a type reference into a string. This method is used by the member tree node for parameter and return types.
/// </summary> /// </summary>
@ -105,7 +108,7 @@ namespace ICSharpCode.ILSpy
else else
return type.Name; return type.Name;
} }
/// <summary> /// <summary>
/// Converts a member signature to a string. /// Converts a member signature to a string.
/// This is used for displaying the tooltip on a member reference. /// This is used for displaying the tooltip on a member reference.
@ -117,14 +120,14 @@ namespace ICSharpCode.ILSpy
else else
return member.ToString(); return member.ToString();
} }
public virtual string FormatPropertyName(PropertyDefinition property, bool? isIndexer = null) public virtual string FormatPropertyName(PropertyDefinition property, bool? isIndexer = null)
{ {
if (property == null) if (property == null)
throw new ArgumentNullException("property"); throw new ArgumentNullException("property");
return property.Name; return property.Name;
} }
/// <summary> /// <summary>
/// Used for WPF keyboard navigation. /// Used for WPF keyboard navigation.
/// </summary> /// </summary>
@ -132,39 +135,49 @@ namespace ICSharpCode.ILSpy
{ {
return Name; return Name;
} }
public virtual bool ShowMember(MemberReference member) public virtual bool ShowMember(MemberReference member)
{ {
return true; return true;
} }
/// <summary>
/// Used by the analyzer to map compiler generated code back to the original code's location
/// </summary>
public virtual MemberReference GetOriginalCodeLocation(MemberReference member)
{
return member;
}
} }
public static class Languages public static class Languages
{ {
static ReadOnlyCollection<Language> allLanguages; static ReadOnlyCollection<Language> allLanguages;
/// <summary> /// <summary>
/// A list of all languages. /// A list of all languages.
/// </summary> /// </summary>
public static ReadOnlyCollection<Language> AllLanguages { public static ReadOnlyCollection<Language> AllLanguages
get { {
get
{
return allLanguages; return allLanguages;
} }
} }
internal static void Initialize(CompositionContainer composition) internal static void Initialize(CompositionContainer composition)
{ {
List<Language> languages = new List<Language>(); List<Language> languages = new List<Language>();
languages.AddRange(composition.GetExportedValues<Language>()); languages.AddRange(composition.GetExportedValues<Language>());
languages.Add(new ILLanguage(true)); languages.Add(new ILLanguage(true));
#if DEBUG #if DEBUG
languages.AddRange(ILAstLanguage.GetDebugLanguages()); languages.AddRange(ILAstLanguage.GetDebugLanguages());
languages.AddRange(CSharpLanguage.GetDebugLanguages()); languages.AddRange(CSharpLanguage.GetDebugLanguages());
#endif #endif
allLanguages = languages.AsReadOnly(); allLanguages = languages.AsReadOnly();
} }
/// <summary> /// <summary>
/// Gets a language using its name. /// Gets a language using its name.
/// If the language is not found, C# is returned instead. /// If the language is not found, C# is returned instead.

43
ILSpy/TreeNodes/Analyzer/AnalyzedEventAccessorsTreeNode.cs → ILSpy/TreeNodes/Analyzer/AnalyzedEventAccessorTreeNode.cs

@ -21,50 +21,19 @@ using Mono.Cecil;
namespace ICSharpCode.ILSpy.TreeNodes.Analyzer namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
{ {
internal sealed class AnalyzedEventAccessorsTreeNode : AnalyzerTreeNode internal class AnalyzedEventAccessorTreeNode : AnalyzedMethodTreeNode
{ {
public AnalyzedEventAccessorsTreeNode(EventDefinition analyzedEvent) private string name;
{
if (analyzedEvent == null)
throw new ArgumentNullException("analyzedEvent");
if (analyzedEvent.AddMethod != null)
this.Children.Add(new AnalyzedEventAccessorTreeNode(analyzedEvent.AddMethod, "add"));
if (analyzedEvent.RemoveMethod != null)
this.Children.Add(new AnalyzedEventAccessorTreeNode(analyzedEvent.RemoveMethod, "remove"));
foreach (var accessor in analyzedEvent.OtherMethods)
this.Children.Add(new AnalyzedEventAccessorTreeNode(accessor, null));
}
public override object Icon public AnalyzedEventAccessorTreeNode(MethodDefinition analyzedMethod, string name)
: base(analyzedMethod)
{ {
get { return Images.Search; } this.name = name;
} }
public override object Text public override object Text
{ {
get { return "Accessors"; } get { return name ?? base.Text; }
}
public static bool CanShow(EventDefinition property)
{
return !MainWindow.Instance.CurrentLanguage.ShowMember(property.AddMethod ?? property.RemoveMethod);
}
internal class AnalyzedEventAccessorTreeNode : AnalyzedMethodTreeNode
{
private string name;
public AnalyzedEventAccessorTreeNode(MethodDefinition analyzedMethod, string name)
: base(analyzedMethod)
{
this.name = name;
}
public override object Text
{
get { return name ?? base.Text; }
}
} }
} }
} }

33
ILSpy/TreeNodes/Analyzer/AnalyzedEventOverridesTreeNode.cs

@ -68,36 +68,25 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
private IEnumerable<SharpTreeNode> FetchChildren(CancellationToken ct) private IEnumerable<SharpTreeNode> FetchChildren(CancellationToken ct)
{ {
return FindReferences(MainWindow.Instance.CurrentAssemblyList.GetAssemblies(), ct); ScopedWhereUsedAnalyzer<SharpTreeNode> analyzer;
}
private IEnumerable<SharpTreeNode> FindReferences(IEnumerable<LoadedAssembly> assemblies, CancellationToken ct)
{
assemblies = assemblies.Where(asm => asm.AssemblyDefinition != null);
// use parallelism only on the assembly level (avoid locks within Cecil) analyzer = new ScopedWhereUsedAnalyzer<SharpTreeNode>(analyzedEvent, FindReferencesInType);
return assemblies.AsParallel().WithCancellation(ct).SelectMany((LoadedAssembly asm) => FindReferences(asm, ct)); return analyzer.PerformAnalysis(ct);
} }
private IEnumerable<SharpTreeNode> FindReferences(LoadedAssembly asm, CancellationToken ct) private IEnumerable<SharpTreeNode> FindReferencesInType(TypeDefinition type)
{ {
string asmName = asm.AssemblyDefinition.Name.Name;
string name = analyzedEvent.Name; string name = analyzedEvent.Name;
string declTypeName = analyzedEvent.DeclaringType.FullName; string declTypeName = analyzedEvent.DeclaringType.FullName;
foreach (TypeDefinition type in TreeTraversal.PreOrder(asm.AssemblyDefinition.MainModule.Types, t => t.NestedTypes)) {
ct.ThrowIfCancellationRequested();
if (!TypesHierarchyHelpers.IsBaseType(analyzedEvent.DeclaringType, type, resolveTypeArguments: false))
continue;
foreach (EventDefinition eventDef in type.Events) { if (!TypesHierarchyHelpers.IsBaseType(analyzedEvent.DeclaringType, type, resolveTypeArguments: false))
ct.ThrowIfCancellationRequested(); yield break;
if (TypesHierarchyHelpers.IsBaseEvent(analyzedEvent, eventDef)) { foreach (EventDefinition eventDef in type.Events) {
MethodDefinition anyAccessor = eventDef.AddMethod ?? eventDef.RemoveMethod; if (TypesHierarchyHelpers.IsBaseEvent(analyzedEvent, eventDef)) {
bool hidesParent = !anyAccessor.IsVirtual ^ anyAccessor.IsNewSlot; MethodDefinition anyAccessor = eventDef.AddMethod ?? eventDef.RemoveMethod;
yield return new AnalyzedEventTreeNode(eventDef, hidesParent ? "(hides) " : ""); bool hidesParent = !anyAccessor.IsVirtual ^ anyAccessor.IsNewSlot;
} yield return new AnalyzedEventTreeNode(eventDef, hidesParent ? "(hides) " : "");
} }
} }
} }

17
ILSpy/TreeNodes/Analyzer/AnalyzedEventTreeNode.cs

@ -57,8 +57,13 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
protected override void LoadChildren() protected override void LoadChildren()
{ {
if (AnalyzedEventAccessorsTreeNode.CanShow(analyzedEvent)) if (analyzedEvent.AddMethod != null)
this.Children.Add(new AnalyzedEventAccessorsTreeNode(analyzedEvent)); this.Children.Add(new AnalyzedEventAccessorTreeNode(analyzedEvent.AddMethod, "add"));
if (analyzedEvent.RemoveMethod != null)
this.Children.Add(new AnalyzedEventAccessorTreeNode(analyzedEvent.RemoveMethod, "remove"));
foreach (var accessor in analyzedEvent.OtherMethods)
this.Children.Add(new AnalyzedEventAccessorTreeNode(accessor, null));
if (AnalyzedEventOverridesTreeNode.CanShow(analyzedEvent)) if (AnalyzedEventOverridesTreeNode.CanShow(analyzedEvent))
this.Children.Add(new AnalyzedEventOverridesTreeNode(analyzedEvent)); this.Children.Add(new AnalyzedEventOverridesTreeNode(analyzedEvent));
if (AnalyzedInterfaceEventImplementedByTreeNode.CanShow(analyzedEvent)) if (AnalyzedInterfaceEventImplementedByTreeNode.CanShow(analyzedEvent))
@ -75,12 +80,12 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
public static bool CanShow(MemberReference member) public static bool CanShow(MemberReference member)
{ {
var property = member as EventDefinition; var eventDef = member as EventDefinition;
if (property == null) if (eventDef == null)
return false; return false;
return AnalyzedEventAccessorsTreeNode.CanShow(property) return !MainWindow.Instance.CurrentLanguage.ShowMember(eventDef.AddMethod ?? eventDef.RemoveMethod)
|| AnalyzedEventOverridesTreeNode.CanShow(property); || AnalyzedEventOverridesTreeNode.CanShow(eventDef);
} }
} }
} }

34
ILSpy/TreeNodes/Analyzer/AnalyzedFieldAccessTreeNode.cs

@ -22,6 +22,7 @@ using System.Threading;
using ICSharpCode.TreeView; using ICSharpCode.TreeView;
using Mono.Cecil; using Mono.Cecil;
using Mono.Cecil.Cil; using Mono.Cecil.Cil;
using System.Collections;
namespace ICSharpCode.ILSpy.TreeNodes.Analyzer namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
{ {
@ -30,6 +31,8 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
private readonly bool showWrites; // true: show writes; false: show read access private readonly bool showWrites; // true: show writes; false: show read access
private readonly FieldDefinition analyzedField; private readonly FieldDefinition analyzedField;
private readonly ThreadingSupport threading; private readonly ThreadingSupport threading;
private Lazy<Hashtable> foundMethods;
private object hashLock = new object();
public AnalyzedFieldAccessTreeNode(FieldDefinition analyzedField, bool showWrites) public AnalyzedFieldAccessTreeNode(FieldDefinition analyzedField, bool showWrites)
{ {
@ -68,8 +71,14 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
private IEnumerable<SharpTreeNode> FetchChildren(CancellationToken ct) private IEnumerable<SharpTreeNode> FetchChildren(CancellationToken ct)
{ {
var analyzer = new ScopedWhereUsedScopeAnalyzer<SharpTreeNode>(analyzedField, FindReferencesInType); foundMethods = new Lazy<Hashtable>(LazyThreadSafetyMode.ExecutionAndPublication);
return analyzer.PerformAnalysis(ct);
var analyzer = new ScopedWhereUsedAnalyzer<SharpTreeNode>(analyzedField, FindReferencesInType);
foreach (var child in analyzer.PerformAnalysis(ct)) {
yield return child;
}
foundMethods = null;
} }
private IEnumerable<SharpTreeNode> FindReferencesInType(TypeDefinition type) private IEnumerable<SharpTreeNode> FindReferencesInType(TypeDefinition type)
@ -95,8 +104,12 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
method.Body = null; method.Body = null;
if (found) if (found) {
yield return new AnalyzedMethodTreeNode(method); MethodDefinition codeLocation = this.Language.GetOriginalCodeLocation(method) as MethodDefinition;
if (codeLocation != null && !HasAlreadyBeenFound(codeLocation)) {
yield return new AnalyzedMethodTreeNode(codeLocation);
}
}
} }
} }
@ -116,5 +129,18 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
return false; return false;
} }
} }
private bool HasAlreadyBeenFound(MethodDefinition method)
{
Hashtable hashtable = foundMethods.Value;
lock (hashLock) {
if (hashtable.Contains(method)) {
return true;
} else {
hashtable.Add(method, null);
return false;
}
}
}
} }
} }

4
ILSpy/TreeNodes/Analyzer/AnalyzedInterfaceEventImplementedByTreeNode.cs

@ -69,8 +69,8 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
private IEnumerable<SharpTreeNode> FetchChildren(CancellationToken ct) private IEnumerable<SharpTreeNode> FetchChildren(CancellationToken ct)
{ {
ScopedWhereUsedScopeAnalyzer<SharpTreeNode> analyzer; ScopedWhereUsedAnalyzer<SharpTreeNode> analyzer;
analyzer = new ScopedWhereUsedScopeAnalyzer<SharpTreeNode>(analyzedMethod, FindReferencesInType); analyzer = new ScopedWhereUsedAnalyzer<SharpTreeNode>(analyzedMethod, FindReferencesInType);
return analyzer.PerformAnalysis(ct); return analyzer.PerformAnalysis(ct);
} }

4
ILSpy/TreeNodes/Analyzer/AnalyzedInterfaceMethodImplementedByTreeNode.cs

@ -67,8 +67,8 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
private IEnumerable<SharpTreeNode> FetchChildren(CancellationToken ct) private IEnumerable<SharpTreeNode> FetchChildren(CancellationToken ct)
{ {
ScopedWhereUsedScopeAnalyzer<SharpTreeNode> analyzer; ScopedWhereUsedAnalyzer<SharpTreeNode> analyzer;
analyzer = new ScopedWhereUsedScopeAnalyzer<SharpTreeNode>(analyzedMethod, FindReferencesInType); analyzer = new ScopedWhereUsedAnalyzer<SharpTreeNode>(analyzedMethod, FindReferencesInType);
return analyzer.PerformAnalysis(ct); return analyzer.PerformAnalysis(ct);
} }

4
ILSpy/TreeNodes/Analyzer/AnalyzedInterfacePropertyImplementedByTreeNode.cs

@ -69,8 +69,8 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
private IEnumerable<SharpTreeNode> FetchChildren(CancellationToken ct) private IEnumerable<SharpTreeNode> FetchChildren(CancellationToken ct)
{ {
ScopedWhereUsedScopeAnalyzer<SharpTreeNode> analyzer; ScopedWhereUsedAnalyzer<SharpTreeNode> analyzer;
analyzer = new ScopedWhereUsedScopeAnalyzer<SharpTreeNode>(analyzedMethod, FindReferencesInType); analyzer = new ScopedWhereUsedAnalyzer<SharpTreeNode>(analyzedMethod, FindReferencesInType);
return analyzer.PerformAnalysis(ct); return analyzer.PerformAnalysis(ct);
} }

51
ILSpy/TreeNodes/Analyzer/AnalyzedMethodOverridesTreeNode.cs

@ -73,45 +73,32 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
private IEnumerable<SharpTreeNode> FetchChildren(CancellationToken ct) private IEnumerable<SharpTreeNode> FetchChildren(CancellationToken ct)
{ {
return FindReferences(MainWindow.Instance.CurrentAssemblyList.GetAssemblies(), ct); ScopedWhereUsedAnalyzer<SharpTreeNode> analyzer;
}
private IEnumerable<SharpTreeNode> FindReferences(IEnumerable<LoadedAssembly> assemblies, CancellationToken ct)
{
assemblies = assemblies.Where(asm => asm.AssemblyDefinition != null);
// use parallelism only on the assembly level (avoid locks within Cecil) analyzer = new ScopedWhereUsedAnalyzer<SharpTreeNode>(analyzedMethod, FindReferencesInType);
return assemblies.AsParallel().WithCancellation(ct).SelectMany((LoadedAssembly asm) => FindReferences(asm, ct)); return analyzer.PerformAnalysis(ct);
} }
private IEnumerable<SharpTreeNode> FindReferences(LoadedAssembly asm, CancellationToken ct) private IEnumerable<SharpTreeNode> FindReferencesInType(TypeDefinition type)
{ {
string asmName = asm.AssemblyDefinition.Name.Name; SharpTreeNode newNode = null;
string name = analyzedMethod.Name; try {
string declTypeName = analyzedMethod.DeclaringType.FullName; if (!TypesHierarchyHelpers.IsBaseType(analyzedMethod.DeclaringType, type, resolveTypeArguments: false))
foreach (TypeDefinition type in TreeTraversal.PreOrder(asm.AssemblyDefinition.MainModule.Types, t => t.NestedTypes)) { yield break;
ct.ThrowIfCancellationRequested();
SharpTreeNode newNode = null; foreach (MethodDefinition method in type.Methods) {
try { if (TypesHierarchyHelpers.IsBaseMethod(analyzedMethod, method)) {
if (!TypesHierarchyHelpers.IsBaseType(analyzedMethod.DeclaringType, type, resolveTypeArguments: false)) bool hidesParent = !method.IsVirtual ^ method.IsNewSlot;
continue; newNode = new AnalyzedMethodTreeNode(method, hidesParent ? "(hides) " : "");
foreach (MethodDefinition method in type.Methods) {
ct.ThrowIfCancellationRequested();
if (TypesHierarchyHelpers.IsBaseMethod(analyzedMethod, method)) {
bool hidesParent = !method.IsVirtual ^ method.IsNewSlot;
newNode = new AnalyzedMethodTreeNode(method, hidesParent ? "(hides) " : "");
}
} }
} }
catch (ReferenceResolvingException) {
// ignore this type definition. maybe add a notification about such cases.
}
if (newNode != null)
yield return newNode;
} }
catch (ReferenceResolvingException) {
// ignore this type definition. maybe add a notification about such cases.
}
if (newNode != null)
yield return newNode;
} }
public static bool CanShow(MethodDefinition method) public static bool CanShow(MethodDefinition method)

8
ILSpy/TreeNodes/Analyzer/AnalyzedMethodTreeNode.cs

@ -58,9 +58,15 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
{ {
if (analyzedMethod.HasBody) if (analyzedMethod.HasBody)
this.Children.Add(new AnalyzedMethodUsesTreeNode(analyzedMethod)); this.Children.Add(new AnalyzedMethodUsesTreeNode(analyzedMethod));
this.Children.Add(new AnalyzedMethodUsedByTreeNode(analyzedMethod));
if (analyzedMethod.IsVirtual && !(analyzedMethod.IsNewSlot && analyzedMethod.IsFinal))
this.Children.Add(new AnalyzedVirtualMethodUsedByTreeNode(analyzedMethod));
else
this.Children.Add(new AnalyzedMethodUsedByTreeNode(analyzedMethod));
if (AnalyzedMethodOverridesTreeNode.CanShow(analyzedMethod)) if (AnalyzedMethodOverridesTreeNode.CanShow(analyzedMethod))
this.Children.Add(new AnalyzedMethodOverridesTreeNode(analyzedMethod)); this.Children.Add(new AnalyzedMethodOverridesTreeNode(analyzedMethod));
if (AnalyzedInterfaceMethodImplementedByTreeNode.CanShow(analyzedMethod)) if (AnalyzedInterfaceMethodImplementedByTreeNode.CanShow(analyzedMethod))
this.Children.Add(new AnalyzedInterfaceMethodImplementedByTreeNode(analyzedMethod)); this.Children.Add(new AnalyzedInterfaceMethodImplementedByTreeNode(analyzedMethod));
} }

28
ILSpy/TreeNodes/Analyzer/AnalyzedMethodUsedByTreeNode.cs

@ -17,6 +17,7 @@
// DEALINGS IN THE SOFTWARE. // DEALINGS IN THE SOFTWARE.
using System; using System;
using System.Collections.Concurrent;
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading; using System.Threading;
using ICSharpCode.TreeView; using ICSharpCode.TreeView;
@ -29,6 +30,7 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
{ {
private readonly MethodDefinition analyzedMethod; private readonly MethodDefinition analyzedMethod;
private readonly ThreadingSupport threading; private readonly ThreadingSupport threading;
private ConcurrentDictionary<MethodDefinition, int> foundMethods;
public AnalyzedMethodUsedByTreeNode(MethodDefinition analyzedMethod) public AnalyzedMethodUsedByTreeNode(MethodDefinition analyzedMethod)
{ {
@ -66,10 +68,14 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
private IEnumerable<SharpTreeNode> FetchChildren(CancellationToken ct) private IEnumerable<SharpTreeNode> FetchChildren(CancellationToken ct)
{ {
ScopedWhereUsedScopeAnalyzer<SharpTreeNode> analyzer; foundMethods = new ConcurrentDictionary<MethodDefinition, int>();
analyzer = new ScopedWhereUsedScopeAnalyzer<SharpTreeNode>(analyzedMethod, FindReferencesInType); var analyzer = new ScopedWhereUsedAnalyzer<SharpTreeNode>(analyzedMethod, FindReferencesInType);
return analyzer.PerformAnalysis(ct); foreach (var child in analyzer.PerformAnalysis(ct)) {
yield return child;
}
foundMethods = null;
} }
private IEnumerable<SharpTreeNode> FindReferencesInType(TypeDefinition type) private IEnumerable<SharpTreeNode> FindReferencesInType(TypeDefinition type)
@ -81,8 +87,7 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
continue; continue;
foreach (Instruction instr in method.Body.Instructions) { foreach (Instruction instr in method.Body.Instructions) {
MethodReference mr = instr.Operand as MethodReference; MethodReference mr = instr.Operand as MethodReference;
if (mr != null && if (mr != null && mr.Name == name &&
mr.Name == name &&
Helpers.IsReferencedBy(analyzedMethod.DeclaringType, mr.DeclaringType) && Helpers.IsReferencedBy(analyzedMethod.DeclaringType, mr.DeclaringType) &&
mr.Resolve() == analyzedMethod) { mr.Resolve() == analyzedMethod) {
found = true; found = true;
@ -92,9 +97,18 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
method.Body = null; method.Body = null;
if (found) if (found) {
yield return new AnalyzedMethodTreeNode(method); MethodDefinition codeLocation = this.Language.GetOriginalCodeLocation(method) as MethodDefinition;
if (codeLocation != null && !HasAlreadyBeenFound(codeLocation)) {
yield return new AnalyzedMethodTreeNode(codeLocation);
}
}
} }
} }
private bool HasAlreadyBeenFound(MethodDefinition method)
{
return !foundMethods.TryAdd(method, 0);
}
} }
} }

43
ILSpy/TreeNodes/Analyzer/AnalyzedPropertyAccessorsTreeNode.cs → ILSpy/TreeNodes/Analyzer/AnalyzedPropertyAccessorTreeNode.cs

@ -21,50 +21,19 @@ using Mono.Cecil;
namespace ICSharpCode.ILSpy.TreeNodes.Analyzer namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
{ {
internal sealed class AnalyzedPropertyAccessorsTreeNode : AnalyzerTreeNode internal class AnalyzedPropertyAccessorTreeNode : AnalyzedMethodTreeNode
{ {
public AnalyzedPropertyAccessorsTreeNode(PropertyDefinition analyzedProperty) private readonly string name;
{
if (analyzedProperty == null)
throw new ArgumentNullException("analyzedProperty");
if (analyzedProperty.GetMethod != null)
this.Children.Add(new AnalyzedPropertyAccessorTreeNode(analyzedProperty.GetMethod, "get"));
if (analyzedProperty.SetMethod != null)
this.Children.Add(new AnalyzedPropertyAccessorTreeNode(analyzedProperty.SetMethod, "set"));
foreach (var accessor in analyzedProperty.OtherMethods)
this.Children.Add(new AnalyzedPropertyAccessorTreeNode(accessor, null));
}
public override object Icon public AnalyzedPropertyAccessorTreeNode(MethodDefinition analyzedMethod, string name)
: base(analyzedMethod)
{ {
get { return Images.Search; } this.name = name;
} }
public override object Text public override object Text
{ {
get { return "Accessors"; } get { return name ?? base.Text; }
}
public static bool CanShow(PropertyDefinition property)
{
return !MainWindow.Instance.CurrentLanguage.ShowMember(property.GetMethod ?? property.SetMethod);
}
private class AnalyzedPropertyAccessorTreeNode : AnalyzedMethodTreeNode
{
private readonly string name;
public AnalyzedPropertyAccessorTreeNode(MethodDefinition analyzedMethod, string name)
: base(analyzedMethod)
{
this.name = name;
}
public override object Text
{
get { return name ?? base.Text; }
}
} }
} }
} }

40
ILSpy/TreeNodes/Analyzer/AnalyzedPropertyOverridesTreeNode.cs

@ -69,45 +69,27 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
private IEnumerable<SharpTreeNode> FetchChildren(CancellationToken ct) private IEnumerable<SharpTreeNode> FetchChildren(CancellationToken ct)
{ {
return FindReferences(MainWindow.Instance.CurrentAssemblyList.GetAssemblies(), ct); ScopedWhereUsedAnalyzer<SharpTreeNode> analyzer;
}
private IEnumerable<SharpTreeNode> FindReferences(IEnumerable<LoadedAssembly> assemblies, CancellationToken ct)
{
assemblies = assemblies.Where(asm => asm.AssemblyDefinition != null);
// use parallelism only on the assembly level (avoid locks within Cecil) analyzer = new ScopedWhereUsedAnalyzer<SharpTreeNode>(analyzedProperty, FindReferencesInType);
return assemblies.AsParallel().WithCancellation(ct).SelectMany((LoadedAssembly asm) => FindReferences(asm, ct)); return analyzer.PerformAnalysis(ct);
} }
private IEnumerable<SharpTreeNode> FindReferences(LoadedAssembly asm, CancellationToken ct) private IEnumerable<SharpTreeNode> FindReferencesInType(TypeDefinition type)
{ {
string asmName = asm.AssemblyDefinition.Name.Name;
string name = analyzedProperty.Name; string name = analyzedProperty.Name;
string declTypeName = analyzedProperty.DeclaringType.FullName; string declTypeName = analyzedProperty.DeclaringType.FullName;
foreach (TypeDefinition type in TreeTraversal.PreOrder(asm.AssemblyDefinition.MainModule.Types, t => t.NestedTypes)) {
ct.ThrowIfCancellationRequested();
SharpTreeNode newNode = null; if (!TypesHierarchyHelpers.IsBaseType(analyzedProperty.DeclaringType, type, resolveTypeArguments: false))
try { yield break;
if (!TypesHierarchyHelpers.IsBaseType(analyzedProperty.DeclaringType, type, resolveTypeArguments: false))
continue;
foreach (PropertyDefinition property in type.Properties) { foreach (PropertyDefinition property in type.Properties) {
ct.ThrowIfCancellationRequested();
if (TypesHierarchyHelpers.IsBaseProperty(analyzedProperty, property)) { if (TypesHierarchyHelpers.IsBaseProperty(analyzedProperty, property)) {
MethodDefinition anyAccessor = property.GetMethod ?? property.SetMethod; MethodDefinition anyAccessor = property.GetMethod ?? property.SetMethod;
bool hidesParent = !anyAccessor.IsVirtual ^ anyAccessor.IsNewSlot; bool hidesParent = !anyAccessor.IsVirtual ^ anyAccessor.IsNewSlot;
newNode = new AnalyzedPropertyTreeNode(property, hidesParent ? "(hides) " : ""); yield return new AnalyzedPropertyTreeNode(property, hidesParent ? "(hides) " : "");
}
}
}
catch (ReferenceResolvingException) {
// ignore this type definition.
} }
if (newNode != null)
yield return newNode;
} }
} }

13
ILSpy/TreeNodes/Analyzer/AnalyzedPropertyTreeNode.cs

@ -60,8 +60,13 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
protected override void LoadChildren() protected override void LoadChildren()
{ {
if (AnalyzedPropertyAccessorsTreeNode.CanShow(analyzedProperty)) if (analyzedProperty.GetMethod != null)
this.Children.Add(new AnalyzedPropertyAccessorsTreeNode(analyzedProperty)); this.Children.Add(new AnalyzedPropertyAccessorTreeNode(analyzedProperty.GetMethod, "get"));
if (analyzedProperty.SetMethod != null)
this.Children.Add(new AnalyzedPropertyAccessorTreeNode(analyzedProperty.SetMethod, "set"));
foreach (var accessor in analyzedProperty.OtherMethods)
this.Children.Add(new AnalyzedPropertyAccessorTreeNode(accessor, null));
if (AnalyzedPropertyOverridesTreeNode.CanShow(analyzedProperty)) if (AnalyzedPropertyOverridesTreeNode.CanShow(analyzedProperty))
this.Children.Add(new AnalyzedPropertyOverridesTreeNode(analyzedProperty)); this.Children.Add(new AnalyzedPropertyOverridesTreeNode(analyzedProperty));
if (AnalyzedInterfacePropertyImplementedByTreeNode.CanShow(analyzedProperty)) if (AnalyzedInterfacePropertyImplementedByTreeNode.CanShow(analyzedProperty))
@ -82,8 +87,8 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
if (property == null) if (property == null)
return false; return false;
return AnalyzedPropertyAccessorsTreeNode.CanShow(property) return !MainWindow.Instance.CurrentLanguage.ShowMember(property.GetMethod ?? property.SetMethod)
|| AnalyzedPropertyOverridesTreeNode.CanShow(property); || AnalyzedPropertyOverridesTreeNode.CanShow(property);
} }
} }
} }

4
ILSpy/TreeNodes/Analyzer/AnalyzedTypeExposedByTreeNode.cs

@ -65,9 +65,9 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
private IEnumerable<SharpTreeNode> FetchChildren(CancellationToken ct) private IEnumerable<SharpTreeNode> FetchChildren(CancellationToken ct)
{ {
ScopedWhereUsedScopeAnalyzer<SharpTreeNode> analyzer; ScopedWhereUsedAnalyzer<SharpTreeNode> analyzer;
analyzer = new ScopedWhereUsedScopeAnalyzer<SharpTreeNode>(analyzedType, FindReferencesInType); analyzer = new ScopedWhereUsedAnalyzer<SharpTreeNode>(analyzedType, FindReferencesInType);
return analyzer.PerformAnalysis(ct); return analyzer.PerformAnalysis(ct);
} }

4
ILSpy/TreeNodes/Analyzer/AnalyzedTypeExtensionMethodsTreeNode.cs

@ -66,9 +66,9 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
private IEnumerable<SharpTreeNode> FetchChildren(CancellationToken ct) private IEnumerable<SharpTreeNode> FetchChildren(CancellationToken ct)
{ {
ScopedWhereUsedScopeAnalyzer<SharpTreeNode> analyzer; ScopedWhereUsedAnalyzer<SharpTreeNode> analyzer;
analyzer = new ScopedWhereUsedScopeAnalyzer<SharpTreeNode>(analyzedType, FindReferencesInType); analyzer = new ScopedWhereUsedAnalyzer<SharpTreeNode>(analyzedType, FindReferencesInType);
return analyzer.PerformAnalysis(ct); return analyzer.PerformAnalysis(ct);
} }

4
ILSpy/TreeNodes/Analyzer/AnalyzedTypeInstantiationsTreeNode.cs

@ -71,9 +71,9 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
private IEnumerable<SharpTreeNode> FetchChildren(CancellationToken ct) private IEnumerable<SharpTreeNode> FetchChildren(CancellationToken ct)
{ {
ScopedWhereUsedScopeAnalyzer<SharpTreeNode> analyzer; ScopedWhereUsedAnalyzer<SharpTreeNode> analyzer;
analyzer = new ScopedWhereUsedScopeAnalyzer<SharpTreeNode>(analyzedType, FindReferencesInType); analyzer = new ScopedWhereUsedAnalyzer<SharpTreeNode>(analyzedType, FindReferencesInType);
return analyzer.PerformAnalysis(ct); return analyzer.PerformAnalysis(ct);
} }

151
ILSpy/TreeNodes/Analyzer/AnalyzedVirtualMethodUsedByTreeNode.cs

@ -0,0 +1,151 @@
// Copyright (c) 2011 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using ICSharpCode.TreeView;
using Mono.Cecil;
using Mono.Cecil.Cil;
using ICSharpCode.Decompiler.Ast;
namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
{
internal sealed class AnalyzedVirtualMethodUsedByTreeNode : AnalyzerTreeNode
{
private readonly MethodDefinition analyzedMethod;
private readonly ThreadingSupport threading;
private ConcurrentDictionary<MethodDefinition, int> foundMethods;
private MethodDefinition baseMethod;
private List<TypeReference> possibleTypes;
public AnalyzedVirtualMethodUsedByTreeNode(MethodDefinition analyzedMethod)
{
if (analyzedMethod == null)
throw new ArgumentNullException("analyzedMethod");
this.analyzedMethod = analyzedMethod;
this.threading = new ThreadingSupport();
this.LazyLoading = true;
}
public override object Text
{
get { return "Used By"; }
}
public override object Icon
{
get { return Images.Search; }
}
protected override void LoadChildren()
{
threading.LoadChildren(this, FetchChildren);
}
protected override void OnCollapsing()
{
if (threading.IsRunning) {
this.LazyLoading = true;
threading.Cancel();
this.Children.Clear();
}
}
private IEnumerable<SharpTreeNode> FetchChildren(CancellationToken ct)
{
InitializeAnalyzer();
var analyzer = new ScopedWhereUsedAnalyzer<SharpTreeNode>(analyzedMethod, FindReferencesInType);
foreach (var child in analyzer.PerformAnalysis(ct)) {
yield return child;
}
ReleaseAnalyzer();
}
private void InitializeAnalyzer()
{
foundMethods = new ConcurrentDictionary<MethodDefinition, int>();
var BaseMethods = TypesHierarchyHelpers.FindBaseMethods(analyzedMethod).ToArray();
if (BaseMethods.Length > 0) {
baseMethod = BaseMethods[BaseMethods.Length - 1];
}
possibleTypes = new List<TypeReference>();
TypeReference type = analyzedMethod.DeclaringType.BaseType;
while (type !=null)
{
possibleTypes.Add(type);
type = type.Resolve().BaseType;
}
}
private void ReleaseAnalyzer()
{
foundMethods = null;
baseMethod = null;
}
private IEnumerable<SharpTreeNode> FindReferencesInType(TypeDefinition type)
{
string name = analyzedMethod.Name;
foreach (MethodDefinition method in type.Methods) {
bool found = false;
string prefix = string.Empty;
if (!method.HasBody)
continue;
foreach (Instruction instr in method.Body.Instructions) {
MethodReference mr = instr.Operand as MethodReference;
if (mr != null && mr.Name == name) {
// explicit call to the requested method
if (Helpers.IsReferencedBy(analyzedMethod.DeclaringType, mr.DeclaringType) && mr.Resolve() == analyzedMethod) {
found = true;
prefix = "(as base) ";
break;
}
// virtual call to base method
if (instr.OpCode.Code == Code.Callvirt && Helpers.IsReferencedBy(baseMethod.DeclaringType, mr.DeclaringType) && mr.Resolve() == baseMethod) {
found = true;
break;
}
}
}
method.Body = null;
if (found) {
MethodDefinition codeLocation = this.Language.GetOriginalCodeLocation(method) as MethodDefinition;
if (codeLocation != null && !HasAlreadyBeenFound(codeLocation)) {
yield return new AnalyzedMethodTreeNode(codeLocation, prefix);
}
}
}
}
private bool HasAlreadyBeenFound(MethodDefinition method)
{
return !foundMethods.TryAdd(method, 0);
}
}
}

63
ILSpy/TreeNodes/Analyzer/Helpers.cs

@ -20,7 +20,10 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using ICSharpCode.Decompiler;
using Mono.Cecil; using Mono.Cecil;
using ICSharpCode.Decompiler.ILAst;
using Mono.Cecil.Cil;
namespace ICSharpCode.ILSpy.TreeNodes.Analyzer namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
{ {
@ -50,5 +53,65 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
return true; return true;
} }
public static MemberReference GetOriginalCodeLocation(MemberReference member)
{
if (member is MethodDefinition)
return GetOriginalCodeLocation((MethodDefinition)member);
return member;
}
public static MethodDefinition GetOriginalCodeLocation(MethodDefinition method)
{
if (method.IsCompilerGenerated()) {
return FindMethodUsageInType(method.DeclaringType, method) ?? method;
}
var typeUsage = GetOriginalCodeLocation(method.DeclaringType, method);
return typeUsage ?? method;
}
public static MethodDefinition GetOriginalCodeLocation(TypeDefinition type, MethodDefinition method)
{
if (type != null && type.DeclaringType != null && type.IsCompilerGenerated()) {
MethodDefinition constructor = GetTypeConstructor(type);
return FindMethodUsageInType(type.DeclaringType, constructor);
}
return null;
}
private static MethodDefinition GetTypeConstructor(TypeDefinition type)
{
foreach (MethodDefinition method in type.Methods) {
if (method.Name == ".ctor")
return method;
}
return null;
}
private static MethodDefinition FindMethodUsageInType(TypeDefinition type, MethodDefinition analyzedMethod)
{
string name = analyzedMethod.Name;
foreach (MethodDefinition method in type.Methods) {
bool found = false;
if (!method.HasBody)
continue;
foreach (Instruction instr in method.Body.Instructions) {
MethodReference mr = instr.Operand as MethodReference;
if (mr != null && mr.Name == name &&
Helpers.IsReferencedBy(analyzedMethod.DeclaringType, mr.DeclaringType) &&
mr.Resolve() == analyzedMethod) {
found = true;
break;
}
}
method.Body = null;
if (found)
return method;
}
return null;
}
} }
} }

89
ILSpy/TreeNodes/Analyzer/ScopedWhereUsedAnalyzer.cs

@ -28,7 +28,7 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
/// <summary> /// <summary>
/// Determines the accessibility domain of a member for where-used analysis. /// Determines the accessibility domain of a member for where-used analysis.
/// </summary> /// </summary>
internal class ScopedWhereUsedScopeAnalyzer<T> internal class ScopedWhereUsedAnalyzer<T>
{ {
private AssemblyDefinition assemblyScope; private AssemblyDefinition assemblyScope;
private TypeDefinition typeScope; private TypeDefinition typeScope;
@ -37,40 +37,36 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
private Accessibility typeAccessibility = Accessibility.Public; private Accessibility typeAccessibility = Accessibility.Public;
private Func<TypeDefinition, IEnumerable<T>> typeAnalysisFunction; private Func<TypeDefinition, IEnumerable<T>> typeAnalysisFunction;
public ScopedWhereUsedScopeAnalyzer(TypeDefinition type, Func<TypeDefinition, IEnumerable<T>> typeAnalysisFunction) public ScopedWhereUsedAnalyzer(TypeDefinition type, Func<TypeDefinition, IEnumerable<T>> typeAnalysisFunction)
{ {
this.typeScope = type; this.typeScope = type;
this.assemblyScope = type.Module.Assembly; this.assemblyScope = type.Module.Assembly;
this.typeAnalysisFunction = typeAnalysisFunction; this.typeAnalysisFunction = typeAnalysisFunction;
} }
public ScopedWhereUsedScopeAnalyzer(MethodDefinition method, Func<TypeDefinition, IEnumerable<T>> typeAnalysisFunction) public ScopedWhereUsedAnalyzer(MethodDefinition method, Func<TypeDefinition, IEnumerable<T>> typeAnalysisFunction)
: this(method.DeclaringType, typeAnalysisFunction) : this(method.DeclaringType, typeAnalysisFunction)
{ {
switch (method.Attributes & MethodAttributes.MemberAccessMask) { this.memberAccessibility = GetMethodAccessibility(method);
case MethodAttributes.Private: }
default:
memberAccessibility = Accessibility.Private; public ScopedWhereUsedAnalyzer(PropertyDefinition property, Func<TypeDefinition, IEnumerable<T>> typeAnalysisFunction)
break; : this(property.DeclaringType, typeAnalysisFunction)
case MethodAttributes.FamANDAssem: {
memberAccessibility = Accessibility.FamilyAndInternal; Accessibility getterAccessibility = (property.GetMethod == null) ? Accessibility.Private : GetMethodAccessibility(property.GetMethod);
break; Accessibility setterAccessibility = (property.SetMethod == null) ? Accessibility.Private : GetMethodAccessibility(property.SetMethod);
case MethodAttributes.Family: this.memberAccessibility = (Accessibility)Math.Max((int)getterAccessibility, (int)setterAccessibility);
memberAccessibility = Accessibility.Family;
break;
case MethodAttributes.Assembly:
memberAccessibility = Accessibility.Internal;
break;
case MethodAttributes.FamORAssem:
memberAccessibility = Accessibility.FamilyOrInternal;
break;
case MethodAttributes.Public:
memberAccessibility = Accessibility.Public;
break;
}
} }
public ScopedWhereUsedScopeAnalyzer(FieldDefinition field, Func<TypeDefinition, IEnumerable<T>> typeAnalysisFunction) public ScopedWhereUsedAnalyzer(EventDefinition eventDef, Func<TypeDefinition, IEnumerable<T>> typeAnalysisFunction)
: this(eventDef.DeclaringType, typeAnalysisFunction)
{
// we only have to check the accessibility of the the get method
// [CLS Rule 30: The accessibility of an event and of its accessors shall be identical.]
this.memberAccessibility = GetMethodAccessibility(eventDef.AddMethod);
}
public ScopedWhereUsedAnalyzer(FieldDefinition field, Func<TypeDefinition, IEnumerable<T>> typeAnalysisFunction)
: this(field.DeclaringType, typeAnalysisFunction) : this(field.DeclaringType, typeAnalysisFunction)
{ {
switch (field.Attributes & FieldAttributes.FieldAccessMask) { switch (field.Attributes & FieldAttributes.FieldAccessMask) {
@ -96,6 +92,33 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
} }
} }
private Accessibility GetMethodAccessibility(MethodDefinition method)
{
Accessibility accessibility;
switch (method.Attributes & MethodAttributes.MemberAccessMask) {
case MethodAttributes.Private:
default:
accessibility = Accessibility.Private;
break;
case MethodAttributes.FamANDAssem:
accessibility = Accessibility.FamilyAndInternal;
break;
case MethodAttributes.Family:
accessibility = Accessibility.Family;
break;
case MethodAttributes.Assembly:
accessibility = Accessibility.Internal;
break;
case MethodAttributes.FamORAssem:
accessibility = Accessibility.FamilyOrInternal;
break;
case MethodAttributes.Public:
accessibility = Accessibility.Public;
break;
}
return accessibility;
}
public IEnumerable<T> PerformAnalysis(CancellationToken ct) public IEnumerable<T> PerformAnalysis(CancellationToken ct)
{ {
if (memberAccessibility == Accessibility.Private) { if (memberAccessibility == Accessibility.Private) {
@ -231,7 +254,7 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
break; break;
} }
} }
if (found) if (found && AssemblyReferencesScopeType(assembly.AssemblyDefinition))
yield return assembly.AssemblyDefinition; yield return assembly.AssemblyDefinition;
} }
} }
@ -255,12 +278,24 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
foreach (var assembly in assemblies) { foreach (var assembly in assemblies) {
ct.ThrowIfCancellationRequested(); ct.ThrowIfCancellationRequested();
if (friendAssemblies.Contains(assembly.ShortName)) { if (friendAssemblies.Contains(assembly.ShortName) && AssemblyReferencesScopeType(assembly.AssemblyDefinition)) {
yield return assembly.AssemblyDefinition; yield return assembly.AssemblyDefinition;
} }
} }
} }
} }
} }
private bool AssemblyReferencesScopeType(AssemblyDefinition asm)
{
bool hasRef = false;
foreach (var typeref in asm.MainModule.GetTypeReferences()) {
if (typeref.Name == typeScope.Name && typeref.Namespace == typeScope.Namespace) {
hasRef = true;
break;
}
}
return hasRef;
}
} }
} }

15
ILSpy/TreeNodes/TypeTreeNode.cs

@ -150,8 +150,10 @@ namespace ICSharpCode.ILSpy.TreeNodes
} else { } else {
if (type.IsInterface) if (type.IsInterface)
return TypeIcon.Interface; return TypeIcon.Interface;
else if (type.BaseType != null && type.BaseType.FullName == typeof(MulticastDelegate).FullName) else if (IsDelegate(type))
return TypeIcon.Delegate; return TypeIcon.Delegate;
else if (IsStaticClass(type))
return TypeIcon.StaticClass;
else else
return TypeIcon.Class; return TypeIcon.Class;
} }
@ -182,6 +184,17 @@ namespace ICSharpCode.ILSpy.TreeNodes
} }
return overlay; return overlay;
} }
private static bool IsDelegate(TypeDefinition type)
{
return type.BaseType != null && type.BaseType.FullName == typeof(MulticastDelegate).FullName;
}
private static bool IsStaticClass(TypeDefinition type)
{
return type.IsSealed && type.IsAbstract;
}
#endregion #endregion
MemberReference IMemberTreeNode.Member { MemberReference IMemberTreeNode.Member {

Loading…
Cancel
Save