common¶
In [ ]:
//// test
open testing
common¶
(:>)¶
In [ ]:
prototype (~:>) r : forall t. t -> r
to_any¶
In [ ]:
inl to_any forall t. (obj : t) : any =
$'!obj '
instance (~:>) any = to_any
(||>)¶
In [ ]:
//// test
///! fsharp
///! cuda
///! rust
///! typescript
///! python
(3i32, 2i32)
||> fun a b => a - b
|> _assert_eq 1
.py output (Cuda): __assert_eq / actual: 1 / expected: 1 Traceback (most recent call last): File "cupy/cuda/stream.pyx", line 36, in cupy.cuda.stream._ThreadLocal.get AttributeError: '_thread._local' object has no attribute 'tls' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/runner/work/polyglot/polyglot/target/spiral_Eval/packages/dd15b576f5b655c9d65b55a74fee7c4d7f14d92fac83e4e835a81157fc278d70/main.py", line 70, in <module> if __name__ == '__main__': result = main(); None if result is None else print(result) ^^^^^^ File "/home/runner/work/polyglot/polyglot/target/spiral_Eval/packages/dd15b576f5b655c9d65b55a74fee7c4d7f14d92fac83e4e835a81157fc278d70/main.py", line 67, in main cp.cuda.get_current_stream().synchronize() # This line is here so the `__trap()` calls on the kernel aren't missed. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "cupy/cuda/stream.pyx", line 87, in cupy.cuda.stream.get_current_stream File "cupy/cuda/stream.pyx", line 96, in cupy.cuda.stream.get_current_stream File "cupy/cuda/stream.pyx", line 38, in cupy.cuda.stream._ThreadLocal.get File "cupy/cuda/stream.pyx", line 24, in cupy.cuda.stream._ThreadLocal.__init__ File "cupy_backends/cuda/api/runtime.pyx", line 393, in cupy_backends.cuda.api.runtime.getDeviceCount File "cupy_backends/cuda/api/runtime.pyx", line 146, in cupy_backends.cuda.api.runtime.check_status cupy_backends.cuda.api.runtime.CUDARuntimeError: cudaErrorInsufficientDriver: CUDA driver version is insufficient for CUDA runtime version .rs output: __assert_eq / actual: 1 / expected: 1 .ts output: __assert_eq / actual: 1 / expected: 1 .py output: __assert_eq / actual: 1 / expected: 1
.fsx output: __assert_eq / actual: 1 / expected: 1
flip¶
In [ ]:
inl flip fn a b =
fn b a
In [ ]:
//// test
///! fsharp
///! cuda
///! rust
///! typescript
///! python
(1i32, 2i32)
||> flip pair
|> _assert_eq (2, 1)
.py output (Cuda): __assert_eq / actual: (2, 1) / expected: (2, 1) Traceback (most recent call last): File "cupy/cuda/stream.pyx", line 36, in cupy.cuda.stream._ThreadLocal.get AttributeError: '_thread._local' object has no attribute 'tls' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/runner/work/polyglot/polyglot/target/spiral_Eval/packages/90fc36f41e64468572a728d793796180ea6fe2e1688b7f6c7dee930bffceb10e/main.py", line 70, in <module> if __name__ == '__main__': result = main(); None if result is None else print(result) ^^^^^^ File "/home/runner/work/polyglot/polyglot/target/spiral_Eval/packages/90fc36f41e64468572a728d793796180ea6fe2e1688b7f6c7dee930bffceb10e/main.py", line 67, in main cp.cuda.get_current_stream().synchronize() # This line is here so the `__trap()` calls on the kernel aren't missed. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "cupy/cuda/stream.pyx", line 87, in cupy.cuda.stream.get_current_stream File "cupy/cuda/stream.pyx", line 96, in cupy.cuda.stream.get_current_stream File "cupy/cuda/stream.pyx", line 38, in cupy.cuda.stream._ThreadLocal.get File "cupy/cuda/stream.pyx", line 24, in cupy.cuda.stream._ThreadLocal.__init__ File "cupy_backends/cuda/api/runtime.pyx", line 393, in cupy_backends.cuda.api.runtime.getDeviceCount File "cupy_backends/cuda/api/runtime.pyx", line 146, in cupy_backends.cuda.api.runtime.check_status cupy_backends.cuda.api.runtime.CUDARuntimeError: cudaErrorInsufficientDriver: CUDA driver version is insufficient for CUDA runtime version .rs output: __assert_eq / actual: (2, 1) / expected: (2, 1) .ts output: __assert_eq / actual: 2,1 / expected: 2,1 .py output: __assert_eq / actual: (2, 1) / expected: (2, 1)
.fsx output: __assert_eq / actual: struct (2, 1) / expected: struct (2, 1)
join_body¶
In [ ]:
inl join_body body acc x =
if var_is x |> not
then body acc x
else
inl acc = dyn acc
join body acc x
In [ ]:
//// test
inl rec fold_list f s = function
| Cons (x, x') => fold_list f (f s x) x'
| Nil => s
In [ ]:
//// test
///! fsharp
///! cuda
///! rust
///! typescript
///! python
//// print_code=true
[ 5i32; 4; join 3; 2; 1 ]
|> fold_list (+) 0
|> _assert_eq 15
.py output (Cuda): __assert_eq / actual: 15 / expected: 15 Traceback (most recent call last): File "cupy/cuda/stream.pyx", line 36, in cupy.cuda.stream._ThreadLocal.get AttributeError: '_thread._local' object has no attribute 'tls' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/runner/work/polyglot/polyglot/target/spiral_Eval/packages/7320be57e43129587415aec54a480c6af6cf50b163339fb451812bb42d8509ae/main.py", line 93, in <module> if __name__ == '__main__': result = main(); None if result is None else print(result) ^^^^^^ File "/home/runner/work/polyglot/polyglot/target/spiral_Eval/packages/7320be57e43129587415aec54a480c6af6cf50b163339fb451812bb42d8509ae/main.py", line 90, in main cp.cuda.get_current_stream().synchronize() # This line is here so the `__trap()` calls on the kernel aren't missed. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "cupy/cuda/stream.pyx", line 87, in cupy.cuda.stream.get_current_stream File "cupy/cuda/stream.pyx", line 96, in cupy.cuda.stream.get_current_stream File "cupy/cuda/stream.pyx", line 38, in cupy.cuda.stream._ThreadLocal.get File "cupy/cuda/stream.pyx", line 24, in cupy.cuda.stream._ThreadLocal.__init__ File "cupy_backends/cuda/api/runtime.pyx", line 393, in cupy_backends.cuda.api.runtime.getDeviceCount File "cupy_backends/cuda/api/runtime.pyx", line 146, in cupy_backends.cuda.api.runtime.check_status cupy_backends.cuda.api.runtime.CUDARuntimeError: cudaErrorInsufficientDriver: CUDA driver version is insufficient for CUDA runtime version .rs output: __assert_eq / actual: 15 / expected: 15 .ts output: __assert_eq / actual: 15 / expected: 15 .py output: __assert_eq / actual: 15 / expected: 15
.fsx: let rec method1 () : int32 = 3 and method2 (v0 : bool) : bool = v0 and closure0 (v0 : string) () : unit = let v1 : (string -> unit) = System.Console.WriteLine v1 v0 and method0 () : unit = let v0 : int32 = method1() let v1 : int32 = 9 + v0 let v2 : int32 = v1 + 2 let v3 : int32 = v2 + 1 let v4 : bool = v3 = 15 let v6 : bool = if v4 then true else method2(v4) let v7 : string = "__assert_eq" let v8 : string = $"{v7} / actual: %A{v3} / expected: %A{15}" let v11 : unit = () let v12 : (unit -> unit) = closure0(v8) let v13 : unit = (fun () -> v12 (); v11) () let v15 : bool = v6 = false if v15 then failwith<unit> v8 method0() .rs: #![allow(dead_code)] #![allow(non_camel_case_types)] #![allow(non_snake_case)] #![allow(non_upper_case_globals)] #![allow(unreachable_code)] #![allow(unused_attributes)] #![allow(unused_imports)] #![allow(unused_macros)] #![allow(unused_parens)] #![allow(unused_variables)] mod module_7e2cd9e0 { pub mod Spiral_builder { use super::*; use fable_library_rust::Native_::on_startup; use fable_library_rust::String_::printfn; use fable_library_rust::String_::sprintf; use fable_library_rust::String_::string; pub fn method1() -> i32 { 3_i32 } pub fn method2(v0: bool) -> bool { v0 } pub fn closure0(v0: string, unitVar: ()) { printfn!("{0}", v0); } pub fn method0() { let v3: i32 = 9_i32 + Spiral_builder::method1() + 2_i32 + 1_i32; let v4: bool = v3 == 15_i32; let v6: bool = if v4 { true } else { Spiral_builder::method2(v4) }; let v8: string = sprintf!( "{} / actual: {:?} / expected: {:?}", string("__assert_eq"), v3, 15_i32 ); let v13: () = { Spiral_builder::closure0(v8.clone(), ()); () }; if v6 == false { panic!("{}", v8,); } } // on_startup!(Spiral_builder::method0()); } } pub use module_7e2cd9e0::*; pub fn main() -> Result<(), String> { Ok(Spiral_builder::method0()) } .ts: import { int32 } from "./fable_modules/fable-library-ts.4.21.0/Int32.js"; import { interpolate, toText } from "./fable_modules/fable-library-ts.4.21.0/String.js"; export function method1(): int32 { return 3; } export function method2(v0: boolean): boolean { return v0; } export function closure0(v0: string, unitVar: void): void { console.log(v0); } export function method0(): void { const v3: int32 = (((9 + method1()) + 2) + 1) | 0; const v4: boolean = v3 === 15; const v6: boolean = v4 ? true : method2(v4); const v8: string = toText(interpolate("%P() / actual: %A%P() / expected: %A%P()", ["__assert_eq", v3, 15])); let v13: any; closure0(v8, undefined); v13 = undefined; if (v6 === false) { throw new Error(v8); } } method0(); .py: from fable_modules.fable_library.string_ import (to_text, interpolate) def method1(__unit: None=None) -> int: return 3 def method2(v0: bool) -> bool: return v0 def closure0(v0: str, unit_var: None) -> None: print(v0) def method0(__unit: None=None) -> None: v3: int = (((9 + method1()) + 2) + 1) or 0 v4: bool = v3 == 15 v6: bool = True if v4 else method2(v4) v8: str = to_text(interpolate("%P() / actual: %A%P() / expected: %A%P()", ["__assert_eq", v3, 15])) v13: None closure0(v8, None) v13 = None if v6 == False: raise Exception(v8) method0() .py: kernel = r""" """ class static_array(): def __init__(self, length): self.ptr = [] for _ in range(length): self.ptr.append(None) def __getitem__(self, index): assert 0 <= index < len(self.ptr), "The get index needs to be in range." return self.ptr[index] def __setitem__(self, index, value): assert 0 <= index < len(self.ptr), "The set index needs to be in range." self.ptr[index] = value class static_array_list(static_array): def __init__(self, length): super().__init__(length) self.length = 0 def __getitem__(self, index): assert 0 <= index < self.length, "The get index needs to be in range." return self.ptr[index] def __setitem__(self, index, value): assert 0 <= index < self.length, "The set index needs to be in range." self.ptr[index] = value def push(self,value): assert (self.length < len(self.ptr)), "The length before pushing has to be less than the maximum length of the array." self.ptr[self.length] = value self.length += 1 def pop(self): assert (0 < self.length), "The length before popping has to be greater than 0." self.length -= 1 return self.ptr[self.length] def unsafe_set_length(self,i): assert 0 <= i <= len(self.ptr), "The new length has to be in range." self.length = i class dynamic_array(static_array): pass class dynamic_array_list(static_array_list): def length_(self): return self.length import cupy as cp from dataclasses import dataclass from typing import NamedTuple, Union, Callable, Tuple i8 = int; i16 = int; i32 = int; i64 = int; u8 = int; u16 = int; u32 = int; u64 = int; f32 = float; f64 = float; char = str; string = str def method1() -> i32: return 3 def method2(v0 : bool) -> bool: return v0 def method0() -> None: v0 = method1() v1 = 9 + v0 del v0 v2 = v1 + 2 del v1 v3 = v2 + 1 del v2 v4 = v3 == 15 if v4: v6 = True else: v6 = method2(v4) del v4 v9 = "__assert_eq" v10 = f"{v9} / actual: {v3} / expected: {15}" del v3, v9 print(v10) v16 = v6 == False del v6 if v16: del v16 raise Exception(v10) else: del v10, v16 return def main_body(): return method0() def main(): r = main_body() cp.cuda.get_current_stream().synchronize() # This line is here so the `__trap()` calls on the kernel aren't missed. return r if __name__ == '__main__': result = main(); None if result is None else print(result) .py: kernel = r""" """ class static_array(): def __init__(self, length): self.ptr = [] for _ in range(length): self.ptr.append(None) def __getitem__(self, index): assert 0 <= index < len(self.ptr), "The get index needs to be in range." return self.ptr[index] def __setitem__(self, index, value): assert 0 <= index < len(self.ptr), "The set index needs to be in range." self.ptr[index] = value class static_array_list(static_array): def __init__(self, length): super().__init__(length) self.length = 0 def __getitem__(self, index): assert 0 <= index < self.length, "The get index needs to be in range." return self.ptr[index] def __setitem__(self, index, value): assert 0 <= index < self.length, "The set index needs to be in range." self.ptr[index] = value def push(self,value): assert (self.length < len(self.ptr)), "The length before pushing has to be less than the maximum length of the array." self.ptr[self.length] = value self.length += 1 def pop(self): assert (0 < self.length), "The length before popping has to be greater than 0." self.length -= 1 return self.ptr[self.length] def unsafe_set_length(self,i): assert 0 <= i <= len(self.ptr), "The new length has to be in range." self.length = i class dynamic_array(static_array): pass class dynamic_array_list(static_array_list): def length_(self): return self.length import cupy as cp from dataclasses import dataclass from typing import NamedTuple, Union, Callable, Tuple i8 = int; i16 = int; i32 = int; i64 = int; u8 = int; u16 = int; u32 = int; u64 = int; f32 = float; f64 = float; char = str; string = str def method1() -> i32: return 3 def method2(v0 : bool) -> bool: return v0 def method0() -> None: v0 = method1() v1 = 9 + v0 del v0 v2 = v1 + 2 del v1 v3 = v2 + 1 del v2 v4 = v3 == 15 if v4: v6 = True else: v6 = method2(v4) del v4 v9 = "__assert_eq" v10 = f"{v9} / actual: {v3} / expected: {15}" del v3, v9 print(v10) v16 = v6 == False del v6 if v16: del v16 raise Exception(v10) else: del v10, v16 return def main_body(): return method0() def main(): r = main_body() cp.cuda.get_current_stream().synchronize() # This line is here so the `__trap()` calls on the kernel aren't missed. return r if __name__ == '__main__': result = main(); None if result is None else print(result) .fsx output: __assert_eq / actual: 15 / expected: 15
In [ ]:
//// test
///! fsharp
///! cuda
///! rust
///! typescript
///! python
//// print_code=true
[ 5i32; 4; join 3; 2; 1 ]
|> fold_list (join_body (+)) 0
|> _assert_eq 15
.py output (Cuda): __assert_eq / actual: 15 / expected: 15 Traceback (most recent call last): File "cupy/cuda/stream.pyx", line 36, in cupy.cuda.stream._ThreadLocal.get AttributeError: '_thread._local' object has no attribute 'tls' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/runner/work/polyglot/polyglot/target/spiral_Eval/packages/64d416b32f474bc59c370e32c50284af0bcd64f9b4b3078c5639ca77d16cce0e/main.py", line 98, in <module> if __name__ == '__main__': result = main(); None if result is None else print(result) ^^^^^^ File "/home/runner/work/polyglot/polyglot/target/spiral_Eval/packages/64d416b32f474bc59c370e32c50284af0bcd64f9b4b3078c5639ca77d16cce0e/main.py", line 95, in main cp.cuda.get_current_stream().synchronize() # This line is here so the `__trap()` calls on the kernel aren't missed. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "cupy/cuda/stream.pyx", line 87, in cupy.cuda.stream.get_current_stream File "cupy/cuda/stream.pyx", line 96, in cupy.cuda.stream.get_current_stream File "cupy/cuda/stream.pyx", line 38, in cupy.cuda.stream._ThreadLocal.get File "cupy/cuda/stream.pyx", line 24, in cupy.cuda.stream._ThreadLocal.__init__ File "cupy_backends/cuda/api/runtime.pyx", line 393, in cupy_backends.cuda.api.runtime.getDeviceCount File "cupy_backends/cuda/api/runtime.pyx", line 146, in cupy_backends.cuda.api.runtime.check_status cupy_backends.cuda.api.runtime.CUDARuntimeError: cudaErrorInsufficientDriver: CUDA driver version is insufficient for CUDA runtime version .rs output: __assert_eq / actual: 15 / expected: 15 .ts output: __assert_eq / actual: 15 / expected: 15 .py output: __assert_eq / actual: 15 / expected: 15
.fsx: let rec method1 () : int32 = 3 and method2 (v0 : int32, v1 : int32) : int32 = let v2 : int32 = v1 + v0 v2 and method3 (v0 : bool) : bool = v0 and closure0 (v0 : string) () : unit = let v1 : (string -> unit) = System.Console.WriteLine v1 v0 and method0 () : unit = let v0 : int32 = method1() let v1 : int32 = 9 let v2 : int32 = method2(v0, v1) let v3 : int32 = v2 + 2 let v4 : int32 = v3 + 1 let v5 : bool = v4 = 15 let v7 : bool = if v5 then true else method3(v5) let v8 : string = "__assert_eq" let v9 : string = $"{v8} / actual: %A{v4} / expected: %A{15}" let v12 : unit = () let v13 : (unit -> unit) = closure0(v9) let v14 : unit = (fun () -> v13 (); v12) () let v16 : bool = v7 = false if v16 then failwith<unit> v9 method0() .rs: #![allow(dead_code)] #![allow(non_camel_case_types)] #![allow(non_snake_case)] #![allow(non_upper_case_globals)] #![allow(unreachable_code)] #![allow(unused_attributes)] #![allow(unused_imports)] #![allow(unused_macros)] #![allow(unused_parens)] #![allow(unused_variables)] mod module_7e2cd9e0 { pub mod Spiral_builder { use super::*; use fable_library_rust::Native_::on_startup; use fable_library_rust::String_::printfn; use fable_library_rust::String_::sprintf; use fable_library_rust::String_::string; pub fn method1() -> i32 { 3_i32 } pub fn method2(v0: i32, v1: i32) -> i32 { v1 + v0 } pub fn method3(v0: bool) -> bool { v0 } pub fn closure0(v0: string, unitVar: ()) { printfn!("{0}", v0); } pub fn method0() { let v4: i32 = Spiral_builder::method2(Spiral_builder::method1(), 9_i32) + 2_i32 + 1_i32; let v5: bool = v4 == 15_i32; let v7: bool = if v5 { true } else { Spiral_builder::method3(v5) }; let v9: string = sprintf!( "{} / actual: {:?} / expected: {:?}", string("__assert_eq"), v4, 15_i32 ); let v14: () = { Spiral_builder::closure0(v9.clone(), ()); () }; if v7 == false { panic!("{}", v9,); } } // on_startup!(Spiral_builder::method0()); } } pub use module_7e2cd9e0::*; pub fn main() -> Result<(), String> { Ok(Spiral_builder::method0()) } .ts: import { int32 } from "./fable_modules/fable-library-ts.4.21.0/Int32.js"; import { interpolate, toText } from "./fable_modules/fable-library-ts.4.21.0/String.js"; export function method1(): int32 { return 3; } export function method2(v0: int32, v1: int32): int32 { return v1 + v0; } export function method3(v0: boolean): boolean { return v0; } export function closure0(v0: string, unitVar: void): void { console.log(v0); } export function method0(): void { const v4: int32 = ((method2(method1(), 9) + 2) + 1) | 0; const v5: boolean = v4 === 15; const v7: boolean = v5 ? true : method3(v5); const v9: string = toText(interpolate("%P() / actual: %A%P() / expected: %A%P()", ["__assert_eq", v4, 15])); let v14: any; closure0(v9, undefined); v14 = undefined; if (v7 === false) { throw new Error(v9); } } method0(); .py: from fable_modules.fable_library.string_ import (to_text, interpolate) def method1(__unit: None=None) -> int: return 3 def method2(v0: int, v1: int) -> int: return v1 + v0 def method3(v0: bool) -> bool: return v0 def closure0(v0: str, unit_var: None) -> None: print(v0) def method0(__unit: None=None) -> None: v4: int = ((method2(method1(), 9) + 2) + 1) or 0 v5: bool = v4 == 15 v7: bool = True if v5 else method3(v5) v9: str = to_text(interpolate("%P() / actual: %A%P() / expected: %A%P()", ["__assert_eq", v4, 15])) v14: None closure0(v9, None) v14 = None if v7 == False: raise Exception(v9) method0() .py: kernel = r""" """ class static_array(): def __init__(self, length): self.ptr = [] for _ in range(length): self.ptr.append(None) def __getitem__(self, index): assert 0 <= index < len(self.ptr), "The get index needs to be in range." return self.ptr[index] def __setitem__(self, index, value): assert 0 <= index < len(self.ptr), "The set index needs to be in range." self.ptr[index] = value class static_array_list(static_array): def __init__(self, length): super().__init__(length) self.length = 0 def __getitem__(self, index): assert 0 <= index < self.length, "The get index needs to be in range." return self.ptr[index] def __setitem__(self, index, value): assert 0 <= index < self.length, "The set index needs to be in range." self.ptr[index] = value def push(self,value): assert (self.length < len(self.ptr)), "The length before pushing has to be less than the maximum length of the array." self.ptr[self.length] = value self.length += 1 def pop(self): assert (0 < self.length), "The length before popping has to be greater than 0." self.length -= 1 return self.ptr[self.length] def unsafe_set_length(self,i): assert 0 <= i <= len(self.ptr), "The new length has to be in range." self.length = i class dynamic_array(static_array): pass class dynamic_array_list(static_array_list): def length_(self): return self.length import cupy as cp from dataclasses import dataclass from typing import NamedTuple, Union, Callable, Tuple i8 = int; i16 = int; i32 = int; i64 = int; u8 = int; u16 = int; u32 = int; u64 = int; f32 = float; f64 = float; char = str; string = str def method1() -> i32: return 3 def method2(v0 : i32, v1 : i32) -> i32: v2 = v1 + v0 del v0, v1 return v2 def method3(v0 : bool) -> bool: return v0 def method0() -> None: v0 = method1() v1 = 9 v2 = method2(v0, v1) del v0, v1 v3 = v2 + 2 del v2 v4 = v3 + 1 del v3 v5 = v4 == 15 if v5: v7 = True else: v7 = method3(v5) del v5 v10 = "__assert_eq" v11 = f"{v10} / actual: {v4} / expected: {15}" del v4, v10 print(v11) v17 = v7 == False del v7 if v17: del v17 raise Exception(v11) else: del v11, v17 return def main_body(): return method0() def main(): r = main_body() cp.cuda.get_current_stream().synchronize() # This line is here so the `__trap()` calls on the kernel aren't missed. return r if __name__ == '__main__': result = main(); None if result is None else print(result) .py: kernel = r""" """ class static_array(): def __init__(self, length): self.ptr = [] for _ in range(length): self.ptr.append(None) def __getitem__(self, index): assert 0 <= index < len(self.ptr), "The get index needs to be in range." return self.ptr[index] def __setitem__(self, index, value): assert 0 <= index < len(self.ptr), "The set index needs to be in range." self.ptr[index] = value class static_array_list(static_array): def __init__(self, length): super().__init__(length) self.length = 0 def __getitem__(self, index): assert 0 <= index < self.length, "The get index needs to be in range." return self.ptr[index] def __setitem__(self, index, value): assert 0 <= index < self.length, "The set index needs to be in range." self.ptr[index] = value def push(self,value): assert (self.length < len(self.ptr)), "The length before pushing has to be less than the maximum length of the array." self.ptr[self.length] = value self.length += 1 def pop(self): assert (0 < self.length), "The length before popping has to be greater than 0." self.length -= 1 return self.ptr[self.length] def unsafe_set_length(self,i): assert 0 <= i <= len(self.ptr), "The new length has to be in range." self.length = i class dynamic_array(static_array): pass class dynamic_array_list(static_array_list): def length_(self): return self.length import cupy as cp from dataclasses import dataclass from typing import NamedTuple, Union, Callable, Tuple i8 = int; i16 = int; i32 = int; i64 = int; u8 = int; u16 = int; u32 = int; u64 = int; f32 = float; f64 = float; char = str; string = str def method1() -> i32: return 3 def method2(v0 : i32, v1 : i32) -> i32: v2 = v1 + v0 del v0, v1 return v2 def method3(v0 : bool) -> bool: return v0 def method0() -> None: v0 = method1() v1 = 9 v2 = method2(v0, v1) del v0, v1 v3 = v2 + 2 del v2 v4 = v3 + 1 del v3 v5 = v4 == 15 if v5: v7 = True else: v7 = method3(v5) del v5 v10 = "__assert_eq" v11 = f"{v10} / actual: {v4} / expected: {15}" del v4, v10 print(v11) v17 = v7 == False del v7 if v17: del v17 raise Exception(v11) else: del v11, v17 return def main_body(): return method0() def main(): r = main_body() cp.cuda.get_current_stream().synchronize() # This line is here so the `__trap()` calls on the kernel aren't missed. return r if __name__ == '__main__': result = main(); None if result is None else print(result) .fsx output: __assert_eq / actual: 15 / expected: 15
join_body_unit¶
In [ ]:
inl join_body_unit body d x =
if var_is d |> not
then body x
else
inl x = dyn x
join body x
In [ ]:
//// test
///! fsharp
///! cuda
///! rust
///! typescript
///! python
//// print_code=true
[ 5i32; 4; join 3; 2; 1 ]
|> fold_list (fun acc n => join_body_unit ((+) acc) n n) 0
|> _assert_eq 15
.py output (Cuda): __assert_eq / actual: 15 / expected: 15 Traceback (most recent call last): File "cupy/cuda/stream.pyx", line 36, in cupy.cuda.stream._ThreadLocal.get AttributeError: '_thread._local' object has no attribute 'tls' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/runner/work/polyglot/polyglot/target/spiral_Eval/packages/35e0592a79aebcdb9fe9d6c1a39649e9824c9eeac908e8c53758d1cbbf15f5a8/main.py", line 97, in <module> if __name__ == '__main__': result = main(); None if result is None else print(result) ^^^^^^ File "/home/runner/work/polyglot/polyglot/target/spiral_Eval/packages/35e0592a79aebcdb9fe9d6c1a39649e9824c9eeac908e8c53758d1cbbf15f5a8/main.py", line 94, in main cp.cuda.get_current_stream().synchronize() # This line is here so the `__trap()` calls on the kernel aren't missed. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "cupy/cuda/stream.pyx", line 87, in cupy.cuda.stream.get_current_stream File "cupy/cuda/stream.pyx", line 96, in cupy.cuda.stream.get_current_stream File "cupy/cuda/stream.pyx", line 38, in cupy.cuda.stream._ThreadLocal.get File "cupy/cuda/stream.pyx", line 24, in cupy.cuda.stream._ThreadLocal.__init__ File "cupy_backends/cuda/api/runtime.pyx", line 393, in cupy_backends.cuda.api.runtime.getDeviceCount File "cupy_backends/cuda/api/runtime.pyx", line 146, in cupy_backends.cuda.api.runtime.check_status cupy_backends.cuda.api.runtime.CUDARuntimeError: cudaErrorInsufficientDriver: CUDA driver version is insufficient for CUDA runtime version .rs output: __assert_eq / actual: 15 / expected: 15 .ts output: __assert_eq / actual: 15 / expected: 15 .py output: __assert_eq / actual: 15 / expected: 15
.fsx: let rec method1 () : int32 = 3 and method2 (v0 : int32) : int32 = let v1 : int32 = 9 + v0 v1 and method3 (v0 : bool) : bool = v0 and closure0 (v0 : string) () : unit = let v1 : (string -> unit) = System.Console.WriteLine v1 v0 and method0 () : unit = let v0 : int32 = method1() let v1 : int32 = method2(v0) let v2 : int32 = v1 + 2 let v3 : int32 = v2 + 1 let v4 : bool = v3 = 15 let v6 : bool = if v4 then true else method3(v4) let v7 : string = "__assert_eq" let v8 : string = $"{v7} / actual: %A{v3} / expected: %A{15}" let v11 : unit = () let v12 : (unit -> unit) = closure0(v8) let v13 : unit = (fun () -> v12 (); v11) () let v15 : bool = v6 = false if v15 then failwith<unit> v8 method0() .rs: #![allow(dead_code)] #![allow(non_camel_case_types)] #![allow(non_snake_case)] #![allow(non_upper_case_globals)] #![allow(unreachable_code)] #![allow(unused_attributes)] #![allow(unused_imports)] #![allow(unused_macros)] #![allow(unused_parens)] #![allow(unused_variables)] mod module_7e2cd9e0 { pub mod Spiral_builder { use super::*; use fable_library_rust::Native_::on_startup; use fable_library_rust::String_::printfn; use fable_library_rust::String_::sprintf; use fable_library_rust::String_::string; pub fn method1() -> i32 { 3_i32 } pub fn method2(v0: i32) -> i32 { 9_i32 + v0 } pub fn method3(v0: bool) -> bool { v0 } pub fn closure0(v0: string, unitVar: ()) { printfn!("{0}", v0); } pub fn method0() { let v3: i32 = Spiral_builder::method2(Spiral_builder::method1()) + 2_i32 + 1_i32; let v4: bool = v3 == 15_i32; let v6: bool = if v4 { true } else { Spiral_builder::method3(v4) }; let v8: string = sprintf!( "{} / actual: {:?} / expected: {:?}", string("__assert_eq"), v3, 15_i32 ); let v13: () = { Spiral_builder::closure0(v8.clone(), ()); () }; if v6 == false { panic!("{}", v8,); } } // on_startup!(Spiral_builder::method0()); } } pub use module_7e2cd9e0::*; pub fn main() -> Result<(), String> { Ok(Spiral_builder::method0()) } .ts: import { int32 } from "./fable_modules/fable-library-ts.4.21.0/Int32.js"; import { interpolate, toText } from "./fable_modules/fable-library-ts.4.21.0/String.js"; export function method1(): int32 { return 3; } export function method2(v0: int32): int32 { return 9 + v0; } export function method3(v0: boolean): boolean { return v0; } export function closure0(v0: string, unitVar: void): void { console.log(v0); } export function method0(): void { const v3: int32 = ((method2(method1()) + 2) + 1) | 0; const v4: boolean = v3 === 15; const v6: boolean = v4 ? true : method3(v4); const v8: string = toText(interpolate("%P() / actual: %A%P() / expected: %A%P()", ["__assert_eq", v3, 15])); let v13: any; closure0(v8, undefined); v13 = undefined; if (v6 === false) { throw new Error(v8); } } method0(); .py: from fable_modules.fable_library.string_ import (to_text, interpolate) def method1(__unit: None=None) -> int: return 3 def method2(v0: int) -> int: return 9 + v0 def method3(v0: bool) -> bool: return v0 def closure0(v0: str, unit_var: None) -> None: print(v0) def method0(__unit: None=None) -> None: v3: int = ((method2(method1()) + 2) + 1) or 0 v4: bool = v3 == 15 v6: bool = True if v4 else method3(v4) v8: str = to_text(interpolate("%P() / actual: %A%P() / expected: %A%P()", ["__assert_eq", v3, 15])) v13: None closure0(v8, None) v13 = None if v6 == False: raise Exception(v8) method0() .py: kernel = r""" """ class static_array(): def __init__(self, length): self.ptr = [] for _ in range(length): self.ptr.append(None) def __getitem__(self, index): assert 0 <= index < len(self.ptr), "The get index needs to be in range." return self.ptr[index] def __setitem__(self, index, value): assert 0 <= index < len(self.ptr), "The set index needs to be in range." self.ptr[index] = value class static_array_list(static_array): def __init__(self, length): super().__init__(length) self.length = 0 def __getitem__(self, index): assert 0 <= index < self.length, "The get index needs to be in range." return self.ptr[index] def __setitem__(self, index, value): assert 0 <= index < self.length, "The set index needs to be in range." self.ptr[index] = value def push(self,value): assert (self.length < len(self.ptr)), "The length before pushing has to be less than the maximum length of the array." self.ptr[self.length] = value self.length += 1 def pop(self): assert (0 < self.length), "The length before popping has to be greater than 0." self.length -= 1 return self.ptr[self.length] def unsafe_set_length(self,i): assert 0 <= i <= len(self.ptr), "The new length has to be in range." self.length = i class dynamic_array(static_array): pass class dynamic_array_list(static_array_list): def length_(self): return self.length import cupy as cp from dataclasses import dataclass from typing import NamedTuple, Union, Callable, Tuple i8 = int; i16 = int; i32 = int; i64 = int; u8 = int; u16 = int; u32 = int; u64 = int; f32 = float; f64 = float; char = str; string = str def method1() -> i32: return 3 def method2(v0 : i32) -> i32: v1 = 9 + v0 del v0 return v1 def method3(v0 : bool) -> bool: return v0 def method0() -> None: v0 = method1() v1 = method2(v0) del v0 v2 = v1 + 2 del v1 v3 = v2 + 1 del v2 v4 = v3 == 15 if v4: v6 = True else: v6 = method3(v4) del v4 v9 = "__assert_eq" v10 = f"{v9} / actual: {v3} / expected: {15}" del v3, v9 print(v10) v16 = v6 == False del v6 if v16: del v16 raise Exception(v10) else: del v10, v16 return def main_body(): return method0() def main(): r = main_body() cp.cuda.get_current_stream().synchronize() # This line is here so the `__trap()` calls on the kernel aren't missed. return r if __name__ == '__main__': result = main(); None if result is None else print(result) .py: kernel = r""" """ class static_array(): def __init__(self, length): self.ptr = [] for _ in range(length): self.ptr.append(None) def __getitem__(self, index): assert 0 <= index < len(self.ptr), "The get index needs to be in range." return self.ptr[index] def __setitem__(self, index, value): assert 0 <= index < len(self.ptr), "The set index needs to be in range." self.ptr[index] = value class static_array_list(static_array): def __init__(self, length): super().__init__(length) self.length = 0 def __getitem__(self, index): assert 0 <= index < self.length, "The get index needs to be in range." return self.ptr[index] def __setitem__(self, index, value): assert 0 <= index < self.length, "The set index needs to be in range." self.ptr[index] = value def push(self,value): assert (self.length < len(self.ptr)), "The length before pushing has to be less than the maximum length of the array." self.ptr[self.length] = value self.length += 1 def pop(self): assert (0 < self.length), "The length before popping has to be greater than 0." self.length -= 1 return self.ptr[self.length] def unsafe_set_length(self,i): assert 0 <= i <= len(self.ptr), "The new length has to be in range." self.length = i class dynamic_array(static_array): pass class dynamic_array_list(static_array_list): def length_(self): return self.length import cupy as cp from dataclasses import dataclass from typing import NamedTuple, Union, Callable, Tuple i8 = int; i16 = int; i32 = int; i64 = int; u8 = int; u16 = int; u32 = int; u64 = int; f32 = float; f64 = float; char = str; string = str def method1() -> i32: return 3 def method2(v0 : i32) -> i32: v1 = 9 + v0 del v0 return v1 def method3(v0 : bool) -> bool: return v0 def method0() -> None: v0 = method1() v1 = method2(v0) del v0 v2 = v1 + 2 del v1 v3 = v2 + 1 del v2 v4 = v3 == 15 if v4: v6 = True else: v6 = method3(v4) del v4 v9 = "__assert_eq" v10 = f"{v9} / actual: {v3} / expected: {15}" del v3, v9 print(v10) v16 = v6 == False del v6 if v16: del v16 raise Exception(v10) else: del v10, v16 return def main_body(): return method0() def main(): r = main_body() cp.cuda.get_current_stream().synchronize() # This line is here so the `__trap()` calls on the kernel aren't missed. return r if __name__ == '__main__': result = main(); None if result is None else print(result) .fsx output: __assert_eq / actual: 15 / expected: 15
retry_fn'¶
In [ ]:
inl retry_fn' retries fn =
let rec loop retry =
inl is_error, result =
match fn () with
| Ok x => false, x
| Error x => true, x
if not is_error || retry >= retries
then result
else
trace Debug
fun () => "common.retry_fn\' / loop"
fun () => { is_error retry = $'$"{!retry}/{!retries}"' : string; result }
loop (retry + 1)
loop 1
fsharp¶
upcast¶
In [ ]:
inl upcast forall t u. (x : t) : u =
$'!x :> `u '
downcast¶
In [ ]:
inl downcast forall t u. (x : t) : u =
$'!x :?> `u '
random¶
In [ ]:
nominal random = $'System.Random'
inl random () : random =
$'`random ' ()
random_next¶
In [ ]:
inl random_next (min : i32) (max : i32) (random : random) : i32 =
$'!random.Next (!min, !max)'
disposable¶
In [ ]:
nominal disposable t = $"backend_switch `({ Fsharp : $'System.IDisposable'; Python : $'object' })"
dispose¶
In [ ]:
inl dispose (disposable : disposable _) : () =
backend_switch {
Fsharp = fun () => disposable |> $'_.Dispose()' : ()
Python = fun () => $'!disposable.__exit__(None, None, None)' : ()
}
yield¶
In [ ]:
inl yield forall t. (x : t) : () =
$'yield !x '
return¶
In [ ]:
inl return forall t. (x : t) : () =
$'return !x '
return'¶
In [ ]:
inl return' forall t. (x : t) : t =
$'return !x '
retry_fn¶
In [ ]:
inl retry_fn forall t. retries (fn : () -> t) : option t =
let rec loop retry =
try
fun () =>
if retry < retries
then fn () |> Some
else None
fun ex =>
trace Warning
fun () => "common.retry_fn"
fun () => { retry ex }
None
|> function
| Some x => x
| None => loop (retry + 1)
loop 0
In [ ]:
//// test
///! fsharp
////! cuda // v3 = $"retry: {v0} / ex: %A{v1} / {v2 ()}"
///! rust
///! typescript
///! python
inl retry_fn_test = mut 0i32
fun () =>
retry_fn_test <- *retry_fn_test + 1
*retry_fn_test
|> retry_fn 3i32
|> _assert_eq' (Some 1i32)
.rs output: __assert_eq' / actual: US0_0(1) / expected: US0_0(1) .ts output: __assert_eq' / actual: US0_0 1 / expected: US0_0 1 .py output: __assert_eq' / actual: US0_0 1 / expected: US0_0 1
.fsx output: __assert_eq' / actual: US0_0 1 / expected: US0_0 1
In [ ]:
//// test
///! fsharp
////! cuda // v3 = $"retry: {v0} / ex: %A{v1} / {v2 ()}"
///! rust
///! typescript
///! python
inl retry_fn_test = mut 0i32
fun () =>
if *retry_fn_test >= 2
then *retry_fn_test
else
retry_fn_test <- *retry_fn_test + 1
failwith "test"
|> retry_fn 3i32
|> _assert_eq' (Some 2i32)
.rs output: 00:00:00 w #1 common.retry_fn / { retry = 0; ex = Exception { message: "test", } } 00:00:00 w #2 common.retry_fn / { retry = 1; ex = Exception { message: "test", } } __assert_eq' / actual: US0_0(2) / expected: US0_0(2) .ts output: 00:00:00 w #1 common.retry_fn / { retry = 0; ex = Error: test } 00:00:00 w #2 common.retry_fn / { retry = 1; ex = Error: test } __assert_eq' / actual: US0_0 2 / expected: US0_0 2 .py output: 00:00:00 w #1 common.retry_fn / { retry = 0; ex = test } 00:00:00 w #2 common.retry_fn / { retry = 1; ex = test } __assert_eq' / actual: US0_0 2 / expected: US0_0 2
.fsx output: 00:00:00 w #1 common.retry_fn / { retry = 0; ex = System.Exception: test at FSI_0033.closure1(Mut0 v0, Int32 v1, Unit unitVar2) at FSI_0033.method1(Mut0 v0, Int32 v1) } 00:00:00 w #2 common.retry_fn / { retry = 1; ex = System.Exception: test at FSI_0033.closure1(Mut0 v0, Int32 v1, Unit unitVar2) at FSI_0033.method1(Mut0 v0, Int32 v1) } __assert_eq' / actual: US0_0 2 / expected: US0_0 2
common¶
random'¶
In [ ]:
inl random' forall t. (min : t) (max : t) : t =
run_target function
| Rust (Contract) => fun () =>
failwith "common.random' / target=Rust(Contract)"
| Rust _ => fun () =>
open rust.rust_operators
!\\((min, max), $'"rand::Rng::gen_range(&mut rand::thread_rng(), $0..$1)"')
| _ => fun () =>
random () |> random_next (i32 min) (i32 max) |> convert
new_disposable¶
In [ ]:
inl new_disposable (fn : () -> ()) : disposable _ =
run_target function
| Rust _ => fun () =>
global "type Disposable (f : unit -> unit) = interface System.IDisposable with member _.Dispose () = f ()"
inl fn = join fn
$'new Disposable (fun () -> Fable.Core.RustInterop.emitRustExpr !fn "$0()" )'
| Fsharp _ | TypeScript _ | Python _ => fun () =>
inl fn = join fn
$'{ new System.IDisposable with member _.Dispose () = !fn () }'
| Cuda _ => fun () =>
$'class Disposable:'
$' def __init__(self, fn):'
$' self.fn = fn'
$' def __exit__(self, exc_type, exc_value, traceback):'
$' self.fn()'
$' return False'
$'Disposable(!fn)'
| _ => fun () => null ()
In [ ]:
//// test
///! fsharp
///! cuda
///! rust
///! typescript
///! python
inl new_disposable_test = mut 0i32
new_disposable fun () => new_disposable_test <- *new_disposable_test + 1
|> fun x => x : disposable ()
|> dispose
*new_disposable_test |> _assert_eq 1
.py output (Cuda): __assert_eq / actual: 1 / expected: 1 Traceback (most recent call last): File "cupy/cuda/stream.pyx", line 36, in cupy.cuda.stream._ThreadLocal.get AttributeError: '_thread._local' object has no attribute 'tls' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/runner/work/polyglot/polyglot/target/spiral_Eval/packages/fda07887a03693bee210a1e65846c1b26dfa7a3c5e01a8a1ecf27d0d50f43380/main.py", line 112, in <module> if __name__ == '__main__': result = main(); None if result is None else print(result) ^^^^^^ File "/home/runner/work/polyglot/polyglot/target/spiral_Eval/packages/fda07887a03693bee210a1e65846c1b26dfa7a3c5e01a8a1ecf27d0d50f43380/main.py", line 109, in main cp.cuda.get_current_stream().synchronize() # This line is here so the `__trap()` calls on the kernel aren't missed. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "cupy/cuda/stream.pyx", line 87, in cupy.cuda.stream.get_current_stream File "cupy/cuda/stream.pyx", line 96, in cupy.cuda.stream.get_current_stream File "cupy/cuda/stream.pyx", line 38, in cupy.cuda.stream._ThreadLocal.get File "cupy/cuda/stream.pyx", line 24, in cupy.cuda.stream._ThreadLocal.__init__ File "cupy_backends/cuda/api/runtime.pyx", line 393, in cupy_backends.cuda.api.runtime.getDeviceCount File "cupy_backends/cuda/api/runtime.pyx", line 146, in cupy_backends.cuda.api.runtime.check_status cupy_backends.cuda.api.runtime.CUDARuntimeError: cudaErrorInsufficientDriver: CUDA driver version is insufficient for CUDA runtime version .rs output: __assert_eq / actual: 1 / expected: 1 .ts output: __assert_eq / actual: 1 / expected: 1 .py output: __assert_eq / actual: 1 / expected: 1
.fsx output: __assert_eq / actual: 1 / expected: 1
In [ ]:
//// test
inl new_disposable_test = mut 0i32
fun () =>
new_disposable fun () => new_disposable_test <- *new_disposable_test + 1
|> fun x => x : disposable ()
|> use
|> ignore
|> return
|> async.new_task
|> async.await_task
|> async.run_synchronously
*new_disposable_test |> _assert_eq 1
__assert_eq / actual: 1 / expected: 1
In [ ]:
//// test
inl new_disposable_test = mut 0i32
fun () =>
new_disposable fun () => new_disposable_test <- *new_disposable_test + 1
|> fun x => x : disposable ()
|> use
|> ignore
|> return
|> async.new_async
|> async.run_synchronously
*new_disposable_test |> _assert_eq 1
__assert_eq / actual: 1 / expected: 1
In [ ]:
//// test
inl new_disposable_test = mut 0i32
fun () =>
new_disposable fun () => new_disposable_test <- *new_disposable_test + 1
|> fun x => x : disposable ()
|> ignore
|> return
|> async.new_async
|> async.run_synchronously
*new_disposable_test |> _assert_eq 0
__assert_eq / actual: 0 / expected: 0
main¶
In [ ]:
inl main () =
init_trace_state None
inl new_disposable x : _ () = new_disposable x
$'let new_disposable x = !new_disposable x' : ()
inl retry_fn (r : i32) (x : () -> _) : optionm'.option' () = retry_fn r x |> optionm'.box
$'let retry_fn x = !retry_fn x' : ()
inl memoize (fn : () -> ()) : () -> () = memoize fn
$'let memoize x = !memoize x' : ()