[mdoc] Improved error handling for multiassembly.
[mono.git] / mcs / tools / mdoc / Mono.Documentation / monodocer.cs
1 // Updater program for syncing Mono's ECMA-style documentation files
2 // with an assembly.
3 // By Joshua Tauberer <tauberer@for.net>
4
5 using System;
6 using System.Collections;
7 using System.Collections.Generic;
8 using System.Collections.ObjectModel;
9 using System.Diagnostics;
10 using System.Globalization;
11 using System.IO;
12 using System.Linq;
13 using System.Text;
14 using System.Xml;
15 using System.Xml.XPath;
16
17 using Mono.Cecil;
18 using Mono.Options;
19
20 using MyXmlNodeList        = System.Collections.Generic.List<System.Xml.XmlNode>;
21 using StringList           = System.Collections.Generic.List<string>;
22 using StringToStringMap    = System.Collections.Generic.Dictionary<string, string>;
23 using StringToXmlNodeMap   = System.Collections.Generic.Dictionary<string, System.Xml.XmlNode>;
24
25 namespace Mono.Documentation {
26         static class NativeTypeManager {
27
28                 static Dictionary<string, string> toNativeType = new Dictionary<string,string>(){
29
30                         {"int", "nint"},
31                         {"Int32", "nint"},
32                         {"System.Int32", "System.nint"},
33                         {"uint", "nuint"},
34                         {"UInt32", "nuint"},
35                         {"System.UInt32", "System.nuint"},
36                         {"float", "nfloat"},
37                         {"Single", "nfloat"},
38                         {"System.Single", "System.nfloat"},
39                         {"SizeF", "CoreGraphics.CGSize"},
40                         {"System.Drawing.SizeF", "CoreGraphics.CGSize"},
41                         {"PointF", "CoreGraphics.CGPoint"},
42                         {"System.Drawing.PointF", "CoreGraphics.CGPoint"},
43                         {"RectangleF", "CoreGraphics.CGRect" },
44                         {"System.Drawing.RectangleF", "CoreGraphics.CGRect"}
45                 };              
46
47                 static Dictionary<string, string> fromNativeType = new Dictionary<string,string>(){
48
49                         {"nint", "int"},
50                         {"System.nint", "System.Int32"},
51                         {"nuint", "uint"},
52                         {"System.nuint", "System.UInt32"},
53                         {"nfloat", "float"},
54                         {"System.nfloat", "System.Single"},
55                         {"CoreGraphics.CGSize", "System.Drawing.SizeF"},
56                         {"CoreGraphics.CGPoint", "System.Drawing.PointF"},
57                         {"CoreGraphics.CGRect", "System.Drawing.RectangleF"},
58                         {"MonoTouch.CoreGraphics.CGSize", "System.Drawing.SizeF"},
59                         {"MonoTouch.CoreGraphics.CGPoint", "System.Drawing.PointF"},
60                         {"MonoTouch.CoreGraphics.CGRect", "System.Drawing.RectangleF"}
61                 };
62
63                 public static string ConvertToNativeType(string typename) {
64                         string nvalue;
65
66                         bool isOut=false;
67                         bool isArray=false;
68                         string valueToCompare = StripToComparableType (typename, ref isOut, ref isArray);
69
70                         if (toNativeType.TryGetValue (valueToCompare, out nvalue)) {
71
72                                 if (isArray) {
73                                         nvalue += "[]";
74                                 }
75                                 if (isOut) {
76                                         nvalue += "&";
77                                 }
78                                 return nvalue;
79                         }
80                         return typename;
81                 }
82                 public static string ConvertFromNativeType(string typename) {
83                         string nvalue;
84
85                         bool isOut=false;
86                         bool isArray=false;
87                         string valueToCompare = StripToComparableType (typename, ref isOut, ref isArray);
88
89                         if (fromNativeType.TryGetValue (valueToCompare, out nvalue)) {
90                                 if (isArray) {
91                                         nvalue += "[]";
92                                 }
93                                 if (isOut) {
94                                         nvalue += "&";
95                                 }
96                                 return nvalue;
97                         }
98                         // it wasn't one of the native types ... just return it
99                         return typename;
100                 }
101
102                 static string StripToComparableType (string typename, ref bool isOut, ref bool isArray)
103                 {
104                         string valueToCompare = typename;
105                         if (typename.EndsWith ("[]")) {
106                                 valueToCompare = typename.Substring (0, typename.Length - 2);
107                                 isArray = true;
108                         }
109                         if (typename.EndsWith ("&")) {
110                                 valueToCompare = typename.Substring (0, typename.Length - 1);
111                                 isOut = true;
112                         }
113                         if (typename.Contains ("<")) {
114                                 // TODO: Need to recursively process generic parameters
115                         }
116                         return valueToCompare;
117                 }
118
119                 public static string GetTranslatedName(TypeReference t) {
120                         string typename = t.FullName;
121
122                         bool isInAssembly = MDocUpdater.IsInAssemblies (t.Module.Name);
123                         if (isInAssembly && !typename.StartsWith ("System") && MDocUpdater.HasDroppedNamespace (t)) {
124                                 string nameWithDropped = string.Format ("{0}.{1}", MDocUpdater.droppedNamespace, typename);
125                                 return nameWithDropped;
126                         }
127                         return typename;
128                 }
129         }
130 class MDocUpdater : MDocCommand
131 {
132         string srcPath;
133         List<AssemblyDefinition> assemblies;
134         readonly DefaultAssemblyResolver assemblyResolver = new DefaultAssemblyResolver();
135         
136         bool multiassembly;
137         bool delete;
138         bool show_exceptions;
139         bool no_assembly_versions, ignore_missing_types;
140         ExceptionLocations? exceptions;
141         
142         internal int additions = 0, deletions = 0;
143
144         List<DocumentationImporter> importers = new List<DocumentationImporter> ();
145
146         DocumentationEnumerator docEnum;
147
148         string since;
149
150         static readonly MemberFormatter docTypeFormatter     = new DocTypeMemberFormatter ();
151         static readonly MemberFormatter filenameFormatter    = new FileNameMemberFormatter ();
152
153         static MemberFormatter[] typeFormatters = new MemberFormatter[]{
154                 new CSharpMemberFormatter (),
155                 new ILMemberFormatter (),
156         };
157
158         static MemberFormatter[] memberFormatters = new MemberFormatter[]{
159                 new CSharpFullMemberFormatter (),
160                 new ILFullMemberFormatter (),
161         };
162
163         internal static readonly MemberFormatter slashdocFormatter    = new SlashDocMemberFormatter ();
164
165         MyXmlNodeList extensionMethods = new MyXmlNodeList ();
166
167         HashSet<string> forwardedTypes = new HashSet<string> ();
168
169         public static string droppedNamespace = string.Empty;
170
171         public static bool HasDroppedNamespace(TypeDefinition forType) 
172         {
173                 return HasDroppedNamespace(forType.Module);
174         }
175
176         public static bool HasDroppedNamespace(MemberReference forMember) 
177         {
178                 return HasDroppedNamespace(forMember.Module);
179         }
180
181         public static bool HasDroppedNamespace(AssemblyDefinition forAssembly) 
182         {
183                 return HasDroppedNamespace(forAssembly.MainModule);
184         }
185
186         public static bool HasDroppedNamespace(ModuleDefinition forModule) 
187         {
188                 return !string.IsNullOrWhiteSpace (droppedNamespace) && droppedAssemblies.Any(da => da == forModule.Name);
189         }
190
191         public static bool HasDroppedAnyNamespace ()
192         {
193                 return !string.IsNullOrWhiteSpace (droppedNamespace);
194         }
195
196         
197         static List<string> droppedAssemblies = new List<string>();
198
199         public string PreserveTag { get; set; }
200         public static MDocUpdater Instance { get; private set; }
201         public static bool SwitchingToMagicTypes { get; private set; }
202
203         public override void Run (IEnumerable<string> args)
204         {
205                 Instance = this;
206                 show_exceptions = DebugOutput;
207                 var types = new List<string> ();
208                 var p = new OptionSet () {
209                         { "delete",
210                                 "Delete removed members from the XML files.",
211                                 v => delete = v != null },
212                         { "exceptions:",
213                           "Document potential exceptions that members can generate.  {SOURCES} " +
214                                 "is a comma-separated list of:\n" +
215                                 "  asm      Method calls in same assembly\n" +
216                                 "  depasm   Method calls in dependent assemblies\n" +
217                                 "  all      Record all possible exceptions\n" +
218                                 "  added    Modifier; only create <exception/>s\n" +
219                                 "             for NEW types/members\n" +
220                                 "If nothing is specified, then only exceptions from the member will " +
221                                 "be listed.",
222                                 v => exceptions = ParseExceptionLocations (v) },
223                         { "f=",
224                                 "Specify a {FLAG} to alter behavior.  See later -f* options for available flags.",
225                                 v => {
226                                         switch (v) {
227                                                 case "ignore-missing-types":
228                                                         ignore_missing_types = true;
229                                                         break;
230                                                 case "no-assembly-versions":
231                                                         no_assembly_versions = true;
232                                                         break;
233                                                 default:
234                                                         throw new Exception ("Unsupported flag `" + v + "'.");
235                                         }
236                                 } },
237                         { "fignore-missing-types",
238                                 "Do not report an error if a --type=TYPE type\nwas not found.",
239                                 v => ignore_missing_types = v != null },
240                         { "fno-assembly-versions",
241                                 "Do not generate //AssemblyVersion elements.",
242                                 v => no_assembly_versions = v != null },
243                         { "i|import=", 
244                                 "Import documentation from {FILE}.",
245                                 v => AddImporter (v) },
246                         { "L|lib=",
247                                 "Check for assembly references in {DIRECTORY}.",
248                                 v => assemblyResolver.AddSearchDirectory (v) },
249                         { "library=",
250                                 "Ignored for compatibility with update-ecma-xml.",
251                                 v => {} },
252                         { "o|out=",
253                                 "Root {DIRECTORY} to generate/update documentation.",
254                                 v => srcPath = v },
255                         { "r=",
256                                 "Search for dependent assemblies in the directory containing {ASSEMBLY}.\n" +
257                                 "(Equivalent to '-L `dirname ASSEMBLY`'.)",
258                                 v => assemblyResolver.AddSearchDirectory (Path.GetDirectoryName (v)) },
259                         { "since=",
260                                 "Manually specify the assembly {VERSION} that new members were added in.",
261                                 v => since = v },
262                         { "type=",
263                           "Only update documentation for {TYPE}.",
264                                 v => types.Add (v) },
265                         { "dropns=",
266                           "When processing assembly {ASSEMBLY}, strip off leading namespace {PREFIX}:\n" +
267                           "  e.g. --dropns ASSEMBLY=PREFIX",
268                           v => {
269                             var parts = v.Split ('=');
270                             if (parts.Length != 2) { Console.Error.WriteLine ("Invalid dropns input"); return; }
271                             var assembly = Path.GetFileName (parts [0].Trim ());
272                             var prefix = parts [1].Trim();
273                             droppedAssemblies.Add (assembly);
274                             droppedNamespace = prefix;
275                         } },
276                         { "ntypes",
277                                 "If the new assembly is switching to 'magic types', then this switch should be defined.",
278                                 v => SwitchingToMagicTypes = true },
279                         { "preserve",
280                                 "Do not delete members that don't exist in the assembly, but rather mark them as preserved.",
281                                 v => PreserveTag = "true" },
282                         { "multiassembly",
283                                 "Allow types to be in multiple assemblies.",
284                                 v => multiassembly = true },
285                 };
286                 var assemblies = Parse (p, args, "update", 
287                                 "[OPTIONS]+ ASSEMBLIES",
288                                 "Create or update documentation from ASSEMBLIES.");
289                 if (assemblies == null)
290                         return;
291                 if (assemblies.Count == 0)
292                         Error ("No assemblies specified.");
293
294                 foreach (var dir in assemblies
295                                 .Where (a => a.Contains (Path.DirectorySeparatorChar))
296                                 .Select (a => Path.GetDirectoryName (a)))
297                         assemblyResolver.AddSearchDirectory (dir);
298
299                 // PARSE BASIC OPTIONS AND LOAD THE ASSEMBLY TO DOCUMENT
300                 
301                 if (srcPath == null)
302                         throw new InvalidOperationException("The --out option is required.");
303                 
304                 this.assemblies = assemblies.Select (a => LoadAssembly (a)).ToList ();
305
306                 // Store types that have been forwarded to avoid duplicate generation
307                 GatherForwardedTypes ();
308
309                 docEnum = docEnum ?? new DocumentationEnumerator ();
310                 
311                 // PERFORM THE UPDATES
312                 
313                 if (types.Count > 0) {
314                         types.Sort ();
315                         DoUpdateTypes (srcPath, types, srcPath);
316                 }
317 #if false
318                 else if (opts.@namespace != null)
319                         DoUpdateNS (opts.@namespace, Path.Combine (opts.path, opts.@namespace),
320                                         Path.Combine (dest_dir, opts.@namespace));
321 #endif
322                 else
323                         DoUpdateAssemblies (srcPath, srcPath);
324
325                 Console.WriteLine("Members Added: {0}, Members Deleted: {1}", additions, deletions);
326         }
327                 public static bool IsInAssemblies(string name) {
328                         var query = Instance.assemblies.Where (a => a.MainModule.Name == name).ToArray ();
329                         return query.Length > 0;
330                 }
331         void AddImporter (string path)
332         {
333                 try {
334                         XmlReader r = new XmlTextReader (path);
335                         if (r.Read ()) {
336                                 while (r.NodeType != XmlNodeType.Element) {
337                                         if (!r.Read ())
338                                                 Error ("Unable to read XML file: {0}.", path);
339                                 }
340                                 if (r.LocalName == "doc") {
341                                         importers.Add (new MsxdocDocumentationImporter (path));
342                                 }
343                                 else if (r.LocalName == "Libraries") {
344                                         var ecmadocs = new XmlTextReader (path);
345                                         docEnum = new EcmaDocumentationEnumerator (this, ecmadocs);
346                                         importers.Add (new EcmaDocumentationImporter (ecmadocs));
347                                 }
348                                 else
349                                         Error ("Unsupported XML format within {0}.", path);
350                         }
351                         r.Close ();
352                 } catch (Exception e) {
353                         Environment.ExitCode = 1;
354                         Error ("Could not load XML file: {0}.", e.Message);
355                 }
356         }
357
358         void GatherForwardedTypes ()
359         {
360                 foreach (var asm in assemblies)
361                         foreach (var type in asm.MainModule.ExportedTypes.Where (t => t.IsForwarder).Select (t => t.FullName))
362                                 forwardedTypes.Add (type);
363         }
364
365         static ExceptionLocations ParseExceptionLocations (string s)
366         {
367                 ExceptionLocations loc = ExceptionLocations.Member;
368                 if (s == null)
369                         return loc;
370                 foreach (var type in s.Split (',')) {
371                         switch (type) {
372                                 case "added":   loc |= ExceptionLocations.AddedMembers; break;
373                                 case "all":     loc |= ExceptionLocations.Assembly | ExceptionLocations.DependentAssemblies; break;
374                                 case "asm":     loc |= ExceptionLocations.Assembly; break;
375                                 case "depasm":  loc |= ExceptionLocations.DependentAssemblies; break;
376                                 default:        throw new NotSupportedException ("Unsupported --exceptions value: " + type);
377                         }
378                 }
379                 return loc;
380         }
381
382         internal void Warning (string format, params object[] args)
383         {
384                 Message (TraceLevel.Warning, "mdoc: " + format, args);
385         }
386         
387         private AssemblyDefinition LoadAssembly (string name)
388         {
389                 AssemblyDefinition assembly = null;
390                 try {
391                         assembly = AssemblyDefinition.ReadAssembly (name, new ReaderParameters { AssemblyResolver = assemblyResolver });
392                 } catch (System.IO.FileNotFoundException) { }
393
394                 if (assembly == null)
395                         throw new InvalidOperationException("Assembly " + name + " not found.");
396
397                 return assembly;
398         }
399
400         private static void WriteXml(XmlElement element, System.IO.TextWriter output) {
401                 OrderTypeAttributes (element);
402                 XmlTextWriter writer = new XmlTextWriter(output);
403                 writer.Formatting = Formatting.Indented;
404                 writer.Indentation = 2;
405                 writer.IndentChar = ' ';
406                 element.WriteTo(writer);
407                 output.WriteLine();     
408         }
409
410         private static void WriteFile (string filename, FileMode mode, Action<TextWriter> action)
411         {
412                 Action<string> creator = file => {
413                         using (var writer = OpenWrite (file, mode))
414                                 action (writer);
415                 };
416
417                 MdocFile.UpdateFile (filename, creator);
418         }
419
420         private static void OrderTypeAttributes (XmlElement e)
421         {
422                 foreach (XmlElement type in e.SelectNodes ("//Type")) {
423                         OrderTypeAttributes (type.Attributes);
424                 }
425         }
426
427         static readonly string[] TypeAttributeOrder = {
428                 "Name", "FullName", "FullNameSP", "Maintainer"
429         };
430
431         private static void OrderTypeAttributes (XmlAttributeCollection c)
432         {
433                 XmlAttribute[] attrs = new XmlAttribute [TypeAttributeOrder.Length];
434                 for (int i = 0; i < c.Count; ++i) {
435                         XmlAttribute a = c [i];
436                         for (int j = 0; j < TypeAttributeOrder.Length; ++j) {
437                                 if (a.Name == TypeAttributeOrder [j]) {
438                                         attrs [j] = a;
439                                         break;
440                                 }
441                         }
442                 }
443                 for (int i = attrs.Length-1; i >= 0; --i) {
444                         XmlAttribute n = attrs [i];
445                         if (n == null)
446                                 continue;
447                         XmlAttribute r = null;
448                         for (int j = i+1; j < attrs.Length; ++j) {
449                                 if (attrs [j] != null) {
450                                         r = attrs [j];
451                                         break;
452                                 }
453                         }
454                         if (r == null)
455                                 continue;
456                         if (c [n.Name] != null) {
457                                 c.RemoveNamedItem (n.Name);
458                                 c.InsertBefore (n, r);
459                         }
460                 }
461         }
462         
463         private XmlDocument CreateIndexStub()
464         {
465                 XmlDocument index = new XmlDocument();
466
467                 XmlElement index_root = index.CreateElement("Overview");
468                 index.AppendChild(index_root);
469
470                 if (assemblies.Count == 0)
471                         throw new Exception ("No assembly");
472
473                 XmlElement index_assemblies = index.CreateElement("Assemblies");
474                 index_root.AppendChild(index_assemblies);
475
476                 XmlElement index_remarks = index.CreateElement("Remarks");
477                 index_remarks.InnerText = "To be added.";
478                 index_root.AppendChild(index_remarks);
479
480                 XmlElement index_copyright = index.CreateElement("Copyright");
481                 index_copyright.InnerText = "To be added.";
482                 index_root.AppendChild(index_copyright);
483
484                 XmlElement index_types = index.CreateElement("Types");
485                 index_root.AppendChild(index_types);
486                 
487                 return index;
488         }
489         
490         private static void WriteNamespaceStub(string ns, string outdir) {
491                 XmlDocument index = new XmlDocument();
492
493                 XmlElement index_root = index.CreateElement("Namespace");
494                 index.AppendChild(index_root);
495                 
496                 index_root.SetAttribute("Name", ns);
497
498                 XmlElement index_docs = index.CreateElement("Docs");
499                 index_root.AppendChild(index_docs);
500
501                 XmlElement index_summary = index.CreateElement("summary");
502                 index_summary.InnerText = "To be added.";
503                 index_docs.AppendChild(index_summary);
504
505                 XmlElement index_remarks = index.CreateElement("remarks");
506                 index_remarks.InnerText = "To be added.";
507                 index_docs.AppendChild(index_remarks);
508
509                 WriteFile (outdir + "/ns-" + ns + ".xml", FileMode.CreateNew, 
510                                 writer => WriteXml (index.DocumentElement, writer));
511         }
512
513         public void DoUpdateTypes (string basepath, List<string> typenames, string dest)
514         {
515                 var index = CreateIndexForTypes (dest);
516
517                 var found = new HashSet<string> ();
518                 foreach (AssemblyDefinition assembly in assemblies) {
519                         foreach (TypeDefinition type in docEnum.GetDocumentationTypes (assembly, typenames)) {
520                                 string relpath = DoUpdateType (type, basepath, dest);
521                                 if (relpath == null)
522                                         continue;
523
524                                 found.Add (type.FullName);
525
526                                 if (index == null)
527                                         continue;
528
529                                 index.Add (assembly);
530                                 index.Add (type);
531                         }
532                 }
533
534                 if (index != null)
535                         index.Write ();
536                 
537                 if (ignore_missing_types)
538                         return;
539
540                 var notFound = from n in typenames where !found.Contains (n) select n;
541                 if (notFound.Any ())
542                         throw new InvalidOperationException("Type(s) not found: " + string.Join (", ", notFound.ToArray ()));
543         }
544
545         class IndexForTypes {
546
547                 MDocUpdater app;
548                 string indexFile;
549
550                 XmlDocument index;
551                 XmlElement index_types;
552                 XmlElement index_assemblies;
553
554                 public IndexForTypes (MDocUpdater app, string indexFile, XmlDocument index)
555                 {
556                         this.app        = app;
557                         this.indexFile  = indexFile;
558                         this.index      = index;
559
560                         index_types = WriteElement (index.DocumentElement, "Types");
561                         index_assemblies = WriteElement (index.DocumentElement, "Assemblies");
562                 }
563
564                 public void Add (AssemblyDefinition assembly)
565                 {
566                         if (index_assemblies.SelectSingleNode ("Assembly[@Name='" + assembly.Name.Name + "']") != null)
567                                 return;
568
569                         app.AddIndexAssembly (assembly, index_assemblies);
570                 }
571
572                 public void Add (TypeDefinition type)
573                 {
574                         app.AddIndexType (type, index_types);
575                 }
576
577                 public void Write ()
578                 {
579                         SortIndexEntries (index_types);
580                         WriteFile (indexFile, FileMode.Create, 
581                                         writer => WriteXml (index.DocumentElement, writer));
582                 }
583         }
584
585         IndexForTypes CreateIndexForTypes (string dest)
586         {
587                 string indexFile = Path.Combine (dest, "index.xml");
588                 if (File.Exists (indexFile))
589                         return null;
590                 return new IndexForTypes (this, indexFile, CreateIndexStub ());
591         }
592
593         /// <summary>Constructs the presumed path to the type's documentation file</summary>
594         /// <returns><c>true</c>, if the type file was found, <c>false</c> otherwise.</returns>
595         /// <param name="result">A typle that contains 1) the 'reltypefile', 2) the 'typefile', and 3) the file info</param>
596         bool TryFindTypeFile(string nsname, string typename, string basepath, out Tuple<string, string, FileInfo> result) {
597                 string reltypefile = DocUtils.PathCombine (nsname, typename + ".xml");
598                 string typefile = Path.Combine (basepath, reltypefile);
599                 System.IO.FileInfo file = new System.IO.FileInfo(typefile);
600
601                 result = new Tuple<string, string, FileInfo> (reltypefile, typefile, file);
602
603                 return file.Exists;
604         }
605         
606         public string DoUpdateType (TypeDefinition type, string basepath, string dest)
607         {
608                 if (type.Namespace == null)
609                         Warning ("warning: The type `{0}' is in the root namespace.  This may cause problems with display within monodoc.",
610                                         type.FullName);
611                 if (!IsPublic (type))
612                         return null;
613                 
614                 // Must get the A+B form of the type name.
615                 string typename = GetTypeFileName(type);
616                 string nsname = DocUtils.GetNamespace (type);
617
618                 // Find the file, if it exists
619                 string[] searchLocations = new string[] {
620                         nsname
621                 };
622
623                 if (MDocUpdater.HasDroppedNamespace (type)) {
624                         // If dropping namespace, types may have moved into a couple of different places.
625                         var newSearchLocations = searchLocations.Union (new string[] {
626                                 string.Format ("{0}.{1}", droppedNamespace, nsname),
627                                 nsname.Replace (droppedNamespace + ".", string.Empty),
628                                 MDocUpdater.droppedNamespace
629                         });
630
631                         searchLocations = newSearchLocations.ToArray ();
632                 }
633
634                 string reltypefile="", typefile="";
635                 System.IO.FileInfo file = null;
636
637                 foreach (var f in searchLocations) {
638                         Tuple<string, string, FileInfo> result;
639                         bool fileExists = TryFindTypeFile (f, typename, basepath, out result);
640
641                         if (fileExists) {
642                                 reltypefile = result.Item1;
643                                 typefile = result.Item2;
644                                 file = result.Item3;
645
646                                 break;
647                         }
648                 }
649
650                 if (file == null || !file.Exists) {
651                         // we were not able to find a file, let's use the original type informatio.
652                         // so that we create the stub in the right place.
653                         Tuple<string, string, FileInfo> result;
654                         TryFindTypeFile (nsname, typename, basepath, out result);
655
656                         reltypefile = result.Item1;
657                         typefile = result.Item2;
658                         file = result.Item3;
659                 }
660                 
661                 string output = null;
662                 if (dest == null) {
663                         output = typefile;
664                 } else if (dest == "-") {
665                         output = null;
666                 } else {
667                         output = Path.Combine (dest, reltypefile);
668                 }       
669
670                 if (file != null && file.Exists) {
671                         // Update
672                         XmlDocument basefile = new XmlDocument();
673                         try {
674                                 basefile.Load(typefile);
675                         } catch (Exception e) {
676                                 throw new InvalidOperationException("Error loading " + typefile + ": " + e.Message, e);
677                         }
678                         
679                         DoUpdateType2("Updating", basefile, type, output, false);
680                 } else {
681                         // Stub
682                         XmlElement td = StubType(type, output);
683                         if (td == null)
684                                 return null;
685                 }
686                 return reltypefile;
687         }
688
689         public void DoUpdateNS (string ns, string nspath, string outpath)
690         {
691                 Dictionary<TypeDefinition, object> seenTypes = new Dictionary<TypeDefinition,object> ();
692                 AssemblyDefinition                  assembly = assemblies [0];
693
694                 foreach (System.IO.FileInfo file in new System.IO.DirectoryInfo(nspath).GetFiles("*.xml")) {
695                         XmlDocument basefile = new XmlDocument();
696                         string typefile = Path.Combine(nspath, file.Name);
697                         try {
698                                 basefile.Load(typefile);
699                         } catch (Exception e) {
700                                 throw new InvalidOperationException("Error loading " + typefile + ": " + e.Message, e);
701                         }
702
703                         string typename = 
704                                 GetTypeFileName (basefile.SelectSingleNode("Type/@FullName").InnerText);
705                         TypeDefinition type = assembly.GetType(typename);
706                         if (type == null) {
707                                         // --
708                                         if (!string.IsNullOrWhiteSpace (droppedNamespace)) {
709                                                 string nameWithNs = string.Format ("{0}.{1}", droppedNamespace, typename);
710                                                 type = assembly.GetType (nameWithNs);
711                                                 if (type == null) {
712                                                         Warning ("Type no longer in assembly: " + typename);
713                                                         continue;
714                                                 }
715                                         }
716                                         //--
717                         }                       
718
719                         seenTypes[type] = seenTypes;
720                         DoUpdateType2("Updating", basefile, type, Path.Combine(outpath, file.Name), false);
721                 }
722                 
723                 // Stub types not in the directory
724                 foreach (TypeDefinition type in docEnum.GetDocumentationTypes (assembly, null)) {
725                         if (type.Namespace != ns || seenTypes.ContainsKey(type))
726                                 continue;
727
728                         XmlElement td = StubType(type, Path.Combine(outpath, GetTypeFileName(type) + ".xml"));
729                         if (td == null) continue;
730                 }
731         }
732         
733         private static string GetTypeFileName (TypeReference type)
734         {
735                 return filenameFormatter.GetName (type);
736         }
737
738         public static string GetTypeFileName (string typename)
739         {
740                 StringBuilder filename = new StringBuilder (typename.Length);
741                 int numArgs = 0;
742                 int numLt = 0;
743                 bool copy = true;
744                 for (int i = 0; i < typename.Length; ++i) {
745                         char c = typename [i];
746                         switch (c) {
747                                 case '<':
748                                         copy = false;
749                                         ++numLt;
750                                         break;
751                                 case '>':
752                                         --numLt;
753                                         if (numLt == 0) {
754                                                 filename.Append ('`').Append ((numArgs+1).ToString());
755                                                 numArgs = 0;
756                                                 copy = true;
757                                         }
758                                         break;
759                                 case ',':
760                                         if (numLt == 1)
761                                                 ++numArgs;
762                                         break;
763                                 default:
764                                         if (copy)
765                                                 filename.Append (c);
766                                         break;
767                         }
768                 }
769                 return filename.ToString ();
770         }
771
772         private void AddIndexAssembly (AssemblyDefinition assembly, XmlElement parent)
773         {
774                 XmlElement index_assembly = null;
775                 if (multiassembly) 
776                         index_assembly = (XmlElement)parent.SelectSingleNode ("Assembly[@Name='"+ assembly.Name.Name +"']");
777                 
778                 if (index_assembly == null) 
779                         index_assembly = parent.OwnerDocument.CreateElement ("Assembly");
780
781                 index_assembly.SetAttribute ("Name", assembly.Name.Name);
782                 index_assembly.SetAttribute ("Version", assembly.Name.Version.ToString());
783
784                 AssemblyNameDefinition name = assembly.Name;
785                 if (name.HasPublicKey) {
786                         XmlElement pubkey = parent.OwnerDocument.CreateElement ("AssemblyPublicKey");
787                         var key = new StringBuilder (name.PublicKey.Length*3 + 2);
788                         key.Append ("[");
789                         foreach (byte b in name.PublicKey)
790                                 key.AppendFormat ("{0,2:x2} ", b);
791                         key.Append ("]");
792                         pubkey.InnerText = key.ToString ();
793                         index_assembly.AppendChild (pubkey);
794                 }
795
796                 if (!string.IsNullOrEmpty (name.Culture)) {
797                         XmlElement culture = parent.OwnerDocument.CreateElement ("AssemblyCulture");
798                         culture.InnerText = name.Culture;
799                         index_assembly.AppendChild (culture);
800                 }
801
802                 MakeAttributes (index_assembly, GetCustomAttributes (assembly.CustomAttributes, ""));
803                 parent.AppendChild(index_assembly);
804         }
805
806         private void AddIndexType (TypeDefinition type, XmlElement index_types)
807         {
808                 string typename = GetTypeFileName(type);
809
810                 // Add namespace and type nodes into the index file as needed
811                 string ns = DocUtils.GetNamespace (type);
812                 XmlElement nsnode = (XmlElement) index_types.SelectSingleNode ("Namespace[@Name='" + ns + "']");
813                 if (nsnode == null) {
814                         nsnode = index_types.OwnerDocument.CreateElement("Namespace");
815                         nsnode.SetAttribute ("Name", ns);
816                         index_types.AppendChild (nsnode);
817                 }
818                 string doc_typename = GetDocTypeName (type);
819                 XmlElement typenode = (XmlElement) nsnode.SelectSingleNode ("Type[@Name='" + typename + "']");
820                 if (typenode == null) {
821                         typenode = index_types.OwnerDocument.CreateElement ("Type");
822                         typenode.SetAttribute ("Name", typename);
823                         nsnode.AppendChild (typenode);
824                 }
825                 if (typename != doc_typename)
826                         typenode.SetAttribute("DisplayName", doc_typename);
827                 else
828                         typenode.RemoveAttribute("DisplayName");
829
830                 typenode.SetAttribute ("Kind", GetTypeKind (type));
831         }
832
833         private void DoUpdateAssemblies (string source, string dest) 
834         {
835                 string indexfile = dest + "/index.xml";
836                 XmlDocument index;
837                 if (System.IO.File.Exists(indexfile)) {
838                         index = new XmlDocument();
839                         index.Load(indexfile);
840
841                         // Format change
842                         ClearElement(index.DocumentElement, "Assembly");
843                         ClearElement(index.DocumentElement, "Attributes");
844                 } else {
845                         index = CreateIndexStub();
846                 }
847                 
848                 string defaultTitle = "Untitled";
849                 if (assemblies.Count == 1)
850                         defaultTitle = assemblies[0].Name.Name;
851                 WriteElementInitialText(index.DocumentElement, "Title", defaultTitle);
852                 
853                 XmlElement index_types = WriteElement(index.DocumentElement, "Types");
854                 XmlElement index_assemblies = WriteElement(index.DocumentElement, "Assemblies");
855                 if (!multiassembly) 
856                         index_assemblies.RemoveAll ();
857
858
859                 HashSet<string> goodfiles = new HashSet<string> (StringComparer.OrdinalIgnoreCase);
860
861                 foreach (AssemblyDefinition assm in assemblies) {
862                         AddIndexAssembly (assm, index_assemblies);
863                         DoUpdateAssembly (assm, index_types, source, dest, goodfiles);
864                 }
865
866                 SortIndexEntries (index_types);
867                 
868                 CleanupFiles (dest, goodfiles);
869                 CleanupIndexTypes (index_types, goodfiles);
870                 CleanupExtensions (index_types);
871
872                 WriteFile (indexfile, FileMode.Create, 
873                                 writer => WriteXml(index.DocumentElement, writer));
874         }
875                 
876         private static char[] InvalidFilenameChars = {'\\', '/', ':', '*', '?', '"', '<', '>', '|'};
877
878         private void DoUpdateAssembly (AssemblyDefinition assembly, XmlElement index_types, string source, string dest, HashSet<string> goodfiles) 
879         {
880                 foreach (TypeDefinition type in docEnum.GetDocumentationTypes (assembly, null)) {
881                         string typename = GetTypeFileName(type);
882                         if (!IsPublic (type) || typename.IndexOfAny (InvalidFilenameChars) >= 0 || forwardedTypes.Contains (type.FullName))
883                                 continue;
884
885                         string reltypepath = DoUpdateType (type, source, dest);
886                         if (reltypepath == null)
887                                 continue;
888                         
889                         // Add namespace and type nodes into the index file as needed
890                         AddIndexType (type, index_types);
891
892                         // Ensure the namespace index file exists
893                         string namespaceToUse = type.Namespace;
894                         if (HasDroppedNamespace(assembly)) {
895                                 namespaceToUse = string.Format ("{0}.{1}", droppedNamespace, namespaceToUse);
896                         }
897                         string onsdoc = DocUtils.PathCombine (dest, namespaceToUse + ".xml");
898                         string nsdoc  = DocUtils.PathCombine (dest, "ns-" + namespaceToUse + ".xml");
899                         if (File.Exists (onsdoc)) {
900                                 File.Move (onsdoc, nsdoc);
901                         }
902
903                         if (!File.Exists (nsdoc)) {
904                                 Console.WriteLine("New Namespace File: " + type.Namespace);
905                                 WriteNamespaceStub(namespaceToUse, dest);
906                         }
907
908                         goodfiles.Add (reltypepath);
909                 }
910         }
911
912         private static void SortIndexEntries (XmlElement indexTypes)
913         {
914                 XmlNodeList namespaces = indexTypes.SelectNodes ("Namespace");
915                 XmlNodeComparer c = new AttributeNameComparer ();
916                 SortXmlNodes (indexTypes, namespaces, c);
917
918                 for (int i = 0; i < namespaces.Count; ++i)
919                         SortXmlNodes (namespaces [i], namespaces [i].SelectNodes ("Type"), c);
920         }
921
922         private static void SortXmlNodes (XmlNode parent, XmlNodeList children, XmlNodeComparer comparer)
923         {
924                 MyXmlNodeList l = new MyXmlNodeList (children.Count);
925                 for (int i = 0; i < children.Count; ++i)
926                         l.Add (children [i]);
927                 l.Sort (comparer);
928                 for (int i = l.Count - 1; i > 0; --i) {
929                         parent.InsertBefore (parent.RemoveChild ((XmlNode) l [i-1]), (XmlNode) l [i]);
930                 }
931         }
932
933         abstract class XmlNodeComparer : IComparer, IComparer<XmlNode>
934         {
935                 public abstract int Compare (XmlNode x, XmlNode y);
936
937                 public int Compare (object x, object y)
938                 {
939                         return Compare ((XmlNode) x, (XmlNode) y);
940                 }
941         }
942
943         class AttributeNameComparer : XmlNodeComparer {
944                 string attribute;
945
946                 public AttributeNameComparer ()
947                         : this ("Name")
948                 {
949                 }
950
951                 public AttributeNameComparer (string attribute)
952                 {
953                         this.attribute = attribute;
954                 }
955
956                 public override int Compare (XmlNode x, XmlNode y)
957                 {
958                         return x.Attributes [attribute].Value.CompareTo (y.Attributes [attribute].Value);
959                 }
960         }
961         
962         class VersionComparer : XmlNodeComparer {
963                 public override int Compare (XmlNode x, XmlNode y)
964                 {
965                         // Some of the existing docs use e.g. 1.0.x.x, which Version doesn't like.
966                         string a = GetVersion (x.InnerText);
967                         string b = GetVersion (y.InnerText);
968                         return new Version (a).CompareTo (new Version (b));
969                 }
970
971                 static string GetVersion (string v)
972                 {
973                         int n = v.IndexOf ("x");
974                         if (n < 0)
975                                 return v;
976                         return v.Substring (0, n-1);
977                 }
978         }
979
980         private static string GetTypeKind (TypeDefinition type)
981         {
982                 if (type.IsEnum)
983                         return "Enumeration";
984                 if (type.IsValueType)
985                         return "Structure";
986                 if (type.IsInterface)
987                         return "Interface";
988                 if (DocUtils.IsDelegate (type))
989                         return "Delegate";
990                 if (type.IsClass || type.FullName == "System.Enum") // FIXME
991                         return "Class";
992                 throw new ArgumentException ("Unknown kind for type: " + type.FullName);
993         }
994
995         public static bool IsPublic (TypeDefinition type)
996         {
997                 TypeDefinition decl = type;
998                 while (decl != null) {
999                         if (!(decl.IsPublic || decl.IsNestedPublic ||
1000                                                 decl.IsNestedFamily || decl.IsNestedFamily || decl.IsNestedFamilyOrAssembly)) {
1001                                 return false;
1002                         }
1003                         decl = (TypeDefinition) decl.DeclaringType;
1004                 }
1005                 return true;
1006         }
1007
1008         private void CleanupFiles (string dest, HashSet<string> goodfiles)
1009         {
1010                 // Look for files that no longer correspond to types
1011                 foreach (System.IO.DirectoryInfo nsdir in new System.IO.DirectoryInfo(dest).GetDirectories("*")) {
1012                         foreach (System.IO.FileInfo typefile in nsdir.GetFiles("*.xml")) {
1013                                 string relTypeFile = Path.Combine(nsdir.Name, typefile.Name);
1014                                 if (!goodfiles.Contains (relTypeFile)) {
1015                                         XmlDocument doc = new XmlDocument ();
1016                                         doc.Load (typefile.FullName);
1017                                         XmlElement e = doc.SelectSingleNode("/Type") as XmlElement;
1018                                         string assemblyName = doc.SelectSingleNode ("/Type/AssemblyInfo/AssemblyName").InnerText;
1019                                         AssemblyDefinition assembly = assemblies.FirstOrDefault (a => a.Name.Name == assemblyName);
1020
1021                                         Action saveDoc = () => {
1022                                                 using (TextWriter writer = OpenWrite (typefile.FullName, FileMode.Truncate))
1023                                                         WriteXml(doc.DocumentElement, writer);
1024                                         };
1025
1026                                         if (e != null && !no_assembly_versions && assembly != null && assemblyName != null && UpdateAssemblyVersions (e, assembly, GetAssemblyVersions(assemblyName), false)) {
1027                                                 saveDoc ();
1028                                                 goodfiles.Add (relTypeFile);
1029                                                 continue;
1030                                         }
1031
1032                                         Action actuallyDelete = () => {
1033                                                 string newname = typefile.FullName + ".remove";
1034                                                 try { System.IO.File.Delete (newname); } catch (Exception) { Warning ("Unable to delete existing file: {0}", newname); }
1035                                                 try { typefile.MoveTo (newname); } catch (Exception) { Warning ("Unable to rename to: {0}", newname); }
1036                                                 Console.WriteLine ("Class no longer present; file renamed: " + Path.Combine (nsdir.Name, typefile.Name));
1037                                         };
1038
1039                                         if (string.IsNullOrWhiteSpace (PreserveTag)) { // only do this if there was not a -preserve
1040                                                 saveDoc ();
1041
1042                                                 var unifiedAssemblyNode = doc.SelectSingleNode ("/Type/AssemblyInfo[@apistyle='unified']");
1043                                                 var classicAssemblyNode = doc.SelectSingleNode ("/Type/AssemblyInfo[@apistyle='classic']");
1044                                                 var unifiedMembers = doc.SelectNodes ("//Member[@apistyle='unified']|//Member/AssemblyInfo[@apistyle='unified']");
1045                                                 var classicMembers = doc.SelectNodes ("//Member[@apistyle='classic']|//Member/AssemblyInfo[@apistyle='classic']");
1046                                                 bool isUnifiedRun = HasDroppedAnyNamespace ();
1047                                                 bool isClassicOrNormalRun = !isUnifiedRun;
1048
1049                                                 Action<XmlNode, ApiStyle> removeStyles = (x, style) => {
1050                                                         var styledNodes = doc.SelectNodes("//*[@apistyle='"+ style.ToString ().ToLowerInvariant () +"']");
1051                                                         if (styledNodes != null && styledNodes.Count > 0) {
1052                                                                 foreach(var node in styledNodes.Cast<XmlNode> ()) {
1053                                                                         node.ParentNode.RemoveChild (node);
1054                                                                 }
1055                                                         }
1056                                                         saveDoc ();
1057                                                 };
1058                                                 if (isClassicOrNormalRun) {
1059                                                         if (unifiedAssemblyNode != null || unifiedMembers.Count > 0) {
1060                                                                 Warning ("*** this type is marked as unified, not deleting during this run: {0}", typefile.FullName);
1061                                                                 // if truly removed from both assemblies, it will be removed fully during the unified run
1062                                                                 removeStyles (doc, ApiStyle.Classic);
1063                                                                 continue;
1064                                                         } else {
1065                                                                 // we should be safe to delete here because it was not marked as a unified assembly
1066                                                                 actuallyDelete ();
1067                                                         }
1068                                                 }
1069                                                 if (isUnifiedRun) {
1070                                                         if (classicAssemblyNode != null || classicMembers.Count > 0) {
1071                                                                 Warning ("*** this type is marked as classic, not deleting {0}", typefile.FullName);
1072                                                                 continue; 
1073                                                         } else {
1074                                                                 // safe to delete because it wasn't marked as a classic assembly, so the type is gone in both.
1075                                                                 actuallyDelete ();
1076                                                         }
1077                                                 }
1078                                         }
1079                                 }
1080                         }
1081                 }
1082         }
1083
1084         private static TextWriter OpenWrite (string path, FileMode mode)
1085         {
1086                 var w = new StreamWriter (
1087                         new FileStream (path, mode),
1088                         new UTF8Encoding (false)
1089                 );
1090                 w.NewLine = "\n";
1091                 return w;
1092         }
1093
1094         private string[] GetAssemblyVersions (string assemblyName)
1095         {
1096                 return (from a in assemblies 
1097                         where a.Name.Name == assemblyName 
1098                         select GetAssemblyVersion (a)).ToArray ();
1099         }
1100
1101         private static void CleanupIndexTypes (XmlElement index_types, HashSet<string> goodfiles)
1102         {
1103                 // Look for type nodes that no longer correspond to types
1104                 MyXmlNodeList remove = new MyXmlNodeList ();
1105                 foreach (XmlElement typenode in index_types.SelectNodes("Namespace/Type")) {
1106                         string fulltypename = Path.Combine (((XmlElement)typenode.ParentNode).GetAttribute("Name"), typenode.GetAttribute("Name") + ".xml");
1107                         if (!goodfiles.Contains (fulltypename)) {
1108                                 remove.Add (typenode);
1109                         }
1110                 }
1111                 foreach (XmlNode n in remove)
1112                         n.ParentNode.RemoveChild (n);
1113         }
1114
1115         private void CleanupExtensions (XmlElement index_types)
1116         {
1117                 XmlNode e = index_types.SelectSingleNode ("/Overview/ExtensionMethods");
1118                 if (extensionMethods.Count == 0) {
1119                         if (e == null)
1120                                 return;
1121                         index_types.SelectSingleNode ("/Overview").RemoveChild (e);
1122                         return;
1123                 }
1124                 if (e == null) {
1125                         e = index_types.OwnerDocument.CreateElement ("ExtensionMethods");
1126                         index_types.SelectSingleNode ("/Overview").AppendChild (e);
1127                 }
1128                 else
1129                         e.RemoveAll ();
1130                 extensionMethods.Sort (DefaultExtensionMethodComparer);
1131                 foreach (XmlNode m in extensionMethods) {
1132                         e.AppendChild (index_types.OwnerDocument.ImportNode (m, true));
1133                 }
1134         }
1135
1136         class ExtensionMethodComparer : XmlNodeComparer {
1137                 public override int Compare (XmlNode x, XmlNode y)
1138                 {
1139                         XmlNode xLink = x.SelectSingleNode ("Member/Link");
1140                         XmlNode yLink = y.SelectSingleNode ("Member/Link");
1141
1142                         int n = xLink.Attributes ["Type"].Value.CompareTo (
1143                                         yLink.Attributes ["Type"].Value);
1144                         if (n != 0)
1145                                 return n;
1146                         n = xLink.Attributes ["Member"].Value.CompareTo (
1147                                         yLink.Attributes ["Member"].Value);
1148                         if (n == 0 && !object.ReferenceEquals (x, y))
1149                                 throw new InvalidOperationException ("Duplicate extension method found!");
1150                         return n;
1151                 }
1152         }
1153
1154         static readonly XmlNodeComparer DefaultExtensionMethodComparer = new ExtensionMethodComparer ();
1155                 
1156         public void DoUpdateType2 (string message, XmlDocument basefile, TypeDefinition type, string output, bool insertSince)
1157         {
1158                 Console.WriteLine(message + ": " + type.FullName);
1159                 
1160                 StringToXmlNodeMap seenmembers = new StringToXmlNodeMap ();
1161
1162                 // Update type metadata
1163                 UpdateType(basefile.DocumentElement, type);
1164
1165                 // Update existing members.  Delete member nodes that no longer should be there,
1166                 // and remember what members are already documented so we don't add them again.
1167                 
1168                 MyXmlNodeList todelete = new MyXmlNodeList ();
1169                 
1170                 foreach (DocsNodeInfo info in docEnum.GetDocumentationMembers (basefile, type)) {
1171                         XmlElement oldmember  = info.Node;
1172                         MemberReference oldmember2 = info.Member;
1173
1174                         if (info.Member != null &&  info.Node != null) {
1175                                 // Check for an error condition where the xml MemberName doesn't match the matched member
1176                                 var memberName = GetMemberName (info.Member);
1177                                 var memberAttribute = info.Node.Attributes ["MemberName"];
1178                                 if (memberAttribute == null || (memberAttribute.Value != memberName && memberAttribute.Value.Split (',').Length != memberName.Split (',').Length)) {
1179                                         oldmember.SetAttribute ("MemberName", memberName);
1180                                 }
1181                         }
1182
1183                         string sig = oldmember2 != null ? memberFormatters [0].GetDeclaration (oldmember2) : null;
1184                         
1185                         // Interface implementations and overrides are deleted from the docs
1186                         // unless the overrides option is given.
1187                         if (oldmember2 != null && sig == null)
1188                                 oldmember2 = null;
1189                         
1190                         // Deleted (or signature changed)
1191                         if (oldmember2 == null) {
1192                                 if (!no_assembly_versions && UpdateAssemblyVersions (oldmember, type.Module.Assembly, new string[]{ GetAssemblyVersion (type.Module.Assembly) }, false))
1193                                         continue;
1194
1195                                 DeleteMember ("Member Removed", output, oldmember, todelete, type);
1196                                 continue;
1197                         }
1198                         
1199                         // Duplicated
1200                         if (seenmembers.ContainsKey (sig)) {
1201                                 if (object.ReferenceEquals (oldmember, seenmembers [sig])) {
1202                                         // ignore, already seen
1203                                 }
1204                                 else if (DefaultMemberComparer.Compare (oldmember, seenmembers [sig]) == 0)
1205                                         DeleteMember ("Duplicate Member Found", output, oldmember, todelete, type);
1206                                 else
1207                                         Warning ("TODO: found a duplicate member '{0}', but it's not identical to the prior member found!", sig);
1208                                 continue;
1209                         }
1210                         
1211                         // Update signature information
1212                         UpdateMember(info);
1213
1214                         // get all apistyles of sig from info.Node
1215                         var styles = oldmember.GetElementsByTagName ("MemberSignature").Cast<XmlElement> ()
1216                                 .Where (x => x.GetAttribute ("Language") == "C#" && !seenmembers.ContainsKey(x.GetAttribute("Value")))
1217                                 .Select (x => x.GetAttribute ("Value"));
1218
1219                         foreach (var stylesig in styles) {
1220                                 seenmembers.Add (stylesig, oldmember);
1221                         }
1222                 }
1223                 foreach (XmlElement oldmember in todelete)
1224                         oldmember.ParentNode.RemoveChild (oldmember);
1225                 
1226                 
1227                 if (!DocUtils.IsDelegate (type)) {
1228                         XmlNode members = WriteElement (basefile.DocumentElement, "Members");
1229                         var typemembers = type.GetMembers()
1230                                         .Where(m => {
1231                                                 if (m is TypeDefinition) return false;
1232                                                 string sig = memberFormatters [0].GetDeclaration (m);
1233                                                 if (sig == null) return false;
1234                                                 if (seenmembers.ContainsKey(sig)) return false;
1235
1236                                                 // Verify that the member isn't an explicitly implemented 
1237                                                 // member of an internal interface, in which case we shouldn't return true.
1238                                                 MethodDefinition methdef = null;
1239                                                 if (m is MethodDefinition) 
1240                                                         methdef = m as MethodDefinition;
1241                                                 else if (m is PropertyDefinition) {
1242                                                         var prop = m as PropertyDefinition;
1243                                                         methdef = prop.GetMethod ?? prop.SetMethod;
1244                                                 }
1245
1246                                                 if (methdef != null) {
1247                                                         TypeReference iface;
1248                                                         MethodReference imethod;
1249
1250                                                         if (methdef.Overrides.Count == 1) {
1251                                                                 DocUtils.GetInfoForExplicitlyImplementedMethod (methdef, out iface, out imethod);
1252                                                                 if (!IsPublic (iface.Resolve ())) return false;
1253                                                         }
1254                                                 }
1255
1256                                                 return true;
1257                                         })
1258                                         .ToArray();
1259                         foreach (MemberReference m in typemembers) {
1260                                 XmlElement mm = MakeMember(basefile, new DocsNodeInfo (null, m));
1261                                 if (mm == null) continue;
1262
1263                                 if (MDocUpdater.SwitchingToMagicTypes) {
1264                                         // this is a unified style API that obviously doesn't exist in the classic API. Let's mark
1265                                         // it with apistyle="unified", so that it's not displayed for classic style APIs
1266                                         mm.SetAttribute ("apistyle", "unified");
1267                                 }
1268
1269                                 members.AppendChild( mm );
1270         
1271                                 Console.WriteLine("Member Added: " + mm.SelectSingleNode("MemberSignature/@Value").InnerText);
1272                                 additions++;
1273                         }
1274                 }
1275                 
1276                 // Import code snippets from files
1277                 foreach (XmlNode code in basefile.GetElementsByTagName("code")) {
1278                         if (!(code is XmlElement)) continue;
1279                         string file = ((XmlElement)code).GetAttribute("src");
1280                         string lang = ((XmlElement)code).GetAttribute("lang");
1281                         if (file != "") {
1282                                 string src = GetCodeSource (lang, Path.Combine (srcPath, file));
1283                                 if (src != null)
1284                                         code.InnerText = src;
1285                         }
1286                 }
1287
1288                 if (insertSince && since != null) {
1289                         XmlNode docs = basefile.DocumentElement.SelectSingleNode("Docs");
1290                         docs.AppendChild (CreateSinceNode (basefile));
1291                 }
1292
1293                 do {
1294                         XmlElement d = basefile.DocumentElement ["Docs"];
1295                         XmlElement m = basefile.DocumentElement ["Members"];
1296                         if (d != null && m != null)
1297                                 basefile.DocumentElement.InsertBefore (
1298                                                 basefile.DocumentElement.RemoveChild (d), m);
1299                         SortTypeMembers (m);
1300                 } while (false);
1301
1302                 if (output == null)
1303                         WriteXml(basefile.DocumentElement, Console.Out);
1304                 else {
1305                         FileInfo file = new FileInfo (output);
1306                         if (!file.Directory.Exists) {
1307                                 Console.WriteLine("Namespace Directory Created: " + type.Namespace);
1308                                 file.Directory.Create ();
1309                         }
1310                         WriteFile (output, FileMode.Create,
1311                                         writer => WriteXml(basefile.DocumentElement, writer));
1312                 }
1313         }
1314
1315         private string GetCodeSource (string lang, string file)
1316         {
1317                 int anchorStart;
1318                 if (lang == "C#" && (anchorStart = file.IndexOf (".cs#")) >= 0) {
1319                         // Grab the specified region
1320                         string region = "#region " + file.Substring (anchorStart + 4);
1321                         file          = file.Substring (0, anchorStart + 3);
1322                         try {
1323                                 using (StreamReader reader = new StreamReader (file)) {
1324                                         string line;
1325                                         StringBuilder src = new StringBuilder ();
1326                                         int indent = -1;
1327                                         while ((line = reader.ReadLine ()) != null) {
1328                                                 if (line.Trim() == region) {
1329                                                         indent = line.IndexOf (region);
1330                                                         continue;
1331                                                 }
1332                                                 if (indent >= 0 && line.Trim().StartsWith ("#endregion")) {
1333                                                         break;
1334                                                 }
1335                                                 if (indent >= 0)
1336                                                         src.Append (
1337                                                                         (line.Length > 0 ? line.Substring (indent) : string.Empty) +
1338                                                                         "\n");
1339                                         }
1340                                         return src.ToString ();
1341                                 }
1342                         } catch (Exception e) {
1343                                 Warning ("Could not load <code/> file '{0}' region '{1}': {2}",
1344                                                 file, region, show_exceptions ? e.ToString () : e.Message);
1345                                 return null;
1346                         }
1347                 }
1348                 try {
1349                         using (StreamReader reader = new StreamReader (file))
1350                                 return reader.ReadToEnd ();
1351                 } catch (Exception e) {
1352                         Warning ("Could not load <code/> file '" + file + "': " + e.Message);
1353                 }
1354                 return null;
1355         }
1356
1357         void DeleteMember (string reason, string output, XmlNode member, MyXmlNodeList todelete, TypeDefinition type)
1358         {
1359                 string format = output != null
1360                         ? "{0}: File='{1}'; Signature='{4}'"
1361                         : "{0}: XPath='/Type[@FullName=\"{2}\"]/Members/Member[@MemberName=\"{3}\"]'; Signature='{4}'";
1362                 string signature = member.SelectSingleNode ("MemberSignature[@Language='C#']/@Value").Value;
1363                 Warning (format,
1364                                 reason, 
1365                                 output,
1366                                 member.OwnerDocument.DocumentElement.GetAttribute ("FullName"),
1367                                 member.Attributes ["MemberName"].Value, 
1368                                 signature);
1369
1370                 // Identify all of the different states that could affect our decision to delete the member
1371                 bool shouldPreserve = !string.IsNullOrWhiteSpace (PreserveTag);
1372                 bool hasContent = MemberDocsHaveUserContent (member);
1373                 bool shouldDelete = !shouldPreserve && (delete || !hasContent);
1374
1375                 bool unifiedRun = HasDroppedNamespace (type);
1376
1377                 var classicAssemblyInfo = member.SelectSingleNode ("AssemblyInfo[@apistyle='classic']");
1378                 bool nodeIsClassic = classicAssemblyInfo != null || member.HasApiStyle (ApiStyle.Classic);
1379                 var unifiedAssemblyInfo = member.SelectSingleNode ("AssemblyInfo[@apistyle='unified']");
1380                 bool nodeIsUnified = unifiedAssemblyInfo != null || member.HasApiStyle (ApiStyle.Unified);
1381
1382                 Action actuallyDelete = () => {
1383                         todelete.Add (member);
1384                         deletions++;
1385                 };
1386
1387                 if (!shouldDelete) {
1388                         // explicitly not deleting
1389                         string message = shouldPreserve ? 
1390                                         "Not deleting '{0}' due to --preserve." :
1391                                         "Not deleting '{0}'; must be enabled with the --delete option";
1392                         Warning (message, signature);
1393                 } else if (unifiedRun && nodeIsClassic) {
1394                         // this is a unified run, and the member doesn't exist, but is marked as being in the classic assembly.
1395                         member.RemoveApiStyle (ApiStyle.Unified);
1396                         Warning ("Not removing '{0}' since it's still in the classic assembly.", signature);
1397                 } else if (unifiedRun && !nodeIsClassic) {
1398                         // unified run, and the node is not classic, which means it doesn't exist anywhere.
1399                         actuallyDelete ();
1400                 } else { 
1401                         if (!nodeIsClassic && !nodeIsUnified) { // regular codepath (ie. not classic/unified)
1402                                 actuallyDelete ();
1403                         } else { // this is a classic run
1404                                 Warning ("Removing classic from '{0}' ... will be removed in the unified run if not present there.", signature);
1405                                 member.RemoveApiStyle (ApiStyle.Classic);
1406                                 if (classicAssemblyInfo != null) {
1407                                         member.RemoveChild (classicAssemblyInfo);
1408                                 }
1409                         }
1410                 }
1411         }
1412
1413         class MemberComparer : XmlNodeComparer {
1414                 public override int Compare (XmlNode x, XmlNode y)
1415                 {
1416                         int r;
1417                         string xMemberName = x.Attributes ["MemberName"].Value;
1418                         string yMemberName = y.Attributes ["MemberName"].Value;
1419
1420                         // generic methods *end* with '>'
1421                         // it's possible for explicitly implemented generic interfaces to
1422                         // contain <...> without being a generic method
1423                         if ((!xMemberName.EndsWith (">") || !yMemberName.EndsWith (">")) &&
1424                                         (r = xMemberName.CompareTo (yMemberName)) != 0)
1425                                 return r;
1426
1427                         int lt;
1428                         if ((lt = xMemberName.IndexOf ("<")) >= 0)
1429                                 xMemberName = xMemberName.Substring (0, lt);
1430                         if ((lt = yMemberName.IndexOf ("<")) >= 0)
1431                                 yMemberName = yMemberName.Substring (0, lt);
1432                         if ((r = xMemberName.CompareTo (yMemberName)) != 0)
1433                                 return r;
1434
1435                         // if @MemberName matches, then it's either two different types of
1436                         // members sharing the same name, e.g. field & property, or it's an
1437                         // overloaded method.
1438                         // for different type, sort based on MemberType value.
1439                         r = x.SelectSingleNode ("MemberType").InnerText.CompareTo (
1440                                         y.SelectSingleNode ("MemberType").InnerText);
1441                         if (r != 0)
1442                                 return r;
1443
1444                         // same type -- must be an overloaded method.  Sort based on type 
1445                         // parameter count, then parameter count, then by the parameter 
1446                         // type names.
1447                         XmlNodeList xTypeParams = x.SelectNodes ("TypeParameters/TypeParameter");
1448                         XmlNodeList yTypeParams = y.SelectNodes ("TypeParameters/TypeParameter");
1449                         if (xTypeParams.Count != yTypeParams.Count)
1450                                 return xTypeParams.Count <= yTypeParams.Count ? -1 : 1;
1451                         for (int i = 0; i < xTypeParams.Count; ++i) {
1452                                 r = xTypeParams [i].Attributes ["Name"].Value.CompareTo (
1453                                                 yTypeParams [i].Attributes ["Name"].Value);
1454                                 if (r != 0)
1455                                         return r;
1456                         }
1457
1458                         XmlNodeList xParams = x.SelectNodes ("Parameters/Parameter");
1459                         XmlNodeList yParams = y.SelectNodes ("Parameters/Parameter");
1460                         if (xParams.Count != yParams.Count)
1461                                 return xParams.Count <= yParams.Count ? -1 : 1;
1462                         for (int i = 0; i < xParams.Count; ++i) {
1463                                 r = xParams [i].Attributes ["Type"].Value.CompareTo (
1464                                                 yParams [i].Attributes ["Type"].Value);
1465                                 if (r != 0)
1466                                         return r;
1467                         }
1468                         // all parameters match, but return value might not match if it was
1469                         // changed between one version and another.
1470                         XmlNode xReturn = x.SelectSingleNode ("ReturnValue/ReturnType");
1471                         XmlNode yReturn = y.SelectSingleNode ("ReturnValue/ReturnType");
1472                         if (xReturn != null && yReturn != null) {
1473                                 r = xReturn.InnerText.CompareTo (yReturn.InnerText);
1474                                 if (r != 0)
1475                                         return r;
1476                         }
1477
1478                         return 0;
1479                 }
1480         }
1481
1482         static readonly MemberComparer DefaultMemberComparer = new MemberComparer ();
1483
1484         private static void SortTypeMembers (XmlNode members)
1485         {
1486                 if (members == null)
1487                         return;
1488                 SortXmlNodes (members, members.SelectNodes ("Member"), DefaultMemberComparer);
1489         }
1490         
1491         private static bool MemberDocsHaveUserContent (XmlNode e)
1492         {
1493                 e = (XmlElement)e.SelectSingleNode("Docs");
1494                 if (e == null) return false;
1495                 foreach (XmlElement d in e.SelectNodes("*"))
1496                         if (d.InnerText != "" && !d.InnerText.StartsWith("To be added"))
1497                                 return true;
1498                 return false;
1499         }
1500         
1501         // UPDATE HELPER FUNCTIONS
1502         
1503         // CREATE A STUB DOCUMENTATION FILE     
1504
1505         public XmlElement StubType (TypeDefinition type, string output)
1506         {
1507                 string typesig = typeFormatters [0].GetDeclaration (type);
1508                 if (typesig == null) return null; // not publicly visible
1509                 
1510                 XmlDocument doc = new XmlDocument();
1511                 XmlElement root = doc.CreateElement("Type");
1512                 doc.AppendChild (root);
1513
1514                 DoUpdateType2 ("New Type", doc, type, output, true);
1515                 
1516                 return root;
1517         }
1518
1519         private XmlElement CreateSinceNode (XmlDocument doc)
1520         {
1521                 XmlElement s = doc.CreateElement ("since");
1522                 s.SetAttribute ("version", since);
1523                 return s;
1524         }
1525         
1526         // STUBBING/UPDATING FUNCTIONS
1527         
1528         public void UpdateType (XmlElement root, TypeDefinition type)
1529         {
1530                 root.SetAttribute("Name", GetDocTypeName (type));
1531                 root.SetAttribute("FullName", GetDocTypeFullName (type));
1532
1533                 foreach (MemberFormatter f in typeFormatters) {
1534                         string element = "TypeSignature[@Language='" + f.Language + "']";
1535                         string valueToUse = f.GetDeclaration (type);
1536
1537                         AddXmlNode (
1538                                 root.SelectNodes (element).Cast<XmlElement> ().ToArray (), 
1539                                 x => x.GetAttribute ("Value") == valueToUse, 
1540                                 x => x.SetAttribute ("Value", valueToUse), 
1541                                 () => {
1542                                         var node = WriteElementAttribute (root, element, "Language", f.Language, forceNewElement: true);
1543                                         var newnode = WriteElementAttribute (root, node, "Value", valueToUse);
1544                                         return newnode;
1545                                 },
1546                                 type);
1547                 }
1548                 
1549                 AddAssemblyNameToNode (root, type);
1550
1551                 string assemblyInfoNodeFilter = MDocUpdater.HasDroppedNamespace (type) ? "[@apistyle='unified']" : "[not(@apistyle) or @apistyle='classic']";
1552                 Func<XmlElement, bool> assemblyFilter = x => x.SelectSingleNode ("AssemblyName").InnerText == type.Module.Assembly.Name.Name;
1553                 foreach(var ass in root.SelectNodes ("AssemblyInfo" + assemblyInfoNodeFilter).Cast<XmlElement> ().Where (assemblyFilter))
1554                 {
1555                         WriteElementText(ass, "AssemblyName", type.Module.Assembly.Name.Name);
1556                         if (!no_assembly_versions) {
1557                                 UpdateAssemblyVersions (ass, type, true);
1558                         }
1559                         else {
1560                                 var versions = ass.SelectNodes ("AssemblyVersion").Cast<XmlNode> ().ToList ();
1561                                 foreach (var version in versions)
1562                                         ass.RemoveChild (version);
1563                         }
1564                         if (!string.IsNullOrEmpty (type.Module.Assembly.Name.Culture))
1565                                 WriteElementText(ass, "AssemblyCulture", type.Module.Assembly.Name.Culture);
1566                         else
1567                                 ClearElement(ass, "AssemblyCulture");
1568
1569
1570                         // Why-oh-why do we put assembly attributes in each type file?
1571                         // Neither monodoc nor monodocs2html use them, so I'm deleting them
1572                         // since they're outdated in current docs, and a waste of space.
1573                         //MakeAttributes(ass, type.Assembly, true);
1574                         XmlNode assattrs = ass.SelectSingleNode("Attributes");
1575                         if (assattrs != null)
1576                                 ass.RemoveChild(assattrs);
1577
1578                         NormalizeWhitespace(ass);
1579                 }
1580                 
1581                 if (type.IsGenericType ()) {
1582                                 MakeTypeParameters (root, type.GenericParameters, type, MDocUpdater.HasDroppedNamespace(type));
1583                 } else {
1584                         ClearElement(root, "TypeParameters");
1585                 }
1586                 
1587                 if (type.BaseType != null) {
1588                         XmlElement basenode = WriteElement(root, "Base");
1589                         
1590                         string basetypename = GetDocTypeFullName (type.BaseType);
1591                         if (basetypename == "System.MulticastDelegate") basetypename = "System.Delegate";
1592                         WriteElementText(root, "Base/BaseTypeName", basetypename);
1593                         
1594                         // Document how this type instantiates the generic parameters of its base type
1595                         TypeReference origBase = type.BaseType.GetElementType ();
1596                         if (origBase.IsGenericType ()) {
1597                                 ClearElement(basenode, "BaseTypeArguments");
1598                                 GenericInstanceType baseInst             = type.BaseType as GenericInstanceType;
1599                                 IList<TypeReference> baseGenArgs    = baseInst == null ? null : baseInst.GenericArguments;
1600                                 IList<GenericParameter> baseGenParams = origBase.GenericParameters;
1601                                 if (baseGenArgs.Count != baseGenParams.Count)
1602                                         throw new InvalidOperationException ("internal error: number of generic arguments doesn't match number of generic parameters.");
1603                                 for (int i = 0; baseGenArgs != null && i < baseGenArgs.Count; i++) {
1604                                         GenericParameter param = baseGenParams [i];
1605                                         TypeReference    value = baseGenArgs [i];
1606
1607                                         XmlElement bta = WriteElement(basenode, "BaseTypeArguments");
1608                                         XmlElement arg = bta.OwnerDocument.CreateElement("BaseTypeArgument");
1609                                         bta.AppendChild(arg);
1610                                         arg.SetAttribute ("TypeParamName", param.Name);
1611                                         arg.InnerText = GetDocTypeFullName (value);
1612                                 }
1613                         }
1614                 } else {
1615                         ClearElement(root, "Base");
1616                 }
1617
1618                 if (!DocUtils.IsDelegate (type) && !type.IsEnum) {
1619                         IEnumerable<TypeReference> userInterfaces = DocUtils.GetUserImplementedInterfaces (type);
1620                         List<string> interface_names = userInterfaces
1621                                         .Select (iface => GetDocTypeFullName (iface))
1622                                         .OrderBy (s => s)
1623                                         .ToList ();
1624
1625                         XmlElement interfaces = WriteElement(root, "Interfaces");
1626                         interfaces.RemoveAll();
1627                         foreach (string iname in interface_names) {
1628                                 XmlElement iface = root.OwnerDocument.CreateElement("Interface");
1629                                 interfaces.AppendChild(iface);
1630                                 WriteElementText(iface, "InterfaceName", iname);
1631                         }
1632                 } else {
1633                         ClearElement(root, "Interfaces");
1634                 }
1635
1636                         MakeAttributes (root, GetCustomAttributes (type), type);
1637                 
1638                 if (DocUtils.IsDelegate (type)) {
1639                         MakeTypeParameters (root, type.GenericParameters, type, MDocUpdater.HasDroppedNamespace(type));
1640                         var member = type.GetMethod ("Invoke");
1641                         MakeParameters(root, member, member.Parameters);
1642                         MakeReturnValue(root, member);
1643                 }
1644                 
1645                 DocsNodeInfo typeInfo = new DocsNodeInfo (WriteElement(root, "Docs"), type);
1646                 MakeDocNode (typeInfo);
1647                 
1648                 if (!DocUtils.IsDelegate (type))
1649                         WriteElement (root, "Members");
1650
1651                 OrderTypeNodes (root, root.ChildNodes);
1652                 NormalizeWhitespace(root);
1653         }
1654
1655         /// <summary>Adds an AssemblyInfo with AssemblyName node to an XmlElement.</summary>
1656         /// <returns>The assembly that was either added, or was already present</returns>
1657         static XmlElement AddAssemblyNameToNode (XmlElement root, TypeDefinition type)
1658         {
1659                 return AddAssemblyNameToNode (root, type.Module);
1660         }
1661
1662         /// <summary>Adds an AssemblyInfo with AssemblyName node to an XmlElement.</summary>
1663         /// <returns>The assembly that was either added, or was already present</returns>
1664         static XmlElement AddAssemblyNameToNode (XmlElement root, ModuleDefinition module)
1665         {
1666                 Func<XmlElement, bool> assemblyFilter = x => {
1667                         var existingName = x.SelectSingleNode ("AssemblyName");
1668                         return existingName != null && existingName.InnerText == module.Assembly.Name.Name;
1669                 };
1670                 
1671                 return AddAssemblyXmlNode (
1672                         root.SelectNodes ("AssemblyInfo").Cast<XmlElement> ().ToArray (), 
1673                         assemblyFilter, x => WriteElementText (x, "AssemblyName", module.Assembly.Name.Name), 
1674                         () =>  {
1675                                 XmlElement ass = WriteElement (root, "AssemblyInfo", forceNewElement: true);
1676                                 if (MDocUpdater.HasDroppedNamespace (module))
1677                                         ass.SetAttribute ("apistyle", "unified");
1678                                 return ass;
1679                         }, module);
1680         }
1681
1682         static readonly string[] TypeNodeOrder = {
1683                 "TypeSignature",
1684                 "MemberOfLibrary",
1685                 "AssemblyInfo",
1686                 "ThreadingSafetyStatement",
1687                 "ThreadSafetyStatement",
1688                 "TypeParameters",
1689                 "Base",
1690                 "Interfaces",
1691                 "Attributes",
1692                 "Parameters",
1693                 "ReturnValue",
1694                 "Docs",
1695                 "Members",
1696                 "TypeExcluded",
1697         };
1698
1699         static void OrderTypeNodes (XmlNode member, XmlNodeList children)
1700         {
1701                 ReorderNodes (member, children, TypeNodeOrder);
1702         }
1703
1704         internal static IEnumerable<T> Sort<T> (IEnumerable<T> list)
1705         {
1706                 List<T> l = new List<T> (list);
1707                 l.Sort ();
1708                 return l;
1709         }
1710
1711         private void UpdateMember (DocsNodeInfo info)
1712         {
1713                 XmlElement me = (XmlElement) info.Node;
1714                 MemberReference mi = info.Member;
1715
1716                 foreach (MemberFormatter f in memberFormatters) {
1717                         string element = "MemberSignature[@Language='" + f.Language + "']";
1718
1719                         var valueToUse = f.GetDeclaration (mi);
1720
1721                         AddXmlNode (
1722                                 me.SelectNodes (element).Cast<XmlElement> ().ToArray(), 
1723                                 x => x.GetAttribute("Value") == valueToUse, 
1724                                 x => x.SetAttribute ("Value", valueToUse), 
1725                                 () => {
1726                                         var node = WriteElementAttribute (me, element, "Language", f.Language, forceNewElement:true);
1727                                         var newNode = WriteElementAttribute (me, node, "Value", valueToUse);
1728                                         return newNode;
1729                                 },
1730                                 mi);
1731
1732                 }
1733
1734                 WriteElementText(me, "MemberType", GetMemberType(mi));
1735
1736                 if (!no_assembly_versions) {
1737                         if (!multiassembly)
1738                                 UpdateAssemblyVersions (me, mi, true);
1739                         else {
1740                                 var node = AddAssemblyNameToNode (me, mi.Module);
1741
1742                                 UpdateAssemblyVersionForAssemblyInfo (node, me, new[] { GetAssemblyVersion (mi.Module.Assembly) }, add: true);
1743                         }
1744                 }
1745                 else {
1746                         ClearElement (me, "AssemblyInfo");
1747                 }
1748
1749                 MakeAttributes (me, GetCustomAttributes (mi), mi.DeclaringType);
1750
1751                 MakeReturnValue(me, mi, MDocUpdater.HasDroppedNamespace(mi));
1752                 if (mi is MethodReference) {
1753                         MethodReference mb = (MethodReference) mi;
1754                         if (mb.IsGenericMethod ())
1755                                         MakeTypeParameters (me, mb.GenericParameters, mi, MDocUpdater.HasDroppedNamespace(mi));
1756                 }
1757                 MakeParameters(me, mi, MDocUpdater.HasDroppedNamespace(mi));
1758                 
1759                 string fieldValue;
1760                 if (mi is FieldDefinition && GetFieldConstValue ((FieldDefinition)mi, out fieldValue))
1761                         WriteElementText(me, "MemberValue", fieldValue);
1762                 
1763                 info.Node = WriteElement (me, "Docs");
1764                 MakeDocNode (info);
1765                 OrderMemberNodes (me, me.ChildNodes);
1766                 UpdateExtensionMethods (me, info);
1767         }
1768
1769         static void AddXmlNode (XmlElement[] relevant, Func<XmlElement, bool> valueMatches, Action<XmlElement> setValue, Func<XmlElement> makeNewNode, MemberReference member) {
1770                 AddXmlNode (relevant, valueMatches, setValue, makeNewNode, member.Module);
1771         }
1772
1773         static void AddXmlNode (XmlElement[] relevant, Func<XmlElement, bool> valueMatches, Action<XmlElement> setValue, Func<XmlElement> makeNewNode, TypeDefinition type) {
1774                 AddXmlNode (relevant, valueMatches, setValue, makeNewNode, type.Module);
1775         }
1776
1777         static XmlElement AddAssemblyXmlNode (XmlElement[] relevant, Func<XmlElement, bool> valueMatches, Action<XmlElement> setValue, Func<XmlElement> makeNewNode, ModuleDefinition module)
1778         {
1779                 bool isUnified = MDocUpdater.HasDroppedNamespace (module);
1780                 XmlElement thisAssemblyNode = relevant.FirstOrDefault (valueMatches);
1781                 if (thisAssemblyNode == null) {
1782                         thisAssemblyNode = makeNewNode ();
1783                         setValue (thisAssemblyNode);
1784                 }
1785
1786                 if (isUnified) {
1787                         thisAssemblyNode.AddApiStyle (ApiStyle.Unified);
1788
1789                         foreach (var otherNodes in relevant.Where (n => n != thisAssemblyNode && n.DoesNotHaveApiStyle (ApiStyle.Unified))) {
1790                                 otherNodes.AddApiStyle (ApiStyle.Classic);
1791                         }
1792                 }
1793                 return thisAssemblyNode;
1794         }
1795
1796         /// <summary>Adds an xml node, reusing the node if it's available</summary>
1797         /// <param name="relevant">The existing set of nodes</param>
1798         /// <param name="valueMatches">Checks to see if the node's value matches what you're trying to write.</param>
1799         /// <param name="setValue">Sets the node's value</param>
1800         /// <param name="makeNewNode">Creates a new node, if valueMatches returns false.</param>
1801         static void AddXmlNode (XmlElement[] relevant, Func<XmlElement, bool> valueMatches, Action<XmlElement> setValue, Func<XmlElement> makeNewNode, ModuleDefinition module)
1802         {
1803                 bool shouldDuplicate = MDocUpdater.HasDroppedNamespace (module);
1804                 var styleToUse = shouldDuplicate ? ApiStyle.Unified : ApiStyle.Classic;
1805                 var existing = relevant;
1806                 bool done = false;
1807                 bool addedOldApiStyle = false;
1808
1809                 if (shouldDuplicate) {
1810                         existing = existing.Where (n => n.HasApiStyle (styleToUse)).ToArray ();
1811                         foreach (var n in relevant.Where (n => n.DoesNotHaveApiStyle (styleToUse))) {
1812                                 if (valueMatches (n)) {
1813                                         done = true;
1814                                 }
1815                                 else {
1816                                         n.AddApiStyle (ApiStyle.Classic);
1817                                         addedOldApiStyle = true;
1818                                 }
1819                         }
1820                 }
1821                 if (!done) {
1822                         if (!existing.Any ()) {
1823                                 var newNode = makeNewNode ();
1824                                 if (shouldDuplicate && addedOldApiStyle) {
1825                                         newNode.AddApiStyle (ApiStyle.Unified);
1826                                 }
1827                         }
1828                         else {
1829                                 var itemToReuse = existing.First ();
1830                                 setValue (itemToReuse);
1831                                 
1832                                 if (shouldDuplicate && addedOldApiStyle) {
1833                                         itemToReuse.AddApiStyle (styleToUse);
1834                                 }
1835                         }
1836                 }
1837         }
1838
1839         static readonly string[] MemberNodeOrder = {
1840                 "MemberSignature",
1841                 "MemberType",
1842                 "AssemblyInfo",
1843                 "Attributes",
1844                 "ReturnValue",
1845                 "TypeParameters",
1846                 "Parameters",
1847                 "MemberValue",
1848                 "Docs",
1849                 "Excluded",
1850                 "ExcludedLibrary",
1851                 "Link",
1852         };
1853
1854         static void OrderMemberNodes (XmlNode member, XmlNodeList children)
1855         {
1856                 ReorderNodes (member, children, MemberNodeOrder);
1857         }
1858
1859         static void ReorderNodes (XmlNode node, XmlNodeList children, string[] ordering)
1860         {
1861                 MyXmlNodeList newChildren = new MyXmlNodeList (children.Count);
1862                 for (int i = 0; i < ordering.Length; ++i) {
1863                         for (int j = 0; j < children.Count; ++j) {
1864                                 XmlNode c = children [j];
1865                                 if (c.Name == ordering [i]) {
1866                                         newChildren.Add (c);
1867                                 }
1868                         }
1869                 }
1870                 if (newChildren.Count >= 0)
1871                         node.PrependChild ((XmlNode) newChildren [0]);
1872                 for (int i = 1; i < newChildren.Count; ++i) {
1873                         XmlNode prev = (XmlNode) newChildren [i-1];
1874                         XmlNode cur  = (XmlNode) newChildren [i];
1875                         node.RemoveChild (cur);
1876                         node.InsertAfter (cur, prev);
1877                 }
1878         }
1879
1880         IEnumerable<string> GetCustomAttributes (MemberReference mi)
1881         {
1882                 IEnumerable<string> attrs = Enumerable.Empty<string>();
1883
1884                 ICustomAttributeProvider p = mi as ICustomAttributeProvider;
1885                 if (p != null)
1886                         attrs = attrs.Concat (GetCustomAttributes (p.CustomAttributes, ""));
1887
1888                 PropertyDefinition pd = mi as PropertyDefinition;
1889                 if (pd != null) {
1890                         if (pd.GetMethod != null)
1891                                 attrs = attrs.Concat (GetCustomAttributes (pd.GetMethod.CustomAttributes, "get: "));
1892                         if (pd.SetMethod != null)
1893                                 attrs = attrs.Concat (GetCustomAttributes (pd.SetMethod.CustomAttributes, "set: "));
1894                 }
1895
1896                 EventDefinition ed = mi as EventDefinition;
1897                 if (ed != null) {
1898                         if (ed.AddMethod != null)
1899                                 attrs = attrs.Concat (GetCustomAttributes (ed.AddMethod.CustomAttributes, "add: "));
1900                         if (ed.RemoveMethod != null)
1901                                 attrs = attrs.Concat (GetCustomAttributes (ed.RemoveMethod.CustomAttributes, "remove: "));
1902                 }
1903
1904                 return attrs;
1905         }
1906
1907         IEnumerable<string> GetCustomAttributes (IList<CustomAttribute> attributes, string prefix)
1908         {
1909                 foreach (CustomAttribute attribute in attributes.OrderBy (ca => ca.AttributeType.FullName)) {
1910
1911                         TypeDefinition attrType = attribute.AttributeType as TypeDefinition;
1912                         if (attrType != null && !IsPublic (attrType))
1913                                 continue;
1914                         if (slashdocFormatter.GetName (attribute.AttributeType) == null)
1915                                 continue;
1916                         
1917                         if (Array.IndexOf (IgnorableAttributes, attribute.AttributeType.FullName) >= 0)
1918                                 continue;
1919                         
1920                         StringList fields = new StringList ();
1921
1922                         for (int i = 0; i < attribute.ConstructorArguments.Count; ++i) {
1923                                 CustomAttributeArgument argument = attribute.ConstructorArguments [i];
1924                                 fields.Add (MakeAttributesValueString (
1925                                                 argument.Value,
1926                                                 argument.Type));
1927                         }
1928                         var namedArgs =
1929                                 (from namedArg in attribute.Fields
1930                                  select new { Type=namedArg.Argument.Type, Name=namedArg.Name, Value=namedArg.Argument.Value })
1931                                 .Concat (
1932                                                 (from namedArg in attribute.Properties
1933                                                  select new { Type=namedArg.Argument.Type, Name=namedArg.Name, Value=namedArg.Argument.Value }))
1934                                 .OrderBy (v => v.Name);
1935                         foreach (var d in namedArgs)
1936                                 fields.Add (string.Format ("{0}={1}", d.Name, 
1937                                                 MakeAttributesValueString (d.Value, d.Type)));
1938
1939                         string a2 = String.Join(", ", fields.ToArray ());
1940                         if (a2 != "") a2 = "(" + a2 + ")";
1941
1942                         string name = attribute.GetDeclaringType();
1943                         if (name.EndsWith("Attribute")) name = name.Substring(0, name.Length-"Attribute".Length);
1944                         yield return prefix + name + a2;
1945                 }
1946         }
1947
1948         static readonly string[] ValidExtensionMembers = {
1949                 "Docs",
1950                 "MemberSignature",
1951                 "MemberType",
1952                 "Parameters",
1953                 "ReturnValue",
1954                 "TypeParameters",
1955         };
1956
1957         static readonly string[] ValidExtensionDocMembers = {
1958                 "param",
1959                 "summary",
1960                 "typeparam",
1961         };
1962
1963         private void UpdateExtensionMethods (XmlElement e, DocsNodeInfo info)
1964         {
1965                 MethodDefinition me = info.Member as MethodDefinition;
1966                 if (me == null)
1967                         return;
1968                 if (info.Parameters.Count < 1)
1969                         return;
1970                 if (!DocUtils.IsExtensionMethod (me))
1971                         return;
1972
1973                 XmlNode em = e.OwnerDocument.CreateElement ("ExtensionMethod");
1974                 XmlNode member = e.CloneNode (true);
1975                 em.AppendChild (member);
1976                 RemoveExcept (member, ValidExtensionMembers);
1977                 RemoveExcept (member.SelectSingleNode ("Docs"), ValidExtensionDocMembers);
1978                 WriteElementText (member, "MemberType", "ExtensionMethod");
1979                 XmlElement link = member.OwnerDocument.CreateElement ("Link");
1980                 link.SetAttribute ("Type", slashdocFormatter.GetName (me.DeclaringType));
1981                 link.SetAttribute ("Member", slashdocFormatter.GetDeclaration (me));
1982                 member.AppendChild (link);
1983                 AddTargets (em, info);
1984
1985                 extensionMethods.Add (em);
1986         }
1987
1988         private static void RemoveExcept (XmlNode node, string[] except)
1989         {
1990                 if (node == null)
1991                         return;
1992                 MyXmlNodeList remove = null;
1993                 foreach (XmlNode n in node.ChildNodes) {
1994                         if (Array.BinarySearch (except, n.Name) < 0) {
1995                                 if (remove == null)
1996                                         remove = new MyXmlNodeList ();
1997                                 remove.Add (n);
1998                         }
1999                 }
2000                 if (remove != null)
2001                         foreach (XmlNode n in remove)
2002                                 node.RemoveChild (n);
2003         }
2004
2005         private static void AddTargets (XmlNode member, DocsNodeInfo info)
2006         {
2007                 XmlElement targets = member.OwnerDocument.CreateElement ("Targets");
2008                 member.PrependChild (targets);
2009                 if (!(info.Parameters [0].ParameterType is GenericParameter)) {
2010                         AppendElementAttributeText (targets, "Target", "Type",
2011                                 slashdocFormatter.GetDeclaration (info.Parameters [0].ParameterType));
2012                 }
2013                 else {
2014                         GenericParameter gp = (GenericParameter) info.Parameters [0].ParameterType;
2015                         IList<TypeReference> constraints = gp.Constraints;
2016                         if (constraints.Count == 0)
2017                                 AppendElementAttributeText (targets, "Target", "Type", "System.Object");
2018                         else
2019                                 foreach (TypeReference c in constraints)
2020                                         AppendElementAttributeText(targets, "Target", "Type",
2021                                                 slashdocFormatter.GetDeclaration (c));
2022                 }
2023         }
2024         
2025         private static bool GetFieldConstValue (FieldDefinition field, out string value)
2026         {
2027                 value = null;
2028                 TypeDefinition type = field.DeclaringType.Resolve ();
2029                 if (type != null && type.IsEnum) return false;
2030                 
2031                 if (type != null && type.IsGenericType ()) return false;
2032                 if (!field.HasConstant)
2033                         return false;
2034                 if (field.IsLiteral) {
2035                         object val = field.Constant;
2036                         if (val == null) value = "null";
2037                         else if (val is Enum) value = val.ToString();
2038                         else if (val is IFormattable) {
2039                                 value = ((IFormattable)val).ToString();
2040                                 if (val is string)
2041                                         value = "\"" + value + "\"";
2042                         }
2043                         if (value != null && value != "")
2044                                 return true;
2045                 }
2046                 return false;
2047         }
2048         
2049         // XML HELPER FUNCTIONS
2050         
2051         internal static XmlElement WriteElement(XmlNode parent, string element, bool forceNewElement = false) {
2052                 XmlElement ret = (XmlElement)parent.SelectSingleNode(element);
2053                 if (ret == null || forceNewElement) {
2054                         string[] path = element.Split('/');
2055                         foreach (string p in path) {
2056                                 ret = (XmlElement)parent.SelectSingleNode(p);
2057                                 if (ret == null || forceNewElement) {
2058                                         string ename = p;
2059                                         if (ename.IndexOf('[') >= 0) // strip off XPath predicate
2060                                                 ename = ename.Substring(0, ename.IndexOf('['));
2061                                         ret = parent.OwnerDocument.CreateElement(ename);
2062                                         parent.AppendChild(ret);
2063                                         parent = ret;
2064                                 } else {
2065                                         parent = ret;
2066                                 }
2067                         }
2068                 }
2069                 return ret;
2070         }
2071         private static XmlElement WriteElementText(XmlNode parent, string element, string value, bool forceNewElement = false) {
2072                 XmlElement node = WriteElement(parent, element, forceNewElement: forceNewElement);
2073                 node.InnerText = value;
2074                 return node;
2075         }
2076
2077         static XmlElement AppendElementText (XmlNode parent, string element, string value)
2078         {
2079                 XmlElement n = parent.OwnerDocument.CreateElement (element);
2080                 parent.AppendChild (n);
2081                 n.InnerText = value;
2082                 return n;
2083         }
2084
2085         static XmlElement AppendElementAttributeText (XmlNode parent, string element, string attribute, string value)
2086         {
2087                 XmlElement n = parent.OwnerDocument.CreateElement (element);
2088                 parent.AppendChild (n);
2089                 n.SetAttribute (attribute, value);
2090                 return n;
2091         }
2092
2093         internal static XmlNode CopyNode (XmlNode source, XmlNode dest)
2094         {
2095                 XmlNode copy = dest.OwnerDocument.ImportNode (source, true);
2096                 dest.AppendChild (copy);
2097                 return copy;
2098         }
2099
2100         private static void WriteElementInitialText(XmlElement parent, string element, string value) {
2101                 XmlElement node = (XmlElement)parent.SelectSingleNode(element);
2102                 if (node != null)
2103                         return;
2104                 node = WriteElement(parent, element);
2105                 node.InnerText = value;
2106         }
2107         private static XmlElement WriteElementAttribute(XmlElement parent, string element, string attribute, string value, bool forceNewElement = false) {
2108                 XmlElement node = WriteElement(parent, element, forceNewElement:forceNewElement);
2109                 return WriteElementAttribute (parent, node, attribute, value);
2110         }
2111         private static XmlElement WriteElementAttribute(XmlElement parent, XmlElement node, string attribute, string value) {
2112                 if (node.GetAttribute (attribute) != value) {
2113                         node.SetAttribute (attribute, value);
2114                 }
2115                 return node;
2116         }
2117         internal static void ClearElement(XmlElement parent, string name) {
2118                 XmlElement node = (XmlElement)parent.SelectSingleNode(name);
2119                 if (node != null)
2120                         parent.RemoveChild(node);
2121         }
2122         
2123         // DOCUMENTATION HELPER FUNCTIONS
2124         
2125         private void MakeDocNode (DocsNodeInfo info)
2126         {
2127                 List<GenericParameter> genericParams      = info.GenericParameters;
2128                 IList<ParameterDefinition> parameters  = info.Parameters;
2129                 TypeReference returntype                  = info.ReturnType;
2130                 bool returnisreturn         = info.ReturnIsReturn;
2131                 XmlElement e                = info.Node;
2132                 bool addremarks             = info.AddRemarks;
2133
2134                 WriteElementInitialText(e, "summary", "To be added.");
2135                 
2136                 if (parameters != null) {
2137                         string[] values = new string [parameters.Count];
2138                         for (int i = 0; i < values.Length; ++i)
2139                                 values [i] = parameters [i].Name;
2140                         UpdateParameters (e, "param", values);
2141                 }
2142
2143                 if (genericParams != null) {
2144                         string[] values = new string [genericParams.Count];
2145                         for (int i = 0; i < values.Length; ++i)
2146                                 values [i] = genericParams [i].Name;
2147                         UpdateParameters (e, "typeparam", values);
2148                 }
2149
2150                 string retnodename = null;
2151                 if (returntype != null && returntype.FullName != "System.Void") { // FIXME
2152                         retnodename = returnisreturn ? "returns" : "value";
2153                         string retnodename_other = !returnisreturn ? "returns" : "value";
2154                         
2155                         // If it has a returns node instead of a value node, change its name.
2156                         XmlElement retother = (XmlElement)e.SelectSingleNode(retnodename_other);
2157                         if (retother != null) {
2158                                 XmlElement retnode = e.OwnerDocument.CreateElement(retnodename);
2159                                 foreach (XmlNode node in retother)
2160                                         retnode.AppendChild(node.CloneNode(true));
2161                                 e.ReplaceChild(retnode, retother);
2162                         } else {
2163                                 WriteElementInitialText(e, retnodename, "To be added.");
2164                         }
2165                 } else {
2166                         ClearElement(e, "returns");
2167                         ClearElement(e, "value");
2168                 }
2169
2170                 if (addremarks)
2171                         WriteElementInitialText(e, "remarks", "To be added.");
2172
2173                 if (exceptions.HasValue && info.Member != null &&
2174                                 (exceptions.Value & ExceptionLocations.AddedMembers) == 0) {
2175                         UpdateExceptions (e, info.Member);
2176                 }
2177
2178                 foreach (DocumentationImporter importer in importers)
2179                         importer.ImportDocumentation (info);
2180                 
2181                 OrderDocsNodes (e, e.ChildNodes);
2182                 NormalizeWhitespace(e);
2183         }
2184
2185         static readonly string[] DocsNodeOrder = {
2186                 "typeparam", "param", "summary", "returns", "value", "remarks",
2187         };
2188
2189         private static void OrderDocsNodes (XmlNode docs, XmlNodeList children)
2190         {
2191                 ReorderNodes (docs, children, DocsNodeOrder);
2192         }
2193         
2194
2195         private void UpdateParameters (XmlElement e, string element, string[] values)
2196         {       
2197                 if (values != null) {
2198                         XmlNode[] paramnodes = new XmlNode[values.Length];
2199                         
2200                         // Some documentation had param nodes with leading spaces.
2201                         foreach (XmlElement paramnode in e.SelectNodes(element)){
2202                                 paramnode.SetAttribute("name", paramnode.GetAttribute("name").Trim());
2203                         }
2204                         
2205                         // If a member has only one parameter, we can track changes to
2206                         // the name of the parameter easily.
2207                         if (values.Length == 1 && e.SelectNodes(element).Count == 1) {
2208                                 UpdateParameterName (e, (XmlElement) e.SelectSingleNode(element), values [0]);
2209                         }
2210
2211                         bool reinsert = false;
2212
2213                         // Pick out existing and still-valid param nodes, and
2214                         // create nodes for parameters not in the file.
2215                         Hashtable seenParams = new Hashtable();
2216                         for (int pi = 0; pi < values.Length; pi++) {
2217                                 string p = values [pi];
2218                                 seenParams[p] = pi;
2219                                 
2220                                 paramnodes[pi] = e.SelectSingleNode(element + "[@name='" + p + "']");
2221                                 if (paramnodes[pi] != null) continue;
2222                                 
2223                                 XmlElement pe = e.OwnerDocument.CreateElement(element);
2224                                 pe.SetAttribute("name", p);
2225                                 pe.InnerText = "To be added.";
2226                                 paramnodes[pi] = pe;
2227                                 reinsert = true;
2228                         }
2229
2230                         // Remove parameters that no longer exist and check all params are in the right order.
2231                         int idx = 0;
2232                         MyXmlNodeList todelete = new MyXmlNodeList ();
2233                         foreach (XmlElement paramnode in e.SelectNodes(element)) {
2234                                 string name = paramnode.GetAttribute("name");
2235                                 if (!seenParams.ContainsKey(name)) {
2236                                         if (!delete && !paramnode.InnerText.StartsWith("To be added")) {
2237                                                 Warning ("The following param node can only be deleted if the --delete option is given: ");
2238                                                 if (e.ParentNode == e.OwnerDocument.DocumentElement) {
2239                                                         // delegate type
2240                                                         Warning ("\tXPath=/Type[@FullName=\"{0}\"]/Docs/param[@name=\"{1}\"]",
2241                                                                         e.OwnerDocument.DocumentElement.GetAttribute ("FullName"),
2242                                                                         name);
2243                                                 }
2244                                                 else {
2245                                                         Warning ("\tXPath=/Type[@FullName=\"{0}\"]//Member[@MemberName=\"{1}\"]/Docs/param[@name=\"{2}\"]",
2246                                                                         e.OwnerDocument.DocumentElement.GetAttribute ("FullName"),
2247                                                                         e.ParentNode.Attributes ["MemberName"].Value, 
2248                                                                         name);
2249                                                 }
2250                                                 Warning ("\tValue={0}", paramnode.OuterXml);
2251                                         } else {
2252                                                 todelete.Add (paramnode);
2253                                         }
2254                                         continue;
2255                                 }
2256
2257                                 if ((int)seenParams[name] != idx)
2258                                         reinsert = true;
2259                                 
2260                                 idx++;
2261                         }
2262
2263                         foreach (XmlNode n in todelete) {
2264                                 n.ParentNode.RemoveChild (n);
2265                         }
2266                         
2267                         // Re-insert the parameter nodes at the top of the doc section.
2268                         if (reinsert)
2269                                 for (int pi = values.Length-1; pi >= 0; pi--)
2270                                         e.PrependChild(paramnodes[pi]);
2271                 } else {
2272                         // Clear all existing param nodes
2273                         foreach (XmlNode paramnode in e.SelectNodes(element)) {
2274                                 if (!delete && !paramnode.InnerText.StartsWith("To be added")) {
2275                                         Console.WriteLine("The following param node can only be deleted if the --delete option is given:");
2276                                         Console.WriteLine(paramnode.OuterXml);
2277                                 } else {
2278                                         paramnode.ParentNode.RemoveChild(paramnode);
2279                                 }
2280                         }
2281                 }
2282         }
2283
2284         private static void UpdateParameterName (XmlElement docs, XmlElement pe, string newName)
2285         {
2286                 string existingName = pe.GetAttribute ("name");
2287                 pe.SetAttribute ("name", newName);
2288                 if (existingName == newName)
2289                         return;
2290                 foreach (XmlElement paramref in docs.SelectNodes (".//paramref"))
2291                         if (paramref.GetAttribute ("name").Trim () == existingName)
2292                                 paramref.SetAttribute ("name", newName);
2293         }
2294
2295         class CrefComparer : XmlNodeComparer {
2296
2297                 public CrefComparer ()
2298                 {
2299                 }
2300
2301                 public override int Compare (XmlNode x, XmlNode y)
2302                 {
2303                         string xType = x.Attributes ["cref"].Value;
2304                         string yType = y.Attributes ["cref"].Value;
2305                         string xNamespace = GetNamespace (xType);
2306                         string yNamespace = GetNamespace (yType);
2307
2308                         int c = xNamespace.CompareTo (yNamespace);
2309                         if (c != 0)
2310                                 return c;
2311                         return xType.CompareTo (yType);
2312                 }
2313
2314                 static string GetNamespace (string type)
2315                 {
2316                         int n = type.LastIndexOf ('.');
2317                         if (n >= 0)
2318                                 return type.Substring (0, n);
2319                         return string.Empty;
2320                 }
2321         }
2322         
2323         private void UpdateExceptions (XmlNode docs, MemberReference member)
2324         {
2325                 string indent = new string (' ', 10);
2326                 foreach (var source in new ExceptionLookup (exceptions.Value)[member]) {
2327                         string cref = slashdocFormatter.GetDeclaration (source.Exception);
2328                         var node = docs.SelectSingleNode ("exception[@cref='" + cref + "']");
2329                         if (node != null)
2330                                 continue;
2331                         XmlElement e = docs.OwnerDocument.CreateElement ("exception");
2332                         e.SetAttribute ("cref", cref);
2333                         e.InnerXml = "To be added; from:\n" + indent + "<see cref=\"" +
2334                                 string.Join ("\" />,\n" + indent + "<see cref=\"",
2335                                                 source.Sources.Select (m => slashdocFormatter.GetDeclaration (m))
2336                                                 .OrderBy (s => s)) +
2337                                 "\" />";
2338                         docs.AppendChild (e);
2339                 }
2340                 SortXmlNodes (docs, docs.SelectNodes ("exception"), 
2341                                 new CrefComparer ());
2342         }
2343
2344         private static void NormalizeWhitespace(XmlElement e) {
2345                 // Remove all text and whitespace nodes from the element so it
2346                 // is outputted with nice indentation and no blank lines.
2347                 ArrayList deleteNodes = new ArrayList();
2348                 foreach (XmlNode n in e)
2349                         if (n is XmlText || n is XmlWhitespace || n is XmlSignificantWhitespace)
2350                                 deleteNodes.Add(n);
2351                 foreach (XmlNode n in deleteNodes)
2352                                 n.ParentNode.RemoveChild(n);
2353         }
2354         
2355         private static bool UpdateAssemblyVersions (XmlElement root, MemberReference member, bool add)
2356         {
2357                 TypeDefinition type = member as TypeDefinition;
2358                 if (type == null)
2359                         type = member.DeclaringType as TypeDefinition;
2360
2361                 var versions = new string[] { GetAssemblyVersion (type.Module.Assembly) };
2362
2363                 if (root.LocalName == "AssemblyInfo")
2364                         return UpdateAssemblyVersionForAssemblyInfo (root, root.ParentNode as XmlElement, versions, add: true);
2365                 else 
2366                         return UpdateAssemblyVersions (root, type.Module.Assembly, versions, add);
2367         }
2368         
2369         private static string GetAssemblyVersion (AssemblyDefinition assembly)
2370         {
2371                 return assembly.Name.Version.ToString();
2372         }
2373         
2374         private static bool UpdateAssemblyVersions(XmlElement root, AssemblyDefinition assembly, string[] assemblyVersions, bool add)
2375         {
2376                 XmlElement av = (XmlElement) root.SelectSingleNode ("AssemblyVersions");
2377                 if (av != null) {
2378                                 // AssemblyVersions is not part of the spec
2379                                 root.RemoveChild (av);
2380                 }
2381
2382                 string oldNodeFilter = "AssemblyInfo[not(@apistyle) or @apistyle='classic']";
2383                 string newNodeFilter = "AssemblyInfo[@apistyle='unified']";
2384                 string thisNodeFilter = MDocUpdater.HasDroppedNamespace (assembly) ? newNodeFilter : oldNodeFilter;
2385                 string thatNodeFilter = MDocUpdater.HasDroppedNamespace (assembly) ? oldNodeFilter : newNodeFilter;
2386
2387                 XmlElement e = (XmlElement) root.SelectSingleNode (thisNodeFilter);
2388                 if (e == null) {
2389                         e = root.OwnerDocument.CreateElement("AssemblyInfo");
2390
2391                         if (MDocUpdater.HasDroppedNamespace (assembly)) {
2392                                 e.SetAttribute ("apistyle", "unified");
2393                         }
2394
2395                         root.AppendChild(e);
2396                 }
2397
2398                 var thatNode = (XmlElement) root.SelectSingleNode (thatNodeFilter);
2399                 if (MDocUpdater.HasDroppedNamespace (assembly) && thatNode != null) {
2400                         // there's a classic node, we should add apistyles
2401                         e.SetAttribute ("apistyle", "unified");
2402                         thatNode.SetAttribute ("apistyle", "classic");
2403                 }
2404
2405                 return UpdateAssemblyVersionForAssemblyInfo (e, root, assemblyVersions, add);
2406         }
2407
2408         static bool UpdateAssemblyVersionForAssemblyInfo (XmlElement e, XmlElement root, string[] assemblyVersions, bool add)
2409         {
2410                 List<XmlNode> matches = e.SelectNodes ("AssemblyVersion").Cast<XmlNode> ().Where (v => Array.IndexOf (assemblyVersions, v.InnerText) >= 0).ToList ();
2411                 // matches.Count > 0 && add: ignore -- already present
2412                 if (matches.Count > 0 && !add) {
2413                         foreach (XmlNode c in matches)
2414                                 e.RemoveChild (c);
2415                 }
2416                 else if (matches.Count == 0 && add) {
2417                         foreach (string sv in assemblyVersions) {
2418                                 XmlElement c = root.OwnerDocument.CreateElement("AssemblyVersion");
2419                                 c.InnerText = sv;
2420                                 e.AppendChild(c);
2421                         }
2422                 }
2423
2424                 // matches.Count == 0 && !add: ignore -- already not present
2425                 XmlNodeList avs = e.SelectNodes ("AssemblyVersion");
2426                 SortXmlNodes (e, avs, new VersionComparer ());
2427
2428                 bool anyNodesLeft = avs.Count != 0;
2429                 if (!anyNodesLeft) {
2430                         e.ParentNode.RemoveChild (e);
2431                 }
2432                 return anyNodesLeft;
2433         }
2434
2435         // FIXME: get TypeReferences instead of string comparison?
2436         private static string[] IgnorableAttributes = {
2437                 // Security related attributes
2438                 "System.Reflection.AssemblyKeyFileAttribute",
2439                 "System.Reflection.AssemblyDelaySignAttribute",
2440                 // Present in @RefType
2441                 "System.Runtime.InteropServices.OutAttribute",
2442                 // For naming the indexer to use when not using indexers
2443                 "System.Reflection.DefaultMemberAttribute",
2444                 // for decimal constants
2445                 "System.Runtime.CompilerServices.DecimalConstantAttribute",
2446                 // compiler generated code
2447                 "System.Runtime.CompilerServices.CompilerGeneratedAttribute",
2448                 // more compiler generated code, e.g. iterator methods
2449                 "System.Diagnostics.DebuggerHiddenAttribute",
2450                 "System.Runtime.CompilerServices.FixedBufferAttribute",
2451                 "System.Runtime.CompilerServices.UnsafeValueTypeAttribute",
2452                 // extension methods
2453                 "System.Runtime.CompilerServices.ExtensionAttribute",
2454                 // Used to differentiate 'object' from C#4 'dynamic'
2455                 "System.Runtime.CompilerServices.DynamicAttribute",
2456         };
2457
2458         private void MakeAttributes (XmlElement root, IEnumerable<string> attributes, TypeReference t=null)
2459         {
2460                 if (!attributes.Any ()) {
2461                         ClearElement (root, "Attributes");
2462                         return;
2463                 }
2464
2465                 XmlElement e = (XmlElement)root.SelectSingleNode("Attributes");
2466                 if (e != null)
2467                         e.RemoveAll();
2468                 else if (e == null)
2469                         e = root.OwnerDocument.CreateElement("Attributes");
2470                 
2471                 foreach (string attribute in attributes) {
2472                         XmlElement ae = root.OwnerDocument.CreateElement("Attribute");
2473                         e.AppendChild(ae);
2474                         
2475                         WriteElementText(ae, "AttributeName", attribute);
2476                 }
2477                 
2478                 if (e.ParentNode == null)
2479                         root.AppendChild(e);
2480
2481                 NormalizeWhitespace(e);
2482         }
2483
2484         public static string MakeAttributesValueString (object v, TypeReference valueType)
2485         {
2486                 var formatters = new [] { 
2487                         new AttributeValueFormatter (), 
2488                         new ApplePlatformEnumFormatter (), 
2489                         new StandardFlagsEnumFormatter (), 
2490                         new DefaultAttributeValueFormatter (),
2491                 };
2492
2493                 ResolvedTypeInfo type = new ResolvedTypeInfo (valueType);
2494                 foreach (var formatter in formatters) {
2495                         string formattedValue;
2496                         if (formatter.TryFormatValue (v, type, out formattedValue)) {
2497                                 return formattedValue;
2498                         }
2499                 }
2500
2501                 // this should never occur because the DefaultAttributeValueFormatter will always
2502                 // successfully format the value ... but this is needed to satisfy the compiler :)
2503                 throw new InvalidDataException (string.Format ("Unable to format attribute value ({0})", v.ToString ()));
2504         }
2505
2506         internal static IDictionary<long, string> GetEnumerationValues (TypeDefinition type)
2507         {
2508                 var values = new Dictionary<long, string> ();
2509                 foreach (var f in 
2510                                 (from f in type.Fields
2511                                  where !(f.IsRuntimeSpecialName || f.IsSpecialName)
2512                                  select f)) {
2513                         values [ToInt64 (f.Constant)] = f.Name;
2514                 }
2515                 return values;
2516         }
2517
2518         internal static long ToInt64 (object value)
2519         {
2520                 if (value is ulong)
2521                         return (long) (ulong) value;
2522                 return Convert.ToInt64 (value);
2523         }
2524         
2525         private void MakeParameters (XmlElement root, MemberReference member, IList<ParameterDefinition> parameters, bool shouldDuplicateWithNew=false)
2526         {
2527                 XmlElement e = WriteElement(root, "Parameters");
2528
2529                 int i = 0;
2530                 foreach (ParameterDefinition p in parameters) {
2531                         XmlElement pe;
2532                         
2533                         // param info
2534                         var ptype = GetDocParameterType (p.ParameterType);
2535                         var newPType = ptype;
2536
2537                         if (MDocUpdater.SwitchingToMagicTypes) {
2538                                 newPType = NativeTypeManager.ConvertFromNativeType (ptype);
2539                         }
2540
2541                         // now find the existing node, if it's there so we can reuse it.
2542                         var nodes = root.SelectSingleNode ("Parameters").SelectNodes ("Parameter")
2543                                 .Cast<XmlElement> ().Where (x => x.GetAttribute ("Name") == p.Name)
2544                                 .ToArray();
2545
2546                         if (nodes.Count () == 0) {
2547                                 // wasn't found, let's make sure it wasn't just cause the param name was changed
2548                                 nodes = root.SelectSingleNode ("Parameters").SelectNodes ("Parameter")
2549                                         .Cast<XmlElement> ()
2550                                         .Skip (i) // this makes sure we don't inadvertently "reuse" nodes when adding new ones
2551                                         .Where (x => x.GetAttribute ("Name") != p.Name && (x.GetAttribute ("Type") == ptype || x.GetAttribute ("Type") == newPType))
2552                                         .Take(1) // there might be more than one that meets this parameter ... only take the first.
2553                                         .ToArray();
2554                         }
2555
2556                         AddXmlNode (nodes, 
2557                                 x => x.GetAttribute ("Type") == ptype,
2558                                 x => x.SetAttribute ("Type", ptype),
2559                                 () => {
2560                                         pe = root.OwnerDocument.CreateElement ("Parameter");
2561                                         e.AppendChild (pe);
2562
2563                                         pe.SetAttribute ("Name", p.Name);
2564                                         pe.SetAttribute ("Type", ptype);
2565                                         if (p.ParameterType is ByReferenceType) {
2566                                                 if (p.IsOut)
2567                                                         pe.SetAttribute ("RefType", "out");
2568                                                 else
2569                                                         pe.SetAttribute ("RefType", "ref");
2570                                         }
2571
2572                                         MakeAttributes (pe, GetCustomAttributes (p.CustomAttributes, ""));
2573                                         return pe;
2574                                 },
2575                                 member);
2576
2577                         i++;
2578                 }
2579         }
2580         
2581         private void MakeTypeParameters (XmlElement root, IList<GenericParameter> typeParams, MemberReference member, bool shouldDuplicateWithNew)
2582         {
2583                 if (typeParams == null || typeParams.Count == 0) {
2584                         XmlElement f = (XmlElement) root.SelectSingleNode ("TypeParameters");
2585                         if (f != null)
2586                                 root.RemoveChild (f);
2587                         return;
2588                 }
2589                 XmlElement e = WriteElement(root, "TypeParameters");
2590
2591                 var nodes = e.SelectNodes ("TypeParameter").Cast<XmlElement> ().ToArray ();
2592
2593                 foreach (GenericParameter t in typeParams) {
2594
2595                                 IList<TypeReference> constraints = t.Constraints;
2596                                 GenericParameterAttributes attrs = t.Attributes;
2597
2598
2599                                 AddXmlNode (
2600                                         nodes,
2601                                         x => { 
2602                                                 var baseType = e.SelectSingleNode("BaseTypeName");
2603                                                 // TODO: should this comparison take into account BaseTypeName?
2604                                                 return x.GetAttribute("Name") == t.Name;
2605                                         },
2606                                         x => {}, // no additional action required
2607                                         () => {
2608
2609                                                 XmlElement pe = root.OwnerDocument.CreateElement("TypeParameter");
2610                                                 e.AppendChild(pe);
2611                                                 pe.SetAttribute("Name", t.Name);
2612                                                         MakeAttributes (pe, GetCustomAttributes (t.CustomAttributes, ""), t.DeclaringType);
2613                                                 XmlElement ce = (XmlElement) e.SelectSingleNode ("Constraints");
2614                                                 if (attrs == GenericParameterAttributes.NonVariant && constraints.Count == 0) {
2615                                                         if (ce != null)
2616                                                                 e.RemoveChild (ce);
2617                                                         return pe;
2618                                                 }
2619                                                 if (ce != null)
2620                                                         ce.RemoveAll();
2621                                                 else {
2622                                                         ce = root.OwnerDocument.CreateElement ("Constraints");
2623                                                 }
2624                                                 pe.AppendChild (ce);
2625                                                 if ((attrs & GenericParameterAttributes.Contravariant) != 0)
2626                                                         AppendElementText (ce, "ParameterAttribute", "Contravariant");
2627                                                 if ((attrs & GenericParameterAttributes.Covariant) != 0)
2628                                                         AppendElementText (ce, "ParameterAttribute", "Covariant");
2629                                                 if ((attrs & GenericParameterAttributes.DefaultConstructorConstraint) != 0)
2630                                                         AppendElementText (ce, "ParameterAttribute", "DefaultConstructorConstraint");
2631                                                 if ((attrs & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0)
2632                                                         AppendElementText (ce, "ParameterAttribute", "NotNullableValueTypeConstraint");
2633                                                 if ((attrs & GenericParameterAttributes.ReferenceTypeConstraint) != 0)
2634                                                         AppendElementText (ce, "ParameterAttribute", "ReferenceTypeConstraint");
2635                                                 foreach (TypeReference c in constraints) {
2636                                                         TypeDefinition cd = c.Resolve ();
2637                                                         AppendElementText (ce,
2638                                                                         (cd != null && cd.IsInterface) ? "InterfaceName" : "BaseTypeName",
2639                                                                         GetDocTypeFullName (c));
2640                                                 }
2641                                         
2642                                                 return pe;
2643                                         },
2644                                 member);
2645                 }
2646         }
2647
2648         private void MakeParameters (XmlElement root, MemberReference mi, bool shouldDuplicateWithNew)
2649         {
2650                 if (mi is MethodDefinition && ((MethodDefinition) mi).IsConstructor)
2651                                 MakeParameters (root, mi, ((MethodDefinition)mi).Parameters, shouldDuplicateWithNew);
2652                 else if (mi is MethodDefinition) {
2653                         MethodDefinition mb = (MethodDefinition) mi;
2654                         IList<ParameterDefinition> parameters = mb.Parameters;
2655                                 MakeParameters(root, mi, parameters, shouldDuplicateWithNew);
2656                         if (parameters.Count > 0 && DocUtils.IsExtensionMethod (mb)) {
2657                                 XmlElement p = (XmlElement) root.SelectSingleNode ("Parameters/Parameter[position()=1]");
2658                                 p.SetAttribute ("RefType", "this");
2659                         }
2660                 }
2661                 else if (mi is PropertyDefinition) {
2662                         IList<ParameterDefinition> parameters = ((PropertyDefinition)mi).Parameters;
2663                         if (parameters.Count > 0)
2664                                         MakeParameters(root, mi, parameters, shouldDuplicateWithNew);
2665                         else
2666                                 return;
2667                 }
2668                 else if (mi is FieldDefinition) return;
2669                 else if (mi is EventDefinition) return;
2670                 else throw new ArgumentException();
2671         }
2672
2673         internal static string GetDocParameterType (TypeReference type)
2674         {
2675                 return GetDocTypeFullName (type).Replace ("@", "&");
2676         }
2677
2678         private void MakeReturnValue (XmlElement root, TypeReference type, IList<CustomAttribute> attributes, bool shouldDuplicateWithNew=false) 
2679                 {
2680                         XmlElement e = WriteElement(root, "ReturnValue");
2681                         var valueToUse = GetDocTypeFullName (type);
2682
2683                         AddXmlNode (e.SelectNodes("ReturnType").Cast<XmlElement> ().ToArray (),
2684                                 x => x.InnerText == valueToUse,
2685                                 x => x.InnerText = valueToUse,
2686                                 () => {
2687                                         var newNode = WriteElementText(e, "ReturnType", valueToUse, forceNewElement: true);
2688                                         if (attributes != null)
2689                                                 MakeAttributes(e, GetCustomAttributes (attributes, ""), type);
2690
2691                                         return newNode;
2692                                 },
2693                         type);
2694         }
2695         
2696         private void MakeReturnValue (XmlElement root, MemberReference mi, bool shouldDuplicateWithNew=false)
2697         {
2698                 if (mi is MethodDefinition && ((MethodDefinition) mi).IsConstructor)
2699                         return;
2700                 else if (mi is MethodDefinition)
2701                         MakeReturnValue (root, ((MethodDefinition)mi).ReturnType, ((MethodDefinition)mi).MethodReturnType.CustomAttributes, shouldDuplicateWithNew);
2702                 else if (mi is PropertyDefinition)
2703                         MakeReturnValue (root, ((PropertyDefinition)mi).PropertyType, null, shouldDuplicateWithNew);
2704                 else if (mi is FieldDefinition)
2705                         MakeReturnValue (root, ((FieldDefinition)mi).FieldType, null, shouldDuplicateWithNew);
2706                 else if (mi is EventDefinition)
2707                         MakeReturnValue (root, ((EventDefinition)mi).EventType, null, shouldDuplicateWithNew);
2708                 else
2709                         throw new ArgumentException(mi + " is a " + mi.GetType().FullName);
2710         }
2711         
2712         private XmlElement MakeMember(XmlDocument doc, DocsNodeInfo info)
2713         {
2714                 MemberReference mi = info.Member;
2715                 if (mi is TypeDefinition) return null;
2716
2717                 string sigs = memberFormatters [0].GetDeclaration (mi);
2718                 if (sigs == null) return null; // not publicly visible
2719                 
2720                 // no documentation for property/event accessors.  Is there a better way of doing this?
2721                 if (mi.Name.StartsWith("get_")) return null;
2722                 if (mi.Name.StartsWith("set_")) return null;
2723                 if (mi.Name.StartsWith("add_")) return null;
2724                 if (mi.Name.StartsWith("remove_")) return null;
2725                 if (mi.Name.StartsWith("raise_")) return null;
2726                 
2727                 XmlElement me = doc.CreateElement("Member");
2728                 me.SetAttribute("MemberName", GetMemberName (mi));
2729
2730                 info.Node = me;
2731                 UpdateMember(info);
2732                 if (exceptions.HasValue && 
2733                                 (exceptions.Value & ExceptionLocations.AddedMembers) != 0)
2734                         UpdateExceptions (info.Node, info.Member);
2735
2736                 if (since != null) {
2737                         XmlNode docs = me.SelectSingleNode("Docs");
2738                         docs.AppendChild (CreateSinceNode (doc));
2739                 }
2740                 
2741                 return me;
2742         }
2743
2744         internal static string GetMemberName (MemberReference mi)
2745         {
2746                 MethodDefinition mb = mi as MethodDefinition;
2747                 if (mb == null) {
2748                         PropertyDefinition pi = mi as PropertyDefinition;
2749                         if (pi == null)
2750                                 return mi.Name;
2751                         return DocUtils.GetPropertyName (pi);
2752                 }
2753                 StringBuilder sb = new StringBuilder (mi.Name.Length);
2754                 if (!DocUtils.IsExplicitlyImplemented (mb))
2755                         sb.Append (mi.Name);
2756                 else {
2757                         TypeReference iface;
2758                         MethodReference ifaceMethod;
2759                         DocUtils.GetInfoForExplicitlyImplementedMethod (mb, out iface, out ifaceMethod);
2760                         sb.Append (GetDocTypeFullName (iface));
2761                         sb.Append ('.');
2762                         sb.Append (ifaceMethod.Name);
2763                 }
2764                 if (mb.IsGenericMethod ()) {
2765                         IList<GenericParameter> typeParams = mb.GenericParameters;
2766                         if (typeParams.Count > 0) {
2767                                 sb.Append ("<");
2768                                 sb.Append (typeParams [0].Name);
2769                                 for (int i = 1; i < typeParams.Count; ++i)
2770                                         sb.Append (",").Append (typeParams [i].Name);
2771                                 sb.Append (">");
2772                         }
2773                 }
2774                 return sb.ToString ();
2775         }
2776         
2777         /// SIGNATURE GENERATION FUNCTIONS
2778         internal static bool IsPrivate (MemberReference mi)
2779         {
2780                 return memberFormatters [0].GetDeclaration (mi) == null;
2781         }
2782
2783         internal static string GetMemberType (MemberReference mi)
2784         {
2785                 if (mi is MethodDefinition && ((MethodDefinition) mi).IsConstructor)
2786                         return "Constructor";
2787                 if (mi is MethodDefinition)
2788                         return "Method";
2789                 if (mi is PropertyDefinition)
2790                         return "Property";
2791                 if (mi is FieldDefinition)
2792                         return "Field";
2793                 if (mi is EventDefinition)
2794                         return "Event";
2795                 throw new ArgumentException();
2796         }
2797
2798         private static string GetDocTypeName (TypeReference type)
2799         {
2800                 return docTypeFormatter.GetName (type);
2801         }
2802
2803         internal static string GetDocTypeFullName (TypeReference type)
2804         {
2805                 return DocTypeFullMemberFormatter.Default.GetName (type);
2806         }
2807
2808         internal static string GetXPathForMember (DocumentationMember member)
2809         {
2810                 StringBuilder xpath = new StringBuilder ();
2811                 xpath.Append ("//Members/Member[@MemberName=\"")
2812                         .Append (member.MemberName)
2813                         .Append ("\"]");
2814                 if (member.Parameters != null && member.Parameters.Count > 0) {
2815                         xpath.Append ("/Parameters[count(Parameter) = ")
2816                                 .Append (member.Parameters.Count);
2817                         for (int i = 0; i < member.Parameters.Count; ++i) {
2818                                 xpath.Append (" and Parameter [").Append (i+1).Append ("]/@Type=\"");
2819                                 xpath.Append (member.Parameters [i]);
2820                                 xpath.Append ("\"");
2821                         }
2822                         xpath.Append ("]/..");
2823                 }
2824                 return xpath.ToString ();
2825         }
2826
2827         public static string GetXPathForMember (XPathNavigator member)
2828         {
2829                 StringBuilder xpath = new StringBuilder ();
2830                 xpath.Append ("//Type[@FullName=\"")
2831                         .Append (member.SelectSingleNode ("../../@FullName").Value)
2832                         .Append ("\"]/");
2833                 xpath.Append ("Members/Member[@MemberName=\"")
2834                         .Append (member.SelectSingleNode ("@MemberName").Value)
2835                         .Append ("\"]");
2836                 XPathNodeIterator parameters = member.Select ("Parameters/Parameter");
2837                 if (parameters.Count > 0) {
2838                         xpath.Append ("/Parameters[count(Parameter) = ")
2839                                 .Append (parameters.Count);
2840                         int i = 0;
2841                         while (parameters.MoveNext ()) {
2842                                 ++i;
2843                                 xpath.Append (" and Parameter [").Append (i).Append ("]/@Type=\"");
2844                                 xpath.Append (parameters.Current.Value);
2845                                 xpath.Append ("\"");
2846                         }
2847                         xpath.Append ("]/..");
2848                 }
2849                 return xpath.ToString ();
2850         }
2851
2852         public static string GetXPathForMember (MemberReference member)
2853         {
2854                 StringBuilder xpath = new StringBuilder ();
2855                 xpath.Append ("//Type[@FullName=\"")
2856                         .Append (member.DeclaringType.FullName)
2857                         .Append ("\"]/");
2858                 xpath.Append ("Members/Member[@MemberName=\"")
2859                         .Append (GetMemberName (member))
2860                         .Append ("\"]");
2861
2862                 IList<ParameterDefinition> parameters = null;
2863                 if (member is MethodDefinition)
2864                         parameters = ((MethodDefinition) member).Parameters;
2865                 else if (member is PropertyDefinition) {
2866                         parameters = ((PropertyDefinition) member).Parameters;
2867                 }
2868                 if (parameters != null && parameters.Count > 0) {
2869                         xpath.Append ("/Parameters[count(Parameter) = ")
2870                                 .Append (parameters.Count);
2871                         for (int i = 0; i < parameters.Count; ++i) {
2872                                 xpath.Append (" and Parameter [").Append (i+1).Append ("]/@Type=\"");
2873                                 xpath.Append (GetDocParameterType (parameters [i].ParameterType));
2874                                 xpath.Append ("\"");
2875                         }
2876                         xpath.Append ("]/..");
2877                 }
2878                 return xpath.ToString ();
2879         }
2880 }
2881
2882 static class CecilExtensions {
2883         public static string GetDeclaringType(this CustomAttribute attribute)
2884         {
2885                         var type = attribute.Constructor.DeclaringType;
2886                         var typeName = type.FullName;
2887
2888                         string translatedType = NativeTypeManager.GetTranslatedName (type);
2889                         return translatedType;
2890         }
2891
2892         public static IEnumerable<MemberReference> GetMembers (this TypeDefinition type)
2893         {
2894                 foreach (var c in type.Methods.Where (m => m.IsConstructor))
2895                         yield return (MemberReference) c;
2896                 foreach (var e in type.Events)
2897                         yield return (MemberReference) e;
2898                 foreach (var f in type.Fields)
2899                         yield return (MemberReference) f;
2900                 foreach (var m in type.Methods.Where (m => !m.IsConstructor))
2901                         yield return (MemberReference) m;
2902                 foreach (var t in type.NestedTypes)
2903                         yield return (MemberReference) t;
2904                 foreach (var p in type.Properties)
2905                         yield return (MemberReference) p;
2906         }
2907
2908         public static IEnumerable<MemberReference> GetMembers (this TypeDefinition type, string member)
2909         {
2910                 return GetMembers (type).Where (m => m.Name == member);
2911         }
2912
2913         public static MemberReference GetMember (this TypeDefinition type, string member)
2914         {
2915                 return GetMembers (type, member).EnsureZeroOrOne ();
2916         }
2917
2918         static T EnsureZeroOrOne<T> (this IEnumerable<T> source)
2919         {
2920                 if (source.Count () > 1)
2921                         throw new InvalidOperationException ("too many matches");
2922                 return source.FirstOrDefault ();
2923         }
2924
2925         public static MethodDefinition GetMethod (this TypeDefinition type, string method)
2926         {
2927                 return type.Methods
2928                         .Where (m => m.Name == method)
2929                         .EnsureZeroOrOne ();
2930         }
2931
2932         public static IEnumerable<MemberReference> GetDefaultMembers (this TypeReference type)
2933         {
2934                 TypeDefinition def = type as TypeDefinition;
2935                 if (def == null)
2936                         return new MemberReference [0];
2937                 CustomAttribute defMemberAttr = def.CustomAttributes
2938                                 .FirstOrDefault (c => c.AttributeType.FullName == "System.Reflection.DefaultMemberAttribute");
2939                 if (defMemberAttr == null)
2940                         return new MemberReference [0];
2941                 string name = (string) defMemberAttr.ConstructorArguments [0].Value;
2942                 return def.Properties
2943                                 .Where (p => p.Name == name)
2944                                 .Select (p => (MemberReference) p);
2945         }
2946
2947         public static IEnumerable<TypeDefinition> GetTypes (this AssemblyDefinition assembly)
2948         {
2949                 return assembly.Modules.SelectMany (md => md.GetAllTypes ());
2950         }
2951
2952         public static TypeDefinition GetType (this AssemblyDefinition assembly, string type)
2953         {
2954                 return GetTypes (assembly)
2955                         .Where (td => td.FullName == type)
2956                         .EnsureZeroOrOne ();
2957         }
2958
2959         public static bool IsGenericType (this TypeReference type)
2960         {
2961                 return type.GenericParameters.Count > 0;
2962         }
2963
2964         public static bool IsGenericMethod (this MethodReference method)
2965         {
2966                 return method.GenericParameters.Count > 0;
2967         }
2968
2969         public static MemberReference Resolve (this MemberReference member)
2970         {
2971                 FieldReference fr = member as FieldReference;
2972                 if (fr != null)
2973                         return fr.Resolve ();
2974                 MethodReference mr = member as MethodReference;
2975                 if (mr != null)
2976                         return mr.Resolve ();
2977                 TypeReference tr = member as TypeReference;
2978                 if (tr != null)
2979                         return tr.Resolve ();
2980                 PropertyReference pr = member as PropertyReference;
2981                 if (pr != null)
2982                         return pr;
2983                 EventReference er = member as EventReference;
2984                 if (er != null)
2985                         return er;
2986                 throw new NotSupportedException ("Cannot find definition for " + member.ToString ());
2987         }
2988
2989         public static TypeReference GetUnderlyingType (this TypeDefinition type)
2990         {
2991                 if (!type.IsEnum)
2992                         return type;
2993                 return type.Fields.First (f => f.Name == "value__").FieldType;
2994         }
2995
2996         public static IEnumerable<TypeDefinition> GetAllTypes (this ModuleDefinition self)
2997         {
2998                 return self.Types.SelectMany (t => t.GetAllTypes ());
2999         }
3000
3001         static IEnumerable<TypeDefinition> GetAllTypes (this TypeDefinition self)
3002         {
3003                 yield return self;
3004
3005                 if (!self.HasNestedTypes)
3006                         yield break;
3007
3008                 foreach (var type in self.NestedTypes.SelectMany (t => t.GetAllTypes ()))
3009                         yield return type;
3010         }
3011 }
3012
3013 enum ApiStyle {
3014         Classic,
3015         Unified
3016 }
3017
3018 static class DocUtils {
3019
3020         public static bool DoesNotHaveApiStyle(this XmlElement element, ApiStyle style) {
3021                 string styleString = style.ToString ().ToLowerInvariant ();
3022                         string apistylevalue = element.GetAttribute ("apistyle");
3023                         return apistylevalue != styleString || string.IsNullOrWhiteSpace(apistylevalue);
3024         }
3025         public static bool HasApiStyle(this XmlElement element, ApiStyle style) {
3026                 string styleString = style.ToString ().ToLowerInvariant ();
3027                 return element.GetAttribute ("apistyle") == styleString;
3028         }
3029         public static bool HasApiStyle(this XmlNode node, ApiStyle style) 
3030         {
3031                 var attribute = node.Attributes ["apistyle"];
3032                 return attribute != null && attribute.Value == style.ToString ().ToLowerInvariant ();
3033         }
3034         public static void AddApiStyle(this XmlElement element, ApiStyle style) {
3035                 string styleString = style.ToString ().ToLowerInvariant ();
3036                 var existingValue = element.GetAttribute ("apistyle");
3037                 if (string.IsNullOrWhiteSpace (existingValue) || existingValue != styleString) {
3038                         element.SetAttribute ("apistyle", styleString);
3039                 }
3040         }
3041         public static void RemoveApiStyle (this XmlElement element, ApiStyle style) 
3042         {
3043                 string styleString = style.ToString ().ToLowerInvariant ();
3044                 string existingValue = element.GetAttribute ("apistyle");
3045                 if (string.IsNullOrWhiteSpace (existingValue) || existingValue == styleString) {
3046                         element.RemoveAttribute ("apistyle");
3047                 }
3048         }
3049         public static void RemoveApiStyle (this XmlNode node, ApiStyle style) 
3050         {
3051                 var styleAttribute = node.Attributes ["apistyle"];
3052                 if (styleAttribute != null && styleAttribute.Value == style.ToString ().ToLowerInvariant ()) {
3053                         node.Attributes.Remove (styleAttribute);
3054                 }
3055         }
3056
3057         public static bool IsExplicitlyImplemented (MethodDefinition method)
3058         {
3059                 return method.IsPrivate && method.IsFinal && method.IsVirtual;
3060         }
3061
3062         public static string GetTypeDotMember (string name)
3063         {
3064                 int startType, startMethod;
3065                 startType = startMethod = -1;
3066                 for (int i = 0; i < name.Length; ++i) {
3067                         if (name [i] == '.') {
3068                                 startType = startMethod;
3069                                 startMethod = i;
3070                         }
3071                 }
3072                 return name.Substring (startType+1);
3073         }
3074
3075         public static string GetMember (string name)
3076         {
3077                 int i = name.LastIndexOf ('.');
3078                 if (i == -1)
3079                         return name;
3080                 return name.Substring (i+1);
3081         }
3082
3083         public static void GetInfoForExplicitlyImplementedMethod (
3084                         MethodDefinition method, out TypeReference iface, out MethodReference ifaceMethod)
3085         {
3086                 iface = null;
3087                 ifaceMethod = null;
3088                 if (method.Overrides.Count != 1)
3089                         throw new InvalidOperationException ("Could not determine interface type for explicitly-implemented interface member " + method.Name);
3090                 iface = method.Overrides [0].DeclaringType;
3091                 ifaceMethod = method.Overrides [0];
3092         }
3093
3094         public static string GetPropertyName (PropertyDefinition pi)
3095         {
3096                 // Issue: (g)mcs-generated assemblies that explicitly implement
3097                 // properties don't specify the full namespace, just the 
3098                 // TypeName.Property; .NET uses Full.Namespace.TypeName.Property.
3099                 MethodDefinition method = pi.GetMethod;
3100                 if (method == null)
3101                         method = pi.SetMethod;
3102                 if (!IsExplicitlyImplemented (method))
3103                         return pi.Name;
3104
3105                 // Need to determine appropriate namespace for this member.
3106                 TypeReference iface;
3107                 MethodReference ifaceMethod;
3108                 GetInfoForExplicitlyImplementedMethod (method, out iface, out ifaceMethod);
3109                 return string.Join (".", new string[]{
3110                                 DocTypeFullMemberFormatter.Default.GetName (iface),
3111                                 GetMember (pi.Name)});
3112         }
3113
3114         public static string GetNamespace (TypeReference type)
3115         {
3116                 if (type.GetElementType ().IsNested)
3117                         type = type.GetElementType ();
3118                 while (type != null && type.IsNested)
3119                         type = type.DeclaringType;
3120                 if (type == null)
3121                         return string.Empty;
3122
3123                         string typeNS = type.Namespace;
3124
3125                         // first, make sure this isn't a type reference to another assembly/module
3126
3127                         bool isInAssembly = MDocUpdater.IsInAssemblies(type.Module.Name);
3128                         if (isInAssembly && !typeNS.StartsWith ("System") && MDocUpdater.HasDroppedNamespace (type)) {
3129                                 typeNS = string.Format ("{0}.{1}", MDocUpdater.droppedNamespace, typeNS);
3130                         }
3131                         return typeNS;
3132         }
3133
3134         public static string PathCombine (string dir, string path)
3135         {
3136                 if (dir == null)
3137                         dir = "";
3138                 if (path == null)
3139                         path = "";
3140                 return Path.Combine (dir, path);
3141         }
3142
3143         public static bool IsExtensionMethod (MethodDefinition method)
3144         {
3145                 return
3146                         method.CustomAttributes
3147                                         .Any (m => m.AttributeType.FullName == "System.Runtime.CompilerServices.ExtensionAttribute")
3148                         && method.DeclaringType.CustomAttributes
3149                                         .Any (m => m.AttributeType.FullName == "System.Runtime.CompilerServices.ExtensionAttribute");
3150         }
3151
3152         public static bool IsDelegate (TypeDefinition type)
3153         {
3154                 TypeReference baseRef = type.BaseType;
3155                 if (baseRef == null)
3156                         return false;
3157                 return !type.IsAbstract && baseRef.FullName == "System.Delegate" || // FIXME
3158                                 baseRef.FullName == "System.MulticastDelegate";
3159         }
3160
3161         public static List<TypeReference> GetDeclaringTypes (TypeReference type)
3162         {
3163                 List<TypeReference> decls = new List<TypeReference> ();
3164                 decls.Add (type);
3165                 while (type.DeclaringType != null) {
3166                         decls.Add (type.DeclaringType);
3167                         type = type.DeclaringType;
3168                 }
3169                 decls.Reverse ();
3170                 return decls;
3171         }
3172
3173         public static int GetGenericArgumentCount (TypeReference type)
3174         {
3175                 GenericInstanceType inst = type as GenericInstanceType;
3176                 return inst != null
3177                                 ? inst.GenericArguments.Count
3178                                 : type.GenericParameters.Count;
3179         }
3180
3181         public static IEnumerable<TypeReference> GetUserImplementedInterfaces (TypeDefinition type)
3182         {
3183                 HashSet<string> inheritedInterfaces = GetInheritedInterfaces (type);
3184                 List<TypeReference> userInterfaces = new List<TypeReference> ();
3185                 foreach (TypeReference iface in type.Interfaces) {
3186                         TypeReference lookup = iface.Resolve () ?? iface;
3187                         if (!inheritedInterfaces.Contains (GetQualifiedTypeName (lookup)))
3188                                 userInterfaces.Add (iface);
3189                 }
3190                 return userInterfaces.Where (i => MDocUpdater.IsPublic (i.Resolve ()));
3191         }
3192
3193         private static string GetQualifiedTypeName (TypeReference type)
3194         {
3195                 return "[" + type.Scope.Name + "]" + type.FullName;
3196         }
3197
3198         private static HashSet<string> GetInheritedInterfaces (TypeDefinition type)
3199         {
3200                 HashSet<string> inheritedInterfaces = new HashSet<string> ();
3201                 Action<TypeDefinition> a = null;
3202                 a = t => {
3203                         if (t == null) return;
3204                         foreach (TypeReference r in t.Interfaces) {
3205                                 inheritedInterfaces.Add (GetQualifiedTypeName (r));
3206                                 a (r.Resolve ());
3207                         }
3208                 };
3209                 TypeReference baseRef = type.BaseType;
3210                 while (baseRef != null) {
3211                         TypeDefinition baseDef = baseRef.Resolve ();
3212                         if (baseDef != null) {
3213                                 a (baseDef);
3214                                 baseRef = baseDef.BaseType;
3215                         }
3216                         else
3217                                 baseRef = null;
3218                 }
3219                 foreach (TypeReference r in type.Interfaces)
3220                         a (r.Resolve ());
3221                 return inheritedInterfaces;
3222         }
3223 }
3224
3225 class DocsNodeInfo {
3226         public DocsNodeInfo (XmlElement node)
3227         {
3228                 this.Node = node;
3229         }
3230
3231         public DocsNodeInfo (XmlElement node, TypeDefinition type)
3232                 : this (node)
3233         {
3234                 SetType (type);
3235         }
3236
3237         public DocsNodeInfo (XmlElement node, MemberReference member)
3238                 : this (node)
3239         {
3240                 SetMemberInfo (member);
3241         }
3242
3243         void SetType (TypeDefinition type)
3244         {
3245                 if (type == null)
3246                         throw new ArgumentNullException ("type");
3247                 Type = type;
3248                 GenericParameters = new List<GenericParameter> (type.GenericParameters);
3249                 List<TypeReference> declTypes = DocUtils.GetDeclaringTypes (type);
3250                 int maxGenArgs = DocUtils.GetGenericArgumentCount (type);
3251                 for (int i = 0; i < declTypes.Count - 1; ++i) {
3252                         int remove = System.Math.Min (maxGenArgs, 
3253                                         DocUtils.GetGenericArgumentCount (declTypes [i]));
3254                         maxGenArgs -= remove;
3255                         while (remove-- > 0)
3256                                 GenericParameters.RemoveAt (0);
3257                 }
3258                 if (DocUtils.IsDelegate (type)) {
3259                         Parameters = type.GetMethod("Invoke").Parameters;
3260                         ReturnType = type.GetMethod("Invoke").ReturnType;
3261                         ReturnIsReturn = true;
3262                 }
3263         }
3264
3265         void SetMemberInfo (MemberReference member)
3266         {
3267                 if (member == null)
3268                         throw new ArgumentNullException ("member");
3269                 ReturnIsReturn = true;
3270                 AddRemarks = true;
3271                 Member = member;
3272                 
3273                 if (member is MethodReference ) {
3274                         MethodReference mr = (MethodReference) member;
3275                         Parameters = mr.Parameters;
3276                         if (mr.IsGenericMethod ()) {
3277                                 GenericParameters = new List<GenericParameter> (mr.GenericParameters);
3278                         }
3279                 }
3280                 else if (member is PropertyDefinition) {
3281                         Parameters = ((PropertyDefinition) member).Parameters;
3282                 }
3283                         
3284                 if (member is MethodDefinition) {
3285                         ReturnType = ((MethodDefinition) member).ReturnType;
3286                 } else if (member is PropertyDefinition) {
3287                         ReturnType = ((PropertyDefinition) member).PropertyType;
3288                         ReturnIsReturn = false;
3289                 }
3290
3291                 // no remarks section for enum members
3292                 if (member.DeclaringType != null && ((TypeDefinition) member.DeclaringType).IsEnum)
3293                         AddRemarks = false;
3294         }
3295
3296         public TypeReference ReturnType;
3297         public List<GenericParameter> GenericParameters;
3298         public IList<ParameterDefinition> Parameters;
3299         public bool ReturnIsReturn;
3300         public XmlElement Node;
3301         public bool AddRemarks = true;
3302         public MemberReference Member;
3303         public TypeDefinition Type;
3304
3305         public override string ToString ()
3306         {
3307                 return string.Format ("{0} - {1} - {2}", Type, Member, Node == null ? "no xml" : "with xml");
3308         }
3309 }
3310
3311 class DocumentationEnumerator {
3312         
3313         public virtual IEnumerable<TypeDefinition> GetDocumentationTypes (AssemblyDefinition assembly, List<string> forTypes)
3314         {
3315                 return GetDocumentationTypes (assembly, forTypes, null);
3316         }
3317
3318         protected IEnumerable<TypeDefinition> GetDocumentationTypes (AssemblyDefinition assembly, List<string> forTypes, HashSet<string> seen)
3319         {
3320                 foreach (TypeDefinition type in assembly.GetTypes()) {
3321                         if (forTypes != null && forTypes.BinarySearch (type.FullName) < 0)
3322                                 continue;
3323                         if (seen != null && seen.Contains (type.FullName))
3324                                 continue;
3325                         yield return type;
3326                         foreach (TypeDefinition nested in type.NestedTypes)
3327                                 yield return nested;
3328                 }
3329         }
3330
3331         public virtual IEnumerable<DocsNodeInfo> GetDocumentationMembers (XmlDocument basefile, TypeDefinition type)
3332         {
3333                 foreach (XmlElement oldmember in basefile.SelectNodes("Type/Members/Member")) {
3334                         if (oldmember.GetAttribute ("__monodocer-seen__") == "true") {
3335                                 oldmember.RemoveAttribute ("__monodocer-seen__");
3336                                 continue;
3337                         }
3338                         MemberReference m = GetMember (type, new DocumentationMember (oldmember));
3339                         if (m == null) {
3340                                 yield return new DocsNodeInfo (oldmember);
3341                         }
3342                         else {
3343                                 yield return new DocsNodeInfo (oldmember, m);
3344                         }
3345                 }
3346         }
3347
3348         protected static MemberReference GetMember (TypeDefinition type, DocumentationMember member)
3349         {
3350                 string membertype = member.MemberType;
3351                 
3352                 string returntype = member.ReturnType;
3353                 
3354                 string docName = member.MemberName;
3355
3356                 string[] docTypeParams = GetTypeParameters (docName, member.TypeParameters);
3357
3358                 // If we're using 'magic types', then we might get false positives ... in those cases, we keep searching
3359                 MemberReference likelyCandidate = null;
3360                 
3361                 // Loop through all members in this type with the same name
3362                 var reflectedMembers = GetReflectionMembers (type, docName).ToArray ();
3363                 foreach (MemberReference mi in reflectedMembers) {
3364                         bool matchedMagicType = false;
3365                         if (mi is TypeDefinition) continue;
3366                         if (MDocUpdater.GetMemberType(mi) != membertype) continue;
3367
3368                         if (MDocUpdater.IsPrivate (mi))
3369                                 continue;
3370
3371                         IList<ParameterDefinition> pis = null;
3372                         string[] typeParams = null;
3373                         if (mi is MethodDefinition) {
3374                                 MethodDefinition mb = (MethodDefinition) mi;
3375                                 pis = mb.Parameters;
3376                                 if (mb.IsGenericMethod ()) {
3377                                         IList<GenericParameter> args = mb.GenericParameters;
3378                                         typeParams = args.Select (p => p.Name).ToArray ();
3379                                 }
3380                         }
3381                         else if (mi is PropertyDefinition)
3382                                 pis = ((PropertyDefinition)mi).Parameters;
3383                                 
3384                         // check type parameters
3385                         int methodTcount = member.TypeParameters == null ? 0 : member.TypeParameters.Count;
3386                         int reflectionTcount = typeParams == null ? 0 : typeParams.Length;
3387                         if (methodTcount != reflectionTcount) 
3388                                 continue;
3389
3390                         // check member parameters
3391                         int mcount = member.Parameters == null ? 0 : member.Parameters.Count;
3392                         int pcount = pis == null ? 0 : pis.Count;
3393                         if (mcount != pcount)
3394                                 continue;
3395
3396                         MethodDefinition mDef = mi as MethodDefinition;
3397                         if (mDef != null && !mDef.IsConstructor) {
3398                                 // Casting operators can overload based on return type.
3399                                 string rtype = GetReplacedString (
3400                                                        MDocUpdater.GetDocTypeFullName (((MethodDefinition)mi).ReturnType), 
3401                                                        typeParams, docTypeParams);
3402                                 string originalRType = rtype;
3403                                 if (MDocUpdater.SwitchingToMagicTypes) {
3404                                         rtype = NativeTypeManager.ConvertFromNativeType (rtype);
3405                                         
3406                                 }
3407                                 if ((returntype != rtype && originalRType == rtype) ||
3408                                         (MDocUpdater.SwitchingToMagicTypes && returntype != originalRType && returntype != rtype && originalRType != rtype)) {
3409                                         continue;
3410                                 }
3411
3412                                 if (originalRType != rtype)
3413                                         matchedMagicType = true;
3414                         }
3415
3416                         if (pcount == 0)
3417                                 return mi;
3418                         bool good = true;
3419                         for (int i = 0; i < pis.Count; i++) {
3420                                 string paramType = GetReplacedString (
3421                                         MDocUpdater.GetDocParameterType (pis [i].ParameterType),
3422                                         typeParams, docTypeParams);
3423
3424                                 // if magictypes, replace paramType to "classic value" ... so the comparison works
3425                                 string originalParamType = paramType;
3426                                 if (MDocUpdater.SwitchingToMagicTypes) {
3427                                         paramType = NativeTypeManager.ConvertFromNativeType (paramType);
3428                                 }
3429
3430                                 string xmlMemberType = member.Parameters [i];
3431                                 if ((!paramType.Equals(xmlMemberType) && paramType.Equals(originalParamType)) || 
3432                                         (MDocUpdater.SwitchingToMagicTypes && !originalParamType.Equals(xmlMemberType) && !paramType.Equals(xmlMemberType) && !paramType.Equals(originalParamType))) {
3433
3434                                         // did not match ... if we're dropping the namespace, and the paramType has the dropped
3435                                         // namespace, we should see if it matches when added
3436                                         bool stillDoesntMatch = true;
3437                                         if (MDocUpdater.HasDroppedNamespace(type) && paramType.StartsWith (MDocUpdater.droppedNamespace)) {
3438                                                 string withDroppedNs = string.Format ("{0}.{1}", MDocUpdater.droppedNamespace, xmlMemberType);
3439
3440                                                 stillDoesntMatch = withDroppedNs != paramType;
3441                                         }
3442
3443                                         if (stillDoesntMatch) {
3444                                                 good = false;
3445                                                 break;
3446                                         }
3447                                 }
3448
3449                                 if (originalParamType != paramType)
3450                                         matchedMagicType = true;
3451                         }
3452                         if (!good) continue;
3453
3454                         if (MDocUpdater.SwitchingToMagicTypes && likelyCandidate == null && matchedMagicType) {
3455                                 // we matched this on a magic type conversion ... let's keep going to see if there's another one we should look at that matches more closely
3456                                 likelyCandidate = mi;
3457                                 continue;
3458                         }
3459
3460                         return mi;
3461                 }
3462                 
3463                 return likelyCandidate;
3464         }
3465
3466         static string[] GetTypeParameters (string docName, IEnumerable<string> knownParameters)
3467         {
3468                 if (docName [docName.Length-1] != '>')
3469                         return null;
3470                 StringList types = new StringList ();
3471                 int endToken = docName.Length-2;
3472                 int i = docName.Length-2;
3473                 do {
3474                         if (docName [i] == ',' || docName [i] == '<') {
3475                                 types.Add (docName.Substring (i + 1, endToken - i));
3476                                 endToken = i-1;
3477                         }
3478                         if (docName [i] == '<')
3479                                 break;
3480                 } while (--i >= 0);
3481
3482                 types.Reverse ();
3483                 var arrayTypes = types.ToArray ();
3484
3485                 if (knownParameters != null && knownParameters.Any () && arrayTypes.Length != knownParameters.Count ())
3486                         return knownParameters.ToArray ();
3487                 else
3488                         return arrayTypes;
3489         }
3490
3491         protected static IEnumerable<MemberReference> GetReflectionMembers (TypeDefinition type, string docName)
3492         {
3493                 // In case of dropping the namespace, we have to remove the dropped NS
3494                 // so that docName will match what's in the assembly/type
3495                 if (MDocUpdater.HasDroppedNamespace (type) && docName.StartsWith(MDocUpdater.droppedNamespace + ".")) {
3496                         int droppedNsLength = MDocUpdater.droppedNamespace.Length;
3497                         docName = docName.Substring (droppedNsLength + 1, docName.Length - droppedNsLength - 1);
3498                 }
3499
3500                 // need to worry about 4 forms of //@MemberName values:
3501                 //  1. "Normal" (non-generic) member names: GetEnumerator
3502                 //    - Lookup as-is.
3503                 //  2. Explicitly-implemented interface member names: System.Collections.IEnumerable.Current
3504                 //    - try as-is, and try type.member (due to "kludge" for property
3505                 //      support.
3506                 //  3. "Normal" Generic member names: Sort<T> (CSC)
3507                 //    - need to remove generic parameters --> "Sort"
3508                 //  4. Explicitly-implemented interface members for generic interfaces: 
3509                 //    -- System.Collections.Generic.IEnumerable<T>.Current
3510                 //    - Try as-is, and try type.member, *keeping* the generic parameters.
3511                 //     --> System.Collections.Generic.IEnumerable<T>.Current, IEnumerable<T>.Current
3512                 //  5. As of 2008-01-02, gmcs will do e.g. 'IFoo`1[A].Method' instead of
3513                 //    'IFoo<A>.Method' for explicitly implemented methods; don't interpret
3514                 //    this as (1) or (2).
3515                 if (docName.IndexOf ('<') == -1 && docName.IndexOf ('[') == -1) {
3516                         // Cases 1 & 2
3517                         foreach (MemberReference mi in type.GetMembers (docName))
3518                                 yield return mi;
3519                         if (CountChars (docName, '.') > 0)
3520                                 // might be a property; try only type.member instead of
3521                                 // namespace.type.member.
3522                                 foreach (MemberReference mi in 
3523                                                 type.GetMembers (DocUtils.GetTypeDotMember (docName)))
3524                                         yield return mi;
3525                         yield break;
3526                 }
3527                 // cases 3 & 4
3528                 int numLt = 0;
3529                 int numDot = 0;
3530                 int startLt, startType, startMethod;
3531                 startLt = startType = startMethod = -1;
3532                 for (int i = 0; i < docName.Length; ++i) {
3533                         switch (docName [i]) {
3534                                 case '<':
3535                                         if (numLt == 0) {
3536                                                 startLt = i;
3537                                         }
3538                                         ++numLt;
3539                                         break;
3540                                 case '>':
3541                                         --numLt;
3542                                         if (numLt == 0 && (i + 1) < docName.Length)
3543                                                 // there's another character in docName, so this <...> sequence is
3544                                                 // probably part of a generic type -- case 4.
3545                                                 startLt = -1;
3546                                         break;
3547                                 case '.':
3548                                         startType = startMethod;
3549                                         startMethod = i;
3550                                         ++numDot;
3551                                         break;
3552                         }
3553                 }
3554                 string refName = startLt == -1 ? docName : docName.Substring (0, startLt);
3555                 // case 3
3556                 foreach (MemberReference mi in type.GetMembers (refName))
3557                         yield return mi;
3558
3559                 // case 4
3560                 foreach (MemberReference mi in type.GetMembers (refName.Substring (startType + 1)))
3561                         yield return mi;
3562
3563                 // If we _still_ haven't found it, we've hit another generic naming issue:
3564                 // post Mono 1.1.18, gmcs generates [[FQTN]] instead of <TypeName> for
3565                 // explicitly-implemented METHOD names (not properties), e.g. 
3566                 // "System.Collections.Generic.IEnumerable`1[[Foo, test, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]].GetEnumerator"
3567                 // instead of "System.Collections.Generic.IEnumerable<Foo>.GetEnumerator",
3568                 // which the XML docs will contain.
3569                 //
3570                 // Alas, we can't derive the Mono name from docName, so we need to iterate
3571                 // over all member names, convert them into CSC format, and compare... :-(
3572                 if (numDot == 0)
3573                         yield break;
3574                 foreach (MemberReference mi in type.GetMembers ()) {
3575                         if (MDocUpdater.GetMemberName (mi) == docName)
3576                                 yield return mi;
3577                 }
3578         }
3579
3580         static string GetReplacedString (string typeName, string[] from, string[] to)
3581         {
3582                 if (from == null)
3583                         return typeName;
3584                 for (int i = 0; i < from.Length; ++i)
3585                         typeName = typeName.Replace (from [i], to [i]);
3586                 return typeName;
3587         }
3588
3589         private static int CountChars (string s, char c)
3590         {
3591                 int count = 0;
3592                 for (int i = 0; i < s.Length; ++i) {
3593                         if (s [i] == c)
3594                                 ++count;
3595                 }
3596                 return count;
3597         }
3598 }
3599
3600 class EcmaDocumentationEnumerator : DocumentationEnumerator {
3601
3602         XmlReader ecmadocs;
3603         MDocUpdater app;
3604
3605         public EcmaDocumentationEnumerator (MDocUpdater app, XmlReader ecmaDocs)
3606         {
3607                 this.app      = app;
3608                 this.ecmadocs = ecmaDocs;
3609         }
3610
3611         public override IEnumerable<TypeDefinition> GetDocumentationTypes (AssemblyDefinition assembly, List<string> forTypes)
3612         {
3613                 HashSet<string> seen = new HashSet<string> ();
3614                 return GetDocumentationTypes (assembly, forTypes, seen)
3615                         .Concat (base.GetDocumentationTypes (assembly, forTypes, seen));
3616         }
3617
3618         new IEnumerable<TypeDefinition> GetDocumentationTypes (AssemblyDefinition assembly, List<string> forTypes, HashSet<string> seen)
3619         {
3620                 int typeDepth = -1;
3621                 while (ecmadocs.Read ()) {
3622                         switch (ecmadocs.Name) {
3623                                 case "Type": {
3624                                         if (typeDepth == -1)
3625                                                 typeDepth = ecmadocs.Depth;
3626                                         if (ecmadocs.NodeType != XmlNodeType.Element)
3627                                                 continue;
3628                                         if (typeDepth != ecmadocs.Depth) // nested <TypeDefinition/> element?
3629                                                 continue;
3630                                         string typename = ecmadocs.GetAttribute ("FullName");
3631                                         string typename2 = MDocUpdater.GetTypeFileName (typename);
3632                                         if (forTypes != null && 
3633                                                         forTypes.BinarySearch (typename) < 0 &&
3634                                                         typename != typename2 &&
3635                                                         forTypes.BinarySearch (typename2) < 0)
3636                                                 continue;
3637                                         TypeDefinition t;
3638                                         if ((t = assembly.GetType (typename)) == null && 
3639                                                         (t = assembly.GetType (typename2)) == null)
3640                                                 continue;
3641                                         seen.Add (typename);
3642                                         if (typename != typename2)
3643                                                 seen.Add (typename2);
3644                                         Console.WriteLine ("  Import: {0}", t.FullName);
3645                                         if (ecmadocs.Name != "Docs") {
3646                                                 int depth = ecmadocs.Depth;
3647                                                 while (ecmadocs.Read ()) {
3648                                                         if (ecmadocs.Name == "Docs" && ecmadocs.Depth == depth + 1)
3649                                                                 break;
3650                                                 }
3651                                         }
3652                                         if (!ecmadocs.IsStartElement ("Docs"))
3653                                                 throw new InvalidOperationException ("Found " + ecmadocs.Name + "; expecting <Docs/>!");
3654                                         yield return t;
3655                                         break;
3656                                 }
3657                                 default:
3658                                         break;
3659                         }
3660                 }
3661         }
3662
3663         public override IEnumerable<DocsNodeInfo> GetDocumentationMembers (XmlDocument basefile, TypeDefinition type)
3664         {
3665                 return GetMembers (basefile, type)
3666                         .Concat (base.GetDocumentationMembers (basefile, type));
3667         }
3668
3669         private IEnumerable<DocsNodeInfo> GetMembers (XmlDocument basefile, TypeDefinition type)
3670         {
3671                 while (ecmadocs.Name != "Members" && ecmadocs.Read ()) {
3672                         // do nothing
3673                 }
3674                 if (ecmadocs.IsEmptyElement)
3675                         yield break;
3676
3677                 int membersDepth = ecmadocs.Depth;
3678                 bool go = true;
3679                 while (go && ecmadocs.Read ()) {
3680                         switch (ecmadocs.Name) {
3681                                 case "Member": {
3682                                         if (membersDepth != ecmadocs.Depth - 1 || ecmadocs.NodeType != XmlNodeType.Element)
3683                                                 continue;
3684                                         DocumentationMember dm = new DocumentationMember (ecmadocs);
3685                                         
3686                                         string xp = MDocUpdater.GetXPathForMember (dm);
3687                                         XmlElement oldmember = (XmlElement) basefile.SelectSingleNode (xp);
3688                                         MemberReference m;
3689                                         if (oldmember == null) {
3690                                                 m = GetMember (type, dm);
3691                                                 if (m == null) {
3692                                                         app.Warning ("Could not import ECMA docs for `{0}'s `{1}': Member not found.",
3693                                                                         type.FullName, dm.MemberSignatures ["C#"]);
3694                                                                         // SelectSingleNode (ecmaDocsMember, "MemberSignature[@Language=\"C#\"]/@Value").Value);
3695                                                         continue;
3696                                                 }
3697                                                 // oldmember lookup may have failed due to type parameter renames.
3698                                                 // Try again.
3699                                                 oldmember = (XmlElement) basefile.SelectSingleNode (MDocUpdater.GetXPathForMember (m));
3700                                                 if (oldmember == null) {
3701                                                         XmlElement members = MDocUpdater.WriteElement (basefile.DocumentElement, "Members");
3702                                                         oldmember = basefile.CreateElement ("Member");
3703                                                         oldmember.SetAttribute ("MemberName", dm.MemberName);
3704                                                         members.AppendChild (oldmember);
3705                                                         foreach (string key in MDocUpdater.Sort (dm.MemberSignatures.Keys)) {
3706                                                                 XmlElement ms = basefile.CreateElement ("MemberSignature");
3707                                                                 ms.SetAttribute ("Language", key);
3708                                                                 ms.SetAttribute ("Value", (string) dm.MemberSignatures [key]);
3709                                                                 oldmember.AppendChild (ms);
3710                                                         }
3711                                                         oldmember.SetAttribute ("__monodocer-seen__", "true");
3712                                                         Console.WriteLine ("Member Added: {0}", oldmember.SelectSingleNode("MemberSignature[@Language='C#']/@Value").InnerText);
3713                                                         app.additions++;
3714                                                 }
3715                                         }
3716                                         else {
3717                                                 m = GetMember (type, new DocumentationMember (oldmember));
3718                                                 if (m == null) {
3719                                                         app.Warning ("Could not import ECMA docs for `{0}'s `{1}': Member not found.",
3720                                                                         type.FullName, dm.MemberSignatures ["C#"]);
3721                                                         continue;
3722                                                 }
3723                                                 oldmember.SetAttribute ("__monodocer-seen__", "true");
3724                                         }
3725                                         DocsNodeInfo node = new DocsNodeInfo (oldmember, m);
3726                                         if (ecmadocs.Name != "Docs")
3727                                                 throw new InvalidOperationException ("Found " + ecmadocs.Name + "; expected <Docs/>!");
3728                                         yield return node;
3729                                         break;
3730                                 }
3731                                 case "Members":
3732                                         if (membersDepth == ecmadocs.Depth && ecmadocs.NodeType == XmlNodeType.EndElement) {
3733                                                 go = false;
3734                                         }
3735                                         break;
3736                         }
3737                 }
3738         }
3739 }
3740
3741 abstract class DocumentationImporter {
3742
3743         public abstract void ImportDocumentation (DocsNodeInfo info);
3744 }
3745
3746 class MsxdocDocumentationImporter : DocumentationImporter {
3747
3748         XmlDocument slashdocs;
3749
3750         public MsxdocDocumentationImporter (string file)
3751         {
3752                 var xml = File.ReadAllText (file);
3753
3754                 // Ensure Unix line endings
3755                 xml = xml.Replace ("\r", "");
3756
3757                 slashdocs = new XmlDocument();
3758                 slashdocs.LoadXml (xml);
3759         }
3760
3761         public override void ImportDocumentation (DocsNodeInfo info)
3762         {
3763                 XmlNode elem = GetDocs (info.Member ?? info.Type);
3764
3765                 if (elem == null)
3766                         return;
3767
3768                 XmlElement e = info.Node;
3769
3770                 if (elem.SelectSingleNode("summary") != null)
3771                         MDocUpdater.ClearElement(e, "summary");
3772                 if (elem.SelectSingleNode("remarks") != null)
3773                         MDocUpdater.ClearElement(e, "remarks");
3774                 if (elem.SelectSingleNode ("value") != null || elem.SelectSingleNode ("returns") != null) {
3775                         MDocUpdater.ClearElement(e, "value");
3776                         MDocUpdater.ClearElement(e, "returns");
3777                 }
3778
3779                 foreach (XmlNode child in elem.ChildNodes) {
3780                         switch (child.Name) {
3781                                 case "param":
3782                                 case "typeparam": {
3783                                         XmlAttribute name = child.Attributes ["name"];
3784                                         if (name == null)
3785                                                 break;
3786                                         XmlElement p2 = (XmlElement) e.SelectSingleNode (child.Name + "[@name='" + name.Value + "']");
3787                                         if (p2 != null)
3788                                                 p2.InnerXml = child.InnerXml;
3789                                         break;
3790                                 }
3791                                 // Occasionally XML documentation will use <returns/> on
3792                                 // properties, so let's try to normalize things.
3793                                 case "value":
3794                                 case "returns": {
3795                                         XmlElement v = e.OwnerDocument.CreateElement (info.ReturnIsReturn ? "returns" : "value");
3796                                         v.InnerXml = child.InnerXml;
3797                                         e.AppendChild (v);
3798                                         break;
3799                                 }
3800                                 case "altmember":
3801                                 case "exception":
3802                                 case "permission": {
3803                                         XmlAttribute cref = child.Attributes ["cref"] ?? child.Attributes ["name"];
3804                                         if (cref == null)
3805                                                 break;
3806                                         XmlElement a = (XmlElement) e.SelectSingleNode (child.Name + "[@cref='" + cref.Value + "']");
3807                                         if (a == null) {
3808                                                 a = e.OwnerDocument.CreateElement (child.Name);
3809                                                 a.SetAttribute ("cref", cref.Value);
3810                                                 e.AppendChild (a);
3811                                         }
3812                                         a.InnerXml = child.InnerXml;
3813                                         break;
3814                                 }
3815                                 case "seealso": {
3816                                         XmlAttribute cref = child.Attributes ["cref"];
3817                                         if (cref == null)
3818                                                 break;
3819                                         XmlElement a = (XmlElement) e.SelectSingleNode ("altmember[@cref='" + cref.Value + "']");
3820                                         if (a == null) {
3821                                                 a = e.OwnerDocument.CreateElement ("altmember");
3822                                                 a.SetAttribute ("cref", cref.Value);
3823                                                 e.AppendChild (a);
3824                                         }
3825                                         break;
3826                                 }
3827                                 default: {
3828                                         bool add = true;
3829                                         if (child.NodeType == XmlNodeType.Element && 
3830                                                         e.SelectNodes (child.Name).Cast<XmlElement>().Any (n => n.OuterXml == child.OuterXml))
3831                                                 add = false;
3832                                         if (add)
3833                                                 MDocUpdater.CopyNode (child, e);
3834                                         break;
3835                                 }
3836                         }
3837                 }
3838         }
3839
3840         private XmlNode GetDocs (MemberReference member)
3841         {
3842                 string slashdocsig = MDocUpdater.slashdocFormatter.GetDeclaration (member);
3843                 if (slashdocsig != null)
3844                         return slashdocs.SelectSingleNode ("doc/members/member[@name='" + slashdocsig + "']");
3845                 return null;
3846         }
3847 }
3848
3849 class EcmaDocumentationImporter : DocumentationImporter {
3850
3851         XmlReader ecmadocs;
3852
3853         public EcmaDocumentationImporter (XmlReader ecmaDocs)
3854         {
3855                 this.ecmadocs = ecmaDocs;
3856         }
3857
3858         public override void ImportDocumentation (DocsNodeInfo info)
3859         {
3860                 if (!ecmadocs.IsStartElement ("Docs")) {
3861                         return;
3862                 }
3863
3864                 XmlElement e = info.Node;
3865
3866                 int depth = ecmadocs.Depth;
3867                 ecmadocs.ReadStartElement ("Docs");
3868                 while (ecmadocs.Read ()) {
3869                         if (ecmadocs.Name == "Docs") {
3870                                 if (ecmadocs.Depth == depth && ecmadocs.NodeType == XmlNodeType.EndElement)
3871                                         break;
3872                                 else
3873                                         throw new InvalidOperationException ("Skipped past current <Docs/> element!");
3874                         }
3875                         if (!ecmadocs.IsStartElement ())
3876                                 continue;
3877                         switch (ecmadocs.Name) {
3878                                 case "param":
3879                                 case "typeparam": {
3880                                         string name = ecmadocs.GetAttribute ("name");
3881                                         if (name == null)
3882                                                 break;
3883                                         XmlNode doc = e.SelectSingleNode (
3884                                                         ecmadocs.Name + "[@name='" + name + "']");
3885                                         string value = ecmadocs.ReadInnerXml ();
3886                                         if (doc != null)
3887                                                 doc.InnerXml = value.Replace ("\r", "");
3888                                         break;
3889                                 }
3890                                 case "altmember":
3891                                 case "exception":
3892                                 case "permission":
3893                                 case "seealso": {
3894                                         string name = ecmadocs.Name;
3895                                         string cref = ecmadocs.GetAttribute ("cref");
3896                                         if (cref == null)
3897                                                 break;
3898                                         XmlNode doc = e.SelectSingleNode (
3899                                                         ecmadocs.Name + "[@cref='" + cref + "']");
3900                                         string value = ecmadocs.ReadInnerXml ().Replace ("\r", "");
3901                                         if (doc != null)
3902                                                 doc.InnerXml = value;
3903                                         else {
3904                                                 XmlElement n = e.OwnerDocument.CreateElement (name);
3905                                                 n.SetAttribute ("cref", cref);
3906                                                 n.InnerXml = value;
3907                                                 e.AppendChild (n);
3908                                         }
3909                                         break;
3910                                 }
3911                                 default: {
3912                                         string name = ecmadocs.Name;
3913                                         string xpath = ecmadocs.Name;
3914                                         StringList attributes = new StringList (ecmadocs.AttributeCount);
3915                                         if (ecmadocs.MoveToFirstAttribute ()) {
3916                                                 do {
3917                                                         attributes.Add ("@" + ecmadocs.Name + "=\"" + ecmadocs.Value + "\"");
3918                                                 } while (ecmadocs.MoveToNextAttribute ());
3919                                                 ecmadocs.MoveToContent ();
3920                                         }
3921                                         if (attributes.Count > 0) {
3922                                                 xpath += "[" + string.Join (" and ", attributes.ToArray ()) + "]";
3923                                         }
3924                                         XmlNode doc = e.SelectSingleNode (xpath);
3925                                         string value = ecmadocs.ReadInnerXml ().Replace ("\r", "");
3926                                         if (doc != null) {
3927                                                 doc.InnerXml = value;
3928                                         }
3929                                         else {
3930                                                 XmlElement n = e.OwnerDocument.CreateElement (name);
3931                                                 n.InnerXml = value;
3932                                                 foreach (string a in attributes) {
3933                                                         int eq = a.IndexOf ('=');
3934                                                         n.SetAttribute (a.Substring (1, eq-1), a.Substring (eq+2, a.Length-eq-3));
3935                                                 }
3936                                                 e.AppendChild (n);
3937                                         }
3938                                         break;
3939                                 }
3940                         }
3941                 }
3942         }
3943 }
3944
3945 class DocumentationMember {
3946         public StringToStringMap MemberSignatures = new StringToStringMap ();
3947         public string ReturnType;
3948         public StringList Parameters;
3949         public StringList TypeParameters;
3950         public string MemberName;
3951         public string MemberType;
3952
3953         public DocumentationMember (XmlReader reader)
3954         {
3955                 MemberName = reader.GetAttribute ("MemberName");
3956                 int depth = reader.Depth;
3957                 bool go = true;
3958                 StringList p = new StringList ();
3959                 StringList tp = new StringList ();
3960                 do {
3961                         if (reader.NodeType != XmlNodeType.Element)
3962                                 continue;
3963
3964                         bool shouldUse = true;
3965                         try {
3966                                 string apistyle = reader.GetAttribute ("apistyle");
3967                                 shouldUse = string.IsNullOrWhiteSpace(apistyle) || apistyle == "classic"; // only use this tag if it's an 'classic' style node
3968                         }
3969                         catch (Exception ex) {}
3970                         switch (reader.Name) {
3971                                 case "MemberSignature":
3972                                         if (shouldUse) {
3973                                                 MemberSignatures [reader.GetAttribute ("Language")] = reader.GetAttribute ("Value");
3974                                         }
3975                                         break;
3976                                 case "MemberType":
3977                                         MemberType = reader.ReadElementString ();
3978                                         break;
3979                                 case "ReturnType":
3980                                         if (reader.Depth == depth + 2 && shouldUse)
3981                                                 ReturnType = reader.ReadElementString ();
3982                                         break;
3983                                 case "Parameter":
3984                                         if (reader.Depth == depth + 2 && shouldUse)
3985                                                 p.Add (reader.GetAttribute ("Type"));
3986                                         break;
3987                                 case "TypeParameter":
3988                                         if (reader.Depth == depth + 2 && shouldUse)
3989                                                 tp.Add (reader.GetAttribute ("Name"));
3990                                         break;
3991                                 case "Docs":
3992                                         if (reader.Depth == depth + 1)
3993                                                 go = false;
3994                                         break;
3995                         }
3996                 } while (go && reader.Read () && reader.Depth >= depth);
3997                 if (p.Count > 0) {
3998                         Parameters = p;
3999                 }
4000                 if (tp.Count > 0) {
4001                         TypeParameters = tp;
4002                 } else {
4003                         DiscernTypeParameters ();
4004                 }
4005         }
4006
4007         public DocumentationMember (XmlNode node)
4008         {
4009                 MemberName = node.Attributes ["MemberName"].Value;
4010                 foreach (XmlNode n in node.SelectNodes ("MemberSignature")) {
4011                         XmlAttribute l = n.Attributes ["Language"];
4012                         XmlAttribute v = n.Attributes ["Value"];
4013                         XmlAttribute apistyle = n.Attributes ["apistyle"];
4014                         bool shouldUse = apistyle == null || apistyle.Value == "classic";
4015                         if (l != null && v != null && shouldUse)
4016                                 MemberSignatures [l.Value] = v.Value;
4017                 }
4018                 MemberType = node.SelectSingleNode ("MemberType").InnerText;
4019                 XmlNode rt = node.SelectSingleNode ("ReturnValue/ReturnType[not(@apistyle) or @apistyle='classic']");
4020                 if (rt != null)
4021                         ReturnType = rt.InnerText;
4022                 XmlNodeList p = node.SelectNodes ("Parameters/Parameter[not(@apistyle) or @apistyle='classic']");
4023                 if (p.Count > 0) {
4024                         Parameters = new StringList (p.Count);
4025                         for (int i = 0; i < p.Count; ++i)
4026                                 Parameters.Add (p [i].Attributes ["Type"].Value);
4027                 }
4028                 XmlNodeList tp = node.SelectNodes ("TypeParameters/TypeParameter[not(@apistyle) or @apistyle='classic']");
4029                 if (tp.Count > 0) {
4030                         TypeParameters = new StringList (tp.Count);
4031                         for (int i = 0; i < tp.Count; ++i)
4032                                 TypeParameters.Add (tp [i].Attributes ["Name"].Value);
4033                 }
4034                 else {
4035                         DiscernTypeParameters ();
4036                 }
4037         }
4038
4039         void DiscernTypeParameters ()
4040         {
4041                 // see if we can discern the param list from the name
4042                 if (MemberName.Contains ("<") && MemberName.EndsWith (">")) {
4043                         var starti = MemberName.IndexOf ("<") + 1;
4044                         var endi = MemberName.LastIndexOf (">");
4045                         var paramlist = MemberName.Substring (starti, endi - starti);
4046                         var tparams = paramlist.Split (new char[] {','}, StringSplitOptions.RemoveEmptyEntries);
4047                         TypeParameters = new StringList (tparams);
4048                 }
4049         }
4050 }
4051
4052 public class DynamicParserContext {
4053         public ReadOnlyCollection<bool> TransformFlags;
4054         public int TransformIndex;
4055
4056         public DynamicParserContext (ICustomAttributeProvider provider)
4057         {
4058                 CustomAttribute da;
4059                 if (provider.HasCustomAttributes &&
4060                                 (da = (provider.CustomAttributes.Cast<CustomAttribute>()
4061                                         .SingleOrDefault (ca => ca.GetDeclaringType() == "System.Runtime.CompilerServices.DynamicAttribute"))) != null) {
4062                         CustomAttributeArgument[] values = da.ConstructorArguments.Count == 0
4063                                 ? new CustomAttributeArgument [0]
4064                                 : (CustomAttributeArgument[]) da.ConstructorArguments [0].Value;
4065
4066                         TransformFlags = new ReadOnlyCollection<bool> (values.Select (t => (bool) t.Value).ToArray());
4067                 }
4068         }
4069 }
4070
4071 public enum MemberFormatterState {
4072         None,
4073         WithinGenericTypeParameters,
4074 }
4075
4076 public abstract class MemberFormatter {
4077
4078         public virtual string Language {
4079                 get {return "";}
4080         }
4081
4082         public string GetName (MemberReference member)
4083         {
4084                 return GetName (member, null);
4085         }
4086
4087         public virtual string GetName (MemberReference member, DynamicParserContext context)
4088         {
4089                 TypeReference type = member as TypeReference;
4090                 if (type != null)
4091                         return GetTypeName (type, context);
4092                 MethodReference method  = member as MethodReference;
4093                 if (method != null && method.Name == ".ctor") // method.IsConstructor
4094                         return GetConstructorName (method);
4095                 if (method != null)
4096                         return GetMethodName (method);
4097                 PropertyReference prop = member as PropertyReference;
4098                 if (prop != null)
4099                         return GetPropertyName (prop);
4100                 FieldReference field = member as FieldReference;
4101                 if (field != null)
4102                         return GetFieldName (field);
4103                 EventReference e = member as EventReference;
4104                 if (e != null)
4105                         return GetEventName (e);
4106                 throw new NotSupportedException ("Can't handle: " +
4107                                         (member == null ? "null" : member.GetType().ToString()));
4108         }
4109
4110         protected virtual string GetTypeName (TypeReference type)
4111         {
4112                 return GetTypeName (type, null);
4113         }
4114
4115         protected virtual string GetTypeName (TypeReference type, DynamicParserContext context)
4116         {
4117                 if (type == null)
4118                         throw new ArgumentNullException ("type");
4119                 return _AppendTypeName (new StringBuilder (type.Name.Length), type, context).ToString ();
4120         }
4121
4122         protected virtual char[] ArrayDelimeters {
4123                 get {return new char[]{'[', ']'};}
4124         }
4125
4126         protected virtual MemberFormatterState MemberFormatterState { get; set; }
4127
4128         protected StringBuilder _AppendTypeName (StringBuilder buf, TypeReference type, DynamicParserContext context)
4129         {
4130                 if (type is ArrayType) {
4131                         TypeSpecification spec = type as TypeSpecification;
4132                         _AppendTypeName (buf, spec != null ? spec.ElementType : type.GetElementType (), context);
4133                         return AppendArrayModifiers (buf, (ArrayType) type);
4134                 }
4135                 if (type is ByReferenceType) {
4136                         return AppendRefTypeName (buf, type, context);
4137                 }
4138                 if (type is PointerType) {
4139                         return AppendPointerTypeName (buf, type, context);
4140                 }
4141                 if (type is GenericParameter) {
4142                         return AppendTypeName (buf, type, context);
4143                 }
4144                 AppendNamespace (buf, type);
4145                 GenericInstanceType genInst = type as GenericInstanceType;
4146                 if (type.GenericParameters.Count == 0 &&
4147                                 (genInst == null ? true : genInst.GenericArguments.Count == 0)) {
4148                         return AppendFullTypeName (buf, type, context);
4149                 }
4150                 return AppendGenericType (buf, type, context);
4151         }
4152
4153         protected virtual StringBuilder AppendNamespace (StringBuilder buf, TypeReference type)
4154         {
4155                 string ns = DocUtils.GetNamespace (type);
4156                 if (ns != null && ns.Length > 0)
4157                         buf.Append (ns).Append ('.');
4158                 return buf;
4159         }
4160
4161         protected virtual StringBuilder AppendFullTypeName (StringBuilder buf, TypeReference type, DynamicParserContext context)
4162         {
4163                 if (type.DeclaringType != null)
4164                         AppendFullTypeName (buf, type.DeclaringType, context).Append (NestedTypeSeparator);
4165                 return AppendTypeName (buf, type, context);
4166         }
4167
4168         protected virtual StringBuilder AppendTypeName (StringBuilder buf, TypeReference type, DynamicParserContext context)
4169         {
4170                 if (context != null)
4171                         context.TransformIndex++;
4172                 return AppendTypeName (buf, type.Name);
4173         }
4174
4175         protected virtual StringBuilder AppendTypeName (StringBuilder buf, string typename)
4176         {
4177                 int n = typename.IndexOf ("`");
4178                 if (n >= 0)
4179                         return buf.Append (typename.Substring (0, n));
4180                 return buf.Append (typename);
4181         }
4182
4183         protected virtual StringBuilder AppendArrayModifiers (StringBuilder buf, ArrayType array)
4184         {
4185                 buf.Append (ArrayDelimeters [0]);
4186                 int rank = array.Rank;
4187                 if (rank > 1)
4188                         buf.Append (new string (',', rank-1));
4189                 return buf.Append (ArrayDelimeters [1]);
4190         }
4191
4192         protected virtual string RefTypeModifier {
4193                 get {return "@";}
4194         }
4195
4196         protected virtual StringBuilder AppendRefTypeName (StringBuilder buf, TypeReference type, DynamicParserContext context)
4197         {
4198                 TypeSpecification spec = type as TypeSpecification;
4199                 return _AppendTypeName (buf, spec != null ? spec.ElementType : type.GetElementType (), context)
4200                                 .Append (RefTypeModifier);
4201         }
4202
4203         protected virtual string PointerModifier {
4204                 get {return "*";}
4205         }
4206
4207         protected virtual StringBuilder AppendPointerTypeName (StringBuilder buf, TypeReference type, DynamicParserContext context)
4208         {
4209                 TypeSpecification spec = type as TypeSpecification;
4210                 return _AppendTypeName (buf, spec != null ? spec.ElementType : type.GetElementType (), context)
4211                                 .Append (PointerModifier);
4212         }
4213
4214         protected virtual char[] GenericTypeContainer {
4215                 get {return new char[]{'<', '>'};}
4216         }
4217
4218         protected virtual char NestedTypeSeparator {
4219                 get {return '.';}
4220         }
4221
4222         protected virtual StringBuilder AppendGenericType (StringBuilder buf, TypeReference type, DynamicParserContext context)
4223         {
4224                 List<TypeReference> decls = DocUtils.GetDeclaringTypes (
4225                                 type is GenericInstanceType ? type.GetElementType () : type);
4226                 List<TypeReference> genArgs = GetGenericArguments (type);
4227                 int argIdx = 0;
4228                 int prev = 0;
4229                 bool insertNested = false;
4230                 foreach (var decl in decls) {
4231                         TypeReference declDef = decl.Resolve () ?? decl;
4232                         if (insertNested) {
4233                                 buf.Append (NestedTypeSeparator);
4234                         }
4235                         insertNested = true;
4236                         AppendTypeName (buf, declDef, context);
4237                         int ac = DocUtils.GetGenericArgumentCount (declDef);
4238                         int c = ac - prev;
4239                         prev = ac;
4240                         if (c > 0) {
4241                                 buf.Append (GenericTypeContainer [0]);
4242                                 var origState = MemberFormatterState;
4243                                 MemberFormatterState = MemberFormatterState.WithinGenericTypeParameters;
4244                                 _AppendTypeName (buf, genArgs [argIdx++], context);
4245                                 for (int i = 1; i < c; ++i) {
4246                                         _AppendTypeName (buf.Append (","), genArgs [argIdx++], context);
4247                                 }
4248                                 MemberFormatterState = origState;
4249                                 buf.Append (GenericTypeContainer [1]);
4250                         }
4251                 }
4252                 return buf;
4253         }
4254
4255         protected List<TypeReference> GetGenericArguments (TypeReference type)
4256         {
4257                 var args = new List<TypeReference> ();
4258                 GenericInstanceType inst = type as GenericInstanceType;
4259                 if (inst != null)
4260                         args.AddRange (inst.GenericArguments.Cast<TypeReference> ());
4261                 else
4262                         args.AddRange (type.GenericParameters.Cast<TypeReference> ());
4263                 return args;
4264         }
4265
4266         protected virtual StringBuilder AppendGenericTypeConstraints (StringBuilder buf, TypeReference type)
4267         {
4268                 return buf;
4269         }
4270
4271         protected virtual string GetConstructorName (MethodReference constructor)
4272         {
4273                 return constructor.Name;
4274         }
4275
4276         protected virtual string GetMethodName (MethodReference method)
4277         {
4278                 return method.Name;
4279         }
4280
4281         protected virtual string GetPropertyName (PropertyReference property)
4282         {
4283                 return property.Name;
4284         }
4285
4286         protected virtual string GetFieldName (FieldReference field)
4287         {
4288                 return field.Name;
4289         }
4290
4291         protected virtual string GetEventName (EventReference e)
4292         {
4293                 return e.Name;
4294         }
4295
4296         public virtual string GetDeclaration (MemberReference member)
4297         {
4298                 if (member == null)
4299                         throw new ArgumentNullException ("member");
4300                 TypeDefinition type = member as TypeDefinition;
4301                 if (type != null)
4302                         return GetTypeDeclaration (type);
4303                 MethodDefinition method = member as MethodDefinition;
4304                 if (method != null && method.IsConstructor)
4305                         return GetConstructorDeclaration (method);
4306                 if (method != null)
4307                         return GetMethodDeclaration (method);
4308                 PropertyDefinition prop = member as PropertyDefinition;
4309                 if (prop != null)
4310                         return GetPropertyDeclaration (prop);
4311                 FieldDefinition field = member as FieldDefinition;
4312                 if (field != null)
4313                         return GetFieldDeclaration (field);
4314                 EventDefinition e = member as EventDefinition;
4315                 if (e != null)
4316                         return GetEventDeclaration (e);
4317                 throw new NotSupportedException ("Can't handle: " + member.GetType().ToString());
4318         }
4319
4320         protected virtual string GetTypeDeclaration (TypeDefinition type)
4321         {
4322                 if (type == null)
4323                         throw new ArgumentNullException ("type");
4324                 StringBuilder buf = new StringBuilder (type.Name.Length);
4325                 _AppendTypeName (buf, type, null);
4326                 AppendGenericTypeConstraints (buf, type);
4327                 return buf.ToString ();
4328         }
4329
4330         protected virtual string GetConstructorDeclaration (MethodDefinition constructor)
4331         {
4332                 return GetConstructorName (constructor);
4333         }
4334
4335         protected virtual string GetMethodDeclaration (MethodDefinition method)
4336         {
4337                 if (method.HasCustomAttributes && method.CustomAttributes.Cast<CustomAttribute>().Any(
4338                                         ca => ca.GetDeclaringType() == "System.Diagnostics.Contracts.ContractInvariantMethodAttribute"))
4339                         return null;
4340
4341                 // Special signature for destructors.
4342                 if (method.Name == "Finalize" && method.Parameters.Count == 0)
4343                         return GetFinalizerName (method);
4344
4345                 StringBuilder buf = new StringBuilder ();
4346
4347                 AppendVisibility (buf, method);
4348                 if (buf.Length == 0 && 
4349                                 !(DocUtils.IsExplicitlyImplemented (method) && !method.IsSpecialName))
4350                         return null;
4351
4352                 AppendModifiers (buf, method);
4353
4354                 if (buf.Length != 0)
4355                         buf.Append (" ");
4356                 buf.Append (GetTypeName (method.ReturnType, new DynamicParserContext (method.MethodReturnType))).Append (" ");
4357
4358                 AppendMethodName (buf, method);
4359                 AppendGenericMethod (buf, method).Append (" ");
4360                 AppendParameters (buf, method, method.Parameters);
4361                 AppendGenericMethodConstraints (buf, method);
4362                 return buf.ToString ();
4363         }
4364
4365         protected virtual StringBuilder AppendMethodName (StringBuilder buf, MethodDefinition method)
4366         {
4367                 return buf.Append (method.Name);
4368         }
4369
4370         protected virtual string GetFinalizerName (MethodDefinition method)
4371         {
4372                 return "Finalize";
4373         }
4374
4375         protected virtual StringBuilder AppendVisibility (StringBuilder buf, MethodDefinition method)
4376         {
4377                 return buf;
4378         }
4379
4380         protected virtual StringBuilder AppendModifiers (StringBuilder buf, MethodDefinition method)
4381         {
4382                 return buf;
4383         }
4384
4385         protected virtual StringBuilder AppendGenericMethod (StringBuilder buf, MethodDefinition method)
4386         {
4387                 return buf;
4388         }
4389
4390         protected virtual StringBuilder AppendParameters (StringBuilder buf, MethodDefinition method, IList<ParameterDefinition> parameters)
4391         {
4392                 return buf;
4393         }
4394
4395         protected virtual StringBuilder AppendGenericMethodConstraints (StringBuilder buf, MethodDefinition method)
4396         {
4397                 return buf;
4398         }
4399
4400         protected virtual string GetPropertyDeclaration (PropertyDefinition property)
4401         {
4402                 return GetPropertyName (property);
4403         }
4404
4405         protected virtual string GetFieldDeclaration (FieldDefinition field)
4406         {
4407                 return GetFieldName (field);
4408         }
4409
4410         protected virtual string GetEventDeclaration (EventDefinition e)
4411         {
4412                 return GetEventName (e);
4413         }
4414 }
4415
4416 class ILFullMemberFormatter : MemberFormatter {
4417
4418         public override string Language {
4419                 get {return "ILAsm";}
4420         }
4421
4422         protected override char NestedTypeSeparator {
4423                 get {
4424                         return '/';
4425                 }
4426         }
4427
4428         protected override StringBuilder AppendNamespace (StringBuilder buf, TypeReference type)
4429         {
4430                 if (GetBuiltinType (type.FullName) != null)
4431                         return buf;
4432                 string ns = DocUtils.GetNamespace (type);
4433                 if (ns != null && ns.Length > 0) {
4434                         if (type.IsValueType)
4435                                 buf.Append ("valuetype ");
4436                         else
4437                                 buf.Append ("class ");
4438                         buf.Append (ns).Append ('.');
4439                 }
4440                 return buf;
4441         }
4442
4443         protected static string GetBuiltinType (string t)
4444         {
4445                 switch (t) {
4446                 case "System.Byte":    return "unsigned int8";
4447                 case "System.SByte":   return "int8";
4448                 case "System.Int16":   return "int16";
4449                 case "System.Int32":   return "int32";
4450                 case "System.Int64":   return "int64";
4451                 case "System.IntPtr":  return "native int";
4452
4453                 case "System.UInt16":  return "unsigned int16";
4454                 case "System.UInt32":  return "unsigned int32";
4455                 case "System.UInt64":  return "unsigned int64";
4456                 case "System.UIntPtr": return "native unsigned int";
4457
4458                 case "System.Single":  return "float32";
4459                 case "System.Double":  return "float64";
4460                 case "System.Boolean": return "bool";
4461                 case "System.Char":    return "char";
4462                 case "System.Void":    return "void";
4463                 case "System.String":  return "string";
4464                 case "System.Object":  return "object";
4465                 }
4466                 return null;
4467         }
4468
4469         protected override StringBuilder AppendTypeName (StringBuilder buf, string typename)
4470         {
4471                 return buf.Append (typename);
4472         }
4473
4474         protected override StringBuilder AppendTypeName (StringBuilder buf, TypeReference type, DynamicParserContext context)
4475         {
4476                 if (type is GenericParameter) {
4477                         AppendGenericParameterConstraints (buf, (GenericParameter) type).Append (type.Name);
4478                         return buf;
4479                 }
4480
4481                 string s = GetBuiltinType (type.FullName);
4482                 if (s != null) {
4483                         return buf.Append (s);
4484                 }
4485                 return base.AppendTypeName (buf, type, context);
4486         }
4487
4488         private StringBuilder AppendGenericParameterConstraints (StringBuilder buf, GenericParameter type)
4489         {
4490                 if (MemberFormatterState != MemberFormatterState.WithinGenericTypeParameters) {
4491                         return buf.Append (type.Owner is TypeReference ? "!" : "!!");
4492                 }
4493                 GenericParameterAttributes attrs = type.Attributes;
4494                 if ((attrs & GenericParameterAttributes.ReferenceTypeConstraint) != 0)
4495                         buf.Append ("class ");
4496                 if ((attrs & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0)
4497                         buf.Append ("struct ");
4498                 if ((attrs & GenericParameterAttributes.DefaultConstructorConstraint) != 0)
4499                         buf.Append (".ctor ");
4500                 IList<TypeReference> constraints = type.Constraints;
4501                 MemberFormatterState = 0;
4502                 if (constraints.Count > 0) {
4503                         var full = new ILFullMemberFormatter ();
4504                         buf.Append ("(").Append (full.GetName (constraints [0]));
4505                         for (int i = 1; i < constraints.Count; ++i) {
4506                                 buf.Append (", ").Append (full.GetName (constraints [i]));
4507                         }
4508                         buf.Append (") ");
4509                 }
4510                 MemberFormatterState = MemberFormatterState.WithinGenericTypeParameters;
4511
4512                 if ((attrs & GenericParameterAttributes.Covariant) != 0)
4513                         buf.Append ("+ ");
4514                 if ((attrs & GenericParameterAttributes.Contravariant) != 0)
4515                         buf.Append ("- ");
4516                 return buf;
4517         }
4518
4519         protected override string GetTypeDeclaration (TypeDefinition type)
4520         {
4521                 string visibility = GetTypeVisibility (type.Attributes);
4522                 if (visibility == null)
4523                         return null;
4524
4525                 StringBuilder buf = new StringBuilder ();
4526
4527                 buf.Append (".class ");
4528                 if (type.IsNested)
4529                         buf.Append ("nested ");
4530                 buf.Append (visibility).Append (" ");
4531                 if (type.IsInterface)
4532                         buf.Append ("interface ");
4533                 if (type.IsSequentialLayout)
4534                         buf.Append ("sequential ");
4535                 if (type.IsAutoLayout)
4536                         buf.Append ("auto ");
4537                 if (type.IsAnsiClass)
4538                         buf.Append ("ansi ");
4539                 if (type.IsAbstract)
4540                         buf.Append ("abstract ");
4541                 if (type.IsSerializable)
4542                         buf.Append ("serializable ");
4543                 if (type.IsSealed)
4544                         buf.Append ("sealed ");
4545                 if (type.IsBeforeFieldInit)
4546                         buf.Append ("beforefieldinit ");
4547                 var state = MemberFormatterState;
4548                 MemberFormatterState = MemberFormatterState.WithinGenericTypeParameters;
4549                 buf.Append (GetName (type));
4550                 MemberFormatterState = state;
4551                 var full = new ILFullMemberFormatter ();
4552                 if (type.BaseType != null) {
4553                         buf.Append (" extends ");
4554                         if (type.BaseType.FullName == "System.Object")
4555                                 buf.Append ("System.Object");
4556                         else
4557                                 buf.Append (full.GetName (type.BaseType).Substring ("class ".Length));
4558                 }
4559                 bool first = true;
4560                 foreach (var name in type.Interfaces.Where (i => MDocUpdater.IsPublic (i.Resolve ()))
4561                                 .Select (i => full.GetName (i))
4562                                 .OrderBy (n => n)) {
4563                         if (first) {
4564                                 buf.Append (" implements ");
4565                                 first = false;
4566                         }
4567                         else {
4568                                 buf.Append (", ");
4569                         }
4570                         buf.Append (name);
4571                 }
4572
4573                 return buf.ToString ();
4574         }
4575
4576         protected override StringBuilder AppendGenericType (StringBuilder buf, TypeReference type, DynamicParserContext context)
4577         {
4578                 List<TypeReference> decls = DocUtils.GetDeclaringTypes (
4579                                 type is GenericInstanceType ? type.GetElementType () : type);
4580                 bool first = true;
4581                 foreach (var decl in decls) {
4582                         TypeReference declDef = decl.Resolve () ?? decl;
4583                         if (!first) {
4584                                 buf.Append (NestedTypeSeparator);
4585                         }
4586                         first = false;
4587                         AppendTypeName (buf, declDef, context);
4588                 }
4589                 buf.Append ('<');
4590                 first = true;
4591                 foreach (TypeReference arg in GetGenericArguments (type)) {
4592                         if (!first)
4593                                 buf.Append (", ");
4594                         first = false;
4595                         _AppendTypeName (buf, arg, context);
4596                 }
4597                 buf.Append ('>');
4598                 return buf;
4599         }
4600
4601         static string GetTypeVisibility (TypeAttributes ta)
4602         {
4603                 switch (ta & TypeAttributes.VisibilityMask) {
4604                 case TypeAttributes.Public:
4605                 case TypeAttributes.NestedPublic:
4606                         return "public";
4607
4608                 case TypeAttributes.NestedFamily:
4609                 case TypeAttributes.NestedFamORAssem:
4610                         return "protected";
4611
4612                 default:
4613                         return null;
4614                 }
4615         }
4616
4617         protected override string GetConstructorDeclaration (MethodDefinition constructor)
4618         {
4619                 return GetMethodDeclaration (constructor);
4620         }
4621
4622         protected override string GetMethodDeclaration (MethodDefinition method)
4623         {
4624                 if (method.IsPrivate && !DocUtils.IsExplicitlyImplemented (method))
4625                         return null;
4626
4627                 var buf = new StringBuilder ();
4628                 buf.Append (".method ");
4629                 AppendVisibility (buf, method);
4630                 if (method.IsStatic)
4631                         buf.Append ("static ");
4632                 if (method.IsHideBySig)
4633                         buf.Append ("hidebysig ");
4634                 if (method.IsPInvokeImpl) {
4635                         var info = method.PInvokeInfo;
4636                         buf.Append ("pinvokeimpl (\"")
4637                                 .Append (info.Module.Name)
4638                                 .Append ("\" as \"")
4639                                 .Append (info.EntryPoint)
4640                                 .Append ("\"");
4641                         if (info.IsCharSetAuto)
4642                                 buf.Append (" auto");
4643                         if (info.IsCharSetUnicode)
4644                                 buf.Append (" unicode");
4645                         if (info.IsCharSetAnsi)
4646                                 buf.Append (" ansi");
4647                         if (info.IsCallConvCdecl)
4648                                 buf.Append (" cdecl");
4649                         if (info.IsCallConvStdCall)
4650                                 buf.Append (" stdcall");
4651                         if (info.IsCallConvWinapi)
4652                                 buf.Append (" winapi");
4653                         if (info.IsCallConvThiscall)
4654                                 buf.Append (" thiscall");
4655                         if (info.SupportsLastError)
4656                                 buf.Append (" lasterr");
4657                         buf.Append (")");
4658                 }
4659                 if (method.IsSpecialName)
4660                         buf.Append ("specialname ");
4661                 if (method.IsRuntimeSpecialName)
4662                         buf.Append ("rtspecialname ");
4663                 if (method.IsNewSlot)
4664                         buf.Append ("newslot ");
4665                 if (method.IsVirtual)
4666                         buf.Append ("virtual ");
4667                 if (!method.IsStatic)
4668                         buf.Append ("instance ");
4669                 _AppendTypeName (buf, method.ReturnType, new DynamicParserContext (method.MethodReturnType));
4670                 buf.Append (' ')
4671                         .Append (method.Name);
4672                 if (method.IsGenericMethod ()) {
4673                         var state = MemberFormatterState;
4674                         MemberFormatterState = MemberFormatterState.WithinGenericTypeParameters;
4675                         IList<GenericParameter> args = method.GenericParameters;
4676                         if (args.Count > 0) {
4677                                 buf.Append ("<");
4678                                 _AppendTypeName (buf, args [0], null);
4679                                 for (int i = 1; i < args.Count; ++i)
4680                                         _AppendTypeName (buf.Append (", "), args [i], null);
4681                                 buf.Append (">");
4682                         }
4683                         MemberFormatterState = state;
4684                 }
4685
4686                 buf.Append ('(');
4687                 bool first = true;
4688                 for (int i = 0; i < method.Parameters.Count; ++i) {
4689                         if (!first)
4690                                 buf.Append (", ");
4691                         first = false;
4692                         _AppendTypeName (buf, method.Parameters [i].ParameterType, new DynamicParserContext (method.Parameters [i]));
4693                         buf.Append (' ');
4694                         buf.Append (method.Parameters [i].Name);
4695                 }
4696                 buf.Append (')');
4697                 if (method.IsIL)
4698                         buf.Append (" cil");
4699                 if (method.IsRuntime)
4700                         buf.Append (" runtime");
4701                 if (method.IsManaged)
4702                         buf.Append (" managed");
4703
4704                 return buf.ToString ();
4705         }
4706
4707         protected override StringBuilder AppendMethodName (StringBuilder buf, MethodDefinition method)
4708         {
4709                 if (DocUtils.IsExplicitlyImplemented (method)) {
4710                         TypeReference iface;
4711                         MethodReference ifaceMethod;
4712                         DocUtils.GetInfoForExplicitlyImplementedMethod (method, out iface, out ifaceMethod);
4713                         return buf.Append (new CSharpMemberFormatter ().GetName (iface))
4714                                 .Append ('.')
4715                                 .Append (ifaceMethod.Name);
4716                 }
4717                 return base.AppendMethodName (buf, method);
4718         }
4719
4720         protected override string RefTypeModifier {
4721                 get {return "";}
4722         }
4723
4724         protected override StringBuilder AppendVisibility (StringBuilder buf, MethodDefinition method)
4725         {
4726                 if (method.IsPublic)
4727                         return buf.Append ("public ");
4728                 if (method.IsFamilyAndAssembly)
4729                         return buf.Append ("familyandassembly");
4730                 if (method.IsFamilyOrAssembly)
4731                         return buf.Append ("familyorassembly");
4732                 if (method.IsFamily)
4733                         return buf.Append ("family");
4734                 return buf;
4735         }
4736
4737         protected override StringBuilder AppendModifiers (StringBuilder buf, MethodDefinition method)
4738         {
4739                 string modifiers = String.Empty;
4740                 if (method.IsStatic) modifiers += " static";
4741                 if (method.IsVirtual && !method.IsAbstract) {
4742                         if ((method.Attributes & MethodAttributes.NewSlot) != 0) modifiers += " virtual";
4743                         else modifiers += " override";
4744                 }
4745                 TypeDefinition declType = (TypeDefinition) method.DeclaringType;
4746                 if (method.IsAbstract && !declType.IsInterface) modifiers += " abstract";
4747                 if (method.IsFinal) modifiers += " sealed";
4748                 if (modifiers == " virtual sealed") modifiers = "";
4749
4750                 return buf.Append (modifiers);
4751         }
4752
4753         protected override StringBuilder AppendGenericMethod (StringBuilder buf, MethodDefinition method)
4754         {
4755                 if (method.IsGenericMethod ()) {
4756                         IList<GenericParameter> args = method.GenericParameters;
4757                         if (args.Count > 0) {
4758                                 buf.Append ("<");
4759                                 buf.Append (args [0].Name);
4760                                 for (int i = 1; i < args.Count; ++i)
4761                                         buf.Append (",").Append (args [i].Name);
4762                                 buf.Append (">");
4763                         }
4764                 }
4765                 return buf;
4766         }
4767
4768         protected override StringBuilder AppendParameters (StringBuilder buf, MethodDefinition method, IList<ParameterDefinition> parameters)
4769         {
4770                 return AppendParameters (buf, method, parameters, '(', ')');
4771         }
4772
4773         private StringBuilder AppendParameters (StringBuilder buf, MethodDefinition method, IList<ParameterDefinition> parameters, char begin, char end)
4774         {
4775                 buf.Append (begin);
4776
4777                 if (parameters.Count > 0) {
4778                         if (DocUtils.IsExtensionMethod (method))
4779                                 buf.Append ("this ");
4780                         AppendParameter (buf, parameters [0]);
4781                         for (int i = 1; i < parameters.Count; ++i) {
4782                                 buf.Append (", ");
4783                                 AppendParameter (buf, parameters [i]);
4784                         }
4785                 }
4786
4787                 return buf.Append (end);
4788         }
4789
4790         private StringBuilder AppendParameter (StringBuilder buf, ParameterDefinition parameter)
4791         {
4792                 if (parameter.ParameterType is ByReferenceType) {
4793                         if (parameter.IsOut)
4794                                 buf.Append ("out ");
4795                         else
4796                                 buf.Append ("ref ");
4797                 }
4798                 buf.Append (GetName (parameter.ParameterType)).Append (" ");
4799                 return buf.Append (parameter.Name);
4800         }
4801
4802         protected override string GetPropertyDeclaration (PropertyDefinition property)
4803         {
4804                 MethodDefinition gm = null, sm = null;
4805
4806                 string get_visible = null;
4807                 if ((gm = property.GetMethod) != null &&
4808                                 (DocUtils.IsExplicitlyImplemented (gm) ||
4809                                  (!gm.IsPrivate && !gm.IsAssembly && !gm.IsFamilyAndAssembly)))
4810                         get_visible = AppendVisibility (new StringBuilder (), gm).ToString ();
4811                 string set_visible = null;
4812                 if ((sm = property.SetMethod) != null &&
4813                                 (DocUtils.IsExplicitlyImplemented (sm) ||
4814                                  (!sm.IsPrivate && !sm.IsAssembly && !sm.IsFamilyAndAssembly)))
4815                         set_visible = AppendVisibility (new StringBuilder (), sm).ToString ();
4816
4817                 if ((set_visible == null) && (get_visible == null))
4818                         return null;
4819
4820                 StringBuilder buf = new StringBuilder ()
4821                         .Append (".property ");
4822                 if (!(gm ?? sm).IsStatic)
4823                         buf.Append ("instance ");
4824                 _AppendTypeName (buf, property.PropertyType, new DynamicParserContext (property));
4825                 buf.Append (' ').Append (property.Name);
4826                 if (!property.HasParameters || property.Parameters.Count == 0)
4827                         return buf.ToString ();
4828
4829                 buf.Append ('(');
4830                 bool first = true;
4831                 foreach (ParameterDefinition p in property.Parameters) {
4832                         if (!first)
4833                                 buf.Append (", ");
4834                         first = false;
4835                         _AppendTypeName (buf, p.ParameterType, new DynamicParserContext (p));
4836                 }
4837                 buf.Append (')');
4838
4839                 return buf.ToString ();
4840         }
4841
4842         protected override string GetFieldDeclaration (FieldDefinition field)
4843         {
4844                 TypeDefinition declType = (TypeDefinition) field.DeclaringType;
4845                 if (declType.IsEnum && field.Name == "value__")
4846                         return null; // This member of enums aren't documented.
4847
4848                 StringBuilder buf = new StringBuilder ();
4849                 AppendFieldVisibility (buf, field);
4850                 if (buf.Length == 0)
4851                         return null;
4852
4853                 buf.Insert (0, ".field ");
4854
4855                 if (field.IsStatic)
4856                         buf.Append ("static ");
4857                 if (field.IsInitOnly)
4858                         buf.Append ("initonly ");
4859                 if (field.IsLiteral)
4860                         buf.Append ("literal ");
4861                 _AppendTypeName (buf, field.FieldType, new DynamicParserContext (field));
4862                 buf.Append (' ').Append (field.Name);
4863                 AppendFieldValue (buf, field);
4864
4865                 return buf.ToString ();
4866         }
4867
4868         static StringBuilder AppendFieldVisibility (StringBuilder buf, FieldDefinition field)
4869         {
4870                 if (field.IsPublic)
4871                         return buf.Append ("public ");
4872                 if (field.IsFamilyAndAssembly)
4873                         return buf.Append ("familyandassembly ");
4874                 if (field.IsFamilyOrAssembly)
4875                         return buf.Append ("familyorassembly ");
4876                 if (field.IsFamily)
4877                         return buf.Append ("family ");
4878                 return buf;
4879         }
4880
4881         static StringBuilder AppendFieldValue (StringBuilder buf, FieldDefinition field)
4882         {
4883                 // enums have a value__ field, which we ignore
4884                 if (field.DeclaringType.IsGenericType ())
4885                         return buf;
4886                 if (field.HasConstant && field.IsLiteral) {
4887                         object val = null;
4888                         try {
4889                                 val   = field.Constant;
4890                         } catch {
4891                                 return buf;
4892                         }
4893                         if (val == null)
4894                                 buf.Append (" = ").Append ("null");
4895                         else if (val is Enum)
4896                                 buf.Append (" = ")
4897                                         .Append (GetBuiltinType (field.DeclaringType.GetUnderlyingType ().FullName))
4898                                         .Append ('(')
4899                                         .Append (val.ToString ())
4900                                         .Append (')');
4901                         else if (val is IFormattable) {
4902                                 string value = ((IFormattable)val).ToString();
4903                                 buf.Append (" = ");
4904                                 if (val is string)
4905                                         buf.Append ("\"" + value + "\"");
4906                                 else
4907                                         buf.Append (GetBuiltinType (field.DeclaringType.GetUnderlyingType ().FullName))
4908                                                 .Append ('(')
4909                                                 .Append (value)
4910                                                 .Append (')');
4911                         }
4912                 }
4913                 return buf;
4914         }
4915
4916         protected override string GetEventDeclaration (EventDefinition e)
4917         {
4918                 StringBuilder buf = new StringBuilder ();
4919                 if (AppendVisibility (buf, e.AddMethod).Length == 0) {
4920                         return null;
4921                 }
4922
4923                 buf.Length = 0;
4924                 buf.Append (".event ")
4925                         .Append (GetName (e.EventType))
4926                         .Append (' ')
4927                         .Append (e.Name);
4928
4929                 return buf.ToString ();
4930         }
4931 }
4932
4933 class ILMemberFormatter : ILFullMemberFormatter {
4934         protected override StringBuilder AppendNamespace (StringBuilder buf, TypeReference type)
4935         {
4936                 return buf;
4937         }
4938 }
4939
4940         class ILNativeTypeMemberFormatter : ILFullMemberFormatter {
4941                 protected static string _GetBuiltinType (string t)
4942                 {
4943                         //string moddedType = base.GetBuiltinType (t);
4944                         return null;
4945                         //return moddedType;
4946                 }
4947         }
4948
4949         class CSharpNativeTypeMemberFormatter : CSharpFullMemberFormatter {
4950                 protected override string GetCSharpType (string t) {
4951                         string moddedType = base.GetCSharpType (t);
4952
4953                         switch (moddedType) {
4954                         case "int":             return "nint";
4955                         case "uint":
4956                                 return "nuint";
4957                         case "float":
4958                                 return "nfloat";
4959                         case "System.Drawing.SizeF":
4960                                 return "CoreGraphics.CGSize";
4961                         case "System.Drawing.PointF":
4962                                 return "CoreGraphics.CGPoint";
4963                         case "System.Drawing.RectangleF":
4964                                 return "CoreGraphics.CGPoint";
4965                         }
4966                         return null;
4967                 }
4968         }
4969
4970 class CSharpFullMemberFormatter : MemberFormatter {
4971
4972         public override string Language {
4973                 get {return "C#";}
4974         }
4975
4976         protected override StringBuilder AppendNamespace (StringBuilder buf, TypeReference type)
4977         {
4978
4979                 string ns = DocUtils.GetNamespace (type);
4980                 if (GetCSharpType (type.FullName) == null && ns != null && ns.Length > 0 && ns != "System")
4981                         buf.Append (ns).Append ('.');
4982                 return buf;
4983         }
4984
4985         protected virtual string GetCSharpType (string t)
4986         {
4987                 switch (t) {
4988                 case "System.Byte":    return "byte";
4989                 case "System.SByte":   return "sbyte";
4990                 case "System.Int16":   return "short";
4991                 case "System.Int32":   return "int";
4992                 case "System.Int64":   return "long";
4993
4994                 case "System.UInt16":  return "ushort";
4995                 case "System.UInt32":  return "uint";
4996                 case "System.UInt64":  return "ulong";
4997
4998                 case "System.Single":  return "float";
4999                 case "System.Double":  return "double";
5000                 case "System.Decimal": return "decimal";
5001                 case "System.Boolean": return "bool";
5002                 case "System.Char":    return "char";
5003                 case "System.Void":    return "void";
5004                 case "System.String":  return "string";
5005                 case "System.Object":  return "object";
5006                 }
5007                 return null;
5008         }
5009
5010         protected override StringBuilder AppendTypeName (StringBuilder buf, TypeReference type, DynamicParserContext context)
5011         {
5012                 if (context != null && context.TransformFlags != null &&
5013                                 (context.TransformFlags.Count == 0 || context.TransformFlags [context.TransformIndex])) {
5014                         context.TransformIndex++;
5015                         return buf.Append ("dynamic");
5016                 }
5017
5018                 if (type is GenericParameter)
5019                         return AppendGenericParameterConstraints (buf, (GenericParameter) type, context).Append (type.Name);
5020                 string t = type.FullName;
5021                 if (!t.StartsWith ("System.")) {
5022                         return base.AppendTypeName (buf, type, context);
5023                 }
5024
5025                 string s = GetCSharpType (t);
5026                 if (s != null) {
5027                         if (context != null)
5028                                 context.TransformIndex++;
5029                         return buf.Append (s);
5030                 }
5031                 
5032                 return base.AppendTypeName (buf, type, context);
5033         }
5034
5035         private StringBuilder AppendGenericParameterConstraints (StringBuilder buf, GenericParameter type, DynamicParserContext context)
5036         {
5037                 if (MemberFormatterState != MemberFormatterState.WithinGenericTypeParameters)
5038                         return buf;
5039                 GenericParameterAttributes attrs = type.Attributes;
5040                 bool isout = (attrs & GenericParameterAttributes.Covariant) != 0;
5041                 bool isin  = (attrs & GenericParameterAttributes.Contravariant) != 0;
5042                 if (isin)
5043                         buf.Append ("in ");
5044                 else if (isout)
5045                         buf.Append ("out ");
5046                 return buf;
5047         }
5048
5049         protected override string GetTypeDeclaration (TypeDefinition type)
5050         {
5051                 string visibility = GetTypeVisibility (type.Attributes);
5052                 if (visibility == null)
5053                         return null;
5054
5055                 StringBuilder buf = new StringBuilder ();
5056                 
5057                 buf.Append (visibility);
5058                 buf.Append (" ");
5059
5060                 MemberFormatter full = new CSharpFullMemberFormatter ();
5061
5062                 if (DocUtils.IsDelegate (type)) {
5063                         buf.Append("delegate ");
5064                         MethodDefinition invoke = type.GetMethod ("Invoke");
5065                         buf.Append (full.GetName (invoke.ReturnType, new DynamicParserContext (invoke.MethodReturnType))).Append (" ");
5066                         buf.Append (GetName (type));
5067                         AppendParameters (buf, invoke, invoke.Parameters);
5068                         AppendGenericTypeConstraints (buf, type);
5069                         buf.Append (";");
5070
5071                         return buf.ToString();
5072                 }
5073                 
5074                 if (type.IsAbstract && !type.IsInterface)
5075                         buf.Append("abstract ");
5076                 if (type.IsSealed && !DocUtils.IsDelegate (type) && !type.IsValueType)
5077                         buf.Append("sealed ");
5078                 buf.Replace ("abstract sealed", "static");
5079
5080                 buf.Append (GetTypeKind (type));
5081                 buf.Append (" ");
5082                 buf.Append (GetCSharpType (type.FullName) == null 
5083                                 ? GetName (type) 
5084                                 : type.Name);
5085
5086                 if (!type.IsEnum) {
5087                         TypeReference basetype = type.BaseType;
5088                         if (basetype != null && basetype.FullName == "System.Object" || type.IsValueType)       // FIXME
5089                                 basetype = null;
5090
5091                         List<string> interface_names = DocUtils.GetUserImplementedInterfaces (type)
5092                                         .Select (iface => full.GetName (iface))
5093                                         .OrderBy (s => s)
5094                                         .ToList ();
5095
5096                         if (basetype != null || interface_names.Count > 0)
5097                                 buf.Append (" : ");
5098                         
5099                         if (basetype != null) {
5100                                 buf.Append (full.GetName (basetype));
5101                                 if (interface_names.Count > 0)
5102                                         buf.Append (", ");
5103                         }
5104                         
5105                         for (int i = 0; i < interface_names.Count; i++){
5106                                 if (i != 0)
5107                                         buf.Append (", ");
5108                                 buf.Append (interface_names [i]);
5109                         }
5110                         AppendGenericTypeConstraints (buf, type);
5111                 }
5112
5113                 return buf.ToString ();
5114         }
5115
5116         static string GetTypeKind (TypeDefinition t)
5117         {
5118                 if (t.IsEnum)
5119                         return "enum";
5120                 if (t.IsValueType)
5121                         return "struct";
5122                 if (t.IsClass || t.FullName == "System.Enum")
5123                         return "class";
5124                 if (t.IsInterface)
5125                         return "interface";
5126                 throw new ArgumentException(t.FullName);
5127         }
5128
5129         static string GetTypeVisibility (TypeAttributes ta)
5130         {
5131                 switch (ta & TypeAttributes.VisibilityMask) {
5132                 case TypeAttributes.Public:
5133                 case TypeAttributes.NestedPublic:
5134                         return "public";
5135
5136                 case TypeAttributes.NestedFamily:
5137                 case TypeAttributes.NestedFamORAssem:
5138                         return "protected";
5139
5140                 default:
5141                         return null;
5142                 }
5143         }
5144
5145         protected override StringBuilder AppendGenericTypeConstraints (StringBuilder buf, TypeReference type)
5146         {
5147                 if (type.GenericParameters.Count == 0)
5148                         return buf;
5149                 return AppendConstraints (buf, type.GenericParameters);
5150         }
5151
5152         private StringBuilder AppendConstraints (StringBuilder buf, IList<GenericParameter> genArgs)
5153         {
5154                 foreach (GenericParameter genArg in genArgs) {
5155                         GenericParameterAttributes attrs = genArg.Attributes;
5156                         IList<TypeReference> constraints = genArg.Constraints;
5157                         if (attrs == GenericParameterAttributes.NonVariant && constraints.Count == 0)
5158                                 continue;
5159
5160                         bool isref = (attrs & GenericParameterAttributes.ReferenceTypeConstraint) != 0;
5161                         bool isvt  = (attrs & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0;
5162                         bool isnew = (attrs & GenericParameterAttributes.DefaultConstructorConstraint) != 0;
5163                         bool comma = false;
5164
5165                         if (!isref && !isvt && !isnew && constraints.Count == 0)
5166                                 continue;
5167                         buf.Append (" where ").Append (genArg.Name).Append (" : ");
5168                         if (isref) {
5169                                 buf.Append ("class");
5170                                 comma = true;
5171                         }
5172                         else if (isvt) {
5173                                 buf.Append ("struct");
5174                                 comma = true;
5175                         }
5176                         if (constraints.Count > 0 && !isvt) {
5177                                 if (comma)
5178                                         buf.Append (", ");
5179                                 buf.Append (GetTypeName (constraints [0]));
5180                                 for (int i = 1; i < constraints.Count; ++i)
5181                                         buf.Append (", ").Append (GetTypeName (constraints [i]));
5182                         }
5183                         if (isnew && !isvt) {
5184                                 if (comma)
5185                                         buf.Append (", ");
5186                                 buf.Append ("new()");
5187                         }
5188                 }
5189                 return buf;
5190         }
5191
5192         protected override string GetConstructorDeclaration (MethodDefinition constructor)
5193         {
5194                 StringBuilder buf = new StringBuilder ();
5195                 AppendVisibility (buf, constructor);
5196                 if (buf.Length == 0)
5197                         return null;
5198
5199                 buf.Append (' ');
5200                 base.AppendTypeName (buf, constructor.DeclaringType.Name).Append (' ');
5201                 AppendParameters (buf, constructor, constructor.Parameters);
5202                 buf.Append (';');
5203
5204                 return buf.ToString ();
5205         }
5206         
5207         protected override string GetMethodDeclaration (MethodDefinition method)
5208         {
5209                 string decl = base.GetMethodDeclaration (method);
5210                 if (decl != null)
5211                         return decl + ";";
5212                 return null;
5213         }
5214
5215         protected override StringBuilder AppendMethodName (StringBuilder buf, MethodDefinition method)
5216         {
5217                 if (DocUtils.IsExplicitlyImplemented (method)) {
5218                         TypeReference iface;
5219                         MethodReference ifaceMethod;
5220                         DocUtils.GetInfoForExplicitlyImplementedMethod (method, out iface, out ifaceMethod);
5221                         return buf.Append (new CSharpMemberFormatter ().GetName (iface))
5222                                 .Append ('.')
5223                                 .Append (ifaceMethod.Name);
5224                 }
5225                 return base.AppendMethodName (buf, method);
5226         }
5227
5228         protected override StringBuilder AppendGenericMethodConstraints (StringBuilder buf, MethodDefinition method)
5229         {
5230                 if (method.GenericParameters.Count == 0)
5231                         return buf;
5232                 return AppendConstraints (buf, method.GenericParameters);
5233         }
5234
5235         protected override string RefTypeModifier {
5236                 get {return "";}
5237         }
5238
5239         protected override string GetFinalizerName (MethodDefinition method)
5240         {
5241                 return "~" + method.DeclaringType.Name + " ()"; 
5242         }
5243
5244         protected override StringBuilder AppendVisibility (StringBuilder buf, MethodDefinition method)
5245         {
5246                 if (method == null)
5247                         return buf;
5248                 if (method.IsPublic)
5249                         return buf.Append ("public");
5250                 if (method.IsFamily || method.IsFamilyOrAssembly)
5251                         return buf.Append ("protected");
5252                 return buf;
5253         }
5254
5255         protected override StringBuilder AppendModifiers (StringBuilder buf, MethodDefinition method)
5256         {
5257                 string modifiers = String.Empty;
5258                 if (method.IsStatic) modifiers += " static";
5259                 if (method.IsVirtual && !method.IsAbstract) {
5260                         if ((method.Attributes & MethodAttributes.NewSlot) != 0) modifiers += " virtual";
5261                         else modifiers += " override";
5262                 }
5263                 TypeDefinition declType = (TypeDefinition) method.DeclaringType;
5264                 if (method.IsAbstract && !declType.IsInterface) modifiers += " abstract";
5265                 if (method.IsFinal) modifiers += " sealed";
5266                 if (modifiers == " virtual sealed") modifiers = "";
5267
5268                 return buf.Append (modifiers);
5269         }
5270
5271         protected override StringBuilder AppendGenericMethod (StringBuilder buf, MethodDefinition method)
5272         {
5273                 if (method.IsGenericMethod ()) {
5274                         IList<GenericParameter> args = method.GenericParameters;
5275                         if (args.Count > 0) {
5276                                 buf.Append ("<");
5277                                 buf.Append (args [0].Name);
5278                                 for (int i = 1; i < args.Count; ++i)
5279                                         buf.Append (",").Append (args [i].Name);
5280                                 buf.Append (">");
5281                         }
5282                 }
5283                 return buf;
5284         }
5285
5286         protected override StringBuilder AppendParameters (StringBuilder buf, MethodDefinition method, IList<ParameterDefinition> parameters)
5287         {
5288                 return AppendParameters (buf, method, parameters, '(', ')');
5289         }
5290
5291         private StringBuilder AppendParameters (StringBuilder buf, MethodDefinition method, IList<ParameterDefinition> parameters, char begin, char end)
5292         {
5293                 buf.Append (begin);
5294
5295                 if (parameters.Count > 0) {
5296                         if (DocUtils.IsExtensionMethod (method))
5297                                 buf.Append ("this ");
5298                         AppendParameter (buf, parameters [0]);
5299                         for (int i = 1; i < parameters.Count; ++i) {
5300                                 buf.Append (", ");
5301                                 AppendParameter (buf, parameters [i]);
5302                         }
5303                 }
5304
5305                 return buf.Append (end);
5306         }
5307
5308         private StringBuilder AppendParameter (StringBuilder buf, ParameterDefinition parameter)
5309         {
5310                 if (parameter.ParameterType is ByReferenceType) {
5311                         if (parameter.IsOut)
5312                                 buf.Append ("out ");
5313                         else
5314                                 buf.Append ("ref ");
5315                 }
5316                 buf.Append (GetTypeName (parameter.ParameterType, new DynamicParserContext (parameter))).Append (" ");
5317                 buf.Append (parameter.Name);
5318                 if (parameter.HasDefault && parameter.IsOptional && parameter.HasConstant) {
5319                         buf.AppendFormat (" = {0}", MDocUpdater.MakeAttributesValueString (parameter.Constant, parameter.ParameterType));
5320                 }
5321                 return buf;
5322         }
5323
5324         protected override string GetPropertyDeclaration (PropertyDefinition property)
5325         {
5326                 MethodDefinition method;
5327
5328                 string get_visible = null;
5329                 if ((method = property.GetMethod) != null && 
5330                                 (DocUtils.IsExplicitlyImplemented (method) || 
5331                                  (!method.IsPrivate && !method.IsAssembly && !method.IsFamilyAndAssembly)))
5332                         get_visible = AppendVisibility (new StringBuilder (), method).ToString ();
5333                 string set_visible = null;
5334                 if ((method = property.SetMethod) != null &&
5335                                 (DocUtils.IsExplicitlyImplemented (method) || 
5336                                  (!method.IsPrivate && !method.IsAssembly && !method.IsFamilyAndAssembly)))
5337                         set_visible = AppendVisibility (new StringBuilder (), method).ToString ();
5338
5339                 if ((set_visible == null) && (get_visible == null))
5340                         return null;
5341
5342                 string visibility;
5343                 StringBuilder buf = new StringBuilder ();
5344                 if (get_visible != null && (set_visible == null || (set_visible != null && get_visible == set_visible)))
5345                         buf.Append (visibility = get_visible);
5346                 else if (set_visible != null && get_visible == null)
5347                         buf.Append (visibility = set_visible);
5348                 else
5349                         buf.Append (visibility = "public");
5350
5351                 // Pick an accessor to use for static/virtual/override/etc. checks.
5352                 method = property.SetMethod;
5353                 if (method == null)
5354                         method = property.GetMethod;
5355         
5356                 string modifiers = String.Empty;
5357                 if (method.IsStatic) modifiers += " static";
5358                 if (method.IsVirtual && !method.IsAbstract) {
5359                                 if ((method.Attributes & MethodAttributes.NewSlot) != 0)
5360                                         modifiers += " virtual";
5361                                 else
5362                                         modifiers += " override";
5363                 }
5364                 TypeDefinition declDef = (TypeDefinition) method.DeclaringType;
5365                 if (method.IsAbstract && !declDef.IsInterface)
5366                         modifiers += " abstract";
5367                 if (method.IsFinal)
5368                         modifiers += " sealed";
5369                 if (modifiers == " virtual sealed")
5370                         modifiers = "";
5371                 buf.Append (modifiers).Append (' ');
5372
5373                 buf.Append (GetTypeName (property.PropertyType, new DynamicParserContext (property))).Append (' ');
5374
5375                 IEnumerable<MemberReference> defs = property.DeclaringType.GetDefaultMembers ();
5376                 string name = property.Name;
5377                 foreach (MemberReference mi in defs) {
5378                         if (mi == property) {
5379                                 name = "this";
5380                                 break;
5381                         }
5382                 }
5383                 buf.Append (name == "this" ? name : DocUtils.GetPropertyName (property));
5384         
5385                 if (property.Parameters.Count != 0) {
5386                         AppendParameters (buf, method, property.Parameters, '[', ']');
5387                 }
5388
5389                 buf.Append (" {");
5390                 if (get_visible != null) {
5391                         if (get_visible != visibility)
5392                                 buf.Append (' ').Append (get_visible);
5393                         buf.Append (" get;");
5394                 }
5395                 if (set_visible != null) {
5396                         if (set_visible != visibility)
5397                                 buf.Append (' ').Append (set_visible);
5398                         buf.Append (" set;");
5399                 }
5400                 buf.Append (" }");
5401         
5402                 return buf [0] != ' ' ? buf.ToString () : buf.ToString (1, buf.Length-1);
5403         }
5404
5405         protected override string GetFieldDeclaration (FieldDefinition field)
5406         {
5407                 TypeDefinition declType = (TypeDefinition) field.DeclaringType;
5408                 if (declType.IsEnum && field.Name == "value__")
5409                         return null; // This member of enums aren't documented.
5410
5411                 StringBuilder buf = new StringBuilder ();
5412                 AppendFieldVisibility (buf, field);
5413                 if (buf.Length == 0)
5414                         return null;
5415
5416                 if (declType.IsEnum)
5417                         return field.Name;
5418
5419                 if (field.IsStatic && !field.IsLiteral)
5420                         buf.Append (" static");
5421                 if (field.IsInitOnly)
5422                         buf.Append (" readonly");
5423                 if (field.IsLiteral)
5424                         buf.Append (" const");
5425
5426                 buf.Append (' ').Append (GetTypeName (field.FieldType, new DynamicParserContext (field))).Append (' ');
5427                 buf.Append (field.Name);
5428                 AppendFieldValue (buf, field);
5429                 buf.Append (';');
5430
5431                 return buf.ToString ();
5432         }
5433
5434         static StringBuilder AppendFieldVisibility (StringBuilder buf, FieldDefinition field)
5435         {
5436                 if (field.IsPublic)
5437                         return buf.Append ("public");
5438                 if (field.IsFamily || field.IsFamilyOrAssembly)
5439                         return buf.Append ("protected");
5440                 return buf;
5441         }
5442
5443         static StringBuilder AppendFieldValue (StringBuilder buf, FieldDefinition field)
5444         {
5445                 // enums have a value__ field, which we ignore
5446                 if (((TypeDefinition ) field.DeclaringType).IsEnum || 
5447                                 field.DeclaringType.IsGenericType ())
5448                         return buf;
5449                 if (field.HasConstant && field.IsLiteral) {
5450                         object val = null;
5451                         try {
5452                                 val   = field.Constant;
5453                         } catch {
5454                                 return buf;
5455                         }
5456                         if (val == null)
5457                                 buf.Append (" = ").Append ("null");
5458                         else if (val is Enum)
5459                                 buf.Append (" = ").Append (val.ToString ());
5460                         else if (val is IFormattable) {
5461                                 string value = ((IFormattable)val).ToString();
5462                                 if (val is string)
5463                                         value = "\"" + value + "\"";
5464                                 buf.Append (" = ").Append (value);
5465                         }
5466                 }
5467                 return buf;
5468         }
5469
5470         protected override string GetEventDeclaration (EventDefinition e)
5471         {
5472                 StringBuilder buf = new StringBuilder ();
5473                 if (AppendVisibility (buf, e.AddMethod).Length == 0) {
5474                         return null;
5475                 }
5476
5477                 AppendModifiers (buf, e.AddMethod);
5478
5479                 buf.Append (" event ");
5480                 buf.Append (GetTypeName (e.EventType, new DynamicParserContext (e.AddMethod.Parameters [0]))).Append (' ');
5481                 buf.Append (e.Name).Append (';');
5482
5483                 return buf.ToString ();
5484         }
5485 }
5486
5487 class CSharpMemberFormatter : CSharpFullMemberFormatter {
5488         protected override StringBuilder AppendNamespace (StringBuilder buf, TypeReference type)
5489         {
5490                 return buf;
5491         }
5492 }
5493
5494 class DocTypeFullMemberFormatter : MemberFormatter {
5495         public static readonly MemberFormatter Default = new DocTypeFullMemberFormatter ();
5496
5497         protected override char NestedTypeSeparator {
5498                 get {return '+';}
5499         }
5500 }
5501
5502 class DocTypeMemberFormatter : DocTypeFullMemberFormatter {
5503         protected override StringBuilder AppendNamespace (StringBuilder buf, TypeReference type)
5504         {
5505                 return buf;
5506         }
5507 }
5508
5509 class SlashDocMemberFormatter : MemberFormatter {
5510
5511         protected override char[] GenericTypeContainer {
5512                 get {return new char[]{'{', '}'};}
5513         }
5514
5515         private bool AddTypeCount = true;
5516
5517         private TypeReference genDeclType;
5518         private MethodReference genDeclMethod;
5519
5520         protected override StringBuilder AppendTypeName (StringBuilder buf, TypeReference type, DynamicParserContext context)
5521         {
5522                 if (type is GenericParameter) {
5523                         int l = buf.Length;
5524                         if (genDeclType != null) {
5525                                 IList<GenericParameter> genArgs = genDeclType.GenericParameters;
5526                                 for (int i = 0; i < genArgs.Count; ++i) {
5527                                         if (genArgs [i].Name == type.Name) {
5528                                                 buf.Append ('`').Append (i);
5529                                                 break;
5530                                         }
5531                                 }
5532                         }
5533                         if (genDeclMethod != null) {
5534                                 IList<GenericParameter> genArgs = null;
5535                                 if (genDeclMethod.IsGenericMethod ()) {
5536                                         genArgs = genDeclMethod.GenericParameters;
5537                                         for (int i = 0; i < genArgs.Count; ++i) {
5538                                                 if (genArgs [i].Name == type.Name) {
5539                                                         buf.Append ("``").Append (i);
5540                                                         break;
5541                                                 }
5542                                         }
5543                                 }
5544                         }
5545                         if (genDeclType == null && genDeclMethod == null) {
5546                                 // Probably from within an explicitly implemented interface member,
5547                                 // where CSC uses parameter names instead of indices (why?), e.g.
5548                                 // MyList`2.Mono#DocTest#Generic#IFoo{A}#Method``1(`0,``0) instead of
5549                                 // MyList`2.Mono#DocTest#Generic#IFoo{`0}#Method``1(`0,``0).
5550                                 buf.Append (type.Name);
5551                         }
5552                         if (buf.Length == l) {
5553                                 throw new Exception (string.Format (
5554                                                 "Unable to translate generic parameter {0}; genDeclType={1}, genDeclMethod={2}", 
5555                                                 type.Name, genDeclType, genDeclMethod));
5556                         }
5557                 }
5558                 else {
5559                         base.AppendTypeName (buf, type, context);
5560                         if (AddTypeCount) {
5561                                 int numArgs = type.GenericParameters.Count;
5562                                 if (type.DeclaringType != null)
5563                                         numArgs -= type.GenericParameters.Count;
5564                                 if (numArgs > 0) {
5565                                         buf.Append ('`').Append (numArgs);
5566                                 }
5567                         }
5568                 }
5569                 return buf;
5570         }
5571
5572         protected override StringBuilder AppendArrayModifiers (StringBuilder buf, ArrayType array)
5573         {
5574                 buf.Append (ArrayDelimeters [0]);
5575                 int rank = array.Rank;
5576                 if (rank > 1) {
5577                         buf.Append ("0:");
5578                         for (int i = 1; i < rank; ++i) {
5579                                 buf.Append (",0:");
5580                         }
5581                 }
5582                 return buf.Append (ArrayDelimeters [1]);
5583         }
5584
5585         protected override StringBuilder AppendGenericType (StringBuilder buf, TypeReference type, DynamicParserContext context)
5586         {
5587                 if (!AddTypeCount)
5588                         base.AppendGenericType (buf, type, context);
5589                 else
5590                         AppendType (buf, type, context);
5591                 return buf;
5592         }
5593
5594         private StringBuilder AppendType (StringBuilder buf, TypeReference type, DynamicParserContext context)
5595         {
5596                 List<TypeReference> decls = DocUtils.GetDeclaringTypes (type);
5597                 bool insertNested = false;
5598                 int prevParamCount = 0;
5599                 foreach (var decl in decls) {
5600                         if (insertNested)
5601                                 buf.Append (NestedTypeSeparator);
5602                         insertNested = true;
5603                         base.AppendTypeName (buf, decl, context);
5604                         int argCount = DocUtils.GetGenericArgumentCount (decl);
5605                         int numArgs = argCount - prevParamCount;
5606                         prevParamCount = argCount;
5607                         if (numArgs > 0)
5608                                 buf.Append ('`').Append (numArgs);
5609                 }
5610                 return buf;
5611         }
5612
5613         public override string GetDeclaration (MemberReference member)
5614         {
5615                 TypeReference r = member as TypeReference;
5616                 if (r != null) {
5617                         return "T:" + GetTypeName (r);
5618                 }
5619                 return base.GetDeclaration (member);
5620         }
5621
5622         protected override string GetConstructorName (MethodReference constructor)
5623         {
5624                 return GetMethodDefinitionName (constructor, "#ctor");
5625         }
5626
5627         protected override string GetMethodName (MethodReference method)
5628         {
5629                 string name = null;
5630                 MethodDefinition methodDef = method as MethodDefinition;
5631                 if (methodDef == null || !DocUtils.IsExplicitlyImplemented (methodDef))
5632                         name = method.Name;
5633                 else {
5634                         TypeReference iface;
5635                         MethodReference ifaceMethod;
5636                         DocUtils.GetInfoForExplicitlyImplementedMethod (methodDef, out iface, out ifaceMethod);
5637                         AddTypeCount = false;
5638                         name = GetTypeName (iface) + "." + ifaceMethod.Name;
5639                         AddTypeCount = true;
5640                 }
5641                 return GetMethodDefinitionName (method, name);
5642         }
5643
5644         private string GetMethodDefinitionName (MethodReference method, string name)
5645         {
5646                 StringBuilder buf = new StringBuilder ();
5647                 buf.Append (GetTypeName (method.DeclaringType));
5648                 buf.Append ('.');
5649                 buf.Append (name.Replace (".", "#"));
5650                 if (method.IsGenericMethod ()) {
5651                         IList<GenericParameter> genArgs = method.GenericParameters;
5652                         if (genArgs.Count > 0)
5653                                 buf.Append ("``").Append (genArgs.Count);
5654                 }
5655                 IList<ParameterDefinition> parameters = method.Parameters;
5656                 try {
5657                         genDeclType   = method.DeclaringType;
5658                         genDeclMethod = method;
5659                         AppendParameters (buf, method.DeclaringType.GenericParameters, parameters);
5660                 }
5661                 finally {
5662                         genDeclType   = null;
5663                         genDeclMethod = null;
5664                 }
5665                 return buf.ToString ();
5666         }
5667
5668         private StringBuilder AppendParameters (StringBuilder buf, IList<GenericParameter> genArgs, IList<ParameterDefinition> parameters)
5669         {
5670                 if (parameters.Count == 0)
5671                         return buf;
5672
5673                 buf.Append ('(');
5674
5675                 AppendParameter (buf, genArgs, parameters [0]);
5676                 for (int i = 1; i < parameters.Count; ++i) {
5677                         buf.Append (',');
5678                         AppendParameter (buf, genArgs, parameters [i]);
5679                 }
5680
5681                 return buf.Append (')');
5682         }
5683
5684         private StringBuilder AppendParameter (StringBuilder buf, IList<GenericParameter> genArgs, ParameterDefinition parameter)
5685         {
5686                 AddTypeCount = false;
5687                 buf.Append (GetTypeName (parameter.ParameterType));
5688                 AddTypeCount = true;
5689                 return buf;
5690         }
5691
5692         protected override string GetPropertyName (PropertyReference property)
5693         {
5694                 string name = null;
5695
5696                 PropertyDefinition propertyDef = property as PropertyDefinition;
5697                 MethodDefinition method = null;
5698                 if (propertyDef != null)
5699                         method = propertyDef.GetMethod ?? propertyDef.SetMethod;
5700                 if (method != null && !DocUtils.IsExplicitlyImplemented (method))
5701                         name = property.Name;
5702                 else {
5703                         TypeReference iface;
5704                         MethodReference ifaceMethod;
5705                         DocUtils.GetInfoForExplicitlyImplementedMethod (method, out iface, out ifaceMethod);
5706                         AddTypeCount = false;
5707                         name = string.Join ("#", new string[]{
5708                                         GetTypeName (iface).Replace (".", "#"),
5709                                         DocUtils.GetMember (property.Name)
5710                         });
5711                         AddTypeCount = true;
5712                 }
5713
5714                 StringBuilder buf = new StringBuilder ();
5715                 buf.Append (GetName (property.DeclaringType));
5716                 buf.Append ('.');
5717                 buf.Append (name);
5718                 IList<ParameterDefinition> parameters = property.Parameters;
5719                 if (parameters.Count > 0) {
5720                         genDeclType = property.DeclaringType;
5721                         buf.Append ('(');
5722                         IList<GenericParameter> genArgs = property.DeclaringType.GenericParameters;
5723                         AppendParameter (buf, genArgs, parameters [0]);
5724                         for (int i = 1; i < parameters.Count; ++i) {
5725                                  buf.Append (',');
5726                                  AppendParameter (buf, genArgs, parameters [i]);
5727                         }
5728                         buf.Append (')');
5729                         genDeclType = null;
5730                 }
5731                 return buf.ToString ();
5732         }
5733
5734         protected override string GetFieldName (FieldReference field)
5735         {
5736                 return string.Format ("{0}.{1}",
5737                         GetName (field.DeclaringType), field.Name);
5738         }
5739
5740         protected override string GetEventName (EventReference e)
5741         {
5742                 return string.Format ("{0}.{1}",
5743                         GetName (e.DeclaringType), e.Name);
5744         }
5745
5746         protected override string GetTypeDeclaration (TypeDefinition type)
5747         {
5748                 string name = GetName (type);
5749                 if (type == null)
5750                         return null;
5751                 return "T:" + name;
5752         }
5753
5754         protected override string GetConstructorDeclaration (MethodDefinition constructor)
5755         {
5756                 string name = GetName (constructor);
5757                 if (name == null)
5758                         return null;
5759                 return "M:" + name;
5760         }
5761
5762         protected override string GetMethodDeclaration (MethodDefinition method)
5763         {
5764                 string name = GetName (method);
5765                 if (name == null)
5766                         return null;
5767                 if (method.Name == "op_Implicit" || method.Name == "op_Explicit") {
5768                         genDeclType = method.DeclaringType;
5769                         genDeclMethod = method;
5770                         name += "~" + GetName (method.ReturnType);
5771                         genDeclType = null;
5772                         genDeclMethod = null;
5773                 }
5774                 return "M:" + name;
5775         }
5776
5777         protected override string GetPropertyDeclaration (PropertyDefinition property)
5778         {
5779                 string name = GetName (property);
5780                 if (name == null)
5781                         return null;
5782                 return "P:" + name;
5783         }
5784
5785         protected override string GetFieldDeclaration (FieldDefinition field)
5786         {
5787                 string name = GetName (field);
5788                 if (name == null)
5789                         return null;
5790                 return "F:" + name;
5791         }
5792
5793         protected override string GetEventDeclaration (EventDefinition e)
5794         {
5795                 string name = GetName (e);
5796                 if (name == null)
5797                         return null;
5798                 return "E:" + name;
5799         }
5800 }
5801
5802 class FileNameMemberFormatter : SlashDocMemberFormatter {
5803         protected override StringBuilder AppendNamespace (StringBuilder buf, TypeReference type)
5804         {
5805                 return buf;
5806         }
5807
5808         protected override char NestedTypeSeparator {
5809                 get {return '+';}
5810         }
5811 }
5812
5813 class ResolvedTypeInfo {
5814         TypeDefinition typeDef;
5815
5816         public ResolvedTypeInfo (TypeReference value) {
5817                 Reference = value;
5818         }
5819
5820         public TypeReference Reference { get; private set; }
5821
5822         public TypeDefinition Definition {
5823                 get {
5824                         if (typeDef == null) {
5825                                 typeDef = Reference.Resolve ();
5826                         }
5827                         return typeDef;
5828                 }
5829         }
5830 }
5831
5832 /// <summary>Formats attribute values. Should return true if it is able to format the value.</summary>
5833 class AttributeValueFormatter {
5834         public virtual bool TryFormatValue (object v, ResolvedTypeInfo type, out string returnvalue)
5835         {
5836                 TypeReference valueType = type.Reference;
5837                 if (v == null) {
5838                         returnvalue = "null";
5839                         return true;
5840                 }
5841                 if (valueType.FullName == "System.Type") {
5842                         var vTypeRef = v as TypeReference;
5843                         if (vTypeRef != null) 
5844                                 returnvalue = "typeof(" + NativeTypeManager.GetTranslatedName (vTypeRef) + ")"; // TODO: drop NS handling
5845                         else
5846                                 returnvalue = "typeof(" + v.ToString () + ")";
5847                         
5848                         return true;
5849                 }
5850                 if (valueType.FullName == "System.String") {
5851                         returnvalue = "\"" + v.ToString () + "\"";
5852                         return true;
5853                 }
5854                 if (valueType.FullName == "System.Char") {
5855                         returnvalue = "'" + v.ToString () + "'";
5856                         return true;
5857                 }
5858                 if (v is Boolean) {
5859                         returnvalue = (bool)v ? "true" : "false";
5860                         return true;
5861                 }
5862
5863                 TypeDefinition valueDef = type.Definition;
5864                 if (valueDef == null || !valueDef.IsEnum) {
5865                         returnvalue = v.ToString ();
5866                         return true;
5867                 }
5868
5869                 string typename = MDocUpdater.GetDocTypeFullName (valueType);
5870                 var values = MDocUpdater.GetEnumerationValues (valueDef);
5871                 long c = MDocUpdater.ToInt64 (v);
5872                 if (values.ContainsKey (c)) {
5873                         returnvalue = typename + "." + values [c];
5874                         return true;
5875                 }
5876
5877                 returnvalue = null;
5878                 return false;
5879         }
5880 }
5881
5882 /// <summary>The final value formatter in the pipeline ... if no other formatter formats the value,
5883 /// then this one will serve as the default implementation.</summary>
5884 class DefaultAttributeValueFormatter : AttributeValueFormatter {
5885         public override bool TryFormatValue (object v, ResolvedTypeInfo type, out string returnvalue)
5886         {
5887                 returnvalue = "(" + MDocUpdater.GetDocTypeFullName (type.Reference) + ") " + v.ToString ();
5888                 return true;
5889         }
5890 }
5891
5892 /// <summary>Flags enum formatter that assumes powers of two values.</summary>
5893 /// <remarks>As described here: https://msdn.microsoft.com/en-us/library/vstudio/ms229062(v=vs.100).aspx</remarks>
5894 class StandardFlagsEnumFormatter : AttributeValueFormatter {
5895         public override bool TryFormatValue (object v, ResolvedTypeInfo type, out string returnvalue)
5896         {
5897                 TypeReference valueType = type.Reference;
5898                 TypeDefinition valueDef = type.Definition;
5899                 if (valueDef.CustomAttributes.Any (ca => ca.AttributeType.FullName == "System.FlagsAttribute")) {
5900
5901                         string typename = MDocUpdater.GetDocTypeFullName (valueType);
5902                         var values = MDocUpdater.GetEnumerationValues (valueDef);
5903                         long c = MDocUpdater.ToInt64 (v);
5904                         returnvalue = string.Join (" | ",
5905                                 (from i in values.Keys
5906                                  where (c & i) == i && i != 0
5907                                  select typename + "." + values [i])
5908                                 .DefaultIfEmpty (c.ToString ()).ToArray ());
5909                         
5910                         return true;
5911                 }
5912
5913                 returnvalue = null;
5914                 return false;
5915         }
5916 }
5917
5918 /// <summary>A custom formatter for the ObjCRuntime.Platform enumeration.</summary>
5919 class ApplePlatformEnumFormatter : AttributeValueFormatter {
5920         public override bool TryFormatValue (object v, ResolvedTypeInfo type, out string returnvalue)
5921         {
5922                 TypeReference valueType = type.Reference;
5923                 string typename = MDocUpdater.GetDocTypeFullName (valueType);
5924                 TypeDefinition valueDef = type.Definition;
5925                 if (typename.Contains ("ObjCRuntime.Platform") && valueDef.CustomAttributes.Any (ca => ca.AttributeType.FullName == "System.FlagsAttribute")) {
5926
5927                         var values = MDocUpdater.GetEnumerationValues (valueDef);
5928                         long c = MDocUpdater.ToInt64 (v);
5929
5930                         returnvalue = Format (c, values, typename);
5931                         return true;
5932                 }
5933
5934                 returnvalue = null;
5935                 return false;
5936         }
5937
5938         string Format (long c, IDictionary<long, string> values, string typename)
5939         {
5940                 int iosarch, iosmajor, iosminor, iossubminor;
5941                 int macarch, macmajor, macminor, macsubminor;
5942                 GetEncodingiOS (c, out iosarch, out iosmajor, out iosminor, out iossubminor);
5943                 GetEncodingMac ((ulong)c, out macarch, out macmajor, out macminor, out macsubminor);
5944
5945                 if (iosmajor == 0 & iosminor == 0 && iossubminor == 0) {
5946                         return FormatValues ("Mac", macarch, macmajor, macminor, macsubminor);
5947                 }
5948
5949                 if (macmajor == 0 & macminor == 0 && macsubminor == 0) {
5950                         return FormatValues ("iOS", iosarch, iosmajor, iosminor, iossubminor);
5951                 }
5952
5953                 return string.Format ("(Platform){0}", c);
5954         }
5955
5956         string FormatValues (string plat, int arch, int major, int minor, int subminor) 
5957         {
5958                 string archstring = "";
5959                 switch (arch) {
5960                 case 1:
5961                         archstring = "32";
5962                         break;
5963                 case 2:
5964                         archstring = "64";
5965                         break;
5966                 }
5967                 return string.Format ("Platform.{4}_{0}_{1}{2} | Platform.{4}_Arch{3}",
5968                         major,
5969                         minor,
5970                         subminor == 0 ? "" : "_" + subminor.ToString (),
5971                         archstring,
5972                         plat
5973                 );
5974         }
5975
5976         void GetEncodingiOS (long entireLong, out int archindex, out int major, out int minor, out int subminor)
5977         {
5978                 long lowerBits = entireLong & 0xffffffff; 
5979                 int lowerBitsAsInt = (int) lowerBits;
5980                 GetEncoding (lowerBitsAsInt, out archindex, out major, out minor, out subminor);
5981         }
5982
5983         void GetEncodingMac (ulong entireLong, out int archindex, out int major, out int minor, out int subminor)
5984         {
5985                 ulong higherBits = entireLong & 0xffffffff00000000; 
5986                 int higherBitsAsInt = (int) ((higherBits) >> 32);
5987                 GetEncoding (higherBitsAsInt, out archindex, out major, out minor, out subminor);
5988         }
5989
5990         void GetEncoding (Int32 encodedBits, out int archindex, out int major, out int minor, out int subminor)
5991         {
5992                 // format is AAJJNNSS
5993                 archindex = (int)((encodedBits & 0xFF000000) >> 24);
5994                 major = (int)((encodedBits & 0x00FF0000) >> 16);
5995                 minor = (int)((encodedBits & 0x0000FF00) >> 8);
5996                 subminor = (int)((encodedBits & 0x000000FF) >> 0);
5997         }
5998 }
5999 }