-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
451 lines (403 loc) · 13.4 KB
/
script.js
File metadata and controls
451 lines (403 loc) · 13.4 KB
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
"use strict";
class instruction{
constructor(opcode, addressMode, regNum, op2){
this.opcode = opcode;
this.addressMode = addressMode;
this.regNum = regNum;
this.operand2 = op2;
}
static OPCODE_SIZE = 3; // Number of bits for the opcodes
static ADDRESS_MODES = 3;
static get haltInstr(){
return new instruction(0,0,0,0);
}
static get Op2Size(){
return Math.max(processor.r_bits, processor.m_bits);
}
static get maxOp2Value(){
return Math.pow(2, instruction.Op2Size) - 1;
}
get instructionSize(){
return instruction.OPCODE_SIZE + numBits(instruction.ADDRESS_MODES) + processor.r_bits + instruction.Op2Size;
}
static getBinaryRepresentation(num, length){
return num.toString(2).padStart(length,'0');
}
toString(){
return instruction.getBinaryRepresentation(this.opcode, instruction.OPCODE_SIZE)
+ instruction.getBinaryRepresentation(this.addressMode,numBits(instruction.ADDRESS_MODES))
+ instruction.getBinaryRepresentation(this.regNum,processor.r_bits)
+ instruction.getBinaryRepresentation(this.operand2,instruction.Op2Size);
}
}
function numBits(n){
return Math.ceil(Math.log2(n));
}
// TODO Display flags
const processor = {
r:[0,0,0,0],
pc:0,
cir:'0',
m:[0,0,0,0],
halted:false,
instructions:[],
zero_flag:false,
neg_flag:false,
labels:{},
addLabel(labelName, index){
if (labelName in this.labels){
throw new Error('Label already exists');
}
this.labels[labelName] = index;
},
loadInstructions(instructions){
this.instructions = instructions;
txtArea_output.value = instructions.map(instr => instr.toString()).join('\n');
},
get r_bits() {
return numBits(this.r.length);
},
get m_bits(){
return numBits(this.m.length);
},
get PC(){
return this.pc;
},
set PC(val){
this.pc = val;
pc.innerHTML = val;
},
get CIR(){
return this.cir;
},
set CIR(val){
this.cir = val;
cir.innerHTML = val;
},
getRegisterValue(n){
return this.r[n]
},
setRegister(n,val){
this.r[n] = val;
registers.forEach(
element =>{
if(element.id == 'r' + n.toString()){
element.innerHTML = val;
}
}
);
},
getMemoryValue(n){
return this.m[n];
},
setMemory(n,val){
this.m[n] = val;
memoryInputs.forEach(
element => {
if(element.id == 'm' + n.toString()){
element.value = val;
}
}
);
},
getOperand2(addressMode, op2) {
switch (addressMode) {
case 0: // Immediate addressing
return op2;
case 1: // Register
return this.getRegisterValue(op2);
case 2: // Direct addressing
return this.getMemoryValue(op2);
default:
throw new Error("Invalid address mode");
}
},
reset() { // Set registers to 0 and clear instructions
this.PC = 0;
this.CIR = '0';
this.halted = false;
for (let i = 0; i < this.r.length; i++) {
this.setRegister(i, 0);
}
this.instructions = [];
this.labels = {};
this.zero_flag = false;
this.neg_flag = false;
txtArea_output.value = '';
},
set_flags(result){
this.zero_flag = result == 0 ? true : false
this.neg_flag = result < 0 ? true : false
},
add(regNum, op2){
const x = this.getRegisterValue(regNum);
const result = x + op2;
this.setRegister(regNum,result);
this.set_flags(result)
},
mov(regNum,op2){
this.setRegister(regNum,op2);
},
halt(){ // Reset processor
this.reset();
this.halted = true; // Set halted to true - once halted cannot run until instructions restored
},
store(regNum, mref){
const x = this.getRegisterValue(regNum);
this.setMemory(mref,x);
},
compare(regNum, op2){
const x = this.getRegisterValue(regNum);
const result = x - op2;
this.set_flags(result);
},
branch(instr){
let index = instr.operand2;
index += instr.regNum >> instruction.Op2Size
index += instr.addressMode >> (instruction.Op2Size + numBits(instruction.ADDRESS_MODES))
this.PC = index;
},
runCycle(){
if(this.halted){
return;
}
const instr = this.instructions[this.PC]
this.CIR = instr.toString();
this.PC += 1
const regNum = instr.regNum;
const op2 = this.getOperand2(instr.addressMode, instr.operand2);
switch (instr.opcode) {
case 0:
this.halt();
case 1:
this.add(regNum,op2);
break;
case 2:
this.mov(regNum,op2);
break;
case 3:
this.store(regNum,instr.operand2);
break;
case 4:
this.compare(regNum,instr.operand2);
break;
case 6:
if(this.zero_flag) this.branch(instr);
break;
case 7:
if(this.neg_flag) this.branch(instr);
break;
case 5:
this.branch(instr);
break;
default:
this.halt();
break;
}
}
};
function run(){ // TODO : Implement run all
}
function isValidRegister(num){
if(isNaN(num) || num >= processor.r.length){
return false;
}
else{
return true;
}
}
function isValidMref(num){
if(isNaN(num) || num >= processor.m.length){
return false;
}
else{
return true;
}
}
function parseRegister(regString){
if(regString[0] != 'R'){
throw new Error("Not a register");
}
let regNum = parseInt(regString.substring(1));
if(isValidRegister(regNum)){
return regNum;
}
else{
throw new Error("Invalid regiser number");
}
}
function parseOperand2(op2String,opcode){
let operand2;
let addressMode;
if(op2String[0] == 'R'){
addressMode = 1; // Register contents: direct addressing
if(opcode == 3){ // Str requires second operand to be mref
throw new Error("Str requires a memory address as second operand");
}
else{
operand2 = parseRegister(op2String);
}
}
else if(op2String[0] == '#'){
addressMode = 0; //Immediate addressing
if(opcode == 3){ // Str requires second operand to be mref
throw new Error("Str requires a memory address as second operand")
}
operand2 = parseInt(op2String.substring(1));
if (operand2 > instruction.maxOp2Value){
throw new Error("Operand 2 is too large to use immediate addressing");
}
}
else{
addressMode = 2; // Mref
operand2 = parseInt(op2String);
if(!isValidMref(operand2)){
throw new Error("Not a valid memory address");
}
}
return {op2: operand2, adrMode : addressMode};
}
function parseBranch(parts){
const op = parts[0];
const label = parts[1]; //TODO check array has only two elements
const instr = new instruction(0,0,0,0)
switch (op) {
case 'B':
instr.opcode = 5;
break;
case 'BEQ':
instr.opcode = 6;
break;
case 'BLT':
instr.opcode = 7;
break;
default:
throw new Error('Invalid syntax');
}
let num = processor.labels[label];
if(isNaN(num)){throw new Error('Label undefined')}
let numBit = instruction.Op2Size;
let rem = num % Math.pow(2,numBit);
instr.operand2 = rem;
num = num >> numBit;
numBit = processor.r_bits;
rem = num % Math.pow(2,numBit);
instr.regNum = rem;
num = num >> numBit;
numBit = numBits(instruction.ADDRESS_MODES);
rem = num % Math.pow(2,numBit);
instr.addressMode = rem;
num = num >> numBit;
if(num != 0){
console.error('Could not load full label');
}
return instr;
}
function parseLine(parts, index){
const op = parts[0];
let opcode;
if (op[0] == 'B'){ // Branch instructions are parsed separately
return null; // Needs to be evaluated at end, once all labels are defined
}
switch (op) {
case 'HLT':
return instruction.haltInstr; // Ignore everything else
case 'ADD':
opcode = 1;
break;
case 'MOV':
opcode = 2;
break;
case 'STR':
opcode = 3;
break;
case 'CMP':
opcode = 4;
break;
default: // Could be label definition
if(op.endsWith(':')){
processor.addLabel(op.slice(0,-1),index); //Remove colon from label name
return parseLine(parts.slice(1), index); // Call parse line on the rest of the line, which the label refers to
}
else {
throw new Error("Syntax Error"); // Not valid
}
}
const operands = parts.slice(1); // Array of operands
if (operands.length != 2){ // Needs 2 arguments
throw new Error("Invalid syntax");
}
let registerNum = parseRegister(operands[0])
let {op2,adrMode} = parseOperand2(operands[1],opcode);
return new instruction(opcode,adrMode,registerNum,op2);
}
function assemble(){
processor.reset();
const text = code_input.value;
const lines = text.split('\n');
const instructions = [];
for (let i = 0; i < lines.length; i++) {
try {
const parts = lines[i].toUpperCase().split(' ').filter(x => x != '') // Split by spaces and removing empty strings also
const instruction = parseLine(parts, i);
instructions.push(instruction);
}
catch (err) {
console.error(err);
txtArea_output.value = "";
return;
// TODO Display error message
}
}
for (let i = 0; i < instructions.length; i++){
if(!instructions[i]){
const parts = lines[i].toUpperCase().split(' ').filter(x => x != '');
instructions[i] = parseBranch(parts);
}
}
processor.loadInstructions(instructions);
}
function reset(){
processor.reset();
}
function autoResize(){
this.style.height = 'auto';
this.style.height = this.scrollHeight + 'px';
}
function memoryChanged(){
const address = parseInt(this.id[1]);
const temp = parseInt(this.value);
if(isNaN(temp)){
this.value = processor.m[address];
}
else{
processor.m[address] = temp;
}
}
function btn_runClicked(){
try{
processor.runCycle();
}
catch(err){ // TODO Display error
console.error(err);
processor.halt();
}
}
const code_input = document.getElementById("code_input");
const txtArea_output = document.getElementById("output");
const pc = document.getElementById("pc");
const cir = document.getElementById("cir")
const textareas = document.querySelectorAll("textarea"); //Get all the textarea and attach listeners
textareas.forEach(element => {
element.addEventListener('change',autoResize);
});
const memoryInputs = document.querySelectorAll(".mem_input");
memoryInputs.forEach(element =>{
element.addEventListener('change',memoryChanged);
});
const btn_assemble = document.getElementById("btn_assemble")
btn_assemble.addEventListener('click',assemble)
const btn_run = document.getElementById('btn_run');
btn_run.addEventListener('click',btn_runClicked);
const registers = document.querySelectorAll('.register');
reset();