@effekt-lang/effekt 0.83.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.
Files changed (33) hide show
  1. package/bin/effekt +0 -0
  2. package/libraries/chez/common/effekt_primitives.ss +9 -0
  3. package/libraries/common/array.effekt +3 -1
  4. package/libraries/common/bench.effekt +0 -5
  5. package/libraries/common/bytearray.effekt +27 -10
  6. package/libraries/common/dictionary.effekt +2 -2
  7. package/libraries/common/effekt.effekt +49 -7
  8. package/libraries/common/exception.effekt +3 -3
  9. package/libraries/common/heap.effekt +100 -90
  10. package/libraries/common/io/console.effekt +3 -3
  11. package/libraries/common/io/error.effekt +9 -4
  12. package/libraries/common/io/filesystem.effekt +73 -44
  13. package/libraries/common/io/network.effekt +277 -96
  14. package/libraries/common/io/signal.effekt +5 -4
  15. package/libraries/common/io.effekt +44 -0
  16. package/libraries/common/process.effekt +118 -83
  17. package/libraries/common/ref.effekt +8 -5
  18. package/libraries/common/result.effekt +17 -1
  19. package/libraries/common/stream.effekt +2 -2
  20. package/libraries/common/string.effekt +10 -2
  21. package/libraries/common/stringbuffer.effekt +1 -1
  22. package/libraries/js/effekt_builtins.js +9 -0
  23. package/libraries/js/effekt_runtime.js +3 -0
  24. package/libraries/llvm/bytearray.c +51 -3
  25. package/libraries/llvm/forward-declare-c.ll +2 -0
  26. package/libraries/llvm/io.c +495 -182
  27. package/libraries/llvm/rts.ll +251 -79
  28. package/libraries/llvm/types.c +3 -2
  29. package/licenses/eclipse public license, version 2.0 - epl-2.0.html +5 -5
  30. package/licenses/mit license - mit-license.html +87 -49
  31. package/licenses/the bsd license - bsd-license.html +85 -47
  32. package/licenses/the mit license - mit.html +88 -50
  33. package/package.json +1 -1
package/bin/effekt CHANGED
Binary file
@@ -133,6 +133,15 @@
133
133
  (define (int-quotient x y)
134
134
  (if (fx= y 0) (quotient x y) (fxquotient x y)))
135
135
 
136
+ (define (int-remainder x y)
137
+ (if (fx= y 0) (remainder x y) (fxremainder x y)))
138
+
139
+ (define (int-div x y)
140
+ (if (fx= y 0) (div x y) (fxdiv x y)))
141
+
142
+ (define (int-mod x y)
143
+ (if (fx= y 0) (mod x y) (fxmod x y)))
144
+
136
145
  (define (relative-timestamp)
137
146
  (let ([t (current-time 'time-monotonic)])
138
147
  (+ (* (time-second t) 1000000000) (time-nanosecond t))))
@@ -22,8 +22,9 @@ extern type Array[T] =
22
22
  /// +--------------+------+------------+
23
23
  /// ```
24
24
  extern llvm """
25
- define void @array_erase_fields(ptr %array_pointer) {
25
+ define void @array_erase_fields(ptr %object) {
26
26
  entry:
27
+ %array_pointer = getelementptr %Header, ptr %object, i64 1
27
28
  %data_pointer = getelementptr inbounds i64, ptr %array_pointer, i64 1
28
29
  %size = load i64, ptr %array_pointer, align 8
29
30
  %size_eq_0 = icmp eq i64 %size, 0
@@ -39,6 +40,7 @@ loop:
39
40
  %cmp = icmp ult i64 %inc, %size
40
41
  br i1 %cmp, label %loop, label %exit
41
42
  exit:
43
+ call void @free(ptr %object)
42
44
  ret void
43
45
  }
44
46
  """
@@ -25,11 +25,6 @@ extern llvm """
25
25
  declare i32 @clock_gettime(i32, ptr)
26
26
  """
27
27
 
28
- // This should not be needed when using NodeJS 16.x or newer.
29
- extern jsNode """
30
- const { performance } = require('node:perf_hooks');
31
- """
32
-
33
28
  /// High-precision timestamp in nanoseconds that should be for measurements.
34
29
  ///
35
30
  /// This timestamp should only be used for **relative** measurements,
@@ -32,7 +32,7 @@ extern def allocate(size: Int) at global: ByteArray =
32
32
  %object_alloc = tail call noalias ptr @calloc(i64 %object_size, i64 1)
33
33
  store i64 0, ptr %object_alloc, align 8
34
34
  %object_data_ptr = getelementptr inbounds i8, ptr %object_alloc, i64 8
35
- store ptr @bytearray_erase_noop, ptr %object_data_ptr, align 8
35
+ store ptr @bytearray_erase, ptr %object_data_ptr, align 8
36
36
  %ret_object1 = insertvalue %Pos poison, i64 ${size}, 0
37
37
  %ret_object2 = insertvalue %Pos %ret_object1, ptr %object_alloc, 1
38
38
  ret %Pos %ret_object2
@@ -120,13 +120,18 @@ def build(size: Int) { index: Int => Byte }: ByteArray = {
120
120
  ///
121
121
  /// O(N)
122
122
  def copy(from: ByteArray, start: Int, to: ByteArray, offset: Int, length: Int): Unit =
123
- if (length < 0 || start < 0 || offset < 0
124
- || start + length > from.size || offset + length > to.size) {
125
- <{ "bytearray::copy: range out of bounds" }>
126
- } else {
123
+ if (from.inBounds(start, length) && to.inBounds(offset, length)) {
127
124
  unsafeCopy(from, start, to, offset, length)
125
+ } else {
126
+ <{ "bytearray::copy: range out of bounds" }>
128
127
  }
129
128
 
129
+ /// Whether `[offset, offset + length)` is a valid range of indices inside `arr`.
130
+ ///
131
+ /// O(1)
132
+ def inBounds(arr: ByteArray, offset: Int, length: Int): Bool =
133
+ offset >= 0 && length >= 0 && offset + length <= arr.size
134
+
130
135
  /// `copy` without its bounds check.
131
136
  /// Corrupts memory if misused; prefer `copy`.
132
137
  extern def unsafeCopy(from: ByteArray, start: Int, to: ByteArray, offset: Int, length: Int) at global: Unit =
@@ -192,18 +197,29 @@ def foreachIndex(arr: ByteArray){ action: (Int, Byte) {Label} => Unit }: Unit =
192
197
  action(i, arr.get(i)) {label}
193
198
  }
194
199
 
195
- 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
196
211
  js "(new TextEncoder().encode(${str}))"
197
212
  llvm """
198
213
  ret %Pos ${str}
199
214
  """
200
215
  chez "(string->utf8 ${str})"
201
216
 
202
- extern def toString(arr: ByteArray) at {}: String =
217
+ extern def toString(arr: ByteArray) at global: String =
203
218
  js "(new TextDecoder('utf-8').decode(${arr}))"
204
219
  // assuming the buffer is already in UTF-8
205
220
  llvm """
206
- ret %Pos ${arr}
221
+ %str = call %Pos @uniqueByteArray(%Pos ${arr})
222
+ ret %Pos %str
207
223
  """
208
224
  chez "(utf8->string ${arr})"
209
225
 
@@ -246,7 +262,8 @@ extern js """
246
262
  """
247
263
 
248
264
  extern llvm """
249
- define void @bytearray_erase_noop(ptr readnone %0) {
265
+ define void @bytearray_erase(ptr %object) {
266
+ call void @free(ptr %object)
250
267
  ret void
251
268
  }
252
269
  """
@@ -267,7 +284,7 @@ extern chez """
267
284
  [else (loop (+ i 1))]))))
268
285
  """
269
286
 
270
- extern def compareByteArrayImpl(b1: ByteArray, b2: ByteArray) at {}: Int =
287
+ extern def compareByteArrayImpl(b1: ByteArray, b2: ByteArray) at global: Int =
271
288
  js "bytearray$compare(${b1}, ${b2})"
272
289
  llvm """
273
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] = {
@@ -72,7 +72,7 @@ extern def readln() at async: String =
72
72
  jsNode "$effekt.capture(callback => $effekt.readln(callback))"
73
73
  llvm """
74
74
  %result = call %Pos @c_io_readln()
75
- notail call void @resume_Pos(%Stack %stack, %Pos %result)
75
+ musttail call tailcc void @return_Pos(%Stack %stack, %Pos %result) "no_callee_saved_registers"
76
76
  ret void
77
77
  """
78
78
 
@@ -280,7 +280,7 @@ extern def infixNeq(x: Char, y: Char) at {}: Bool =
280
280
 
281
281
  extern def infixEq(x: String, y: String) at {}: Bool =
282
282
  js "${x} === ${y}"
283
- chez "(equal? ${x} ${y})"
283
+ chez "(string=? ${x} ${y})"
284
284
  llvm """
285
285
  %res = call %Pos @c_bytearray_equal(%Pos ${x}, %Pos ${y})
286
286
  ret %Pos %res
@@ -290,7 +290,7 @@ def infixNeq(x: String, y: String): Bool = not(x == y)
290
290
 
291
291
  extern def infixEq(x: Bool, y: Bool) at {}: Bool =
292
292
  js "${x} === ${y}"
293
- chez "(equal? ${x} ${y})"
293
+ chez "(eq? ${x} ${y})"
294
294
  llvm """
295
295
  %slim_x = extractvalue %Pos ${x}, 0
296
296
  %slim_y = extractvalue %Pos ${y}, 0
@@ -302,7 +302,7 @@ extern def infixEq(x: Bool, y: Bool) at {}: Bool =
302
302
 
303
303
  extern def infixNeq(x: Bool, y: Bool) at {}: Bool =
304
304
  js "${x} !== ${y}"
305
- chez "(not (equal? ${x} ${y}))"
305
+ chez "(not (eq? ${x} ${y}))"
306
306
  llvm """
307
307
  %slim_x = extractvalue %Pos ${x}, 0
308
308
  %slim_y = extractvalue %Pos ${y}, 0
@@ -334,6 +334,12 @@ extern def infixNeq(x: Byte, y: Byte) at {}: Bool =
334
334
 
335
335
  // Math ops
336
336
  // ========
337
+
338
+ // Numeric representations in the backends:
339
+ // LLVM: int64_t (64-bit integer)
340
+ // JS: 64-bit floating-point (64-bit IEEE 754)
341
+ // Chez: 64-bit integer
342
+
337
343
  extern def infixPlus(x: Int, y: Int) at {}: Int =
338
344
  js "(${x} + ${y})"
339
345
  chez "(fx+ ${x} ${y})"
@@ -355,11 +361,48 @@ extern def infixMinus(x: Int, y: Int) at {}: Int =
355
361
  chez "(fx- ${x} ${y})"
356
362
  llvm "%z = sub %Int ${x}, ${y} ret %Int %z"
357
363
 
358
- extern def mod(x: Int, y: Int) at {}: Int =
364
+ /// Computes the quotient of truncated division (rounds towards zero)
365
+ extern def quot(x: Int, y: Int) at {}: Int =
366
+ js "Math.trunc(${x} / ${y})"
367
+ chez "(int-quotient ${x} ${y})"
368
+ llvm "%z = sdiv %Int ${x}, ${y} ret %Int %z"
369
+
370
+ /// Computes the remainder of truncated division (has the sign of the dividend)
371
+ extern def rem(x: Int, y: Int) at {}: Int =
359
372
  js "(${x} % ${y})"
360
- chez "(fxmodulo ${x} ${y})"
373
+ chez "(int-remainder ${x} ${y})"
361
374
  llvm "%z = srem %Int ${x}, ${y} ret %Int %z"
362
375
 
376
+ /// Computes the quotient of Euclidean division
377
+ extern def div(x: Int, y: Int) at {}: Int =
378
+ js "$effekt.div(${x}, ${y})"
379
+ chez "(int-div ${x} ${y})"
380
+ llvm """
381
+ %q = sdiv %Int ${x}, ${y}
382
+ %r = srem %Int ${x}, ${y}
383
+ %rNeg = ashr %Int %r, 63
384
+ %yNeg = ashr %Int ${y}, 63
385
+ %ySign = or %Int %yNeg, 1
386
+ %adjust = and %Int %rNeg, %ySign
387
+ %z = sub %Int %q, %adjust
388
+ ret %Int %z
389
+ """
390
+
391
+ /// Computes the remainder of Euclidean division (is never negative)
392
+ extern def mod(x: Int, y: Int) at {}: Int =
393
+ js "$effekt.mod(${x}, ${y})"
394
+ chez "(int-mod ${x} ${y})"
395
+ llvm """
396
+ %r = srem %Int ${x}, ${y}
397
+ %rNeg = ashr %Int %r, 63
398
+ %yNeg = ashr %Int ${y}, 63
399
+ %yFlip = xor %Int ${y}, %yNeg
400
+ %yAbs = sub %Int %yFlip, %yNeg
401
+ %adjust = and %Int %rNeg, %yAbs
402
+ %z = add %Int %r, %adjust
403
+ ret %Int %z
404
+ """
405
+
363
406
  extern def infixPlus(x: Double, y: Double) at {}: Double =
364
407
  js "(${x} + ${y})"
365
408
  chez "(fl+ ${x} ${y})"
@@ -661,7 +704,6 @@ extern def bitwiseNot(x: Int) at {}: Int =
661
704
  chez "(fxnot ${x})"
662
705
  llvm "%z = xor %Int ${x}, -1 ret %Int %z"
663
706
 
664
-
665
707
  // Byte operations
666
708
  // ===============
667
709
  extern def toByte(n: Int) at {}: Byte =
@@ -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}
@@ -1,111 +1,121 @@
1
1
  module heap
2
- import resizable_array
3
2
 
4
- /// Resizable 2-ary min-heap, backed by a resizable array
5
- /// `cmp` defines the ordering of elements
6
- record Heap[T](rawContents: ResizableArray[T], cmp: (T, T) => Ordering at {})
3
+ import stream
7
4
 
8
- /// Make a new Heap with the given comparison operation
9
- def heap[T](cmp: (T,T) => Ordering at {}) =
10
- Heap[T](resizableArray(), cmp)
11
-
12
- /// Make a new Heap with the given comparison operation and initial capacity
13
- def heap[T](cmp: (T,T) => Ordering at {}, capacity: Int) =
14
- Heap[T](resizableArray(capacity), cmp)
5
+ /// A value together with its priority. Smaller weights come first.
6
+ record Weighted[A](value: A, weight: Double)
15
7
 
16
8
  namespace internal {
17
- def left(idx: Int) = 2 * idx + 1
18
- def right(idx: Int) = 2 * idx + 2
19
- def parent(idx: Int) = (idx - 1) / 2
20
-
21
- def bubbleUp[A](heap: Heap[A], idx: Int) = {
22
- val arr = heap.rawContents
23
- arr.boundsCheck(idx) // idx > parent(idx), parent(parent(idx)) etc
24
-
25
- def go(idx: Int): Unit = {
26
- if (idx > 0 and (heap.cmp)(arr.get(parent(idx)), arr.get(idx)) is Greater()) {
27
- arr.swap(parent(idx), idx)
28
- go(parent(idx))
29
- }
30
- }
31
- go(idx)
9
+ /// A pairing heap: empty, or a minimal element with its subheaps.
10
+ type Tree[A] {
11
+ Node(value: A, weight: Double, subheaps: List[Tree[A]])
12
+ Empty()
32
13
  }
33
- def sinkDown[A](heap: Heap[A], idx: Int) = {
34
- val arr = heap.rawContents
35
14
 
36
- def infixLt(x: A, y: A) = {
37
- if ((heap.cmp)(x,y) is Less()) { true } else { false }
38
- }
39
-
40
- def go(idx: Int): Unit = {
41
- if (right(idx) < arr.size) {
42
- val v = arr.get(idx)
43
- val l = arr.get(left(idx))
44
- val r = arr.get(right(idx))
45
- if (l < v && r < v) {
46
- // swap with the smaller one
47
- if (l < r) {
48
- arr.swap(left(idx), idx)
49
- go(left(idx))
50
- } else {
51
- arr.swap(right(idx), idx)
52
- go(right(idx))
53
- }
54
- } else if (l < v) {
55
- arr.swap(left(idx), idx)
56
- go(left(idx))
57
- } else if (r < v) {
58
- arr.swap(right(idx), idx)
59
- go(right(idx))
60
- }
61
- } else if (left(idx) < arr.size) {
62
- if (arr.get(left(idx)) < arr.get(idx)) {
63
- arr.swap(left(idx), idx)
64
- go(left(idx))
65
- }
66
- } // else: we are at the bottom
67
- }
68
- go(idx)
15
+ /// Merge a nonempty list of heaps, given as head and tail, using the two-pass pairing strategy.
16
+ ///
17
+ /// O(log n) amortized
18
+ def mergePairs[A](heap: Tree[A], heaps: List[Tree[A]]): Tree[A] = heaps match {
19
+ case Nil() => heap
20
+ case Cons(heap1, Nil()) => meld(heap, heap1)
21
+ case Cons(heap1, Cons(heap2, rest)) => meld(meld(heap, heap1), mergePairs(heap2, rest))
69
22
  }
70
23
  }
71
24
 
72
- /// Insert value into heap
25
+ /// Persistent min-heap, implemented as a pairing heap.
26
+ type Heap[A] = internal::Tree[A]
27
+
28
+ /// The empty heap.
73
29
  ///
74
- /// O(log n) worst case if capacity suffices, O(1) average
75
- def insert[T](heap: Heap[T], value: T): Unit = {
76
- with on[OutOfBounds].panic();
77
- val idx = heap.rawContents.add(value)
78
- internal::bubbleUp(heap, idx)
79
- }
30
+ /// O(1)
31
+ def empty[A](): Heap[A] = internal::Empty()
80
32
 
81
- /// find and return (but not remove) the minimal element in this heap
82
- /// panics when heap is empty
33
+ /// A heap containing exactly one element.
83
34
  ///
84
35
  /// O(1)
85
- def findMin[T](heap: Heap[T]): T / Exception[OutOfBounds] = {
86
- heap.rawContents.get(0)
36
+ def single[A](value: A, weight: Double): Heap[A] = internal::Node(value, weight, Nil())
37
+
38
+ /// Check if the heap is empty.
39
+ ///
40
+ /// O(1)
41
+ def isEmpty[A](heap: Heap[A]): Bool = heap match {
42
+ case internal::Empty() => true
43
+ case internal::Node(_, _, _) => false
87
44
  }
88
45
 
89
- /// find and remove the minimal element in this heap
90
- /// panics when heap is empty
46
+ /// Merge two heaps.
91
47
  ///
92
- /// O(log n)
93
- def deleteMin[T](heap: Heap[T]): T / Exception[OutOfBounds] = {
94
- val arr = heap.rawContents
95
- val res = arr.get(0)
96
- if (arr.size == 1) {
97
- arr.popRight()
98
- res
99
- } else {
100
- arr.set(0, arr.popRight())
101
- internal::sinkDown(heap, 0)
102
- res
103
- }
48
+ /// O(1)
49
+ def meld[A](heap1: Heap[A], heap2: Heap[A]): Heap[A] = (heap1, heap2) match {
50
+ case (internal::Empty(), heap2) => heap2
51
+ case (heap1, internal::Empty()) => heap1
52
+ case (internal::Node(x1, w1, subheaps1), internal::Node(x2, w2, subheaps2)) =>
53
+ if (w1 < w2) {
54
+ internal::Node(x1, w1, Cons(heap2, subheaps1))
55
+ } else {
56
+ internal::Node(x2, w2, Cons(heap1, subheaps2))
57
+ }
104
58
  }
105
59
 
106
- /// Number of elements in the heap
60
+ /// Insert a value with the given weight.
107
61
  ///
108
62
  /// O(1)
109
- def size[T](heap: Heap[T]): Int = {
110
- heap.rawContents.size
111
- }
63
+ def insert[A](heap: Heap[A], value: A, weight: Double): Heap[A] =
64
+ meld(single(value, weight), heap)
65
+
66
+ /// The element with the smallest weight, without removing it.
67
+ /// Returns `None()` if the heap is empty.
68
+ ///
69
+ /// O(1)
70
+ def findMinimum[A](heap: Heap[A]): Option[Weighted[A]] = heap match {
71
+ case internal::Empty() => None()
72
+ case internal::Node(x, w, _) => Some(Weighted(x, w))
73
+ }
74
+
75
+ /// Remove the element with the smallest weight, returning it and the remaining heap.
76
+ /// Returns `None()` if the heap is empty.
77
+ ///
78
+ /// O(log n) amortized
79
+ def extract[A](heap: Heap[A]): Option[(Weighted[A], Heap[A])] = heap match {
80
+ case internal::Empty() => None()
81
+ case internal::Node(x, w, Nil()) => Some((Weighted(x, w), internal::Empty()))
82
+ case internal::Node(x, w, Cons(heap1, heaps)) => Some((Weighted(x, w), internal::mergePairs(heap1, heaps)))
83
+ }
84
+
85
+ /// Insert the given value and remove the element with the smallest weight.
86
+ /// Returns the given value and the unchanged heap if its weight is not larger than all others.
87
+ ///
88
+ /// O(log n) amortized
89
+ def exchange[A](heap: Heap[A], value: A, weight: Double): (Weighted[A], Heap[A]) = heap match {
90
+ case internal::Node(x, w, heaps) =>
91
+ if (w < weight) {
92
+ (Weighted(x, w), internal::mergePairs(single(value, weight), heaps))
93
+ } else {
94
+ (Weighted(value, weight), heap)
95
+ }
96
+ case internal::Empty() => (Weighted(value, weight), heap)
97
+ }
98
+
99
+ /// Emit all elements in ascending order of weight.
100
+ ///
101
+ /// O(n log n)
102
+ def each[A](heap: Heap[A]): Unit / emit[Weighted[A]] = extract(heap) match {
103
+ case None() => ()
104
+ case Some((element, rest)) =>
105
+ do emit(element)
106
+ each(rest)
107
+ }
108
+
109
+ /// Collect all emitted elements into a heap.
110
+ ///
111
+ /// O(n)
112
+ def collectHeap[A] { stream: () => Unit / emit[Weighted[A]] }: Heap[A] = {
113
+ var heap: Heap[A] = empty()
114
+ try {
115
+ stream()
116
+ } with emit[Weighted[A]] { case Weighted(value, weight) =>
117
+ heap = insert(heap, value, weight)
118
+ resume(())
119
+ }
120
+ heap
121
+ }
@@ -23,14 +23,14 @@ def console[R] { program: () => R / Console }: R = {
23
23
  namespace js {
24
24
 
25
25
  extern jsNode """
26
- const readline = require('node:readline');
26
+ const console$readline = require('node:readline');
27
27
  """
28
28
 
29
29
  extern type JSConsole =
30
- js "readline.createInterface return type"
30
+ js "console$readline.createInterface return type"
31
31
 
32
32
  extern def newConsole() at io: JSConsole =
33
- jsNode """readline.createInterface({
33
+ jsNode """console$readline.createInterface({
34
34
  input: process.stdin,
35
35
  output: process.stdout,
36
36
  })"""
@@ -363,7 +363,12 @@ namespace internal {
363
363
  """
364
364
 
365
365
  extern jsNode """
366
- const { getSystemErrorName } = require('node:util');
366
+ const error$getSystemErrorName = require('node:util').getSystemErrorName;
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;
367
372
 
368
373
  /**
369
374
  * Maps the error code to a Effekt-stable (platform independent) numeric value.
@@ -376,7 +381,7 @@ extern jsNode """
376
381
  * For reference, see the following Deno code which is more readable than the NodeJS implementation:
377
382
  * https://github.com/denoland/deno/blob/8fb073d7b4ea83b57fd1bf9875681347b414bbe6/ext/node/polyfills/internal_binding/uv.ts
378
383
  */
379
- function errorNumber(errno) {
384
+ function error$number(errno) {
380
385
  const mapByName = {
381
386
  EPERM: 1,
382
387
  ENOENT: 2,
@@ -461,7 +466,7 @@ extern jsNode """
461
466
 
462
467
  // When the error code is not known, we return 217 (UNKNOWN).
463
468
  try {
464
- const name = getSystemErrorName(errno);
469
+ const name = error$getSystemErrorName(errno);
465
470
  return mapByName[name] ?? 217;
466
471
  } catch {
467
472
  return 217;
@@ -470,7 +475,7 @@ extern jsNode """
470
475
  """
471
476
 
472
477
  extern def errorNumber(errno: Int) at {}: Int =
473
- jsNode "errorNumber(${errno})"
478
+ jsNode "error$number(${errno})"
474
479
  llvm """
475
480
  %z = call %Int @c_error_number(%Int ${errno})
476
481
  ret %Int %z