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