66using SER . Code . TokenSystem . Tokens ;
77using SER . Code . TokenSystem . Tokens . Interfaces ;
88using SER . Code . ValueSystem ;
9+ using SER . Code . ValueSystem . Other ;
910
1011namespace SER . Code . Extensions ;
1112
@@ -25,12 +26,19 @@ public static TryGet<TOut> SuccessTryCast<TOut>(this TryGet<Value> value) where
2526
2627 public static TryGet < TOut > TryCast < TOut > ( this object value , string rawRep = "" )
2728 {
28- switch ( value )
29+ if ( value is null ) throw new AndrzejFuckedUpException ( ) ;
30+ if ( value is TOut outValue ) return outValue ;
31+
32+ if ( value is IInvalidable inv && inv . SafeValue is TOut outValue2 )
33+ return outValue2 ;
34+
35+ if ( typeof ( TOut ) . IsGenericType && typeof ( TOut ) . GetGenericTypeDefinition ( ) == typeof ( Invalidable < > ) )
2936 {
30- case null :
31- throw new AndrzejFuckedUpException ( ) ;
32- case TOut outValue :
33- return outValue ;
37+ var innerType = typeof ( TOut ) . GetGenericArguments ( ) [ 0 ] ;
38+ if ( innerType . IsInstanceOfType ( value ) )
39+ {
40+ return ( TOut ) Activator . CreateInstance ( typeof ( TOut ) , value ) ;
41+ }
3442 }
3543
3644 string valueRep = "" ;
@@ -42,6 +50,11 @@ public static TryGet<TOut> TryCast<TOut>(this object value, string rawRep = "")
4250 return $ "{ valueRep } { value . FriendlyTypeName ( ) } is not a { typeof ( TOut ) . FriendlyTypeName ( ) } ";
4351 }
4452
53+ private static Type Unwrap ( Type type ) =>
54+ ( type . IsGenericType && type . GetGenericTypeDefinition ( ) == typeof ( Invalidable < > ) )
55+ ? type . GetGenericArguments ( ) [ 0 ]
56+ : type ;
57+
4558 extension ( BaseToken token )
4659 {
4760 public bool CanReturn < T > ( [ NotNullWhen ( true ) ] out Func < TryGet < T > > ? get ) where T : Value
@@ -93,7 +106,15 @@ public bool CapableOf<T>([NotNullWhen(true)] out Func<TryGet<T>>? get) where T :
93106 if ( ! valToken . PossibleValues . AreKnown ( out var knownReturnTypes ) ) return true ;
94107
95108 // if any of known types is assignable to T, or T to type, then it may return T
96- return knownReturnTypes . Any ( type => typeof ( T ) . IsAssignableFrom ( type ) || type . IsAssignableFrom ( typeof ( T ) ) ) ;
109+ return knownReturnTypes . Any ( type =>
110+ {
111+ if ( typeof ( T ) . IsAssignableFrom ( type ) || type . IsAssignableFrom ( typeof ( T ) ) ) return true ;
112+
113+ var unwrappedTarget = Unwrap ( typeof ( T ) ) ;
114+ var unwrappedSource = Unwrap ( type ) ;
115+
116+ return unwrappedTarget . IsAssignableFrom ( unwrappedSource ) || unwrappedSource . IsAssignableFrom ( unwrappedTarget ) ;
117+ } ) ;
97118 }
98119
99120 public TryGet < T > TryGet < T > ( ) where T : Value
0 commit comments