summaryrefslogtreecommitdiffstats
path: root/Tools/wasm/python.worker.js
diff options
context:
space:
mode:
authorChristian Heimes <christian@python.org>2022-04-05 09:21:11 (GMT)
committerGitHub <noreply@github.com>2022-04-05 09:21:11 (GMT)
commit96e09837fb8031aebe8d823dd19ef664a34bcfad (patch)
tree28f6efee3352292d27370a2aeea27090755bed6f /Tools/wasm/python.worker.js
parentfaa12088c179dd896fde713448a7f142f820c1aa (diff)
downloadcpython-96e09837fb8031aebe8d823dd19ef664a34bcfad.zip
cpython-96e09837fb8031aebe8d823dd19ef664a34bcfad.tar.gz
cpython-96e09837fb8031aebe8d823dd19ef664a34bcfad.tar.bz2
bpo-40280: Add limited Emscripten REPL (GH-32284)
Co-authored-by: Katie Bell <katie@katharos.id.au>
Diffstat (limited to 'Tools/wasm/python.worker.js')
-rw-r--r--Tools/wasm/python.worker.js87
1 files changed, 87 insertions, 0 deletions
diff --git a/Tools/wasm/python.worker.js b/Tools/wasm/python.worker.js
new file mode 100644
index 0000000..c3a8bdf
--- /dev/null
+++ b/Tools/wasm/python.worker.js
@@ -0,0 +1,87 @@
+class StdinBuffer {
+ constructor() {
+ this.sab = new SharedArrayBuffer(128 * Int32Array.BYTES_PER_ELEMENT)
+ this.buffer = new Int32Array(this.sab)
+ this.readIndex = 1;
+ this.numberOfCharacters = 0;
+ this.sentNull = true
+ }
+
+ prompt() {
+ this.readIndex = 1
+ Atomics.store(this.buffer, 0, -1)
+ postMessage({
+ type: 'stdin',
+ buffer: this.sab
+ })
+ Atomics.wait(this.buffer, 0, -1)
+ this.numberOfCharacters = this.buffer[0]
+ }
+
+ stdin = () => {
+ if (this.numberOfCharacters + 1 === this.readIndex) {
+ if (!this.sentNull) {
+ // Must return null once to indicate we're done for now.
+ this.sentNull = true
+ return null
+ }
+ this.sentNull = false
+ this.prompt()
+ }
+ const char = this.buffer[this.readIndex]
+ this.readIndex += 1
+ // How do I send an EOF??
+ return char
+ }
+}
+
+const stdoutBufSize = 128;
+const stdoutBuf = new Int32Array()
+let index = 0;
+
+const stdout = (charCode) => {
+ if (charCode) {
+ postMessage({
+ type: 'stdout',
+ stdout: String.fromCharCode(charCode),
+ })
+ } else {
+ console.log(typeof charCode, charCode)
+ }
+}
+
+const stderr = (charCode) => {
+ if (charCode) {
+ postMessage({
+ type: 'stderr',
+ stderr: String.fromCharCode(charCode),
+ })
+ } else {
+ console.log(typeof charCode, charCode)
+ }
+}
+
+const stdinBuffer = new StdinBuffer()
+
+var Module = {
+ noInitialRun: true,
+ stdin: stdinBuffer.stdin,
+ stdout: stdout,
+ stderr: stderr,
+ onRuntimeInitialized: () => {
+ postMessage({type: 'ready', stdinBuffer: stdinBuffer.sab})
+ }
+}
+
+onmessage = (event) => {
+ if (event.data.type === 'run') {
+ // TODO: Set up files from event.data.files
+ const ret = callMain(event.data.args)
+ postMessage({
+ type: 'finished',
+ returnCode: ret
+ })
+ }
+}
+
+importScripts('python.js')