X-Git-Url: https://git.kengrimes.com/?p=watForth.git;a=blobdiff_plain;f=forth.js;h=3dbfc2b78daef434efcb2b2c8e97ebd61927e25a;hp=27804d0208b2ad0e49b1c672d5faecd0ef9188d1;hb=fb7946e17777ee389e3eaf742e6ff87a5d832710;hpb=d30761f3974c9a6ccc543392c20060885ca91a36 diff --git a/forth.js b/forth.js index 27804d0..3dbfc2b 100644 --- a/forth.js +++ b/forth.js @@ -11,84 +11,247 @@ You should have received a copy of the GNU General Public License along with this program. If not, see . */ 'use strict' -const initialize = Promise.all([ - fetch('forth.forth').then((re) => re.text()), - fetch('forth.wasm').then(re => re.arrayBuffer()) -]) -window.onload = () => { - const simstack = [] - const rstack = [] +/* State */ +const output = { + print: (string) => {}, + updateViews: () => {} +} +const channels = [] +let wasmMem, forth + +/* Init */ +Promise.all([ + fetch('forth.forth', {credentials: 'include', headers:{'content-type':'text/plain'}}).then((re) => re.text()), + fetch('forth.wasm', {credentials: 'include', headers:{'content-type':'application/wasm'}}).then(re => re.arrayBuffer()) +]).then((results) => { + WebAssembly.instantiate(results[1], wasmImport).then((module) => { + wasmMem = module.instance.exports.memory.buffer + forth = (chno, data) => { + if (typeof chno !== "number") { + data = chno + chno = 0 + } + channels[chno].writeEnv(data) + if (chno === 0) + output.print(data) + module.instance.exports.main(chno) + output.updateViews() + } + console.log('wasm loaded') + forth(results[0]) + }) +}) + +/* Environment functions */ +const wasmString = (addr, u) => + String.fromCharCode.apply( + null, + new Uint16Array(wasmMem, addr, u >> 1) + ) +const strToArrayBuffer = (str) => { + const buf = new ArrayBuffer(str.length << 1); + const bufView = new Uint16Array(buf); + for (let i = 0, strLen = str.length; i < strLen; i++) + bufView[i] = str.charCodeAt(i); + return buf; +} +const bufJoin = (buf1, buf2) => { + const newBuf = new Uint8Array(buf1.byteLength + buf2.byteLength) + newBuf.set(new Uint8Array(buf1), 0) + newBuf.set(new Uint8Array(buf2), buf1.byteLength) + return newBuf.buffer +} + +/* I/O Channel Drivers */ +class Channel { + constructor(opt) { + opt.chno = channels.indexOf(undefined) + if (opt.chno === -1) + opt.chno = channels.length + Object.assign(this, opt) + if (this.buffer === undefined) + this.buffer = new ArrayBuffer(0) + channels[this.chno] = this + return this + } + read(writeAddr, maxBytes) { + const wasmView = new Uint8Array(wasmMem, writeAddr, maxBytes) + const bufBytes = Math.min(maxBytes, this.buffer.byteLength) + const bufView = new Uint8Array(this.buffer, 0, bufBytes) + wasmView.set(bufView, 0) + this.buffer = this.buffer.slice(bufBytes) + return bufBytes + } + write(readAddr, maxBytes) { + const newBuf = new Uint8Array(this.buffer.byteLength + maxBytes) + newBuf.set(new Uint8Array(this.buffer), 0) + newBuf.set(new Uint8Array(wasmMem, readAddr, maxBytes), this.buffer.byteLength) + this.buffer = newBuf + } + writeEnv(data) { + switch (typeof data) { + case "string": + this.buffer = bufJoin(this.buffer, strToArrayBuffer(data)) + break + case "object" : + if (data instanceof ArrayBuffer) + this.buffer = bufJoin(this.buffer, data) + else + this.buffer = bufJoin(this.buffer, strToArrayBuffer(JSON.stringify(data))) + break + case "number" : + const buf = new ArrayBuffer(4) + new DataView(buf, 0, 4).setInt32(data) + this.buffer = bufJoin(this.buffer, buf) + break + default : + console.error(`environment wrote unhandled object: ${data}`) + return + } + } +} +/* 0 STDIN, 1 STDOUT, 2 STDERR */ +new Channel({ + write(readAddr, maxBytes) { + super.write(readAddr, maxBytes) + output.print(wasmString(readAddr, maxBytes)) + } +}) +new Channel({ + read(writeAddr, maxBytes) { return 0 }, + write(readAddr, maxBytes) { output.print(`\\\ => ${wasmString(readAddr, maxBytes)}\n`) } +}) +new Channel({ + read(writeAddr, maxBytes) { return 0 }, + write(readAddr, maxBytes) { console.error(wasmString(readAddr, maxBytes)) } +}) + +/* System runtime */ +const simstack = [] +const rstack = [] +const dictionary = { EXECUTE: 12 } +const doesDictionary = {} +const wasmImport = { + env: { + pop: () => simstack.pop(), + push: (val) => simstack.push(val), + rinit: () => rstack.length = 0, + rpop: () => rstack.length ? rstack.pop() : 16388, + rpush: (val) => rstack.push(val), + sys_write: (chno, addr, u) => channels[chno] === undefined ? 0 : channels[chno].write(addr, u), + sys_read: (chno, addr, u) => channels[chno] === undefined ? 0 : channels[chno].read(addr, u), + sys_listen: (chno, cbAddr, addr, u) => { //sys_connect? + //TODO: call into the module to wasm fn "event" to push an event + //to forth, which pushes esi to the return stack and queues the + //callback function provided from listen. reqaddr could be + //"fetch", in which case no channel is used. otherwise very + //similar to sys_fetch. + + //callbacks are events, like listen events + //totally event-driven, one listener per event + //other listen types: mouse, keyboard, touch, main_loop (10ms interval), wrtc, etc + //fetch is different because it offers no "write" interface, doesn't repeat + }, + sys_fetch: (cbAddr, addr, u) => { + const str = wasmString(addr, u) + console.log(`fetching: ${str}`) + const args = JSON.parse(wasmString(addr, u)) + console.log(args) + const url = args.url + delete args.url + const channel = new Channel() + fetch(url, args).then((re) => { + if (args.headers === undefined || + args.headers['content-type'] === undefined || + args.headers['content-type'].toLowerCase().indexOf('text/plain') === 0 ) + re.text().then((txt) => forth(channel.chno, txt)) + else { + const reader = new FileReader() + reader.onload = (evt) => forth(channel.chno, evt.target.result) + re.blob().then((blob) => reader.readAsArrayBuffer(blob)) + } + }).catch(console.error) + //TODO: map to fetch promise, write to channel buffer, + //javascript "fetch" as fallback, explicit handles for + //"textEntry" or any third party protocols like activitypub + return channel.chno + }, + sys_close: (chno) => delete channels[chno], + sys_echo: (val, base) => output.print(`\\\ => ${val.toString(base)} `), + sys_echochar: (val) => output.print(String.fromCharCode(val)), + sys_reflect: (addr) => { + console.log(`reflect: ${addr}: ${ + new DataView(wasmMem, addr, 4) + .getUint32(0,true) + }`) + }, + vocab_get: (addr, u) => dictionary[wasmString(addr, u).toUpperCase()] || 0, + vocab_set: (addr, u, v) => dictionary[wasmString(addr, u).toUpperCase()] = v, + does_get: (addr, u) => doesDictionary[wasmString(addr, u).toUpperCase()] || 0, + does_set: (addr, u, v) => doesDictionary[wasmString(addr, u).toUpperCase()] = v, + is_whitespace: (key) => /\s/.test(String.fromCharCode(key)), + sys_stack: () => console.log(`[${simstack}][${rstack}]`), + sys_parsenum: (addr, u, base) => { + const answer = Number.parseInt(wasmString(addr, u), base) + if (Number.isNaN(answer)) + return -1 + new DataView(wasmMem, addr, 4).setUint32(0,answer,true) + return 0 + }, + sys_words: () => { + output.print(Object.getOwnPropertyNames(dictionary).toString().split(',').join(' ')) + } + } +} + +/* View Logic */ +window.onload = () => { let forthdiv = document.getElementById("forth") if (forthdiv === null) { forthdiv = document.createElement("div") - forthdiv.setAttribute("style","height:100%;margin:auto;width:80%;") + forthdiv.setAttribute("style","height:100%;margin:auto;width:100%;max-width:640px;overflow-x:hidden;") document.body.appendChild(forthdiv) } const outframe = document.createElement("div") - outframe.setAttribute("style", "background-color:black;padding-left:6px;padding-right:6px;color:chartreuse;height:256px;resize:vertical;display:flex;align-items:flex-end;") + outframe.setAttribute("style", "background-color:black;padding-left:6px;padding-right:6px;color:chartreuse;height:268px;resize:vertical;display:flex;align-items:flex-end;flex-flow:row;") const stackview = document.createElement("pre") - stackview.setAttribute("style", "white-space:pre-wrap;flex:0 1 8%;") + stackview.setAttribute("style", "white-space:pre-wrap;flex:0 0 6%;") outframe.appendChild(stackview) const txtoutput = document.createElement("pre") - txtoutput.setAttribute("style", "white-space:pre-wrap;overflow-y:scroll;flex:1 0 342px;") + txtoutput.setAttribute("style", "white-space:pre-wrap;max-height:256px;overflow-y:scroll;flex:1 0 342px;") outframe.appendChild(txtoutput) - const rstackview = document.createElement("pre") + /* const rstackview = document.createElement("pre") rstackview.setAttribute("style", "white-space:pre-wrap;flex:0 1 8%;") - outframe.appendChild(rstackview) + outframe.appendChild(rstackview) */ const memview = document.createElement("pre") - memview.setAttribute("style", "white-space:pre-wrap;flex:0 0 356px;") + memview.setAttribute("style", "padding-left: 8px; white-space:pre-wrap;flex:0 0 88px;") outframe.appendChild(memview) const txtinput = document.createElement("textarea") txtinput.setAttribute("autofocus", "true") - txtinput.setAttribute("rows", "1") - txtinput.setAttribute("style", "white-space:pre;margin-left:8%;width:60%;") - txtinput.oninput = () => txtinput.rows = (txtinput.value.match(/[\n]/g) || [1]).length; - forthdiv.appendChild(outframe) - forthdiv.appendChild(txtinput) - let wasmMem - let forth - const output = { - print: (string) => txtoutput.textContent += `\\\ => ${string} \n` - } - const updateViews = () => { - stackview.textContent = simstack.join('\n') - rstackview.textContent = rstack.join('\n') - let cnt = 0; - const maxBytes = 256 - let here = new DataView(wasmMem.buffer, 14340 /* here */, 4).getUint32(0,true) - memview.textContent = Array.from(new Uint8Array(wasmMem.buffer, here - maxBytes, maxBytes), (v) => { - cnt++; - v = ('0' + (v & 0xFF).toString(16)).slice(-2) - if (cnt === maxBytes) - return v - if ((cnt % 16) === 0) - return v + '\n' - if ((cnt % 4) === 0) - return v + ', ' - return v + ' ' - }).join('') - outframe.scrollTop = outframe.scrollHeight - } - /* Input capture */ - let stdin = "" - txtinput.addEventListener('keydown', (event) => { + txtinput.setAttribute("wrap", "hard") + txtinput.setAttribute("style", "resize:none;white-space:pre;margin-left:6%;width:77%;") + txtinput.oninput = () => txtinput.setAttribute("rows", ((txtinput.value.match(/[\n]/g) || [1]).length + 1).toString()); + txtinput.oninput() + txtinput.onkeydown = (event) => { switch (event.key) { case "Enter": if (event.ctrlKey) { - txtinput.value += '\n' + const endPos = txtinput.selectionStart + 1 + txtinput.value = + txtinput.value.substring(0, txtinput.selectionStart) + + '\n' + + txtinput.value.substring(txtinput.selectionEnd, txtinput.value.length) + txtinput.setSelectionRange(endPos, endPos) txtinput.oninput() } else { - stdin += txtinput.value - txtoutput.textContent += txtinput.value if (!/\s/.test(txtinput.value.slice(-1))) - txtoutput.textContent += " " - txtinput.value = "" + txtinput.value += " " event.preventDefault() event.stopPropagation() - forth() - updateViews() + forth(txtinput.value) + txtinput.value = "" } break case "Backspace": @@ -96,145 +259,30 @@ window.onload = () => { default: break } - }) - const channels = [{ - read: (writeAddr, maxBytes) => { - const maxChars = maxBytes >> 1 - const bufView = new Uint16Array(wasmMem.buffer, writeAddr, maxChars) - let i - for (i = 0; i < maxChars && i < stdin.length; i++) - bufView[i] = stdin.charCodeAt(i) - stdin = stdin.substring(maxChars) - return i << 1 - }, - write: (readAddr, maxBytes) => - output.print(String.fromCharCode.apply( - null, - new Uint16Array(wasmMem.buffer, readAddr, maxBytes >> 1) - )) - }] - const dictionary = { - ';': 1, - 'LIT': 2, - RINIT: 3, - WORD: 16500, - KEY: 5, - DUP: 6, - '+': 7, - 'NOOP2': 8, - '.': 9, - '@': 10, - '!': 11, - EXECUTE: 12, - NOOP: 13, - 'JZ:': 14, - 'JNZ:': 15, - DROP: 16, - 'WS?': 17, - 'JMP:': 18, - 'WPUTC': 19, - 'WB0': 20, - 'FIND': 21, - 'NUMBER': 22, - 'W!LEN': 23, - 'J-1:': 24, - 'BYE': 25, - 'SWAP': 26, - 'WORDS': 27, - 'HERE': 28, - 'DEFINE': 29, - '2DUP': 30, - 'ROT': 31, - '2DROP': 32, - ',': 33, - '-': 34, - 'CHANNEL!': 35, - 'HERE!': 36, - '=?': 37, - '.S': 38, - 'STRING-START': 39, - 'STRING-PUT': 40, - 'STRING-END': 41, - ':': 16800, - 'MODE': 14336, - 'EXECUTE-MODE': 16680, - 'QUIT': 16384, - 'INTERPRET': 16400 } - const wasmImport = { - env: { - pop: () => simstack.pop(), - push: (val) => simstack.push(val), - rinit: () => rstack.length = 0, - rpop: () => rstack.pop(), - rpush: (val) => rstack.push(val), - sys_write: (channel, addr, u) => channels[channel] === undefined ? 0 : channels[channel].write(addr, u), - sys_read: (channel, addr, u) => channels[channel] === undefined ? 0 : channels[channel].read(addr, u), - sys_listen: (reqAddr, cbAddr) => { - //TODO: call into the module to wasm fn "event" to push an event - //to forth, which pushes esi to the return stack and queues the - //callback function provided from listen. reqaddr could be - //"fetch", in which case no channel is used. otherwise very - //similar to sys_fetch. - }, - sys_fetch: (channel, reqAddr) => { - //TODO: map to fetch promise, write to channel buffer, - //javascript "fetch" as fallback, explicit handles for - //"textEntry" or any third party protocols like activitypub - console.log(`fetch ${channel} ${reqAddr}`) - }, - sys_echo: (val) => output.print(`${val} `), - sys_echochar: (val) => output.print(String.fromCharCode(val)), - sys_reflect: (addr) => { - console.log(`reflect: ${addr}: ${ - new DataView(wasmMem.buffer, addr, 4) - .getUint32(0,true) - }`) - }, - vocab_get: (addr, u) => { - const word = String.fromCharCode.apply( - null, - new Uint16Array(wasmMem.buffer, addr, u >> 1) - ) - const answer = dictionary[word.toUpperCase()] - if (answer === undefined) - return 0 - return answer - }, - vocab_set: (addr, u, num) => { - const word = String.fromCharCode.apply( - null, - new Uint16Array(wasmMem.buffer, addr, u >> 1) - ) - dictionary[word.toUpperCase()] = num - return 0 - }, - is_whitespace: (key) => /\s/.test(String.fromCharCode(key)), - sys_stack: () => console.log(`[${simstack}]`), - sys_parsenum: (addr, u, base) => { - const word = String.fromCharCode.apply( - null, - new Uint16Array(wasmMem.buffer, addr, u >> 1) - ) - const answer = Number.parseInt(word, base) - if (Number.isNaN(answer)) - return -1 - new DataView(wasmMem.buffer, addr, 4).setUint32(0,answer,true) - return 0 - }, - sys_words: () => { - output.print(Object.getOwnPropertyNames(dictionary).toString().split(',').join(' ')) - } - } + forthdiv.appendChild(outframe) + forthdiv.appendChild(txtinput) + /* Set up output functions */ + output.print = (string) => txtoutput.textContent += string, + output.updateViews = () => { + const base = new DataView(wasmMem, 14348 /* base */, 4).getUint32(0,true) + stackview.textContent = simstack.map((v) => v.toString(base)).join('\n') + // rstackview.textContent = rstack.join('\n') + let cnt = 0; + const maxBytes = 64 + let here = new DataView(wasmMem, 14340 /* here */, 4).getUint32(0,true) + memview.textContent = Array.from(new Uint8Array(wasmMem, here - maxBytes, maxBytes), (v) => { + cnt++; + v = ('0' + (v & 0xFF).toString(16)).slice(-2) + if (cnt === maxBytes) + return v + if ((cnt % 16) === 0) + return `${v}\n=> ${(here -maxBytes + cnt).toString(base)}\n` + if ((cnt % 4) === 0) + return `${v}\n` + return `${v} ` + }).join('') + outframe.scrollTop = outframe.scrollHeight + txtoutput.scrollTop = txtoutput.scrollHeight } - initialize.then((results) => { - stdin = results[0] - WebAssembly.instantiate(results[1], wasmImport).then((module) => { - wasmMem = module.instance.exports.memory - forth = module.instance.exports.main - console.log('wasm loaded') - forth() - updateViews() - }) - }) }