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