53d729eacd439bbaa3e1ea5578134fd2f4e26c98
[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 e.Type;
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                         // no need to detect warning 419 here
334                         return FindDocumentedMember (mc, parent,
335                                 identifier.Substring (index + 1),
336                                 Type.EmptyTypes,
337                                 ds, out warn, cref, false, null) as Type;
338                 }
339
340                 //
341                 // Returns a MemberInfo that is referenced in XML documentation
342                 // (by "see" or "seealso" elements).
343                 //
344                 private static MemberInfo FindDocumentedMember (MemberCore mc,
345                         Type type, string memberName, Type [] paramList, 
346                         DeclSpace ds, out int warningType, string cref,
347                         bool warn419, string nameForError)
348                 {
349                         warningType = 0;
350                         MethodSignature msig = new MethodSignature (memberName, null, paramList);
351                         MemberInfo [] mis = type.FindMembers (
352                                 MemberTypes.All,
353                                 BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance,
354                                 MethodSignature.method_signature_filter,
355                                 msig);
356                         if (warn419 && mis.Length > 0) {
357                                 if (IsAmbiguous (mis))
358                                         Report419 (mc, nameForError, mis);
359                                 return mis [0];
360                         }
361
362                         if (paramList.Length == 0) {
363                                 // search for fields/events etc.
364                                 mis = TypeManager.MemberLookup (null, null,
365                                         type, MemberTypes.All,
366                                         BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance,
367                                         memberName, null);
368                                 if (mis == null || mis.Length == 0)
369                                         return null;
370                                 if (warn419 && IsAmbiguous (mis))
371                                         Report419 (mc, nameForError, mis);
372                                 return mis [0];
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 cref attribute `{1}'",
448                                                 mc.GetSignatureForError (), cref);
449                                         return null;
450                                 }
451                         }
452                         // here we still don't consider return type (to
453                         // detect CS1581 or CS1002+CS1584).
454                         msig = new MethodSignature (oper, null, paramList);
455                         mis = type.FindMembers (
456                                 MemberTypes.Method,
457                                 BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static,
458                                 MethodSignature.method_signature_filter,
459                                 msig);
460                         if (mis.Length == 0)
461                                 return null; // CS1574
462                         MemberInfo mi = mis [0];
463                         Type expected = mi is MethodInfo ?
464                                 ((MethodInfo) mi).ReturnType :
465                                 mi is PropertyInfo ?
466                                 ((PropertyInfo) mi).PropertyType :
467                                 null;
468                         if (returnTypeName != null) {
469                                 Type returnType = FindDocumentedType (mc, returnTypeName, ds, cref);
470                                 if (returnType == null || returnType != expected) {
471                                         warningType = 1581;
472                                         Report.Warning (1581, 1, mc.Location, "Invalid return type in XML comment cref attribute `{0}'", cref);
473                                         return null;
474                                 }
475                         }
476                         return mis [0];
477                 }
478
479                 private static bool IsAmbiguous (MemberInfo [] members)
480                 {
481                         if (members.Length < 2)
482                                 return false;
483                         if (members.Length > 2)
484                                 return true;
485                         if (members [0] is EventInfo && members [1] is FieldInfo)
486                                 return false;
487                         if (members [1] is EventInfo && members [0] is FieldInfo)
488                                 return false;
489                         return true;
490                 }
491
492                 //
493                 // Processes "see" or "seealso" elements.
494                 // Checks cref attribute.
495                 //
496                 private static void HandleXrefCommon (MemberCore mc,
497                         DeclSpace ds, XmlElement xref)
498                 {
499                         string cref = xref.GetAttribute ("cref").Trim (wsChars);
500                         // when, XmlReader, "if (cref == null)"
501                         if (!xref.HasAttribute ("cref"))
502                                 return;
503                         if (cref.Length == 0)
504                                 Report.Warning (1001, 1, mc.Location, "Identifier expected");
505                                 // ... and continue until CS1584.
506
507                         string signature; // "x:" are stripped
508                         string name; // method invokation "(...)" are removed
509                         string parameters; // method parameter list
510
511                         // strip 'T:' 'M:' 'F:' 'P:' 'E:' etc.
512                         // Here, MS ignores its member kind. No idea why.
513                         if (cref.Length > 2 && cref [1] == ':')
514                                 signature = cref.Substring (2).Trim (wsChars);
515                         else
516                                 signature = cref;
517
518                         int parensPos = signature.IndexOf ('(');
519                         int bracePos = parensPos >= 0 ? -1 :
520                                 signature.IndexOf ('[');
521                         if (parensPos > 0 && signature [signature.Length - 1] == ')') {
522                                 name = signature.Substring (0, parensPos).Trim (wsChars);
523                                 parameters = signature.Substring (parensPos + 1, signature.Length - parensPos - 2).Trim (wsChars);
524                         }
525                         else if (bracePos > 0 && signature [signature.Length - 1] == ']') {
526                                 name = signature.Substring (0, bracePos).Trim (wsChars);
527                                 parameters = signature.Substring (bracePos + 1, signature.Length - bracePos - 2).Trim (wsChars);
528                         }
529                         else {
530                                 name = signature;
531                                 parameters = String.Empty;
532                         }
533                         Normalize (mc, ref name);
534
535                         string identifier = GetBodyIdentifierFromName (name);
536
537                         // Check if identifier is valid.
538                         // This check is not necessary to mark as error, but
539                         // csc specially reports CS1584 for wrong identifiers.
540                         string [] nameElems = identifier.Split ('.');
541                         for (int i = 0; i < nameElems.Length; i++) {
542                                 string nameElem = GetBodyIdentifierFromName (nameElems [i]);
543                                 if (i > 0)
544                                         Normalize (mc, ref nameElem);
545                                 if (!Tokenizer.IsValidIdentifier (nameElem)
546                                         && nameElem.IndexOf ("operator") < 0) {
547                                         Report.Warning (1584, 1, mc.Location, "XML comment on `{0}' has syntactically incorrect cref attribute `{1}'",
548                                                 mc.GetSignatureForError (), cref);
549                                         xref.SetAttribute ("cref", "!:" + signature);
550                                         return;
551                                 }
552                         }
553
554                         // check if parameters are valid
555                         Type [] parameterTypes = Type.EmptyTypes;
556                         if (parameters.Length > 0) {
557                                 string [] paramList = parameters.Split (',');
558                                 ArrayList plist = new ArrayList ();
559                                 for (int i = 0; i < paramList.Length; i++) {
560                                         string paramTypeName = paramList [i].Trim (wsChars);
561                                         Normalize (mc, ref paramTypeName);
562                                         Type paramType = FindDocumentedType (mc, paramTypeName, ds, cref);
563                                         if (paramType == null) {
564                                                 Report.Warning (1580, 1, mc.Location, "Invalid type for parameter `{0}' in XML comment cref attribute `{1}'",
565                                                         (i + 1).ToString (), cref);
566                                                 return;
567                                         }
568                                         plist.Add (paramType);
569                                 }
570                                 parameterTypes = plist.ToArray (typeof (Type)) as Type [];
571                         }
572
573                         Type type = FindDocumentedType (mc, name, ds, cref);
574                         if (type != null
575                                 // delegate must not be referenced with args
576                                 && (!type.IsSubclassOf (typeof (System.Delegate))
577                                 || parameterTypes.Length == 0)) {
578                                 string result = type.FullName.Replace ("+", ".")
579                                         + (bracePos < 0 ? String.Empty : signature.Substring (bracePos));
580                                 xref.SetAttribute ("cref", "T:" + result);
581                                 return; // a type
582                         }
583
584                         // don't use identifier here. System[] is not alloed.
585                         if (RootNamespace.Global.IsNamespace (name)) {
586                                 xref.SetAttribute ("cref", "N:" + name);
587                                 return; // a namespace
588                         }
589
590                         int period = name.LastIndexOf ('.');
591                         if (period > 0) {
592                                 string typeName = name.Substring (0, period);
593                                 string memberName = name.Substring (period + 1);
594                                 Normalize (mc, ref memberName);
595                                 type = FindDocumentedType (mc, typeName, ds, cref);
596                                 int warnResult;
597                                 if (type != null) {
598                                         MemberInfo mi = FindDocumentedMember (mc, type, memberName, parameterTypes, ds, out warnResult, cref, true, name);
599                                         if (warnResult > 0)
600                                                 return;
601                                         if (mi != null) {
602                                                 xref.SetAttribute ("cref", GetMemberDocHead (mi.MemberType) + type.FullName.Replace ("+", ".") + "." + memberName + GetParametersFormatted (mi));
603                                                 return; // a member of a type
604                                         }
605                                 }
606                         }
607                         else {
608                                 int warnResult;
609                                 MemberInfo mi = FindDocumentedMember (mc, ds.TypeBuilder, name, parameterTypes, ds, out warnResult, cref, true, name);
610                                 if (warnResult > 0)
611                                         return;
612                                 if (mi != null) {
613                                         xref.SetAttribute ("cref", GetMemberDocHead (mi.MemberType) + ds.TypeBuilder.FullName.Replace ("+", ".") + "." + name + GetParametersFormatted (mi));
614                                         return; // local member name
615                                 }
616                         }
617
618                         Report.Warning (1574, 1, mc.Location, "XML comment on `{0}' has cref attribute `{1}' that could not be resolved",
619                                 mc.GetSignatureForError (), cref);
620
621                         xref.SetAttribute ("cref", "!:" + name);
622                 }
623
624                 static string GetParametersFormatted (MemberInfo mi)
625                 {
626                         MethodBase mb = mi as MethodBase;
627                         bool isSetter = false;
628                         PropertyInfo pi = mi as PropertyInfo;
629                         if (pi != null) {
630                                 mb = pi.GetGetMethod ();
631                                 if (mb == null) {
632                                         isSetter = true;
633                                         mb = pi.GetSetMethod ();
634                                 }
635                         }
636                         if (mb == null)
637                                 return String.Empty;
638
639                         ParameterData parameters = TypeManager.GetParameterData (mb);
640                         if (parameters == null || parameters.Count == 0)
641                                 return String.Empty;
642
643                         StringBuilder sb = new StringBuilder ();
644                         sb.Append ('(');
645                         for (int i = 0; i < parameters.Count; i++) {
646                                 if (isSetter && i + 1 == parameters.Count)
647                                         break; // skip "value".
648                                 if (i > 0)
649                                         sb.Append (',');
650                                 Type t = parameters.ParameterType (i);
651                                 sb.Append (t.FullName.Replace ('+', '.').Replace ('&', '@'));
652                         }
653                         sb.Append (')');
654                         return sb.ToString ();
655                 }
656
657                 static string GetBodyIdentifierFromName (string name)
658                 {
659                         string identifier = name;
660
661                         if (name.Length > 0 && name [name.Length - 1] == ']') {
662                                 string tmp = name.Substring (0, name.Length - 1).Trim (wsChars);
663                                 int last = tmp.LastIndexOf ('[');
664                                 if (last > 0)
665                                         identifier = tmp.Substring (0, last).Trim (wsChars);
666                         }
667
668                         return identifier;
669                 }
670
671                 static void Report419 (MemberCore mc, string memberName, MemberInfo [] mis)
672                 {
673                         Report.Warning (419, 3, mc.Location, 
674                                 "Ambiguous reference in cref attribute `{0}'. Assuming `{1}' but other overloads including `{2}' have also matched",
675                                 memberName,
676                                 TypeManager.GetFullNameSignature (mis [0]),
677                                 TypeManager.GetFullNameSignature (mis [1]));
678                 }
679
680                 //
681                 // Get a prefix from member type for XML documentation (used
682                 // to formalize cref target name).
683                 //
684                 static string GetMemberDocHead (MemberTypes type)
685                 {
686                         switch (type) {
687                         case MemberTypes.Constructor:
688                         case MemberTypes.Method:
689                                 return "M:";
690                         case MemberTypes.Event:
691                                 return "E:";
692                         case MemberTypes.Field:
693                                 return "F:";
694                         case MemberTypes.NestedType:
695                         case MemberTypes.TypeInfo:
696                                 return "T:";
697                         case MemberTypes.Property:
698                                 return "P:";
699                         }
700                         return "!:";
701                 }
702
703                 // MethodCore
704
705                 //
706                 // Returns a string that represents the signature for this 
707                 // member which should be used in XML documentation.
708                 //
709                 public static string GetMethodDocCommentName (MethodCore mc, DeclSpace ds)
710                 {
711                         Parameter [] plist = mc.Parameters.FixedParameters;
712                         Parameter parr = mc.Parameters.ArrayParameter;
713                         string paramSpec = String.Empty;
714                         if (plist != null) {
715                                 StringBuilder psb = new StringBuilder ();
716                                 foreach (Parameter p in plist) {
717                                         psb.Append (psb.Length != 0 ? "," : "(");
718                                         psb.Append (p.ExternalType ().FullName.Replace ("+", ".").Replace ('&', '@'));
719                                 }
720                                 paramSpec = psb.ToString ();
721                         }
722                         if (parr != null)
723                                 paramSpec += String.Concat (
724                                         paramSpec == String.Empty ? "(" : ",",
725                                         parr.ParameterType.FullName.Replace ("+", "."));
726
727                         if (paramSpec.Length > 0)
728                                 paramSpec += ")";
729
730                         string name = mc is Constructor ? "#ctor" : mc.Name;
731                         string suffix = String.Empty;
732                         Operator op = mc as Operator;
733                         if (op != null) {
734                                 switch (op.OperatorType) {
735                                 case Operator.OpType.Implicit:
736                                 case Operator.OpType.Explicit:
737                                         suffix = "~" + op.OperatorMethodBuilder.ReturnType.FullName.Replace ('+', '.');
738                                         break;
739                                 }
740                         }
741                         return String.Concat (mc.DocCommentHeader, ds.Name, ".", name, paramSpec, suffix);
742                 }
743
744                 //
745                 // Raised (and passed an XmlElement that contains the comment)
746                 // when GenerateDocComment is writing documentation expectedly.
747                 //
748                 // FIXME: with a few effort, it could be done with XmlReader,
749                 // that means removal of DOM use.
750                 //
751                 internal static void OnMethodGenerateDocComment (
752                         MethodCore mc, DeclSpace ds, XmlElement el)
753                 {
754                         Hashtable paramTags = new Hashtable ();
755                         foreach (XmlElement pelem in el.SelectNodes ("param")) {
756                                 int i;
757                                 string xname = pelem.GetAttribute ("name");
758                                 if (xname == "")
759                                         continue; // really? but MS looks doing so
760                                 if (xname != "" && mc.Parameters.GetParameterByName (xname, out i) == null)
761                                         Report.Warning (1572, 2, mc.Location, "XML comment on `{0}' has a param tag for `{1}', but there is no parameter by that name",
762                                                 mc.GetSignatureForError (), xname);
763                                 else if (paramTags [xname] != null)
764                                         Report.Warning (1571, 2, mc.Location, "XML comment on `{0}' has a duplicate param tag for `{1}'",
765                                                 mc.GetSignatureForError (), xname);
766                                 paramTags [xname] = xname;
767                         }
768                         Parameter [] plist = mc.Parameters.FixedParameters;
769                         if (plist != null) {
770                                 foreach (Parameter p in plist) {
771                                         if (paramTags.Count > 0 && paramTags [p.Name] == null)
772                                                 Report.Warning (1573, 4, mc.Location, "Parameter `{0}' has no matching param tag in the XML comment for `{1}'",
773                                                         p.Name, mc.GetSignatureForError ());
774                                 }
775                         }
776                 }
777
778                 private static void Normalize (MemberCore mc, ref string name)
779                 {
780                         if (name.Length > 0 && name [0] == '@')
781                                 name = name.Substring (1);
782                         else if (name == "this")
783                                 name = "Item";
784                         else if (Tokenizer.IsKeyword (name) && !IsTypeName (name))
785                                 Report.Warning (1041, 1, mc.Location, "Identifier expected. `{0}' is a keyword", name);
786                 }
787
788                 private static bool IsTypeName (string name)
789                 {
790                         switch (name) {
791                         case "bool":
792                         case "byte":
793                         case "char":
794                         case "decimal":
795                         case "double":
796                         case "float":
797                         case "int":
798                         case "long":
799                         case "object":
800                         case "sbyte":
801                         case "short":
802                         case "string":
803                         case "uint":
804                         case "ulong":
805                         case "ushort":
806                         case "void":
807                                 return true;
808                         }
809                         return false;
810                 }
811         }
812
813         //
814         // Implements XML documentation generation.
815         //
816         public class Documentation
817         {
818                 public Documentation (string xml_output_filename)
819                 {
820                         docfilename = xml_output_filename;
821                         XmlDocumentation = new XmlDocument ();
822                         XmlDocumentation.PreserveWhitespace = false;
823                 }
824
825                 private string docfilename;
826
827                 //
828                 // Used to create element which helps well-formedness checking.
829                 //
830                 public XmlDocument XmlDocumentation;
831
832                 //
833                 // The output for XML documentation.
834                 //
835                 public XmlWriter XmlCommentOutput;
836
837                 //
838                 // Stores XmlDocuments that are included in XML documentation.
839                 // Keys are included filenames, values are XmlDocuments.
840                 //
841                 public Hashtable StoredDocuments = new Hashtable ();
842
843                 //
844                 // Stores comments on partial types (should handle uniquely).
845                 // Keys are PartialContainers, values are comment strings
846                 // (didn't use StringBuilder; usually we have just 2 or more).
847                 //
848                 public IDictionary PartialComments = new ListDictionary ();
849
850                 //
851                 // Outputs XML documentation comment from tokenized comments.
852                 //
853                 public bool OutputDocComment (string asmfilename)
854                 {
855                         XmlTextWriter w = null;
856                         try {
857                                 w = new XmlTextWriter (docfilename, null);
858                                 w.Indentation = 4;
859                                 w.Formatting = Formatting.Indented;
860                                 w.WriteStartDocument ();
861                                 w.WriteStartElement ("doc");
862                                 w.WriteStartElement ("assembly");
863                                 w.WriteStartElement ("name");
864                                 w.WriteString (Path.ChangeExtension (asmfilename, null));
865                                 w.WriteEndElement (); // name
866                                 w.WriteEndElement (); // assembly
867                                 w.WriteStartElement ("members");
868                                 XmlCommentOutput = w;
869                                 GenerateDocComment ();
870                                 w.WriteFullEndElement (); // members
871                                 w.WriteEndElement ();
872                                 w.WriteWhitespace (Environment.NewLine);
873                                 w.WriteEndDocument ();
874                                 return true;
875                         } catch (Exception ex) {
876                                 Report.Error (1569, "Error generating XML documentation file `{0}' (`{1}')", docfilename, ex.Message);
877                                 return false;
878                         } finally {
879                                 if (w != null)
880                                         w.Close ();
881                         }
882                 }
883
884                 //
885                 // Fixes full type name of each documented types/members up.
886                 //
887                 public void GenerateDocComment ()
888                 {
889                         TypeContainer root = RootContext.Tree.Types;
890                         if (root.Interfaces != null)
891                                 foreach (Interface i in root.Interfaces) 
892                                         DocUtil.GenerateTypeDocComment (i, null);
893
894                         if (root.Types != null)
895                                 foreach (TypeContainer tc in root.Types)
896                                         DocUtil.GenerateTypeDocComment (tc, null);
897
898                         if (root.Parts != null) {
899                                 IDictionary comments = PartialComments;
900                                 foreach (ClassPart cp in root.Parts) {
901                                         if (cp.DocComment == null)
902                                                 continue;
903                                         comments [cp] = cp;
904                                 }
905                         }
906
907                         if (root.Delegates != null)
908                                 foreach (Delegate d in root.Delegates) 
909                                         DocUtil.GenerateDocComment (d, null);
910
911                         if (root.Enums != null)
912                                 foreach (Enum e in root.Enums)
913                                         e.GenerateDocComment (null);
914
915                         IDictionary table = new ListDictionary ();
916                         foreach (ClassPart cp in PartialComments.Keys) {
917                                 // FIXME: IDictionary does not guarantee that the keys will be
918                                 //        accessed in the order they were added.
919                                 table [cp.PartialContainer] += cp.DocComment;
920                         }
921                         foreach (PartialContainer pc in table.Keys) {
922                                 pc.DocComment = table [pc] as string;
923                                 DocUtil.GenerateDocComment (pc, null);
924                         }
925                 }
926         }
927 }
928
929 #endif