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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
//! This module contains the virtual machine which executes Strontium bytecode. The VM uses a set of typed 
//! registers to do number arithmetic, and a memory vector provides the storage space for anything else.

use crate::types::{MemoryAddress, Location};

pub mod memory;
pub mod instruction;

use self::memory::Memory;
use self::instruction::{
	Instruction,
	Instruction::*,
	MemoryMethod, 
	ComparisonMethod, 
	CalculationMethod, 
	Interrupt,
};

use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};

/*/// A set of signed and unsigned integers and floating point values
#[derive(Debug)]
pub struct Registers {
	pub int:   [i64; 32],
	pub uint:  [u64; 32],
	pub float: [f64; 32],
}
impl Registers {
	pub fn new() -> Self {
		Self {
			int:   [0; 32],
			uint:  [0; 32],
			float: [0.0; 32],
		}
	}
}*/

#[derive(Debug, PartialEq)]
pub enum StrontiumError {
	/// A division by zero has occured.
	DivisionByZero,
	/// An invalid memory or register address has been accessed.
	OutOfBounds,
	Other(String),
}

const NUM_REGISTERS: usize = 64;


pub struct Strontium {
	/// Holds 64 64-bit floating point values
	pub registers: [f64; NUM_REGISTERS],
	/// Models memory as a vector of bytes. This structure holds program-related data,
	/// and will probably be replaced by a more complex, paged structure later on
	pub memory:    Memory,
	/// Contains the parsed bytecode
	pub program:   Vec<Instruction>,
	/// Our current position in the program
	pub index:     usize,
	/// Contains references for function arguments and return values
	pub call_stack:    Vec<MemoryAddress>,
}

impl Strontium {
	/// Create a new instance of the virtual machine
	pub fn new() -> Self {
		Self {
			registers:  [0.0; NUM_REGISTERS],
			memory:     Memory::new(),
			program:    vec![],
			index:      0,
			call_stack: vec![],
		}
	}

	/// Append an instruction to the program vector
	pub fn add_instruction(&mut self, instruction: Instruction) {
		self.program.push(instruction);
	}

	/// Get a full slice of the memory vector
	pub fn dump_memory(&self) -> &[u8] {
		&self.memory.data[..]
	}

	/// Execute a single instruction
	pub fn execute(&mut self) -> Result<bool, StrontiumError> {
		let instruction = self.peek();

		match instruction {
			HALT => {
				Ok(
					self.halt()
				)
			},

			LOAD { value, register } => {
				Ok(
					self.load(value, register as usize)?
				)
			},

			MOVE { source, destination } => {
				Ok(
					self.move_value(source, destination)?
				)
			},

			COPY { source, destination } => {
				Ok(
					self.copy_value(source, destination)
				)
			},

			CALCULATE { method, operand1, operand2, destination } => {
				Ok(
					self.calculate(method.clone(), operand1 as usize, operand2 as usize, destination as usize)?
				)
			},
			
			COMPARE { method, operand1, operand2, destination } => {
				Ok(
					self.compare(method.clone(), operand1 as usize, operand2 as usize, destination as usize)?
				)
			},

			MEMORY { method } => {
				Ok(
					self.bitwise(method.clone())?
				)
			},

			JUMP { destination } => {
				Ok(
					self.jump(destination)
				)
			},

			JUMPC { destination, conditional_address } => {
				Ok(
					self.jumpc(destination, conditional_address)
				)
			},

			INTERRUPT { interrupt } => {
				Ok(
					self.interrupt(interrupt.clone())?
				)
			},
		}
	}

	fn halt(&mut self) -> bool {
		false
	}

	fn load(&mut self, value: f64, register: usize) -> Result<bool, StrontiumError> {
		if register <= NUM_REGISTERS {
			self.registers[register] = value;
		} else {
			return Err(StrontiumError::OutOfBounds);
		}
		
		self.advance();

		Ok(true)
	}

	fn move_value(&mut self, source: Location, destination: Location) -> Result<bool, StrontiumError> {
		match source {
			Location::Memory(src_address) => {
				match destination {
					Location::Memory(dest_address)   => {
						self.memory.compute(MemoryMethod::SET_RANGE {
							address: dest_address,
							values:  self.memory.range(src_address as usize .. src_address as usize + 8)?.to_vec(),
						})?;
					},

					Location::Register(dest_address)   => {
						if dest_address as usize <= NUM_REGISTERS {
							let mut range = self.memory.range(src_address as usize .. src_address as usize + 8)?;

							self.registers[dest_address as usize] = range.read_f64::<LittleEndian>()
        						.expect("Cannot read f64 value from memory");
						} else {
							return Err(StrontiumError::OutOfBounds)
						}
					},
				}
			},

			Location::Register(src_address) => {
				match destination {
					Location::Memory(dest_address)   => {
						if src_address  as usize <= NUM_REGISTERS {
							let mut  values = vec![];

							values
								.write_f64::<LittleEndian>(self.registers[src_address as usize])
								.expect("Cannot write f64 value to temporary buffer");

							self.memory.compute(MemoryMethod::SET_RANGE {
								address: dest_address,
								values,
							})?;
						} else {
							return Err(StrontiumError::OutOfBounds)
						}
					},
					Location::Register(dest_address) => {
						if    src_address  as usize <= NUM_REGISTERS 
						   && dest_address as usize <= NUM_REGISTERS {
						   	self.registers[src_address as usize] = self.registers[dest_address as usize];
						} else {
							return Err(StrontiumError::OutOfBounds)
						}
					},
				}
			}
		}
		
		Ok(true)
	}

	fn copy_value(&mut self, _source: Location, _destination: Location) -> bool {
		println!("The COPY instruction has not yet been implemented");
		true
	}

	fn jump(&mut self, destination: usize) -> bool {
		self.index = destination;

		true
	}

	fn jumpc(&mut self, destination: usize, pointer: MemoryAddress) -> bool {
		if self.memory.data[pointer as usize] == 1 {
			self.index = destination;
		}

		true
	}

	fn bitwise(&mut self, method: MemoryMethod) -> Result<bool, StrontiumError> {
		self.memory.compute(method)?;

		self.advance();

		Ok(true)
	}

	fn calculate(&mut self, method: CalculationMethod, a: usize, b: usize, destination: usize) -> Result<bool, StrontiumError> {
		match method {
			CalculationMethod::ADD 		=> self.registers[destination] = self.registers[a] + self.registers[b],
			CalculationMethod::SUBTRACT => self.registers[destination] = self.registers[a] - self.registers[b],
			CalculationMethod::MULTIPLY => self.registers[destination] = self.registers[a] * self.registers[b],
			CalculationMethod::DIVIDE 	=> self.registers[destination] = self.registers[a] / self.registers[b],
			CalculationMethod::POWER 	=> self.registers[destination] = self.registers[a].powf(self.registers[b]),
			CalculationMethod::MODULO 	=> self.registers[destination] = self.registers[a] % self.registers[b],
		}

		self.advance();

		Ok(true)
	}

	fn compare(&mut self, method: ComparisonMethod, a: usize, b: usize, destination: usize) -> Result<bool, StrontiumError> {
		match method {
			ComparisonMethod::EQ  => self.memory.set(destination, (self.registers[a] == self.registers[b]) as u8),
			ComparisonMethod::NEQ => self.memory.set(destination, (self.registers[a] != self.registers[b]) as u8),
			ComparisonMethod::GT  => self.memory.set(destination, (self.registers[a] >  self.registers[b]) as u8),
			ComparisonMethod::GTE => self.memory.set(destination, (self.registers[a] >= self.registers[b]) as u8),
			ComparisonMethod::LT  => self.memory.set(destination, (self.registers[a] <  self.registers[b]) as u8),
			ComparisonMethod::LTE => self.memory.set(destination, (self.registers[a] <= self.registers[b]) as u8),
		}

		self.advance();

		Ok(true)
	}

	fn interrupt(&mut self, _kind: Interrupt) -> Result<bool, StrontiumError> {
		Ok(true)
	}

	fn peek(&self) -> Instruction {
		self.program[self.index].clone()
	}

	fn advance(&mut self) -> bool {
		if self.index + 1 < self.program.len() {
			self.index += 1;
			true
		} else {
			false
		}
	}
}

#[cfg(test)]
mod tests {
	use super::*;

    #[test]
    fn halt() {
 		let mut machine = Strontium::new();

 		machine.add_instruction(Instruction::HALT);

 		assert_eq!(machine.execute(), Ok(false));
    }

    #[test]
    fn load() {
 		let mut machine = Strontium::new();

 		machine.add_instruction(Instruction::LOAD { value: 1332.5, register: 5 });

 		machine.execute().unwrap();

 		assert_eq!(machine.registers[5], 1332.5);
    }

    #[test]
    fn add() {
 		let mut machine = Strontium::new();

 		machine.add_instruction(Instruction::LOAD { value: 44.7, register: 1 });
 		machine.add_instruction(Instruction::LOAD { value: 36.8, register: 2 });

 		machine.add_instruction(Instruction::CALCULATE { 
 			method: CalculationMethod::ADD,
 			operand1: 1,
 			operand2: 2,
 			destination: 3,
 		});

 		machine.execute().unwrap();
 		machine.execute().unwrap();
 		machine.execute().unwrap();

 		assert_eq!(machine.registers[3], 44.7 + 36.8);
    }

    #[test]
    fn subtract() {
 		let mut machine = Strontium::new();

 		machine.add_instruction(Instruction::LOAD { value: 3452.37, register: 1 });
 		machine.add_instruction(Instruction::LOAD { value: 3685.8148, register: 2 });

 		machine.add_instruction(Instruction::CALCULATE { 
 			method: CalculationMethod::SUBTRACT,
 			operand1: 1,
 			operand2: 2,
 			destination: 3,
 		});
 		
 		machine.execute().unwrap();
 		machine.execute().unwrap();
 		machine.execute().unwrap();

 		assert_eq!(machine.registers[3], 3452.37 - 3685.8148);
    }

    #[test]
    fn multiply() {
 		let mut machine = Strontium::new();

 		machine.add_instruction(Instruction::LOAD { value: 3.642, register: 1 });
 		machine.add_instruction(Instruction::LOAD { value: 2.46682, register: 2 });

 		machine.add_instruction(Instruction::CALCULATE { 
 			method: CalculationMethod::MULTIPLY,
 			operand1: 1,
 			operand2: 2,
 			destination: 3,
 		});
 		
 		machine.execute().unwrap();
 		machine.execute().unwrap();
 		machine.execute().unwrap();

 		assert_eq!(machine.registers[3], 3.642 * 2.46682);
    }

    #[test]
    fn divide() {
 		let mut machine = Strontium::new();

 		machine.add_instruction(Instruction::LOAD { value: 12.534, register: 1 });
 		machine.add_instruction(Instruction::LOAD { value: 8.388475294, register: 2 });

 		machine.add_instruction(Instruction::CALCULATE { 
 			method: CalculationMethod::DIVIDE,
 			operand1: 1,
 			operand2: 2,
 			destination: 3,
 		});
 		
 		machine.execute().unwrap();
 		machine.execute().unwrap();
 		machine.execute().unwrap();

 		assert_eq!(machine.registers[3], 12.534 / 8.388475294);
    }

    #[test]
    fn power() {
 		let mut machine = Strontium::new();

 		machine.add_instruction(Instruction::LOAD { value: 3.141592, register: 1 });
 		machine.add_instruction(Instruction::LOAD { value: 4.0, register: 2 });

 		machine.add_instruction(Instruction::CALCULATE { 
 			method: CalculationMethod::POWER,
 			operand1: 1,
 			operand2: 2,
 			destination: 3,
 		});
 		
 		machine.execute().unwrap();
 		machine.execute().unwrap();
 		machine.execute().unwrap();

 		assert_eq!(machine.registers[3], (3.141592 as f64).powf(4.0));
    }

    #[test]
    fn modulo() {
 		let mut machine = Strontium::new();

 		machine.add_instruction(Instruction::LOAD { value: 3.141592, register: 1 });
 		machine.add_instruction(Instruction::LOAD { value: 4.0, register: 2 });

 		machine.add_instruction(Instruction::CALCULATE { 
 			method: CalculationMethod::MODULO,
 			operand1: 1,
 			operand2: 2,
 			destination: 3,
 		});
 		
 		machine.execute().unwrap();
 		machine.execute().unwrap();
 		machine.execute().unwrap();

 		assert_eq!(machine.registers[3], 3.141592 % 4.0);
    }

    #[test]
    fn and() {
 		let mut machine = Strontium::new();

 		machine.add_instruction(Instruction::MEMORY {
 			method: MemoryMethod::GROW { amount: 8 }
 		});

 		machine.add_instruction(Instruction::MEMORY {
 			method: MemoryMethod::SET { value: 3, address: 2 }
 		});

 		machine.add_instruction(Instruction::MEMORY {
 			method: MemoryMethod::SET { value: 7, address: 3 }
 		});

 		machine.add_instruction(Instruction::MEMORY { 
 			method: MemoryMethod::AND {
 				a: 2,
 				b: 3,
 				out: 4,
 				len: 1,
 			}
 		});
 		
 		machine.execute().unwrap();
 		machine.execute().unwrap();
 		machine.execute().unwrap();
 		machine.execute().unwrap();

 		println!("{:?}", machine.memory.data);

 		assert_eq!(machine.memory.data[4], 3 & 7);
    }
}