2005-11-24 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
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                                 Type.EmptyTypes,
337                                 ds, out warn, cref, false, null) as Type;
338                 }
339
340                 private static MemberInfo [] empty_member_infos =
341                         new MemberInfo [0];
342
343                 private static MemberInfo [] FindMethodBase (Type type,
344                         BindingFlags bindingFlags, MethodSignature signature)
345                 {
346                         MemberList ml = TypeManager.FindMembers (
347                                 type,
348                                 MemberTypes.Constructor | MemberTypes.Method | MemberTypes.Property | MemberTypes.Custom,
349                                 bindingFlags,
350                                 MethodSignature.method_signature_filter,
351                                 signature);
352                         if (ml == null)
353                                 return empty_member_infos;
354
355                         return FilterOverridenMembersOut (type, (MemberInfo []) ml);
356                 }
357
358                 static bool IsOverride (PropertyInfo deriv_prop, PropertyInfo base_prop)
359                 {
360                         if (!Invocation.IsAncestralType (base_prop.DeclaringType, deriv_prop.DeclaringType))
361                                 return false;
362
363                         Type [] deriv_pd = TypeManager.GetArgumentTypes (deriv_prop);
364                         Type [] base_pd = TypeManager.GetArgumentTypes (base_prop);
365                 
366                         if (deriv_pd.Length != base_pd.Length)
367                                 return false;
368
369                         for (int j = 0; j < deriv_pd.Length; ++j) {
370                                 if (deriv_pd [j] != base_pd [j])
371                                         return false;
372                                 Type ct = TypeManager.TypeToCoreType (deriv_pd [j]);
373                                 Type bt = TypeManager.TypeToCoreType (base_pd [j]);
374
375                                 if (ct != bt)
376                                         return false;
377                         }
378
379                         return true;
380                 }
381
382                 private static MemberInfo [] FilterOverridenMembersOut (
383                         Type type, MemberInfo [] ml)
384                 {
385                         if (ml == null)
386                                 return empty_member_infos;
387                         if (type.IsInterface)
388                                 return ml;
389
390                         ArrayList al = new ArrayList (ml.Length);
391                         for (int i = 0; i < ml.Length; i++) {
392                                 // Interface methods which are returned
393                                 // from the filter must exist in the 
394                                 // target type (if there is only a 
395                                 // private implementation, then the 
396                                 // filter should not return it.)
397                                 // This filtering is required to 
398                                 // deambiguate results.
399                                 //
400                                 // It is common to properties, so check it here.
401                                 if (ml [i].DeclaringType.IsInterface)
402                                         continue;
403                                 MethodBase mx = ml [i] as MethodBase;
404                                 PropertyInfo px = ml [i] as PropertyInfo;
405                                 if (mx != null || px != null) {
406                                         bool overriden = false;
407                                         for (int j = 0; j < ml.Length; j++) {
408                                                 if (j == i)
409                                                         continue;
410                                                 MethodBase my = ml [j] as MethodBase;
411                                                 if (mx != null && my != null &&
412                                                         Invocation.IsOverride (my, mx)) {
413                                                         overriden = true;
414                                                         break;
415                                                 }
416                                                 else if (mx != null)
417                                                         continue;
418                                                 PropertyInfo py = ml [j] as PropertyInfo;
419                                                 if (px != null && py != null &&
420                                                         IsOverride (py, px)) {
421                                                         overriden = true;
422                                                         break;
423                                                 }
424                                         }
425                                         if (overriden)
426                                                 continue;
427                                 }
428                                 al.Add (ml [i]);
429                         }
430                         return al.ToArray (typeof (MemberInfo)) as MemberInfo [];
431                 }
432
433                 //
434                 // Returns a MemberInfo that is referenced in XML documentation
435                 // (by "see" or "seealso" elements).
436                 //
437                 private static MemberInfo FindDocumentedMember (MemberCore mc,
438                         Type type, string memberName, Type [] paramList, 
439                         DeclSpace ds, out int warningType, string cref,
440                         bool warn419, string nameForError)
441                 {
442                         warningType = 0;
443                         MethodSignature msig = new MethodSignature (memberName, null, paramList);
444                         MemberInfo [] mis = FindMethodBase (type, 
445                                 BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance,
446                                 msig);
447
448                         if (warn419 && mis.Length > 0) {
449                                 if (IsAmbiguous (mis))
450                                         Report419 (mc, nameForError, mis);
451                                 return mis [0];
452                         }
453
454                         if (paramList.Length == 0) {
455                                 // search for fields/events etc.
456                                 mis = TypeManager.MemberLookup (type, null,
457                                         type, MemberTypes.All,
458                                         BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance,
459                                         memberName, null);
460                                 mis = FilterOverridenMembersOut (type, mis);
461                                 if (mis == null || mis.Length == 0)
462                                         return null;
463                                 if (warn419 && IsAmbiguous (mis))
464                                         Report419 (mc, nameForError, mis);
465                                 return mis [0];
466                         }
467
468                         // search for operators (whose parameters exactly
469                         // matches with the list) and possibly report CS1581.
470                         string oper = null;
471                         string returnTypeName = null;
472                         if (memberName.StartsWith ("implicit operator ")) {
473                                 oper = "op_Implicit";
474                                 returnTypeName = memberName.Substring (18).Trim (wsChars);
475                         }
476                         else if (memberName.StartsWith ("explicit operator ")) {
477                                 oper = "op_Explicit";
478                                 returnTypeName = memberName.Substring (18).Trim (wsChars);
479                         }
480                         else if (memberName.StartsWith ("operator ")) {
481                                 oper = memberName.Substring (9).Trim (wsChars);
482                                 switch (oper) {
483                                 // either unary or binary
484                                 case "+":
485                                         oper = paramList.Length == 2 ?
486                                                 Binary.oper_names [(int) Binary.Operator.Addition] :
487                                                 Unary.oper_names [(int) Unary.Operator.UnaryPlus];
488                                         break;
489                                 case "-":
490                                         oper = paramList.Length == 2 ?
491                                                 Binary.oper_names [(int) Binary.Operator.Subtraction] :
492                                                 Unary.oper_names [(int) Unary.Operator.UnaryNegation];
493                                         break;
494                                 // unary
495                                 case "!":
496                                         oper = Unary.oper_names [(int) Unary.Operator.LogicalNot]; break;
497                                 case "~":
498                                         oper = Unary.oper_names [(int) Unary.Operator.OnesComplement]; break;
499                                         
500                                 case "++":
501                                         oper = "op_Increment"; break;
502                                 case "--":
503                                         oper = "op_Decrement"; break;
504                                 case "true":
505                                         oper = "op_True"; break;
506                                 case "false":
507                                         oper = "op_False"; break;
508                                 // binary
509                                 case "*":
510                                         oper = Binary.oper_names [(int) Binary.Operator.Multiply]; break;
511                                 case "/":
512                                         oper = Binary.oper_names [(int) Binary.Operator.Division]; break;
513                                 case "%":
514                                         oper = Binary.oper_names [(int) Binary.Operator.Modulus]; break;
515                                 case "&":
516                                         oper = Binary.oper_names [(int) Binary.Operator.BitwiseAnd]; break;
517                                 case "|":
518                                         oper = Binary.oper_names [(int) Binary.Operator.BitwiseOr]; break;
519                                 case "^":
520                                         oper = Binary.oper_names [(int) Binary.Operator.ExclusiveOr]; break;
521                                 case "<<":
522                                         oper = Binary.oper_names [(int) Binary.Operator.LeftShift]; break;
523                                 case ">>":
524                                         oper = Binary.oper_names [(int) Binary.Operator.RightShift]; break;
525                                 case "==":
526                                         oper = Binary.oper_names [(int) Binary.Operator.Equality]; break;
527                                 case "!=":
528                                         oper = Binary.oper_names [(int) Binary.Operator.Inequality]; break;
529                                 case "<":
530                                         oper = Binary.oper_names [(int) Binary.Operator.LessThan]; break;
531                                 case ">":
532                                         oper = Binary.oper_names [(int) Binary.Operator.GreaterThan]; break;
533                                 case "<=":
534                                         oper = Binary.oper_names [(int) Binary.Operator.LessThanOrEqual]; break;
535                                 case ">=":
536                                         oper = Binary.oper_names [(int) Binary.Operator.GreaterThanOrEqual]; break;
537                                 default:
538                                         warningType = 1584;
539                                         Report.Warning (1020, 1, mc.Location, "Overloadable {0} operator is expected", paramList.Length == 2 ? "binary" : "unary");
540                                         Report.Warning (1584, 1, mc.Location, "XML comment on `{0}' has syntactically incorrect cref attribute `{1}'",
541                                                 mc.GetSignatureForError (), cref);
542                                         return null;
543                                 }
544                         }
545                         // here we still don't consider return type (to
546                         // detect CS1581 or CS1002+CS1584).
547                         msig = new MethodSignature (oper, null, paramList);
548
549                         mis = FindMethodBase (type, 
550                                 BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance,
551                                 msig);
552                         if (mis.Length == 0)
553                                 return null; // CS1574
554                         MemberInfo mi = mis [0];
555                         Type expected = mi is MethodInfo ?
556                                 ((MethodInfo) mi).ReturnType :
557                                 mi is PropertyInfo ?
558                                 ((PropertyInfo) mi).PropertyType :
559                                 null;
560                         if (returnTypeName != null) {
561                                 Type returnType = FindDocumentedType (mc, returnTypeName, ds, cref);
562                                 if (returnType == null || returnType != expected) {
563                                         warningType = 1581;
564                                         Report.Warning (1581, 1, mc.Location, "Invalid return type in XML comment cref attribute `{0}'", cref);
565                                         return null;
566                                 }
567                         }
568                         return mis [0];
569                 }
570
571                 private static bool IsAmbiguous (MemberInfo [] members)
572                 {
573                         if (members.Length < 2)
574                                 return false;
575                         if (members.Length > 2)
576                                 return true;
577                         if (members [0] is EventInfo && members [1] is FieldInfo)
578                                 return false;
579                         if (members [1] is EventInfo && members [0] is FieldInfo)
580                                 return false;
581                         return true;
582                 }
583
584                 //
585                 // Processes "see" or "seealso" elements.
586                 // Checks cref attribute.
587                 //
588                 private static void HandleXrefCommon (MemberCore mc,
589                         DeclSpace ds, XmlElement xref)
590                 {
591                         string cref = xref.GetAttribute ("cref").Trim (wsChars);
592                         // when, XmlReader, "if (cref == null)"
593                         if (!xref.HasAttribute ("cref"))
594                                 return;
595                         if (cref.Length == 0)
596                                 Report.Warning (1001, 1, mc.Location, "Identifier expected");
597                                 // ... and continue until CS1584.
598
599                         string signature; // "x:" are stripped
600                         string name; // method invokation "(...)" are removed
601                         string parameters; // method parameter list
602
603                         // strip 'T:' 'M:' 'F:' 'P:' 'E:' etc.
604                         // Here, MS ignores its member kind. No idea why.
605                         if (cref.Length > 2 && cref [1] == ':')
606                                 signature = cref.Substring (2).Trim (wsChars);
607                         else
608                                 signature = cref;
609
610                         int parensPos = signature.IndexOf ('(');
611                         int bracePos = parensPos >= 0 ? -1 :
612                                 signature.IndexOf ('[');
613                         if (parensPos > 0 && signature [signature.Length - 1] == ')') {
614                                 name = signature.Substring (0, parensPos).Trim (wsChars);
615                                 parameters = signature.Substring (parensPos + 1, signature.Length - parensPos - 2).Trim (wsChars);
616                         }
617                         else if (bracePos > 0 && signature [signature.Length - 1] == ']') {
618                                 name = signature.Substring (0, bracePos).Trim (wsChars);
619                                 parameters = signature.Substring (bracePos + 1, signature.Length - bracePos - 2).Trim (wsChars);
620                         }
621                         else {
622                                 name = signature;
623                                 parameters = String.Empty;
624                         }
625                         Normalize (mc, ref name);
626
627                         string identifier = GetBodyIdentifierFromName (name);
628
629                         // Check if identifier is valid.
630                         // This check is not necessary to mark as error, but
631                         // csc specially reports CS1584 for wrong identifiers.
632                         string [] nameElems = identifier.Split ('.');
633                         for (int i = 0; i < nameElems.Length; i++) {
634                                 string nameElem = GetBodyIdentifierFromName (nameElems [i]);
635                                 if (i > 0)
636                                         Normalize (mc, ref nameElem);
637                                 if (!Tokenizer.IsValidIdentifier (nameElem)
638                                         && nameElem.IndexOf ("operator") < 0) {
639                                         Report.Warning (1584, 1, mc.Location, "XML comment on `{0}' has syntactically incorrect cref attribute `{1}'",
640                                                 mc.GetSignatureForError (), cref);
641                                         xref.SetAttribute ("cref", "!:" + signature);
642                                         return;
643                                 }
644                         }
645
646                         // check if parameters are valid
647                         Type [] parameterTypes = Type.EmptyTypes;
648                         if (parameters.Length > 0) {
649                                 string [] paramList = parameters.Split (',');
650                                 ArrayList plist = new ArrayList ();
651                                 for (int i = 0; i < paramList.Length; i++) {
652                                         string paramTypeName = paramList [i].Trim (wsChars);
653                                         Normalize (mc, ref paramTypeName);
654                                         Type paramType = FindDocumentedType (mc, paramTypeName, ds, cref);
655                                         if (paramType == null) {
656                                                 Report.Warning (1580, 1, mc.Location, "Invalid type for parameter `{0}' in XML comment cref attribute `{1}'",
657                                                         (i + 1).ToString (), cref);
658                                                 return;
659                                         }
660                                         plist.Add (paramType);
661                                 }
662                                 parameterTypes = plist.ToArray (typeof (Type)) as Type [];
663                         }
664
665                         Type type = FindDocumentedType (mc, name, ds, cref);
666                         if (type != null
667                                 // delegate must not be referenced with args
668                                 && (!type.IsSubclassOf (typeof (System.Delegate))
669                                 || parameterTypes.Length == 0)) {
670                                 string result = type.FullName.Replace ("+", ".")
671                                         + (bracePos < 0 ? String.Empty : signature.Substring (bracePos));
672                                 xref.SetAttribute ("cref", "T:" + result);
673                                 return; // a type
674                         }
675
676                         // don't use identifier here. System[] is not alloed.
677                         if (RootNamespace.Global.IsNamespace (name)) {
678                                 xref.SetAttribute ("cref", "N:" + name);
679                                 return; // a namespace
680                         }
681
682                         int period = name.LastIndexOf ('.');
683                         if (period > 0) {
684                                 string typeName = name.Substring (0, period);
685                                 string memberName = name.Substring (period + 1);
686                                 Normalize (mc, ref memberName);
687                                 type = FindDocumentedType (mc, typeName, ds, cref);
688                                 int warnResult;
689                                 if (type != null) {
690                                         MemberInfo mi = FindDocumentedMember (mc, type, memberName, parameterTypes, ds, out warnResult, cref, true, name);
691                                         if (warnResult > 0)
692                                                 return;
693                                         if (mi != null) {
694                                                 xref.SetAttribute ("cref", GetMemberDocHead (mi.MemberType) + type.FullName.Replace ("+", ".") + "." + memberName + GetParametersFormatted (mi));
695                                                 return; // a member of a type
696                                         }
697                                 }
698                         }
699                         else {
700                                 int warnResult;
701                                 MemberInfo mi = FindDocumentedMember (mc, ds.TypeBuilder, name, parameterTypes, ds, out warnResult, cref, true, name);
702                                 if (warnResult > 0)
703                                         return;
704                                 if (mi != null) {
705                                         xref.SetAttribute ("cref", GetMemberDocHead (mi.MemberType) + ds.TypeBuilder.FullName.Replace ("+", ".") + "." + name + GetParametersFormatted (mi));
706                                         return; // local member name
707                                 }
708                         }
709
710                         Report.Warning (1574, 1, mc.Location, "XML comment on `{0}' has cref attribute `{1}' that could not be resolved",
711                                 mc.GetSignatureForError (), cref);
712
713                         xref.SetAttribute ("cref", "!:" + name);
714                 }
715
716                 static string GetParametersFormatted (MemberInfo mi)
717                 {
718                         MethodBase mb = mi as MethodBase;
719                         bool isSetter = false;
720                         PropertyInfo pi = mi as PropertyInfo;
721                         if (pi != null) {
722                                 mb = pi.GetGetMethod ();
723                                 if (mb == null) {
724                                         isSetter = true;
725                                         mb = pi.GetSetMethod ();
726                                 }
727                         }
728                         if (mb == null)
729                                 return String.Empty;
730
731                         ParameterData parameters = TypeManager.GetParameterData (mb);
732                         if (parameters == null || parameters.Count == 0)
733                                 return String.Empty;
734
735                         StringBuilder sb = new StringBuilder ();
736                         sb.Append ('(');
737                         for (int i = 0; i < parameters.Count; i++) {
738                                 if (isSetter && i + 1 == parameters.Count)
739                                         break; // skip "value".
740                                 if (i > 0)
741                                         sb.Append (',');
742                                 Type t = parameters.ParameterType (i);
743                                 sb.Append (t.FullName.Replace ('+', '.').Replace ('&', '@'));
744                         }
745                         sb.Append (')');
746                         return sb.ToString ();
747                 }
748
749                 static string GetBodyIdentifierFromName (string name)
750                 {
751                         string identifier = name;
752
753                         if (name.Length > 0 && name [name.Length - 1] == ']') {
754                                 string tmp = name.Substring (0, name.Length - 1).Trim (wsChars);
755                                 int last = tmp.LastIndexOf ('[');
756                                 if (last > 0)
757                                         identifier = tmp.Substring (0, last).Trim (wsChars);
758                         }
759
760                         return identifier;
761                 }
762
763                 static void Report419 (MemberCore mc, string memberName, MemberInfo [] mis)
764                 {
765                         Report.Warning (419, 3, mc.Location, 
766                                 "Ambiguous reference in cref attribute `{0}'. Assuming `{1}' but other overloads including `{2}' have also matched",
767                                 memberName,
768                                 TypeManager.GetFullNameSignature (mis [0]),
769                                 TypeManager.GetFullNameSignature (mis [1]));
770                 }
771
772                 //
773                 // Get a prefix from member type for XML documentation (used
774                 // to formalize cref target name).
775                 //
776                 static string GetMemberDocHead (MemberTypes type)
777                 {
778                         switch (type) {
779                         case MemberTypes.Constructor:
780                         case MemberTypes.Method:
781                                 return "M:";
782                         case MemberTypes.Event:
783                                 return "E:";
784                         case MemberTypes.Field:
785                                 return "F:";
786                         case MemberTypes.NestedType:
787                         case MemberTypes.TypeInfo:
788                                 return "T:";
789                         case MemberTypes.Property:
790                                 return "P:";
791                         }
792                         return "!:";
793                 }
794
795                 // MethodCore
796
797                 //
798                 // Returns a string that represents the signature for this 
799                 // member which should be used in XML documentation.
800                 //
801                 public static string GetMethodDocCommentName (MethodCore mc, DeclSpace ds)
802                 {
803                         Parameter [] plist = mc.Parameters.FixedParameters;
804                         string paramSpec = String.Empty;
805                         if (plist != null) {
806                                 StringBuilder psb = new StringBuilder ();
807                                 foreach (Parameter p in plist) {
808                                         psb.Append (psb.Length != 0 ? "," : "(");
809                                         psb.Append (p.ExternalType ().FullName.Replace ("+", ".").Replace ('&', '@'));
810                                 }
811                                 paramSpec = psb.ToString ();
812                         }
813
814                         if (paramSpec.Length > 0)
815                                 paramSpec += ")";
816
817                         string name = mc is Constructor ? "#ctor" : mc.Name;
818                         string suffix = String.Empty;
819                         Operator op = mc as Operator;
820                         if (op != null) {
821                                 switch (op.OperatorType) {
822                                 case Operator.OpType.Implicit:
823                                 case Operator.OpType.Explicit:
824                                         suffix = "~" + op.OperatorMethodBuilder.ReturnType.FullName.Replace ('+', '.');
825                                         break;
826                                 }
827                         }
828                         return String.Concat (mc.DocCommentHeader, ds.Name, ".", name, paramSpec, suffix);
829                 }
830
831                 //
832                 // Raised (and passed an XmlElement that contains the comment)
833                 // when GenerateDocComment is writing documentation expectedly.
834                 //
835                 // FIXME: with a few effort, it could be done with XmlReader,
836                 // that means removal of DOM use.
837                 //
838                 internal static void OnMethodGenerateDocComment (
839                         MethodCore mc, DeclSpace ds, XmlElement el)
840                 {
841                         Hashtable paramTags = new Hashtable ();
842                         foreach (XmlElement pelem in el.SelectNodes ("param")) {
843                                 int i;
844                                 string xname = pelem.GetAttribute ("name");
845                                 if (xname == "")
846                                         continue; // really? but MS looks doing so
847                                 if (xname != "" && mc.Parameters.GetParameterByName (xname, out i) == null)
848                                         Report.Warning (1572, 2, mc.Location, "XML comment on `{0}' has a param tag for `{1}', but there is no parameter by that name",
849                                                 mc.GetSignatureForError (), xname);
850                                 else if (paramTags [xname] != null)
851                                         Report.Warning (1571, 2, mc.Location, "XML comment on `{0}' has a duplicate param tag for `{1}'",
852                                                 mc.GetSignatureForError (), xname);
853                                 paramTags [xname] = xname;
854                         }
855                         Parameter [] plist = mc.Parameters.FixedParameters;
856                         foreach (Parameter p in plist) {
857                                 if (paramTags.Count > 0 && paramTags [p.Name] == null)
858                                         Report.Warning (1573, 4, mc.Location, "Parameter `{0}' has no matching param tag in the XML comment for `{1}'",
859                                                 p.Name, mc.GetSignatureForError ());
860                         }
861                 }
862
863                 private static void Normalize (MemberCore mc, ref string name)
864                 {
865                         if (name.Length > 0 && name [0] == '@')
866                                 name = name.Substring (1);
867                         else if (name == "this")
868                                 name = "Item";
869                         else if (Tokenizer.IsKeyword (name) && !IsTypeName (name))
870                                 Report.Warning (1041, 1, mc.Location, "Identifier expected. `{0}' is a keyword", name);
871                 }
872
873                 private static bool IsTypeName (string name)
874                 {
875                         switch (name) {
876                         case "bool":
877                         case "byte":
878                         case "char":
879                         case "decimal":
880                         case "double":
881                         case "float":
882                         case "int":
883                         case "long":
884                         case "object":
885                         case "sbyte":
886                         case "short":
887                         case "string":
888                         case "uint":
889                         case "ulong":
890                         case "ushort":
891                         case "void":
892                                 return true;
893                         }
894                         return false;
895                 }
896         }
897
898         //
899         // Implements XML documentation generation.
900         //
901         public class Documentation
902         {
903                 public Documentation (string xml_output_filename)
904                 {
905                         docfilename = xml_output_filename;
906                         XmlDocumentation = new XmlDocument ();
907                         XmlDocumentation.PreserveWhitespace = false;
908                 }
909
910                 private string docfilename;
911
912                 //
913                 // Used to create element which helps well-formedness checking.
914                 //
915                 public XmlDocument XmlDocumentation;
916
917                 //
918                 // The output for XML documentation.
919                 //
920                 public XmlWriter XmlCommentOutput;
921
922                 //
923                 // Stores XmlDocuments that are included in XML documentation.
924                 // Keys are included filenames, values are XmlDocuments.
925                 //
926                 public Hashtable StoredDocuments = new Hashtable ();
927
928                 //
929                 // Stores comments on partial types (should handle uniquely).
930                 // Keys are PartialContainers, values are comment strings
931                 // (didn't use StringBuilder; usually we have just 2 or more).
932                 //
933                 public IDictionary PartialComments = new ListDictionary ();
934
935                 //
936                 // Outputs XML documentation comment from tokenized comments.
937                 //
938                 public bool OutputDocComment (string asmfilename)
939                 {
940                         XmlTextWriter w = null;
941                         try {
942                                 w = new XmlTextWriter (docfilename, null);
943                                 w.Indentation = 4;
944                                 w.Formatting = Formatting.Indented;
945                                 w.WriteStartDocument ();
946                                 w.WriteStartElement ("doc");
947                                 w.WriteStartElement ("assembly");
948                                 w.WriteStartElement ("name");
949                                 w.WriteString (Path.ChangeExtension (asmfilename, null));
950                                 w.WriteEndElement (); // name
951                                 w.WriteEndElement (); // assembly
952                                 w.WriteStartElement ("members");
953                                 XmlCommentOutput = w;
954                                 GenerateDocComment ();
955                                 w.WriteFullEndElement (); // members
956                                 w.WriteEndElement ();
957                                 w.WriteWhitespace (Environment.NewLine);
958                                 w.WriteEndDocument ();
959                                 return true;
960                         } catch (Exception ex) {
961                                 Report.Error (1569, "Error generating XML documentation file `{0}' (`{1}')", docfilename, ex.Message);
962                                 return false;
963                         } finally {
964                                 if (w != null)
965                                         w.Close ();
966                         }
967                 }
968
969                 //
970                 // Fixes full type name of each documented types/members up.
971                 //
972                 public void GenerateDocComment ()
973                 {
974                         TypeContainer root = RootContext.Tree.Types;
975                         if (root.Interfaces != null)
976                                 foreach (Interface i in root.Interfaces) 
977                                         DocUtil.GenerateTypeDocComment (i, null);
978
979                         if (root.Types != null)
980                                 foreach (TypeContainer tc in root.Types)
981                                         DocUtil.GenerateTypeDocComment (tc, null);
982
983                         if (root.Parts != null) {
984                                 IDictionary comments = PartialComments;
985                                 foreach (ClassPart cp in root.Parts) {
986                                         if (cp.DocComment == null)
987                                                 continue;
988                                         comments [cp] = cp;
989                                 }
990                         }
991
992                         if (root.Delegates != null)
993                                 foreach (Delegate d in root.Delegates) 
994                                         DocUtil.GenerateDocComment (d, null);
995
996                         if (root.Enums != null)
997                                 foreach (Enum e in root.Enums)
998                                         e.GenerateDocComment (null);
999
1000                         IDictionary table = new ListDictionary ();
1001                         foreach (ClassPart cp in PartialComments.Keys) {
1002                                 // FIXME: IDictionary does not guarantee that the keys will be
1003                                 //        accessed in the order they were added.
1004                                 table [cp.PartialContainer] += cp.DocComment;
1005                         }
1006                         foreach (PartialContainer pc in table.Keys) {
1007                                 pc.DocComment = table [pc] as string;
1008                                 DocUtil.GenerateDocComment (pc, null);
1009                         }
1010                 }
1011         }
1012 }
1013
1014 #endif