inlean-runtime 0.2.0

Runtime support for Rust code generated from Lean by inlean
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
//! Conversions between Rust values and Lean values, chosen by the Lean type.
//!
//! Several Lean types share one Rust type: `Array α` and `List α` are both `Vec<T>`, and
//! `ByteArray` and `Array UInt8` are both `Vec<u8>`. A conversion therefore cannot be found
//! from the Rust type alone. Generated code names it instead, as a type that implements
//! [`Codec`] and mirrors the Lean type. Each type of this module stands for the Lean type of
//! the same name, so `Array<Option<String>>` converts a `Vec<Option<String>>` to and from a
//! Lean `Array (Option String)`.
//!
//! A conversion moves what it can. [`Codec::into_lean`] takes the Rust value and builds the
//! Lean value around its buffers. [`Codec::from_lean`] takes out of the Lean value whatever
//! nothing else refers to, as Lean's own compiled code does when it takes a value apart.
//! Only [`Codec::to_lean`], which leaves the Rust value with the caller, always copies.
//!
//! The conversions are safe functions because of [`Value`]: a Lean value together with its
//! type and the one reference to it that the holder owns. The single unsafe claim at the
//! boundary is [`Value::from_raw`], where generated code says what a Lean function returned.

use crate::object::{self as o, box_, dec, dec_ref, inc, Obj};
use std::marker::PhantomData;

/// How Lean passes a value of a type: as an object, or as a scalar it keeps unboxed.
pub trait Repr: Copy {
    /// The value as an object: the form it has as an element of an array, an argument of a
    /// closure or a field of a polymorphic type. The object takes over the reference.
    fn into_object(self) -> Obj;

    /// The value out of an object that [`Repr::into_object`] made, whose reference is given
    /// up.
    ///
    /// # Safety
    /// `object` holds a value of this representation and the caller owns a reference to it.
    unsafe fn take(object: Obj) -> Self;

    /// The value out of an object that stays with its owner: one more reference to an
    /// object, a copy of a scalar.
    ///
    /// # Safety
    /// `object` holds a value of this representation.
    unsafe fn share(object: Obj) -> Self;

    /// Gives up the reference the value holds. A scalar holds none.
    ///
    /// # Safety
    /// The caller owns the reference.
    unsafe fn release(self);

    /// The same value with a reference of its own.
    ///
    /// # Safety
    /// The value is alive.
    unsafe fn retain(self) -> Self;
}

impl Repr for Obj {
    #[inline(always)]
    fn into_object(self) -> Obj {
        self
    }

    #[inline(always)]
    unsafe fn take(object: Obj) -> Obj {
        object
    }

    #[inline(always)]
    unsafe fn share(object: Obj) -> Obj {
        inc(object);
        object
    }

    #[inline(always)]
    unsafe fn release(self) {
        dec(self)
    }

    #[inline(always)]
    unsafe fn retain(self) -> Obj {
        inc(self);
        self
    }
}

/// A representation that is a plain number, with no reference to count.
pub trait Scalar: Repr {}

macro_rules! scalar_reprs {
    ($($ty:ty: |$value:ident| $boxed:expr, |$object:ident| $unboxed:expr;)*) => {$(
        impl Repr for $ty {
            #[inline(always)]
            fn into_object(self) -> Obj {
                let $value = self;
                // Allocation aside, boxing has no precondition.
                #[allow(unused_unsafe)]
                unsafe {
                    $boxed
                }
            }

            #[inline(always)]
            unsafe fn take($object: Obj) -> $ty {
                let value = $unboxed;
                dec($object);
                value
            }

            #[inline(always)]
            unsafe fn share($object: Obj) -> $ty {
                $unboxed
            }

            #[inline(always)]
            unsafe fn release(self) {}

            #[inline(always)]
            unsafe fn retain(self) -> $ty {
                self
            }
        }

        impl Scalar for $ty {}
    )*};
}

scalar_reprs! {
    u8: |v| box_(v as usize), |x| o::unbox(x) as u8;
    u16: |v| box_(v as usize), |x| o::unbox(x) as u16;
    u32: |v| o::box_uint32(v), |x| o::unbox_uint32(x);
    u64: |v| o::box_uint64(v), |x| o::unbox_uint64(x);
    usize: |v| o::box_usize(v), |x| o::unbox_usize(x);
    f64: |v| o::box_float(v), |x| o::unbox_float(x);
    f32: |v| o::box_float32(v), |x| o::unbox_float32(x);
}

/// A Lean value of the type `C` stands for, with the one reference to it that the holder
/// owns. Dropping it gives the reference up.
///
/// A value of a type that Lean passes as a scalar is that scalar. A codec of such a type
/// accepts every scalar in [`Codec::from_lean`], which is what lets [`Value::from_scalar`]
/// be safe.
#[repr(transparent)]
pub struct Value<C: Codec>(C::Repr, PhantomData<C>);

impl<C: Codec> Value<C> {
    /// # Safety
    /// `repr` is a value of the Lean type `C` stands for, produced by this runtime, and the
    /// caller owns a reference to it.
    #[inline(always)]
    pub unsafe fn from_raw(repr: C::Repr) -> Value<C> {
        Value(repr, PhantomData)
    }

    /// The value of a type that Lean passes as a scalar.
    #[inline(always)]
    pub fn from_scalar(repr: C::Repr) -> Value<C>
    where
        C::Repr: Scalar,
    {
        Value(repr, PhantomData)
    }

    /// The representation, with the reference.
    #[inline(always)]
    pub fn into_raw(self) -> C::Repr {
        let repr = self.0;
        std::mem::forget(self);
        repr
    }

    /// The representation, for a function that borrows it. The reference stays here.
    #[inline(always)]
    pub fn as_raw(&self) -> C::Repr {
        self.0
    }

    /// The value as an object; see [`Repr::into_object`].
    #[inline(always)]
    pub fn into_object(self) -> Obj {
        self.into_raw().into_object()
    }

    /// The value out of an object whose reference is given up.
    ///
    /// # Safety
    /// `object` holds a value of the Lean type `C` stands for, in the form
    /// [`Value::into_object`] gives it, and the caller owns a reference to it.
    #[inline(always)]
    pub unsafe fn take(object: Obj) -> Value<C> {
        Value(C::Repr::take(object), PhantomData)
    }

    /// The value out of an object that stays with its owner.
    ///
    /// # Safety
    /// `object` holds a value of the Lean type `C` stands for, in the form
    /// [`Value::into_object`] gives it.
    #[inline(always)]
    pub unsafe fn share(object: Obj) -> Value<C> {
        Value(C::Repr::share(object), PhantomData)
    }

    /// The same Lean value, with a reference of its own.
    #[inline(always)]
    pub fn retain(&self) -> Value<C> {
        Value(unsafe { self.0.retain() }, PhantomData)
    }

    /// The same value under another codec.
    ///
    /// # Safety
    /// `D` stands for the same Lean type as `C`.
    #[inline(always)]
    pub unsafe fn cast<D: Codec<Repr = C::Repr>>(self) -> Value<D> {
        Value(self.into_raw(), PhantomData)
    }
}

impl<C: Codec> Drop for Value<C> {
    #[inline(always)]
    fn drop(&mut self) {
        unsafe { self.0.release() }
    }
}

/// A conversion between a Rust type and the Lean type the implementor stands for.
pub trait Codec: Sized {
    /// The Rust type that owns a value.
    type Rust;

    /// How Lean passes a value of the type.
    type Repr: Repr;

    /// The Lean value of a Rust value that is given up. What can move is moved.
    fn into_lean(value: Self::Rust) -> Value<Self>;

    /// The Lean value of a Rust value that stays with the caller. A copy.
    fn to_lean(value: &Self::Rust) -> Value<Self>;

    /// The Rust value of a Lean value. What nothing else refers to is taken out of it, and
    /// the rest is copied.
    ///
    /// A codec whose representation is a scalar must accept every value of that scalar
    /// here, since [`Value::from_scalar`] makes a value of it from any.
    fn from_lean(value: Value<Self>) -> Self::Rust;

    /// The Lean value of a Rust value that the caller of an exported function passed by
    /// reference. The default converts it, as `to_lean` does. A codec whose Lean object holds
    /// the Rust value makes an object that stands for the caller's value instead, so that
    /// nothing is copied until Lean needs a value of its own.
    ///
    /// # Safety
    /// The value returned, and every reference Lean takes to it, is given up before the borrow
    /// of `value` ends.
    #[doc(hidden)]
    unsafe fn lent(value: &Self::Rust) -> Value<Self> {
        Self::to_lean(value)
    }

    /// Calls `f` with the Rust form of a Lean value that is only lent: the lender keeps its
    /// reference. This is how a Rust function bound to a Lean declaration receives an argument
    /// that Lean passes with `@&`.
    ///
    /// The default copies the value out for the length of the call. A codec whose Lean object
    /// holds the Rust value lends that value itself.
    fn lend<R>(value: &Value<Self>, f: impl FnOnce(&Self::Rust) -> R) -> R {
        let copy = Self::from_lean(value.retain());
        f(&copy)
    }
}

/// A type whose values Lean may keep in a constant that every thread reads: one that is `Sync`.
///
/// The trait and the function below exist for their names, which are what rustc shows when a
/// type falls short: the type is not `Sync`, it has to be to implement this trait, and the
/// bound is that of a function named after the reason.
pub trait KeptByLeanForAllThreads {}

impl<T: Sync> KeptByLeanForAllThreads for T {}

/// States that `T` is the type of a value that a trusted function returns to Lean.
///
/// Lean computes a closed term once and keeps the result for all threads. A value of an opaque
/// or foreign type that a trusted function returns can be part of such a term, so the type must
/// be `Sync`. A value that only comes in through an argument of an exported function cannot be.
#[inline(always)]
pub fn returned_by_a_trusted_function<T: KeptByLeanForAllThreads>() {}

/// States that `T` is the type of a value that a trusted function gives to a Lean function it
/// was passed.
///
/// The Lean function can make the value part of what it returns, and that goes back into Lean
/// as it is. So the value can end up in a closed term as one that the trusted function returns
/// can, and the type must be `Sync` for the same reason.
#[inline(always)]
pub fn given_to_a_lean_function<T: KeptByLeanForAllThreads>() {}

macro_rules! scalars {
    ($($name:ident: $rust:ty as $repr:ty, |$value:ident| $to:expr, |$raw:ident| $from:expr;)*) => {$(
        #[doc = concat!("Lean's `", stringify!($name), "`.")]
        pub struct $name;

        impl Codec for $name {
            type Rust = $rust;
            type Repr = $repr;

            #[inline(always)]
            fn into_lean($value: $rust) -> Value<$name> {
                Value::from_scalar($to)
            }

            #[inline(always)]
            fn to_lean(value: &$rust) -> Value<$name> {
                Self::into_lean(*value)
            }

            #[inline(always)]
            fn from_lean(value: Value<$name>) -> $rust {
                let $raw = value.into_raw();
                $from
            }
        }
    )*};
}

// A signed integer is the unsigned one of its width in Lean's IR, with the same bits. A
// `Bool` is a byte, and a `Char` is a `u32` that Lean proved to be a Unicode scalar value.
scalars! {
    UInt8: u8 as u8, |v| v, |r| r;
    UInt16: u16 as u16, |v| v, |r| r;
    UInt32: u32 as u32, |v| v, |r| r;
    UInt64: u64 as u64, |v| v, |r| r;
    USize: usize as usize, |v| v, |r| r;
    Int8: i8 as u8, |v| v as u8, |r| r as i8;
    Int16: i16 as u16, |v| v as u16, |r| r as i16;
    Int32: i32 as u32, |v| v as u32, |r| r as i32;
    Int64: i64 as u64, |v| v as u64, |r| r as i64;
    ISize: isize as usize, |v| v as usize, |r| r as isize;
    Bool: bool as u8, |v| v as u8, |r| r != 0;
    Char: char as u32, |v| v as u32, |r| crate::char_of_u32(r);
    Float: f64 as f64, |v| v, |r| r;
    Float32: f32 as f32, |v| v, |r| r;
}

/// A value of a type that a declaration bound to Rust is generic in, as [`crate::Generic`]:
/// the Lean object, passed on as it is. `N` is the type's place among the declaration's
/// type parameters.
pub struct Generic<'a, const N: usize>(PhantomData<&'a ()>);

impl<'a, const N: usize> Codec for Generic<'a, N> {
    type Rust = crate::Generic<'a, N>;
    type Repr = Obj;

    #[inline]
    fn into_lean(value: crate::Generic<'a, N>) -> Value<Self> {
        unsafe { Value::from_raw(value.into_raw()) }
    }

    #[inline]
    fn to_lean(value: &crate::Generic<'a, N>) -> Value<Self> {
        Self::into_lean(value.clone())
    }

    #[inline]
    fn from_lean(value: Value<Self>) -> crate::Generic<'a, N> {
        unsafe { crate::Generic::from_raw(value.into_raw()) }
    }
}

/// Lean's `Unit`, where it is part of another type.
pub struct Unit;

impl Codec for Unit {
    type Rust = ();
    type Repr = Obj;

    fn into_lean(_value: ()) -> Value<Unit> {
        unsafe { Value::from_raw(box_(0)) }
    }

    fn to_lean(_value: &()) -> Value<Unit> {
        unsafe { Value::from_raw(box_(0)) }
    }

    fn from_lean(_value: Value<Unit>) {}
}

/// Lean's `Nat` as [`crate::Nat`], which is the Lean object itself where nothing else holds
/// the object, and a copy of it otherwise.
pub struct Nat;

impl Codec for Nat {
    type Rust = crate::Nat;
    type Repr = Obj;

    #[inline]
    fn into_lean(value: crate::Nat) -> Value<Nat> {
        unsafe { Value::from_raw(value.into_raw()) }
    }

    #[inline]
    fn to_lean(value: &crate::Nat) -> Value<Nat> {
        Self::into_lean(value.clone())
    }

    #[inline]
    fn from_lean(value: Value<Nat>) -> crate::Nat {
        unsafe { crate::Nat::owning(value.into_raw()) }
    }

    #[inline]
    fn lend<R>(value: &Value<Nat>, f: impl FnOnce(&crate::Nat) -> R) -> R {
        // A `Nat` is the object itself. This one does not own its reference.
        let nat = std::mem::ManuallyDrop::new(unsafe { crate::Nat::from_raw(value.as_raw()) });
        f(&nat)
    }
}

/// Lean's `Int` as [`crate::Int`], which is the Lean object itself where nothing else holds
/// the object, and a copy of it otherwise.
pub struct Int;

impl Codec for Int {
    type Rust = crate::Int;
    type Repr = Obj;

    #[inline]
    fn into_lean(value: crate::Int) -> Value<Int> {
        unsafe { Value::from_raw(value.into_raw()) }
    }

    #[inline]
    fn to_lean(value: &crate::Int) -> Value<Int> {
        Self::into_lean(value.clone())
    }

    #[inline]
    fn from_lean(value: Value<Int>) -> crate::Int {
        unsafe { crate::Int::owning(value.into_raw()) }
    }

    #[inline]
    fn lend<R>(value: &Value<Int>, f: impl FnOnce(&crate::Int) -> R) -> R {
        let int = std::mem::ManuallyDrop::new(unsafe { crate::Int::from_raw(value.as_raw()) });
        f(&int)
    }
}

/// Lean's `String`. The Lean object holds a Rust `String`, so a value moves both ways.
pub struct String;

impl Codec for String {
    type Rust = std::string::String;
    type Repr = Obj;

    fn into_lean(value: std::string::String) -> Value<String> {
        unsafe { Value::from_raw(crate::string::from_string(value)) }
    }

    fn to_lean(value: &std::string::String) -> Value<String> {
        unsafe { Value::from_raw(crate::string::mk_string(value)) }
    }

    fn from_lean(value: Value<String>) -> std::string::String {
        unsafe { crate::string::into_string(value.into_raw()) }
    }

    fn lend<R>(value: &Value<String>, f: impl FnOnce(&std::string::String) -> R) -> R {
        f(unsafe { crate::string::held_string(value.as_raw()) })
    }
}

/// Lean's `ByteArray`. The Lean object holds a `Vec<u8>`, so a value moves both ways.
pub struct ByteArray;

impl Codec for ByteArray {
    type Rust = Vec<u8>;
    type Repr = Obj;

    fn into_lean(value: Vec<u8>) -> Value<ByteArray> {
        unsafe { Value::from_raw(crate::sarray::byte_array_from_vec(value)) }
    }

    fn to_lean(value: &Vec<u8>) -> Value<ByteArray> {
        Self::into_lean(value.clone())
    }

    fn from_lean(value: Value<ByteArray>) -> Vec<u8> {
        unsafe { crate::sarray::byte_array_into_vec(value.into_raw()) }
    }

    fn lend<R>(value: &Value<ByteArray>, f: impl FnOnce(&Vec<u8>) -> R) -> R {
        f(unsafe { crate::sarray::held_bytes(value.as_raw()) })
    }
}

/// Lean's `FloatArray`. The Lean object holds a `Vec<f64>`, so a value moves both ways.
pub struct FloatArray;

impl Codec for FloatArray {
    type Rust = Vec<f64>;
    type Repr = Obj;

    fn into_lean(value: Vec<f64>) -> Value<FloatArray> {
        unsafe { Value::from_raw(crate::sarray::float_array_from_vec(value)) }
    }

    fn to_lean(value: &Vec<f64>) -> Value<FloatArray> {
        Self::into_lean(value.clone())
    }

    fn from_lean(value: Value<FloatArray>) -> Vec<f64> {
        unsafe { crate::sarray::float_array_into_vec(value.into_raw()) }
    }

    fn lend<R>(value: &Value<FloatArray>, f: impl FnOnce(&Vec<f64>) -> R) -> R {
        f(unsafe { crate::sarray::held_floats(value.as_raw()) })
    }
}

/// Objects whose references the holder owns and has not handed on yet. They are released
/// if a conversion panics before that, so that a failing conversion of the user's leaves
/// nothing behind.
struct Owned(Vec<Obj>);

impl Owned {
    fn into_vec(mut self) -> Vec<Obj> {
        std::mem::take(&mut self.0)
    }
}

impl Drop for Owned {
    fn drop(&mut self) {
        for &object in &self.0 {
            unsafe { dec(object) }
        }
    }
}

/// [`Owned`] for objects that are being handed on one by one.
struct Rest(std::vec::IntoIter<Obj>);

impl Drop for Rest {
    fn drop(&mut self) {
        for object in &mut self.0 {
            unsafe { dec(object) }
        }
    }
}

/// The fields of a constructor object whose reference the caller gives up. They are taken
/// when nothing else refers to the object, and shared with it otherwise: the rule Lean's
/// compiled code follows when it takes a value apart.
pub struct Fields {
    object: Obj,
    exclusive: bool,
}

impl Fields {
    /// # Safety
    /// `object` is a constructor object on the heap, and the caller owns a reference to it.
    /// Every object field must be read once with [`Fields::object`] before [`Fields::done`].
    #[inline(always)]
    pub unsafe fn of(object: Obj) -> Fields {
        Fields { object, exclusive: o::is_exclusive(object) }
    }

    /// Object field `i`, as a value of the Lean type `C` stands for.
    ///
    /// # Safety
    /// The field holds such a value.
    #[inline(always)]
    pub unsafe fn object<C: Codec>(&self, i: u32) -> Value<C> {
        let field = o::ctor_get(self.object, i);
        if self.exclusive {
            Value::take(field)
        } else {
            Value::share(field)
        }
    }

    /// Gives the object up.
    ///
    /// # Safety
    /// Every object field has been read once.
    #[inline(always)]
    pub unsafe fn done(self) {
        if self.exclusive {
            o::free_object(self.object)
        } else {
            dec_ref(self.object)
        }
    }
}

/// Lean's `Array α` as a `Vec`.
pub struct Array<C>(PhantomData<C>);

impl<C: Codec> Array<C> {
    /// The array of the values `items` yields.
    pub fn from_values(items: impl ExactSizeIterator<Item = Value<C>>) -> Value<Self> {
        let mut objects = Owned(Vec::with_capacity(items.len()));
        for item in items {
            objects.0.push(item.into_object());
        }
        unsafe { Value::from_raw(crate::array::from_vec(objects.into_vec())) }
    }
}

impl<C: Codec> Codec for Array<C> {
    type Rust = Vec<C::Rust>;
    type Repr = Obj;

    fn into_lean(value: Vec<C::Rust>) -> Value<Self> {
        Self::from_values(value.into_iter().map(C::into_lean))
    }

    fn to_lean(value: &Vec<C::Rust>) -> Value<Self> {
        Self::from_values(value.iter().map(C::to_lean))
    }

    fn from_lean(value: Value<Self>) -> Vec<C::Rust> {
        let object = value.into_raw();
        unsafe {
            if o::is_exclusive(object) {
                // The array is ours alone: its elements are taken, not copied.
                let mut rest = Rest(crate::array::into_vec(object).into_iter());
                let mut items = Vec::with_capacity(rest.0.len());
                while let Some(item) = rest.0.next() {
                    items.push(C::from_lean(Value::take(item)));
                }
                items
            } else {
                // Still referred to from elsewhere: gives up the reference only once the
                // elements are read, so that a panic on the way leaves the array intact.
                let _shared = Value::<Self>::from_raw(object);
                crate::array::elements(object).iter().map(|&item| C::from_lean(Value::share(item))).collect()
            }
        }
    }
}

/// Lean's `List α` as a `Vec`.
pub struct List<C>(PhantomData<C>);

impl<C: Codec> List<C> {
    /// The list of what `items` yields from its last item to its first.
    fn build(items: impl Iterator<Item = Obj>) -> Value<Self> {
        // A list is built from its end. Held as a value, the part built so far is released
        // if a conversion panics.
        let mut list: Value<Self> = unsafe { Value::from_raw(box_(0)) };
        for item in items {
            unsafe {
                // `List.cons head tail`.
                let cell = o::alloc_ctor(1, 2, 0, 0);
                o::ctor_set(cell, 0, item);
                o::ctor_set(cell, 1, list.into_raw());
                list = Value::from_raw(cell);
            }
        }
        list
    }
}

impl<C: Codec> Codec for List<C> {
    type Rust = Vec<C::Rust>;
    type Repr = Obj;

    fn into_lean(value: Vec<C::Rust>) -> Value<Self> {
        Self::build(value.into_iter().rev().map(|item| C::into_lean(item).into_object()))
    }

    fn to_lean(value: &Vec<C::Rust>) -> Value<Self> {
        Self::build(value.iter().rev().map(|item| C::to_lean(item).into_object()))
    }

    fn from_lean(value: Value<Self>) -> Vec<C::Rust> {
        let mut items = Vec::new();
        let mut rest = value;
        loop {
            let cell = rest.into_raw();
            if o::is_scalar(cell) {
                return items;
            }
            unsafe {
                let fields = Fields::of(cell);
                let head = fields.object::<C>(0);
                let tail = fields.object::<Self>(1);
                fields.done();
                rest = tail;
                items.push(C::from_lean(head));
            }
        }
    }
}

/// Lean's `Option α`.
pub struct Option<C>(PhantomData<C>);

impl<C: Codec> Option<C> {
    fn some(field: Value<C>) -> Value<Self> {
        unsafe {
            let some = o::alloc_ctor(1, 1, 0, 0);
            o::ctor_set(some, 0, field.into_object());
            Value::from_raw(some)
        }
    }
}

impl<C: Codec> Codec for Option<C> {
    type Rust = core::option::Option<C::Rust>;
    type Repr = Obj;

    fn into_lean(value: Self::Rust) -> Value<Self> {
        match value {
            None => unsafe { Value::from_raw(box_(0)) },
            Some(value) => Self::some(C::into_lean(value)),
        }
    }

    fn to_lean(value: &Self::Rust) -> Value<Self> {
        match value {
            None => unsafe { Value::from_raw(box_(0)) },
            Some(value) => Self::some(C::to_lean(value)),
        }
    }

    fn from_lean(value: Value<Self>) -> Self::Rust {
        let object = value.into_raw();
        if o::is_scalar(object) {
            return None;
        }
        unsafe {
            let fields = Fields::of(object);
            let field = fields.object::<C>(0);
            fields.done();
            Some(C::from_lean(field))
        }
    }
}

/// Lean's `α × β` as a pair.
pub struct Prod<A, B>(PhantomData<(A, B)>);

impl<A: Codec, B: Codec> Prod<A, B> {
    fn pair(first: Value<A>, second: Value<B>) -> Value<Self> {
        unsafe {
            let pair = o::alloc_ctor(0, 2, 0, 0);
            o::ctor_set(pair, 0, first.into_object());
            o::ctor_set(pair, 1, second.into_object());
            Value::from_raw(pair)
        }
    }

    /// The Lean pair of two values held separately, as the entries of a Rust map are.
    pub fn from_refs(first: &A::Rust, second: &B::Rust) -> Value<Self> {
        Self::pair(A::to_lean(first), B::to_lean(second))
    }
}

impl<A: Codec, B: Codec> Codec for Prod<A, B> {
    type Rust = (A::Rust, B::Rust);
    type Repr = Obj;

    fn into_lean(value: Self::Rust) -> Value<Self> {
        let first = A::into_lean(value.0);
        Self::pair(first, B::into_lean(value.1))
    }

    fn to_lean(value: &Self::Rust) -> Value<Self> {
        Self::from_refs(&value.0, &value.1)
    }

    fn from_lean(value: Value<Self>) -> Self::Rust {
        unsafe {
            let fields = Fields::of(value.into_raw());
            let (first, second) = (fields.object::<A>(0), fields.object::<B>(1));
            fields.done();
            let first = A::from_lean(first);
            (first, B::from_lean(second))
        }
    }
}

/// Lean's `Except ε α` as a `Result`. Lean names the error type first, Rust the value type.
pub struct Except<E, A>(PhantomData<(E, A)>);

impl<E: Codec, A: Codec> Except<E, A> {
    /// `Except.error` is constructor 0 and `Except.ok` constructor 1, each with one field.
    fn with(tag: u32, field: Obj) -> Value<Self> {
        unsafe {
            let object = o::alloc_ctor(tag, 1, 0, 0);
            o::ctor_set(object, 0, field);
            Value::from_raw(object)
        }
    }
}

impl<E: Codec, A: Codec> Codec for Except<E, A> {
    type Rust = Result<A::Rust, E::Rust>;
    type Repr = Obj;

    fn into_lean(value: Self::Rust) -> Value<Self> {
        match value {
            Err(error) => Self::with(0, E::into_lean(error).into_object()),
            Ok(value) => Self::with(1, A::into_lean(value).into_object()),
        }
    }

    fn to_lean(value: &Self::Rust) -> Value<Self> {
        match value {
            Err(error) => Self::with(0, E::to_lean(error).into_object()),
            Ok(value) => Self::with(1, A::to_lean(value).into_object()),
        }
    }

    fn from_lean(value: Value<Self>) -> Self::Rust {
        let object = value.into_raw();
        unsafe {
            let ok = o::obj_tag(object) == 1;
            let fields = Fields::of(object);
            if ok {
                let field = fields.object::<A>(0);
                fields.done();
                Ok(A::from_lean(field))
            } else {
                let field = fields.object::<E>(0);
                fields.done();
                Err(E::from_lean(field))
            }
        }
    }
}

/// A value that the Rust type keeps in a `Box`, as recursive types must.
pub struct Boxed<C>(PhantomData<C>);

impl<C: Codec> Codec for Boxed<C> {
    type Rust = Box<C::Rust>;
    type Repr = C::Repr;

    fn into_lean(value: Self::Rust) -> Value<Self> {
        unsafe { C::into_lean(*value).cast() }
    }

    fn to_lean(value: &Self::Rust) -> Value<Self> {
        unsafe { C::to_lean(value).cast() }
    }

    fn from_lean(value: Value<Self>) -> Self::Rust {
        Box::new(C::from_lean(unsafe { value.cast() }))
    }
}

/// A type the block declares `opaque`. Lean cannot look inside a value of it or make one, so
/// nothing is converted: the value is the Rust value itself, in an object. It moves into Lean
/// and moves back out. A value the caller keeps is cloned, and so is one that Lean still
/// holds somewhere else when it comes out, which is why the type must be `Clone`.
pub struct Opaque<T>(PhantomData<T>);

impl<T: Clone + 'static> Codec for Opaque<T> {
    type Rust = T;
    type Repr = Obj;

    fn into_lean(value: T) -> Value<Self> {
        unsafe { Value::from_raw(o::hold_external(value)) }
    }

    fn to_lean(value: &T) -> Value<Self> {
        Self::into_lean(value.clone())
    }

    unsafe fn lent(value: &T) -> Value<Self> {
        Value::from_raw(o::lend_external(value))
    }

    fn from_lean(value: Value<Self>) -> T {
        unsafe {
            // A value that is only lent to the object is not the object's to give.
            if o::is_exclusive(value.as_raw()) && !o::is_lent(value.as_raw()) {
                o::take_external(value.into_raw())
            } else {
                // The reference is given up when `value` goes out of scope, also if the
                // clone panics.
                o::external::<T>(value.as_raw()).clone()
            }
        }
    }

    fn lend<R>(value: &Value<Self>, f: impl FnOnce(&T) -> R) -> R {
        f(unsafe { o::external::<T>(value.as_raw()) })
    }
}

/// `limbs` padded with zeros to `N` limbs, or `None` when there are more.
pub(crate) fn fixed_limbs<const N: usize>(limbs: &[u64]) -> core::option::Option<[u64; N]> {
    let mut out = [0u64; N];
    out.get_mut(..limbs.len())?.copy_from_slice(limbs);
    Some(out)
}

/// A Rust type that holds exactly the values of a `BitVec w`: an unsigned integer of `w`
/// bits, or `w / 64` limbs with the least significant first.
pub trait Word: Copy {
    #[doc(hidden)]
    fn to_nat(self) -> Obj;

    /// # Safety
    /// `nat` must be a `Nat` of this runtime that is below 2^w.
    #[doc(hidden)]
    unsafe fn of_nat(nat: Obj) -> Self;
}

macro_rules! words {
    ($($ty:ty),*) => {$(
        impl Word for $ty {
            fn to_nat(self) -> Obj {
                crate::nat::uint64_to_nat(self as u64)
            }

            unsafe fn of_nat(nat: Obj) -> $ty {
                crate::nat::with_limbs(nat, |limbs| limbs.first().copied().unwrap_or(0)) as $ty
            }
        }
    )*};
}

words!(u8, u16, u32, u64);

impl Word for u128 {
    fn to_nat(self) -> Obj {
        crate::nat::of_u128(self)
    }

    unsafe fn of_nat(nat: Obj) -> u128 {
        let [low, high] = <[u64; 2]>::of_nat(nat);
        (high as u128) << 64 | low as u128
    }
}

impl<const N: usize> Word for [u64; N] {
    fn to_nat(self) -> Obj {
        crate::nat::of_limbs(&self)
    }

    unsafe fn of_nat(nat: Obj) -> [u64; N] {
        match crate::nat::with_limbs(nat, fixed_limbs) {
            Some(limbs) => limbs,
            None => panic!("inlean: Lean returned a BitVec wider than its type"),
        }
    }
}

/// Lean's `BitVec w` as the unsigned integer or the limbs `W`. Lean keeps a bit vector as the
/// natural number it encodes, so a value crosses with one copy of its limbs, and one that is
/// below 2^63 without an allocation.
pub struct BitVec<W>(PhantomData<W>);

impl<W: Word> Codec for BitVec<W> {
    type Rust = W;
    type Repr = Obj;

    fn into_lean(value: W) -> Value<Self> {
        unsafe { Value::from_raw(value.to_nat()) }
    }

    fn to_lean(value: &W) -> Value<Self> {
        Self::into_lean(*value)
    }

    fn from_lean(value: Value<Self>) -> W {
        // The number is released when `value` goes out of scope.
        unsafe { W::of_nat(value.as_raw()) }
    }
}

/// A primitive type of your own: a Rust type of your choice in place of the one inlean gives
/// a Lean type.
///
/// Signatures and generated types then use [`Primitive::Rust`], with no conversion left to
/// the caller. The trait is implemented for a marker type, so the Rust type can come from any
/// crate. To have a 256-bit integer of a library stand for `BitVec 256`:
///
/// ```
/// # #[derive(Clone, Copy)] pub struct U256([u64; 4]);
/// pub struct U256Primitive;
///
/// impl inlean_runtime::Primitive for U256Primitive {
///     type Lean = [u64; 4]; // what inlean uses for `BitVec 256`
///     type Rust = U256;
///
///     fn to_lean(value: &U256) -> [u64; 4] {
///         value.0
///     }
///
///     fn from_lean(limbs: [u64; 4]) -> U256 {
///         U256(limbs)
///     }
/// }
/// ```
///
/// and name the marker in `Cargo.toml`, by a path that starts with `crate::` or `::`:
///
/// ```toml
/// [package.metadata.inlean.types]
/// "BitVec 256" = "crate::U256Primitive"
/// ```
///
/// Both functions must be total, and a value that goes to Lean and comes back must be the
/// same value: a function written in Lean is proved for every value of its Lean types, and
/// that is only worth something if every Rust value is one of them.
pub trait Primitive {
    /// The Rust type inlean gives the Lean type by default.
    type Lean;
    /// The type to use instead.
    type Rust;

    /// The default type's value of a value that stays with the caller.
    fn to_lean(value: &Self::Rust) -> Self::Lean;

    /// The default type's value of a value that is given up. Implement it when the value
    /// owns something that can move into the result, such as a buffer; the default copies.
    fn into_lean(value: Self::Rust) -> Self::Lean {
        Self::to_lean(&value)
    }

    fn from_lean(value: Self::Lean) -> Self::Rust;
}

/// The Lean type of codec `C` as the Rust type the primitive `P` chose.
pub struct Via<C, P>(PhantomData<(C, P)>);

impl<C: Codec, P: Primitive<Lean = C::Rust>> Codec for Via<C, P> {
    type Rust = P::Rust;
    type Repr = C::Repr;

    fn into_lean(value: P::Rust) -> Value<Self> {
        unsafe { C::into_lean(P::into_lean(value)).cast() }
    }

    fn to_lean(value: &P::Rust) -> Value<Self> {
        // The default type's value is ours, so it moves into Lean.
        unsafe { C::into_lean(P::to_lean(value)).cast() }
    }

    fn from_lean(value: Value<Self>) -> P::Rust {
        P::from_lean(C::from_lean(unsafe { value.cast() }))
    }
}

/// An argument of type `T` for a function written in Lean: the value itself, which moves
/// into Lean, or a reference to it. A reference to a value that Lean converts, such as a
/// `String`, is copied. A reference to a value that Lean holds as it is, of an opaque or a
/// foreign type or a collection of `import Inlean`, is lent for the call: Lean reads the
/// caller's value, and clones it only where it needs one of its own.
///
/// A value may also come in what holds it: a `Box`, a reference to a `Box`, an `Rc` or an
/// `Arc`, or a `Cow`. A `String` also takes a `&str`, and a `Vec<T>` a slice or an array of
/// `T`.
///
/// ```
/// # fn shout(text: impl inlean_runtime::Pass<String>) {}
/// let name = String::from("ada");
/// shout(&name);  // copied: a `String` is converted
/// shout("ada");  // copied
/// shout(name);   // moved: Lean's string is this buffer
/// ```
pub trait Pass<T>: Sized {
    /// The Lean value of the argument under the codec the function names.
    #[doc(hidden)]
    fn pass<C: Codec<Rust = T>>(self) -> Value<C>;

    /// The same for an exported function, which holds the argument for as long as Lean runs.
    /// A reference is then lent where the codec can lend: the Lean value stands for what the
    /// reference points at, and nothing is copied until Lean needs a value of its own.
    ///
    /// # Safety
    /// The value returned, and every reference Lean takes to it, is given up before the
    /// argument's borrow ends.
    #[doc(hidden)]
    #[inline]
    unsafe fn lend<C: Codec<Rust = T>>(self) -> Value<C> {
        self.pass()
    }
}

impl<T> Pass<T> for T {
    #[inline]
    fn pass<C: Codec<Rust = T>>(self) -> Value<C> {
        C::into_lean(self)
    }
}

impl<T> Pass<T> for &T {
    #[inline]
    fn pass<C: Codec<Rust = T>>(self) -> Value<C> {
        C::to_lean(self)
    }

    #[inline]
    unsafe fn lend<C: Codec<Rust = T>>(self) -> Value<C> {
        C::lent(self)
    }
}

impl Pass<std::string::String> for &str {
    #[inline]
    fn pass<C: Codec<Rust = std::string::String>>(self) -> Value<C> {
        C::into_lean(self.to_owned())
    }
}

impl<T: Clone> Pass<Vec<T>> for &[T] {
    #[inline]
    fn pass<C: Codec<Rust = Vec<T>>>(self) -> Value<C> {
        C::into_lean(self.to_vec())
    }
}

impl<T: Clone, const N: usize> Pass<Vec<T>> for &[T; N] {
    #[inline]
    fn pass<C: Codec<Rust = Vec<T>>>(self) -> Value<C> {
        C::into_lean(self.to_vec())
    }
}

impl<T, const N: usize> Pass<Vec<T>> for [T; N] {
    #[inline]
    fn pass<C: Codec<Rust = Vec<T>>>(self) -> Value<C> {
        C::into_lean(Vec::from(self))
    }
}

impl<T> Pass<T> for Box<T> {
    #[inline]
    fn pass<C: Codec<Rust = T>>(self) -> Value<C> {
        C::into_lean(*self)
    }
}

impl<T> Pass<T> for &Box<T> {
    #[inline]
    fn pass<C: Codec<Rust = T>>(self) -> Value<C> {
        C::to_lean(self)
    }

    #[inline]
    unsafe fn lend<C: Codec<Rust = T>>(self) -> Value<C> {
        C::lent(self)
    }
}

impl<T> Pass<T> for &std::rc::Rc<T> {
    #[inline]
    fn pass<C: Codec<Rust = T>>(self) -> Value<C> {
        C::to_lean(self)
    }

    #[inline]
    unsafe fn lend<C: Codec<Rust = T>>(self) -> Value<C> {
        C::lent(self)
    }
}

impl<T> Pass<T> for &std::sync::Arc<T> {
    #[inline]
    fn pass<C: Codec<Rust = T>>(self) -> Value<C> {
        C::to_lean(self)
    }

    #[inline]
    unsafe fn lend<C: Codec<Rust = T>>(self) -> Value<C> {
        C::lent(self)
    }
}

impl<T: Clone> Pass<T> for std::borrow::Cow<'_, T> {
    #[inline]
    fn pass<C: Codec<Rust = T>>(self) -> Value<C> {
        C::into_lean(self.into_owned())
    }
}

impl Pass<std::string::String> for std::borrow::Cow<'_, str> {
    #[inline]
    fn pass<C: Codec<Rust = std::string::String>>(self) -> Value<C> {
        C::into_lean(self.into_owned())
    }
}

impl<T: Clone> Pass<Vec<T>> for std::borrow::Cow<'_, [T]> {
    #[inline]
    fn pass<C: Codec<Rust = Vec<T>>>(self) -> Value<C> {
        C::into_lean(self.into_owned())
    }
}