cleanup, compilation semantics
[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 const initialize = Promise.all([
15 fetch('forth.forth', {credentials: 'include', headers:{'content-type':'text/plain'}}).then((re) => re.text()),
16 fetch('forth.wasm', {credentials: 'include', headers:{'content-type':'application/wasm'}}).then(re => re.arrayBuffer())
17 ])
18 window.onload = () => {
19 /* Initialize Views */
20 let forthdiv = document.getElementById("forth")
21 if (forthdiv === null) {
22 forthdiv = document.createElement("div")
23 forthdiv.setAttribute("style","height:100%;margin:auto;width:100%;max-width:640px;overflow-x:hidden;")
24 document.body.appendChild(forthdiv)
25 }
26 const outframe = document.createElement("div")
27 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;")
28 const stackview = document.createElement("pre")
29 stackview.setAttribute("style", "white-space:pre-wrap;flex:0 0 8%;")
30 outframe.appendChild(stackview)
31 const txtoutput = document.createElement("pre")
32 txtoutput.setAttribute("style", "white-space:pre-wrap;max-height:256px;overflow-y:scroll;flex:1 0 342px;")
33 outframe.appendChild(txtoutput)
34 /* const rstackview = document.createElement("pre")
35 rstackview.setAttribute("style", "white-space:pre-wrap;flex:0 1 8%;")
36 outframe.appendChild(rstackview) */
37 const memview = document.createElement("pre")
38 memview.setAttribute("style", "padding-left: 8px; white-space:pre-wrap;flex:0 0 88px;")
39 outframe.appendChild(memview)
40 const txtinput = document.createElement("textarea")
41 txtinput.setAttribute("autofocus", "true")
42 txtinput.setAttribute("wrap", "hard")
43 txtinput.setAttribute("style", "resize:none;white-space:pre;margin-left:8%;width:75%;")
44 txtinput.oninput = () => txtinput.setAttribute("rows", ((txtinput.value.match(/[\n]/g) || [1]).length + 1).toString());
45 txtinput.oninput()
46 forthdiv.appendChild(outframe)
47 forthdiv.appendChild(txtinput)
48
49 /* Initialize State */
50 const simstack = []
51 const rstack = []
52 let wasmMem
53 let forth
54 const dictionary = { EXECUTE: 12 }
55 const doesDictionary = {}
56
57 /* Environment functions */
58 const output = {
59 print: (string) => txtoutput.textContent += `\\\ => ${string} \n`
60 }
61 const wasmString = (addr, u) =>
62 String.fromCharCode.apply(
63 null,
64 new Uint16Array(wasmMem.buffer, addr, u >> 1)
65 )
66 const updateViews = () => {
67 const base = new DataView(wasmMem.buffer, 14348 /* base */, 4).getUint32(0,true)
68 stackview.textContent = simstack.map((v) => v.toString(base)).join('\n')
69 // rstackview.textContent = rstack.join('\n')
70 let cnt = 0;
71 const maxBytes = 64
72 let here = new DataView(wasmMem.buffer, 14340 /* here */, 4).getUint32(0,true)
73 memview.textContent = Array.from(new Uint8Array(wasmMem.buffer, here - maxBytes, maxBytes), (v) => {
74 cnt++;
75 v = ('0' + (v & 0xFF).toString(16)).slice(-2)
76 if (cnt === maxBytes)
77 return v
78 if ((cnt % 16) === 0)
79 return `${v}\n=> ${(here -maxBytes + cnt).toString(base)}\n`
80 if ((cnt % 4) === 0)
81 return `${v}\n`
82 return `${v} `
83 }).join('')
84 outframe.scrollTop = outframe.scrollHeight
85 }
86
87 /* Input capture */
88 let stdin = ""
89 txtinput.addEventListener('keydown', (event) => {
90 switch (event.key) {
91 case "Enter":
92 if (event.ctrlKey) {
93 const endPos = txtinput.selectionStart + 1
94 txtinput.value =
95 txtinput.value.substring(0, txtinput.selectionStart) +
96 '\n' +
97 txtinput.value.substring(txtinput.selectionEnd, txtinput.value.length)
98 txtinput.setSelectionRange(endPos, endPos)
99 txtinput.oninput()
100 }
101 else {
102 stdin += txtinput.value
103 txtoutput.textContent += txtinput.value
104 if (!/\s/.test(txtinput.value.slice(-1)))
105 txtoutput.textContent += " "
106 txtinput.value = ""
107 event.preventDefault()
108 event.stopPropagation()
109 forth()
110 updateViews()
111 txtoutput.scrollTop = txtoutput.scrollHeight
112 }
113 break
114 case "Backspace":
115 break
116 default:
117 break
118 }
119 })
120 const channels = [{
121 read: (writeAddr, maxBytes) => {
122 const maxChars = maxBytes >> 1
123 const bufView = new Uint16Array(wasmMem.buffer, writeAddr, maxChars)
124 let i
125 for (i = 0; i < maxChars && i < stdin.length; i++)
126 bufView[i] = stdin.charCodeAt(i)
127 stdin = stdin.substring(maxChars)
128 return i << 1
129 },
130 write: (readAddr, maxBytes) =>
131 output.print(String.fromCharCode.apply(
132 null,
133 new Uint16Array(wasmMem.buffer, readAddr, maxBytes >> 1)
134 ))
135 }]
136
137 /* System runtime */
138 const wasmImport = {
139 env: {
140 pop: () => simstack.pop(),
141 push: (val) => simstack.push(val),
142 rinit: () => rstack.length = 0,
143 rpop: () => rstack.pop(),
144 rpush: (val) => rstack.push(val),
145 sys_write: (channel, addr, u) => channels[channel] === undefined ? 0 : channels[channel].write(addr, u),
146 sys_read: (channel, addr, u) => channels[channel] === undefined ? 0 : channels[channel].read(addr, u),
147 sys_listen: (reqAddr, cbAddr) => {
148 //TODO: call into the module to wasm fn "event" to push an event
149 //to forth, which pushes esi to the return stack and queues the
150 //callback function provided from listen. reqaddr could be
151 //"fetch", in which case no channel is used. otherwise very
152 //similar to sys_fetch.
153 },
154 sys_fetch: (channel, reqAddr) => {
155 //TODO: map to fetch promise, write to channel buffer,
156 //javascript "fetch" as fallback, explicit handles for
157 //"textEntry" or any third party protocols like activitypub
158 console.log(`fetch ${channel} ${reqAddr}`)
159 },
160 sys_echo: (val, base) => output.print(`${val.toString(base)} `),
161 sys_echochar: (val) => output.print(String.fromCharCode(val)),
162 sys_reflect: (addr) => {
163 console.log(`reflect: ${addr}: ${
164 new DataView(wasmMem.buffer, addr, 4)
165 .getUint32(0,true)
166 }`)
167 },
168 vocab_get: (addr, u) => dictionary[wasmString(addr, u).toUpperCase()] || 0,
169 vocab_set: (addr, u, v) => dictionary[wasmString(addr, u).toUpperCase()] = v,
170 does_get: (addr, u) => doesDictionary[wasmString(addr, u).toUpperCase()] || 0,
171 does_set: (addr, u, v) => doesDictionary[wasmString(addr, u).toUpperCase()] = v,
172 is_whitespace: (key) => /\s/.test(String.fromCharCode(key)),
173 sys_stack: () => console.log(`[${simstack}][${rstack}]`),
174 sys_parsenum: (addr, u, base) => {
175 const answer = Number.parseInt(wasmString(addr, u), base)
176 if (Number.isNaN(answer))
177 return -1
178 new DataView(wasmMem.buffer, addr, 4).setUint32(0,answer,true)
179 return 0
180 },
181 sys_words: () => {
182 output.print(Object.getOwnPropertyNames(dictionary).toString().split(',').join(' '))
183 }
184 }
185 }
186 initialize.then((results) => {
187 stdin = results[0]
188 WebAssembly.instantiate(results[1], wasmImport).then((module) => {
189 wasmMem = module.instance.exports.memory
190 forth = module.instance.exports.main
191 console.log('wasm loaded')
192 forth()
193 updateViews()
194 })
195 })
196 }