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