@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.
- package/bin/effekt +0 -0
- package/libraries/chez/common/effekt_primitives.ss +9 -0
- package/libraries/common/array.effekt +3 -1
- package/libraries/common/bench.effekt +0 -5
- package/libraries/common/bytearray.effekt +27 -10
- package/libraries/common/dictionary.effekt +2 -2
- package/libraries/common/effekt.effekt +49 -7
- package/libraries/common/exception.effekt +3 -3
- package/libraries/common/heap.effekt +100 -90
- package/libraries/common/io/console.effekt +3 -3
- package/libraries/common/io/error.effekt +9 -4
- package/libraries/common/io/filesystem.effekt +73 -44
- package/libraries/common/io/network.effekt +277 -96
- package/libraries/common/io/signal.effekt +5 -4
- package/libraries/common/io.effekt +44 -0
- package/libraries/common/process.effekt +118 -83
- package/libraries/common/ref.effekt +8 -5
- package/libraries/common/result.effekt +17 -1
- package/libraries/common/stream.effekt +2 -2
- package/libraries/common/string.effekt +10 -2
- package/libraries/common/stringbuffer.effekt +1 -1
- package/libraries/js/effekt_builtins.js +9 -0
- package/libraries/js/effekt_runtime.js +3 -0
- package/libraries/llvm/bytearray.c +51 -3
- package/libraries/llvm/forward-declare-c.ll +2 -0
- package/libraries/llvm/io.c +495 -182
- package/libraries/llvm/rts.ll +251 -79
- package/libraries/llvm/types.c +3 -2
- package/licenses/eclipse public license, version 2.0 - epl-2.0.html +5 -5
- package/licenses/mit license - mit-license.html +87 -49
- package/licenses/the bsd license - bsd-license.html +85 -47
- package/licenses/the mit license - mit.html +88 -50
- package/package.json +1 -1
|
@@ -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
|
-
|
|
15
|
+
jsNode "process$exit(${errorCode})"
|
|
6
16
|
llvm """
|
|
7
17
|
%exitCode = trunc i64 ${errorCode} to i32
|
|
8
18
|
call void @exit(i32 %exitCode)
|
|
@@ -13,86 +23,40 @@ extern def exit(errorCode: Int) at io: Nothing =
|
|
|
13
23
|
// Subprocesses
|
|
14
24
|
// ------------
|
|
15
25
|
|
|
16
|
-
|
|
17
|
-
const { spawn } = require('node:child_process');
|
|
18
|
-
"""
|
|
19
|
-
extern llvm """
|
|
20
|
-
declare %Pos @c_spawn_options_default()
|
|
21
|
-
declare %Pos @c_spawn_options_on_stdout(%Pos, %Pos)
|
|
22
|
-
declare %Pos @c_spawn_options_on_stderr(%Pos, %Pos)
|
|
23
|
-
declare %Pos @c_spawn_options_pipe_stdin(%Pos, %Pos)
|
|
24
|
-
declare %Pos @c_write_stream(%Pos, %Pos)
|
|
25
|
-
declare %Pos @c_close_stream(%Pos)
|
|
26
|
-
declare %Pos @c_spawn(%Pos, %Pos, %Pos)
|
|
27
|
-
"""
|
|
28
|
-
|
|
29
|
-
extern type SpawnOptions =
|
|
30
|
-
jsNode "{ stdio: list[int], onSpawn: fn => {} }"
|
|
31
|
-
llvm "%Pos"
|
|
32
|
-
extern def default() at {}: SpawnOptions =
|
|
33
|
-
jsNode """{ stdio: [0,1,2], onSpawn: (p) => {} }"""
|
|
34
|
-
llvm """
|
|
35
|
-
%opts = call %Pos @c_spawn_options_default()
|
|
36
|
-
ret %Pos %opts
|
|
37
|
-
"""
|
|
38
|
-
extern def onStdout(opts: SpawnOptions, callback: String => Unit at {io, global}) at {}: SpawnOptions =
|
|
39
|
-
jsNode """(function() {
|
|
40
|
-
let old = ${opts};
|
|
41
|
-
old.stdio[1] = 'pipe';
|
|
42
|
-
let oldSpawn = old.onSpawn;
|
|
43
|
-
old.onSpawn = function(p) {
|
|
44
|
-
oldSpawn(p);
|
|
45
|
-
p.stdout.on('data', (chunk) => {
|
|
46
|
-
$effekt.runToplevel((ks, k) => (${callback})(chunk, ks, k));
|
|
47
|
-
});
|
|
48
|
-
};
|
|
49
|
-
return old; })()"""
|
|
50
|
-
llvm """
|
|
51
|
-
%opts = call %Pos @c_spawn_options_on_stdout(%Pos ${opts}, %Neg ${callback})
|
|
52
|
-
ret %Pos %opts
|
|
53
|
-
"""
|
|
54
|
-
extern def onStderr(opts: SpawnOptions, callback: String => Unit at {io, global}) at {}: SpawnOptions =
|
|
55
|
-
jsNode """(function() {
|
|
56
|
-
let old = ${opts};
|
|
57
|
-
old.stdio[2] = 'pipe';
|
|
58
|
-
let oldSpawn = old.onSpawn;
|
|
59
|
-
old.onSpawn = function(p) {
|
|
60
|
-
oldSpawn(p);
|
|
61
|
-
p.stderr.on('data', (chunk) => {
|
|
62
|
-
$effekt.runToplevel((ks, k) => (${callback})(chunk, ks, k));
|
|
63
|
-
});
|
|
64
|
-
};
|
|
65
|
-
return old; })()"""
|
|
66
|
-
llvm """
|
|
67
|
-
%opts = call %Pos @c_spawn_options_on_stderr(%Pos ${opts}, %Neg ${callback})
|
|
68
|
-
ret %Pos %opts
|
|
69
|
-
"""
|
|
26
|
+
/// The standard input of a spawned process.
|
|
70
27
|
extern type WritableStream =
|
|
71
28
|
jsNode "stream.Writable"
|
|
72
29
|
llvm "%Pos"
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
30
|
+
|
|
31
|
+
/// How the standard streams of a spawned process are connected to it:
|
|
32
|
+
/// each one is either inherited from this process (`None`), or piped to a given callback.
|
|
33
|
+
record SpawnOptions(
|
|
34
|
+
stdin: Option[WritableStream => Unit at {io, global}],
|
|
35
|
+
stdout: Option[String => Unit at {io, global}],
|
|
36
|
+
stderr: Option[String => Unit at {io, global}]
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
def SpawnOptions::default(): SpawnOptions = SpawnOptions(None(), None(), None())
|
|
40
|
+
|
|
41
|
+
/// Pipes the process's standard output to `callback`, chunk by chunk.
|
|
42
|
+
def onStdout(opts: SpawnOptions, callback: String => Unit at {io, global}): SpawnOptions =
|
|
43
|
+
SpawnOptions(opts.stdin, Some(internal::chain(opts.stdout, callback)), opts.stderr)
|
|
44
|
+
|
|
45
|
+
/// Pipes the process's standard error to `callback`, chunk by chunk.
|
|
46
|
+
def onStderr(opts: SpawnOptions, callback: String => Unit at {io, global}): SpawnOptions =
|
|
47
|
+
SpawnOptions(opts.stdin, opts.stdout, Some(internal::chain(opts.stderr, callback)))
|
|
48
|
+
|
|
49
|
+
/// Pipes the process's standard input from `callback`, which runs once the process has started.
|
|
50
|
+
def withStdin(opts: SpawnOptions, callback: WritableStream => Unit at {io, global}): SpawnOptions =
|
|
51
|
+
SpawnOptions(Some(internal::chain(opts.stdin, callback)), opts.stdout, opts.stderr)
|
|
52
|
+
|
|
90
53
|
extern def write(to: WritableStream, s: String) at io: Unit =
|
|
91
54
|
jsNode """${to}.write(${s})"""
|
|
92
55
|
llvm """
|
|
93
56
|
call void @c_write_stream(%Pos ${to}, %Pos ${s})
|
|
94
57
|
ret %Pos zeroinitializer
|
|
95
58
|
"""
|
|
59
|
+
|
|
96
60
|
extern def close(to: WritableStream) at io: Unit =
|
|
97
61
|
jsNode """${to}.end()"""
|
|
98
62
|
llvm """
|
|
@@ -100,14 +64,85 @@ extern def close(to: WritableStream) at io: Unit =
|
|
|
100
64
|
ret %Pos zeroinitializer
|
|
101
65
|
"""
|
|
102
66
|
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
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
|
+
)
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
namespace internal {
|
|
96
|
+
def chain[A](first: Option[A => Unit at {io, global}], then: A => Unit at {io, global}): A => Unit at {io, global} =
|
|
97
|
+
first match {
|
|
98
|
+
case None() => then
|
|
99
|
+
case Some(f) => box { a => f(a); then(a) }
|
|
100
|
+
}
|
|
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
|
+
|
|
106
|
+
/// 1 if a stream is piped to a callback, 0 if it is inherited.
|
|
107
|
+
def piped[A](callback: Option[A]): Int = callback match {
|
|
108
|
+
case Some(_) => 1
|
|
109
|
+
case None() => 0
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
extern jsNode """
|
|
113
|
+
const { spawn: process$nodeSpawn } = require('node:child_process');
|
|
114
|
+
const process$signals = require('node:os').constants.signals;
|
|
115
|
+
|
|
116
|
+
function process$spawn(cmd, args, pipeStdin, stdin, pipeStdout, stdout, pipeStderr, stderr, callback) {
|
|
117
|
+
const stdio = [pipeStdin ? 'pipe' : 'inherit', pipeStdout ? 'pipe' : 'inherit', pipeStderr ? 'pipe' : 'inherit'];
|
|
118
|
+
const p = process$nodeSpawn(cmd, args, { stdio });
|
|
119
|
+
// Note: Decoded as UTF-8 by the stream itself, so that a character split between two chunks stays whole.
|
|
120
|
+
if (pipeStdout) { p.stdout.setEncoding('utf8'); p.stdout.on('data', chunk => $effekt.runToplevel((ks, k) => stdout(chunk, ks, k))); }
|
|
121
|
+
if (pipeStderr) { p.stderr.setEncoding('utf8'); p.stderr.on('data', chunk => $effekt.runToplevel((ks, k) => stderr(chunk, ks, k))); }
|
|
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
|
+
});
|
|
130
|
+
}
|
|
131
|
+
"""
|
|
132
|
+
|
|
133
|
+
extern llvm """
|
|
134
|
+
declare void @c_spawn(%Pos, %Pos, %Neg, %Neg, %Neg, %Int, %Int, %Int, %Stack)
|
|
135
|
+
declare void @c_write_stream(%Pos, %Pos)
|
|
136
|
+
declare void @c_close_stream(%Pos)
|
|
137
|
+
"""
|
|
138
|
+
|
|
139
|
+
extern def spawn(cmd: String, args: Array[String],
|
|
140
|
+
pipeStdin: Int, stdin: WritableStream => Unit at {io, global},
|
|
141
|
+
pipeStdout: Int, stdout: String => Unit at {io, global},
|
|
142
|
+
pipeStderr: Int, stderr: String => Unit at {io, global}) at async: Int =
|
|
143
|
+
jsNode "$effekt.capture(k => process$spawn(${cmd}, ${args}, ${pipeStdin}, ${stdin}, ${pipeStdout}, ${stdout}, ${pipeStderr}, ${stderr}, k))"
|
|
144
|
+
llvm """
|
|
145
|
+
notail call void @c_spawn(%Pos ${cmd}, %Pos ${args}, %Neg ${stdin}, %Neg ${stdout}, %Neg ${stderr}, %Int ${pipeStdin}, %Int ${pipeStdout}, %Int ${pipeStderr}, %Stack %stack)
|
|
146
|
+
ret void
|
|
147
|
+
"""
|
|
148
|
+
}
|
|
@@ -3,16 +3,19 @@ module ref
|
|
|
3
3
|
import effekt
|
|
4
4
|
|
|
5
5
|
extern js """
|
|
6
|
-
function set
|
|
6
|
+
function ref$set(ref, value) {
|
|
7
7
|
ref.value = value;
|
|
8
8
|
return $effekt.unit;
|
|
9
9
|
}
|
|
10
10
|
"""
|
|
11
11
|
|
|
12
12
|
extern llvm """
|
|
13
|
-
define void @c_ref_erase_field(ptr %
|
|
14
|
-
%
|
|
15
|
-
|
|
13
|
+
define void @c_ref_erase_field(ptr %object) {
|
|
14
|
+
%fieldPointer = getelementptr %Header, ptr %object, i64 1
|
|
15
|
+
%field = load %Pos, ptr %fieldPointer, align 8
|
|
16
|
+
call void @free(ptr %object)
|
|
17
|
+
%fieldObject = extractvalue %Pos %field, 1
|
|
18
|
+
musttail call void @eraseObject(%Object %fieldObject)
|
|
16
19
|
ret void
|
|
17
20
|
}
|
|
18
21
|
"""
|
|
@@ -90,7 +93,7 @@ llvm """
|
|
|
90
93
|
|
|
91
94
|
/// Sets the referenced element of the `ref` to `value` in constant time.
|
|
92
95
|
extern def set[T](ref: Ref[T], value: T) at global: Unit =
|
|
93
|
-
js "set
|
|
96
|
+
js "ref$set(${ref}, ${value})"
|
|
94
97
|
chez "(set-box! ${ref} ${value})"
|
|
95
98
|
llvm """
|
|
96
99
|
%refField_pointer = extractvalue %Pos ${ref}, 1
|
|
@@ -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
|
|
197
|
+
countIf { _ => true } {stream}
|
|
198
198
|
|
|
199
199
|
def source[A] { stream: () => Unit / emit[A] } { driver: () => Unit / next[A] }: Unit =
|
|
200
|
-
returning::source
|
|
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 {
|
|
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.
|
|
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 =
|
|
30
|
+
val bytes = unsafeFromString(string)
|
|
31
31
|
val n = bytes.size
|
|
32
32
|
ensureCapacity(n)
|
|
33
33
|
// safe: `ensureCapacity` just established the target range
|
|
@@ -18,6 +18,15 @@ $effekt.equals = function(obj1, obj2) {
|
|
|
18
18
|
}
|
|
19
19
|
}
|
|
20
20
|
|
|
21
|
+
$effekt.mod = function(x, y) {
|
|
22
|
+
const r = x % y
|
|
23
|
+
return r < 0 ? r + Math.abs(y) : r
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
$effekt.div = function(x, y) {
|
|
27
|
+
return (x - $effekt.mod(x, y)) / y
|
|
28
|
+
}
|
|
29
|
+
|
|
21
30
|
function compare$prim(n1, n2) {
|
|
22
31
|
if (n1 == n2) { return 0; }
|
|
23
32
|
else if (n1 > n2) { return 1; }
|
|
@@ -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
|
|
@@ -14,16 +27,20 @@
|
|
|
14
27
|
* | Rc | Eraser | Contents ... |
|
|
15
28
|
* +--------------+--------------+
|
|
16
29
|
*
|
|
17
|
-
* The eraser
|
|
30
|
+
* The eraser only frees the object.
|
|
18
31
|
*/
|
|
19
32
|
|
|
20
33
|
|
|
21
|
-
void
|
|
34
|
+
void c_bytearray_erase(void *object) { free(object); }
|
|
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; }
|
|
22
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;
|
|
26
|
-
*headerPtr = (struct Header) { .rc = 0, .eraser =
|
|
43
|
+
*headerPtr = (struct Header) { .rc = 0, .eraser = c_bytearray_erase, };
|
|
27
44
|
return (struct Pos) {
|
|
28
45
|
.tag = size,
|
|
29
46
|
.obj = 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)
|