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
use std::borrow::Borrow;
use std::fmt::Debug;
use std::rc::Rc;
use std::string::String;

use klvm_rs::allocator::{Allocator, NodePtr, SExp};
use klvm_rs::reduction::EvalErr;

use bls12_381::G1Affine;

use crate::classic::klvm::__type_compatibility__::{Bytes, BytesFromType, Stream};
use crate::classic::klvm::serialize::sexp_to_stream;
use crate::util::{u8_from_number, Number};

#[derive(Debug)]
pub enum CastableType {
    KLVMObject(NodePtr),
    Bytes(Bytes),
    String(String),
    Number(Number),
    G1Affine(G1Affine),
    ListOf(usize, Vec<Rc<CastableType>>),
    TupleOf(Rc<CastableType>, Rc<CastableType>),
}

#[derive(Debug)]
pub enum SexpStackOp {
    OpConvert,
    OpSetPair(bool, usize),
    OpPrepend(usize),
}

pub fn to_sexp_type(allocator: &mut Allocator, value: CastableType) -> Result<NodePtr, EvalErr> {
    let mut stack = vec![Rc::new(value)];
    let mut ops: Vec<SexpStackOp> = vec![SexpStackOp::OpConvert];

    loop {
        let op = match ops.pop() {
            None => {
                break;
            }
            Some(o) => o,
        };

        let top = match stack.pop() {
            None => {
                return Err(EvalErr(allocator.null(), "empty value stack".to_string()));
            }
            Some(rc) => rc,
        };

        // convert value
        match op {
            SexpStackOp::OpConvert => {
                match top.borrow() {
                    CastableType::KLVMObject(_) => {
                        stack.push(top.clone());
                    }
                    CastableType::TupleOf(left, right) => {
                        let target_index = stack.len();
                        match allocator.new_pair(allocator.null(), allocator.null()) {
                            Ok(pair) => {
                                stack.push(Rc::new(CastableType::KLVMObject(pair)));
                            }
                            Err(e) => {
                                return Err(e);
                            }
                        };
                        stack.push(right.clone());
                        ops.push(SexpStackOp::OpSetPair(true, target_index)); // set right
                        ops.push(SexpStackOp::OpConvert); // convert

                        stack.push(left.clone());
                        ops.push(SexpStackOp::OpSetPair(false, target_index));
                        ops.push(SexpStackOp::OpConvert);
                    }
                    CastableType::ListOf(_sel, v) => {
                        let target_index = stack.len();
                        stack.push(Rc::new(CastableType::KLVMObject(allocator.null())));
                        for vi in v.iter().take(v.len() - 1) {
                            stack.push(vi.clone());
                            ops.push(SexpStackOp::OpPrepend(target_index));
                            // we only need to convert if it's not already the right type
                            ops.push(SexpStackOp::OpConvert);
                        }
                    }
                    CastableType::Bytes(b) => match allocator.new_atom(b.data()) {
                        Ok(a) => {
                            stack.push(Rc::new(CastableType::KLVMObject(a)));
                        }
                        Err(e) => {
                            return Err(e);
                        }
                    },
                    CastableType::String(s) => {
                        match allocator.new_atom(s.as_bytes()) {
                            Ok(a) => {
                                stack.push(Rc::new(CastableType::KLVMObject(a)));
                            }
                            Err(e) => {
                                return Err(e);
                            }
                        };
                    }
                    CastableType::Number(n) => {
                        match allocator.new_atom(&u8_from_number(n.clone())) {
                            Ok(a) => {
                                stack.push(Rc::new(CastableType::KLVMObject(a)));
                            }
                            Err(e) => {
                                return Err(e);
                            }
                        }
                    }
                    CastableType::G1Affine(g) => {
                        let bytes_ver = Bytes::new(Some(BytesFromType::G1Element(*g)));

                        match allocator.new_atom(bytes_ver.data()) {
                            Ok(a) => {
                                stack.push(Rc::new(CastableType::KLVMObject(a)));
                            }
                            Err(e) => {
                                return Err(e);
                            }
                        }
                    }
                }
            }
            SexpStackOp::OpSetPair(toset, target) => match top.borrow() {
                CastableType::KLVMObject(new_value) => match stack[target].borrow() {
                    CastableType::KLVMObject(target_value) => match allocator.sexp(*target_value) {
                        SExp::Pair(l, r) => {
                            if toset {
                                match allocator.new_pair(l, *new_value) {
                                    Ok(pair) => {
                                        stack[target] = Rc::new(CastableType::KLVMObject(pair));
                                    }
                                    Err(e) => {
                                        return Err(e);
                                    }
                                }
                            } else {
                                match allocator.new_pair(*new_value, r) {
                                    Ok(pair) => {
                                        stack[target] = Rc::new(CastableType::KLVMObject(pair));
                                    }
                                    Err(e) => {
                                        return Err(e);
                                    }
                                }
                            }
                        }
                        SExp::Atom => {
                            return Err(EvalErr(
                                *target_value,
                                "attempt to set_pair in atom".to_string(),
                            ));
                        }
                    },
                    _ => {
                        return Err(EvalErr(
                            allocator.null(),
                            format!("Setting wing of non pair {:?}", stack[target]),
                        ));
                    }
                },
                _ => {
                    return Err(EvalErr(
                        allocator.null(),
                        format!("op_set_pair on atom item {target:?} in vec {stack:?} ops {ops:?}"),
                    ));
                }
            },

            SexpStackOp::OpPrepend(target) => match top.borrow() {
                CastableType::KLVMObject(f) => match stack[target].borrow() {
                    CastableType::KLVMObject(o) => match allocator.new_pair(*f, *o) {
                        Ok(pair) => {
                            stack[target] = Rc::new(CastableType::KLVMObject(pair));
                        }
                        Err(e) => {
                            return Err(e);
                        }
                    },
                    _ => {
                        return Err(EvalErr(
                            allocator.null(),
                            format!("unrealized pair prepended {:?}", stack[target]),
                        ));
                    }
                },
                _ => {
                    return Err(EvalErr(
                        allocator.null(),
                        format!("unrealized prepend {top:?}"),
                    ));
                }
            },
        }
    }

    if stack.len() != 1 {
        return Err(EvalErr(
            allocator.null(),
            format!("too many values left on op stack {stack:?}"),
        ));
    }

    return match stack.pop() {
        None => Err(EvalErr(allocator.null(), "stack empty".to_string())),
        Some(top) => match top.borrow() {
            CastableType::KLVMObject(o) => Ok(*o),
            _ => Err(EvalErr(
                allocator.null(),
                format!("unimplemented {:?}", stack[0]),
            )),
        },
    };
}

pub fn sexp_as_bin(allocator: &mut Allocator, sexp: NodePtr) -> Bytes {
    let mut f = Stream::new(None);
    sexp_to_stream(allocator, sexp, &mut f);
    f.get_value()
}

pub fn bool_sexp(allocator: &Allocator, b: bool) -> NodePtr {
    if b {
        allocator.one()
    } else {
        allocator.null()
    }
}

// export class SExp implements KLVMType {
//   atom: Optional<Bytes> = None;
//   // this is always a 2-tuple of an object implementing the KLVM object protocol.
//   pair: Optional<Tuple<any, any>> = None;

//   static readonly TRUE: SExp = new SExp(new KLVMObject(Bytes.from("0x01", "hex")));
//   static readonly FALSE: SExp = new SExp(new KLVMObject(Bytes.NULL));
//   static readonly __NULL__: SExp = new SExp(new KLVMObject(Bytes.NULL));

//   static to(v: CastableType): SExp {
//     if(isSExp(v)){
//       return v;
//     }

//     if(looks_like_klvm_object(v)){
//       return new SExp(v);
//     }

//     // this will lazily convert elements
//     return new SExp(to_sexp_type(v));
//   }

//   static null(){
//     return SExp.__NULL__;
//   }

//   public as_pair(): Tuple<SExp, SExp>|None {
//     const pair = this.pair;
//     if(pair === None){
//       return pair;
//     }
//     return t(new SExp(pair[0]), new SExp(pair[1]));
//   }

//   public as_int(){
//     return int_from_bytes(this.atom, {signed: true});
//   }

//   public as_bigint(){
//     return bigint_from_bytes(this.atom, {signed: true});
//   }

//   public *as_iter(){
//     let v: SExp = this;
//     while(!v.nullp()){
//       yield v.first();
//       v = v.rest();
//     }
//   }

//   public equal_to(other: any/* CastableType */): boolean {
//     try{
//       other = SExp.to(other);
//       const to_compare_stack = [t(this, other)] as Array<Tuple<SExp, SExp>>;
//       while(to_compare_stack.length){
//         const [s1, s2] = (to_compare_stack.pop() as Tuple<SExp, SExp>);
//         const p1 = s1.as_pair();
//         if(p1){
//           const p2 = s2.as_pair();
//           if(p2){
//             to_compare_stack.push(t(p1[0], p2[0]));
//             to_compare_stack.push(t(p1[1], p2[1]));
//           }
//           else{
//             return false;
//           }
//         }
//         else if(s2.as_pair() || !(s1.atom && s2.atom && s1.atom.equal_to(s2.atom))){
//           return false;
//         }
//       }
//       return true;
//     }
//     catch(e){
//       return false;
//     }
//   }

//   public as_javascript(){
//     return as_javascript(this);
//   }

//   public toString(){
//     return this.as_bin().hex();
//   }

//   public __repr__(){
//     return `SExp(${this.as_bin().hex()})`;
//   }
// }

// export function isSExp(v: any): v is SExp {
//   return v && typeof v.atom !== "undefined"
//     && typeof v.pair !== "undefined"
//     && typeof v.first === "function"
//     && typeof v.rest === "function"
//     && typeof v.cons === "function"
//   ;
// }

pub fn non_nil(allocator: &Allocator, sexp: NodePtr) -> bool {
    match allocator.sexp(sexp) {
        SExp::Pair(_, _) => true,
        // sexp is the only node in scope, was !is_empty
        SExp::Atom => allocator.atom_len(sexp) != 0,
    }
}

pub fn first(allocator: &Allocator, sexp: NodePtr) -> Result<NodePtr, EvalErr> {
    match allocator.sexp(sexp) {
        SExp::Pair(f, _) => Ok(f),
        _ => Err(EvalErr(sexp, "first of non-cons".to_string())),
    }
}

pub fn rest(allocator: &Allocator, sexp: NodePtr) -> Result<NodePtr, EvalErr> {
    match allocator.sexp(sexp) {
        SExp::Pair(_, r) => Ok(r),
        _ => Err(EvalErr(sexp, "rest of non-cons".to_string())),
    }
}

pub fn atom(allocator: &Allocator, sexp: NodePtr) -> Result<Vec<u8>, EvalErr> {
    match allocator.sexp(sexp) {
        SExp::Atom => Ok(allocator.atom(sexp).to_vec()), // only sexp in scope
        _ => Err(EvalErr(sexp, "not an atom".to_string())),
    }
}

pub fn proper_list(allocator: &Allocator, sexp: NodePtr, store: bool) -> Option<Vec<NodePtr>> {
    let mut args = vec![];
    let mut args_sexp = sexp;
    loop {
        match allocator.sexp(args_sexp) {
            SExp::Atom => {
                if !non_nil(allocator, args_sexp) {
                    return Some(args);
                } else {
                    return None;
                }
            }
            SExp::Pair(f, r) => {
                if store {
                    args.push(f);
                }
                args_sexp = r;
            }
        }
    }
}

pub fn enlist(allocator: &mut Allocator, vec: &[NodePtr]) -> Result<NodePtr, EvalErr> {
    let mut built = allocator.null();

    for i_reverse in 0..vec.len() {
        let i = vec.len() - i_reverse - 1;
        match allocator.new_pair(vec[i], built) {
            Err(e) => return Err(e),
            Ok(v) => {
                built = v;
            }
        }
    }
    Ok(built)
}

pub fn map_m<T>(
    allocator: &mut Allocator,
    iter: &mut impl Iterator<Item = T>,
    f: &dyn Fn(&mut Allocator, T) -> Result<NodePtr, EvalErr>,
) -> Result<Vec<NodePtr>, EvalErr> {
    let mut result = Vec::new();
    loop {
        match iter.next() {
            None => {
                return Ok(result);
            }
            Some(v) => match f(allocator, v) {
                Err(e) => {
                    return Err(e);
                }
                Ok(v) => {
                    result.push(v);
                }
            },
        }
    }
}

pub fn fold_m<A, B, E>(
    allocator: &mut Allocator,
    f: &dyn Fn(&mut Allocator, A, B) -> Result<A, E>,
    start_: A,
    iter: &mut impl Iterator<Item = B>,
) -> Result<A, E> {
    let mut start = start_;
    loop {
        match iter.next() {
            None => {
                return Ok(start);
            }
            Some(v) => match f(allocator, start, v) {
                Err(e) => {
                    return Err(e);
                }
                Ok(v) => {
                    start = v;
                }
            },
        }
    }
}

pub fn equal_to(allocator: &mut Allocator, first_: NodePtr, second_: NodePtr) -> bool {
    let mut first = first_;
    let mut second = second_;

    loop {
        if first == second {
            return true;
        }
        match (allocator.sexp(first), allocator.sexp(second)) {
            (SExp::Atom, SExp::Atom) => {
                // two atoms in scope, both are used
                return allocator.atom(first) == allocator.atom(second);
            }
            (SExp::Pair(ff, fr), SExp::Pair(rf, rr)) => {
                if !equal_to(allocator, ff, rf) {
                    return false;
                }
                first = fr;
                second = rr;
            }
            _ => {
                return false;
            }
        }
    }
}

pub fn flatten(allocator: &mut Allocator, tree_: NodePtr, res: &mut Vec<NodePtr>) {
    let mut tree = tree_;

    loop {
        match allocator.sexp(tree) {
            SExp::Atom => {
                if non_nil(allocator, tree) {
                    res.push(tree);
                }
                return;
            }
            SExp::Pair(l, r) => {
                flatten(allocator, l, res);
                tree = r;
            }
        }
    }
}

// Wrapper around last that properly bubbles the error into EvalErr for use in
// the classic chiklisp code.
pub fn nonempty_last<X>(nil: NodePtr, lst: &[X]) -> Result<X, EvalErr>
where
    X: Copy,
{
    lst.last()
        .copied()
        .ok_or_else(|| EvalErr(nil, "alist is empty and shouldn't be".to_string()))
}

// This is a trait that generates a haskell-like ad-hoc type from the user's
// construction of NodeSel and ThisNode.
// the result is transformed into a NodeSel tree of NodePtr if it can be.
// The type of the result is an ad-hoc shape derived from the shape of the
// original request.
#[derive(Debug, Clone)]
pub enum NodeSel<T, U> {
    Cons(T, U),
}

#[derive(Debug, Clone)]
pub enum First<T> {
    Here(T),
}

#[derive(Debug, Clone)]
pub enum Rest<T> {
    Here(T),
}

#[derive(Debug, Clone)]
pub enum ThisNode {
    Here,
}

pub trait SelectNode<T, E> {
    fn select_nodes(&self, allocator: &mut Allocator, n: NodePtr) -> Result<T, E>;
}

impl<E> SelectNode<NodePtr, E> for ThisNode {
    fn select_nodes(&self, _allocator: &mut Allocator, n: NodePtr) -> Result<NodePtr, E> {
        Ok(n)
    }
}

impl<E> SelectNode<(), E> for () {
    fn select_nodes(&self, _allocator: &mut Allocator, _n: NodePtr) -> Result<(), E> {
        Ok(())
    }
}

impl<R, T, E> SelectNode<First<T>, E> for First<R>
where
    R: SelectNode<T, E> + Clone,
    E: From<EvalErr>,
{
    fn select_nodes(&self, allocator: &mut Allocator, n: NodePtr) -> Result<First<T>, E> {
        let First::Here(f) = &self;
        let NodeSel::Cons(first, ()) = NodeSel::Cons(f.clone(), ()).select_nodes(allocator, n)?;
        Ok(First::Here(first))
    }
}

impl<R, T, E> SelectNode<Rest<T>, E> for Rest<R>
where
    R: SelectNode<T, E> + Clone,
    E: From<EvalErr>,
{
    fn select_nodes(&self, allocator: &mut Allocator, n: NodePtr) -> Result<Rest<T>, E> {
        let Rest::Here(f) = &self;
        let NodeSel::Cons((), rest) = NodeSel::Cons((), f.clone()).select_nodes(allocator, n)?;
        Ok(Rest::Here(rest))
    }
}

impl<R, S, T, U, E> SelectNode<NodeSel<T, U>, E> for NodeSel<R, S>
where
    R: SelectNode<T, E>,
    S: SelectNode<U, E>,
    E: From<EvalErr>,
{
    fn select_nodes(&self, allocator: &mut Allocator, n: NodePtr) -> Result<NodeSel<T, U>, E> {
        let NodeSel::Cons(my_left, my_right) = &self;
        let l = first(allocator, n)?;
        let r = rest(allocator, n)?;
        let first = my_left.select_nodes(allocator, l)?;
        let rest = my_right.select_nodes(allocator, r)?;
        Ok(NodeSel::Cons(first, rest))
    }
}