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