@@ -3,15 +3,93 @@ namespace FSharp.SystemCommandLine
33open System
44open System.CommandLine
55
6- module private MaybeParser =
6+ module private MaybeParser =
7+ /// Parses an argument token value to the given type.
8+ let parseTokenValueForType ( typ : Type ) ( tokenValue : string ) =
9+ match typ with
10+ | t when t = typeof< IO.DirectoryInfo> -> IO.DirectoryInfo( tokenValue) :> obj
11+ | t when t = typeof< IO.FileInfo> -> IO.FileInfo( tokenValue)
12+ | t when t = typeof< Uri> -> Uri( tokenValue)
13+ | t -> Convert.ChangeType( tokenValue, t)
14+
715 /// Parses an argument token value.
816 /// TODO: Ideally, this should use the S.CL Arugment parser.
917 let parseTokenValue < 'T > ( tokenValue : string ) =
10- match typeof< 'T> with
11- | t when t = typeof< IO.DirectoryInfo> -> IO.DirectoryInfo( tokenValue) |> unbox< 'T> |> Some
12- | t when t = typeof< IO.FileInfo> -> IO.FileInfo( tokenValue) |> unbox< 'T> |> Some
13- | t when t = typeof< Uri> -> Uri( tokenValue) |> unbox< 'T> |> Some
14- | t -> Convert.ChangeType( tokenValue, t) :?> 'T |> Some
18+ parseTokenValueForType typeof< 'T> tokenValue :?> 'T |> Some
19+
20+ /// Short alias used in SafeInputLists for constraints and delegate construction.
21+ type private ParseFunc < 'T > = Func< Parsing.ArgumentResult, 'T>
22+ type private SafeInputLists =
23+ // bound generic `List.OfArray` method
24+ static let ofArrayInfo =
25+ typeof< list< obj>>
26+ .Assembly
27+ .GetType( " Microsoft.FSharp.Collections.ListModule" )
28+ .GetMethod( " OfArray" , System.Reflection.BindingFlags.Static ||| System.Reflection.BindingFlags.Public)
29+ // invokes `List.OfArray` with the given array using the provided type as the element type
30+ static let ofArrayForType ( typ : Type ) ( elements : Array ) =
31+ ofArrayInfo.MakeGenericMethod( typ.GetGenericArguments()[ 0 ]) .Invoke( null , [| elements |])
32+ // safely retrieves the element type of a list type
33+ static let listElementType ( typ : Type ) =
34+ // naive tests show more predictable behaviour
35+ // with the presence of this branch
36+ match typ.GetElementType() with
37+ | null -> typ.GetGenericArguments()[ 0 ]
38+ | typ -> typ
39+ // retrieves the `List.Empty` property for the given element type generic
40+ static let makeEmptyList ( typ : Type ) =
41+ match typ.GetProperty( " Empty" , System.Reflection.BindingFlags.Static ||| System.Reflection.BindingFlags.Public) with
42+ | null -> Error $" Could not find Empty property on type %s {typ.FullName}."
43+ | prop -> prop.GetValue( null ) |> Ok
44+ // determines whether provided type is a generic `list` type
45+ static let isListGeneric ( typ : Type ) =
46+ typ.IsGenericType
47+ && typ.GetGenericTypeDefinition() = typedefof< list<_>>
48+ static member inline private dynamicParser < ^T , ^U
49+ // static binding of Option < _ > and Argument < _ >
50+ // where T is the typar for U : the generic Option / Argument
51+ when ^U :( member set_DefaultValueFactory : ParseFunc<^T> -> unit )
52+ and ^U :( member set_CustomParser : ParseFunc<^T> -> unit )
53+ and ^U :( member set_Arity : ArgumentArity -> unit )>
54+ ( o : ^U ) =
55+ let typ = typeof< 'T>
56+ // if not a list, noop
57+ if not <| isListGeneric typ then () else
58+ let elementType = listElementType typ
59+ // parses token to element type
60+ let changeType : Parsing.Token -> obj =
61+ let fn = MaybeParser.parseTokenValueForType elementType
62+ _. Value >> fn
63+ // converts array to final list type
64+ let ofArray = ofArrayForType typ
65+ let empty = makeEmptyList typ
66+ // Default Value Factory -> List.Empty
67+ ParseFunc( fun result ->
68+ match empty with
69+ | Error err ->
70+ result.AddError err
71+ Unchecked.defaultof< 'T>
72+ | Ok empty -> empty |> unbox< 'T>)
73+ |> o.set_ DefaultValueFactory
74+ // Custom Parser -> tokens -> Array -> List.OfArray
75+ ParseFunc( fun result ->
76+ let count = result.Tokens.Count
77+ let dynamicArray = Array.CreateInstance( elementType, count)
78+ for i, token in result.Tokens |> Seq.indexed do
79+ try
80+ dynamicArray.SetValue( changeType token, i)
81+ // should this be more permissive?
82+ with :? FormatException as e -> result.AddError e.Message
83+ ofArray dynamicArray |> unbox< 'T>)
84+ |> o.set_ CustomParser
85+ ArgumentArity( 0 , 100_000 )
86+ |> o.set_ Arity
87+ /// Checks ` 'T ` for a ` List<_> ` generic type. Injects list compatible CustomParser and DefaultValueFactory
88+ /// if ` true ` ; noop if ` false `
89+ static member protect < 'T >( o : Argument < 'T >) = SafeInputLists.dynamicParser< 'T, _> o; o
90+ /// Checks ` 'T ` for a ` List<_> ` generic type. Injects list compatible CustomParser and DefaultValueFactory
91+ /// if ` true ` ; noop if ` false `
92+ static member protect < 'T >( o : Option < 'T >) = SafeInputLists.dynamicParser< 'T, _> o; o
1593
1694/// A custom action context that contains the ` ParseResult ` and a cancellation token.
1795type ActionContext =
@@ -101,7 +179,9 @@ module Input =
101179
102180 /// Creates a named option. Example: ` option "--file-name" `
103181 let option < 'T > ( name : string ) =
104- Option< 'T>( name) |> ActionInput.OfOption
182+ Option< 'T>( name)
183+ |> SafeInputLists.protect
184+ |> ActionInput.OfOption
105185
106186 /// Edits the underlying System.CommandLine.Option<'T>.
107187 let editOption ( edit : Option < 'T > -> unit ) ( input : ActionInput < 'T >) =
@@ -216,8 +296,9 @@ module Input =
216296
217297 /// Creates a named argument. Example: ` argument "file-name" `
218298 let argument < 'T > ( name : string ) =
219- let a = Argument< 'T>( name)
220- ActionInput.OfArgument< 'T> a
299+ Argument< 'T>( name)
300+ |> SafeInputLists.protect
301+ |> ActionInput.OfArgument< 'T>
221302
222303 /// Creates a named argument of type ` Argument<'T option> ` that defaults to ` None ` .
223304 let argumentMaybe < 'T > ( name : string ) =
0 commit comments