@effekt-lang/effekt 0.84.0 → 0.85.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.
package/bin/effekt CHANGED
Binary file
@@ -197,18 +197,29 @@ def foreachIndex(arr: ByteArray){ action: (Int, Byte) {Label} => Unit }: Unit =
197
197
  action(i, arr.get(i)) {label}
198
198
  }
199
199
 
200
- extern def fromString(str: String) at {}: ByteArray =
200
+ extern def fromString(str: String) at global: ByteArray =
201
+ js "(new TextEncoder().encode(${str}))"
202
+ llvm """
203
+ %arr = call %Pos @uniqueByteArray(%Pos ${str})
204
+ ret %Pos %arr
205
+ """
206
+ chez "(string->utf8 ${str})"
207
+
208
+ /// The _read-only_ UTF-8 bytes of `str`.
209
+ /// On LLVM they are `str` itself, so they must be read-only!
210
+ extern def unsafeFromString(str: String) at {}: ByteArray = // just a copy of 'fromString' on JS and Chez, but without the global capture
201
211
  js "(new TextEncoder().encode(${str}))"
202
212
  llvm """
203
213
  ret %Pos ${str}
204
214
  """
205
215
  chez "(string->utf8 ${str})"
206
216
 
207
- extern def toString(arr: ByteArray) at {}: String =
217
+ extern def toString(arr: ByteArray) at global: String =
208
218
  js "(new TextDecoder('utf-8').decode(${arr}))"
209
219
  // assuming the buffer is already in UTF-8
210
220
  llvm """
211
- ret %Pos ${arr}
221
+ %str = call %Pos @uniqueByteArray(%Pos ${arr})
222
+ ret %Pos %str
212
223
  """
213
224
  chez "(utf8->string ${arr})"
214
225
 
@@ -273,7 +284,7 @@ extern chez """
273
284
  [else (loop (+ i 1))]))))
274
285
  """
275
286
 
276
- extern def compareByteArrayImpl(b1: ByteArray, b2: ByteArray) at {}: Int =
287
+ extern def compareByteArrayImpl(b1: ByteArray, b2: ByteArray) at global: Int =
277
288
  js "bytearray$compare(${b1}, ${b2})"
278
289
  llvm """
279
290
  %x = call %Int @c_bytearray_compare(%Pos ${b1}, %Pos ${b2})
@@ -49,7 +49,7 @@ def empty[A](): Dictionary[A] = ref(Empty())
49
49
 
50
50
  /// Insert a value with a String key.
51
51
  def insert[A](dictionary: Dictionary[A], key: String, value: A): Unit =
52
- insert(dictionary, key.fromString, value)
52
+ insert(dictionary, key.unsafeFromString, value)
53
53
 
54
54
  /// Insert a key-value pair into the dictionary with a ByteArray key.
55
55
  def insert[A](dictionary: Dictionary[A], key: ByteArray, value: A): Unit = {
@@ -158,7 +158,7 @@ def insert[A](dictionary: Dictionary[A], key: ByteArray, value: A): Unit = {
158
158
 
159
159
  /// Look up a value in the dictionary by string key.
160
160
  def lookup[A](dictionary: Dictionary[A], key: String): Option[A] =
161
- lookup(dictionary, key.fromString)
161
+ lookup(dictionary, key.unsafeFromString)
162
162
 
163
163
  /// Look up a value in the dictionary by bytearray key.
164
164
  def lookup[A](dictionary: Dictionary[A], key: ByteArray): Option[A] = {
@@ -93,16 +93,16 @@ def finalize[E, T] { finalizer: => Unit } { prog: => T / Exception[E] }: T / Exc
93
93
  record on[E]()
94
94
 
95
95
  def ignore[E](proxy: on[E]) { prog: => Unit / Exception[E] }: Unit =
96
- ignore[E] {prog}
96
+ ignore {prog}
97
97
 
98
98
  def default[E, T](proxy: on[E]) { d: => T } { prog: => T / Exception[E] }: T =
99
99
  default[E, T] {d} {prog}
100
100
 
101
101
  def panic[E, T](proxy: on[E]) { prog: => T / Exception[E] }: T =
102
- panicOn[E, T] {prog}
102
+ panicOn {prog}
103
103
 
104
104
  def report[E](proxy: on[E]) { prog: => Unit / Exception[E] }: Unit =
105
- report[E] {prog}
105
+ report {prog}
106
106
 
107
107
  def finalize[E, T](proxy: on[E]) { finalizer: => Unit } { prog: => T / Exception[E] }: T / Exception[E] =
108
108
  finalize[E, T] {finalizer} {prog}
@@ -365,6 +365,11 @@ namespace internal {
365
365
  extern jsNode """
366
366
  const error$getSystemErrorName = require('node:util').getSystemErrorName;
367
367
 
368
+ // Error results of the I/O modules are negative libuv codes, as Node reports them in `err.errno`.
369
+ // Their numbers differ between platforms, so the modules look them up here by name.
370
+ const error$code = {};
371
+ for (const [code, [name]] of require('node:util').getSystemErrorMap()) error$code[name] = code;
372
+
368
373
  /**
369
374
  * Maps the error code to a Effekt-stable (platform independent) numeric value.
370
375
  *
@@ -6,8 +6,12 @@ import io
6
6
  import io/error
7
7
 
8
8
 
9
- /// A file descriptor. Should not be inspected.
10
- type File = Int
9
+ /// A file, either open or closed.
10
+ /// Reading, writing or closing a closed file raises `EBADF`.
11
+ /// Closing is explicit, for example with `with on[IOError].finalize { close(file) }`.
12
+ extern type File =
13
+ jsNode "number"
14
+ llvm "i64"
11
15
 
12
16
 
13
17
  /// Reads a file at given path as utf8 encoded string.
@@ -41,7 +45,7 @@ def writeFile(path: String, contents: String): Unit / Exception[IOError] = {
41
45
  with on[IOError].finalize { close(file) }
42
46
 
43
47
  val chunkSize = 1048576 // 1MB
44
- val buffer = contents.fromString
48
+ val buffer = contents.unsafeFromString
45
49
  var offset = 0;
46
50
 
47
51
  def go(): Unit = {
@@ -59,7 +63,7 @@ def appendFile(path: String, contents: String): Unit / Exception[IOError] = {
59
63
  with on[IOError].finalize { close(file) }
60
64
 
61
65
  val chunkSize = 1048576 // 1MB
62
- val buffer = contents.fromString
66
+ val buffer = contents.unsafeFromString
63
67
  var offset = 0;
64
68
 
65
69
  def go(): Unit = {
@@ -162,13 +166,13 @@ def filesystem[R] { program: => R / Files }: R / Exception[IOError] = // TODO mo
162
166
 
163
167
 
164
168
  def openForReading(path: String): File / Exception[IOError] =
165
- internal::checkResult(internal::openForReading(path))
169
+ internal::file(internal::checkResult(internal::openForReading(path)))
166
170
 
167
171
  def openForWriting(path: String): File / Exception[IOError] =
168
- internal::checkResult(internal::openForWriting(path))
172
+ internal::file(internal::checkResult(internal::openForWriting(path)))
169
173
 
170
174
  def openForAppending(path: String): File / Exception[IOError] =
171
- internal::checkResult(internal::openForAppending(path))
175
+ internal::file(internal::checkResult(internal::openForAppending(path)))
172
176
 
173
177
  /// Reads up to `size` bytes from `file` at `position` (-1 for the current position) into `buffer`, starting at `offset`.
174
178
  /// Returns the number of bytes read, and 0 at end of file.
@@ -209,28 +213,38 @@ namespace internal {
209
213
  extern jsNode """
210
214
  const filesystem$node = require("fs");
211
215
 
216
+ // Resumes with the handle of the opened file (see `io`), or with the (negative) error.
212
217
  function filesystem$open(path, flags, callback) {
213
- filesystem$node.open(path, flags, (err, file) => {
214
- if (err) { callback(err.errno) } else { callback(file) }
218
+ filesystem$node.open(path, flags, (err, fd) => {
219
+ if (err) { callback(err.errno) } else { callback(io$open(fd)) }
215
220
  })
216
221
  }
217
222
 
218
223
  function filesystem$read(file, buffer, offset, size, position, callback) {
224
+ const fd = io$get(file);
225
+ if (fd === undefined) { callback(error$code.EBADF); return; }
226
+
219
227
  let positionOrNull = position === -1 ? null : position;
220
- filesystem$node.read(file, io$toBuffer(buffer), offset, size, positionOrNull, (err, bytesRead) => {
228
+ filesystem$node.read(fd, io$toBuffer(buffer), offset, size, positionOrNull, (err, bytesRead) => {
221
229
  if (err) { callback(err.errno) } else { callback(bytesRead) }
222
230
  })
223
231
  }
224
232
 
225
233
  function filesystem$write(file, buffer, offset, size, position, callback) {
234
+ const fd = io$get(file);
235
+ if (fd === undefined) { callback(error$code.EBADF); return; }
236
+
226
237
  let positionOrNull = position === -1 ? null : position;
227
- filesystem$node.write(file, io$toBuffer(buffer), offset, size, positionOrNull, (err, bytesWritten) => {
238
+ filesystem$node.write(fd, io$toBuffer(buffer), offset, size, positionOrNull, (err, bytesWritten) => {
228
239
  if (err) { callback(err.errno) } else { callback(bytesWritten) }
229
240
  })
230
241
  }
231
242
 
232
243
  function filesystem$close(file, callback) {
233
- filesystem$node.close(file, (err) => {
244
+ const fd = io$close(file);
245
+ if (fd === undefined) { callback(error$code.EBADF); return; }
246
+
247
+ filesystem$node.close(fd, (err) => {
234
248
  if (err) { callback(err.errno) } else { callback(0) }
235
249
  })
236
250
  }
@@ -273,27 +287,32 @@ namespace internal {
273
287
  ret void
274
288
  """
275
289
 
276
- extern def read(file: Int, buffer: ByteArray, offset: Int, size: Int, position: Int) at async: Int =
290
+ extern def read(file: File, buffer: ByteArray, offset: Int, size: Int, position: Int) at async: Int =
277
291
  jsNode "$effekt.capture(callback => filesystem$read(${file}, ${buffer}, ${offset}, ${size}, ${position}, callback))"
278
292
  llvm """
279
293
  notail call void @c_fs_read(%Int ${file}, %Pos ${buffer}, %Int ${offset}, %Int ${size}, %Int ${position}, %Stack %stack)
280
294
  ret void
281
295
  """
282
296
 
283
- extern def write(file: Int, buffer: ByteArray, offset: Int, size: Int, position: Int) at async: Int =
297
+ extern def write(file: File, buffer: ByteArray, offset: Int, size: Int, position: Int) at async: Int =
284
298
  jsNode "$effekt.capture(callback => filesystem$write(${file}, ${buffer}, ${offset}, ${size}, ${position}, callback))"
285
299
  llvm """
286
300
  notail call void @c_fs_write(%Int ${file}, %Pos ${buffer}, %Int ${offset}, %Int ${size}, %Int ${position}, %Stack %stack)
287
301
  ret void
288
302
  """
289
303
 
290
- extern def close(file: Int) at async: Int =
304
+ extern def close(file: File) at async: Int =
291
305
  jsNode "$effekt.capture(callback => filesystem$close(${file}, callback))"
292
306
  llvm """
293
307
  notail call void @c_fs_close(%Int ${file}, %Stack %stack)
294
308
  ret void
295
309
  """
296
310
 
311
+ /// The file whose handle `openForReading`, `openForWriting` or `openForAppending` returned.
312
+ extern def file(handle: Int) at {}: File =
313
+ jsNode "${handle}"
314
+ llvm "ret %Int ${handle}"
315
+
297
316
  extern def mkdir(path: String) at async: Int =
298
317
  jsNode "$effekt.capture(callback => filesystem$mkdir(${path}, callback))"
299
318
  llvm """
@@ -3,17 +3,23 @@ module io/network
3
3
  import stream
4
4
  import bytearray
5
5
 
6
+ import io
6
7
  import io/error
7
8
 
8
9
 
9
- /// A TCP handle. Should not be inspected.
10
- type Connection = Int
10
+ /// A TCP connection, either open or closed.
11
+ /// Reading from or writing to a closed connection raises `EBADF`, but closing it again does nothing.
12
+ /// Closing is explicit.
13
+ extern type Connection =
14
+ jsNode "number"
15
+ llvm "i64"
11
16
 
12
17
  /// Reads up to `size` bytes from a TCP connection into `buffer`, starting at `offset`.
13
18
  ///
14
19
  /// Returns as soon as at least one byte is available, so the result may be smaller than `size`.
15
20
  /// Returns 0 once the peer has closed the connection (end of file), and every subsequent call returns 0 too.
16
21
  /// At most one read can be pending on a connection: another one raises `EALREADY`.
22
+ /// Raises `EBADF` if the connection is closed.
17
23
  /// Panics unless:
18
24
  /// - `size` is positive (a read of nothing would look like end of file), and
19
25
  /// - `[offset, offset + size)` is a valid range inside `buffer` (like `bytearray::copy`).
@@ -29,6 +35,7 @@ def read(handle: Connection, buffer: ByteArray, offset: Int, size: Int): Int / E
29
35
  /// Writes `size` bytes from `buffer`, starting at `offset`, to a TCP connection.
30
36
  ///
31
37
  /// Returns once all bytes are written, and returns `size`.
38
+ /// Raises `EBADF` if the connection is closed.
32
39
  /// Panics unless `[offset, offset + size)` is a valid range inside `buffer` (like `bytearray::copy`).
33
40
  def write(handle: Connection, buffer: ByteArray, offset: Int, size: Int): Int / Exception[IOError] = {
34
41
  if (buffer.inBounds(offset, size)) {
@@ -38,23 +45,56 @@ def write(handle: Connection, buffer: ByteArray, offset: Int, size: Int): Int /
38
45
  }
39
46
  }
40
47
 
41
- /// Establishes a TCP connection to the specified host and port.
48
+ /// An IP address (v4 or v6) resolved by the system from a previously given host.
49
+ extern type Address =
50
+ jsNode "string"
51
+ llvm "%Pos"
52
+
53
+ /// The text of the given `address`, such as `127.0.0.1` or `::1`.
54
+ extern def toString(address: Address) at {}: String =
55
+ jsNode "${address}"
56
+ llvm "ret %Pos ${address}"
57
+
58
+ /// Resolves the given `host`, a name or an IPv4 or IPv6 address, to its addresses, in the order which the system prefers.
59
+ /// Raises the error of the resolver, such as `EAI_NONAME`, if it has none.
60
+ def resolve(host: String): List[Address] / Exception[IOError] = {
61
+ val resolution = internal::checkResult(internal::resolve(host))
62
+ val addresses = list::collect[Address] { internal::addresses(resolution) }
63
+ internal::release(resolution)
64
+ addresses
65
+ }
66
+
67
+ /// Establishes a TCP connection to the given `address` and port.
68
+ def connect(address: Address, port: Int): Connection / Exception[IOError] =
69
+ internal::connection(internal::checkResult(internal::connect(address, port)))
70
+
71
+ /// Establishes a TCP connection to the given `host` and port,
72
+ /// trying the addresses of the host in turn until one accepts (o/w raising the error of the last one).
42
73
  def connect(host: String, port: Int): Connection / Exception[IOError] =
43
- internal::checkResult(internal::connect(host, port))
74
+ internal::eachAddress(resolve(host)) { address => connect(address, port) }
44
75
 
45
76
  /// Closes a TCP connection and releases associated resources.
46
77
  def close(handle: Connection): Unit =
47
78
  internal::close(handle)
48
79
 
49
- /// A TCP listener. Should not be inspected.
50
- type Listener = Int
80
+ /// A TCP listener, either listening or shut down.
81
+ /// Listening on a listener that was shut down raises `EBADF`, but shutting it down again does nothing.
82
+ extern type Listener =
83
+ jsNode "number"
84
+ llvm "i64"
51
85
 
52
- /// Creates a TCP listener bound to the specified host and port, reserving the address (o/w raising `EADDRINUSE`).
86
+ /// Creates a TCP listener bound to the given `address` and port, reserving it (o/w raising `EADDRINUSE`).
53
87
  /// Port 0 asks the system for a free port, which `port` then returns.
88
+ def bind(address: Address, port: Int): Listener / Exception[IOError] =
89
+ internal::listener(internal::checkResult(internal::bind(address, port)))
90
+
91
+ /// Creates a TCP listener bound to the given `host` and port,
92
+ /// trying the addresses of the host in turn until one can be bound (o/w raising the error of the last one).
54
93
  def bind(host: String, port: Int): Listener / Exception[IOError] =
55
- internal::checkResult(internal::bind(host, port))
94
+ internal::eachAddress(resolve(host)) { address => bind(address, port) }
56
95
 
57
96
  /// The port which the given `listener` is bound to.
97
+ /// Raises `EBADF` if the listener was shut down.
58
98
  def port(listener: Listener): Int / Exception[IOError] =
59
99
  internal::checkResult(internal::port(listener))
60
100
 
@@ -88,19 +128,32 @@ def streaming[R](connection: Connection) { program: () => R / {next[ByteArray],
88
128
 
89
129
  namespace internal {
90
130
 
131
+ /// The addresses of a `resolution`, in order.
132
+ def addresses(resolution: Int): Unit / emit[Address] = {
133
+ with val i = for[Int] { range(0, addressCount(resolution)) }
134
+ do emit(addressAt(resolution, i))
135
+ }
136
+
137
+ /// Runs `attempt` on each of the `addresses` of a host in turn until one succeeds,
138
+ /// and otherwise raises the error of the last attempt.
139
+ def eachAddress[R](addresses: List[Address]) { attempt: Address => R / Exception[IOError] }: R / Exception[IOError] = {
140
+ val Cons(first, rest) = addresses else panic("io/network: `resolve` returned no addresses")
141
+ firstSuccess(first, rest) {attempt}
142
+ }
143
+
91
144
  extern jsNode """
92
145
  const network$net = require('net');
146
+ const network$dns = require('node:dns');
93
147
 
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; }
148
+ // Resumes with a handle to the addresses of `host` (see `io`), in the order of the system, or with the (negative) error.
149
+ function network$resolve(host, callback) {
150
+ network$dns.lookup(host, { all: true, verbatim: true }, (err, addresses) => {
151
+ if (err) { callback(network$errno(err)); } else { callback(io$open(addresses.map(entry => entry.address))); }
152
+ });
153
+ }
99
154
 
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); }
155
+ // Error results are negative libuv codes, as Node reports them in `err.errno` (see `io/error`).
156
+ function network$errno(err) { return (typeof err.errno === 'number' && err.errno < 0) ? err.errno : error$code.UNKNOWN; }
104
157
 
105
158
  // A connection records errors and end of file as they happen, and wakes the one which is pending a read.
106
159
  // Its listeners stay attached for its whole life, so an error with no read pending is kept
@@ -120,7 +173,7 @@ namespace internal {
120
173
  socket.pause();
121
174
  const onConnect = () => {
122
175
  socket.removeListener('error', onError);
123
- callback(network$alloc(network$connection(socket)));
176
+ callback(io$open(network$connection(socket)));
124
177
  };
125
178
  const onError = err => {
126
179
  socket.removeListener('connect', onConnect);
@@ -132,9 +185,9 @@ namespace internal {
132
185
  }
133
186
 
134
187
  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; }
188
+ const conn = io$get(handle);
189
+ if (conn === undefined) { callback(error$code.EBADF); return; }
190
+ if (conn.waiter) { callback(error$code.EALREADY); return; }
138
191
 
139
192
  const attempt = () => {
140
193
  const chunk = conn.socket.read();
@@ -156,8 +209,8 @@ namespace internal {
156
209
  }
157
210
 
158
211
  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; }
212
+ const conn = io$get(handle);
213
+ if (conn === undefined) { callback(error$code.EBADF); return; }
161
214
  if (conn.error) { callback(network$errno(conn.error)); return; }
162
215
 
163
216
  conn.socket.write(io$toBuffer(buffer).subarray(offset, offset + size), err => {
@@ -166,9 +219,8 @@ namespace internal {
166
219
  }
167
220
 
168
221
  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);
222
+ const conn = io$close(handle);
223
+ if (conn === undefined) { callback($effekt.unit); return; }
172
224
  const { socket } = conn;
173
225
  if (socket.destroyed) { callback($effekt.unit); return; }
174
226
  socket.end(() => { socket.destroy(); callback($effekt.unit); });
@@ -188,34 +240,33 @@ namespace internal {
188
240
  server.listen(port, host, () => {
189
241
  server.removeListener('error', onError);
190
242
  server.on('error', _err => {});
191
- callback(network$alloc(entry));
243
+ callback(io$open(entry));
192
244
  });
193
245
  }
194
246
 
195
247
  function network$port(listenerHandle) {
196
- const entry = network$handles.get(listenerHandle);
197
- if (!entry || !entry.server) return network$code.EBADF;
248
+ const entry = io$get(listenerHandle);
249
+ if (entry === undefined) return error$code.EBADF;
198
250
  return entry.server.address().port;
199
251
  }
200
252
 
201
253
  // Settles with `EBADF` if the listener was shut down, and with 0 once `shutdown` is called.
202
254
  // On the other hand, errors of listening, such as `EADDRINUSE`, are raised by `bind`.
203
255
  function network$listen(listenerHandle, handler, callback) {
204
- const entry = network$handles.get(listenerHandle);
205
- if (!entry || !entry.server) { callback(network$code.EBADF); return; }
256
+ const entry = io$get(listenerHandle);
257
+ if (entry === undefined) { callback(error$code.EBADF); return; }
206
258
 
207
259
  entry.finished = () => callback(0);
208
260
  entry.accept = socket => {
209
- const connHandle = network$alloc(network$connection(socket));
261
+ const connHandle = io$open(network$connection(socket));
210
262
  $effekt.runToplevel((ks, k) => handler(connHandle, ks, k));
211
263
  };
212
264
  entry.pending.splice(0).forEach(entry.accept);
213
265
  }
214
266
 
215
267
  function network$shutdown(listenerHandle, callback) {
216
- const entry = network$handles.get(listenerHandle);
217
- if (!entry || !entry.server) { callback($effekt.unit); return; }
218
- network$free(listenerHandle);
268
+ const entry = io$close(listenerHandle);
269
+ if (entry === undefined) { callback($effekt.unit); return; }
219
270
  // Stop accepting without waiting for open connections to end (to avoid a deadlock on Node)
220
271
  entry.server.close();
221
272
  if (entry.finished) entry.finished();
@@ -223,63 +274,106 @@ namespace internal {
223
274
  }
224
275
  """
225
276
 
226
- extern def connect(host: String, port: Int) at async: Int =
227
- jsNode "$effekt.capture(k => network$connect(${host}, ${port}, k))"
277
+ extern def resolve(host: String) at async: Int =
278
+ jsNode "$effekt.capture(k => network$resolve(${host}, k))"
228
279
  llvm """
229
- notail call void @c_tcp_connect(%Pos ${host}, %Int ${port}, %Stack %stack)
280
+ notail call void @c_tcp_resolve(%Pos ${host}, %Stack %stack)
230
281
  ret void
231
282
  """
232
283
 
233
- extern def read(handle: Int, buffer: ByteArray, offset: Int, size: Int) at async: Int =
284
+ /// The number of addresses in a `resolution`, and each of them by its index, as for `args`.
285
+ extern def addressCount(resolution: Int) at io: Int =
286
+ jsNode "io$get(${resolution}).length"
287
+ llvm """
288
+ %count = call %Int @c_tcp_address_count(%Int ${resolution})
289
+ ret %Int %count
290
+ """
291
+
292
+ extern def addressAt(resolution: Int, index: Int) at io: Address =
293
+ jsNode "io$get(${resolution})[${index}]"
294
+ llvm """
295
+ %address = call %Pos @c_tcp_address(%Int ${resolution}, %Int ${index})
296
+ ret %Pos %address
297
+ """
298
+
299
+ extern def release(resolution: Int) at io: Unit =
300
+ jsNode "(io$close(${resolution}), $effekt.unit)"
301
+ llvm """
302
+ call void @c_tcp_resolution_release(%Int ${resolution})
303
+ ret %Pos zeroinitializer
304
+ """
305
+
306
+ extern def connect(address: Address, port: Int) at async: Int =
307
+ jsNode "$effekt.capture(k => network$connect(${address}, ${port}, k))"
308
+ llvm """
309
+ notail call void @c_tcp_connect(%Pos ${address}, %Int ${port}, %Stack %stack)
310
+ ret void
311
+ """
312
+
313
+ extern def read(handle: Connection, buffer: ByteArray, offset: Int, size: Int) at async: Int =
234
314
  jsNode "$effekt.capture(k => network$read(${handle}, ${buffer}, ${offset}, ${size}, k))"
235
315
  llvm """
236
316
  notail call void @c_tcp_read(%Int ${handle}, %Pos ${buffer}, %Int ${offset}, %Int ${size}, %Stack %stack)
237
317
  ret void
238
318
  """
239
319
 
240
- extern def write(handle: Int, buffer: ByteArray, offset: Int, size: Int) at async: Int =
320
+ extern def write(handle: Connection, buffer: ByteArray, offset: Int, size: Int) at async: Int =
241
321
  jsNode "$effekt.capture(k => network$write(${handle}, ${buffer}, ${offset}, ${size}, k))"
242
322
  llvm """
243
323
  notail call void @c_tcp_write(%Int ${handle}, %Pos ${buffer}, %Int ${offset}, %Int ${size}, %Stack %stack)
244
324
  ret void
245
325
  """
246
326
 
247
- extern def close(handle: Int) at async: Unit =
327
+ extern def close(handle: Connection) at async: Unit =
248
328
  jsNode "$effekt.capture(k => network$close(${handle}, k))"
249
329
  llvm """
250
330
  notail call void @c_tcp_close(%Int ${handle}, %Stack %stack)
251
331
  ret void
252
332
  """
253
333
 
254
- extern def bind(host: String, port: Int) at async: Int =
255
- jsNode "$effekt.capture(k => network$bind(${host}, ${port}, k))"
334
+ extern def bind(address: Address, port: Int) at async: Int =
335
+ jsNode "$effekt.capture(k => network$bind(${address}, ${port}, k))"
256
336
  llvm """
257
- notail call void @c_tcp_bind(%Pos ${host}, %Int ${port}, %Stack %stack)
337
+ notail call void @c_tcp_bind(%Pos ${address}, %Int ${port}, %Stack %stack)
258
338
  ret void
259
339
  """
260
340
 
261
- extern def port(listener: Int) at io: Int =
341
+ extern def port(listener: Listener) at io: Int =
262
342
  jsNode "network$port(${listener})"
263
343
  llvm """
264
344
  %result = call %Int @c_tcp_port(%Int ${listener})
265
345
  ret %Int %result
266
346
  """
267
347
 
268
- extern def listen(listener: Int, handler: Connection => Unit at {io, async, global}) at async: Int =
348
+ extern def listen(listener: Listener, handler: Connection => Unit at {io, async, global}) at async: Int =
269
349
  jsNode "$effekt.capture(k => network$listen(${listener}, ${handler}, k))"
270
350
  llvm """
271
351
  notail call void @c_tcp_listen(%Int ${listener}, %Neg ${handler}, %Stack %stack)
272
352
  ret void
273
353
  """
274
354
 
275
- extern def shutdown(handle: Int) at async: Unit =
355
+ extern def shutdown(handle: Listener) at async: Unit =
276
356
  jsNode "$effekt.capture(k => network$shutdown(${handle}, k))"
277
357
  llvm """
278
358
  notail call void @c_tcp_shutdown(%Int ${handle}, %Stack %stack)
279
359
  ret void
280
360
  """
281
361
 
362
+ /// The connection whose handle `connect` returned, or which `listen` passed to its handler.
363
+ extern def connection(handle: Int) at {}: Connection =
364
+ jsNode "${handle}"
365
+ llvm "ret %Int ${handle}"
366
+
367
+ /// The listener whose handle `bind` returned.
368
+ extern def listener(handle: Int) at {}: Listener =
369
+ jsNode "${handle}"
370
+ llvm "ret %Int ${handle}"
371
+
282
372
  extern llvm """
373
+ declare void @c_tcp_resolve(%Pos, %Stack)
374
+ declare %Int @c_tcp_address_count(%Int)
375
+ declare %Pos @c_tcp_address(%Int, %Int)
376
+ declare void @c_tcp_resolution_release(%Int)
283
377
  declare void @c_tcp_connect(%Pos, %Int, %Stack)
284
378
  declare void @c_tcp_read(%Int, %Pos, %Int, %Int, %Stack)
285
379
  declare void @c_tcp_write(%Int, %Pos, %Int, %Int, %Stack)
@@ -4,14 +4,50 @@ 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
7
  extern jsNode """
10
8
  function io$toBuffer(bytes) {
11
9
  return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
12
10
  }
13
11
  """
14
12
 
13
+ // Files, connections and listeners are generational handles into a single table of open I/O resources,
14
+ // as on the LLVM backend (see `io.c`): a slot of the table, and the generation which the slot had when it was opened.
15
+ // Closing a resource starts the next generation of its slot, so its handles no longer match.
16
+ // This is a sort-of cheap way to recover at least some safety :)
17
+ extern jsNode """
18
+ const io$slots = [];
19
+ const io$free = [];
20
+
21
+ function io$open(value) {
22
+ const slot = io$free.length > 0 ? io$free.pop() : io$slots.push({ value: null, generation: 0, open: false }) - 1;
23
+ const entry = io$slots[slot];
24
+ entry.value = value;
25
+ entry.open = true;
26
+ return entry.generation * 0x100000000 + slot;
27
+ }
28
+
29
+ // The resource of a handle which is still open, or `undefined`.
30
+ function io$get(handle) {
31
+ if (handle < 0) return undefined;
32
+ const entry = io$slots[handle % 0x100000000];
33
+ return (entry && entry.open && entry.generation === Math.floor(handle / 0x100000000)) ? entry.value : undefined;
34
+ }
35
+
36
+ // Closes a handle which is still open and returns its resource, or returns `undefined`.
37
+ function io$close(handle) {
38
+ const value = io$get(handle);
39
+ if (value === undefined) return undefined;
40
+
41
+ const slot = handle % 0x100000000;
42
+ const entry = io$slots[slot];
43
+ entry.open = false;
44
+ entry.value = null;
45
+ entry.generation = (entry.generation + 1) % 0x200000; // 21 bits, so that a handle stays an exact integer on JS
46
+ io$free.push(slot);
47
+ return value;
48
+ }
49
+ """
50
+
15
51
  extern llvm """
16
52
  declare void @c_yield(%Stack)
17
53
  """