pr47 0.1.4-CHARLIE

A semi-experimental programming language. Still working in progress.
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
use std::ptr::{addr_of_mut, NonNull, slice_from_raw_parts_mut};

use crate::data::Value;

#[cfg(debug_assertions)]
#[derive(Copy, Clone)]
pub struct StackSlice(*mut [Option<Value>]);

#[cfg(debug_assertions)]
impl StackSlice {
    pub unsafe fn set_value(&mut self, idx: usize, value: Value) {
        (*self.0)[idx].replace(value);
    }

    pub unsafe fn get_value(&self, idx: usize) -> Value {
        (*self.0)[idx].unwrap()
    }

    pub unsafe fn get_value_mut_ref(&self, idx: usize) -> *mut Value {
        // create empty, dummy value
        let value: &mut Value = (*self.0)[idx].get_or_insert(Value::new_null());
        value as *mut Value
    }
}

#[cfg(not(debug_assertions))]
#[derive(Copy, Clone)]
pub struct StackSlice(*mut Value);

#[cfg(not(debug_assertions))]
impl StackSlice {
    #[inline(always)] pub unsafe fn set_value(&mut self, idx: usize, value: Value) {
        let dest: &mut Value = &mut *self.0.add(idx);
        *dest = value;
    }

    #[inline(always)] pub unsafe fn get_value(&mut self, idx: usize) -> Value {
        *self.0.add(idx)
    }

    #[inline(always)] pub unsafe fn get_value_mut_ref(&self, idx: usize) -> *mut Value {
        self.0.add(idx)
    }
}

#[derive(Debug)]
pub struct FrameInfo {
    pub frame_start: usize,
    pub frame_end: usize,
    pub ret_value_locs: NonNull<[usize]>,
    pub ret_addr: usize,

    pub func_id: usize
}

impl FrameInfo {
    pub fn new(
        frame_start: usize,
        frame_end: usize,
        ret_value_locs: NonNull<[usize]>,
        ret_addr: usize,
        func_id: usize
    ) -> Self {
        Self {
            frame_start,
            frame_end,
            ret_value_locs,
            ret_addr,
            func_id
        }
    }
}

#[cfg(debug_assertions)]
pub struct Stack {
    pub values: Vec<Option<Value>>,
    pub frames: Vec<FrameInfo>
}

pub const EMPTY_RET_LOCS_SLICE: &[usize] = &[];

#[cfg(debug_assertions)]
impl Stack {
    pub fn new() -> Self {
        Self {
            values: Vec::with_capacity(64),
            frames: Vec::with_capacity(4)
        }
    }

    pub unsafe fn ext_func_call_grow_stack(
        &mut self,
        func_id: usize,
        frame_size: usize,
        args: &[Value]
    ) -> StackSlice {
        assert_eq!(self.values.len(), 0);
        assert_eq!(self.frames.len(), 0);

        self.values.resize(frame_size, None);
        for (i /*: usize*/, arg /*: &Value*/) in args.iter().enumerate() {
            self.values[i].replace(*arg);
        }
        self.frames.push(FrameInfo::new(
            0, frame_size, NonNull::from(EMPTY_RET_LOCS_SLICE), 0, func_id
        ));
        StackSlice(&mut self.values[..] as *mut [Option<Value>])
    }

    pub unsafe fn func_call_grow_stack(
        &mut self,
        func_id: usize,
        frame_size: usize,
        arg_locs: &[usize],
        ret_value_locs: NonNull<[usize]>,
        ret_addr: usize
    ) -> StackSlice {
        let this_frame: &FrameInfo = self.frames.last().unwrap();
        let (this_frame_start, this_frame_end): (usize, usize)
            = (this_frame.frame_start, this_frame.frame_end);

        assert_eq!(this_frame_end, self.values.len());
        let new_frame_end: usize = this_frame_end + frame_size;
        self.values.resize(new_frame_end, None);
        self.frames.push(
            FrameInfo::new(this_frame_end, new_frame_end, ret_value_locs, ret_addr, func_id)
        );

        let old_slice: StackSlice =
            StackSlice(slice_from_raw_parts_mut(
                self.values.as_mut_ptr().add(this_frame_start),
                this_frame_end - this_frame_start
            ));
        let mut new_slice: StackSlice =
            StackSlice(slice_from_raw_parts_mut(
                self.values.as_mut_ptr().add(this_frame_end),
                frame_size
            ));
        for (i /*: usize*/, arg_loc/*: &usize*/) in arg_locs.iter().enumerate() {
            new_slice.set_value(i, old_slice.get_value(*arg_loc));
        }
        new_slice
    }

    pub unsafe fn closure_call_grow_stack(
        &mut self,
        func_id: usize,
        frame_size: usize,
        captures: &[Value],
        arg_locs: &[usize],
        ret_value_locs: NonNull<[usize]>,
        ret_addr: usize
    ) -> StackSlice {
        let this_frame: &FrameInfo = self.frames.last().unwrap();
        let (this_frame_start, this_frame_end): (usize, usize)
            = (this_frame.frame_start, this_frame.frame_end);

        assert_eq!(this_frame_end, self.values.len());
        let new_frame_end: usize = this_frame_end + frame_size;
        self.values.resize(new_frame_end, None);
        self.frames.push(
            FrameInfo::new(this_frame_end, new_frame_end, ret_value_locs, ret_addr, func_id)
        );
        let old_slice: StackSlice =
            StackSlice(&mut self.values[this_frame_start..this_frame_end] as *mut _);
        let mut new_slice: StackSlice =
            StackSlice(&mut self.values[this_frame_end..new_frame_end] as *mut _);
        for (i /*: usize*/, &capture /*: Value*/) in captures.iter().enumerate() {
            new_slice.set_value(i, capture);
        }
        for (i /*: usize*/, arg_loc /*: &usize*/) in arg_locs.iter().enumerate() {
            new_slice.set_value(i + captures.len(), old_slice.get_value(*arg_loc));
        }
        new_slice
    }

    pub unsafe fn done_func_call_shrink_stack0(&mut self) -> Option<(StackSlice, usize)> {
        self.done_func_call_shrink_stack(&[])
    }

    pub unsafe fn done_func_call_shrink_stack1(
        &mut self,
        ret_value_src: usize
    ) -> Option<(StackSlice, usize)> {
        self.done_func_call_shrink_stack(&[ret_value_src])
    }

    pub unsafe fn done_func_call_shrink_stack(
        &mut self,
        ret_values: &[usize]
    ) -> Option<(StackSlice, usize)> {
        let frame_count: usize = self.frames.len();
        if frame_count == 1 {
            return None;
        }

        let this_frame: &FrameInfo = &self.frames[frame_count - 1];
        let prev_frame: &FrameInfo = &self.frames[frame_count - 2];
        assert_eq!(prev_frame.frame_end, this_frame.frame_start);
        let this_slice: StackSlice = StackSlice(slice_from_raw_parts_mut(
            self.values.as_mut_ptr().add(this_frame.frame_start),
            this_frame.frame_end - this_frame.frame_start
        ));
        let mut prev_slice: StackSlice = StackSlice(slice_from_raw_parts_mut(
            self.values.as_mut_ptr().add(prev_frame.frame_start),
            prev_frame.frame_end - prev_frame.frame_start
        ));

        assert_eq!(ret_values.len(), this_frame.ret_value_locs.as_ref().len());
        for (ret_value /*: &usize*/, ret_value_loc /*: &usize*/) in
            ret_values.iter().zip(this_frame.ret_value_locs.as_ref().iter())
        {
            prev_slice.set_value(*ret_value_loc, this_slice.get_value(*ret_value))
        }

        let ret_addr: usize = this_frame.ret_addr;
        self.values.truncate(prev_frame.frame_end);
        self.frames.pop().unwrap();
        Some((prev_slice, ret_addr))
    }

    pub unsafe fn last_frame_slice(&mut self) -> StackSlice {
        let frame: &FrameInfo = self.frames.last().unwrap_unchecked();
        StackSlice(&mut self.values[frame.frame_start..frame.frame_end] as *mut _)
    }

    pub unsafe fn unwind_shrink_slice(&mut self) {
        let frame: FrameInfo = self.frames.pop().unwrap_unchecked();
        self.values.truncate(frame.frame_start);
    }
}

#[cfg(any(feature = "bench", test))]
impl Stack {
    pub fn trace(&self) {
        eprintln!("[STACK-TRACE] Begin stack tracing");
        eprintln!("[STACK-TRACE] {{");
        for (i, frame) /*: (usize, &FrameInfo)*/ in self.frames.iter().enumerate() {
            eprintln!("[STACK-TRACE]     <frame {}: size = {}, ret_addr = {}, ret_val_locs = {:?}>",
                      i,
                      frame.frame_end - frame.frame_start,
                      frame.ret_addr,
                      unsafe { frame.ret_value_locs.as_ref() });
            eprintln!("[STACK-TRACE]     [");
            #[cfg(debug_assertions)]
            for i /*: usize*/ in frame.frame_start..frame.frame_end {
                if let Some(value /*: &Value*/) = &self.values[i] {
                    eprintln!("[STACK-TRACE]         [{}] = {:?}", i - frame.frame_start, value);
                } else {
                    eprintln!("[STACK-TRACE]         [{}] = UNINIT", i - frame.frame_start);
                }
            }
            #[cfg(not(debug_assertions))]
            for i /*: usize*/ in frame.frame_start..frame.frame_end {
                let value: &Value = &self.values[i];
                eprintln!("[STACK-TRACE]         [{}] = {:?}", i - frame.frame_start, value);
            }
            eprintln!("[STACK-TRACE]     ]");
        }
        eprintln!("[STACK-TRACE] }}");
        eprintln!("[STACK-TRACE] End stack tracing");
    }
}

#[cfg(not(debug_assertions))]
pub struct Stack {
    pub values: Vec<Value>,
    pub frames: Vec<FrameInfo>
}

#[cfg(not(debug_assertions))]
impl Stack {
    pub fn new() -> Self {
        Self {
            values: Vec::with_capacity(64),
            frames: Vec::with_capacity(4)
        }
    }

    pub unsafe fn ext_func_call_grow_stack(
        &mut self,
        func_id: usize,
        frame_size: usize,
        args: &[Value]
    ) -> StackSlice {
        self.values.resize(frame_size, Value::new_null());
        for (i /*: usize*/, arg /*: &Value*/) in args.iter().enumerate() {
            let dest: &mut Value = self.values.get_unchecked_mut(i);
            *dest = *arg;
        }
        self.frames.push(FrameInfo::new(
            0, frame_size, NonNull::from(EMPTY_RET_LOCS_SLICE), 0, func_id)
        );
        StackSlice(self.values.as_mut_ptr())
    }

    pub unsafe fn func_call_grow_stack(
        &mut self,
        func_id: usize,
        frame_size: usize,
        arg_locs: &[usize],
        ret_value_locs: NonNull<[usize]>,
        ret_addr: usize
    ) -> StackSlice {
        let this_frame: &FrameInfo = self.frames.last().unwrap_unchecked();
        let (this_frame_start, this_frame_end): (usize, usize)
            = (this_frame.frame_start, this_frame.frame_end);
        let new_frame_end: usize = this_frame_end + frame_size;
        self.values.resize(new_frame_end, Value::new_null());
        self.frames.push(
            FrameInfo::new(this_frame_end, new_frame_end, ret_value_locs, ret_addr, func_id)
        );
        let old_slice_ptr: *mut Value = self.values.as_mut_ptr().add(this_frame_start);
        let new_slice_ptr: *mut Value = self.values.as_mut_ptr().add(this_frame_end);

        for i /*: usize*/ in 0..arg_locs.len() {
            let arg_loc: usize = *arg_locs.get_unchecked(i);
            *new_slice_ptr.add(i) = *old_slice_ptr.add(arg_loc);
        }
        StackSlice(new_slice_ptr)
    }

    pub unsafe fn closure_call_grow_stack(
        &mut self,
        func_id: usize,
        frame_size: usize,
        captures: &[Value],
        arg_locs: &[usize],
        ret_value_locs: NonNull<[usize]>,
        ret_addr: usize
    ) -> StackSlice {
        let this_frame: &FrameInfo = self.frames.last().unwrap_unchecked();
        let (this_frame_start, this_frame_end): (usize, usize)
            = (this_frame.frame_start, this_frame.frame_end);
        let new_frame_end: usize = this_frame_end + frame_size;
        self.values.resize(new_frame_end, Value::new_null());
        self.frames.push(
            FrameInfo::new(this_frame_end, new_frame_end, ret_value_locs, ret_addr, func_id)
        );
        let old_slice_ptr: *mut Value = self.values.as_mut_ptr().add(this_frame_start);
        let new_slice_ptr: *mut Value = self.values.as_mut_ptr().add(this_frame_end);

        let captures_len: usize = captures.len();
        for i in 0..captures_len {
            *new_slice_ptr.add(i) = *captures.get_unchecked(i);
        }
        for i /*: usize*/ in 0..arg_locs.len() {
            let arg_loc: usize = *arg_locs.get_unchecked(i);
            *new_slice_ptr.add(i + captures_len) = *old_slice_ptr.add(arg_loc);
        }
        StackSlice(new_slice_ptr)
    }

    #[inline] pub unsafe fn done_func_call_shrink_stack0(&mut self) -> Option<(StackSlice, usize)> {
        let frame_count = self.frames.len();
        if frame_count == 1 {
            return None;
        }

        let this_frame: &FrameInfo = self.frames.get_unchecked(frame_count - 1);
        let prev_frame: &FrameInfo = self.frames.get_unchecked(frame_count - 2);
        let prev_slice_ptr: *mut Value = self.values.as_mut_ptr().add(prev_frame.frame_start);

        let ret_addr: usize = this_frame.ret_addr;
        self.values.truncate(prev_frame.frame_end);
        self.frames.pop().unwrap_unchecked();
        Some((StackSlice(prev_slice_ptr), ret_addr))
    }

    #[inline] pub unsafe fn done_func_call_shrink_stack1(
        &mut self,
        ret_value_src: usize
    ) -> Option<(StackSlice, usize)> {
        let frame_count = self.frames.len();
        if frame_count == 1 {
            return None;
        }

        let this_frame: &FrameInfo = self.frames.get_unchecked(frame_count - 1);
        let prev_frame: &FrameInfo = self.frames.get_unchecked(frame_count - 2);

        let this_slice_ptr = self.values.as_ptr().add(this_frame.frame_start);
        let prev_slice_ptr = self.values.as_mut_ptr().add(prev_frame.frame_start);

        let ret_value_loc: usize = *this_frame.ret_value_locs.as_ref().get_unchecked(0);
        *prev_slice_ptr.add(ret_value_loc) = *this_slice_ptr.add(ret_value_src);

        let ret_addr: usize = this_frame.ret_addr;
        self.values.truncate(prev_frame.frame_end);
        self.frames.pop().unwrap_unchecked();
        Some((StackSlice(prev_slice_ptr), ret_addr))
    }

    pub unsafe fn done_func_call_shrink_stack(
        &mut self,
        ret_values: &[usize]
    ) -> Option<(StackSlice, usize)> {
        let frame_count = self.frames.len();
        if frame_count == 1 {
            return None;
        }

        let this_frame: &FrameInfo = self.frames.get_unchecked(frame_count - 1);
        let prev_frame: &FrameInfo = self.frames.get_unchecked(frame_count - 2);
        let this_slice_ptr: *mut Value = self.values.as_mut_ptr().add(this_frame.frame_start);
        let prev_slice_ptr: *mut Value = self.values.as_mut_ptr().add(prev_frame.frame_start);

        let len: usize = ret_values.len();
        for i /*: usize*/ in 0..len {
            let ret_value_loc: usize = *this_frame.ret_value_locs.as_ref().get_unchecked(i);
            let ret_value_src: usize = *ret_values.get_unchecked(i);
            *prev_slice_ptr.add(ret_value_loc) = *this_slice_ptr.add(ret_value_src);
        }

        let ret_addr: usize = this_frame.ret_addr;
        self.values.truncate(prev_frame.frame_end);
        self.frames.pop().unwrap_unchecked();
        Some((StackSlice(prev_slice_ptr), ret_addr))
    }

    #[inline] pub unsafe fn last_frame_slice(&mut self) -> StackSlice {
        let frame: &FrameInfo = self.frames.last().unwrap_unchecked();
        StackSlice(self.values.as_mut_ptr().add(frame.frame_start))
    }

    #[inline] pub unsafe fn unwind_shrink_slice(&mut self) {
        let frame: FrameInfo = self.frames.pop().unwrap_unchecked();
        self.values.truncate(frame.frame_start);
    }
}