Update copyright notices
[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                                 oper = "op_Implicit";
509                                 return_type_name = member_name.Substring (18).Trim (wsChars);
510                         }
511                         else if (member_name.StartsWith ("explicit operator ")) {
512                                 oper = "op_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                                                 Binary.GetOperatorMetadataName (Binary.Operator.Addition) :
522                                                 Unary.oper_names [(int) Unary.Operator.UnaryPlus];
523                                         break;
524                                 case "-":
525                                         oper = param_list.Length == 2 ?
526                                                 Binary.GetOperatorMetadataName (Binary.Operator.Subtraction) :
527                                                 Unary.oper_names [(int) Unary.Operator.UnaryNegation];
528                                         break;
529                                 // unary
530                                 case "!":
531                                         oper = Unary.oper_names [(int) Unary.Operator.LogicalNot]; break;
532                                 case "~":
533                                         oper = Unary.oper_names [(int) Unary.Operator.OnesComplement]; break;
534                                         
535                                 case "++":
536                                         oper = "op_Increment"; break;
537                                 case "--":
538                                         oper = "op_Decrement"; break;
539                                 case "true":
540                                         oper = "op_True"; break;
541                                 case "false":
542                                         oper = "op_False"; break;
543                                 // binary
544                                 case "*":
545                                         oper = Binary.GetOperatorMetadataName (Binary.Operator.Multiply); break;
546                                 case "/":
547                                         oper = Binary.GetOperatorMetadataName (Binary.Operator.Division); break;
548                                 case "%":
549                                         oper = Binary.GetOperatorMetadataName (Binary.Operator.Modulus); break;
550                                 case "&":
551                                         oper = Binary.GetOperatorMetadataName (Binary.Operator.BitwiseAnd); break;
552                                 case "|":
553                                         oper = Binary.GetOperatorMetadataName (Binary.Operator.BitwiseOr); break;
554                                 case "^":
555                                         oper = Binary.GetOperatorMetadataName (Binary.Operator.ExclusiveOr); break;
556                                 case "<<":
557                                         oper = Binary.GetOperatorMetadataName (Binary.Operator.LeftShift); break;
558                                 case ">>":
559                                         oper = Binary.GetOperatorMetadataName (Binary.Operator.RightShift); break;
560                                 case "==":
561                                         oper = Binary.GetOperatorMetadataName (Binary.Operator.Equality); break;
562                                 case "!=":
563                                         oper = Binary.GetOperatorMetadataName (Binary.Operator.Inequality); break;
564                                 case "<":
565                                         oper = Binary.GetOperatorMetadataName (Binary.Operator.LessThan); break;
566                                 case ">":
567                                         oper = Binary.GetOperatorMetadataName (Binary.Operator.GreaterThan); break;
568                                 case "<=":
569                                         oper = Binary.GetOperatorMetadataName (Binary.Operator.LessThanOrEqual); break;
570                                 case ">=":
571                                         oper = Binary.GetOperatorMetadataName (Binary.Operator.GreaterThanOrEqual); break;
572                                 default:
573                                         warning_type = 1584;
574                                         Report.Warning (1020, 1, mc.Location, "Overloadable {0} operator is expected", param_list.Length == 2 ? "binary" : "unary");
575                                         Report.Warning (1584, 1, mc.Location, "XML comment on `{0}' has syntactically incorrect cref attribute `{1}'",
576                                                 mc.GetSignatureForError (), cref);
577                                         return null;
578                                 }
579                         }
580                         // here we still don't consider return type (to
581                         // detect CS1581 or CS1002+CS1584).
582                         msig = new MethodSignature (oper, null, param_list);
583
584                         mis = FindMethodBase (type, 
585                                 BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance,
586                                 msig);
587                         if (mis.Length == 0)
588                                 return null; // CS1574
589                         MemberInfo mi = mis [0];
590                         Type expected = mi is MethodInfo ?
591                                 ((MethodInfo) mi).ReturnType :
592                                 mi is PropertyInfo ?
593                                 ((PropertyInfo) mi).PropertyType :
594                                 null;
595                         if (return_type_name != null) {
596                                 Type returnType = FindDocumentedType (mc, return_type_name, ds, cref);
597                                 if (returnType == null || returnType != expected) {
598                                         warning_type = 1581;
599                                         Report.Warning (1581, 1, mc.Location, "Invalid return type in XML comment cref attribute `{0}'", cref);
600                                         return null;
601                                 }
602                         }
603                         return mis [0];
604                 }
605
606                 private static bool IsAmbiguous (MemberInfo [] members)
607                 {
608                         if (members.Length < 2)
609                                 return false;
610                         if (members.Length > 2)
611                                 return true;
612                         if (members [0] is EventInfo && members [1] is FieldInfo)
613                                 return false;
614                         if (members [1] is EventInfo && members [0] is FieldInfo)
615                                 return false;
616                         return true;
617                 }
618
619                 //
620                 // Processes "see" or "seealso" elements.
621                 // Checks cref attribute.
622                 //
623                 private static void HandleXrefCommon (MemberCore mc,
624                         DeclSpace ds, XmlElement xref)
625                 {
626                         string cref = xref.GetAttribute ("cref").Trim (wsChars);
627                         // when, XmlReader, "if (cref == null)"
628                         if (!xref.HasAttribute ("cref"))
629                                 return;
630                         if (cref.Length == 0)
631                                 Report.Warning (1001, 1, mc.Location, "Identifier expected");
632                                 // ... and continue until CS1584.
633
634                         string signature; // "x:" are stripped
635                         string name; // method invokation "(...)" are removed
636                         string parameters; // method parameter list
637
638                         // When it found '?:' ('T:' 'M:' 'F:' 'P:' 'E:' etc.),
639                         // MS ignores not only its member kind, but also
640                         // the entire syntax correctness. Nor it also does
641                         // type fullname resolution i.e. "T:List(int)" is kept
642                         // as T:List(int), not
643                         // T:System.Collections.Generic.List&lt;System.Int32&gt;
644                         if (cref.Length > 2 && cref [1] == ':')
645                                 return;
646                         else
647                                 signature = cref;
648
649                         // Also note that without "T:" any generic type 
650                         // indication fails.
651
652                         int parens_pos = signature.IndexOf ('(');
653                         int brace_pos = parens_pos >= 0 ? -1 :
654                                 signature.IndexOf ('[');
655                         if (parens_pos > 0 && signature [signature.Length - 1] == ')') {
656                                 name = signature.Substring (0, parens_pos).Trim (wsChars);
657                                 parameters = signature.Substring (parens_pos + 1, signature.Length - parens_pos - 2).Trim (wsChars);
658                         }
659                         else if (brace_pos > 0 && signature [signature.Length - 1] == ']') {
660                                 name = signature.Substring (0, brace_pos).Trim (wsChars);
661                                 parameters = signature.Substring (brace_pos + 1, signature.Length - brace_pos - 2).Trim (wsChars);
662                         }
663                         else {
664                                 name = signature;
665                                 parameters = null;
666                         }
667                         Normalize (mc, ref name);
668
669                         string identifier = GetBodyIdentifierFromName (name);
670
671                         // Check if identifier is valid.
672                         // This check is not necessary to mark as error, but
673                         // csc specially reports CS1584 for wrong identifiers.
674                         string [] name_elems = identifier.Split ('.');
675                         for (int i = 0; i < name_elems.Length; i++) {
676                                 string nameElem = GetBodyIdentifierFromName (name_elems [i]);
677                                 if (i > 0)
678                                         Normalize (mc, ref nameElem);
679                                 if (!Tokenizer.IsValidIdentifier (nameElem)
680                                         && nameElem.IndexOf ("operator") < 0) {
681                                         Report.Warning (1584, 1, mc.Location, "XML comment on `{0}' has syntactically incorrect cref attribute `{1}'",
682                                                 mc.GetSignatureForError (), cref);
683                                         xref.SetAttribute ("cref", "!:" + signature);
684                                         return;
685                                 }
686                         }
687
688                         // check if parameters are valid
689                         Type [] parameter_types;
690                         if (parameters == null)
691                                 parameter_types = null;
692                         else if (parameters.Length == 0)
693                                 parameter_types = Type.EmptyTypes;
694                         else {
695                                 string [] param_list = parameters.Split (',');
696                                 ArrayList plist = new ArrayList ();
697                                 for (int i = 0; i < param_list.Length; i++) {
698                                         string param_type_name = param_list [i].Trim (wsChars);
699                                         Normalize (mc, ref param_type_name);
700                                         Type param_type = FindDocumentedType (mc, param_type_name, ds, cref);
701                                         if (param_type == null) {
702                                                 Report.Warning (1580, 1, mc.Location, "Invalid type for parameter `{0}' in XML comment cref attribute `{1}'",
703                                                         (i + 1).ToString (), cref);
704                                                 return;
705                                         }
706                                         plist.Add (param_type);
707                                 }
708                                 parameter_types = plist.ToArray (typeof (Type)) as Type [];
709                         }
710
711                         Type type = FindDocumentedType (mc, name, ds, cref);
712                         if (type != null
713                                 // delegate must not be referenced with args
714                                 && (!TypeManager.IsDelegateType (type)
715                                 || parameter_types == null)) {
716                                 string result = GetSignatureForDoc (type)
717                                         + (brace_pos < 0 ? String.Empty : signature.Substring (brace_pos));
718                                 xref.SetAttribute ("cref", "T:" + result);
719                                 return; // a type
720                         }
721
722                         int period = name.LastIndexOf ('.');
723                         if (period > 0) {
724                                 string typeName = name.Substring (0, period);
725                                 string member_name = name.Substring (period + 1);
726                                 Normalize (mc, ref member_name);
727                                 type = FindDocumentedType (mc, typeName, ds, cref);
728                                 int warn_result;
729                                 if (type != null) {
730                                         FoundMember fm = FindDocumentedMember (mc, type, member_name, parameter_types, ds, out warn_result, cref, true, name);
731                                         if (warn_result > 0)
732                                                 return;
733                                         if (!fm.IsEmpty) {
734                                                 MemberInfo mi = fm.Member;
735                                                 // we cannot use 'type' directly
736                                                 // to get its name, since mi
737                                                 // could be from DeclaringType
738                                                 // for nested types.
739                                                 xref.SetAttribute ("cref", GetMemberDocHead (mi.MemberType) + GetSignatureForDoc (fm.Type) + "." + member_name + GetParametersFormatted (mi));
740                                                 return; // a member of a type
741                                         }
742                                 }
743                         }
744                         else {
745                                 int warn_result;
746                                 FoundMember fm = FindDocumentedMember (mc, ds.TypeBuilder, name, parameter_types, ds, out warn_result, cref, true, name);
747                                 if (warn_result > 0)
748                                         return;
749                                 if (!fm.IsEmpty) {
750                                         MemberInfo mi = fm.Member;
751                                         // we cannot use 'type' directly
752                                         // to get its name, since mi
753                                         // could be from DeclaringType
754                                         // for nested types.
755                                         xref.SetAttribute ("cref", GetMemberDocHead (mi.MemberType) + GetSignatureForDoc (fm.Type) + "." + name + GetParametersFormatted (mi));
756                                         return; // local member name
757                                 }
758                         }
759
760                         // It still might be part of namespace name.
761                         Namespace ns = ds.NamespaceEntry.NS.GetNamespace (name, false);
762                         if (ns != null) {
763                                 xref.SetAttribute ("cref", "N:" + ns.FullName);
764                                 return; // a namespace
765                         }
766                         if (RootNamespace.Global.IsNamespace (name)) {
767                                 xref.SetAttribute ("cref", "N:" + name);
768                                 return; // a namespace
769                         }
770
771                         Report.Warning (1574, 1, mc.Location, "XML comment on `{0}' has cref attribute `{1}' that could not be resolved",
772                                 mc.GetSignatureForError (), cref);
773
774                         xref.SetAttribute ("cref", "!:" + name);
775                 }
776
777                 static string GetParametersFormatted (MemberInfo mi)
778                 {
779                         MethodBase mb = mi as MethodBase;
780                         bool is_setter = false;
781                         PropertyInfo pi = mi as PropertyInfo;
782                         if (pi != null) {
783                                 mb = pi.GetGetMethod ();
784                                 if (mb == null) {
785                                         is_setter = true;
786                                         mb = pi.GetSetMethod ();
787                                 }
788                         }
789                         if (mb == null)
790                                 return String.Empty;
791
792                         ParameterData parameters = TypeManager.GetParameterData (mb);
793                         if (parameters == null || parameters.Count == 0)
794                                 return String.Empty;
795
796                         StringBuilder sb = new StringBuilder ();
797                         sb.Append ('(');
798                         for (int i = 0; i < parameters.Count; i++) {
799                                 if (is_setter && i + 1 == parameters.Count)
800                                         break; // skip "value".
801                                 if (i > 0)
802                                         sb.Append (',');
803                                 Type t = parameters.ParameterType (i);
804                                 sb.Append (GetSignatureForDoc (t));
805                         }
806                         sb.Append (')');
807                         return sb.ToString ();
808                 }
809
810                 static string GetBodyIdentifierFromName (string name)
811                 {
812                         string identifier = name;
813
814                         if (name.Length > 0 && name [name.Length - 1] == ']') {
815                                 string tmp = name.Substring (0, name.Length - 1).Trim (wsChars);
816                                 int last = tmp.LastIndexOf ('[');
817                                 if (last > 0)
818                                         identifier = tmp.Substring (0, last).Trim (wsChars);
819                         }
820
821                         return identifier;
822                 }
823
824                 static void Report419 (MemberCore mc, string member_name, MemberInfo [] mis)
825                 {
826                         Report.Warning (419, 3, mc.Location, 
827                                 "Ambiguous reference in cref attribute `{0}'. Assuming `{1}' but other overloads including `{2}' have also matched",
828                                 member_name,
829                                 TypeManager.GetFullNameSignature (mis [0]),
830                                 TypeManager.GetFullNameSignature (mis [1]));
831                 }
832
833                 //
834                 // Get a prefix from member type for XML documentation (used
835                 // to formalize cref target name).
836                 //
837                 static string GetMemberDocHead (MemberTypes type)
838                 {
839                         switch (type) {
840                         case MemberTypes.Constructor:
841                         case MemberTypes.Method:
842                                 return "M:";
843                         case MemberTypes.Event:
844                                 return "E:";
845                         case MemberTypes.Field:
846                                 return "F:";
847                         case MemberTypes.NestedType:
848                         case MemberTypes.TypeInfo:
849                                 return "T:";
850                         case MemberTypes.Property:
851                                 return "P:";
852                         }
853                         return "!:";
854                 }
855
856                 // MethodCore
857
858                 //
859                 // Returns a string that represents the signature for this 
860                 // member which should be used in XML documentation.
861                 //
862                 public static string GetMethodDocCommentName (MemberCore mc, Parameters parameters, DeclSpace ds)
863                 {
864                         Parameter [] plist = parameters.FixedParameters;
865                         string paramSpec = String.Empty;
866                         if (plist != null) {
867                                 StringBuilder psb = new StringBuilder ();
868                                 foreach (Parameter p in plist) {
869                                         psb.Append (psb.Length != 0 ? "," : "(");
870                                         psb.Append (GetSignatureForDoc (p.ParameterType));
871                                         if ((p.ModFlags & Parameter.Modifier.ISBYREF) != 0)
872                                                 psb.Append ('@');
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 #if GMCS_SOURCE                                             
882                         if (mc.MemberName.IsGeneric)
883                                 name += "``" + mc.MemberName.CountTypeArguments;
884 #endif
885                         string suffix = String.Empty;
886                         Operator op = mc as Operator;
887                         if (op != null) {
888                                 switch (op.OperatorType) {
889                                 case Operator.OpType.Implicit:
890                                 case Operator.OpType.Explicit:
891                                         suffix = "~" + GetSignatureForDoc (op.MethodBuilder.ReturnType);
892                                         break;
893                                 }
894                         }
895                         return String.Concat (mc.DocCommentHeader, ds.Name, ".", name, paramSpec, suffix);
896                 }
897
898                 static string GetSignatureForDoc (Type type)
899                 {
900 #if GMCS_SOURCE
901                         if (TypeManager.IsGenericParameter (type))
902                                 return (type.DeclaringMethod != null ? "``" : "`") + TypeManager.GenericParameterPosition (type);
903
904                         if (TypeManager.IsGenericType (type)) {
905                                 string g = type.Namespace;
906                                 if (g != null && g.Length > 0)
907                                         g += '.';
908                                 int idx = type.Name.LastIndexOf ('`');
909                                 g += (idx < 0 ? type.Name : type.Name.Substring (0, idx)) + '{';
910                                 int argpos = 0;
911                                 foreach (Type t in type.GetGenericArguments ())
912                                         g += (argpos++ > 0 ? "," : String.Empty) + GetSignatureForDoc (t);
913                                 g += '}';
914                                 return g;
915                         }
916 #endif
917
918                         string name = type.FullName != null ? type.FullName : type.Name;
919                         return name.Replace ("+", ".").Replace ('&', '@');
920                 }
921
922                 //
923                 // Raised (and passed an XmlElement that contains the comment)
924                 // when GenerateDocComment is writing documentation expectedly.
925                 //
926                 // FIXME: with a few effort, it could be done with XmlReader,
927                 // that means removal of DOM use.
928                 //
929                 internal static void OnMethodGenerateDocComment (
930                         MethodCore mc, XmlElement el)
931                 {
932                         Hashtable paramTags = new Hashtable ();
933                         foreach (XmlElement pelem in el.SelectNodes ("param")) {
934                                 int i;
935                                 string xname = pelem.GetAttribute ("name");
936                                 if (xname.Length == 0)
937                                         continue; // really? but MS looks doing so
938                                 if (xname != "" && mc.Parameters.GetParameterByName (xname, out i) == null)
939                                         Report.Warning (1572, 2, mc.Location, "XML comment on `{0}' has a param tag for `{1}', but there is no parameter by that name",
940                                                 mc.GetSignatureForError (), xname);
941                                 else if (paramTags [xname] != null)
942                                         Report.Warning (1571, 2, mc.Location, "XML comment on `{0}' has a duplicate param tag for `{1}'",
943                                                 mc.GetSignatureForError (), xname);
944                                 paramTags [xname] = xname;
945                         }
946                         Parameter [] plist = mc.Parameters.FixedParameters;
947                         foreach (Parameter p in plist) {
948                                 if (paramTags.Count > 0 && paramTags [p.Name] == null)
949                                         Report.Warning (1573, 4, mc.Location, "Parameter `{0}' has no matching param tag in the XML comment for `{1}'",
950                                                 p.Name, mc.GetSignatureForError ());
951                         }
952                 }
953
954                 private static void Normalize (MemberCore mc, ref string name)
955                 {
956                         if (name.Length > 0 && name [0] == '@')
957                                 name = name.Substring (1);
958                         else if (name == "this")
959                                 name = "Item";
960                         else if (Tokenizer.IsKeyword (name) && !IsTypeName (name))
961                                 Report.Warning (1041, 1, mc.Location, "Identifier expected. `{0}' is a keyword", name);
962                 }
963
964                 private static bool IsTypeName (string name)
965                 {
966                         switch (name) {
967                         case "bool":
968                         case "byte":
969                         case "char":
970                         case "decimal":
971                         case "double":
972                         case "float":
973                         case "int":
974                         case "long":
975                         case "object":
976                         case "sbyte":
977                         case "short":
978                         case "string":
979                         case "uint":
980                         case "ulong":
981                         case "ushort":
982                         case "void":
983                                 return true;
984                         }
985                         return false;
986                 }
987         }
988
989         //
990         // Implements XML documentation generation.
991         //
992         public class Documentation
993         {
994                 public Documentation (string xml_output_filename)
995                 {
996                         docfilename = xml_output_filename;
997                         XmlDocumentation = new XmlDocument ();
998                         XmlDocumentation.PreserveWhitespace = false;
999                 }
1000
1001                 private string docfilename;
1002
1003                 //
1004                 // Used to create element which helps well-formedness checking.
1005                 //
1006                 public XmlDocument XmlDocumentation;
1007
1008                 //
1009                 // The output for XML documentation.
1010                 //
1011                 public XmlWriter XmlCommentOutput;
1012
1013                 //
1014                 // Stores XmlDocuments that are included in XML documentation.
1015                 // Keys are included filenames, values are XmlDocuments.
1016                 //
1017                 public Hashtable StoredDocuments = new Hashtable ();
1018
1019                 //
1020                 // Outputs XML documentation comment from tokenized comments.
1021                 //
1022                 public bool OutputDocComment (string asmfilename)
1023                 {
1024                         XmlTextWriter w = null;
1025                         try {
1026                                 w = new XmlTextWriter (docfilename, null);
1027                                 w.Indentation = 4;
1028                                 w.Formatting = Formatting.Indented;
1029                                 w.WriteStartDocument ();
1030                                 w.WriteStartElement ("doc");
1031                                 w.WriteStartElement ("assembly");
1032                                 w.WriteStartElement ("name");
1033                                 w.WriteString (Path.ChangeExtension (asmfilename, null));
1034                                 w.WriteEndElement (); // name
1035                                 w.WriteEndElement (); // assembly
1036                                 w.WriteStartElement ("members");
1037                                 XmlCommentOutput = w;
1038                                 GenerateDocComment ();
1039                                 w.WriteFullEndElement (); // members
1040                                 w.WriteEndElement ();
1041                                 w.WriteWhitespace (Environment.NewLine);
1042                                 w.WriteEndDocument ();
1043                                 return true;
1044                         } catch (Exception ex) {
1045                                 Report.Error (1569, "Error generating XML documentation file `{0}' (`{1}')", docfilename, ex.Message);
1046                                 return false;
1047                         } finally {
1048                                 if (w != null)
1049                                         w.Close ();
1050                         }
1051                 }
1052
1053                 //
1054                 // Fixes full type name of each documented types/members up.
1055                 //
1056                 public void GenerateDocComment ()
1057                 {
1058                         TypeContainer root = RootContext.ToplevelTypes;
1059
1060                         if (root.Types != null)
1061                                 foreach (TypeContainer tc in root.Types)
1062                                         DocUtil.GenerateTypeDocComment (tc, null);
1063
1064                         if (root.Delegates != null)
1065                                 foreach (Delegate d in root.Delegates) 
1066                                         DocUtil.GenerateDocComment (d, null);
1067                 }
1068         }
1069 }
1070 #endif