@effekt-lang/effekt 0.84.0 → 0.86.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.
@@ -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
  """
@@ -1,8 +1,18 @@
1
1
  module process
2
2
  import array
3
+ import io/error
3
4
 
5
+ extern jsNode """
6
+ // Node writes to pipes in an async way, so we need to wait for them to finish.
7
+ function process$exit(code) {
8
+ process.stdout.write('', () => process.stderr.write('', () => process.exit(code)));
9
+ $effekt.abort();
10
+ }
11
+ """
12
+
13
+ /// Ends the program with the given `errorCode`, once its standard output and error are written.
4
14
  extern def exit(errorCode: Int) at io: Nothing =
5
- js "(function() { process.exit(${errorCode}) })()"
15
+ jsNode "process$exit(${errorCode})"
6
16
  llvm """
7
17
  %exitCode = trunc i64 ${errorCode} to i32
8
18
  call void @exit(i32 %exitCode)
@@ -54,24 +64,32 @@ extern def close(to: WritableStream) at io: Unit =
54
64
  ret %Pos zeroinitializer
55
65
  """
56
66
 
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)
67
+ /// How a process ended:
68
+ /// - either it exited with a `code`, which is its result even if it is not 0,
69
+ /// - or it was terminated by a `signal`, numbered in a platform-specific way.
70
+ type ExitStatus {
71
+ Exited(code: Int)
72
+ Signaled(signal: Int)
73
+ }
74
+
75
+ /// Runs `cmd` with `args`, connecting its standard streams as per `options`.
76
+ /// Returns an `ExitStatus` once it has exited and its piped output has ended, so that every callback for that output has run.
77
+ /// Raises `IOError` if it cannot be started, such as `ENOENT` for a missing command.
78
+ def spawn(cmd: String, args: Array[String], options: SpawnOptions): ExitStatus / Exception[IOError] = {
79
+ val stdin: WritableStream => Unit at {io, global} = options.stdin.getOrElse { box { _ => () } }
80
+ val stdout: String => Unit at {io, global} = options.stdout.getOrElse { box { _ => () } }
81
+ val stderr: String => Unit at {io, global} = options.stderr.getOrElse { box { _ => () } }
82
+
83
+ internal::exitStatus(
84
+ internal::checkResult(
85
+ internal::spawn(
86
+ cmd, args,
87
+ internal::piped(options.stdin), stdin,
88
+ internal::piped(options.stdout), stdout,
89
+ internal::piped(options.stderr), stderr
90
+ )
91
+ )
92
+ )
75
93
  }
76
94
 
77
95
  namespace internal {
@@ -81,6 +99,10 @@ namespace internal {
81
99
  case Some(f) => box { a => f(a); then(a) }
82
100
  }
83
101
 
102
+ /// The result of `spawn` is the exit code, or the signal times 2^32 (exit codes have 32 bits on every platform).
103
+ def exitStatus(status: Int): ExitStatus =
104
+ if (status >= 4294967296) Signaled(status / 4294967296) else Exited(status)
105
+
84
106
  /// 1 if a stream is piped to a callback, 0 if it is inherited.
85
107
  def piped[A](callback: Option[A]): Int = callback match {
86
108
  case Some(_) => 1
@@ -89,6 +111,7 @@ namespace internal {
89
111
 
90
112
  extern jsNode """
91
113
  const { spawn: process$nodeSpawn } = require('node:child_process');
114
+ const process$signals = require('node:os').constants.signals;
92
115
 
93
116
  function process$spawn(cmd, args, pipeStdin, stdin, pipeStdout, stdout, pipeStderr, stderr, callback) {
94
117
  const stdio = [pipeStdin ? 'pipe' : 'inherit', pipeStdout ? 'pipe' : 'inherit', pipeStderr ? 'pipe' : 'inherit'];
@@ -96,8 +119,14 @@ namespace internal {
96
119
  // Note: Decoded as UTF-8 by the stream itself, so that a character split between two chunks stays whole.
97
120
  if (pipeStdout) { p.stdout.setEncoding('utf8'); p.stdout.on('data', chunk => $effekt.runToplevel((ks, k) => stdout(chunk, ks, k))); }
98
121
  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));
122
+ if (pipeStdin) { p.on('spawn', () => $effekt.runToplevel((ks, k) => stdin(p.stdin, ks, k))); }
123
+ let error = null;
124
+ p.on('error', err => { error = err; });
125
+ p.on('close', (code, signal) => {
126
+ if (error !== null) { callback(error.errno); }
127
+ else if (signal !== null) { callback(process$signals[signal] * 4294967296); }
128
+ else { callback(code); }
129
+ });
101
130
  }
102
131
  """
103
132
 
@@ -3,6 +3,7 @@ module result
3
3
  import effekt
4
4
  import option
5
5
  import exception
6
+ import list
6
7
 
7
8
  /// Represents the result of a potentially failing computation.
8
9
  /// It is the "reification" of the Exception[E] effect.
@@ -40,4 +41,19 @@ def isError[A, E](r: Result[A, E]): Bool =
40
41
  if (r is Error(_, _)) true else false
41
42
 
42
43
  def isSuccess[A, E](r: Result[A, E]): Bool =
43
- if (r is Success(_)) true else false
44
+ if (r is Success(_)) true else false
45
+
46
+ /// Runs `action` on `head`, and then on each element of `tail` one by one, returning the result of the first which does not raise,
47
+ /// otherwise the exception of the last one.
48
+ /// Similar to `default`, but for multiple alternatives, one after another.
49
+ def firstSuccess[A, R, E](head: A, tail: List[A]) { action: A => R / Exception[E] }: R / Exception[E] = {
50
+ def go(candidate: A, rest: List[A]): R = rest match {
51
+ case Nil() => action(candidate)
52
+ case Cons(next, more) =>
53
+ result[R, E] { action(candidate) } match {
54
+ case Success(value) => value
55
+ case Error(_, _) => go(next, more)
56
+ }
57
+ }
58
+ go(head, tail)
59
+ }
@@ -194,10 +194,10 @@ def countIf[A] { shouldCount: A => Bool } { stream: () => Unit / emit[A] }: Int
194
194
 
195
195
  /// Count the number of emitted values.
196
196
  def count[A] { stream: () => Unit / emit[A] }: Int =
197
- countIf[A] { _ => true } {stream}
197
+ countIf { _ => true } {stream}
198
198
 
199
199
  def source[A] { stream: () => Unit / emit[A] } { driver: () => Unit / next[A] }: Unit =
200
- returning::source[A, Unit]{stream}{driver}
200
+ returning::source{stream}{driver}
201
201
 
202
202
  /// Combines two streams together calling action on pairs in lockstep.
203
203
  /// Terminates when either of them terminates.
@@ -71,15 +71,37 @@ def repeat(str: String, n: Int): String = {
71
71
  go(n, "")
72
72
  }
73
73
 
74
+ /// Left-pad the given string with `fill` to length `n`
75
+ def padLeft(str: String, n: Int, fill: Char): String =
76
+ if (str.length >= n) str else fill.toString.repeat(n - str.length) ++ str
77
+
78
+ /// Right-pad the given string with `fill` to length `n`
79
+ def padRight(str: String, n: Int, fill: Char): String =
80
+ if (str.length >= n) str else str ++ fill.toString.repeat(n - str.length)
81
+
74
82
  /// Left-pad the given string with spaces
75
- def padLeft(str: String, n: Int): String = {
76
- " ".repeat(n - str.length) ++ str
77
- }
83
+ def padLeft(str: String, n: Int): String = str.padLeft(n, ' ')
78
84
 
79
85
  /// Right-pad the given string with spaces
80
- def padRight(str: String, n: Int): String = {
81
- str ++ " ".repeat(n - str.length)
82
- }
86
+ def padRight(str: String, n: Int): String = str.padRight(n, ' ')
87
+
88
+ /// Show the given `unscaled` number with 10^-`scale`.
89
+ ///
90
+ /// Examples:
91
+ /// ```
92
+ /// > -105.showScaled(2)
93
+ /// -1.05
94
+ /// > 7.showScaled(3)
95
+ /// 0.007
96
+ /// ```
97
+ def showScaled(unscaled: Int, scale: Int): String =
98
+ if (scale <= 0) (unscaled * pow(10, 0 - scale)).show
99
+ else {
100
+ val factor = pow(10, scale)
101
+ val magnitude = abs(unscaled)
102
+ val sign = if (unscaled < 0) "-" else ""
103
+ sign ++ (magnitude / factor).show ++ "." ++ magnitude.rem(factor).show.padLeft(scale, '0')
104
+ }
83
105
 
84
106
  // TODO use .split() in JS
85
107
  def split(str: String, sep: String): List[String] = {
@@ -205,6 +227,14 @@ def lastIndexOf(str: String, sub: String, from: Int): Option[Int] = {
205
227
  }
206
228
 
207
229
  namespace internal {
230
+ /// Compares the UTF-8 bytes of two strings, as `bytearray::compareByteArray` does,
231
+ /// but in a pure way since strings are immutable.
232
+ extern def compareBytes(left: String, right: String) at {}: Int =
233
+ llvm """
234
+ %x = call %Int @c_bytearray_compare(%Pos ${left}, %Pos ${right})
235
+ ret %Int %x
236
+ """
237
+
208
238
  def utf8ByteLength(str: String): Int = stream::sum {
209
239
  for {str.each} { (c: Char) =>
210
240
  do emit(c.utf8ByteCount)
@@ -260,7 +290,7 @@ extern def utf8ByteLength(str: String) at {io, global}: Int =
260
290
  /// Compares two strings lexicographically by code point.
261
291
  /// Identical on every backend.
262
292
  extern def compareStringBytes(left: String, right: String) at {}: Ordering =
263
- llvm { compareByteArray(fromString(left), fromString(right)) }
293
+ llvm { fromInt(internal::compareBytes(left, right)) }
264
294
  default { internal::compareCodePoints(left, right) }
265
295
 
266
296
  def charAt(str: String, index: Int): Char / Exception[OutOfBounds] =
@@ -273,7 +303,8 @@ extern def unsafeCharAt(str: String, n: Int) at {}: Char =
273
303
  js "${str}.codePointAt(${n})"
274
304
  chez "(char->integer (string-ref ${str} ${n}))"
275
305
  llvm """
276
- %x = call %Int @c_bytearray_character_at(%Pos ${str}, %Int ${n})
306
+ %c = call i32 @c_bytearray_character_at(%Pos ${str}, %Int ${n})
307
+ %x = zext i32 %c to %Int
277
308
  ret %Int %x
278
309
  """
279
310
 
@@ -282,7 +313,7 @@ extern def unsafeCharAt(str: String, n: Int) at {}: Char =
282
313
  // ---------
283
314
 
284
315
  def feed[R](string: String) { driver: () => R / next[Char] } =
285
- feed(string.fromString) { decodeUTF8 { driver() } }
316
+ feed(string.unsafeFromString) { decodeUTF8 { driver() } }
286
317
 
287
318
  def each(string: String): Unit / emit[Char] =
288
319
  feed(string) {
@@ -27,7 +27,7 @@ def flushableStringBuffer[A] { program: () => A / { write, flush } }: A = {
27
27
  try {
28
28
  program()
29
29
  } with write { string =>
30
- val bytes = fromString(string)
30
+ val bytes = unsafeFromString(string)
31
31
  val n = bytes.size
32
32
  ensureCapacity(n)
33
33
  // safe: `ensureCapacity` just established the target range
@@ -255,3 +255,6 @@ $effekt.run = RUN
255
255
  * If a runtime is available, use `$effekt.run`, instead.
256
256
  */
257
257
  $effekt.runToplevel = RUN_TOPLEVEL
258
+
259
+ /** Ends the currently running Effekt computation, without returning to it, used in `process::exit` */
260
+ $effekt.abort = ABORT
@@ -5,6 +5,19 @@
5
5
  #include <stdint.h>
6
6
  #include <inttypes.h>
7
7
 
8
+ // `usable_size` is the usable size of a heap block (at least what was requested),
9
+ // used in string concat in order to append into its spare room
10
+ #if defined(__APPLE__)
11
+ #include <malloc/malloc.h>
12
+ #define usable_size(p) malloc_size(p)
13
+ #elif defined(_WIN32)
14
+ #include <malloc.h>
15
+ #define usable_size(p) _msize(p)
16
+ #else
17
+ #include <malloc.h>
18
+ #define usable_size(p) malloc_usable_size(p)
19
+ #endif
20
+
8
21
  /** We represent bytearrays like positive types.
9
22
  *
10
23
  * - The field `tag` contains the size
@@ -20,6 +33,10 @@
20
33
 
21
34
  void c_bytearray_erase(void *object) { free(object); }
22
35
 
36
+ // The eraser of string literals, which are global objects that are never freed.
37
+ // Therefore, unlike `c_bytearray_erase`, they must not free their object.
38
+ void c_bytearray_erase_noop(void *object) { (void)object; }
39
+
23
40
  struct Pos c_bytearray_new(const Int size) {
24
41
  void *objPtr = malloc(sizeof(struct Header) + size);
25
42
  struct Header *headerPtr = objPtr;
@@ -73,6 +90,14 @@ struct Pos c_bytearray_construct(const uint64_t n, const uint8_t *data) {
73
90
  return arr;
74
91
  }
75
92
 
93
+ // The slow path of `uniqueByteArray` (in rts.ll): make a copy of `arr`, because we're sharing ours with someone else.
94
+ // Strings are immutable and but bytearrays are not, so when converting, we must not share.
95
+ struct Pos c_bytearray_copy_shared(const struct Pos arr) {
96
+ struct Pos copy = c_bytearray_construct(arr.tag, c_bytearray_data(arr));
97
+ erasePositive(arr);
98
+ return copy;
99
+ }
100
+
76
101
  // Complex Operations
77
102
 
78
103
  struct Pos c_bytearray_from_nullterminated_string(const char *data) {
@@ -144,6 +169,29 @@ struct Pos c_bytearray_show_Double(const Double x) {
144
169
  struct Pos c_bytearray_concatenate(const struct Pos left, const struct Pos right) {
145
170
  uint64_t left_size = left.tag;
146
171
  uint64_t right_size = right.tag;
172
+ // if we're the only ones holding a reference to the `left` and `|left| >= |right|`, append `right` in place
173
+ if (left.obj != NULL && ((struct Header*) left.obj)->rc == 0 && left_size >= right_size) {
174
+ size_t needed = sizeof(struct Header) + left_size + right_size;
175
+ void *objPtr = left.obj;
176
+ // double the size if we need to
177
+ if (usable_size(objPtr) < needed) {
178
+ size_t doubled = 2 * (sizeof(struct Header) + left_size);
179
+ objPtr = realloc(objPtr, doubled > needed ? doubled : needed);
180
+ }
181
+ memcpy((uint8_t*) objPtr + sizeof(struct Header) + left_size, c_bytearray_data(right), right_size);
182
+ erasePositive(right);
183
+ return (struct Pos) { .tag = left_size + right_size, .obj = objPtr };
184
+ }
185
+ // early exit for rhs or lhs being empty strings
186
+ if (right_size == 0) {
187
+ erasePositive(right);
188
+ return left;
189
+ }
190
+ if (left_size == 0) {
191
+ erasePositive(left);
192
+ return right;
193
+ }
194
+
147
195
  const struct Pos concatenated = c_bytearray_new(left_size + right_size);
148
196
  // two memcpys rather than a byte loop with a branch per byte
149
197
  memcpy(c_bytearray_data(concatenated), c_bytearray_data(left), left_size);
@@ -1,7 +1,7 @@
1
1
  ; forward-declared from primitives.c
2
2
 
3
3
  declare i64 @c_get_argc()
4
- declare %Pos @c_get_arg(i64)
4
+ declare %Pos @c_get_arg(i64 zeroext)
5
5
 
6
6
  declare void @c_io_print(%Pos)
7
7
  declare void @c_io_println(%Pos)
@@ -12,36 +12,29 @@ declare void @hole(i8*) cold noreturn
12
12
  declare void @duplicated_prompt() cold noreturn
13
13
  declare void @unmatched_tag() cold noreturn
14
14
 
15
- declare %Pos @c_ref_fresh(%Pos)
16
- declare %Pos @c_ref_get(%Pos)
17
- declare %Pos @c_ref_set(%Pos, %Pos)
18
-
19
- declare %Pos @c_array_new(%Int)
20
- declare %Int @c_array_size(%Pos)
21
- declare %Pos @c_array_get(%Pos, %Int)
22
- declare %Pos @c_array_set(%Pos, %Int, %Pos)
23
-
24
- declare %Pos @c_bytearray_new(%Int)
15
+ declare %Pos @c_bytearray_new(%Int signext)
25
16
  declare %Int @c_bytearray_size(%Pos)
26
- declare %Byte @c_bytearray_get(%Pos, %Int)
27
- declare %Pos @c_bytearray_set(%Pos, %Int, %Byte)
17
+ declare %Byte @c_bytearray_get(%Pos, %Int signext)
18
+ declare %Pos @c_bytearray_set(%Pos, %Int signext, %Byte zeroext)
28
19
 
29
- declare %Pos @c_bytearray_copy(%Pos, %Int, %Pos, %Int, %Int)
20
+ declare %Pos @c_bytearray_copy(%Pos, %Int signext, %Pos, %Int signext, %Int signext)
30
21
  declare ptr @c_bytearray_data(%Pos)
31
- declare %Pos @c_bytearray_construct(i64, ptr)
22
+ declare %Pos @c_bytearray_construct(i64 zeroext, ptr)
23
+ declare void @c_bytearray_erase_noop(ptr)
24
+ declare %Pos @c_bytearray_copy_shared(%Pos)
32
25
 
33
26
  declare %Pos @c_bytearray_from_nullterminated_string(ptr)
34
27
  declare ptr @c_bytearray_into_nullterminated_string(%Pos)
35
28
 
36
- declare %Pos @c_bytearray_show_Int(i64)
37
- declare %Pos @c_bytearray_show_Char(i32)
38
- declare %Pos @c_bytearray_show_Byte(i8)
29
+ declare %Pos @c_bytearray_show_Int(i64 signext)
30
+ declare %Pos @c_bytearray_show_Char(i64 zeroext)
31
+ declare %Pos @c_bytearray_show_Byte(i8 zeroext)
39
32
  declare %Pos @c_bytearray_show_Double(double)
40
33
 
41
34
  declare %Pos @c_bytearray_concatenate(%Pos, %Pos)
42
35
  declare %Pos @c_bytearray_equal(%Pos, %Pos)
43
36
  declare %Int @c_bytearray_compare(%Pos, %Pos)
44
37
 
45
- declare %Pos @c_bytearray_substring(%Pos, i64, i64)
46
- declare %Int @c_bytearray_character_at(%Pos, i64)
38
+ declare %Pos @c_bytearray_substring(%Pos, i64 zeroext, i64 zeroext)
39
+ declare i32 @c_bytearray_character_at(%Pos, i64 zeroext)
47
40