-
Notifications
You must be signed in to change notification settings - Fork 3
/
lmsm-ui-vanilla.js
443 lines (381 loc) · 15.2 KB
/
lmsm-ui-vanilla.js
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
class LMSMUi {
lmsm = null;
asmEditor = null;
assemblySourceMap = null;
firthEditor = null;
firthSourceMap = null;
speed = 500;
outputAppendHandler = (e) => {
e.target.innerHTML += `<div>${e.detail.entry}</div>`;
}
makeLMSM() {
const lmsm = new LittleManStackMachine();
lmsm.outputCallback = (value) => {
const elem = document.querySelector("#outputPane");
const event = new CustomEvent("output:append", {
detail: {
timestamp: new Date(),
entry: value,
}
});
elem.dispatchEvent(event);
}
const outputPane = document.querySelector("#outputPane");
outputPane.removeEventListener('output:append', this.outputAppendHandler);
outputPane.addEventListener('output:append', this.outputAppendHandler);
const callback = (mutationList, observer) => {
mutationList.forEach((mutation) => {
switch (mutation.type) {
case 'childList':
mutation.target.scroll({ top: mutation.target.scrollHeight, left: 0, behavior: 'smooth' });
break;
default: break;
}
})
};
const observer = new MutationObserver(callback);
observer.observe(outputPane, { childList: true });
return lmsm;
}
constructor() {
this.lmsm = this.makeLMSM();
CodeMirror.defineSimpleMode('lmsm-assembly', {
start: [
{
regex: /(?:CALL|DAT|ADD|SUB|STA|LDI|LDA|BRA|BRZ|BRP|NOOP|INP|OUT|SPUSH|SPOP|SDUP|SDROP|SSWAP|SADD|SSUB|SMUL|SDIV|SMAX|SMIN|JAL|RET|HLT)\b/,
token: 'keyword'
},
{
regex: /\d\d/,
token: 'number',
},
],
});
this.asmEditor = CodeMirror.fromTextArea(document.querySelector('#codeEditor'), {
lineNumbers: true,
tabSize: 2,
});
// TODO - ASM Linter
this.asmEditor.setSize('100%', '25em');
this.asmEditor.setOption('mode', 'lmsm-assembly');
CodeMirror.defineSimpleMode('firth', {
start: [
{
regex: /(?:def|loop|get|else|stop|var|return|swap|end|dup|do)\b/,
token: 'keyword'
},
{
regex: /zero\?/,
token: 'keyword',
},
{
regex: /asm/,
token: 'keyword',
mode: { spec: 'lmsm-assembly', end: /end/ }
},
{
regex: /\*/,
token: 'operator'
},
{
regex: /\d\d/,
token: 'number',
},
],
});
this.firthEditor = CodeMirror.fromTextArea(document.querySelector('#codeEditorFirth'), {
lineNumbers: true,
tabSize: 2,
lint: {
getAnnotations: (x) => {
let diagnostics = []
if (this.firthEditor) {
let compiler = new FirthCompiler();
let compileResult = compiler.compile(this.firthEditor.getValue());
for (const error of compileResult.errors) {
diagnostics.push({
from: {
line: error.token.line - 1,
ch: error.token.lineOffset
},
to: {
line: error.token.line - 1,
ch: error.token.lineOffsetEnd
},
message: error.message,
severity: "error"
})
}
}
return diagnostics
}
},
});
this.firthEditor.setSize('100%', '25em');
this.firthEditor.setOption('mode', 'firth');
}
clearOutput() {
document.querySelector('#outputPane').innerHTML = '';
}
updateMemory() {
const mem = document.querySelectorAll(".memory tr input");
mem.forEach((m, i) => {
this.setMemory(i, m.value);
})
}
syncToDOM() {
document.querySelector("#pc").value = this.getProgramCounter();
document.querySelector("#acc").value = this.getAccumulator();
document.querySelector("#ci").value = this.getCurrentInstruction();
document.querySelector("#sp").value = this.getStackPointer();
document.querySelector("#rap").value = this.getReturnAddressPointer();
document.querySelector("#statusOutput").value = this.getStatus();
document.querySelector("#nextInstructionOutput").innerHTML = this.getNextInstructionDescription();
const slots = document.querySelectorAll(".memory tr input");
slots.forEach((s, i) => {
s.value = this.getMemory(i);
});
const pc = document.querySelectorAll(".program_counter");
pc.forEach((m, i) => {
m.classList.remove("program_counter");
});
slots.item(this.getProgramCounter()).classList.add("program_counter");
const sp = document.querySelectorAll(".stack_pointer");
sp.forEach((m, i) => {
m.classList.remove("stack_pointer");
});
if (this.getStackPointer() < 200) {
slots.item(this.getStackPointer()).classList.add("stack_pointer");
}
const rap = document.querySelectorAll(".return_address_pointer");
rap.forEach((m, i) => {
m.classList.remove("return_address_pointer");
});
if (this.getReturnAddressPointer() > 100) {
slots.item(this.getReturnAddressPointer()).classList.add("return_address_pointer");
}
}
getNextInstruction() {
return this.getMemory(this.getProgramCounter());
}
getNextInstructionDescription() {
let nextInstruction = this.getNextInstruction()
let detail = "";
if (nextInstruction == null) {
detail = "No Instruction Found";
} else if (nextInstruction === 0) {
detail = "HLT - The Halt Instruction. This instruction will halt the machine.";
} else if (100 <= nextInstruction && nextInstruction < 200) {
detail = "ADD - The Add Instruction. This instruction will add the value found in memory slot " + (nextInstruction - 100) + " to the value found in the accumulator register.";
} else if (200 <= nextInstruction && nextInstruction < 200) {
detail = "SUB - The Subtraction Instruction. This instruction will subtract the value found in memory slot " + (nextInstruction - 100) + " to the value found in the accumulator register.";
} else if (300 <= nextInstruction && nextInstruction < 400) {
detail = "STA - The Store Instruction. This instruction will store the accumulator to the memory slot " + (nextInstruction - 100);
} else if (400 <= nextInstruction && nextInstruction < 500) {
detail = "LDI - The Load Immediate Instruction. This instruction will put the value " + (nextInstruction - 400) + " into the accumulator";
} else if (500 <= nextInstruction && nextInstruction < 600) {
detail = "LDA - The Load Instruction. This instruction will load the value in the memory slot " + (nextInstruction - 100) + " into the accumulator";
} else if (600 <= nextInstruction && nextInstruction < 700) {
detail = "BRA - The Branch Unconditionally Instruction. This instruction will update the program counter to the value " + (nextInstruction - 100);
} else if (700 <= nextInstruction && nextInstruction < 800) {
detail = "BRZ - The Branch If Zero Instruction. This instruction will update the program counter to the value " + (nextInstruction - 100) + " if the current value of the accumulator is zero";
} else if (800 <= nextInstruction && nextInstruction < 900) {
detail = "BRP - The Branch If Positive Instruction. This instruction will update the program counter to the value " + (nextInstruction - 100) + " if the current value of the accumulator is positive or zero";
} else if (901 === nextInstruction) {
detail = "INP - The Input Instruction. This instruction will ask the user for a numeric value and place it in the accumulator";
} else if (902 === nextInstruction) {
detail = "OUT - The Output Instruction. This instruction will print the current value of the accumulator to the output";
} else if (910 === nextInstruction) {
detail = "JAL - The Jump & Link Instruction. This instruction will consume the top of the value stack and update the program counter to it. It will also push the address of the next instruction onto the return address stack.";
} else if (911 === nextInstruction) {
detail = "RET - The Return Instruction. This instruction will consume the top of the return address stack and update the program counter to it.";
} else if (920 === nextInstruction) {
detail = "SPUSH - The Push Instruction. This instruction will push the value of the accumulator onto the value stack";
} else if (921 === nextInstruction) {
detail = "SPOP - The Pop Instruction. This instruction will pop the opt value of the value stack off and place it in the accumulator";
} else if (922 === nextInstruction) {
detail = "SDUP - The Duplicate Instruction. This instruction will duplicate the value on the top of the value stack";
} else if (923 === nextInstruction) {
detail = "SDROP - The Drop Instruction. This instruction will drop/remove the value on the top of the value stack";
} else if (924 === nextInstruction) {
detail = "SSWAP - The Swap Instruction. This instruction will swap the two values on the top of the value stack";
} else if (930 === nextInstruction) {
detail = "SADD - The Stack Add Instruction. This instruction will add the top two values on the top of the value stack and replace them with the result";
} else if (931 === nextInstruction) {
detail = "SSUB - The Stack Subtract Instruction. This instruction will subtract the top two values on the top of the value stack and replace them with the result";
} else if (932 === nextInstruction) {
detail = "SMUL - The Stack Multiply Instruction. This instruction will multiply the top two values on the top of the value stack and replace them with the result";
} else if (933 === nextInstruction) {
detail = "SDIV - The Stack Divide Instruction. This instruction will divide the top two values on the top of the value stack and replace them with the result";
} else if (934 === nextInstruction) {
detail = "SMAX - The Stack Max Instruction. This instruction will remove the top two values on the top of the value stack and replace them with the maximum of those values";
} else if (935 === nextInstruction) {
detail = "SMIN - The Stack Min Instruction. This instruction will remove the top two values on the top of the value stack and replace them with the minimum of those values";
} else {
detail = "Unknown instruction - The behavior of this machine instruction is undefined.";
}
let desc = `<h3>Instruction: ${nextInstruction || ''}</h3>
<p>${detail}</p>`;
return desc;
}
getStatus() {
return this.lmsm.status;
}
compile() {
this.lmsm = this.makeLMSM();
const code = this.firthEditor.getValue();
let compiler = new FirthCompiler();
let compileResult = compiler.compile(code);
if (compileResult.errors.length > 0) {
console.error("Compilation Errors:")
for (const err of compileResult.errors) {
console.error(err)
}
return;
}
this.firthSourceMap = compileResult.sourceMap;
this.asmEditor.setValue(compileResult.assembly);
let assembler = new LMSMAssembler();
let assemblyResult = assembler.assemble(compileResult.assembly);
this.assemblySourceMap = assemblyResult.sourceMap;
this.lmsm.load(assemblyResult.machineCode);
}
assemble() {
this.lmsm = this.makeLMSM();
const code = this.asmEditor.getValue();
let assembler = new LMSMAssembler();
let assemblyResult = assembler.assemble(code);
this.assemblySourceMap = assemblyResult.sourceMap;
this.lmsm.load(assemblyResult.machineCode);
}
runLoop() {
if (this.lmsm.status === 'Stopped') {
this.currentTimeout = null;
return;
}
this.step()
this.syncToDOM();
this.currentTimeout = setTimeout(() => {
this.runLoop();
}, this.speed);
}
pause() {
if (this.currentTimeout) {
clearTimeout(this.currentTimeout);
}
}
resume() {
this.runLoop();
}
setSpeed(delay) {
this.speed = delay;
if (this.currentTimeout) {
clearTimeout(this.currentTimeout);
this.currentTimeout = setTimeout(() => {
this.runLoop();
}, this.speed);
}
}
run() {
// TODO reset registers & upper memory?
this.setProgramCounter(0);
this.lmsm.status = "Ready";
this.runLoop(1);
}
assembleAndRun() {
this.lmsm = this.makeLMSM();
const code = this.asmEditor.getValue();
this.lmsm.assembleAndRun(code);
}
reset() {
this.setProgramCounter(0);
this.setStackPointer(200);
this.setReturnAddressPointer(99);
this.lmsm.status = "Ready";
}
step() {
if (this.lmsm.status === "Stopped") {
return;
}
this.lmsm.step();
let currentProgramCounter = this.lmsm.registers.program_counter;
if (this.lastActiveAssemblyLine != null) {
this.asmEditor.getDoc()
.removeLineClass(this.lastActiveAssemblyLine, 'background', 'markCode');
}
if (this.assemblySourceMap) {
let mappedAssemblyLine = this.assemblySourceMap[currentProgramCounter];
if (mappedAssemblyLine != null) {
// editor is zero-based
this.lastActiveAssemblyLine = mappedAssemblyLine - 1;
this.asmEditor.getDoc()
.addLineClass(this.lastActiveAssemblyLine, 'background', 'markCode');
} else {
this.lastActiveAssemblyLine = null;
}
}
if (this.lastActiveFirthLine != null) {
this.firthEditor.getDoc()
.removeLineClass(this.lastActiveFirthLine, 'background', 'markCode');
}
if (this.firthSourceMap != null && this.lastActiveAssemblyLine != null) {
let mappedValue = this.firthSourceMap[this.lastActiveAssemblyLine + 1];
if (mappedValue != null) {
// editor is zero-based
this.lastActiveFirthLine = mappedValue - 1;
this.firthEditor.getDoc()
.addLineClass(this.lastActiveFirthLine, 'background', 'markCode');
} else {
this.lastActiveFirthLine = null;
}
}
}
getProgramCounter() {
return this.lmsm.registers.program_counter;
}
setProgramCounter(value) {
this.lmsm.registers.program_counter = value;
}
getAccumulator() {
return this.lmsm.registers.accumulator;
}
setAccumulator(value) {
this.lmsm.registers.accumulator = value;
}
getCurrentInstruction() {
return this.lmsm.registers.current_instruction;
}
setCurrentInstruction(value) {
this.lmsm.registers.current_instruction = value;
}
getStackPointer() {
return this.lmsm.registers.stack_pointer;
}
setStackPointer(value) {
this.lmsm.registers.stack_pointer = value;
}
getReturnAddressPointer() {
return this.lmsm.registers.return_address_pointer;
}
setReturnAddressPointer(value) {
this.lmsm.registers.return_address_pointer = value;
}
getMemory(mempos) {
return this.lmsm.memory[mempos] == null ? null : this.lmsm.memory[mempos];
}
setMemory(position, value) {
this.lmsm.memory[position] = value;
}
cellClass(mempos) {
if (this.lmsm.registers.program_counter == mempos)
return 'memory_slot program_counter'
else if (this.lmsm.registers.stack_pointer === mempos)
return 'memory_slot stack_pointer'
else if (this.lmsm.registers.return_address_pointer === mempos)
return 'memory_slot return_address_pointer'
else return 'memory_slot';
}
resetMachine() {
this.lmsm = new LittleManStackMachine();
}
}