2006-10-14 Marek Sieradzki <marek.sieradzki@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 // Licensed under the terms of the GNU GPL
8 //
9 // (C) 2004 Novell, Inc.
10 //
11 //
12 #if ! BOOTSTRAP_WITH_OLDLIB
13 using System;
14 using System.Collections;
15 using System.Collections.Specialized;
16 using System.IO;
17 using System.Reflection;
18 using System.Reflection.Emit;
19 using System.Runtime.CompilerServices;
20 using System.Runtime.InteropServices;
21 using System.Security;
22 using System.Security.Permissions;
23 using System.Text;
24 using System.Xml;
25
26 using Mono.CompilerServices.SymbolWriter;
27
28 namespace Mono.CSharp {
29
30         //
31         // Support class for XML documentation.
32         //
33 #if NET_2_0
34         static
35 #else
36         abstract
37 #endif
38         public class DocUtil
39         {
40 #if !NET_2_0
41                 private DocUtil () {}
42 #endif
43                 // TypeContainer
44
45                 //
46                 // Generates xml doc comments (if any), and if required,
47                 // handle warning report.
48                 //
49                 internal static void GenerateTypeDocComment (TypeContainer t,
50                         DeclSpace ds)
51                 {
52                         GenerateDocComment (t, ds);
53
54                         if (t.DefaultStaticConstructor != null)
55                                 t.DefaultStaticConstructor.GenerateDocComment (t);
56
57                         if (t.InstanceConstructors != null)
58                                 foreach (Constructor c in t.InstanceConstructors)
59                                         c.GenerateDocComment (t);
60
61                         if (t.Types != null)
62                                 foreach (TypeContainer tc in t.Types)
63                                         tc.GenerateDocComment (t);
64
65                         if (t.Enums != null)
66                                 foreach (Enum en in t.Enums)
67                                         en.GenerateDocComment (t);
68
69                         if (t.Constants != null)
70                                 foreach (Const c in t.Constants)
71                                         c.GenerateDocComment (t);
72
73                         if (t.Fields != null)
74                                 foreach (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 lineHead =
100                         Environment.NewLine + "            ";
101
102                 private static XmlNode GetDocCommentNode (MemberCore mc,
103                         string name)
104                 {
105                         // FIXME: It could be even optimizable as not
106                         // to use XmlDocument. But anyways the nodes
107                         // are not kept in memory.
108                         XmlDocument doc = RootContext.Documentation.XmlDocumentation;
109                         try {
110                                 XmlElement el = doc.CreateElement ("member");
111                                 el.SetAttribute ("name", name);
112                                 string normalized = mc.DocComment;
113                                 el.InnerXml = normalized;
114                                 // csc keeps lines as written in the sources
115                                 // and inserts formatting indentation (which 
116                                 // is different from XmlTextWriter.Formatting
117                                 // one), but when a start tag contains an 
118                                 // endline, it joins the next line. We don't
119                                 // have to follow such a hacky behavior.
120                                 string [] split =
121                                         normalized.Split ('\n');
122                                 int j = 0;
123                                 for (int i = 0; i < split.Length; i++) {
124                                         string s = split [i].TrimEnd ();
125                                         if (s.Length > 0)
126                                                 split [j++] = s;
127                                 }
128                                 el.InnerXml = lineHead + String.Join (
129                                         lineHead, split, 0, j);
130                                 return el;
131                         } catch (XmlException ex) {
132                                 Report.Warning (1570, 1, mc.Location, "XML comment on `{0}' has non-well-formed XML ({1})", name, ex.Message);
133                                 XmlComment com = doc.CreateComment (String.Format ("FIXME: Invalid documentation markup was found for member {0}", name));
134                                 return com;
135                         }
136                 }
137
138                 //
139                 // Generates xml doc comments (if any), and if required,
140                 // handle warning report.
141                 //
142                 internal static void GenerateDocComment (MemberCore mc,
143                         DeclSpace ds)
144                 {
145                         if (mc.DocComment != null) {
146                                 string name = mc.GetDocCommentName (ds);
147
148                                 XmlNode n = GetDocCommentNode (mc, name);
149
150                                 XmlElement el = n as XmlElement;
151                                 if (el != null) {
152                                         mc.OnGenerateDocComment (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 dsTarget = mc as DeclSpace;
168                                         if (dsTarget == null)
169                                                 dsTarget = ds;
170
171                                         foreach (XmlElement see in n.SelectNodes (".//see"))
172                                                 HandleSee (mc, dsTarget, see);
173                                         foreach (XmlElement seealso in n.SelectNodes (".//seealso"))
174                                                 HandleSeeAlso (mc, dsTarget, seealso);
175                                         foreach (XmlElement see in n.SelectNodes (".//exception"))
176                                                 HandleException (mc, dsTarget, 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 keepIncludeNode = 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                                 keepIncludeNode = 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                                 keepIncludeNode = 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                                                         keepIncludeNode = 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 keepIncludeNode;
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 isArray = 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                                         isArray = true;
282                                 }
283                         }
284                         Type t = FindDocumentedTypeNonArray (mc, identifier, ds, cref);
285                         if (t != null && isArray)
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 typeof (int);
296                         case "uint":
297                                 return typeof (uint);
298                         case "short":
299                                 return typeof (short);
300                         case "ushort":
301                                 return typeof (ushort);
302                         case "long":
303                                 return typeof (long);
304                         case "ulong":
305                                 return typeof (ulong);
306                         case "float":
307                                 return typeof (float);
308                         case "double":
309                                 return typeof (double);
310                         case "char":
311                                 return typeof (char);
312                         case "decimal":
313                                 return typeof (decimal);
314                         case "byte":
315                                 return typeof (byte);
316                         case "sbyte":
317                                 return typeof (sbyte);
318                         case "object":
319                                 return typeof (object);
320                         case "bool":
321                                 return typeof (bool);
322                         case "string":
323                                 return typeof (string);
324                         case "void":
325                                 return typeof (void);
326                         }
327                         FullNamedExpression e = ds.LookupType (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 bindingFlags, MethodSignature signature)
351                 {
352                         MemberList ml = TypeManager.FindMembers (
353                                 type,
354                                 MemberTypes.Constructor | MemberTypes.Method | MemberTypes.Property | MemberTypes.Custom,
355                                 bindingFlags,
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 (!Invocation.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                                                         Invocation.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 regardlessOfThisValueItsEmpty)
435                         {
436                                 IsEmpty = true;
437                                 Member = null;
438                                 Type = null;
439                         }
440
441                         public FoundMember (Type foundType, MemberInfo member)
442                         {
443                                 IsEmpty = false;
444                                 Type = foundType;
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 memberName, Type [] paramList, 
455                         DeclSpace ds, out int warningType, string cref,
456                         bool warn419, string nameForError)
457                 {
458                         for (; type != null; type = type.DeclaringType) {
459                                 MemberInfo mi = FindDocumentedMemberNoNest (
460                                         mc, type, memberName, paramList, ds,
461                                         out warningType, cref, warn419,
462                                         nameForError);
463                                 if (mi != null)
464                                         return new FoundMember (type, mi);
465                         }
466                         warningType = 0;
467                         return FoundMember.Empty;
468                 }
469
470                 private static MemberInfo FindDocumentedMemberNoNest (
471                         MemberCore mc, Type type, string memberName,
472                         Type [] paramList, DeclSpace ds, out int warningType, 
473                         string cref, bool warn419, string nameForError)
474                 {
475                         warningType = 0;
476                         MemberInfo [] mis;
477
478                         if (paramList == 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                                         memberName, null);
484                                 mis = FilterOverridenMembersOut (mis);
485                                 if (mis == null || mis.Length == 0)
486                                         return null;
487                                 if (warn419 && IsAmbiguous (mis))
488                                         Report419 (mc, nameForError, mis);
489                                 return mis [0];
490                         }
491
492                         MethodSignature msig = new MethodSignature (memberName, null, paramList);
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, nameForError, 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 returnTypeName = null;
507                         if (memberName.StartsWith ("implicit operator ")) {
508                                 oper = "op_Implicit";
509                                 returnTypeName = memberName.Substring (18).Trim (wsChars);
510                         }
511                         else if (memberName.StartsWith ("explicit operator ")) {
512                                 oper = "op_Explicit";
513                                 returnTypeName = memberName.Substring (18).Trim (wsChars);
514                         }
515                         else if (memberName.StartsWith ("operator ")) {
516                                 oper = memberName.Substring (9).Trim (wsChars);
517                                 switch (oper) {
518                                 // either unary or binary
519                                 case "+":
520                                         oper = paramList.Length == 2 ?
521                                                 Binary.oper_names [(int) Binary.Operator.Addition] :
522                                                 Unary.oper_names [(int) Unary.Operator.UnaryPlus];
523                                         break;
524                                 case "-":
525                                         oper = paramList.Length == 2 ?
526                                                 Binary.oper_names [(int) 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.oper_names [(int) Binary.Operator.Multiply]; break;
546                                 case "/":
547                                         oper = Binary.oper_names [(int) Binary.Operator.Division]; break;
548                                 case "%":
549                                         oper = Binary.oper_names [(int) Binary.Operator.Modulus]; break;
550                                 case "&":
551                                         oper = Binary.oper_names [(int) Binary.Operator.BitwiseAnd]; break;
552                                 case "|":
553                                         oper = Binary.oper_names [(int) Binary.Operator.BitwiseOr]; break;
554                                 case "^":
555                                         oper = Binary.oper_names [(int) Binary.Operator.ExclusiveOr]; break;
556                                 case "<<":
557                                         oper = Binary.oper_names [(int) Binary.Operator.LeftShift]; break;
558                                 case ">>":
559                                         oper = Binary.oper_names [(int) Binary.Operator.RightShift]; break;
560                                 case "==":
561                                         oper = Binary.oper_names [(int) Binary.Operator.Equality]; break;
562                                 case "!=":
563                                         oper = Binary.oper_names [(int) Binary.Operator.Inequality]; break;
564                                 case "<":
565                                         oper = Binary.oper_names [(int) Binary.Operator.LessThan]; break;
566                                 case ">":
567                                         oper = Binary.oper_names [(int) Binary.Operator.GreaterThan]; break;
568                                 case "<=":
569                                         oper = Binary.oper_names [(int) Binary.Operator.LessThanOrEqual]; break;
570                                 case ">=":
571                                         oper = Binary.oper_names [(int) Binary.Operator.GreaterThanOrEqual]; break;
572                                 default:
573                                         warningType = 1584;
574                                         Report.Warning (1020, 1, mc.Location, "Overloadable {0} operator is expected", paramList.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, paramList);
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 (returnTypeName != null) {
596                                 Type returnType = FindDocumentedType (mc, returnTypeName, ds, cref);
597                                 if (returnType == null || returnType != expected) {
598                                         warningType = 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                         // strip 'T:' 'M:' 'F:' 'P:' 'E:' etc.
639                         // Here, MS ignores its member kind. No idea why.
640                         if (cref.Length > 2 && cref [1] == ':')
641                                 signature = cref.Substring (2).Trim (wsChars);
642                         else
643                                 signature = cref;
644
645                         int parensPos = signature.IndexOf ('(');
646                         int bracePos = parensPos >= 0 ? -1 :
647                                 signature.IndexOf ('[');
648                         if (parensPos > 0 && signature [signature.Length - 1] == ')') {
649                                 name = signature.Substring (0, parensPos).Trim (wsChars);
650                                 parameters = signature.Substring (parensPos + 1, signature.Length - parensPos - 2).Trim (wsChars);
651                         }
652                         else if (bracePos > 0 && signature [signature.Length - 1] == ']') {
653                                 name = signature.Substring (0, bracePos).Trim (wsChars);
654                                 parameters = signature.Substring (bracePos + 1, signature.Length - bracePos - 2).Trim (wsChars);
655                         }
656                         else {
657                                 name = signature;
658                                 parameters = null;
659                         }
660                         Normalize (mc, ref name);
661
662                         string identifier = GetBodyIdentifierFromName (name);
663
664                         // Check if identifier is valid.
665                         // This check is not necessary to mark as error, but
666                         // csc specially reports CS1584 for wrong identifiers.
667                         string [] nameElems = identifier.Split ('.');
668                         for (int i = 0; i < nameElems.Length; i++) {
669                                 string nameElem = GetBodyIdentifierFromName (nameElems [i]);
670                                 if (i > 0)
671                                         Normalize (mc, ref nameElem);
672                                 if (!Tokenizer.IsValidIdentifier (nameElem)
673                                         && nameElem.IndexOf ("operator") < 0) {
674                                         Report.Warning (1584, 1, mc.Location, "XML comment on `{0}' has syntactically incorrect cref attribute `{1}'",
675                                                 mc.GetSignatureForError (), cref);
676                                         xref.SetAttribute ("cref", "!:" + signature);
677                                         return;
678                                 }
679                         }
680
681                         // check if parameters are valid
682                         Type [] parameterTypes;
683                         if (parameters == null)
684                                 parameterTypes = null;
685                         else if (parameters.Length == 0)
686                                 parameterTypes = Type.EmptyTypes;
687                         else {
688                                 string [] paramList = parameters.Split (',');
689                                 ArrayList plist = new ArrayList ();
690                                 for (int i = 0; i < paramList.Length; i++) {
691                                         string paramTypeName = paramList [i].Trim (wsChars);
692                                         Normalize (mc, ref paramTypeName);
693                                         Type paramType = FindDocumentedType (mc, paramTypeName, ds, cref);
694                                         if (paramType == null) {
695                                                 Report.Warning (1580, 1, mc.Location, "Invalid type for parameter `{0}' in XML comment cref attribute `{1}'",
696                                                         (i + 1).ToString (), cref);
697                                                 return;
698                                         }
699                                         plist.Add (paramType);
700                                 }
701                                 parameterTypes = plist.ToArray (typeof (Type)) as Type [];
702                         }
703
704                         Type type = FindDocumentedType (mc, name, ds, cref);
705                         if (type != null
706                                 // delegate must not be referenced with args
707                                 && (!type.IsSubclassOf (typeof (System.Delegate))
708                                 || parameterTypes == null)) {
709                                 string result = GetSignatureForDoc (type)
710                                         + (bracePos < 0 ? String.Empty : signature.Substring (bracePos));
711                                 xref.SetAttribute ("cref", "T:" + result);
712                                 return; // a type
713                         }
714
715                         int period = name.LastIndexOf ('.');
716                         if (period > 0) {
717                                 string typeName = name.Substring (0, period);
718                                 string memberName = name.Substring (period + 1);
719                                 Normalize (mc, ref memberName);
720                                 type = FindDocumentedType (mc, typeName, ds, cref);
721                                 int warnResult;
722                                 if (type != null) {
723                                         FoundMember fm = FindDocumentedMember (mc, type, memberName, parameterTypes, ds, out warnResult, cref, true, name);
724                                         if (warnResult > 0)
725                                                 return;
726                                         if (!fm.IsEmpty) {
727                                                 MemberInfo mi = fm.Member;
728                                                 // we cannot use 'type' directly
729                                                 // to get its name, since mi
730                                                 // could be from DeclaringType
731                                                 // for nested types.
732                                                 xref.SetAttribute ("cref", GetMemberDocHead (mi.MemberType) + GetSignatureForDoc (fm.Type) + "." + memberName + GetParametersFormatted (mi));
733                                                 return; // a member of a type
734                                         }
735                                 }
736                         }
737                         else {
738                                 int warnResult;
739                                 FoundMember fm = FindDocumentedMember (mc, ds.TypeBuilder, name, parameterTypes, ds, out warnResult, cref, true, name);
740                                 if (warnResult > 0)
741                                         return;
742                                 if (!fm.IsEmpty) {
743                                         MemberInfo mi = fm.Member;
744                                         // we cannot use 'type' directly
745                                         // to get its name, since mi
746                                         // could be from DeclaringType
747                                         // for nested types.
748                                         xref.SetAttribute ("cref", GetMemberDocHead (mi.MemberType) + GetSignatureForDoc (fm.Type) + "." + name + GetParametersFormatted (mi));
749                                         return; // local member name
750                                 }
751                         }
752
753                         // It still might be part of namespace name.
754                         Namespace ns = ds.NamespaceEntry.NS.GetNamespace (name, false);
755                         if (ns != null) {
756                                 xref.SetAttribute ("cref", "N:" + ns.FullName);
757                                 return; // a namespace
758                         }
759                         if (RootNamespace.Global.IsNamespace (name)) {
760                                 xref.SetAttribute ("cref", "N:" + name);
761                                 return; // a namespace
762                         }
763
764                         Report.Warning (1574, 1, mc.Location, "XML comment on `{0}' has cref attribute `{1}' that could not be resolved",
765                                 mc.GetSignatureForError (), cref);
766
767                         xref.SetAttribute ("cref", "!:" + name);
768                 }
769
770                 static string GetParametersFormatted (MemberInfo mi)
771                 {
772                         MethodBase mb = mi as MethodBase;
773                         bool isSetter = false;
774                         PropertyInfo pi = mi as PropertyInfo;
775                         if (pi != null) {
776                                 mb = pi.GetGetMethod ();
777                                 if (mb == null) {
778                                         isSetter = true;
779                                         mb = pi.GetSetMethod ();
780                                 }
781                         }
782                         if (mb == null)
783                                 return String.Empty;
784
785                         ParameterData parameters = TypeManager.GetParameterData (mb);
786                         if (parameters == null || parameters.Count == 0)
787                                 return String.Empty;
788
789                         StringBuilder sb = new StringBuilder ();
790                         sb.Append ('(');
791                         for (int i = 0; i < parameters.Count; i++) {
792                                 if (isSetter && i + 1 == parameters.Count)
793                                         break; // skip "value".
794                                 if (i > 0)
795                                         sb.Append (',');
796                                 Type t = parameters.ParameterType (i);
797                                 sb.Append (GetSignatureForDoc (t));
798                         }
799                         sb.Append (')');
800                         return sb.ToString ();
801                 }
802
803                 static string GetBodyIdentifierFromName (string name)
804                 {
805                         string identifier = name;
806
807                         if (name.Length > 0 && name [name.Length - 1] == ']') {
808                                 string tmp = name.Substring (0, name.Length - 1).Trim (wsChars);
809                                 int last = tmp.LastIndexOf ('[');
810                                 if (last > 0)
811                                         identifier = tmp.Substring (0, last).Trim (wsChars);
812                         }
813
814                         return identifier;
815                 }
816
817                 static void Report419 (MemberCore mc, string memberName, MemberInfo [] mis)
818                 {
819                         Report.Warning (419, 3, mc.Location, 
820                                 "Ambiguous reference in cref attribute `{0}'. Assuming `{1}' but other overloads including `{2}' have also matched",
821                                 memberName,
822                                 TypeManager.GetFullNameSignature (mis [0]),
823                                 TypeManager.GetFullNameSignature (mis [1]));
824                 }
825
826                 //
827                 // Get a prefix from member type for XML documentation (used
828                 // to formalize cref target name).
829                 //
830                 static string GetMemberDocHead (MemberTypes type)
831                 {
832                         switch (type) {
833                         case MemberTypes.Constructor:
834                         case MemberTypes.Method:
835                                 return "M:";
836                         case MemberTypes.Event:
837                                 return "E:";
838                         case MemberTypes.Field:
839                                 return "F:";
840                         case MemberTypes.NestedType:
841                         case MemberTypes.TypeInfo:
842                                 return "T:";
843                         case MemberTypes.Property:
844                                 return "P:";
845                         }
846                         return "!:";
847                 }
848
849                 // MethodCore
850
851                 //
852                 // Returns a string that represents the signature for this 
853                 // member which should be used in XML documentation.
854                 //
855                 public static string GetMethodDocCommentName (MethodCore mc, DeclSpace ds)
856                 {
857                         Parameter [] plist = mc.Parameters.FixedParameters;
858                         string paramSpec = String.Empty;
859                         if (plist != null) {
860                                 StringBuilder psb = new StringBuilder ();
861                                 foreach (Parameter p in plist) {
862                                         psb.Append (psb.Length != 0 ? "," : "(");
863                                         psb.Append (GetSignatureForDoc (p.ExternalType ()));
864                                 }
865                                 paramSpec = psb.ToString ();
866                         }
867
868                         if (paramSpec.Length > 0)
869                                 paramSpec += ")";
870
871                         string name = mc is Constructor ? "#ctor" : mc.Name;
872                         string suffix = String.Empty;
873                         Operator op = mc as Operator;
874                         if (op != null) {
875                                 switch (op.OperatorType) {
876                                 case Operator.OpType.Implicit:
877                                 case Operator.OpType.Explicit:
878                                         suffix = "~" + GetSignatureForDoc (op.MethodBuilder.ReturnType);
879                                         break;
880                                 }
881                         }
882                         return String.Concat (mc.DocCommentHeader, ds.Name, ".", name, paramSpec, suffix);
883                 }
884
885                 static string GetSignatureForDoc (Type type)
886                 {
887                         return TypeManager.IsGenericParameter (type) ?
888                                 "`" + TypeManager.GenericParameterPosition (type) :
889                                 type.FullName.Replace ("+", ".").Replace ('&', '@');
890                 }
891
892                 //
893                 // Raised (and passed an XmlElement that contains the comment)
894                 // when GenerateDocComment is writing documentation expectedly.
895                 //
896                 // FIXME: with a few effort, it could be done with XmlReader,
897                 // that means removal of DOM use.
898                 //
899                 internal static void OnMethodGenerateDocComment (
900                         MethodCore mc, XmlElement el)
901                 {
902                         Hashtable paramTags = new Hashtable ();
903                         foreach (XmlElement pelem in el.SelectNodes ("param")) {
904                                 int i;
905                                 string xname = pelem.GetAttribute ("name");
906                                 if (xname.Length == 0)
907                                         continue; // really? but MS looks doing so
908                                 if (xname != "" && mc.Parameters.GetParameterByName (xname, out i) == null)
909                                         Report.Warning (1572, 2, mc.Location, "XML comment on `{0}' has a param tag for `{1}', but there is no parameter by that name",
910                                                 mc.GetSignatureForError (), xname);
911                                 else if (paramTags [xname] != null)
912                                         Report.Warning (1571, 2, mc.Location, "XML comment on `{0}' has a duplicate param tag for `{1}'",
913                                                 mc.GetSignatureForError (), xname);
914                                 paramTags [xname] = xname;
915                         }
916                         Parameter [] plist = mc.Parameters.FixedParameters;
917                         foreach (Parameter p in plist) {
918                                 if (paramTags.Count > 0 && paramTags [p.Name] == null)
919                                         Report.Warning (1573, 4, mc.Location, "Parameter `{0}' has no matching param tag in the XML comment for `{1}'",
920                                                 p.Name, mc.GetSignatureForError ());
921                         }
922                 }
923
924                 private static void Normalize (MemberCore mc, ref string name)
925                 {
926                         if (name.Length > 0 && name [0] == '@')
927                                 name = name.Substring (1);
928                         else if (name == "this")
929                                 name = "Item";
930                         else if (Tokenizer.IsKeyword (name) && !IsTypeName (name))
931                                 Report.Warning (1041, 1, mc.Location, "Identifier expected. `{0}' is a keyword", name);
932                 }
933
934                 private static bool IsTypeName (string name)
935                 {
936                         switch (name) {
937                         case "bool":
938                         case "byte":
939                         case "char":
940                         case "decimal":
941                         case "double":
942                         case "float":
943                         case "int":
944                         case "long":
945                         case "object":
946                         case "sbyte":
947                         case "short":
948                         case "string":
949                         case "uint":
950                         case "ulong":
951                         case "ushort":
952                         case "void":
953                                 return true;
954                         }
955                         return false;
956                 }
957         }
958
959         //
960         // Implements XML documentation generation.
961         //
962         public class Documentation
963         {
964                 public Documentation (string xml_output_filename)
965                 {
966                         docfilename = xml_output_filename;
967                         XmlDocumentation = new XmlDocument ();
968                         XmlDocumentation.PreserveWhitespace = false;
969                 }
970
971                 private string docfilename;
972
973                 //
974                 // Used to create element which helps well-formedness checking.
975                 //
976                 public XmlDocument XmlDocumentation;
977
978                 //
979                 // The output for XML documentation.
980                 //
981                 public XmlWriter XmlCommentOutput;
982
983                 //
984                 // Stores XmlDocuments that are included in XML documentation.
985                 // Keys are included filenames, values are XmlDocuments.
986                 //
987                 public Hashtable StoredDocuments = new Hashtable ();
988
989                 //
990                 // Outputs XML documentation comment from tokenized comments.
991                 //
992                 public bool OutputDocComment (string asmfilename)
993                 {
994                         XmlTextWriter w = null;
995                         try {
996                                 w = new XmlTextWriter (docfilename, null);
997                                 w.Indentation = 4;
998                                 w.Formatting = Formatting.Indented;
999                                 w.WriteStartDocument ();
1000                                 w.WriteStartElement ("doc");
1001                                 w.WriteStartElement ("assembly");
1002                                 w.WriteStartElement ("name");
1003                                 w.WriteString (Path.ChangeExtension (asmfilename, null));
1004                                 w.WriteEndElement (); // name
1005                                 w.WriteEndElement (); // assembly
1006                                 w.WriteStartElement ("members");
1007                                 XmlCommentOutput = w;
1008                                 GenerateDocComment ();
1009                                 w.WriteFullEndElement (); // members
1010                                 w.WriteEndElement ();
1011                                 w.WriteWhitespace (Environment.NewLine);
1012                                 w.WriteEndDocument ();
1013                                 return true;
1014                         } catch (Exception ex) {
1015                                 Report.Error (1569, "Error generating XML documentation file `{0}' (`{1}')", docfilename, ex.Message);
1016                                 return false;
1017                         } finally {
1018                                 if (w != null)
1019                                         w.Close ();
1020                         }
1021                 }
1022
1023                 //
1024                 // Fixes full type name of each documented types/members up.
1025                 //
1026                 public void GenerateDocComment ()
1027                 {
1028                         TypeContainer root = RootContext.ToplevelTypes;
1029                         if (root.Interfaces != null)
1030                                 foreach (Interface i in root.Interfaces) 
1031                                         DocUtil.GenerateTypeDocComment (i, null);
1032
1033                         if (root.Types != null)
1034                                 foreach (TypeContainer tc in root.Types)
1035                                         DocUtil.GenerateTypeDocComment (tc, null);
1036
1037                         if (root.Delegates != null)
1038                                 foreach (Delegate d in root.Delegates) 
1039                                         DocUtil.GenerateDocComment (d, null);
1040
1041                         if (root.Enums != null)
1042                                 foreach (Enum e in root.Enums)
1043                                         e.GenerateDocComment (null);
1044
1045                 }
1046         }
1047 }
1048 #endif