forked from sehugg/8bitworkshop
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasic.ts
More file actions
308 lines (286 loc) · 9.72 KB
/
basic.ts
File metadata and controls
308 lines (286 loc) · 9.72 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
import { Platform, BreakpointCallback, DebugCondition, DebugEvalCondition } from "../common/baseplatform";
import { PLATFORMS, AnimationTimer, EmuHalt } from "../common/emu";
import { BASICRuntime } from "../common/basic/runtime";
import { BASICProgram } from "../common/basic/compiler";
import { TeleTypeWithKeyboard } from "../common/teletype";
import { lpad } from "../common/util";
import { FileData } from "../common/workertypes";
import { haltEmulation } from "../ide/ui"; // TODO: make this a callback
const BASIC_PRESETS = [
{ id: 'hello.bas', name: 'Hello' },
{ id: 'tutorial.bas', name: 'Tutorial' },
{ id: 'sieve.bas', name: 'Sieve Benchmark' },
{ id: 'mortgage.bas', name: 'Interest Calculator' },
{ id: '23match.bas', name: '23 Matches' },
{ id: 'craps.bas', name: 'Craps' },
{ id: 'lander.bas', name: 'Lander' },
{ id: 'hamurabi.bas', name: 'Hammurabi' },
{ id: 'wumpus.bas', name: 'Hunt The Wumpus' },
{ id: 'startrader.bas', name: 'Star Trader' },
{ id: 'haunted.bas', name: 'Haunted House' },
];
class BASICPlatform implements Platform {
mainElement: HTMLElement;
program: BASICProgram;
runtime: BASICRuntime;
clock: number = 0;
timer: AnimationTimer;
tty: TeleTypeWithKeyboard;
hotReload: boolean = true;
animcount: number = 0;
internalFiles : {[path:string] : FileData} = {};
transcript: string[];
constructor(mainElement: HTMLElement) {
//super();
this.mainElement = mainElement;
mainElement.style.overflowY = 'auto';
}
async start() {
// create runtime
this.runtime = new BASICRuntime();
this.runtime.reset();
// create divs
var parent = this.mainElement;
// TODO: input line should be always flush left
var gameport = $('<div id="gameport" style="margin-top:calc(100vh - 8em)"/>').appendTo(parent);
var windowport = $('<div id="windowport" class="transcript transcript-style-2"/>').appendTo(gameport);
var inputport = $('<div id="inputport" class="transcript-bottom"/>').appendTo(gameport);
var inputline = $('<input class="transcript-input transcript-style-2" type="text" style="max-width:95%"/>').appendTo(inputport);
//var printhead = $('<div id="printhead" class="transcript-print-head"/>').appendTo(parent);
//var printshield = $('<div id="printhead" class="transcript-print-shield"/>').appendTo(parent);
this.tty = new TeleTypeWithKeyboard(windowport[0], true, inputline[0] as HTMLInputElement);
this.tty.keepinput = true; // input stays @ bottom
this.tty.splitInput = true; // split into arguments
this.tty.keephandler = false; // set handler each input
this.tty.hideinput();
this.tty.scrolldiv = parent;
this.tty.bell = new Audio('res/ttybell.mp3');
this.runtime.input = async (prompt:string, nargs:number) => {
return new Promise( (resolve, reject) => {
if (prompt != null) {
this.tty.addtext(prompt, 0);
this.tty.addtext('? ', 0);
this.tty.waitingfor = 'line';
} else {
this.tty.waitingfor = 'char';
}
this.tty.focusinput();
this.tty.resolveInput = resolve;
});
}
this.timer = new AnimationTimer(60, this.animate.bind(this));
this.resize = () => {
this.tty.resize(80);
}
this.resize();
this.runtime.print = (s:string) => {
// TODO: why null sometimes?
this.animcount = 0; // exit advance loop when printing
this.tty.print(s);
this.transcript.push(s);
}
this.runtime.resume = this.resume.bind(this);
}
animate() {
if (this.tty.isBusy()) return;
var ips = this.program.opts.commandsPerSec || 1000;
this.animcount += ips / 60;
while (this.runtime.running && this.animcount-- > 0) {
if (!this.advance())
break;
}
}
// should not depend on tty state
advance(novideo?: boolean) : number {
if (this.runtime.running) {
if (this.checkDebugTrap())
return 0;
var more = this.runtime.step();
if (!more) {
this.pause();
if (this.runtime.exited) {
this.exitmsg();
this.didExit();
}
}
this.clock++;
return 1;
} else {
return 0;
}
}
exitmsg() {
this.tty.print("\n\n");
this.tty.addtext("*** END OF PROGRAM ***", 1);
this.tty.showPrintHead(false);
}
resize: () => void;
loadROM(title, data) {
// TODO: disable hot reload if error
// TODO: only hot reload when we hit a label?
var didExit = this.runtime.exited;
this.program = data;
var resumePC = this.runtime.load(data);
this.tty.uppercaseOnly = true; // this.program.opts.uppercaseOnly; //TODO?
// only reset if we exited, or couldn't restart at label (PC reset to 0)
if (!this.hotReload || didExit || !resumePC)
this.reset();
}
getROMExtension() {
return ".json";
}
reset(): void {
this.tty.clear();
this.runtime.reset();
this.clock = 0;
this.transcript = [];
}
pause(): void {
this.timer.stop();
}
resume(): void {
if (this.isBlocked()) return;
this.animcount = 0;
this.timer.start();
}
isBlocked() { return this.tty.waitingfor != null || this.runtime.exited; } // is blocked for input?
isRunning() { return this.timer.isRunning(); }
getDefaultExtensions() { return [".bas"]; }
getToolForFilename() { return "basic"; }
getPresets() { return BASIC_PRESETS; }
getPC() {
return this.runtime.curpc;
}
getSP() {
return 0x1000 - this.runtime.returnStack.length;
}
isStable() {
return true;
}
getCPUState() {
return { PC: this.getPC(), SP: this.getSP() }
}
saveState() {
return {
c: this.getCPUState(),
rt: this.runtime.saveState(),
}
}
loadState(state) {
this.runtime.loadState(state);
}
getDebugTree() {
return {
CurrentLine: this.runtime.getCurrentLabel(),
Variables: this.runtime.vars,
Arrays: this.runtime.arrays,
Functions: this.runtime.defs,
ForLoops: this.runtime.forLoops,
WhileLoops: this.runtime.whileLoops,
ReturnStack: this.runtime.returnStack,
NextDatum: this.runtime.datums[this.runtime.dataptr],
Clock: this.clock,
Options: this.runtime.opts,
Internals: this.runtime,
}
}
inspect(sym: string) {
let o = this.runtime.vars[sym];
if (o != null) return `${sym} = ${o}`;
}
showHelp() {
return "https://8bitworkshop.com/docs/platforms/basic/";
}
getDebugCategories() {
return ['Variables'];
}
getDebugInfo(category:string, state) : string {
switch (category) {
case 'Variables': return this.varsToLongString();
}
}
varsToLongString() : string {
var s = '';
var vars = Object.keys(this.runtime.vars);
vars.sort();
for (var name of vars) {
var value = this.runtime.vars[name];
var valstr = JSON.stringify(value);
if (valstr.length > 24) valstr = `${valstr.substr(0,24)}...(${valstr.length})`;
s += lpad(name,3) + " = " + valstr + "\n";
}
return s;
}
// TODO: debugging (get running state, etc)
onBreakpointHit : BreakpointCallback;
debugTrap : DebugCondition;
setupDebug(callback : BreakpointCallback) : void {
this.onBreakpointHit = callback;
}
clearDebug() {
this.onBreakpointHit = null;
this.debugTrap = null;
}
checkDebugTrap() : boolean {
if (this.debugTrap && this.debugTrap()) {
this.pause();
this.break();
return true;
}
return false;
}
break() {
// TODO: why doesn't highlight go away on resume?
if (this.onBreakpointHit) {
this.onBreakpointHit(this.saveState());
}
}
step() {
var prevClock = this.clock;
this.debugTrap = () => {
return this.clock > prevClock;
};
this.resume();
}
stepOver() {
var stmt = this.runtime.getStatement();
if (stmt && (stmt.command == 'GOSUB' || stmt.command == 'ONGOSUB')) {
var nextPC = this.getPC() + 1;
this.runEval(() => this.getPC() == nextPC);
} else {
this.step();
}
}
runUntilReturn() {
var prevSP = this.getSP();
this.runEval(() => this.getSP() > prevSP);
}
runEval(evalfunc : DebugEvalCondition) {
this.debugTrap = () => evalfunc(this.getCPUState());
this.resume();
}
restartAtPC?(pc:number) : boolean {
pc = Math.round(pc);
if (pc >= 0 && pc < this.runtime.allstmts.length) {
this.runtime.curpc = pc;
this.tty.cancelinput();
this.clock = 0;
return true;
} else {
return false;
}
}
readFile(path: string) : FileData {
return this.internalFiles[path];
}
writeFile(path: string, data: FileData) : boolean {
this.internalFiles[path] = data;
return true;
}
didExit() {
this.internalFiles['stdout.txt'] = this.transcript.join("");
haltEmulation();
}
}
//
PLATFORMS['basic'] = BASICPlatform;