2 // doc.cs: Support for XML documentation comment.
5 // Atsushi Enomoto <atsushi@ximian.com>
7 // Licensed under the terms of the GNU GPL
9 // (C) 2004 Novell, Inc.
13 using System.Collections;
14 using System.Collections.Specialized;
16 using System.Reflection;
17 using System.Reflection.Emit;
18 using System.Runtime.CompilerServices;
19 using System.Runtime.InteropServices;
20 using System.Security;
21 using System.Security.Permissions;
25 using Mono.CompilerServices.SymbolWriter;
27 namespace Mono.CSharp {
30 // Support class for XML documentation.
32 public static class DocUtil
37 // Generates xml doc comments (if any), and if required,
38 // handle warning report.
40 internal static void GenerateTypeDocComment (TypeContainer t,
43 GenerateDocComment (t, ds);
45 if (t.DefaultStaticConstructor != null)
46 t.DefaultStaticConstructor.GenerateDocComment (t);
48 if (t.InstanceConstructors != null)
49 foreach (Constructor c in t.InstanceConstructors)
50 c.GenerateDocComment (t);
53 foreach (TypeContainer tc in t.Types)
54 tc.GenerateDocComment (t);
56 if (t.Parts != null) {
57 IDictionary comments = RootContext.Documentation.PartialComments;
58 foreach (ClassPart cp in t.Parts) {
59 if (cp.DocComment == null)
66 foreach (Enum en in t.Enums)
67 en.GenerateDocComment (t);
69 if (t.Constants != null)
70 foreach (Const c in t.Constants)
71 c.GenerateDocComment (t);
74 foreach (Field f in t.Fields)
75 f.GenerateDocComment (t);
78 foreach (Event e in t.Events)
79 e.GenerateDocComment (t);
81 if (t.Indexers != null)
82 foreach (Indexer ix in t.Indexers)
83 ix.GenerateDocComment (t);
85 if (t.Properties != null)
86 foreach (Property p in t.Properties)
87 p.GenerateDocComment (t);
89 if (t.Methods != null)
90 foreach (Method m in t.Methods)
91 m.GenerateDocComment (t);
93 if (t.Operators != null)
94 foreach (Operator o in t.Operators)
95 o.GenerateDocComment (t);
99 private static readonly string lineHead =
100 Environment.NewLine + " ";
102 private static XmlNode GetDocCommentNode (MemberCore mc,
105 // FIXME: It could be even optimizable as not
106 // to use XmlDocument. But anyways the nodes
107 // are not kept in memory.
108 XmlDocument doc = RootContext.Documentation.XmlDocumentation;
110 XmlElement el = doc.CreateElement ("member");
111 el.SetAttribute ("name", name);
112 string normalized = mc.DocComment;
113 el.InnerXml = normalized;
114 // csc keeps lines as written in the sources
115 // and inserts formatting indentation (which
116 // is different from XmlTextWriter.Formatting
117 // one), but when a start tag contains an
118 // endline, it joins the next line. We don't
119 // have to follow such a hacky behavior.
121 normalized.Split ('\n');
123 for (int i = 0; i < split.Length; i++) {
124 string s = split [i].TrimEnd ();
128 el.InnerXml = lineHead + String.Join (
129 lineHead, split, 0, j);
131 } catch (XmlException ex) {
132 Report.Warning (1570, 1, mc.Location, "XML comment on '{0}' has non-well-formed XML ({1}).", name, ex.Message);
133 XmlComment com = doc.CreateComment (String.Format ("FIXME: Invalid documentation markup was found for member {0}", name));
139 // Generates xml doc comments (if any), and if required,
140 // handle warning report.
142 internal static void GenerateDocComment (MemberCore mc,
145 if (mc.DocComment != null) {
146 string name = mc.GetDocCommentName (ds);
148 XmlNode n = GetDocCommentNode (mc, name);
150 XmlElement el = n as XmlElement;
152 mc.OnGenerateDocComment (ds, el);
154 // FIXME: it could be done with XmlReader
155 foreach (XmlElement inc in n.SelectNodes (".//include"))
156 HandleInclude (mc, inc);
158 // FIXME: it could be done with XmlReader
159 DeclSpace dsTarget = mc as DeclSpace;
160 if (dsTarget == null)
163 foreach (XmlElement see in n.SelectNodes (".//see"))
164 HandleSee (mc, dsTarget, see);
165 foreach (XmlElement seealso in n.SelectNodes (".//seealso"))
166 HandleSeeAlso (mc, dsTarget, seealso);
167 foreach (XmlElement see in n.SelectNodes (".//exception"))
168 HandleException (mc, dsTarget, see);
171 n.WriteTo (RootContext.Documentation.XmlCommentOutput);
173 else if (mc.IsExposedFromAssembly (ds)) {
174 Constructor c = mc as Constructor;
175 if (c == null || !c.IsDefault ())
176 Report.Warning (1591, 4, mc.Location,
177 "Missing XML comment for publicly visible type or member '{0}'", mc.GetSignatureForError ());
182 // Processes "include" element. Check included file and
183 // embed the document content inside this documentation node.
185 private static void HandleInclude (MemberCore mc, XmlElement el)
187 string file = el.GetAttribute ("file");
188 string path = el.GetAttribute ("path");
190 Report.Warning (1590, 1, mc.Location, "Invalid XML 'include' element; Missing 'file' attribute.");
191 el.ParentNode.InsertBefore (el.OwnerDocument.CreateComment (" Include tag is invalid "), el);
193 else if (path == "") {
194 Report.Warning (1590, 1, mc.Location, "Invalid XML 'include' element; Missing 'path' attribute.");
195 el.ParentNode.InsertBefore (el.OwnerDocument.CreateComment (" Include tag is invalid "), el);
198 XmlDocument doc = RootContext.Documentation.StoredDocuments [file] as XmlDocument;
201 doc = new XmlDocument ();
203 RootContext.Documentation.StoredDocuments.Add (file, doc);
204 } catch (Exception) {
205 el.ParentNode.InsertBefore (el.OwnerDocument.CreateComment (String.Format (" Badly formed XML in at comment file '{0}': cannot be included ", file)), el);
206 Report.Warning (1592, 1, mc.Location, "Badly formed XML in included comments file -- '{0}'", file);
209 bool keepIncludeNode = false;
212 XmlNodeList nl = doc.SelectNodes (path);
214 el.ParentNode.InsertBefore (el.OwnerDocument.CreateComment (" No matching elements were found for the include tag embedded here. "), el);
216 keepIncludeNode = true;
218 foreach (XmlNode n in nl)
219 el.ParentNode.InsertBefore (el.OwnerDocument.ImportNode (n, true), el);
220 } catch (Exception ex) {
221 el.ParentNode.InsertBefore (el.OwnerDocument.CreateComment (" Failed to insert some or all of included XML "), el);
222 Report.Warning (1589, 1, mc.Location, "Unable to include XML fragment '{0}' of file {1} -- {2}.", path, file, ex.Message);
225 if (!keepIncludeNode)
226 el.ParentNode.RemoveChild (el);
231 // Handles <see> elements.
233 private static void HandleSee (MemberCore mc,
234 DeclSpace ds, XmlElement see)
236 HandleXrefCommon (mc, ds, see);
240 // Handles <seealso> elements.
242 private static void HandleSeeAlso (MemberCore mc,
243 DeclSpace ds, XmlElement seealso)
245 HandleXrefCommon (mc, ds, seealso);
249 // Handles <exception> elements.
251 private static void HandleException (MemberCore mc,
252 DeclSpace ds, XmlElement seealso)
254 HandleXrefCommon (mc, ds, seealso);
257 static readonly char [] wsChars =
258 new char [] {' ', '\t', '\n', '\r'};
261 // returns a full runtime type name from a name which might
262 // be C# specific type name.
264 private static Type FindDocumentedType (MemberCore mc,
265 string name, DeclSpace ds, bool allowAlias, string cref)
267 bool isArray = false;
268 string identifier = name;
269 if (name [name.Length - 1] == ']') {
270 string tmp = name.Substring (0, name.Length - 1).Trim (wsChars);
271 if (tmp [tmp.Length - 1] == '[') {
272 identifier = tmp.Substring (0, tmp.Length - 1).Trim (wsChars);
276 Type t = FindDocumentedTypeNonArray (mc, identifier,
277 ds, allowAlias, cref);
278 if (t != null && isArray)
279 t = Array.CreateInstance (t, 0).GetType ();
283 private static Type FindDocumentedTypeNonArray (MemberCore mc,
284 string identifier, DeclSpace ds, bool allowAlias,
287 switch (identifier) {
291 return typeof (uint);
293 return typeof (short);
295 return typeof (ushort);
297 return typeof (long);
299 return typeof (ulong);
301 return typeof (float);
303 return typeof (double);
305 return typeof (char);
307 return typeof (decimal);
309 return typeof (byte);
311 return typeof (sbyte);
313 return typeof (object);
315 return typeof (bool);
317 return typeof (string);
319 return typeof (void);
322 IAlias alias = ds.LookupAlias (identifier);
324 identifier = alias.Name;
326 Type t = ds.FindType (mc.Location, identifier);
328 t = TypeManager.LookupType (identifier);
330 int index = identifier.LastIndexOf ('.');
334 Type parent = FindDocumentedType (mc,
335 identifier.Substring (0, index),
336 ds, allowAlias, cref);
339 t = FindDocumentedMember (mc, parent,
340 identifier.Substring (index + 1),
342 ds, out warn, cref) as Type;
348 // Returns a MemberInfo that is referenced in XML documentation
349 // (by "see" or "seealso" elements).
351 private static MemberInfo FindDocumentedMember (MemberCore mc,
352 Type type, string memberName, Type [] paramList,
353 DeclSpace ds, out int warningType, string cref)
356 MethodSignature msig = new MethodSignature (memberName, null, paramList);
357 MemberInfo [] mis = type.FindMembers (
359 BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance,
360 MethodSignature.method_signature_filter,
365 if (paramList.Length == 0) {
366 // search for fields/events etc.
367 mis = type.FindMembers (
369 BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance,
372 return (mis.Length > 0) ? mis [0] : null;
375 // search for operators (whose parameters exactly
376 // matches with the list) and possibly report CS1581.
378 string returnTypeName = null;
379 if (memberName.StartsWith ("implicit operator ")) {
380 oper = "op_Implicit";
381 returnTypeName = memberName.Substring (18).Trim (wsChars);
383 else if (memberName.StartsWith ("explicit operator ")) {
384 oper = "op_Explicit";
385 returnTypeName = memberName.Substring (18).Trim (wsChars);
387 else if (memberName.StartsWith ("operator ")) {
388 oper = memberName.Substring (9).Trim (wsChars);
390 // either unary or binary
392 oper = paramList.Length == 2 ?
393 Binary.oper_names [(int) Binary.Operator.Addition] :
394 Unary.oper_names [(int) Unary.Operator.UnaryPlus];
397 oper = paramList.Length == 2 ?
398 Binary.oper_names [(int) Binary.Operator.Subtraction] :
399 Unary.oper_names [(int) Unary.Operator.UnaryNegation];
403 oper = Unary.oper_names [(int) Unary.Operator.LogicalNot]; break;
405 oper = Unary.oper_names [(int) Unary.Operator.OnesComplement]; break;
408 oper = "op_Increment"; break;
410 oper = "op_Decrement"; break;
412 oper = "op_True"; break;
414 oper = "op_False"; break;
417 oper = Binary.oper_names [(int) Binary.Operator.Multiply]; break;
419 oper = Binary.oper_names [(int) Binary.Operator.Division]; break;
421 oper = Binary.oper_names [(int) Binary.Operator.Modulus]; break;
423 oper = Binary.oper_names [(int) Binary.Operator.BitwiseAnd]; break;
425 oper = Binary.oper_names [(int) Binary.Operator.BitwiseOr]; break;
427 oper = Binary.oper_names [(int) Binary.Operator.ExclusiveOr]; break;
429 oper = Binary.oper_names [(int) Binary.Operator.LeftShift]; break;
431 oper = Binary.oper_names [(int) Binary.Operator.RightShift]; break;
433 oper = Binary.oper_names [(int) Binary.Operator.Equality]; break;
435 oper = Binary.oper_names [(int) Binary.Operator.Inequality]; break;
437 oper = Binary.oper_names [(int) Binary.Operator.LessThan]; break;
439 oper = Binary.oper_names [(int) Binary.Operator.GreaterThan]; break;
441 oper = Binary.oper_names [(int) Binary.Operator.LessThanOrEqual]; break;
443 oper = Binary.oper_names [(int) Binary.Operator.GreaterThanOrEqual]; break;
446 Report.Warning (1020, 1, mc.Location, "Overloadable {0} operator is expected", paramList.Length == 2 ? "binary" : "unary");
447 Report.Warning (1584, 1, mc.Location, "XML comment on '{0}' has syntactically incorrect attribute '{1}'", mc.GetSignatureForError (), cref);
451 // here we still does not consider return type (to
452 // detect CS1581 or CS1002+CS1584).
453 msig = new MethodSignature (oper, null, paramList);
454 mis = type.FindMembers (
456 BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static,
457 MethodSignature.method_signature_filter,
460 return null; // CS1574
461 MemberInfo mi = mis [0];
462 Type expected = mi is MethodInfo ?
463 ((MethodInfo) mi).ReturnType :
465 ((PropertyInfo) mi).PropertyType :
467 if (returnTypeName != null) {
468 Type returnType = FindDocumentedType (mc, returnTypeName, ds, true, cref);
469 if (returnType == null || returnType != expected) {
471 Report.Warning (1581, 1, mc.Location, "Invalid return type in XML comment cref attribute '{0}'", cref);
478 private static Type [] emptyParamList = new Type [0];
481 // Processes "see" or "seealso" elements.
482 // Checks cref attribute.
484 private static void HandleXrefCommon (MemberCore mc,
485 DeclSpace ds, XmlElement xref)
487 string cref = xref.GetAttribute ("cref").Trim (wsChars);
488 // when, XmlReader, "if (cref == null)"
489 if (!xref.HasAttribute ("cref"))
491 if (cref.Length == 0)
492 Report.Warning (1001, 1, mc.Location, "Identifier expected");
493 // ... and continue until CS1584.
495 string signature; // "x:" are stripped
496 string name; // method invokation "(...)" are removed
497 string parameters; // method parameter list
499 // strip 'T:' 'M:' 'F:' 'P:' 'E:' etc.
500 // Here, MS ignores its member kind. No idea why.
501 if (cref.Length > 2 && cref [1] == ':')
502 signature = cref.Substring (2).Trim (wsChars);
506 int parensPos = signature.IndexOf ('(');
507 if (parensPos > 0 && signature [signature.Length - 1] == ')') {
508 name = signature.Substring (0, parensPos).Trim (wsChars);
509 parameters = signature.Substring (parensPos + 1, signature.Length - parensPos - 2);
513 parameters = String.Empty;
516 string identifier = name;
518 if (name.Length > 0 && name [name.Length - 1] == ']') {
519 string tmp = name.Substring (0, name.Length - 1).Trim (wsChars);
520 if (tmp [tmp.Length - 1] == '[')
521 identifier = tmp.Substring (0, tmp.Length - 1).Trim (wsChars);
524 // Check if identifier is valid.
525 // This check is not necessary to mark as error, but
526 // csc specially reports CS1584 for wrong identifiers.
527 foreach (string nameElem in identifier.Split ('.')) {
528 if (!Tokenizer.IsValidIdentifier (nameElem)
529 && nameElem.IndexOf ("operator") < 0) {
530 if (nameElem.EndsWith ("[]") &&
531 Tokenizer.IsValidIdentifier (
533 0, nameElem.Length - 2)))
536 Report.Warning (1584, 1, mc.Location, "XML comment on '{0}' has syntactically incorrect attribute '{1}'", mc.GetSignatureForError (), cref);
537 xref.SetAttribute ("cref", "!:" + signature);
542 // check if parameters are valid
543 Type [] parameterTypes = emptyParamList;
544 if (parameters.Length > 0) {
545 string [] paramList = parameters.Split (',');
546 ArrayList plist = new ArrayList ();
547 for (int i = 0; i < paramList.Length; i++) {
548 string paramTypeName = paramList [i].Trim (wsChars);
549 Type paramType = FindDocumentedType (mc, paramTypeName, ds, true, cref);
550 if (paramType == null) {
551 Report.Warning (1580, 1, mc.Location, "Invalid type for parameter '{0}' in XML comment cref attribute '{1}'", i + 1, cref);
554 plist.Add (paramType);
556 parameterTypes = plist.ToArray (typeof (Type)) as Type [];
557 StringBuilder sb = new StringBuilder ();
559 for (int i = 0; i < parameterTypes.Length; i++) {
560 Type t = parameterTypes [i];
563 sb.Append (t.FullName.Replace ('+', '.'));
566 parameters = sb.ToString ();
569 Type type = FindDocumentedType (mc, name, ds, true, cref);
571 xref.SetAttribute ("cref", "T:" + type.FullName.Replace ("+", "."));
575 // don't use identifier here. System[] is not alloed.
576 if (Namespace.IsNamespace (name)) {
577 xref.SetAttribute ("cref", "N:" + name);
578 return; // a namespace
581 int period = name.LastIndexOf ('.');
583 string typeName = name.Substring (0, period);
584 string memberName = name.Substring (period + 1);
585 type = FindDocumentedType (mc, typeName, ds, false, cref);
588 MemberInfo mi = FindDocumentedMember (mc, type, memberName, parameterTypes, ds, out warnResult, cref);
592 xref.SetAttribute ("cref", GetMemberDocHead (mi.MemberType) + type.FullName.Replace ("+", ".") + "." + memberName + parameters);
593 return; // a member of a type
599 MemberInfo mi = FindDocumentedMember (mc, ds.TypeBuilder, name, parameterTypes, ds, out warnResult, cref);
603 xref.SetAttribute ("cref", GetMemberDocHead (mi.MemberType) + ds.TypeBuilder.FullName.Replace ("+", ".") + "." + name);
604 return; // local member name
608 Report.Warning (1574, 1, mc.Location, "XML comment on '{0}' has cref attribute '{1}' that could not be resolved in '{2}'.", mc.GetSignatureForError (), cref, ds.GetSignatureForError ());
610 xref.SetAttribute ("cref", "!:" + name);
614 // Get a prefix from member type for XML documentation (used
615 // to formalize cref target name).
617 static string GetMemberDocHead (MemberTypes type)
620 case MemberTypes.Constructor:
621 case MemberTypes.Method:
623 case MemberTypes.Event:
625 case MemberTypes.Field:
627 case MemberTypes.NestedType:
628 case MemberTypes.TypeInfo:
630 case MemberTypes.Property:
639 // Returns a string that represents the signature for this
640 // member which should be used in XML documentation.
642 public static string GetMethodDocCommentName (MethodCore mc, DeclSpace ds)
644 Parameter [] plist = mc.Parameters.FixedParameters;
645 Parameter parr = mc.Parameters.ArrayParameter;
646 string paramSpec = String.Empty;
648 StringBuilder psb = new StringBuilder ();
649 foreach (Parameter p in plist) {
650 psb.Append (psb.Length != 0 ? "," : "(");
651 psb.Append (p.ParameterType.FullName.Replace ("+", "."));
653 paramSpec = psb.ToString ();
656 paramSpec += String.Concat (
657 paramSpec == String.Empty ? "(" : ",",
658 parr.ParameterType.FullName.Replace ("+", "."));
660 if (paramSpec.Length > 0)
663 string name = mc is Constructor ? "#ctor" : mc.Name;
664 string suffix = String.Empty;
665 Operator op = mc as Operator;
667 switch (op.OperatorType) {
668 case Operator.OpType.Implicit:
669 case Operator.OpType.Explicit:
670 suffix = "~" + op.OperatorMethodBuilder.ReturnType.FullName.Replace ('+', '.');
674 return String.Concat (mc.DocCommentHeader, ds.Name, ".", name, paramSpec, suffix);
678 // Raised (and passed an XmlElement that contains the comment)
679 // when GenerateDocComment is writing documentation expectedly.
681 // FIXME: with a few effort, it could be done with XmlReader,
682 // that means removal of DOM use.
684 internal static void OnMethodGenerateDocComment (
685 MethodCore mc, DeclSpace ds, XmlElement el)
687 Hashtable paramTags = new Hashtable ();
688 foreach (XmlElement pelem in el.SelectNodes ("param")) {
690 string xname = pelem.GetAttribute ("name");
692 continue; // really? but MS looks doing so
693 if (xname != "" && mc.Parameters.GetParameterByName (xname, out i) == null)
694 Report.Warning (1572, 2, mc.Location, "XML comment on '{0}' has a 'param' tag for '{1}', but there is no such parameter.", mc.Name, xname);
695 else if (paramTags [xname] != null)
696 Report.Warning (1571, 2, mc.Location, "XML comment on '{0}' has a duplicate param tag for '{1}'", mc.Name, xname);
697 paramTags [xname] = xname;
699 Parameter [] plist = mc.Parameters.FixedParameters;
701 foreach (Parameter p in plist) {
702 if (paramTags.Count > 0 && paramTags [p.Name] == null)
703 Report.Warning (1573, 4, mc.Location, "Parameter '{0}' has no matching param tag in the XML comment for '{1}' (but other parameters do)", mc.Name, p.Name);
709 public static void GenerateEnumDocComment (Enum e, DeclSpace ds)
711 GenerateDocComment (e, ds);
712 foreach (string name in e.ordered_enums) {
713 MemberCore mc = e.GetDefinition (name);
714 GenerateDocComment (mc, e);
720 // Implements XML documentation generation.
722 public class Documentation
724 public Documentation (string xml_output_filename)
726 docfilename = xml_output_filename;
727 XmlDocumentation = new XmlDocument ();
728 XmlDocumentation.PreserveWhitespace = false;
731 private string docfilename;
734 // Used to create element which helps well-formedness checking.
736 public XmlDocument XmlDocumentation;
739 // The output for XML documentation.
741 public XmlWriter XmlCommentOutput;
744 // Stores XmlDocuments that are included in XML documentation.
745 // Keys are included filenames, values are XmlDocuments.
747 public Hashtable StoredDocuments = new Hashtable ();
750 // Stores comments on partial types (should handle uniquely).
751 // Keys are PartialContainers, values are comment strings
752 // (didn't use StringBuilder; usually we have just 2 or more).
754 public IDictionary PartialComments = new ListDictionary ();
757 // Outputs XML documentation comment from tokenized comments.
759 public bool OutputDocComment (string asmfilename)
761 XmlTextWriter w = null;
763 w = new XmlTextWriter (docfilename, null);
765 w.Formatting = Formatting.Indented;
766 w.WriteStartDocument ();
767 w.WriteStartElement ("doc");
768 w.WriteStartElement ("assembly");
769 w.WriteStartElement ("name");
770 w.WriteString (Path.ChangeExtension (asmfilename, null));
771 w.WriteEndElement (); // name
772 w.WriteEndElement (); // assembly
773 w.WriteStartElement ("members");
774 XmlCommentOutput = w;
775 GenerateDocComment ();
776 w.WriteFullEndElement (); // members
777 w.WriteEndElement ();
778 w.WriteWhitespace (Environment.NewLine);
779 w.WriteEndDocument ();
781 } catch (Exception ex) {
782 Report.Error (1569, "Error generating XML documentation file '{0}' ('{1}')", docfilename, ex.Message);
791 // Fixes full type name of each documented types/members up.
793 public void GenerateDocComment ()
795 TypeContainer root = RootContext.Tree.Types;
796 if (root.Interfaces != null)
797 foreach (Interface i in root.Interfaces)
798 DocUtil.GenerateTypeDocComment (i, null);
800 if (root.Types != null)
801 foreach (TypeContainer tc in root.Types)
802 DocUtil.GenerateTypeDocComment (tc, null);
804 if (root.Parts != null) {
805 IDictionary comments = PartialComments;
806 foreach (ClassPart cp in root.Parts) {
807 if (cp.DocComment == null)
813 if (root.Delegates != null)
814 foreach (Delegate d in root.Delegates)
815 DocUtil.GenerateDocComment (d, null);
817 if (root.Enums != null)
818 foreach (Enum e in root.Enums)
819 DocUtil.GenerateEnumDocComment (e, null);
821 IDictionary table = new ListDictionary ();
822 foreach (ClassPart cp in PartialComments.Keys) {
823 table [cp.PartialContainer] += cp.DocComment;
825 foreach (PartialContainer pc in table.Keys) {
826 pc.DocComment = table [pc] as string;
827 DocUtil.GenerateDocComment (pc, null);