**** Merged r36954 from MCS ****
[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 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                                 // There are no warnings when the container also
175                                 // misses documentations.
176                                 (ds == null || ds.DocComment != null))
177                         {
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)
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);
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                 {
288                         switch (identifier) {
289                         case "int":
290                                 return typeof (int);
291                         case "uint":
292                                 return typeof (uint);
293                         case "short":
294                                 return typeof (short);
295                         case "ushort":
296                                 return typeof (ushort);
297                         case "long":
298                                 return typeof (long);
299                         case "ulong":
300                                 return typeof (ulong);
301                         case "float":
302                                 return typeof (float);
303                         case "double":
304                                 return typeof (double);
305                         case "char":
306                                 return typeof (char);
307                         case "decimal":
308                                 return typeof (decimal);
309                         case "byte":
310                                 return typeof (byte);
311                         case "sbyte":
312                                 return typeof (sbyte);
313                         case "object":
314                                 return typeof (object);
315                         case "bool":
316                                 return typeof (bool);
317                         case "string":
318                                 return typeof (string);
319                         case "void":
320                                 return typeof (void);
321                         }
322                         if (allowAlias) {
323                                 string alias = ds.LookupAlias (identifier);
324                                 if (alias != null)
325                                         identifier = alias;
326                         }
327                         Type t = ds.FindType (mc.Location, identifier);
328                         if (t == null)
329                                 t = TypeManager.LookupTypeDirect (identifier);
330                         return t;
331                 }
332
333                 //
334                 // Returns a MemberInfo that is referenced in XML documentation
335                 // (by "see" or "seealso" elements).
336                 //
337                 private static MemberInfo FindDocumentedMember (MemberCore mc,
338                         Type type, string memberName, Type [] paramList, 
339                         DeclSpace ds, out int warningType, string cref)
340                 {
341                         warningType = 0;
342                         MethodSignature msig = new MethodSignature (memberName, null, paramList);
343                         MemberInfo [] mis = type.FindMembers (
344                                 MemberTypes.All,
345                                 BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance,
346                                 MethodSignature.method_signature_filter,
347                                 msig);
348                         if (mis.Length > 0)
349                                 return mis [0];
350
351                         if (paramList.Length == 0) {
352                                 // search for fields/events etc.
353                                 mis = type.FindMembers (
354                                         MemberTypes.All,
355                                         BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance,
356                                         Type.FilterName,
357                                         memberName);
358                                 return (mis.Length > 0) ? mis [0] : null;
359                         }
360
361                         // search for operators (whose parameters exactly
362                         // matches with the list) and possibly report CS1581.
363                         string oper = null;
364                         string returnTypeName = null;
365                         if (memberName.StartsWith ("implicit operator ")) {
366                                 oper = "op_Implicit";
367                                 returnTypeName = memberName.Substring (18).Trim (wsChars);
368                         }
369                         else if (memberName.StartsWith ("explicit operator ")) {
370                                 oper = "op_Explicit";
371                                 returnTypeName = memberName.Substring (18).Trim (wsChars);
372                         }
373                         else if (memberName.StartsWith ("operator ")) {
374                                 oper = memberName.Substring (9).Trim (wsChars);
375                                 switch (oper) {
376                                 // either unary or binary
377                                 case "+":
378                                         oper = paramList.Length == 2 ?
379                                                 Binary.oper_names [(int) Binary.Operator.Addition] :
380                                                 Unary.oper_names [(int) Unary.Operator.UnaryPlus];
381                                         break;
382                                 case "-":
383                                         oper = paramList.Length == 2 ?
384                                                 Binary.oper_names [(int) Binary.Operator.Subtraction] :
385                                                 Unary.oper_names [(int) Unary.Operator.UnaryNegation];
386                                         break;
387                                 // unary
388                                 case "!":
389                                         oper = Unary.oper_names [(int) Unary.Operator.LogicalNot]; break;
390                                 case "~":
391                                         oper = Unary.oper_names [(int) Unary.Operator.OnesComplement]; break;
392                                         
393                                 case "++":
394                                         oper = "op_Increment"; break;
395                                 case "--":
396                                         oper = "op_Decrement"; break;
397                                 case "true":
398                                         oper = "op_True"; break;
399                                 case "false":
400                                         oper = "op_False"; break;
401                                 // binary
402                                 case "*":
403                                         oper = Binary.oper_names [(int) Binary.Operator.Multiply]; break;
404                                 case "/":
405                                         oper = Binary.oper_names [(int) Binary.Operator.Division]; break;
406                                 case "%":
407                                         oper = Binary.oper_names [(int) Binary.Operator.Modulus]; break;
408                                 case "&":
409                                         oper = Binary.oper_names [(int) Binary.Operator.BitwiseAnd]; break;
410                                 case "|":
411                                         oper = Binary.oper_names [(int) Binary.Operator.BitwiseOr]; break;
412                                 case "^":
413                                         oper = Binary.oper_names [(int) Binary.Operator.ExclusiveOr]; break;
414                                 case "<<":
415                                         oper = Binary.oper_names [(int) Binary.Operator.LeftShift]; break;
416                                 case ">>":
417                                         oper = Binary.oper_names [(int) Binary.Operator.RightShift]; break;
418                                 case "==":
419                                         oper = Binary.oper_names [(int) Binary.Operator.Equality]; break;
420                                 case "!=":
421                                         oper = Binary.oper_names [(int) Binary.Operator.Inequality]; break;
422                                 case "<":
423                                         oper = Binary.oper_names [(int) Binary.Operator.LessThan]; break;
424                                 case ">":
425                                         oper = Binary.oper_names [(int) Binary.Operator.GreaterThan]; break;
426                                 case "<=":
427                                         oper = Binary.oper_names [(int) Binary.Operator.LessThanOrEqual]; break;
428                                 case ">=":
429                                         oper = Binary.oper_names [(int) Binary.Operator.GreaterThanOrEqual]; break;
430                                 default:
431                                         warningType = 1584;
432                                         Report.Warning (1020, 1, mc.Location, "Overloadable {0} operator is expected", paramList.Length == 2 ? "binary" : "unary");
433                                         Report.Warning (1584, 1, mc.Location, "XML comment on '{0}' has syntactically incorrect attribute '{1}'", mc.GetSignatureForError (), cref);
434                                         return null;
435                                 }
436                         }
437                         // here we still does not consider return type (to
438                         // detect CS1581 or CS1002+CS1584).
439                         msig = new MethodSignature (oper, null, paramList);
440                         mis = type.FindMembers (
441                                 MemberTypes.Method,
442                                 BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static,
443                                 MethodSignature.method_signature_filter,
444                                 msig);
445                         if (mis.Length == 0)
446                                 return null; // CS1574
447                         MemberInfo mi = mis [0];
448                         Type expected = mi is MethodInfo ?
449                                 ((MethodInfo) mi).ReturnType :
450                                 mi is PropertyInfo ?
451                                 ((PropertyInfo) mi).PropertyType :
452                                 null;
453                         if (returnTypeName != null) {
454                                 Type returnType = FindDocumentedType (mc, returnTypeName, ds, true);
455                                 if (returnType == null || returnType != expected) {
456                                         warningType = 1581;
457                                         Report.Warning (1581, 1, mc.Location, "Invalid return type in XML comment cref attribute '{0}'", cref);
458                                         return null;
459                                 }
460                         }
461                         return mis [0];
462                 }
463
464                 private static Type [] emptyParamList = new Type [0];
465
466                 //
467                 // Processes "see" or "seealso" elements.
468                 // Checks cref attribute.
469                 //
470                 private static void HandleXrefCommon (MemberCore mc,
471                         DeclSpace ds, XmlElement xref)
472                 {
473                         string cref = xref.GetAttribute ("cref").Trim (wsChars);
474                         // when, XmlReader, "if (cref == null)"
475                         if (!xref.HasAttribute ("cref"))
476                                 return;
477                         if (cref.Length == 0)
478                                 Report.Warning (1001, 1, mc.Location, "Identifier expected");
479                                 // ... and continue until CS1584.
480
481                         string signature; // "x:" are stripped
482                         string name; // method invokation "(...)" are removed
483                         string identifiers; // array indexer "[]" are removed
484                         string parameters; // method parameter list
485
486                         // strip 'T:' 'M:' 'F:' 'P:' 'E:' etc.
487                         // Here, MS ignores its member kind. No idea why.
488                         if (cref.Length > 2 && cref [1] == ':')
489                                 signature = cref.Substring (2).Trim (wsChars);
490                         else
491                                 signature = cref;
492
493                         int parensPos = signature.IndexOf ('(');
494                         if (parensPos > 0 && signature [signature.Length - 1] == ')') {
495                                 name = signature.Substring (0, parensPos).Trim (wsChars);
496                                 parameters = signature.Substring (parensPos + 1, signature.Length - parensPos - 2);
497                         }
498                         else {
499                                 name = signature;
500                                 parameters = String.Empty;
501                         }
502
503                         string identifier = name;
504
505                         if (name.Length > 0 && name [name.Length - 1] == ']') {
506                                 string tmp = name.Substring (0, name.Length - 1).Trim (wsChars);
507                                 if (tmp [tmp.Length - 1] == '[')
508                                         identifier = tmp.Substring (0, tmp.Length - 1).Trim (wsChars);
509                         }
510
511                         // Check if identifier is valid.
512                         // This check is not necessary to mark as error, but
513                         // csc specially reports CS1584 for wrong identifiers.
514                         foreach (string nameElem in identifier.Split ('.')) {
515                                 if (!Tokenizer.IsValidIdentifier (nameElem)
516                                         && nameElem.IndexOf ("operator") < 0) {
517                                         if (nameElem.EndsWith ("[]") &&
518                                                 Tokenizer.IsValidIdentifier (
519                                                 nameElem.Substring (
520                                                 0, nameElem.Length - 2)))
521                                                 continue;
522
523                                         Report.Warning (1584, 1, mc.Location, "XML comment on '{0}' has syntactically incorrect attribute '{1}'", mc.GetSignatureForError (), cref);
524                                         xref.SetAttribute ("cref", "!:" + signature);
525                                         return;
526                                 }
527                         }
528
529                         // check if parameters are valid
530                         Type [] parameterTypes = emptyParamList;
531                         if (parameters.Length > 0) {
532                                 string [] paramList = parameters.Split (',');
533                                 ArrayList plist = new ArrayList ();
534                                 for (int i = 0; i < paramList.Length; i++) {
535                                         string paramTypeName = paramList [i].Trim (wsChars);
536                                         Type paramType = FindDocumentedType (mc, paramTypeName, ds, true);
537                                         if (paramType == null) {
538                                                 Report.Warning (1580, 1, mc.Location, "Invalid type for parameter '{0}' in XML comment cref attribute '{1}'", i + 1, cref);
539                                                 return;
540                                         }
541                                         plist.Add (paramType);
542                                 }
543                                 parameterTypes = plist.ToArray (typeof (Type)) as Type [];
544                                 StringBuilder sb = new StringBuilder ();
545                                 sb.Append ('(');
546                                 for (int i = 0; i < parameterTypes.Length; i++) {
547                                         Type t = parameterTypes [i];
548                                         if (sb.Length > 1)
549                                                 sb.Append (',');
550                                         sb.Append (t.FullName.Replace ('+', '.'));
551                                 }
552                                 sb.Append (')');
553                                 parameters = sb.ToString ();
554                         }
555
556                         Type type = FindDocumentedType (mc, name, ds, true);
557                         if (type != null) {
558                                 xref.SetAttribute ("cref", "T:" + type.FullName.Replace ("+", "."));
559                                 return; // a type
560                         }
561
562                         // don't use identifier here. System[] is not alloed.
563                         if (Namespace.IsNamespace (name)) {
564                                 xref.SetAttribute ("cref", "N:" + name);
565                                 return; // a namespace
566                         }
567
568                         int period = name.LastIndexOf ('.');
569                         if (period > 0) {
570                                 string typeName = name.Substring (0, period);
571                                 string memberName = name.Substring (period + 1);
572                                 type = FindDocumentedType (mc, typeName, ds, false);
573                                 int warnResult;
574                                 if (type != null) {
575                                         MemberInfo mi = FindDocumentedMember (mc, type, memberName, parameterTypes, ds, out warnResult, cref);
576                                         if (warnResult > 0)
577                                                 return;
578                                         if (mi != null) {
579                                                 xref.SetAttribute ("cref", GetMemberDocHead (mi.MemberType) + type.FullName.Replace ("+", ".") + "." + memberName + parameters);
580                                                 return; // a member of a type
581                                         }
582                                 }
583                         }
584                         else {
585                                 int warnResult;
586                                 MemberInfo mi = FindDocumentedMember (mc, ds.TypeBuilder, name, parameterTypes, ds, out warnResult, cref);
587                                 if (warnResult > 0)
588                                         return;
589                                 if (mi != null) {
590                                         xref.SetAttribute ("cref", GetMemberDocHead (mi.MemberType) + ds.TypeBuilder.FullName.Replace ("+", ".") + "." + name);
591                                         return; // local member name
592                                 }
593                         }
594
595                         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 ());
596
597                         xref.SetAttribute ("cref", "!:" + name);
598                 }
599
600                 //
601                 // Get a prefix from member type for XML documentation (used
602                 // to formalize cref target name).
603                 //
604                 static string GetMemberDocHead (MemberTypes type)
605                 {
606                         switch (type) {
607                         case MemberTypes.Constructor:
608                         case MemberTypes.Method:
609                                 return "M:";
610                         case MemberTypes.Event:
611                                 return "E:";
612                         case MemberTypes.Field:
613                                 return "F:";
614                         case MemberTypes.NestedType:
615                         case MemberTypes.TypeInfo:
616                                 return "T:";
617                         case MemberTypes.Property:
618                                 return "P:";
619                         }
620                         return "!:";
621                 }
622
623                 // MethodCore
624
625                 //
626                 // Returns a string that represents the signature for this 
627                 // member which should be used in XML documentation.
628                 //
629                 public static string GetMethodDocCommentName (MethodCore mc, DeclSpace ds)
630                 {
631                         Parameter [] plist = mc.Parameters.FixedParameters;
632                         Parameter parr = mc.Parameters.ArrayParameter;
633                         string paramSpec = String.Empty;
634                         if (plist != null) {
635                                 StringBuilder psb = new StringBuilder ();
636                                 foreach (Parameter p in plist) {
637                                         psb.Append (psb.Length != 0 ? "," : "(");
638                                         psb.Append (p.ParameterType.FullName.Replace ("+", "."));
639                                 }
640                                 paramSpec = psb.ToString ();
641                         }
642                         if (parr != null)
643                                 paramSpec += String.Concat (
644                                         paramSpec == String.Empty ? "(" : ",",
645                                         parr.ParameterType.FullName.Replace ("+", "."));
646
647                         if (paramSpec.Length > 0)
648                                 paramSpec += ")";
649
650                         string name = mc is Constructor ? "#ctor" : mc.Name;
651                         return String.Concat (mc.DocCommentHeader, ds.Name, ".", name, paramSpec);
652                 }
653
654                 //
655                 // Raised (and passed an XmlElement that contains the comment)
656                 // when GenerateDocComment is writing documentation expectedly.
657                 //
658                 // FIXME: with a few effort, it could be done with XmlReader,
659                 // that means removal of DOM use.
660                 //
661                 internal static void OnMethodGenerateDocComment (
662                         MethodCore mc, DeclSpace ds, XmlElement el)
663                 {
664                         Hashtable paramTags = new Hashtable ();
665                         foreach (XmlElement pelem in el.SelectNodes ("param")) {
666                                 int i;
667                                 string xname = pelem.GetAttribute ("name");
668                                 if (xname == "")
669                                         continue; // really? but MS looks doing so
670                                 if (xname != "" && mc.Parameters.GetParameterByName (xname, out i) == null)
671                                         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);
672                                 else if (paramTags [xname] != null)
673                                         Report.Warning (1571, 2, mc.Location, "XML comment on '{0}' has a duplicate param tag for '{1}'", mc.Name, xname);
674                                 paramTags [xname] = xname;
675                         }
676                         Parameter [] plist = mc.Parameters.FixedParameters;
677                         Parameter parr = mc.Parameters.ArrayParameter;
678                         if (plist != null) {
679                                 foreach (Parameter p in plist) {
680                                         if (paramTags.Count > 0 && paramTags [p.Name] == null)
681                                                 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);
682                                 }
683                         }
684                 }
685
686                 // Enum
687                 public static void GenerateEnumDocComment (Enum e, DeclSpace ds)
688                 {
689                         GenerateDocComment (e, ds);
690                         foreach (string name in e.ordered_enums) {
691                                 MemberCore mc = e.GetDefinition (name);
692                                 GenerateDocComment (mc, e);
693                         }
694                 }
695         }
696
697         //
698         // Implements XML documentation generation.
699         //
700         public class Documentation
701         {
702                 public Documentation (string xml_output_filename)
703                 {
704                         docfilename = xml_output_filename;
705                         XmlDocumentation = new XmlDocument ();
706                         XmlDocumentation.PreserveWhitespace = false;
707                 }
708
709                 private string docfilename;
710
711                 //
712                 // Used to create element which helps well-formedness checking.
713                 //
714                 public XmlDocument XmlDocumentation;
715
716                 //
717                 // The output for XML documentation.
718                 //
719                 public XmlWriter XmlCommentOutput;
720
721                 //
722                 // Stores XmlDocuments that are included in XML documentation.
723                 // Keys are included filenames, values are XmlDocuments.
724                 //
725                 public Hashtable StoredDocuments = new Hashtable ();
726
727                 //
728                 // Stores comments on partial types (should handle uniquely).
729                 // Keys are PartialContainers, values are comment strings
730                 // (didn't use StringBuilder; usually we have just 2 or more).
731                 //
732                 public IDictionary PartialComments = new ListDictionary ();
733
734                 //
735                 // Outputs XML documentation comment from tokenized comments.
736                 //
737                 public bool OutputDocComment (string asmfilename)
738                 {
739                         XmlTextWriter w = null;
740                         try {
741                                 w = new XmlTextWriter (docfilename, null);
742                                 w.Indentation = 4;
743                                 w.Formatting = Formatting.Indented;
744                                 w.WriteStartDocument ();
745                                 w.WriteStartElement ("doc");
746                                 w.WriteStartElement ("assembly");
747                                 w.WriteStartElement ("name");
748                                 w.WriteString (Path.ChangeExtension (asmfilename, null));
749                                 w.WriteEndElement (); // name
750                                 w.WriteEndElement (); // assembly
751                                 w.WriteStartElement ("members");
752                                 XmlCommentOutput = w;
753                                 GenerateDocComment ();
754                                 w.WriteFullEndElement (); // members
755                                 w.WriteEndElement ();
756                                 w.WriteWhitespace (Environment.NewLine);
757                                 w.WriteEndDocument ();
758                                 return true;
759                         } catch (Exception ex) {
760                                 Report.Error (1569, "Error generating XML documentation file '{0}' ('{1}')", docfilename, ex.Message);
761                                 return false;
762                         } finally {
763                                 if (w != null)
764                                         w.Close ();
765                         }
766                 }
767
768                 //
769                 // Fixes full type name of each documented types/members up.
770                 //
771                 public void GenerateDocComment ()
772                 {
773                         TypeContainer root = RootContext.Tree.Types;
774                         if (root.Interfaces != null)
775                                 foreach (Interface i in root.Interfaces) 
776                                         DocUtil.GenerateTypeDocComment (i, null);
777
778                         if (root.Types != null)
779                                 foreach (TypeContainer tc in root.Types)
780                                         DocUtil.GenerateTypeDocComment (tc, null);
781
782                         if (root.Parts != null) {
783                                 IDictionary comments = PartialComments;
784                                 foreach (ClassPart cp in root.Parts) {
785                                         if (cp.DocComment == null)
786                                                 continue;
787                                         comments [cp] = cp;
788                                 }
789                         }
790
791                         if (root.Delegates != null)
792                                 foreach (Delegate d in root.Delegates) 
793                                         DocUtil.GenerateDocComment (d, null);
794
795                         if (root.Enums != null)
796                                 foreach (Enum e in root.Enums)
797                                         DocUtil.GenerateEnumDocComment (e, null);
798
799                         IDictionary table = new ListDictionary ();
800                         foreach (ClassPart cp in PartialComments.Keys) {
801                                 table [cp.PartialContainer] += cp.DocComment;
802                         }
803                         foreach (PartialContainer pc in table.Keys) {
804                                 pc.DocComment = table [pc] as string;
805                                 DocUtil.GenerateDocComment (pc, null);
806                         }
807                 }
808         }
809 }