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