2008-06-26 Marek Safar <marek.safar@gmail.com>
[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 // Dual licensed under the terms of the MIT X11 or GNU GPL
8 //
9 // Copyright 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.Delegates != null)
66                                 foreach (Delegate de in t.Delegates)
67                                         de.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 (FieldBase 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 line_head =
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 = line_head + String.Join (
129                                         line_head, split, 0, j);
130                                 return el;
131                         } catch (Exception 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 (el);
153
154                                         // FIXME: it could be done with XmlReader
155                                         XmlNodeList nl = n.SelectNodes (".//include");
156                                         if (nl.Count > 0) {
157                                                 // It could result in current node removal, so prepare another list to iterate.
158                                                 ArrayList al = new ArrayList (nl.Count);
159                                                 foreach (XmlNode inc in nl)
160                                                         al.Add (inc);
161                                                 foreach (XmlElement inc in al)
162                                                         if (!HandleInclude (mc, inc))
163                                                                 inc.ParentNode.RemoveChild (inc);
164                                         }
165
166                                         // FIXME: it could be done with XmlReader
167                                         DeclSpace ds_target = mc as DeclSpace;
168                                         if (ds_target == null)
169                                                 ds_target = ds;
170
171                                         foreach (XmlElement see in n.SelectNodes (".//see"))
172                                                 HandleSee (mc, ds_target, see);
173                                         foreach (XmlElement seealso in n.SelectNodes (".//seealso"))
174                                                 HandleSeeAlso (mc, ds_target, seealso);
175                                         foreach (XmlElement see in n.SelectNodes (".//exception"))
176                                                 HandleException (mc, ds_target, see);
177                                 }
178
179                                 n.WriteTo (RootContext.Documentation.XmlCommentOutput);
180                         }
181                         else if (mc.IsExposedFromAssembly ()) {
182                                 Constructor c = mc as Constructor;
183                                 if (c == null || !c.IsDefault ())
184                                         Report.Warning (1591, 4, mc.Location,
185                                                 "Missing XML comment for publicly visible type or member `{0}'", mc.GetSignatureForError ());
186                         }
187                 }
188
189                 //
190                 // Processes "include" element. Check included file and
191                 // embed the document content inside this documentation node.
192                 //
193                 private static bool HandleInclude (MemberCore mc, XmlElement el)
194                 {
195                         bool keep_include_node = false;
196                         string file = el.GetAttribute ("file");
197                         string path = el.GetAttribute ("path");
198                         if (file == "") {
199                                 Report.Warning (1590, 1, mc.Location, "Invalid XML `include' element. Missing `file' attribute");
200                                 el.ParentNode.InsertBefore (el.OwnerDocument.CreateComment (" Include tag is invalid "), el);
201                                 keep_include_node = true;
202                         }
203                         else if (path.Length == 0) {
204                                 Report.Warning (1590, 1, mc.Location, "Invalid XML `include' element. Missing `path' attribute");
205                                 el.ParentNode.InsertBefore (el.OwnerDocument.CreateComment (" Include tag is invalid "), el);
206                                 keep_include_node = true;
207                         }
208                         else {
209                                 XmlDocument doc = RootContext.Documentation.StoredDocuments [file] as XmlDocument;
210                                 if (doc == null) {
211                                         try {
212                                                 doc = new XmlDocument ();
213                                                 doc.Load (file);
214                                                 RootContext.Documentation.StoredDocuments.Add (file, doc);
215                                         } catch (Exception) {
216                                                 el.ParentNode.InsertBefore (el.OwnerDocument.CreateComment (String.Format (" Badly formed XML in at comment file `{0}': cannot be included ", file)), el);
217                                                 Report.Warning (1592, 1, mc.Location, "Badly formed XML in included comments file -- `{0}'", file);
218                                         }
219                                 }
220                                 if (doc != null) {
221                                         try {
222                                                 XmlNodeList nl = doc.SelectNodes (path);
223                                                 if (nl.Count == 0) {
224                                                         el.ParentNode.InsertBefore (el.OwnerDocument.CreateComment (" No matching elements were found for the include tag embedded here. "), el);
225                                         
226                                                         keep_include_node = true;
227                                                 }
228                                                 foreach (XmlNode n in nl)
229                                                         el.ParentNode.InsertBefore (el.OwnerDocument.ImportNode (n, true), el);
230                                         } catch (Exception ex) {
231                                                 el.ParentNode.InsertBefore (el.OwnerDocument.CreateComment (" Failed to insert some or all of included XML "), el);
232                                                 Report.Warning (1589, 1, mc.Location, "Unable to include XML fragment `{0}' of file `{1}' ({2})", path, file, ex.Message);
233                                         }
234                                 }
235                         }
236                         return keep_include_node;
237                 }
238
239                 //
240                 // Handles <see> elements.
241                 //
242                 private static void HandleSee (MemberCore mc,
243                         DeclSpace ds, XmlElement see)
244                 {
245                         HandleXrefCommon (mc, ds, see);
246                 }
247
248                 //
249                 // Handles <seealso> elements.
250                 //
251                 private static void HandleSeeAlso (MemberCore mc,
252                         DeclSpace ds, XmlElement seealso)
253                 {
254                         HandleXrefCommon (mc, ds, seealso);
255                 }
256
257                 //
258                 // Handles <exception> elements.
259                 //
260                 private static void HandleException (MemberCore mc,
261                         DeclSpace ds, XmlElement seealso)
262                 {
263                         HandleXrefCommon (mc, ds, seealso);
264                 }
265
266                 static readonly char [] wsChars =
267                         new char [] {' ', '\t', '\n', '\r'};
268
269                 //
270                 // returns a full runtime type name from a name which might
271                 // be C# specific type name.
272                 //
273                 private static Type FindDocumentedType (MemberCore mc, string name, DeclSpace ds, string cref)
274                 {
275                         bool is_array = false;
276                         string identifier = name;
277                         if (name [name.Length - 1] == ']') {
278                                 string tmp = name.Substring (0, name.Length - 1).Trim (wsChars);
279                                 if (tmp [tmp.Length - 1] == '[') {
280                                         identifier = tmp.Substring (0, tmp.Length - 1).Trim (wsChars);
281                                         is_array = true;
282                                 }
283                         }
284                         Type t = FindDocumentedTypeNonArray (mc, identifier, ds, cref);
285                         if (t != null && is_array)
286                                 t = Array.CreateInstance (t, 0).GetType ();
287                         return t;
288                 }
289
290                 private static Type FindDocumentedTypeNonArray (MemberCore mc, 
291                         string identifier, DeclSpace ds, string cref)
292                 {
293                         switch (identifier) {
294                         case "int":
295                                 return TypeManager.int32_type;
296                         case "uint":
297                                 return TypeManager.uint32_type;
298                         case "short":
299                                 return TypeManager.short_type;;
300                         case "ushort":
301                                 return TypeManager.ushort_type;
302                         case "long":
303                                 return TypeManager.int64_type;
304                         case "ulong":
305                                 return TypeManager.uint64_type;;
306                         case "float":
307                                 return TypeManager.float_type;;
308                         case "double":
309                                 return TypeManager.double_type;
310                         case "char":
311                                 return TypeManager.char_type;;
312                         case "decimal":
313                                 return TypeManager.decimal_type;;
314                         case "byte":
315                                 return TypeManager.byte_type;;
316                         case "sbyte":
317                                 return TypeManager.sbyte_type;;
318                         case "object":
319                                 return TypeManager.object_type;;
320                         case "bool":
321                                 return TypeManager.bool_type;;
322                         case "string":
323                                 return TypeManager.string_type;;
324                         case "void":
325                                 return TypeManager.void_type;;
326                         }
327                         FullNamedExpression e = ds.LookupNamespaceOrType (identifier, mc.Location, false);
328                         if (e != null) {
329                                 if (!(e is TypeExpr))
330                                         return null;
331                                 return e.Type;
332                         }
333                         int index = identifier.LastIndexOf ('.');
334                         if (index < 0)
335                                 return null;
336                         int warn;
337                         Type parent = FindDocumentedType (mc, identifier.Substring (0, index), ds, cref);
338                         if (parent == null)
339                                 return null;
340                         // no need to detect warning 419 here
341                         return FindDocumentedMember (mc, parent,
342                                 identifier.Substring (index + 1),
343                                 null, ds, out warn, cref, false, null).Member as Type;
344                 }
345
346                 private static MemberInfo [] empty_member_infos =
347                         new MemberInfo [0];
348
349                 private static MemberInfo [] FindMethodBase (Type type,
350                         BindingFlags binding_flags, MethodSignature signature)
351                 {
352                         MemberList ml = TypeManager.FindMembers (
353                                 type,
354                                 MemberTypes.Constructor | MemberTypes.Method | MemberTypes.Property | MemberTypes.Custom,
355                                 binding_flags,
356                                 MethodSignature.method_signature_filter,
357                                 signature);
358                         if (ml == null)
359                                 return empty_member_infos;
360
361                         return FilterOverridenMembersOut ((MemberInfo []) ml);
362                 }
363
364                 static bool IsOverride (PropertyInfo deriv_prop, PropertyInfo base_prop)
365                 {
366                         if (!MethodGroupExpr.IsAncestralType (base_prop.DeclaringType, deriv_prop.DeclaringType))
367                                 return false;
368
369                         Type [] deriv_pd = TypeManager.GetArgumentTypes (deriv_prop);
370                         Type [] base_pd = TypeManager.GetArgumentTypes (base_prop);
371                 
372                         if (deriv_pd.Length != base_pd.Length)
373                                 return false;
374
375                         for (int j = 0; j < deriv_pd.Length; ++j) {
376                                 if (deriv_pd [j] != base_pd [j])
377                                         return false;
378                                 Type ct = TypeManager.TypeToCoreType (deriv_pd [j]);
379                                 Type bt = TypeManager.TypeToCoreType (base_pd [j]);
380
381                                 if (ct != bt)
382                                         return false;
383                         }
384
385                         return true;
386                 }
387
388                 private static MemberInfo [] FilterOverridenMembersOut (
389                         MemberInfo [] ml)
390                 {
391                         if (ml == null)
392                                 return empty_member_infos;
393
394                         ArrayList al = new ArrayList (ml.Length);
395                         for (int i = 0; i < ml.Length; i++) {
396                                 MethodBase mx = ml [i] as MethodBase;
397                                 PropertyInfo px = ml [i] as PropertyInfo;
398                                 if (mx != null || px != null) {
399                                         bool overriden = false;
400                                         for (int j = 0; j < ml.Length; j++) {
401                                                 if (j == i)
402                                                         continue;
403                                                 MethodBase my = ml [j] as MethodBase;
404                                                 if (mx != null && my != null &&
405                                                         MethodGroupExpr.IsOverride (my, mx)) {
406                                                         overriden = true;
407                                                         break;
408                                                 }
409                                                 else if (mx != null)
410                                                         continue;
411                                                 PropertyInfo py = ml [j] as PropertyInfo;
412                                                 if (px != null && py != null &&
413                                                         IsOverride (py, px)) {
414                                                         overriden = true;
415                                                         break;
416                                                 }
417                                         }
418                                         if (overriden)
419                                                 continue;
420                                 }
421                                 al.Add (ml [i]);
422                         }
423                         return al.ToArray (typeof (MemberInfo)) as MemberInfo [];
424                 }
425
426                 struct FoundMember
427                 {
428                         public static FoundMember Empty = new FoundMember (true);
429
430                         public bool IsEmpty;
431                         public readonly MemberInfo Member;
432                         public readonly Type Type;
433
434                         public FoundMember (bool regardless_of_this_value_its_empty)
435                         {
436                                 IsEmpty = true;
437                                 Member = null;
438                                 Type = null;
439                         }
440
441                         public FoundMember (Type found_type, MemberInfo member)
442                         {
443                                 IsEmpty = false;
444                                 Type = found_type;
445                                 Member = member;
446                         }
447                 }
448
449                 //
450                 // Returns a MemberInfo that is referenced in XML documentation
451                 // (by "see" or "seealso" elements).
452                 //
453                 private static FoundMember FindDocumentedMember (MemberCore mc,
454                         Type type, string member_name, Type [] param_list, 
455                         DeclSpace ds, out int warning_type, string cref,
456                         bool warn419, string name_for_error)
457                 {
458                         for (; type != null; type = type.DeclaringType) {
459                                 MemberInfo mi = FindDocumentedMemberNoNest (
460                                         mc, type, member_name, param_list, ds,
461                                         out warning_type, cref, warn419,
462                                         name_for_error);
463                                 if (mi != null)
464                                         return new FoundMember (type, mi);
465                         }
466                         warning_type = 0;
467                         return FoundMember.Empty;
468                 }
469
470                 private static MemberInfo FindDocumentedMemberNoNest (
471                         MemberCore mc, Type type, string member_name,
472                         Type [] param_list, DeclSpace ds, out int warning_type, 
473                         string cref, bool warn419, string name_for_error)
474                 {
475                         warning_type = 0;
476                         MemberInfo [] mis;
477
478                         if (param_list == null) {
479                                 // search for fields/events etc.
480                                 mis = TypeManager.MemberLookup (type, null,
481                                         type, MemberTypes.All,
482                                         BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance,
483                                         member_name, null);
484                                 mis = FilterOverridenMembersOut (mis);
485                                 if (mis == null || mis.Length == 0)
486                                         return null;
487                                 if (warn419 && IsAmbiguous (mis))
488                                         Report419 (mc, name_for_error, mis);
489                                 return mis [0];
490                         }
491
492                         MethodSignature msig = new MethodSignature (member_name, null, param_list);
493                         mis = FindMethodBase (type, 
494                                 BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance,
495                                 msig);
496
497                         if (warn419 && mis.Length > 0) {
498                                 if (IsAmbiguous (mis))
499                                         Report419 (mc, name_for_error, mis);
500                                 return mis [0];
501                         }
502
503                         // search for operators (whose parameters exactly
504                         // matches with the list) and possibly report CS1581.
505                         string oper = null;
506                         string return_type_name = null;
507                         if (member_name.StartsWith ("implicit operator ")) {
508                                 Operator.GetMetadataName (Operator.OpType.Implicit);
509                                 return_type_name = member_name.Substring (18).Trim (wsChars);
510                         }
511                         else if (member_name.StartsWith ("explicit operator ")) {
512                                 oper = Operator.GetMetadataName (Operator.OpType.Explicit);
513                                 return_type_name = member_name.Substring (18).Trim (wsChars);
514                         }
515                         else if (member_name.StartsWith ("operator ")) {
516                                 oper = member_name.Substring (9).Trim (wsChars);
517                                 switch (oper) {
518                                 // either unary or binary
519                                 case "+":
520                                         oper = param_list.Length == 2 ?
521                                                 Operator.GetMetadataName (Operator.OpType.Addition) :
522                                                 Operator.GetMetadataName (Operator.OpType.UnaryPlus);
523                                         break;
524                                 case "-":
525                                         oper = param_list.Length == 2 ?
526                                                 Operator.GetMetadataName (Operator.OpType.Subtraction) :
527                                                 Operator.GetMetadataName (Operator.OpType.UnaryNegation);
528                                         break;
529                                 default:
530                                         oper = Operator.GetMetadataName (oper);
531                                         if (oper != null)
532                                                 break;
533
534                                         warning_type = 1584;
535                                         Report.Warning (1020, 1, mc.Location, "Overloadable {0} operator is expected", param_list.Length == 2 ? "binary" : "unary");
536                                         Report.Warning (1584, 1, mc.Location, "XML comment on `{0}' has syntactically incorrect cref attribute `{1}'",
537                                                 mc.GetSignatureForError (), cref);
538                                         return null;
539                                 }
540                         }
541                         // here we still don't consider return type (to
542                         // detect CS1581 or CS1002+CS1584).
543                         msig = new MethodSignature (oper, null, param_list);
544
545                         mis = FindMethodBase (type, 
546                                 BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance,
547                                 msig);
548                         if (mis.Length == 0)
549                                 return null; // CS1574
550                         MemberInfo mi = mis [0];
551                         Type expected = mi is MethodInfo ?
552                                 ((MethodInfo) mi).ReturnType :
553                                 mi is PropertyInfo ?
554                                 ((PropertyInfo) mi).PropertyType :
555                                 null;
556                         if (return_type_name != null) {
557                                 Type returnType = FindDocumentedType (mc, return_type_name, ds, cref);
558                                 if (returnType == null || returnType != expected) {
559                                         warning_type = 1581;
560                                         Report.Warning (1581, 1, mc.Location, "Invalid return type in XML comment cref attribute `{0}'", cref);
561                                         return null;
562                                 }
563                         }
564                         return mis [0];
565                 }
566
567                 private static bool IsAmbiguous (MemberInfo [] members)
568                 {
569                         if (members.Length < 2)
570                                 return false;
571                         if (members.Length > 2)
572                                 return true;
573                         if (members [0] is EventInfo && members [1] is FieldInfo)
574                                 return false;
575                         if (members [1] is EventInfo && members [0] is FieldInfo)
576                                 return false;
577                         return true;
578                 }
579
580                 //
581                 // Processes "see" or "seealso" elements.
582                 // Checks cref attribute.
583                 //
584                 private static void HandleXrefCommon (MemberCore mc,
585                         DeclSpace ds, XmlElement xref)
586                 {
587                         string cref = xref.GetAttribute ("cref").Trim (wsChars);
588                         // when, XmlReader, "if (cref == null)"
589                         if (!xref.HasAttribute ("cref"))
590                                 return;
591                         if (cref.Length == 0)
592                                 Report.Warning (1001, 1, mc.Location, "Identifier expected");
593                                 // ... and continue until CS1584.
594
595                         string signature; // "x:" are stripped
596                         string name; // method invokation "(...)" are removed
597                         string parameters; // method parameter list
598
599                         // When it found '?:' ('T:' 'M:' 'F:' 'P:' 'E:' etc.),
600                         // MS ignores not only its member kind, but also
601                         // the entire syntax correctness. Nor it also does
602                         // type fullname resolution i.e. "T:List(int)" is kept
603                         // as T:List(int), not
604                         // T:System.Collections.Generic.List&lt;System.Int32&gt;
605                         if (cref.Length > 2 && cref [1] == ':')
606                                 return;
607                         else
608                                 signature = cref;
609
610                         // Also note that without "T:" any generic type 
611                         // indication fails.
612
613                         int parens_pos = signature.IndexOf ('(');
614                         int brace_pos = parens_pos >= 0 ? -1 :
615                                 signature.IndexOf ('[');
616                         if (parens_pos > 0 && signature [signature.Length - 1] == ')') {
617                                 name = signature.Substring (0, parens_pos).Trim (wsChars);
618                                 parameters = signature.Substring (parens_pos + 1, signature.Length - parens_pos - 2).Trim (wsChars);
619                         }
620                         else if (brace_pos > 0 && signature [signature.Length - 1] == ']') {
621                                 name = signature.Substring (0, brace_pos).Trim (wsChars);
622                                 parameters = signature.Substring (brace_pos + 1, signature.Length - brace_pos - 2).Trim (wsChars);
623                         }
624                         else {
625                                 name = signature;
626                                 parameters = null;
627                         }
628                         Normalize (mc, ref name);
629
630                         string identifier = GetBodyIdentifierFromName (name);
631
632                         // Check if identifier is valid.
633                         // This check is not necessary to mark as error, but
634                         // csc specially reports CS1584 for wrong identifiers.
635                         string [] name_elems = identifier.Split ('.');
636                         for (int i = 0; i < name_elems.Length; i++) {
637                                 string nameElem = GetBodyIdentifierFromName (name_elems [i]);
638                                 if (i > 0)
639                                         Normalize (mc, ref nameElem);
640                                 if (!Tokenizer.IsValidIdentifier (nameElem)
641                                         && nameElem.IndexOf ("operator") < 0) {
642                                         Report.Warning (1584, 1, mc.Location, "XML comment on `{0}' has syntactically incorrect cref attribute `{1}'",
643                                                 mc.GetSignatureForError (), cref);
644                                         xref.SetAttribute ("cref", "!:" + signature);
645                                         return;
646                                 }
647                         }
648
649                         // check if parameters are valid
650                         Type [] parameter_types;
651                         if (parameters == null)
652                                 parameter_types = null;
653                         else if (parameters.Length == 0)
654                                 parameter_types = Type.EmptyTypes;
655                         else {
656                                 string [] param_list = parameters.Split (',');
657                                 ArrayList plist = new ArrayList ();
658                                 for (int i = 0; i < param_list.Length; i++) {
659                                         string param_type_name = param_list [i].Trim (wsChars);
660                                         Normalize (mc, ref param_type_name);
661                                         Type param_type = FindDocumentedType (mc, param_type_name, ds, cref);
662                                         if (param_type == null) {
663                                                 Report.Warning (1580, 1, mc.Location, "Invalid type for parameter `{0}' in XML comment cref attribute `{1}'",
664                                                         (i + 1).ToString (), cref);
665                                                 return;
666                                         }
667                                         plist.Add (param_type);
668                                 }
669                                 parameter_types = plist.ToArray (typeof (Type)) as Type [];
670                         }
671
672                         Type type = FindDocumentedType (mc, name, ds, cref);
673                         if (type != null
674                                 // delegate must not be referenced with args
675                                 && (!TypeManager.IsDelegateType (type)
676                                 || parameter_types == null)) {
677                                 string result = GetSignatureForDoc (type)
678                                         + (brace_pos < 0 ? String.Empty : signature.Substring (brace_pos));
679                                 xref.SetAttribute ("cref", "T:" + result);
680                                 return; // a type
681                         }
682
683                         int period = name.LastIndexOf ('.');
684                         if (period > 0) {
685                                 string typeName = name.Substring (0, period);
686                                 string member_name = name.Substring (period + 1);
687                                 Normalize (mc, ref member_name);
688                                 type = FindDocumentedType (mc, typeName, ds, cref);
689                                 int warn_result;
690                                 if (type != null) {
691                                         FoundMember fm = FindDocumentedMember (mc, type, member_name, parameter_types, ds, out warn_result, cref, true, name);
692                                         if (warn_result > 0)
693                                                 return;
694                                         if (!fm.IsEmpty) {
695                                                 MemberInfo mi = fm.Member;
696                                                 // we cannot use 'type' directly
697                                                 // to get its name, since mi
698                                                 // could be from DeclaringType
699                                                 // for nested types.
700                                                 xref.SetAttribute ("cref", GetMemberDocHead (mi.MemberType) + GetSignatureForDoc (fm.Type) + "." + member_name + GetParametersFormatted (mi));
701                                                 return; // a member of a type
702                                         }
703                                 }
704                         }
705                         else {
706                                 int warn_result;
707                                 FoundMember fm = FindDocumentedMember (mc, ds.TypeBuilder, name, parameter_types, ds, out warn_result, cref, true, name);
708                                 if (warn_result > 0)
709                                         return;
710                                 if (!fm.IsEmpty) {
711                                         MemberInfo mi = fm.Member;
712                                         // we cannot use 'type' directly
713                                         // to get its name, since mi
714                                         // could be from DeclaringType
715                                         // for nested types.
716                                         xref.SetAttribute ("cref", GetMemberDocHead (mi.MemberType) + GetSignatureForDoc (fm.Type) + "." + name + GetParametersFormatted (mi));
717                                         return; // local member name
718                                 }
719                         }
720
721                         // It still might be part of namespace name.
722                         Namespace ns = ds.NamespaceEntry.NS.GetNamespace (name, false);
723                         if (ns != null) {
724                                 xref.SetAttribute ("cref", "N:" + ns.GetSignatureForError ());
725                                 return; // a namespace
726                         }
727                         if (RootNamespace.Global.IsNamespace (name)) {
728                                 xref.SetAttribute ("cref", "N:" + name);
729                                 return; // a namespace
730                         }
731
732                         Report.Warning (1574, 1, mc.Location, "XML comment on `{0}' has cref attribute `{1}' that could not be resolved",
733                                 mc.GetSignatureForError (), cref);
734
735                         xref.SetAttribute ("cref", "!:" + name);
736                 }
737
738                 static string GetParametersFormatted (MemberInfo mi)
739                 {
740                         MethodBase mb = mi as MethodBase;
741                         bool is_setter = false;
742                         PropertyInfo pi = mi as PropertyInfo;
743                         if (pi != null) {
744                                 mb = pi.GetGetMethod ();
745                                 if (mb == null) {
746                                         is_setter = true;
747                                         mb = pi.GetSetMethod ();
748                                 }
749                         }
750                         if (mb == null)
751                                 return String.Empty;
752
753                         ParameterData parameters = TypeManager.GetParameterData (mb);
754                         if (parameters == null || parameters.Count == 0)
755                                 return String.Empty;
756
757                         StringBuilder sb = new StringBuilder ();
758                         sb.Append ('(');
759                         for (int i = 0; i < parameters.Count; i++) {
760                                 if (is_setter && i + 1 == parameters.Count)
761                                         break; // skip "value".
762                                 if (i > 0)
763                                         sb.Append (',');
764                                 Type t = parameters.ParameterType (i);
765                                 sb.Append (GetSignatureForDoc (t));
766                         }
767                         sb.Append (')');
768                         return sb.ToString ();
769                 }
770
771                 static string GetBodyIdentifierFromName (string name)
772                 {
773                         string identifier = name;
774
775                         if (name.Length > 0 && name [name.Length - 1] == ']') {
776                                 string tmp = name.Substring (0, name.Length - 1).Trim (wsChars);
777                                 int last = tmp.LastIndexOf ('[');
778                                 if (last > 0)
779                                         identifier = tmp.Substring (0, last).Trim (wsChars);
780                         }
781
782                         return identifier;
783                 }
784
785                 static void Report419 (MemberCore mc, string member_name, MemberInfo [] mis)
786                 {
787                         Report.Warning (419, 3, mc.Location, 
788                                 "Ambiguous reference in cref attribute `{0}'. Assuming `{1}' but other overloads including `{2}' have also matched",
789                                 member_name,
790                                 TypeManager.GetFullNameSignature (mis [0]),
791                                 TypeManager.GetFullNameSignature (mis [1]));
792                 }
793
794                 //
795                 // Get a prefix from member type for XML documentation (used
796                 // to formalize cref target name).
797                 //
798                 static string GetMemberDocHead (MemberTypes type)
799                 {
800                         switch (type) {
801                         case MemberTypes.Constructor:
802                         case MemberTypes.Method:
803                                 return "M:";
804                         case MemberTypes.Event:
805                                 return "E:";
806                         case MemberTypes.Field:
807                                 return "F:";
808                         case MemberTypes.NestedType:
809                         case MemberTypes.TypeInfo:
810                                 return "T:";
811                         case MemberTypes.Property:
812                                 return "P:";
813                         }
814                         return "!:";
815                 }
816
817                 // MethodCore
818
819                 //
820                 // Returns a string that represents the signature for this 
821                 // member which should be used in XML documentation.
822                 //
823                 public static string GetMethodDocCommentName (MemberCore mc, Parameters parameters, DeclSpace ds)
824                 {
825                         Parameter [] plist = parameters.FixedParameters;
826                         string paramSpec = String.Empty;
827                         if (plist != null) {
828                                 StringBuilder psb = new StringBuilder ();
829                                 foreach (Parameter p in plist) {
830                                         psb.Append (psb.Length != 0 ? "," : "(");
831                                         psb.Append (GetSignatureForDoc (p.ParameterType));
832                                         if ((p.ModFlags & Parameter.Modifier.ISBYREF) != 0)
833                                                 psb.Append ('@');
834                                 }
835                                 paramSpec = psb.ToString ();
836                         }
837
838                         if (paramSpec.Length > 0)
839                                 paramSpec += ")";
840
841                         string name = mc is Constructor ? "#ctor" : mc.Name;
842 #if GMCS_SOURCE                                             
843                         if (mc.MemberName.IsGeneric)
844                                 name += "``" + mc.MemberName.CountTypeArguments;
845 #endif
846                         string suffix = String.Empty;
847                         Operator op = mc as Operator;
848                         if (op != null) {
849                                 switch (op.OperatorType) {
850                                 case Operator.OpType.Implicit:
851                                 case Operator.OpType.Explicit:
852                                         suffix = "~" + GetSignatureForDoc (op.MethodBuilder.ReturnType);
853                                         break;
854                                 }
855                         }
856                         return String.Concat (mc.DocCommentHeader, ds.Name, ".", name, paramSpec, suffix);
857                 }
858
859                 static string GetSignatureForDoc (Type type)
860                 {
861 #if GMCS_SOURCE
862                         if (TypeManager.IsGenericParameter (type))
863                                 return (type.DeclaringMethod != null ? "``" : "`") + TypeManager.GenericParameterPosition (type);
864
865                         if (TypeManager.IsGenericType (type)) {
866                                 string g = type.Namespace;
867                                 if (g != null && g.Length > 0)
868                                         g += '.';
869                                 int idx = type.Name.LastIndexOf ('`');
870                                 g += (idx < 0 ? type.Name : type.Name.Substring (0, idx)) + '{';
871                                 int argpos = 0;
872                                 foreach (Type t in type.GetGenericArguments ())
873                                         g += (argpos++ > 0 ? "," : String.Empty) + GetSignatureForDoc (t);
874                                 g += '}';
875                                 return g;
876                         }
877 #endif
878
879                         string name = type.FullName != null ? type.FullName : type.Name;
880                         return name.Replace ("+", ".").Replace ('&', '@');
881                 }
882
883                 //
884                 // Raised (and passed an XmlElement that contains the comment)
885                 // when GenerateDocComment is writing documentation expectedly.
886                 //
887                 // FIXME: with a few effort, it could be done with XmlReader,
888                 // that means removal of DOM use.
889                 //
890                 internal static void OnMethodGenerateDocComment (
891                         MethodCore mc, XmlElement el)
892                 {
893                         Hashtable paramTags = new Hashtable ();
894                         foreach (XmlElement pelem in el.SelectNodes ("param")) {
895                                 int i;
896                                 string xname = pelem.GetAttribute ("name");
897                                 if (xname.Length == 0)
898                                         continue; // really? but MS looks doing so
899                                 if (xname != "" && mc.Parameters.GetParameterByName (xname, out i) == null)
900                                         Report.Warning (1572, 2, mc.Location, "XML comment on `{0}' has a param tag for `{1}', but there is no parameter by that name",
901                                                 mc.GetSignatureForError (), xname);
902                                 else if (paramTags [xname] != null)
903                                         Report.Warning (1571, 2, mc.Location, "XML comment on `{0}' has a duplicate param tag for `{1}'",
904                                                 mc.GetSignatureForError (), xname);
905                                 paramTags [xname] = xname;
906                         }
907                         Parameter [] plist = mc.Parameters.FixedParameters;
908                         foreach (Parameter p in plist) {
909                                 if (paramTags.Count > 0 && paramTags [p.Name] == null)
910                                         Report.Warning (1573, 4, mc.Location, "Parameter `{0}' has no matching param tag in the XML comment for `{1}'",
911                                                 p.Name, mc.GetSignatureForError ());
912                         }
913                 }
914
915                 private static void Normalize (MemberCore mc, ref string name)
916                 {
917                         if (name.Length > 0 && name [0] == '@')
918                                 name = name.Substring (1);
919                         else if (name == "this")
920                                 name = "Item";
921                         else if (Tokenizer.IsKeyword (name) && !IsTypeName (name))
922                                 Report.Warning (1041, 1, mc.Location, "Identifier expected. `{0}' is a keyword", name);
923                 }
924
925                 private static bool IsTypeName (string name)
926                 {
927                         switch (name) {
928                         case "bool":
929                         case "byte":
930                         case "char":
931                         case "decimal":
932                         case "double":
933                         case "float":
934                         case "int":
935                         case "long":
936                         case "object":
937                         case "sbyte":
938                         case "short":
939                         case "string":
940                         case "uint":
941                         case "ulong":
942                         case "ushort":
943                         case "void":
944                                 return true;
945                         }
946                         return false;
947                 }
948         }
949
950         //
951         // Implements XML documentation generation.
952         //
953         public class Documentation
954         {
955                 public Documentation (string xml_output_filename)
956                 {
957                         docfilename = xml_output_filename;
958                         XmlDocumentation = new XmlDocument ();
959                         XmlDocumentation.PreserveWhitespace = false;
960                 }
961
962                 private string docfilename;
963
964                 //
965                 // Used to create element which helps well-formedness checking.
966                 //
967                 public XmlDocument XmlDocumentation;
968
969                 //
970                 // The output for XML documentation.
971                 //
972                 public XmlWriter XmlCommentOutput;
973
974                 //
975                 // Stores XmlDocuments that are included in XML documentation.
976                 // Keys are included filenames, values are XmlDocuments.
977                 //
978                 public Hashtable StoredDocuments = new Hashtable ();
979
980                 //
981                 // Outputs XML documentation comment from tokenized comments.
982                 //
983                 public bool OutputDocComment (string asmfilename)
984                 {
985                         XmlTextWriter w = null;
986                         try {
987                                 w = new XmlTextWriter (docfilename, null);
988                                 w.Indentation = 4;
989                                 w.Formatting = Formatting.Indented;
990                                 w.WriteStartDocument ();
991                                 w.WriteStartElement ("doc");
992                                 w.WriteStartElement ("assembly");
993                                 w.WriteStartElement ("name");
994                                 w.WriteString (Path.ChangeExtension (asmfilename, null));
995                                 w.WriteEndElement (); // name
996                                 w.WriteEndElement (); // assembly
997                                 w.WriteStartElement ("members");
998                                 XmlCommentOutput = w;
999                                 GenerateDocComment ();
1000                                 w.WriteFullEndElement (); // members
1001                                 w.WriteEndElement ();
1002                                 w.WriteWhitespace (Environment.NewLine);
1003                                 w.WriteEndDocument ();
1004                                 return true;
1005                         } catch (Exception ex) {
1006                                 Report.Error (1569, "Error generating XML documentation file `{0}' (`{1}')", docfilename, ex.Message);
1007                                 return false;
1008                         } finally {
1009                                 if (w != null)
1010                                         w.Close ();
1011                         }
1012                 }
1013
1014                 //
1015                 // Fixes full type name of each documented types/members up.
1016                 //
1017                 public void GenerateDocComment ()
1018                 {
1019                         TypeContainer root = RootContext.ToplevelTypes;
1020
1021                         if (root.Types != null)
1022                                 foreach (TypeContainer tc in root.Types)
1023                                         DocUtil.GenerateTypeDocComment (tc, null);
1024
1025                         if (root.Delegates != null)
1026                                 foreach (Delegate d in root.Delegates) 
1027                                         DocUtil.GenerateDocComment (d, null);
1028                 }
1029         }
1030 }
1031 #endif