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