kohebi-core 0.0.20

Values, shapes, collections, allocator, and garbage collector for the kohebi Python runtime
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
//! An exception as something a program holds, rather than as something the
//! runtime returns.
//!
//! Two types, because Python has two: `ValueError` is a class and
//! `ValueError('x')` is an instance of it, and a `raise` accepts either. The
//! class is [`Class`] and the instance is [`Exception`], and both are values
//! that go in variables, get passed to functions and get printed.
//!
//! ## Why these are here and not above
//!
//! [`Native`] exists so that the runtime can define types this crate does not
//! know the shape of, and its documentation names exceptions as one of them.
//! That turned out to be true of a function and an iterator, which need to know
//! where output goes and how the interpreter steps, and not true of these. An
//! exception is a class name and a tuple of arguments. Nothing about it depends
//! on the interpreter, and [`Error`] has to be able to carry one, so it lives
//! next to [`Error`] rather than a crate away from it.
//!
//! ## What a class is missing
//!
//! Attributes. `e.args`, `e.__cause__` and the `errno` an `OSError` is supposed
//! to have are all readable in CPython and none of them are readable here,
//! because there is no attribute access yet. The arguments are kept anyway,
//! since `str` and `repr` are made out of them and since the reading is what is
//! missing rather than the data.
//!
//! Constructor signatures, for the handful that have one. `OSError(2, 'x')`
//! sets `errno` and comes back as a `FileNotFoundError` in CPython, and
//! `UnicodeDecodeError` demands five arguments. Here every class takes whatever
//! it is given. That is a difference worth writing down and not one worth
//! fixing before the attributes those arguments would be stored in exist.

use std::any::Any;
use std::cell::{Cell, RefCell};

use crate::error::{Error, Kind, Result};
use crate::native::Native;
use crate::object::Object;

/// A builtin exception class, as a value.
///
/// This is what the name `ValueError` is bound to. Calling it makes an
/// [`Exception`], which is the only thing it does, and which is why it holds
/// nothing but the [`Kind`] it constructs.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Class {
    kind: Kind,
}

impl Class {
    /// The class for this kind.
    #[must_use]
    pub const fn new(kind: Kind) -> Self {
        Class { kind }
    }

    /// Which class it is.
    #[must_use]
    pub const fn kind(self) -> Kind {
        self.kind
    }

    /// An instance of it, which is what calling the class does.
    #[must_use]
    pub fn instance(self, args: Vec<Object>) -> Object {
        Object::native(Exception::new(self.kind, args))
    }
}

impl Native for Class {
    /// The type of a class is `type`, the same as for every other class.
    fn type_name(&self) -> &str {
        "type"
    }

    fn repr(&self) -> String {
        format!("<class '{}'>", self.kind.name())
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

/// An exception instance.
///
/// Made by calling a [`Class`], and after that it is an ordinary value until
/// something raises it.
#[derive(Debug)]
pub struct Exception {
    kind: Kind,
    args: Box<[Object]>,
    /// What `raise this from that` put there.
    ///
    /// A cell because `raise x from y` sets it on an instance that already
    /// exists and may already be bound to a name, which is what CPython does
    /// too.
    cause: RefCell<Option<Object>>,
    /// What was being handled when this was raised, which is `__context__`.
    ///
    /// Nobody writes this. The runtime sets it whenever an exception is raised
    /// inside an `except` clause, which is how a mistake in a handler prints
    /// with the exception it was handling above it rather than on its own.
    context: RefCell<Option<Object>>,
    /// Whether to print the context, which is `__suppress_context__`.
    ///
    /// A written `from` sets this, including `raise x from None`. That is the
    /// whole of what `from None` means: the context is still recorded and is
    /// still readable, and the traceback stops printing it.
    suppress: Cell<bool>,
}

impl Exception {
    /// An instance of this class with these arguments.
    #[must_use]
    pub fn new(kind: Kind, args: Vec<Object>) -> Self {
        Exception {
            kind,
            args: args.into_boxed_slice(),
            cause: RefCell::new(None),
            context: RefCell::new(None),
            suppress: Cell::new(false),
        }
    }

    /// Which class it is an instance of.
    #[must_use]
    pub const fn kind(&self) -> Kind {
        self.kind
    }

    /// What it was constructed with, which is `e.args` and is what everything
    /// it prints is made out of.
    #[must_use]
    pub fn args(&self) -> &[Object] {
        &self.args
    }

    /// What it was raised from, if it was raised from anything.
    ///
    /// Cloned out rather than borrowed, because the cell it lives in cannot
    /// stay borrowed across the walk up a chain of them.
    #[must_use]
    pub fn cause(&self) -> Option<Object> {
        self.cause.borrow().clone()
    }

    /// Record what this was raised from, which is the `from` in a `raise`.
    ///
    /// Writing a `from` at all is what suppresses the context, so `raise x from
    /// None` says "this one, and do not print whatever I happened to be
    /// handling", which is the only way to write that sentence.
    pub fn raised_from(&self, cause: Option<Object>) {
        *self.cause.borrow_mut() = cause;
        self.suppress.set(true);
    }

    /// What was being handled when this was raised, if anything was.
    ///
    /// Cloned out for the same reason [`Exception::cause`] is: the cell cannot
    /// stay borrowed across the walk up a chain of them.
    #[must_use]
    pub fn context(&self) -> Option<Object> {
        self.context.borrow().clone()
    }

    /// Whether a traceback should stop before printing the context.
    #[must_use]
    pub fn suppresses_context(&self) -> bool {
        self.suppress.get()
    }

    /// What `str(e)` says, which is the half of a traceback's last line after
    /// the colon.
    ///
    /// Three shapes and one exception to them. No arguments says nothing at
    /// all, one argument is that argument, and more than one is the tuple of
    /// them. `KeyError` is the one that prints its single argument the way
    /// `repr` would, which is what makes a missing key of `''` visible.
    #[must_use]
    pub fn message(&self) -> String {
        match &*self.args {
            [] => String::new(),
            [only] if self.kind == Kind::KeyError => only.repr(),
            [only] => only.display(),
            many => Object::tuple(many.to_vec()).repr(),
        }
    }
}

impl Native for Exception {
    fn type_name(&self) -> &str {
        self.kind.name()
    }

    /// The class name and the arguments, which is what reads back as the call
    /// that would make it again.
    fn repr(&self) -> String {
        let args: Vec<String> = self.args.iter().map(Object::repr).collect();
        format!("{}({})", self.kind.name(), args.join(", "))
    }

    fn display(&self) -> String {
        self.message()
    }

    /// Every exception is true, including the ones with no arguments, which is
    /// worth saying because an empty tuple is not.
    fn truthy(&self) -> bool {
        true
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

/// The instance a value stands for where an exception is wanted.
///
/// An instance stands for itself, sharing rather than copying, because the
/// object raised is the object caught. A class stands for a fresh instance of
/// itself with no arguments, which is what makes `raise ValueError` and
/// `raise ValueError()` the same statement. Anything else stands for nothing.
#[must_use]
pub fn instance_of(value: &Object) -> Option<Object> {
    if value.exception().is_some() {
        return Some(value.clone());
    }
    let class = value.downcast::<Class>()?;
    Some(class.instance(Vec::new()))
}

/// Whether an `except` clause catches this exception.
///
/// The clause names a class or a tuple of them, and a class catches an
/// exception that is an instance of it or of anything below it, which is the
/// walk [`Kind::derives_from`] does. A tuple catches whatever any of its
/// members catches, and only one deep: CPython used to allow a tuple inside a
/// tuple and stopped, so a nested one is the same mistake as writing a number.
///
/// # Errors
///
/// A `TypeError` when the clause names something that is not an exception
/// class, which is a mistake in the handler rather than in what it was trying
/// to catch.
pub fn matches(raised: &Exception, test: &Object) -> Result<bool> {
    if let Object::Tuple(members) = test {
        for member in members.iter() {
            if caught_by(raised, member)? {
                return Ok(true);
            }
        }
        return Ok(false);
    }
    caught_by(raised, test)
}

/// One class of an `except` clause, which is the whole of it unless it is a
/// tuple.
fn caught_by(raised: &Exception, test: &Object) -> Result<bool> {
    let Some(class) = test.downcast::<Class>() else {
        return Err(Error::type_error(
            "catching classes that do not inherit from BaseException is not allowed",
        ));
    };
    Ok(raised.kind().derives_from(class.kind()))
}

/// Every builtin exception class, bound to its name.
///
/// Built once per run rather than per lookup, so that `ValueError is
/// ValueError` is true the way it is in CPython.
#[must_use]
pub fn classes() -> Vec<(&'static str, Object)> {
    Kind::ALL
        .iter()
        .map(|&kind| (kind.name(), Object::native(Class::new(kind))))
        .collect()
}

/// What an exception that reached the top of the program does to the process.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Exit {
    /// Print this on standard error and stop unsuccessfully, which is what
    /// every exception but one does.
    Report(String),
    /// Stop with this status and print nothing.
    ///
    /// Only `SystemExit` asks for this, and only when what it was given is a
    /// number. The number is truncated to a byte because that is all a process
    /// status has room for, which is why `SystemExit(256)` is a success and
    /// `SystemExit(-1)` is a failure.
    Status(u8),
}

/// What to do about an exception nothing caught.
///
/// `SystemExit` is the one class that is asking for something rather than
/// reporting something, which is why it is the only one this has to look at.
#[must_use]
pub fn uncaught(error: &Error) -> Exit {
    if error.kind != Kind::SystemExit {
        return Exit::Report(error.to_string());
    }
    // `SystemExit.code` is the argument it was given, or nothing when it was
    // given none, or all of them when it was given several.
    let code = match error
        .value()
        .and_then(Object::exception)
        .map(Exception::args)
    {
        None | Some([]) => Object::None,
        Some([only]) => only.clone(),
        Some(many) => Object::tuple(many.to_vec()),
    };
    match code {
        Object::None => Exit::Status(0),
        // A bool is an int here the way it is everywhere else, so
        // `SystemExit(True)` is a failure and `SystemExit(False)` is not.
        Object::Bool(value) => Exit::Status(u8::from(value)),
        // A number too big for a machine word is the one CPython cannot
        // convert either, and 255 is what it stops with when it cannot.
        Object::Int(value) => Exit::Status(value.to_i64().map_or(255, status)),
        // Anything else is a message, which goes out and fails.
        other => Exit::Report(other.display()),
    }
}

/// A process status from a number, the way a shell sees one.
///
/// `rem_euclid` rather than a cast so that a negative status wraps the way the
/// operating system wraps it: `-1` is the 255 that `echo $?` prints.
fn status(code: i64) -> u8 {
    u8::try_from(code.rem_euclid(256)).unwrap_or(255)
}

/// Record that `raised` happened while `handled` was being handled.
///
/// This is what puts the exception a handler was working on above the one the
/// handler went on to raise. Nothing a program writes reaches it: `__context__`
/// is set by the runtime at the moment of the raise, and `raise x from y` only
/// decides whether it is printed.
///
/// Two things it will not do, both of which are CPython's rules and both of
/// which exist to keep the chain a chain. A bare `raise` inside a handler
/// re-raises the exception being handled, and an exception is not raised while
/// handling itself, so that one is left alone. And an exception that is already
/// somewhere above `raised` in the chain has its link cut before the new one is
/// made, because a ring here is a traceback that never finishes printing.
pub fn raised_while_handling(raised: &Object, handled: &Object) {
    let (Some(new), Some(old)) = (raised.exception(), handled.exception()) else {
        return;
    };
    if std::ptr::eq(new, old) {
        return;
    }
    // Terminates because this is the only thing that ever writes a context and
    // it refuses to close a ring, so what it is walking is a chain.
    let mut at = handled.clone();
    loop {
        let next = {
            let Some(exception) = at.exception() else {
                break;
            };
            let Some(context) = exception.context() else {
                break;
            };
            if context
                .exception()
                .is_some_and(|link| std::ptr::eq(link, new))
            {
                *exception.context.borrow_mut() = None;
                break;
            }
            context
        };
        at = next;
    }
    *new.context.borrow_mut() = Some(handled.clone());
}

/// The same exception, put back on its way out.
///
/// Not [`raise`], although it fails the same way. What is put back was raised
/// once already and settled then what it was raised while handling, so none of
/// that is settled again: an `except` chain that matched nothing and the end of
/// a `finally` an exception reached are both the middle of one exception
/// leaving rather than the start of another.
///
/// The register this reads is one the interpreter filled at a handler, so what
/// is in it is always an exception. The other answer is there because
/// hand-written bytecode could put anything anywhere, and a `TypeError` is a
/// better thing to say about that than a panic.
#[must_use]
pub fn reraise(exc: &Object) -> Error {
    let Some(exception) = exc.exception() else {
        return Error::type_error("exceptions must derive from BaseException");
    };
    Error::new(exception.kind(), exception.message()).with_value(exc.clone())
}

/// What a `raise` statement raises.
///
/// The whole of the statement's meaning, which is worth having in one function
/// away from the interpreter because none of it depends on the interpreter:
/// what is raised is a value, what it is raised from is a value, and the answer
/// is an [`Error`] either way, including when the answer is that the program
/// raised something that is not an exception.
#[must_use]
pub fn raise(exc: Option<&Object>, cause: Option<&Object>) -> Error {
    let Some(exc) = exc else {
        // A bare `raise` re-raises whatever is being handled, and nothing can
        // be being handled until there is an `except` to handle it in. Until
        // then this is the only thing a bare `raise` can mean.
        return Error::new(Kind::RuntimeError, "No active exception to reraise");
    };
    let Some(raised) = instance_of(exc) else {
        return Error::type_error("exceptions must derive from BaseException");
    };
    // No `from` clause and `from None` both end up with nothing to record. They
    // are not the same statement, which is what the check below is about, but
    // they have the same cause and it is nothing.
    let from = match cause {
        None | Some(Object::None) => None,
        Some(cause) => match instance_of(cause) {
            Some(from) => Some(from),
            None => {
                return Error::type_error("exception causes must derive from BaseException");
            }
        },
    };

    let error = {
        let Some(exception) = raised.exception() else {
            unreachable!("what instance_of gives back is an exception or nothing")
        };
        // Only a written `from` touches the cause. `raise e` leaves whatever
        // the instance already had, which matters because it can be re-raising
        // one that was raised from something once already, and `from None` is
        // written precisely to take that away.
        if cause.is_some() {
            exception.raised_from(from);
        }
        Error::new(exception.kind(), exception.message())
    };
    error.with_value(raised)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn exception(kind: Kind, args: Vec<Object>) -> Exception {
        Exception::new(kind, args)
    }

    #[test]
    fn a_class_prints_the_way_a_class_does_and_an_instance_the_way_a_call_does() {
        assert_eq!(Class::new(Kind::ValueError).repr(), "<class 'ValueError'>");
        assert_eq!(Class::new(Kind::ValueError).type_name(), "type");
        assert_eq!(
            exception(Kind::ValueError, Vec::new()).repr(),
            "ValueError()"
        );
        assert_eq!(
            exception(Kind::ValueError, vec![Object::str("x")]).repr(),
            "ValueError('x')"
        );
        assert_eq!(
            exception(Kind::ValueError, vec![Object::int(1), Object::int(2)]).repr(),
            "ValueError(1, 2)"
        );
    }

    /// `str` and `repr` differ for an exception the way they do for a string,
    /// and for the same reason: one is for reading and one is for reading back.
    #[test]
    fn what_an_exception_says_is_its_arguments_rather_than_its_repr() {
        assert_eq!(exception(Kind::ValueError, Vec::new()).message(), "");
        assert_eq!(
            exception(Kind::ValueError, vec![Object::str("boom")]).message(),
            "boom"
        );
        assert_eq!(
            exception(Kind::ValueError, vec![Object::int(1), Object::int(2)]).message(),
            "(1, 2)"
        );
    }

    /// A `KeyError` whose key is a string prints the quotes, because the key
    /// `''` and the key `' '` are different keys and neither prints as
    /// anything without them.
    #[test]
    fn a_key_error_says_its_key_the_way_repr_would() {
        assert_eq!(
            exception(Kind::KeyError, vec![Object::str("k")]).message(),
            "'k'"
        );
        assert_eq!(
            exception(Kind::KeyError, vec![Object::str("")]).message(),
            "''"
        );
        // More than one argument is the tuple, for a `KeyError` like any other.
        assert_eq!(
            exception(Kind::KeyError, vec![Object::int(1), Object::int(2)]).message(),
            "(1, 2)"
        );
    }

    /// `except ArithmeticError` catches a `ZeroDivisionError` for the same
    /// reason `except ZeroDivisionError` does, which is that a class catches
    /// everything below it as well as itself.
    #[test]
    fn a_clause_catches_its_class_and_everything_under_it() {
        let raised = exception(Kind::ZeroDivisionError, Vec::new());
        for kind in [
            Kind::ZeroDivisionError,
            Kind::ArithmeticError,
            Kind::Exception,
            Kind::BaseException,
        ] {
            let test = Object::native(Class::new(kind));
            assert!(
                matches(&raised, &test).expect("a class is a clause"),
                "{kind}"
            );
        }
        let test = Object::native(Class::new(Kind::ValueError));
        assert!(!matches(&raised, &test).expect("a class is a clause"));
    }

    /// `except (A, B)` catches whatever either of them catches, and only one
    /// deep, because CPython used to allow a tuple inside a tuple and stopped.
    #[test]
    fn a_tuple_catches_what_any_of_its_members_catches() {
        let raised = exception(Kind::ValueError, Vec::new());
        let class = |kind| Object::native(Class::new(kind));
        let test = Object::tuple(vec![class(Kind::KeyError), class(Kind::ValueError)]);
        assert!(matches(&raised, &test).expect("a tuple is a clause"));

        let test = Object::tuple(vec![class(Kind::KeyError), class(Kind::TypeError)]);
        assert!(!matches(&raised, &test).expect("a tuple is a clause"));

        // Empty, which is a clause that catches nothing rather than a mistake.
        assert!(!matches(&raised, &Object::tuple(Vec::new())).expect("a tuple is a clause"));

        let nested = Object::tuple(vec![Object::tuple(vec![class(Kind::ValueError)])]);
        assert!(matches(&raised, &nested).is_err());
    }

    /// The mistake is in the handler rather than in what it was trying to
    /// catch, so it is a `TypeError` and not the exception that was raised.
    #[test]
    fn a_clause_that_names_something_that_is_not_a_class_says_so() {
        let raised = exception(Kind::ValueError, Vec::new());
        let error = matches(&raised, &Object::int(5)).expect_err("a number is not a clause");
        assert_eq!(
            error.to_string(),
            "TypeError: catching classes that do not inherit from BaseException is not allowed"
        );
        // An instance is not a class either, which is the mistake of writing
        // `except e` where `e` is what a previous handler bound.
        let instance = Object::native(exception(Kind::ValueError, Vec::new()));
        assert!(matches(&raised, &instance).is_err());
    }

    #[test]
    fn a_class_stands_for_an_instance_of_it_and_a_number_stands_for_nothing() {
        let class = Object::native(Class::new(Kind::ValueError));
        let made = instance_of(&class).expect("a class is something to raise");
        assert_eq!(made.repr(), "ValueError()");
        assert!(instance_of(&Object::int(5)).is_none());
        assert!(instance_of(&Object::None).is_none());
    }

    /// The instance a `raise` is handed is the instance it raises, rather than
    /// a copy that would fail an `is` against the original.
    #[test]
    fn an_instance_stands_for_itself() {
        let raised = Object::native(exception(Kind::ValueError, vec![Object::str("x")]));
        let again = instance_of(&raised).expect("an instance is something to raise");
        assert!(raised.is(&again));
    }

    #[test]
    fn every_builtin_class_is_bound_to_its_own_name() {
        let bound = classes();
        assert_eq!(bound.len(), Kind::ALL.len());
        for (name, value) in &bound {
            let class = value.downcast::<Class>().expect("a class is bound");
            assert_eq!(class.kind().name(), *name);
        }
    }

    /// The class and the instance are both accepted, and the message is what
    /// the last line of the traceback would say.
    #[test]
    fn raising_a_class_and_raising_an_instance_of_it_say_the_same_thing() {
        let class = Object::native(Class::new(Kind::ValueError));
        assert_eq!(raise(Some(&class), None).to_string(), "ValueError");
        let instance = Object::native(exception(Kind::ValueError, vec![Object::str("boom")]));
        assert_eq!(raise(Some(&instance), None).to_string(), "ValueError: boom");
    }

    #[test]
    fn raising_something_that_is_not_an_exception_says_so() {
        assert_eq!(
            raise(Some(&Object::int(5)), None).to_string(),
            "TypeError: exceptions must derive from BaseException"
        );
        let cause = Object::int(5);
        let raised = Object::native(exception(Kind::ValueError, Vec::new()));
        assert_eq!(
            raise(Some(&raised), Some(&cause)).to_string(),
            "TypeError: exception causes must derive from BaseException"
        );
    }

    /// A bare `raise` needs an exception to be being handled, and until there
    /// is an `except` there never is one.
    #[test]
    fn a_bare_raise_has_nothing_to_re_raise() {
        assert_eq!(
            raise(None, None).to_string(),
            "RuntimeError: No active exception to reraise"
        );
    }

    /// The chain prints oldest first, which is the order it happened in, and
    /// `from None` takes it away again.
    #[test]
    fn a_cause_prints_above_the_exception_it_caused() {
        let cause = Object::native(exception(Kind::KeyError, vec![Object::str("k")]));
        let raised = Object::native(exception(Kind::ValueError, vec![Object::str("boom")]));
        assert_eq!(
            raise(Some(&raised), Some(&cause)).to_string(),
            "KeyError: 'k'\n\nThe above exception was the direct cause of the \
             following exception:\n\nValueError: boom"
        );
        assert_eq!(
            raise(Some(&raised), Some(&Object::None)).to_string(),
            "ValueError: boom"
        );
    }

    /// Everything but a `SystemExit` is something to report, including the
    /// ones the runtime raised itself and so has no instance for.
    #[test]
    fn an_uncaught_exception_is_reported() {
        assert_eq!(
            uncaught(&Error::zero_division("division by zero")),
            Exit::Report("ZeroDivisionError: division by zero".to_owned())
        );
        let raised = Object::native(exception(Kind::ValueError, vec![Object::str("boom")]));
        assert_eq!(
            uncaught(&raise(Some(&raised), None)),
            Exit::Report("ValueError: boom".to_owned())
        );
    }

    /// A `SystemExit` given a number is a status, and a status is a byte, so
    /// 256 comes out a success and -1 comes out the 255 a shell prints.
    #[test]
    fn a_system_exit_given_a_number_is_that_status() {
        let status = |args: Vec<Object>| {
            let raised = Object::native(exception(Kind::SystemExit, args));
            uncaught(&raise(Some(&raised), None))
        };
        assert_eq!(status(Vec::new()), Exit::Status(0));
        assert_eq!(status(vec![Object::None]), Exit::Status(0));
        assert_eq!(status(vec![Object::int(3)]), Exit::Status(3));
        assert_eq!(status(vec![Object::int(256)]), Exit::Status(0));
        assert_eq!(status(vec![Object::int(-1)]), Exit::Status(255));
        // A bool is an int, so one of them is a failure and the other is not.
        assert_eq!(status(vec![Object::Bool(true)]), Exit::Status(1));
        assert_eq!(status(vec![Object::Bool(false)]), Exit::Status(0));
    }

    /// Anything that is not a number is a message, and several arguments are
    /// the tuple of them, which is what `SystemExit.code` is in that case.
    #[test]
    fn a_system_exit_given_anything_else_is_a_message() {
        let raised = Object::native(exception(Kind::SystemExit, vec![Object::str("no good")]));
        assert_eq!(
            uncaught(&raise(Some(&raised), None)),
            Exit::Report("no good".to_owned())
        );
        let pair = Object::native(exception(
            Kind::SystemExit,
            vec![Object::str("a"), Object::str("b")],
        ));
        assert_eq!(
            uncaught(&raise(Some(&pair), None)),
            Exit::Report("('a', 'b')".to_owned())
        );
    }

    /// The context is the exception the handler was already working on, and it
    /// prints above the new one under its own sentence rather than a cause's.
    #[test]
    fn what_was_being_handled_prints_above_what_was_raised_while_handling_it() {
        let handled = Object::native(exception(Kind::ValueError, vec![Object::str("a")]));
        let raised = Object::native(exception(Kind::KeyError, vec![Object::str("b")]));
        raised_while_handling(&raised, &handled);
        assert_eq!(
            raise(Some(&raised), None).to_string(),
            "ValueError: a\n\nDuring handling of the above exception, another \
             exception occurred:\n\nKeyError: 'b'"
        );
    }

    /// A `from` clause wins over a context, and writing one at all is what
    /// stops the context being printed, which is the whole of what `from None`
    /// means.
    #[test]
    fn a_cause_is_printed_instead_of_a_context_and_from_none_prints_neither() {
        let handled = Object::native(exception(Kind::ValueError, vec![Object::str("a")]));
        let cause = Object::native(exception(Kind::IndexError, vec![Object::str("i")]));
        let raised = Object::native(exception(Kind::KeyError, vec![Object::str("b")]));
        raised_while_handling(&raised, &handled);
        assert_eq!(
            raise(Some(&raised), Some(&cause)).to_string(),
            "IndexError: i\n\nThe above exception was the direct cause of the \
             following exception:\n\nKeyError: 'b'"
        );
        // The context is still there and still readable. What `from None` takes
        // away is the printing of it.
        assert_eq!(
            raise(Some(&raised), Some(&Object::None)).to_string(),
            "KeyError: 'b'"
        );
    }

    /// Nothing is raised while handling itself, which is what a bare `raise`
    /// and a `raise` of what a clause just caught both are.
    #[test]
    fn an_exception_is_not_the_context_of_itself() {
        let raised = Object::native(exception(Kind::ValueError, vec![Object::str("a")]));
        raised_while_handling(&raised, &raised);
        assert_eq!(raise(Some(&raised), None).to_string(), "ValueError: a");
    }

    /// An exception put back over the top of something that already records it
    /// would close a ring, so the older link is cut on the way past, however
    /// far up it is.
    #[test]
    fn making_a_context_cuts_whatever_link_would_close_a_ring() {
        let a = Object::native(exception(Kind::ValueError, vec![Object::str("a")]));
        let b = Object::native(exception(Kind::KeyError, vec![Object::str("b")]));
        let c = Object::native(exception(Kind::IndexError, vec![Object::str("c")]));
        raised_while_handling(&b, &a);
        raised_while_handling(&c, &b);
        // `c` has `b` which has `a`, and now `a` is raised while `c` is being
        // handled, so `b` loses its `a` and the chain is `b`, `c`, `a`.
        raised_while_handling(&a, &c);
        assert_eq!(
            raise(Some(&a), None).to_string(),
            "KeyError: 'b'\n\nDuring handling of the above exception, another \
             exception occurred:\n\nIndexError: c\n\nDuring handling of the \
             above exception, another exception occurred:\n\nValueError: a"
        );
    }

    /// Putting an exception back says the same thing raising it does, and
    /// leaves what it was raised while handling alone rather than settling it
    /// again.
    #[test]
    fn a_reraise_says_the_same_thing_and_settles_nothing_again() {
        let handled = Object::native(exception(Kind::ValueError, vec![Object::str("a")]));
        let raised = Object::native(exception(Kind::KeyError, vec![Object::str("b")]));
        raised_while_handling(&raised, &handled);
        let put_back = reraise(&raised);
        assert!(put_back.instance().is(&raised));
        assert_eq!(
            put_back.to_string(),
            "ValueError: a\n\nDuring handling of the above exception, another \
             exception occurred:\n\nKeyError: 'b'"
        );
    }

    /// `raise e from e` is a ring, and a printer that followed it would not
    /// come back. CPython prints it once, because the exception it is printing
    /// counts as already printed before it looks for a cause.
    #[test]
    fn an_exception_raised_from_itself_prints_once() {
        let raised = Object::native(exception(Kind::ValueError, vec![Object::str("x")]));
        assert_eq!(
            raise(Some(&raised), Some(&raised)).to_string(),
            "ValueError: x"
        );
    }
}