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 #if ! BOOTSTRAP_WITH_OLDLIB
15 using System.Collections;
16 using System.Collections.Specialized;
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;
27 using Mono.CompilerServices.SymbolWriter;
29 namespace Mono.CSharp {
32 // Support class for XML documentation.
39 // Generates xml doc comments (if any), and if required,
40 // handle warning report.
42 internal static void GenerateTypeDocComment (TypeContainer t,
45 GenerateDocComment (t, ds);
47 if (t.DefaultStaticConstructor != null)
48 t.DefaultStaticConstructor.GenerateDocComment (t);
50 if (t.InstanceConstructors != null)
51 foreach (Constructor c in t.InstanceConstructors)
52 c.GenerateDocComment (t);
55 foreach (TypeContainer tc in t.Types)
56 tc.GenerateDocComment (t);
58 if (t.Parts != null) {
59 IDictionary comments = RootContext.Documentation.PartialComments;
60 foreach (ClassPart cp in t.Parts) {
61 if (cp.DocComment == null)
68 foreach (Enum en in t.Enums)
69 en.GenerateDocComment (t);
71 if (t.Constants != null)
72 foreach (Const c in t.Constants)
73 c.GenerateDocComment (t);
76 foreach (Field f in t.Fields)
77 f.GenerateDocComment (t);
80 foreach (Event e in t.Events)
81 e.GenerateDocComment (t);
83 if (t.Indexers != null)
84 foreach (Indexer ix in t.Indexers)
85 ix.GenerateDocComment (t);
87 if (t.Properties != null)
88 foreach (Property p in t.Properties)
89 p.GenerateDocComment (t);
91 if (t.Methods != null)
92 foreach (Method m in t.Methods)
93 m.GenerateDocComment (t);
95 if (t.Operators != null)
96 foreach (Operator o in t.Operators)
97 o.GenerateDocComment (t);
101 private static readonly string lineHead =
102 Environment.NewLine + " ";
104 private static XmlNode GetDocCommentNode (MemberCore mc,
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;
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.
123 normalized.Split ('\n');
125 for (int i = 0; i < split.Length; i++) {
126 string s = split [i].TrimEnd ();
130 el.InnerXml = lineHead + String.Join (
131 lineHead, split, 0, j);
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));
141 // Generates xml doc comments (if any), and if required,
142 // handle warning report.
144 internal static void GenerateDocComment (MemberCore mc,
147 if (mc.DocComment != null) {
148 string name = mc.GetDocCommentName (ds);
150 XmlNode n = GetDocCommentNode (mc, name);
152 XmlElement el = n as XmlElement;
154 mc.OnGenerateDocComment (ds, el);
156 // FIXME: it could be done with XmlReader
157 foreach (XmlElement inc in n.SelectNodes (".//include"))
158 HandleInclude (mc, inc);
160 // FIXME: it could be done with XmlReader
161 DeclSpace dsTarget = mc as DeclSpace;
162 if (dsTarget == null)
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);
173 n.WriteTo (RootContext.Documentation.XmlCommentOutput);
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 ());
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, string name, DeclSpace ds, string cref)
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);
277 Type t = FindDocumentedTypeNonArray (mc, identifier, ds, 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, string cref)
286 switch (identifier) {
290 return typeof (uint);
292 return typeof (short);
294 return typeof (ushort);
296 return typeof (long);
298 return typeof (ulong);
300 return typeof (float);
302 return typeof (double);
304 return typeof (char);
306 return typeof (decimal);
308 return typeof (byte);
310 return typeof (sbyte);
312 return typeof (object);
314 return typeof (bool);
316 return typeof (string);
318 return typeof (void);
320 FullNamedExpression e = ds.FindType (mc.Location, identifier);
322 if (!(e is TypeExpr))
324 return ((TypeExpr) e).ResolveType (ds.EmitContext);
326 int index = identifier.LastIndexOf ('.');
330 Type parent = FindDocumentedType (mc, identifier.Substring (0, index), ds, cref);
333 return FindDocumentedMember (mc, parent,
334 identifier.Substring (index + 1),
336 ds, out warn, cref) as Type;
340 // Returns a MemberInfo that is referenced in XML documentation
341 // (by "see" or "seealso" elements).
343 private static MemberInfo FindDocumentedMember (MemberCore mc,
344 Type type, string memberName, Type [] paramList,
345 DeclSpace ds, out int warningType, string cref)
348 MethodSignature msig = new MethodSignature (memberName, null, paramList);
349 MemberInfo [] mis = type.FindMembers (
351 BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance,
352 MethodSignature.method_signature_filter,
357 if (paramList.Length == 0) {
358 // search for fields/events etc.
359 mis = type.FindMembers (
361 BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance,
364 return (mis.Length > 0) ? mis [0] : null;
367 // search for operators (whose parameters exactly
368 // matches with the list) and possibly report CS1581.
370 string returnTypeName = null;
371 if (memberName.StartsWith ("implicit operator ")) {
372 oper = "op_Implicit";
373 returnTypeName = memberName.Substring (18).Trim (wsChars);
375 else if (memberName.StartsWith ("explicit operator ")) {
376 oper = "op_Explicit";
377 returnTypeName = memberName.Substring (18).Trim (wsChars);
379 else if (memberName.StartsWith ("operator ")) {
380 oper = memberName.Substring (9).Trim (wsChars);
382 // either unary or binary
384 oper = paramList.Length == 2 ?
385 Binary.oper_names [(int) Binary.Operator.Addition] :
386 Unary.oper_names [(int) Unary.Operator.UnaryPlus];
389 oper = paramList.Length == 2 ?
390 Binary.oper_names [(int) Binary.Operator.Subtraction] :
391 Unary.oper_names [(int) Unary.Operator.UnaryNegation];
395 oper = Unary.oper_names [(int) Unary.Operator.LogicalNot]; break;
397 oper = Unary.oper_names [(int) Unary.Operator.OnesComplement]; break;
400 oper = "op_Increment"; break;
402 oper = "op_Decrement"; break;
404 oper = "op_True"; break;
406 oper = "op_False"; break;
409 oper = Binary.oper_names [(int) Binary.Operator.Multiply]; break;
411 oper = Binary.oper_names [(int) Binary.Operator.Division]; break;
413 oper = Binary.oper_names [(int) Binary.Operator.Modulus]; break;
415 oper = Binary.oper_names [(int) Binary.Operator.BitwiseAnd]; break;
417 oper = Binary.oper_names [(int) Binary.Operator.BitwiseOr]; break;
419 oper = Binary.oper_names [(int) Binary.Operator.ExclusiveOr]; break;
421 oper = Binary.oper_names [(int) Binary.Operator.LeftShift]; break;
423 oper = Binary.oper_names [(int) Binary.Operator.RightShift]; break;
425 oper = Binary.oper_names [(int) Binary.Operator.Equality]; break;
427 oper = Binary.oper_names [(int) Binary.Operator.Inequality]; break;
429 oper = Binary.oper_names [(int) Binary.Operator.LessThan]; break;
431 oper = Binary.oper_names [(int) Binary.Operator.GreaterThan]; break;
433 oper = Binary.oper_names [(int) Binary.Operator.LessThanOrEqual]; break;
435 oper = Binary.oper_names [(int) Binary.Operator.GreaterThanOrEqual]; break;
438 Report.Warning (1020, 1, mc.Location, "Overloadable {0} operator is expected", paramList.Length == 2 ? "binary" : "unary");
439 Report.Warning (1584, 1, mc.Location, "XML comment on '{0}' has syntactically incorrect attribute '{1}'", mc.GetSignatureForError (), cref);
443 // here we still does not consider return type (to
444 // detect CS1581 or CS1002+CS1584).
445 msig = new MethodSignature (oper, null, paramList);
446 mis = type.FindMembers (
448 BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static,
449 MethodSignature.method_signature_filter,
452 return null; // CS1574
453 MemberInfo mi = mis [0];
454 Type expected = mi is MethodInfo ?
455 ((MethodInfo) mi).ReturnType :
457 ((PropertyInfo) mi).PropertyType :
459 if (returnTypeName != null) {
460 Type returnType = FindDocumentedType (mc, returnTypeName, ds, cref);
461 if (returnType == null || returnType != expected) {
463 Report.Warning (1581, 1, mc.Location, "Invalid return type in XML comment cref attribute '{0}'", cref);
470 private static Type [] emptyParamList = new Type [0];
473 // Processes "see" or "seealso" elements.
474 // Checks cref attribute.
476 private static void HandleXrefCommon (MemberCore mc,
477 DeclSpace ds, XmlElement xref)
479 string cref = xref.GetAttribute ("cref").Trim (wsChars);
480 // when, XmlReader, "if (cref == null)"
481 if (!xref.HasAttribute ("cref"))
483 if (cref.Length == 0)
484 Report.Warning (1001, 1, mc.Location, "Identifier expected");
485 // ... and continue until CS1584.
487 string signature; // "x:" are stripped
488 string name; // method invokation "(...)" are removed
489 string parameters; // method parameter list
491 // strip 'T:' 'M:' 'F:' 'P:' 'E:' etc.
492 // Here, MS ignores its member kind. No idea why.
493 if (cref.Length > 2 && cref [1] == ':')
494 signature = cref.Substring (2).Trim (wsChars);
498 int parensPos = signature.IndexOf ('(');
499 if (parensPos > 0 && signature [signature.Length - 1] == ')') {
500 name = signature.Substring (0, parensPos).Trim (wsChars);
501 parameters = signature.Substring (parensPos + 1, signature.Length - parensPos - 2);
505 parameters = String.Empty;
508 string identifier = name;
510 if (name.Length > 0 && name [name.Length - 1] == ']') {
511 string tmp = name.Substring (0, name.Length - 1).Trim (wsChars);
512 if (tmp [tmp.Length - 1] == '[')
513 identifier = tmp.Substring (0, tmp.Length - 1).Trim (wsChars);
516 // Check if identifier is valid.
517 // This check is not necessary to mark as error, but
518 // csc specially reports CS1584 for wrong identifiers.
519 foreach (string nameElem in identifier.Split ('.')) {
520 if (!Tokenizer.IsValidIdentifier (nameElem)
521 && nameElem.IndexOf ("operator") < 0) {
522 if (nameElem.EndsWith ("[]") &&
523 Tokenizer.IsValidIdentifier (
525 0, nameElem.Length - 2)))
528 Report.Warning (1584, 1, mc.Location, "XML comment on '{0}' has syntactically incorrect attribute '{1}'", mc.GetSignatureForError (), cref);
529 xref.SetAttribute ("cref", "!:" + signature);
534 // check if parameters are valid
535 Type [] parameterTypes = emptyParamList;
536 if (parameters.Length > 0) {
537 string [] paramList = parameters.Split (',');
538 ArrayList plist = new ArrayList ();
539 for (int i = 0; i < paramList.Length; i++) {
540 string paramTypeName = paramList [i].Trim (wsChars);
541 Type paramType = FindDocumentedType (mc, paramTypeName, ds, cref);
542 if (paramType == null) {
543 Report.Warning (1580, 1, mc.Location, "Invalid type for parameter '{0}' in XML comment cref attribute '{1}'", i + 1, cref);
546 plist.Add (paramType);
548 parameterTypes = plist.ToArray (typeof (Type)) as Type [];
549 StringBuilder sb = new StringBuilder ();
551 for (int i = 0; i < parameterTypes.Length; i++) {
552 Type t = parameterTypes [i];
555 sb.Append (t.FullName.Replace ('+', '.'));
558 parameters = sb.ToString ();
561 Type type = FindDocumentedType (mc, name, ds, cref);
563 xref.SetAttribute ("cref", "T:" + type.FullName.Replace ("+", "."));
567 // don't use identifier here. System[] is not alloed.
568 if (Namespace.IsNamespace (name)) {
569 xref.SetAttribute ("cref", "N:" + name);
570 return; // a namespace
573 int period = name.LastIndexOf ('.');
575 string typeName = name.Substring (0, period);
576 string memberName = name.Substring (period + 1);
577 type = FindDocumentedType (mc, typeName, ds, cref);
580 MemberInfo mi = FindDocumentedMember (mc, type, memberName, parameterTypes, ds, out warnResult, cref);
584 xref.SetAttribute ("cref", GetMemberDocHead (mi.MemberType) + type.FullName.Replace ("+", ".") + "." + memberName + parameters);
585 return; // a member of a type
591 MemberInfo mi = FindDocumentedMember (mc, ds.TypeBuilder, name, parameterTypes, ds, out warnResult, cref);
595 xref.SetAttribute ("cref", GetMemberDocHead (mi.MemberType) + ds.TypeBuilder.FullName.Replace ("+", ".") + "." + name);
596 return; // local member name
600 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 ());
602 xref.SetAttribute ("cref", "!:" + name);
606 // Get a prefix from member type for XML documentation (used
607 // to formalize cref target name).
609 static string GetMemberDocHead (MemberTypes type)
612 case MemberTypes.Constructor:
613 case MemberTypes.Method:
615 case MemberTypes.Event:
617 case MemberTypes.Field:
619 case MemberTypes.NestedType:
620 case MemberTypes.TypeInfo:
622 case MemberTypes.Property:
631 // Returns a string that represents the signature for this
632 // member which should be used in XML documentation.
634 public static string GetMethodDocCommentName (MethodCore mc, DeclSpace ds)
636 Parameter [] plist = mc.Parameters.FixedParameters;
637 Parameter parr = mc.Parameters.ArrayParameter;
638 string paramSpec = String.Empty;
640 StringBuilder psb = new StringBuilder ();
641 foreach (Parameter p in plist) {
642 psb.Append (psb.Length != 0 ? "," : "(");
643 psb.Append (p.ParameterType.FullName.Replace ("+", "."));
645 paramSpec = psb.ToString ();
648 paramSpec += String.Concat (
649 paramSpec == String.Empty ? "(" : ",",
650 parr.ParameterType.FullName.Replace ("+", "."));
652 if (paramSpec.Length > 0)
655 string name = mc is Constructor ? "#ctor" : mc.Name;
656 string suffix = String.Empty;
657 Operator op = mc as Operator;
659 switch (op.OperatorType) {
660 case Operator.OpType.Implicit:
661 case Operator.OpType.Explicit:
662 suffix = "~" + op.OperatorMethodBuilder.ReturnType.FullName.Replace ('+', '.');
666 return String.Concat (mc.DocCommentHeader, ds.Name, ".", name, paramSpec, suffix);
670 // Raised (and passed an XmlElement that contains the comment)
671 // when GenerateDocComment is writing documentation expectedly.
673 // FIXME: with a few effort, it could be done with XmlReader,
674 // that means removal of DOM use.
676 internal static void OnMethodGenerateDocComment (
677 MethodCore mc, DeclSpace ds, XmlElement el)
679 Hashtable paramTags = new Hashtable ();
680 foreach (XmlElement pelem in el.SelectNodes ("param")) {
682 string xname = pelem.GetAttribute ("name");
684 continue; // really? but MS looks doing so
685 if (xname != "" && mc.Parameters.GetParameterByName (xname, out i) == null)
686 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);
687 else if (paramTags [xname] != null)
688 Report.Warning (1571, 2, mc.Location, "XML comment on '{0}' has a duplicate param tag for '{1}'", mc.Name, xname);
689 paramTags [xname] = xname;
691 Parameter [] plist = mc.Parameters.FixedParameters;
693 foreach (Parameter p in plist) {
694 if (paramTags.Count > 0 && paramTags [p.Name] == null)
695 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);
701 public static void GenerateEnumDocComment (Enum e, DeclSpace ds)
703 GenerateDocComment (e, ds);
704 foreach (string name in e.ordered_enums) {
705 MemberCore mc = e.GetDefinition (name);
706 GenerateDocComment (mc, e);
712 // Implements XML documentation generation.
714 public class Documentation
716 public Documentation (string xml_output_filename)
718 docfilename = xml_output_filename;
719 XmlDocumentation = new XmlDocument ();
720 XmlDocumentation.PreserveWhitespace = false;
723 private string docfilename;
726 // Used to create element which helps well-formedness checking.
728 public XmlDocument XmlDocumentation;
731 // The output for XML documentation.
733 public XmlWriter XmlCommentOutput;
736 // Stores XmlDocuments that are included in XML documentation.
737 // Keys are included filenames, values are XmlDocuments.
739 public Hashtable StoredDocuments = new Hashtable ();
742 // Stores comments on partial types (should handle uniquely).
743 // Keys are PartialContainers, values are comment strings
744 // (didn't use StringBuilder; usually we have just 2 or more).
746 public IDictionary PartialComments = new ListDictionary ();
749 // Outputs XML documentation comment from tokenized comments.
751 public bool OutputDocComment (string asmfilename)
753 XmlTextWriter w = null;
755 w = new XmlTextWriter (docfilename, null);
757 w.Formatting = Formatting.Indented;
758 w.WriteStartDocument ();
759 w.WriteStartElement ("doc");
760 w.WriteStartElement ("assembly");
761 w.WriteStartElement ("name");
762 w.WriteString (Path.ChangeExtension (asmfilename, null));
763 w.WriteEndElement (); // name
764 w.WriteEndElement (); // assembly
765 w.WriteStartElement ("members");
766 XmlCommentOutput = w;
767 GenerateDocComment ();
768 w.WriteFullEndElement (); // members
769 w.WriteEndElement ();
770 w.WriteWhitespace (Environment.NewLine);
771 w.WriteEndDocument ();
773 } catch (Exception ex) {
774 Report.Error (1569, "Error generating XML documentation file '{0}' ('{1}')", docfilename, ex.Message);
783 // Fixes full type name of each documented types/members up.
785 public void GenerateDocComment ()
787 TypeContainer root = RootContext.Tree.Types;
788 if (root.Interfaces != null)
789 foreach (Interface i in root.Interfaces)
790 DocUtil.GenerateTypeDocComment (i, null);
792 if (root.Types != null)
793 foreach (TypeContainer tc in root.Types)
794 DocUtil.GenerateTypeDocComment (tc, null);
796 if (root.Parts != null) {
797 IDictionary comments = PartialComments;
798 foreach (ClassPart cp in root.Parts) {
799 if (cp.DocComment == null)
805 if (root.Delegates != null)
806 foreach (Delegate d in root.Delegates)
807 DocUtil.GenerateDocComment (d, null);
809 if (root.Enums != null)
810 foreach (Enum e in root.Enums)
811 DocUtil.GenerateEnumDocComment (e, null);
813 IDictionary table = new ListDictionary ();
814 foreach (ClassPart cp in PartialComments.Keys) {
815 table [cp.PartialContainer] += cp.DocComment;
817 foreach (PartialContainer pc in table.Keys) {
818 pc.DocComment = table [pc] as string;
819 DocUtil.GenerateDocComment (pc, null);