@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
@@ -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,7 @@ 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
367
 
368
368
  /**
369
369
  * Maps the error code to a Effekt-stable (platform independent) numeric value.
@@ -376,7 +376,7 @@ extern jsNode """
376
376
  * For reference, see the following Deno code which is more readable than the NodeJS implementation:
377
377
  * https://github.com/denoland/deno/blob/8fb073d7b4ea83b57fd1bf9875681347b414bbe6/ext/node/polyfills/internal_binding/uv.ts
378
378
  */
379
- function errorNumber(errno) {
379
+ function error$number(errno) {
380
380
  const mapByName = {
381
381
  EPERM: 1,
382
382
  ENOENT: 2,
@@ -461,7 +461,7 @@ extern jsNode """
461
461
 
462
462
  // When the error code is not known, we return 217 (UNKNOWN).
463
463
  try {
464
- const name = getSystemErrorName(errno);
464
+ const name = error$getSystemErrorName(errno);
465
465
  return mapByName[name] ?? 217;
466
466
  } catch {
467
467
  return 217;
@@ -470,7 +470,7 @@ extern jsNode """
470
470
  """
471
471
 
472
472
  extern def errorNumber(errno: Int) at {}: Int =
473
- jsNode "errorNumber(${errno})"
473
+ jsNode "error$number(${errno})"
474
474
  llvm """
475
475
  %z = call %Int @c_error_number(%Int ${errno})
476
476
  ret %Int %z
@@ -170,11 +170,31 @@ def openForWriting(path: String): File / Exception[IOError] =
170
170
  def openForAppending(path: String): File / Exception[IOError] =
171
171
  internal::checkResult(internal::openForAppending(path))
172
172
 
173
- def read(file: File, buffer: ByteArray, offset: Int, size: Int, position: Int): Int / Exception[IOError] =
174
- internal::checkResult(internal::read(file, buffer, offset, size, position))
173
+ /// Reads up to `size` bytes from `file` at `position` (-1 for the current position) into `buffer`, starting at `offset`.
174
+ /// Returns the number of bytes read, and 0 at end of file.
175
+ /// Panics unless:
176
+ /// - `size` is positive (a read of nothing would look like end of file), and
177
+ /// - `[offset, offset + size)` is a valid range inside `buffer` (like `bytearray::copy`).
178
+ def read(file: File, buffer: ByteArray, offset: Int, size: Int, position: Int): Int / Exception[IOError] = {
179
+ if (size <= 0) { panic("io/filesystem::read: size must be positive") }
180
+
181
+ if (buffer.inBounds(offset, size)) {
182
+ internal::checkResult(internal::read(file, buffer, offset, size, position))
183
+ } else {
184
+ panic("io/filesystem::read: window out of bounds")
185
+ }
186
+ }
175
187
 
176
- def write(file: File, buffer: ByteArray, offset: Int, size: Int, position: Int): Int / Exception[IOError] =
177
- internal::checkResult(internal::write(file, buffer, offset, size, position))
188
+ /// Writes up to `size` bytes from `buffer`, starting at `offset`, to `file` at `position` (-1 for the current position).
189
+ /// Returns the number of bytes written, which may be fewer than `size`.
190
+ /// Panics unless `[offset, offset + size)` is a valid range inside `buffer` (like `bytearray::copy`).
191
+ def write(file: File, buffer: ByteArray, offset: Int, size: Int, position: Int): Int / Exception[IOError] = {
192
+ if (buffer.inBounds(offset, size)) {
193
+ internal::checkResult(internal::write(file, buffer, offset, size, position))
194
+ } else {
195
+ panic("io/filesystem::write: window out of bounds")
196
+ }
197
+ }
178
198
 
179
199
  def close(file: File): Unit / Exception[IOError] = {
180
200
  internal::checkResult(internal::close(file)); ()
@@ -186,47 +206,37 @@ def mkdir(path: String): Unit / Exception[IOError] = {
186
206
 
187
207
  namespace internal {
188
208
 
189
- extern js """
190
- /**
191
- * Nodejs file operations expect buffers, but we represent buffers as typed arrays.
192
- * This function converts between the two without copying.
193
- */
194
- function toBuffer(buffer) {
195
- return Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength)
196
- }
197
- """
198
-
199
209
  extern jsNode """
200
- const fs = require("fs");
210
+ const filesystem$node = require("fs");
201
211
 
202
- function open(path, flags, callback) {
203
- fs.open(path, flags, (err, file) => {
212
+ function filesystem$open(path, flags, callback) {
213
+ filesystem$node.open(path, flags, (err, file) => {
204
214
  if (err) { callback(err.errno) } else { callback(file) }
205
215
  })
206
216
  }
207
217
 
208
- function read(file, buffer, offset, size, position, callback) {
218
+ function filesystem$read(file, buffer, offset, size, position, callback) {
209
219
  let positionOrNull = position === -1 ? null : position;
210
- fs.read(file, toBuffer(buffer), offset, size, positionOrNull, (err, bytesRead) => {
220
+ filesystem$node.read(file, io$toBuffer(buffer), offset, size, positionOrNull, (err, bytesRead) => {
211
221
  if (err) { callback(err.errno) } else { callback(bytesRead) }
212
222
  })
213
223
  }
214
224
 
215
- function write(file, buffer, offset, size, position, callback) {
225
+ function filesystem$write(file, buffer, offset, size, position, callback) {
216
226
  let positionOrNull = position === -1 ? null : position;
217
- fs.write(file, toBuffer(buffer), offset, size, positionOrNull, (err, bytesWritten) => {
227
+ filesystem$node.write(file, io$toBuffer(buffer), offset, size, positionOrNull, (err, bytesWritten) => {
218
228
  if (err) { callback(err.errno) } else { callback(bytesWritten) }
219
229
  })
220
230
  }
221
231
 
222
- function close(file, callback) {
223
- fs.close(file, (err) => {
232
+ function filesystem$close(file, callback) {
233
+ filesystem$node.close(file, (err) => {
224
234
  if (err) { callback(err.errno) } else { callback(0) }
225
235
  })
226
236
  }
227
237
 
228
- function mkdir(path, callback) {
229
- fs.mkdir(path, (err) => {
238
+ function filesystem$mkdir(path, callback) {
239
+ filesystem$node.mkdir(path, (err) => {
230
240
  if (err) { callback(err.errno) } else { callback(0) }
231
241
  })
232
242
  }
@@ -243,49 +253,49 @@ namespace internal {
243
253
  """
244
254
 
245
255
  extern def openForReading(path: String) at async: Int =
246
- jsNode "$effekt.capture(callback => open(${path}, 'r', callback))"
256
+ jsNode "$effekt.capture(callback => filesystem$open(${path}, 'r', callback))"
247
257
  llvm """
248
258
  notail call void @c_fs_open_reading(%Pos ${path}, %Stack %stack)
249
259
  ret void
250
260
  """
251
261
 
252
262
  extern def openForWriting(path: String) at async: Int =
253
- jsNode "$effekt.capture(callback => open(${path}, 'w', callback))"
263
+ jsNode "$effekt.capture(callback => filesystem$open(${path}, 'w', callback))"
254
264
  llvm """
255
265
  notail call void @c_fs_open_writing(%Pos ${path}, %Stack %stack)
256
266
  ret void
257
267
  """
258
268
 
259
269
  extern def openForAppending(path: String) at async: Int =
260
- jsNode "$effekt.capture(callback => open(${path}, 'a', callback))"
270
+ jsNode "$effekt.capture(callback => filesystem$open(${path}, 'a', callback))"
261
271
  llvm """
262
272
  notail call void @c_fs_open_appending(%Pos ${path}, %Stack %stack)
263
273
  ret void
264
274
  """
265
275
 
266
276
  extern def read(file: Int, buffer: ByteArray, offset: Int, size: Int, position: Int) at async: Int =
267
- jsNode "$effekt.capture(callback => read(${file}, ${buffer}, ${offset}, ${size}, ${position}, callback))"
277
+ jsNode "$effekt.capture(callback => filesystem$read(${file}, ${buffer}, ${offset}, ${size}, ${position}, callback))"
268
278
  llvm """
269
279
  notail call void @c_fs_read(%Int ${file}, %Pos ${buffer}, %Int ${offset}, %Int ${size}, %Int ${position}, %Stack %stack)
270
280
  ret void
271
281
  """
272
282
 
273
283
  extern def write(file: Int, buffer: ByteArray, offset: Int, size: Int, position: Int) at async: Int =
274
- jsNode "$effekt.capture(callback => write(${file}, ${buffer}, ${offset}, ${size}, ${position}, callback))"
284
+ jsNode "$effekt.capture(callback => filesystem$write(${file}, ${buffer}, ${offset}, ${size}, ${position}, callback))"
275
285
  llvm """
276
286
  notail call void @c_fs_write(%Int ${file}, %Pos ${buffer}, %Int ${offset}, %Int ${size}, %Int ${position}, %Stack %stack)
277
287
  ret void
278
288
  """
279
289
 
280
290
  extern def close(file: Int) at async: Int =
281
- jsNode "$effekt.capture(callback => close(${file}, callback))"
291
+ jsNode "$effekt.capture(callback => filesystem$close(${file}, callback))"
282
292
  llvm """
283
293
  notail call void @c_fs_close(%Int ${file}, %Stack %stack)
284
294
  ret void
285
295
  """
286
296
 
287
297
  extern def mkdir(path: String) at async: Int =
288
- jsNode "$effekt.capture(callback => mkdir(${path}, callback))"
298
+ jsNode "$effekt.capture(callback => filesystem$mkdir(${path}, callback))"
289
299
  llvm """
290
300
  notail call void @c_fs_mkdir(%Pos ${path}, %Stack %stack)
291
301
  ret void