~cdv/loxen

ref: bba9ce3300c5bae29961fe8617fc0d173c430afe loxen/rs/src/chunk.rs -rw-r--r-- 6.5 KiB
bba9ce33Chris Vittal [relox] Many changes, notably, strings. 1 year, 5 months ago
                                                                                
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
use crate::value::Value;

#[derive(Debug, Default)]
pub struct Chunk {
    pub(crate) code: Vec<u8>,
    pub(crate) constants: Vec<Value>,
    lines: LineArray,
}

const MAX_CONSTANTS: usize = 0xffffff;

impl Chunk {
    pub fn write(&mut self, b: u8, line: u32) {
        let line_off: i32 = if self.lines.first_line == 0 {
            self.lines.first_line = line;
            0
        } else {
            line as i32 - self.lines.prev_line as i32
        };
        self.lines.prev_line = line;
        self.lines.push_line(line_off);
        self.code.push(b);
    }

    pub fn write_op(&mut self, op: Op, line: u32) {
        self.write(op as u8, line);
    }

    pub fn write_constant(&mut self, v: Value, line: u32) -> Result<(), &'static str> {
        let ind = self.add_const(v);
        if ind > MAX_CONSTANTS {
            return Err("too many constants in chunk");
        }
        if ind < u8::MAX as usize {
            self.write_op(Op::Constant, line);
            self.write(ind as u8, line);
        } else {
            self.write_op(Op::ConstantLong, line);
            self.write(ind as u8, line);
            self.write((ind >> 8) as u8, line);
            self.write((ind >> 16) as u8, line);
        }
        Ok(())
    }

    pub fn add_const(&mut self, v: Value) -> usize {
        self.constants.push(v);
        self.constants.len() - 1
    }

    #[cfg(debug_assertions)]
    pub fn disassemble(&self, name: &str) {
        use std::convert::TryFrom;
        eprintln!("=== {} (begin) ===", name);
        let mut off = 0;
        let mut prev_line = u32::MAX;
        while off < self.code.len() {
            match Op::try_from(self.code[off]) {
                Ok(v) => {
                    off = v.disassemble(&self, off, &mut prev_line);
                }
                Err(InvalidInstruction) => {
                    eprintln!("Unknown opcode {}", self.code[off]);
                    off += 1;
                }
            }
        }
        eprintln!("=== {} ( end ) ===", name);
    }

    pub fn get_line(&self, offset: usize) -> u32 {
        let mut addr: usize = 0;
        let mut line = self.lines.first_line as i32;
        for &LineOffset { byte_off, line_off } in &self.lines.array {
            addr += byte_off as usize;
            if addr > offset {
                break;
            }
            line = line.wrapping_add(line_off as i32)
        }
        line as u32
    }
}

impl<I: std::slice::SliceIndex<[u8]>> std::ops::Index<I> for Chunk {
    type Output = I::Output;
    #[inline]
    fn index(&self, i: I) -> &I::Output {
        self.code.index(i)
    }
}

macro_rules! op_codes {
    ($($name:ident, $const:ident, $pretty:expr;)*) => {
#[derive(Debug,Clone,Copy,PartialEq,Eq)]
#[repr(u8)]
pub enum Op {
    $($name,)*
}

#[derive(Debug)]
pub struct InvalidInstruction;

$(pub const $const: u8 = Op::$name as u8;)*

impl ::std::convert::TryFrom<u8> for Op {
    type Error = InvalidInstruction;
    fn try_from(b: u8) -> ::std::result::Result<Self, Self::Error> {
        match b {
            $($const => Ok(Op::$name),)*
            _ => Err(InvalidInstruction)
        }
    }
}

impl Into<u8> for Op {
    #[inline(always)]
    fn into(self) -> u8 {
        self as u8
    }
}

impl ::std::fmt::Display for Op {
    fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
        match self {
            $(Op::$name => f.pad($pretty),)*
        }
    }
}}
}

op_codes!(
    Return, OP_RETURN, "RETURN";
    Constant, OP_CONSTANT, "CONSTANT";
    ConstantLong, OP_CONSTANT_LONG, "CONSTANT_LONG";
    Nil, OP_NIL, "NIL";
    True, OP_TRUE, "TRUE";
    False, OP_FALSE, "FALSE";
    Equal, OP_EQUAL, "EQUAL";
    Greater, OP_GREATER, "GREATER";
    Less, OP_LESS, "LESS";
    Add, OP_ADD, "ADD";
    Sub, OP_SUBTRACT, "SUBTRACT";
    Mul, OP_MULTIPLY, "MULTIPLY";
    Div, OP_DIVIDE, "DIVIDE";
    Not, OP_NOT, "NOT";
    Negate, OP_NEGATE, "NEGATE";
);

impl Op {
    #[cfg(debug_assertions)]
    pub fn disassemble(&self, c: &Chunk, off: usize, prev_line: &mut u32) -> usize {
        use Op::*;
        let line = c.get_line(off);
        eprint!("{:04} ", off);
        if line == *prev_line {
            eprint!("   |  ");
        } else {
            eprint!("{:4}  ", line);
            *prev_line = line;
        }
        match self {
            Return | Nil | True | False | Equal | Greater | Less | Add | Sub | Mul | Div
            | Negate | Not => {
                eprintln!("{:16}", self);
                off + 1
            }
            Constant => {
                let cid = c.code[off + 1] as usize;
                eprintln!("{:16} {:4} '{}'", self, cid, c.constants[cid]);
                off + 2
            }
            ConstantLong => {
                let cid = (c.code[off + 1] as usize)
                    | (c.code[off + 2] as usize) << 8
                    | (c.code[off + 3] as usize) << 16;
                eprintln!("{:16} {:4} '{}'", self, cid, c.constants[cid]);
                off + 4
            }
        }
    }
}

#[derive(Debug, Clone)]
struct LineArray {
    array: Vec<LineOffset>,
    next_byte_off: usize,
    prev_line: u32,
    first_line: u32,
}

impl LineArray {
    fn push_line(&mut self, mut line_offset: i32) {
        use std::mem;
        self.next_byte_off = self.next_byte_off.wrapping_add(1);
        if line_offset == 0 {
            return;
        }
        while line_offset != 0 {
            let lo = if self.next_byte_off > u8::MAX as usize {
                self.next_byte_off -= u8::MAX as usize;
                LineOffset::new(u8::MAX, 0)
            } else {
                let btmp = mem::replace(&mut self.next_byte_off, 0) as u8;
                if line_offset < i8::MIN as i32 {
                    line_offset -= i8::MIN as i32;
                    LineOffset::new(btmp, i8::MIN)
                } else if line_offset > i8::MAX as i32 {
                    line_offset -= i8::MAX as i32;
                    LineOffset::new(btmp, i8::MAX)
                } else {
                    let ltmp = mem::replace(&mut line_offset, 0) as i8;
                    LineOffset::new(btmp, ltmp)
                }
            };
            self.array.push(lo)
        }
    }
}

impl Default for LineArray {
    fn default() -> Self {
        Self {
            array: Vec::new(),
            prev_line: 0,
            first_line: 0,
            next_byte_off: ::std::usize::MAX,
        }
    }
}

#[derive(Debug, Clone, Copy)]
struct LineOffset {
    byte_off: u8,
    line_off: i8,
}

impl LineOffset {
    fn new(byte_off: u8, line_off: i8) -> Self {
        Self { byte_off, line_off }
    }
}