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