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 // There are no warnings when the container also
175 // misses documentations.
176 (ds == null || ds.DocComment != null))
178 Report.Warning (1591, 4, mc.Location,
179 "Missing XML comment for publicly visible type or member '{0}'", mc.GetSignatureForError ());
184 // Processes "include" element. Check included file and
185 // embed the document content inside this documentation node.
187 private static void HandleInclude (MemberCore mc, XmlElement el)
189 string file = el.GetAttribute ("file");
190 string path = el.GetAttribute ("path");
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);
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);
200 XmlDocument doc = RootContext.Documentation.StoredDocuments [file] as XmlDocument;
203 doc = new XmlDocument ();
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);
211 bool keepIncludeNode = false;
214 XmlNodeList nl = doc.SelectNodes (path);
216 el.ParentNode.InsertBefore (el.OwnerDocument.CreateComment (" No matching elements were found for the include tag embedded here. "), el);
218 keepIncludeNode = true;
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);
227 if (!keepIncludeNode)
228 el.ParentNode.RemoveChild (el);
233 // Handles <see> elements.
235 private static void HandleSee (MemberCore mc,
236 DeclSpace ds, XmlElement see)
238 HandleXrefCommon (mc, ds, see);
242 // Handles <seealso> elements.
244 private static void HandleSeeAlso (MemberCore mc,
245 DeclSpace ds, XmlElement seealso)
247 HandleXrefCommon (mc, ds, seealso);
251 // Handles <exception> elements.
253 private static void HandleException (MemberCore mc,
254 DeclSpace ds, XmlElement seealso)
256 HandleXrefCommon (mc, ds, seealso);
259 static readonly char [] wsChars =
260 new char [] {' ', '\t', '\n', '\r'};
263 // returns a full runtime type name from a name which might
264 // be C# specific type name.
266 private static Type FindDocumentedType (MemberCore mc,
267 string name, DeclSpace ds, bool allowAlias)
269 bool isArray = false;
270 string identifier = name;
271 if (name [name.Length - 1] == ']') {
272 string tmp = name.Substring (0, name.Length - 1).Trim (wsChars);
273 if (tmp [tmp.Length - 1] == '[') {
274 identifier = tmp.Substring (0, tmp.Length - 1).Trim (wsChars);
278 Type t = FindDocumentedTypeNonArray (mc, identifier,
280 if (t != null && isArray)
281 t = Array.CreateInstance (t, 0).GetType ();
285 private static Type FindDocumentedTypeNonArray (MemberCore mc,
286 string identifier, DeclSpace ds, bool allowAlias)
288 switch (identifier) {
292 return typeof (uint);
294 return typeof (short);
296 return typeof (ushort);
298 return typeof (long);
300 return typeof (ulong);
302 return typeof (float);
304 return typeof (double);
306 return typeof (char);
308 return typeof (decimal);
310 return typeof (byte);
312 return typeof (sbyte);
314 return typeof (object);
316 return typeof (bool);
318 return typeof (string);
320 return typeof (void);
323 IAlias alias = ds.LookupAlias (identifier);
325 identifier = alias.Name;
327 Type t = ds.FindType (mc.Location, identifier);
329 t = TypeManager.LookupTypeDirect (identifier);
334 // Returns a MemberInfo that is referenced in XML documentation
335 // (by "see" or "seealso" elements).
337 private static MemberInfo FindDocumentedMember (MemberCore mc,
338 Type type, string memberName, Type [] paramList,
339 DeclSpace ds, out int warningType, string cref)
342 MethodSignature msig = new MethodSignature (memberName, null, paramList);
343 MemberInfo [] mis = type.FindMembers (
345 BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance,
346 MethodSignature.method_signature_filter,
351 if (paramList.Length == 0) {
352 // search for fields/events etc.
353 mis = type.FindMembers (
355 BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance,
358 return (mis.Length > 0) ? mis [0] : null;
361 // search for operators (whose parameters exactly
362 // matches with the list) and possibly report CS1581.
364 string returnTypeName = null;
365 if (memberName.StartsWith ("implicit operator ")) {
366 oper = "op_Implicit";
367 returnTypeName = memberName.Substring (18).Trim (wsChars);
369 else if (memberName.StartsWith ("explicit operator ")) {
370 oper = "op_Explicit";
371 returnTypeName = memberName.Substring (18).Trim (wsChars);
373 else if (memberName.StartsWith ("operator ")) {
374 oper = memberName.Substring (9).Trim (wsChars);
376 // either unary or binary
378 oper = paramList.Length == 2 ?
379 Binary.oper_names [(int) Binary.Operator.Addition] :
380 Unary.oper_names [(int) Unary.Operator.UnaryPlus];
383 oper = paramList.Length == 2 ?
384 Binary.oper_names [(int) Binary.Operator.Subtraction] :
385 Unary.oper_names [(int) Unary.Operator.UnaryNegation];
389 oper = Unary.oper_names [(int) Unary.Operator.LogicalNot]; break;
391 oper = Unary.oper_names [(int) Unary.Operator.OnesComplement]; break;
394 oper = "op_Increment"; break;
396 oper = "op_Decrement"; break;
398 oper = "op_True"; break;
400 oper = "op_False"; break;
403 oper = Binary.oper_names [(int) Binary.Operator.Multiply]; break;
405 oper = Binary.oper_names [(int) Binary.Operator.Division]; break;
407 oper = Binary.oper_names [(int) Binary.Operator.Modulus]; break;
409 oper = Binary.oper_names [(int) Binary.Operator.BitwiseAnd]; break;
411 oper = Binary.oper_names [(int) Binary.Operator.BitwiseOr]; break;
413 oper = Binary.oper_names [(int) Binary.Operator.ExclusiveOr]; break;
415 oper = Binary.oper_names [(int) Binary.Operator.LeftShift]; break;
417 oper = Binary.oper_names [(int) Binary.Operator.RightShift]; break;
419 oper = Binary.oper_names [(int) Binary.Operator.Equality]; break;
421 oper = Binary.oper_names [(int) Binary.Operator.Inequality]; break;
423 oper = Binary.oper_names [(int) Binary.Operator.LessThan]; break;
425 oper = Binary.oper_names [(int) Binary.Operator.GreaterThan]; break;
427 oper = Binary.oper_names [(int) Binary.Operator.LessThanOrEqual]; break;
429 oper = Binary.oper_names [(int) Binary.Operator.GreaterThanOrEqual]; break;
432 Report.Warning (1020, 1, mc.Location, "Overloadable {0} operator is expected", paramList.Length == 2 ? "binary" : "unary");
433 Report.Warning (1584, 1, mc.Location, "XML comment on '{0}' has syntactically incorrect attribute '{1}'", mc.GetSignatureForError (), cref);
437 // here we still does not consider return type (to
438 // detect CS1581 or CS1002+CS1584).
439 msig = new MethodSignature (oper, null, paramList);
440 mis = type.FindMembers (
442 BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static,
443 MethodSignature.method_signature_filter,
446 return null; // CS1574
447 MemberInfo mi = mis [0];
448 Type expected = mi is MethodInfo ?
449 ((MethodInfo) mi).ReturnType :
451 ((PropertyInfo) mi).PropertyType :
453 if (returnTypeName != null) {
454 Type returnType = FindDocumentedType (mc, returnTypeName, ds, true);
455 if (returnType == null || returnType != expected) {
457 Report.Warning (1581, 1, mc.Location, "Invalid return type in XML comment cref attribute '{0}'", cref);
464 private static Type [] emptyParamList = new Type [0];
467 // Processes "see" or "seealso" elements.
468 // Checks cref attribute.
470 private static void HandleXrefCommon (MemberCore mc,
471 DeclSpace ds, XmlElement xref)
473 string cref = xref.GetAttribute ("cref").Trim (wsChars);
474 // when, XmlReader, "if (cref == null)"
475 if (!xref.HasAttribute ("cref"))
477 if (cref.Length == 0)
478 Report.Warning (1001, 1, mc.Location, "Identifier expected");
479 // ... and continue until CS1584.
481 string signature; // "x:" are stripped
482 string name; // method invokation "(...)" are removed
483 string identifiers; // array indexer "[]" are removed
484 string parameters; // method parameter list
486 // strip 'T:' 'M:' 'F:' 'P:' 'E:' etc.
487 // Here, MS ignores its member kind. No idea why.
488 if (cref.Length > 2 && cref [1] == ':')
489 signature = cref.Substring (2).Trim (wsChars);
493 int parensPos = signature.IndexOf ('(');
494 if (parensPos > 0 && signature [signature.Length - 1] == ')') {
495 name = signature.Substring (0, parensPos).Trim (wsChars);
496 parameters = signature.Substring (parensPos + 1, signature.Length - parensPos - 2);
500 parameters = String.Empty;
503 string identifier = name;
505 if (name.Length > 0 && name [name.Length - 1] == ']') {
506 string tmp = name.Substring (0, name.Length - 1).Trim (wsChars);
507 if (tmp [tmp.Length - 1] == '[')
508 identifier = tmp.Substring (0, tmp.Length - 1).Trim (wsChars);
511 // Check if identifier is valid.
512 // This check is not necessary to mark as error, but
513 // csc specially reports CS1584 for wrong identifiers.
514 foreach (string nameElem in identifier.Split ('.')) {
515 if (!Tokenizer.IsValidIdentifier (nameElem)
516 && nameElem.IndexOf ("operator") < 0) {
517 if (nameElem.EndsWith ("[]") &&
518 Tokenizer.IsValidIdentifier (
520 0, nameElem.Length - 2)))
523 Report.Warning (1584, 1, mc.Location, "XML comment on '{0}' has syntactically incorrect attribute '{1}'", mc.GetSignatureForError (), cref);
524 xref.SetAttribute ("cref", "!:" + signature);
529 // check if parameters are valid
530 Type [] parameterTypes = emptyParamList;
531 if (parameters.Length > 0) {
532 string [] paramList = parameters.Split (',');
533 ArrayList plist = new ArrayList ();
534 for (int i = 0; i < paramList.Length; i++) {
535 string paramTypeName = paramList [i].Trim (wsChars);
536 Type paramType = FindDocumentedType (mc, paramTypeName, ds, true);
537 if (paramType == null) {
538 Report.Warning (1580, 1, mc.Location, "Invalid type for parameter '{0}' in XML comment cref attribute '{1}'", i + 1, cref);
541 plist.Add (paramType);
543 parameterTypes = plist.ToArray (typeof (Type)) as Type [];
544 StringBuilder sb = new StringBuilder ();
546 for (int i = 0; i < parameterTypes.Length; i++) {
547 Type t = parameterTypes [i];
550 sb.Append (t.FullName.Replace ('+', '.'));
553 parameters = sb.ToString ();
556 Type type = FindDocumentedType (mc, name, ds, true);
558 xref.SetAttribute ("cref", "T:" + type.FullName.Replace ("+", "."));
562 // don't use identifier here. System[] is not alloed.
563 if (Namespace.IsNamespace (name)) {
564 xref.SetAttribute ("cref", "N:" + name);
565 return; // a namespace
568 int period = name.LastIndexOf ('.');
570 string typeName = name.Substring (0, period);
571 string memberName = name.Substring (period + 1);
572 type = FindDocumentedType (mc, typeName, ds, false);
575 MemberInfo mi = FindDocumentedMember (mc, type, memberName, parameterTypes, ds, out warnResult, cref);
579 xref.SetAttribute ("cref", GetMemberDocHead (mi.MemberType) + type.FullName.Replace ("+", ".") + "." + memberName + parameters);
580 return; // a member of a type
586 MemberInfo mi = FindDocumentedMember (mc, ds.TypeBuilder, name, parameterTypes, ds, out warnResult, cref);
590 xref.SetAttribute ("cref", GetMemberDocHead (mi.MemberType) + ds.TypeBuilder.FullName.Replace ("+", ".") + "." + name);
591 return; // local member name
595 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 ());
597 xref.SetAttribute ("cref", "!:" + name);
601 // Get a prefix from member type for XML documentation (used
602 // to formalize cref target name).
604 static string GetMemberDocHead (MemberTypes type)
607 case MemberTypes.Constructor:
608 case MemberTypes.Method:
610 case MemberTypes.Event:
612 case MemberTypes.Field:
614 case MemberTypes.NestedType:
615 case MemberTypes.TypeInfo:
617 case MemberTypes.Property:
626 // Returns a string that represents the signature for this
627 // member which should be used in XML documentation.
629 public static string GetMethodDocCommentName (MethodCore mc, DeclSpace ds)
631 Parameter [] plist = mc.Parameters.FixedParameters;
632 Parameter parr = mc.Parameters.ArrayParameter;
633 string paramSpec = String.Empty;
635 StringBuilder psb = new StringBuilder ();
636 foreach (Parameter p in plist) {
637 psb.Append (psb.Length != 0 ? "," : "(");
638 psb.Append (p.ParameterType.FullName.Replace ("+", "."));
640 paramSpec = psb.ToString ();
643 paramSpec += String.Concat (
644 paramSpec == String.Empty ? "(" : ",",
645 parr.ParameterType.FullName.Replace ("+", "."));
647 if (paramSpec.Length > 0)
650 string name = mc is Constructor ? "#ctor" : mc.Name;
651 return String.Concat (mc.DocCommentHeader, ds.Name, ".", name, paramSpec);
655 // Raised (and passed an XmlElement that contains the comment)
656 // when GenerateDocComment is writing documentation expectedly.
658 // FIXME: with a few effort, it could be done with XmlReader,
659 // that means removal of DOM use.
661 internal static void OnMethodGenerateDocComment (
662 MethodCore mc, DeclSpace ds, XmlElement el)
664 Hashtable paramTags = new Hashtable ();
665 foreach (XmlElement pelem in el.SelectNodes ("param")) {
667 string xname = pelem.GetAttribute ("name");
669 continue; // really? but MS looks doing so
670 if (xname != "" && mc.Parameters.GetParameterByName (xname, out i) == null)
671 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);
672 else if (paramTags [xname] != null)
673 Report.Warning (1571, 2, mc.Location, "XML comment on '{0}' has a duplicate param tag for '{1}'", mc.Name, xname);
674 paramTags [xname] = xname;
676 Parameter [] plist = mc.Parameters.FixedParameters;
677 Parameter parr = mc.Parameters.ArrayParameter;
679 foreach (Parameter p in plist) {
680 if (paramTags.Count > 0 && paramTags [p.Name] == null)
681 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);
687 public static void GenerateEnumDocComment (Enum e, DeclSpace ds)
689 GenerateDocComment (e, ds);
690 foreach (string name in e.ordered_enums) {
691 MemberCore mc = e.GetDefinition (name);
692 GenerateDocComment (mc, e);
698 // Implements XML documentation generation.
700 public class Documentation
702 public Documentation (string xml_output_filename)
704 docfilename = xml_output_filename;
705 XmlDocumentation = new XmlDocument ();
706 XmlDocumentation.PreserveWhitespace = false;
709 private string docfilename;
712 // Used to create element which helps well-formedness checking.
714 public XmlDocument XmlDocumentation;
717 // The output for XML documentation.
719 public XmlWriter XmlCommentOutput;
722 // Stores XmlDocuments that are included in XML documentation.
723 // Keys are included filenames, values are XmlDocuments.
725 public Hashtable StoredDocuments = new Hashtable ();
728 // Stores comments on partial types (should handle uniquely).
729 // Keys are PartialContainers, values are comment strings
730 // (didn't use StringBuilder; usually we have just 2 or more).
732 public IDictionary PartialComments = new ListDictionary ();
735 // Outputs XML documentation comment from tokenized comments.
737 public bool OutputDocComment (string asmfilename)
739 XmlTextWriter w = null;
741 w = new XmlTextWriter (docfilename, null);
743 w.Formatting = Formatting.Indented;
744 w.WriteStartDocument ();
745 w.WriteStartElement ("doc");
746 w.WriteStartElement ("assembly");
747 w.WriteStartElement ("name");
748 w.WriteString (Path.ChangeExtension (asmfilename, null));
749 w.WriteEndElement (); // name
750 w.WriteEndElement (); // assembly
751 w.WriteStartElement ("members");
752 XmlCommentOutput = w;
753 GenerateDocComment ();
754 w.WriteFullEndElement (); // members
755 w.WriteEndElement ();
756 w.WriteWhitespace (Environment.NewLine);
757 w.WriteEndDocument ();
759 } catch (Exception ex) {
760 Report.Error (1569, "Error generating XML documentation file '{0}' ('{1}')", docfilename, ex.Message);
769 // Fixes full type name of each documented types/members up.
771 public void GenerateDocComment ()
773 TypeContainer root = RootContext.Tree.Types;
774 if (root.Interfaces != null)
775 foreach (Interface i in root.Interfaces)
776 DocUtil.GenerateTypeDocComment (i, null);
778 if (root.Types != null)
779 foreach (TypeContainer tc in root.Types)
780 DocUtil.GenerateTypeDocComment (tc, null);
782 if (root.Parts != null) {
783 IDictionary comments = PartialComments;
784 foreach (ClassPart cp in root.Parts) {
785 if (cp.DocComment == null)
791 if (root.Delegates != null)
792 foreach (Delegate d in root.Delegates)
793 DocUtil.GenerateDocComment (d, null);
795 if (root.Enums != null)
796 foreach (Enum e in root.Enums)
797 DocUtil.GenerateEnumDocComment (e, null);
799 IDictionary table = new ListDictionary ();
800 foreach (ClassPart cp in PartialComments.Keys) {
801 table [cp.PartialContainer] += cp.DocComment;
803 foreach (PartialContainer pc in table.Keys) {
804 pc.DocComment = table [pc] as string;
805 DocUtil.GenerateDocComment (pc, null);