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