lumesh 0.18.2

a lighting shell ⚡ bash alternative
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
// 运算符重载(内存优化)

use std::{
    collections::{BTreeMap, HashMap},
    rc::Rc,
};

use crate::RuntimeErrorKind;

use super::Expression;

use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Rem, Sub, SubAssign};

impl Add for Expression {
    type Output = Result<Self, RuntimeErrorKind>;

    fn add(self, other: Self) -> Result<Self, RuntimeErrorKind> {
        match (self, other) {
            // 数值运算
            (Self::Integer(m), Self::Integer(n)) => m
                .checked_add(n)
                .map(Self::Integer)
                .ok_or_else(|| RuntimeErrorKind::Overflow(format!("{m} + {n}"))),
            (Self::Integer(m), Self::Float(n)) => Ok(Self::Float(m as f64 + n)),
            (Self::Float(m), Self::Integer(n)) => Ok(Self::Float(m + n as f64)),
            (Self::Float(m), Self::Float(n)) => Ok(Self::Float(m + n)),

            (Self::Integer(m), Self::String(n)) => {
                // 尝试将字符串转换为整数
                match n.parse::<i64>() {
                    Ok(n) => Ok(Self::Integer(m + n)),
                    Err(_) => Err(RuntimeErrorKind::CommandFailed2(
                        "+".into(),
                        format!("Cannot convert string `{n}` to integer"),
                    )), // 转换失败
                }
            }
            (Self::Float(m), Self::String(n)) => {
                // 尝试将字符串转换为浮点数
                match n.parse::<f64>() {
                    Ok(n) => Ok(Self::Float(m + n)),
                    Err(_) => Err(RuntimeErrorKind::CommandFailed2(
                        "+".into(),
                        format!("Cannot convert string `{n}` to integer"),
                    )), // 转换失败
                }
            }
            // to-list
            (Self::Integer(m), Self::List(b)) => {
                // 将列表内部元素求和
                let sum: i64 = b
                    .as_ref()
                    .iter()
                    .filter_map(|x| {
                        if let Self::Integer(n) = x {
                            Some(*n)
                        } else {
                            None // 只处理整数
                        }
                    })
                    .sum();
                Ok(Self::Integer(m + sum))
            }
            (Self::Float(m), Self::List(b)) => {
                // 将列表内部元素求和
                let sum: f64 = b
                    .as_ref()
                    .iter()
                    .filter_map(|x| {
                        if let Self::Float(n) = x {
                            Some(*n)
                        } else if let Self::Integer(n) = x {
                            Some(*n as f64)
                        } else {
                            None // 只处理整数和浮点数
                        }
                    })
                    .sum();
                Ok(Self::Float(m + sum))
            }

            // 字符串拼接
            (Self::String(m), Self::String(n)) => Ok(Self::String(m + &n)),
            (Self::String(m), Self::Integer(n)) => Ok(Self::String(m + &n.to_string())),
            (Self::String(m), Self::Float(n)) => Ok(Self::String(m + &n.to_string())),

            (Self::String(m), Self::List(b)) => {
                let concatenated: String = b
                    .as_ref()
                    .iter()
                    .filter_map(|x| {
                        if let Self::String(n) = x {
                            Some(n.clone())
                        } else {
                            None // 只处理字符串
                        }
                    })
                    .collect();
                Ok(Self::String(m + &concatenated))
            }

            // range
            (Self::Range(a, step), Self::Integer(b)) if b >= 0 => {
                let end = a
                    .end
                    .checked_add(b)
                    .ok_or_else(|| RuntimeErrorKind::Overflow(format!("{} + {b}", a.end)))?;
                Ok(Expression::Range(a.start..end, step))
            }
            (Self::Range(a, step), Self::Integer(b)) => {
                let start = a
                    .start
                    .checked_add(b)
                    .ok_or_else(|| RuntimeErrorKind::Overflow(format!("{} + {b}", a.start)))?;
                Ok(Expression::Range(start..a.end, step))
            }

            // 列表合并
            (Self::List(a), Self::List(b)) => {
                let mut new_vec = Vec::with_capacity(a.len() + b.len());
                new_vec.extend_from_slice(&a);
                new_vec.extend_from_slice(&b);
                Ok(Self::List(Rc::new(new_vec)))
            }
            (Self::List(a), other) => {
                let mut new_vec = Vec::with_capacity(a.len() + 1);
                new_vec.extend_from_slice(&a);
                new_vec.push(other);
                Ok(Self::List(Rc::new(new_vec)))
            }

            // set merging
            (Self::BSet(a), Self::BSet(b)) => {
                let mut new_set = a.as_ref().clone();
                new_set.extend(b.as_ref().iter().cloned());
                Ok(Self::BSet(Rc::new(new_set)))
            }
            (Self::BSet(a), other) => {
                let mut new_set = a.as_ref().clone();
                new_set.insert(other);
                Ok(Self::BSet(Rc::new(new_set)))
            }

            // Map merging
            (Self::HMap(a), Self::HMap(b)) => {
                let mut new_map = HashMap::new();
                new_map.extend(a.iter().map(|(k, v)| (k.clone(), v.clone())));
                new_map.extend(b.iter().map(|(k, v)| (k.clone(), v.clone())));
                Ok(Self::HMap(Rc::new(new_map)))
            }
            (Self::HMap(a), other) => {
                let mut new_map = HashMap::new();
                new_map.extend(a.iter().map(|(k, v)| (k.clone(), v.clone())));
                new_map.insert(other.to_string(), other);
                Ok(Self::from(new_map))
            }
            (Self::Map(a), Self::Map(b)) => {
                let mut new_map = BTreeMap::new();
                new_map.extend(a.iter().map(|(k, v)| (k.clone(), v.clone())));
                new_map.extend(b.iter().map(|(k, v)| (k.clone(), v.clone())));
                Ok(Self::Map(Rc::new(new_map)))
            }
            (Self::Map(a), other) => {
                let mut new_map = BTreeMap::new();
                new_map.extend(a.iter().map(|(k, v)| (k.clone(), v.clone())));
                new_map.insert(other.to_string(), other);
                Ok(Self::Map(Rc::new(new_map)))
            }

            // bytes
            (Self::Bytes(mut a), Self::Bytes(b)) => {
                a.extend(b);
                Ok(Self::Bytes(a))
            }
            (Self::Bytes(mut a), Self::String(n)) => {
                a.extend(n.into_bytes());
                Ok(Self::Bytes(a))
            }
            (Self::Bytes(mut a), Self::Integer(n)) => {
                a.push(n as u8);
                Ok(Self::Bytes(a))
            }
            (Self::String(m), Self::Bytes(n)) => {
                let result = format!("{}{}", m, String::from_utf8_lossy(n.as_ref()));
                Ok(Self::String(result))
            }
            // (Self::Integer(n), Self::Bytes(mut a)) => {
            //     a.insert(0, n as u8);
            //     Ok(Self::Bytes(a))
            // }

            // 其他情况
            (m, n) => Err(RuntimeErrorKind::CommandFailed2(
                "+".into(),
                format!(
                    "Cannot add {}:{} and {}:{}",
                    m,
                    m.type_name(),
                    n,
                    n.type_name()
                ),
            )),
        }
    }
}

impl Sub for Expression {
    type Output = Result<Self, RuntimeErrorKind>;

    fn sub(self, other: Self) -> Result<Self, RuntimeErrorKind> {
        match (self, other) {
            // 数值运算
            (Self::Integer(m), Self::Integer(n)) => m
                .checked_sub(n)
                .map(Self::Integer)
                .ok_or_else(|| RuntimeErrorKind::Overflow(format!("{m} - {n}"))),
            (Self::Integer(m), Self::Float(n)) => Ok(Self::Float(m as f64 - n)),
            (Self::Float(m), Self::Integer(n)) => Ok(Self::Float(m - n as f64)),
            (Self::Float(m), Self::Float(n)) => Ok(Self::Float(m - n)),
            // to-string
            (Self::Integer(m), Self::String(n)) => {
                // 尝试将字符串转换为整数
                match n.parse::<i64>() {
                    Ok(n) => Ok(Self::Integer(m - n)),
                    Err(_) => Err(RuntimeErrorKind::CommandFailed2(
                        "-".into(),
                        format!("Cannot convert string `{n}` to integer"),
                    )), // 转换失败
                }
            }
            (Self::Float(m), Self::String(n)) => {
                // 尝试将字符串转换为浮点数
                match n.parse::<f64>() {
                    Ok(n) => Ok(Self::Float(m - n)),
                    Err(_) => Err(RuntimeErrorKind::CommandFailed2(
                        "-".into(),
                        format!("Cannot convert string `{n}` to integer"),
                    )), // 转换失败
                }
            }

            // string
            (Self::String(m), Self::String(n)) => {
                // 从字符串中移除另一个字符串
                if let Some(pos) = m.find(&n) {
                    let new_string = m[..pos].to_string() + &m[pos + n.len()..];
                    Ok(Self::String(new_string))
                } else {
                    Ok(Self::String(m))
                }
            }
            (Self::String(m), Self::Integer(n)) => {
                // 字符串首尾截取
                if n >= 0 {
                    if m.len() >= n as usize {
                        let l = m.len() - n as usize;
                        Ok(Self::String(m[..l].to_string()))
                    } else {
                        Ok(Self::String("".to_owned()))
                    }
                } else {
                    let l = n
                        .checked_neg()
                        .ok_or_else(|| RuntimeErrorKind::Overflow(format!("-{n}")))?
                        as usize;
                    if l <= m.len() {
                        Ok(Self::String(m[l..].to_string()))
                    } else {
                        Ok(Self::String("".to_owned()))
                    }
                }
            }
            (Self::String(m), Self::Float(n)) => {
                // 将整数转换为字符串并从前一个字符串中移除
                let n_str = n.to_string();
                if let Some(pos) = m.find(&n_str) {
                    let new_string = m[..pos].to_string() + &m[pos + n_str.len()..];
                    Ok(Self::String(new_string))
                } else {
                    Ok(Self::String(m))
                }
            }

            (Self::Range(a, step), Self::Integer(b)) if b >= 0 => {
                let end = a
                    .end
                    .checked_sub(b)
                    .ok_or_else(|| RuntimeErrorKind::Overflow(format!("{} - {b}", a.end)))?;
                Ok(Expression::Range(a.start..end, step))
            }
            (Self::Range(a, step), Self::Integer(b)) => {
                let start = a
                    .start
                    .checked_add(b)
                    .ok_or_else(|| RuntimeErrorKind::Overflow(format!("{} - {b}", a.start)))?;
                Ok(Expression::Range(start..a.end, step))
            }

            (Self::List(a), Self::List(b)) => {
                if Rc::ptr_eq(&a, &b) {
                    Ok(Self::List(Rc::new(Vec::new()))) // Clear the list if they are the same
                } else {
                    let mut a_items = a.as_ref().to_vec(); // Clone items directly into a new Vec
                    let b_items = b.as_ref().to_vec(); // Use a HashSet for faster lookups
                    a_items.retain(|x| !b_items.contains(x)); // Remove items in b from a
                    Ok(Self::List(Rc::new(a_items)))
                }
            }

            (Self::List(a), value) => {
                let pos = a.as_ref().iter().position(|x| *x == value);

                if let Some(pos) = pos {
                    // Create a new Vec without the element at the found position
                    let mut a_items: Vec<_> = a.as_ref().to_vec();
                    a_items.remove(pos);
                    Ok(Self::List(Rc::new(a_items)))
                } else {
                    Ok(Self::List(a))
                }
            }

            // set
            (Self::BSet(a), Self::BSet(b)) => {
                let mut new_set = a.as_ref().clone();
                for item in b.as_ref().iter() {
                    new_set.remove(item);
                }
                Ok(Self::BSet(Rc::new(new_set)))
            }
            (Self::BSet(a), value) => {
                let mut new_set = a.as_ref().clone();
                new_set.remove(&value);
                Ok(Self::BSet(Rc::new(new_set)))
            }

            // Map operations
            (Self::HMap(a), Self::HMap(b)) => {
                // 如果两个 Rc 指向同一个 HashMap,返回一个新的空 HashMap
                if Rc::ptr_eq(&a, &b) {
                    return Ok(Self::HMap(Rc::new(HashMap::new())));
                }
                // 创建一个新的 HashMap,直接从 a 中移除 b 中的键
                let mut a_map = a.as_ref().clone(); // 只在这里克隆一次
                for key in b.as_ref().keys() {
                    a_map.remove(key); // 从 a_map 中移除 b_map 的键
                }
                Ok(Self::from(a_map))
            }

            (Self::HMap(a), Self::Symbol(key) | Self::String(key)) => {
                let mut new_map = a.as_ref().clone();
                new_map.remove(&key);
                Ok(Self::from(new_map))
            }
            // BMap
            (Self::Map(a), Self::Map(b)) => {
                // 如果两个 Rc 指向同一个 HashMap,返回一个新的空 HashMap
                if Rc::ptr_eq(&a, &b) {
                    return Ok(Self::Map(Rc::new(BTreeMap::new())));
                }
                // 创建一个新的 HashMap,直接从 a 中移除 b 中的键
                let mut a_map = a.as_ref().clone(); // 只在这里克隆一次
                for key in b.as_ref().keys() {
                    a_map.remove(key); // 从 a_map 中移除 b_map 的键
                }
                Ok(Self::from(a_map))
            }

            (Self::Map(a), Self::Symbol(key) | Self::String(key)) => {
                let mut new_map = a.as_ref().clone();
                new_map.remove(&key);
                Ok(Self::from(new_map))
            }

            (Self::DateTime(a), Self::DateTime(b)) => {
                let d = a - b;
                Ok(Self::from(d.num_milliseconds()))
            }
            // bytes
            (Self::Bytes(m), Self::Bytes(n)) => {
                if let Some(pos) = subslice(&m, &n) {
                    let mut result = m[..pos].to_vec();
                    result.extend_from_slice(&m[pos + n.len()..]);
                    Ok(Self::Bytes(result))
                } else {
                    Ok(Self::Bytes(m))
                }
            }
            (Self::Bytes(m), Self::String(n)) => {
                let n_bytes = n.into_bytes();
                if let Some(pos) = subslice(&m, &n_bytes) {
                    let mut result = m[..pos].to_vec();
                    result.extend_from_slice(&m[pos + n_bytes.len()..]);
                    Ok(Self::Bytes(result))
                } else {
                    Ok(Self::Bytes(m))
                }
            }
            (Self::Bytes(m), Self::Integer(n)) => {
                if n >= 0 {
                    let n = n as usize;
                    if m.len() >= n {
                        Ok(Self::Bytes(m[..m.len() - n].to_vec()))
                    } else {
                        Ok(Self::Bytes(Vec::new()))
                    }
                } else {
                    let n = n
                        .checked_neg()
                        .ok_or_else(|| RuntimeErrorKind::Overflow(format!("-{n}")))?
                        as usize;
                    if n <= m.len() {
                        Ok(Self::Bytes(m[n..].to_vec()))
                    } else {
                        Ok(Self::Bytes(Vec::new()))
                    }
                }
            }

            // 其他情况
            (n, m) => Err(RuntimeErrorKind::CommandFailed2(
                "-".into(),
                format!(
                    "Cannot subtract {}:{} from {}:{}",
                    m,
                    m.type_name(),
                    n,
                    n.type_name()
                ),
            )),
        }
    }
}
fn subslice(haystack: &[u8], needle: &[u8]) -> Option<usize> {
    if needle.is_empty() {
        return Some(0);
    }
    haystack.windows(needle.len()).position(|w| w == needle)
}
impl Mul for Expression {
    type Output = Result<Self, RuntimeErrorKind>;

    fn mul(self, other: Self) -> Result<Self, RuntimeErrorKind> {
        match (self, other) {
            // num
            (Self::Integer(m), Self::Integer(n)) => match m.checked_mul(n) {
                Some(result) => Ok(Self::Integer(result)),
                None => Err(RuntimeErrorKind::Overflow(format!(
                    "Integer overflow when multiplying {m} and {n}"
                ))),
            },
            (Self::Integer(m), Self::Float(n)) => Ok(Self::Float(m as f64 * n)),
            (Self::Float(m), Self::Integer(n)) => Ok(Self::Float(m * n as f64)),
            (Self::Float(m), Self::Float(n)) => Ok(Self::Float(m * n)),
            // to-string
            (Self::Integer(n), Self::String(m)) => {
                // 尝试将字符串转换为整数
                match m.parse::<i64>() {
                    Ok(num) => Ok(Self::Integer(n * num)),
                    Err(_) => Err(RuntimeErrorKind::CommandFailed2(
                        "*".into(),
                        format!("Cannot convert string `{m}` to integer"),
                    )),
                }
            }
            (Self::Float(n), Self::String(m)) => {
                // 尝试将字符串转换为浮点数
                match m.parse::<f64>() {
                    Ok(num) => Ok(Self::Float(n * num)),
                    Err(_) => Err(RuntimeErrorKind::CommandFailed2(
                        "*".into(),
                        format!("Cannot convert string `{m}` to float"),
                    )),
                }
            }

            // string
            (Self::String(m), Self::Integer(n)) => {
                if n == 0 {
                    Ok(Self::String(String::new()))
                } else if n < 0 {
                    Err(RuntimeErrorKind::CommandFailed2(
                        "*".into(),
                        format!("Cannot multiply string by negative number {n}"),
                    ))
                } else {
                    Ok(Self::String(m.repeat(n as usize)))
                }
            }

            // list
            (Self::List(a), Self::List(b)) => {
                // 矩阵乘法
                // 假设 a 是 m x n 矩阵,b 是 n x p 矩阵
                let a_rows = a.as_ref().len();
                let a_cols = if a_rows > 0 {
                    match &a.as_ref()[0] {
                        Self::List(inner) => inner.as_ref().len(),
                        _ => 0,
                    }
                } else {
                    0
                };
                let b_cols = if !b.as_ref().is_empty() {
                    match &b.as_ref()[0] {
                        Self::List(inner) => inner.as_ref().len(),
                        _ => 0,
                    }
                } else {
                    0
                };

                if a_cols != b.as_ref().len() {
                    return Err(RuntimeErrorKind::CommandFailed2(
                        "*".into(),
                        format!(
                            "Matrix dimensions do not match for multiplication: {}x{} and {}x{}",
                            a_rows,
                            a_cols,
                            b.as_ref().len(),
                            b_cols
                        ),
                    ));
                }

                let mut result = Vec::new();
                for i in 0..a_rows {
                    let mut row_result = Vec::new();
                    for j in 0..b_cols {
                        let mut sum = 0.0; // 使用浮点数进行计算
                        for k in 0..a_cols {
                            let a_value = match &a.as_ref()[i] {
                                Self::List(inner) => match inner.as_ref().get(k) {
                                    Some(val) => match val {
                                        Self::Integer(v) => *v as f64,
                                        Self::Float(v) => *v,
                                        _ => 0.0,
                                    },
                                    None => 0.0,
                                },
                                _ => 0.0,
                            };
                            let b_value = match &b.as_ref()[k] {
                                Self::List(inner) => match inner.as_ref().get(j) {
                                    Some(val) => match val {
                                        Self::Integer(v) => *v as f64,
                                        Self::Float(v) => *v,
                                        _ => 0.0,
                                    },
                                    None => 0.0,
                                },
                                _ => 0.0,
                            };
                            sum += a_value * b_value;
                        }
                        row_result.push(Self::Float(sum));
                    }
                    result.push(Self::from(row_result));
                }
                Ok(Self::from(result))
            }

            (Self::List(a), value) => {
                let mut new_list = Vec::new();
                let n = match value {
                    Self::Integer(n) => n as f64, // 将整数转换为浮点数
                    Self::Float(n) => n,
                    _ => {
                        return Err(RuntimeErrorKind::CommandFailed2(
                            "*".into(),
                            format!("Cannot multiply by non-numeric value {value:?}"),
                        ));
                    }
                };

                for element in a.as_ref().iter() {
                    match element {
                        Self::Integer(val) => new_list.push(Self::Float(*val as f64 * n)),
                        Self::Float(val) => new_list.push(Self::Float(val * n)),
                        _ => {
                            return Err(RuntimeErrorKind::CommandFailed2(
                                "*".into(),
                                format!("Cannot multiply non-numeric element {element:?}"),
                            ));
                        }
                    }
                }
                Ok(Self::from(new_list))
            }

            // 交集运算
            (Self::BSet(a), Self::BSet(b)) => {
                let new_set = a.as_ref().intersection(b.as_ref()).cloned().collect();
                Ok(Self::BSet(Rc::new(new_set)))
            }

            // bytes
            (Self::Bytes(m), Self::Integer(n)) => {
                let n = n as usize;
                if n > 0 && n < usize::MAX {
                    Ok(Self::Bytes(m.repeat(n)))
                } else {
                    Ok(Self::None)
                }
            }
            // 其他情况
            (m, n) => Err(RuntimeErrorKind::CommandFailed2(
                "*".into(),
                format!(
                    "Cannot multiply {}:{} and {}:{}",
                    m,
                    m.type_name(),
                    n,
                    n.type_name()
                ),
            )),
        }
    }
}

impl Div for Expression {
    type Output = Result<Self, RuntimeErrorKind>;

    fn div(self, other: Self) -> Result<Self, RuntimeErrorKind> {
        match (self, other) {
            // 数值类型
            (l, Self::Integer(0) | Self::Float(0.0)) => Err(RuntimeErrorKind::CustomError(
                format!("can't divide {l} by zero").into(),
            )),
            (l, Self::String(s)) if s == "0" || s == "0.0" => Err(RuntimeErrorKind::CustomError(
                format!("can't divide {l} by zero").into(),
            )),
            (Self::Integer(m), Self::Integer(n)) => Ok(Self::Integer(m / n)),
            (Self::Integer(m), Self::Float(n)) => Ok(Self::Float(m as f64 / n)),
            (Self::Float(m), Self::Integer(n)) => Ok(Self::Float(m / n as f64)),
            (Self::Float(m), Self::Float(n)) => Ok(Self::Float(m / n)),

            // to-string
            (Self::Integer(n), Self::String(m)) => {
                // 尝试将字符串转换为整数
                match m.parse::<i64>() {
                    Ok(num) => Ok(Self::Integer(n / num)),
                    Err(_) => Err(RuntimeErrorKind::CommandFailed2(
                        "/".into(),
                        format!("Cannot convert string `{m}` to integer"),
                    )),
                }
            }
            (Self::Float(n), Self::String(m)) => {
                // 尝试将字符串转换为浮点数
                match m.parse::<f64>() {
                    Ok(num) => Ok(Self::Float(n / num)),
                    Err(_) => Err(RuntimeErrorKind::CommandFailed2(
                        "/".into(),
                        format!("Cannot convert string `{m}` to float"),
                    )),
                }
            }

            // 列表类型
            (Self::List(a), value) => {
                let divisor = match value {
                    Self::Integer(n) => n as f64,
                    Self::Float(n) => n,
                    _ => {
                        return Err(RuntimeErrorKind::CommandFailed2(
                            "/".into(),
                            format!("Cannot divide by non-numeric value {value:?}"),
                        ));
                    }
                };

                let new_list: Result<Vec<Self>, RuntimeErrorKind> = a
                    .as_ref()
                    .iter()
                    .map(|element| match element {
                        Self::Integer(val) => Ok(Self::Float(*val as f64 / divisor)),
                        Self::Float(val) => Ok(Self::Float(val / divisor)),
                        _ => Err(RuntimeErrorKind::CommandFailed2(
                            "/".into(),
                            format!("Cannot divide non-numeric element {element:?}"),
                        )),
                    })
                    .collect();

                new_list.map(Self::from) // 将 Result<Vec<Self>, RuntimeError> 转换为 Result<Self, RuntimeError>
            }

            // 其他情况
            (m, n) => Err(RuntimeErrorKind::CommandFailed2(
                "/".into(),
                format!(
                    "Cannot divide {}:{} by {}:{}",
                    m,
                    m.type_name(),
                    n,
                    n.type_name()
                ),
            )),
        }
    }
}

impl Neg for Expression {
    type Output = Expression;
    #[inline]
    fn neg(self) -> Self::Output {
        match self {
            Self::Integer(n) => Self::Integer(-n),
            Self::Float(n) => Self::Float(-n),
            Self::Boolean(b) => Self::Boolean(!b),
            _ => Self::None,
        }
    }
}
impl AddAssign for Expression {
    fn add_assign(&mut self, other: Self) {
        *self = match (&self, other) {
            (Self::Integer(m), Self::Integer(n)) => Self::Integer(m.wrapping_add(n)),
            (Self::Integer(m), Self::Float(n)) => Self::Float(*m as f64 + n),
            (Self::Float(m), Self::Integer(n)) => Self::Float(*m + n as f64),
            (Self::Float(m), Self::Float(n)) => Self::Float(*m + n),
            _ => return,
        }
    }
}
impl SubAssign for Expression {
    fn sub_assign(&mut self, other: Self) {
        *self = match (&self, other) {
            (Self::Integer(m), Self::Integer(n)) => Self::Integer(m.wrapping_sub(n)),
            (Self::Integer(m), Self::Float(n)) => Self::Float(*m as f64 - n),
            (Self::Float(m), Self::Integer(n)) => Self::Float(*m - n as f64),
            (Self::Float(m), Self::Float(n)) => Self::Float(*m - n),
            _ => return,
        }
    }
}
impl MulAssign for Expression {
    fn mul_assign(&mut self, other: Self) {
        *self = match (&self, other) {
            (Self::Integer(m), Self::Integer(n)) => Self::Integer(m.wrapping_mul(n)),
            (Self::Integer(m), Self::Float(n)) => Self::Float(*m as f64 * n),
            (Self::Float(m), Self::Integer(n)) => Self::Float(*m * n as f64),
            (Self::Float(m), Self::Float(n)) => Self::Float(*m * n),
            _ => return,
        }
    }
}
impl DivAssign for Expression {
    fn div_assign(&mut self, other: Self) {
        *self = match (&self, other) {
            (_, Self::Integer(0)) => Self::None,
            (_, Self::Float(0.0)) => Self::None,
            (Self::Integer(m), Self::Integer(n)) => Self::Integer(*m / n),
            (Self::Integer(m), Self::Float(n)) => Self::Float(*m as f64 / n),
            (Self::Float(m), Self::Integer(n)) => Self::Float(*m / n as f64),
            (Self::Float(m), Self::Float(n)) => Self::Float(*m / n),
            _ => return,
        }
    }
}

impl Rem for Expression {
    type Output = Self;
    fn rem(self, other: Self) -> Self {
        match (self, other) {
            (Self::Integer(m), Self::Integer(n)) => Self::Integer(m % n),
            (Self::Float(m), Self::Integer(n)) => Self::Float(m % n as f64),
            (Self::Integer(m), Self::Float(n)) => Self::Float(m as f64 % n),
            (Self::Float(m), Self::Float(n)) => Self::Float(m % n),
            _ => Self::None,
        }
    }
}