2005-01-10 Marek Safar <marek.safar@seznam.cz>
[mono.git] / mcs / mcs / doc.cs
1 //
2 // doc.cs: Support for XML documentation comment.
3 //
4 // Author:
5 //      Atsushi Enomoto <atsushi@ximian.com>
6 //
7 // Licensed under the terms of the GNU GPL
8 //
9 // (C) 2004 Novell, Inc.
10 //
11 //
12
13 #if ! BOOTSTRAP_WITH_OLDLIB
14 using System;
15 using System.Collections;
16 using System.Collections.Specialized;
17 using System.IO;
18 using System.Reflection;
19 using System.Reflection.Emit;
20 using System.Runtime.CompilerServices;
21 using System.Runtime.InteropServices;
22 using System.Security;
23 using System.Security.Permissions;
24 using System.Text;
25 using System.Xml;
26
27 using Mono.CompilerServices.SymbolWriter;
28
29 namespace Mono.CSharp {
30
31         //
32         // Support class for XML documentation.
33         //
34         public class DocUtil
35         {
36                 // TypeContainer
37
38                 //
39                 // Generates xml doc comments (if any), and if required,
40                 // handle warning report.
41                 //
42                 internal static void GenerateTypeDocComment (TypeContainer t,
43                         DeclSpace ds)
44                 {
45                         GenerateDocComment (t, ds);
46
47                         if (t.DefaultStaticConstructor != null)
48                                 t.DefaultStaticConstructor.GenerateDocComment (t);
49
50                         if (t.InstanceConstructors != null)
51                                 foreach (Constructor c in t.InstanceConstructors)
52                                         c.GenerateDocComment (t);
53
54                         if (t.Types != null)
55                                 foreach (TypeContainer tc in t.Types)
56                                         tc.GenerateDocComment (t);
57
58                         if (t.Parts != null) {
59                                 IDictionary comments = RootContext.Documentation.PartialComments;
60                                 foreach (ClassPart cp in t.Parts) {
61                                         if (cp.DocComment == null)
62                                                 continue;
63                                         comments [cp] = cp;
64                                 }
65                         }
66
67                         if (t.Enums != null)
68                                 foreach (Enum en in t.Enums)
69                                         en.GenerateDocComment (t);
70
71                         if (t.Constants != null)
72                                 foreach (Const c in t.Constants)
73                                         c.GenerateDocComment (t);
74
75                         if (t.Fields != null)
76                                 foreach (Field f in t.Fields)
77                                         f.GenerateDocComment (t);
78
79                         if (t.Events != null)
80                                 foreach (Event e in t.Events)
81                                         e.GenerateDocComment (t);
82
83                         if (t.Indexers != null)
84                                 foreach (Indexer ix in t.Indexers)
85                                         ix.GenerateDocComment (t);
86
87                         if (t.Properties != null)
88                                 foreach (Property p in t.Properties)
89                                         p.GenerateDocComment (t);
90
91                         if (t.Methods != null)
92                                 foreach (Method m in t.Methods)
93                                         m.GenerateDocComment (t);
94
95                         if (t.Operators != null)
96                                 foreach (Operator o in t.Operators)
97                                         o.GenerateDocComment (t);
98                 }
99
100                 // MemberCore
101                 private static readonly string lineHead =
102                         Environment.NewLine + "            ";
103
104                 private static XmlNode GetDocCommentNode (MemberCore mc,
105                         string name)
106                 {
107                         // FIXME: It could be even optimizable as not
108                         // to use XmlDocument. But anyways the nodes
109                         // are not kept in memory.
110                         XmlDocument doc = RootContext.Documentation.XmlDocumentation;
111                         try {
112                                 XmlElement el = doc.CreateElement ("member");
113                                 el.SetAttribute ("name", name);
114                                 string normalized = mc.DocComment;
115                                 el.InnerXml = normalized;
116                                 // csc keeps lines as written in the sources
117                                 // and inserts formatting indentation (which 
118                                 // is different from XmlTextWriter.Formatting
119                                 // one), but when a start tag contains an 
120                                 // endline, it joins the next line. We don't
121                                 // have to follow such a hacky behavior.
122                                 string [] split =
123                                         normalized.Split ('\n');
124                                 int j = 0;
125                                 for (int i = 0; i < split.Length; i++) {
126                                         string s = split [i].TrimEnd ();
127                                         if (s.Length > 0)
128                                                 split [j++] = s;
129                                 }
130                                 el.InnerXml = lineHead + String.Join (
131                                         lineHead, split, 0, j);
132                                 return el;
133                         } catch (XmlException ex) {
134                                 Report.Warning (1570, 1, mc.Location, "XML comment on '{0}' has non-well-formed XML ({1}).", name, ex.Message);
135                                 XmlComment com = doc.CreateComment (String.Format ("FIXME: Invalid documentation markup was found for member {0}", name));
136                                 return com;
137                         }
138                 }
139
140                 //
141                 // Generates xml doc comments (if any), and if required,
142                 // handle warning report.
143                 //
144                 internal static void GenerateDocComment (MemberCore mc,
145                         DeclSpace ds)
146                 {
147                         if (mc.DocComment != null) {
148                                 string name = mc.GetDocCommentName (ds);
149
150                                 XmlNode n = GetDocCommentNode (mc, name);
151
152                                 XmlElement el = n as XmlElement;
153                                 if (el != null) {
154                                         mc.OnGenerateDocComment (ds, el);
155
156                                         // FIXME: it could be done with XmlReader
157                                         foreach (XmlElement inc in n.SelectNodes (".//include"))
158                                                 HandleInclude (mc, inc);
159
160                                         // FIXME: it could be done with XmlReader
161                                         DeclSpace dsTarget = mc as DeclSpace;
162                                         if (dsTarget == null)
163                                                 dsTarget = ds;
164
165                                         foreach (XmlElement see in n.SelectNodes (".//see"))
166                                                 HandleSee (mc, dsTarget, see);
167                                         foreach (XmlElement seealso in n.SelectNodes (".//seealso"))
168                                                 HandleSeeAlso (mc, dsTarget, seealso);
169                                         foreach (XmlElement see in n.SelectNodes (".//exception"))
170                                                 HandleException (mc, dsTarget, see);
171                                 }
172
173                                 n.WriteTo (RootContext.Documentation.XmlCommentOutput);
174                         }
175                         else if (mc.IsExposedFromAssembly (ds)) {
176                                 Constructor c = mc as Constructor;
177                                 if (c == null || !c.IsDefault ())
178                                         Report.Warning (1591, 4, mc.Location,
179                                                 "Missing XML comment for publicly visible type or member '{0}'", mc.GetSignatureForError ());
180                         }
181                 }
182
183                 //
184                 // Processes "include" element. Check included file and
185                 // embed the document content inside this documentation node.
186                 //
187                 private static void HandleInclude (MemberCore mc, XmlElement el)
188                 {
189                         string file = el.GetAttribute ("file");
190                         string path = el.GetAttribute ("path");
191                         if (file == "") {
192                                 Report.Warning (1590, 1, mc.Location, "Invalid XML 'include' element; Missing 'file' attribute.");
193                                 el.ParentNode.InsertBefore (el.OwnerDocument.CreateComment (" Include tag is invalid "), el);
194                         }
195                         else if (path == "") {
196                                 Report.Warning (1590, 1, mc.Location, "Invalid XML 'include' element; Missing 'path' attribute.");
197                                 el.ParentNode.InsertBefore (el.OwnerDocument.CreateComment (" Include tag is invalid "), el);
198                         }
199                         else {
200                                 XmlDocument doc = RootContext.Documentation.StoredDocuments [file] as XmlDocument;
201                                 if (doc == null) {
202                                         try {
203                                                 doc = new XmlDocument ();
204                                                 doc.Load (file);
205                                                 RootContext.Documentation.StoredDocuments.Add (file, doc);
206                                         } catch (Exception) {
207                                                 el.ParentNode.InsertBefore (el.OwnerDocument.CreateComment (String.Format (" Badly formed XML in at comment file '{0}': cannot be included ", file)), el);
208                                                 Report.Warning (1592, 1, mc.Location, "Badly formed XML in included comments file -- '{0}'", file);
209                                         }
210                                 }
211                                 bool keepIncludeNode = false;
212                                 if (doc != null) {
213                                         try {
214                                                 XmlNodeList nl = doc.SelectNodes (path);
215                                                 if (nl.Count == 0) {
216                                                         el.ParentNode.InsertBefore (el.OwnerDocument.CreateComment (" No matching elements were found for the include tag embedded here. "), el);
217                                         
218                                                         keepIncludeNode = true;
219                                                 }
220                                                 foreach (XmlNode n in nl)
221                                                         el.ParentNode.InsertBefore (el.OwnerDocument.ImportNode (n, true), el);
222                                         } catch (Exception ex) {
223                                                 el.ParentNode.InsertBefore (el.OwnerDocument.CreateComment (" Failed to insert some or all of included XML "), el);
224                                                 Report.Warning (1589, 1, mc.Location, "Unable to include XML fragment '{0}' of file {1} -- {2}.", path, file, ex.Message);
225                                         }
226                                 }
227                                 if (!keepIncludeNode)
228                                         el.ParentNode.RemoveChild (el);
229                         }
230                 }
231
232                 //
233                 // Handles <see> elements.
234                 //
235                 private static void HandleSee (MemberCore mc,
236                         DeclSpace ds, XmlElement see)
237                 {
238                         HandleXrefCommon (mc, ds, see);
239                 }
240
241                 //
242                 // Handles <seealso> elements.
243                 //
244                 private static void HandleSeeAlso (MemberCore mc,
245                         DeclSpace ds, XmlElement seealso)
246                 {
247                         HandleXrefCommon (mc, ds, seealso);
248                 }
249
250                 //
251                 // Handles <exception> elements.
252                 //
253                 private static void HandleException (MemberCore mc,
254                         DeclSpace ds, XmlElement seealso)
255                 {
256                         HandleXrefCommon (mc, ds, seealso);
257                 }
258
259                 static readonly char [] wsChars =
260                         new char [] {' ', '\t', '\n', '\r'};
261
262                 //
263                 // returns a full runtime type name from a name which might
264                 // be C# specific type name.
265                 //
266                 private static Type FindDocumentedType (MemberCore mc,
267                         string name, DeclSpace ds, bool allowAlias, string cref)
268                 {
269                         bool isArray = false;
270                         string identifier = name;
271                         if (name [name.Length - 1] == ']') {
272                                 string tmp = name.Substring (0, name.Length - 1).Trim (wsChars);
273                                 if (tmp [tmp.Length - 1] == '[') {
274                                         identifier = tmp.Substring (0, tmp.Length - 1).Trim (wsChars);
275                                         isArray = true;
276                                 }
277                         }
278                         Type t = FindDocumentedTypeNonArray (mc, identifier,
279                                 ds, allowAlias, cref);
280                         if (t != null && isArray)
281                                 t = Array.CreateInstance (t, 0).GetType ();
282                         return t;
283                 }
284
285                 private static Type FindDocumentedTypeNonArray (MemberCore mc,
286                         string identifier, DeclSpace ds, bool allowAlias,
287                         string cref)
288                 {
289                         switch (identifier) {
290                         case "int":
291                                 return typeof (int);
292                         case "uint":
293                                 return typeof (uint);
294                         case "short":
295                                 return typeof (short);
296                         case "ushort":
297                                 return typeof (ushort);
298                         case "long":
299                                 return typeof (long);
300                         case "ulong":
301                                 return typeof (ulong);
302                         case "float":
303                                 return typeof (float);
304                         case "double":
305                                 return typeof (double);
306                         case "char":
307                                 return typeof (char);
308                         case "decimal":
309                                 return typeof (decimal);
310                         case "byte":
311                                 return typeof (byte);
312                         case "sbyte":
313                                 return typeof (sbyte);
314                         case "object":
315                                 return typeof (object);
316                         case "bool":
317                                 return typeof (bool);
318                         case "string":
319                                 return typeof (string);
320                         case "void":
321                                 return typeof (void);
322                         }
323                         if (allowAlias) {
324                                 IAlias alias = ds.LookupAlias (identifier);
325                                 if (alias != null)
326                                         identifier = alias.Name;
327                         }
328                         Type t = ds.FindType (mc.Location, identifier);
329                         if (t == null)
330                                 t = TypeManager.LookupType (identifier);
331                         if (t == null) {
332                                 int index = identifier.LastIndexOf ('.');
333                                 if (index < 0)
334                                         return null;
335                                 int warn;
336                                 Type parent = FindDocumentedType (mc,
337                                         identifier.Substring (0, index),
338                                         ds, allowAlias, cref);
339                                 if (parent == null)
340                                         return null;
341                                 t = FindDocumentedMember (mc, parent,
342                                         identifier.Substring (index + 1),
343                                         emptyParamList,
344                                         ds, out warn, cref) as Type;
345                         }
346                         return t;
347                 }
348
349                 //
350                 // Returns a MemberInfo that is referenced in XML documentation
351                 // (by "see" or "seealso" elements).
352                 //
353                 private static MemberInfo FindDocumentedMember (MemberCore mc,
354                         Type type, string memberName, Type [] paramList, 
355                         DeclSpace ds, out int warningType, string cref)
356                 {
357                         warningType = 0;
358                         MethodSignature msig = new MethodSignature (memberName, null, paramList);
359                         MemberInfo [] mis = type.FindMembers (
360                                 MemberTypes.All,
361                                 BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance,
362                                 MethodSignature.method_signature_filter,
363                                 msig);
364                         if (mis.Length > 0)
365                                 return mis [0];
366
367                         if (paramList.Length == 0) {
368                                 // search for fields/events etc.
369                                 mis = type.FindMembers (
370                                         MemberTypes.All,
371                                         BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance,
372                                         Type.FilterName,
373                                         memberName);
374                                 return (mis.Length > 0) ? mis [0] : null;
375                         }
376
377                         // search for operators (whose parameters exactly
378                         // matches with the list) and possibly report CS1581.
379                         string oper = null;
380                         string returnTypeName = null;
381                         if (memberName.StartsWith ("implicit operator ")) {
382                                 oper = "op_Implicit";
383                                 returnTypeName = memberName.Substring (18).Trim (wsChars);
384                         }
385                         else if (memberName.StartsWith ("explicit operator ")) {
386                                 oper = "op_Explicit";
387                                 returnTypeName = memberName.Substring (18).Trim (wsChars);
388                         }
389                         else if (memberName.StartsWith ("operator ")) {
390                                 oper = memberName.Substring (9).Trim (wsChars);
391                                 switch (oper) {
392                                 // either unary or binary
393                                 case "+":
394                                         oper = paramList.Length == 2 ?
395                                                 Binary.oper_names [(int) Binary.Operator.Addition] :
396                                                 Unary.oper_names [(int) Unary.Operator.UnaryPlus];
397                                         break;
398                                 case "-":
399                                         oper = paramList.Length == 2 ?
400                                                 Binary.oper_names [(int) Binary.Operator.Subtraction] :
401                                                 Unary.oper_names [(int) Unary.Operator.UnaryNegation];
402                                         break;
403                                 // unary
404                                 case "!":
405                                         oper = Unary.oper_names [(int) Unary.Operator.LogicalNot]; break;
406                                 case "~":
407                                         oper = Unary.oper_names [(int) Unary.Operator.OnesComplement]; break;
408                                         
409                                 case "++":
410                                         oper = "op_Increment"; break;
411                                 case "--":
412                                         oper = "op_Decrement"; break;
413                                 case "true":
414                                         oper = "op_True"; break;
415                                 case "false":
416                                         oper = "op_False"; break;
417                                 // binary
418                                 case "*":
419                                         oper = Binary.oper_names [(int) Binary.Operator.Multiply]; break;
420                                 case "/":
421                                         oper = Binary.oper_names [(int) Binary.Operator.Division]; break;
422                                 case "%":
423                                         oper = Binary.oper_names [(int) Binary.Operator.Modulus]; break;
424                                 case "&":
425                                         oper = Binary.oper_names [(int) Binary.Operator.BitwiseAnd]; break;
426                                 case "|":
427                                         oper = Binary.oper_names [(int) Binary.Operator.BitwiseOr]; break;
428                                 case "^":
429                                         oper = Binary.oper_names [(int) Binary.Operator.ExclusiveOr]; break;
430                                 case "<<":
431                                         oper = Binary.oper_names [(int) Binary.Operator.LeftShift]; break;
432                                 case ">>":
433                                         oper = Binary.oper_names [(int) Binary.Operator.RightShift]; break;
434                                 case "==":
435                                         oper = Binary.oper_names [(int) Binary.Operator.Equality]; break;
436                                 case "!=":
437                                         oper = Binary.oper_names [(int) Binary.Operator.Inequality]; break;
438                                 case "<":
439                                         oper = Binary.oper_names [(int) Binary.Operator.LessThan]; break;
440                                 case ">":
441                                         oper = Binary.oper_names [(int) Binary.Operator.GreaterThan]; break;
442                                 case "<=":
443                                         oper = Binary.oper_names [(int) Binary.Operator.LessThanOrEqual]; break;
444                                 case ">=":
445                                         oper = Binary.oper_names [(int) Binary.Operator.GreaterThanOrEqual]; break;
446                                 default:
447                                         warningType = 1584;
448                                         Report.Warning (1020, 1, mc.Location, "Overloadable {0} operator is expected", paramList.Length == 2 ? "binary" : "unary");
449                                         Report.Warning (1584, 1, mc.Location, "XML comment on '{0}' has syntactically incorrect attribute '{1}'", mc.GetSignatureForError (), cref);
450                                         return null;
451                                 }
452                         }
453                         // here we still does not consider return type (to
454                         // detect CS1581 or CS1002+CS1584).
455                         msig = new MethodSignature (oper, null, paramList);
456                         mis = type.FindMembers (
457                                 MemberTypes.Method,
458                                 BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static,
459                                 MethodSignature.method_signature_filter,
460                                 msig);
461                         if (mis.Length == 0)
462                                 return null; // CS1574
463                         MemberInfo mi = mis [0];
464                         Type expected = mi is MethodInfo ?
465                                 ((MethodInfo) mi).ReturnType :
466                                 mi is PropertyInfo ?
467                                 ((PropertyInfo) mi).PropertyType :
468                                 null;
469                         if (returnTypeName != null) {
470                                 Type returnType = FindDocumentedType (mc, returnTypeName, ds, true, cref);
471                                 if (returnType == null || returnType != expected) {
472                                         warningType = 1581;
473                                         Report.Warning (1581, 1, mc.Location, "Invalid return type in XML comment cref attribute '{0}'", cref);
474                                         return null;
475                                 }
476                         }
477                         return mis [0];
478                 }
479
480                 private static Type [] emptyParamList = new Type [0];
481
482                 //
483                 // Processes "see" or "seealso" elements.
484                 // Checks cref attribute.
485                 //
486                 private static void HandleXrefCommon (MemberCore mc,
487                         DeclSpace ds, XmlElement xref)
488                 {
489                         string cref = xref.GetAttribute ("cref").Trim (wsChars);
490                         // when, XmlReader, "if (cref == null)"
491                         if (!xref.HasAttribute ("cref"))
492                                 return;
493                         if (cref.Length == 0)
494                                 Report.Warning (1001, 1, mc.Location, "Identifier expected");
495                                 // ... and continue until CS1584.
496
497                         string signature; // "x:" are stripped
498                         string name; // method invokation "(...)" are removed
499                         string parameters; // method parameter list
500
501                         // strip 'T:' 'M:' 'F:' 'P:' 'E:' etc.
502                         // Here, MS ignores its member kind. No idea why.
503                         if (cref.Length > 2 && cref [1] == ':')
504                                 signature = cref.Substring (2).Trim (wsChars);
505                         else
506                                 signature = cref;
507
508                         int parensPos = signature.IndexOf ('(');
509                         if (parensPos > 0 && signature [signature.Length - 1] == ')') {
510                                 name = signature.Substring (0, parensPos).Trim (wsChars);
511                                 parameters = signature.Substring (parensPos + 1, signature.Length - parensPos - 2);
512                         }
513                         else {
514                                 name = signature;
515                                 parameters = String.Empty;
516                         }
517
518                         string identifier = name;
519
520                         if (name.Length > 0 && name [name.Length - 1] == ']') {
521                                 string tmp = name.Substring (0, name.Length - 1).Trim (wsChars);
522                                 if (tmp [tmp.Length - 1] == '[')
523                                         identifier = tmp.Substring (0, tmp.Length - 1).Trim (wsChars);
524                         }
525
526                         // Check if identifier is valid.
527                         // This check is not necessary to mark as error, but
528                         // csc specially reports CS1584 for wrong identifiers.
529                         foreach (string nameElem in identifier.Split ('.')) {
530                                 if (!Tokenizer.IsValidIdentifier (nameElem)
531                                         && nameElem.IndexOf ("operator") < 0) {
532                                         if (nameElem.EndsWith ("[]") &&
533                                                 Tokenizer.IsValidIdentifier (
534                                                 nameElem.Substring (
535                                                 0, nameElem.Length - 2)))
536                                                 continue;
537
538                                         Report.Warning (1584, 1, mc.Location, "XML comment on '{0}' has syntactically incorrect attribute '{1}'", mc.GetSignatureForError (), cref);
539                                         xref.SetAttribute ("cref", "!:" + signature);
540                                         return;
541                                 }
542                         }
543
544                         // check if parameters are valid
545                         Type [] parameterTypes = emptyParamList;
546                         if (parameters.Length > 0) {
547                                 string [] paramList = parameters.Split (',');
548                                 ArrayList plist = new ArrayList ();
549                                 for (int i = 0; i < paramList.Length; i++) {
550                                         string paramTypeName = paramList [i].Trim (wsChars);
551                                         Type paramType = FindDocumentedType (mc, paramTypeName, ds, true, cref);
552                                         if (paramType == null) {
553                                                 Report.Warning (1580, 1, mc.Location, "Invalid type for parameter '{0}' in XML comment cref attribute '{1}'", i + 1, cref);
554                                                 return;
555                                         }
556                                         plist.Add (paramType);
557                                 }
558                                 parameterTypes = plist.ToArray (typeof (Type)) as Type [];
559                                 StringBuilder sb = new StringBuilder ();
560                                 sb.Append ('(');
561                                 for (int i = 0; i < parameterTypes.Length; i++) {
562                                         Type t = parameterTypes [i];
563                                         if (sb.Length > 1)
564                                                 sb.Append (',');
565                                         sb.Append (t.FullName.Replace ('+', '.'));
566                                 }
567                                 sb.Append (')');
568                                 parameters = sb.ToString ();
569                         }
570
571                         Type type = FindDocumentedType (mc, name, ds, true, cref);
572                         if (type != null) {
573                                 xref.SetAttribute ("cref", "T:" + type.FullName.Replace ("+", "."));
574                                 return; // a type
575                         }
576
577                         // don't use identifier here. System[] is not alloed.
578                         if (Namespace.IsNamespace (name)) {
579                                 xref.SetAttribute ("cref", "N:" + name);
580                                 return; // a namespace
581                         }
582
583                         int period = name.LastIndexOf ('.');
584                         if (period > 0) {
585                                 string typeName = name.Substring (0, period);
586                                 string memberName = name.Substring (period + 1);
587                                 type = FindDocumentedType (mc, typeName, ds, false, cref);
588                                 int warnResult;
589                                 if (type != null) {
590                                         MemberInfo mi = FindDocumentedMember (mc, type, memberName, parameterTypes, ds, out warnResult, cref);
591                                         if (warnResult > 0)
592                                                 return;
593                                         if (mi != null) {
594                                                 xref.SetAttribute ("cref", GetMemberDocHead (mi.MemberType) + type.FullName.Replace ("+", ".") + "." + memberName + parameters);
595                                                 return; // a member of a type
596                                         }
597                                 }
598                         }
599                         else {
600                                 int warnResult;
601                                 MemberInfo mi = FindDocumentedMember (mc, ds.TypeBuilder, name, parameterTypes, ds, out warnResult, cref);
602                                 if (warnResult > 0)
603                                         return;
604                                 if (mi != null) {
605                                         xref.SetAttribute ("cref", GetMemberDocHead (mi.MemberType) + ds.TypeBuilder.FullName.Replace ("+", ".") + "." + name);
606                                         return; // local member name
607                                 }
608                         }
609
610                         Report.Warning (1574, 1, mc.Location, "XML comment on '{0}' has cref attribute '{1}' that could not be resolved in '{2}'.", mc.GetSignatureForError (), cref, ds.GetSignatureForError ());
611
612                         xref.SetAttribute ("cref", "!:" + name);
613                 }
614
615                 //
616                 // Get a prefix from member type for XML documentation (used
617                 // to formalize cref target name).
618                 //
619                 static string GetMemberDocHead (MemberTypes type)
620                 {
621                         switch (type) {
622                         case MemberTypes.Constructor:
623                         case MemberTypes.Method:
624                                 return "M:";
625                         case MemberTypes.Event:
626                                 return "E:";
627                         case MemberTypes.Field:
628                                 return "F:";
629                         case MemberTypes.NestedType:
630                         case MemberTypes.TypeInfo:
631                                 return "T:";
632                         case MemberTypes.Property:
633                                 return "P:";
634                         }
635                         return "!:";
636                 }
637
638                 // MethodCore
639
640                 //
641                 // Returns a string that represents the signature for this 
642                 // member which should be used in XML documentation.
643                 //
644                 public static string GetMethodDocCommentName (MethodCore mc, DeclSpace ds)
645                 {
646                         Parameter [] plist = mc.Parameters.FixedParameters;
647                         Parameter parr = mc.Parameters.ArrayParameter;
648                         string paramSpec = String.Empty;
649                         if (plist != null) {
650                                 StringBuilder psb = new StringBuilder ();
651                                 foreach (Parameter p in plist) {
652                                         psb.Append (psb.Length != 0 ? "," : "(");
653                                         psb.Append (p.ParameterType.FullName.Replace ("+", "."));
654                                 }
655                                 paramSpec = psb.ToString ();
656                         }
657                         if (parr != null)
658                                 paramSpec += String.Concat (
659                                         paramSpec == String.Empty ? "(" : ",",
660                                         parr.ParameterType.FullName.Replace ("+", "."));
661
662                         if (paramSpec.Length > 0)
663                                 paramSpec += ")";
664
665                         string name = mc is Constructor ? "#ctor" : mc.Name;
666                         string suffix = String.Empty;
667                         Operator op = mc as Operator;
668                         if (op != null) {
669                                 switch (op.OperatorType) {
670                                 case Operator.OpType.Implicit:
671                                 case Operator.OpType.Explicit:
672                                         suffix = "~" + op.OperatorMethodBuilder.ReturnType.FullName.Replace ('+', '.');
673                                         break;
674                                 }
675                         }
676                         return String.Concat (mc.DocCommentHeader, ds.Name, ".", name, paramSpec, suffix);
677                 }
678
679                 //
680                 // Raised (and passed an XmlElement that contains the comment)
681                 // when GenerateDocComment is writing documentation expectedly.
682                 //
683                 // FIXME: with a few effort, it could be done with XmlReader,
684                 // that means removal of DOM use.
685                 //
686                 internal static void OnMethodGenerateDocComment (
687                         MethodCore mc, DeclSpace ds, XmlElement el)
688                 {
689                         Hashtable paramTags = new Hashtable ();
690                         foreach (XmlElement pelem in el.SelectNodes ("param")) {
691                                 int i;
692                                 string xname = pelem.GetAttribute ("name");
693                                 if (xname == "")
694                                         continue; // really? but MS looks doing so
695                                 if (xname != "" && mc.Parameters.GetParameterByName (xname, out i) == null)
696                                         Report.Warning (1572, 2, mc.Location, "XML comment on '{0}' has a 'param' tag for '{1}', but there is no such parameter.", mc.Name, xname);
697                                 else if (paramTags [xname] != null)
698                                         Report.Warning (1571, 2, mc.Location, "XML comment on '{0}' has a duplicate param tag for '{1}'", mc.Name, xname);
699                                 paramTags [xname] = xname;
700                         }
701                         Parameter [] plist = mc.Parameters.FixedParameters;
702                         if (plist != null) {
703                                 foreach (Parameter p in plist) {
704                                         if (paramTags.Count > 0 && paramTags [p.Name] == null)
705                                                 Report.Warning (1573, 4, mc.Location, "Parameter '{0}' has no matching param tag in the XML comment for '{1}' (but other parameters do)", mc.Name, p.Name);
706                                 }
707                         }
708                 }
709
710                 // Enum
711                 public static void GenerateEnumDocComment (Enum e, DeclSpace ds)
712                 {
713                         GenerateDocComment (e, ds);
714                         foreach (string name in e.ordered_enums) {
715                                 MemberCore mc = e.GetDefinition (name);
716                                 GenerateDocComment (mc, e);
717                         }
718                 }
719         }
720
721         //
722         // Implements XML documentation generation.
723         //
724         public class Documentation
725         {
726                 public Documentation (string xml_output_filename)
727                 {
728                         docfilename = xml_output_filename;
729                         XmlDocumentation = new XmlDocument ();
730                         XmlDocumentation.PreserveWhitespace = false;
731                 }
732
733                 private string docfilename;
734
735                 //
736                 // Used to create element which helps well-formedness checking.
737                 //
738                 public XmlDocument XmlDocumentation;
739
740                 //
741                 // The output for XML documentation.
742                 //
743                 public XmlWriter XmlCommentOutput;
744
745                 //
746                 // Stores XmlDocuments that are included in XML documentation.
747                 // Keys are included filenames, values are XmlDocuments.
748                 //
749                 public Hashtable StoredDocuments = new Hashtable ();
750
751                 //
752                 // Stores comments on partial types (should handle uniquely).
753                 // Keys are PartialContainers, values are comment strings
754                 // (didn't use StringBuilder; usually we have just 2 or more).
755                 //
756                 public IDictionary PartialComments = new ListDictionary ();
757
758                 //
759                 // Outputs XML documentation comment from tokenized comments.
760                 //
761                 public bool OutputDocComment (string asmfilename)
762                 {
763                         XmlTextWriter w = null;
764                         try {
765                                 w = new XmlTextWriter (docfilename, null);
766                                 w.Indentation = 4;
767                                 w.Formatting = Formatting.Indented;
768                                 w.WriteStartDocument ();
769                                 w.WriteStartElement ("doc");
770                                 w.WriteStartElement ("assembly");
771                                 w.WriteStartElement ("name");
772                                 w.WriteString (Path.ChangeExtension (asmfilename, null));
773                                 w.WriteEndElement (); // name
774                                 w.WriteEndElement (); // assembly
775                                 w.WriteStartElement ("members");
776                                 XmlCommentOutput = w;
777                                 GenerateDocComment ();
778                                 w.WriteFullEndElement (); // members
779                                 w.WriteEndElement ();
780                                 w.WriteWhitespace (Environment.NewLine);
781                                 w.WriteEndDocument ();
782                                 return true;
783                         } catch (Exception ex) {
784                                 Report.Error (1569, "Error generating XML documentation file '{0}' ('{1}')", docfilename, ex.Message);
785                                 return false;
786                         } finally {
787                                 if (w != null)
788                                         w.Close ();
789                         }
790                 }
791
792                 //
793                 // Fixes full type name of each documented types/members up.
794                 //
795                 public void GenerateDocComment ()
796                 {
797                         TypeContainer root = RootContext.Tree.Types;
798                         if (root.Interfaces != null)
799                                 foreach (Interface i in root.Interfaces) 
800                                         DocUtil.GenerateTypeDocComment (i, null);
801
802                         if (root.Types != null)
803                                 foreach (TypeContainer tc in root.Types)
804                                         DocUtil.GenerateTypeDocComment (tc, null);
805
806                         if (root.Parts != null) {
807                                 IDictionary comments = PartialComments;
808                                 foreach (ClassPart cp in root.Parts) {
809                                         if (cp.DocComment == null)
810                                                 continue;
811                                         comments [cp] = cp;
812                                 }
813                         }
814
815                         if (root.Delegates != null)
816                                 foreach (Delegate d in root.Delegates) 
817                                         DocUtil.GenerateDocComment (d, null);
818
819                         if (root.Enums != null)
820                                 foreach (Enum e in root.Enums)
821                                         DocUtil.GenerateEnumDocComment (e, null);
822
823                         IDictionary table = new ListDictionary ();
824                         foreach (ClassPart cp in PartialComments.Keys) {
825                                 table [cp.PartialContainer] += cp.DocComment;
826                         }
827                         foreach (PartialContainer pc in table.Keys) {
828                                 pc.DocComment = table [pc] as string;
829                                 DocUtil.GenerateDocComment (pc, null);
830                         }
831                 }
832         }
833 }
834
835 #endif