@effekt-lang/effekt 0.82.0 → 0.84.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/README.md +0 -8
  2. package/bin/effekt +0 -0
  3. package/libraries/chez/callcc/seq0.ss +8 -9
  4. package/libraries/chez/callcc/tail0.ss +35 -19
  5. package/libraries/chez/common/effekt_primitives.ss +28 -3
  6. package/libraries/chez/cps/effekt.ss +180 -165
  7. package/libraries/chez/monadic/effekt.ss +28 -13
  8. package/libraries/chez/monadic/seq0.ss +8 -9
  9. package/libraries/common/array.effekt +3 -1
  10. package/libraries/common/bench.effekt +1 -5
  11. package/libraries/common/bytearray.effekt +12 -6
  12. package/libraries/common/char.effekt +4 -4
  13. package/libraries/common/effekt.effekt +92 -50
  14. package/libraries/common/heap.effekt +100 -90
  15. package/libraries/common/io/console.effekt +3 -3
  16. package/libraries/common/io/error.effekt +4 -4
  17. package/libraries/common/io/filesystem.effekt +42 -32
  18. package/libraries/common/io/network.effekt +170 -83
  19. package/libraries/common/io/signal.effekt +5 -4
  20. package/libraries/common/io.effekt +8 -0
  21. package/libraries/common/process.effekt +88 -82
  22. package/libraries/common/ref.effekt +8 -5
  23. package/libraries/common/string.effekt +1 -1
  24. package/libraries/js/effekt_builtins.js +9 -0
  25. package/libraries/js/effekt_runtime.js +2 -4
  26. package/libraries/llvm/bytearray.c +3 -3
  27. package/libraries/llvm/forward-declare-c.ll +3 -2
  28. package/libraries/llvm/io.c +201 -135
  29. package/libraries/llvm/panic.c +9 -2
  30. package/libraries/llvm/rts.ll +233 -83
  31. package/libraries/llvm/types.c +3 -2
  32. package/licenses/eclipse public license, version 2.0 - epl-2.0.html +3 -3
  33. package/licenses/mit license - mit-license.html +176 -100
  34. package/licenses/the bsd license - bsd-license.html +176 -100
  35. package/licenses/the mit license - mit.html +177 -101
  36. package/package.json +1 -1
@@ -9,13 +9,34 @@ import io/error
9
9
  /// A TCP handle. Should not be inspected.
10
10
  type Connection = Int
11
11
 
12
- /// Reads data from a TCP connection into a buffer at the given offset.
13
- def read(handle: Connection, buffer: ByteArray, offset: Int, size: Int): Int / Exception[IOError] =
14
- internal::checkResult(internal::read(handle, buffer, offset, size))
12
+ /// Reads up to `size` bytes from a TCP connection into `buffer`, starting at `offset`.
13
+ ///
14
+ /// Returns as soon as at least one byte is available, so the result may be smaller than `size`.
15
+ /// Returns 0 once the peer has closed the connection (end of file), and every subsequent call returns 0 too.
16
+ /// At most one read can be pending on a connection: another one raises `EALREADY`.
17
+ /// Panics unless:
18
+ /// - `size` is positive (a read of nothing would look like end of file), and
19
+ /// - `[offset, offset + size)` is a valid range inside `buffer` (like `bytearray::copy`).
20
+ def read(handle: Connection, buffer: ByteArray, offset: Int, size: Int): Int / Exception[IOError] = {
21
+ if (size <= 0) { panic("io/network::read: size must be positive") }
22
+ if (buffer.inBounds(offset, size)) {
23
+ internal::checkResult(internal::read(handle, buffer, offset, size))
24
+ } else {
25
+ panic("io/network::read: window out of bounds")
26
+ }
27
+ }
15
28
 
16
- /// Writes data from a buffer at the given offset to a TCP connection.
17
- def write(handle: Connection, buffer: ByteArray, offset: Int, size: Int): Int / Exception[IOError] =
18
- internal::checkResult(internal::write(handle, buffer, offset, size))
29
+ /// Writes `size` bytes from `buffer`, starting at `offset`, to a TCP connection.
30
+ ///
31
+ /// Returns once all bytes are written, and returns `size`.
32
+ /// Panics unless `[offset, offset + size)` is a valid range inside `buffer` (like `bytearray::copy`).
33
+ def write(handle: Connection, buffer: ByteArray, offset: Int, size: Int): Int / Exception[IOError] = {
34
+ if (buffer.inBounds(offset, size)) {
35
+ internal::checkResult(internal::write(handle, buffer, offset, size))
36
+ } else {
37
+ panic("io/network::write: window out of bounds")
38
+ }
39
+ }
19
40
 
20
41
  /// Establishes a TCP connection to the specified host and port.
21
42
  def connect(host: String, port: Int): Connection / Exception[IOError] =
@@ -28,12 +49,17 @@ def close(handle: Connection): Unit =
28
49
  /// A TCP listener. Should not be inspected.
29
50
  type Listener = Int
30
51
 
31
- /// Creates a TCP listener bound to the specified host and port.
52
+ /// Creates a TCP listener bound to the specified host and port, reserving the address (o/w raising `EADDRINUSE`).
53
+ /// Port 0 asks the system for a free port, which `port` then returns.
32
54
  def bind(host: String, port: Int): Listener / Exception[IOError] =
33
55
  internal::checkResult(internal::bind(host, port))
34
56
 
35
- /// Starts listening for incoming connections and handles them with the provided handler function.
36
- /// Runs until `shutdown` is called on this `Listener`.
57
+ /// The port which the given `listener` is bound to.
58
+ def port(listener: Listener): Int / Exception[IOError] =
59
+ internal::checkResult(internal::port(listener))
60
+
61
+ /// Starts listening for incoming connections and handles each with the given `handler`, including those which arrived since `bind`.
62
+ /// Returns only once `shutdown` is called on this `Listener`, so it is usually run with `spawn`.
37
63
  def listen(listener: Listener, handler: Connection => Unit at {io, async, global}): Unit / Exception[IOError] = {
38
64
  internal::checkResult(internal::listen(listener, handler)); ()
39
65
  }
@@ -42,6 +68,9 @@ def listen(listener: Listener, handler: Connection => Unit at {io, async, global
42
68
  def shutdown(listener: Listener): Unit =
43
69
  internal::shutdown(listener)
44
70
 
71
+ /// Runs `program` with `emit` writing to the connection and `next` reading from it.
72
+ /// `next` returns the bytes read so far (at most 4096) and performs `stop` at end of file,
73
+ /// so a loop over `next` ends when the peer closes the connection.
45
74
  def streaming[R](connection: Connection) { program: () => R / {next[ByteArray], emit[ByteArray]} }: R / Exception[IOError] =
46
75
  try {
47
76
  program()
@@ -51,6 +80,7 @@ def streaming[R](connection: Connection) { program: () => R / {next[ByteArray],
51
80
  } with next[ByteArray] { () =>
52
81
  val bytes = bytearray::allocate(4096)
53
82
  read(connection, bytes, 0, bytes.size) match {
83
+ case 0 => resume { do stop() }
54
84
  case r and r == bytes.size => resume { return bytes }
55
85
  case r => resume { bytes.resize(r) }
56
86
  }
@@ -58,136 +88,192 @@ def streaming[R](connection: Connection) { program: () => R / {next[ByteArray],
58
88
 
59
89
  namespace internal {
60
90
 
61
- // TODO: also in `io/filesystem`, perhaps we want this in a common place?
62
- extern js """
63
- function toBuffer(buffer) {
64
- return Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength);
65
- }
66
- """
67
-
68
91
  extern jsNode """
69
- const net = require('net');
70
-
71
- const tcp$handles = new Map();
72
- let tcp$next = 1;
73
- function tcp$alloc(entry) { const h = tcp$next++; tcp$handles.set(h, entry); return h; }
74
- function tcp$free(h) { tcp$handles.delete(h); }
92
+ const network$net = require('net');
93
+
94
+ // Error results are negative libuv codes, as Node reports them in `err.errno` (see `io/filesystem`).
95
+ // Their numbers differ between platforms, so the ones used here are looked up by name.
96
+ const network$code = {};
97
+ for (const [code, [name]] of require('node:util').getSystemErrorMap()) network$code[name] = code;
98
+ function network$errno(err) { return (typeof err.errno === 'number' && err.errno < 0) ? err.errno : network$code.UNKNOWN; }
99
+
100
+ const network$handles = new Map();
101
+ let network$next = 1;
102
+ function network$alloc(entry) { const h = network$next++; network$handles.set(h, entry); return h; }
103
+ function network$free(h) { network$handles.delete(h); }
104
+
105
+ // A connection records errors and end of file as they happen, and wakes the one which is pending a read.
106
+ // Its listeners stay attached for its whole life, so an error with no read pending is kept
107
+ // for the next operation instead of crashing the process.
108
+ function network$connection(socket) {
109
+ const conn = { socket, error: null, ended: false, waiter: null };
110
+ const wake = () => { const w = conn.waiter; if (w) { conn.waiter = null; w(); } };
111
+ socket.on('readable', wake);
112
+ socket.on('end', () => { conn.ended = true; wake(); });
113
+ socket.on('error', err => { if (!conn.error) conn.error = err; wake(); });
114
+ socket.on('close', () => { conn.ended = true; wake(); });
115
+ return conn;
116
+ }
75
117
 
76
- function tcp$connect(host, port, callback) {
77
- const socket = net.createConnection({ host, port });
78
- socket.once('connect', () => { socket.pause(); callback(tcp$alloc({ socket })); });
79
- socket.once('error', err => callback(-(err.errno || 1)));
118
+ function network$connect(host, port, callback) {
119
+ const socket = network$net.createConnection({ host, port });
120
+ socket.pause();
121
+ const onConnect = () => {
122
+ socket.removeListener('error', onError);
123
+ callback(network$alloc(network$connection(socket)));
124
+ };
125
+ const onError = err => {
126
+ socket.removeListener('connect', onConnect);
127
+ socket.destroy();
128
+ callback(network$errno(err));
129
+ };
130
+ socket.once('connect', onConnect);
131
+ socket.once('error', onError);
80
132
  }
81
133
 
82
- function tcp$read(handle, buffer, offset, size, callback) {
83
- const { socket } = tcp$handles.get(handle);
84
- function cleanup() {
85
- socket.removeListener('readable', onReadable);
86
- socket.removeListener('end', onEnd);
87
- socket.removeListener('error', onError);
88
- }
89
- function onReadable() { cleanup(); tryRead(); }
90
- function onEnd() { cleanup(); callback(0); }
91
- function onError(err) { cleanup(); callback(-(err.errno || 1)); }
92
- function tryRead() {
93
- const chunk = socket.read(size);
94
- if (chunk !== null) { chunk.copy(toBuffer(buffer), offset); callback(chunk.length); return; }
95
- if (socket.readableEnded) { callback(0); return; }
96
- socket.once('readable', onReadable);
97
- socket.once('end', onEnd);
98
- socket.once('error', onError);
99
- }
100
- tryRead();
134
+ function network$read(handle, buffer, offset, size, callback) {
135
+ const conn = network$handles.get(handle);
136
+ if (!conn || !conn.socket) { callback(network$code.EBADF); return; }
137
+ if (conn.waiter) { callback(network$code.EALREADY); return; }
138
+
139
+ const attempt = () => {
140
+ const chunk = conn.socket.read();
141
+ if (chunk !== null) {
142
+ const n = Math.min(size, chunk.length);
143
+ chunk.copy(io$toBuffer(buffer), offset, 0, n);
144
+ if (n < chunk.length) conn.socket.unshift(chunk.subarray(n));
145
+ callback(n);
146
+ } else if (conn.error) {
147
+ callback(network$errno(conn.error));
148
+ } else if (conn.ended || conn.socket.readableEnded) {
149
+ callback(0);
150
+ } else {
151
+ conn.waiter = attempt;
152
+ }
153
+ };
154
+
155
+ attempt();
101
156
  }
102
157
 
103
- function tcp$write(handle, buffer, offset, size, callback) {
104
- const { socket } = tcp$handles.get(handle);
105
- socket.write(toBuffer(buffer).slice(offset, offset + size), err => {
106
- if (err) callback(-(err.errno || 1)); else callback(size);
158
+ function network$write(handle, buffer, offset, size, callback) {
159
+ const conn = network$handles.get(handle);
160
+ if (!conn || !conn.socket) { callback(network$code.EBADF); return; }
161
+ if (conn.error) { callback(network$errno(conn.error)); return; }
162
+
163
+ conn.socket.write(io$toBuffer(buffer).subarray(offset, offset + size), err => {
164
+ if (err) callback(network$errno(err)); else callback(size);
107
165
  });
108
166
  }
109
167
 
110
- function tcp$close(handle, callback) {
111
- const entry = tcp$handles.get(handle);
112
- if (!entry || !entry.socket) { callback($effekt.unit); return; }
113
- tcp$free(handle);
114
- const { socket } = entry;
168
+ function network$close(handle, callback) {
169
+ const conn = network$handles.get(handle);
170
+ if (!conn || !conn.socket) { callback($effekt.unit); return; }
171
+ network$free(handle);
172
+ const { socket } = conn;
115
173
  if (socket.destroyed) { callback($effekt.unit); return; }
116
- socket.once('error', _err => {});
117
174
  socket.end(() => { socket.destroy(); callback($effekt.unit); });
118
175
  }
119
176
 
120
- function tcp$bind(host, port) {
121
- return tcp$alloc({ server: net.createServer(), host, port });
122
- }
177
+ // Node binds only when listening, so `bind` listens already, and keeps connections alive until `listen` takes them.
178
+ function network$bind(host, port, callback) {
179
+ const server = network$net.createServer();
180
+ const entry = { server, accept: null, pending: [], finished: null };
181
+ server.on('connection', socket => {
182
+ socket.pause();
183
+ if (entry.accept) entry.accept(socket); else entry.pending.push(socket);
184
+ });
123
185
 
124
- function tcp$listen(listenerHandle, handler, callback) {
125
- const { server, host, port } = tcp$handles.get(listenerHandle);
126
- server.once('error', err => callback(-(err.errno || 1)));
186
+ const onError = err => callback(network$errno(err));
187
+ server.once('error', onError);
127
188
  server.listen(port, host, () => {
128
- server.removeAllListeners('error');
189
+ server.removeListener('error', onError);
129
190
  server.on('error', _err => {});
130
- server.on('connection', socket => {
131
- socket.pause();
132
- const connHandle = tcp$alloc({ socket });
133
- $effekt.runToplevel((ks, k) => handler(connHandle, ks, k));
134
- });
135
- callback(0);
191
+ callback(network$alloc(entry));
136
192
  });
137
193
  }
138
194
 
139
- function tcp$shutdown(listenerHandle, callback) {
140
- const entry = tcp$handles.get(listenerHandle);
195
+ function network$port(listenerHandle) {
196
+ const entry = network$handles.get(listenerHandle);
197
+ if (!entry || !entry.server) return network$code.EBADF;
198
+ return entry.server.address().port;
199
+ }
200
+
201
+ // Settles with `EBADF` if the listener was shut down, and with 0 once `shutdown` is called.
202
+ // On the other hand, errors of listening, such as `EADDRINUSE`, are raised by `bind`.
203
+ function network$listen(listenerHandle, handler, callback) {
204
+ const entry = network$handles.get(listenerHandle);
205
+ if (!entry || !entry.server) { callback(network$code.EBADF); return; }
206
+
207
+ entry.finished = () => callback(0);
208
+ entry.accept = socket => {
209
+ const connHandle = network$alloc(network$connection(socket));
210
+ $effekt.runToplevel((ks, k) => handler(connHandle, ks, k));
211
+ };
212
+ entry.pending.splice(0).forEach(entry.accept);
213
+ }
214
+
215
+ function network$shutdown(listenerHandle, callback) {
216
+ const entry = network$handles.get(listenerHandle);
141
217
  if (!entry || !entry.server) { callback($effekt.unit); return; }
142
- tcp$free(listenerHandle);
143
- entry.server.close(() => callback($effekt.unit));
218
+ network$free(listenerHandle);
219
+ // Stop accepting without waiting for open connections to end (to avoid a deadlock on Node)
220
+ entry.server.close();
221
+ if (entry.finished) entry.finished();
222
+ callback($effekt.unit);
144
223
  }
145
224
  """
146
225
 
147
226
  extern def connect(host: String, port: Int) at async: Int =
148
- jsNode "$effekt.capture(k => tcp$connect(${host}, ${port}, k))"
227
+ jsNode "$effekt.capture(k => network$connect(${host}, ${port}, k))"
149
228
  llvm """
150
229
  notail call void @c_tcp_connect(%Pos ${host}, %Int ${port}, %Stack %stack)
151
230
  ret void
152
231
  """
153
232
 
154
233
  extern def read(handle: Int, buffer: ByteArray, offset: Int, size: Int) at async: Int =
155
- jsNode "$effekt.capture(k => tcp$read(${handle}, ${buffer}, ${offset}, ${size}, k))"
234
+ jsNode "$effekt.capture(k => network$read(${handle}, ${buffer}, ${offset}, ${size}, k))"
156
235
  llvm """
157
236
  notail call void @c_tcp_read(%Int ${handle}, %Pos ${buffer}, %Int ${offset}, %Int ${size}, %Stack %stack)
158
237
  ret void
159
238
  """
160
239
 
161
240
  extern def write(handle: Int, buffer: ByteArray, offset: Int, size: Int) at async: Int =
162
- jsNode "$effekt.capture(k => tcp$write(${handle}, ${buffer}, ${offset}, ${size}, k))"
241
+ jsNode "$effekt.capture(k => network$write(${handle}, ${buffer}, ${offset}, ${size}, k))"
163
242
  llvm """
164
243
  notail call void @c_tcp_write(%Int ${handle}, %Pos ${buffer}, %Int ${offset}, %Int ${size}, %Stack %stack)
165
244
  ret void
166
245
  """
167
246
 
168
247
  extern def close(handle: Int) at async: Unit =
169
- jsNode "$effekt.capture(k => tcp$close(${handle}, k))"
248
+ jsNode "$effekt.capture(k => network$close(${handle}, k))"
170
249
  llvm """
171
250
  notail call void @c_tcp_close(%Int ${handle}, %Stack %stack)
172
251
  ret void
173
252
  """
174
253
 
175
- extern def bind(host: String, port: Int) at io: Int =
176
- jsNode "tcp$bind(${host}, ${port})"
254
+ extern def bind(host: String, port: Int) at async: Int =
255
+ jsNode "$effekt.capture(k => network$bind(${host}, ${port}, k))"
256
+ llvm """
257
+ notail call void @c_tcp_bind(%Pos ${host}, %Int ${port}, %Stack %stack)
258
+ ret void
259
+ """
260
+
261
+ extern def port(listener: Int) at io: Int =
262
+ jsNode "network$port(${listener})"
177
263
  llvm """
178
- %result = call %Int @c_tcp_bind(%Pos ${host}, %Int ${port})
264
+ %result = call %Int @c_tcp_port(%Int ${listener})
179
265
  ret %Int %result
180
266
  """
181
267
 
182
268
  extern def listen(listener: Int, handler: Connection => Unit at {io, async, global}) at async: Int =
183
- jsNode "$effekt.capture(k => tcp$listen(${listener}, ${handler}, k))"
269
+ jsNode "$effekt.capture(k => network$listen(${listener}, ${handler}, k))"
184
270
  llvm """
185
271
  notail call void @c_tcp_listen(%Int ${listener}, %Neg ${handler}, %Stack %stack)
186
272
  ret void
187
273
  """
188
274
 
189
275
  extern def shutdown(handle: Int) at async: Unit =
190
- jsNode "$effekt.capture(k => tcp$shutdown(${handle}, k))"
276
+ jsNode "$effekt.capture(k => network$shutdown(${handle}, k))"
191
277
  llvm """
192
278
  notail call void @c_tcp_shutdown(%Int ${handle}, %Stack %stack)
193
279
  ret void
@@ -198,8 +284,9 @@ namespace internal {
198
284
  declare void @c_tcp_read(%Int, %Pos, %Int, %Int, %Stack)
199
285
  declare void @c_tcp_write(%Int, %Pos, %Int, %Int, %Stack)
200
286
  declare void @c_tcp_close(%Int, %Stack)
201
- declare %Int @c_tcp_bind(%Pos, %Int)
202
- declare void @c_tcp_listen(%Int, %Pos, %Stack)
287
+ declare void @c_tcp_bind(%Pos, %Int, %Stack)
288
+ declare %Int @c_tcp_port(%Int)
289
+ declare void @c_tcp_listen(%Int, %Neg, %Stack)
203
290
  declare void @c_tcp_shutdown(%Int, %Stack)
204
291
  """
205
292
  }
@@ -12,8 +12,7 @@ extern type Signal[A, B] =
12
12
  extern llvm """
13
13
  %Signal = type { %Header, i64, ptr, %Pos }
14
14
 
15
- define void @signal_erase(ptr %envPtr) {
16
- %base = getelementptr %Header, ptr %envPtr, i64 -1
15
+ define void @signal_erase(ptr %base) {
17
16
  %statePtr = getelementptr %Signal, ptr %base, i64 0, i32 1
18
17
  %stackPtr = getelementptr %Signal, ptr %base, i64 0, i32 2
19
18
  %valuePtr = getelementptr %Signal, ptr %base, i64 0, i32 3
@@ -24,8 +23,10 @@ define void @signal_erase(ptr %envPtr) {
24
23
  %value = load %Pos, ptr %valuePtr
25
24
  call void @erasePositive(%Pos %value)
26
25
  call void @eraseStack(%Stack %stack)
26
+ call void @free(ptr %base)
27
27
  ret void
28
28
  none:
29
+ call void @free(ptr %base)
29
30
  ret void
30
31
  }
31
32
  """
@@ -82,7 +83,7 @@ extern def fire[A, B](signal: Signal[A, B], value: A) at async: B =
82
83
  store i64 3, ptr %statePtr
83
84
  notail call void @erasePositive(%Pos ${signal})
84
85
  notail call void @resume_Pos(%Stack %otherStack, %Pos ${value})
85
- notail call void @resume_Pos(%Stack %stack, %Pos %otherValue)
86
+ musttail call tailcc void @return_Pos(%Stack %stack, %Pos %otherValue) "no_callee_saved_registers"
86
87
  ret void
87
88
  panic:
88
89
  notail call void @exit(i32 1)
@@ -110,7 +111,7 @@ extern def wait[A, B](signal: Signal[A, B], value: B) at async: A =
110
111
  store i64 3, ptr %statePtr
111
112
  notail call void @erasePositive(%Pos ${signal})
112
113
  notail call void @resume_Pos(%Stack %otherStack, %Pos ${value})
113
- notail call void @resume_Pos(%Stack %stack, %Pos %otherValue)
114
+ musttail call tailcc void @return_Pos(%Stack %stack, %Pos %otherValue) "no_callee_saved_registers"
114
115
  ret void
115
116
  panic:
116
117
  notail call void @exit(i32 1)
@@ -4,6 +4,14 @@ module io
4
4
  // Event Loop
5
5
  // ----------
6
6
 
7
+ // Shared by `io/filesystem` and `io/network`: Node's I/O expects a `Buffer`, and a byte array is a typed array,
8
+ // so this views the same bytes without copying, and Node then writes into the array itself.
9
+ extern jsNode """
10
+ function io$toBuffer(bytes) {
11
+ return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
12
+ }
13
+ """
14
+
7
15
  extern llvm """
8
16
  declare void @c_yield(%Stack)
9
17
  """
@@ -13,86 +13,40 @@ extern def exit(errorCode: Int) at io: Nothing =
13
13
  // Subprocesses
14
14
  // ------------
15
15
 
16
- extern jsNode """
17
- const { spawn } = require('node:child_process');
18
- """
19
- extern llvm """
20
- declare %Pos @c_spawn_options_default()
21
- declare %Pos @c_spawn_options_on_stdout(%Pos, %Pos)
22
- declare %Pos @c_spawn_options_on_stderr(%Pos, %Pos)
23
- declare %Pos @c_spawn_options_pipe_stdin(%Pos, %Pos)
24
- declare %Pos @c_write_stream(%Pos, %Pos)
25
- declare %Pos @c_close_stream(%Pos)
26
- declare %Pos @c_spawn(%Pos, %Pos, %Pos)
27
- """
28
-
29
- extern type SpawnOptions =
30
- jsNode "{ stdio: list[int], onSpawn: fn => {} }"
31
- llvm "%Pos"
32
- extern def default() at {}: SpawnOptions =
33
- jsNode """{ stdio: [0,1,2], onSpawn: (p) => {} }"""
34
- llvm """
35
- %opts = call %Pos @c_spawn_options_default()
36
- ret %Pos %opts
37
- """
38
- extern def onStdout(opts: SpawnOptions, callback: String => Unit at {io, global}) at {}: SpawnOptions =
39
- jsNode """(function() {
40
- let old = ${opts};
41
- old.stdio[1] = 'pipe';
42
- let oldSpawn = old.onSpawn;
43
- old.onSpawn = function(p) {
44
- oldSpawn(p);
45
- p.stdout.on('data', (chunk) => {
46
- $effekt.runToplevel((ks, k) => (${callback})(chunk, ks, k));
47
- });
48
- };
49
- return old; })()"""
50
- llvm """
51
- %opts = call %Pos @c_spawn_options_on_stdout(%Pos ${opts}, %Neg ${callback})
52
- ret %Pos %opts
53
- """
54
- extern def onStderr(opts: SpawnOptions, callback: String => Unit at {io, global}) at {}: SpawnOptions =
55
- jsNode """(function() {
56
- let old = ${opts};
57
- old.stdio[2] = 'pipe';
58
- let oldSpawn = old.onSpawn;
59
- old.onSpawn = function(p) {
60
- oldSpawn(p);
61
- p.stderr.on('data', (chunk) => {
62
- $effekt.runToplevel((ks, k) => (${callback})(chunk, ks, k));
63
- });
64
- };
65
- return old; })()"""
66
- llvm """
67
- %opts = call %Pos @c_spawn_options_on_stderr(%Pos ${opts}, %Neg ${callback})
68
- ret %Pos %opts
69
- """
16
+ /// The standard input of a spawned process.
70
17
  extern type WritableStream =
71
18
  jsNode "stream.Writable"
72
19
  llvm "%Pos"
73
- extern def withStdin(opts: SpawnOptions, callback: WritableStream => Unit at {io, global}) at {}: SpawnOptions =
74
- jsNode """(function () {
75
- let old = ${opts};
76
- old.stdio[0] = 'pipe'
77
- let oldSpawn = old.onSpawn;
78
- old.onSpawn = function(p) {
79
- oldSpawn(p);
80
- p.on('spawn', () => {
81
- $effekt.runToplevel((ks, k) => (${callback})(p.stdin, ks, k));
82
- });
83
- };
84
- return old;
85
- })()"""
86
- llvm """
87
- %opts = call %Pos @c_spawn_options_pipe_stdin(%Pos ${opts}, %Neg ${callback})
88
- ret %Pos %opts
89
- """
20
+
21
+ /// How the standard streams of a spawned process are connected to it:
22
+ /// each one is either inherited from this process (`None`), or piped to a given callback.
23
+ record SpawnOptions(
24
+ stdin: Option[WritableStream => Unit at {io, global}],
25
+ stdout: Option[String => Unit at {io, global}],
26
+ stderr: Option[String => Unit at {io, global}]
27
+ )
28
+
29
+ def SpawnOptions::default(): SpawnOptions = SpawnOptions(None(), None(), None())
30
+
31
+ /// Pipes the process's standard output to `callback`, chunk by chunk.
32
+ def onStdout(opts: SpawnOptions, callback: String => Unit at {io, global}): SpawnOptions =
33
+ SpawnOptions(opts.stdin, Some(internal::chain(opts.stdout, callback)), opts.stderr)
34
+
35
+ /// Pipes the process's standard error to `callback`, chunk by chunk.
36
+ def onStderr(opts: SpawnOptions, callback: String => Unit at {io, global}): SpawnOptions =
37
+ SpawnOptions(opts.stdin, opts.stdout, Some(internal::chain(opts.stderr, callback)))
38
+
39
+ /// Pipes the process's standard input from `callback`, which runs once the process has started.
40
+ def withStdin(opts: SpawnOptions, callback: WritableStream => Unit at {io, global}): SpawnOptions =
41
+ SpawnOptions(Some(internal::chain(opts.stdin, callback)), opts.stdout, opts.stderr)
42
+
90
43
  extern def write(to: WritableStream, s: String) at io: Unit =
91
44
  jsNode """${to}.write(${s})"""
92
45
  llvm """
93
46
  call void @c_write_stream(%Pos ${to}, %Pos ${s})
94
47
  ret %Pos zeroinitializer
95
48
  """
49
+
96
50
  extern def close(to: WritableStream) at io: Unit =
97
51
  jsNode """${to}.end()"""
98
52
  llvm """
@@ -100,14 +54,66 @@ extern def close(to: WritableStream) at io: Unit =
100
54
  ret %Pos zeroinitializer
101
55
  """
102
56
 
103
- extern def spawn(cmd: String, args: Array[String], options: SpawnOptions) at async: Int =
104
- jsNode """$effekt.capture(k => {
105
- let p = spawn(${cmd}, ${args}, ${options});
106
- ${options}.onSpawn(p);
107
- p.on('close', (exitcode, sig) => { k(exitcode) });
108
- return p;
109
- })"""
110
- llvm """
111
- notail call void @c_spawn(%Pos ${cmd}, %Pos ${args}, %Pos ${options}, %Stack %stack)
112
- ret void
113
- """
57
+ /// Runs `cmd` with `args`, connecting its standard streams as per `options`, returning its exit code.
58
+ def spawn(cmd: String, args: Array[String], options: SpawnOptions): Int = {
59
+ val stdin: WritableStream => Unit at {io, global} = options.stdin match {
60
+ case Some(callback) => callback
61
+ case None() => box { _ => () }
62
+ }
63
+ val stdout: String => Unit at {io, global} = options.stdout match {
64
+ case Some(callback) => callback
65
+ case None() => box { _ => () }
66
+ }
67
+ val stderr: String => Unit at {io, global} = options.stderr match {
68
+ case Some(callback) => callback
69
+ case None() => box { _ => () }
70
+ }
71
+ internal::spawn(cmd, args,
72
+ internal::piped(options.stdin), stdin,
73
+ internal::piped(options.stdout), stdout,
74
+ internal::piped(options.stderr), stderr)
75
+ }
76
+
77
+ namespace internal {
78
+ def chain[A](first: Option[A => Unit at {io, global}], then: A => Unit at {io, global}): A => Unit at {io, global} =
79
+ first match {
80
+ case None() => then
81
+ case Some(f) => box { a => f(a); then(a) }
82
+ }
83
+
84
+ /// 1 if a stream is piped to a callback, 0 if it is inherited.
85
+ def piped[A](callback: Option[A]): Int = callback match {
86
+ case Some(_) => 1
87
+ case None() => 0
88
+ }
89
+
90
+ extern jsNode """
91
+ const { spawn: process$nodeSpawn } = require('node:child_process');
92
+
93
+ function process$spawn(cmd, args, pipeStdin, stdin, pipeStdout, stdout, pipeStderr, stderr, callback) {
94
+ const stdio = [pipeStdin ? 'pipe' : 'inherit', pipeStdout ? 'pipe' : 'inherit', pipeStderr ? 'pipe' : 'inherit'];
95
+ const p = process$nodeSpawn(cmd, args, { stdio });
96
+ // Note: Decoded as UTF-8 by the stream itself, so that a character split between two chunks stays whole.
97
+ if (pipeStdout) { p.stdout.setEncoding('utf8'); p.stdout.on('data', chunk => $effekt.runToplevel((ks, k) => stdout(chunk, ks, k))); }
98
+ if (pipeStderr) { p.stderr.setEncoding('utf8'); p.stderr.on('data', chunk => $effekt.runToplevel((ks, k) => stderr(chunk, ks, k))); }
99
+ if (pipeStdin) p.on('spawn', () => $effekt.runToplevel((ks, k) => stdin(p.stdin, ks, k)));
100
+ p.on('close', (exitCode, _signal) => callback(exitCode));
101
+ }
102
+ """
103
+
104
+ extern llvm """
105
+ declare void @c_spawn(%Pos, %Pos, %Neg, %Neg, %Neg, %Int, %Int, %Int, %Stack)
106
+ declare void @c_write_stream(%Pos, %Pos)
107
+ declare void @c_close_stream(%Pos)
108
+ """
109
+
110
+ extern def spawn(cmd: String, args: Array[String],
111
+ pipeStdin: Int, stdin: WritableStream => Unit at {io, global},
112
+ pipeStdout: Int, stdout: String => Unit at {io, global},
113
+ pipeStderr: Int, stderr: String => Unit at {io, global}) at async: Int =
114
+ jsNode "$effekt.capture(k => process$spawn(${cmd}, ${args}, ${pipeStdin}, ${stdin}, ${pipeStdout}, ${stdout}, ${pipeStderr}, ${stderr}, k))"
115
+ llvm """
116
+ notail call void @c_spawn(%Pos ${cmd}, %Pos ${args}, %Neg ${stdin}, %Neg ${stdout}, %Neg ${stderr}, %Int ${pipeStdin}, %Int ${pipeStdout}, %Int ${pipeStderr}, %Stack %stack)
117
+ ret void
118
+ """
119
+ }
@@ -3,16 +3,19 @@ module ref
3
3
  import effekt
4
4
 
5
5
  extern js """
6
- function set$impl(ref, value) {
6
+ function ref$set(ref, value) {
7
7
  ref.value = value;
8
8
  return $effekt.unit;
9
9
  }
10
10
  """
11
11
 
12
12
  extern llvm """
13
- define void @c_ref_erase_field(ptr %0) {
14
- %field = load %Pos, ptr %0, align 8
15
- tail call void @erasePositive(%Pos %field)
13
+ define void @c_ref_erase_field(ptr %object) {
14
+ %fieldPointer = getelementptr %Header, ptr %object, i64 1
15
+ %field = load %Pos, ptr %fieldPointer, align 8
16
+ call void @free(ptr %object)
17
+ %fieldObject = extractvalue %Pos %field, 1
18
+ musttail call void @eraseObject(%Object %fieldObject)
16
19
  ret void
17
20
  }
18
21
  """
@@ -90,7 +93,7 @@ llvm """
90
93
 
91
94
  /// Sets the referenced element of the `ref` to `value` in constant time.
92
95
  extern def set[T](ref: Ref[T], value: T) at global: Unit =
93
- js "set$impl(${ref}, ${value})"
96
+ js "ref$set(${ref}, ${value})"
94
97
  chez "(set-box! ${ref} ${value})"
95
98
  llvm """
96
99
  %refField_pointer = extractvalue %Pos ${ref}, 1
@@ -174,7 +174,7 @@ def toInt(str: String, base: Int): Int / fail = {
174
174
  /// Native versions of toInt (unused right now)
175
175
  extern def unsafeToInt(str: String) at {}: Int =
176
176
  js "(Number.isNaN(parseInt(${str})) ? undefined : parseInt(${str}))"
177
- chez "(string->number ${str})"
177
+ chez "(let ([n (string->number ${str})]) (and (fixnum? n) n))"
178
178
 
179
179
 
180
180
  /// Returns the index of the first occurrence of `sub` in `str`