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