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
use r_derive::*;

use super::core::*;
use crate::context::Context;
use crate::error::Error;
use crate::lang::{CallStack, EvalResult};
use crate::object::types::*;
use crate::object::*;

#[derive(Debug, Clone, PartialEq)]
#[builtin(sym = "<-", kind = Infix)]
pub struct InfixAssign;
impl CallableFormals for InfixAssign {}
impl Callable for InfixAssign {
    fn call(&self, args: ExprList, stack: &mut CallStack) -> EvalResult {
        let (lhs, rhs) = args.unnamed_binary_args();
        stack.assign_lazy(lhs, rhs)
    }
}

#[derive(Debug, Clone, PartialEq)]
#[builtin(sym = "+", kind = Infix)]
pub struct InfixAdd;
impl CallableFormals for InfixAdd {}
impl Callable for InfixAdd {
    fn call(&self, args: ExprList, stack: &mut CallStack) -> EvalResult {
        let (lhs, rhs) = stack.eval_binary(args.unnamed_binary_args())?;
        lhs + rhs
    }
}

#[derive(Debug, Clone, PartialEq)]
#[builtin(sym = "-", kind = Infix)]
pub struct InfixSub;
impl CallableFormals for InfixSub {}
impl Callable for InfixSub {
    fn call(&self, args: ExprList, stack: &mut CallStack) -> EvalResult {
        let (lhs, rhs) = stack.eval_binary(args.unnamed_binary_args())?;
        lhs - rhs
    }
}

#[derive(Debug, Clone, PartialEq)]
#[builtin(sym = "-", kind = Prefix)]
pub struct PrefixSub;
impl CallableFormals for PrefixSub {}
impl Callable for PrefixSub {
    fn call(&self, args: ExprList, stack: &mut CallStack) -> EvalResult {
        let what = stack.eval(args.unnamed_unary_arg())?;
        -what
    }
}

#[derive(Debug, Clone, PartialEq)]
#[builtin(sym = "!", kind = Prefix)]
pub struct PrefixNot;
impl CallableFormals for PrefixNot {}
impl Callable for PrefixNot {
    fn call(&self, args: ExprList, stack: &mut CallStack) -> EvalResult {
        let what = stack.eval(args.unnamed_unary_arg())?;
        !what
    }
}

#[derive(Debug, Clone, PartialEq)]
#[builtin(sym = "..", kind = Prefix)]
pub struct PrefixPack;
impl CallableFormals for PrefixPack {}
impl Callable for PrefixPack {
    fn call(&self, _args: ExprList, _stack: &mut CallStack) -> EvalResult {
        Error::IncorrectContext("..".to_string()).into()
    }
}

#[derive(Debug, Clone, PartialEq)]
#[builtin(sym = "*", kind = Infix)]
pub struct InfixMul;
impl CallableFormals for InfixMul {}
impl Callable for InfixMul {
    fn call(&self, args: ExprList, stack: &mut CallStack) -> EvalResult {
        let (lhs, rhs) = stack.eval_binary(args.unnamed_binary_args())?;
        lhs * rhs
    }
}

#[derive(Debug, Clone, PartialEq)]
#[builtin(sym = "/", kind = Infix)]
pub struct InfixDiv;
impl CallableFormals for InfixDiv {}
impl Callable for InfixDiv {
    fn call(&self, args: ExprList, stack: &mut CallStack) -> EvalResult {
        let (lhs, rhs) = stack.eval_binary(args.unnamed_binary_args())?;
        lhs / rhs
    }
}

#[derive(Debug, Clone, PartialEq)]
#[builtin(sym = "^")]
pub struct InfixPow;
impl CallableFormals for InfixPow {}
impl Callable for InfixPow {
    fn call(&self, args: ExprList, stack: &mut CallStack) -> EvalResult {
        let (lhs, rhs) = stack.eval_binary(args.unnamed_binary_args())?;
        lhs.power(rhs)
    }
}

#[derive(Debug, Clone, PartialEq)]
#[builtin(sym = "%", kind = Infix)]
pub struct InfixMod;
impl CallableFormals for InfixMod {}
impl Callable for InfixMod {
    fn call(&self, args: ExprList, stack: &mut CallStack) -> EvalResult {
        let (lhs, rhs) = stack.eval_binary(args.unnamed_binary_args())?;
        lhs % rhs
    }
}

#[derive(Debug, Clone, PartialEq)]
#[builtin(sym = "||", kind = Infix)]
pub struct InfixOr;
impl CallableFormals for InfixOr {}
impl Callable for InfixOr {
    fn call(&self, args: ExprList, stack: &mut CallStack) -> EvalResult {
        let (lhs, rhs) = stack.eval_binary(args.unnamed_binary_args())?;
        let res = match (lhs, rhs) {
            (Obj::Vector(l), Obj::Vector(r)) => {
                let Ok(lhs) = l.try_into() else { todo!() };
                let Ok(rhs) = r.try_into() else { todo!() };
                Obj::Vector(Vector::from(vec![OptionNA::Some(lhs || rhs)]))
            }
            _ => Obj::Null,
        };

        Ok(res)
    }
}

#[derive(Debug, Clone, PartialEq)]
#[builtin(sym = "&&", kind = Infix)]
pub struct InfixAnd;
impl CallableFormals for InfixAnd {}
impl Callable for InfixAnd {
    fn call(&self, args: ExprList, stack: &mut CallStack) -> EvalResult {
        let (lhs, rhs) = stack.eval_binary(args.unnamed_binary_args())?;
        let res = match (lhs, rhs) {
            (Obj::Vector(l), Obj::Vector(r)) => {
                let Ok(lhs) = l.try_into() else { todo!() };
                let Ok(rhs) = r.try_into() else { todo!() };
                Obj::Vector(Vector::from(vec![OptionNA::Some(lhs && rhs)]))
            }
            _ => Obj::Null,
        };

        Ok(res)
    }
}

#[derive(Debug, Clone, PartialEq)]
#[builtin(sym = "|", kind = Infix)]
pub struct InfixVectorOr;
impl CallableFormals for InfixVectorOr {}
impl Callable for InfixVectorOr {
    fn call(&self, args: ExprList, stack: &mut CallStack) -> EvalResult {
        let (lhs, rhs) = stack.eval_binary(args.unnamed_binary_args())?;
        lhs | rhs
    }
}

#[derive(Debug, Clone, PartialEq)]
#[builtin(sym = "&", kind = Infix)]
pub struct InfixVectorAnd;
impl CallableFormals for InfixVectorAnd {}
impl Callable for InfixVectorAnd {
    fn call(&self, args: ExprList, stack: &mut CallStack) -> EvalResult {
        let (lhs, rhs) = stack.eval_binary(args.unnamed_binary_args())?;
        lhs & rhs
    }
}

#[derive(Debug, Clone, PartialEq)]
#[builtin(sym = ">", kind = Infix)]
pub struct InfixGreater;
impl CallableFormals for InfixGreater {}
impl Callable for InfixGreater {
    fn call(&self, args: ExprList, stack: &mut CallStack) -> EvalResult {
        let (lhs, rhs) = stack.eval_binary(args.unnamed_binary_args())?;
        lhs.vec_gt(rhs)
    }
}

#[derive(Debug, Clone, PartialEq)]
#[builtin(sym = ">=", kind = Infix)]
pub struct InfixGreaterEqual;
impl CallableFormals for InfixGreaterEqual {}
impl Callable for InfixGreaterEqual {
    fn call(&self, args: ExprList, stack: &mut CallStack) -> EvalResult {
        let (lhs, rhs) = stack.eval_binary(args.unnamed_binary_args())?;
        lhs.vec_gte(rhs)
    }
}

#[derive(Debug, Clone, PartialEq)]
#[builtin(sym = "<", kind = Infix)]
pub struct InfixLess;
impl CallableFormals for InfixLess {}
impl Callable for InfixLess {
    fn call(&self, args: ExprList, stack: &mut CallStack) -> EvalResult {
        let (lhs, rhs) = stack.eval_binary(args.unnamed_binary_args())?;
        lhs.vec_lt(rhs)
    }
}

#[derive(Debug, Clone, PartialEq)]
#[builtin(sym = "<=", kind = Infix)]
pub struct InfixLessEqual;
impl CallableFormals for InfixLessEqual {}
impl Callable for InfixLessEqual {
    fn call(&self, args: ExprList, stack: &mut CallStack) -> EvalResult {
        let (lhs, rhs) = stack.eval_binary(args.unnamed_binary_args())?;
        lhs.vec_lte(rhs)
    }
}

#[derive(Debug, Clone, PartialEq)]
#[builtin(sym = "==", kind = Infix)]
pub struct InfixEqual;
impl CallableFormals for InfixEqual {}
impl Callable for InfixEqual {
    fn call(&self, args: ExprList, stack: &mut CallStack) -> EvalResult {
        let (lhs, rhs) = stack.eval_binary(args.unnamed_binary_args())?;
        lhs.vec_eq(rhs)
    }
}

#[derive(Debug, Clone, PartialEq)]
#[builtin(sym = "!=", kind = Infix)]
pub struct InfixNotEqual;
impl CallableFormals for InfixNotEqual {}
impl Callable for InfixNotEqual {
    fn call(&self, args: ExprList, stack: &mut CallStack) -> EvalResult {
        let (lhs, rhs) = stack.eval_binary(args.unnamed_binary_args())?;
        lhs.vec_neq(rhs)
    }
}

#[derive(Debug, Clone, PartialEq)]
#[builtin(sym = "|>", kind = Infix)]
pub struct InfixPipe;
impl CallableFormals for InfixPipe {}
impl Callable for InfixPipe {
    fn call(&self, args: ExprList, stack: &mut CallStack) -> EvalResult {
        // TODO: reduce call stack nesting here
        let (lhs, rhs) = args.unnamed_binary_args();

        use Expr::*;
        match rhs {
            Call(what, mut args) => {
                args.insert(0, lhs);
                let new_expr = Call(what, args);
                stack.eval(new_expr)
            }
            s @ Symbol(..) | s @ String(..) => {
                let args = ExprList::from(vec![(None, lhs)]);
                let new_expr = Call(Box::new(s), args);
                stack.eval(new_expr)
            }
            _ => unreachable!(),
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
#[builtin(sym = ":", kind = Infix)]
pub struct InfixColon;
impl CallableFormals for InfixColon {}
impl Callable for InfixColon {
    fn call(&self, args: ExprList, stack: &mut CallStack) -> EvalResult {
        let mut argstream = args.into_iter();
        let arg1 = argstream.next().map(|(_, v)| v).unwrap_or(Expr::Null);
        let arg2 = argstream.next().map(|(_, v)| v).unwrap_or(Expr::Null);

        fn colon_args(arg: &Expr) -> Option<(Expr, Expr)> {
            if let Expr::Call(what, largs) = arg.clone() {
                if let Expr::Primitive(p) = *what {
                    if p == (Box::new(InfixColon) as Box<dyn Builtin>) {
                        return Some(largs.clone().unnamed_binary_args());
                    }
                }
            }

            None
        }

        // handle special case of chained colon ops: `x:y:z`
        if let Some((llhs, lrhs)) = colon_args(&arg1) {
            // since we're rearranging calls here, we might need to modify the call stack
            let args = ExprList::from(vec![(None, llhs), (None, lrhs), (None, arg2)]);
            InfixColon.call(args, stack)

        // tertiary case
        } else if let Some((_, arg3)) = argstream.next() {
            // currently always returns double vector
            let start: f64 = stack.eval(arg1)?.try_into()?;
            let by: f64 = stack.eval(arg2)?.try_into()?;
            let end: f64 = stack.eval(arg3)?.try_into()?;

            if by == 0.0 {
                return Error::Other("Cannot increment by 0".to_string()).into();
            }

            let range = end - start;

            if range / by < 0.0 {
                return Ok(Obj::Vector(Vector::from(Vec::<Double>::new())));
            }

            let mut v = start;
            return Ok(Obj::Vector(Vector::from(
                vec![start]
                    .into_iter()
                    .chain(std::iter::repeat_with(|| {
                        v += by;
                        v
                    }))
                    .take_while(|x| if start <= end { x <= &end } else { x >= &end })
                    .collect::<Vec<f64>>(),
            )));

        // binary case
        } else {
            let start: i32 = stack.eval(arg1)?.as_integer()?.try_into()?;
            let end: i32 = stack.eval(arg2)?.as_integer()?.try_into()?;
            if start > end {
                return Error::InvalidRange.into();
            }
            return Ok(Obj::Vector(Vector::from(if start <= end {
                (start..=end).map(|i| i as f64).collect::<Vec<f64>>()
            } else {
                (end..=start).map(|i| i as f64).rev().collect::<Vec<f64>>()
            })));
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
#[builtin(sym = "$", kind = Infix)]
pub struct InfixDollar;
impl CallableFormals for InfixDollar {}
impl Callable for InfixDollar {
    fn call(&self, args: ExprList, stack: &mut CallStack) -> EvalResult {
        let mut argstream = args.into_iter();

        let Some((_, what)) = argstream.next() else {
            unreachable!();
        };

        let Some((_, index)) = argstream.next() else {
            unreachable!();
        };

        let mut what = stack.eval(what)?;

        match index {
            Expr::String(s) | Expr::Symbol(s) => what.try_get_named(&s),
            _ => Ok(Obj::Null),
        }
    }

    fn call_mut(&self, args: ExprList, stack: &mut CallStack) -> EvalResult {
        let mut argstream = args.into_iter();

        let Some((_, what)) = argstream.next() else {
            unreachable!();
        };

        let Some((_, index)) = argstream.next() else {
            unreachable!();
        };

        let mut what = stack.eval_mut(what)?;

        match index {
            Expr::String(s) | Expr::Symbol(s) => what.try_get_named_mut(s.as_str()),
            _ => Ok(Obj::Null),
        }
    }

    fn call_assign(&self, value: Expr, args: ExprList, stack: &mut CallStack) -> EvalResult {
        let mut argstream = args.into_iter();

        let Some((_, what)) = argstream.next() else {
            unreachable!();
        };

        let Some((_, name)) = argstream.next() else {
            unreachable!();
        };

        let value = stack.eval(value)?;
        let mut what = stack.eval_mut(what)?;

        match name {
            Expr::String(s) | Expr::Symbol(s) => what.try_set_named(&s, value),
            _ => unimplemented!(),
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
#[builtin(sym = "..", kind = Postfix)]
pub struct PostfixPack;
impl CallableFormals for PostfixPack {}
impl Callable for PostfixPack {
    fn call(&self, _args: ExprList, _stack: &mut CallStack) -> EvalResult {
        Error::IncorrectContext("..".to_string()).into()
    }
}

#[derive(Debug, Clone, PartialEq)]
#[builtin(sym = "[[", kind = PostfixCall("[[", "]]"))]
pub struct PostfixIndex;
impl CallableFormals for PostfixIndex {}
impl Callable for PostfixIndex {
    fn call(&self, args: ExprList, stack: &mut CallStack) -> EvalResult {
        let (what, index) = stack.eval_binary(args.unnamed_binary_args())?;
        what.try_get_inner(index)
    }

    fn call_mut(&self, args: ExprList, stack: &mut CallStack) -> EvalResult {
        let x = args.unnamed_binary_args();
        let what = stack.eval_mut(x.0)?;
        let index = stack.eval(x.1)?;
        what.try_get_inner_mut(index)
    }

    fn call_assign(&self, value: Expr, args: ExprList, stack: &mut CallStack) -> EvalResult {
        let mut argstream = args.into_iter();

        let Some((_, what)) = argstream.next() else {
            unreachable!();
        };

        let Some((_, index)) = argstream.next() else {
            unreachable!();
        };

        let value = stack.eval(value)?;
        let what = stack.eval_mut(what)?;
        let index = stack.eval(index)?;

        let subset = index.try_into()?;

        Ok(match what {
            Obj::List(mut v) => v.set_subset(subset, value)?,
            Obj::Vector(mut v) => v.set_subset(subset, value).map(Obj::Vector)?,
            _ => unimplemented!(),
        })
    }
}

#[derive(Debug, Clone, PartialEq)]
#[builtin(sym = "[", kind = PostfixCall("[", "]"))]
pub struct PostfixVecIndex;
impl CallableFormals for PostfixVecIndex {}
impl Callable for PostfixVecIndex {
    fn call(&self, args: ExprList, stack: &mut CallStack) -> EvalResult {
        let (what, index) = stack.eval_binary(args.unnamed_binary_args())?;
        what.try_get(index)
    }

    fn call_mut(&self, args: ExprList, stack: &mut CallStack) -> EvalResult {
        let x = args.unnamed_binary_args();
        let what = stack.eval_mut(x.0)?;
        let index = stack.eval(x.1)?;
        what.try_get(index)
    }
}

#[cfg(test)]
mod tests {
    use crate::error::Error;
    use crate::lang::{EvalResult, Signal};
    use crate::{r, r_expect};
    #[test]
    fn colon_operator() {
        assert_eq!(EvalResult::Err(Signal::Error(Error::InvalidRange)), r!(1:0));
        assert_eq!(r!([1, 2]), r!(1:2));
        assert_eq!(r!([1]), r!(1:1));
        assert_eq!(r!(1:-2:-3), r!([1, -1, -3]));
    }

    #[test]
    fn dollar_assign() {
        r_expect! {{"
            l = (a = 1, )
            x = (l$a = 2)
            l$a == 2 & x == 2
        "}}
    }
    #[test]
    fn dollar_assign_nested() {
        r_expect! {{"
            l = (a = (b = 1,),)
            x = (l$a$b = 2)
            l$a$b == 2 & x == 2
        "}}
    }

    #[test]
    fn dollar_access() {
        r_expect! {{"
            l = (a = 1, )
            l$a == 1
        "}}
    }
}