channels working
[watForth.git] / forth.js
1 /* This program is free software: you can redistribute it and/or modify
2 it under the terms of the GNU General Public License as published by
3 the Free Software Foundation, either version 3 of the License, or
4 (at your option) any later version.
5
6 This program is distributed in the hope that it will be useful,
7 but WITHOUT ANY WARRANTY; without even the implied warranty of
8 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
9 GNU General Public License for more details.
10
11 You should have received a copy of the GNU General Public License
12 along with this program. If not, see <http://www.gnu.org/licenses/>. */
13 'use strict'
14
15 /* State */
16 const output = {
17 print: (string) => {},
18 updateViews: () => {}
19 }
20 let wasmMem, wasmMain
21
22 /* Environment functions */
23 const bufString = (arrayBuf, addr, u) =>
24 String.fromCharCode.apply(null, new Uint16Array(arrayBuf, addr, u >> 1))
25 const wasmString = (addr, u) => bufString(wasmMem, addr, u)
26 const wasmBase = () => new DataView(wasmMem, 14348, 4).getUint32(0,true)
27 const strToArrayBuffer = (str) => {
28 const buf = new ArrayBuffer(str.length << 1)
29 const bufView = new Uint16Array(buf)
30 for (let i = 0, strLen = str.length; i < strLen; i++)
31 bufView[i] = str.charCodeAt(i)
32 return buf
33 }
34 const bufJoin = (buf1, buf2) => {
35 const newBuf = new Uint8Array(buf1.byteLength + buf2.byteLength)
36 newBuf.set(new Uint8Array(buf1), 0)
37 newBuf.set(new Uint8Array(buf2), buf1.byteLength)
38 return newBuf.buffer
39 }
40
41 /* I/O Channel Drivers */
42 const channels = []
43 const getChannel = (chno) => {
44 const channel = channels[chno]
45 if (!channel)
46 throw new Error(`invalid channel access ${chno}`)
47 return channel
48 }
49 class Channel {
50 constructor(opt) {
51 opt = opt || Object.create(null)
52 opt.chno = channels.indexOf(undefined)
53 if (opt.chno === -1)
54 opt.chno = channels.length
55 Object.assign(this, opt)
56 if (this.buffer === undefined)
57 this.buffer = new ArrayBuffer(0)
58 channels[this.chno] = this
59 return this
60 }
61 read(writeArray, writeAddr, writeMax) {
62 const bufBytes = Math.min(writeMax, this.buffer.byteLength)
63 new Uint8Array(writeArray).set(new Uint8Array(this.buffer, 0, bufBytes), writeAddr)
64 this.buffer = this.buffer.slice(bufBytes)
65 return bufBytes
66 }
67 write(readArray, readAddr, readSize) {
68 this.buffer = bufJoin(this.buffer, new Uint8Array(readArray, readAddr, readSize))
69 wasmMain(this.chno)
70 output.updateViews()
71 }
72 send(readArray, readAddr, readSize) {
73 this.write(readArray, readAddr, readSize)
74 }
75 }
76
77 /* System runtime */
78 const simstack = []
79 const rstack = []
80 const dictionary = { EXECUTE: 12 }
81 const doesDictionary = {}
82 const wasmImport = {
83 env: {
84 pop: () => simstack.pop(),
85 push: (val) => simstack.push(val),
86 rinit: () => rstack.length = 0,
87 rpop: () => rstack.pop(),
88 rpush: (val) => rstack.push(val),
89 sys_write: (chno, addr, u) => getChannel(chno).write(wasmMem, addr, u),
90 sys_read: (chno, addr, u) => getChannel(chno).read(wasmMem, addr, u),
91 sys_send: (chno, addr, u) => getChannel(chno).send(wasmMem, addr, u),
92 sys_connect: (addr, u) => {
93 //TODO: call into the module to wasm fn "event" to push an event
94 //to forth, which pushes esi to the return stack and queues the
95 //callback function provided from listen. reqaddr could be
96 //"fetch", in which case no channel is used. otherwise very
97 //similar to sys_fetch.
98
99 //callbacks are events, like listen events
100 //totally event-driven, one listener per event
101 //other listen types: mouse, keyboard, touch, main_loop (10ms interval), wrtc, etc
102 //fetch is different because it offers no "write" interface, doesn't repeat
103 },
104 sys_fetch: (chno, addr, u) => {
105 const str = wasmString(addr, u)
106 console.log(`fetching: ${str} || ${addr} ${u}`)
107 const args = JSON.parse(wasmString(addr, u))
108 console.log(args)
109 const url = args.url
110 delete args.url
111 const channel = channels[chno]
112 if (!channel) {
113 console.error(`invalid channel fetch: ${chno}`)
114 return -1
115 }
116 fetch(url, args).then((re) => {
117 if (args.headers === undefined ||
118 args.headers['content-type'] === undefined ||
119 args.headers['content-type'].toLowerCase().indexOf('text/plain') === 0 )
120 re.text().then((txt) => channel.write(strToArrayBuffer(txt), 0, txt.length << 1))
121 else {
122 const reader = new FileReader()
123 reader.onload = (evt) => channel.write(evt.target.result, 0, evt.target.result.byteLength)
124 re.blob().then((blob) => reader.readAsArrayBuffer(blob))
125 }
126 }).catch(console.error)
127 return 0
128 },
129 sys_open: () => new Channel().chno,
130 sys_close: (chno) => chno < 3 ? 0 : delete channels[chno],
131 sys_echo: (val) => output.print(`\\\ => ${val.toString(wasmBase())}\n`),
132 sys_log: (addr, u) => console.log(`=> ${wasmString(addr, u)}`),
133 sys_reflect: (addr) => {
134 console.log(`reflect: ${addr}: ${
135 new DataView(wasmMem, addr, 4)
136 .getUint32(0,true)
137 }`)
138 },
139 vocab_get: (addr, u) => dictionary[wasmString(addr, u).toUpperCase()] || 0,
140 vocab_set: (addr, u, v) => dictionary[wasmString(addr, u).toUpperCase()] = v,
141 does_get: (addr, u) => doesDictionary[wasmString(addr, u).toUpperCase()] || 0,
142 does_set: (addr, u, v) => doesDictionary[wasmString(addr, u).toUpperCase()] = v,
143 is_whitespace: (key) => /\s/.test(String.fromCharCode(key)),
144 sys_stack: () => { console.log(`[${simstack}][${rstack}]`)
145 console.log(new Uint32Array(wasmMem, 16900, 28))
146 },
147 sys_parsenum: (addr, u) => {
148 const answer = Number.parseInt(wasmString(addr, u), wasmBase())
149 if (Number.isNaN(answer))
150 return -1
151 new DataView(wasmMem, addr, 4).setUint32(0,answer,true)
152 return 0
153 },
154 sys_words: () => {
155 output.print(Object.getOwnPropertyNames(dictionary).toString().split(',').join(' '))
156 }
157 }
158 }
159
160 /* Initialization */
161 /* 0 STDIN, 1 STDOUT, 2 STDERR */
162 new Channel({
163 send(readArray, readAddr, readSize) { output.print(bufString(readArray, readAddr, readSize)) }
164 })
165 new Channel({
166 write(readArray, readAddr, readSize) { output.print(bufString(readArray, readAddr, readSize)) },
167 send(readArray, readAddr, readSize) { output.print(`\n\\\ => ${bufString(readArray, readAddr, readSize)}\n`) }
168 })
169 new Channel({
170 write(readArray, readAddr, readSize) { console.error(bufString(readArray, readAddr, readSize)) }
171 })
172
173 /* Fetch wasm file, and initial forth file */
174 Promise.all([
175 fetch('forth.forth', {credentials: 'include', headers:{'content-type':'text/plain'}}).then((re) => re.text()),
176 fetch('forth.wasm', {credentials: 'include', headers:{'content-type':'application/wasm'}}).then(re => re.arrayBuffer())
177 ]).then((results) => {
178 WebAssembly.instantiate(results[1], wasmImport).then((module) => {
179 wasmMem = module.instance.exports.memory.buffer
180 wasmMain = module.instance.exports.main
181 console.log('wasm loaded')
182 getChannel(0).write(strToArrayBuffer(results[0]))
183 })
184 })
185
186 /* View Logic */
187 window.onload = () => {
188 let forthdiv = document.getElementById("forth")
189 if (forthdiv === null) {
190 forthdiv = document.createElement("div")
191 forthdiv.setAttribute("style","height:100%;margin:auto;width:100%;max-width:640px;overflow-x:hidden;")
192 document.body.appendChild(forthdiv)
193 }
194 const outframe = document.createElement("div")
195 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;")
196 const stackview = document.createElement("pre")
197 stackview.setAttribute("style", "white-space:pre-wrap;flex:0 0 6%;")
198 outframe.appendChild(stackview)
199 const txtoutput = document.createElement("pre")
200 txtoutput.setAttribute("style", "white-space:pre-wrap;max-height:256px;overflow-y:scroll;flex:1 0 342px;")
201 outframe.appendChild(txtoutput)
202 /* const rstackview = document.createElement("pre")
203 rstackview.setAttribute("style", "white-space:pre-wrap;flex:0 1 8%;")
204 outframe.appendChild(rstackview) */
205 const memview = document.createElement("pre")
206 memview.setAttribute("style", "padding-left: 8px; white-space:pre-wrap;flex:0 0 88px;")
207 outframe.appendChild(memview)
208 const txtinput = document.createElement("textarea")
209 txtinput.setAttribute("autofocus", "true")
210 txtinput.setAttribute("wrap", "hard")
211 txtinput.setAttribute("style", "resize:none;white-space:pre;margin-left:6%;width:77%;")
212 txtinput.oninput = () => txtinput.setAttribute("rows", ((txtinput.value.match(/[\n]/g) || [1]).length + 1).toString());
213 txtinput.oninput()
214 txtinput.onkeydown = (event) => {
215 switch (event.key) {
216 case "Enter":
217 if (event.ctrlKey) {
218 const endPos = txtinput.selectionStart + 1
219 txtinput.value =
220 txtinput.value.substring(0, txtinput.selectionStart) +
221 '\n' +
222 txtinput.value.substring(txtinput.selectionEnd, txtinput.value.length)
223 txtinput.setSelectionRange(endPos, endPos)
224 txtinput.oninput()
225 }
226 else {
227 if (txtinput.value.length && !/\s/.test(txtinput.value.slice(-1)))
228 txtinput.value += " "
229 event.preventDefault()
230 event.stopPropagation()
231 getChannel(0).write(strToArrayBuffer(txtinput.value))
232 txtinput.value = ""
233 }
234 break
235 case "Backspace":
236 break
237 default:
238 break
239 }
240 }
241 forthdiv.appendChild(outframe)
242 forthdiv.appendChild(txtinput)
243 /* Set up output functions */
244 output.print = (string) => txtoutput.textContent += string,
245 output.updateViews = () => {
246 const base = wasmBase()
247 stackview.textContent = simstack.map((v) => v.toString(base)).join('\n')
248 // rstackview.textContent = rstack.join('\n')
249 let cnt = 0;
250 const maxBytes = 64
251 let here = new DataView(wasmMem, 14340 /* here */, 4).getUint32(0,true)
252 memview.textContent = Array.from(new Uint8Array(wasmMem, here - maxBytes, maxBytes), (v) => {
253 cnt++;
254 v = ('0' + (v & 0xFF).toString(16)).slice(-2)
255 if (cnt === maxBytes)
256 return v
257 if ((cnt % 16) === 0)
258 return `${v}\n=> ${(here -maxBytes + cnt).toString(base)}\n`
259 if ((cnt % 4) === 0)
260 return `${v}\n`
261 return `${v} `
262 }).join('')
263 outframe.scrollTop = outframe.scrollHeight
264 txtoutput.scrollTop = txtoutput.scrollHeight
265 }
266 }