Browse Source

Merge branch 'master' of git://github.com/icsharpcode/ILSpy

Conflicts:
	ICSharpCode.Decompiler/ICSharpCode.Decompiler.csproj
	ILSpy.SharpDevelop.LGPL/ILSpy.SharpDevelop.LGPL.csproj
pull/205/head
Pent Ploompuu 15 years ago
parent
commit
d2488a497e
  1. 5
      AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/VBNET-Mode.xshd
  2. 11
      Debugger/ILSpy.Debugger/Commands/DebuggerCommands.cs
  3. 5
      Debugger/ILSpy.Debugger/ILSpy.Debugger.csproj
  4. 15
      ICSharpCode.Decompiler/Ast/Annotations.cs
  5. 30
      ICSharpCode.Decompiler/Ast/AstMethodBodyBuilder.cs
  6. 9
      ICSharpCode.Decompiler/Ast/TextOutputFormatter.cs
  7. 6
      ICSharpCode.Decompiler/Ast/Transforms/IntroduceExtensionMethods.cs
  8. 9
      ICSharpCode.Decompiler/Ast/Transforms/ReplaceMethodCallsWithOperators.cs
  9. 2
      ICSharpCode.Decompiler/Ast/Transforms/TransformationPipeline.cs
  10. 8
      ICSharpCode.Decompiler/CecilExtensions.cs
  11. 27
      ICSharpCode.Decompiler/CodeMappings.cs
  12. 32
      ICSharpCode.Decompiler/DecompilerSettings.cs
  13. 2
      ICSharpCode.Decompiler/FlowAnalysis/SsaFormBuilder.cs
  14. 1
      ICSharpCode.Decompiler/ICSharpCode.Decompiler.csproj
  15. 23
      ICSharpCode.Decompiler/ILAst/ILAstBuilder.cs
  16. 8
      ICSharpCode.Decompiler/ILAst/ILAstOptimizer.cs
  17. 2
      ICSharpCode.Decompiler/ILAst/YieldReturnDecompiler.cs
  18. 6
      ILSpy.BamlDecompiler/BamlResourceNodeFactory.cs
  19. 2
      ILSpy.BamlDecompiler/ConnectMethodDecompiler.cs
  20. 20
      ILSpy.SharpDevelop.LGPL/ILSpy.SharpDevelop.LGPL.csproj
  21. 18
      ILSpy.sln
  22. 34
      ILSpy/AnalyzerTreeView.cs
  23. 14
      ILSpy/AssemblyList.cs
  24. 26
      ILSpy/Controls/ResourceStringTable.xaml
  25. 51
      ILSpy/Controls/ResourceStringTable.xaml.cs
  26. 22
      ILSpy/ILSpy.csproj
  27. 4
      ILSpy/Languages/ILAstLanguage.cs
  28. 16
      ILSpy/MainWindow.xaml.cs
  29. 228
      ILSpy/SearchPane.cs
  30. 2
      ILSpy/TextView/DecompilerTextView.cs
  31. 28
      ILSpy/TreeNodes/Analyzer/AnalyzedEventFiredByTreeNode.cs
  32. 32
      ILSpy/TreeNodes/Analyzer/AnalyzedEventOverridesTreeNode.cs
  33. 12
      ILSpy/TreeNodes/Analyzer/AnalyzedEventTreeNode.cs
  34. 32
      ILSpy/TreeNodes/Analyzer/AnalyzedFieldAccessTreeNode.cs
  35. 11
      ILSpy/TreeNodes/Analyzer/AnalyzedFieldTreeNode.cs
  36. 31
      ILSpy/TreeNodes/Analyzer/AnalyzedInterfaceEventImplementedByTreeNode.cs
  37. 31
      ILSpy/TreeNodes/Analyzer/AnalyzedInterfaceMethodImplementedByTreeNode.cs
  38. 31
      ILSpy/TreeNodes/Analyzer/AnalyzedInterfacePropertyImplementedByTreeNode.cs
  39. 32
      ILSpy/TreeNodes/Analyzer/AnalyzedMethodOverridesTreeNode.cs
  40. 11
      ILSpy/TreeNodes/Analyzer/AnalyzedMethodTreeNode.cs
  41. 30
      ILSpy/TreeNodes/Analyzer/AnalyzedMethodUsedByTreeNode.cs
  42. 19
      ILSpy/TreeNodes/Analyzer/AnalyzedMethodUsesTreeNode.cs
  43. 32
      ILSpy/TreeNodes/Analyzer/AnalyzedPropertyOverridesTreeNode.cs
  44. 12
      ILSpy/TreeNodes/Analyzer/AnalyzedPropertyTreeNode.cs
  45. 32
      ILSpy/TreeNodes/Analyzer/AnalyzedTypeExposedByTreeNode.cs
  46. 32
      ILSpy/TreeNodes/Analyzer/AnalyzedTypeExtensionMethodsTreeNode.cs
  47. 32
      ILSpy/TreeNodes/Analyzer/AnalyzedTypeInstantiationsTreeNode.cs
  48. 11
      ILSpy/TreeNodes/Analyzer/AnalyzedTypeTreeNode.cs
  49. 30
      ILSpy/TreeNodes/Analyzer/AnalyzedVirtualMethodUsedByTreeNode.cs
  50. 53
      ILSpy/TreeNodes/Analyzer/AnalyzerEntityTreeNode.cs
  51. 67
      ILSpy/TreeNodes/Analyzer/AnalyzerSearchTreeNode.cs
  52. 11
      ILSpy/TreeNodes/Analyzer/AnalyzerTreeNode.cs
  53. 15
      ILSpy/TreeNodes/Analyzer/ScopedWhereUsedAnalyzer.cs
  54. 15
      ILSpy/TreeNodes/ResourceNodes/CursorResourceEntryNode.cs
  55. 2
      ILSpy/TreeNodes/ResourceNodes/IResourceNodeFactory.cs
  56. 18
      ILSpy/TreeNodes/ResourceNodes/ImageResourceEntryNode.cs
  57. 4
      ILSpy/TreeNodes/ResourceNodes/ResourceEntryNode.cs
  58. 31
      ILSpy/TreeNodes/ResourceNodes/ResourcesFileTreeNode.cs
  59. 6
      ILSpy/TreeNodes/ResourceNodes/XamlResourceNode.cs
  60. 10
      ILSpy/TreeNodes/ResourceNodes/XmlResourceNode.cs
  61. 2
      ILSpy/TreeNodes/ThreadingSupport.cs
  62. 152
      ILSpy/VB/ILSpyEnvironmentProvider.cs
  63. 523
      ILSpy/VB/VBLanguage.cs
  64. 153
      ILSpy/VB/VBTextOutputFormatter.cs
  65. 1
      Mono.Cecil/.gitignore
  66. 29
      Mono.Cecil/Mono.Cecil.PE/ByteBuffer.cs
  67. 3
      Mono.Cecil/Mono.Cecil.PE/ImageReader.cs
  68. 2
      Mono.Cecil/Mono.Cecil.nuspec
  69. 4
      Mono.Cecil/Mono.Cecil/AssemblyInfo.cs
  70. 32
      Mono.Cecil/Mono.Cecil/AssemblyReader.cs
  71. 14
      Mono.Cecil/Mono.Cecil/AssemblyWriter.cs
  72. 12
      Mono.Cecil/Mono.Cecil/BaseAssemblyResolver.cs
  73. 12
      Mono.Cecil/Mono.Cecil/MetadataResolver.cs
  74. 20
      Mono.Cecil/Mono.Cecil/ModuleDefinition.cs
  75. 9
      Mono.Cecil/Mono.Cecil/ParameterDefinition.cs
  76. 8
      Mono.Cecil/Mono/Empty.cs
  77. 9
      Mono.Cecil/Test/Mono.Cecil.Tests/FieldTests.cs
  78. 20
      Mono.Cecil/Test/Mono.Cecil.Tests/SecurityDeclarationTests.cs
  79. BIN
      Mono.Cecil/Test/Resources/assemblies/empty-decsec-att.dll
  80. 4
      Mono.Cecil/rocks/Mono.Cecil.Rocks/AssemblyInfo.cs
  81. 4
      Mono.Cecil/symbols/mdb/Mono.Cecil.Mdb/AssemblyInfo.cs
  82. 4
      Mono.Cecil/symbols/pdb/Mono.Cecil.Pdb/AssemblyInfo.cs
  83. 39
      NRefactory/ICSharpCode.NRefactory.VB/Ast/AstNode.cs
  84. 67
      NRefactory/ICSharpCode.NRefactory.VB/Ast/Comment.cs
  85. 221
      NRefactory/ICSharpCode.NRefactory.VB/Ast/Enums.cs
  86. 41
      NRefactory/ICSharpCode.NRefactory.VB/Ast/Expressions/AnonymousObjectCreationExpression.cs
  87. 64
      NRefactory/ICSharpCode.NRefactory.VB/Ast/Expressions/ArrayCreateExpression.cs
  88. 53
      NRefactory/ICSharpCode.NRefactory.VB/Ast/Expressions/ArrayInitializerExpression.cs
  89. 44
      NRefactory/ICSharpCode.NRefactory.VB/Ast/Expressions/AssignmentExpression.cs
  90. 110
      NRefactory/ICSharpCode.NRefactory.VB/Ast/Expressions/BinaryOperatorExpression.cs
  91. 95
      NRefactory/ICSharpCode.NRefactory.VB/Ast/Expressions/CastExpression.cs
  92. 42
      NRefactory/ICSharpCode.NRefactory.VB/Ast/Expressions/CollectionRangeVariableDeclaration.cs
  93. 44
      NRefactory/ICSharpCode.NRefactory.VB/Ast/Expressions/ConditionalExpression.cs
  94. 59
      NRefactory/ICSharpCode.NRefactory.VB/Ast/Expressions/EmptyExpression.cs
  95. 76
      NRefactory/ICSharpCode.NRefactory.VB/Ast/Expressions/Expression.cs
  96. 49
      NRefactory/ICSharpCode.NRefactory.VB/Ast/Expressions/FieldInitializerExpression.cs
  97. 31
      NRefactory/ICSharpCode.NRefactory.VB/Ast/Expressions/GetTypeExpression.cs
  98. 32
      NRefactory/ICSharpCode.NRefactory.VB/Ast/Expressions/GetXmlNamespaceExpression.cs
  99. 39
      NRefactory/ICSharpCode.NRefactory.VB/Ast/Expressions/IdentifierExpression.cs
  100. 61
      NRefactory/ICSharpCode.NRefactory.VB/Ast/Expressions/InstanceExpression.cs
  101. Some files were not shown because too many files have changed in this diff Show More

5
AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/VBNET-Mode.xshd

@ -4,6 +4,7 @@ @@ -4,6 +4,7 @@
<!-- Updated 2005 by Daniel Grunwald for VB.NET 2.0 -->
<!-- Converted to AvalonEdit format by Daniel Grunwald in 2010 -->
<!-- Updated 2010 by Siegfried Oleg Pammer for VB.NET 9 and 10 -->
<!-- Updated 2011 by Siegfried Oleg Pammer for VB 11 CTP -->
<SyntaxDefinition name="VBNET" extensions=".vb" xmlns="http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008">
<Color name="Comment" foreground="Green" exampleText="' comment" />
<Color name="String" exampleText="text = &quot;Hello, World!&quot;" />
@ -64,6 +65,7 @@ @@ -64,6 +65,7 @@
<Word>AddressOf</Word>
<Word>And</Word>
<Word>AndAlso</Word>
<Word>Await</Word>
<Word>Is</Word>
<Word>IsNot</Word>
<Word>Like</Word>
@ -208,6 +210,7 @@ @@ -208,6 +210,7 @@
<Word>Aggregate</Word>
<Word>Ansi</Word>
<Word>Ascending</Word>
<Word>Async</Word>
<Word>Auto</Word>
<Word>Binary</Word>
<Word>By</Word>
@ -221,6 +224,7 @@ @@ -221,6 +224,7 @@
<Word>Group</Word>
<Word>Infer</Word>
<Word>Into</Word>
<Word>Iterator</Word>
<Word>Join</Word>
<Word>Key</Word>
<Word>Off</Word>
@ -232,6 +236,7 @@ @@ -232,6 +236,7 @@
<Word>Unicode</Word>
<Word>Until</Word>
<Word>Where</Word>
<Word>Yield</Word>
</Keywords>
</RuleSet>
<RuleSet name="PreprocessorSet" ignoreCase="true">

11
Debugger/ILSpy.Debugger/Commands/DebuggerCommands.cs

@ -10,7 +10,6 @@ using System.Windows.Input; @@ -10,7 +10,6 @@ using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Xml.Linq;
using ICSharpCode.AvalonEdit.Document;
using ICSharpCode.ILSpy.Bookmarks;
using ICSharpCode.ILSpy.Debugger;
@ -20,6 +19,7 @@ using ICSharpCode.ILSpy.Debugger.UI; @@ -20,6 +19,7 @@ using ICSharpCode.ILSpy.Debugger.UI;
using ICSharpCode.ILSpy.TreeNodes;
using ICSharpCode.TreeView;
using Microsoft.Win32;
using Mono.Cecil;
namespace ICSharpCode.ILSpy.Debugger.Commands
{
@ -182,7 +182,14 @@ namespace ICSharpCode.ILSpy.Debugger.Commands @@ -182,7 +182,14 @@ namespace ICSharpCode.ILSpy.Debugger.Commands
{
public bool IsVisible(SharpTreeNode[] selectedNodes)
{
return selectedNodes.All(n => n is AssemblyTreeNode && null != (n as AssemblyTreeNode).LoadedAssembly.AssemblyDefinition.EntryPoint);
return selectedNodes.All(
delegate (SharpTreeNode n) {
AssemblyTreeNode a = n as AssemblyTreeNode;
if (a == null)
return false;
AssemblyDefinition asm = a.LoadedAssembly.AssemblyDefinition;
return asm != null && asm.EntryPoint != null;
});
}
public bool IsEnabled(SharpTreeNode[] selectedNodes)

5
Debugger/ILSpy.Debugger/ILSpy.Debugger.csproj

@ -3,7 +3,7 @@ @@ -3,7 +3,7 @@
<PropertyGroup>
<ProjectGuid>{6D3D0F0D-348D-456A-A6ED-E9BD5EFABB6A}</ProjectGuid>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">x86</Platform>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<OutputType>Library</OutputType>
<RootNamespace>ICSharpCode.ILSpy.Debugger</RootNamespace>
<AssemblyName>ILSpy.Debugger.Plugin</AssemblyName>
@ -42,9 +42,6 @@ @@ -42,9 +42,6 @@
<PlatformTarget>AnyCPU</PlatformTarget>
<FileAlignment>4096</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Platform)' == 'x86' ">
<PlatformTarget>x86</PlatformTarget>
</PropertyGroup>
<ItemGroup>
<Reference Include="PresentationCore" />
<Reference Include="PresentationFramework" />

15
ICSharpCode.Decompiler/Ast/Annotations.cs

@ -0,0 +1,15 @@ @@ -0,0 +1,15 @@
using System;
using Mono.Cecil;
namespace ICSharpCode.Decompiler.Ast
{
public class TypeInformation
{
public readonly TypeReference InferredType;
public TypeInformation(TypeReference inferredType)
{
this.InferredType = inferredType;
}
}
}

30
ICSharpCode.Decompiler/Ast/AstMethodBodyBuilder.cs

@ -95,7 +95,7 @@ namespace ICSharpCode.Decompiler.Ast @@ -95,7 +95,7 @@ namespace ICSharpCode.Decompiler.Ast
context.CancellationToken.ThrowIfCancellationRequested();
ILBlock ilMethod = new ILBlock();
ILAstBuilder astBuilder = new ILAstBuilder();
ilMethod.Body = astBuilder.Build(methodDef, true);
ilMethod.Body = astBuilder.Build(methodDef, true, context);
context.CancellationToken.ThrowIfCancellationRequested();
ILAstOptimizer bodyGraph = new ILAstOptimizer();
@ -258,6 +258,9 @@ namespace ICSharpCode.Decompiler.Ast @@ -258,6 +258,9 @@ namespace ICSharpCode.Decompiler.Ast
else
result = node;
if (result != null)
result = result.WithAnnotation(new TypeInformation(expr.InferredType));
if (result != null)
return result.WithAnnotation(ilRanges);
@ -397,7 +400,7 @@ namespace ICSharpCode.Decompiler.Ast @@ -397,7 +400,7 @@ namespace ICSharpCode.Decompiler.Ast
ace.Initializer.Elements.AddRange(args);
return ace;
}
case ILCode.Ldlen: return arg1.Member("Length");
case ILCode.Ldlen: return arg1.Member("Length");
case ILCode.Ldelem_I:
case ILCode.Ldelem_I1:
case ILCode.Ldelem_I2:
@ -918,14 +921,21 @@ namespace ICSharpCode.Decompiler.Ast @@ -918,14 +921,21 @@ namespace ICSharpCode.Decompiler.Ast
target = ((DirectionExpression)target).Expression;
target.Remove(); // detach from DirectionExpression
}
if (cecilMethodDef != null && cecilMethodDef.DeclaringType.IsInterface) {
TypeReference tr = byteCode.Arguments[0].InferredType;
if (tr != null) {
TypeDefinition td = tr.Resolve();
if (td != null && !td.IsInterface) {
// Calling an interface method on a non-interface object:
// we need to introduce an explicit cast
target = target.CastTo(AstBuilder.ConvertType(cecilMethod.DeclaringType));
if (cecilMethodDef != null) {
// convert null.ToLower() to ((string)null).ToLower()
if (target is NullReferenceExpression)
target = target.CastTo(AstBuilder.ConvertType(cecilMethod.DeclaringType));
if (cecilMethodDef.DeclaringType.IsInterface) {
TypeReference tr = byteCode.Arguments[0].InferredType;
if (tr != null) {
TypeDefinition td = tr.Resolve();
if (td != null && !td.IsInterface) {
// Calling an interface method on a non-interface object:
// we need to introduce an explicit cast
target = target.CastTo(AstBuilder.ConvertType(cecilMethod.DeclaringType));
}
}
}
}

9
ICSharpCode.Decompiler/Ast/TextOutputFormatter.cs

@ -131,13 +131,14 @@ namespace ICSharpCode.Decompiler.Ast @@ -131,13 +131,14 @@ namespace ICSharpCode.Decompiler.Ast
output.Write("*/");
break;
case CommentType.Documentation:
if (!inDocumentationComment)
bool isLastLine = !(nodeStack.Peek().NextSibling is Comment);
if (!inDocumentationComment && !isLastLine) {
inDocumentationComment = true;
output.MarkFoldStart("///" + content, true);
}
output.Write("///");
output.Write(content);
inDocumentationComment = true;
bool isLastLine = !(nodeStack.Peek().NextSibling is Comment);
if (isLastLine) {
if (inDocumentationComment && isLastLine) {
inDocumentationComment = false;
output.MarkFoldEnd();
}

6
ICSharpCode.Decompiler/Ast/Transforms/IntroduceExtensionMethods.cs

@ -45,7 +45,11 @@ namespace ICSharpCode.Decompiler.Ast.Transforms @@ -45,7 +45,11 @@ namespace ICSharpCode.Decompiler.Ast.Transforms
if (d != null) {
foreach (var ca in d.CustomAttributes) {
if (ca.AttributeType.Name == "ExtensionAttribute" && ca.AttributeType.Namespace == "System.Runtime.CompilerServices") {
mre.Target = invocation.Arguments.First().Detach();
var firstArgument = invocation.Arguments.First();
if (firstArgument is NullReferenceExpression)
firstArgument = firstArgument.ReplaceWith(expr => expr.CastTo(AstBuilder.ConvertType(d.Parameters.First().ParameterType)));
else
mre.Target = firstArgument.Detach();
if (invocation.Arguments.Any()) {
// HACK: removing type arguments should be done indepently from whether a method is an extension method,
// just by testing whether the arguments can be inferred

9
ICSharpCode.Decompiler/Ast/Transforms/ReplaceMethodCallsWithOperators.cs

@ -40,6 +40,13 @@ namespace ICSharpCode.Decompiler.Ast.Transforms @@ -40,6 +40,13 @@ namespace ICSharpCode.Decompiler.Ast.Transforms
MemberName = "TypeHandle"
};
DecompilerContext context;
public ReplaceMethodCallsWithOperators(DecompilerContext context)
{
this.context = context;
}
public override object VisitInvocationExpression(InvocationExpression invocationExpression, object data)
{
base.VisitInvocationExpression(invocationExpression, data);
@ -214,7 +221,7 @@ namespace ICSharpCode.Decompiler.Ast.Transforms @@ -214,7 +221,7 @@ namespace ICSharpCode.Decompiler.Ast.Transforms
}
}
}
if (assignment.Operator == AssignmentOperatorType.Add || assignment.Operator == AssignmentOperatorType.Subtract) {
if (context.Settings.IntroduceIncrementAndDecrement && (assignment.Operator == AssignmentOperatorType.Add || assignment.Operator == AssignmentOperatorType.Subtract)) {
// detect increment/decrement
if (assignment.Right.IsMatch(new PrimitiveExpression(1))) {
// only if it's not a custom operator

2
ICSharpCode.Decompiler/Ast/Transforms/TransformationPipeline.cs

@ -35,7 +35,7 @@ namespace ICSharpCode.Decompiler.Ast.Transforms @@ -35,7 +35,7 @@ namespace ICSharpCode.Decompiler.Ast.Transforms
new PushNegation(),
new DelegateConstruction(context),
new PatternStatementTransform(context),
new ReplaceMethodCallsWithOperators(),
new ReplaceMethodCallsWithOperators(context),
new IntroduceUnsafeModifier(),
new AddCheckedBlocks(),
new DeclareVariables(context), // should run after most transforms that modify statements

8
ICSharpCode.Decompiler/CecilExtensions.cs

@ -59,7 +59,7 @@ namespace ICSharpCode.Decompiler @@ -59,7 +59,7 @@ namespace ICSharpCode.Decompiler
throw new NotSupportedException ();
}
public static int? GetPopDelta(this Instruction instruction)
public static int? GetPopDelta(this Instruction instruction, MethodDefinition methodDef)
{
OpCode code = instruction.OpCode;
switch (code.StackBehaviourPop) {
@ -93,15 +93,17 @@ namespace ICSharpCode.Decompiler @@ -93,15 +93,17 @@ namespace ICSharpCode.Decompiler
case StackBehaviour.Varpop:
if (code == OpCodes.Ret)
return null;
return methodDef.ReturnType.IsVoid() ? 0 : 1;
if (code.FlowControl != FlowControl.Call)
break;
IMethodSignature method = (IMethodSignature) instruction.Operand;
int count = method.HasParameters ? method.Parameters.Count : 0;
if (code == OpCodes.Calli || (method.HasThis && code != OpCodes.Newobj))
if (method.HasThis && code != OpCodes.Newobj)
++count;
if (code == OpCodes.Calli)
++count; // calli takes a function pointer in additional to the normal args
return count;
}

27
ICSharpCode.Decompiler/CodeMappings.cs

@ -24,6 +24,7 @@ using System.Linq; @@ -24,6 +24,7 @@ using System.Linq;
using ICSharpCode.Decompiler.Ast;
using ICSharpCode.Decompiler.Disassembler;
using ICSharpCode.Decompiler.ILAst;
using ICSharpCode.NRefactory.CSharp;
using Mono.Cecil;
namespace ICSharpCode.Decompiler
@ -316,4 +317,30 @@ namespace ICSharpCode.Decompiler @@ -316,4 +317,30 @@ namespace ICSharpCode.Decompiler
return true;
}
}
/// <summary>
/// Decompilation data. Can be used by other applications to store the decompilation data.
/// </summary>
public class DecompileInformation
{
/// <summary>
/// Gets ot sets the code mappings
/// </summary>
public Dictionary<int, List<MemberMapping>> CodeMappings { get; set; }
/// <summary>
/// Gets or sets the local variables.
/// </summary>
public ConcurrentDictionary<int, IEnumerable<ILVariable>> LocalVariables { get; set; }
/// <summary>
/// Gets the list of MembeReferences that are decompiled (TypeDefinitions, MethodDefinitions, etc)
/// </summary>
public Dictionary<int, MemberReference> DecompiledMemberReferences { get; set; }
/// <summary>
/// Gets (or internal sets) the AST nodes.
/// </summary>
public IEnumerable<AstNode> AstNodes { get; set; }
}
}

32
ICSharpCode.Decompiler/DecompilerSettings.cs

@ -224,6 +224,38 @@ namespace ICSharpCode.Decompiler @@ -224,6 +224,38 @@ namespace ICSharpCode.Decompiler
}
}
#region Options to aid VB decompilation
bool introduceIncrementAndDecrement = true;
/// <summary>
/// Gets/Sets whether to use increment and decrement operators
/// </summary>
public bool IntroduceIncrementAndDecrement {
get { return introduceIncrementAndDecrement; }
set {
if (introduceIncrementAndDecrement != value) {
introduceIncrementAndDecrement = value;
OnPropertyChanged("IntroduceIncrementAndDecrement");
}
}
}
bool alwaysGenerateExceptionVariableForCatchBlocks = false;
/// <summary>
/// Gets/Sets whether to always generate exception variables in catch blocks
/// </summary>
public bool AlwaysGenerateExceptionVariableForCatchBlocks {
get { return alwaysGenerateExceptionVariableForCatchBlocks; }
set {
if (alwaysGenerateExceptionVariableForCatchBlocks != value) {
alwaysGenerateExceptionVariableForCatchBlocks = value;
OnPropertyChanged("AlwaysGenerateExceptionVariableForCatchBlocks");
}
}
}
#endregion
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)

2
ICSharpCode.Decompiler/FlowAnalysis/SsaFormBuilder.cs

@ -129,7 +129,7 @@ namespace ICSharpCode.Decompiler.FlowAnalysis @@ -129,7 +129,7 @@ namespace ICSharpCode.Decompiler.FlowAnalysis
continue;
}
int popCount = inst.GetPopDelta() ?? stackSize;
int popCount = inst.GetPopDelta(method) ?? stackSize;
stackSize -= popCount;
if (stackSize < 0)
throw new InvalidProgramException("IL stack underflow");

1
ICSharpCode.Decompiler/ICSharpCode.Decompiler.csproj

@ -48,6 +48,7 @@ @@ -48,6 +48,7 @@
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="Ast\Annotations.cs" />
<Compile Include="Ast\AstBuilder.cs" />
<Compile Include="Ast\AstMethodBodyBuilder.cs" />
<Compile Include="Ast\CecilTypeResolveContext.cs" />

23
ICSharpCode.Decompiler/ILAst/ILAstBuilder.cs

@ -62,7 +62,7 @@ namespace ICSharpCode.Decompiler.ILAst @@ -62,7 +62,7 @@ namespace ICSharpCode.Decompiler.ILAst
/// <summary> Immutable </summary>
class VariableSlot
{
{
public readonly ByteCode[] StoredBy; // One of those
public readonly bool StoredByAll; // Overestimate which is useful for exceptional control flow.
@ -224,10 +224,13 @@ namespace ICSharpCode.Decompiler.ILAst @@ -224,10 +224,13 @@ namespace ICSharpCode.Decompiler.ILAst
// Virtual instructions to load exception on stack
Dictionary<ExceptionHandler, ByteCode> ldexceptions = new Dictionary<ExceptionHandler, ILAstBuilder.ByteCode>();
public List<ILNode> Build(MethodDefinition methodDef, bool optimize)
DecompilerContext context;
public List<ILNode> Build(MethodDefinition methodDef, bool optimize, DecompilerContext context)
{
this.methodDef = methodDef;
this.optimize = optimize;
this.context = context;
if (methodDef.Body.Instructions.Count == 0) return new List<ILNode>();
@ -260,7 +263,7 @@ namespace ICSharpCode.Decompiler.ILAst @@ -260,7 +263,7 @@ namespace ICSharpCode.Decompiler.ILAst
EndOffset = inst.Next != null ? inst.Next.Offset : methodDef.Body.CodeSize,
Code = code,
Operand = operand,
PopCount = inst.GetPopDelta(),
PopCount = inst.GetPopDelta(methodDef),
PushCount = inst.GetPushDelta()
};
if (prefixes != null) {
@ -352,7 +355,7 @@ namespace ICSharpCode.Decompiler.ILAst @@ -352,7 +355,7 @@ namespace ICSharpCode.Decompiler.ILAst
if (!byteCode.Code.IsUnconditionalControlFlow()) {
if (exceptionHandlerStarts.Contains(byteCode.Next)) {
// Do not fall though down to exception handler
// It is invalid IL as per ECMA-335 §12.4.2.8.1, but some obfuscators produce it
// It is invalid IL as per ECMA-335 §12.4.2.8.1, but some obfuscators produce it
} else {
branchTargets.Add(byteCode.Next);
}
@ -703,8 +706,9 @@ namespace ICSharpCode.Decompiler.ILAst @@ -703,8 +706,9 @@ namespace ICSharpCode.Decompiler.ILAst
};
// Handle the automatically pushed exception on the stack
ByteCode ldexception = ldexceptions[eh];
if (ldexception.StoreTo.Count == 0) {
throw new Exception("Exception should be consumed by something");
if (ldexception.StoreTo == null || ldexception.StoreTo.Count == 0) {
// Exception is not used
catchBlock.ExceptionVariable = null;
} else if (ldexception.StoreTo.Count == 1) {
ILExpression first = catchBlock.Body[0] as ILExpression;
if (first != null &&
@ -713,7 +717,10 @@ namespace ICSharpCode.Decompiler.ILAst @@ -713,7 +717,10 @@ namespace ICSharpCode.Decompiler.ILAst
first.Arguments[0].Operand == ldexception.StoreTo[0])
{
// The exception is just poped - optimize it all away;
catchBlock.ExceptionVariable = null;
if (context.Settings.AlwaysGenerateExceptionVariableForCatchBlocks)
catchBlock.ExceptionVariable = new ILVariable() { Name = "ex_" + eh.HandlerStart.Offset.ToString("X2"), IsGenerated = true };
else
catchBlock.ExceptionVariable = null;
catchBlock.Body.RemoveAt(0);
} else {
catchBlock.ExceptionVariable = ldexception.StoreTo[0];
@ -780,7 +787,7 @@ namespace ICSharpCode.Decompiler.ILAst @@ -780,7 +787,7 @@ namespace ICSharpCode.Decompiler.ILAst
StackSlot slot = byteCode.StackBefore[i];
expr.Arguments.Add(new ILExpression(ILCode.Ldloc, slot.LoadFrom));
}
// Store the result to temporary variable(s) if needed
if (byteCode.StoreTo == null || byteCode.StoreTo.Count == 0) {
ast.Add(expr);

8
ICSharpCode.Decompiler/ILAst/ILAstOptimizer.cs

@ -248,6 +248,7 @@ namespace ICSharpCode.Decompiler.ILAst @@ -248,6 +248,7 @@ namespace ICSharpCode.Decompiler.ILAst
/// <summary>
/// Removes redundatant Br, Nop, Dup, Pop
/// Ignore arguments of 'leave'
/// </summary>
/// <param name="method"></param>
void RemoveRedundantCode(ILBlock method)
@ -286,6 +287,13 @@ namespace ICSharpCode.Decompiler.ILAst @@ -286,6 +287,13 @@ namespace ICSharpCode.Decompiler.ILAst
block.Body = newBody;
}
// Ignore arguments of 'leave'
foreach (ILExpression expr in method.GetSelfAndChildrenRecursive<ILExpression>(e => e.Code == ILCode.Leave)) {
if (expr.Arguments.Any(arg => !arg.Match(ILCode.Ldloc)))
throw new Exception("Leave should have just ldloc at this stage");
expr.Arguments.Clear();
}
// 'dup' removal
foreach (ILExpression expr in method.GetSelfAndChildrenRecursive<ILExpression>()) {
for (int i = 0; i < expr.Arguments.Count; i++) {

2
ICSharpCode.Decompiler/ILAst/YieldReturnDecompiler.cs

@ -224,7 +224,7 @@ namespace ICSharpCode.Decompiler.ILAst @@ -224,7 +224,7 @@ namespace ICSharpCode.Decompiler.ILAst
ILBlock ilMethod = new ILBlock();
ILAstBuilder astBuilder = new ILAstBuilder();
ilMethod.Body = astBuilder.Build(method, true);
ilMethod.Body = astBuilder.Build(method, true, context);
ILAstOptimizer optimizer = new ILAstOptimizer();
optimizer.Optimize(context, ilMethod, ILAstOptimizationStep.YieldReturn);
return ilMethod;

6
ILSpy.BamlDecompiler/BamlResourceNodeFactory.cs

@ -18,10 +18,10 @@ namespace ILSpy.BamlDecompiler @@ -18,10 +18,10 @@ namespace ILSpy.BamlDecompiler
return null;
}
public ILSpyTreeNode CreateNode(string key, Stream data)
public ILSpyTreeNode CreateNode(string key, object data)
{
if (key.EndsWith(".baml", StringComparison.OrdinalIgnoreCase))
return new BamlResourceEntryNode(key, data);
if (key.EndsWith(".baml", StringComparison.OrdinalIgnoreCase) && data is Stream)
return new BamlResourceEntryNode(key, (Stream)data);
else
return null;
}

2
ILSpy.BamlDecompiler/ConnectMethodDecompiler.cs

@ -56,9 +56,9 @@ namespace ILSpy.BamlDecompiler @@ -56,9 +56,9 @@ namespace ILSpy.BamlDecompiler
// decompile method and optimize the switch
ILBlock ilMethod = new ILBlock();
ILAstBuilder astBuilder = new ILAstBuilder();
ilMethod.Body = astBuilder.Build(def, true);
ILAstOptimizer optimizer = new ILAstOptimizer();
var context = new DecompilerContext(type.Module) { CurrentMethod = def, CurrentType = type };
ilMethod.Body = astBuilder.Build(def, true, context);
optimizer.Optimize(context, ilMethod, ILAstOptimizationStep.RemoveRedundantCode3);
ILSwitch ilSwitch = ilMethod.Body.OfType<ILSwitch>().FirstOrDefault();

20
ILSpy.SharpDevelop.LGPL/ILSpy.SharpDevelop.LGPL.csproj

@ -3,23 +3,24 @@ @@ -3,23 +3,24 @@
<PropertyGroup>
<ProjectGuid>{704F66F1-5C7F-4326-A7AA-C604A3896D4E}</ProjectGuid>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">x86</Platform>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<OutputType>Library</OutputType>
<RootNamespace>ICSharpCode.ILSpy.SharpDevelop</RootNamespace>
<AssemblyName>ILSpy.SharpDevelop.LGPL</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<AppDesignerFolder>Properties</AppDesignerFolder>
<BaseAddress>6881280</BaseAddress>
</PropertyGroup>
<PropertyGroup Condition=" '$(Platform)' == 'x86' ">
<PlatformTarget>x86</PlatformTarget>
</PropertyGroup>
<PropertyGroup Condition=" '$(Platform)' == 'AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<SignAssembly>False</SignAssembly>
<DelaySign>False</DelaySign>
<RunPostBuildEvent>OnBuildSuccess</RunPostBuildEvent>
<AllowUnsafeBlocks>False</AllowUnsafeBlocks>
<NoStdLib>False</NoStdLib>
<WarningLevel>4</WarningLevel>
<TreatWarningsAsErrors>false</TreatWarningsAsErrors>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
<OutputPath>bin\Debug\</OutputPath>
<DebugSymbols>True</DebugSymbols>
<DebugSymbols>true</DebugSymbols>
<DebugType>Full</DebugType>
<Optimize>False</Optimize>
<CheckForOverflowUnderflow>True</CheckForOverflowUnderflow>
@ -32,6 +33,9 @@ @@ -32,6 +33,9 @@
<Optimize>True</Optimize>
<CheckForOverflowUnderflow>False</CheckForOverflowUnderflow>
<DefineConstants>TRACE</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition=" '$(Platform)' == 'AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
</PropertyGroup>
<ItemGroup>
<Reference Include="PresentationCore">

18
ILSpy.sln

@ -1,7 +1,7 @@ @@ -1,7 +1,7 @@

Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010
# SharpDevelop 4.1.0.7595-alpha
# SharpDevelop 4.1.0.7638-alpha
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "doc", "doc", "{F45DB999-7E72-4000-B5AD-3A7B485A0896}"
ProjectSection(SolutionItems) = postProject
doc\Command Line.txt = doc\Command Line.txt
@ -11,10 +11,10 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Debugger", "Debugger", "{89 @@ -11,10 +11,10 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Debugger", "Debugger", "{89
ProjectSection(SolutionItems) = postProject
EndProjectSection
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ILSpy.Debugger", "Debugger\ILSpy.Debugger\ILSpy.Debugger.csproj", "{6D3D0F0D-348D-456A-A6ED-E9BD5EFABB6A}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Debugger.Core", "Debugger\Debugger.Core\Debugger.Core.csproj", "{1D18D788-F7EE-4585-A23B-34DC8EC63CB8}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ILSpy.Debugger", "Debugger\ILSpy.Debugger\ILSpy.Debugger.csproj", "{6D3D0F0D-348D-456A-A6ED-E9BD5EFABB6A}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ILSpy", "ILSpy\ILSpy.csproj", "{1E85EFF9-E370-4683-83E4-8A3D063FF791}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ICSharpCode.TreeView", "SharpTreeView\ICSharpCode.TreeView.csproj", "{DDE2A481-8271-4EAC-A330-8FA6A38D13D1}"
@ -33,6 +33,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestPlugin", "TestPlugin\Te @@ -33,6 +33,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestPlugin", "TestPlugin\Te
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Mono.Cecil.Pdb", "Mono.Cecil\symbols\pdb\Mono.Cecil.Pdb.csproj", "{63E6915C-7EA4-4D76-AB28-0D7191EEA626}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ICSharpCode.NRefactory.VB", "NRefactory\ICSharpCode.NRefactory.VB\ICSharpCode.NRefactory.VB.csproj", "{7B82B671-419F-45F4-B778-D9286F996EFA}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ILSpy.BamlDecompiler", "ILSpy.BamlDecompiler\ILSpy.BamlDecompiler.csproj", "{A6BAD2BA-76BA-461C-8B6D-418607591247}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ILSpy.BamlDecompiler.Tests", "ILSpy.BamlDecompiler\Tests\ILSpy.BamlDecompiler.Tests.csproj", "{1169E6D1-1899-43D4-A500-07CE4235B388}"
@ -119,6 +121,14 @@ Global @@ -119,6 +121,14 @@ Global
{63E6915C-7EA4-4D76-AB28-0D7191EEA626}.Release|Any CPU.ActiveCfg = net_4_0_Release|Any CPU
{63E6915C-7EA4-4D76-AB28-0D7191EEA626}.Release|x86.Build.0 = net_4_0_Debug|Any CPU
{63E6915C-7EA4-4D76-AB28-0D7191EEA626}.Release|x86.ActiveCfg = net_4_0_Release|Any CPU
{7B82B671-419F-45F4-B778-D9286F996EFA}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7B82B671-419F-45F4-B778-D9286F996EFA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7B82B671-419F-45F4-B778-D9286F996EFA}.Debug|x86.Build.0 = Debug|Any CPU
{7B82B671-419F-45F4-B778-D9286F996EFA}.Debug|x86.ActiveCfg = Debug|Any CPU
{7B82B671-419F-45F4-B778-D9286F996EFA}.Release|Any CPU.Build.0 = Release|Any CPU
{7B82B671-419F-45F4-B778-D9286F996EFA}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7B82B671-419F-45F4-B778-D9286F996EFA}.Release|x86.Build.0 = Release|Any CPU
{7B82B671-419F-45F4-B778-D9286F996EFA}.Release|x86.ActiveCfg = Release|Any CPU
{A6BAD2BA-76BA-461C-8B6D-418607591247}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A6BAD2BA-76BA-461C-8B6D-418607591247}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A6BAD2BA-76BA-461C-8B6D-418607591247}.Debug|x86.Build.0 = Debug|x86
@ -156,7 +166,7 @@ Global @@ -156,7 +166,7 @@ Global
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{1D18D788-F7EE-4585-A23B-34DC8EC63CB8} = {89C4A682-2706-44A3-ADDC-BC273164C37E}
{6D3D0F0D-348D-456A-A6ED-E9BD5EFABB6A} = {89C4A682-2706-44A3-ADDC-BC273164C37E}
{1D18D788-F7EE-4585-A23B-34DC8EC63CB8} = {89C4A682-2706-44A3-ADDC-BC273164C37E}
EndGlobalSection
EndGlobal

34
ILSpy/AnalyzerTreeView.cs

@ -17,6 +17,9 @@ @@ -17,6 +17,9 @@
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using ICSharpCode.ILSpy.TreeNodes.Analyzer;
using ICSharpCode.TreeView;
@ -44,8 +47,24 @@ namespace ICSharpCode.ILSpy @@ -44,8 +47,24 @@ namespace ICSharpCode.ILSpy
private AnalyzerTreeView()
{
this.ShowRoot = false;
this.Root = new AnalyzerTreeNode { Language = MainWindow.Instance.CurrentLanguage };
this.Root = new AnalyzerRootNode { Language = MainWindow.Instance.CurrentLanguage };
ContextMenuProvider.Add(this);
MainWindow.Instance.CurrentAssemblyListChanged += MainWindow_Instance_CurrentAssemblyListChanged;
}
void MainWindow_Instance_CurrentAssemblyListChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.Action == NotifyCollectionChangedAction.Reset) {
this.Root.Children.Clear();
} else {
List<LoadedAssembly> removedAssemblies = new List<LoadedAssembly>();
if (e.OldItems != null)
removedAssemblies.AddRange(e.OldItems.Cast<LoadedAssembly>());
List<LoadedAssembly> addedAssemblies = new List<LoadedAssembly>();
if (e.NewItems != null)
addedAssemblies.AddRange(e.NewItems.Cast<LoadedAssembly>());
((AnalyzerRootNode)this.Root).HandleAssemblyListChanged(removedAssemblies, addedAssemblies);
}
}
public void Show()
@ -68,5 +87,18 @@ namespace ICSharpCode.ILSpy @@ -68,5 +87,18 @@ namespace ICSharpCode.ILSpy
{
this.Root.Children.Clear();
}
sealed class AnalyzerRootNode : AnalyzerTreeNode
{
public override bool HandleAssemblyListChanged(ICollection<LoadedAssembly> removedAssemblies, ICollection<LoadedAssembly> addedAssemblies)
{
this.Children.RemoveAll(
delegate(SharpTreeNode n) {
AnalyzerTreeNode an = n as AnalyzerTreeNode;
return an == null || !an.HandleAssemblyListChanged(removedAssemblies, addedAssemblies);
});
return true;
}
}
}
}

14
ILSpy/AssemblyList.cs

@ -148,6 +148,20 @@ namespace ICSharpCode.ILSpy @@ -148,6 +148,20 @@ namespace ICSharpCode.ILSpy
lock (assemblies) {
assemblies.Remove(assembly);
}
RequestGC();
}
static bool gcRequested;
void RequestGC()
{
if (gcRequested) return;
gcRequested = true;
App.Current.Dispatcher.BeginInvoke(DispatcherPriority.ContextIdle, new Action(
delegate {
gcRequested = false;
GC.Collect();
}));
}
public void Sort(IComparer<LoadedAssembly> comparer)

26
ILSpy/Controls/ResourceStringTable.xaml

@ -0,0 +1,26 @@ @@ -0,0 +1,26 @@
<?xml version="1.0" encoding="utf-8"?>
<UserControl
x:Class="ICSharpCode.ILSpy.Controls.ResourceStringTable" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<UserControl.CommandBindings>
<CommandBinding Command="ApplicationCommands.Copy"
Executed="ExecuteCopy"
CanExecute="CanExecuteCopy"/>
</UserControl.CommandBindings>
<ListView
Name="resourceListView"
SelectionMode="Extended">
<ListView.View>
<GridView
AllowsColumnReorder="False">
<GridView.Columns>
<GridViewColumn
Header="Resource id"
DisplayMemberBinding="{Binding Key}" />
<GridViewColumn
Header="Resource value"
DisplayMemberBinding="{Binding Value}" />
</GridView.Columns>
</GridView>
</ListView.View>
</ListView>
</UserControl>

51
ILSpy/Controls/ResourceStringTable.xaml.cs

@ -0,0 +1,51 @@ @@ -0,0 +1,51 @@
/*
* Created by SharpDevelop.
* User: Ronny Klier
* Date: 31.05.2011
* Time: 00:13
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
using System.Collections;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
namespace ICSharpCode.ILSpy.Controls
{
/// <summary>
/// Interaction logic for ResourceStringTable.xaml
/// </summary>
public partial class ResourceStringTable : UserControl
{
public ResourceStringTable(IEnumerable strings)
{
InitializeComponent();
// set size to fit decompiler window
// TODO: there should be a more transparent way to do this
MaxWidth = MainWindow.Instance.mainPane.ActualWidth-20;
MaxHeight = MainWindow.Instance.mainPane.ActualHeight-100;
resourceListView.ItemsSource = strings;
}
void ExecuteCopy(object sender, ExecutedRoutedEventArgs args)
{
StringBuilder sb = new StringBuilder();
foreach (var item in resourceListView.SelectedItems)
{
sb.AppendLine(item.ToString());
}
Clipboard.SetText(sb.ToString());
}
void CanExecuteCopy(object sender, CanExecuteRoutedEventArgs args)
{
args.CanExecute = true;
}
}
}

22
ILSpy/ILSpy.csproj

@ -9,8 +9,7 @@ @@ -9,8 +9,7 @@
<AssemblyName>ILSpy</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<AppDesignerFolder>Properties</AppDesignerFolder>
<TargetFrameworkProfile>
</TargetFrameworkProfile>
<TargetFrameworkProfile>Client</TargetFrameworkProfile>
<RunPostBuildEvent>OnBuildSuccess</RunPostBuildEvent>
<AllowUnsafeBlocks>True</AllowUnsafeBlocks>
<NoStdLib>False</NoStdLib>
@ -67,6 +66,7 @@ @@ -67,6 +66,7 @@
<Reference Include="System.Data.DataSetExtensions">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Drawing" />
<Reference Include="System.Xaml">
<RequiredTargetFramework>4.0</RequiredTargetFramework>
</Reference>
@ -134,6 +134,10 @@ @@ -134,6 +134,10 @@
<DependentUpon>OpenFromGacDialog.xaml</DependentUpon>
<SubType>Code</SubType>
</Compile>
<Compile Include="Controls\ResourceStringTable.xaml.cs">
<DependentUpon>ResourceStringTable.xaml</DependentUpon>
<SubType>Code</SubType>
</Compile>
<Compile Include="Options\DecompilerSettingsPanel.xaml.cs">
<DependentUpon>DecompilerSettingsPanel.xaml</DependentUpon>
<SubType>Code</SubType>
@ -168,6 +172,8 @@ @@ -168,6 +172,8 @@
<Compile Include="TreeNodes\Analyzer\AnalyzedTypeTreeNode.cs" />
<Compile Include="TreeNodes\Analyzer\AnalyzedEventAccessorTreeNode.cs" />
<Compile Include="TreeNodes\Analyzer\AnalyzedVirtualMethodUsedByTreeNode.cs" />
<Compile Include="TreeNodes\Analyzer\AnalyzerEntityTreeNode.cs" />
<Compile Include="TreeNodes\Analyzer\AnalyzerSearchTreeNode.cs" />
<Compile Include="TreeNodes\Analyzer\Helpers.cs" />
<Compile Include="TreeNodes\Analyzer\ScopedWhereUsedAnalyzer.cs" />
<Compile Include="TreeNodes\BaseTypesEntryNode.cs" />
@ -182,6 +188,9 @@ @@ -182,6 +188,9 @@
<Compile Include="TreeNodes\ResourceNodes\XamlResourceNode.cs" />
<Compile Include="TreeNodes\Analyzer\AnalyzedPropertyOverridesTreeNode.cs" />
<Compile Include="TreeNodes\Analyzer\AnalyzedPropertyTreeNode.cs" />
<Compile Include="VB\ILSpyEnvironmentProvider.cs" />
<Compile Include="VB\VBLanguage.cs" />
<Compile Include="VB\VBTextOutputFormatter.cs" />
<Compile Include="XmlDoc\AddXmlDocTransform.cs" />
<Compile Include="XmlDoc\XmlDocKeyProvider.cs" />
<Compile Include="XmlDoc\XmlDocLoader.cs" />
@ -249,6 +258,7 @@ @@ -249,6 +258,7 @@
<EmbeddedResource Include="TextView\ILAsm-Mode.xshd" />
</ItemGroup>
<ItemGroup>
<Page Include="Controls\ResourceStringTable.xaml" />
<Page Include="Controls\SearchBoxStyle.xaml">
<DependentUpon>SearchBox.cs</DependentUpon>
</Page>
@ -330,6 +340,10 @@ @@ -330,6 +340,10 @@
<Project>{63E6915C-7EA4-4D76-AB28-0D7191EEA626}</Project>
<Name>Mono.Cecil.Pdb</Name>
</ProjectReference>
<ProjectReference Include="..\NRefactory\ICSharpCode.NRefactory.VB\ICSharpCode.NRefactory.VB.csproj">
<Project>{7B82B671-419F-45F4-B778-D9286F996EFA}</Project>
<Name>ICSharpCode.NRefactory.VB</Name>
</ProjectReference>
<ProjectReference Include="..\NRefactory\ICSharpCode.NRefactory\ICSharpCode.NRefactory.csproj">
<Project>{3B2A5653-EC97-4001-BB9B-D90F1AF2C371}</Project>
<Name>ICSharpCode.NRefactory</Name>
@ -339,12 +353,14 @@ @@ -339,12 +353,14 @@
<Name>ICSharpCode.TreeView</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<Folder Include="VB" />
</ItemGroup>
<ItemGroup>
<Resource Include="Images\ResourceXml.png" />
<Resource Include="Images\ResourceXsd.png" />
<Resource Include="Images\ResourceXslt.png" />
</ItemGroup>
<ItemGroup />
<ItemGroup>
<Folder Include="AvalonEdit" />
<Folder Include="Bookmarks" />

4
ILSpy/Languages/ILAstLanguage.cs

@ -53,10 +53,10 @@ namespace ICSharpCode.ILSpy @@ -53,10 +53,10 @@ namespace ICSharpCode.ILSpy
ILAstBuilder astBuilder = new ILAstBuilder();
ILBlock ilMethod = new ILBlock();
ilMethod.Body = astBuilder.Build(method, inlineVariables);
DecompilerContext context = new DecompilerContext(method.Module) { CurrentType = method.DeclaringType, CurrentMethod = method };
ilMethod.Body = astBuilder.Build(method, inlineVariables, context);
if (abortBeforeStep != null) {
DecompilerContext context = new DecompilerContext(method.Module) { CurrentType = method.DeclaringType, CurrentMethod = method };
new ILAstOptimizer().Optimize(context, ilMethod, abortBeforeStep.Value);
}

16
ILSpy/MainWindow.xaml.cs

@ -224,6 +224,8 @@ namespace ICSharpCode.ILSpy @@ -224,6 +224,8 @@ namespace ICSharpCode.ILSpy
get { return assemblyList; }
}
public event NotifyCollectionChangedEventHandler CurrentAssemblyListChanged;
List<LoadedAssembly> commandLineLoadedAssemblies = new List<LoadedAssembly>();
bool HandleCommandLineArguments(CommandLineArguments args)
@ -341,9 +343,17 @@ namespace ICSharpCode.ILSpy @@ -341,9 +343,17 @@ namespace ICSharpCode.ILSpy
void assemblyList_Assemblies_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.OldItems != null)
foreach (LoadedAssembly asm in e.OldItems)
history.RemoveAll(n => n.TreeNodes.Any(nd => nd.AncestorsAndSelf().OfType<AssemblyTreeNode>().Any(a => a.LoadedAssembly == asm)));
if (e.Action == NotifyCollectionChangedAction.Reset) {
history.RemoveAll(_ => true);
}
if (e.OldItems != null) {
var oldAssemblies = new HashSet<LoadedAssembly>(e.OldItems.Cast<LoadedAssembly>());
history.RemoveAll(n => n.TreeNodes.Any(
nd => nd.AncestorsAndSelf().OfType<AssemblyTreeNode>().Any(
a => oldAssemblies.Contains(a.LoadedAssembly))));
}
if (CurrentAssemblyListChanged != null)
CurrentAssemblyListChanged(this, e);
}
void LoadInitialAssemblies()

228
ILSpy/SearchPane.cs

@ -19,7 +19,9 @@ @@ -19,7 +19,9 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
@ -30,8 +32,12 @@ using System.Windows.Documents; @@ -30,8 +32,12 @@ using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
using ICSharpCode.Decompiler.ILAst;
using ICSharpCode.ILSpy.TreeNodes;
using ICSharpCode.NRefactory.CSharp;
using ICSharpCode.NRefactory.Utils;
using Mono.Cecil;
using Mono.Cecil.Cil;
namespace ICSharpCode.ILSpy
{
@ -55,19 +61,40 @@ namespace ICSharpCode.ILSpy @@ -55,19 +61,40 @@ namespace ICSharpCode.ILSpy
const int SearchMode_Type = 0;
const int SearchMode_Member = 1;
const int SearchMode_Literal = 2;
private SearchPane()
{
InitializeComponent();
searchModeComboBox.Items.Add(new { Image = Images.Class, Name = "Type" });
searchModeComboBox.Items.Add(new { Image = Images.Property, Name = "Member" });
searchModeComboBox.Items.Add(new { Image = Images.Literal, Name = "Constant" });
searchModeComboBox.SelectedIndex = SearchMode_Type;
MainWindow.Instance.CurrentAssemblyListChanged += MainWindow_Instance_CurrentAssemblyListChanged;
}
bool runSearchOnNextShow;
void MainWindow_Instance_CurrentAssemblyListChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (IsVisible) {
StartSearch(this.SearchTerm);
} else {
StartSearch(null);
runSearchOnNextShow = true;
}
}
public void Show()
{
if (!IsVisible)
if (!IsVisible) {
MainWindow.Instance.ShowInTopPane("Search", this);
if (runSearchOnNextShow) {
runSearchOnNextShow = false;
StartSearch(this.SearchTerm);
}
}
Dispatcher.BeginInvoke(
DispatcherPriority.Background,
new Func<bool>(searchBox.Focus));
@ -144,6 +171,9 @@ namespace ICSharpCode.ILSpy @@ -144,6 +171,9 @@ namespace ICSharpCode.ILSpy
} else if (e.Key == Key.M && e.KeyboardDevice.Modifiers == ModifierKeys.Control) {
searchModeComboBox.SelectedIndex = SearchMode_Member;
e.Handled = true;
} else if (e.Key == Key.S && e.KeyboardDevice.Modifiers == ModifierKeys.Control) {
searchModeComboBox.SelectedIndex = SearchMode_Literal;
e.Handled = true;
}
}
@ -162,11 +192,14 @@ namespace ICSharpCode.ILSpy @@ -162,11 +192,14 @@ namespace ICSharpCode.ILSpy
readonly CancellationTokenSource cts = new CancellationTokenSource();
readonly LoadedAssembly[] assemblies;
readonly string searchTerm;
readonly int searchMode;
int searchMode;
readonly Language language;
public readonly ObservableCollection<SearchResult> Results = new ObservableCollection<SearchResult>();
int resultCount;
TypeCode searchTermLiteralType = TypeCode.Empty;
object searchTermLiteralValue;
public RunningSearch(LoadedAssembly[] assemblies, string searchTerm, int searchMode, Language language)
{
this.dispatcher = Dispatcher.CurrentDispatcher;
@ -186,6 +219,33 @@ namespace ICSharpCode.ILSpy @@ -186,6 +219,33 @@ namespace ICSharpCode.ILSpy
public void Run()
{
try {
if (searchMode == SearchMode_Literal) {
CSharpParser parser = new CSharpParser();
PrimitiveExpression pe = parser.ParseExpression(new StringReader(searchTerm)) as PrimitiveExpression;
if (pe != null && pe.Value != null) {
TypeCode peValueType = Type.GetTypeCode(pe.Value.GetType());
switch (peValueType) {
case TypeCode.Byte:
case TypeCode.SByte:
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Int64:
case TypeCode.UInt64:
searchTermLiteralType = TypeCode.Int64;
searchTermLiteralValue = CSharpPrimitiveCast.Cast(TypeCode.Int64, pe.Value, false);
break;
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.String:
searchTermLiteralType = peValueType;
searchTermLiteralValue = pe.Value;
break;
}
}
}
foreach (var loadedAssembly in assemblies) {
AssemblyDefinition asm = loadedAssembly.AssemblyDefinition;
if (asm == null)
@ -245,7 +305,7 @@ namespace ICSharpCode.ILSpy @@ -245,7 +305,7 @@ namespace ICSharpCode.ILSpy
return;
foreach (FieldDefinition field in type.Fields) {
if (IsMatch(field.Name)) {
if (IsMatch(field)) {
AddResult(new SearchResult {
Member = field,
Image = FieldTreeNode.GetIcon(field),
@ -256,7 +316,7 @@ namespace ICSharpCode.ILSpy @@ -256,7 +316,7 @@ namespace ICSharpCode.ILSpy
}
}
foreach (PropertyDefinition property in type.Properties) {
if (IsMatch(property.Name)) {
if (IsMatch(property)) {
AddResult(new SearchResult {
Member = property,
Image = PropertyTreeNode.GetIcon(property),
@ -267,7 +327,7 @@ namespace ICSharpCode.ILSpy @@ -267,7 +327,7 @@ namespace ICSharpCode.ILSpy
}
}
foreach (EventDefinition ev in type.Events) {
if (IsMatch(ev.Name)) {
if (IsMatch(ev)) {
AddResult(new SearchResult {
Member = ev,
Image = EventTreeNode.GetIcon(ev),
@ -278,7 +338,15 @@ namespace ICSharpCode.ILSpy @@ -278,7 +338,15 @@ namespace ICSharpCode.ILSpy
}
}
foreach (MethodDefinition method in type.Methods) {
if (IsMatch(method.Name)) {
switch (method.SemanticsAttributes) {
case MethodSemanticsAttributes.Setter:
case MethodSemanticsAttributes.Getter:
case MethodSemanticsAttributes.AddOn:
case MethodSemanticsAttributes.RemoveOn:
case MethodSemanticsAttributes.Fire:
continue;
}
if (IsMatch(method)) {
AddResult(new SearchResult {
Member = method,
Image = MethodTreeNode.GetIcon(method),
@ -289,6 +357,152 @@ namespace ICSharpCode.ILSpy @@ -289,6 +357,152 @@ namespace ICSharpCode.ILSpy
}
}
}
bool IsMatch(FieldDefinition field)
{
if (searchMode == SearchMode_Literal)
return IsLiteralMatch(field.Constant);
else
return IsMatch(field.Name);
}
bool IsMatch(PropertyDefinition property)
{
if (searchMode == SearchMode_Literal)
return MethodIsLiteralMatch(property.GetMethod) || MethodIsLiteralMatch(property.SetMethod);
else
return IsMatch(property.Name);
}
bool IsMatch(EventDefinition ev)
{
if (searchMode == SearchMode_Literal)
return MethodIsLiteralMatch(ev.AddMethod) || MethodIsLiteralMatch(ev.RemoveMethod) || MethodIsLiteralMatch(ev.InvokeMethod);
else
return IsMatch(ev.Name);
}
bool IsMatch(MethodDefinition m)
{
if (searchMode == SearchMode_Literal)
return MethodIsLiteralMatch(m);
else
return IsMatch(m.Name);
}
bool IsLiteralMatch(object val)
{
if (val == null)
return false;
switch (searchTermLiteralType) {
case TypeCode.Int64:
TypeCode tc = Type.GetTypeCode(val.GetType());
if (tc >= TypeCode.SByte && tc <= TypeCode.UInt64)
return Convert.ToInt64(val) == (long)searchTermLiteralValue;
else
return false;
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.String:
return searchTermLiteralValue.Equals(val);
default:
// substring search with searchTerm
return IsMatch(val.ToString());
}
}
bool MethodIsLiteralMatch(MethodDefinition m)
{
if (m == null)
return false;
var body = m.Body;
if (body == null)
return false;
if (searchTermLiteralType == TypeCode.Int64) {
long val = (long)searchTermLiteralValue;
foreach (var inst in body.Instructions) {
switch (inst.OpCode.Code) {
case Code.Ldc_I8:
if (val == (long)inst.Operand)
return true;
break;
case Code.Ldc_I4:
if (val == (int)inst.Operand)
return true;
break;
case Code.Ldc_I4_S:
if (val == (sbyte)inst.Operand)
return true;
break;
case Code.Ldc_I4_M1:
if (val == -1)
return true;
break;
case Code.Ldc_I4_0:
if (val == 0)
return true;
break;
case Code.Ldc_I4_1:
if (val == 1)
return true;
break;
case Code.Ldc_I4_2:
if (val == 2)
return true;
break;
case Code.Ldc_I4_3:
if (val == 3)
return true;
break;
case Code.Ldc_I4_4:
if (val == 4)
return true;
break;
case Code.Ldc_I4_5:
if (val == 5)
return true;
break;
case Code.Ldc_I4_6:
if (val == 6)
return true;
break;
case Code.Ldc_I4_7:
if (val == 7)
return true;
break;
case Code.Ldc_I4_8:
if (val == 8)
return true;
break;
}
}
} else if (searchTermLiteralType != TypeCode.Empty) {
Code expectedCode;
switch (searchTermLiteralType) {
case TypeCode.Single:
expectedCode = Code.Ldc_R4;
break;
case TypeCode.Double:
expectedCode = Code.Ldc_R8;
break;
case TypeCode.String:
expectedCode = Code.Ldstr;
break;
default:
throw new InvalidOperationException();
}
foreach (var inst in body.Instructions) {
if (inst.OpCode.Code == expectedCode && searchTermLiteralValue.Equals(inst.Operand))
return true;
}
} else {
foreach (var inst in body.Instructions) {
if (inst.OpCode.Code == Code.Ldstr && IsMatch((string)inst.Operand))
return true;
}
}
return false;
}
}
sealed class SearchResult : INotifyPropertyChanged, IMemberTreeNode
@ -311,7 +525,7 @@ namespace ICSharpCode.ILSpy @@ -311,7 +525,7 @@ namespace ICSharpCode.ILSpy
}
}
}
[ExportMainMenuCommand(Menu = "_View", Header = "_Search", MenuIcon="Images/Find.png", MenuCategory = "ShowPane", MenuOrder = 100)]
[ExportToolbarCommand(ToolTip = "Search (F3)", ToolbarIcon = "Images/Find.png", ToolbarCategory = "View", ToolbarOrder = 100)]
sealed class ShowSearchCommand : CommandWrapper

2
ILSpy/TextView/DecompilerTextView.cs

@ -75,7 +75,7 @@ namespace ICSharpCode.ILSpy.TextView @@ -75,7 +75,7 @@ namespace ICSharpCode.ILSpy.TextView
readonly TextMarkerService textMarkerService;
[ImportMany(typeof(ITextEditorListener))]
IEnumerable<ITextEditorListener> textEditorListeners;
IEnumerable<ITextEditorListener> textEditorListeners = null;
#region Constructor
public DecompilerTextView()

28
ILSpy/TreeNodes/Analyzer/AnalyzedEventFiredByTreeNode.cs

@ -27,13 +27,12 @@ using Mono.Cecil.Cil; @@ -27,13 +27,12 @@ using Mono.Cecil.Cil;
namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
{
internal sealed class AnalyzedEventFiredByTreeNode : AnalyzerTreeNode
internal sealed class AnalyzedEventFiredByTreeNode : AnalyzerSearchTreeNode
{
private readonly EventDefinition analyzedEvent;
private readonly FieldDefinition eventBackingField;
private readonly MethodDefinition eventFiringMethod;
private readonly ThreadingSupport threading;
private ConcurrentDictionary<MethodDefinition, int> foundMethods;
public AnalyzedEventFiredByTreeNode(EventDefinition analyzedEvent)
@ -42,8 +41,6 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer @@ -42,8 +41,6 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
throw new ArgumentNullException("analyzedEvent");
this.analyzedEvent = analyzedEvent;
this.threading = new ThreadingSupport();
this.LazyLoading = true;
this.eventBackingField = GetBackingField(analyzedEvent);
this.eventFiringMethod = analyzedEvent.EventType.Resolve().Methods.First(md => md.Name == "Invoke");
@ -54,26 +51,7 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer @@ -54,26 +51,7 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
get { return "Raised 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)
protected override IEnumerable<AnalyzerTreeNode> FetchChildren(CancellationToken ct)
{
foundMethods = new ConcurrentDictionary<MethodDefinition, int>();
@ -84,7 +62,7 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer @@ -84,7 +62,7 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
foundMethods = null;
}
private IEnumerable<SharpTreeNode> FindReferencesInType(TypeDefinition type)
private IEnumerable<AnalyzerTreeNode> FindReferencesInType(TypeDefinition type)
{
// HACK: in lieu of proper flow analysis, I'm going to use a simple heuristic
// If the method accesses the event's backing field, and calls invoke on a delegate

32
ILSpy/TreeNodes/Analyzer/AnalyzedEventOverridesTreeNode.cs

@ -27,10 +27,9 @@ using Mono.Cecil; @@ -27,10 +27,9 @@ using Mono.Cecil;
namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
{
internal sealed class AnalyzedEventOverridesTreeNode : AnalyzerTreeNode
internal sealed class AnalyzedEventOverridesTreeNode : AnalyzerSearchTreeNode
{
private readonly EventDefinition analyzedEvent;
private readonly ThreadingSupport threading;
public AnalyzedEventOverridesTreeNode(EventDefinition analyzedEvent)
{
@ -38,8 +37,6 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer @@ -38,8 +37,6 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
throw new ArgumentNullException("analyzedEvent");
this.analyzedEvent = analyzedEvent;
this.threading = new ThreadingSupport();
this.LazyLoading = true;
}
public override object Text
@ -47,36 +44,15 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer @@ -47,36 +44,15 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
get { return "Overridden By"; }
}
public override object Icon
protected override IEnumerable<AnalyzerTreeNode> FetchChildren(CancellationToken ct)
{
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)
{
ScopedWhereUsedAnalyzer<SharpTreeNode> analyzer;
analyzer = new ScopedWhereUsedAnalyzer<SharpTreeNode>(analyzedEvent, FindReferencesInType);
var analyzer = new ScopedWhereUsedAnalyzer<AnalyzerTreeNode>(analyzedEvent, FindReferencesInType);
foreach (var child in analyzer.PerformAnalysis(ct).OrderBy(n => n.Text)) {
yield return child;
}
}
private IEnumerable<SharpTreeNode> FindReferencesInType(TypeDefinition type)
private IEnumerable<AnalyzerTreeNode> FindReferencesInType(TypeDefinition type)
{
string name = analyzedEvent.Name;
string declTypeName = analyzedEvent.DeclaringType.FullName;

12
ILSpy/TreeNodes/Analyzer/AnalyzedEventTreeNode.cs

@ -21,7 +21,7 @@ using Mono.Cecil; @@ -21,7 +21,7 @@ using Mono.Cecil;
namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
{
internal sealed class AnalyzedEventTreeNode : AnalyzerTreeNode
internal sealed class AnalyzedEventTreeNode : AnalyzerEntityTreeNode
{
private readonly EventDefinition analyzedEvent;
private readonly string prefix;
@ -35,6 +35,10 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer @@ -35,6 +35,10 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
this.LazyLoading = true;
}
public override MemberReference Member {
get { return analyzedEvent; }
}
public override object Icon
{
get { return EventTreeNode.GetIcon(analyzedEvent); }
@ -49,12 +53,6 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer @@ -49,12 +53,6 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
}
}
public override void ActivateItem(System.Windows.RoutedEventArgs e)
{
e.Handled = true;
MainWindow.Instance.JumpToReference(analyzedEvent);
}
protected override void LoadChildren()
{
if (analyzedEvent.AddMethod != null)

32
ILSpy/TreeNodes/Analyzer/AnalyzedFieldAccessTreeNode.cs

@ -27,13 +27,12 @@ using System.Collections; @@ -27,13 +27,12 @@ using System.Collections;
namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
{
internal sealed class AnalyzedFieldAccessTreeNode : AnalyzerTreeNode
internal sealed class AnalyzedFieldAccessTreeNode : AnalyzerSearchTreeNode
{
private readonly bool showWrites; // true: show writes; false: show read access
private readonly FieldDefinition analyzedField;
private readonly ThreadingSupport threading;
private Lazy<Hashtable> foundMethods;
private object hashLock = new object();
private readonly object hashLock = new object();
public AnalyzedFieldAccessTreeNode(FieldDefinition analyzedField, bool showWrites)
{
@ -42,8 +41,6 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer @@ -42,8 +41,6 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
this.analyzedField = analyzedField;
this.showWrites = showWrites;
this.threading = new ThreadingSupport();
this.LazyLoading = true;
}
public override object Text
@ -51,30 +48,11 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer @@ -51,30 +48,11 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
get { return showWrites ? "Assigned By" : "Read 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)
protected override IEnumerable<AnalyzerTreeNode> FetchChildren(CancellationToken ct)
{
foundMethods = new Lazy<Hashtable>(LazyThreadSafetyMode.ExecutionAndPublication);
var analyzer = new ScopedWhereUsedAnalyzer<SharpTreeNode>(analyzedField, FindReferencesInType);
var analyzer = new ScopedWhereUsedAnalyzer<AnalyzerTreeNode>(analyzedField, FindReferencesInType);
foreach (var child in analyzer.PerformAnalysis(ct).OrderBy(n => n.Text)) {
yield return child;
}
@ -82,7 +60,7 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer @@ -82,7 +60,7 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
foundMethods = null;
}
private IEnumerable<SharpTreeNode> FindReferencesInType(TypeDefinition type)
private IEnumerable<AnalyzerTreeNode> FindReferencesInType(TypeDefinition type)
{
string name = analyzedField.Name;
string declTypeName = analyzedField.DeclaringType.FullName;

11
ILSpy/TreeNodes/Analyzer/AnalyzedFieldTreeNode.cs

@ -21,7 +21,7 @@ using Mono.Cecil; @@ -21,7 +21,7 @@ using Mono.Cecil;
namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
{
internal class AnalyzedFieldTreeNode : AnalyzerTreeNode, IMemberTreeNode
internal class AnalyzedFieldTreeNode : AnalyzerEntityTreeNode
{
private readonly FieldDefinition analyzedField;
@ -47,12 +47,6 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer @@ -47,12 +47,6 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
}
}
public override void ActivateItem(System.Windows.RoutedEventArgs e)
{
e.Handled = true;
MainWindow.Instance.JumpToReference(analyzedField);
}
protected override void LoadChildren()
{
this.Children.Add(new AnalyzedFieldAccessTreeNode(analyzedField, false));
@ -60,8 +54,7 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer @@ -60,8 +54,7 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
this.Children.Add(new AnalyzedFieldAccessTreeNode(analyzedField, true));
}
MemberReference IMemberTreeNode.Member
{
public override MemberReference Member {
get { return analyzedField; }
}
}

31
ILSpy/TreeNodes/Analyzer/AnalyzedInterfaceEventImplementedByTreeNode.cs

@ -26,11 +26,10 @@ using Mono.Cecil; @@ -26,11 +26,10 @@ using Mono.Cecil;
namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
{
internal sealed class AnalyzedInterfaceEventImplementedByTreeNode : AnalyzerTreeNode
internal sealed class AnalyzedInterfaceEventImplementedByTreeNode : AnalyzerSearchTreeNode
{
private readonly EventDefinition analyzedEvent;
private readonly MethodDefinition analyzedMethod;
private readonly ThreadingSupport threading;
public AnalyzedInterfaceEventImplementedByTreeNode(EventDefinition analyzedEvent)
{
@ -39,8 +38,6 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer @@ -39,8 +38,6 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
this.analyzedEvent = analyzedEvent;
this.analyzedMethod = this.analyzedEvent.AddMethod ?? this.analyzedEvent.RemoveMethod;
this.threading = new ThreadingSupport();
this.LazyLoading = true;
}
public override object Text
@ -48,35 +45,15 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer @@ -48,35 +45,15 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
get { return "Implemented By"; }
}
public override object Icon
protected override IEnumerable<AnalyzerTreeNode> FetchChildren(CancellationToken ct)
{
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)
{
ScopedWhereUsedAnalyzer<SharpTreeNode> analyzer;
analyzer = new ScopedWhereUsedAnalyzer<SharpTreeNode>(analyzedMethod, FindReferencesInType);
var analyzer = new ScopedWhereUsedAnalyzer<AnalyzerTreeNode>(analyzedMethod, FindReferencesInType);
foreach (var child in analyzer.PerformAnalysis(ct).OrderBy(n => n.Text)) {
yield return child;
}
}
private IEnumerable<SharpTreeNode> FindReferencesInType(TypeDefinition type)
private IEnumerable<AnalyzerTreeNode> FindReferencesInType(TypeDefinition type)
{
if (!type.HasInterfaces)
yield break;

31
ILSpy/TreeNodes/Analyzer/AnalyzedInterfaceMethodImplementedByTreeNode.cs

@ -26,10 +26,9 @@ using Mono.Cecil; @@ -26,10 +26,9 @@ using Mono.Cecil;
namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
{
internal sealed class AnalyzedInterfaceMethodImplementedByTreeNode : AnalyzerTreeNode
internal sealed class AnalyzedInterfaceMethodImplementedByTreeNode : AnalyzerSearchTreeNode
{
private readonly MethodDefinition analyzedMethod;
private readonly ThreadingSupport threading;
public AnalyzedInterfaceMethodImplementedByTreeNode(MethodDefinition analyzedMethod)
{
@ -37,8 +36,6 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer @@ -37,8 +36,6 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
throw new ArgumentNullException("analyzedMethod");
this.analyzedMethod = analyzedMethod;
this.threading = new ThreadingSupport();
this.LazyLoading = true;
}
public override object Text
@ -46,35 +43,15 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer @@ -46,35 +43,15 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
get { return "Implemented By"; }
}
public override object Icon
protected override IEnumerable<AnalyzerTreeNode> FetchChildren(CancellationToken ct)
{
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)
{
ScopedWhereUsedAnalyzer<SharpTreeNode> analyzer;
analyzer = new ScopedWhereUsedAnalyzer<SharpTreeNode>(analyzedMethod, FindReferencesInType);
var analyzer = new ScopedWhereUsedAnalyzer<AnalyzerTreeNode>(analyzedMethod, FindReferencesInType);
foreach (var child in analyzer.PerformAnalysis(ct).OrderBy(n => n.Text)) {
yield return child;
}
}
private IEnumerable<SharpTreeNode> FindReferencesInType(TypeDefinition type)
private IEnumerable<AnalyzerTreeNode> FindReferencesInType(TypeDefinition type)
{
if (!type.HasInterfaces)
yield break;

31
ILSpy/TreeNodes/Analyzer/AnalyzedInterfacePropertyImplementedByTreeNode.cs

@ -26,11 +26,10 @@ using Mono.Cecil; @@ -26,11 +26,10 @@ using Mono.Cecil;
namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
{
internal sealed class AnalyzedInterfacePropertyImplementedByTreeNode : AnalyzerTreeNode
internal sealed class AnalyzedInterfacePropertyImplementedByTreeNode : AnalyzerSearchTreeNode
{
private readonly PropertyDefinition analyzedProperty;
private readonly MethodDefinition analyzedMethod;
private readonly ThreadingSupport threading;
public AnalyzedInterfacePropertyImplementedByTreeNode(PropertyDefinition analyzedProperty)
{
@ -39,8 +38,6 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer @@ -39,8 +38,6 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
this.analyzedProperty = analyzedProperty;
this.analyzedMethod = this.analyzedProperty.GetMethod ?? this.analyzedProperty.SetMethod;
this.threading = new ThreadingSupport();
this.LazyLoading = true;
}
public override object Text
@ -48,35 +45,15 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer @@ -48,35 +45,15 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
get { return "Implemented By"; }
}
public override object Icon
protected override IEnumerable<AnalyzerTreeNode> FetchChildren(CancellationToken ct)
{
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)
{
ScopedWhereUsedAnalyzer<SharpTreeNode> analyzer;
analyzer = new ScopedWhereUsedAnalyzer<SharpTreeNode>(analyzedMethod, FindReferencesInType);
var analyzer = new ScopedWhereUsedAnalyzer<AnalyzerTreeNode>(analyzedMethod, FindReferencesInType);
foreach (var child in analyzer.PerformAnalysis(ct).OrderBy(n => n.Text)) {
yield return child;
}
}
private IEnumerable<SharpTreeNode> FindReferencesInType(TypeDefinition type)
private IEnumerable<AnalyzerTreeNode> FindReferencesInType(TypeDefinition type)
{
if (!type.HasInterfaces)
yield break;

32
ILSpy/TreeNodes/Analyzer/AnalyzedMethodOverridesTreeNode.cs

@ -32,10 +32,9 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer @@ -32,10 +32,9 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
/// <summary>
/// Searches for overrides of the analyzed method.
/// </summary>
internal sealed class AnalyzedMethodOverridesTreeNode : AnalyzerTreeNode
internal sealed class AnalyzedMethodOverridesTreeNode : AnalyzerSearchTreeNode
{
private readonly MethodDefinition analyzedMethod;
private readonly ThreadingSupport threading;
public AnalyzedMethodOverridesTreeNode(MethodDefinition analyzedMethod)
{
@ -43,8 +42,6 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer @@ -43,8 +42,6 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
throw new ArgumentNullException("analyzedMethod");
this.analyzedMethod = analyzedMethod;
this.threading = new ThreadingSupport();
this.LazyLoading = true;
}
public override object Text
@ -52,36 +49,15 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer @@ -52,36 +49,15 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
get { return "Overridden By"; }
}
public override object Icon
protected override IEnumerable<AnalyzerTreeNode> FetchChildren(CancellationToken ct)
{
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)
{
ScopedWhereUsedAnalyzer<SharpTreeNode> analyzer;
analyzer = new ScopedWhereUsedAnalyzer<SharpTreeNode>(analyzedMethod, FindReferencesInType);
var analyzer = new ScopedWhereUsedAnalyzer<AnalyzerTreeNode>(analyzedMethod, FindReferencesInType);
foreach (var child in analyzer.PerformAnalysis(ct).OrderBy(n => n.Text)) {
yield return child;
}
}
private IEnumerable<SharpTreeNode> FindReferencesInType(TypeDefinition type)
private IEnumerable<AnalyzerTreeNode> FindReferencesInType(TypeDefinition type)
{
AnalyzerTreeNode newNode = null;
try {

11
ILSpy/TreeNodes/Analyzer/AnalyzedMethodTreeNode.cs

@ -21,7 +21,7 @@ using Mono.Cecil; @@ -21,7 +21,7 @@ using Mono.Cecil;
namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
{
internal class AnalyzedMethodTreeNode : AnalyzerTreeNode, IMemberTreeNode
internal class AnalyzedMethodTreeNode : AnalyzerEntityTreeNode
{
private readonly MethodDefinition analyzedMethod;
private readonly string prefix;
@ -48,12 +48,6 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer @@ -48,12 +48,6 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
}
}
public override void ActivateItem(System.Windows.RoutedEventArgs e)
{
e.Handled = true;
MainWindow.Instance.JumpToReference(analyzedMethod);
}
protected override void LoadChildren()
{
if (analyzedMethod.HasBody)
@ -71,8 +65,7 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer @@ -71,8 +65,7 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
this.Children.Add(new AnalyzedInterfaceMethodImplementedByTreeNode(analyzedMethod));
}
MemberReference IMemberTreeNode.Member
{
public override MemberReference Member {
get { return analyzedMethod; }
}
}

30
ILSpy/TreeNodes/Analyzer/AnalyzedMethodUsedByTreeNode.cs

@ -27,10 +27,9 @@ using Mono.Cecil.Cil; @@ -27,10 +27,9 @@ using Mono.Cecil.Cil;
namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
{
internal sealed class AnalyzedMethodUsedByTreeNode : AnalyzerTreeNode
internal sealed class AnalyzedMethodUsedByTreeNode : AnalyzerSearchTreeNode
{
private readonly MethodDefinition analyzedMethod;
private readonly ThreadingSupport threading;
private ConcurrentDictionary<MethodDefinition, int> foundMethods;
public AnalyzedMethodUsedByTreeNode(MethodDefinition analyzedMethod)
@ -39,8 +38,6 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer @@ -39,8 +38,6 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
throw new ArgumentNullException("analyzedMethod");
this.analyzedMethod = analyzedMethod;
this.threading = new ThreadingSupport();
this.LazyLoading = true;
}
public override object Text
@ -48,30 +45,11 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer @@ -48,30 +45,11 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
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)
protected override IEnumerable<AnalyzerTreeNode> FetchChildren(CancellationToken ct)
{
foundMethods = new ConcurrentDictionary<MethodDefinition, int>();
var analyzer = new ScopedWhereUsedAnalyzer<SharpTreeNode>(analyzedMethod, FindReferencesInType);
var analyzer = new ScopedWhereUsedAnalyzer<AnalyzerTreeNode>(analyzedMethod, FindReferencesInType);
foreach (var child in analyzer.PerformAnalysis(ct).OrderBy(n => n.Text)) {
yield return child;
}
@ -79,7 +57,7 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer @@ -79,7 +57,7 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
foundMethods = null;
}
private IEnumerable<SharpTreeNode> FindReferencesInType(TypeDefinition type)
private IEnumerable<AnalyzerTreeNode> FindReferencesInType(TypeDefinition type)
{
string name = analyzedMethod.Name;
foreach (MethodDefinition method in type.Methods) {

19
ILSpy/TreeNodes/Analyzer/AnalyzedMethodUsesTreeNode.cs

@ -19,6 +19,7 @@ @@ -19,6 +19,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Mono.Cecil;
using Mono.Cecil.Cil;
@ -27,7 +28,7 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer @@ -27,7 +28,7 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
/// <summary>
/// Shows the methods that are used by this method.
/// </summary>
internal sealed class AnalyzedMethodUsesTreeNode : AnalyzerTreeNode
internal sealed class AnalyzedMethodUsesTreeNode : AnalyzerSearchTreeNode
{
private readonly MethodDefinition analyzedMethod;
@ -37,7 +38,6 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer @@ -37,7 +38,6 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
throw new ArgumentNullException("analyzedMethod");
this.analyzedMethod = analyzedMethod;
this.LazyLoading = true;
}
public override object Text
@ -45,20 +45,7 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer @@ -45,20 +45,7 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
get { return "Uses"; }
}
public override object Icon
{
get { return Images.Search; }
}
protected override void LoadChildren()
{
analyzedMethod.Body = null;
foreach (var child in GetChildren().OrderBy(n => n.Text)) {
this.Children.Add(child);
}
}
private IEnumerable<AnalyzerTreeNode> GetChildren()
protected override IEnumerable<AnalyzerTreeNode> FetchChildren(CancellationToken ct)
{
foreach (var f in GetUsedFields().Distinct()) {
var node = new AnalyzedFieldTreeNode(f);

32
ILSpy/TreeNodes/Analyzer/AnalyzedPropertyOverridesTreeNode.cs

@ -28,10 +28,9 @@ using Mono.Cecil; @@ -28,10 +28,9 @@ using Mono.Cecil;
namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
{
internal sealed class AnalyzedPropertyOverridesTreeNode : AnalyzerTreeNode
internal sealed class AnalyzedPropertyOverridesTreeNode : AnalyzerSearchTreeNode
{
private readonly PropertyDefinition analyzedProperty;
private readonly ThreadingSupport threading;
public AnalyzedPropertyOverridesTreeNode(PropertyDefinition analyzedProperty)
{
@ -39,8 +38,6 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer @@ -39,8 +38,6 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
throw new ArgumentNullException("analyzedProperty");
this.analyzedProperty = analyzedProperty;
this.threading = new ThreadingSupport();
this.LazyLoading = true;
}
public override object Text
@ -48,36 +45,15 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer @@ -48,36 +45,15 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
get { return "Overridden By"; }
}
public override object Icon
protected override IEnumerable<AnalyzerTreeNode> FetchChildren(CancellationToken ct)
{
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)
{
ScopedWhereUsedAnalyzer<SharpTreeNode> analyzer;
analyzer = new ScopedWhereUsedAnalyzer<SharpTreeNode>(analyzedProperty, FindReferencesInType);
var analyzer = new ScopedWhereUsedAnalyzer<AnalyzerTreeNode>(analyzedProperty, FindReferencesInType);
foreach (var child in analyzer.PerformAnalysis(ct).OrderBy(n => n.Text)) {
yield return child;
}
}
private IEnumerable<SharpTreeNode> FindReferencesInType(TypeDefinition type)
private IEnumerable<AnalyzerTreeNode> FindReferencesInType(TypeDefinition type)
{
string name = analyzedProperty.Name;
string declTypeName = analyzedProperty.DeclaringType.FullName;

12
ILSpy/TreeNodes/Analyzer/AnalyzedPropertyTreeNode.cs

@ -22,7 +22,7 @@ using Mono.Cecil; @@ -22,7 +22,7 @@ using Mono.Cecil;
namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
{
internal sealed class AnalyzedPropertyTreeNode : AnalyzerTreeNode
internal sealed class AnalyzedPropertyTreeNode : AnalyzerEntityTreeNode
{
private readonly PropertyDefinition analyzedProperty;
private readonly bool isIndexer;
@ -52,12 +52,6 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer @@ -52,12 +52,6 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
}
}
public override void ActivateItem(System.Windows.RoutedEventArgs e)
{
e.Handled = true;
MainWindow.Instance.JumpToReference(analyzedProperty);
}
protected override void LoadChildren()
{
if (analyzedProperty.GetMethod != null)
@ -90,5 +84,9 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer @@ -90,5 +84,9 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
return !MainWindow.Instance.CurrentLanguage.ShowMember(property.GetMethod ?? property.SetMethod)
|| AnalyzedPropertyOverridesTreeNode.CanShow(property);
}
public override MemberReference Member {
get { return analyzedProperty; }
}
}
}

32
ILSpy/TreeNodes/Analyzer/AnalyzedTypeExposedByTreeNode.cs

@ -25,10 +25,9 @@ using Mono.Cecil; @@ -25,10 +25,9 @@ using Mono.Cecil;
namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
{
internal sealed class AnalyzedTypeExposedByTreeNode : AnalyzerTreeNode
internal sealed class AnalyzedTypeExposedByTreeNode : AnalyzerSearchTreeNode
{
private readonly TypeDefinition analyzedType;
private readonly ThreadingSupport threading;
public AnalyzedTypeExposedByTreeNode(TypeDefinition analyzedType)
{
@ -36,8 +35,6 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer @@ -36,8 +35,6 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
throw new ArgumentNullException("analyzedType");
this.analyzedType = analyzedType;
this.threading = new ThreadingSupport();
this.LazyLoading = true;
}
public override object Text
@ -45,36 +42,15 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer @@ -45,36 +42,15 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
get { return "Exposed By"; }
}
public override object Icon
protected override IEnumerable<AnalyzerTreeNode> FetchChildren(CancellationToken ct)
{
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)
{
ScopedWhereUsedAnalyzer<SharpTreeNode> analyzer;
analyzer = new ScopedWhereUsedAnalyzer<SharpTreeNode>(analyzedType, FindReferencesInType);
var analyzer = new ScopedWhereUsedAnalyzer<AnalyzerTreeNode>(analyzedType, FindReferencesInType);
foreach (var child in analyzer.PerformAnalysis(ct).OrderBy(n => n.Text)) {
yield return child;
}
}
private IEnumerable<SharpTreeNode> FindReferencesInType(TypeDefinition type)
private IEnumerable<AnalyzerTreeNode> FindReferencesInType(TypeDefinition type)
{
if (analyzedType.IsEnum && type == analyzedType)
yield break;

32
ILSpy/TreeNodes/Analyzer/AnalyzedTypeExtensionMethodsTreeNode.cs

@ -25,10 +25,9 @@ using Mono.Cecil; @@ -25,10 +25,9 @@ using Mono.Cecil;
namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
{
internal class AnalyzedTypeExtensionMethodsTreeNode : AnalyzerTreeNode
internal class AnalyzedTypeExtensionMethodsTreeNode : AnalyzerSearchTreeNode
{
private readonly TypeDefinition analyzedType;
private readonly ThreadingSupport threading;
public AnalyzedTypeExtensionMethodsTreeNode(TypeDefinition analyzedType)
{
@ -36,8 +35,6 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer @@ -36,8 +35,6 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
throw new ArgumentNullException("analyzedType");
this.analyzedType = analyzedType;
this.threading = new ThreadingSupport();
this.LazyLoading = true;
}
public override object Text
@ -45,36 +42,15 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer @@ -45,36 +42,15 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
get { return "Extension Methods"; }
}
public override object Icon
protected override IEnumerable<AnalyzerTreeNode> FetchChildren(CancellationToken ct)
{
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)
{
ScopedWhereUsedAnalyzer<SharpTreeNode> analyzer;
analyzer = new ScopedWhereUsedAnalyzer<SharpTreeNode>(analyzedType, FindReferencesInType);
var analyzer = new ScopedWhereUsedAnalyzer<AnalyzerTreeNode>(analyzedType, FindReferencesInType);
foreach (var child in analyzer.PerformAnalysis(ct).OrderBy(n => n.Text)) {
yield return child;
}
}
private IEnumerable<SharpTreeNode> FindReferencesInType(TypeDefinition type)
private IEnumerable<AnalyzerTreeNode> FindReferencesInType(TypeDefinition type)
{
if (!HasExtensionAttribute(type))
yield break;

32
ILSpy/TreeNodes/Analyzer/AnalyzedTypeInstantiationsTreeNode.cs

@ -27,10 +27,9 @@ using Mono.Cecil.Cil; @@ -27,10 +27,9 @@ using Mono.Cecil.Cil;
namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
{
internal sealed class AnalyzedTypeInstantiationsTreeNode : AnalyzerTreeNode
internal sealed class AnalyzedTypeInstantiationsTreeNode : AnalyzerSearchTreeNode
{
private readonly TypeDefinition analyzedType;
private readonly ThreadingSupport threading;
private readonly bool isSystemObject;
public AnalyzedTypeInstantiationsTreeNode(TypeDefinition analyzedType)
@ -39,8 +38,6 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer @@ -39,8 +38,6 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
throw new ArgumentNullException("analyzedType");
this.analyzedType = analyzedType;
this.threading = new ThreadingSupport();
this.LazyLoading = true;
this.isSystemObject = (analyzedType.FullName == "System.Object");
}
@ -50,36 +47,15 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer @@ -50,36 +47,15 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
get { return "Instantiated By"; }
}
public override object Icon
protected override IEnumerable<AnalyzerTreeNode> FetchChildren(CancellationToken ct)
{
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)
{
ScopedWhereUsedAnalyzer<SharpTreeNode> analyzer;
analyzer = new ScopedWhereUsedAnalyzer<SharpTreeNode>(analyzedType, FindReferencesInType);
var analyzer = new ScopedWhereUsedAnalyzer<AnalyzerTreeNode>(analyzedType, FindReferencesInType);
foreach (var child in analyzer.PerformAnalysis(ct).OrderBy(n => n.Text)) {
yield return child;
}
}
private IEnumerable<SharpTreeNode> FindReferencesInType(TypeDefinition type)
private IEnumerable<AnalyzerTreeNode> FindReferencesInType(TypeDefinition type)
{
foreach (MethodDefinition method in type.Methods) {
bool found = false;

11
ILSpy/TreeNodes/Analyzer/AnalyzedTypeTreeNode.cs

@ -21,7 +21,7 @@ using Mono.Cecil; @@ -21,7 +21,7 @@ using Mono.Cecil;
namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
{
internal class AnalyzedTypeTreeNode : AnalyzerTreeNode, IMemberTreeNode
internal class AnalyzedTypeTreeNode : AnalyzerEntityTreeNode
{
private readonly TypeDefinition analyzedType;
@ -46,12 +46,6 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer @@ -46,12 +46,6 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
}
}
public override void ActivateItem(System.Windows.RoutedEventArgs e)
{
e.Handled = true;
MainWindow.Instance.JumpToReference(analyzedType);
}
protected override void LoadChildren()
{
if (AnalyzedTypeInstantiationsTreeNode.CanShow(analyzedType))
@ -64,8 +58,7 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer @@ -64,8 +58,7 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
this.Children.Add(new AnalyzedTypeExtensionMethodsTreeNode(analyzedType));
}
MemberReference IMemberTreeNode.Member
{
public override MemberReference Member {
get { return analyzedType; }
}
}

30
ILSpy/TreeNodes/Analyzer/AnalyzedVirtualMethodUsedByTreeNode.cs

@ -28,10 +28,9 @@ using ICSharpCode.Decompiler.Ast; @@ -28,10 +28,9 @@ using ICSharpCode.Decompiler.Ast;
namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
{
internal sealed class AnalyzedVirtualMethodUsedByTreeNode : AnalyzerTreeNode
internal sealed class AnalyzedVirtualMethodUsedByTreeNode : AnalyzerSearchTreeNode
{
private readonly MethodDefinition analyzedMethod;
private readonly ThreadingSupport threading;
private ConcurrentDictionary<MethodDefinition, int> foundMethods;
private MethodDefinition baseMethod;
private List<TypeReference> possibleTypes;
@ -42,8 +41,6 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer @@ -42,8 +41,6 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
throw new ArgumentNullException("analyzedMethod");
this.analyzedMethod = analyzedMethod;
this.threading = new ThreadingSupport();
this.LazyLoading = true;
}
public override object Text
@ -51,30 +48,11 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer @@ -51,30 +48,11 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
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)
protected override IEnumerable<AnalyzerTreeNode> FetchChildren(CancellationToken ct)
{
InitializeAnalyzer();
var analyzer = new ScopedWhereUsedAnalyzer<SharpTreeNode>(analyzedMethod, FindReferencesInType);
var analyzer = new ScopedWhereUsedAnalyzer<AnalyzerTreeNode>(analyzedMethod, FindReferencesInType);
foreach (var child in analyzer.PerformAnalysis(ct).OrderBy(n => n.Text)) {
yield return child;
}
@ -107,7 +85,7 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer @@ -107,7 +85,7 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
baseMethod = null;
}
private IEnumerable<SharpTreeNode> FindReferencesInType(TypeDefinition type)
private IEnumerable<AnalyzerTreeNode> FindReferencesInType(TypeDefinition type)
{
string name = analyzedMethod.Name;
foreach (MethodDefinition method in type.Methods) {

53
ILSpy/TreeNodes/Analyzer/AnalyzerEntityTreeNode.cs

@ -0,0 +1,53 @@ @@ -0,0 +1,53 @@
// 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.Generic;
using ICSharpCode.TreeView;
using Mono.Cecil;
namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
{
/// <summary>
/// Base class for entity nodes.
/// </summary>
public abstract class AnalyzerEntityTreeNode : AnalyzerTreeNode, IMemberTreeNode
{
public abstract MemberReference Member { get; }
public override void ActivateItem(System.Windows.RoutedEventArgs e)
{
e.Handled = true;
MainWindow.Instance.JumpToReference(this.Member);
}
public override bool HandleAssemblyListChanged(ICollection<LoadedAssembly> removedAssemblies, ICollection<LoadedAssembly> addedAssemblies)
{
foreach (LoadedAssembly asm in removedAssemblies) {
if (this.Member.Module.Assembly == asm.AssemblyDefinition)
return false; // remove this node
}
this.Children.RemoveAll(
delegate(SharpTreeNode n) {
AnalyzerTreeNode an = n as AnalyzerTreeNode;
return an == null || !an.HandleAssemblyListChanged(removedAssemblies, addedAssemblies);
});
return true;
}
}
}

67
ILSpy/TreeNodes/Analyzer/AnalyzerSearchTreeNode.cs

@ -0,0 +1,67 @@ @@ -0,0 +1,67 @@
// 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.Generic;
using System.Threading;
namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
{
/// <summary>
/// Base class for analyzer nodes that perform a search.
/// </summary>
public abstract class AnalyzerSearchTreeNode : AnalyzerTreeNode
{
private readonly ThreadingSupport threading = new ThreadingSupport();
protected AnalyzerSearchTreeNode()
{
this.LazyLoading = true;
}
public override object Icon
{
get { return Images.Search; }
}
protected override void LoadChildren()
{
threading.LoadChildren(this, FetchChildren);
}
protected abstract IEnumerable<AnalyzerTreeNode> FetchChildren(CancellationToken ct);
protected override void OnIsVisibleChanged()
{
base.OnIsVisibleChanged();
if (!this.IsVisible && threading.IsRunning) {
this.LazyLoading = true;
threading.Cancel();
this.Children.Clear();
}
}
public override bool HandleAssemblyListChanged(ICollection<LoadedAssembly> removedAssemblies, ICollection<LoadedAssembly> addedAssemblies)
{
this.LazyLoading = true;
threading.Cancel();
this.Children.Clear();
return true;
}
}
}

11
ILSpy/TreeNodes/Analyzer/AnalyzerTreeNode.cs

@ -17,12 +17,14 @@ @@ -17,12 +17,14 @@
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using ICSharpCode.TreeView;
namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
{
public class AnalyzerTreeNode : SharpTreeNode
public abstract class AnalyzerTreeNode : SharpTreeNode
{
private Language language;
@ -54,7 +56,7 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer @@ -54,7 +56,7 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
DeleteCore();
}
protected override void OnChildrenChanged(System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
protected override void OnChildrenChanged(NotifyCollectionChangedEventArgs e)
{
if (e.NewItems != null) {
foreach (AnalyzerTreeNode a in e.NewItems.OfType<AnalyzerTreeNode>())
@ -62,5 +64,10 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer @@ -62,5 +64,10 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
}
base.OnChildrenChanged(e);
}
/// <summary>
/// Handles changes to the assembly list.
/// </summary>
public abstract bool HandleAssemblyListChanged(ICollection<LoadedAssembly> removedAssemblies, ICollection<LoadedAssembly> addedAssemblies);
}
}

15
ILSpy/TreeNodes/Analyzer/ScopedWhereUsedAnalyzer.cs

@ -128,7 +128,7 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer @@ -128,7 +128,7 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
DetermineTypeAccessibility();
if (typeAccessibility == Accessibility.Private) {
return FindReferencesInTypeScope(ct);
return FindReferencesInEnclosingTypeScope(ct);
}
if (memberAccessibility == Accessibility.Internal ||
@ -139,7 +139,7 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer @@ -139,7 +139,7 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
return FindReferencesGlobal(ct);
}
private void DetermineTypeAccessibility()
{
while (typeScope.IsNested) {
@ -237,6 +237,17 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer @@ -237,6 +237,17 @@ namespace ICSharpCode.ILSpy.TreeNodes.Analyzer
}
}
private IEnumerable<T> FindReferencesInEnclosingTypeScope(CancellationToken ct)
{
foreach (TypeDefinition type in TreeTraversal.PreOrder(typeScope.DeclaringType, t => t.NestedTypes)) {
ct.ThrowIfCancellationRequested();
foreach (var result in typeAnalysisFunction(type)) {
ct.ThrowIfCancellationRequested();
yield return result;
}
}
}
private IEnumerable<AssemblyDefinition> GetReferencingAssemblies(AssemblyDefinition asm, CancellationToken ct)
{
yield return asm;

15
ILSpy/TreeNodes/ResourceNodes/CursorResourceEntryNode.cs

@ -40,11 +40,13 @@ namespace ICSharpCode.ILSpy.TreeNodes @@ -40,11 +40,13 @@ namespace ICSharpCode.ILSpy.TreeNodes
return null;
}
public ILSpyTreeNode CreateNode(string key, Stream data)
public ILSpyTreeNode CreateNode(string key, object data)
{
if (!(data is Stream))
return null;
foreach (string fileExt in imageFileExtensions) {
if (key.EndsWith(fileExt, StringComparison.OrdinalIgnoreCase))
return new CursorResourceEntryNode(key, data);
return new CursorResourceEntryNode(key, (Stream)data);
}
return null;
}
@ -71,7 +73,14 @@ namespace ICSharpCode.ILSpy.TreeNodes @@ -71,7 +73,14 @@ namespace ICSharpCode.ILSpy.TreeNodes
//HACK: windows imaging does not understand that .cur files have the same layout as .ico
// so load to data, and modify the ResourceType in the header to make look like an icon...
byte[] curData = ((MemoryStream)Data).ToArray();
MemoryStream s = Data as MemoryStream;
if (null == s)
{
// data was stored in another stream type (e.g. PinnedBufferedMemoryStream)
s = new MemoryStream();
Data.CopyTo(s);
}
byte[] curData = s.ToArray();
curData[2] = 1;
using (Stream stream = new MemoryStream(curData)) {
image.BeginInit();

2
ILSpy/TreeNodes/ResourceNodes/IResourceNodeFactory.cs

@ -28,6 +28,6 @@ namespace ICSharpCode.ILSpy.TreeNodes @@ -28,6 +28,6 @@ namespace ICSharpCode.ILSpy.TreeNodes
public interface IResourceNodeFactory
{
ILSpyTreeNode CreateNode(Resource resource);
ILSpyTreeNode CreateNode(string key, Stream data);
ILSpyTreeNode CreateNode(string key, object data);
}
}

18
ILSpy/TreeNodes/ResourceNodes/ImageResourceEntryNode.cs

@ -40,11 +40,25 @@ namespace ICSharpCode.ILSpy.TreeNodes @@ -40,11 +40,25 @@ namespace ICSharpCode.ILSpy.TreeNodes
return null;
}
public ILSpyTreeNode CreateNode(string key, Stream data)
public ILSpyTreeNode CreateNode(string key, object data)
{
if (data is System.Drawing.Icon)
{
MemoryStream s = new MemoryStream();
((System.Drawing.Icon)data).Save(s);
return new ImageResourceEntryNode(key, s);
}
else if (data is System.Drawing.Image)
{
MemoryStream s = new MemoryStream();
((System.Drawing.Image)data).Save(s, System.Drawing.Imaging.ImageFormat.Bmp);
return new ImageResourceEntryNode(key, s);
}
if (!(data is Stream))
return null;
foreach (string fileExt in imageFileExtensions) {
if (key.EndsWith(fileExt, StringComparison.OrdinalIgnoreCase))
return new ImageResourceEntryNode(key, data);
return new ImageResourceEntryNode(key, (Stream)data);
}
return null;
}

4
ILSpy/TreeNodes/ResourceNodes/ResourceEntryNode.cs

@ -62,7 +62,7 @@ namespace ICSharpCode.ILSpy.TreeNodes @@ -62,7 +62,7 @@ namespace ICSharpCode.ILSpy.TreeNodes
this.data = data;
}
public static ILSpyTreeNode Create(string key, Stream data)
public static ILSpyTreeNode Create(string key, object data)
{
ILSpyTreeNode result = null;
foreach (var factory in App.CompositionContainer.GetExportedValues<IResourceNodeFactory>()) {
@ -70,7 +70,7 @@ namespace ICSharpCode.ILSpy.TreeNodes @@ -70,7 +70,7 @@ namespace ICSharpCode.ILSpy.TreeNodes
if (result != null)
break;
}
return result ?? new ResourceEntryNode(key, data);
return result ?? new ResourceEntryNode(key, data as Stream);
}
public override void Decompile(Language language, ITextOutput output, DecompilationOptions options)

31
ILSpy/TreeNodes/ResourceNodes/ResourcesFileTreeNode.cs

@ -18,10 +18,15 @@ @@ -18,10 +18,15 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.Composition;
using System.IO;
using System.Linq;
using System.Resources;
using ICSharpCode.Decompiler;
using ICSharpCode.ILSpy.Controls;
using Mono.Cecil;
namespace ICSharpCode.ILSpy.TreeNodes
@ -38,7 +43,7 @@ namespace ICSharpCode.ILSpy.TreeNodes @@ -38,7 +43,7 @@ namespace ICSharpCode.ILSpy.TreeNodes
return null;
}
public ILSpyTreeNode CreateNode(string key, Stream data)
public ILSpyTreeNode CreateNode(string key, object data)
{
return null;
}
@ -46,6 +51,8 @@ namespace ICSharpCode.ILSpy.TreeNodes @@ -46,6 +51,8 @@ namespace ICSharpCode.ILSpy.TreeNodes
sealed class ResourcesFileTreeNode : ResourceTreeNode
{
ICollection<KeyValuePair<string, string>> filteredEntries = new ObservableCollection<KeyValuePair<string, string>>();
public ResourcesFileTreeNode(EmbeddedResource er)
: base(er)
{
@ -71,12 +78,30 @@ namespace ICSharpCode.ILSpy.TreeNodes @@ -71,12 +78,30 @@ namespace ICSharpCode.ILSpy.TreeNodes
return;
}
foreach (DictionaryEntry entry in reader.Cast<DictionaryEntry>().OrderBy(e => e.Key.ToString())) {
if (entry.Value is Stream)
Children.Add(ResourceEntryNode.Create(entry.Key.ToString(), (Stream)entry.Value));
if (entry.Value is String)
filteredEntries.Add(new KeyValuePair<string, string>(entry.Key.ToString(), (string)entry.Value));
else if (entry.Value is byte[])
Children.Add(ResourceEntryNode.Create(entry.Key.ToString(), new MemoryStream((byte[])entry.Value)));
else
Children.Add(ResourceEntryNode.Create(entry.Key.ToString(), entry.Value));
}
}
}
public override void Decompile(Language language, ITextOutput output, DecompilationOptions options)
{
base.Decompile(language, output, options);
if (filteredEntries.Count == 0)
return;
ISmartTextOutput smartOutput = output as ISmartTextOutput;
if (null != smartOutput) {
smartOutput.AddUIElement(
delegate {
return new ResourceStringTable(filteredEntries);
}
);
}
output.WriteLine();
}
}
}

6
ILSpy/TreeNodes/ResourceNodes/XamlResourceNode.cs

@ -35,10 +35,10 @@ namespace ICSharpCode.ILSpy.Xaml @@ -35,10 +35,10 @@ namespace ICSharpCode.ILSpy.Xaml
return null;
}
public ILSpyTreeNode CreateNode(string key, Stream data)
public ILSpyTreeNode CreateNode(string key, object data)
{
if (key.EndsWith(".xaml", StringComparison.OrdinalIgnoreCase))
return new XamlResourceEntryNode(key, data);
if (key.EndsWith(".xaml", StringComparison.OrdinalIgnoreCase) && data is Stream)
return new XamlResourceEntryNode(key, (Stream)data);
else
return null;
}

10
ILSpy/TreeNodes/ResourceNodes/XmlResourceNode.cs

@ -41,12 +41,16 @@ namespace ICSharpCode.ILSpy.Xaml @@ -41,12 +41,16 @@ namespace ICSharpCode.ILSpy.Xaml
return null;
}
public ILSpyTreeNode CreateNode(string key, Stream data)
public ILSpyTreeNode CreateNode(string key, object data)
{
if (!(data is Stream))
return null;
foreach (string fileExt in xmlFileExtensions)
{
if (key.EndsWith(fileExt, StringComparison.OrdinalIgnoreCase))
return new XmlResourceEntryNode(key, data);
return null;
return new XmlResourceEntryNode(key, (Stream)data);
}
return null;
}
}

2
ILSpy/TreeNodes/ThreadingSupport.cs

@ -36,7 +36,7 @@ namespace ICSharpCode.ILSpy.TreeNodes @@ -36,7 +36,7 @@ namespace ICSharpCode.ILSpy.TreeNodes
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
public bool IsRunning {
get { return !loadChildrenTask.IsCompleted; }
get { return loadChildrenTask != null && !loadChildrenTask.IsCompleted; }
}
public void Cancel()

152
ILSpy/VB/ILSpyEnvironmentProvider.cs

@ -0,0 +1,152 @@ @@ -0,0 +1,152 @@
// 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.Generic;
using System.Linq;
using ICSharpCode.Decompiler;
using ICSharpCode.Decompiler.Ast;
using ICSharpCode.NRefactory.TypeSystem;
using ICSharpCode.NRefactory.VB.Visitors;
using Mono.Cecil;
namespace ICSharpCode.ILSpy.VB
{
public class ILSpyEnvironmentProvider : IEnvironmentProvider
{
public string RootNamespace {
get {
return "";
}
}
ITypeResolveContext context;
CecilLoader loader = new CecilLoader(false);
public ILSpyEnvironmentProvider(ITypeResolveContext context)
{
this.context = context;
}
public ITypeResolveContext ResolveContext {
get {
return context;
}
}
public string GetTypeNameForAttribute(ICSharpCode.NRefactory.CSharp.Attribute attribute)
{
return attribute.Type.Annotations
.OfType<Mono.Cecil.MemberReference>()
.First()
.FullName;
}
public IType ResolveType(NRefactory.VB.Ast.AstType type, NRefactory.VB.Ast.TypeDeclaration entity = null)
{
var annotation = type.Annotation<TypeReference>();
if (annotation == null )
return null;
IEntity current = null;
if (entity != null) {
var typeInfo = entity.Annotation<TypeReference>();
current = loader.ReadTypeReference(typeInfo).Resolve(context).GetDefinition();
}
return loader.ReadTypeReference(annotation, entity: current).Resolve(context);
}
public ClassType GetClassTypeForAstType(ICSharpCode.NRefactory.CSharp.AstType type)
{
var definition = type.Annotations.OfType<TypeReference>().First().ResolveOrThrow();
if (definition.IsClass)
return ClassType.Class;
if (definition.IsInterface)
return ClassType.Interface;
if (definition.IsEnum)
return ClassType.Enum;
if (definition.IsFunctionPointer)
return ClassType.Delegate;
if (definition.IsValueType)
return ClassType.Struct;
return ClassType.Module;
}
public TypeCode ResolveExpression(ICSharpCode.NRefactory.CSharp.Expression expression)
{
var annotation = expression.Annotations.OfType<TypeInformation>().FirstOrDefault();
if (annotation == null)
return TypeCode.Object;
var definition = annotation.InferredType.Resolve();
if (definition == null)
return TypeCode.Object;
switch (definition.FullName) {
case "System.String":
return TypeCode.String;
default:
break;
}
return TypeCode.Object;
}
public Nullable<bool> IsReferenceType(ICSharpCode.NRefactory.CSharp.Expression expression)
{
if (expression is ICSharpCode.NRefactory.CSharp.NullReferenceExpression)
return true;
var annotation = expression.Annotations.OfType<TypeInformation>().FirstOrDefault();
if (annotation == null)
return null;
var definition = annotation.InferredType.Resolve();
if (definition == null)
return null;
return !definition.IsValueType;
}
public IEnumerable<NRefactory.VB.Ast.InterfaceMemberSpecifier> CreateMemberSpecifiersForInterfaces(IEnumerable<NRefactory.VB.Ast.AstType> interfaces)
{
foreach (var type in interfaces) {
var def = type.Annotation<TypeReference>().Resolve();
if (def == null) continue;
foreach (var method in def.Methods.Where(m => !m.Name.StartsWith("get_") && !m.Name.StartsWith("set_"))) {
yield return new NRefactory.VB.Ast.InterfaceMemberSpecifier((NRefactory.VB.Ast.AstType)type.Clone(), method.Name);
}
foreach (var property in def.Properties) {
yield return new NRefactory.VB.Ast.InterfaceMemberSpecifier((NRefactory.VB.Ast.AstType)type.Clone(), property.Name);
}
}
}
}
}

523
ILSpy/VB/VBLanguage.cs

@ -0,0 +1,523 @@ @@ -0,0 +1,523 @@
// 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;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
using System.Linq;
using System.Resources;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using ICSharpCode.Decompiler;
using ICSharpCode.Decompiler.Ast;
using ICSharpCode.Decompiler.Ast.Transforms;
using ICSharpCode.ILSpy.XmlDoc;
using ICSharpCode.NRefactory.TypeSystem;
using ICSharpCode.NRefactory.TypeSystem.Implementation;
using ICSharpCode.NRefactory.VB;
using ICSharpCode.NRefactory.VB.Visitors;
using Mono.Cecil;
namespace ICSharpCode.ILSpy.VB
{
/// <summary>
/// Decompiler logic for VB.
/// </summary>
[Export(typeof(Language))]
public class VBLanguage : Language
{
Predicate<IAstTransform> transformAbortCondition = null;
bool showAllMembers = false;
public VBLanguage()
{
}
public override string Name {
get { return "VB"; }
}
public override string FileExtension {
get { return ".vb"; }
}
public override string ProjectFileExtension {
get { return ".vbproj"; }
}
public override void WriteCommentLine(ITextOutput output, string comment)
{
output.WriteLine("' " + comment);
}
public override void DecompileAssembly(LoadedAssembly assembly, ITextOutput output, DecompilationOptions options)
{
if (options.FullDecompilation && options.SaveAsProjectDirectory != null) {
HashSet<string> directories = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var files = WriteCodeFilesInProject(assembly.AssemblyDefinition, options, directories).ToList();
files.AddRange(WriteResourceFilesInProject(assembly, options, directories));
WriteProjectFile(new TextOutputWriter(output), files, assembly.AssemblyDefinition.MainModule);
} else {
base.DecompileAssembly(assembly, output, options);
output.WriteLine();
ModuleDefinition mainModule = assembly.AssemblyDefinition.MainModule;
if (mainModule.EntryPoint != null) {
output.Write("' Entry point: ");
output.WriteReference(mainModule.EntryPoint.DeclaringType.FullName + "." + mainModule.EntryPoint.Name, mainModule.EntryPoint);
output.WriteLine();
}
switch (mainModule.Architecture) {
case TargetArchitecture.I386:
if ((mainModule.Attributes & ModuleAttributes.Required32Bit) == ModuleAttributes.Required32Bit)
WriteCommentLine(output, "Architecture: x86");
else
WriteCommentLine(output, "Architecture: AnyCPU");
break;
case TargetArchitecture.AMD64:
WriteCommentLine(output, "Architecture: x64");
break;
case TargetArchitecture.IA64:
WriteCommentLine(output, "Architecture: Itanium-64");
break;
}
if ((mainModule.Attributes & ModuleAttributes.ILOnly) == 0) {
WriteCommentLine(output, "This assembly contains unmanaged code.");
}
switch (mainModule.Runtime) {
case TargetRuntime.Net_1_0:
WriteCommentLine(output, "Runtime: .NET 1.0");
break;
case TargetRuntime.Net_1_1:
WriteCommentLine(output, "Runtime: .NET 1.1");
break;
case TargetRuntime.Net_2_0:
WriteCommentLine(output, "Runtime: .NET 2.0");
break;
case TargetRuntime.Net_4_0:
WriteCommentLine(output, "Runtime: .NET 4.0");
break;
}
output.WriteLine();
// don't automatically load additional assemblies when an assembly node is selected in the tree view
using (options.FullDecompilation ? null : LoadedAssembly.DisableAssemblyLoad()) {
AstBuilder codeDomBuilder = CreateAstBuilder(options, currentModule: assembly.AssemblyDefinition.MainModule);
codeDomBuilder.AddAssembly(assembly.AssemblyDefinition, onlyAssemblyLevel: !options.FullDecompilation);
RunTransformsAndGenerateCode(codeDomBuilder, output, options, assembly.AssemblyDefinition.MainModule);
}
}
OnDecompilationFinished(null);
}
static readonly string[] projectImports = new[] {
"System.Diagnostics",
"Microsoft.VisualBasic",
"System",
"System.Collections",
"System.Collections.Generic"
};
#region WriteProjectFile
void WriteProjectFile(TextWriter writer, IEnumerable<Tuple<string, string>> files, ModuleDefinition module)
{
const string ns = "http://schemas.microsoft.com/developer/msbuild/2003";
string platformName;
switch (module.Architecture) {
case TargetArchitecture.I386:
if ((module.Attributes & ModuleAttributes.Required32Bit) == ModuleAttributes.Required32Bit)
platformName = "x86";
else
platformName = "AnyCPU";
break;
case TargetArchitecture.AMD64:
platformName = "x64";
break;
case TargetArchitecture.IA64:
platformName = "Itanium";
break;
default:
throw new NotSupportedException("Invalid value for TargetArchitecture");
}
using (XmlTextWriter w = new XmlTextWriter(writer)) {
w.Formatting = Formatting.Indented;
w.WriteStartDocument();
w.WriteStartElement("Project", ns);
w.WriteAttributeString("ToolsVersion", "4.0");
w.WriteAttributeString("DefaultTargets", "Build");
w.WriteStartElement("PropertyGroup");
w.WriteElementString("ProjectGuid", Guid.NewGuid().ToString().ToUpperInvariant());
w.WriteStartElement("Configuration");
w.WriteAttributeString("Condition", " '$(Configuration)' == '' ");
w.WriteValue("Debug");
w.WriteEndElement(); // </Configuration>
w.WriteStartElement("Platform");
w.WriteAttributeString("Condition", " '$(Platform)' == '' ");
w.WriteValue(platformName);
w.WriteEndElement(); // </Platform>
switch (module.Kind) {
case ModuleKind.Windows:
w.WriteElementString("OutputType", "WinExe");
break;
case ModuleKind.Console:
w.WriteElementString("OutputType", "Exe");
break;
default:
w.WriteElementString("OutputType", "Library");
break;
}
w.WriteElementString("AssemblyName", module.Assembly.Name.Name);
switch (module.Runtime) {
case TargetRuntime.Net_1_0:
w.WriteElementString("TargetFrameworkVersion", "v1.0");
break;
case TargetRuntime.Net_1_1:
w.WriteElementString("TargetFrameworkVersion", "v1.1");
break;
case TargetRuntime.Net_2_0:
w.WriteElementString("TargetFrameworkVersion", "v2.0");
// TODO: Detect when .NET 3.0/3.5 is required
break;
default:
w.WriteElementString("TargetFrameworkVersion", "v4.0");
// TODO: Detect TargetFrameworkProfile
break;
}
w.WriteElementString("WarningLevel", "4");
w.WriteEndElement(); // </PropertyGroup>
w.WriteStartElement("PropertyGroup"); // platform-specific
w.WriteAttributeString("Condition", " '$(Platform)' == '" + platformName + "' ");
w.WriteElementString("PlatformTarget", platformName);
w.WriteEndElement(); // </PropertyGroup> (platform-specific)
w.WriteStartElement("PropertyGroup"); // Debug
w.WriteAttributeString("Condition", " '$(Configuration)' == 'Debug' ");
w.WriteElementString("OutputPath", "bin\\Debug\\");
w.WriteElementString("DebugSymbols", "true");
w.WriteElementString("DebugType", "full");
w.WriteElementString("Optimize", "false");
w.WriteEndElement(); // </PropertyGroup> (Debug)
w.WriteStartElement("PropertyGroup"); // Release
w.WriteAttributeString("Condition", " '$(Configuration)' == 'Release' ");
w.WriteElementString("OutputPath", "bin\\Release\\");
w.WriteElementString("DebugSymbols", "true");
w.WriteElementString("DebugType", "pdbonly");
w.WriteElementString("Optimize", "true");
w.WriteEndElement(); // </PropertyGroup> (Release)
w.WriteStartElement("ItemGroup"); // References
foreach (AssemblyNameReference r in module.AssemblyReferences) {
if (r.Name != "mscorlib") {
w.WriteStartElement("Reference");
w.WriteAttributeString("Include", r.Name);
// TODO: RequiredTargetFramework
w.WriteEndElement();
}
}
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)) {
w.WriteStartElement("ItemGroup");
foreach (string file in gr.OrderBy(f => f, StringComparer.OrdinalIgnoreCase)) {
w.WriteStartElement(gr.Key);
w.WriteAttributeString("Include", file);
w.WriteEndElement();
}
w.WriteEndElement();
}
w.WriteStartElement("ItemGroup"); // Imports
foreach (var import in projectImports.OrderBy(x => x)) {
w.WriteStartElement("Import");
w.WriteAttributeString("Include", import);
w.WriteEndElement();
}
w.WriteEndElement(); // </ItemGroup> (Imports)
w.WriteStartElement("Import");
w.WriteAttributeString("Project", "$(MSBuildToolsPath)\\Microsoft.VisualBasic.targets");
w.WriteEndElement();
w.WriteEndDocument();
}
}
#endregion
#region WriteCodeFilesInProject
bool IncludeTypeWhenDecompilingProject(TypeDefinition type, DecompilationOptions options)
{
if (type.Name == "<Module>" || AstBuilder.MemberIsHidden(type, options.DecompilerSettings))
return false;
if (type.Namespace == "XamlGeneratedNamespace" && type.Name == "GeneratedInternalTypeHelper")
return false;
return true;
}
IEnumerable<Tuple<string, string>> WriteCodeFilesInProject(AssemblyDefinition assembly, DecompilationOptions options, HashSet<string> directories)
{
var files = assembly.MainModule.Types.Where(t => IncludeTypeWhenDecompilingProject(t, options)).GroupBy(
delegate(TypeDefinition type) {
string file = TextView.DecompilerTextView.CleanUpName(type.Name) + this.FileExtension;
if (string.IsNullOrEmpty(type.Namespace)) {
return file;
} else {
string dir = TextView.DecompilerTextView.CleanUpName(type.Namespace);
if (directories.Add(dir))
Directory.CreateDirectory(Path.Combine(options.SaveAsProjectDirectory, dir));
return Path.Combine(dir, file);
}
}, StringComparer.OrdinalIgnoreCase).ToList();
AstMethodBodyBuilder.ClearUnhandledOpcodes();
Parallel.ForEach(
files,
new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount },
delegate(IGrouping<string, TypeDefinition> file) {
using (StreamWriter w = new StreamWriter(Path.Combine(options.SaveAsProjectDirectory, file.Key))) {
AstBuilder codeDomBuilder = CreateAstBuilder(options, currentModule: assembly.MainModule);
foreach (TypeDefinition type in file) {
codeDomBuilder.AddType(type);
}
RunTransformsAndGenerateCode(codeDomBuilder, new PlainTextOutput(w), options, assembly.MainModule);
}
});
AstMethodBodyBuilder.PrintNumberOfUnhandledOpcodes();
return files.Select(f => Tuple.Create("Compile", f.Key));
}
#endregion
#region WriteResourceFilesInProject
IEnumerable<Tuple<string, string>> WriteResourceFilesInProject(LoadedAssembly assembly, DecompilationOptions options, HashSet<string> directories)
{
AppDomain bamlDecompilerAppDomain = null;
try {
foreach (EmbeddedResource r in assembly.AssemblyDefinition.MainModule.Resources.OfType<EmbeddedResource>()) {
string fileName;
Stream s = r.GetResourceStream();
s.Position = 0;
if (r.Name.EndsWith(".g.resources", StringComparison.OrdinalIgnoreCase)) {
IEnumerable<DictionaryEntry> rs = null;
try {
rs = new ResourceSet(s).Cast<DictionaryEntry>();
}
catch (ArgumentException) {
}
if (rs != null && rs.All(e => e.Value is Stream)) {
foreach (var pair in rs) {
fileName = Path.Combine(((string)pair.Key).Split('/').Select(p => TextView.DecompilerTextView.CleanUpName(p)).ToArray());
string dirName = Path.GetDirectoryName(fileName);
if (!string.IsNullOrEmpty(dirName) && directories.Add(dirName)) {
Directory.CreateDirectory(Path.Combine(options.SaveAsProjectDirectory, dirName));
}
Stream entryStream = (Stream)pair.Value;
entryStream.Position = 0;
if (fileName.EndsWith(".baml", StringComparison.OrdinalIgnoreCase)) {
MemoryStream ms = new MemoryStream();
entryStream.CopyTo(ms);
// TODO implement extension point
// var decompiler = Baml.BamlResourceEntryNode.CreateBamlDecompilerInAppDomain(ref bamlDecompilerAppDomain, assembly.FileName);
// string xaml = null;
// try {
// xaml = decompiler.DecompileBaml(ms, assembly.FileName, new ConnectMethodDecompiler(assembly), new AssemblyResolver(assembly));
// }
// catch (XamlXmlWriterException) { } // ignore XAML writer exceptions
// if (xaml != null) {
// File.WriteAllText(Path.Combine(options.SaveAsProjectDirectory, Path.ChangeExtension(fileName, ".xaml")), xaml);
// yield return Tuple.Create("Page", Path.ChangeExtension(fileName, ".xaml"));
// continue;
// }
}
using (FileStream fs = new FileStream(Path.Combine(options.SaveAsProjectDirectory, fileName), FileMode.Create, FileAccess.Write)) {
entryStream.CopyTo(fs);
}
yield return Tuple.Create("Resource", fileName);
}
continue;
}
}
fileName = GetFileNameForResource(r.Name, directories);
using (FileStream fs = new FileStream(Path.Combine(options.SaveAsProjectDirectory, fileName), FileMode.Create, FileAccess.Write)) {
s.CopyTo(fs);
}
yield return Tuple.Create("EmbeddedResource", fileName);
}
}
finally {
if (bamlDecompilerAppDomain != null)
AppDomain.Unload(bamlDecompilerAppDomain);
}
}
string GetFileNameForResource(string fullName, HashSet<string> directories)
{
string[] splitName = fullName.Split('.');
string fileName = TextView.DecompilerTextView.CleanUpName(fullName);
for (int i = splitName.Length - 1; i > 0; i--) {
string ns = string.Join(".", splitName, 0, i);
if (directories.Contains(ns)) {
string name = string.Join(".", splitName, i, splitName.Length - i);
fileName = Path.Combine(ns, TextView.DecompilerTextView.CleanUpName(name));
break;
}
}
return fileName;
}
#endregion
public override void DecompileMethod(MethodDefinition method, ITextOutput output, DecompilationOptions options)
{
WriteCommentLine(output, TypeToString(method.DeclaringType, includeNamespace: true));
AstBuilder codeDomBuilder = CreateAstBuilder(options, currentType: method.DeclaringType, isSingleMember: true);
codeDomBuilder.AddMethod(method);
RunTransformsAndGenerateCode(codeDomBuilder, output, options, method.Module);
}
public override void DecompileProperty(PropertyDefinition property, ITextOutput output, DecompilationOptions options)
{
WriteCommentLine(output, TypeToString(property.DeclaringType, includeNamespace: true));
AstBuilder codeDomBuilder = CreateAstBuilder(options, currentType: property.DeclaringType, isSingleMember: true);
codeDomBuilder.AddProperty(property);
RunTransformsAndGenerateCode(codeDomBuilder, output, options, property.Module);
}
public override void DecompileField(FieldDefinition field, ITextOutput output, DecompilationOptions options)
{
WriteCommentLine(output, TypeToString(field.DeclaringType, includeNamespace: true));
AstBuilder codeDomBuilder = CreateAstBuilder(options, currentType: field.DeclaringType, isSingleMember: true);
codeDomBuilder.AddField(field);
RunTransformsAndGenerateCode(codeDomBuilder, output, options, field.Module);
}
public override void DecompileEvent(EventDefinition ev, ITextOutput output, DecompilationOptions options)
{
WriteCommentLine(output, TypeToString(ev.DeclaringType, includeNamespace: true));
AstBuilder codeDomBuilder = CreateAstBuilder(options, currentType: ev.DeclaringType, isSingleMember: true);
codeDomBuilder.AddEvent(ev);
RunTransformsAndGenerateCode(codeDomBuilder, output, options, ev.Module);
}
public override void DecompileType(TypeDefinition type, ITextOutput output, DecompilationOptions options)
{
AstBuilder codeDomBuilder = CreateAstBuilder(options, currentType: type);
codeDomBuilder.AddType(type);
RunTransformsAndGenerateCode(codeDomBuilder, output, options, type.Module);
}
public override bool ShowMember(MemberReference member)
{
return showAllMembers || !AstBuilder.MemberIsHidden(member, new DecompilationOptions().DecompilerSettings);
}
void RunTransformsAndGenerateCode(AstBuilder astBuilder, ITextOutput output, DecompilationOptions options, ModuleDefinition module)
{
astBuilder.RunTransformations(transformAbortCondition);
if (options.DecompilerSettings.ShowXmlDocumentation)
AddXmlDocTransform.Run(astBuilder.CompilationUnit);
var unit = astBuilder.CompilationUnit.AcceptVisitor(new CSharpToVBConverterVisitor(new ILSpyEnvironmentProvider(CreateResolveContext(module))), null);
var outputFormatter = new VBTextOutputFormatter(output);
var formattingPolicy = new VBFormattingOptions();
unit.AcceptVisitor(new OutputVisitor(outputFormatter, formattingPolicy), null);
}
AstBuilder CreateAstBuilder(DecompilationOptions options, ModuleDefinition currentModule = null, TypeDefinition currentType = null, bool isSingleMember = false)
{
if (currentModule == null)
currentModule = currentType.Module;
DecompilerSettings settings = options.DecompilerSettings;
settings = settings.Clone();
if (isSingleMember)
settings.UsingDeclarations = false;
settings.IntroduceIncrementAndDecrement = false;
settings.QueryExpressions = false;
settings.AlwaysGenerateExceptionVariableForCatchBlocks = true;
return new AstBuilder(
new DecompilerContext(currentModule) {
CancellationToken = options.CancellationToken,
CurrentType = currentType,
Settings = settings
});
}
public override string FormatTypeName(TypeDefinition type)
{
if (type == null)
throw new ArgumentNullException("type");
return TypeToString(ConvertTypeOptions.DoNotUsePrimitiveTypeNames | ConvertTypeOptions.IncludeTypeParameterDefinitions, type);
}
public override string TypeToString(TypeReference type, bool includeNamespace, ICustomAttributeProvider typeAttributes = null)
{
ConvertTypeOptions options = ConvertTypeOptions.IncludeTypeParameterDefinitions;
if (includeNamespace)
options |= ConvertTypeOptions.IncludeNamespace;
return TypeToString(options, type, typeAttributes);
}
ITypeResolveContext CreateResolveContext(ModuleDefinition module)
{
IProjectContent projectContent = new CecilTypeResolveContext(module);
List<ITypeResolveContext> resolveContexts = new List<ITypeResolveContext>();
resolveContexts.Add(projectContent);
foreach (AssemblyNameReference r in module.AssemblyReferences) {
AssemblyDefinition d = module.AssemblyResolver.Resolve(r);
if (d != null) {
resolveContexts.Add(new CecilTypeResolveContext(d.MainModule));
}
}
return new CompositeTypeResolveContext(resolveContexts);
}
string TypeToString(ConvertTypeOptions options, TypeReference type, ICustomAttributeProvider typeAttributes = null)
{
var astType = AstBuilder
.ConvertType(type, typeAttributes, options)
.AcceptVisitor(new CSharpToVBConverterVisitor(new ILSpyEnvironmentProvider(CreateResolveContext(type.Resolve().Module))), null);
StringWriter w = new StringWriter();
// TODO
// if (type.IsByReference) {
// ParameterDefinition pd = typeAttributes as ParameterDefinition;
// if (pd != null && (!pd.IsIn && pd.IsOut))
// w.Write("out ");
// else
// w.Write("ref ");
//
// if (astType is ComposedType && ((ComposedType)astType).PointerRank > 0)
// ((ComposedType)astType).PointerRank--;
// }
astType.AcceptVisitor(new OutputVisitor(w, new VBFormattingOptions()), null);
return w.ToString();
}
}
}

153
ILSpy/VB/VBTextOutputFormatter.cs

@ -0,0 +1,153 @@ @@ -0,0 +1,153 @@
// 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.Generic;
using System.Linq;
using ICSharpCode.Decompiler;
using ICSharpCode.Decompiler.ILAst;
using ICSharpCode.NRefactory.VB;
using Mono.Cecil;
namespace ICSharpCode.ILSpy.VB
{
/// <summary>
/// Description of VBTextOutputFormatter.
/// </summary>
public class VBTextOutputFormatter : IOutputFormatter
{
readonly ITextOutput output;
readonly Stack<AstNode> nodeStack = new Stack<AstNode>();
public VBTextOutputFormatter(ITextOutput output)
{
if (output == null)
throw new ArgumentNullException("output");
this.output = output;
}
public void StartNode(AstNode node)
{
// var ranges = node.Annotation<List<ILRange>>();
// if (ranges != null && ranges.Count > 0)
// {
// // find the ancestor that has method mapping as annotation
// if (node.Ancestors != null && node.Ancestors.Count() > 0)
// {
// var n = node.Ancestors.FirstOrDefault(a => a.Annotation<MemberMapping>() != null);
// if (n != null) {
// MemberMapping mapping = n.Annotation<MemberMapping>();
//
// // add all ranges
// foreach (var range in ranges) {
// mapping.MemberCodeMappings.Add(new SourceCodeMapping {
// ILInstructionOffset = range,
// SourceCodeLine = output.CurrentLine,
// MemberMapping = mapping
// });
// }
// }
// }
// }
nodeStack.Push(node);
}
public void EndNode(AstNode node)
{
if (nodeStack.Pop() != node)
throw new InvalidOperationException();
}
public void WriteIdentifier(string identifier)
{
MemberReference memberRef = GetCurrentMemberReference();
if (memberRef != null)
output.WriteReference(identifier, memberRef);
else
output.Write(identifier);
}
MemberReference GetCurrentMemberReference()
{
AstNode node = nodeStack.Peek();
MemberReference memberRef = node.Annotation<MemberReference>();
// TODO : implement this!
// if (memberRef == null && node.Role == AstNode.Roles.TargetExpression && (node.Parent is InvocationExpression || node.Parent is ObjectCreateExpression)) {
// memberRef = node.Parent.Annotation<MemberReference>();
// }
return memberRef;
}
public void WriteKeyword(string keyword)
{
output.Write(keyword);
}
public void WriteToken(string token)
{
// Attach member reference to token only if there's no identifier in the current node.
MemberReference memberRef = GetCurrentMemberReference();
if (memberRef != null && nodeStack.Peek().GetChildByRole(AstNode.Roles.Identifier).IsNull)
output.WriteReference(token, memberRef);
else
output.Write(token);
}
public void Space()
{
output.Write(' ');
}
public void Indent()
{
output.Indent();
}
public void Unindent()
{
output.Unindent();
}
public void NewLine()
{
output.WriteLine();
}
public void WriteComment(bool isDocumentation, string content)
{
if (isDocumentation)
output.Write("'''");
else
output.Write("'");
output.WriteLine(content);
}
public void MarkFoldStart()
{
output.MarkFoldStart();
}
public void MarkFoldEnd()
{
output.MarkFoldEnd();
}
}
}

1
Mono.Cecil/.gitignore vendored

@ -6,3 +6,4 @@ obj @@ -6,3 +6,4 @@ obj
*.userprefs
*.xml
*.nupkg
**/test-results/*

29
Mono.Cecil/Mono.Cecil.PE/ByteBuffer.cs

@ -140,11 +140,16 @@ namespace Mono.Cecil.PE { @@ -140,11 +140,16 @@ namespace Mono.Cecil.PE {
public int ReadCompressedInt32 ()
{
var value = (int) ReadCompressedUInt32 ();
return (value & 1) != 0
? -(value >> 1)
: value >> 1;
var value = (int) (ReadCompressedUInt32 () >> 1);
if ((value & 1) == 0)
return value;
if (value < 0x40)
return value - 0x40;
if (value < 0x2000)
return value - 0x2000;
if (value < 0x10000000)
return value - 0x10000000;
return value - 0x20000000;
}
public float ReadSingle ()
@ -267,7 +272,19 @@ namespace Mono.Cecil.PE { @@ -267,7 +272,19 @@ namespace Mono.Cecil.PE {
public void WriteCompressedInt32 (int value)
{
WriteCompressedUInt32 ((uint) ((value < 0) ? ((-value) << 1) | 1 : value << 1));
if (value >= 0) {
WriteCompressedUInt32 ((uint) (value << 1));
return;
}
if (value > -0x40)
value = 0x40 + value;
else if (value >= -0x2000)
value = 0x2000 + value;
else if (value >= -0x20000000)
value = 0x20000000 + value;
WriteCompressedUInt32 ((uint) ((value << 1) | 1));
}
public void WriteBytes (byte [] bytes)

3
Mono.Cecil/Mono.Cecil.PE/ImageReader.cs

@ -276,9 +276,6 @@ namespace Mono.Cecil.PE { @@ -276,9 +276,6 @@ namespace Mono.Cecil.PE {
sections [i] = section;
if (section.Name == ".reloc")
continue;
ReadSectionData (section);
}

2
Mono.Cecil/Mono.Cecil.nuspec

@ -2,7 +2,7 @@ @@ -2,7 +2,7 @@
<package xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<metadata xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd">
<id>Mono.Cecil</id>
<version>0.9.4.1</version>
<version>0.9.5.0</version>
<title>Mono.Cecil</title>
<authors>Jb Evain</authors>
<owners>Jb Evain</owners>

4
Mono.Cecil/Mono.Cecil/AssemblyInfo.cs

@ -38,9 +38,9 @@ using System.Runtime.InteropServices; @@ -38,9 +38,9 @@ using System.Runtime.InteropServices;
[assembly: Guid ("fd225bb4-fa53-44b2-a6db-85f5e48dcb54")]
[assembly: AssemblyVersion ("0.9.4.0")]
[assembly: AssemblyVersion ("0.9.5.0")]
#if !CF
[assembly: AssemblyFileVersion ("0.9.4.0")]
[assembly: AssemblyFileVersion ("0.9.5.0")]
#endif
[assembly: InternalsVisibleTo ("Mono.Cecil.Pdb, PublicKey=002400000480000094000000060200000024000052534131000400000100010079159977d2d03a8e6bea7a2e74e8d1afcc93e8851974952bb480a12c9134474d04062447c37e0e68c080536fcf3c3fbe2ff9c979ce998475e506e8ce82dd5b0f350dc10e93bf2eeecf874b24770c5081dbea7447fddafa277b22de47d6ffea449674a4f9fccf84d15069089380284dbdd35f46cdff12a1bd78e4ef0065d016df")]

32
Mono.Cecil/Mono.Cecil/AssemblyReader.cs

@ -703,9 +703,24 @@ namespace Mono.Cecil { @@ -703,9 +703,24 @@ namespace Mono.Cecil {
types.Add (type);
}
if (image.HasTable (Table.MethodPtr) || image.HasTable (Table.FieldPtr))
CompleteTypes ();
return types;
}
void CompleteTypes ()
{
var types = metadata.Types;
for (int i = 0; i < types.Length; i++) {
var type = types [i];
InitializeCollection (type.Fields);
InitializeCollection (type.Methods);
}
}
void InitializeTypeDefinitions ()
{
if (metadata.Types != null)
@ -2560,10 +2575,8 @@ namespace Mono.Cecil { @@ -2560,10 +2575,8 @@ namespace Mono.Cecil {
scope = metadata.AssemblyReferences [(int) token.RID - 1];
break;
case TokenType.File:
InitializeModuleReferences ();
scope = GetModuleReferenceFromFile (token);
if (scope == null)
throw new NotSupportedException ();
break;
default:
throw new NotSupportedException ();
@ -2582,16 +2595,15 @@ namespace Mono.Cecil { @@ -2582,16 +2595,15 @@ namespace Mono.Cecil {
var file_name = ReadString ();
var modules = module.ModuleReferences;
ModuleReference reference = null;
ModuleReference reference;
for (int i = 0; i < modules.Count; i++) {
var module_reference = modules [i];
if (module_reference.Name != file_name)
continue;
reference = module_reference;
break;
reference = modules [i];
if (reference.Name == file_name)
return reference;
}
reference = new ModuleReference (file_name);
modules.Add (reference);
return reference;
}

14
Mono.Cecil/Mono.Cecil/AssemblyWriter.cs

@ -935,11 +935,13 @@ namespace Mono.Cecil { @@ -935,11 +935,13 @@ namespace Mono.Cecil {
? reference.PublicKeyToken
: reference.PublicKey;
var version = reference.Version;
var rid = table.AddRow (new AssemblyRefRow (
(ushort) reference.Version.Major,
(ushort) reference.Version.Minor,
(ushort) reference.Version.Build,
(ushort) reference.Version.Revision,
(ushort) version.Major,
(ushort) version.Minor,
(ushort) version.Build,
(ushort) version.Revision,
reference.Attributes,
GetBlobIndex (key_or_token),
GetStringIndex (reference.Name),
@ -2448,12 +2450,12 @@ namespace Mono.Cecil { @@ -2448,12 +2450,12 @@ namespace Mono.Cecil {
var count = GetNamedArgumentCount (attribute);
if (count == 0) {
WriteCompressedUInt32 (0); // length
WriteCompressedUInt32 (1); // length
WriteCompressedUInt32 (0); // count
return;
}
var buffer = new SignatureWriter (metadata);
var buffer = new SignatureWriter (metadata);
buffer.WriteCompressedUInt32 ((uint) count);
buffer.WriteICustomAttributeNamedArguments (attribute);

12
Mono.Cecil/Mono.Cecil/BaseAssemblyResolver.cs

@ -51,6 +51,9 @@ namespace Mono.Cecil { @@ -51,6 +51,9 @@ namespace Mono.Cecil {
}
}
#if !SILVERLIGHT && !CF
[Serializable]
#endif
public class AssemblyResolutionException : FileNotFoundException {
readonly AssemblyNameReference reference;
@ -64,6 +67,15 @@ namespace Mono.Cecil { @@ -64,6 +67,15 @@ namespace Mono.Cecil {
{
this.reference = reference;
}
#if !SILVERLIGHT && !CF
protected AssemblyResolutionException (
System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context)
: base (info, context)
{
}
#endif
}
public abstract class BaseAssemblyResolver : IAssemblyResolver {

12
Mono.Cecil/Mono.Cecil/MetadataResolver.cs

@ -41,6 +41,9 @@ namespace Mono.Cecil { @@ -41,6 +41,9 @@ namespace Mono.Cecil {
AssemblyDefinition Resolve (string fullName, ReaderParameters parameters);
}
#if !SILVERLIGHT && !CF
[Serializable]
#endif
public class ResolutionException : Exception {
readonly MemberReference member;
@ -54,6 +57,15 @@ namespace Mono.Cecil { @@ -54,6 +57,15 @@ namespace Mono.Cecil {
{
this.member = member;
}
#if !SILVERLIGHT && !CF
protected ResolutionException (
System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context)
: base (info, context)
{
}
#endif
}
static class MetadataResolver {

20
Mono.Cecil/Mono.Cecil/ModuleDefinition.cs

@ -506,6 +506,26 @@ namespace Mono.Cecil { @@ -506,6 +506,26 @@ namespace Mono.Cecil {
return ((TypeDefinitionCollection) this.Types).GetType (@namespace ?? string.Empty, name);
}
public IEnumerable<TypeDefinition> GetTypes ()
{
return GetTypes (Types);
}
static IEnumerable<TypeDefinition> GetTypes (Collection<TypeDefinition> types)
{
for (int i = 0; i < types.Count; i++) {
var type = types [i];
yield return type;
if (!type.HasNestedTypes)
continue;
foreach (var nested in GetTypes (type.NestedTypes))
yield return nested;
}
}
static void CheckFullName (string fullName)
{
if (fullName == null)

9
Mono.Cecil/Mono.Cecil/ParameterDefinition.cs

@ -49,6 +49,15 @@ namespace Mono.Cecil { @@ -49,6 +49,15 @@ namespace Mono.Cecil {
get { return method; }
}
public int Sequence {
get {
if (method == null)
return -1;
return method.HasThis ? index + 1 : index;
}
}
public bool HasConstant {
get {
this.ResolveConstant (ref constant, parameter_type.Module);

8
Mono.Cecil/Mono/Empty.cs

@ -26,9 +26,7 @@ @@ -26,9 +26,7 @@
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using System.Collections.Generic;
using Mono.Collections.Generic;
namespace Mono {
@ -47,9 +45,9 @@ namespace Mono.Cecil { @@ -47,9 +45,9 @@ namespace Mono.Cecil {
return self == null || self.Length == 0;
}
public static bool IsNullOrEmpty<T> (this ICollection<T> self)
public static bool IsNullOrEmpty<T> (this Collection<T> self)
{
return self == null || self.Count == 0;
return self == null || self.size == 0;
}
}
}

9
Mono.Cecil/Test/Mono.Cecil.Tests/FieldTests.cs

@ -163,6 +163,15 @@ namespace Mono.Cecil.Tests { @@ -163,6 +163,15 @@ namespace Mono.Cecil.Tests {
Assert.IsTrue (array.Dimensions [1].IsSized);
Assert.AreEqual (0, array.Dimensions [1].LowerBound);
Assert.AreEqual (null, array.Dimensions [1].UpperBound);
var rank_one_low_bound_m1 = types.GetField ("rank_one_low_bound_m1");
array = rank_one_low_bound_m1.FieldType as ArrayType;
Assert.IsNotNull (array);
Assert.AreEqual (1, array.Rank);
Assert.IsTrue (array.Dimensions [0].IsSized);
Assert.AreEqual (-1, array.Dimensions [0].LowerBound);
Assert.AreEqual (4, array.Dimensions [0].UpperBound);
}
[TestCSharp ("Fields.cs")]

20
Mono.Cecil/Test/Mono.Cecil.Tests/SecurityDeclarationTests.cs

@ -88,6 +88,26 @@ namespace Mono.Cecil.Tests { @@ -88,6 +88,26 @@ namespace Mono.Cecil.Tests {
Assert.AreEqual (permission_set, argument.Value);
}
[TestModule ("empty-decsec-att.dll")]
public void SecurityDeclarationWithoutAttributes (ModuleDefinition module)
{
var type = module.GetType ("TestSecurityAction.ModalUITypeEditor");
var method = type.GetMethod ("GetEditStyle");
Assert.IsNotNull (method);
Assert.AreEqual (1, method.SecurityDeclarations.Count);
var declaration = method.SecurityDeclarations [0];
Assert.AreEqual (SecurityAction.LinkDemand, declaration.Action);
Assert.AreEqual (1, declaration.SecurityAttributes.Count);
var attribute = declaration.SecurityAttributes [0];
Assert.AreEqual ("System.Security.Permissions.SecurityPermissionAttribute", attribute.AttributeType.FullName);
Assert.AreEqual (0, attribute.Fields.Count);
Assert.AreEqual (0, attribute.Properties.Count);
}
[TestModule ("decsec-att.dll")]
public void AttributeSecurityDeclaration (ModuleDefinition module)
{

BIN
Mono.Cecil/Test/Resources/assemblies/empty-decsec-att.dll

Binary file not shown.

4
Mono.Cecil/rocks/Mono.Cecil.Rocks/AssemblyInfo.cs

@ -37,5 +37,5 @@ using System.Runtime.InteropServices; @@ -37,5 +37,5 @@ using System.Runtime.InteropServices;
[assembly: CLSCompliant (false)]
[assembly: ComVisible (false)]
[assembly: AssemblyVersion ("0.9.4.0")]
[assembly: AssemblyFileVersion ("0.9.4.0")]
[assembly: AssemblyVersion ("0.9.5.0")]
[assembly: AssemblyFileVersion ("0.9.5.0")]

4
Mono.Cecil/symbols/mdb/Mono.Cecil.Mdb/AssemblyInfo.cs

@ -37,5 +37,5 @@ using System.Runtime.InteropServices; @@ -37,5 +37,5 @@ using System.Runtime.InteropServices;
[assembly: CLSCompliant (false)]
[assembly: ComVisible (false)]
[assembly: AssemblyVersion ("0.9.4.0")]
[assembly: AssemblyFileVersion ("0.9.4.0")]
[assembly: AssemblyVersion ("0.9.5.0")]
[assembly: AssemblyFileVersion ("0.9.5.0")]

4
Mono.Cecil/symbols/pdb/Mono.Cecil.Pdb/AssemblyInfo.cs

@ -37,5 +37,5 @@ using System.Runtime.InteropServices; @@ -37,5 +37,5 @@ using System.Runtime.InteropServices;
[assembly: CLSCompliant (false)]
[assembly: ComVisible (false)]
[assembly: AssemblyVersion ("0.9.4.0")]
[assembly: AssemblyFileVersion ("0.9.4.0")]
[assembly: AssemblyVersion ("0.9.5.0")]
[assembly: AssemblyFileVersion ("0.9.5.0")]

39
NRefactory/ICSharpCode.NRefactory.VB/Ast/AstNode.cs

@ -1,28 +1,5 @@ @@ -1,28 +1,5 @@
//
// AstNode.cs
//
// Author:
// Mike Krüger <mkrueger@novell.com>
//
// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
//
// 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.
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under MIT X11 license (for details please see \doc\license.txt)
using System;
using System.Collections;
@ -532,13 +509,13 @@ namespace ICSharpCode.NRefactory.VB @@ -532,13 +509,13 @@ namespace ICSharpCode.NRefactory.VB
public static readonly Role<XmlIdentifier> XmlIdentifier = new Role<XmlIdentifier>("XmlIdentifier", Ast.XmlIdentifier.Null);
public static readonly Role<XmlLiteralString> XmlLiteralString = new Role<XmlLiteralString>("XmlLiteralString", Ast.XmlLiteralString.Null);
// public static readonly Role<BlockStatement> Body = new Role<BlockStatement>("Body", CSharp.BlockStatement.Null);
public static readonly Role<BlockStatement> Body = new Role<BlockStatement>("Body", Ast.BlockStatement.Null);
public static readonly Role<ParameterDeclaration> Parameter = new Role<ParameterDeclaration>("Parameter");
public static readonly Role<Expression> Argument = new Role<Expression>("Argument", Ast.Expression.Null);
public static readonly Role<AstType> Type = new Role<AstType>("Type", AstType.Null);
public static readonly Role<Expression> Expression = new Role<Expression>("Expression", Ast.Expression.Null);
// public static readonly Role<Expression> TargetExpression = new Role<Expression>("Target", CSharp.Expression.Null);
// public readonly static Role<Expression> Condition = new Role<Expression>("Condition", CSharp.Expression.Null);
public static readonly Role<Expression> TargetExpression = new Role<Expression>("Target", Ast.Expression.Null);
public readonly static Role<Expression> Condition = new Role<Expression>("Condition", Ast.Expression.Null);
//
public static readonly Role<TypeParameterDeclaration> TypeParameter = new Role<TypeParameterDeclaration>("TypeParameter");
public static readonly Role<AstType> TypeArgument = new Role<AstType>("TypeArgument", AstType.Null);
@ -558,6 +535,7 @@ namespace ICSharpCode.NRefactory.VB @@ -558,6 +535,7 @@ namespace ICSharpCode.NRefactory.VB
public static readonly Role<VBTokenNode> LChevron = new Role<VBTokenNode>("LChevron", VBTokenNode.Null);
public static readonly Role<VBTokenNode> RChevron = new Role<VBTokenNode>("RChevron", VBTokenNode.Null);
public static readonly Role<VBTokenNode> Comma = new Role<VBTokenNode>("Comma", VBTokenNode.Null);
public static readonly Role<VBTokenNode> QuestionMark = new Role<VBTokenNode>("QuestionMark", VBTokenNode.Null);
public static readonly Role<VBTokenNode> Dot = new Role<VBTokenNode>("Dot", VBTokenNode.Null);
public static readonly Role<VBTokenNode> Semicolon = new Role<VBTokenNode>("Semicolon", VBTokenNode.Null);
public static readonly Role<VBTokenNode> Assign = new Role<VBTokenNode>("Assign", VBTokenNode.Null);
@ -579,8 +557,5 @@ namespace ICSharpCode.NRefactory.VB @@ -579,8 +557,5 @@ namespace ICSharpCode.NRefactory.VB
}
}
public class Comment
{
}
}

67
NRefactory/ICSharpCode.NRefactory.VB/Ast/Comment.cs

@ -0,0 +1,67 @@ @@ -0,0 +1,67 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under MIT X11 license (for details please see \doc\license.txt)
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using ICSharpCode.NRefactory.PatternMatching;
using ICSharpCode.NRefactory.VB.Ast;
namespace ICSharpCode.NRefactory.VB
{
public class Comment : AstNode
{
public bool IsDocumentationComment { get; set; }
public bool StartsLine {
get;
set;
}
public string Content {
get;
set;
}
AstLocation startLocation;
public override AstLocation StartLocation {
get {
return startLocation;
}
}
AstLocation endLocation;
public override AstLocation EndLocation {
get {
return endLocation;
}
}
public Comment (string content, bool isDocumentation = false)
{
this.IsDocumentationComment = isDocumentation;
this.Content = content;
}
public Comment (bool isDocumentation, AstLocation startLocation, AstLocation endLocation)
{
this.IsDocumentationComment = isDocumentation;
this.startLocation = startLocation;
this.endLocation = endLocation;
}
public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
{
return visitor.VisitComment(this, data);
}
protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
{
Comment o = other as Comment;
return o != null && this.IsDocumentationComment == o.IsDocumentationComment && MatchString(this.Content, o.Content);
}
}
}

221
NRefactory/ICSharpCode.NRefactory.VB/Ast/Enums.cs

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
// This code is distributed under MIT X11 license (for details please see \doc\license.txt)
using System;
@ -25,7 +25,7 @@ namespace ICSharpCode.NRefactory.VB.Ast @@ -25,7 +25,7 @@ namespace ICSharpCode.NRefactory.VB.Ast
Const = 0x0200,
Shared = 0x0400,
Static = 0x0800,
Override = 0x1000,
Overrides = 0x1000,
ReadOnly = 0x2000,
Shadows = 0x4000,
Partial = 0x8000,
@ -45,6 +45,12 @@ namespace ICSharpCode.NRefactory.VB.Ast @@ -45,6 +45,12 @@ namespace ICSharpCode.NRefactory.VB.Ast
ParamArray = 0x800000,
Optional = 0x1000000,
Narrowing = 0x2000000,
Widening = 0x4000000,
Iterator = 0x8000000,
Async = 0x10000000,
/// <summary>
/// Special value used to match any modifiers during pattern matching.
/// </summary>
@ -67,13 +73,6 @@ namespace ICSharpCode.NRefactory.VB.Ast @@ -67,13 +73,6 @@ namespace ICSharpCode.NRefactory.VB.Ast
Ref
}
public enum VarianceModifier
{
Invariant,
Covariant,
Contravariant
};
public enum AssignmentOperatorType
{
None,
@ -83,7 +82,6 @@ namespace ICSharpCode.NRefactory.VB.Ast @@ -83,7 +82,6 @@ namespace ICSharpCode.NRefactory.VB.Ast
Subtract,
Multiply,
Divide,
Modulus,
Power, // (VB only)
DivideInteger, // (VB only)
@ -91,117 +89,6 @@ namespace ICSharpCode.NRefactory.VB.Ast @@ -91,117 +89,6 @@ namespace ICSharpCode.NRefactory.VB.Ast
ShiftLeft,
ShiftRight,
BitwiseAnd,
BitwiseOr,
ExclusiveOr,
}
public enum BinaryOperatorType
{
None,
/// <summary>'&amp;' in C#, 'And' in VB.</summary>
BitwiseAnd,
/// <summary>'|' in C#, 'Or' in VB.</summary>
BitwiseOr,
/// <summary>'&amp;&amp;' in C#, 'AndAlso' in VB.</summary>
LogicalAnd,
/// <summary>'||' in C#, 'OrElse' in VB.</summary>
LogicalOr,
/// <summary>'^' in C#, 'Xor' in VB.</summary>
ExclusiveOr,
/// <summary>&gt;</summary>
GreaterThan,
/// <summary>&gt;=</summary>
GreaterThanOrEqual,
/// <summary>'==' in C#, '=' in VB.</summary>
Equality,
/// <summary>'!=' in C#, '&lt;&gt;' in VB.</summary>
InEquality,
/// <summary>&lt;</summary>
LessThan,
/// <summary>&lt;=</summary>
LessThanOrEqual,
/// <summary>+</summary>
Add,
/// <summary>-</summary>
Subtract,
/// <summary>*</summary>
Multiply,
/// <summary>/</summary>
Divide,
/// <summary>'%' in C#, 'Mod' in VB.</summary>
Modulus,
/// <summary>VB-only: \</summary>
DivideInteger,
/// <summary>VB-only: ^</summary>
Power,
/// <summary>VB-only: &amp;</summary>
Concat,
/// <summary>C#: &lt;&lt;</summary>
ShiftLeft,
/// <summary>C#: &gt;&gt;</summary>
ShiftRight,
/// <summary>VB-only: Is</summary>
ReferenceEquality,
/// <summary>VB-only: IsNot</summary>
ReferenceInequality,
/// <summary>VB-only: Like</summary>
Like,
/// <summary>
/// C#: ??
/// VB: IF(x, y)
/// </summary>
NullCoalescing,
/// <summary>VB-only: !</summary>
DictionaryAccess
}
public enum CastType
{
/// <summary>
/// direct cast (C#, VB "DirectCast")
/// </summary>
Cast,
/// <summary>
/// try cast (C# "as", VB "TryCast")
/// </summary>
TryCast,
/// <summary>
/// converting cast (VB "CType")
/// </summary>
Conversion,
/// <summary>
/// primitive converting cast (VB "CString" etc.)
/// </summary>
PrimitiveConversion
}
public enum UnaryOperatorType
{
None,
Not,
BitNot,
Minus,
Plus,
Increment,
Decrement,
PostIncrement,
PostDecrement,
/// <summary>Dereferencing pointer</summary>
Dereference,
/// <summary>Get address of</summary>
AddressOf
}
public enum ContinueType
@ -215,38 +102,12 @@ namespace ICSharpCode.NRefactory.VB.Ast @@ -215,38 +102,12 @@ namespace ICSharpCode.NRefactory.VB.Ast
public enum ConditionType
{
None,
Until,
While,
LoopUntil,
LoopWhile,
DoUntil,
DoWhile
}
public enum ConditionPosition
{
None,
Start,
End
}
public enum ExitType
{
None,
Sub,
Function,
Property,
Do,
For,
While,
Select,
Try
}
public enum ConstructorInitializerType
{
None,
Base,
This
}
public enum ConversionType
{
None,
@ -254,66 +115,10 @@ namespace ICSharpCode.NRefactory.VB.Ast @@ -254,66 +115,10 @@ namespace ICSharpCode.NRefactory.VB.Ast
Explicit
}
public enum OverloadableOperatorType
{
None,
Add,
Subtract,
Multiply,
Divide,
Modulus,
Concat,
UnaryPlus,
UnaryMinus,
Not,
BitNot,
BitwiseAnd,
BitwiseOr,
ExclusiveOr,
ShiftLeft,
ShiftRight,
GreaterThan,
GreaterThanOrEqual,
Equality,
InEquality,
LessThan,
LessThanOrEqual,
Increment,
Decrement,
IsTrue,
IsFalse,
// VB specific
Like,
Power,
CType,
DivideInteger
}
///<summary>
/// Charset types, used in external methods
/// declarations (VB only).
///</summary>
public enum CharsetModifier
{
None,
Auto,
Unicode,
Ansi
}
/// <summary>
/// Specifies the ordering direction of a QueryExpressionOrdering node.
/// </summary>
public enum QueryExpressionOrderingDirection
public enum QueryOrderingDirection
{
None,
Ascending,
@ -324,7 +129,7 @@ namespace ICSharpCode.NRefactory.VB.Ast @@ -324,7 +129,7 @@ namespace ICSharpCode.NRefactory.VB.Ast
/// Specifies the partition type for a VB.NET
/// query expression.
/// </summary>
public enum QueryExpressionPartitionType
public enum PartitionKind
{
Take,
TakeWhile,

41
NRefactory/ICSharpCode.NRefactory.VB/Ast/Expressions/AnonymousObjectCreationExpression.cs

@ -0,0 +1,41 @@ @@ -0,0 +1,41 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under MIT X11 license (for details please see \doc\license.txt)
using System;
using System.Collections.Generic;
namespace ICSharpCode.NRefactory.VB.Ast
{
public class AnonymousObjectCreationExpression : Expression
{
public AstNodeCollection<Expression> Initializer {
get { return GetChildrenByRole(Roles.Expression); }
}
public AnonymousObjectCreationExpression ()
{
}
public AnonymousObjectCreationExpression (IEnumerable<Expression> initializer)
{
foreach (var ini in initializer) {
AddChild (ini, Roles.Expression);
}
}
public AnonymousObjectCreationExpression (params Expression[] initializer) : this ((IEnumerable<Expression>)initializer)
{
}
public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
{
return visitor.VisitAnonymousObjectCreationExpression(this, data);
}
protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
{
var o = other as AnonymousObjectCreationExpression;
return o != null && this.Initializer.DoMatch(o.Initializer, match);
}
}
}

64
NRefactory/ICSharpCode.NRefactory.VB/Ast/Expressions/ArrayCreateExpression.cs

@ -0,0 +1,64 @@ @@ -0,0 +1,64 @@
// 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;
namespace ICSharpCode.NRefactory.VB.Ast
{
/// <summary>
/// New Type[Dimensions]
/// </summary>
public class ArrayCreateExpression : Expression
{
public readonly static Role<ArraySpecifier> AdditionalArraySpecifierRole = new Role<ArraySpecifier>("AdditionalArraySpecifier");
public readonly static Role<ArrayInitializerExpression> InitializerRole = new Role<ArrayInitializerExpression>("Initializer", ArrayInitializerExpression.Null);
public AstType Type {
get { return GetChildByRole (Roles.Type); }
set { SetChildByRole (Roles.Type, value); }
}
public AstNodeCollection<Expression> Arguments {
get { return GetChildrenByRole (Roles.Argument); }
}
/// <summary>
/// Gets additional array ranks (those without size info).
/// Empty for "New Integer(5,1)"; will contain a single element for "New Integer(5)()".
/// </summary>
public AstNodeCollection<ArraySpecifier> AdditionalArraySpecifiers {
get { return GetChildrenByRole(AdditionalArraySpecifierRole); }
}
public ArrayInitializerExpression Initializer {
get { return GetChildByRole (InitializerRole); }
set { SetChildByRole (InitializerRole, value); }
}
public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
{
return visitor.VisitArrayCreateExpression (this, data);
}
protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
{
ArrayCreateExpression o = other as ArrayCreateExpression;
return o != null && this.Type.DoMatch(o.Type, match) && this.Arguments.DoMatch(o.Arguments, match) && this.AdditionalArraySpecifiers.DoMatch(o.AdditionalArraySpecifiers, match) && this.Initializer.DoMatch(o.Initializer, match);
}
}
}

53
NRefactory/ICSharpCode.NRefactory.VB/Ast/Expressions/ArrayInitializerExpression.cs

@ -0,0 +1,53 @@ @@ -0,0 +1,53 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under MIT X11 license (for details please see \doc\license.txt)
using System;
namespace ICSharpCode.NRefactory.VB.Ast
{
/// <summary>
/// { Elements }
/// </summary>
public class ArrayInitializerExpression : Expression
{
#region Null
public new static readonly ArrayInitializerExpression Null = new NullArrayInitializerExpression ();
sealed class NullArrayInitializerExpression : ArrayInitializerExpression
{
public override bool IsNull {
get {
return true;
}
}
public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
{
return default (S);
}
protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
{
return other == null || other.IsNull;
}
}
#endregion
public readonly static Role<ArrayInitializerExpression> InitializerRole = new Role<ArrayInitializerExpression>("Initializer", ArrayInitializerExpression.Null);
public AstNodeCollection<Expression> Elements {
get { return GetChildrenByRole(Roles.Expression); }
}
public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
{
return visitor.VisitArrayInitializerExpression (this, data);
}
protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
{
ArrayInitializerExpression o = other as ArrayInitializerExpression;
return o != null && this.Elements.DoMatch(o.Elements, match);
}
}
}

44
NRefactory/ICSharpCode.NRefactory.VB/Ast/Expressions/AssignmentExpression.cs

@ -0,0 +1,44 @@ @@ -0,0 +1,44 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under MIT X11 license (for details please see \doc\license.txt)
using System;
using System.Collections.Generic;
namespace ICSharpCode.NRefactory.VB.Ast
{
public class AssignmentExpression : Expression
{
public readonly static Role<Expression> LeftExpressionRole = BinaryOperatorExpression.LeftExpressionRole;
public readonly static Role<VBTokenNode> OperatorRole = BinaryOperatorExpression.OperatorRole;
public readonly static Role<Expression> RightExpressionRole = BinaryOperatorExpression.RightExpressionRole;
public AssignmentExpression(Expression left, AssignmentOperatorType type, Expression right)
{
AddChild(left, LeftExpressionRole);
AddChild(right, RightExpressionRole);
Operator = type;
}
public Expression Left {
get { return GetChildByRole(LeftExpressionRole); }
set { SetChildByRole(LeftExpressionRole, value); }
}
public AssignmentOperatorType Operator { get; set; }
public Expression Right {
get { return GetChildByRole(RightExpressionRole); }
set { SetChildByRole(RightExpressionRole, value); }
}
protected internal override bool DoMatch(AstNode other, ICSharpCode.NRefactory.PatternMatching.Match match)
{
throw new NotImplementedException();
}
public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data)
{
return visitor.VisitAssignmentExpression(this, data);
}
}
}

110
NRefactory/ICSharpCode.NRefactory.VB/Ast/Expressions/BinaryOperatorExpression.cs

@ -0,0 +1,110 @@ @@ -0,0 +1,110 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under MIT X11 license (for details please see \doc\license.txt)
using System;
using System.Collections.Generic;
namespace ICSharpCode.NRefactory.VB.Ast
{
public class BinaryOperatorExpression : Expression
{
public readonly static Role<Expression> LeftExpressionRole = new Role<Expression>("Left");
public readonly static Role<VBTokenNode> OperatorRole = new Role<VBTokenNode>("Operator");
public readonly static Role<Expression> RightExpressionRole = new Role<Expression>("Right");
public BinaryOperatorExpression(Expression left, BinaryOperatorType type, Expression right)
{
AddChild(left, LeftExpressionRole);
AddChild(right, RightExpressionRole);
Operator = type;
}
public Expression Left {
get { return GetChildByRole(LeftExpressionRole); }
set { SetChildByRole(LeftExpressionRole, value); }
}
public BinaryOperatorType Operator { get; set; }
public Expression Right {
get { return GetChildByRole(RightExpressionRole); }
set { SetChildByRole(RightExpressionRole, value); }
}
protected internal override bool DoMatch(AstNode other, ICSharpCode.NRefactory.PatternMatching.Match match)
{
throw new NotImplementedException();
}
public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data)
{
return visitor.VisitBinaryOperatorExpression(this, data);
}
}
public enum BinaryOperatorType
{
None,
/// <summary>'&amp;' in C#, 'And' in VB.</summary>
BitwiseAnd,
/// <summary>'|' in C#, 'Or' in VB.</summary>
BitwiseOr,
/// <summary>'&amp;&amp;' in C#, 'AndAlso' in VB.</summary>
LogicalAnd,
/// <summary>'||' in C#, 'OrElse' in VB.</summary>
LogicalOr,
/// <summary>'^' in C#, 'Xor' in VB.</summary>
ExclusiveOr,
/// <summary>&gt;</summary>
GreaterThan,
/// <summary>&gt;=</summary>
GreaterThanOrEqual,
/// <summary>'==' in C#, '=' in VB.</summary>
Equality,
/// <summary>'!=' in C#, '&lt;&gt;' in VB.</summary>
InEquality,
/// <summary>&lt;</summary>
LessThan,
/// <summary>&lt;=</summary>
LessThanOrEqual,
/// <summary>+</summary>
Add,
/// <summary>-</summary>
Subtract,
/// <summary>*</summary>
Multiply,
/// <summary>/</summary>
Divide,
/// <summary>'%' in C#, 'Mod' in VB.</summary>
Modulus,
/// <summary>VB-only: \</summary>
DivideInteger,
/// <summary>VB-only: ^</summary>
Power,
/// <summary>VB-only: &amp;</summary>
Concat,
/// <summary>C#: &lt;&lt;</summary>
ShiftLeft,
/// <summary>C#: &gt;&gt;</summary>
ShiftRight,
/// <summary>VB-only: Is</summary>
ReferenceEquality,
/// <summary>VB-only: IsNot</summary>
ReferenceInequality,
/// <summary>VB-only: Like</summary>
Like,
/// <summary>
/// C#: ??
/// VB: IF(x, y)
/// </summary>
NullCoalescing,
/// <summary>VB-only: !</summary>
DictionaryAccess
}
}

95
NRefactory/ICSharpCode.NRefactory.VB/Ast/Expressions/CastExpression.cs

@ -0,0 +1,95 @@ @@ -0,0 +1,95 @@
// 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;
namespace ICSharpCode.NRefactory.VB.Ast
{
/// <summary>
/// CastType(Expression, AstType)
/// </summary>
public class CastExpression : Expression
{
public CastType CastType { get; set; }
public VBTokenNode CastTypeToken {
get { return GetChildByRole (Roles.Keyword); }
}
public AstType Type {
get { return GetChildByRole (Roles.Type); }
set { SetChildByRole (Roles.Type, value); }
}
public Expression Expression {
get { return GetChildByRole (Roles.Expression); }
set { SetChildByRole (Roles.Expression, value); }
}
public CastExpression ()
{
}
public CastExpression (CastType castType, AstType castToType, Expression expression)
{
CastType = castType;
AddChild (castToType, Roles.Type);
AddChild (expression, Roles.Expression);
}
public CastExpression (CastType castType, Expression expression)
{
CastType = castType;
AddChild (expression, Roles.Expression);
}
public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
{
return visitor.VisitCastExpression (this, data);
}
protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
{
CastExpression o = other as CastExpression;
return o != null && this.CastType == o.CastType && this.Type.DoMatch(o.Type, match) && this.Expression.DoMatch(o.Expression, match);
}
}
public enum CastType
{
DirectCast,
TryCast,
CType,
CBool,
CByte,
CChar,
CDate,
CDec,
CDbl,
CInt,
CLng,
CObj,
CSByte,
CShort,
CSng,
CStr,
CUInt,
CULng,
CUShort
}
}

42
NRefactory/ICSharpCode.NRefactory.VB/Ast/Expressions/CollectionRangeVariableDeclaration.cs

@ -0,0 +1,42 @@ @@ -0,0 +1,42 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under MIT X11 license (for details please see \doc\license.txt)
using System;
using System.Collections.Generic;
namespace ICSharpCode.NRefactory.VB.Ast
{
/// <summary>
/// Identifier As Type In Expression
/// </summary>
public class CollectionRangeVariableDeclaration : AstNode
{
public static readonly Role<CollectionRangeVariableDeclaration> CollectionRangeVariableDeclarationRole = new Role<CollectionRangeVariableDeclaration>("CollectionRangeVariableDeclaration");
public VariableIdentifier Identifier {
get { return GetChildByRole(VariableIdentifier.VariableIdentifierRole); }
set { SetChildByRole(VariableIdentifier.VariableIdentifierRole, value); }
}
public AstType Type {
get { return GetChildByRole(Roles.Type); }
set { SetChildByRole(Roles.Type, value); }
}
public Expression Expression {
get { return GetChildByRole (Roles.Expression); }
set { SetChildByRole (Roles.Expression, value); }
}
public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data)
{
return visitor.VisitCollectionRangeVariableDeclaration(this, data);
}
protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
{
CollectionRangeVariableDeclaration o = other as CollectionRangeVariableDeclaration;
return o != null && this.Identifier.DoMatch(o.Identifier, match) && this.Type.DoMatch(o.Type, match) && this.Expression.DoMatch(o.Expression, match);
}
}
}

44
NRefactory/ICSharpCode.NRefactory.VB/Ast/Expressions/ConditionalExpression.cs

@ -0,0 +1,44 @@ @@ -0,0 +1,44 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under MIT X11 license (for details please see \doc\license.txt)
using System;
using System.Collections.Generic;
namespace ICSharpCode.NRefactory.VB.Ast
{
public class ConditionalExpression : Expression
{
public readonly static Role<Expression> ConditionExpressionRole = new Role<Expression>("ConditionExpressionRole", Expression.Null);
public readonly static Role<Expression> TrueExpressionRole = new Role<Expression>("TrueExpressionRole", Expression.Null);
public readonly static Role<Expression> FalseExpressionRole = new Role<Expression>("FalseExpressionRole", Expression.Null);
public VBTokenNode IfToken {
get { return GetChildByRole (Roles.Keyword); }
}
public Expression ConditionExpression {
get { return GetChildByRole (ConditionExpressionRole); }
set { SetChildByRole (ConditionExpressionRole, value); }
}
public Expression TrueExpression {
get { return GetChildByRole (TrueExpressionRole); }
set { SetChildByRole (TrueExpressionRole, value); }
}
public Expression FalseExpression {
get { return GetChildByRole (FalseExpressionRole); }
set { SetChildByRole (FalseExpressionRole, value); }
}
protected internal override bool DoMatch(AstNode other, ICSharpCode.NRefactory.PatternMatching.Match match)
{
throw new NotImplementedException();
}
public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data)
{
return visitor.VisitConditionalExpression(this, data);
}
}
}

59
NRefactory/ICSharpCode.NRefactory.VB/Ast/Expressions/EmptyExpression.cs

@ -0,0 +1,59 @@ @@ -0,0 +1,59 @@
// 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;
namespace ICSharpCode.NRefactory.VB.Ast
{
public class EmptyExpression : Expression
{
AstLocation location;
public override AstLocation StartLocation {
get {
return location;
}
}
public override AstLocation EndLocation {
get {
return location;
}
}
public EmptyExpression()
{
}
public EmptyExpression(AstLocation location)
{
this.location = location;
}
public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data)
{
return visitor.VisitEmptyExpression(this, data);
}
protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
{
var o = other as EmptyExpression;
return o != null;
}
}
}

76
NRefactory/ICSharpCode.NRefactory.VB/Ast/Expressions/Expression.cs

@ -1,7 +1,8 @@ @@ -1,7 +1,8 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
// This code is distributed under MIT X11 license (for details please see \doc\license.txt)
using System;
using System.Collections.Generic;
namespace ICSharpCode.NRefactory.VB.Ast
{
@ -29,5 +30,78 @@ namespace ICSharpCode.NRefactory.VB.Ast @@ -29,5 +30,78 @@ namespace ICSharpCode.NRefactory.VB.Ast
}
}
#endregion
#region Builder methods
/// <summary>
/// Builds an member reference expression using this expression as target.
/// </summary>
public MemberAccessExpression Member(string memberName)
{
return new MemberAccessExpression { Target = this, MemberName = memberName };
}
/// <summary>
/// Builds an invocation expression using this expression as target.
/// </summary>
public InvocationExpression Invoke(string methodName, IEnumerable<Expression> arguments)
{
return Invoke(methodName, null, arguments);
}
/// <summary>
/// Builds an invocation expression using this expression as target.
/// </summary>
public InvocationExpression Invoke(string methodName, params Expression[] arguments)
{
return Invoke(methodName, null, arguments);
}
/// <summary>
/// Builds an invocation expression using this expression as target.
/// </summary>
public InvocationExpression Invoke(string methodName, IEnumerable<AstType> typeArguments, IEnumerable<Expression> arguments)
{
InvocationExpression ie = new InvocationExpression();
MemberAccessExpression mre = new MemberAccessExpression();
mre.Target = this;
mre.MemberName = methodName;
mre.TypeArguments.AddRange(typeArguments);
ie.Target = mre;
ie.Arguments.AddRange(arguments);
return ie;
}
/// <summary>
/// Builds an invocation expression using this expression as target.
/// </summary>
public InvocationExpression Invoke(IEnumerable<Expression> arguments)
{
InvocationExpression ie = new InvocationExpression();
ie.Target = this;
ie.Arguments.AddRange(arguments);
return ie;
}
/// <summary>
/// Builds an invocation expression using this expression as target.
/// </summary>
public InvocationExpression Invoke(params Expression[] arguments)
{
InvocationExpression ie = new InvocationExpression();
ie.Target = this;
ie.Arguments.AddRange(arguments);
return ie;
}
public CastExpression CastTo(AstType type)
{
return new CastExpression { CastType = CastType.CType, Type = type, Expression = this };
}
public CastExpression CastTo(Type type)
{
return new CastExpression { CastType = CastType.CType, Type = AstType.Create(type), Expression = this };
}
#endregion
}
}

49
NRefactory/ICSharpCode.NRefactory.VB/Ast/Expressions/FieldInitializerExpression.cs

@ -0,0 +1,49 @@ @@ -0,0 +1,49 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under MIT X11 license (for details please see \doc\license.txt)
using System;
using System.Collections.Generic;
namespace ICSharpCode.NRefactory.VB.Ast
{
/// <summary>
/// [ Key ] .Identifier = Expression
/// </summary>
public class FieldInitializerExpression : Expression
{
public bool IsKey { get; set; }
public VBTokenNode KeyToken {
get { return GetChildByRole (Roles.Keyword); }
}
public VBTokenNode DotToken {
get { return GetChildByRole (Roles.Dot); }
}
public Identifier Identifier {
get { return GetChildByRole(Roles.Identifier); }
set { SetChildByRole(Roles.Identifier, value); }
}
public VBTokenNode AssignToken {
get { return GetChildByRole (Roles.Assign); }
}
public Expression Expression {
get { return GetChildByRole (Roles.Expression); }
set { SetChildByRole (Roles.Expression, value); }
}
public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data)
{
return visitor.VisitFieldInitializerExpression(this, data);
}
protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
{
FieldInitializerExpression o = other as FieldInitializerExpression;
return o != null && this.IsKey == o.IsKey && this.Identifier.DoMatch(o.Identifier, match) && this.Expression.DoMatch(o.Expression, match);
}
}
}

31
NRefactory/ICSharpCode.NRefactory.VB/Ast/Expressions/GetTypeExpression.cs

@ -0,0 +1,31 @@ @@ -0,0 +1,31 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under MIT X11 license (for details please see \doc\license.txt)
using System;
namespace ICSharpCode.NRefactory.VB.Ast
{
public class GetTypeExpression : Expression
{
public GetTypeExpression()
{
}
public AstType Type {
get { return GetChildByRole(Roles.Type); }
set { SetChildByRole(Roles.Type, value); }
}
protected internal override bool DoMatch(AstNode other, ICSharpCode.NRefactory.PatternMatching.Match match)
{
var expr = other as GetTypeExpression;
return expr != null &&
Type.DoMatch(expr.Type, match);
}
public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data)
{
return visitor.VisitGetTypeExpression(this, data);
}
}
}

32
NRefactory/ICSharpCode.NRefactory.VB/Ast/Expressions/GetXmlNamespaceExpression.cs

@ -0,0 +1,32 @@ @@ -0,0 +1,32 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under MIT X11 license (for details please see \doc\license.txt)
using System;
namespace ICSharpCode.NRefactory.VB.Ast
{
public class GetXmlNamespaceExpression : Expression
{
public GetXmlNamespaceExpression(XmlIdentifier namespaceName)
{
SetChildByRole(Roles.XmlIdentifier, namespaceName);
}
public XmlIdentifier NamespaceName {
get { return GetChildByRole(Roles.XmlIdentifier); }
set { SetChildByRole(Roles.XmlIdentifier, value); }
}
protected internal override bool DoMatch(AstNode other, ICSharpCode.NRefactory.PatternMatching.Match match)
{
var expr = other as GetXmlNamespaceExpression;
return expr != null &&
NamespaceName.DoMatch(expr.NamespaceName, match);
}
public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data)
{
return visitor.VisitGetXmlNamespaceExpression(this, data);
}
}
}

39
NRefactory/ICSharpCode.NRefactory.VB/Ast/Expressions/IdentifierExpression.cs

@ -0,0 +1,39 @@ @@ -0,0 +1,39 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under MIT X11 license (for details please see \doc\license.txt)
using System;
namespace ICSharpCode.NRefactory.VB.Ast
{
public class IdentifierExpression : Expression
{
public IdentifierExpression()
{
}
public IdentifierExpression(Identifier identifier)
{
this.Identifier = identifier;
}
public Identifier Identifier {
get { return GetChildByRole(Roles.Identifier); }
set { SetChildByRole(Roles.Identifier, value); }
}
public AstNodeCollection<AstType> TypeArguments {
get { return GetChildrenByRole(Roles.TypeArgument); }
}
protected internal override bool DoMatch(AstNode other, ICSharpCode.NRefactory.PatternMatching.Match match)
{
throw new NotImplementedException();
}
public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data)
{
return visitor.VisitIdentifierExpression(this, data);
}
}
}

61
NRefactory/ICSharpCode.NRefactory.VB/Ast/Expressions/InstanceExpression.cs

@ -0,0 +1,61 @@ @@ -0,0 +1,61 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under MIT X11 license (for details please see \doc\license.txt)
using System;
namespace ICSharpCode.NRefactory.VB.Ast
{
/// <summary>
/// Description of InstanceExpression.
/// </summary>
public class InstanceExpression : Expression
{
AstLocation location;
public InstanceExpression(InstanceExpressionType type, AstLocation location)
{
this.Type = type;
this.location = location;
}
public override AstLocation StartLocation {
get { return location; }
}
public override AstLocation EndLocation {
get {
switch (Type) {
case InstanceExpressionType.Me:
return new AstLocation(location.Line, location.Column + "Me".Length);
case InstanceExpressionType.MyBase:
return new AstLocation(location.Line, location.Column + "MyBase".Length);
case InstanceExpressionType.MyClass:
return new AstLocation(location.Line, location.Column + "MyClass".Length);
default:
throw new Exception("Invalid value for InstanceExpressionType");
}
}
}
public InstanceExpressionType Type { get; set; }
protected internal override bool DoMatch(AstNode other, ICSharpCode.NRefactory.PatternMatching.Match match)
{
var expr = other as InstanceExpression;
return expr != null &&
Type == expr.Type;
}
public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data)
{
return visitor.VisitInstanceExpression(this, data);
}
}
public enum InstanceExpressionType
{
Me,
MyBase,
MyClass
}
}

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save