-
-
Save infogulch/81947d1911454c64ba8e9af29134c5e2 to your computer and use it in GitHub Desktop.
Incomplete methods for pretty-printing LanguageExt types
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static PrettifyExtensions | |
{ | |
public static string Prettify(this Type t) | |
{ | |
if (t.IsArray) | |
{ | |
return Prettify(t.GetElementType()) + "[]"; | |
} | |
if (t.IsValueTupleType()) // external extension method | |
{ | |
return string.Format( | |
"({1})", | |
t.Name.Substring(0, t.Name.LastIndexOf("`", StringComparison.InvariantCulture)), | |
t.GetGenericArguments().Select(Prettify).Join(", ") | |
); | |
} | |
if (t.IsGenericType) | |
{ | |
return string.Format( | |
"{0}<{1}>", | |
t.Name.Substring(0, t.Name.LastIndexOf("`", StringComparison.InvariantCulture)), | |
t.GetGenericArguments().Select(Prettify).Join(", ") | |
); | |
} | |
return t.Name; | |
} | |
public static string Prettify<T>(T t) => Prettify((object)t); | |
public static string Prettify(this object o) | |
{ | |
if (o is Type t) | |
return t.Prettify(); | |
// Unwrap is an extension method to get tuple types and values | |
if (o.IsValueTuple()) | |
return $"({ValidationExtensions.Unwrap(o).values.Map(Prettify).Join(", ")})"; // syntax highlighting doesn't understand $" yet it seems | |
var ot = o.GetType(); | |
if (!ot.IsGenericType) | |
return o.ToString(); | |
var otd = ot.GetGenericTypeDefinition(); | |
if (otd == typeof(Seq<>)) | |
return (string)InvokeGenericMethod(typeof(Extensions), "PrettifySeq", ot.GenericTypeArguments, null, o); | |
return o.ToString(); | |
} | |
public static string PrettifySeq<T>(this Seq<T> s) => $"Seq({s.Map(Prettify).Join(", ")})"; // $" | |
public static object InvokeGenericMethod(Type t, string methodName, Type[] types, object self, params object[] parameters) => | |
t.GetMethod(methodName).MakeGenericMethod(types).Invoke(self, parameters); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment