2 // outline -- support for rendering in monop
3 // Some code stolen from updater.cs in monodoc.
6 // Ben Maurer (bmaurer@users.sourceforge.net)
12 // Permission is hereby granted, free of charge, to any person obtaining
13 // a copy of this software and associated documentation files (the
14 // "Software"), to deal in the Software without restriction, including
15 // without limitation the rights to use, copy, modify, merge, publish,
16 // distribute, sublicense, and/or sell copies of the Software, and to
17 // permit persons to whom the Software is furnished to do so, subject to
18 // the following conditions:
20 // The above copyright notice and this permission notice shall be
21 // included in all copies or substantial portions of the Software.
23 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
24 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
25 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
26 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
27 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
28 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
29 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
35 using System.Reflection;
36 using System.Collections;
37 using System.CodeDom.Compiler;
41 namespace Mono.CSharp {
42 public class Outline {
51 public Outline (Type t, TextWriter output, bool declared_only, bool show_private, bool filter_obsolete)
54 this.o = new IndentedTextWriter (output, "\t");
55 this.declared_only = declared_only;
56 this.show_private = show_private;
57 this.filter_obsolete = filter_obsolete;
60 public void OutlineType ()
65 o.Write (GetTypeVisibility (t));
67 if (t.IsClass && !t.IsSubclassOf (typeof (System.MulticastDelegate))) {
69 o.Write (t.IsAbstract ? " static" : " sealed");
70 else if (t.IsAbstract)
71 o.Write (" abstract");
75 o.Write (GetTypeKind (t));
78 Type [] interfaces = (Type []) Comparer.Sort (TypeGetInterfaces (t, declared_only));
79 Type parent = t.BaseType;
81 if (t.IsSubclassOf (typeof (System.MulticastDelegate))) {
84 method = t.GetMethod ("Invoke");
86 o.Write (FormatType (method.ReturnType));
88 o.Write (GetTypeName (t));
90 OutlineParams (method.GetParameters ());
93 WriteGenericConstraints (t.GetGenericArguments ());
99 o.Write (GetTypeName (t));
100 if (((parent != null && parent != typeof (object) && parent != typeof (ValueType)) || interfaces.Length != 0) && ! t.IsEnum) {
104 if (parent != null && parent != typeof (object) && parent != typeof (ValueType)) {
105 o.Write (FormatType (parent));
109 foreach (Type intf in interfaces) {
110 if (!first) o.Write (", ");
113 o.Write (FormatType (intf));
118 Type underlyingType = System.Enum.GetUnderlyingType (t);
119 if (underlyingType != typeof (int))
120 o.Write (" : {0}", FormatType (underlyingType));
123 WriteGenericConstraints (t.GetGenericArguments ());
129 bool is_first = true;
130 foreach (FieldInfo fi in t.GetFields (BindingFlags.Public | BindingFlags.Static)) {
138 o.Indent--; o.WriteLine ("}");
144 foreach (ConstructorInfo ci in t.GetConstructors (DefaultFlags)) {
145 if (! ShowMember (ci))
152 OutlineMemberAttribute (ci);
153 OutlineConstructor (ci);
161 foreach (MethodInfo m in Comparer.Sort (t.GetMethods (DefaultFlags))) {
163 if (! ShowMember (m))
166 if ((m.Attributes & MethodAttributes.SpecialName) != 0)
173 OutlineMemberAttribute (m);
181 foreach (MethodInfo m in t.GetMethods (DefaultFlags)) {
183 if (! ShowMember (m))
186 if ((m.Attributes & MethodAttributes.SpecialName) == 0)
188 if (!(m.Name.StartsWith ("op_")))
195 OutlineMemberAttribute (m);
203 foreach (PropertyInfo pi in Comparer.Sort (t.GetProperties (DefaultFlags))) {
205 if (! ((pi.CanRead && ShowMember (pi.GetGetMethod (true))) ||
206 (pi.CanWrite && ShowMember (pi.GetSetMethod (true)))))
213 OutlineMemberAttribute (pi);
214 OutlineProperty (pi);
221 foreach (FieldInfo fi in t.GetFields (DefaultFlags)) {
223 if (! ShowMember (fi))
230 OutlineMemberAttribute (fi);
238 foreach (EventInfo ei in Comparer.Sort (t.GetEvents (DefaultFlags))) {
240 if (! ShowMember (ei.GetAddMethod (true)))
247 OutlineMemberAttribute (ei);
255 foreach (Type ntype in Comparer.Sort (t.GetNestedTypes (DefaultFlags))) {
257 if (! ShowMember (ntype))
264 new Outline (ntype, o, declared_only, show_private, filter_obsolete).OutlineType ();
267 o.Indent--; o.WriteLine ("}");
270 BindingFlags DefaultFlags {
272 BindingFlags f = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
275 f |= BindingFlags.DeclaredOnly;
281 // FIXME: add other interesting attributes?
282 void OutlineAttributes ()
284 if (t.IsSerializable)
285 o.WriteLine ("[Serializable]");
287 if (t.IsDefined (typeof (System.FlagsAttribute), true))
288 o.WriteLine ("[Flags]");
290 if (t.IsDefined (typeof (System.ObsoleteAttribute), true))
291 o.WriteLine ("[Obsolete]");
294 void OutlineMemberAttribute (MemberInfo mi)
296 if (!mi.IsDefined (typeof (System.ObsoleteAttribute), false))
298 var oa = mi.GetCustomAttributes (typeof (System.ObsoleteAttribute), false) [0] as ObsoleteAttribute;
299 var msg = oa.Message;
300 o.WriteLine ("[Obsolete{0}]", msg == null || msg == "" ? "" : string.Format ("(\"{0}\")", msg));
303 void OutlineEvent (EventInfo ei)
305 MethodBase accessor = ei.GetAddMethod (true);
307 o.Write (GetMethodVisibility (accessor));
309 o.Write (FormatType (ei.EventHandlerType));
315 void OutlineConstructor (ConstructorInfo ci)
317 o.Write (GetMethodVisibility (ci));
318 o.Write (RemoveGenericArity (t.Name));
320 OutlineParams (ci.GetParameters ());
325 void OutlineProperty (PropertyInfo pi)
327 ParameterInfo [] idxp = pi.GetIndexParameters ();
328 MethodBase g = pi.GetGetMethod (true);
329 MethodBase s = pi.GetSetMethod (true);
330 MethodBase accessor = g != null ? g : s;
332 if (pi.CanRead && pi.CanWrite) {
335 // Get the more accessible accessor
336 if ((g.Attributes & MethodAttributes.MemberAccessMask) !=
337 (s.Attributes & MethodAttributes.MemberAccessMask)) {
339 if (g.IsPublic) accessor = g;
340 else if (s.IsPublic) accessor = s;
341 else if (g.IsFamilyOrAssembly) accessor = g;
342 else if (s.IsFamilyOrAssembly) accessor = s;
343 else if (g.IsAssembly || g.IsFamily) accessor = g;
344 else if (s.IsAssembly || s.IsFamily) accessor = s;
348 o.Write (GetMethodVisibility (accessor));
349 o.Write (GetMethodModifiers (accessor));
350 o.Write (FormatType (pi.PropertyType));
353 if (idxp.Length == 0)
357 OutlineParams (idxp);
364 if (g != null && ShowMember (g)) {
365 if ((g.Attributes & MethodAttributes.MemberAccessMask) !=
366 (accessor.Attributes & MethodAttributes.MemberAccessMask))
367 o.Write (GetMethodVisibility (g));
368 o.WriteLine ("get;");
371 if (s != null && ShowMember (s)) {
372 if ((s.Attributes & MethodAttributes.MemberAccessMask) !=
373 (accessor.Attributes & MethodAttributes.MemberAccessMask))
374 o.Write (GetMethodVisibility (s));
375 o.WriteLine ("set;");
382 void OutlineMethod (MethodInfo mi)
384 if (MethodIsExplicitIfaceImpl (mi)) {
385 o.Write (FormatType (mi.ReturnType));
387 // MSFT has no way to get the method that we are overriding
388 // from the interface. this would allow us to pretty print
389 // the type name (and be more correct if there compiler
390 // were to do some strange naming thing).
392 o.Write (GetMethodVisibility (mi));
393 o.Write (GetMethodModifiers (mi));
394 o.Write (FormatType (mi.ReturnType));
399 o.Write (FormatGenericParams (mi.GetGenericArguments ()));
401 OutlineParams (mi.GetParameters ());
403 WriteGenericConstraints (mi.GetGenericArguments ());
407 void OutlineOperator (MethodInfo mi)
409 o.Write (GetMethodVisibility (mi));
410 o.Write (GetMethodModifiers (mi));
411 if (mi.Name == "op_Explicit" || mi.Name == "op_Implicit") {
412 o.Write (mi.Name.Substring (3).ToLower ());
413 o.Write (" operator ");
414 o.Write (FormatType (mi.ReturnType));
416 o.Write (FormatType (mi.ReturnType));
417 o.Write (" operator ");
418 o.Write (OperatorFromName (mi.Name));
421 OutlineParams (mi.GetParameters ());
425 void OutlineParams (ParameterInfo [] pi)
428 foreach (ParameterInfo p in pi) {
429 if (p.ParameterType.IsByRef) {
430 o.Write (p.IsOut ? "out " : "ref ");
431 o.Write (FormatType (p.ParameterType.GetElementType ()));
432 } else if (p.IsDefined (typeof (ParamArrayAttribute), false)) {
434 o.Write (FormatType (p.ParameterType));
436 o.Write (FormatType (p.ParameterType));
441 if (i + 1 < pi.Length)
447 void OutlineField (FieldInfo fi)
449 if (fi.IsPublic) o.Write ("public ");
450 if (fi.IsFamily) o.Write ("protected ");
451 if (fi.IsPrivate) o.Write ("private ");
452 if (fi.IsAssembly) o.Write ("internal ");
453 if (fi.IsLiteral) o.Write ("const ");
454 else if (fi.IsStatic) o.Write ("static ");
455 if (fi.IsInitOnly) o.Write ("readonly ");
457 o.Write (FormatType (fi.FieldType));
461 object v = fi.GetValue (this);
463 // TODO: Escape values here
466 o.Write ("'{0}'", v);
467 else if (v is string)
468 o.Write ("\"{0}\"", v);
470 o.Write (fi.GetValue (this));
475 static string GetMethodVisibility (MethodBase m)
477 // itnerfaces have no modifiers here
478 if (m.DeclaringType.IsInterface)
481 if (m.IsPublic) return "public ";
482 if (m.IsFamily) return "protected ";
483 if (m.IsPrivate) return "private ";
484 if (m.IsAssembly) return "internal ";
489 static string GetMethodModifiers (MethodBase method)
494 if (method.IsFinal) {
495 // This will happen if you have
497 // public void A () {}
498 // static void Main () {}
504 // A needs to be virtual (the CLR requires
505 // methods implementing an iface be virtual),
506 // but can not be inherited. It also can not
507 // be inherited. In C# this is represented
508 // with no special modifiers
510 if (method.IsVirtual)
515 // all interface methods are "virtual" but we don't say that in c#
516 if (method.IsVirtual && !method.DeclaringType.IsInterface) {
517 if (method.IsAbstract)
520 return ((method.Attributes & MethodAttributes.NewSlot) != 0) ?
528 static string GetTypeKind (Type t)
533 if (t.IsSubclassOf (typeof (System.MulticastDelegate)))
545 static string GetTypeVisibility (Type t)
547 switch (t.Attributes & TypeAttributes.VisibilityMask){
548 case TypeAttributes.Public:
549 case TypeAttributes.NestedPublic:
552 case TypeAttributes.NestedFamily:
553 case TypeAttributes.NestedFamANDAssem:
554 case TypeAttributes.NestedFamORAssem:
562 string FormatGenericParams (Type [] args)
564 StringBuilder sb = new StringBuilder ();
565 if (args.Length == 0)
569 for (int i = 0; i < args.Length; i++) {
572 sb.Append (FormatType (args [i]));
575 return sb.ToString ();
578 // TODO: fine tune this so that our output is less verbose. We need to figure
579 // out a way to do this while not making things confusing.
580 string FormatType (Type t)
585 string type = GetFullName (t);
587 return t.ToString ();
589 if (!type.StartsWith ("System.")) {
590 if (t.Namespace == this.t.Namespace)
595 if (t.HasElementType) {
596 Type et = t.GetElementType ();
598 return FormatType (et) + " []";
600 return FormatType (et) + " *";
602 return "ref " + FormatType (et);
606 case "System.Byte": return "byte";
607 case "System.SByte": return "sbyte";
608 case "System.Int16": return "short";
609 case "System.Int32": return "int";
610 case "System.Int64": return "long";
612 case "System.UInt16": return "ushort";
613 case "System.UInt32": return "uint";
614 case "System.UInt64": return "ulong";
616 case "System.Single": return "float";
617 case "System.Double": return "double";
618 case "System.Decimal": return "decimal";
619 case "System.Boolean": return "bool";
620 case "System.Char": return "char";
621 case "System.String": return "string";
623 case "System.Object": return "object";
624 case "System.Void": return "void";
627 if (type.LastIndexOf(".") == 6)
628 return type.Substring(7);
631 // If the namespace of the type is the namespace of what
632 // we are printing (or is a member of one if its children
633 // don't print it. This basically means that in C# we would
634 // automatically get the namespace imported by virtue of the
635 // namespace {} block.
637 if (this.t.Namespace.StartsWith (t.Namespace + ".") || t.Namespace == this.t.Namespace)
638 return type.Substring (t.Namespace.Length + 1);
643 public static string RemoveGenericArity (string name)
646 StringBuilder sb = new StringBuilder ();
647 while (start < name.Length) {
648 int pos = name.IndexOf ('`', start);
650 sb.Append (name.Substring (start));
653 sb.Append (name.Substring (start, pos-start));
657 while ((pos < name.Length) && Char.IsNumber (name [pos]))
663 return sb.ToString ();
666 string GetTypeName (Type t)
668 StringBuilder sb = new StringBuilder ();
670 return sb.ToString ();
673 void GetTypeName (StringBuilder sb, Type t)
675 sb.Append (RemoveGenericArity (t.Name));
676 sb.Append (FormatGenericParams (t.GetGenericArguments ()));
679 string GetFullName (Type t)
681 StringBuilder sb = new StringBuilder ();
682 GetFullName_recursed (sb, t, false);
683 return sb.ToString ();
686 void GetFullName_recursed (StringBuilder sb, Type t, bool recursed)
688 if (t.IsGenericParameter) {
693 if (t.DeclaringType != null) {
694 GetFullName_recursed (sb, t.DeclaringType, true);
699 string ns = t.Namespace;
700 if ((ns != null) && (ns != "")) {
709 void WriteGenericConstraints (Type [] args)
712 foreach (Type t in args) {
714 Type[] ifaces = TypeGetInterfaces (t, true);
716 GenericParameterAttributes attrs = t.GenericParameterAttributes & GenericParameterAttributes.SpecialConstraintMask;
717 GenericParameterAttributes [] interesting = {
718 GenericParameterAttributes.ReferenceTypeConstraint,
719 GenericParameterAttributes.NotNullableValueTypeConstraint,
720 GenericParameterAttributes.DefaultConstructorConstraint
723 if (t.BaseType != typeof (object) || ifaces.Length != 0 || attrs != 0) {
725 o.Write (FormatType (t));
729 if (t.BaseType != typeof (object)) {
730 o.Write (FormatType (t.BaseType));
734 foreach (Type iface in ifaces) {
739 o.Write (FormatType (iface));
742 foreach (GenericParameterAttributes a in interesting) {
743 if ((attrs & a) == 0)
751 case GenericParameterAttributes.ReferenceTypeConstraint:
754 case GenericParameterAttributes.NotNullableValueTypeConstraint:
757 case GenericParameterAttributes.DefaultConstructorConstraint:
765 string OperatorFromName (string name)
768 case "op_UnaryPlus": return "+";
769 case "op_UnaryNegation": return "-";
770 case "op_LogicalNot": return "!";
771 case "op_OnesComplement": return "~";
772 case "op_Increment": return "++";
773 case "op_Decrement": return "--";
774 case "op_True": return "true";
775 case "op_False": return "false";
776 case "op_Addition": return "+";
777 case "op_Subtraction": return "-";
778 case "op_Multiply": return "*";
779 case "op_Division": return "/";
780 case "op_Modulus": return "%";
781 case "op_BitwiseAnd": return "&";
782 case "op_BitwiseOr": return "|";
783 case "op_ExclusiveOr": return "^";
784 case "op_LeftShift": return "<<";
785 case "op_RightShift": return ">>";
786 case "op_Equality": return "==";
787 case "op_Inequality": return "!=";
788 case "op_GreaterThan": return ">";
789 case "op_LessThan": return "<";
790 case "op_GreaterThanOrEqual": return ">=";
791 case "op_LessThanOrEqual": return "<=";
792 default: return name;
796 bool MethodIsExplicitIfaceImpl (MethodBase mb)
798 if (!(mb.IsFinal && mb.IsVirtual && mb.IsPrivate))
801 // UGH msft has no way to get the info about what method is
802 // getting overriden. Another reason to use cecil :-)
804 //MethodInfo mi = mb as MethodInfo;
808 //Console.WriteLine (mi.GetBaseDefinition ().DeclaringType);
809 //return mi.GetBaseDefinition ().DeclaringType.IsInterface;
811 // So, we guess that virtual final private methods only come
816 bool ShowMember (MemberInfo mi)
818 if (mi.MemberType == MemberTypes.Constructor && ((MethodBase) mi).IsStatic)
824 if (filter_obsolete && mi.IsDefined (typeof (ObsoleteAttribute), false))
827 switch (mi.MemberType) {
828 case MemberTypes.Constructor:
829 case MemberTypes.Method:
830 MethodBase mb = mi as MethodBase;
832 if (mb.IsFamily || mb.IsPublic || mb.IsFamilyOrAssembly)
835 if (MethodIsExplicitIfaceImpl (mb))
841 case MemberTypes.Field:
842 FieldInfo fi = mi as FieldInfo;
844 if (fi.IsFamily || fi.IsPublic || fi.IsFamilyOrAssembly)
850 case MemberTypes.NestedType:
851 case MemberTypes.TypeInfo:
854 switch (t.Attributes & TypeAttributes.VisibilityMask){
855 case TypeAttributes.Public:
856 case TypeAttributes.NestedPublic:
857 case TypeAttributes.NestedFamily:
858 case TypeAttributes.NestedFamORAssem:
869 static Type [] TypeGetInterfaces (Type t, bool declonly)
871 if (t.IsGenericParameter)
874 Type [] ifaces = t.GetInterfaces ();
878 // Handle Object. Also, optimize for no interfaces
879 if (t.BaseType == null || ifaces.Length == 0)
882 ArrayList ar = new ArrayList ();
884 foreach (Type i in ifaces)
885 if (! i.IsAssignableFrom (t.BaseType))
888 return (Type []) ar.ToArray (typeof (Type));
892 public class Comparer : IComparer {
893 delegate int ComparerFunc (object a, object b);
897 Comparer (ComparerFunc f)
902 public int Compare (object a, object b)
907 static int CompareType (object a, object b)
909 Type type1 = (Type) a;
910 Type type2 = (Type) b;
912 if (type1.IsSubclassOf (typeof (System.MulticastDelegate)) != type2.IsSubclassOf (typeof (System.MulticastDelegate)))
913 return (type1.IsSubclassOf (typeof (System.MulticastDelegate)))? -1:1;
914 return string.Compare (type1.Name, type2.Name);
918 // static Comparer TypeComparer = new Comparer (new ComparerFunc (CompareType));
920 // static Type [] Sort (Type [] types)
922 // Array.Sort (types, TypeComparer);
926 static int CompareMemberInfo (object a, object b)
928 return string.Compare (((MemberInfo) a).Name, ((MemberInfo) b).Name);
931 static Comparer MemberInfoComparer = new Comparer (new ComparerFunc (CompareMemberInfo));
933 public static MemberInfo [] Sort (MemberInfo [] inf)
935 Array.Sort (inf, MemberInfoComparer);
939 static int CompareMethodBase (object a, object b)
941 MethodBase aa = (MethodBase) a, bb = (MethodBase) b;
943 if (aa.IsStatic == bb.IsStatic) {
944 int c = CompareMemberInfo (a, b);
947 ParameterInfo [] ap, bp;
950 // Sort overloads by the names of their types
951 // put methods with fewer params first.
954 ap = aa.GetParameters ();
955 bp = bb.GetParameters ();
956 int n = System.Math.Min (ap.Length, bp.Length);
958 for (int i = 0; i < n; i ++)
959 if ((c = CompareType (ap [i].ParameterType, bp [i].ParameterType)) != 0)
962 return ap.Length.CompareTo (bp.Length);
970 static Comparer MethodBaseComparer = new Comparer (new ComparerFunc (CompareMethodBase));
972 public static MethodBase [] Sort (MethodBase [] inf)
974 Array.Sort (inf, MethodBaseComparer);
978 static int ComparePropertyInfo (object a, object b)
980 PropertyInfo aa = (PropertyInfo) a, bb = (PropertyInfo) b;
982 bool astatic = (aa.CanRead ? aa.GetGetMethod (true) : aa.GetSetMethod (true)).IsStatic;
983 bool bstatic = (bb.CanRead ? bb.GetGetMethod (true) : bb.GetSetMethod (true)).IsStatic;
985 if (astatic == bstatic)
986 return CompareMemberInfo (a, b);
994 static Comparer PropertyInfoComparer = new Comparer (new ComparerFunc (ComparePropertyInfo));
996 public static PropertyInfo [] Sort (PropertyInfo [] inf)
998 Array.Sort (inf, PropertyInfoComparer);
1002 static int CompareEventInfo (object a, object b)
1004 EventInfo aa = (EventInfo) a, bb = (EventInfo) b;
1006 bool astatic = aa.GetAddMethod (true).IsStatic;
1007 bool bstatic = bb.GetAddMethod (true).IsStatic;
1009 if (astatic == bstatic)
1010 return CompareMemberInfo (a, b);
1018 static Comparer EventInfoComparer = new Comparer (new ComparerFunc (CompareEventInfo));
1020 public static EventInfo [] Sort (EventInfo [] inf)
1022 Array.Sort (inf, EventInfoComparer);