-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmd-basic.js
703 lines (655 loc) · 21.4 KB
/
md-basic.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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
const ARBITRARY_ARITY = -1
class MDBError {
constructor(msg, location) {
this.msg = msg
this.location = location
}
}
export default class MDBasic {
constructor(doc = window.document.body) {
this.doc = doc
this.PC = this.findPC()
this.lastOutput = null
this.ARGSTACK = null
this.CALLSTACK = this.obtainMemArea("_STACK")
this.STORAGE = this.obtainMemArea("_LOCAL")
this.executionSpeed = 150
this.provideStyleSheets()
this.binaryOperators = {
"+": (x,y) => x + y,
"-": (x,y) => x - y,
"*": (x,y) => x * y,
"/": (x,y) => x / y,
"^": (x,y) => x ** y,
"=": (x,y) => x == y,
"<>": (x,y) => x != y,
">": (x,y) => x > y,
"<": (x,y) => x < y,
">=": (x,y) => x >= y,
"<=": (x,y) => x <= y,
"MOD": (x,y) => x % y,
"AND": (x,y) => x & y,
"OR": (x,y) => x | y,
}
this.builtInFunctions = {
// memory management
"input": {
arity: ARBITRARY_ARITY,
documentation: "Fill variables with values from the input stack.",
lazy: true,
fun: (...vars) => {
this.popArgs(vars)
}
},
"output": {
arity: ARBITRARY_ARITY,
documentation: "Add a value to the output history.",
fun: (...outs) => {
this.output(outs)
}
},
"push": {
arity: ARBITRARY_ARITY,
documentation: "Add a value to the input stack.",
fun: (...outs) => {
this.pushArgs(outs)
}
},
"stash": {
arity: 0,
documentation: "Serialize local memory including variable labels into a string.",
fun: () => {
return this.quoteMemory(this.STORAGE, true)
}
},
"unstash": {
arity: 1,
documentation: "Fill local memory with named variables and their content from a string.",
fun: (quotedMem) => {
return this.loadMemory(this.STORAGE, quotedMem)
}
},
"clone": {
arity: 1,
documentation: "Create a shallow copy of a complex value on the heap and return its reference.",
fun: (obj) => {
return this.cloneObject(obj)
}
},
"delete": {
arity: ARBITRARY_ARITY,
documentation: "Remove objects from the heap.",
fun: (...objs) => {
objs.forEach(this.deleteObject)
}
},
// math functions
"abs": {
arity: 1,
documentation: "Take the absolute value of a number",
fun: (x) => Math.abs(x)
},
// list functions
"length": {
arity: 1,
documentation: "Determine length of a list",
fun: (x) => {
if (x.children && x.children.length !== undefined) {
return x.children.length
} else {
throw new MDBError(`Does not have a length: ${x}`, x)
}
}
},
// conversions
"string": {
arity: 1,
documentation: "Convert a value to a string",
fun: (x) => x.outerHTML || x.toString()
},
}
// auto-start if there is a RUNNING tag
if (this.PC) this.run()
}
obtainMemArea(id) {
let mem = this.doc.querySelector(`#${id}`)
if (mem === null) {
mem = window.document.createElement("h2")
mem.id = id
mem.innerText = id
this.doc.append(mem)
mem.insertAdjacentHTML("afterend", "<hr>")
}
return mem
}
provideStyleSheets() {
let style = document.createElement("style")
document.head.appendChild(style)
style.sheet.insertRule(".mdb-pc, .mdb-pc:first-child { background-color: rgba(100,150,250, .8) }")
style.sheet.insertRule(".mdb-pc>a, .mdb-pc>code { margin-left: .7rem}")
style.sheet.insertRule(".mdb-call { background-color: rgba(50,140,200, .6) }")
style.sheet.insertRule(".mdb-call, .mdb-pc { float: left; margin-right: -100%; transform: translate(-110%, 0px); z-index: -10;}")
style.sheet.insertRule(".mdb-debug { background-color: rgba(230,230,50, .4); float: right; }")
style.sheet.insertRule(".mdb-output { background-color: rgba(150,230,150, .5); float: right; margin-left: .7rem; margin-top: -.2rem; margin-bottom: -.2rem }")
style.sheet.insertRule(".mdb-output, .mdb-pc, .mdb-debug, .mdb-output { padding: .1rem; border-radius: .2rem }")
}
findPC() {
let pcs = [...this.doc.querySelectorAll("em")]
.filter(el => el?.firstChild?.innerText === "RUN" || el?.firstChild?.innerText === "RUNNING")
if (pcs.length === 0) {
// address that Jekyll and other systems might invert the order of strong and em...
pcs = [...this.doc.querySelectorAll("strong")]
.filter(el => el?.firstChild?.innerText === "RUN" || el?.firstChild?.innerText === "RUNNING")
}
pcs.forEach(pc => this.decoratePCPointer(pc))
return pcs.find(el => el?.firstChild?.innerText === "RUNNING")
}
decoratePCPointer(pc) {
pc.addEventListener("click", (ev) => {
if (pc.firstChild.innerHTML.split("-")[0] === "RUN") {
this.run(pc)
}
})
pc.classList.add("mdb-pc")
pc.style.cursor = "pointer"
}
findCall(stackLevel) {
return [...this.doc.querySelectorAll("em")]
.find(el => el?.firstChild?.innerText === "CALL-" + stackLevel)
}
insertCall(pc, stackLevel) {
pc.insertAdjacentHTML("beforebegin", `<em class="mdb-call"><strong>CALL-${stackLevel}</strong><em/>`)
}
run(pc) {
if (pc !== this.PC) {
this.cleanupCalls()
}
this.PC = pc || this.PC
this.ARGSTACK = pc.firstChild
if (!this.PC) {
throw "You have to name a starting position!"
}
this.setPCState("RUNNING")
this.shiftPC()
this.runStep()
}
runStep() {
if (this.getPCState() === "RUNNING") {
try {
this.executeLine(this.getPCLocation())
setTimeout(() => this.runStep(), this.executionSpeed)
} catch (e) {
if (e instanceof MDBError) {
if (e.msg === "Program has ended.") {
this.setPCState("EXIT")
this.debugMessage(e.msg)
} else {
this.setPCState("ERROR")
this.debugMessage(e.msg, "error")
}
} else {
throw e
}
}
}
}
setPCState(state, stackLevel) {
if (stackLevel === undefined) {
stackLevel = this.getPCStackLevel()
}
this.PC.firstChild.innerHTML = state + "-" + stackLevel
}
getPCState() {
return this.PC.firstChild.innerHTML.split("-")[0]
}
getPCStackLevel() {
return parseInt(this.PC.firstChild.innerHTML.split("-")[1]) || 0
}
getPCLocation() {
return this.PC.nextSibling || this.PC.parentElement.nextSibling
}
debugMessage(message, mode = "info") {
this.getPCLocation().insertAdjacentHTML("beforeend", `<div class="mdb-debug alert alert-${mode} part">${message}</div>`)
}
isMDBElement(element) {
return element.classList &&
Array.from(element.classList.values()).some(c => c.startsWith("mdb-"))
}
shiftPC(skipElse = true) {
let newPCScope = this.getPCLocation()
// move out of nested code blocks
while (true) {
if (newPCScope.nextElementSibling) {
this.setPC(newPCScope.nextElementSibling)
if (skipElse && this.getPCLocation()?.innerText.match(/^ELSE\W/i)) {
// skip ELSE branches when moving out of blocks
// (= they have to be reached through IF jumps.)
this.shiftPC()
}
return
} else {
newPCScope = newPCScope.parentElement
if (newPCScope.innerText.match(/^WHILE\W/i)) {
// loop at whiles
this.setPC(newPCScope)
return
} else if (newPCScope instanceof HTMLQuoteElement) {
throw new MDBError("Hit end of quoted code block.")
}
}
}
}
setPC(newPCLocation) {
if (newPCLocation === null || newPCLocation instanceof HTMLHRElement) {
if (this.getPCStackLevel() !== 0) {
throw new MDBError("Program ended unexpectedly during a function call. (Missing <code>RETURN</code>?)")
} else {
throw new MDBError("Program has ended.")
}
}
while (newPCLocation instanceof HTMLUListElement || newPCLocation instanceof HTMLOListElement) {
// move into list blocks
newPCLocation = newPCLocation.children[0]
}
newPCLocation.insertAdjacentElement("beforebegin", this.PC)
}
executeLine(line) {
let tokens = this.tokenizeLine(line)
console.log(tokens)
const command = tokens.shift()
const oldPC = this.PC
switch (typeof command === "string" && command.toLowerCase()) {
case "if":
const cond = this.readArguments(tokens, false, "then").shift()
if (cond) {
this.setPC(tokens.shift())
} else {
this.shiftPC(false)
}
tokens.length = 0
break
case "else":
if (tokens[0].toLowerCase && tokens[0].toLowerCase() === "if") {
tokens.shift()
const cond = this.readArguments(tokens, false, "then").shift()
if (cond) {
this.setPC(tokens.shift())
} else {
this.shiftPC(false)
}
tokens.length = 0
} else {
this.setPC(tokens.shift())
}
break
case "while":
const whileCond = this.readArguments(tokens, false, "do").shift()
if (whileCond) {
this.setPC(tokens.shift())
} else {
this.shiftPC(false)
}
tokens.length = 0
break
case "goto":
this.setPC(this.readArguments(tokens, true).shift())
break
case "return":
const returnValues = this.readArguments(tokens)
this.output(returnValues)
this.popStack()
this.shiftPC()
break
default:
if (command !== null) {
tokens.unshift(command)
const returns = this.readExpression(tokens, false)
if (returns?.function) {
// invoke a user defined function
this.pushArgs(returns.args)
this.pushStack(this.getPCLocation(), returns.writeback)
this.setPC(returns.function)
} else {
this.shiftPC()
}
}
}
if (tokens.length !== 0) {
// restore previous position in order to highlight the line where the error occurred
this.setPC(oldPC)
throw new MDBError("Could not parse the line. Remainder: " + tokens)
}
}
tokenizeLine(line) {
const tokens = []
for (let e of line.childNodes) {
if (e instanceof Text) {
const subtokens =
e.data.match(/\-?[a-z0-9\_]+|,|\]|\[|\(|\)|\:\=|[\>\<\=\^]+|[\+\-\*\/]/gi)
if (subtokens) {
tokens.push(...subtokens)
}
} else if (!this.isMDBElement(e)) {
tokens.push(e)
}
}
return tokens
}
readArguments(lineTokens, lazy = false, end = "") {
const args = []
if (lineTokens.length === 0) return args
if (lineTokens[0].toLowerCase && lineTokens[0].toLowerCase() === end) {
lineTokens.shift()
return args
}
while (true) {
if (lazy) {
args.push(this.readVariable(lineTokens))
} else {
args.push(this.readExpression(lineTokens))
}
if (lineTokens.length === 0) {
return args
} else if (lineTokens[0].toLowerCase && lineTokens[0].toLowerCase() === end) {
lineTokens.shift()
return args
} else {
this.parseConsume(lineTokens, ",")
}
}
}
readExpression(lineTokens, requireReturns = true) {
const mainToken = lineTokens[0]
let value = mainToken
if (typeof mainToken === "string" && mainToken.match(/\-?[0-9]+/)) {
// token is an integer literal
value = parseInt(mainToken)
lineTokens.shift()
} else if (typeof mainToken === "string" || mainToken instanceof HTMLAnchorElement) {
// the token is a variable and will be resolved
value = this.readVariable(lineTokens)
if (lineTokens[0] === ":=") {
// we are updating an assignment
lineTokens.shift()
const newValue = this.readExpression(lineTokens)
if (newValue.function) {
newValue.writeback = value
value = newValue
} else {
this.assign(value, newValue)
}
} else if (lineTokens[0] === "("){
// we are calling a function
lineTokens.shift()
const args = this.readArguments(lineTokens, value.lazy, ")")
value = this.callFunction(value, args)
} else if (!requireReturns) {
// we are calling a function in command syntax (==> no returns!)
const args = this.readArguments(lineTokens, value.lazy)
this.callFunction(value, args)
}
if (value === undefined) {
if (requireReturns) {
throw new MDBError("This command does not return values.")
} else {
return
}
}
} else {
lineTokens.shift()
}
value = this.unwrapValue(value)
// try to read infix operators (right-associatively for now)
if (lineTokens[0] in this.binaryOperators) {
const op = this.binaryOperators[lineTokens[0]]
lineTokens.shift()
const secondArg = this.readExpression(lineTokens)
this.checkValuesPrimitive(value, secondArg)
value = op(value, secondArg)
}
console.log("Eval returns", value)
return value
}
/* returns the cell where the content of a variable is stored*/
readVariable(lineTokens) {
let mainToken = lineTokens.shift()
let normalizedName = mainToken.hash?.slice(1) || mainToken.toLowerCase()
if (!normalizedName.match(/\w+/i)) {
if (normalizedName === "=") {
throw new MDBError(`Please use <code>:=</code> for variable assignments! (<code>=</code> is reserved for comparing values.)`)
} else {
throw new MDBError(`Proper identifier expected, but found <code>${normalizedName}</code>. (Only alphanumeric characters are allowed here!)`)
}
}
let value = window.document.querySelector(`#${normalizedName}`)
if (value === null) {
if (normalizedName in this.builtInFunctions) {
// look up the name in the build-in functions
value = this.builtInFunctions[normalizedName]
} else {
// non-existent variables will implicitly be created
value = this.createVar(normalizedName)
}
}
if (lineTokens[0] === "[") {
// we are navigating an array
lineTokens.shift()
const offset = this.readExpression(lineTokens)
this.parseConsume(lineTokens, "]")
value = this.resolve(value, offset)
} else {
value = this.resolve(value)
}
return value
}
resolve(label, offset = undefined) {
if (label.arity !== undefined) {
// this is a built-in function and needs no further resolution
return label
}
let value = label.nextElementSibling
// automatically resolve heap references
while (value.localName === "a") {
console.log("Lookup address", value.hash)
const result = window.document.querySelector(`${value.hash}`)?.nextElementSibling
if (result) {
value = result
} else {
throw new MDBError(`Could not find object ${value.hash}! (Likely due to a dangling reference.)`)
}
}
if (offset !== undefined) {
value = value.children[offset]
if (value === undefined) {
throw new MDBError(`${offset} out of bounds.`)
}
}
if (value === undefined || value.localName === "hr") {
throw new MDBError(`Ran into a memory barrier when accessing <code>${label.textContent}</code>!`)
}
return value
}
/* unwrap what has been saved in a memory value to be used in interpretation */
unwrapValue(value) {
if (["code", "pre", "li", "p"].includes(value.localName)) {
value = value.textContent
if (value.match(/^\-?[0-9]+$/)) {
value = parseInt(value)
}
}
return value
}
/* wrap a value from interpretation to be written to memory as HTML element */
wrapValue(value) {
if (value.localName) {
// it's already some kind of HTML element
return this.createRef(value)
} else {
const element = window.document.createElement("code")
element.innerText = value
return element
}
}
checkValuesPrimitive(...values) {
const nonPrimitive = values.find(v => typeof v === "object" || typeof v === "function")
if (nonPrimitive?.function) {
throw new MDBError(`You may not place a call to a user-defined function like this.`)
} else if (nonPrimitive) {
throw new MDBError(`Expected primitive value but found ${nonPrimitive}.`)
}
}
peek(label) {
return this.unwrapValue(this.resolve(label))
}
/* quotes a part of the document till the end or <hr> is reached */
quoteMemory(label, andDelete = false) {
let quoted = ""
label = label.nextSibling
while (label !== null && !(label instanceof HTMLHRElement)) {
quoted += label.outerHTML || label.textContent
const newLabel = label.nextSibling
if (andDelete) {
label.remove()
}
label = newLabel
}
return quoted
}
/* inserts quoted memory into active memory */
loadMemory(label, quotedMem) {
label.insertAdjacentHTML("afterend", quotedMem)
}
output(out) {
for (let o of out) {
const outText = this.wrapValue(o)
this.lastOutput = window.document.createElement("span")
this.lastOutput.classList.add("mdb-output")
this.lastOutput.appendChild(outText)
this.getPCLocation().insertAdjacentElement("beforeend", this.lastOutput)
}
}
getLastOutput() {
return this.unwrapValue(this.lastOutput.firstChild)
}
createVar(name) {
const variable = window.document.createElement("h4")
variable.id = name
variable.textContent = name
const emptyCell = this.wrapValue("")
this.STORAGE.insertAdjacentElement("afterend", variable)
variable.insertAdjacentElement("afterend", emptyCell)
return variable
}
createRef(variable) {
variable = this.getLabel(variable)
const ref = window.document.createElement("a")
ref.href = "#"+variable
ref.innerText = variable
return ref
}
cloneObject(value) {
if (value.localName) {
const cloneId = "clone_" + Math.floor(Math.random() * 65536)
const clone = value.cloneNode(true)
const cloneLabel = window.document.createElement("h4")
cloneLabel.id = cloneId
cloneLabel.textContent = cloneId
value.insertAdjacentElement("afterend", cloneLabel)
cloneLabel.insertAdjacentElement("afterend", clone)
return clone
} else {
throw new MDBError("You may only clone heap objects!")
}
}
deleteObject(value) {
if (value.localName && value.previousElementSibling?.id) {
value.previousElementSibling.remove()
value.remove()
} else {
throw new MDBError("You may only delete labeled heap objects!")
}
}
assign(cell, value) {
console.log(`Assing ${this.getLabel(cell)} with value ${value}.`)
cell.insertAdjacentElement("beforebegin", this.wrapValue(value))
cell.remove()
}
getLabel(object) {
return object?.previousElementSibling?.id
}
callFunction(func, args) {
if (func.arity !== undefined) {
if (args.length === func.arity || func.arity === ARBITRARY_ARITY) {
if (args.some(a => a.function)) {
throw new MDBError(`User-defined functions may not be appear as arguments to function calls.`)
}
return func.fun(...args)
} else {
throw new MDBError(`Expected ${func.arity} arguments but received ${args.length}.`)
}
} else {
return {
function: func,
args: args,
writeback: undefined
}
}
}
pushArgs(args) {
for (let o of args.reverse()) {
this.ARGSTACK.insertAdjacentElement("afterend", this.wrapValue(o))
}
}
popArgs(args) {
for (let cell of args) {
this.assign(cell, this.peek(this.ARGSTACK))
this.ARGSTACK.nextElementSibling.remove()
}
}
pushStack(pc, writebackAddress = undefined) {
const stackLevel = this.getPCStackLevel()
this.insertCall(pc, stackLevel)
if (writebackAddress) {
writebackAddress.classList.add(`writeback-${stackLevel}`)
}
const stackEntry = this.quoteMemory(this.STORAGE, true)
this.CALLSTACK.insertAdjacentElement("afterend", this.wrapValue(stackEntry))
this.setPCState(this.getPCState(), stackLevel + 1)
}
popStack() {
let stackLevel = this.getPCStackLevel()
if (stackLevel <= 0) {
throw new MDBError("Can't return at empty stack.")
}
stackLevel -= 1
// delete local variables and restore old local context
this.quoteMemory(this.STORAGE, true)
let stackEntry = this.CALLSTACK.nextElementSibling
this.loadMemory(this.STORAGE, this.unwrapValue(stackEntry))
stackEntry.remove()
// restore PC
let oldPC = this.findCall(stackLevel)
this.setPC(oldPC)
oldPC.remove()
// if a writeback is expected, perform it from output stack
const writeback = window.document.querySelector(`.writeback-${stackLevel}`)
if (writeback) {
writeback.classList.remove(`writeback-${stackLevel}`)
this.assign(writeback, this.getLastOutput())
}
this.setPCState(this.getPCState(), stackLevel)
}
cleanupCalls() {
let stackLevel = (!this.PC && -1) || this.getPCStackLevel()
for (let i = 0; i < stackLevel; i++) {
window.document.querySelectorAll(`.writeback-${i}`).forEach(e => e.remove())
this.findCall(i).remove()
}
}
parseConsume(tokens, expectation) {
const token = tokens.shift()
if (expectation !== token) {
throw new MDBError(`Expected \`${expectation}\` but found \`${token}\`!`)
}
}
}