From bed44db6420864e2f32d06db1d41416c93f59afb Mon Sep 17 00:00:00 2001 From: John Colvin Date: Tue, 12 Jul 2022 12:53:36 -0400 Subject: [PATCH] refactor: Clean up ReflectionHelper a bit * Rename '(static_)property_delegates_of_type' -> '(static_)property_getters', and include name w/ prop getters * Rename 'FindApplicableConstructor' -> 'get_constructor' * Remove unused fns --- .../AW2/ViewModel/VolSurfaceMacroActionsVM.cs | 4 +- .../Market/MarketView/MarketViewSettings.cs | 4 +- .../Modules/Market/MarketView/MarketViewVM.cs | 4 +- .../Settings/TimeAndSalesSettings.cs | 4 +- .../Market/TimeAndSales/TimeAndSalesVM.cs | 4 +- .../AlgoParamTemplateSelector.cs | 2 +- .../spark/Modules/Trading/PNL/VM/PNLVM.cs | 5 +- .../ReconcileReportSettings.cs | 4 +- .../core/Collections/ObservableAutoWrapper.cs | 2 +- .../core/Utility/PropertyChangeDetector.cs | 9 +- .../Filters/DataGridFilterHelper.cs | 5 +- .../Extensions/EnumerableExtensions.cs | 10 ++ .../spark_core/Reflection/ReflectionHelper.cs | 127 +++--------------- 13 files changed, 52 insertions(+), 132 deletions(-) diff --git a/src/client/spark/AW2/ViewModel/VolSurfaceMacroActionsVM.cs b/src/client/spark/AW2/ViewModel/VolSurfaceMacroActionsVM.cs index 7a31bcba5..087b34df1 100644 --- a/src/client/spark/AW2/ViewModel/VolSurfaceMacroActionsVM.cs +++ b/src/client/spark/AW2/ViewModel/VolSurfaceMacroActionsVM.cs @@ -77,8 +77,8 @@ public IRaiseCanExecuteChangedCommand vol_shift { get; } IEnumerable _commands => - ReflectionHelper.property_delegates_of_type() - .Select(g => g(this)); + ReflectionHelper.property_getters() + .Select(pg => pg.get(this)); public void selection_changed(IEnumerable selected) { _selected_exps = selected.ToList(); diff --git a/src/client/spark/Modules/Market/MarketView/MarketViewSettings.cs b/src/client/spark/Modules/Market/MarketView/MarketViewSettings.cs index 827a33468..dbceb2b8e 100644 --- a/src/client/spark/Modules/Market/MarketView/MarketViewSettings.cs +++ b/src/client/spark/Modules/Market/MarketView/MarketViewSettings.cs @@ -137,8 +137,8 @@ namespace bts.shell.market_view { } public static IEnumerable all => - ReflectionHelper.static_property_delegates_of_type(typeof(DefaultColumns)) - .Select(g => g()); + ReflectionHelper.static_property_getters(typeof(DefaultColumns)) + .Select(pg => pg.get()); static GridColumnSettings _mk(Columns key, string display_name = null, double width = 80, bool is_visible = true, Color? fg = null, Color? bg = null, HorizontalAlignment h_align = HorizontalAlignment.Right) => new(col_id(key), display_name, is_visible, font_color_override: fg, width: width, horizontal_alignment: h_align, background_color_override: bg); diff --git a/src/client/spark/Modules/Market/MarketView/MarketViewVM.cs b/src/client/spark/Modules/Market/MarketView/MarketViewVM.cs index 34c232511..f8dd5df47 100644 --- a/src/client/spark/Modules/Market/MarketView/MarketViewVM.cs +++ b/src/client/spark/Modules/Market/MarketView/MarketViewVM.cs @@ -47,8 +47,8 @@ namespace mbts.spark { /// Viewmodel class designed for /// partial class MarketViewVM : DisposableViewModelBase, IHandleRowSelection { - static readonly IReadOnlyList>> _filter_getters = - ReflectionHelper.property_delegates_of_type>().ToReadOnlyList(); + static readonly IEnumerable>> _filter_getters = + ReflectionHelper.property_getters>().Cut2(); static readonly IComparer _sec_md_key_comparer = Comparer.Default.wrap(SecurityMD.key_fn); static readonly IComparer _row_key_comparer = _sec_md_key_comparer.wrap(r => r.security_md); diff --git a/src/client/spark/Modules/Market/TimeAndSales/Settings/TimeAndSalesSettings.cs b/src/client/spark/Modules/Market/TimeAndSales/Settings/TimeAndSalesSettings.cs index 7f229068d..f11df7be9 100644 --- a/src/client/spark/Modules/Market/TimeAndSales/Settings/TimeAndSalesSettings.cs +++ b/src/client/spark/Modules/Market/TimeAndSales/Settings/TimeAndSalesSettings.cs @@ -132,8 +132,8 @@ namespace bts.shell.time_and_sales { } public static IEnumerable all => - ReflectionHelper.static_property_delegates_of_type(typeof(DefaultColumns)) - .Select(g => g()); + ReflectionHelper.static_property_getters(typeof(DefaultColumns)) + .Select(pg => pg.get()); static GridColumnSettings _mk_col( ColKey key, diff --git a/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesVM.cs b/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesVM.cs index 7d6db3b29..fa112426e 100644 --- a/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesVM.cs +++ b/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesVM.cs @@ -281,8 +281,8 @@ } IEnumerable> _filters => - ReflectionHelper.property_delegates_of_type>() - .Select(fn => fn(this)); + ReflectionHelper.property_getters>() + .Select(pg => pg.get(this)); public (TimeAndSalesFilterSettings filters, IReadOnlyList sorting_criteria, GridSettings grid_settings) create() => (_get_filter_states(), _sorting_criteria, grid_settings_manager.create()); diff --git a/src/client/spark/Modules/Trading/AlgoStudio/View/AlgoEditorGridView/AlgoParamTemplateSelector.cs b/src/client/spark/Modules/Trading/AlgoStudio/View/AlgoEditorGridView/AlgoParamTemplateSelector.cs index 2f3cdf1eb..0e2886807 100644 --- a/src/client/spark/Modules/Trading/AlgoStudio/View/AlgoEditorGridView/AlgoParamTemplateSelector.cs +++ b/src/client/spark/Modules/Trading/AlgoStudio/View/AlgoEditorGridView/AlgoParamTemplateSelector.cs @@ -63,7 +63,7 @@ namespace mbts.ui.spark { if (pvm is IAlgoParamVM) return QuantityMeasureTemplate; if (pvm is IAlgoParamVM) return ExecutionStrategyTemplate; if (pvm is IAlgoParamVM) return TimestampTemplate; - var targ = ReflectionHelper.GetGenericTypeArgs(pvm.GetType(), generic_algo_param_itype).FirstOrDefault(); + var targ = ReflectionHelper.get_generic_type_args(pvm.GetType(), generic_algo_param_itype).FirstOrDefault(); if (targ != null) { if (targ.IsEnum) return EnumTemplate; diff --git a/src/client/spark/Modules/Trading/PNL/VM/PNLVM.cs b/src/client/spark/Modules/Trading/PNL/VM/PNLVM.cs index a23bff661..051791059 100644 --- a/src/client/spark/Modules/Trading/PNL/VM/PNLVM.cs +++ b/src/client/spark/Modules/Trading/PNL/VM/PNLVM.cs @@ -39,8 +39,9 @@ using SecurityType = api.Security.ContractOneofCase; class PNLVM : DisposableViewModelBase, IHandleRowSelection { - static readonly IReadOnlyList>> _filter_getters = - ReflectionHelper.property_delegates_of_type>().ToReadOnlyList(); + static readonly IEnumerable>> _filter_getters = + ReflectionHelper.property_getters>().Cut2(); + static readonly TimeSpan _auxiliary_grid_update_throttle = TimeSpan.FromSeconds(0.2); // delegates static readonly Func _order_pnl_key_fn = o => new PNLKey(o.order.order.account_id(), o.order.order.security_key()); diff --git a/src/client/spark/Modules/Trading/ReconcileReport/ReconcileReportSettings.cs b/src/client/spark/Modules/Trading/ReconcileReport/ReconcileReportSettings.cs index 194b6e55d..20d273ba7 100644 --- a/src/client/spark/Modules/Trading/ReconcileReport/ReconcileReportSettings.cs +++ b/src/client/spark/Modules/Trading/ReconcileReport/ReconcileReportSettings.cs @@ -119,8 +119,8 @@ namespace Spark.Trading { } public static IEnumerable all => - ReflectionHelper.static_property_delegates_of_type(typeof(DefaultColumns)) - .Select(g => g()); + ReflectionHelper.static_property_getters(typeof(DefaultColumns)) + .Select(pg => pg.get()); static GridColumnSettings _mk( ColKey key, diff --git a/src/client/spark/core/Collections/ObservableAutoWrapper.cs b/src/client/spark/core/Collections/ObservableAutoWrapper.cs index bf4378901..76d5d2799 100644 --- a/src/client/spark/core/Collections/ObservableAutoWrapper.cs +++ b/src/client/spark/core/Collections/ObservableAutoWrapper.cs @@ -498,7 +498,7 @@ namespace mbts.ui.utility { public class ObservableAutoWrapper : ObservableCollection { private static Func _get_default_converter() { - var constructor = ReflectionHelper.FindApplicableConstructor(typeof(View), typeof(Model)); + var constructor = ReflectionHelper.get_constructor(typeof(View), typeof(Model)); if (constructor == null) throw new InvalidOperationException("[{0}] {1} type does not have a public constructor({0})".fmt(typeof(ObservableAutoWrapper), typeof(View), typeof(Model))); return model => (View)constructor.Invoke(new object[] { model }); diff --git a/src/client/spark/core/Utility/PropertyChangeDetector.cs b/src/client/spark/core/Utility/PropertyChangeDetector.cs index 94bbf9b8f..09a7fc806 100644 --- a/src/client/spark/core/Utility/PropertyChangeDetector.cs +++ b/src/client/spark/core/Utility/PropertyChangeDetector.cs @@ -27,7 +27,7 @@ // convert to a hashset for quicker lookups var exclude = new HashSet(except_props); return new PropertyChangeDetector( - ReflectionHelper.get_props() + ReflectionHelper.properties() .Where(p => !exclude.Contains(p.Name)) .Select(p => p.Name) .ToArray()); @@ -52,9 +52,10 @@ readonly (string name, Action initialize, Func refresh)[] _property_monitors; public PropertyChangeDetector() { - _property_monitors = new (string name, Action initialize, Func refresh)[ReflectionHelper.get_props().Count]; + var num_props = ReflectionHelper.properties().Count; + _property_monitors = new (string, Action, Func)[num_props]; int i = 0; - foreach (var pad in ReflectionHelper.prop_accessors().Values) { + foreach (var pad in ReflectionHelper.property_accessors().Values) { var (initialize, refresh) = pad.create_snapshot(); _property_monitors[i++] = (pad.prop_info.Name, initialize, refresh); } @@ -64,7 +65,7 @@ _property_monitors = new (string name, Action initialize, Func refresh)[props.Length]; int ppos = 0, pm_pos = 0; while (ppos < props.Length) { - if (ReflectionHelper.prop_accessors().TryGetValue(props[ppos++], out var pad)) { + if (ReflectionHelper.property_accessors().TryGetValue(props[ppos++], out var pad)) { var (initialize, refresh) = pad.create_snapshot(); _property_monitors[pm_pos++] = (pad.prop_info.Name, initialize, refresh); } diff --git a/src/client/spark/view/Controls/DataGridEx/Filters/DataGridFilterHelper.cs b/src/client/spark/view/Controls/DataGridEx/Filters/DataGridFilterHelper.cs index 21708f10a..ca082f792 100644 --- a/src/client/spark/view/Controls/DataGridEx/Filters/DataGridFilterHelper.cs +++ b/src/client/spark/view/Controls/DataGridEx/Filters/DataGridFilterHelper.cs @@ -11,8 +11,9 @@ static class DataGridFilterHelper { public static IDisposable hook_all(TSource source, ICollectionView rows) => hook_filters(rows, - ReflectionHelper.property_delegates_of_type>() - .Select(f => f(source)) + ReflectionHelper.property_getters>() + .Cut2() + .Curry(source) .ExceptNull() .ToList()); diff --git a/src/client/spark_core/Collections/Extensions/EnumerableExtensions.cs b/src/client/spark_core/Collections/Extensions/EnumerableExtensions.cs index be462dd99..0de0933e1 100644 --- a/src/client/spark_core/Collections/Extensions/EnumerableExtensions.cs +++ b/src/client/spark_core/Collections/Extensions/EnumerableExtensions.cs @@ -48,6 +48,16 @@ namespace System.Collections.Generic { } } + public static IEnumerable Cut1(this IEnumerable<(T1, T2)> source) => + source.Select(tup => tup.Item1); + + public static IEnumerable Cut2(this IEnumerable<(T1, T2)> source) => + source.Select(tup => tup.Item2); + + public static IEnumerable Curry( + this IEnumerable> fns, TIn input) => + fns.Select(fn => fn(input)); + public static IEnumerable SelectWhereValues(this IEnumerable source) where T : struct { foreach (var v in source) { if (v.HasValue) { diff --git a/src/client/spark_core/Reflection/ReflectionHelper.cs b/src/client/spark_core/Reflection/ReflectionHelper.cs index 533d1aba6..2e58d8e96 100644 --- a/src/client/spark_core/Reflection/ReflectionHelper.cs +++ b/src/client/spark_core/Reflection/ReflectionHelper.cs @@ -19,7 +19,7 @@ static class ReflectionHelper { /// /// Searches for a constructor with any set of parameters that are assignable by the types in - /// + /// /// /// The type of the constructor to be sought /// The argument-types of the constructor to find @@ -27,101 +27,13 @@ /// The for with parameter types that /// match or are implicit in Type[] types argument /// - public static ConstructorInfo FindApplicableConstructor( + public static ConstructorInfo get_constructor( Type target_type, params Type[] ctr_type_args) { var constructors = target_type.GetConstructors(); return _find_explicit_constructor(constructors, ctr_type_args) ?? _find_implicit_constructor(constructors, ctr_type_args); } - /// - /// Creates an instance of a generic type - /// - /// The generic type definition of object to create - /// The generic type arguments of the object to create - /// The constructor arguments of the object to create - /// A reference to the newly created object - /// - /// - /// The current type does not represent a generic type definition. That is, - /// System.Type.IsGenericTypeDefinition returns false. - /// - /// - /// - /// typeArguments is null. -or- Any element of typeArguments is null. - /// - /// - /// - /// The number of elements in typeArguments is not the same as the number of type parameters - /// in the current generic type definition. -or- Any element of typeArguments does not satisfy - /// the constraints specified for the corresponding type parameter of the current generic - /// type. -or- typeArguments contains an element that is a pointer type (System.Type.IsPointer - /// returns true), a by-ref type (System.Type.IsByRef returns true), or System.Void. - /// - /// - /// - /// Does not find an applicable constructor for the provided arguments - /// () - /// - /// - /// - /// type is not a RuntimeType. -or- type is an open generic type (that is, the - /// System.Type.ContainsGenericParameters property returns true). - /// - /// - /// - /// type cannot be a System.Reflection.Emit.TypeBuilder. -or- Creation of System.TypedReference, - /// System.ArgIterator, System.Void, and System.RuntimeArgumentHandle types, or arrays - /// of those types, is not supported. -or- The assembly that contains type is a dynamic - /// assembly that was created with System.Reflection.Emit.AssemblyBuilderAccess.Save. - /// - /// - /// - /// The constructor being called throws an exception. - /// - /// - /// - /// The caller does not have permission to call this constructor. - /// - // - /// - /// Cannot create an instance of an abstract class, or this member was invoked with a - /// late-binding mechanism. - /// - /// - /// - /// The COM type was not obtained through Overload:System.Type.GetTypeFromProgID or - /// Overload:System.Type.GetTypeFromCLSID. - /// - /// - /// - /// No matching public constructor was found. - /// - /// - /// - /// type is a COM object but the class identifier used to obtain the type is invalid, - /// or the identified class is not registered. - /// - /// - /// type is not a valid type. - public static object CreateInstance( - Type generic_def, Type[] generic_args, params object[] ctr_args) { - if (!generic_def.IsGenericTypeDefinition) { - throw Exceptions.not_generic_type_definition(generic_def); - } - - var t = generic_def.MakeGenericType(generic_args); - if (ctr_args.Length == 0) { - return Activator.CreateInstance(t); - } - - var constructor = FindApplicableConstructor( - t, ctr_args.Select(c => c.GetType()).ToArray()) ?? - throw new ArgumentException( - "Did not find applicable constructor for the provided arguments"); - return constructor.Invoke(ctr_args); - } - /// /// Gets the type arguments for a generic type, , which is /// assignable from a particular instantiable type, @@ -141,7 +53,7 @@ /// does not represent a generic type /// definition (i.e., is false) /// - public static Type[] GetGenericTypeArgs(Type type, Type generic_def) { + public static Type[] get_generic_type_args(Type type, Type generic_def) { if (!generic_def.IsGenericTypeDefinition) { throw Exceptions.not_generic_type_definition(generic_def); } @@ -152,11 +64,6 @@ throw Exceptions.does_not_implement_or_derive_from(type, generic_def); } - public static Delegate create_property_getter(object obj, string property) => - create_property_getter(obj, obj.GetType().GetProperty(property) ?? - throw new ArgumentException( - $"Failed to create getter for property '{property}'", nameof(property))); - public static Delegate create_property_getter(object obj, PropertyInfo prop_info) { if (obj is null) { throw new ArgumentNullException(nameof(obj)); @@ -170,12 +77,12 @@ nameof(prop_info)); } - public static IReadOnlyList get_props( + public static IReadOnlyList properties( BindingFlags flags = BindingFlags.Instance | BindingFlags.Public, bool include_immutable = true) => - PropertyInfoStore.get_props(flags, include_immutable); + PropertyInfoStore.get_properties(flags, include_immutable); - public static IReadOnlyDictionary> prop_accessors() => + public static IReadOnlyDictionary> property_accessors() => DelegateStore.accessor_data; public static Func create_property_getter(object obj, string property) { @@ -200,11 +107,11 @@ /// /// Gets 'getter' delegates for a set of properties /// - public static IReadOnlyList> property_delegates_of_type( + public static IReadOnlyList<(string name, Func get)> property_getters( BindingFlags flags = BindingFlags.Instance | BindingFlags.Public) => PropertyGetterStore.get_getters(flags); - public static IReadOnlyList> static_property_delegates_of_type( + public static IReadOnlyList<(string name, Func get)> static_property_getters( Type source_type) => StaticPropertyGetterStore.get(source_type); @@ -303,7 +210,7 @@ } public static IDisposable create(T instance) => - create(instance, PropertyInfoStore.get_props(include_immutable: false)); + create(instance, PropertyInfoStore.get_properties(include_immutable: false)); public static IDisposable create(T instance, IReadOnlyList props) { var snapshot = props.as_mutable().WrapSelectorRO(p => p.GetValue(instance)).ToList(); @@ -417,7 +324,7 @@ static class PropertyInfoStore { static readonly AtomicDictionaryWrapper _props = new(); - public static IReadOnlyList get_props( + public static IReadOnlyList get_properties( BindingFlags flags = BindingFlags.Instance | BindingFlags.Public, bool include_immutable = true ) { @@ -465,7 +372,7 @@ static DelegateStore() { var prop_dels = new Dictionary>(); var accessor_type_cache = new Dictionary(); - foreach (var p in PropertyInfoStore.get_props()) { + foreach (var p in PropertyInfoStore.get_properties()) { prop_dels[p.Name] = (IPropertyAccessorData)Activator.CreateInstance( accessor_type_cache.GetOrAdd(p.PropertyType, mk_prop_accessor_type), new[] { p }); @@ -484,16 +391,16 @@ } static class PropertyGetterStore { - static readonly AtomicDictionaryWrapper>> _getters = new(); + static readonly AtomicDictionaryWrapper)>> _getters = new(); public static readonly IReadOnlyList> value; - public static IReadOnlyList> get_getters(BindingFlags flags) { + public static IReadOnlyList<(string, Func)> get_getters(BindingFlags flags) { Log.assert(flags == (BindingFlags.Instance | BindingFlags.Public)); return _getters.GetOrAdd(flags, _ => { var res = typeof(TSource).GetProperties(BindingFlags.Public | BindingFlags.Instance) .Where(p => typeof(TValue).IsAssignableFrom(p.PropertyType)) - .Select(_prop_getter) + .Select(p => (p.Name, _prop_getter(p))) .ToReadOnlyList(); Log.assert(res.Count == value.Count); return res; @@ -510,9 +417,9 @@ } static class StaticPropertyGetterStore { - static Dictionary>> _cache = new(); + static Dictionary)>> _cache = new(); - public static IReadOnlyList> get(Type type) { + public static IReadOnlyList<(string, Func)> get(Type type) { // Updates to the cache are done atomically (thread-safe) var cache = _cache; if (cache.TryGetValue(type, out var getters)) { @@ -520,7 +427,7 @@ } getters = type.GetProperties(BindingFlags.Public | BindingFlags.Static) .Where(p => typeof(TValue).IsAssignableFrom(p.PropertyType)) - .Select(p => (Func)p.GetGetMethod().CreateDelegate(typeof(Func))) + .Select(p => (p.Name, (Func)p.GetGetMethod().CreateDelegate(typeof(Func)))) .ToReadOnlyList(); cache[type] = getters; _cache = cache;