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
//! Representation of the operand bytes

use std::fmt;
use super::instruction::Instruction;

/// Bit offset for the destination byte
pub const DESTINATION_OFFSET: u32 = 8;
/// Bit offset for the first source byte
pub const FIRST_SOURCE_OFFSET: u32 = 16;
/// Bit offset for the second source byte
pub const SECOND_SOURCE_OFFSET: u32 = 24;
/// Bit offset for an instruction pointer (2 bytes)
///
/// Used by the jump family of instructions.
pub const INSTRUCTION_POINTER_OFFSET: u32 = 16;

/// Ability for a type to be the destination byte in an instruction
pub trait AsDestination {
  fn as_destination(self) -> Instruction;
}

/// Ability for a type to be created from an instruction destination
pub trait FromDestination {
  fn from_destination(instruction: Instruction) -> Self;
}

/// Ability for a type to be either of the source bytes in an instruction
pub trait AsSource {
  fn as_first(self) -> Instruction;
  fn as_second(self) -> Instruction;
}

/// Ability for a type to be created from an instruction source
pub trait FromSource {
  fn from_first(instruction: Instruction) -> Self;
  fn from_second(instruction: Instruction) -> Self;
}

impl<L: AsSource, R: AsSource> AsSource for either::Either<L, R> {
  fn as_first(self) -> Instruction {
    either::for_both!(self, inner => inner.as_first())
  }
  fn as_second(self) -> Instruction {
    either::for_both!(self, inner => inner.as_second())
  }
}

impl<L: AsDestination, R: AsDestination> AsDestination for either::Either<L, R> {
  fn as_destination(self) -> Instruction {
    either::for_both!(self, inner => inner.as_destination())
  }
}

/// Types that can be used as a register
pub trait Register: AsSource + AsDestination + Clone + fmt::Display { }

/// Register with a known register number
#[derive(Debug, Copy, Clone)]
#[repr(transparent)]
pub struct RawRegister(pub u8);

impl fmt::Display for RawRegister {
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    write!(f, "R{}", self.0)
  }
}

impl Register for RawRegister { }

impl AsDestination for RawRegister {
  fn as_destination(self) -> Instruction {
    Instruction((self.0 as u32) << DESTINATION_OFFSET)
  }
}

impl AsSource for RawRegister {
  fn as_first(self) -> Instruction {
    Instruction((self.0 as u32) << FIRST_SOURCE_OFFSET)
  }
  fn as_second(self) -> Instruction {
    Instruction((self.0 as u32) << SECOND_SOURCE_OFFSET)
  }
}

impl FromDestination for RawRegister {
  fn from_destination(instruction: Instruction) -> Self {
    Self((instruction.0 >> DESTINATION_OFFSET) as u8)
  }
}

impl FromSource for RawRegister {
  fn from_first(instruction: Instruction) -> Self {
    Self((instruction.0 >> FIRST_SOURCE_OFFSET) as u8)
  }
  fn from_second(instruction: Instruction) -> Self {
    Self((instruction.0 >> SECOND_SOURCE_OFFSET) as u8)
  }
}

/// TODO
#[derive(Debug, Copy, Clone)]
#[repr(transparent)]
pub struct Global(pub u8);

impl fmt::Display for Global {
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    write!(f, "G{}", self.0)
  }
}

impl AsDestination for Global {
  fn as_destination(self) -> Instruction {
    Instruction((self.0 as u32) << DESTINATION_OFFSET)
  }
}

impl FromDestination for Global {
  fn from_destination(instruction: Instruction) -> Self {
    Global((instruction.0 >> DESTINATION_OFFSET) as u8)
  }
}

impl AsSource for Global {
  fn as_first(self) -> Instruction {
    Instruction((self.0 as u32) << FIRST_SOURCE_OFFSET)
  }
  fn as_second(self) -> Instruction {
    Instruction((self.0 as u32) << SECOND_SOURCE_OFFSET)
  }
}

impl FromSource for Global {
  fn from_first(instruction: Instruction) -> Self {
    Global((instruction.0 >> FIRST_SOURCE_OFFSET) as u8)
  }
  fn from_second(instruction: Instruction) -> Self {
    Global((instruction.0 >> SECOND_SOURCE_OFFSET) as u8)
  }
}

/// Integer literal small enough to fit into a single signed byte
///
/// Values must be in the range `-128..=127` to be an immediate.  Immediates are
/// embedded directly into an operand byte of an [`Instruction`].
///
/// Integers outside this range and other literal types like double-precision floats
/// and strings must use [`ConstantKey`].
#[derive(Debug, Copy, Clone)]
#[repr(transparent)]
pub struct Immediate(pub i8);

impl fmt::Display for Immediate {
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    write!(f, "#{}", self.0)
  }
}

impl AsSource for Immediate {
  fn as_first(self) -> Instruction {
    Instruction((self.0 as u32) << FIRST_SOURCE_OFFSET)
  }
  fn as_second(self) -> Instruction {
    Instruction((self.0 as u32) << SECOND_SOURCE_OFFSET)
  }
}

impl FromSource for Immediate {
  fn from_first(instruction: Instruction) -> Self {
    Immediate((instruction.0 >> FIRST_SOURCE_OFFSET) as u8 as i8)
  }
  fn from_second(instruction: Instruction) -> Self {
    Immediate((instruction.0 >> SECOND_SOURCE_OFFSET) as u8 as i8)
  }
}

/// A key into a function's constant table
///
/// Used for integer literals outsize the range of `-127..=128` and other literal types.
/// A compiled function, [`Procedure`], has a field holding a table of [`ConstantValue`]s.
/// A `ConstantKey` is an index into this table.
///
/// [`Procedure`]: crate::bytecode::Procedure
/// [`ConstantValue`]: crate::bytecode::constant_value::ConstantValue
#[derive(Debug, Copy, Clone)]
#[repr(transparent)]
pub struct ConstantKey(pub u8);

impl fmt::Display for ConstantKey {
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    // TODO: find a better way to forward format args
    format!("&{}", self.0).fmt(f)
  }
}

impl AsSource for ConstantKey {
  fn as_first(self) -> Instruction {
    Instruction((self.0 as u32) << FIRST_SOURCE_OFFSET)
  }
  fn as_second(self) -> Instruction {
    Instruction((self.0 as u32) << SECOND_SOURCE_OFFSET)
  }
}

impl FromSource for ConstantKey {
  fn from_first(instruction: Instruction) -> Self {
    ConstantKey((instruction.0 >> FIRST_SOURCE_OFFSET) as u8)
  }
  fn from_second(instruction: Instruction) -> Self {
    ConstantKey((instruction.0 >> SECOND_SOURCE_OFFSET) as u8)
  }
}

/// Wildcard destination operand (register or global)
#[derive(Debug, Clone)]
pub enum WildDestination<R: Register> {
  Register(R),
  Global(Global),
}

impl<R: Register> From<R> for WildDestination<R> {
  fn from(register: R) -> Self {
    Self::Register(register)
  }
}

impl<R: Register> From<Global> for WildDestination<R> {
  fn from(global: Global) -> Self {
    Self::Global(global)
  }
}

impl<R: Register> fmt::Display for WildDestination<R> {
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    use WildDestination::*;
    match self {
      Register(register) => write!(f, "{register}"),
      Global(global) => write!(f, "{global}"),
    }
  }
}

impl<R: Register> AsDestination for WildDestination<R> {
  fn as_destination(self) -> Instruction {
    use WildDestination::*;
    match self {
      Register(register) => register.as_destination(),
      Global(global) => global.as_destination(),
    }
  }
}

/// Wildcard source operand (register, global, immediate, or constant)
#[derive(Debug, Clone)]
pub enum WildSource<R: Register> {
  Register(R),
  Global(Global),
  Immediate(Immediate),
  Constant(ConstantKey),
}

impl<R: Register> From<R> for WildSource<R> {
  fn from(register: R) -> Self {
    Self::Register(register)
  }
}

impl<R: Register> From<Global> for WildSource<R> {
  fn from(global: Global) -> Self {
    Self::Global(global)
  }
}

impl<R: Register> From<Immediate> for WildSource<R> {
  fn from(immediate: Immediate) -> Self {
    Self::Immediate(immediate)
  }
}

impl<R: Register> From<ConstantKey> for WildSource<R> {
  fn from(constant: ConstantKey) -> Self {
    Self::Constant(constant)
  }
}

impl<R: Register> fmt::Display for WildSource<R> {
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    use WildSource::*;
    match self {
      Register(register) => write!(f, "{register}"),
      Global(global) => write!(f, "{global}"),
      Immediate(immediate) => write!(f, "{immediate}"),
      Constant(constant) => write!(f, "{constant}"),
    }
  }
}

impl<R: Register> AsSource for WildSource<R> {
  fn as_first(self) -> Instruction {
    use WildSource::*;
    match self {
      Register(register) => register.as_first(),
      Global(global) => global.as_first(),
      Immediate(immediate) => immediate.as_first(),
      Constant(constant) => constant.as_first(),
    }
  }
  fn as_second(self) -> Instruction {
    use WildSource::*;
    match self {
      Register(register) => register.as_second(),
      Global(global) => global.as_second(),
      Immediate(immediate) => immediate.as_second(),
      Constant(constant) => constant.as_second(),
    }
  }
}

/// An index into the bytecode array
///
/// A 16 bit unsigned integer taking up both source operand bytes.  It is used by the
/// jump family of instructions under [misc](../opcode/misc/index.html).
///
/// Instruction pointers are always an absolute offset from the beginning of a
/// function's bytecode.  Setting a jump's instruction pointer target to be outside the
/// bounds of the function's bytecode will cause a [`RuntimeError`] in the
/// [`VirtualMachine`].  Runtime errors are safe and recoverable by host code, but hault
/// client code running in a virtual machine when they are encountered.
///
/// [`RuntimeError`]: crate::runtime::RuntimeError
/// [`VirtualMachine`]: crate::runtime::VirtualMachine
#[derive(Debug, Copy, Clone)]
#[repr(transparent)]
pub struct InstructionPointer(pub u16);

impl InstructionPointer {
  pub fn empty_place_holder() -> Self {
    InstructionPointer(0)
  }
  pub fn as_both_operands(self) -> Instruction {
    Instruction((self.0 as u32) << INSTRUCTION_POINTER_OFFSET)
  }
  pub fn from_both_operands(instruction: Instruction) -> Self {
    InstructionPointer((instruction.0 >> FIRST_SOURCE_OFFSET & 0x_ff_ff) as u16)
  }
}

impl fmt::Display for InstructionPointer {
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    write!(f, "ip ")?;
    self.0.fmt(f)
  }
}

/// A key into a function table
///
/// Each compiled function has a list of other functions it refers to.  A `FunctionKey`
/// is an index into this list.  `FunctionKey`s are currently only used by the call
/// instruction under [misc](../opcode/misc/index.html).
#[derive(Debug, Copy, Clone)]
#[repr(transparent)]
pub struct FunctionKey(pub u8);

impl FunctionKey {
  pub fn as_first(self) -> Instruction {
    Instruction((self.0 as u32) << FIRST_SOURCE_OFFSET)
  }
  pub fn from_first(instruction: Instruction) -> Self {
    FunctionKey((instruction.0 >> FIRST_SOURCE_OFFSET & 0xff) as u8)
  }
}

impl fmt::Display for FunctionKey {
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    format!("F{}", self.0).fmt(f)
  }
}