Merge pull request #900 from Blewzman/FixAggregateExceptionGetBaseException
[mono.git] / mcs / tools / corcompare / mono-api-info.cs
1 //
2 // mono-api-info.cs - Dumps public assembly information to an xml file.
3 //
4 // Authors:
5 //      Gonzalo Paniagua Javier (gonzalo@ximian.com)
6 //
7 // Copyright (C) 2003-2008 Novell, Inc (http://www.novell.com)
8 //
9
10 using System;
11 using System.Collections;
12 using System.Collections.Generic;
13 using System.Globalization;
14 using System.Linq;
15 using System.Runtime.CompilerServices;
16 using System.Runtime.InteropServices;
17 using System.Security.Permissions;
18 using System.Text;
19 using System.Xml;
20
21 using Mono.Cecil;
22 using Mono.Cecil.Cil;
23 using System.IO;
24
25 namespace CorCompare
26 {
27         public class Driver
28         {
29                 public static int Main (string [] args)
30                 {
31                         if (args.Length == 0)
32                                 return 1;
33
34                         AbiMode = false;
35
36                         AssemblyCollection acoll = new AssemblyCollection ();
37
38                         string windir = Environment.GetFolderPath(Environment.SpecialFolder.Windows);
39                         string pf = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
40                         TypeHelper.Resolver.AddSearchDirectory (Path.Combine (windir, @"assembly\GAC\MSDATASRC\7.0.3300.0__b03f5f7f11d50a3a"));
41
42                         foreach (string arg in args) {
43                                 if (arg == "--abi") {
44                                         AbiMode = true;
45                                 } else {
46                                         acoll.Add (arg);
47
48                                         if (arg.Contains ("v3.0")) {
49                                                 TypeHelper.Resolver.AddSearchDirectory (Path.Combine (windir, @"Microsoft.NET\Framework\v2.0.50727"));
50                                         } else if (arg.Contains ("v3.5")) {
51                                                 TypeHelper.Resolver.AddSearchDirectory (Path.Combine (windir, @"Microsoft.NET\Framework\v2.0.50727"));
52                                                 TypeHelper.Resolver.AddSearchDirectory (Path.Combine (windir, @"Microsoft.NET\Framework\v3.0\Windows Communication Foundation"));
53                                         } else if (arg.Contains ("v4.0")) {
54                                                 if (arg.Contains ("Silverlight")) {
55                                                         TypeHelper.Resolver.AddSearchDirectory (Path.Combine (pf, @"Microsoft Silverlight\4.0.51204.0"));
56                                                 } else {
57                                                         TypeHelper.Resolver.AddSearchDirectory (Path.Combine (windir, @"Microsoft.NET\Framework\v4.0.30319"));
58                                                         TypeHelper.Resolver.AddSearchDirectory (Path.Combine (windir, @"Microsoft.NET\Framework\v4.0.30319\WPF"));
59                                                 }
60                                         } else {
61                                                 TypeHelper.Resolver.AddSearchDirectory (Path.GetDirectoryName (arg));
62                                         }
63                                 }
64                         }
65
66                         XmlDocument doc = new XmlDocument ();
67                         acoll.Document = doc;
68                         acoll.DoOutput ();
69
70                         var writer = new WellFormedXmlWriter (new XmlTextWriter (Console.Out) { Formatting = Formatting.Indented });
71                         XmlNode decl = doc.CreateXmlDeclaration ("1.0", "utf-8", null);
72                         doc.InsertBefore (decl, doc.DocumentElement);
73                         doc.WriteTo (writer);
74                         return 0;
75                 }
76
77                 internal static bool AbiMode { get; private set; }
78         }
79
80         public class Utils {
81
82                 public static string CleanupTypeName (TypeReference type)
83                 {
84                         return CleanupTypeName (type.FullName);
85                 }
86
87                 public static string CleanupTypeName (string t)
88                 {
89                         return t.Replace ('<', '[').Replace ('>', ']').Replace ('/', '+');
90                 }
91         }
92
93         class AssemblyCollection
94         {
95                 XmlDocument document;
96                 List<AssemblyDefinition> assemblies = new List<AssemblyDefinition> ();
97
98                 public AssemblyCollection ()
99                 {
100                 }
101
102                 public bool Add (string name)
103                 {
104                         AssemblyDefinition ass = LoadAssembly (name);
105                         if (ass == null) {
106                                 Console.Error.WriteLine ("Cannot load assembly file " + name);
107                                 return false;
108                         }
109
110                         assemblies.Add (ass);
111                         return true;
112                 }
113
114                 public void DoOutput ()
115                 {
116                         if (document == null)
117                                 throw new InvalidOperationException ("Document not set");
118
119                         XmlNode nassemblies = document.CreateElement ("assemblies", null);
120                         document.AppendChild (nassemblies);
121                         foreach (AssemblyDefinition a in assemblies) {
122                                 AssemblyData data = new AssemblyData (document, nassemblies, a);
123                                 data.DoOutput ();
124                         }
125                 }
126
127                 public XmlDocument Document {
128                         set { document = value; }
129                 }
130
131                 AssemblyDefinition LoadAssembly (string assembly)
132                 {
133                         try {
134                                 if (File.Exists (assembly))
135                                         return TypeHelper.Resolver.ResolveFile (assembly);
136
137                                 return TypeHelper.Resolver.Resolve (assembly);
138                         } catch (Exception e) {
139                                 Console.WriteLine (e);
140                                 return null;
141                         }
142                 }
143         }
144
145         abstract class BaseData
146         {
147                 protected XmlDocument document;
148                 protected XmlNode parent;
149
150                 protected BaseData (XmlDocument doc, XmlNode parent)
151                 {
152                         this.document = doc;
153                         this.parent = parent;
154                 }
155
156                 public abstract void DoOutput ();
157
158                 protected void AddAttribute (XmlNode node, string name, string value)
159                 {
160                         XmlAttribute attr = document.CreateAttribute (name);
161                         attr.Value = value;
162                         node.Attributes.Append (attr);
163                 }
164         }
165
166         class TypeForwardedToData : BaseData
167         {
168                 AssemblyDefinition ass;
169
170                 public TypeForwardedToData (XmlDocument document, XmlNode parent, AssemblyDefinition ass)
171                         : base (document, parent)
172                 {
173                         this.ass = ass;
174                 }
175
176                 public override void DoOutput ()
177                 {
178                         XmlNode natts = parent.SelectSingleNode("attributes");
179                         if (natts == null) {
180                                 natts = document.CreateElement ("attributes", null);
181                                 parent.AppendChild (natts);
182                         }
183
184                         foreach (ExportedType type in ass.MainModule.ExportedTypes) {
185
186                                 if (((uint)type.Attributes & 0x200000u) == 0)
187                                         continue;
188
189                                 XmlNode node = document.CreateElement ("attribute");
190                                 AddAttribute (node, "name", typeof (TypeForwardedToAttribute).FullName);
191                                 XmlNode properties = node.AppendChild (document.CreateElement ("properties"));
192                                 XmlNode property = properties.AppendChild (document.CreateElement ("property"));
193                                 AddAttribute (property, "name", "Destination");
194                                 AddAttribute (property, "value", Utils.CleanupTypeName (type.FullName));
195                                 natts.AppendChild (node);
196                         }
197                 }
198
199                 public static void OutputForwarders (XmlDocument document, XmlNode parent, AssemblyDefinition ass)
200                 {
201                         TypeForwardedToData tftd = new TypeForwardedToData (document, parent, ass);
202                         tftd.DoOutput ();
203                 }
204         }
205
206         class AssemblyData : BaseData
207         {
208                 AssemblyDefinition ass;
209
210                 public AssemblyData (XmlDocument document, XmlNode parent, AssemblyDefinition ass)
211                         : base (document, parent)
212                 {
213                         this.ass = ass;
214                 }
215
216                 public override void DoOutput ()
217                 {
218                         if (document == null)
219                                 throw new InvalidOperationException ("Document not set");
220
221                         XmlNode nassembly = document.CreateElement ("assembly", null);
222                         AssemblyNameDefinition aname = ass.Name;
223                         AddAttribute (nassembly, "name", aname.Name);
224                         AddAttribute (nassembly, "version", aname.Version.ToString ());
225                         parent.AppendChild (nassembly);
226                         TypeForwardedToData.OutputForwarders (document, nassembly, ass);
227                         AttributeData.OutputAttributes (document, nassembly, ass.CustomAttributes);
228                         var typesCollection = ass.MainModule.Types;
229                         if (typesCollection == null || typesCollection.Count == 0)
230                                 return;
231                         object [] typesArray = new object [typesCollection.Count];
232                         for (int i = 0; i < typesCollection.Count; i++) {
233                                 typesArray [i] = typesCollection [i];
234                         }
235                         Array.Sort (typesArray, TypeReferenceComparer.Default);
236
237                         XmlNode nss = document.CreateElement ("namespaces", null);
238                         nassembly.AppendChild (nss);
239
240                         string current_namespace = "$%&$&";
241                         XmlNode ns = null;
242                         XmlNode classes = null;
243                         foreach (TypeDefinition t in typesArray) {
244                                 if (string.IsNullOrEmpty (t.Namespace))
245                                         continue;
246
247                                 if (!Driver.AbiMode && ((t.Attributes & TypeAttributes.VisibilityMask) != TypeAttributes.Public))
248                                         continue;
249
250                                 if (t.DeclaringType != null)
251                                         continue; // enforce !nested
252
253                                 if (t.Namespace != current_namespace) {
254                                         current_namespace = t.Namespace;
255                                         ns = document.CreateElement ("namespace", null);
256                                         AddAttribute (ns, "name", current_namespace);
257                                         nss.AppendChild (ns);
258                                         classes = document.CreateElement ("classes", null);
259                                         ns.AppendChild (classes);
260                                 }
261
262                                 TypeData bd = new TypeData (document, classes, t);
263                                 bd.DoOutput ();
264                         }
265                 }
266         }
267
268         abstract class MemberData : BaseData
269         {
270                 MemberReference [] members;
271
272                 public MemberData (XmlDocument document, XmlNode parent, MemberReference [] members)
273                         : base (document, parent)
274                 {
275                         this.members = members;
276                 }
277
278                 public override void DoOutput ()
279                 {
280                         XmlNode mclass = document.CreateElement (ParentTag, null);
281                         parent.AppendChild (mclass);
282
283                         foreach (MemberReference member in members) {
284                                 XmlNode mnode = document.CreateElement (Tag, null);
285                                 mclass.AppendChild (mnode);
286                                 AddAttribute (mnode, "name", GetName (member));
287                                 if (!NoMemberAttributes)
288                                         AddAttribute (mnode, "attrib", GetMemberAttributes (member));
289
290                                 AttributeData.OutputAttributes (document, mnode, GetCustomAttributes (member));
291
292                                 AddExtraData (mnode, member);
293                         }
294                 }
295
296
297                 protected abstract IList<CustomAttribute> GetCustomAttributes (MemberReference member);
298
299                 protected virtual void AddExtraData (XmlNode p, MemberReference memberDefenition)
300                 {
301                 }
302
303                 protected virtual string GetName (MemberReference memberDefenition)
304                 {
305                         return "NoNAME";
306                 }
307
308                 protected virtual string GetMemberAttributes (MemberReference memberDefenition)
309                 {
310                         return null;
311                 }
312
313                 public virtual bool NoMemberAttributes {
314                         get { return false; }
315                         set {}
316                 }
317
318                 public virtual string ParentTag {
319                         get { return "NoPARENTTAG"; }
320                 }
321
322                 public virtual string Tag {
323                         get { return "NoTAG"; }
324                 }
325
326                 public static void OutputGenericParameters (XmlDocument document, XmlNode nclass, IGenericParameterProvider provider)
327                 {
328                         if (provider.GenericParameters.Count == 0)
329                                 return;
330
331                         var gparameters = provider.GenericParameters;
332
333                         XmlElement ngeneric = document.CreateElement (string.Format ("generic-parameters"));
334                         nclass.AppendChild (ngeneric);
335
336                         foreach (GenericParameter gp in gparameters) {
337                                 XmlElement nparam = document.CreateElement (string.Format ("generic-parameter"));
338                                 nparam.SetAttribute ("name", gp.Name);
339                                 nparam.SetAttribute ("attributes", ((int) gp.Attributes).ToString ());
340
341                                 AttributeData.OutputAttributes (document, nparam, gp.CustomAttributes);
342
343                                 ngeneric.AppendChild (nparam);
344
345                                 var constraints = gp.Constraints;
346                                 if (constraints.Count == 0)
347                                         continue;
348
349                                 XmlElement nconstraint = document.CreateElement ("generic-parameter-constraints");
350
351                                 foreach (TypeReference constraint in constraints) {
352                                         XmlElement ncons = document.CreateElement ("generic-parameter-constraint");
353                                         ncons.SetAttribute ("name", Utils.CleanupTypeName (constraint));
354                                         nconstraint.AppendChild (ncons);
355                                 }
356
357                                 nparam.AppendChild (nconstraint);
358                         }
359                 }
360         }
361
362         class TypeData : MemberData
363         {
364                 TypeDefinition type;
365
366                 public TypeData (XmlDocument document, XmlNode parent, TypeDefinition type)
367                         : base (document, parent, null)
368                 {
369                         this.type = type;
370                 }
371
372                 protected override IList<CustomAttribute> GetCustomAttributes (MemberReference member) {
373                         return ((TypeDefinition) member).CustomAttributes;
374                 }
375
376                 public override void DoOutput ()
377                 {
378                         if (document == null)
379                                 throw new InvalidOperationException ("Document not set");
380
381                         XmlNode nclass = document.CreateElement ("class", null);
382                         AddAttribute (nclass, "name", type.Name);
383                         string classType = GetClassType (type);
384                         AddAttribute (nclass, "type", classType);
385
386                         if (type.BaseType != null)
387                                 AddAttribute (nclass, "base", Utils.CleanupTypeName (type.BaseType));
388
389                         if (type.IsSealed)
390                                 AddAttribute (nclass, "sealed", "true");
391
392                         if (type.IsAbstract)
393                                 AddAttribute (nclass, "abstract", "true");
394
395                         if ( (type.Attributes & TypeAttributes.Serializable) != 0 || type.IsEnum)
396                                 AddAttribute (nclass, "serializable", "true");
397
398                         string charSet = GetCharSet (type);
399                         AddAttribute (nclass, "charset", charSet);
400
401                         string layout = GetLayout (type);
402                         if (layout != null)
403                                 AddAttribute (nclass, "layout", layout);
404
405                         if (type.PackingSize >= 0) {
406                                 AddAttribute (nclass, "pack", type.PackingSize.ToString ());
407                         }
408
409                         if (type.ClassSize >= 0) {
410                                 AddAttribute (nclass, "size", type.ClassSize.ToString ());
411                         }
412
413                         parent.AppendChild (nclass);
414
415                         AttributeData.OutputAttributes (document, nclass, GetCustomAttributes(type));
416
417                         XmlNode ifaces = null;
418
419                         foreach (TypeReference iface in  TypeHelper.GetInterfaces (type)) {
420                                 if (!TypeHelper.IsPublic (iface))
421                                         // we're only interested in public interfaces
422                                         continue;
423
424                                 if (ifaces == null) {
425                                         ifaces = document.CreateElement ("interfaces", null);
426                                         nclass.AppendChild (ifaces);
427                                 }
428
429                                 XmlNode iface_node = document.CreateElement ("interface", null);
430                                 AddAttribute (iface_node, "name", Utils.CleanupTypeName (iface));
431                                 ifaces.AppendChild (iface_node);
432                         }
433
434                         MemberData.OutputGenericParameters (document, nclass, type);
435
436                         ArrayList members = new ArrayList ();
437
438                         FieldDefinition [] fields = GetFields (type);
439                         if (fields.Length > 0) {
440                                 Array.Sort (fields, MemberReferenceComparer.Default);
441                                 FieldData fd = new FieldData (document, nclass, fields);
442                                 members.Add (fd);
443                         }
444
445                         if (type.IsEnum) {
446                                 var value_type = GetEnumValueField (type);
447                                 if (value_type == null)
448                                         throw new NotSupportedException ();
449
450                                 AddAttribute (nclass, "enumtype", Utils.CleanupTypeName (value_type.FieldType));
451                         }
452
453                         if (!Driver.AbiMode) {
454
455                                 MethodDefinition [] ctors = GetConstructors (type);
456                                 if (ctors.Length > 0) {
457                                         Array.Sort (ctors, MemberReferenceComparer.Default);
458                                         members.Add (new ConstructorData (document, nclass, ctors));
459                                 }
460
461                                 PropertyDefinition[] properties = GetProperties (type);
462                                 if (properties.Length > 0) {
463                                         Array.Sort (properties, MemberReferenceComparer.Default);
464                                         members.Add (new PropertyData (document, nclass, properties));
465                                 }
466
467                                 EventDefinition [] events = GetEvents (type);
468                                 if (events.Length > 0) {
469                                         Array.Sort (events, MemberReferenceComparer.Default);
470                                         members.Add (new EventData (document, nclass, events));
471                                 }
472
473                                 MethodDefinition [] methods = GetMethods (type);
474                                 if (methods.Length > 0) {
475                                         Array.Sort (methods, MemberReferenceComparer.Default);
476                                         members.Add (new MethodData (document, nclass, methods));
477                                 }
478                         }
479
480                         foreach (MemberData md in members)
481                                 md.DoOutput ();
482
483                         var nested = type.NestedTypes;
484                         //remove non public(familiy) and nested in second degree
485                         for (int i = nested.Count - 1; i >= 0; i--) {
486                                 TypeDefinition t = nested [i];
487                                 if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPublic ||
488                                         (t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedFamily ||
489                                         (t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedFamORAssem) {
490                                         // public
491                                         if (t.DeclaringType == type)
492                                                 continue; // not nested of nested
493                                 }
494
495                                 nested.RemoveAt (i);
496                         }
497
498
499                         if (nested.Count > 0) {
500                                 XmlNode classes = document.CreateElement ("classes", null);
501                                 nclass.AppendChild (classes);
502                                 foreach (TypeDefinition t in nested) {
503                                         TypeData td = new TypeData (document, classes, t);
504                                         td.DoOutput ();
505                                 }
506                         }
507                 }
508
509                 static FieldReference GetEnumValueField (TypeDefinition type)
510                 {
511                         foreach (FieldDefinition field in type.Fields)
512                                 if (field.IsSpecialName && field.Name == "value__")
513                                         return field;
514
515                         return null;
516                 }
517
518                 protected override string GetMemberAttributes (MemberReference member)
519                 {
520                         if (member != type)
521                                 throw new InvalidOperationException ("odd");
522
523                         return ((int) type.Attributes).ToString (CultureInfo.InvariantCulture);
524                 }
525
526                 public static bool MustDocumentMethod (MethodDefinition method) {
527                         // All other methods
528                         MethodAttributes maskedAccess = method.Attributes & MethodAttributes.MemberAccessMask;
529                         return maskedAccess == MethodAttributes.Public
530                                 || maskedAccess == MethodAttributes.Family
531                                 || maskedAccess == MethodAttributes.FamORAssem;
532                 }
533
534                 static string GetClassType (TypeDefinition t)
535                 {
536                         if (t.IsEnum)
537                                 return "enum";
538
539                         if (t.IsValueType)
540                                 return "struct";
541
542                         if (t.IsInterface)
543                                 return "interface";
544
545                         if (TypeHelper.IsDelegate(t))
546                                 return "delegate";
547
548                         return "class";
549                 }
550
551                 static string GetCharSet (TypeDefinition type)
552                 {
553                         TypeAttributes maskedStringFormat = type.Attributes & TypeAttributes.StringFormatMask;
554                         if (maskedStringFormat == TypeAttributes.AnsiClass)
555                                 return CharSet.Ansi.ToString ();
556
557                         if (maskedStringFormat == TypeAttributes.AutoClass)
558                                 return CharSet.Auto.ToString ();
559
560                         if (maskedStringFormat == TypeAttributes.UnicodeClass)
561                                 return CharSet.Unicode.ToString ();
562
563                         return CharSet.None.ToString ();
564                 }
565
566                 static string GetLayout (TypeDefinition type)
567                 {
568                         TypeAttributes maskedLayout = type.Attributes & TypeAttributes.LayoutMask;
569                         if (maskedLayout == TypeAttributes.AutoLayout)
570                                 return LayoutKind.Auto.ToString ();
571
572                         if (maskedLayout == TypeAttributes.ExplicitLayout)
573                                 return LayoutKind.Explicit.ToString ();
574
575                         if (maskedLayout == TypeAttributes.SequentialLayout)
576                                 return LayoutKind.Sequential.ToString ();
577
578                         return null;
579                 }
580
581                 FieldDefinition [] GetFields (TypeDefinition type) {
582                         ArrayList list = new ArrayList ();
583
584                         var fields = type.Fields;
585                         foreach (FieldDefinition field in fields) {
586                                 if (field.IsSpecialName)
587                                         continue;
588
589                                 if (Driver.AbiMode && field.IsStatic)
590                                         continue;
591
592                                 // we're only interested in public or protected members
593                                 FieldAttributes maskedVisibility = (field.Attributes & FieldAttributes.FieldAccessMask);
594                                 if (Driver.AbiMode && !field.IsNotSerialized) {
595                                         list.Add (field);
596                                 } else {
597                                         if (maskedVisibility == FieldAttributes.Public
598                                                 || maskedVisibility == FieldAttributes.Family
599                                                 || maskedVisibility == FieldAttributes.FamORAssem) {
600                                                 list.Add (field);
601                                         }
602                                 }
603                         }
604
605                         return (FieldDefinition []) list.ToArray (typeof (FieldDefinition));
606                 }
607
608
609                 internal static PropertyDefinition [] GetProperties (TypeDefinition type) {
610                         ArrayList list = new ArrayList ();
611
612                         var properties = type.Properties;//type.GetProperties (flags);
613                         foreach (PropertyDefinition property in properties) {
614                                 MethodDefinition getMethod = property.GetMethod;
615                                 MethodDefinition setMethod = property.SetMethod;
616
617                                 bool hasGetter = (getMethod != null) && MustDocumentMethod (getMethod);
618                                 bool hasSetter = (setMethod != null) && MustDocumentMethod (setMethod);
619
620                                 // if neither the getter or setter should be documented, then
621                                 // skip the property
622                                 if (hasGetter || hasSetter) {
623                                         list.Add (property);
624                                 }
625                         }
626
627                         return (PropertyDefinition []) list.ToArray (typeof (PropertyDefinition));
628                 }
629
630                 private MethodDefinition[] GetMethods (TypeDefinition type)
631                 {
632                         ArrayList list = new ArrayList ();
633
634                         var methods = type.Methods;//type.GetMethods (flags);
635                         foreach (MethodDefinition method in methods) {
636                                 if (method.IsSpecialName && !method.Name.StartsWith ("op_"))
637                                         continue;
638
639                                 // we're only interested in public or protected members
640                                 if (!MustDocumentMethod(method))
641                                         continue;
642
643                                 if (IsFinalizer (method)) {
644                                         string name = method.DeclaringType.Name;
645                                         int arity = name.IndexOf ('`');
646                                         if (arity > 0)
647                                                 name = name.Substring (0, arity);
648
649                                         method.Name = "~" + name;
650                                 }
651
652                                 list.Add (method);
653                         }
654
655                         return (MethodDefinition []) list.ToArray (typeof (MethodDefinition));
656                 }
657
658                 static bool IsFinalizer (MethodDefinition method)
659                 {
660                         if (method.Name != "Finalize")
661                                 return false;
662
663                         if (!method.IsVirtual)
664                                 return false;
665
666                         if (method.Parameters.Count != 0)
667                                 return false;
668
669                         return true;
670                 }
671
672                 private MethodDefinition [] GetConstructors (TypeDefinition type)
673                 {
674                         ArrayList list = new ArrayList ();
675
676                         var ctors = type.Methods.Where (m => m.IsConstructor);//type.GetConstructors (flags);
677                         foreach (MethodDefinition constructor in ctors) {
678                                 // we're only interested in public or protected members
679                                 if (!MustDocumentMethod(constructor))
680                                         continue;
681
682                                 list.Add (constructor);
683                         }
684
685                         return (MethodDefinition []) list.ToArray (typeof (MethodDefinition));
686                 }
687
688                 private EventDefinition[] GetEvents (TypeDefinition type)
689                 {
690                         ArrayList list = new ArrayList ();
691
692                         var events = type.Events;//type.GetEvents (flags);
693                         foreach (EventDefinition eventDef in events) {
694                                 MethodDefinition addMethod = eventDef.AddMethod;//eventInfo.GetAddMethod (true);
695
696                                 if (addMethod == null || !MustDocumentMethod (addMethod))
697                                         continue;
698
699                                 list.Add (eventDef);
700                         }
701
702                         return (EventDefinition []) list.ToArray (typeof (EventDefinition));
703                 }
704         }
705
706         class FieldData : MemberData
707         {
708                 public FieldData (XmlDocument document, XmlNode parent, FieldDefinition [] members)
709                         : base (document, parent, members)
710                 {
711                 }
712
713                 protected override IList<CustomAttribute> GetCustomAttributes (MemberReference member) {
714                         return ((FieldDefinition) member).CustomAttributes;
715                 }
716
717                 protected override string GetName (MemberReference memberDefenition)
718                 {
719                         FieldDefinition field = (FieldDefinition) memberDefenition;
720                         return field.Name;
721                 }
722
723                 protected override string GetMemberAttributes (MemberReference memberDefenition)
724                 {
725                         FieldDefinition field = (FieldDefinition) memberDefenition;
726                         return ((int) field.Attributes).ToString (CultureInfo.InvariantCulture);
727                 }
728
729                 protected override void AddExtraData (XmlNode p, MemberReference memberDefenition)
730                 {
731                         base.AddExtraData (p, memberDefenition);
732                         FieldDefinition field = (FieldDefinition) memberDefenition;
733                         AddAttribute (p, "fieldtype", Utils.CleanupTypeName (field.FieldType));
734
735                         if (field.IsLiteral) {
736                                 object value = field.Constant;//object value = field.GetValue (null);
737                                 string stringValue = null;
738                                 //if (value is Enum) {
739                                 //    // FIXME: when Mono bug #60090 has been
740                                 //    // fixed, we should just be able to use
741                                 //    // Convert.ToString
742                                 //    stringValue = ((Enum) value).ToString ("D", CultureInfo.InvariantCulture);
743                                 //}
744                                 //else {
745                                         stringValue = Convert.ToString (value, CultureInfo.InvariantCulture);
746                                 //}
747
748                                 if (stringValue != null)
749                                         AddAttribute (p, "value", stringValue);
750                         }
751                 }
752
753                 public override string ParentTag {
754                         get { return "fields"; }
755                 }
756
757                 public override string Tag {
758                         get { return "field"; }
759                 }
760         }
761
762         class PropertyData : MemberData
763         {
764                 public PropertyData (XmlDocument document, XmlNode parent, PropertyDefinition [] members)
765                         : base (document, parent, members)
766                 {
767                 }
768
769                 protected override IList<CustomAttribute> GetCustomAttributes (MemberReference member) {
770                         return ((PropertyDefinition) member).CustomAttributes;
771                 }
772
773                 protected override string GetName (MemberReference memberDefenition)
774                 {
775                         PropertyDefinition prop = (PropertyDefinition) memberDefenition;
776                         return prop.Name;
777                 }
778
779                 protected override void AddExtraData (XmlNode p, MemberReference memberDefenition)
780                 {
781                         base.AddExtraData (p, memberDefenition);
782                         PropertyDefinition prop = (PropertyDefinition) memberDefenition;
783                         AddAttribute (p, "ptype", Utils.CleanupTypeName (prop.PropertyType));
784                         MethodDefinition _get = prop.GetMethod;
785                         MethodDefinition _set = prop.SetMethod;
786                         bool haveGet = (_get != null && TypeData.MustDocumentMethod(_get));
787                         bool haveSet = (_set != null && TypeData.MustDocumentMethod(_set));
788                         MethodDefinition [] methods;
789
790                         if (haveGet && haveSet) {
791                                 methods = new MethodDefinition [] { _get, _set };
792                         } else if (haveGet) {
793                                 methods = new MethodDefinition [] { _get };
794                         } else if (haveSet) {
795                                 methods = new MethodDefinition [] { _set };
796                         } else {
797                                 //odd
798                                 return;
799                         }
800
801                         if (haveGet || _set.Parameters.Count > 1) {
802                                 string parms = Parameters.GetSignature (methods [0].Parameters);
803                                 if (!string.IsNullOrEmpty (parms))
804                                         AddAttribute (p, "params", parms);
805                         }
806
807                         MethodData data = new MethodData (document, p, methods);
808                         //data.NoMemberAttributes = true;
809                         data.DoOutput ();
810                 }
811
812                 protected override string GetMemberAttributes (MemberReference memberDefenition)
813                 {
814                         PropertyDefinition prop = (PropertyDefinition) memberDefenition;
815                         return ((int) prop.Attributes).ToString (CultureInfo.InvariantCulture);
816                 }
817
818                 public override string ParentTag {
819                         get { return "properties"; }
820                 }
821
822                 public override string Tag {
823                         get { return "property"; }
824                 }
825         }
826
827         class EventData : MemberData
828         {
829                 public EventData (XmlDocument document, XmlNode parent, EventDefinition [] members)
830                         : base (document, parent, members)
831                 {
832                 }
833
834                 protected override IList<CustomAttribute> GetCustomAttributes (MemberReference member) {
835                         return ((EventDefinition) member).CustomAttributes;
836                 }
837
838                 protected override string GetName (MemberReference memberDefenition)
839                 {
840                         EventDefinition evt = (EventDefinition) memberDefenition;
841                         return evt.Name;
842                 }
843
844                 protected override string GetMemberAttributes (MemberReference memberDefenition)
845                 {
846                         EventDefinition evt = (EventDefinition) memberDefenition;
847                         return ((int) evt.Attributes).ToString (CultureInfo.InvariantCulture);
848                 }
849
850                 protected override void AddExtraData (XmlNode p, MemberReference memberDefenition)
851                 {
852                         base.AddExtraData (p, memberDefenition);
853                         EventDefinition evt = (EventDefinition) memberDefenition;
854                         AddAttribute (p, "eventtype", Utils.CleanupTypeName (evt.EventType));
855                 }
856
857                 public override string ParentTag {
858                         get { return "events"; }
859                 }
860
861                 public override string Tag {
862                         get { return "event"; }
863                 }
864         }
865
866         class MethodData : MemberData
867         {
868                 bool noAtts;
869
870                 public MethodData (XmlDocument document, XmlNode parent, MethodDefinition [] members)
871                         : base (document, parent, members)
872                 {
873                 }
874
875                 protected override IList<CustomAttribute> GetCustomAttributes (MemberReference member) {
876                         return ((MethodDefinition) member).CustomAttributes;
877                 }
878
879                 protected override string GetName (MemberReference memberDefenition)
880                 {
881                         MethodDefinition method = (MethodDefinition) memberDefenition;
882                         string name = method.Name;
883                         string parms = Parameters.GetSignature (method.Parameters);
884
885                         return string.Format ("{0}({1})", name, parms);
886                 }
887
888                 protected override string GetMemberAttributes (MemberReference memberDefenition)
889                 {
890                         MethodDefinition method = (MethodDefinition) memberDefenition;
891                         return ((int)( method.Attributes)).ToString (CultureInfo.InvariantCulture);
892                 }
893
894                 protected override void AddExtraData (XmlNode p, MemberReference memberDefenition)
895                 {
896                         base.AddExtraData (p, memberDefenition);
897
898                         if (!(memberDefenition is MethodDefinition))
899                                 return;
900
901                         MethodDefinition mbase = (MethodDefinition) memberDefenition;
902
903                         ParameterData parms = new ParameterData (document, p, mbase.Parameters);
904                         parms.DoOutput ();
905
906                         if (mbase.IsAbstract)
907                                 AddAttribute (p, "abstract", "true");
908                         if (mbase.IsVirtual)
909                                 AddAttribute (p, "virtual", "true");
910                         if (mbase.IsStatic)
911                                 AddAttribute (p, "static", "true");
912
913                         string rettype = Utils.CleanupTypeName (mbase.MethodReturnType.ReturnType);
914                         if (rettype != "System.Void" || !mbase.IsConstructor)
915                                 AddAttribute (p, "returntype", (rettype));
916
917                         AttributeData.OutputAttributes (document, p, mbase.MethodReturnType.CustomAttributes);
918
919                         MemberData.OutputGenericParameters (document, p, mbase);
920                 }
921
922                 public override bool NoMemberAttributes {
923                         get { return noAtts; }
924                         set { noAtts = value; }
925                 }
926
927                 public override string ParentTag {
928                         get { return "methods"; }
929                 }
930
931                 public override string Tag {
932                         get { return "method"; }
933                 }
934         }
935
936         class ConstructorData : MethodData
937         {
938                 public ConstructorData (XmlDocument document, XmlNode parent, MethodDefinition [] members)
939                         : base (document, parent, members)
940                 {
941                 }
942
943                 public override string ParentTag {
944                         get { return "constructors"; }
945                 }
946
947                 public override string Tag {
948                         get { return "constructor"; }
949                 }
950         }
951
952         class ParameterData : BaseData
953         {
954                 private IList<ParameterDefinition> parameters;
955
956                 public ParameterData (XmlDocument document, XmlNode parent, IList<ParameterDefinition> parameters)
957                         : base (document, parent)
958                 {
959                         this.parameters = parameters;
960                 }
961
962                 public override void DoOutput ()
963                 {
964                         XmlNode parametersNode = document.CreateElement ("parameters");
965                         parent.AppendChild (parametersNode);
966
967                         foreach (ParameterDefinition parameter in parameters) {
968                                 XmlNode paramNode = document.CreateElement ("parameter");
969                                 parametersNode.AppendChild (paramNode);
970                                 AddAttribute (paramNode, "name", parameter.Name);
971                                 AddAttribute (paramNode, "position", parameter.Method.Parameters.IndexOf(parameter).ToString(CultureInfo.InvariantCulture));
972                                 AddAttribute (paramNode, "attrib", ((int) parameter.Attributes).ToString());
973
974                                 string direction = "in";
975
976                                 if (parameter.ParameterType is ByReferenceType)
977                                         direction = parameter.IsOut ? "out" : "ref";
978
979                                 TypeReference t = parameter.ParameterType;
980                                 AddAttribute (paramNode, "type", Utils.CleanupTypeName (t));
981
982                                 if (parameter.IsOptional) {
983                                         AddAttribute (paramNode, "optional", "true");
984                                         if (parameter.HasConstant)
985                                                 AddAttribute (paramNode, "defaultValue", parameter.Constant == null ? "NULL" : parameter.Constant.ToString ());
986                                 }
987
988                                 if (direction != "in")
989                                         AddAttribute (paramNode, "direction", direction);
990
991                                 AttributeData.OutputAttributes (document, paramNode, parameter.CustomAttributes);
992                         }
993                 }
994         }
995
996         class AttributeData : BaseData
997         {
998                 IList<CustomAttribute> atts;
999
1000                 AttributeData (XmlDocument doc, XmlNode parent, IList<CustomAttribute> attributes)
1001                         : base (doc, parent)
1002                 {
1003                         atts = attributes;
1004                 }
1005
1006                 public override void DoOutput ()
1007                 {
1008                         if (document == null)
1009                                 throw new InvalidOperationException ("Document not set");
1010
1011                         if (atts == null || atts.Count == 0)
1012                                 return;
1013
1014                         XmlNode natts = parent.SelectSingleNode("attributes");
1015                         if (natts == null) {
1016                                 natts = document.CreateElement ("attributes", null);
1017                                 parent.AppendChild (natts);
1018                         }
1019
1020                         for (int i = 0; i < atts.Count; ++i) {
1021                                 CustomAttribute att = atts [i];
1022
1023                                 string attName = Utils.CleanupTypeName (att.Constructor.DeclaringType);
1024                                 if (SkipAttribute (att))
1025                                         continue;
1026
1027                                 XmlNode node = document.CreateElement ("attribute");
1028                                 AddAttribute (node, "name", attName);
1029
1030                                 XmlNode properties = null;
1031
1032                                 Dictionary<string, object> attribute_mapping = CreateAttributeMapping (att);
1033
1034                                 foreach (string name in attribute_mapping.Keys) {
1035                                         if (name == "TypeId")
1036                                                 continue;
1037
1038                                         if (properties == null) {
1039                                                 properties = node.AppendChild (document.CreateElement ("properties"));
1040                                         }
1041
1042                                         object o = attribute_mapping [name];
1043
1044                                         XmlNode n = properties.AppendChild (document.CreateElement ("property"));
1045                                         AddAttribute (n, "name", name);
1046
1047                                         if (o == null) {
1048                                                 AddAttribute (n, "value", "null");
1049                                                 continue;
1050                                         }
1051                                         
1052                                         string value = o.ToString ();
1053                                         if (attName.EndsWith ("GuidAttribute"))
1054                                                 value = value.ToUpper ();
1055                                         AddAttribute (n, "value", value);
1056                                 }
1057
1058                                 natts.AppendChild (node);
1059                         }
1060                 }
1061
1062                 static Dictionary<string, object> CreateAttributeMapping (CustomAttribute attribute)
1063                 {
1064                         var mapping = new Dictionary<string, object> ();
1065
1066                         PopulateMapping (mapping, attribute);
1067
1068                         var constructor = attribute.Constructor.Resolve ();
1069                         if (constructor == null || constructor.Parameters.Count == 0)
1070                                 return mapping;
1071
1072                         PopulateMapping (mapping, constructor, attribute);
1073
1074                         return mapping;
1075                 }
1076
1077                 static void PopulateMapping (Dictionary<string, object> mapping, CustomAttribute attribute)
1078                 {
1079                         foreach (var named_argument in attribute.Properties) {
1080                                 var name = named_argument.Name;
1081                                 var arg = named_argument.Argument;
1082
1083                                 if (arg.Value is CustomAttributeArgument)
1084                                         arg = (CustomAttributeArgument) arg.Value;
1085
1086                                 mapping.Add (name, GetArgumentValue (arg.Type, arg.Value));
1087                         }
1088                 }
1089
1090                 static Dictionary<FieldReference, int> CreateArgumentFieldMapping (MethodDefinition constructor)
1091                 {
1092                         Dictionary<FieldReference, int> field_mapping = new Dictionary<FieldReference, int> ();
1093
1094                         int? argument = null;
1095
1096                         foreach (Instruction instruction in constructor.Body.Instructions) {
1097                                 switch (instruction.OpCode.Code) {
1098                                 case Code.Ldarg_1:
1099                                         argument = 1;
1100                                         break;
1101                                 case Code.Ldarg_2:
1102                                         argument = 2;
1103                                         break;
1104                                 case Code.Ldarg_3:
1105                                         argument = 3;
1106                                         break;
1107                                 case Code.Ldarg:
1108                                 case Code.Ldarg_S:
1109                                         argument = ((ParameterDefinition) instruction.Operand).Index + 1;
1110                                         break;
1111
1112                                 case Code.Stfld:
1113                                         FieldReference field = (FieldReference) instruction.Operand;
1114                                         if (field.DeclaringType.FullName != constructor.DeclaringType.FullName)
1115                                                 continue;
1116
1117                                         if (!argument.HasValue)
1118                                                 break;
1119
1120                                         if (!field_mapping.ContainsKey (field))
1121                                                 field_mapping.Add (field, (int) argument - 1);
1122
1123                                         argument = null;
1124                                         break;
1125                                 }
1126                         }
1127
1128                         return field_mapping;
1129                 }
1130
1131                 static Dictionary<PropertyDefinition, FieldReference> CreatePropertyFieldMapping (TypeDefinition type)
1132                 {
1133                         Dictionary<PropertyDefinition, FieldReference> property_mapping = new Dictionary<PropertyDefinition, FieldReference> ();
1134
1135                         foreach (PropertyDefinition property in type.Properties) {
1136                                 if (property.GetMethod == null)
1137                                         continue;
1138                                 if (!property.GetMethod.HasBody)
1139                                         continue;
1140
1141                                 foreach (Instruction instruction in property.GetMethod.Body.Instructions) {
1142                                         if (instruction.OpCode.Code != Code.Ldfld)
1143                                                 continue;
1144
1145                                         FieldReference field = (FieldReference) instruction.Operand;
1146                                         if (field.DeclaringType.FullName != type.FullName)
1147                                                 continue;
1148
1149                                         property_mapping.Add (property, field);
1150                                         break;
1151                                 }
1152                         }
1153
1154                         return property_mapping;
1155                 }
1156
1157                 static void PopulateMapping (Dictionary<string, object> mapping, MethodDefinition constructor, CustomAttribute attribute)
1158                 {
1159                         if (!constructor.HasBody)
1160                                 return;
1161
1162                         // Custom handling for attributes with arguments which cannot be easily extracted
1163                         var ca = attribute.ConstructorArguments;
1164                         switch (constructor.DeclaringType.FullName) {
1165                         case "System.Runtime.CompilerServices.DecimalConstantAttribute":
1166                                 var dca = constructor.Parameters[2].ParameterType == constructor.Module.TypeSystem.Int32 ?
1167                                         new DecimalConstantAttribute ((byte) ca[0].Value, (byte) ca[1].Value, (int) ca[2].Value, (int) ca[3].Value, (int) ca[4].Value) :
1168                                         new DecimalConstantAttribute ((byte) ca[0].Value, (byte) ca[1].Value, (uint) ca[2].Value, (uint) ca[3].Value, (uint) ca[4].Value);
1169
1170                                 mapping.Add ("Value", dca.Value);
1171                                 return;
1172                         case "System.ComponentModel.BindableAttribute":
1173                                 if (ca.Count != 1)
1174                                         break;
1175
1176                                 if (constructor.Parameters[0].ParameterType == constructor.Module.TypeSystem.Boolean) {
1177                                         mapping.Add ("Bindable", ca[0].Value);
1178                                 } else {
1179                                         throw new NotImplementedException ();
1180                                 }
1181
1182                                 return;
1183                         }
1184
1185                         var field_mapping = CreateArgumentFieldMapping (constructor);
1186                         var property_mapping = CreatePropertyFieldMapping ((TypeDefinition) constructor.DeclaringType);
1187
1188                         foreach (var pair in property_mapping) {
1189                                 int argument;
1190                                 if (!field_mapping.TryGetValue (pair.Value, out argument))
1191                                         continue;
1192
1193                                 var ca_arg = ca [argument];
1194                                 if (ca_arg.Value is CustomAttributeArgument)
1195                                         ca_arg = (CustomAttributeArgument) ca_arg.Value;
1196
1197                                 mapping.Add (pair.Key.Name, GetArgumentValue (ca_arg.Type, ca_arg.Value));
1198                         }
1199                 }
1200
1201                 static object GetArgumentValue (TypeReference reference, object value)
1202                 {
1203                         var type = reference.Resolve ();
1204                         if (type == null)
1205                                 return value;
1206
1207                         if (type.IsEnum) {
1208                                 if (IsFlaggedEnum (type))
1209                                         return GetFlaggedEnumValue (type, value);
1210
1211                                 return GetEnumValue (type, value);
1212                         }
1213
1214                         return value;
1215                 }
1216
1217                 static bool IsFlaggedEnum (TypeDefinition type)
1218                 {
1219                         if (!type.IsEnum)
1220                                 return false;
1221
1222                         if (type.CustomAttributes.Count == 0)
1223                                 return false;
1224
1225                         foreach (CustomAttribute attribute in type.CustomAttributes)
1226                                 if (attribute.Constructor.DeclaringType.FullName == "System.FlagsAttribute")
1227                                         return true;
1228
1229                         return false;
1230                 }
1231
1232                 static object GetFlaggedEnumValue (TypeDefinition type, object value)
1233                 {
1234                         if (value is ulong)
1235                                 return GetFlaggedEnumValue (type, (ulong)value);
1236
1237                         long flags = Convert.ToInt64 (value);
1238                         var signature = new StringBuilder ();
1239
1240                         for (int i = type.Fields.Count - 1; i >= 0; i--) {
1241                                 FieldDefinition field = type.Fields [i];
1242
1243                                 if (!field.HasConstant)
1244                                         continue;
1245
1246                                 long flag = Convert.ToInt64 (field.Constant);
1247
1248                                 if (flag == 0)
1249                                         continue;
1250
1251                                 if ((flags & flag) == flag) {
1252                                         if (signature.Length != 0)
1253                                                 signature.Append (", ");
1254
1255                                         signature.Append (field.Name);
1256                                         flags -= flag;
1257                                 }
1258                         }
1259
1260                         return signature.ToString ();
1261                 }
1262
1263                 static object GetFlaggedEnumValue (TypeDefinition type, ulong flags)
1264                 {
1265                         var signature = new StringBuilder ();
1266
1267                         for (int i = type.Fields.Count - 1; i >= 0; i--) {
1268                                 FieldDefinition field = type.Fields [i];
1269
1270                                 if (!field.HasConstant)
1271                                         continue;
1272
1273                                 ulong flag = Convert.ToUInt64 (field.Constant);
1274
1275                                 if (flag == 0)
1276                                         continue;
1277
1278                                 if ((flags & flag) == flag) {
1279                                         if (signature.Length != 0)
1280                                                 signature.Append (", ");
1281
1282                                         signature.Append (field.Name);
1283                                         flags -= flag;
1284                                 }
1285                         }
1286
1287                         return signature.ToString ();
1288                 }
1289
1290                 static object GetEnumValue (TypeDefinition type, object value)
1291                 {
1292                         foreach (FieldDefinition field in type.Fields) {
1293                                 if (!field.HasConstant)
1294                                         continue;
1295
1296                                 if (Comparer.Default.Compare (field.Constant, value) == 0)
1297                                         return field.Name;
1298                         }
1299
1300                         return value;
1301                 }
1302
1303                 static bool SkipAttribute (CustomAttribute attribute)
1304                 {
1305                         var type_name = Utils.CleanupTypeName (attribute.Constructor.DeclaringType);
1306
1307                         return !TypeHelper.IsPublic (attribute)
1308                                 || type_name.EndsWith ("TODOAttribute");
1309                 }
1310
1311                 public static void OutputAttributes (XmlDocument doc, XmlNode parent, IList<CustomAttribute> attributes)
1312                 {
1313                         AttributeData ad = new AttributeData (doc, parent, attributes);
1314                         ad.DoOutput ();
1315                 }
1316         }
1317
1318         static class Parameters {
1319
1320                 public static string GetSignature (IList<ParameterDefinition> infos)
1321                 {
1322                         if (infos == null || infos.Count == 0)
1323                                 return "";
1324
1325                         var signature = new StringBuilder ();
1326                         for (int i = 0; i < infos.Count; i++) {
1327
1328                                 if (i > 0)
1329                                         signature.Append (", ");
1330
1331                                 ParameterDefinition info = infos [i];
1332
1333                                 string modifier;
1334                                 if ((info.Attributes & ParameterAttributes.In) != 0)
1335                                         modifier = "in";
1336                                 else if ((info.Attributes & ParameterAttributes.Out) != 0)
1337                                         modifier = "out";
1338                                 else
1339                                         modifier = string.Empty;
1340
1341                                 if (modifier.Length > 0)
1342                                         signature.AppendFormat ("{0} ", modifier);
1343
1344                                 signature.Append (Utils.CleanupTypeName (info.ParameterType));
1345                         }
1346
1347                         return signature.ToString ();
1348                 }
1349
1350         }
1351
1352         class TypeReferenceComparer : IComparer
1353         {
1354                 public static TypeReferenceComparer Default = new TypeReferenceComparer ();
1355
1356                 public int Compare (object a, object b)
1357                 {
1358                         TypeReference ta = (TypeReference) a;
1359                         TypeReference tb = (TypeReference) b;
1360                         int result = String.Compare (ta.Namespace, tb.Namespace);
1361                         if (result != 0)
1362                                 return result;
1363
1364                         return String.Compare (ta.Name, tb.Name);
1365                 }
1366         }
1367
1368         class MemberReferenceComparer : IComparer
1369         {
1370                 public static MemberReferenceComparer Default = new MemberReferenceComparer ();
1371
1372                 public int Compare (object a, object b)
1373                 {
1374                         MemberReference ma = (MemberReference) a;
1375                         MemberReference mb = (MemberReference) b;
1376                         return String.Compare (ma.Name, mb.Name);
1377                 }
1378         }
1379
1380         class MethodDefinitionComparer : IComparer
1381         {
1382                 public static MethodDefinitionComparer Default = new MethodDefinitionComparer ();
1383
1384                 public int Compare (object a, object b)
1385                 {
1386                         MethodDefinition ma = (MethodDefinition) a;
1387                         MethodDefinition mb = (MethodDefinition) b;
1388                         int res = String.Compare (ma.Name, mb.Name);
1389                         if (res != 0)
1390                                 return res;
1391
1392                         IList<ParameterDefinition> pia = ma.Parameters ;
1393                         IList<ParameterDefinition> pib = mb.Parameters;
1394                         res = pia.Count - pib.Count;
1395                         if (res != 0)
1396                                 return res;
1397
1398                         string siga = Parameters.GetSignature (pia);
1399                         string sigb = Parameters.GetSignature (pib);
1400                         return String.Compare (siga, sigb);
1401                 }
1402         }
1403 }
1404