sm'¶
In [ ]:
//// test
open testing
In [ ]:
open rust
open rust_operators
open sm'_real
rust¶
std_string¶
In [ ]:
//// real
nominal std_string =
`(
backend_switch `(()) `({}) {
Fsharp =
(fun () =>
global "#if FABLE_COMPILER\n[<Fable.Core.Erase; Fable.Core.Emit(\"std::string::String\")>]\ntype std_string_String = class end\n#else\ntype std_string_String = string\n#endif\n"
) : () -> ()
}
$'' : $'std_string_String'
)
In [ ]:
type std_string = sm'_real.std_string
to_string¶
In [ ]:
inl to_string forall t. (x : t) : std_string =
!\($'$"!x.to_string()"')
from_std_string¶
In [ ]:
//// real
inl from_std_string (str : std_string) : string =
open rust
rust.emit_expr `std_string `string str ($'"fable_library_rust::String_::fromString($0)"' : string)
In [ ]:
inl from_std_string (str : std_string) : string =
real sm'_real.from_std_string str
sm'¶
symbol_to_string¶
In [ ]:
//// real
inl symbol_to_string forall t {symbol}. : string =
// inl x = real_core.type_lit_to_lit `t
// inl x = real_core.type_to_symbol `t
// inl x = real_core.type_lit_to_lit `t
// !!!!SymbolToString (`(`t))
inl x = real_core.type_to_symbol `t
!!!!SymbolToString (x)
In [ ]:
inl symbol_to_string forall t {symbol}. (x : t) : string =
real symbol_to_string `t
In [ ]:
//// test
.test
|> symbol_to_string
|> _assert_eq "test"
__assert_eq / actual: "test" / expected: "test"
In [ ]:
//// test
//// real
open testing
inl x = .test
inl x = symbol_to_string `(`x)
_assert_eq `string "test" x
__assert_eq / actual: "test" / expected: "test"
index¶
In [ ]:
inl index i (str : string) : char =
sm.index str i
length¶
In [ ]:
inl length forall dim {int}. (input : string) : dim =
input |> sm.length
to_char_array¶
In [ ]:
inl to_char_array (str : string) : array_base char =
am.init (str |> length) (fun i => str |> index i)
|> fun (a x : _ int _) => x
In [ ]:
//// test
"abc"
|> to_char_array
|> _assert_eq' ;[ 'a'; 'b'; 'c' ]
__assert_eq' / actual: [|'a'; 'b'; 'c'|] / expected: [|'a'; 'b'; 'c'|]
to_char_list¶
In [ ]:
inl to_char_list (str : string) : list char =
listm.init (str |> length) (fun (i : i64) => str |> index i)
In [ ]:
//// test
"abc"
|> to_char_list
|> _assert_eq [ 'a'; 'b'; 'c' ]
__assert_eq / actual: UH0_1 ('a', UH0_1 ('b', UH0_1 ('c', UH0_0))) / expected: UH0_1 ('a', UH0_1 ('b', UH0_1 ('c', UH0_0)))
is_empty¶
In [ ]:
inl is_empty (input : string) : bool =
length input = 0i32
slice¶
In [ ]:
inl slice from to s : string =
sm.slice s { from to }
format_debug¶
In [ ]:
//// real
inl format_debug forall t. (x : t) : string =
backend_switch `string `({}) {
Fsharp = (fun () => $'$"%A{!x}"' : string) : () -> string
Python = (fun () => $'f"{!x}"' : string) : () -> string
}
In [ ]:
inl format_debug forall t. (x : t) : string =
real format_debug `t x
In [ ]:
//// test
{ c = "1"; a = "2"; b = "3" }
|> format_debug
|> _assert_eq "struct (\"1\", \"2\", \"3\")"
__assert_eq / actual: "struct ("1", "2", "3")" / expected: "struct ("1", "2", "3")"
format_pretty¶
In [ ]:
//// real
inl format_pretty forall t. (x : t) : string =
run_target_args `string `t (fun () => x) function
| Rust _ => fun x =>
open rust
inl result = rust.emit_expr `t `std_string x ($'"format\!(\\\"{:#?}\\\", $0)"' : string)
from_std_string result
| _ => fun _ => format_debug `t x
In [ ]:
inl format_pretty forall t. (x : t) : string =
real sm'_real.format_pretty `t x
prim¶
In [ ]:
inl prim x = real
match x with
| (x : i8) | (x : i16) | (x : i32) | (x : i64) => "%d", x
| (x : u8) | (x : u16) | (x : u32) | (x : u64) => "%u", x
| (x : f32) | (x : f64) => "%f", x
| (x : string) => "%s", x
| (x : char) => "%c", x
printable¶
In [ ]:
//// real
prototype printable t : t -> ()
format_real¶
In [ ]:
//// real
let format_real forall t. (x : t) : string =
inl result = mut `string (join "")
inl rec write x =
inl p ((a : string), b) =
inl s : string =
backend_switch `string `({}) {
Fsharp =
(fun () =>
match b with
| (_ : f32) | (_ : f64) => $'$"%+.6f{!b}"' : string
| _ => $'$"{!b}"' : string
) : () -> string
Python =
(fun () =>
match b with
| (_ : f32) | (_ : f64) => $'"{:.6f}".format(!b)' : string
| _ => $'f"{!b}"' : string
) : () -> string
}
exec_unit ((fun () => result <- (+.) `string ((~*) `string result) s) : () -> ())
match x with // According to Bing it shouldn't matter whether these are %d or %lld in printf.
| () => ()
| (x : i8) | (x : i16) | (x : i32) | (x : i64) => p ("%d", x)
| (x : u8) | (x : u16) | (x : u32) | (x : u64) => p ("%u", x)
| (x : f32) | (x : f64) => p ("%f", x)
| (x : string) => p ("%s", x)
| (x : char) => p ("%c", x)
| (x : bool) => p ("%s", if x then "true" else "false")
| (a,b) => write a . write ", " . write b
| {} as x =>
write "{ "
inl _result =
real_core.record_fold
fun { state = separator key value } =>
write separator
write (symbol_to_string `(`key)) . write " = " . write value
"; "
() x
write " }"
| x when real_core.symbol_is x => write (symbol_to_string `(`x))
| x when real_core.function_is x => write (x ())
| x when real_core.union_is x =>
if real_core.prototype_has `(`x) printable then printable `(`x) x
else
write (format_debug `(`x) x)
// real_core.unbox x (fun (k, v) =>
// write k
// match v with
// | () => ()
// | _ => write "(" . write v . write ")"
// )
| x when real_core.nominal_is x =>
if real_core.prototype_has `(`x) printable then printable `(`x) x
// elif layout_is x then write *x // TODO: Deal with all the layout type cases.
else write (format_pretty `(`x) x)
| x => write (format_debug `(`x) x)
write x
(~*) `string result
format¶
In [ ]:
inl format forall t. (x : t) : string =
real format_real `t x
In [ ]:
//// test
///! fsharp
////! cuda
////! rust
////! typescript
////! python
("1", "2", ["3"; "4"], { b = "5"; c = "6"; a = fun () => "7" })
|> format
|> _assert_eq "1, 2, UH0_1 (\"3\", UH0_1 (\"4\", UH0_0)), { b = 5; c = 6; a = 7 }"
__assert_eq / actual: "1, 2, UH0_1 ("3", UH0_1 ("4", UH0_0)), { b = 5; c = 6; a = 7 }" / expected: "1, 2, UH0_1 ("3", UH0_1 ("4", UH0_0)), { b = 5; c = 6; a = 7 }"
concat_array_trailing¶
In [ ]:
inl concat_array_trailing (separator : string) (input : a i32 string) =
("", input)
||> am.fold fun acc (x : string) =>
$'!acc + !x + !separator + ""'
In [ ]:
//// test
///! typescript
;[
"1"
"2"
"3"
]
|> fun x =>
inl code = (a x : _ i32 _) |> concat_array_trailing "\n"
code
|> _assert_eq "1\n2\n3\n"
__assert_eq / actual: 1 2 3 / expected: 1 2 3
concat_list_trailing¶
In [ ]:
inl concat_list_trailing separator input =
("", input)
||> listm.fold fun acc (x : string) =>
$'!acc + !x + !separator + ""'
In [ ]:
//// test
///! rust
[
"1"
"2"
"3"
]
|> fun x =>
inl code = (x : _) |> concat_list_trailing "\n"
code
|> _assert_eq "1\n2\n3\n"
__assert_eq / actual: "1 2 3 " / expected: "1 2 3 "
concat_list_heap_trailing¶
In [ ]:
inl concat_list_heap_trailing separator input =
inl separator = join separator
("", input)
||> listm.fold fun acc (x : string) =>
$'$"{!acc}{!x}{!separator}"'
In [ ]:
//// test
///! rust
[
"1"
"2"
"3"
]
|> fun x =>
inl code = (x : _) |> concat_list_heap_trailing "\n"
code
|> _assert_eq "1\n2\n3\n"
__assert_eq / actual: "1 2 3 " / expected: "1 2 3 "
ellipsis¶
In [ ]:
inl ellipsis (max : i32) (s : string) =
if sm.length s <= max
then s
else s |> slice 0 (max - 1) |> fun x => $'!x + "..."'
In [ ]:
//// test
"12345"
|> ellipsis 2
|> _assert_eq "12..."
"12345"
|> ellipsis 4
|> _assert_eq "1234..."
__assert_eq / actual: "12..." / expected: "12..." __assert_eq / actual: "1234..." / expected: "1234..."
fsharp¶
ends_with¶
In [ ]:
inl ends_with (value : string) (s : string) : bool =
$'!s.EndsWith !value '
last_index_of¶
In [ ]:
inl last_index_of (search : string) (s : string) : i32 =
$'!s.LastIndexOf !search '
index_of¶
In [ ]:
inl index_of (search : string) (s : string) : i32 =
$'!s.IndexOf !search '
replicate¶
In [ ]:
inl replicate (n : i32) (s : string) : string =
backend_switch {
Fsharp = fun () => s |> $'String.replicate' n : string
Python = fun () => $'!s * !n ' : string
}
obj_to_string¶
In [ ]:
inl obj_to_string x : string =
backend_switch {
Fsharp = fun () => x |> $'_.ToString()' : string
Python = fun () => $'str(!x)' : string
}
pad_left¶
In [ ]:
inl pad_left (total_width : i32) (padding_char : char) (s : string) : string =
backend_switch {
Fsharp = fun () => $'!s.PadLeft (!total_width, !padding_char)' : string
Python = fun () =>
inl padding = padding_char |> obj_to_string |> replicate (total_width - length s)
padding +. s
}
pad_right¶
In [ ]:
inl pad_right (total_width : i32) (padding_char : char) (s : string) : string =
$'!s.PadRight (!total_width, !padding_char)'
In [ ]:
//// test
"123"
|> pad_right 6 ' '
|> _assert_eq "123 "
__assert_eq / actual: "123 " / expected: "123 "
starts_with¶
In [ ]:
inl starts_with (value : string) (s : string) : bool =
backend_switch {
Fsharp = fun () => $'!s.StartsWith !value ' : bool
Python = fun () => $'!s.startswith(!value)' : bool
}
is_white_space¶
In [ ]:
inl is_white_space (c : char) : bool =
c |> $'System.Char.IsWhiteSpace'
substring¶
In [ ]:
inl substring (start : i32) (len : i32) (str : string) : string =
$'!str.Substring (!start, !len)'
to_lower¶
In [ ]:
inl to_lower (input : string) : string =
backend_switch {
Fsharp = fun () => $'!input.ToLower' () : string
Python = fun () => $'!input.lower()' : string
}
to_upper¶
In [ ]:
inl to_upper (input : string) : string =
$'!input.ToUpper' ()
char_to_upper¶
In [ ]:
inl char_to_upper (input : char) : char =
$'System.Char.ToUpper !input '
string_builder¶
In [ ]:
nominal string_builder = $'System.Text.StringBuilder'
inl string_builder (initial : string) : string_builder =
inl initial =
if initial = ""
then join initial
else initial
initial |> $'`string_builder '
builder_append¶
In [ ]:
inl builder_append (item : string) (sb : string_builder) : string_builder =
($'!sb.Append' item : string_builder) |> ignore
sb
builder_append_line¶
In [ ]:
inl builder_append_line (sb : string_builder) : string_builder =
($'!sb.AppendLine ()' : string_builder) |> ignore
sb
builder_replace¶
In [ ]:
inl builder_replace (old : string) (new : string) (sb : string_builder) : string_builder =
($'!sb.Replace (!old, !new)' : string_builder) |> ignore
sb
builder_insert¶
In [ ]:
inl builder_insert (n : i32) (s : string) (sb : string_builder) : string_builder =
($'!sb.Insert (!n, !s)' : string_builder) |> ignore
sb
builder_clear¶
In [ ]:
inl builder_clear (sb : string_builder) : string_builder =
($'!sb.Clear' () : string_builder) |> ignore
sb
trim¶
In [ ]:
inl trim (input : string) : string =
$'!input.Trim' ()
concat¶
In [ ]:
inl concat (a : string) (b : seq.seq' string) : string =
backend_switch {
Fsharp = fun () =>
inl a =
if a = "\n"
then join a
else a
b |> $'String.concat' a : string
Python = fun () =>
$'!a.join(!b)' : string
}
trim_end¶
In [ ]:
inl trim_end (trim_chars : list char) (input : string) : string =
inl trim_chars = trim_chars |> listm'.box
backend_switch {
Fsharp = fun () =>
inl trim_chars = trim_chars |> listm'.to_array'
$'!input.TrimEnd !trim_chars ' : string
Python = fun () =>
inl trim_chars = trim_chars |> listm'.map obj_to_string |> seq.of_list' |> concat ""
$'!input.rstrip(!trim_chars)' : string
}
trim_start¶
In [ ]:
inl trim_start (trim_chars : list char) (input : string) : string =
inl trim_chars = trim_chars |> listm'.box
backend_switch {
Fsharp = fun () =>
inl trim_chars = trim_chars |> listm'.to_array'
$'!input.TrimStart !trim_chars ' : string
Python = fun () =>
inl trim_chars = trim_chars |> listm'.map obj_to_string |> seq.of_list' |> concat ""
$'!input.lstrip(!trim_chars)' : string
}
length'¶
In [ ]:
inl length' forall dim. (input : string) : dim =
input |> $'String.length'
to_string any¶
In [ ]:
instance to_string any =
obj_to_string
replace¶
In [ ]:
inl replace (old_value : string) (new_value : string) (s : string) : string =
$'!s.Replace (!old_value, !new_value)'
split¶
In [ ]:
inl split (separator : string) (str : string) : array_base string =
backend_switch {
Fsharp = fun () => $'!str.Split !separator ' : array_base string
Python = fun () => $'!str.split(!separator)' : array_base string
}
split_string¶
In [ ]:
inl split_string (separator : array_base string) (str : string) : array_base string =
run_target_args (fun () => str, separator) function
| Fsharp (Native) => fun str, separator => $'!str.Split (!separator, System.StringSplitOptions.None)'
| _ => fun str, separator => str |> split ((a separator : _ int _) |> seq.of_array |> concat (join ""))
join'¶
In [ ]:
inl join' (concat : string) (s : a int string) : string =
$'System.String.Join (!concat, !s)'
encoding¶
In [ ]:
nominal encoding = $'System.Text.Encoding'
encoding_utf8¶
In [ ]:
inl encoding_utf8 () : encoding =
$'`encoding.UTF8'
utf8_get_bytes¶
In [ ]:
inl utf8_get_bytes (s : string) : a i32 u8 =
s |> (encoding_utf8 () |> $'_.GetBytes')
byte_to_string¶
In [ ]:
inl byte_to_string (format : string) (x : u8) : string =
$'!x.ToString' format
rust¶
str¶
In [ ]:
nominal str =
`(
global "#if FABLE_COMPILER\n[<Fable.Core.Erase; Fable.Core.Emit(\"str\")>]\ntype Str = class end\n#else\ntype Str = string\n#endif\n"
$'' : $'Str'
)
chars¶
In [ ]:
inl chars (x : rust.ref str) : rust.mut' (into_iterator char) =
!\\(x, $'$"$0.chars()"')
char_is_alphanumeric¶
In [ ]:
inl char_is_alphanumeric (x : char) : bool =
!\\(x, $'$"$0.is_alphanumeric()"')
byte_slice¶
In [ ]:
inl byte_slice (s : string) : rust.ref (am'.slice u8) =
!\($'"b\\\"" + !s + "\\\""')
display¶
In [ ]:
nominal display t =
`(
global "#if FABLE_COMPILER\n[<Fable.Core.Erase; Fable.Core.Emit(\"std::fmt::Display<$0>\")>]\n#endif\ntype std_fmt_Display<'T> = class end"
$'' : $'std_fmt_Display<`t>'
)
base64_decode_error¶
In [ ]:
nominal base64_decode_error =
`(
global "#if FABLE_COMPILER\n[<Fable.Core.Erase; Fable.Core.Emit(\"base64::DecodeError\")>]\n#endif\ntype base64_DecodeError = class end"
$'' : $'base64_DecodeError'
)
borsh_io_error¶
In [ ]:
nominal borsh_io_error =
`(
global "#if FABLE_COMPILER\n[<Fable.Core.Erase; Fable.Core.Emit(\"borsh::io::Error\")>]\n#endif\ntype borsh_io_Error = class end"
$'' : $'borsh_io_Error'
)
utf8_error¶
In [ ]:
nominal utf8_error =
`(
global "#if FABLE_COMPILER\n[<Fable.Core.Erase; Fable.Core.Emit(\"std::str::Utf8Error\")>]\n#endif\ntype std_str_Utf8Error = class end"
$'' : $'std_str_Utf8Error'
)
from_utf8_error¶
In [ ]:
nominal from_utf8_error =
`(
global "#if FABLE_COMPILER\n[<Fable.Core.Erase; Fable.Core.Emit(\"std::string::FromUtf8Error\")>]\n#endif\ntype std_string_FromUtf8Error = class end"
$'' : $'std_string_FromUtf8Error'
)
json_value¶
In [ ]:
nominal json_value =
`(
global "#if FABLE_COMPILER\n[<Fable.Core.Erase; Fable.Core.Emit(\"serde_json::Value\")>]\n#endif\ntype serde_json_Value = class end"
$'' : $'serde_json_Value'
)
json_error¶
In [ ]:
nominal json_error =
`(
global "#if FABLE_COMPILER\n[<Fable.Core.Erase; Fable.Core.Emit(\"serde_json::Error\")>]\n#endif\ntype serde_json_Error = class end"
$'' : $'serde_json_Error'
)
serde_wasm_bindgen_error¶
In [ ]:
nominal serde_wasm_bindgen_error =
`(
global "#if FABLE_COMPILER\n[<Fable.Core.Erase; Fable.Core.Emit(\"serde_wasm_bindgen::Error\")>]\n#endif\ntype serde_wasm_bindgen_Error = class end"
$'' : $'serde_wasm_bindgen_Error'
)
js_string¶
In [ ]:
nominal js_string =
`(
global "#if FABLE_COMPILER\n[<Fable.Core.Erase; Fable.Core.Emit(\"js_sys::JsString\")>]\n#endif\ntype js_sys_JsString = class end"
$'' : $'js_sys_JsString'
)
os_str¶
In [ ]:
nominal os_str =
`(
global "#if FABLE_COMPILER\n[<Fable.Core.Erase; Fable.Core.Emit(\"std::ffi::OsStr\")>]\n#endif\ntype std_ffi_OsStr = class end"
$'' : $'std_ffi_OsStr'
)
os_string¶
In [ ]:
nominal os_string =
`(
global "#if FABLE_COMPILER\n[<Fable.Core.Erase; Fable.Core.Emit(\"std::ffi::OsString\")>]\n#endif\ntype std_ffi_OsString = class end"
$'' : $'std_ffi_OsString'
)
raw_string_literal¶
In [ ]:
inl raw_string_literal (s : string) : rust.ref str =
!\($'"r#\\"" + !s + "\\"#"')
raw_string_literal_static¶
In [ ]:
inl raw_string_literal_static (s : string) : rust.static_ref str =
!\($'"r#\\"" + !s + "\\"#"')
(~#)¶
In [ ]:
inl (~#) s =
s |> raw_string_literal
(~##)¶
In [ ]:
inl (~##) s =
s |> raw_string_literal_static
include_str¶
In [ ]:
inl include_str (path : string) : rust.ref str =
!\($'"include_str\!(\\\"" + !path + "\\\")"')
as_str¶
In [ ]:
inl as_str (s : string) : rust.ref str =
// !\\(s, $'"fable_library_rust::String_::LrcStr::as_str(&$0)"')
run_target_args (fun () => s) function
| Rust _ => fun s => !\\(s, $'"&*$0"')
| _ => fun s => s |> unbox
from_iter¶
In [ ]:
inl from_iter forall (t : * -> *). (s : t char) : std_string =
!\\(s, $'"String::from_iter($0)"')
ref_to_std_string¶
In [ ]:
inl ref_to_std_string (str : rust.ref str) : std_string =
run_target_args (fun () => str) function
| Rust _ => fun str => !\\(str, $'"String::from($0)"')
| _ => fun str => str |> unbox
cow_to_std_string¶
In [ ]:
inl cow_to_std_string (str : rust.cow str) : std_string =
!\\(str, $'"String::from($0)"')
to_std_string¶
In [ ]:
inl to_std_string (s : string) : std_string =
s |> as_str |> ref_to_std_string
as_str_std¶
In [ ]:
inl as_str_std (s : std_string) : rust.ref str =
!\\(s, $'"$0.as_str()"')
into_boxed_str¶
In [ ]:
inl into_boxed_str (s : std_string) : rust.box str =
!\\(s, $'"$0.into_boxed_str()"')
os_string_as_ref¶
In [ ]:
inl os_string_as_ref (s : os_string) : rust.ref os_str =
!\\(s, $'"$0.as_ref()"')
to_os_string¶
In [ ]:
inl to_os_string (s : rust.ref os_str) : os_string =
!\\(s, $'"$0.to_os_string()"')
os_to_str¶
In [ ]:
inl os_to_str (s : os_string) : optionm'.option' (rust.ref str) =
!\\(s, $'"$0.to_str()"')
from_os_str_ref¶
In [ ]:
inl from_os_str_ref s =
s
|> to_os_string
|> os_to_str
|> optionm'.unwrap
|> ref_to_std_string
|> from_std_string
format_custom'¶
In [ ]:
inl format_custom' (f : string) x : std_string =
run_target function
| Rust _ => fun () =>
!\\(x, $'"format\!(\\\"" + !f + "\\\", $0)"')
| _ => fun () => null ()
format_debug'¶
In [ ]:
inl format_debug' x : std_string =
run_target function
| Rust _ => fun () =>
!\\(x, $'"format\!(\\\"{:?}\\\", $0)"')
| _ => fun () => null ()
format'¶
In [ ]:
inl format' x : std_string =
run_target_args (fun () => x) function
| Rust _ => fun x =>
!\\(x, $'"format\!(\\\"{}\\\", $0)"')
| _ => fun _ => null ()
format_hex'¶
In [ ]:
inl format_hex' x : std_string =
!\\(x, $'"format\!(\\\"{:02x}\\\", $0)"')
format''¶
In [ ]:
inl format'' (format : string) : std_string =
!\($'@@$"format\!(" + !format + ")"')
regex¶
In [ ]:
nominal regex =
`(
global "#if FABLE_COMPILER\n[<Fable.Core.Erase; Fable.Core.Emit(\"regex::Regex\")>]\n#endif\ntype regex_Regex = class end"
$'' : $'regex_Regex'
)
regex_error¶
In [ ]:
nominal regex_error =
`(
global "#if FABLE_COMPILER\n[<Fable.Core.Erase; Fable.Core.Emit(\"regex::Error\")>]\n#endif\ntype regex_Error = class end"
$'' : $'regex_Error'
)
new_regex¶
In [ ]:
inl new_regex (pattern : string) : resultm.result' regex regex_error =
!\\(pattern, $'$"regex::Regex::new(&$0)"')
captures¶
In [ ]:
nominal regex_captures t =
`(
global "#if FABLE_COMPILER\n[<Fable.Core.Erase; Fable.Core.Emit(\"regex::Captures<$0>\")>]\n#endif\ntype regex_Captures<'T> = class end"
$'' : $'regex_Captures<`t>'
)
regex_capture_matches¶
In [ ]:
nominal regex_capture_matches =
`(
global "#if FABLE_COMPILER\n[<Fable.Core.Erase; Fable.Core.Emit(\"regex::CaptureMatches\")>]\n#endif\ntype regex_CaptureMatches = class end"
$'' : $'regex_CaptureMatches'
)
regex_capture_names¶
In [ ]:
nominal regex_capture_names =
`(
global "#if FABLE_COMPILER\n[<Fable.Core.Erase; Fable.Core.Emit(\"regex::CaptureNames\")>]\n#endif\ntype regex_CaptureNames = class end"
$'' : $'regex_CaptureNames'
)
inl regex_capture_names (regex : regex) : regex_capture_names =
!\\(regex, $'$"$0.capture_names()"')
match'¶
In [ ]:
nominal match' =
`(
global "#if FABLE_COMPILER\n[<Fable.Core.Erase; Fable.Core.Emit(\"regex::Match\")>]\n#endif\ntype regex_Match = class end"
$'' : $'regex_Match'
)
regex_captures_iter¶
In [ ]:
inl regex_captures_iter (s : rust.static_ref (rust.mut' std_string)) (regex : regex) : regex_capture_matches =
inl regex = regex |> rust.emit
!\\(regex, $'$"$0.captures_iter(!s)"')
regex_captures¶
In [ ]:
let regex_captures (s : string) (regex : regex) : am'.vec (mapm.hash_map string string) =
// inl s = join s
// !\\(regex, $'$"$0.captures_iter(&*!s).map(|caps| $0.capture_names().map(|x| x.and_then(|n| Some((n, caps.name(n)?.as_str())))).flatten().collect()).collect()"')
inl s = s |> to_std_string
fun () =>
inl matches =
inl s = s |> rust.new_box |> rust.box_leak
regex |> regex_captures_iter s
(!\($'"true; let _regex_captures : Vec<_> = !matches.map(|x| { //"') : bool) |> ignore
inl fn (match' : rust.static_ref (rust.mut' (regex_captures rust.static_lifetime))) : mapm.hash_map string string =
inl names = regex |> regex_capture_names
(!\($'"true; let _regex_captures : std::collections::HashMap<_, _> = !names.map(|x| { //"') : bool) |> ignore
inl fn (n : string) : pair string string =
inl n' = n |> rust.clone
new_pair n' !\\(n, $'$"!match'.name(&$0).map(|x| x.as_str()).unwrap_or(\\\"\\\").to_string().into()"')
(!\\(fn !\($'"x.unwrap_or(\\\"\\\").to_string().into()"'), $'"true; $0 }).map(|x| std::sync::Arc::try_unwrap(x).unwrap_or_else(|x| (*x).clone())).collect()"') : bool) |> ignore
!\($'"_regex_captures"')
inl x =
!\($'$"x"')
|> rust.new_box
|> rust.box_leak
(!\\(fn x, $'"true; $0 }).collect::<Vec<_>>()"') : bool) |> ignore
!\($'"_regex_captures"')
|> rust.capture_move
In [ ]:
//// test
///! rust -d regex
"fable-library-ts\\.(?<a>[\\d.]+)$"
|> new_regex
|> resultm.unwrap'
|> regex_captures "fable_modules/fable-library-ts.4.17.0"
|> am'.vec_map (mapm.to_vec >> am'.vec_sort_by_key id)
|> sm'.format_debug
|> _assert_eq (
;[
;[ "", ""; "a", "4.17.0" ]
|> am'.to_vec
]
|> am'.to_vec
|> sm'.format_debug
)
__assert_eq / actual: "[[("", ""), ("a", "4.17.0")]]" / expected: "[[("", ""), ("a", "4.17.0")]]"
replace_regex'¶
In [ ]:
inl replace_regex' (pattern : string) (replacement : a i32 string) (s : string) : string =
run_target_args (fun () => s, pattern, replacement) function
| Rust (Native) => fun s, pattern, replacement =>
inl regex = pattern |> new_regex |> resultm.unwrap'
!\\((regex, #s, replacement), $'$"$0.replace_all($1, &*$2)"')
|> cow_to_std_string
|> from_std_string
| _ => fun _ => null ()
serialize¶
In [ ]:
inl serialize forall t. (x : t) : resultm.result' std_string json_error =
!\($'"serde_json::to_string(&!x)"')
deserialize¶
In [ ]:
inl deserialize forall t. (json : string) : resultm.result' t std_string =
inl json = join json
inl json = json |> as_str
!\\(json, $'"serde_json::from_str(&$0)"')
|> resultm.map_error' fun (x : json_error) => x |> format'
borsh_serialize¶
In [ ]:
inl borsh_serialize forall t. (data : t) : am'.vec u8 =
(!\($'"true; let mut data = Vec::new()"') : bool) |> ignore
(!\\(data, $'"true; borsh::BorshSerialize::serialize(&$0, &mut data).unwrap()"') : bool) |> ignore
!\($'"data"')
borsh_deserialize¶
In [ ]:
inl borsh_deserialize forall t. (data : array_base u8) : resultm.result' t std_string =
inl data = data |> am'.as_slice
(!\($'"true; let mut !data = !data"') : bool) |> ignore
inl result = !\($'"borsh::BorshDeserialize::deserialize(&mut !data)"')
result
|> resultm.map_error' fun (x : borsh_io_error) => x |> format'
deserialize_vec¶
In [ ]:
inl deserialize_vec (value : json_value) : resultm.result' (am'.vec u8) std_string =
inl value = join value
!\($'"serde_json::from_value(!value)"')
|> resultm.map_error' fun (x : json_error) => x |> format'
encode_uri_component¶
In [ ]:
inl encode_uri_component (s : std_string) : js_string =
!\($'"js_sys::encode_uri_component(&!s)"')
strip_prefix¶
In [ ]:
inl strip_prefix (prefix : char) (s : std_string) : optionm'.option' (rust.ref str) =
inl s = join s
!\($'"!s.strip_prefix(!prefix)"')
str_from_utf8¶
In [ ]:
inl str_from_utf8 (bytes : rust.ref (am'.slice u8)) : resultm.result' (rust.ref str) utf8_error =
!\\(bytes, $'"std::str::from_utf8($0)"')
string_from_utf8¶
In [ ]:
inl string_from_utf8 (bytes : am'.vec u8) : resultm.result' std_string from_utf8_error =
inl bytes = join bytes
!\\(bytes, $'"std::string::String::from_utf8($0)"')
base64_decode¶
In [ ]:
inl base64_decode (s : std_string) : result std_string std_string =
fun () =>
inl s = join s
inl bytes : resultm.result' (am'.vec u8) base64_decode_error =
!\($'"base64::Engine::decode(&base64::engine::general_purpose::STANDARD, !s)"')
bytes
|> resultm.map_error' format'
|> resultm.try'
|> string_from_utf8
|> resultm.map_error' format'
|> fun x =>
join x ()
|> resultm.unbox
encoding'¶
In [ ]:
nominal encoding' =
`(
global "#if FABLE_COMPILER\n[<Fable.Core.Erase; Fable.Core.Emit(\"encoding_rs::Encoding\")>]\n#endif\ntype encoding_rs_Encoding = class end"
$'' : $'encoding_rs_Encoding'
)
encoding_utf8'¶
In [ ]:
inl encoding_utf8' () : rust.ref encoding' =
!\($'"encoding_rs::UTF_8"')
encoding_1252¶
In [ ]:
inl encoding_1252' () : rust.ref encoding' =
!\($'"encoding_rs::WINDOWS_1252"')
encoding_encode¶
In [ ]:
inl encoding_encode' (encoding : rust.ref encoding') (text : string) : rust.cow (am'.slice u8) =
!\\((encoding, text), $'"$0.encode(&*$1).0"')
utf8_decode¶
In [ ]:
inl utf8_decode (data : am'.vec u8) : resultm.result' std_string (rust.cow str) =
!\($'$"encoding::Encoding::decode(encoding::all::UTF_8, &!data, encoding::DecoderTrap::Replace)"')
windows¶
In [ ]:
nominal windows t =
`(
global "#if FABLE_COMPILER\n[<Fable.Core.Erase; Fable.Core.Emit(\"std::slice::Windows<$0>\")>]\n#endif\ntype std_slice_Windows<'T> = class end"
$'' : $'std_slice_Windows<`t>'
)
inl windows (len : unativeint) (source : am'.vec u8) : windows u8 =
inl source = source |> rust.new_box |> rust.box_leak
// inl source' = source |> rust.clone
inl result = !\\(len, $'"<[_]>::windows(!source, $0)"')
// source |> rust.drop
result
any¶
In [ ]:
inl any forall t. (fn : string -> bool) (source : windows t) : bool =
(!\($'"true; let mut !source = !source"') : bool) |> ignore
inl fn' x =
x
|> str_from_utf8
|> resultm.unwrap_or' #""
|> ref_to_std_string
|> from_std_string
|> fn
!\\(fn', $'"!source.any(move |x| $0(x))"')
slice_contains¶
In [ ]:
inl slice_contains (text : string) (source : am'.vec u8) : bool =
fun () =>
inl source = join source
source
|> windows (text |> length |> (fun x => x : i32) |> convert)
|> any ((=.) text)
|> fun x => join x ()
as_bytes¶
In [ ]:
inl as_bytes (text : string) : rust.ref (am'.slice u8) =
inl text = join text
!\($'"!text.as_bytes()"')
into_bytes¶
In [ ]:
inl into_bytes (x : std_string) : am'.vec u8 =
!\\(x, $'$"$0.into_bytes()"')
python¶
encode_utf8¶
In [ ]:
inl encode_utf8 (s : string) : string =
inl encoding = "utf-8"
backend_switch {
Fsharp = fun () =>
open python_operators
!\\((s, encoding), $'"$0.encode($1)"') : string
Python = fun () =>
$'!s.encode(!encoding)' : string
}
sm'¶
contains¶
In [ ]:
inl contains (value : string) (s : string) : bool =
backend_switch {
Fsharp = fun () => $'!s.Contains !value ' : bool
Python = fun () => $'!value in !s ' : bool
}
to_string result t u¶
In [ ]:
instance to_string result t u = fun x =>
real
open rust
typecase (t * u) with
| string * string =>
match x with
| Ok x => x
| Error x => $'"sm\'.to_string result / Error: " + !x + ""' : string
| std_string * std_string =>
match x with
| Ok x => from_std_string x
| Error x => $'"sm\'.to_string result / Error: " + string !x + ""' : string
| _ => obj_to_string `u x
format_exception¶
In [ ]:
inl format_exception (ex : exn) : string =
run_target function
| Fsharp (Native) => fun () => $'$"{!ex.GetType ()}: {!ex.Message}"'
| _ => fun () => ex |> format_debug
In [ ]:
//// test
///! fsharp
///! rust
///! typescript
///! python
fun () => failwith "test"
|> _throws
|> optionm.value
|> sm'.format_exception
|> _assert_eq (run_target function
| Fsharp _ => fun () => join "System.Exception: test"
| Rust _ => fun () => "Exception { message: \"test\" }"
| TypeScript _ => fun () => "Error: test"
| Python _ => fun () => join "test"
| _ => fun () => null ()
)
.rs output: __assert_eq / actual: "Exception { message: "test" }" / expected: "Exception { message: "test" }" .ts output: __assert_eq / actual: Error: test / expected: Error: test .py output: __assert_eq / actual: test / expected: test
.fsx output: __assert_eq / actual: "System.Exception: test" / expected: "System.Exception: test"
range¶
In [ ]:
inl range forall t. (start : am'.range t) (end : am'.range t) s =
inl start, end =
match start, end with
| Start start, End fn =>
start, s |> length' |> fn
| End start_fn, End end_fn =>
inl len = s |> length'
start_fn len, end_fn len
s |> slice (start |> i32) (end |> i32)
concat_list¶
In [ ]:
inl concat_list s list =
list
|> listm'.box
|> seq.of_list'
|> concat s
ellipsis_end¶
In [ ]:
let ellipsis_end (max : i64) (s : string) =
inl len = sm.length s
if len <= max
then s
else
inl half = f64 max / 2
inl start_half = half |> math.ceil |> i64
inl end_half = half |> math.floor |> i64
inl start = s |> slice 0 (start_half - 1)
inl end = s |> slice (len - end_half) (len - 1)
(a ;[start; "..."; end] : _ i32 _)
|> seq.of_array
|> concat ""
In [ ]:
//// test
"12345"
|> ellipsis_end 2
|> _assert_eq "1...5"
"12345"
|> ellipsis_end 3
|> _assert_eq "12...5"
"1234567"
|> ellipsis_end 4
|> _assert_eq "12...67"
__assert_eq / actual: "1...5" / expected: "1...5" __assert_eq / actual: "12...5" / expected: "12...5" __assert_eq / actual: "12...67" / expected: "12...67"
format_ellipsis¶
In [ ]:
inl format_ellipsis s =
s
|> format_debug
|> ellipsis_end 400
replace_regex¶
In [ ]:
let replace_regex (pattern : string) (replacement : string) (s : string) : string =
run_target_args (fun () => s, pattern, replacement) function
| Fsharp (Native) => fun s, pattern, replacement =>
$'System.Text.RegularExpressions.Regex.Replace (!s, !pattern, !replacement)'
| Rust (Native) => fun s, pattern, replacement =>
inl regex = pattern |> new_regex |> resultm.unwrap'
inl s = join s
!\\((regex, s, replacement), $'$"$0.replace_all(&*$1, &*$2)"')
|> cow_to_std_string
|> from_std_string
| _ => fun _ => null ()
In [ ]:
//// test
///! fsharp
///! rust -d regex
" 123"
|> replace_regex "\\s\\w2" ""
|> _assert_eq "3"
.rs output (rust -d regex): __assert_eq / actual: "3" / expected: "3"
.fsx output: __assert_eq / actual: "3" / expected: "3"
In [ ]:
//// test
///! rust -d regex
" let main args =\n ()\n"
|> replace_regex $'@@"(?P<a> *)(?P<b>let\\s+main\\s+.*?\\s*=)"' "$a[<EntryPoint>]\n$a$b"
|> _assert_eq " [<EntryPoint>]\n let main args =\n ()\n"
__assert_eq / actual: " [<EntryPoint>] let main args = () " / expected: " [<EntryPoint>] let main args = () "
main¶
In [ ]:
inl main () =
$'let contains x = !contains x' : ()
$'let ends_with x = !ends_with x' : ()
$'let pad_left x = !pad_left x' : ()
$'let pad_right x = !pad_right x' : ()
$'let replace x = !replace x' : ()
$'let replace_regex x = !replace_regex x' : ()
inl slice (a : i32) (b : i32) c = slice a b c
$'let slice x = !slice x' : ()
$'let split x = !split x' : ()
$'let split_string x = !split_string x' : ()
$'let starts_with x = !starts_with x' : ()
$'let substring x = !substring x' : ()
$'let to_lower x = !to_lower x' : ()
$'let to_upper x = !to_upper x' : ()
$'let trim x = !trim x' : ()
inl trim_end x = (a x : _ int _) |> am'.to_list' |> listm'.unbox |> trim_end
$'let trim_end x = !trim_end x' : ()
inl trim_start x = (a x : _ int _) |> am'.to_list' |> listm'.unbox |> trim_start
$'let trim_start x = !trim_start x' : ()
$'let ellipsis x = !ellipsis x' : ()
$'let ellipsis_end x = !ellipsis_end x' : ()
$'let format_exception x = !format_exception x' : ()
$'let concat_array_trailing x = !concat_array_trailing x' : ()
inl concat a (b : seq.seq' string) = concat a b
$'let concat x = !concat x' : ()
$'let join\' x = !join' x' : ()
$'let to_char_array x = !to_char_array x' : ()
rust¶
to_string std_string¶
In [ ]:
open rust
instance to_string std_string = from_std_string