Browse Source

Analyzer: Redirect result from compiler-generated type/method to original code location.

pull/170/head
Ed Harvey 15 years ago
parent
commit
4e95f435a4
  1. 34
      ILSpy/CSharpLanguage.cs
  2. 27
      ILSpy/Language.cs
  3. 32
      ILSpy/TreeNodes/Analyzer/AnalyzedFieldAccessTreeNode.cs
  4. 37
      ILSpy/TreeNodes/Analyzer/AnalyzedMethodUsedByTreeNode.cs
  5. 64
      ILSpy/TreeNodes/Analyzer/Helpers.cs

34
ILSpy/CSharpLanguage.cs

@ -51,7 +51,7 @@ namespace ICSharpCode.ILSpy
{ {
} }
#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));
@ -70,17 +70,20 @@ 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"; }
} }
@ -286,7 +289,7 @@ namespace ICSharpCode.ILSpy
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;
@ -301,7 +304,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) {
@ -329,7 +332,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) {
@ -347,7 +351,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"));
@ -368,7 +373,8 @@ 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);
} }
@ -466,6 +472,14 @@ namespace ICSharpCode.ILSpy
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;

27
ILSpy/Language.cs

@ -41,15 +41,18 @@ namespace ICSharpCode.ILSpy
/// </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);
} }
} }
@ -137,6 +140,14 @@ namespace ICSharpCode.ILSpy
{ {
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
@ -146,8 +157,10 @@ namespace ICSharpCode.ILSpy
/// <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;
} }
} }
@ -158,10 +171,10 @@ namespace ICSharpCode.ILSpy
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();
} }

32
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)
{ {
foundMethods = new Lazy<Hashtable>(LazyThreadSafetyMode.ExecutionAndPublication);
var analyzer = new ScopedWhereUsedScopeAnalyzer<SharpTreeNode>(analyzedField, FindReferencesInType); var analyzer = new ScopedWhereUsedScopeAnalyzer<SharpTreeNode>(analyzedField, 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)
@ -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;
}
}
}
} }
} }

37
ILSpy/TreeNodes/Analyzer/AnalyzedMethodUsedByTreeNode.cs

@ -17,6 +17,7 @@
// DEALINGS IN THE SOFTWARE. // DEALINGS IN THE SOFTWARE.
using System; using System;
using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading; using System.Threading;
using ICSharpCode.TreeView; using ICSharpCode.TreeView;
@ -29,6 +30,8 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
{ {
private readonly MethodDefinition analyzedMethod; private readonly MethodDefinition analyzedMethod;
private readonly ThreadingSupport threading; private readonly ThreadingSupport threading;
private Lazy<Hashtable> foundMethods;
private object hashLock = new object();
public AnalyzedMethodUsedByTreeNode(MethodDefinition analyzedMethod) public AnalyzedMethodUsedByTreeNode(MethodDefinition analyzedMethod)
{ {
@ -66,10 +69,14 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
private IEnumerable<SharpTreeNode> FetchChildren(CancellationToken ct) private IEnumerable<SharpTreeNode> FetchChildren(CancellationToken ct)
{ {
ScopedWhereUsedScopeAnalyzer<SharpTreeNode> analyzer; foundMethods = new Lazy<Hashtable>(LazyThreadSafetyMode.ExecutionAndPublication);
analyzer = new ScopedWhereUsedScopeAnalyzer<SharpTreeNode>(analyzedMethod, FindReferencesInType); var analyzer = new ScopedWhereUsedScopeAnalyzer<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 +88,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,8 +98,25 @@ 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)
{
Hashtable hashtable = foundMethods.Value;
lock (hashLock) {
if (hashtable.Contains(method)) {
return true;
} else {
hashtable.Add(method, null);
return false;
}
} }
} }
} }

64
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,66 @@ 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.Name.StartsWith("<", StringComparison.Ordinal) && method.IsCompilerGenerated()) {
return FindMethodUsageInType(method.DeclaringType, 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.Name.StartsWith("<", StringComparison.Ordinal) && 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;
}
} }
} }

Loading…
Cancel
Save