summaryrefslogtreecommitdiff
path: root/src/vm/core.js
blob: 074e1560eb1d541729694fb1aa132b90acb44177 (plain)
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
'use strict';

const { Op, AddrMode} = require('./enum.js');


class Core {
	constructor(size) {
		this.data = new Array(size);

		// initialize core to all DAT 0, 0
		for (let i=0; i<size; i++) {
			this.data[i] = {
				opcode: Op.DAT,
				a: { value: 0, mode: AddrMode.Immediate },
				b: { value: 0, mode: AddrMode.Immediate },
			};
		}
	}


	normalize(pc, value) {
		return (pc + value) % this.data.length;
	}


	getLocation(pc, address) {
		switch(address.mode) {
			case AddrMode.Immediate:
				throw "Cannot get location from immediate-mode address";
			case AddrMode.Direct:
				return this.normalize(pc, address.value);
			case AddrMode.Indirect: {
				let loc = this.normalize(pc, address.value);
				let b = this.data[loc];
				return this.normalize(loc, b);
			}
			case AddrMode.Predecrement: {
				let loc = this.normalize(pc, address.value);
				this.data[loc].b -= 1;
				let b = this.data[loc].b;
				return this.normalize(loc, b);
			}
			default:
				throw `Invalid addressing mode "${address.mode}"`;
		}
	}

	getValue(pc, address) {
		return this.data[this.getLocation(pc, address)];
	}
}


exports.Core = Core;