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.
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.
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/>. */
17 print
: (string
) => {},
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
)
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
)
41 /* I/O Channel Drivers */
43 const getChannel = (chno) => {
44 const channel = channels[chno]
46 throw new Error(`invalid channel access ${chno}`)
51 opt = opt || Object.create(null)
52 opt.chno = channels.indexOf(undefined)
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
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)
67 write(readArray, readAddr, readSize) {
68 this.buffer = bufJoin(this.buffer, new Uint8Array(readArray, readAddr, readSize))
72 send(readArray, readAddr, readSize) {
73 this.write(readArray, readAddr, readSize)
80 const dictionary
= { EXECUTE
: 12 }
81 const doesDictionary
= {}
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.
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
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
))
111 const channel
= channels
[chno
]
113 console
.error(`invalid channel fetch: ${chno}`)
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))
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
))
126 }).catch(console
.error
)
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)
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 sys_parsenum
: (addr
, u
) => {
146 const answer
= Number
.parseInt(wasmString(addr
, u
), wasmBase())
147 if (Number
.isNaN(answer
))
149 new DataView(wasmMem
, addr
, 4).setUint32(0,answer
,true)
153 output
.print(Object
.getOwnPropertyNames(dictionary
).toString().split(',').join(' '))
159 /* 0 STDIN, 1 STDOUT, 2 STDERR */
161 send(readArray
, readAddr
, readSize
) { output
.print(bufString(readArray
, readAddr
, readSize
)) }
164 write(readArray
, readAddr
, readSize
) { output
.print(bufString(readArray
, readAddr
, readSize
)) },
165 send(readArray
, readAddr
, readSize
) { output
.print(`\n\\\ => ${bufString(readArray, readAddr, readSize)}\n`) }
168 write(readArray
, readAddr
, readSize
) { console
.error(bufString(readArray
, readAddr
, readSize
)) }
171 /* Fetch wasm file, and initial forth file */
173 fetch('forth.forth', {credentials
: 'include', headers
:{'content-type':'text/plain'}}).then((re
) => re
.text()),
174 fetch('forth.wasm', {credentials
: 'include', headers
:{'content-type':'application/wasm'}}).then(re
=> re
.arrayBuffer())
175 ]).then((results
) => {
176 WebAssembly
.instantiate(results
[1], wasmImport
).then((module
) => {
177 wasmMem
= module
.instance
.exports
.memory
.buffer
178 wasmMain
= module
.instance
.exports
.main
179 console
.log('wasm loaded')
180 getChannel(0).write(strToArrayBuffer(results
[0]))
185 window
.onload
= () => {
186 let forthdiv
= document
.getElementById("forth")
187 if (forthdiv
=== null) {
188 forthdiv
= document
.createElement("div")
189 forthdiv
.setAttribute("style","height:100%;margin:auto;width:100%;max-width:640px;overflow-x:hidden;")
190 document
.body
.appendChild(forthdiv
)
192 const outframe
= document
.createElement("div")
193 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;")
194 const stackview
= document
.createElement("pre")
195 stackview
.setAttribute("style", "white-space:pre-wrap;flex:0 0 6%;")
196 outframe
.appendChild(stackview
)
197 const txtoutput
= document
.createElement("pre")
198 txtoutput
.setAttribute("style", "white-space:pre-wrap;max-height:256px;overflow-y:scroll;flex:1 0 342px;")
199 outframe
.appendChild(txtoutput
)
200 /* const rstackview = document.createElement("pre")
201 rstackview.setAttribute("style", "white-space:pre-wrap;flex:0 1 8%;")
202 outframe.appendChild(rstackview) */
203 const memview
= document
.createElement("pre")
204 memview
.setAttribute("style", "padding-left: 8px; white-space:pre-wrap;flex:0 0 88px;")
205 outframe
.appendChild(memview
)
206 const txtinput
= document
.createElement("textarea")
207 txtinput
.setAttribute("autofocus", "true")
208 txtinput
.setAttribute("wrap", "hard")
209 txtinput
.setAttribute("style", "resize:none;white-space:pre;margin-left:6%;width:77%;")
210 txtinput
.oninput
= () => txtinput
.setAttribute("rows", ((txtinput
.value
.match(/[\n]/g) || [1]).length
+ 1).toString());
212 txtinput
.onkeydown
= (event
) => {
216 const endPos
= txtinput
.selectionStart
+ 1
218 txtinput
.value
.substring(0, txtinput
.selectionStart
) +
220 txtinput
.value
.substring(txtinput
.selectionEnd
, txtinput
.value
.length
)
221 txtinput
.setSelectionRange(endPos
, endPos
)
225 if (!/\s/.test(txtinput
.value
.slice(-1)))
226 txtinput
.value
+= " "
227 event
.preventDefault()
228 event
.stopPropagation()
229 getChannel(0).write(strToArrayBuffer(txtinput
.value
))
239 forthdiv
.appendChild(outframe
)
240 forthdiv
.appendChild(txtinput
)
241 /* Set up output functions */
242 output
.print
= (string
) => txtoutput
.textContent
+= string
,
243 output
.updateViews
= () => {
244 const base
= wasmBase()
245 stackview
.textContent
= simstack
.map((v
) => v
.toString(base
)).join('\n')
246 // rstackview.textContent = rstack.join('\n')
249 let here
= new DataView(wasmMem
, 14340 /* here */, 4).getUint32(0,true)
250 memview
.textContent
= Array
.from(new Uint8Array(wasmMem
, here
- maxBytes
, maxBytes
), (v
) => {
252 v
= ('0' + (v
& 0xFF).toString(16)).slice(-2)
253 if (cnt
=== maxBytes
)
255 if ((cnt
% 16) === 0)
256 return `${v}\n=> ${(here -maxBytes + cnt).toString(base)}\n`
261 outframe
.scrollTop
= outframe
.scrollHeight
262 txtoutput
.scrollTop
= txtoutput
.scrollHeight