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
|
import { getById, div, span, h, writeError } from "/common.module.js";
import lzString from "/lz-string.module.js";
let definitions = {};
let log = undefined;
let input = undefined;
export function onLoad() {
console.log('Loaded');
const form = getById("form");
input = getById("input");
log = getById("log");
form.onsubmit = async (event) => {
event.preventDefault();
await submitForm();
};
const urlParams = new URLSearchParams(window.location.search);
const queryInput = urlParams.get("in");
if (input.value.length === 0) {
input.value = lzString.decompressFromEncodedURIComponent(queryInput);
}
}
export function onUpdate() {
const urlParams = new URLSearchParams(window.location.search);
const queryInput = urlParams.get("in");
if (input.value.length === 0) {
input.value = lzString.decompressFromEncodedURIComponent(queryInput);
}
}
async function submitForm() {
console.log(input.value);
resetLog();
try {
definitions = {};
const stack = await evalString(input.value);
console.log(stack);
const path = window.location.pathname;
const params = new URLSearchParams(window.location.search);
const hash = window.location.hash;
params.set("in", lzString.compressToEncodedURIComponent(input.value));
window.history.replaceState(
{},
"",
`${path}?${params.toString()}${hash}`,
);
} catch (error) {
writeError(error);
console.log(error);
}
}
function splitWords(input) {
return input
.trim()
.split(/\s+/)
.filter((i) => i);
}
/** @param {string} inputString */
function evalString(inputString) {
let words = splitWords(inputString);
return evalWords(words);
}
function effect2(f) {
return (stack) => {
if (stack.length <= 1) throw "stack underflow, need 2 numbers";
let [x, y, ...rest] = stack;
return [f(y, x), ...rest];
};
}
const plus = effect2((a, b) => a + b);
const subtract = effect2((a, b) => a - b);
const multiply = effect2((a, b) => a * b);
const divide = effect2((a, b) => a / b);
async function evalWords(inputWords) {
let words = inputWords;
let stack = [];
while (words.length > 0) {
await writeLog(stack, words);
if (words.length === 0) return stack;
let [word, ...rest] = words;
[stack, words] = evalWord(word, stack, rest);
await new Promise((r) => setTimeout(r, 100));
}
await writeLog(stack, words);
return stack;
}
function evalWord(word, stack, rest) {
switch (word) {
case "+":
return [plus(stack), rest];
case "-":
return [subtract(stack), rest];
case "*":
return [multiply(stack), rest];
case "/":
return [divide(stack), rest];
case "dup":
return [dup(stack), rest];
case "drop":
return [drop(stack), rest];
case "swap":
return [swap(stack), rest];
case "skip":
return skip(stack, rest);
case ",,":
return unquote(stack, rest);
case ":":
return [stack, define(rest)];
default:
return parse(word, stack, rest);
}
}
function unquote(stack, rest) {
let [quote, ...restStack] = stack;
if (typeof quote === "string" || quote instanceof String) {
return [restStack, [...splitWords(quote), ...rest]];
} else {
throw "not a string, only strings are unquoteable";
}
}
function skip(stack, words) {
if (stack.length === 0) throw "stack underflow, dont know how much to skip";
let [amount, ...restStack] = stack;
if (amount > words.length)
throw `program underflow, cant skip ${amount} words`;
if (amount <= 0) return [stack.slice(1), words]; // no skipping on <= 0
let restWords = words.slice(amount);
return [restStack, restWords];
}
function define(words) {
if (words.length < 2) throw "missing definition after ':'";
let [ident, ...rest] = words;
let index = 0;
let definition = [];
for (; index < rest.length; index++) {
const word = rest[index];
if (word === ";") {
break;
} else if (rest.length - 1 === index) {
throw "expected ';', found end of program";
}
definition.push(word);
}
definitions[ident] = definition;
return rest.slice(index + 1);
}
function dup(stack) {
if (stack.length === 0) throw "stack underflow, nothing to duplicate";
let [x, ...rest] = stack;
return [x, x, ...rest];
}
function drop(stack) {
if (stack.length === 0) throw "stack underflow, nothing to drop";
let [_, ...rest] = stack;
return rest;
}
function swap(stack) {
if (stack.length < 2) throw "stack underflow, not enough to swap";
let [x, y, ...rest] = stack;
return [y, x, ...rest];
}
function parse(word, stack, rest) {
if (word.startsWith('"')) {
return parseString(word, stack, rest);
}
if (word in definitions) {
return [stack, [...definitions[word], ...rest]];
}
let num = Number(word);
if (isNaN(num)) {
throw `word '${word}' not recognised`;
}
return [[num, ...stack], rest];
}
function parseString(word, stack, rest) {
if (word.length > 1 && word.endsWith('"')) {
return [[word.slice(1, -1), ...stack], rest];
}
let string = word.slice(1);
let index = 0;
for (; index < rest.length; index++) {
const word = rest[index];
if (word.endsWith('"')) {
string = string.concat(" ", word.slice(0, -1));
break;
} else if (rest.length - 1 === index) {
throw "expected word ending with '\"', found end of program";
}
string = string.concat(" ", word);
}
return [[string, ...stack], rest.slice(index + 1)];
}
function writeLog(stack, words) {
return new Promise((resolve, _reject) => {
let log_left = span(`[${stack.join(", ")}]`);
let log_right = span(words.join(" "));
if (words.length === 0) {
log_left.textContent += " <==";
}
let log_row = div(log_left, log_right);
log_row.className = "flex-spread";
log.appendChild(log_row);
resolve();
});
}
function resetLog() {
if (!log.hasChildNodes()) return;
let summary = h("summary");
summary.textContent = log.firstChild.lastChild.textContent;
let old_log = log.cloneNode(true);
old_log.id = "";
let details = h("details", summary, old_log);
details.className = "history";
log.insertAdjacentElement("afterend", details);
log.replaceChildren(); //remove children, clear log
}
|