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);
479 // Processes "see" or "seealso" elements.
480 // Checks cref attribute.
482 private static void HandleXrefCommon (MemberCore mc,
483 DeclSpace ds, XmlElement xref)
485 string cref = xref.GetAttribute ("cref").Trim (wsChars);
486 // when, XmlReader, "if (cref == null)"
487 if (!xref.HasAttribute ("cref"))
489 if (cref.Length == 0)
490 Report.Warning (1001, 1, mc.Location, "Identifier expected");
491 // ... and continue until CS1584.
493 string signature; // "x:" are stripped
494 string name; // method invokation "(...)" are removed
495 string parameters; // method parameter list
497 // strip 'T:' 'M:' 'F:' 'P:' 'E:' etc.
498 // Here, MS ignores its member kind. No idea why.
499 if (cref.Length > 2 && cref [1] == ':')
500 signature = cref.Substring (2).Trim (wsChars);
504 int parensPos = signature.IndexOf ('(');
505 if (parensPos > 0 && signature [signature.Length - 1] == ')') {
506 name = signature.Substring (0, parensPos).Trim (wsChars);
507 parameters = signature.Substring (parensPos + 1, signature.Length - parensPos - 2);
511 parameters = String.Empty;
514 string identifier = name;
516 if (name.Length > 0 && name [name.Length - 1] == ']') {
517 string tmp = name.Substring (0, name.Length - 1).Trim (wsChars);
518 if (tmp [tmp.Length - 1] == '[')
519 identifier = tmp.Substring (0, tmp.Length - 1).Trim (wsChars);
522 // Check if identifier is valid.
523 // This check is not necessary to mark as error, but
524 // csc specially reports CS1584 for wrong identifiers.
525 foreach (string nameElem in identifier.Split ('.')) {
526 if (!Tokenizer.IsValidIdentifier (nameElem)
527 && nameElem.IndexOf ("operator") < 0) {
528 if (nameElem.EndsWith ("[]") &&
529 Tokenizer.IsValidIdentifier (
531 0, nameElem.Length - 2)))
534 Report.Warning (1584, 1, mc.Location, "XML comment on '{0}' has syntactically incorrect attribute '{1}'", mc.GetSignatureForError (), cref);
535 xref.SetAttribute ("cref", "!:" + signature);
540 // check if parameters are valid
541 Type [] parameterTypes = Type.EmptyTypes;
542 if (parameters.Length > 0) {
543 string [] paramList = parameters.Split (',');
544 ArrayList plist = new ArrayList ();
545 for (int i = 0; i < paramList.Length; i++) {
546 string paramTypeName = paramList [i].Trim (wsChars);
547 Type paramType = FindDocumentedType (mc, paramTypeName, ds, true, cref);
548 if (paramType == null) {
549 Report.Warning (1580, 1, mc.Location, "Invalid type for parameter '{0}' in XML comment cref attribute '{1}'", i + 1, cref);
552 plist.Add (paramType);
554 parameterTypes = plist.ToArray (typeof (Type)) as Type [];
555 StringBuilder sb = new StringBuilder ();
557 for (int i = 0; i < parameterTypes.Length; i++) {
558 Type t = parameterTypes [i];
561 sb.Append (t.FullName.Replace ('+', '.'));
564 parameters = sb.ToString ();
567 Type type = FindDocumentedType (mc, name, ds, true, cref);
569 xref.SetAttribute ("cref", "T:" + type.FullName.Replace ("+", "."));
573 // don't use identifier here. System[] is not alloed.
574 if (Namespace.IsNamespace (name)) {
575 xref.SetAttribute ("cref", "N:" + name);
576 return; // a namespace
579 int period = name.LastIndexOf ('.');
581 string typeName = name.Substring (0, period);
582 string memberName = name.Substring (period + 1);
583 type = FindDocumentedType (mc, typeName, ds, false, cref);
586 MemberInfo mi = FindDocumentedMember (mc, type, memberName, parameterTypes, ds, out warnResult, cref);
590 xref.SetAttribute ("cref", GetMemberDocHead (mi.MemberType) + type.FullName.Replace ("+", ".") + "." + memberName + parameters);
591 return; // a member of a type
597 MemberInfo mi = FindDocumentedMember (mc, ds.TypeBuilder, name, parameterTypes, ds, out warnResult, cref);
601 xref.SetAttribute ("cref", GetMemberDocHead (mi.MemberType) + ds.TypeBuilder.FullName.Replace ("+", ".") + "." + name);
602 return; // local member name
606 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 ());
608 xref.SetAttribute ("cref", "!:" + name);
612 // Get a prefix from member type for XML documentation (used
613 // to formalize cref target name).
615 static string GetMemberDocHead (MemberTypes type)
618 case MemberTypes.Constructor:
619 case MemberTypes.Method:
621 case MemberTypes.Event:
623 case MemberTypes.Field:
625 case MemberTypes.NestedType:
626 case MemberTypes.TypeInfo:
628 case MemberTypes.Property:
637 // Returns a string that represents the signature for this
638 // member which should be used in XML documentation.
640 public static string GetMethodDocCommentName (MethodCore mc, DeclSpace ds)
642 Parameter [] plist = mc.Parameters.FixedParameters;
643 Parameter parr = mc.Parameters.ArrayParameter;
644 string paramSpec = String.Empty;
646 StringBuilder psb = new StringBuilder ();
647 foreach (Parameter p in plist) {
648 psb.Append (psb.Length != 0 ? "," : "(");
649 psb.Append (p.ParameterType.FullName.Replace ("+", "."));
651 paramSpec = psb.ToString ();
654 paramSpec += String.Concat (
655 paramSpec == String.Empty ? "(" : ",",
656 parr.ParameterType.FullName.Replace ("+", "."));
658 if (paramSpec.Length > 0)
661 string name = mc is Constructor ? "#ctor" : mc.Name;
662 string suffix = String.Empty;
663 Operator op = mc as Operator;
665 switch (op.OperatorType) {
666 case Operator.OpType.Implicit:
667 case Operator.OpType.Explicit:
668 suffix = "~" + op.OperatorMethodBuilder.ReturnType.FullName.Replace ('+', '.');
672 return String.Concat (mc.DocCommentHeader, ds.Name, ".", name, paramSpec, suffix);
676 // Raised (and passed an XmlElement that contains the comment)
677 // when GenerateDocComment is writing documentation expectedly.
679 // FIXME: with a few effort, it could be done with XmlReader,
680 // that means removal of DOM use.
682 internal static void OnMethodGenerateDocComment (
683 MethodCore mc, DeclSpace ds, XmlElement el)
685 Hashtable paramTags = new Hashtable ();
686 foreach (XmlElement pelem in el.SelectNodes ("param")) {
688 string xname = pelem.GetAttribute ("name");
690 continue; // really? but MS looks doing so
691 if (xname != "" && mc.Parameters.GetParameterByName (xname, out i) == null)
692 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);
693 else if (paramTags [xname] != null)
694 Report.Warning (1571, 2, mc.Location, "XML comment on '{0}' has a duplicate param tag for '{1}'", mc.Name, xname);
695 paramTags [xname] = xname;
697 Parameter [] plist = mc.Parameters.FixedParameters;
699 foreach (Parameter p in plist) {
700 if (paramTags.Count > 0 && paramTags [p.Name] == null)
701 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);
707 public static void GenerateEnumDocComment (Enum e, DeclSpace ds)
709 GenerateDocComment (e, ds);
710 foreach (string name in e.ordered_enums) {
711 MemberCore mc = e.GetDefinition (name);
712 GenerateDocComment (mc, e);
718 // Implements XML documentation generation.
720 public class Documentation
722 public Documentation (string xml_output_filename)
724 docfilename = xml_output_filename;
725 XmlDocumentation = new XmlDocument ();
726 XmlDocumentation.PreserveWhitespace = false;
729 private string docfilename;
732 // Used to create element which helps well-formedness checking.
734 public XmlDocument XmlDocumentation;
737 // The output for XML documentation.
739 public XmlWriter XmlCommentOutput;
742 // Stores XmlDocuments that are included in XML documentation.
743 // Keys are included filenames, values are XmlDocuments.
745 public Hashtable StoredDocuments = new Hashtable ();
748 // Stores comments on partial types (should handle uniquely).
749 // Keys are PartialContainers, values are comment strings
750 // (didn't use StringBuilder; usually we have just 2 or more).
752 public IDictionary PartialComments = new ListDictionary ();
755 // Outputs XML documentation comment from tokenized comments.
757 public bool OutputDocComment (string asmfilename)
759 XmlTextWriter w = null;
761 w = new XmlTextWriter (docfilename, null);
763 w.Formatting = Formatting.Indented;
764 w.WriteStartDocument ();
765 w.WriteStartElement ("doc");
766 w.WriteStartElement ("assembly");
767 w.WriteStartElement ("name");
768 w.WriteString (Path.ChangeExtension (asmfilename, null));
769 w.WriteEndElement (); // name
770 w.WriteEndElement (); // assembly
771 w.WriteStartElement ("members");
772 XmlCommentOutput = w;
773 GenerateDocComment ();
774 w.WriteFullEndElement (); // members
775 w.WriteEndElement ();
776 w.WriteWhitespace (Environment.NewLine);
777 w.WriteEndDocument ();
779 } catch (Exception ex) {
780 Report.Error (1569, "Error generating XML documentation file '{0}' ('{1}')", docfilename, ex.Message);
789 // Fixes full type name of each documented types/members up.
791 public void GenerateDocComment ()
793 TypeContainer root = RootContext.Tree.Types;
794 if (root.Interfaces != null)
795 foreach (Interface i in root.Interfaces)
796 DocUtil.GenerateTypeDocComment (i, null);
798 if (root.Types != null)
799 foreach (TypeContainer tc in root.Types)
800 DocUtil.GenerateTypeDocComment (tc, null);
802 if (root.Parts != null) {
803 IDictionary comments = PartialComments;
804 foreach (ClassPart cp in root.Parts) {
805 if (cp.DocComment == null)
811 if (root.Delegates != null)
812 foreach (Delegate d in root.Delegates)
813 DocUtil.GenerateDocComment (d, null);
815 if (root.Enums != null)
816 foreach (Enum e in root.Enums)
817 DocUtil.GenerateEnumDocComment (e, null);
819 IDictionary table = new ListDictionary ();
820 foreach (ClassPart cp in PartialComments.Keys) {
821 table [cp.PartialContainer] += cp.DocComment;
823 foreach (PartialContainer pc in table.Keys) {
824 pc.DocComment = table [pc] as string;
825 DocUtil.GenerateDocComment (pc, null);