2 // The provider for a tree of ECMA documents
5 // Miguel de Icaza (miguel@ximian.com)
6 // Joshua Tauberer (tauberer@for.net)
8 // (C) 2002, 2003 Ximian, Inc.
9 // (C) 2003 Joshua Tauberer.
12 // Should cluster together constructors
15 // Should render attributes on the signature.
16 // Include examples as well.
20 using System.Diagnostics;
21 using System.Reflection;
24 using System.Xml.XPath;
27 using System.Collections;
28 using Monodoc.Lucene.Net.Index;
29 using Monodoc.Lucene.Net.Documents;
31 using Mono.Documentation;
33 using BF = System.Reflection.BindingFlags;
36 // Helper routines to extract information from an Ecma XML document
38 public static class EcmaDoc {
39 public static string GetFullClassName (XmlDocument doc)
41 return doc.SelectSingleNode ("/Type").Attributes ["FullName"].InnerText;
44 public static string GetClassName (XmlDocument doc)
46 return GetDisplayName (doc.SelectSingleNode ("/Type")).Replace ("+", ".");
49 public static string GetDisplayName (XmlNode type)
51 if (type.Attributes ["DisplayName"] != null) {
52 return type.Attributes ["DisplayName"].Value;
54 return type.Attributes ["Name"].Value;
57 public static string GetClassAssembly (XmlDocument doc)
59 return doc.SelectSingleNode ("/Type/AssemblyInfo/AssemblyName").InnerText;
62 public static string GetClassNamespace (XmlDocument doc)
64 string s = doc.SelectSingleNode ("/Type").Attributes ["FullName"].InnerText;
66 return s.Substring (0, s.LastIndexOf ("."));
69 public static string GetTypeKind (XmlDocument doc)
71 XmlNode node = doc.SelectSingleNode ("/Type/Base/BaseTypeName");
74 if (GetFullClassName (doc) == "System.Object")
79 switch (node.InnerText){
81 case "System.Delegate":
82 case "System.MulticastDelegate":
84 case "System.ValueType":
94 // Utility function: converts a fully .NET qualified type name into a C#-looking one
96 public static string ConvertCTSName (string type)
98 if (!type.StartsWith ("System."))
101 if (type.EndsWith ("*"))
102 return ConvertCTSName(type.Substring(0, type.Length - 1)) + "*";
103 if (type.EndsWith ("&"))
104 return ConvertCTSName(type.Substring(0, type.Length - 1)) + "&";
105 if (type.EndsWith ("[]"))
106 return ConvertCTSName(type.Substring(0, type.Length - 2)) + "[]";
109 case "System.Byte": return "byte";
110 case "System.SByte": return "sbyte";
111 case "System.Int16": return "short";
112 case "System.Int32": return "int";
113 case "System.Int64": return "long";
115 case "System.UInt16": return "ushort";
116 case "System.UInt32": return "uint";
117 case "System.UInt64": return "ulong";
119 case "System.Single": return "float";
120 case "System.Double": return "double";
121 case "System.Decimal": return "decimal";
122 case "System.Boolean": return "bool";
123 case "System.Char": return "char";
124 case "System.String": return "string";
126 case "System.Object": return "object";
127 case "System.Void": return "void";
130 if (type.LastIndexOf(".") == 6)
131 return type.Substring(7);
136 internal static string GetNamespaceFile (string dir, string ns)
138 string nsxml = Path.Combine (dir, "ns-" + ns + ".xml");
139 if (!File.Exists (nsxml))
140 nsxml = Path.Combine (dir, ns + ".xml");
144 public static string GetCref (XmlElement member)
146 string typeName = XmlDocUtils.ToEscapedTypeName (member.SelectSingleNode("/Type/@FullName").InnerText);
147 if (member.Name == "Type")
148 return "T:" + typeName;
149 string memberType = member.SelectSingleNode("MemberType").InnerText;
150 switch (memberType) {
152 return "C:" + typeName + MakeArgs(member);
154 return "E:" + typeName + "." + XmlDocUtils.ToEscapedMemberName (member.GetAttribute("MemberName"));
156 return "F:" + typeName + "." + XmlDocUtils.ToEscapedMemberName (member.GetAttribute("MemberName"));
158 string name = "M:" + typeName + "." + XmlDocUtils.ToEscapedMemberName (member.GetAttribute("MemberName")) + MakeArgs(member);
159 if (member.GetAttribute("MemberName") == "op_Implicit" || member.GetAttribute("MemberName") == "op_Explicit")
160 name += "~" + XmlDocUtils.ToTypeName (member.SelectSingleNode("ReturnValue/ReturnType").InnerText, member);
164 return "P:" + typeName + "." + XmlDocUtils.ToEscapedMemberName (member.GetAttribute("MemberName")) + MakeArgs(member);
166 throw new NotSupportedException ("MemberType '" + memberType + "' is not supported.");
170 private static string MakeArgs (XmlElement member)
172 XmlNodeList parameters = member.SelectNodes ("Parameters/Parameter");
173 if (parameters.Count == 0)
175 StringBuilder args = new StringBuilder ();
177 args.Append (XmlDocUtils.ToTypeName (parameters [0].Attributes ["Type"].Value, member));
178 for (int i = 1; i < parameters.Count; ++i) {
180 args.Append (XmlDocUtils.ToTypeName (parameters [i].Attributes ["Type"].Value, member));
183 return args.ToString ();
188 // The Ecma documentation provider:
190 // It populates a tree with contents during the help assembly
192 public class EcmaProvider : Provider {
193 ArrayList/*<string>*/ asm_dirs = new ArrayList ();
195 public EcmaProvider ()
199 public EcmaProvider (string base_directory)
201 AddDirectory (base_directory);
204 public void AddDirectory (string directory)
206 if (!Directory.Exists (directory))
207 throw new FileNotFoundException (String.Format ("The directory `{0}' does not exist", directory));
208 asm_dirs.Add (directory);
211 public override void PopulateTree (Tree tree)
213 ArrayList ns_dirs = new ArrayList ();
214 foreach (string asm in asm_dirs) {
215 ns_dirs.AddRange (Directory.GetDirectories (asm));
218 foreach (string ns in ns_dirs){
219 string basedir = Directory.GetParent (ns).FullName;
220 string [] files = Directory.GetFiles (ns);
224 Hashtable nsnodes = new Hashtable();
226 foreach (string file in files){
227 if (!file.EndsWith (".xml"))
230 if (ns_node == null) {
231 tn = Path.GetFileName (ns);
232 tree.HelpSource.Message (TraceLevel.Info, "Processing namespace {0}", tn);
233 ns_node = tree.LookupNode (tn, "N:" + tn);
234 string ns_summary_file = EcmaDoc.GetNamespaceFile (basedir, tn);
236 nsnodes[ns_node] = nsnodes;
238 if (File.Exists (ns_summary_file)) {
239 XmlDocument nsSummaryFile = new XmlDocument ();
240 nsSummaryFile.Load (ns_summary_file);
241 namespace_realpath [tn] = ns_summary_file;
243 XmlNode ns_summary = nsSummaryFile.SelectSingleNode ("Namespace/Docs/summary");
244 if (ns_summary != null && ns_summary.InnerText.Trim () != "To be added." && ns_summary.InnerText != "") {
245 namespace_summaries [tn] = ns_summary;
246 namespace_remarks [tn] = nsSummaryFile.SelectSingleNode ("Namespace/Docs/remarks");
249 } else if (!namespace_summaries.ContainsKey (tn)) {
250 namespace_summaries [tn] = null;
251 namespace_remarks [tn] = null;
254 tree.HelpSource.Message (TraceLevel.Verbose, " Processing input file {0}", Path.GetFileName (file));
256 PopulateClass (tree, tn, ns_node, file);
259 // Sort the list of types in each namespace
260 foreach (Node ns_node2 in nsnodes.Keys)
266 struct TypeInfo : IComparable {
267 public string type_assembly;
268 public string type_name;
269 public string type_full;
270 public string type_kind;
271 public XmlNode type_doc;
273 public TypeInfo (string k, string a, string f, string s, XmlNode n)
282 public int CompareTo (object b)
285 TypeInfo nb = (TypeInfo) b;
287 return String.Compare (na.type_full, nb.type_full);
292 // Packs a file with the summary data
294 public override void CloseTree (HelpSource hs, Tree tree)
296 foreach (DictionaryEntry de in class_summaries){
297 XmlDocument doc = new XmlDocument ();
298 string ns = (string) de.Key;
300 ArrayList list = (ArrayList) de.Value;
303 XmlElement elements = doc.CreateElement ("elements");
304 doc.AppendChild (elements);
306 if (namespace_summaries [ns] != null)
307 elements.AppendChild (doc.ImportNode ((XmlNode)namespace_summaries [ns],true));
309 elements.AppendChild (doc.CreateElement("summary"));
311 if (namespace_remarks [ns] != null)
312 elements.AppendChild (doc.ImportNode ((XmlNode)namespace_remarks [ns],true));
314 elements.AppendChild (doc.CreateElement("remarks"));
316 hs.Message (TraceLevel.Info, "Have {0} elements in the {1}", list.Count, ns);
317 foreach (TypeInfo p in list){
320 switch (p.type_kind){
322 e = doc.CreateElement ("class");
326 e = doc.CreateElement ("enum");
330 e = doc.CreateElement ("struct");
334 e = doc.CreateElement ("delegate");
338 e = doc.CreateElement ("interface");
342 e.SetAttribute ("name", p.type_name);
343 e.SetAttribute ("fullname", p.type_full);
344 e.SetAttribute ("assembly", p.type_assembly);
345 XmlNode copy = doc.ImportNode (p.type_doc, true);
346 e.AppendChild (copy);
347 elements.AppendChild (e);
349 hs.PackXml ("xml.summary." + ns, doc,(string) namespace_realpath[ns]);
353 XmlDocument nsSummary = new XmlDocument ();
354 XmlElement root = nsSummary.CreateElement ("elements");
355 nsSummary.AppendChild (root);
357 foreach (DictionaryEntry de in namespace_summaries) {
358 XmlNode n = (XmlNode)de.Value;
359 XmlElement summary = nsSummary.CreateElement ("namespace");
360 summary.SetAttribute ("ns", (string)de.Key);
361 root.AppendChild (summary);
363 summary.AppendChild (nsSummary.ImportNode (n,true));
365 summary.AppendChild (nsSummary.CreateElement("summary"));
367 tree.HelpSource.PackXml ("mastersummary.xml", nsSummary, null);
368 AddExtensionMethods (tree);
371 void AddExtensionMethods (Tree tree)
373 XmlDocument extensions = null;
376 foreach (string asm in asm_dirs) {
377 string overview_file = Path.Combine (asm, "index.xml");
378 if (File.Exists (overview_file)) {
379 XmlDocument overview = new XmlDocument ();
380 overview.Load (overview_file);
381 XmlNodeList e = overview.SelectNodes ("/Overview/ExtensionMethods/*");
383 if (extensions == null) {
384 extensions = new XmlDocument ();
385 root = extensions.CreateElement ("ExtensionMethods");
386 extensions.AppendChild (root);
388 foreach (XmlNode n in e) {
390 root.AppendChild (extensions.ImportNode (n, true));
395 if (extensions != null) {
396 tree.HelpSource.Message (TraceLevel.Info, "Have {0} extension methods", numMethods);
397 tree.HelpSource.PackXml ("ExtensionMethods.xml", extensions, "ExtensionMethods.xml");
401 Hashtable class_summaries = new Hashtable ();
402 Hashtable namespace_summaries = new Hashtable ();
403 Hashtable namespace_remarks = new Hashtable ();
404 Hashtable namespace_realpath = new Hashtable ();
407 void PopulateClass (Tree tree, string ns, Node ns_node, string file)
409 doc = new XmlDocument ();
412 string name = EcmaDoc.GetClassName (doc);
413 string assembly = EcmaDoc.GetClassAssembly (doc);
414 string kind = EcmaDoc.GetTypeKind (doc);
415 string full = EcmaDoc.GetFullClassName (doc);
418 string file_code = ns_node.tree.HelpSource.PackFile (file);
420 XmlNode class_summary = doc.SelectSingleNode ("/Type/Docs/summary");
421 ArrayList l = (ArrayList) class_summaries [ns];
423 l = new ArrayList ();
424 class_summaries [ns] = (object) l;
426 l.Add (new TypeInfo (kind, assembly, full, name, class_summary));
428 class_node = ns_node.LookupNode (String.Format ("{0} {1}", name, kind), "ecma:" + file_code + "#" + name + "/");
430 if (kind == "Delegate") {
431 if (doc.SelectSingleNode("/Type/ReturnValue") == null)
432 tree.HelpSource.Message (TraceLevel.Error, "Delegate " + name + " does not have a ReturnValue node. See the ECMA-style updates.");
435 if (kind == "Enumeration")
438 if (kind == "Delegate")
442 // Always add the Members node
444 class_node.CreateNode ("Members", "*");
446 PopulateMember (name, class_node, "Constructor", "Constructors");
447 PopulateMember (name, class_node, "Method", "Methods");
448 PopulateMember (name, class_node, "Property", "Properties");
449 PopulateMember (name, class_node, "Field", "Fields");
450 PopulateMember (name, class_node, "Event", "Events");
451 PopulateMember (name, class_node, "Operator", "Operators");
458 public NodeIndex (XmlNode node, int index)
465 struct NodeCompare : IComparer {
466 public int Compare (object a, object b)
468 NodeIndex na = (NodeIndex) a;
469 NodeIndex nb = (NodeIndex) b;
471 return String.Compare (na.node.Attributes ["MemberName"].InnerText,
472 nb.node.Attributes ["MemberName"].InnerText);
476 string GetMemberName (XmlNode node)
478 return node.Attributes ["MemberName"].InnerText;
482 // Performs an XPath query on the document to extract the nodes for the various members
483 // we also use some extra text to pluralize the caption
485 void PopulateMember (string typename, Node node, string type, string caption)
487 string select = type;
488 if (select == "Operator") select = "Method";
490 XmlNodeList list1 = doc.SelectNodes (String.Format ("/Type/Members/Member[MemberType=\"{0}\"]", select));
491 ArrayList list = new ArrayList();
493 foreach (XmlElement n in list1) {
494 n.SetAttribute("assembler_index", (i++).ToString());
495 if (type == "Method" && GetMemberName(n).StartsWith("op_")) continue;
496 if (type == "Operator" && !GetMemberName(n).StartsWith("op_")) continue;
500 int count = list.Count;
506 string key = type.Substring (0, 1);
507 nodes_node = node.CreateNode (caption, key);
512 foreach (XmlElement n in list)
513 nodes_node.CreateNode (GetMemberName (n), n.GetAttribute("assembler_index"));
517 foreach (XmlElement n in list)
518 nodes_node.CreateNode (EcmaHelpSource.MakeSignature(n, typename), n.GetAttribute("assembler_index"));
521 case "Property": // properties with indexers can be overloaded too
524 foreach (XmlElement n in list) {
525 bool multiple = false;
526 foreach (XmlNode nn in list) {
527 if (n != nn && GetMemberName(n) == nn.Attributes ["MemberName"].InnerText) {
533 string group, name, sig;
534 if (type != "Operator") {
535 name = GetMemberName(n);
536 sig = EcmaHelpSource.MakeSignature(n, null);
539 EcmaHelpSource.MakeOperatorSignature(n, out name, out sig);
544 nodes_node.LookupNode (group, group)
545 .CreateNode (sig, n.GetAttribute("assembler_index"));
547 nodes_node.CreateNode (name, n.GetAttribute("assembler_index"));
551 foreach (Node n in nodes_node.Nodes) {
559 throw new InvalidOperationException();
568 // The Ecma HelpSource provider
570 public class EcmaHelpSource : HelpSource {
572 public EcmaHelpSource (string base_file, bool create) : base (base_file, create)
574 ExtObject = new ExtensionObject (this);
577 public EcmaHelpSource ()
579 ExtObject = new ExtensionObject (this);
582 static string css_ecma;
583 public static string css_ecma_code {
585 if (css_ecma != null)
588 System.Reflection.Assembly assembly = typeof(EcmaHelpSource).Assembly;
589 Stream str_css = assembly.GetManifestResourceStream ("mono-ecma.css");
590 css_ecma = (new StreamReader (str_css)).ReadToEnd();
592 css_ecma = String.Empty;
598 public override string InlineCss {
599 get {return base.InlineCss + css_ecma_code;}
603 public static string js_code {
608 System.Reflection.Assembly assembly = typeof(EcmaHelpSource).Assembly;
609 Stream str_js = assembly.GetManifestResourceStream ("helper.js");
610 js = (new StreamReader (str_js)).ReadToEnd();
618 public override string InlineJavaScript {
619 get {return js_code + base.InlineJavaScript;}
622 public override string GetPublicUrl (string url)
624 if (url == null || url.Length == 0)
628 XmlDocument d = GetXmlFromUrl (url, out rest);
630 return EcmaDoc.GetCref (d.DocumentElement);
631 XmlElement e = GetDocElement (d, rest);
633 return EcmaDoc.GetCref (d.DocumentElement) + "/" + rest;
634 return EcmaDoc.GetCref (e);
636 catch (Exception e) {
641 private static XmlElement GetDocElement (XmlDocument d, string rest)
643 string memberType = null;
644 string memberIndex = null;
646 string [] nodes = rest.Split (new char [] {'/'});
648 switch (nodes.Length) {
649 // e.g. C; not supported.
652 // e.g. C/0 or M/MethodName; the latter isn't supported.
655 // XPath wants 1-based indexes, while the url uses 0-based values.
656 memberIndex = (int.Parse (nodes [1]) + 1).ToString ();
657 memberType = GetMemberType (nodes [0]);
662 // e.g. M/MethodName/0
664 memberIndex = (int.Parse (nodes [2]) + 1).ToString ();
665 memberType = GetMemberType (nodes [0]);
671 string xpath = "/Type/Members/Member[MemberType=\"" + memberType + "\"]" +
672 "[position()=" + memberIndex + "]";
673 return (XmlElement) d.SelectSingleNode (xpath);
676 private static string GetMemberType (string type)
679 case "C": return "Constructor";
680 case "E": return "Event";
681 case "F": return "Field";
682 case "M": return "Method";
683 case "P": return "Property";
685 throw new NotSupportedException ("Member Type: '" + type + "'.");
689 public override string GetText (string url, out Node match_node)
693 string cached = GetCachedText (url);
699 XmlReader summary = GetHelpXml ("mastersummary.xml");
703 XsltArgumentList args = new XsltArgumentList();
704 args.AddExtensionObject("monodoc:///extensions", ExtObject);
705 args.AddParam("show", "", "masteroverview");
706 string s = Htmlize(summary, args);
707 return BuildHtml (css_ecma_code, js_code, s);
710 if (url.StartsWith ("ecma:")) {
711 string s = GetTextFromUrl (url);
712 return BuildHtml (css_ecma_code, js_code, s);
719 string RenderMemberLookup (string typename, string member, ref Node type_node)
721 if (type_node.Nodes == null)
724 string membername = member;
725 string[] argtypes = null;
726 if (member.IndexOf("(") > 0) {
727 membername = membername.Substring(0, member.IndexOf("("));
728 member = member.Replace("@", "&");
730 // reform the member signature with CTS names
732 string x = member.Substring(member.IndexOf("(")+1);
733 argtypes = x.Substring(0, x.Length-1).Split(',', ':'); // operator signatures have colons
735 if (membername == ".ctor")
736 membername = typename;
738 member = membername + "(";
739 for (int i = 0; i < argtypes.Length; i++) {
740 argtypes[i] = EcmaDoc.ConvertCTSName(argtypes[i]);
741 if (i > 0) member += ",";
742 member += argtypes[i];
747 // Check if a node caption matches exactly
749 bool isoperator = false;
751 if ((membername == "op_Implicit" || membername == "op_Explicit") && argtypes.Length == 2) {
753 membername = "Conversion";
754 member = argtypes[0] + " to " + argtypes[1];
755 } else if (membername.StartsWith("op_")) {
757 membername = membername.Substring(3);
760 foreach (Node x in type_node.Nodes){
763 if (isoperator && x.Caption != "Operators")
766 foreach (Node m in x.Nodes) {
767 string caption = m.Caption;
768 string ecaption = ToEscapedMemberName (caption);
770 // No overloading (usually), is just the member name. The whole thing for constructors.
771 if (caption == membername || caption == member ||
772 ecaption == membername || ecaption == member) {
774 return GetTextFromUrl (m.URL);
776 } else if (caption == member || ecaption == member) {
777 // Though there are overloads, no arguments are in the url, so use this base node
779 return GetTextFromUrl (m.URL);
781 // Check subnodes which are the overloads -- must match signature
782 foreach (Node mm in m.Nodes) {
783 ecaption = ToEscapedTypeName (mm.Caption);
784 if (mm.Caption == member || ecaption == member) {
786 return GetTextFromUrl (mm.URL);
796 public static string MakeSignature (XmlNode n, string cstyleclass)
800 if (cstyleclass == null)
801 sig = n.Attributes["MemberName"].InnerText;
807 /*if (n.SelectSingleNode("MemberType").InnerText == "Method" || n.SelectSingleNode("MemberType").InnerText == "Constructor") {*/ // properties with indexers too
808 XmlNodeList paramnodes = n.SelectNodes("Parameters/Parameter");
811 foreach (XmlNode p in paramnodes) {
812 if (!first) sig += ",";
813 string type = p.Attributes["Type"].InnerText;
814 type = EcmaDoc.ConvertCTSName(type);
824 public static void MakeOperatorSignature (XmlNode n, out string nicename, out string sig)
828 name = n.Attributes["MemberName"].InnerText;
829 nicename = name.Substring(3);
832 // unary operators: no overloading possible
833 case "op_UnaryPlus": case "op_UnaryNegation": case "op_LogicalNot": case "op_OnesComplement":
834 case "op_Increment": case "op_Decrement":
835 case "op_True": case "op_False":
839 // binary operators: overloading is possible based on parameter types
840 case "op_Addition": case "op_Subtraction": case "op_Multiply": case "op_Division": case "op_Modulus":
841 case "op_BitwiseAnd": case "op_BitwiseOr": case "op_ExclusiveOr":
842 case "op_LeftShift": case "op_RightShift":
843 case "op_Equality": case "op_Inequality":
844 case "op_GreaterThan": case "op_LessThan": case "op_GreaterThanOrEqual": case "op_LessThanOrEqual":
845 XmlNodeList paramnodes = n.SelectNodes("Parameters/Parameter");
846 sig = nicename + "(";
848 foreach (XmlNode p in paramnodes) {
849 if (!first) sig += ",";
850 string type = p.Attributes["Type"].InnerText;
851 type = EcmaDoc.ConvertCTSName(type);
858 // overloading based on parameter and return type
859 case "op_Implicit": case "op_Explicit":
860 nicename = "Conversion";
861 string arg = n.SelectSingleNode("Parameters/Parameter/@Type").InnerText;
862 string ret = n.SelectSingleNode("ReturnValue/ReturnType").InnerText;
863 sig = EcmaDoc.ConvertCTSName(arg) + " to " + EcmaDoc.ConvertCTSName(ret);
867 throw new InvalidOperationException();
872 // This routine has to perform a lookup on a type.
874 // Example: T:System.Text.StringBuilder
876 // The prefix is the kind of opereation being requested (T:, E:, M: etc)
877 // ns is the namespace being looked up
878 // type is the type being requested
880 // This has to walk our toplevel (which is always a namespace)
881 // And then the type space, and then walk further down depending on the request
883 public override string RenderTypeLookup (string prefix, string ns, string type, string member, out Node match_node)
885 string url = GetUrlForType (prefix, ns, type, member, out match_node);
886 if (url == null) return null;
887 return GetTextFromUrl (url);
890 public virtual string GetIdFromUrl (string prefix, string ns, string type)
892 Node tmp_node = new Node (Tree, "", "");
893 string url = GetUrlForType (prefix, ns, type, null, out tmp_node);
894 if (url == null) return null;
895 return GetFile (url.Substring (5), out url);
898 public string GetUrlForType (string prefix, string ns, string type, string member, out Node match_node)
900 if (!prefix.EndsWith(":"))
901 throw new ArgumentException("prefix");
904 member = member.Replace ("#", ".").Replace ("{", "<").Replace ("}", ">");
906 // If a nested type, compare only inner type name to node list.
907 // This should be removed when the node list doesn't lose the containing type name.
908 type = ToEscapedTypeName (type.Replace("+", "."));
909 MatchAttempt[] attempts = GetAttempts (ns, type);
911 foreach (Node ns_node in Tree.Nodes){
912 string ns_node_namespace = ns_node.Element.Substring (2);
914 if (!MatchesNamespace (attempts, ns_node_namespace, out type))
917 foreach (Node type_node in ns_node.Nodes){
918 string element = type_node.Element;
921 if (element.StartsWith("T:")) {
922 cname = element.Substring(2);
924 RootTree.GetNamespaceAndType (cname, out _ns, out cname);
925 cname = ToEscapedTypeName (cname);
926 int pidx = cname.LastIndexOf (".");
927 cname = cname.Substring(pidx+1);
928 pidx = cname.LastIndexOf ("/");
930 cname = cname.Substring(0, pidx);
931 cname = cname.Replace("+", ".");
933 int pidx = element.IndexOf ("#");
934 int sidx = element.IndexOf ("/");
935 cname = element.Substring (pidx + 1, sidx-pidx-1);
936 cname = ToEscapedTypeName (cname);
939 //Console.WriteLine ("t:{0} cn:{1} p:{2}", type, cname, prefix);
941 if (type == cname && prefix == "T:") {
942 match_node = type_node;
943 return type_node.URL;
944 } else if (type.StartsWith (cname)){
945 int p = cname.Length;
947 match_node = type_node;
949 string ret = RenderMemberLookup (type, member, ref match_node);
951 return type_node.URL;
952 return match_node.URL;
954 } else if (type [p] == '/'){
956 // This handles summaries
959 foreach (Node nd in type_node.Nodes) {
960 if (nd.Element [nd.Element.Length - 1] == type [p + 1]) {
966 string ret = type_node.URL;
967 if (!ret.EndsWith("/")) ret += "/";
968 return ret + type.Substring (p + 1);
978 struct MatchAttempt {
979 public string Namespace;
982 public MatchAttempt (string ns, string t)
989 private static MatchAttempt[] GetAttempts (string ns, string type)
991 MatchAttempt[] attempts = new MatchAttempt [Count (ns, '.') + 1];
993 for (int i = 0; i < ns.Length; ++i) {
995 attempts [wns++] = new MatchAttempt (ns.Substring (0, i),
996 ns.Substring (i+1) + "." + type);
998 attempts [wns++] = new MatchAttempt (ns, type);
1002 private static int Count (string s, char c)
1005 for (int i = 0; i < s.Length; ++i)
1011 private static bool MatchesNamespace (MatchAttempt[] attempts, string ns, out string type)
1013 for (int i = 0; i < attempts.Length; ++i)
1014 if (ns == attempts [i].Namespace) {
1015 type = attempts [i].Type;
1022 public static string ToEscapedTypeName (string typename)
1024 return ToEscapedName (typename, "`");
1027 static string ToEscapedName (string name, string escape)
1029 StringBuilder filename = new StringBuilder (name.Length);
1034 for (int i = 0; i < name.Length; ++i) {
1046 filename.Append (escape).Append ((numArgs+1).ToString());
1057 filename.Append (c);
1061 return filename.ToString ();
1064 static string ToEscapedMemberName (string membername)
1066 return ToEscapedName (membername, "``");
1069 public override string GetNodeXPath (XPathNavigator n)
1071 if (n.Matches ("/Type/Docs/param")) {
1072 string type_name = (string) n.Evaluate ("string (ancestor::Type/@FullName)");
1073 string param_name = (string) n.Evaluate ("string (@name)");
1075 return String.Format ("/Type [@FullName = '{0}']/Docs/param[@name='{1}']", type_name, param_name);
1078 if (n.Matches ("/Type/Docs/*")) {
1079 string type_name = (string) n.Evaluate ("string (ancestor::Type/@FullName)");
1081 return String.Format ("/Type [@FullName = '{0}']/Docs/{1}", type_name, n.Name);
1084 if (n.Matches ("/Type/Members/Member/Docs/*")) {
1085 string type_name = (string) n.Evaluate ("string (ancestor::Type/@FullName)");
1086 string member_name = (string) n.Evaluate ("string (ancestor::Member/@MemberName)");
1087 string member_sig = (string) n.Evaluate ("string (ancestor::Member/MemberSignature [@Language='C#']/@Value)");
1088 string param_name = (string) n.Evaluate ("string (@name)");
1090 if (param_name == null || param_name == "") {
1091 return String.Format (
1092 "/Type [@FullName = '{0}']/Members/Member [@MemberName = '{1}'][MemberSignature [@Language='C#']/@Value = '{2}']/Docs/{3}",
1093 type_name, member_name, member_sig, n.Name);
1095 return String.Format (
1096 "/Type [@FullName = '{0}']/Members/Member [@MemberName = '{1}'][MemberSignature [@Language='C#']/@Value = '{2}']/Docs/param [@name = '{3}']",
1097 type_name, member_name, member_sig, param_name);
1101 Message (TraceLevel.Warning, "WARNING: Was not able to get clean XPath expression for node {0}", EditingUtils.GetXPath (n));
1102 return base.GetNodeXPath (n);
1105 protected virtual XmlDocument GetNamespaceDocument (string ns)
1107 return GetHelpXmlWithChanges ("xml.summary." + ns);
1110 public override string RenderNamespaceLookup (string nsurl, out Node match_node)
1112 foreach (Node ns_node in Tree.Nodes){
1113 if (ns_node.Element != nsurl)
1116 match_node = ns_node;
1117 string ns_name = nsurl.Substring (2);
1119 XmlDocument doc = GetNamespaceDocument (ns_name);
1123 XsltArgumentList args = new XsltArgumentList();
1124 args.AddExtensionObject("monodoc:///extensions", ExtObject);
1125 args.AddParam("show", "", "namespace");
1126 args.AddParam("namespace", "", ns_name);
1127 string s = Htmlize(new XmlNodeReader (doc), args);
1128 return BuildHtml (css_ecma_code, js_code, s);
1135 private string SelectString(XmlNode node, string xpath) {
1136 XmlNode ret = node.SelectSingleNode(xpath);
1137 if (ret == null) return "";
1138 return ret.InnerText;
1140 private int SelectCount(XmlNode node, string xpath) {
1141 return node.SelectNodes(xpath).Count;
1145 // Returns the XmlDocument from the given url, and fills in `rest'
1147 protected virtual XmlDocument GetXmlFromUrl(string url, out string rest) {
1149 url = url.Substring (5);
1150 string file = GetFile (url, out rest);
1152 // Console.WriteLine ("Got [{0}] and [{1}]", file, rest);
1153 return GetHelpXmlWithChanges (file);
1156 string GetTextFromUrl (string url)
1159 string path = XmlDocUtils.GetCachedFileName (base_dir, url);
1160 if (File.Exists (path))
1161 return File.OpenText (path).ReadToEnd ();
1168 XmlDocument doc = GetXmlFromUrl (url, out rest);
1170 // Load base-type information so the stylesheet can draw the inheritance
1171 // tree and (optionally) include inherited members in the members list.
1172 XmlElement basenode = (XmlElement)doc.SelectSingleNode("Type/Base");
1173 XmlElement membersnode = (XmlElement)doc.SelectSingleNode("Type/Members");
1174 XmlNode basetype = doc.SelectSingleNode("Type/Base/BaseTypeName");
1176 while (basetype != null) {
1177 // Add the ParentType node to Type/Base
1178 XmlElement inheritancenode = doc.CreateElement("ParentType");
1179 inheritancenode.SetAttribute("Type", basetype.InnerText);
1180 inheritancenode.SetAttribute("Order", (baseindex++).ToString());
1181 basenode.AppendChild(inheritancenode);
1183 // Load the base type XML data
1184 int dot = basetype.InnerText.LastIndexOf('.');
1185 string ns = basetype.InnerText.Substring(0, dot == -1 ? 0 : dot);
1186 string n = basetype.InnerText.Substring(dot == -1 ? 0 : dot+1);
1187 string basetypeurl = GetUrlForType("T:", ns, n, null, out node);
1188 XmlDocument basetypedoc = null;
1189 if (basetypeurl != null)
1190 basetypedoc = GetXmlFromUrl (basetypeurl, out rest2);
1191 if (basetypedoc == null) {
1192 inheritancenode.SetAttribute("Incomplete", "1");
1196 if (SettingsHandler.Settings.ShowInheritedMembers) {
1197 // Add inherited members
1198 foreach (XmlElement member in basetypedoc.SelectNodes("Type/Members/Member[not(MemberType='Constructor')]")) {
1199 string sig = SelectString(member, "MemberSignature[@Language='C#']/@Value");
1200 if (sig.IndexOf(" static ") >= 0) continue;
1202 // If the signature of member matches the signature of a member already in the XML,
1204 string xpath = "@MemberName='" + SelectString(member, "@MemberName") + "'";
1205 xpath += " and ReturnValue/ReturnType='" + SelectString(member, "ReturnValue/ReturnType") + "'";
1206 xpath += " and count(Parameters/Parameter)=" + SelectCount(member, "Parameters/Parameter") + "";
1208 foreach (XmlElement p in member.SelectNodes("Parameters/Parameter")) {
1209 xpath += " and Parameters/Parameter[position()=" + pi + "]/@Type = '" + p.GetAttribute("Type") + "'";
1213 // If a signature match is found, don't add.
1214 XmlNode match = membersnode.SelectSingleNode("Member[" + xpath + "]");
1218 member.SetAttribute("DeclaredIn", basetype.InnerText);
1219 membersnode.AppendChild(membersnode.OwnerDocument.ImportNode(member, true));
1223 basetype = basetypedoc.SelectSingleNode("Type/Base/BaseTypeName");
1225 ArrayList extensions = new ArrayList ();
1226 AddExtensionMethodsFromHelpSource (extensions, this);
1227 foreach (HelpSource hs in RootTree.HelpSources) {
1228 EcmaHelpSource es = hs as EcmaHelpSource;
1233 AddExtensionMethodsFromHelpSource (extensions, es);
1235 XmlDocUtils.AddExtensionMethods (doc, extensions, delegate (string s) {
1236 s = s.StartsWith ("T:") ? s : "T:" + s;
1237 return RootTree.GetHelpXml (s);
1240 XsltArgumentList args = new XsltArgumentList();
1242 args.AddExtensionObject("monodoc:///extensions", ExtObject);
1245 args.AddParam("show", "", "typeoverview");
1246 string s = Htmlize(new XmlNodeReader (doc), args);
1247 return BuildHtml (css_ecma_code, js_code, s);
1250 string [] nodes = rest.Split (new char [] {'/'});
1252 switch (nodes.Length) {
1254 args.AddParam("show", "", "members");
1255 args.AddParam("index", "", "all");
1258 // Could either be a single member, or an overload thingy
1260 int.Parse (nodes [1]); // is it an int
1262 args.AddParam("show", "", "member");
1263 args.AddParam("index", "", nodes [1]);
1265 args.AddParam("show", "", "overloads");
1266 args.AddParam("index", "", nodes [1]);
1270 args.AddParam("show", "", "member");
1271 args.AddParam("index", "", nodes [2]);
1274 return "What the hell is this URL " + url;
1279 args.AddParam("membertype", "", "Constructor");
1282 args.AddParam("membertype", "", "Method");
1285 args.AddParam("membertype", "", "Property");
1288 args.AddParam("membertype", "", "Field");
1291 args.AddParam("membertype", "", "Event");
1294 args.AddParam("membertype", "", "Operator");
1297 args.AddParam("membertype", "", "ExtensionMethod");
1300 args.AddParam("membertype", "", "All");
1303 return "Unknown url: " + url;
1306 string html = Htmlize(new XmlNodeReader (doc), args);
1307 return BuildHtml (css_ecma_code, js_code, html);
1310 void AddExtensionMethodsFromHelpSource (ArrayList extensions, EcmaHelpSource es)
1312 Stream s = es.GetHelpStream ("ExtensionMethods.xml");
1314 XmlDocument d = new XmlDocument ();
1316 foreach (XmlNode n in d.SelectNodes ("/ExtensionMethods/*")) {
1323 public override void RenderPreviewDocs (XmlNode newNode, XmlWriter writer)
1325 XsltArgumentList args = new XsltArgumentList ();
1326 args.AddExtensionObject ("monodoc:///extensions", ExtObject);
1328 Htmlize (new XmlNodeReader (newNode), args, writer);
1331 static XslCompiledTransform ecma_transform;
1333 public string Htmlize (XmlReader ecma_xml)
1335 return Htmlize(ecma_xml, null);
1338 public string Htmlize (XmlReader ecma_xml, XsltArgumentList args)
1342 var output = new StringBuilder ();
1343 ecma_transform.Transform (ecma_xml,
1345 XmlWriter.Create (output, ecma_transform.OutputSettings),
1346 CreateDocumentResolver ());
1347 return output.ToString ();
1350 protected virtual XmlResolver CreateDocumentResolver ()
1352 // results in using XmlUrlResolver
1356 static void Htmlize (XmlReader ecma_xml, XsltArgumentList args, XmlWriter w)
1360 if (ecma_xml == null)
1363 ecma_transform.Transform (ecma_xml, args, w, null);
1366 static XslCompiledTransform ecma_transform_css, ecma_transform_no_css;
1367 static void EnsureTransform ()
1369 if (ecma_transform == null) {
1370 ecma_transform_css = new XslCompiledTransform ();
1371 ecma_transform_no_css = new XslCompiledTransform ();
1372 Assembly assembly = System.Reflection.Assembly.GetCallingAssembly ();
1374 Stream stream = assembly.GetManifestResourceStream ("mono-ecma-css.xsl");
1375 XmlReader xml_reader = new XmlTextReader (stream);
1376 XmlResolver r = new ManifestResourceResolver (".");
1377 ecma_transform_css.Load (xml_reader, XsltSettings.TrustedXslt, r);
1379 stream = assembly.GetManifestResourceStream ("mono-ecma.xsl");
1380 xml_reader = new XmlTextReader (stream);
1381 ecma_transform_no_css.Load (xml_reader, XsltSettings.TrustedXslt, r);
1384 ecma_transform = ecma_transform_css;
1386 ecma_transform = ecma_transform_no_css;
1389 // This ExtensionObject stuff is used to check at run time whether
1390 // types and members have been implemented and whether there are any
1391 // MonoTODO attributes left on them.
1393 public readonly ExtensionObject ExtObject;
1394 public class ExtensionObject {
1395 readonly EcmaHelpSource hs;
1398 // We are setting this to quiet now, as we need to transition
1399 // monodoc to run with the 2.x runtime and provide accurate
1400 // information in those cases.
1404 public ExtensionObject (EcmaHelpSource hs)
1409 public string Colorize(string code, string lang) {
1410 return(Mono.Utilities.Colorizer.Colorize(code,lang));
1412 // Used by stylesheet to nicely reformat the <see cref=> tags.
1413 public string MakeNiceSignature(string sig, string contexttype)
1421 sig = sig.Substring(2);
1424 case 'N': return sig;
1425 case 'T': return ShortTypeName(sig, contexttype);
1427 case 'C': case 'M': case 'P': case 'F': case 'E':
1428 string type, mem, arg;
1432 if (s == 'C' || s == 'M')
1433 paren = sig.IndexOf("(");
1435 paren = sig.IndexOf("[");
1439 if (paren > 0 && paren < sig.Length-1) {
1440 string[] args = sig.Substring(paren+1, sig.Length-paren-2).Split(',');
1441 for (int i = 0; i < args.Length; i++)
1442 args[i] = ShortTypeName(args[i], contexttype);
1443 arg = "(" + String.Join(", ", args) + ")";
1444 sig = sig.Substring(0, paren);
1449 // Get type and member names
1450 int dot = sig.LastIndexOf(".");
1451 if (s == 'C' || dot <= 0 || dot == sig.Length-1) {
1455 type = sig.Substring(0, dot);
1456 mem = sig.Substring(dot);
1459 type = ShortTypeName(type, contexttype);
1461 return type + mem + arg;
1468 public string EditUrl (XPathNodeIterator itr)
1470 if (itr.MoveNext ())
1471 return hs.GetEditUri (itr.Current);
1476 public string EditUrlNamespace (XPathNodeIterator itr, string ns, string section)
1478 if (hs is EcmaUncompiledHelpSource)
1479 return "edit:file:" + Path.Combine(((EcmaUncompiledHelpSource)hs).BasePath, ns + ".xml") + "@/Namespace/Docs/" + section;
1480 else if (itr.MoveNext ())
1481 return EditingUtils.FormatEditUri(itr.Current.BaseURI, "/elements/" + section);
1485 private static string ShortTypeName(string name, string contexttype)
1487 int dot = contexttype.LastIndexOf(".");
1488 if (dot < 0) return name;
1489 string contextns = contexttype.Substring(0, dot+1);
1491 if (name == contexttype)
1492 return name.Substring(dot+1);
1494 if (name.StartsWith(contextns))
1495 return name.Substring(contextns.Length);
1497 return name.Replace("+", ".");
1500 public string MonoImpInfo(string assemblyname, string typename, string membername, string arglist, bool strlong)
1505 ArrayList a = new ArrayList();
1506 if (arglist != "") a.Add(arglist);
1507 return MonoImpInfo(assemblyname, typename, membername, a, strlong);
1510 public string MonoImpInfo(string assemblyname, string typename, string membername, XPathNodeIterator itr, bool strlong)
1515 ArrayList rgs = new ArrayList ();
1516 while (itr.MoveNext ())
1517 rgs.Add (itr.Current.Value);
1519 return MonoImpInfo (assemblyname, typename, membername, rgs, strlong);
1522 public string MonoImpInfo(string assemblyname, string typename, string membername, ArrayList arglist, bool strlong)
1525 Assembly assembly = null;
1528 assembly = Assembly.LoadWithPartialName(assemblyname);
1529 } catch (Exception) {
1533 if (assembly == null) {
1534 /*if (strlong) return "The assembly " + assemblyname + " is not available to MonoDoc.";
1536 return ""; // silently ignore
1539 Type t = assembly.GetType(typename, false);
1542 return typename + " has not been implemented.";
1544 return "Not implemented.";
1547 // The following code is flakey and fails to find existing members
1550 MemberInfo[] mis = t.GetMember(membername, BF.Static | BF.Instance | BF.Public | BF.NonPublic);
1552 if (mis.Length == 0)
1553 return "This member has not been implemented.";
1554 if (mis.Length == 1)
1555 return MonoImpInfo(mis[0], "member", strlong);
1557 // Scan for the appropriate member
1558 foreach (MemberInfo mi in mis) {
1559 System.Reflection.ParameterInfo[] pis;
1561 if (mi is MethodInfo || mi is ConstructorInfo)
1562 pis = ((MethodBase)mi).GetParameters();
1563 else if (mi is PropertyInfo)
1564 pis = ((PropertyInfo)mi).GetIndexParameters();
1570 if (pis.Length != arglist.Count) continue;
1571 for (int i = 0; i < pis.Length; i++) {
1572 if (pis[i].ParameterType.FullName != (string)arglist[i]) { good = false; break; }
1574 if (!good) continue;
1577 return MonoImpInfo(mi, "member", strlong);
1580 } catch (Exception) {
1585 public string MonoImpInfo(System.Reflection.MemberInfo mi, string itemtype, bool strlong)
1592 object[] atts = mi.GetCustomAttributes(true);
1594 foreach (object att in atts) if (att.GetType().Name == "MonoTODOAttribute") todoctr++;
1598 s = "This " + itemtype + " is marked as being unfinished.<BR/>\n";
1606 public string MonoImpInfo(string assemblyname, string typename, bool strlong)
1612 if (assemblyname == "")
1615 Assembly assembly = Assembly.LoadWithPartialName(assemblyname);
1616 if (assembly == null)
1619 Type t = assembly.GetType(typename, false);
1622 return typename + " has not been implemented.";
1624 return "Not implemented.";
1627 string s = MonoImpInfo(t, "type", strlong);
1630 MemberInfo[] mis = t.GetMembers(BF.Static | BF.Instance | BF.Public | BF.NonPublic);
1632 // Scan members for MonoTODO attributes
1634 foreach (MemberInfo mi in mis) {
1635 string mii = MonoImpInfo(mi, null, false);
1636 if (mii != "") mctr++;
1639 s += "This type has " + mctr + " members that are marked as unfinished.<BR/>";
1645 } catch (Exception) {
1650 public bool MonoEditing ()
1652 return SettingsHandler.Settings.EnableEditing;
1655 public bool IsToBeAdded(string text) {
1656 return text.StartsWith("To be added");
1661 // This takes one of the ecma urls, which look like this:
1662 // ecma:NUMERIC_ID#OPAQUE/REST
1664 // NUMERIC_ID is the numeric ID assigned by the compressor
1665 // OPAQUE is opaque for node rendering (it typically contains T:System.Byte for example)
1666 // REST is the rest of the argument used to decode information
1668 static string GetFile (string url, out string rest)
1670 int pound = url.IndexOf ("#");
1671 int slash = url.IndexOf ("/");
1673 string fname = url.Substring (0, pound);
1674 rest = url.Substring (slash+1);
1680 // This should have a little cache or something.
1681 static XmlDocument GetDocument (HelpSource hs, string fname)
1683 Stream s = hs.GetHelpStream (fname);
1685 Error ("Could not fetch document {0}", fname);
1689 XmlDocument doc = new XmlDocument ();
1697 string GetKindFromCaption (string s)
1699 int p = s.LastIndexOf (' ');
1701 return s.Substring (p + 1);
1706 // Obtain an URL of the type T:System.Object from the node
1708 public static string GetNiceUrl (Node node) {
1709 if (node.Element.StartsWith("N:"))
1710 return node.Element;
1712 int bk_pos = node.Caption.IndexOf (' ');
1713 // node from an overview
1715 name = node.Caption.Substring (0, bk_pos);
1716 full = node.Parent.Caption + "." + name.Replace ('.', '+');
1719 // node that lists constructors, methods, fields, ...
1720 if ((node.Caption == "Constructors") || (node.Caption == "Fields") || (node.Caption == "Events")
1721 || (node.Caption == "Members") || (node.Caption == "Properties") || (node.Caption == "Methods")
1722 || (node.Caption == "Operators")) {
1723 bk_pos = node.Parent.Caption.IndexOf (' ');
1724 name = node.Parent.Caption.Substring (0, bk_pos);
1725 full = node.Parent.Parent.Caption + "." + name.Replace ('.', '+');
1726 return "T:" + full + "/" + node.Element;
1728 int pr_pos = node.Caption.IndexOf ('(');
1729 // node from a constructor
1730 if (node.Parent.Element == "C") {
1731 name = node.Parent.Parent.Parent.Caption;
1732 int idx = node.URL.IndexOf ('/');
1733 return node.URL[idx+1] + ":" + name + "." + node.Caption.Replace ('.', '+');
1734 // node from a method with one signature, field, property, operator
1735 } else if (pr_pos == -1) {
1736 bk_pos = node.Parent.Parent.Caption.IndexOf (' ');
1737 name = node.Parent.Parent.Caption.Substring (0, bk_pos);
1738 full = node.Parent.Parent.Parent.Caption + "." + name.Replace ('.', '+');
1739 int idx = node.URL.IndexOf ('/');
1740 return node.URL[idx+1] + ":" + full + "." + node.Caption;
1741 // node from a method with several signatures
1743 bk_pos = node.Parent.Parent.Parent.Caption.IndexOf (' ');
1744 name = node.Parent.Parent.Parent.Caption.Substring (0, bk_pos);
1745 full = node.Parent.Parent.Parent.Parent.Caption + "." + name.Replace ('.', '+');
1746 int idx = node.URL.IndexOf ('/');
1747 return node.URL[idx+1] + ":" + full + "." + node.Caption;
1752 // Populates the index.
1754 public override void PopulateIndex (IndexMaker index_maker)
1756 foreach (Node ns_node in Tree.Nodes){
1757 foreach (Node type_node in ns_node.Nodes){
1758 string typename = type_node.Caption.Substring (0, type_node.Caption.IndexOf (' '));
1759 string full = ns_node.Caption + "." + typename;
1761 string doc_tag = GetKindFromCaption (type_node.Caption);
1762 string url = "T:" + full;
1764 if (doc_tag == "Class" || doc_tag == "Structure" || doc_tag == "Interface"){
1766 index_maker.Add (type_node.Caption, typename, url);
1767 index_maker.Add (full + " " + doc_tag, full, url);
1769 foreach (Node c in type_node.Nodes){
1771 case "Constructors":
1772 index_maker.Add (" constructors", typename+"0", url + "/C");
1775 index_maker.Add (" fields", typename+"1", url + "/F");
1778 index_maker.Add (" events", typename+"2", url + "/E");
1781 index_maker.Add (" properties", typename+"3", url + "/P");
1784 index_maker.Add (" methods", typename+"4", url + "/M");
1787 index_maker.Add (" operators", typename+"5", url + "/O");
1793 // Now repeat, but use a different sort key, to make sure we come after
1794 // the summary data above, start the counter at 6
1796 string keybase = typename + "6.";
1798 foreach (Node c in type_node.Nodes){
1800 case "Constructors":
1803 foreach (Node nc in c.Nodes){
1804 string res = nc.Caption;
1806 string nurl = String.Format ("F:{0}.{1}", full, res);
1807 index_maker.Add (String.Format ("{0}.{1} field", typename, res),
1808 keybase + res, nurl);
1809 index_maker.Add (String.Format ("{0} field", res), res, nurl);
1814 foreach (Node nc in c.Nodes){
1815 string res = nc.Caption;
1816 string nurl = String.Format ("E:{0}.{1}", full, res);
1818 index_maker.Add (String.Format ("{0}.{1} event", typename, res),
1819 keybase + res, nurl);
1820 index_maker.Add (String.Format ("{0} event", res), res, nurl);
1824 foreach (Node nc in c.Nodes){
1825 string res = nc.Caption;
1826 string nurl = String.Format ("P:{0}.{1}", full, res);
1827 index_maker.Add (String.Format ("{0}.{1} property", typename, res),
1828 keybase + res, nurl);
1829 index_maker.Add (String.Format ("{0} property", res), res, nurl);
1833 foreach (Node nc in c.Nodes){
1834 string res = nc.Caption;
1835 int p = res.IndexOf ("(");
1837 res = res.Substring (0, p);
1838 string nurl = String.Format ("M:{0}.{1}", full, res);
1839 index_maker.Add (String.Format ("{0}.{1} method", typename, res),
1840 keybase + res, nurl);
1841 index_maker.Add (String.Format ("{0} method", res), res, nurl);
1846 foreach (Node nc in c.Nodes){
1847 string res = nc.Caption;
1848 string nurl = String.Format ("O:{0}.{1}", full, res);
1849 index_maker.Add (String.Format ("{0}.{1} operator", typename, res),
1850 keybase + res, nurl);
1855 } else if (doc_tag == "Enumeration"){
1857 // Enumerations: add the enumeration values
1859 index_maker.Add (type_node.Caption, typename, url);
1860 index_maker.Add (full + " " + doc_tag, full, url);
1862 // Now, pull the values.
1864 XmlDocument x = GetXmlFromUrl (type_node.URL, out rest);
1868 XmlNodeList members = x.SelectNodes ("/Type/Members/Member");
1870 if (members == null)
1873 foreach (XmlNode member_node in members){
1874 string enum_value = member_node.Attributes ["MemberName"].InnerText;
1875 string caption = enum_value + " value";
1876 index_maker.Add (caption, caption, url);
1878 } else if (doc_tag == "Delegate"){
1879 index_maker.Add (type_node.Caption, typename, url);
1880 index_maker.Add (full + " " + doc_tag, full, url);
1886 // Create list of documents for searching
1888 public override void PopulateSearchableIndex (IndexWriter writer)
1891 foreach (Node ns_node in Tree.Nodes) {
1892 Message (TraceLevel.Info, "\tNamespace: {0} ({1})", ns_node.Caption, ns_node.Nodes.Count);
1893 foreach (Node type_node in ns_node.Nodes) {
1894 string typename = type_node.Caption.Substring (0, type_node.Caption.IndexOf (' '));
1895 string full = ns_node.Caption + "." + typename;
1896 string doc_tag = GetKindFromCaption (type_node.Caption);
1897 string url = "T:" + full;
1899 XmlDocument xdoc = GetXmlFromUrl (type_node.URL, out rest);
1904 // For classes, structures or interfaces add a doc for the overview and
1905 // add a doc for every constructor, method, event, ...
1907 if (doc_tag == "Class" || doc_tag == "Structure" || doc_tag == "Interface"){
1909 // Adds a doc for every overview of every type
1910 SearchableDocument doc = new SearchableDocument ();
1911 doc.title = type_node.Caption;
1912 doc.hottext = typename;
1915 XmlNode node_sel = xdoc.SelectSingleNode ("/Type/Docs");
1916 text = new StringBuilder ();
1917 GetTextFromNode (node_sel, text);
1918 doc.text = text.ToString ();
1920 text = new StringBuilder ();
1921 GetExamples (node_sel, text);
1922 doc.examples = text.ToString ();
1924 writer.AddDocument (doc.LuceneDoc);
1926 //Add docs for contructors, methods, etc.
1927 foreach (Node c in type_node.Nodes) { // c = Constructors || Fields || Events || Properties || Methods || Operators
1929 if (c.Element == "*")
1932 foreach (Node nc in c.Nodes) {
1933 //xpath to the docs xml node
1935 if (c.Caption == "Constructors")
1936 xpath = String.Format ("/Type/Members/Member[{0}]/Docs", i++);
1937 else if (c.Caption == "Operators")
1938 xpath = String.Format ("/Type/Members/Member[@MemberName='op_{0}']/Docs", nc.Caption);
1940 xpath = String.Format ("/Type/Members/Member[@MemberName='{0}']/Docs", nc.Caption);
1941 //construct url of the form M:Array.Sort
1943 if (c.Caption == "Constructors")
1944 urlnc = String.Format ("{0}:{1}.{2}", c.Caption[0], ns_node.Caption, nc.Caption);
1946 urlnc = String.Format ("{0}:{1}.{2}.{3}", c.Caption[0], ns_node.Caption, typename, nc.Caption);
1949 SearchableDocument doc_nod = new SearchableDocument ();
1950 doc_nod.title = LargeName (nc);
1951 //dont add the parameters to the hottext
1952 int ppos = nc.Caption.IndexOf ('(');
1954 doc_nod.hottext = nc.Caption.Substring (0, ppos);
1956 doc_nod.hottext = nc.Caption;
1958 doc_nod.url = urlnc;
1960 XmlNode xmln = xdoc.SelectSingleNode (xpath);
1962 Error ("Problem: {0}, with xpath: {1}", urlnc, xpath);
1966 text = new StringBuilder ();
1967 GetTextFromNode (xmln, text);
1968 doc_nod.text = text.ToString ();
1970 text = new StringBuilder ();
1971 GetExamples (xmln, text);
1972 doc_nod.examples = text.ToString ();
1974 writer.AddDocument (doc_nod.LuceneDoc);
1978 // Enumerations: add the enumeration values
1980 } else if (doc_tag == "Enumeration"){
1982 XmlNodeList members = xdoc.SelectNodes ("/Type/Members/Member");
1983 if (members == null)
1986 text = new StringBuilder ();
1987 foreach (XmlNode member_node in members) {
1988 string enum_value = member_node.Attributes ["MemberName"].InnerText;
1989 text.Append (enum_value);
1991 GetTextFromNode (member_node["Docs"], text);
1994 SearchableDocument doc = new SearchableDocument ();
1996 text = new StringBuilder ();
1997 GetExamples (xdoc.SelectSingleNode ("/Type/Docs"), text);
1998 doc.examples = text.ToString ();
2000 doc.title = type_node.Caption;
2001 doc.hottext = xdoc.DocumentElement.Attributes["Name"].Value;
2003 doc.text = text.ToString();
2004 writer.AddDocument (doc.LuceneDoc);
2008 } else if (doc_tag == "Delegate"){
2009 SearchableDocument doc = new SearchableDocument ();
2010 doc.title = type_node.Caption;
2011 doc.hottext = xdoc.DocumentElement.Attributes["Name"].Value;
2014 XmlNode node_sel = xdoc.SelectSingleNode ("/Type/Docs");
2016 text = new StringBuilder ();
2017 GetTextFromNode (node_sel, text);
2018 doc.text = text.ToString();
2020 text = new StringBuilder ();
2021 GetExamples (node_sel, text);
2022 doc.examples = text.ToString();
2024 writer.AddDocument (doc.LuceneDoc);
2031 // Extract the interesting text from the docs node
2033 void GetTextFromNode (XmlNode n, StringBuilder sb)
2035 //don't include example code
2036 if (n.Name == "code")
2039 //include the url to which points the see tag
2040 if (n.Name == "see" && n.Attributes.Count > 0)
2041 sb.Append (n.Attributes [0].Value);
2043 //include the name of the parameter
2044 if (n.Name == "paramref" && n.Attributes.Count > 0)
2045 sb.Append (n.Attributes [0].Value);
2047 //include the contents for the node that contains text
2048 if (n.NodeType == XmlNodeType.Text)
2049 sb.Append (n.Value);
2051 //add the rest of xml tags recursively
2052 if (n.HasChildNodes)
2053 foreach (XmlNode n_child in n.ChildNodes)
2054 GetTextFromNode (n_child, sb);
2057 // Extract the code nodes from the docs
2059 void GetExamples (XmlNode n, StringBuilder sb)
2061 if (n.Name == "code") {
2062 sb.Append (n.InnerText);
2064 if (n.HasChildNodes)
2065 foreach (XmlNode n_child in n.ChildNodes)
2066 GetExamples (n_child, sb);
2070 // Extract a large name for the Node
2071 // (copied from mono-tools/docbrowser/browser.Render()
2072 static string LargeName (Node matched_node)
2074 string[] parts = matched_node.URL.Split('/', '#');
2075 if(parts.Length == 3 && parts[2] != String.Empty) { //List of Members, properties, events, ...
2076 return parts[1] + ": " + matched_node.Caption;
2077 } else if(parts.Length >= 4) { //Showing a concrete Member, property, ...
2078 return parts[1] + "." + matched_node.Caption;
2080 return matched_node.Caption;
2086 public class EcmaUncompiledHelpSource : EcmaHelpSource {
2087 readonly DirectoryInfo basedir;
2088 readonly XmlDocument basedoc;
2090 public new readonly string Name;
2091 public readonly string BasePath;
2093 public EcmaUncompiledHelpSource (string base_file) : base ()
2095 Message (TraceLevel.Info, "Loading uncompiled help from " + base_file);
2097 basedir = new DirectoryInfo(base_file);
2098 BasePath = basedir.FullName;
2100 basedoc = new XmlDocument();
2101 basedoc.Load(Path.Combine(basedir.FullName, "index.xml"));
2103 Name = basedoc.SelectSingleNode("Overview/Title").InnerText;
2105 bool has_content = false;
2107 foreach (XmlElement ns in basedoc.SelectNodes("Overview/Types/Namespace")) {
2109 Node nsnode = Tree.CreateNode(ns.GetAttribute("Name"), "N:" + ns.GetAttribute("Name"));
2111 bool has_types = false;
2112 foreach (XmlElement t in ns.SelectNodes("Type")) {
2114 string typename = EcmaDoc.GetDisplayName (t).Replace("+", ".");
2116 // Must load in each document to get the list of members...
2117 XmlDocument typedoc = new XmlDocument();
2118 typedoc.Load(Path.Combine(Path.Combine(basedir.FullName, ns.GetAttribute("Name")), t.GetAttribute("Name") + ".xml"));
2119 string kind = EcmaDoc.GetTypeKind (typedoc);
2121 string url = ns.GetAttribute("Name") + "." + t.GetAttribute("Name");
2122 Node typenode = nsnode.CreateNode(typename + " " + kind, "T:" + url);
2123 //Node typemembers = typenode.CreateNode("Members", "T:" + url + "/*");
2125 Hashtable groups = new Hashtable();
2126 Hashtable groups_count = new Hashtable();
2127 foreach (XmlElement member in typedoc.SelectNodes("Type/Members/Member")) {
2128 string membername = member.GetAttribute("MemberName");
2129 string membertype = member.SelectSingleNode("MemberType").InnerText;
2131 if (membertype == "Constructor")
2132 membername = t.GetAttribute("Name");
2133 if (membername.StartsWith("op_"))
2134 membertype = "Operator";
2137 if (groups.ContainsKey(membertype)) {
2138 group = (Node)groups[membertype];
2140 string membertypeplural = membertype + "s";
2141 if (membertypeplural == "Propertys") membertypeplural = "Properties";
2143 group = typenode.CreateNode(membertypeplural, "T:" + url + "/" + membertype[0]);
2144 groups[membertype] = group;
2145 groups_count[membertype] = 0;
2148 if (membertype == "Constructor" || membertype == "Method" ||
2149 (membertype == "Property" && member.SelectNodes("Parameters/Parameter").Count > 0)) {
2150 membername = EcmaHelpSource.MakeSignature(member, membertype == "Constructor" ? membername : null);
2151 } else if (membertype == "Operator") {
2153 EcmaHelpSource.MakeOperatorSignature(member, out dummy, out membername);
2156 int index = (int)groups_count[membertype];
2157 groups_count[membertype] = index + 1;
2159 group.CreateNode(membername, index.ToString());
2162 foreach (Node group in groups.Values)
2174 public override string GetIdFromUrl (string prefix, string ns, string type)
2177 throw new NotImplementedException();
2178 return Path.Combine(Path.Combine(basedir.FullName, ns), type + ".xml");
2181 protected override XmlDocument GetXmlFromUrl(string url, out string rest) {
2183 url = url.Substring(2);
2185 int sidx = url.IndexOf("/");
2189 rest = url.Substring(sidx+1);
2190 url = url.Substring(0, sidx);
2194 if (!RootTree.GetNamespaceAndType (url, out ns, out type)) {
2195 Message (TraceLevel.Error, "Could not determine namespace/type for {0}", url);
2199 string file = Path.Combine(Path.Combine(basedir.FullName, ns),
2200 ToEscapedTypeName (type).Replace ('.', '+') + ".xml");
2201 if (!new FileInfo(file).Exists) return null;
2203 XmlDocument typedoc = new XmlDocument();
2208 public override string GetText (string url, out Node match_node) {
2209 if (url == "root:") {
2213 XmlDocument index = new XmlDocument ();
2214 index.Load (Path.Combine (basedir.FullName, "index.xml"));
2215 XmlNodeList nodes = index.SelectNodes ("/Overview/Types/Namespace");
2217 //recreate masteroverview.xml
2218 XmlDocument summary = new XmlDocument ();
2219 XmlElement elements = summary.CreateElement ("elements");
2220 foreach (XmlNode node in nodes) {
2221 XmlElement ns = summary.CreateElement ("namespace");
2222 XmlAttribute attr = summary.CreateAttribute ("ns");
2223 attr.Value = EcmaDoc.GetDisplayName (node);
2224 ns.Attributes.Append (attr);
2225 elements.AppendChild (ns);
2227 summary.AppendChild (elements);
2229 XmlReader reader = new XmlTextReader (new StringReader (summary.OuterXml));
2231 //transform the recently created masteroverview.xml
2232 XsltArgumentList args = new XsltArgumentList();
2233 args.AddExtensionObject("monodoc:///extensions", ExtObject);
2234 args.AddParam("show", "", "masteroverview");
2235 string s = Htmlize(reader, args);
2236 return BuildHtml (css_ecma_code, js_code, s);
2238 return base.GetText(url, out match_node);
2241 protected override XmlDocument GetNamespaceDocument (string ns)
2243 XmlDocument nsdoc = new XmlDocument();
2244 nsdoc.Load (EcmaDoc.GetNamespaceFile (basedir.FullName, ns));
2246 XmlDocument elements = new XmlDocument();
2247 XmlElement docnode = elements.CreateElement("elements");
2248 elements.AppendChild (docnode);
2250 foreach (XmlElement doc in nsdoc.SelectNodes("Namespace/Docs/*")) {
2251 docnode.AppendChild(elements.ImportNode(doc, true));
2254 foreach (XmlElement t in basedoc.SelectNodes("Overview/Types/Namespace[@Name='" + ns + "']/Type")) {
2255 XmlDocument typedoc = new XmlDocument();
2256 typedoc.Load(Path.Combine(Path.Combine(basedir.FullName, ns), t.GetAttribute("Name") + ".xml"));
2259 switch (EcmaDoc.GetTypeKind(typedoc)) {
2260 case "Class": typekind = "class"; break;
2261 case "Enumeration": typekind = "enum"; break;
2262 case "Structure": typekind = "struct"; break;
2263 case "Delegate": typekind = "delegate"; break;
2264 case "Interface": typekind = "interface"; break;
2265 default: throw new InvalidOperationException();
2268 XmlElement typenode = elements.CreateElement(typekind);
2269 typenode.SetAttribute("name", EcmaDoc.GetDisplayName (t).Replace ('+', '.'));
2270 typenode.SetAttribute("fullname", ns + "." + t.GetAttribute("Name"));
2271 typenode.AppendChild(elements.ImportNode(typedoc.SelectSingleNode("Type/Docs/summary"), true));
2273 docnode.AppendChild(typenode);
2279 public override Stream GetHelpStream (string id)
2281 if (id == "ExtensionMethods.xml") {
2282 // TODO: generate ExtensionMethods.xml based on index.xml contents.
2287 public override XmlDocument GetHelpXmlWithChanges (string id)
2289 XmlDocument doc = new XmlDocument ();
2294 class UncompiledResolver : XmlResolver {
2295 public override Uri ResolveUri (Uri baseUri, string relativeUri)
2300 public override object GetEntity (Uri absoluteUri, string role, Type ofObjectToReturn)
2305 public override System.Net.ICredentials Credentials {
2310 protected override XmlResolver CreateDocumentResolver ()
2312 return new UncompiledResolver ();