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

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


function mod(a, N) {
	const A = a % N;
	if (A < 0) {
		return A + N;
	} else {
		return A;
	}
}


class Range {
	constructor(start, end, coresize) {
		this.start = start;
		this.end = end;
		this.coresize = coresize;
	}

	
	// thanks to https://fgiesen.wordpress.com/2015/09/24/intervals-in-modular-arithmetic/
	// c:
	contains(n) {
		return mod(n - this.start, this.coresize) <= mod(this.end - this.start, this.coresize);
	}

	overlaps(other) {
		return (
			this.contains(other.start) ||
			other.contains(this.start)
		);
	}
}


function randomRange(coresize, length) {
	const start = Math.floor(Math.random() * coresize);
	const end = mod(start + length - 1, coresize);
	return new Range(start, end, coresize);
}


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 },
			};
		}
	}


	getRanges(lengths, ranges) {
		if (ranges === undefined) {
			ranges = [];
		}

		if (lengths.length === 0) {
			return ranges;
		}

		const length = lengths[0];
		let range;
		do {
			range = randomRange(this.data.length, length);
		} while (
			ranges
				.map(r => r.overlaps(range))
				.reduce((acc, overlap) => acc || overlap, false)
		);

		return this.getRanges(lengths.slice(1), [...ranges, range]);
	}


	normalize(pc, value) {
		return mod((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].b.value;
				return this.normalize(pc, b);
			}
			case AddrMode.Predecrement: {
				let loc = this.normalize(pc, address.value);
				this.data[loc].b.value -= 1;
				let b = this.data[loc].b.value;
				return this.normalize(pc, b);
			}
			default:
				throw `Invalid addressing mode "${address.mode}"`;
		}
	}

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


exports.mod = mod;
exports.Range = Range;
exports.Core = Core;