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. 110
      ILSpy/CSharpLanguage.cs
  2. 69
      ILSpy/Language.cs
  3. 32
      ILSpy/TreeNodes/Analyzer/AnalyzedFieldAccessTreeNode.cs
  4. 37
      ILSpy/TreeNodes/Analyzer/AnalyzedMethodUsedByTreeNode.cs
  5. 64
      ILSpy/TreeNodes/Analyzer/Helpers.cs

110
ILSpy/CSharpLanguage.cs

@ -46,12 +46,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));
@ -70,20 +70,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.RunTransformations(transformAbortCondition); codeDomBuilder.RunTransformations(transformAbortCondition);
codeDomBuilder.GenerateCode(output); codeDomBuilder.GenerateCode(output);
} }
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));
@ -101,7 +104,7 @@ namespace ICSharpCode.ILSpy
codeDomBuilder.RunTransformations(transformAbortCondition); codeDomBuilder.RunTransformations(transformAbortCondition);
codeDomBuilder.GenerateCode(output); codeDomBuilder.GenerateCode(output);
} }
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));
@ -110,7 +113,7 @@ namespace ICSharpCode.ILSpy
codeDomBuilder.RunTransformations(transformAbortCondition); codeDomBuilder.RunTransformations(transformAbortCondition);
codeDomBuilder.GenerateCode(output); codeDomBuilder.GenerateCode(output);
} }
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));
@ -119,7 +122,7 @@ namespace ICSharpCode.ILSpy
codeDomBuilder.RunTransformations(transformAbortCondition); codeDomBuilder.RunTransformations(transformAbortCondition);
codeDomBuilder.GenerateCode(output); codeDomBuilder.GenerateCode(output);
} }
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);
@ -127,7 +130,7 @@ namespace ICSharpCode.ILSpy
codeDomBuilder.RunTransformations(transformAbortCondition); codeDomBuilder.RunTransformations(transformAbortCondition);
codeDomBuilder.GenerateCode(output); codeDomBuilder.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) {
@ -146,7 +149,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)
{ {
@ -174,20 +177,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");
@ -199,7 +202,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:
@ -218,14 +221,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\\");
@ -233,7 +236,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\\");
@ -241,8 +244,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") {
@ -253,7 +256,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)) {
@ -263,16 +266,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)
{ {
@ -282,11 +285,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;
@ -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) {
@ -315,7 +318,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)
{ {
@ -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,12 +373,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('.');
@ -389,7 +395,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)
@ -413,7 +419,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;
@ -421,11 +427,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();
} }
@ -460,12 +466,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;
@ -486,12 +500,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);
} }
} }

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.

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