@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.
@@ -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.
@@ -205,6 +205,14 @@ def lastIndexOf(str: String, sub: String, from: Int): Option[Int] = {
205
205
  }
206
206
 
207
207
  namespace internal {
208
+ /// Compares the UTF-8 bytes of two strings, as `bytearray::compareByteArray` does,
209
+ /// but in a pure way since strings are immutable.
210
+ extern def compareBytes(left: String, right: String) at {}: Int =
211
+ llvm """
212
+ %x = call %Int @c_bytearray_compare(%Pos ${left}, %Pos ${right})
213
+ ret %Int %x
214
+ """
215
+
208
216
  def utf8ByteLength(str: String): Int = stream::sum {
209
217
  for {str.each} { (c: Char) =>
210
218
  do emit(c.utf8ByteCount)
@@ -260,7 +268,7 @@ extern def utf8ByteLength(str: String) at {io, global}: Int =
260
268
  /// Compares two strings lexicographically by code point.
261
269
  /// Identical on every backend.
262
270
  extern def compareStringBytes(left: String, right: String) at {}: Ordering =
263
- llvm { compareByteArray(fromString(left), fromString(right)) }
271
+ llvm { fromInt(internal::compareBytes(left, right)) }
264
272
  default { internal::compareCodePoints(left, right) }
265
273
 
266
274
  def charAt(str: String, index: Int): Char / Exception[OutOfBounds] =
@@ -282,7 +290,7 @@ extern def unsafeCharAt(str: String, n: Int) at {}: Char =
282
290
  // ---------
283
291
 
284
292
  def feed[R](string: String) { driver: () => R / next[Char] } =
285
- feed(string.fromString) { decodeUTF8 { driver() } }
293
+ feed(string.unsafeFromString) { decodeUTF8 { driver() } }
286
294
 
287
295
  def each(string: String): Unit / emit[Char] =
288
296
  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);
@@ -29,6 +29,8 @@ declare %Pos @c_bytearray_set(%Pos, %Int, %Byte)
29
29
  declare %Pos @c_bytearray_copy(%Pos, %Int, %Pos, %Int, %Int)
30
30
  declare ptr @c_bytearray_data(%Pos)
31
31
  declare %Pos @c_bytearray_construct(i64, ptr)
32
+ declare void @c_bytearray_erase_noop(ptr)
33
+ declare %Pos @c_bytearray_copy_shared(%Pos)
32
34
 
33
35
  declare %Pos @c_bytearray_from_nullterminated_string(ptr)
34
36
  declare ptr @c_bytearray_into_nullterminated_string(%Pos)