-
Notifications
You must be signed in to change notification settings - Fork 0
/
FormattingExtensions.cs
824 lines (677 loc) · 20.8 KB
/
FormattingExtensions.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
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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
//
// Author:
// Marek Habersack <[email protected]>
//
// Copyright (c) 2010-2011, Marek Habersack
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the distribution.
// * Neither the name of Marek Habersack nor the names of the contributors may be used to endorse or promote products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Mono.Cecil;
using Mono.Cecil.Metadata;
using Mono.Collections.Generic;
namespace StubGen
{
public static class FormattingExtensions
{
static Dictionary <string, bool> ignored_attributes = new Dictionary<string, bool> (StringComparer.Ordinal) {
{ "System.Runtime.TargetedPatchingOptOutAttribute", true },
{ "System.ParamArrayAttribute", true },
{ "System.Runtime.CompilerServices.CompilerGeneratedAttribute", true }
};
public static string FormatName (this MetadataType type)
{
switch (type) {
case MetadataType.Boolean:
return "bool";
case MetadataType.Char:
return "char";
case MetadataType.SByte:
return "sbyte";
case MetadataType.Byte:
return "byte";
case MetadataType.Int16:
return "short";
case MetadataType.UInt16:
return "ushort";
case MetadataType.Int32:
return "int";
case MetadataType.UInt32:
return "uint";
case MetadataType.Int64:
return "long";
case MetadataType.UInt64:
return "ulong";
case MetadataType.Single:
return "float";
case MetadataType.Double:
return "double";
case MetadataType.String:
return "string";
default:
return type.ToString ();
}
}
public static string FormatName (this TypeReference type)
{
if (type == null)
return String.Empty;
string ns = type.Namespace;
if (!String.IsNullOrEmpty (ns))
Utils.Usings.AddUsing (ns);
if (type.IsGenericParameter)
return FormatName (type as GenericParameter);
if (type.IsArray)
return FormatName (type as ArrayType);
if (type.IsPrimitive)
return FormatName (type.MetadataType);
switch (type.FullName) {
case "System.String":
return "string";
case "System.Object":
return "object";
case "System.Void":
return "void";
}
TypeDefinition tdef = type.ResolveType ();
if (tdef == null)
return type.GetTypeName ();
string name = FormatGenericTypeName (tdef.GetTypeName ());
var sb = new StringBuilder ();
bool nullable = type.FullName.StartsWith ("System.Nullable`1", StringComparison.Ordinal);
if (!nullable) {
if (type.IsPointer)
sb.Append (FormatName (type as PointerType));
else
sb.Append (name);
}
bool first = true;
if (type.IsGenericInstance) {
GenericInstanceType git = type as GenericInstanceType;
if (nullable) {
TypeReference gtype = git.GenericArguments.FirstOrDefault ();
if (gtype != null)
sb.AppendFormat ("{0}?", FormatName (gtype));
} else {
sb.Append (" <");
foreach (TypeReference gtype in git.GenericArguments) {
if (!first)
sb.Append (", ");
else
first = false;
sb.Append (FormatName (gtype));
}
sb.Append (">");
}
} else if (tdef.HasGenericParameters) {
sb.Append (" <");
Collection <GenericParameter> gpcoll = tdef.GenericParameters;
foreach (GenericParameter gp in gpcoll) {
if (!first)
sb.Append (", ");
else
first = false;
sb.Append (FormatName (gp));
}
sb.Append (">");
}
return sb.ToString ();
}
public static string FormatName (this ArrayType type)
{
if (type == null)
return String.Empty;
// TODO: add support for multi-dimensional arrays
// TODO: add support for size spec
return FormatName (type.ElementType) + "[]";
}
public static string FormatName (this PointerType type)
{
if (type == null)
return String.Empty;
return "unsafe " + FormatName (type.ElementType) + "*";
}
public static string Format (this TargetRuntime runtime)
{
switch (runtime) {
case TargetRuntime.Net_1_0:
return "1.0";
case TargetRuntime.Net_1_1:
return "1.1";
case TargetRuntime.Net_2_0:
return "2.0/3.5";
case TargetRuntime.Net_4_0:
return "4.0";
default:
return runtime.ToString ();
}
}
public static string Format (this Collection <CustomAttribute> attributes)
{
if (attributes == null || attributes.Count == 0)
return String.Empty;
var sb = new StringBuilder ();
foreach (CustomAttribute attr in attributes) {
if (ignored_attributes.ContainsKey (attr.AttributeType.FullName))
continue;
sb.AppendIndent ("[");
sb.Append (FormatName (attr));
sb.AppendLine ("]");
}
return sb.ToString ();
}
public static string FormatCustomAttributesOneLine (this Collection <CustomAttribute> attributes)
{
if (attributes == null || attributes.Count == 0)
return String.Empty;
bool first = true;
var sb = new StringBuilder ();
foreach (CustomAttribute attr in attributes) {
if (attr.AttributeType.FullName == "System.ParamArrayAttribute")
continue;
if (!first)
sb.Append (", ");
else {
sb.Append ("[");
first = false;
}
sb.Append (FormatName (attr));
}
if (sb.Length > 0)
sb.Append ("]");
if (sb.Length == 0)
return String.Empty;
return sb.ToString ();
}
public static string FormatName (this GenericParameter gp)
{
if (gp == null)
return String.Empty;
var sb = new StringBuilder ();
if (gp.HasCustomAttributes) {
sb.Append (FormatCustomAttributesOneLine (gp.CustomAttributes));
sb.Append (' ');
}
sb.Append (gp.Name);
return sb.ToString ();
}
public static string FormatName (this CustomAttribute attr)
{
if (attr == null)
return String.Empty;
TypeReference type = attr.AttributeType;
string str = type.Namespace;
Utils.Usings.AddUsing (str);
var sb = new StringBuilder ();
str = type.Name;
if (str.EndsWith ("Attribute", StringComparison.Ordinal))
str = str.Substring (0, str.Length - 9);
sb.Append (str);
bool first = true;
bool needParen = false;
if (attr.HasConstructorArguments) {
needParen = true;
sb.Append (" (");
foreach (Mono.Cecil.CustomAttributeArgument arg in attr.ConstructorArguments) {
if (!first)
sb.Append (", ");
else
first = false;
sb.Append (Utils.FormatValue (arg.Value, arg.Type, Utils.Usings));
}
}
if (attr.HasFields) {
if (!needParen) {
needParen = true;
sb.Append (" (");
}
foreach (Mono.Cecil.CustomAttributeNamedArgument arg in attr.Fields) {
if (!first)
sb.Append (", ");
else
first = false;
sb.AppendFormat ("{0}={1}", arg.Name, Utils.FormatValue (arg.Argument.Value, arg.Argument.Type, Utils.Usings));
}
}
if (attr.HasProperties) {
if (!needParen) {
needParen = true;
sb.Append (" (");
}
foreach (Mono.Cecil.CustomAttributeNamedArgument arg in attr.Properties) {
if (!first)
sb.Append (", ");
else
first = false;
sb.AppendFormat ("{0}={1}", arg.Name, Utils.FormatValue (arg.Argument.Value, arg.Argument.Type, Utils.Usings));
}
}
if (needParen)
sb.Append (")");
return sb.ToString ();
}
public static string FormatName (this FieldDefinition field)
{
if (field == null)
return String.Empty;
if (field.HasCustomAttributes)
field.CustomAttributes.Format ();
var sb = new StringBuilder ();
sb.AppendIndent (FormatAttributes (field));
sb.Append (' ');
sb.Append (FormatName (field.FieldType));
sb.Append (' ');
sb.Append (field.Name);
if (field.HasConstant) {
sb.Append (" = ");
sb.Append (Utils.FormatValue (field.Constant, field.FieldType));
}
sb.AppendLine (";");
return sb.ToString ();
}
public static string FormatAttributes (this FieldDefinition field)
{
if (field == null)
return String.Empty;
var attrs = new List <string> ();
if (field.IsPublic)
attrs.Add ("public");
else if (field.IsFamily)
attrs.Add ("protected");
else if (field.IsFamilyOrAssembly)
attrs.Add ("protected internal");
else if (field.IsAssembly)
attrs.Add ("internal");
if (field.IsStatic)
attrs.Add ("static");
if (field.IsInitOnly)
attrs.Add ("readonly");
if (field.IsLiteral)
attrs.Add ("const");
if (attrs.Count == 0)
return String.Empty;
return String.Join (" ", attrs.ToArray ()) + " ";
}
public static string FormatAttributes (this MethodDefinition method)
{
if (method == null || method.DeclaringType.IsInterface || method.IsExplicitImplementation ())
return String.Empty;
var attrs = new List <string> ();
if (method.IsPublic)
attrs.Add ("public");
else if (method.IsFamily)
attrs.Add ("protected");
else if (method.IsFamilyOrAssembly)
attrs.Add ("protected internal");
else if (method.IsAssembly)
attrs.Add ("internal");
if (method.IsFinal) {
if (!method.IsVirtual)
attrs.Add ("sealed");
} else {
if (method.IsStatic)
attrs.Add ("static");
if (method.IsAbstract)
attrs.Add ("abstract");
else if (method.IsVirtual) {
if (method.IsNewSlot)
attrs.Add ("virtual");
else
attrs.Add ("override");
} else if (method.IsNewSlot)
attrs.Add ("new");
}
if (attrs.Count == 0)
return String.Empty;
return String.Join (" ", attrs.ToArray ()) + " ";
}
public static string FormatAccessor (string name, MethodDefinition accessor, bool needsAttributes)
{
if (accessor == null || String.IsNullOrEmpty (name))
return String.Empty;
var sb = new StringBuilder ();
Utils.Indent++;
try {
sb.AppendLine ();
if (accessor.HasCustomAttributes)
sb.Append (accessor.CustomAttributes.Format ());
if (needsAttributes) {
sb.AppendIndent (FormatAttributes (accessor));
sb.Append (' ');
} else
sb.AppendIndent ();
sb.Append (name);
bool needNewline = false;
if (accessor.IsAbstract || accessor.DeclaringType.IsInterface || (needNewline = accessor.IsCompilerGenerated ())) {
sb.Append (";");
} else
sb.Append (" { throw new NotImplementedException (); }");
} finally {
Utils.Indent--;
}
return sb.ToString ();
}
public static string FormatName (this EventDefinition ev)
{
if (ev == null)
return String.Empty;
var sb = new StringBuilder ();
if (ev.HasCustomAttributes)
sb.Append (ev.CustomAttributes.Format ());
MethodDefinition adder = ev.AddMethod;
MethodDefinition remover = ev.RemoveMethod;
MethodDefinition accessor = null;
ushort adderAccessMask;
ushort removerAccessMask;
ushort evAccessMask;
GatherAccessorInfo (adder, remover, out accessor, out evAccessMask, out adderAccessMask, out removerAccessMask);
sb.AppendIndent (FormatAttributes (accessor));
sb.Append ("event ");
sb.Append (FormatName (ev.EventType));
sb.Append (' ');
sb.Append (ev.Name);
sb.Append (' ');
sb.Append ("{");
sb.Append (FormatAccessor ("add", adder, adderAccessMask != evAccessMask));
sb.Append (FormatAccessor ("remove", remover, removerAccessMask != evAccessMask));
sb.AppendLine ();
sb.AppendLineIndent ("}");
sb.AppendLine ();
return sb.ToString ();
}
public static string FormatName (this PropertyDefinition prop)
{
if (prop == null)
return String.Empty;
var sb = new StringBuilder ();
if (prop.HasCustomAttributes)
sb.Append (prop.CustomAttributes.Format ());
MethodDefinition getter = prop.GetMethod;
MethodDefinition setter = prop.SetMethod;
MethodDefinition accessor = null;
ushort getterAccessMask;
ushort setterAccessMask;
ushort propAccessMask;
GatherAccessorInfo (getter, setter, out accessor, out propAccessMask, out getterAccessMask, out setterAccessMask);
sb.AppendIndent (FormatAttributes (accessor));
sb.Append (FormatName (prop.PropertyType));
sb.Append (' ');
if (prop.HasParameters) {
sb.Append ("this [");
bool first = true;
foreach (ParameterDefinition p in prop.Parameters) {
if (!first)
sb.Append (", ");
else
first = false;
sb.Append (FormatName (p));
}
sb.Append ("]");
} else if (accessor.IsExplicitImplementation ()) {
TypeReference iface;
MethodReference ifaceMethod;
accessor.GetInfoForExplicitlyImplementedMethod (out iface, out ifaceMethod);
if (iface != null) {
sb.Append (iface.Name);
sb.Append ('.');
string name = prop.Name;
string iname = iface.FullName + ".";
if (name.StartsWith (iname, StringComparison.OrdinalIgnoreCase))
sb.Append (name.Substring (iname.Length));
else
sb.Append (name);
} else
sb.Append (prop.Name);
} else
sb.Append (prop.Name);
sb.Append (' ');
sb.Append ("{");
sb.Append (FormatAccessor ("get", getter, getterAccessMask != propAccessMask));
sb.Append (FormatAccessor ("set", setter, setterAccessMask != propAccessMask));
sb.AppendLine ();
sb.AppendLineIndent ("}");
sb.AppendLine ();
return sb.ToString ();
}
public static string FormatName (this MethodDefinition method)
{
if (method == null)
return String.Empty;
string name = method.Name;
var sb = new StringBuilder ();
if (method.HasCustomAttributes)
sb.Append (method.CustomAttributes.Format ());
sb.AppendIndent (FormatAttributes (method));
if (!method.IsSpecialName) {
sb.Append (FormatName (method.ReturnType));
sb.Append (' ');
} else if (method.IsAccessor ())
return String.Empty;
if (method.IsConstructor)
sb.Append (FormatGenericTypeName (method.DeclaringType.Name));
else if (name == "Finalize")
sb.Append ("~" + FormatGenericTypeName (method.DeclaringType.Name));
else if (method.IsSpecialName)
sb.Append (TranslateSpecialName (method));
else if (method.IsExplicitImplementation ()) {
TypeReference iface;
MethodReference ifaceMethod;
method.GetInfoForExplicitlyImplementedMethod (out iface, out ifaceMethod);
if (iface != null) {
sb.Append (FormatName (iface));
sb.Append ('.');
sb.Append (ifaceMethod.Name);
} else
sb.Append (method.Name);
} else
sb.Append (name);
bool first = true;
if (method.HasGenericParameters) {
sb.Append ('<');
foreach (GenericParameter gp in method.GenericParameters) {
if (!first)
sb.Append (", ");
else
first = false;
sb.Append (FormatName (gp));
}
sb.Append ("> ");
}
sb.Append (" (");
if (method.HasParameters) {
first = true;
foreach (ParameterDefinition p in method.Parameters) {
if (!first)
sb.Append (", ");
else
first = false;
sb.Append (FormatName (p));
}
}
sb.Append (")");
if (method.IsAbstract || method.DeclaringType.IsInterface)
sb.AppendLine (";");
else {
sb.AppendLine ();
sb.AppendLineIndent ("{");
try {
Utils.Indent++;
sb.AppendLineIndent ("throw new NotImplementedException ();");
} finally {
Utils.Indent--;
}
sb.AppendLineIndent ("}");
sb.AppendLine ();
}
return sb.ToString ();
}
public static string FormatName (this ParameterDefinition parameter)
{
if (parameter == null)
return String.Empty;
var sb = new StringBuilder ();
bool isParamArray = false;
if (parameter.HasCustomAttributes) {
if (parameter.CustomAttributes.First (attr => {
if (String.Compare (attr.AttributeType.FullName, "System.ParamArrayAttribute", StringComparison.Ordinal) == 0)
return true;
return false;
}) != null)
isParamArray = true;
if (isParamArray && parameter.CustomAttributes.Count > 1) {
sb.Append (FormatCustomAttributesOneLine (parameter.CustomAttributes));
sb.Append (' ');
}
}
if (isParamArray)
sb.Append ("params ");
sb.Append (FormatName (parameter.ParameterType));
sb.Append (' ');
sb.Append (parameter.Name);
return sb.ToString ();
}
public static string FormatGenericTypeName (this string name)
{
if (String.IsNullOrEmpty (name))
return String.Empty;
int idx = name.IndexOf ('`');
if (idx >= 0)
name = name.Substring (0, idx);
return name;
}
static void GatherAccessorInfo (MethodDefinition first, MethodDefinition second, out MethodDefinition moreVisible, out ushort moreVisibleAccessMask,
out ushort firstAccessMask, out ushort secondAccessMask)
{
moreVisible = first != null ? first : second;
if (first != null && second != null) {
if ((first.Attributes & MethodAttributes.MemberAccessMask) != (second.Attributes & MethodAttributes.MemberAccessMask)) {
if (first.IsPublic)
moreVisible = first;
else if (second.IsPublic)
moreVisible = second;
else if (first.IsFamilyOrAssembly)
moreVisible = first;
else if (second.IsFamilyOrAssembly)
moreVisible = second;
else if ((first.IsAssembly || first.IsFamily))
moreVisible = first;
else if ((second.IsAssembly || second.IsAssembly))
moreVisible = second;
}
}
moreVisibleAccessMask = (ushort) (moreVisible.Attributes & MethodAttributes.MemberAccessMask);
firstAccessMask = first != null ? (ushort) (first.Attributes & MethodAttributes.MemberAccessMask) : (ushort)0;
secondAccessMask = second != null ? (ushort) (second.Attributes & MethodAttributes.MemberAccessMask) : (ushort)0;
}
static string TranslateSpecialName (MethodDefinition method)
{
string name = method != null ? method.Name : String.Empty;
if (String.IsNullOrEmpty (name) || !name.StartsWith ("op_"))
return name;
string ret;
switch (name) {
case "op_Explicit":
case "op_Implicit":
return name.Substring (3).ToLower () + " operator " + FormatName (method.ReturnType);
case "op_UnaryPlus":
ret = "+";
break;
case "op_UnaryNegation":
ret = "-";
break;
case "op_LogicalNot":
ret = "!";
break;
case "op_OnesComplement":
ret = "~";
break;
case "op_Increment":
ret = "++";
break;
case "op_Decrement":
ret = "--";
break;
case "op_True":
ret = "true";
break;
case "op_False":
ret = "false";
break;
case "op_Addition":
ret = "+";
break;
case "op_Subtraction":
ret = "-";
break;
case "op_Multiply":
ret = "*";
break;
case "op_Division":
ret = "/";
break;
case "op_Modulus":
ret = "%";
break;
case "op_BitwiseAnd":
ret = "&";
break;
case "op_BitwiseOr":
ret = "|";
break;
case "op_ExclusiveOr":
ret = "^";
break;
case "op_LeftShift":
ret = "<<";
break;
case "op_RightShift":
ret = ">>";
break;
case "op_Equality":
ret = "==";
break;
case "op_Inequality":
ret = "!=";
break;
case "op_GreaterThan":
ret = ">";
break;
case "op_LessThan":
ret = "<";
break;
case "op_GreaterThanOrEqual":
ret = ">=";
break;
case "op_LessThanOrEqual":
ret = "<=";
break;
default:
ret = name;
break;
}
return FormatName (method.ReturnType) + " operator " + ret;
}
}
}