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
//! Source code mappings, [`Location`]s, printing stacktraces

use serde::{
    Deserialize,
    Serialize,
};

use crate::prelude::*;
use crate::{
    Exception,
    Heap,
    Interpreted,
    JSObject,
    JSValue,
};

const CALLER_LOCATION: &str = "[[caller_location]]";

#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
pub struct Position {
    line: u32,
    column: u32,
}

impl Position {
    pub fn new(line: u32, column: u32) -> Position {
        Position { line, column }
    }
}

#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
pub struct Location {
    start: Position,
    end: Position,
}

impl Location {
    pub fn new(start: Position, end: Position) -> Location {
        Location { start, end }
    }

    fn from_saved(object: &JSObject, heap: &Heap) -> Result<Location, Exception> {
        if let Some(array) = object.as_array() {
            let line = array.storage[0].numberify(heap).unwrap() as u32;
            let column = array.storage[1].numberify(heap).unwrap() as u32;
            let start = Position { line, column };

            let line = array.storage[2].numberify(heap).unwrap() as u32;
            let column = array.storage[3].numberify(heap).unwrap() as u32;
            let end = Position { line, column };

            Ok(Location { start, end })
        } else {
            Err(Exception::TypeErrorNotArraylike(Interpreted::VOID))
        }
    }
}

#[derive(Clone, Debug)]
pub struct Document {
    _name: String,
}

pub fn save_caller(caller: Option<Box<Location>>, heap: &mut Heap) -> Result<(), Exception> {
    if let Some(loc) = caller {
        let array = vec![
            JSValue::from(loc.start.line as f64),
            JSValue::from(loc.start.column as f64),
            JSValue::from(loc.end.line as f64),
            JSValue::from(loc.end.column as f64),
        ];
        let loc_ref = heap.alloc(JSObject::from_array(array));
        heap.scope_mut()
            .set_system(CALLER_LOCATION.into(), loc_ref)?;
    }
    Ok(())
}

/// Usage: `println!("{}", Callstack { heap} );`
struct Callstack<'heap> {
    heap: &'heap Heap,
}

impl<'heap> fmt::Display for Callstack<'heap> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self.heap.loc.as_ref() {
            None => return Ok(()),
            Some(loc) => writeln!(f, "Thrown at: {:?}", loc)?,
        };

        let mut scoperef = self.heap.local_scope().unwrap_or(Heap::NULL);
        while scoperef != Heap::NULL {
            if let Some(val) = self.heap.get(scoperef).get_own_value(CALLER_LOCATION) {
                let loc_ref = val.to_ref().map_err(|_| fmt::Error)?;
                match Location::from_saved(self.heap.get(loc_ref), self.heap) {
                    Ok(loc) => writeln!(f, "   {:?}", loc)?,
                    Err(err) => writeln!(f, "   ??? ({:?})", err)?,
                }
            };

            scoperef = match self.heap.get(scoperef).get_own_value(Heap::SAVED_SCOPE) {
                Some(v) => v.to_ref().unwrap_or(Heap::NULL),
                None => Heap::NULL,
            };
        }

        Ok(())
    }
}

#[cfg(feature = "std")]
pub fn print_callstack(heap: &Heap) -> Result<(), Exception> {
    use std::io::Write;

    let callstack = Callstack { heap };
    let mut stderr = std::io::stderr();
    write!(&mut stderr, "{}", callstack).map_err(|e| {
        let msg = format!("Error while printing callstack: {}", e);
        Exception::UserThrown(JSValue::from(msg))
    })
}

#[cfg(not(feature = "std"))]
pub fn print_callstack(_heap: &Heap) -> Result<(), Exception> {
    unimplemented!()
}