2008-12-17 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                                 if (IsFinalizer (method))
536                                         continue;
537
538                                 list.Add (method);
539                         }
540
541                         return (MethodDefinition []) list.ToArray (typeof (MethodDefinition));
542                 }
543
544                 static bool IsFinalizer (MethodDefinition method)
545                 {
546                         if (method.Name != "Finalize")
547                                 return false;
548
549                         if (!method.IsVirtual)
550                                 return false;
551
552                         if (method.Parameters.Count != 0)
553                                 return false;
554
555                         return true;
556                 }
557
558                 private MethodDefinition [] GetConstructors (TypeDefinition type)
559                 {
560                         ArrayList list = new ArrayList ();
561
562                         ConstructorCollection ctors = type.Constructors;//type.GetConstructors (flags);
563                         foreach (MethodDefinition constructor in ctors) {
564                                 // we're only interested in public or protected members
565                                 if (!MustDocumentMethod(constructor))
566                                         continue;
567
568                                 list.Add (constructor);
569                         }
570
571                         return (MethodDefinition []) list.ToArray (typeof (MethodDefinition));
572                 }
573
574                 private EventDefinition[] GetEvents (TypeDefinition type)
575                 {
576                         ArrayList list = new ArrayList ();
577
578                         EventDefinitionCollection events = type.Events;//type.GetEvents (flags);
579                         foreach (EventDefinition eventDef in events) {
580                                 MethodDefinition addMethod = eventDef.AddMethod;//eventInfo.GetAddMethod (true);
581
582                                 if (addMethod == null || !MustDocumentMethod (addMethod))
583                                         continue;
584
585                                 list.Add (eventDef);
586                         }
587
588                         return (EventDefinition []) list.ToArray (typeof (EventDefinition));
589                 }
590         }
591
592         class FieldData : MemberData
593         {
594                 public FieldData (XmlDocument document, XmlNode parent, FieldDefinition [] members)
595                         : base (document, parent, members)
596                 {
597                 }
598
599                 protected override CustomAttributeCollection GetCustomAttributes (MemberReference member) {
600                         return ((FieldDefinition) member).CustomAttributes;
601                 }
602
603                 protected override string GetName (MemberReference memberDefenition)
604                 {
605                         FieldDefinition field = (FieldDefinition) memberDefenition;
606                         return field.Name;
607                 }
608
609                 protected override string GetMemberAttributes (MemberReference memberDefenition)
610                 {
611                         FieldDefinition field = (FieldDefinition) memberDefenition;
612                         return ((int) field.Attributes).ToString (CultureInfo.InvariantCulture);
613                 }
614
615                 protected override void AddExtraData (XmlNode p, MemberReference memberDefenition)
616                 {
617                         base.AddExtraData (p, memberDefenition);
618                         FieldDefinition field = (FieldDefinition) memberDefenition;
619                         AddAttribute (p, "fieldtype", Utils.CleanupTypeName (field.FieldType));
620
621                         if (field.IsLiteral) {
622                                 object value = field.Constant;//object value = field.GetValue (null);
623                                 string stringValue = null;
624                                 //if (value is Enum) {
625                                 //    // FIXME: when Mono bug #60090 has been
626                                 //    // fixed, we should just be able to use
627                                 //    // Convert.ToString
628                                 //    stringValue = ((Enum) value).ToString ("D", CultureInfo.InvariantCulture);
629                                 //}
630                                 //else {
631                                         stringValue = Convert.ToString (value, CultureInfo.InvariantCulture);
632                                 //}
633
634                                 if (stringValue != null)
635                                         AddAttribute (p, "value", stringValue);
636                         }
637                 }
638
639                 public override string ParentTag {
640                         get { return "fields"; }
641                 }
642
643                 public override string Tag {
644                         get { return "field"; }
645                 }
646         }
647
648         class PropertyData : MemberData
649         {
650                 public PropertyData (XmlDocument document, XmlNode parent, PropertyDefinition [] members)
651                         : base (document, parent, members)
652                 {
653                 }
654
655                 protected override CustomAttributeCollection GetCustomAttributes (MemberReference member) {
656                         return ((PropertyDefinition) member).CustomAttributes;
657                 }
658
659                 protected override string GetName (MemberReference memberDefenition)
660                 {
661                         PropertyDefinition prop = (PropertyDefinition) memberDefenition;
662                         return prop.Name;
663                 }
664
665                 protected override void AddExtraData (XmlNode p, MemberReference memberDefenition)
666                 {
667                         base.AddExtraData (p, memberDefenition);
668                         PropertyDefinition prop = (PropertyDefinition) memberDefenition;
669                         AddAttribute (p, "ptype", Utils.CleanupTypeName (prop.PropertyType));
670                         MethodDefinition _get = prop.GetMethod;
671                         MethodDefinition _set = prop.SetMethod;
672                         bool haveGet = (_get != null && TypeData.MustDocumentMethod(_get));
673                         bool haveSet = (_set != null && TypeData.MustDocumentMethod(_set));
674                         MethodDefinition [] methods;
675
676                         if (haveGet && haveSet) {
677                                 methods = new MethodDefinition [] { _get, _set };
678                         } else if (haveGet) {
679                                 methods = new MethodDefinition [] { _get };
680                         } else if (haveSet) {
681                                 methods = new MethodDefinition [] { _set };
682                         } else {
683                                 //odd
684                                 return;
685                         }
686
687                         string parms = Parameters.GetSignature (methods [0].Parameters);
688                         AddAttribute (p, "params", parms);
689
690                         MethodData data = new MethodData (document, p, methods);
691                         //data.NoMemberAttributes = true;
692                         data.DoOutput ();
693                 }
694
695                 protected override string GetMemberAttributes (MemberReference memberDefenition)
696                 {
697                         PropertyDefinition prop = (PropertyDefinition) memberDefenition;
698                         return ((int) prop.Attributes).ToString (CultureInfo.InvariantCulture);
699                 }
700
701                 public override string ParentTag {
702                         get { return "properties"; }
703                 }
704
705                 public override string Tag {
706                         get { return "property"; }
707                 }
708         }
709
710         class EventData : MemberData
711         {
712                 public EventData (XmlDocument document, XmlNode parent, EventDefinition [] members)
713                         : base (document, parent, members)
714                 {
715                 }
716
717                 protected override CustomAttributeCollection GetCustomAttributes (MemberReference member) {
718                         return ((EventDefinition) member).CustomAttributes;
719                 }
720
721                 protected override string GetName (MemberReference memberDefenition)
722                 {
723                         EventDefinition evt = (EventDefinition) memberDefenition;
724                         return evt.Name;
725                 }
726
727                 protected override string GetMemberAttributes (MemberReference memberDefenition)
728                 {
729                         EventDefinition evt = (EventDefinition) memberDefenition;
730                         return ((int) evt.Attributes).ToString (CultureInfo.InvariantCulture);
731                 }
732
733                 protected override void AddExtraData (XmlNode p, MemberReference memberDefenition)
734                 {
735                         base.AddExtraData (p, memberDefenition);
736                         EventDefinition evt = (EventDefinition) memberDefenition;
737                         AddAttribute (p, "eventtype", Utils.CleanupTypeName (evt.EventType));
738                 }
739
740                 public override string ParentTag {
741                         get { return "events"; }
742                 }
743
744                 public override string Tag {
745                         get { return "event"; }
746                 }
747         }
748
749         class MethodData : MemberData
750         {
751                 bool noAtts;
752
753                 public MethodData (XmlDocument document, XmlNode parent, MethodDefinition [] members)
754                         : base (document, parent, members)
755                 {
756                 }
757
758                 protected override CustomAttributeCollection GetCustomAttributes (MemberReference member) {
759                         return ((MethodDefinition) member).CustomAttributes;
760                 }
761
762                 protected override string GetName (MemberReference memberDefenition)
763                 {
764                         MethodDefinition method = (MethodDefinition) memberDefenition;
765                         string name = method.Name;
766                         string parms = Parameters.GetSignature (method.Parameters);
767
768                         return string.Format ("{0}({1})", name, parms);
769                 }
770
771                 protected override string GetMemberAttributes (MemberReference memberDefenition)
772                 {
773                         MethodDefinition method = (MethodDefinition) memberDefenition;
774                         return ((int)( method.Attributes)).ToString (CultureInfo.InvariantCulture);
775                 }
776
777                 protected override void AddExtraData (XmlNode p, MemberReference memberDefenition)
778                 {
779                         base.AddExtraData (p, memberDefenition);
780
781                         if (!(memberDefenition is MethodDefinition))
782                                 return;
783
784                         MethodDefinition mbase = (MethodDefinition) memberDefenition;
785
786                         ParameterData parms = new ParameterData (document, p, mbase.Parameters);
787                         parms.DoOutput ();
788
789                         if (mbase.IsAbstract)
790                                 AddAttribute (p, "abstract", "true");
791                         if (mbase.IsVirtual)
792                                 AddAttribute (p, "virtual", "true");
793                         if (mbase.IsStatic)
794                                 AddAttribute (p, "static", "true");
795
796                         //if (!(member is MethodInfo))
797                         //    return;
798
799                         //MethodInfo method = (MethodInfo) member;
800                         string rettype = Utils.CleanupTypeName (mbase.ReturnType.ReturnType);
801                         if (rettype != "System.Void" || !mbase.IsConstructor)
802                                 AddAttribute (p, "returntype", (rettype));
803
804                         AttributeData.OutputAttributes (document, p, mbase.ReturnType.CustomAttributes);
805
806                         MemberData.OutputGenericParameters (document, p, mbase);
807                 }
808
809                 public override bool NoMemberAttributes {
810                         get { return noAtts; }
811                         set { noAtts = value; }
812                 }
813
814                 public override string ParentTag {
815                         get { return "methods"; }
816                 }
817
818                 public override string Tag {
819                         get { return "method"; }
820                 }
821         }
822
823         class ConstructorData : MethodData
824         {
825                 public ConstructorData (XmlDocument document, XmlNode parent, MethodDefinition [] members)
826                         : base (document, parent, members)
827                 {
828                 }
829
830                 public override string ParentTag {
831                         get { return "constructors"; }
832                 }
833
834                 public override string Tag {
835                         get { return "constructor"; }
836                 }
837         }
838
839         class ParameterData : BaseData
840         {
841                 private ParameterDefinitionCollection parameters;
842
843                 public ParameterData (XmlDocument document, XmlNode parent, ParameterDefinitionCollection parameters)
844                         : base (document, parent)
845                 {
846                         this.parameters = parameters;
847                 }
848
849                 public override void DoOutput ()
850                 {
851                         XmlNode parametersNode = document.CreateElement ("parameters");
852                         parent.AppendChild (parametersNode);
853
854                         foreach (ParameterDefinition parameter in parameters) {
855                                 XmlNode paramNode = document.CreateElement ("parameter");
856                                 parametersNode.AppendChild (paramNode);
857                                 AddAttribute (paramNode, "name", parameter.Name);
858                                 AddAttribute (paramNode, "position", parameter.Method.Parameters.IndexOf(parameter).ToString(CultureInfo.InvariantCulture));
859                                 AddAttribute (paramNode, "attrib", ((int) parameter.Attributes).ToString());
860
861                                 string direction = "in";
862
863                                 if (parameter.ParameterType is ReferenceType)
864                                         direction = parameter.IsOut ? "out" : "ref";
865
866                                 TypeReference t = parameter.ParameterType;
867                                 AddAttribute (paramNode, "type", Utils.CleanupTypeName (t));
868
869                                 if (parameter.IsOptional) {
870                                         AddAttribute (paramNode, "optional", "true");
871                                         if (parameter.HasConstant)
872                                                 AddAttribute (paramNode, "defaultValue", parameter.Constant == null ? "NULL" : parameter.Constant.ToString ());
873                                 }
874
875                                 if (direction != "in")
876                                         AddAttribute (paramNode, "direction", direction);
877
878                                 AttributeData.OutputAttributes (document, paramNode, parameter.CustomAttributes);
879                         }
880                 }
881         }
882
883         class AttributeData : BaseData
884         {
885                 CustomAttributeCollection atts;
886
887                 AttributeData (XmlDocument doc, XmlNode parent, CustomAttributeCollection attributes)
888                         : base (doc, parent)
889                 {
890                         atts = attributes;
891                 }
892
893                 public override void DoOutput ()
894                 {
895                         if (document == null)
896                                 throw new InvalidOperationException ("Document not set");
897
898                         if (atts == null || atts.Count == 0)
899                                 return;
900
901                         XmlNode natts = parent.SelectSingleNode("attributes");
902                         if (natts == null) {
903                                 natts = document.CreateElement ("attributes", null);
904                                 parent.AppendChild (natts);
905                         }
906
907                         for (int i = 0; i < atts.Count; ++i) {
908                                 CustomAttribute att = atts [i];
909                                 try {
910                                         att.Resolve ();
911                                 } catch {}
912
913                                 if (!att.Resolved)
914                                         continue;
915
916                                 string attName = Utils.CleanupTypeName (att.Constructor.DeclaringType);
917                                 if (SkipAttribute (att))
918                                         continue;
919
920                                 XmlNode node = document.CreateElement ("attribute");
921                                 AddAttribute (node, "name", attName);
922
923                                 XmlNode properties = null;
924
925                                 Dictionary<string, object> attribute_mapping = CreateAttributeMapping (att);
926
927                                 foreach (string name in attribute_mapping.Keys) {
928                                         if (name == "TypeId")
929                                                 continue;
930
931                                         if (properties == null) {
932                                                 properties = node.AppendChild (document.CreateElement ("properties"));
933                                         }
934
935                                         object o = attribute_mapping [name];
936
937                                         XmlNode n = properties.AppendChild (document.CreateElement ("property"));
938                                         AddAttribute (n, "name", name);
939
940                                         if (o == null) {
941                                                 AddAttribute (n, "value", "null");
942                                                 continue;
943                                         }
944                                         string value = o.ToString ();
945                                         if (attName.EndsWith ("GuidAttribute"))
946                                                 value = value.ToUpper ();
947                                         AddAttribute (n, "value", value);
948                                 }
949
950                                 natts.AppendChild (node);
951                         }
952                 }
953
954                 static Dictionary<string, object> CreateAttributeMapping (CustomAttribute attribute)
955                 {
956                         var mapping = new Dictionary<string, object> ();
957
958                         PopulateMapping (mapping, attribute);
959
960                         var constructor = TypeHelper.Resolver.Resolve (attribute.Constructor);
961                         if (constructor == null || constructor.Parameters.Count == 0)
962                                 return mapping;
963
964                         PopulateMapping (mapping, constructor, attribute);
965
966                         return mapping;
967                 }
968
969                 static void PopulateMapping (Dictionary<string, object> mapping, CustomAttribute attribute)
970                 {
971                         foreach (DictionaryEntry entry in attribute.Properties) {
972                                 var name = (string) entry.Key;
973
974                                 mapping.Add (name, GetArgumentValue (attribute.GetPropertyType (name), entry.Value));
975                         }
976                 }
977
978                 static Dictionary<FieldReference, int> CreateArgumentFieldMapping (MethodDefinition constructor)
979                 {
980                         Dictionary<FieldReference, int> field_mapping = new Dictionary<FieldReference, int> ();
981
982                         int? argument = null;
983
984                         foreach (Instruction instruction in constructor.Body.Instructions) {
985                                 switch (instruction.OpCode.Code) {
986                                 case Code.Ldarg_1:
987                                         argument = 1;
988                                         break;
989                                 case Code.Ldarg_2:
990                                         argument = 2;
991                                         break;
992                                 case Code.Ldarg_3:
993                                         argument = 3;
994                                         break;
995                                 case Code.Ldarg:
996                                 case Code.Ldarg_S:
997                                         argument = ((ParameterDefinition) instruction.Operand).Sequence;
998                                         break;
999
1000                                 case Code.Stfld:
1001                                         FieldReference field = (FieldReference) instruction.Operand;
1002                                         if (field.DeclaringType.FullName != constructor.DeclaringType.FullName)
1003                                                 continue;
1004
1005                                         if (!argument.HasValue)
1006                                                 break;
1007
1008                                         if (!field_mapping.ContainsKey (field))
1009                                                 field_mapping.Add (field, (int) argument - 1);
1010
1011                                         argument = null;
1012                                         break;
1013                                 }
1014                         }
1015
1016                         return field_mapping;
1017                 }
1018
1019                 static Dictionary<PropertyDefinition, FieldReference> CreatePropertyFieldMapping (TypeDefinition type)
1020                 {
1021                         Dictionary<PropertyDefinition, FieldReference> property_mapping = new Dictionary<PropertyDefinition, FieldReference> ();
1022
1023                         foreach (PropertyDefinition property in type.Properties) {
1024                                 if (property.GetMethod == null)
1025                                         continue;
1026                                 if (!property.GetMethod.HasBody)
1027                                         continue;
1028
1029                                 foreach (Instruction instruction in property.GetMethod.Body.Instructions) {
1030                                         if (instruction.OpCode.Code != Code.Ldfld)
1031                                                 continue;
1032
1033                                         FieldReference field = (FieldReference) instruction.Operand;
1034                                         if (field.DeclaringType.FullName != type.FullName)
1035                                                 continue;
1036
1037                                         property_mapping.Add (property, field);
1038                                         break;
1039                                 }
1040                         }
1041
1042                         return property_mapping;
1043                 }
1044
1045                 static void PopulateMapping (Dictionary<string, object> mapping, MethodDefinition constructor, CustomAttribute attribute)
1046                 {
1047                         if (!constructor.HasBody)
1048                                 return;
1049
1050                         var field_mapping = CreateArgumentFieldMapping (constructor);
1051                         var property_mapping = CreatePropertyFieldMapping ((TypeDefinition) constructor.DeclaringType);
1052
1053                         foreach (var pair in property_mapping) {
1054                                 int argument;
1055                                 if (!field_mapping.TryGetValue (pair.Value, out argument))
1056                                         continue;
1057
1058                                 mapping.Add (pair.Key.Name, GetArgumentValue (constructor.Parameters [argument].ParameterType, attribute.ConstructorParameters [argument]));
1059                         }
1060                 }
1061
1062                 static object GetArgumentValue (TypeReference reference, object value)
1063                 {
1064                         var type = TypeHelper.Resolver.Resolve (reference);
1065                         if (type == null)
1066                                 return value;
1067
1068                         if (type.IsEnum) {
1069                                 if (IsFlaggedEnum (type))
1070                                         return GetFlaggedEnumValue (type, value);
1071
1072                                 return GetEnumValue (type, value);
1073                         }
1074
1075                         return value;
1076                 }
1077
1078                 static bool IsFlaggedEnum (TypeDefinition type)
1079                 {
1080                         if (!type.IsEnum)
1081                                 return false;
1082
1083                         if (type.CustomAttributes.Count == 0)
1084                                 return false;
1085
1086                         foreach (CustomAttribute attribute in type.CustomAttributes)
1087                                 if (attribute.Constructor.DeclaringType.FullName == "System.FlagsAttribute")
1088                                         return true;
1089
1090                         return false;
1091                 }
1092
1093                 static object GetFlaggedEnumValue (TypeDefinition type, object value)
1094                 {
1095                         long flags = Convert.ToInt64 (value);
1096                         var signature = new StringBuilder ();
1097
1098                         for (int i = type.Fields.Count - 1; i >= 0; i--) {
1099                                 FieldDefinition field = type.Fields [i];
1100
1101                                 if (!field.HasConstant)
1102                                         continue;
1103
1104                                 long flag = Convert.ToInt64 (field.Constant);
1105
1106                                 if (flag == 0)
1107                                         continue;
1108
1109                                 if ((flags & flag) == flag) {
1110                                         if (signature.Length != 0)
1111                                                 signature.Append (", ");
1112
1113                                         signature.Append (field.Name);
1114                                         flags -= flag;
1115                                 }
1116                         }
1117
1118                         return signature.ToString ();
1119                 }
1120
1121                 static object GetEnumValue (TypeDefinition type, object value)
1122                 {
1123                         foreach (FieldDefinition field in type.Fields) {
1124                                 if (!field.HasConstant)
1125                                         continue;
1126
1127                                 if (Comparer.Default.Compare (field.Constant, value) == 0)
1128                                         return field.Name;
1129                         }
1130
1131                         return value;
1132                 }
1133
1134                 static bool SkipAttribute (CustomAttribute attribute)
1135                 {
1136                         var type_name = Utils.CleanupTypeName (attribute.Constructor.DeclaringType);
1137
1138                         return !TypeHelper.IsPublic (attribute)
1139                                 || type_name.EndsWith ("TODOAttribute");
1140                 }
1141
1142                 public static void OutputAttributes (XmlDocument doc, XmlNode parent, CustomAttributeCollection attributes)
1143                 {
1144                         AttributeData ad = new AttributeData (doc, parent, attributes);
1145                         ad.DoOutput ();
1146                 }
1147         }
1148
1149         static class Parameters {
1150
1151                 public static string GetSignature (ParameterDefinitionCollection infos)
1152                 {
1153                         if (infos == null || infos.Count == 0)
1154                                 return "";
1155
1156                         var signature = new StringBuilder ();
1157                         for (int i = 0; i < infos.Count; i++) {
1158
1159                                 if (i > 0)
1160                                         signature.Append (", ");
1161
1162                                 ParameterDefinition info = infos [i];
1163
1164                                 string modifier;
1165                                 if ((info.Attributes & ParameterAttributes.In) != 0)
1166                                         modifier = "in";
1167                                 else if (((int)info.Attributes & 0x8) != 0) // retval
1168                                         modifier = "ref";
1169                                 else if ((info.Attributes & ParameterAttributes.Out) != 0)
1170                                         modifier = "out";
1171                                 else
1172                                         modifier = string.Empty;
1173
1174                                 if (modifier.Length > 0)
1175                                         signature.AppendFormat ("{0} ", modifier);
1176
1177                                 signature.Append (Utils.CleanupTypeName (info.ParameterType));
1178                         }
1179
1180                         return signature.ToString ();
1181                 }
1182
1183         }
1184
1185         class TypeReferenceComparer : IComparer
1186         {
1187                 public static TypeReferenceComparer Default = new TypeReferenceComparer ();
1188
1189                 public int Compare (object a, object b)
1190                 {
1191                         TypeReference ta = (TypeReference) a;
1192                         TypeReference tb = (TypeReference) b;
1193                         int result = String.Compare (ta.Namespace, tb.Namespace);
1194                         if (result != 0)
1195                                 return result;
1196
1197                         return String.Compare (ta.Name, tb.Name);
1198                 }
1199         }
1200
1201         class MemberReferenceComparer : IComparer
1202         {
1203                 public static MemberReferenceComparer Default = new MemberReferenceComparer ();
1204
1205                 public int Compare (object a, object b)
1206                 {
1207                         MemberReference ma = (MemberReference) a;
1208                         MemberReference mb = (MemberReference) b;
1209                         return String.Compare (ma.Name, mb.Name);
1210                 }
1211         }
1212
1213         class MethodDefinitionComparer : IComparer
1214         {
1215                 public static MethodDefinitionComparer Default = new MethodDefinitionComparer ();
1216
1217                 public int Compare (object a, object b)
1218                 {
1219                         MethodDefinition ma = (MethodDefinition) a;
1220                         MethodDefinition mb = (MethodDefinition) b;
1221                         int res = String.Compare (ma.Name, mb.Name);
1222                         if (res != 0)
1223                                 return res;
1224
1225                         ParameterDefinitionCollection pia = ma.Parameters ;
1226                         ParameterDefinitionCollection pib = mb.Parameters;
1227                         res = pia.Count - pib.Count;
1228                         if (res != 0)
1229                                 return res;
1230
1231                         string siga = Parameters.GetSignature (pia);
1232                         string sigb = Parameters.GetSignature (pib);
1233                         return String.Compare (siga, sigb);
1234                 }
1235         }
1236 }
1237