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
use crate::{
codemap::{CodeMap, FileSpan, Span},
errors::Frame,
values::{ControlError, Trace, Tracer, Value},
};
use gazebo::prelude::*;
use std::{fmt, fmt::Debug};
#[derive(Clone, Copy, Dupe)]
struct CheapFrame<'v> {
function: Value<'v>,
file: Option<&'v CodeMap>,
span: Span,
}
impl CheapFrame<'_> {
fn location(&self) -> Option<FileSpan> {
self.file.map(|file| FileSpan {
file: file.dupe(),
span: self.span,
})
}
fn to_frame(&self) -> Frame {
Frame {
name: self.function.to_repr(),
location: self.location(),
}
}
}
impl Debug for CheapFrame<'_> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut x = f.debug_struct("Frame");
x.field("function", &self.function);
x.field("span", &self.span);
x.field("file", &self.file);
x.finish()
}
}
#[derive(Debug)]
pub(crate) struct CallStack<'v> {
count: usize,
stack: [CheapFrame<'v>; MAX_CALLSTACK_RECURSION],
}
impl<'v> Default for CallStack<'v> {
fn default() -> Self {
Self {
count: 0,
stack: [CheapFrame {
function: Value::new_none(),
file: None,
span: Span::default(),
}; MAX_CALLSTACK_RECURSION],
}
}
}
const MAX_CALLSTACK_RECURSION: usize = 40;
unsafe impl<'v> Trace<'v> for CallStack<'v> {
fn trace(&mut self, tracer: &Tracer<'v>) {
for x in self.stack[0..self.count].iter_mut() {
x.function.trace(tracer);
}
for x in self.stack[self.count..].iter_mut() {
x.function = Value::new_none();
x.file = None;
}
}
}
impl<'v> CallStack<'v> {
pub(crate) fn push(
&mut self,
function: Value<'v>,
span: Span,
file: Option<&'v CodeMap>,
) -> anyhow::Result<()> {
if self.count >= MAX_CALLSTACK_RECURSION {
return Err(ControlError::TooManyRecursionLevel.into());
}
self.stack[self.count] = CheapFrame {
function,
file,
span,
};
self.count += 1;
Ok(())
}
pub(crate) fn pop(&mut self) {
debug_assert!(self.count >= 1);
self.count -= 1;
}
pub fn top_location(&self) -> Option<FileSpan> {
if self.count == 0 {
None
} else {
self.stack[self.count - 1].location()
}
}
pub fn to_diagnostic_frames(&self) -> Vec<Frame> {
self.stack[1..self.count].map(CheapFrame::to_frame)
}
pub(crate) fn to_function_values(&self) -> Vec<Value<'v>> {
self.stack[1..self.count].map(|x| x.function)
}
}