-
-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathMiscellaneous.cs
272 lines (241 loc) · 12.8 KB
/
Miscellaneous.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
using Cecilifier.Core.Tests.Tests.Unit.Framework;
using NUnit.Framework;
namespace Cecilifier.Core.Tests.Tests.Unit
{
[TestFixture]
public class MiscellaneousTests : CecilifierUnitTestBase
{
[Test]
public void Test_Issue110()
{
var code = "class Foo { void Bar(string s) { var index = 2; Bar(s.Substring(0, index)); } }";
var expectedSnippet = @".*(?<emit>.+\.Emit\(OpCodes\.)Ldarg_0\);\s"
+ @"\1Ldarg_1.+;\s"
+ @"\1Ldc_I4, 0.+;\s"
+ @"\1Ldloc, l_index_4.+;\s"
+ @"\1Callvirt, .+""Substring"".+;\s"
+ @"\1Call, m_bar_1.+;\s"
+ @"\1Ret.+;";
var result = RunCecilifier(code);
Assert.That(result.GeneratedCode.ReadToEnd(), Does.Match(expectedSnippet));
}
[Test]
public void CustomDelegate_ComparisonToNull_GeneratesCeqInstruction_InsteadOfCalling_Operator()
{
var code = @"using System;
public delegate object CustomDelegate(int arg);
public static class ObjectMaker
{
public static bool Test(CustomDelegate cd) => cd == null;
}";
var expectedCecilifiedCode = @"il_test_10.Emit\(OpCodes.Ldarg_0\).+\s+" +
@"il_test_10.Emit\(OpCodes.Ldnull\).+\s+" +
@"il_test_10.Emit\(OpCodes.Ceq\).+\s+" +
@"il_test_10.Emit\(OpCodes.Ret\);";
var result = RunCecilifier(code);
var cecilifiedCode = result.GeneratedCode.ReadToEnd();
Assert.That(cecilifiedCode, Does.Match(expectedCecilifiedCode), cecilifiedCode);
}
[Test]
public void Nested_Enum()
{
var code = @"
public static class Outer
{
public enum Nested { First = 42 }
}";
var result = RunCecilifier(code);
var cecilifiedCode = result.GeneratedCode.ReadToEnd();
Assert.That(cecilifiedCode,
Contains.Substring("var enum_nested_1 = new TypeDefinition(\"\", \"Nested\", TypeAttributes.NestedPublic | TypeAttributes.Sealed, assembly.MainModule.ImportReference(typeof(System.Enum)));"),
cecilifiedCode);
Assert.That(cecilifiedCode,
Contains.Substring(
"var l_first_3 = new FieldDefinition(\"First\", FieldAttributes.Static | FieldAttributes.Literal | FieldAttributes.Public | FieldAttributes.HasDefault, enum_nested_1) { Constant = 42 } ;"),
cecilifiedCode);
}
[Test]
public void Test_Issue_126_Types()
{
var result = RunCecilifier(@"
using System.IO;
namespace NS { public struct FileStream { } }
class Foo
{
public FileStream file; // System.IO.FileStream since NS.FileStream is not in scope here.
public NS.FileStream definedInNS;
}");
var cecilifiedCode = result.GeneratedCode.ReadToEnd();
Assert.That(cecilifiedCode.Contains("FieldDefinition(\"file\", FieldAttributes.Public, st_fileStream_0);"), Is.False, cecilifiedCode);
Assert.That(cecilifiedCode,Does.Match("""var st_fileStream_0 = new TypeDefinition\("NS", "FileStream", .+\);"""));
Assert.That(cecilifiedCode.Contains("FieldDefinition(\"definedInNS\", FieldAttributes.Public, st_fileStream_0);"), Is.True, cecilifiedCode);
Assert.That(cecilifiedCode.Contains("FieldDefinition(\"file\", FieldAttributes.Public, assembly.MainModule.ImportReference(typeof(System.IO.FileStream)));"), Is.True, cecilifiedCode);
}
[Test]
public void Test_Issue_126_Members()
{
var result = RunCecilifier(@"
using System;
using System.Diagnostics;
namespace NS
{
public struct Process { public void Kill() { } public string ProcessName => """"; public event EventHandler Exited;}
}
class Foo
{
public Process proc;
private void Handler(object sender, EventArgs args) { }
void Method() => proc.Kill();
string Property() => proc.ProcessName;
// void Event() => proc.Exited += Handler; // Depends on issue # 127
}");
var cecilifiedCode = result.GeneratedCode.ReadToEnd();
Assert.That(cecilifiedCode, Does.Match("""il_method_\d+.Emit\(OpCodes.Callvirt, .*typeof\(System.Diagnostics.Process\), "Kill".+"""), cecilifiedCode);
Assert.That(cecilifiedCode, Does.Match(@"il_property_\d+.Emit\(OpCodes.Callvirt, .+typeof\(System.Diagnostics.Process\), ""get_ProcessName"".+"), cecilifiedCode);
}
[TestCase("class StaticFieldAddress { static int field; static void M1(ref int i) { } static void M() => M1(ref field); }", "Ldsflda", TestName = "StaticPassingByRef")]
[TestCase("class FieldAddress { int field; void M1(ref int i) { } void M() => M1(ref field); }", "Ldflda", TestName = "PassingByRef")]
[TestCase("class FieldAddress { int field; unsafe void Fixed() { fixed(int *p = &field) { } } }", "Ldflda", TestName = "Fixed")]
[TestCase("class StaticFieldAddress { static int field; static unsafe void Fixed() { fixed(int *p = &field) { } } }", "Ldsflda", TestName = "StaticFixed")]
public void Field_Address(string code, string expectedLoadOpCode)
{
var result = RunCecilifier(code);
var cecilifiedCode = result.GeneratedCode.ReadToEnd();
Assert.That(cecilifiedCode, Contains.Substring(expectedLoadOpCode));
}
[TestCase("fieldDelegate")]
[TestCase("PropertyDelegate")]
[TestCase("localDelegate")]
[TestCase("paramDelegate")]
[TestCase("fieldFunction")]
[TestCase("PropertyFunction")]
[TestCase("localFunction")]
[TestCase("paramFunction")]
public void LdindTests(string varToUse)
{
var code =
$@"
using System;
unsafe class Foo
{{
delegate*<bool, int, void> fieldFunction;
Action<bool, int> fieldDelegate;
delegate*<bool, int, void> PropertyFunction {{ get; set; }}
Action<bool, int> PropertyDelegate {{ get; set; }}
void Bar(Action<bool, int> paramDelegate, delegate*<bool, int, void> paramFunction, int v)
{{
Action<bool, int> localDelegate = paramDelegate;
delegate*<bool, int, void> localFunction = paramFunction;
{varToUse}(true, v);
}}
}}";
var result = RunCecilifier(code);
var cecilifiedCode = result.GeneratedCode.ReadToEnd();
Assert.That(cecilifiedCode, Does.Not.Contains("Ldind"));
}
[Test]
public void TestEvents()
{
var source = @"class Foo {
private void Handler(object sender, System.EventArgs args) { }
void SetEvent(System.Diagnostics.Process proc) => proc.Exited += Handler;
}";
var result = RunCecilifier(source);
Assert.That(result.GeneratedCode.ReadToEnd(), Does.Match(
@"il_setEvent_6.Emit\(OpCodes.Ldarg_1\);
il_setEvent_6.Emit\(OpCodes.Ldarg_0\);
il_setEvent_6.Emit\(OpCodes.Ldftn, m_handler_1\);
il_setEvent_6.Emit\(OpCodes.Newobj,.+System.EventHandler.+,.+System.Object.+,.+System.IntPtr.+\);
il_setEvent_6.Emit\(OpCodes.Callvirt,.+add_Exited.+\);"));
}
[Test]
public void TypesNotInSystemCorelib_AreResolved()
{
var source = @"class Foo {
private void Handler(object sender, System.ConsoleCancelEventArgs args) { }
void SetEvent() => System.Console.CancelKeyPress += Handler;
}";
var result = RunCecilifier(source);
Assert.That(result.GeneratedCode.ReadToEnd(), Contains.Substring("typeof(System.Console), \"add_CancelKeyPress\","));
}
[TestCase("j")]
[TestCase("j + 2")]
[TestCase("j > 1 ? 0 : 1")]
public void TestCallerArgumentExpressionAttribute(string expression)
{
var source = $@"class Foo {{ void M(int i, [System.Runtime.CompilerServices.CallerArgumentExpression(""i"")] string s = null) {{ }} void Call(int j) => M({expression}); }}";
var result = RunCecilifier(source);
Assert.That(result.GeneratedCode.ReadToEnd(), Contains.Substring($"Ldstr, \"{expression}\""));
}
[TestCase("\"foo\"")]
[TestCase("null")]
public void TestCallerArgumentExpressionAttribute_InvalidParameterName(string defaultParameterValue)
{
var source = $@"class Foo {{ void M(int i, [System.Runtime.CompilerServices.CallerArgumentExpression(""DoNotExist"")] string s = {defaultParameterValue}) {{ }} void Call(int j) => M(j); }}";
var result = RunCecilifier(source);
if (defaultParameterValue == "null")
Assert.That(result.GeneratedCode.ReadToEnd(), Contains.Substring("Ldnull"));
else
Assert.That(result.GeneratedCode.ReadToEnd(), Contains.Substring($"Ldstr, {defaultParameterValue}"));
}
[TestCase(
"System.DateTime d = new();",
"""
(il_topLevelMain_\d+).Emit\(OpCodes.Ldloca_S, l_d_\d+\);
\s+\1.Emit\(OpCodes.Initobj, .+ImportReference\(typeof\(System.DateTime\)\)\);
""",
TestName = "Value Type")]
[TestCase("object o = new();", """il_topLevelMain_\d+.Emit\(OpCodes.Newobj,.+typeof\(System.Object\), ".ctor",.+\);""", TestName = "Simplest")]
[TestCase(
"C c = new(42); class C { public C(int i) {} }",
"""
var ctor_C_\d+ = new MethodDefinition\(".ctor", .+, assembly.MainModule.TypeSystem.Void\);
""",
"""
var (p_i_\d+) = new ParameterDefinition\("i", ParameterAttributes.None, assembly.MainModule.TypeSystem.Int32\);
\s+ctor_C_\d+.Parameters.Add\(\1\);
""",
"""
\s+il_topLevelMain_7.Emit\(OpCodes.Ldc_I4, 42\);
\s+il_topLevelMain_7.Emit\(OpCodes.Newobj, ctor_C_\d+\);
""",
TestName = "Constructor")]
[TestCase(
"C c = new() { Value = 42 }; class C { public int Value; }",
"""
(il_topLevelMain_\d+.Emit\(OpCodes\.)Newobj, ctor_C_\d+\);
\s+\1Dup\);
\s+\1Ldc_I4, 42\);
\s+\1Stfld, fld_value_\d+\);
\s+\1Stloc, l_c_\d+\);
""",
TestName = "Object Initializer")]
public void TestImplicitObjectCreation(string code, params string[] expectations)
{
var r = RunCecilifier(code);
var cecilifiedCode = r.GeneratedCode.ReadToEnd();
foreach(var expected in expectations)
{
Assert.That(cecilifiedCode, Does.Match(expected));
}
}
public class RecordTests : CecilifierUnitTestBase
{
[TestCase("class", TestName = "NullableContext and NullableAttribute are added to the type definition - class")]
[TestCase("struct", TestName = "NullableContext and NullableAttribute are added to the type definition - struct")]
public void NullableContextAndNullableAttributes(string kind)
{
var r = RunCecilifier($"public record {kind} RecordTest;");
var cecilifiedCode = r.GeneratedCode.ReadToEnd();
Assert.That(cecilifiedCode, Does.Match("""
(attr_nullableContext_\d+).ConstructorArguments.Add\(new CustomAttributeArgument\(assembly.MainModule.TypeSystem.Int32, 1\)\);
\s+rec_recordTest_\d+.CustomAttributes.Add\(\1\);
"""));
Assert.That(cecilifiedCode, Does.Match("""
(attr_nullable_\d+).ConstructorArguments.Add\(new CustomAttributeArgument\(assembly.MainModule.TypeSystem.Int32, 0\)\);
\s+rec_recordTest_\d+.CustomAttributes.Add\(\1\);
"""));
}
}
}
}