forked from Fody/ToString
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathModuleWeaver.cs
More file actions
493 lines (406 loc) · 18.4 KB
/
ModuleWeaver.cs
File metadata and controls
493 lines (406 loc) · 18.4 KB
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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
using System;
using System.Collections;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System.Xml.Linq;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Cecil.Rocks;
using Mono.Collections.Generic;
using System.Globalization;
using System.CodeDom.Compiler;
using System.Diagnostics;
using ToString.Fody.Extensions;
public class ModuleWeaver
{
public ModuleDefinition ModuleDefinition { get; set; }
public IAssemblyResolver AssemblyResolver { get; set; }
public XElement Config { get; set; }
private TypeReference stringBuilderType;
private MethodReference appendString;
private MethodReference moveNext;
private MethodReference currrent;
private MethodReference getEnumerator;
private MethodReference getInvariantCulture;
private MethodReference formatMethod;
public IEnumerable<TypeDefinition> GetMachingTypes()
{
return ModuleDefinition.GetTypes().Where(x => x.CustomAttributes.Any(a => a.AttributeType.Name == "ToStringAttribute"));
}
public void Execute()
{
stringBuilderType = ModuleDefinition.Import(typeof (StringBuilder));
appendString = ModuleDefinition.Import(typeof(StringBuilder).GetMethod("Append", new[] { typeof(object) }));
moveNext = ModuleDefinition.Import(typeof(IEnumerator).GetMethod("MoveNext"));
currrent = ModuleDefinition.Import(typeof(IEnumerator).GetProperty("Current").GetGetMethod());
getEnumerator = ModuleDefinition.Import(typeof(IEnumerable).GetMethod("GetEnumerator"));
formatMethod = this.ModuleDefinition.Import(this.ModuleDefinition.TypeSystem.String.Resolve().FindMethod("Format", "IFormatProvider", "String", "Object[]"));
var cultureInfoType = ModuleDefinition.Import(typeof(CultureInfo)).Resolve();
var invariantCulture = cultureInfoType.Properties.Single(x => x.Name == "InvariantCulture");
getInvariantCulture = ModuleDefinition.Import(invariantCulture.GetMethod);
foreach (var type in GetMachingTypes())
{
AddToString(type);
}
this.RemoveReference();
}
private PropertyDefinition[] GetPublicProperties(TypeDefinition type)
{
return type.Properties.Where(x => x.GetMethod != null).ToArray();
}
private void AddToString(TypeDefinition type)
{
var methodAttributes = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Virtual;
var strType = ModuleDefinition.TypeSystem.String;
var method = new MethodDefinition("ToString", methodAttributes, strType);
method.Body.Variables.Add(new VariableDefinition(new ArrayType(ModuleDefinition.TypeSystem.Object)));
var allProperties = type.GetProperties();
var properties = RemoveIgnoredProperties(allProperties);
var format = GetFormatString(type, properties);
var body = method.Body;
var ins = body.Instructions;
var hasCollections = properties.Any(x => x.PropertyType.Resolve().IsCollection());
if (hasCollections)
{
method.Body.Variables.Add(new VariableDefinition(stringBuilderType));
var enumeratorType = this.ModuleDefinition.Import(typeof (IEnumerator));
method.Body.Variables.Add(new VariableDefinition(enumeratorType));
method.Body.Variables.Add(new VariableDefinition(ModuleDefinition.TypeSystem.Boolean));
method.Body.Variables.Add(new VariableDefinition(new ArrayType(ModuleDefinition.TypeSystem.Object)));
}
var genericOffset = !type.HasGenericParameters ? 0 : type.GenericParameters.Count;
this.AddInitCode(ins, format, properties, genericOffset);
if (type.HasGenericParameters)
{
AddGenericParameterNames(type, ins);
}
for (var i = 0; i < properties.Length; i++)
{
var property = properties[i];
AddPropertyCode(method.Body, i + genericOffset, property, type);
}
this.AddMethodAttributes(method);
this.AddEndCode(body);
body.OptimizeMacros();
type.Methods.Add(method);
this.RemoveFodyAttributes(type, allProperties);
}
private void AddGenericParameterNames(TypeDefinition type, Collection<Instruction> ins)
{
var typeType = ModuleDefinition.Import(typeof(Type)).Resolve();
var memberInfoType = ModuleDefinition.Import(typeof(System.Reflection.MemberInfo)).Resolve();
var getTypeMethod = this.ModuleDefinition.Import(ModuleDefinition.TypeSystem.Object.Resolve().FindMethod("GetType"));
var getGenericArgumentsMethod = this.ModuleDefinition.Import(typeType.FindMethod("GetGenericArguments"));
var nameProperty = memberInfoType.Properties.Where(x => x.Name == "Name").Single();
var nameGet = ModuleDefinition.Import(nameProperty.GetMethod);
for (var i = 0; i < type.GenericParameters.Count; i++)
{
ins.Add(Instruction.Create(OpCodes.Ldloc_0));
ins.Add(Instruction.Create(OpCodes.Ldc_I4, i));
ins.Add(Instruction.Create(OpCodes.Ldarg_0));
ins.Add(Instruction.Create(OpCodes.Callvirt, getTypeMethod));
ins.Add(Instruction.Create(OpCodes.Callvirt, getGenericArgumentsMethod));
ins.Add(Instruction.Create(OpCodes.Ldc_I4, i));
ins.Add(Instruction.Create(OpCodes.Ldelem_Ref));
ins.Add(Instruction.Create(OpCodes.Callvirt, nameGet));
ins.Add(Instruction.Create(OpCodes.Stelem_Ref));
}
}
private void AddMethodAttributes(MethodDefinition method)
{
var generatedConstructor = ModuleDefinition.Import(typeof(GeneratedCodeAttribute).GetConstructor(new[] { typeof(string), typeof(string) }));
var version = typeof(ModuleWeaver).Assembly.GetName().Version.ToString();
var generatedAttribute = new CustomAttribute(generatedConstructor);
generatedAttribute.ConstructorArguments.Add(new CustomAttributeArgument(ModuleDefinition.TypeSystem.String, "Fody.ToString"));
generatedAttribute.ConstructorArguments.Add(new CustomAttributeArgument(ModuleDefinition.TypeSystem.String, version));
method.CustomAttributes.Add(generatedAttribute);
var debuggerConstructor = ModuleDefinition.Import(typeof(DebuggerNonUserCodeAttribute).GetConstructor(Type.EmptyTypes));
var debuggerAttribute = new CustomAttribute(debuggerConstructor);
method.CustomAttributes.Add(debuggerAttribute);
}
private void AddEndCode(MethodBody body)
{
var stringType = this.ModuleDefinition.TypeSystem.String.Resolve();
var formatMethod = this.ModuleDefinition.Import(stringType.FindMethod("Format", "IFormatProvider", "String", "Object[]"));
body.Instructions.Add(Instruction.Create(OpCodes.Ldloc_0));
body.Instructions.Add(Instruction.Create(OpCodes.Call, formatMethod));
body.Instructions.Add(Instruction.Create(OpCodes.Ret));
}
private void AddInitCode(Collection<Instruction> ins, string format, PropertyDefinition[] properties, int genericOffset)
{
var cultureInfoType = ModuleDefinition.Import(typeof(CultureInfo)).Resolve();
var invariantCulture = cultureInfoType.Properties.Single(x => x.Name == "InvariantCulture");
var getInvariantCulture = ModuleDefinition.Import(invariantCulture.GetMethod);
ins.Add(Instruction.Create(OpCodes.Call, getInvariantCulture));
ins.Add(Instruction.Create(OpCodes.Ldstr, format));
ins.Add(Instruction.Create(OpCodes.Ldc_I4, properties.Length + genericOffset));
ins.Add(Instruction.Create(OpCodes.Newarr, this.ModuleDefinition.TypeSystem.Object));
ins.Add(Instruction.Create(OpCodes.Stloc_0));
}
private void AddPropertyCode(MethodBody body, int index, PropertyDefinition property, TypeDefinition targetType)
{
var ins = body.Instructions;
ins.Add(Instruction.Create(OpCodes.Ldloc_0));
ins.Add(Instruction.Create(OpCodes.Ldc_I4, index));
MethodReference get = property.GetGetMethod(targetType);
ins.Add(Instruction.Create(OpCodes.Ldarg_0));
ins.Add(Instruction.Create(OpCodes.Call, get));
if ( get.ReturnType.IsValueType)
{
ins.Add(Instruction.Create(OpCodes.Box, property.GetMethod.ReturnType));
}
else
{
var propType = property.PropertyType.Resolve();
var isCollection = propType.IsCollection();
if (isCollection)
{
AssignFalseToFirstFLag(ins);
this.If(ins,
nc =>
{
nc.Add(Instruction.Create(OpCodes.Dup));
},
nt =>
{
this.GetEnumerator(nt);
this.NewStringBuilder(nt);
this.AppendString(nt, "[");
this.While(nt,
c =>
{
c.Add(Instruction.Create(OpCodes.Ldloc_2));
c.Add(Instruction.Create(OpCodes.Callvirt, moveNext));
},
b =>
{
AppendSeparator(b, appendString);
ins.Add(Instruction.Create(OpCodes.Ldloc_1));
this.If(ins,
c =>
{
c.Add(Instruction.Create(OpCodes.Ldloc_2));
c.Add(Instruction.Create(OpCodes.Callvirt, currrent));
},
t =>
{
t.Add(Instruction.Create(OpCodes.Call, getInvariantCulture));
string format;
var collectionType = ((GenericInstanceType)property.PropertyType).GenericArguments[0];
if (HaveToAddQuotes(collectionType))
{
format = "\"{0}\"";
}
else
{
format = "{0}";
}
t.Add(Instruction.Create(OpCodes.Ldstr, format));
t.Add(Instruction.Create(OpCodes.Ldc_I4, 1));
t.Add(Instruction.Create(OpCodes.Newarr, this.ModuleDefinition.TypeSystem.Object));
t.Add(Instruction.Create(OpCodes.Stloc, body.Variables[4]));
t.Add(Instruction.Create(OpCodes.Ldloc, body.Variables[4]));
t.Add(Instruction.Create(OpCodes.Ldc_I4_0));
t.Add(Instruction.Create(OpCodes.Ldloc_2));
t.Add(Instruction.Create(OpCodes.Callvirt, currrent));
t.Add(Instruction.Create(OpCodes.Stelem_Ref));
t.Add(Instruction.Create(OpCodes.Ldloc, body.Variables[4]));
t.Add(Instruction.Create(OpCodes.Call, formatMethod));
},
e =>
{
e.Add(Instruction.Create(OpCodes.Ldstr, "null"));
});
ins.Add(Instruction.Create(OpCodes.Callvirt, appendString));
ins.Add(Instruction.Create(OpCodes.Pop));
});
this.AppendString(ins, "]");
this.StringBuilderToString(ins);
},
nf =>
{
ins.Add(Instruction.Create(OpCodes.Pop));
ins.Add(Instruction.Create(OpCodes.Ldstr, "null"));
});
}
else
{
this.If(ins,
c =>
{
ins.Add(Instruction.Create(OpCodes.Dup));
},
t => {},
e =>
{
ins.Add(Instruction.Create(OpCodes.Pop));
ins.Add(Instruction.Create(OpCodes.Ldstr, "null"));
});
}
}
ins.Add(Instruction.Create(OpCodes.Stelem_Ref));
}
private void NewStringBuilder(Collection<Instruction> ins)
{
var stringBuilderConstructor = this.ModuleDefinition.Import(typeof (StringBuilder).GetConstructor(new Type[] {}));
ins.Add(Instruction.Create(OpCodes.Newobj, stringBuilderConstructor));
ins.Add(Instruction.Create(OpCodes.Stloc_1));
}
private void GetEnumerator(Collection<Instruction> ins)
{
ins.Add(Instruction.Create(OpCodes.Callvirt, this.getEnumerator));
ins.Add(Instruction.Create(OpCodes.Stloc_2));
}
private static void AssignFalseToFirstFLag(Collection<Instruction> ins)
{
ins.Add(Instruction.Create(OpCodes.Ldc_I4_0));
ins.Add(Instruction.Create(OpCodes.Stloc_3));
}
private void While(
Collection<Instruction> ins,
Action<Collection<Instruction>> condition,
Action<Collection<Instruction>> body )
{
var loopBegin = Instruction.Create(OpCodes.Nop);
var loopEnd = Instruction.Create(OpCodes.Nop);
ins.Add(loopBegin);
condition(ins);
ins.Add(Instruction.Create(OpCodes.Brfalse, loopEnd));
body(ins);
ins.Add(Instruction.Create(OpCodes.Br, loopBegin));
ins.Add(loopEnd);
}
private void AppendString(Collection<Instruction> ins, string str)
{
ins.Add(Instruction.Create(OpCodes.Ldloc_1));
ins.Add(Instruction.Create(OpCodes.Ldstr, str));
ins.Add(Instruction.Create(OpCodes.Callvirt, appendString));
ins.Add(Instruction.Create(OpCodes.Pop));
}
private void StringBuilderToString(Collection<Instruction> ins)
{
ins.Add(Instruction.Create(OpCodes.Ldloc_1));
var toStringMethod = this.ModuleDefinition.Import(stringBuilderType.Resolve().FindMethod("ToString"));
ins.Add(Instruction.Create(OpCodes.Callvirt, toStringMethod));
}
private void If(Collection<Instruction> ins,
Action<Collection<Instruction>> condition,
Action<Collection<Instruction>> thenStatment,
Action<Collection<Instruction>> elseStetment)
{
var ifEnd = Instruction.Create(OpCodes.Nop);
var ifElse = Instruction.Create(OpCodes.Nop);
condition(ins);
ins.Add(Instruction.Create(OpCodes.Brfalse, ifElse));
thenStatment(ins);
ins.Add(Instruction.Create(OpCodes.Br, ifEnd));
ins.Add(ifElse);
elseStetment(ins);
ins.Add(ifEnd);
}
private void AppendSeparator(Collection<Instruction> ins, MethodReference appendString)
{
If(ins,
c =>
{
c.Add(Instruction.Create(OpCodes.Ldloc_3));
},
t =>
{
AppendString(t, ", ");
},
e =>
{
ins.Add(Instruction.Create(OpCodes.Ldc_I4_1));
ins.Add(Instruction.Create(OpCodes.Stloc_3));
});
}
private string GetFormatString(TypeDefinition type, PropertyDefinition[] properties)
{
var sb = new StringBuilder();
sb.Append("{{T: \"");
int offset = 0;
if (!type.HasGenericParameters)
{
sb.Append(type.Name);
}
else
{
var name = type.Name.Remove(type.Name.IndexOf('`'));
offset = type.GenericParameters.Count;
sb.Append(name);
sb.Append('<');
for (var i = 0; i < offset; i++)
{
sb.Append("{");
sb.Append(i);
sb.Append("}");
if (i + 1 != offset)
{
sb.Append(", ");
}
}
sb.Append('>');
}
sb.Append("\", ");
for (var i = 0; i < properties.Length; i++)
{
var property = properties[i];
sb.Append(property.Name);
sb.Append(": ");
if (HaveToAddQuotes(property.PropertyType))
{
sb.Append('"');
}
sb.Append('{');
sb.Append(i + offset);
if (property.PropertyType.FullName == "System.DateTime")
{
sb.Append(":O");
}
sb.Append("}");
if (HaveToAddQuotes(property.PropertyType))
{
sb.Append('"');
}
if (i != properties.Length - 1)
{
sb.Append(", ");
}
}
sb.Append("}}");
var format = sb.ToString();
return format;
}
private static bool HaveToAddQuotes(TypeReference type)
{
var name = type.FullName;
if(name == "System.String" || name == "System.Char" || name == "System.DateTime")
{
return true;
}
var resolved = type.Resolve();
return resolved != null && resolved.IsEnum;
}
private void RemoveReference()
{
var referenceToRemove = ModuleDefinition.AssemblyReferences.FirstOrDefault(x => x.Name == "ToString");
if (referenceToRemove != null)
{
ModuleDefinition.AssemblyReferences.Remove(referenceToRemove);
}
}
private void RemoveFodyAttributes(TypeDefinition type, PropertyDefinition[] allProperties)
{
type.RemoveAttribute("ToStringAttribute");
foreach (var property in allProperties)
{
property.RemoveAttribute("IgnoreDuringToStringAttribute");
}
}
private PropertyDefinition[] RemoveIgnoredProperties(PropertyDefinition[] allProperties)
{
return allProperties.Where(x => x.CustomAttributes.All(y => y.AttributeType.Name != "IgnoreDuringToStringAttribute")).ToArray();
}
}