fantom-polycall 0.0.0-stage → 1.0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 OBINexus Computing / Nnamdi Michael Okpala
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,194 @@
1
- # Temporary Holding Version
1
+ # fantom-polycall
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Fantom binding for the [Polycall](https://github.com/obinexus/polycall) core,
4
+ binding ABI v1 (polycall >= 1.1.0). It is a Fantom pod, `polycall`, that
5
+ calls the real core through Fantom's Java FFI and the Java Foreign Function
6
+ & Memory API (`java.lang.foreign`).
7
+
8
+ ## Quick start
9
+
10
+ **1. Install the package** (the source of a Fantom pod, delivered through npm):
11
+
12
+ ```sh
13
+ npm i fantom-polycall
14
+ ```
15
+
16
+ **2. Have the Polycall core, Fantom 1.0.84 and a JDK >= 22.** Build the core
17
+ from <https://github.com/obinexus/polycall> and note where its shared
18
+ library is:
19
+
20
+ | | shared library (`POLYCALL_LIBRARY`) |
21
+ | --- | --- |
22
+ | Windows | `polycall\build\windows-cmake\bin\polycall.dll` |
23
+ | Linux | `<prefix>/lib/libpolycall.so.1` |
24
+
25
+ ```powershell
26
+ # Windows (PowerShell), in a polycall checkout
27
+ .\build-windows.ps1
28
+ ```
29
+
30
+ ```sh
31
+ # Linux, in a polycall checkout
32
+ cmake -S . -B build -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_LIBDIR=lib
33
+ cmake --build build --parallel && cmake --install build --prefix "$HOME/polycall"
34
+ ```
35
+
36
+ Fantom is the zip from <https://github.com/fantom-lang/fantom/releases>
37
+ (unpack it anywhere; `FAN_HOME` below is that directory). The Fantom
38
+ launcher runs `%JAVA_HOME%\bin\java` / `$JAVA_HOME/bin/java`, which must be
39
+ a JDK 22 or newer (tested with Temurin 25).
40
+
41
+ **3. Build the pod and run the packaged example** from your project
42
+ directory (the one that now contains `node_modules`). The pod is built into
43
+ the project itself through a `util::PathEnv`, so nothing is written into the
44
+ Fantom installation:
45
+
46
+ ```powershell
47
+ # Windows (PowerShell)
48
+ $env:JAVA_HOME = "C:\path\to\jdk-25"
49
+ $env:FAN_HOME = "C:\path\to\fantom-1.0.84"
50
+ $env:FAN_ENV = "util::PathEnv"; $env:FAN_ENV_PATH = (Get-Location).Path
51
+ $env:JDK_JAVA_OPTIONS = "--enable-native-access=ALL-UNNAMED"
52
+ $env:POLYCALL_LIBRARY = "C:\path\to\polycall\build\windows-cmake\bin\polycall.dll"
53
+ & "$env:FAN_HOME\bin\fan.bat" node_modules\fantom-polycall\build.fan
54
+ Copy-Item node_modules\fantom-polycall\examples\consumer\consumer.fan .
55
+ & "$env:FAN_HOME\bin\fan.bat" consumer.fan node_modules\fantom-polycall\test\fixtures\good.polycallrc node_modules\fantom-polycall\test\fixtures\bad.polycallrc
56
+ ```
57
+
58
+ ```sh
59
+ # Linux
60
+ export JAVA_HOME=/path/to/jdk-25 FAN_HOME=/path/to/fantom-1.0.84
61
+ export FAN_ENV=util::PathEnv FAN_ENV_PATH="$PWD"
62
+ export JDK_JAVA_OPTIONS=--enable-native-access=ALL-UNNAMED
63
+ export POLYCALL_LIBRARY="$HOME/polycall/lib/libpolycall.so.1"
64
+ chmod +x "$FAN_HOME"/bin/*
65
+ "$FAN_HOME/bin/fan" node_modules/fantom-polycall/build.fan
66
+ cp node_modules/fantom-polycall/examples/consumer/consumer.fan .
67
+ "$FAN_HOME/bin/fan" consumer.fan node_modules/fantom-polycall/test/fixtures/good.polycallrc node_modules/fantom-polycall/test/fixtures/bad.polycallrc
68
+ ```
69
+
70
+ The two arguments are a configuration file the core accepts and one it
71
+ refuses; the package ships one of each. A third argument, the `host:port`
72
+ of a running `polycall start`, adds one RPC round trip. Expected output
73
+ (paths shortened):
74
+
75
+ ```
76
+ core 1.1.0, binding ABI 1
77
+ OK good.polycallrc
78
+ REFUSED config
79
+ POLYCALL_E_CONFIG: invalid configuration: bad.polycallrc:1: malformed key=value entry
80
+ peer listening on 127.0.0.1:53124
81
+ all checks passed
82
+ ```
83
+
84
+ Without a core the example exits 1 with:
85
+
86
+ ```
87
+ fantom-polycall: the Polycall core library could not be loaded.
88
+ Set the environment variable POLYCALL_LIBRARY to the core's shared library: the full path of polycall.dll (Windows) / libpolycall.so.1 (Linux), or the directory that contains it. Alternatively put that directory on PATH (Windows) or LD_LIBRARY_PATH (Linux).
89
+ ...
90
+ ```
91
+
92
+ ## Using it in your own Fantom project
93
+
94
+ Build the pod once into your environment as in step 3 (or into any
95
+ `PathEnv` work directory), then depend on it in your `build.fan`:
96
+
97
+ ```fantom
98
+ depends = ["sys 1.0", "polycall 1.0"]
99
+ ```
100
+
101
+ or use it from a script with `using polycall`. The core is not needed to
102
+ build: it is loaded on first use, from `POLYCALL_LIBRARY` (a file, or a
103
+ directory holding `polycall.dll` / `libpolycall.so.1`), else through the
104
+ system loader (`PATH` on Windows, `LD_LIBRARY_PATH` / the ld.so cache on
105
+ Linux). Pass `--enable-native-access=ALL-UNNAMED` to the JVM
106
+ (`JDK_JAVA_OPTIONS`, or `java.options` in `etc/sys/config.props` of your
107
+ Fantom installation); without it JDK 22+ prints a restricted-method warning
108
+ and newer JDKs may refuse.
109
+
110
+ ```fantom
111
+ using polycall
112
+
113
+ Polycall.checkAbi // Status.unsupported unless ABI v1
114
+ Polycall.runConfig("Polycallfile", ConfigMode.run)
115
+
116
+ json := Polycall.call("127.0.0.1:8084", "inventory", "get", Str<|{"item_id":"widget-a"}|>, 5000)
117
+
118
+ node := Peer.open("alpha", "127.0.0.1:0")
119
+ try node.send("beta", "hello".toBuf)
120
+ finally node.close
121
+
122
+ try Polycall.runConfig("bad.polycallrc")
123
+ catch (PolycallErr e) echo("$e.status $e.code $e.detail")
124
+ ```
125
+
126
+ ## What it covers
127
+
128
+ Interop route: **direct C FFI** through Fantom's Java FFI
129
+ (`using [java] java.lang.foreign`). [`fan/Native.fan`](fan/Native.fan)
130
+ loads the library with `SymbolLookup.libraryLookup` and builds one
131
+ `Linker.nativeLinker().downcallHandle` per C function of `polycall.h`
132
+ (cdecl; `int`/`uint32_t` as `JAVA_INT`, `size_t` as `JAVA_LONG`, pointers as
133
+ `ADDRESS`), so neither the headers nor JNI/JNA nor any Java source are
134
+ needed. Fantom's Java FFI compiles calls to *static interface methods*
135
+ (`Arena.ofConfined`, `Linker.nativeLinker`, `FunctionDescriptor.of`,
136
+ `SymbolLookup.libraryLookup`) against a non-existent `Iface$` class, so
137
+ those four entry points are reached through `MethodHandles.lookup().findStatic`
138
+ and the layout constants through reflection; all other calls are plain FFI.
139
+ Nothing is reimplemented in Fantom and no CLI is spawned.
140
+
141
+ | area | Fantom API | C function |
142
+ | --- | --- | --- |
143
+ | library | `Polycall.libraryAbiVersion`, `checkAbi`, `version`, `strerror`, `lastError` | `polycall_ffi_abi_version`, `polycall_ffi_version`, `polycall_strerror`, `polycall_last_error` |
144
+ | configuration | `Polycall.runConfig(path, ConfigMode.validate / run)`, `describe` | `polycall_ffi_run_config`, `polycall_ffi_describe` |
145
+ | RPC | `Polycall.call`, `callRaw` (returns a `Reply`) | `polycall_call` |
146
+ | peer node | `Peer.open`, `close`, `endpoint`, `nodeId`, `register`, `unregister`, `list`, `ping`, `send`, `recv` (returns a `PeerMessage`), `cancel`, `health` | `polycall_peer_*` |
147
+
148
+ * **Errors**: a negative status is thrown as `PolycallErr`; `e.status` is
149
+ the `Status` enum member (`Status.config`, `Status.notFound`,
150
+ `Status.timeout` ...; `Status.internalErr` for `POLYCALL_E_INTERNAL`,
151
+ `Status.unknown` for a code newer than this package), `e.code` the raw
152
+ value, `e.detail` the calling thread's `polycall_last_error` text read
153
+ right after the failing call, and `e.msg` is
154
+ `"<polycall_strerror text>: <detail>"`. `Status.cName` gives the C macro
155
+ name. A core that cannot be located is `PolycallLoadErr` and says what to
156
+ set.
157
+ * **Ownership**: the library never returns memory to free. Every output is
158
+ written into a buffer this binding allocates in a confined `Arena` for one
159
+ call and copies into an immutable `Str` / `Buf` before returning. Output
160
+ sizes are parameters with defaults (`describe(path, capacity)`,
161
+ `recv(timeoutMs, capacity)`); a too-small capacity is `Status.tooLarge`
162
+ with `PolycallErr.needed`, and for `recv` the message stays queued.
163
+ * **Peers**: `Peer` is a `const` class holding one library handle until
164
+ `close()`; a second `close()` or any use afterwards is
165
+ `Status.invalidHandle`, never a crash. Payloads are `Buf`s and binary
166
+ safe (NUL bytes included).
167
+ * `call` and `Peer.recv` block the calling thread for up to `timeoutMs`
168
+ (`Polycall.waitForever` for `recv`); `cancel` from another thread wakes it.
169
+
170
+ ## Tests
171
+
172
+ Every test runs against the real core; nothing is mocked.
173
+
174
+ ```sh
175
+ # POLYCALL_LIB_DIR, POLYCALL_CLI (and POLYCALL_BIN_DIR on Windows) point at a built core;
176
+ # FAN_HOME at fantom-1.0.84 and JAVA_HOME at a JDK >= 22
177
+ npm test # build the pod, fant polycall: 11 integration tests, then the missing-core diagnostic
178
+ npm run test:consumer # npm pack -> install into a clean project -> build the pod there -> packaged example
179
+ ```
180
+
181
+ `npm run test:consumer` installs the packed tarball into a temporary project
182
+ outside the checkout, builds the pod from `node_modules/fantom-polycall`
183
+ there and runs the example: a known-good file, a known-bad file, the peer
184
+ lifecycle, one RPC round trip against `polycall start`, a malformed file
185
+ passed as known-good (must fail), and the missing-core diagnostic with every
186
+ `POLYCALL_*` variable unset and the core off `PATH`.
187
+
188
+ Tested: Windows 11 x64, Fantom 1.0.84, Temurin JDK 25.0.5.1, core
189
+ `66c744d` (1.1.0, MSVC build). Linux runs in CI
190
+ ([`.github/workflows/ci.yml`](.github/workflows/ci.yml)).
191
+
192
+ ## License
193
+
194
+ MIT -- see [LICENSE](LICENSE).
package/build.fan ADDED
@@ -0,0 +1,33 @@
1
+ #! /usr/bin/env fan
2
+ //
3
+ // Builds the pod `polycall` (Fantom binding for the Polycall core).
4
+ //
5
+ // fan build.fan writes polycall.pod into Env.cur.workDir/lib/fan/
6
+ //
7
+ // Use a PathEnv so nothing is written into the Fantom installation:
8
+ // FAN_ENV=util::PathEnv FAN_ENV_PATH=<your project directory>
9
+ //
10
+ // The core itself is not needed to build: it is loaded at run time
11
+ // (POLYCALL_LIBRARY, else the system loader).
12
+ //
13
+
14
+ using build
15
+
16
+ class Build : BuildPod
17
+ {
18
+ new make()
19
+ {
20
+ podName = "polycall"
21
+ summary = "Fantom binding for the Polycall core (binding ABI v1, polycall >= 1.1.0)"
22
+ version = Version("1.0.0")
23
+ meta = [
24
+ "org.name": "OBINexusComputing",
25
+ "license.name": "MIT",
26
+ "vcs.uri": "https://github.com/obinexus/fantom-polycall",
27
+ "polycall.abi": "1",
28
+ ]
29
+ depends = ["sys 1.0", "concurrent 1.0"]
30
+ srcDirs = [`fan/`, `test/`]
31
+ docSrc = true
32
+ }
33
+ }
@@ -0,0 +1,77 @@
1
+ #! /usr/bin/env fan
2
+ //
3
+ // Minimal fantom-polycall consumer (a Fantom script using the pod
4
+ // `polycall` that `fan node_modules/fantom-polycall/build.fan` built):
5
+ //
6
+ // fan consumer.fan <known-good config> <known-bad config> [host:port of `polycall start`]
7
+ //
8
+ // Exits 0 only when every result is the expected one.
9
+ //
10
+
11
+ using polycall
12
+
13
+ class Main
14
+ {
15
+ static Int main(Str[] args)
16
+ {
17
+ if (args.size < 2)
18
+ {
19
+ Env.cur.err.printLine("usage: fan consumer.fan <good config> <bad config> [host:port]")
20
+ return 2
21
+ }
22
+ try
23
+ {
24
+ return run(args)
25
+ }
26
+ catch (PolycallLoadErr e)
27
+ {
28
+ Env.cur.err.printLine(e.msg)
29
+ return 1
30
+ }
31
+ catch (PolycallErr e)
32
+ {
33
+ Env.cur.err.printLine("FAIL $e.msg")
34
+ return 1
35
+ }
36
+ }
37
+
38
+ static Int run(Str[] args)
39
+ {
40
+ Polycall.checkAbi
41
+ echo("core $Polycall.version, binding ABI $Polycall.libraryAbiVersion")
42
+
43
+ // known-good: accepted for running with this build
44
+ Polycall.runConfig(args[0], ConfigMode.run)
45
+ echo("OK ${args[0]}")
46
+
47
+ // known-bad: refused, with the library's status and this thread's detail
48
+ try
49
+ {
50
+ Polycall.runConfig(args[1], ConfigMode.run)
51
+ echo("FAIL: ${args[1]} was accepted")
52
+ return 1
53
+ }
54
+ catch (PolycallErr e)
55
+ {
56
+ echo("REFUSED $e.status\n $e.msg")
57
+ if (e.status != Status.config && e.status != Status.unsupported) return 1
58
+ }
59
+
60
+ // a peer node: open, read its endpoint, close; a second close is refused
61
+ node := Peer.open("consumer", "127.0.0.1:0")
62
+ echo("peer listening on $node.endpoint")
63
+ node.close
64
+ try { node.close; return 1 }
65
+ catch (PolycallErr e) { if (e.status != Status.invalidHandle) return 1 }
66
+
67
+ // optional: one RPC round trip against a running `polycall start`
68
+ if (args.size > 2)
69
+ {
70
+ reply := Polycall.call(args[2], "debug", "echo", Str<|{"fantom":true}|>, 5000)
71
+ echo("call debug.echo -> $reply")
72
+ if (reply != Str<|{"echo":{"fantom":true}}|>) return 1
73
+ }
74
+ echo("all checks passed")
75
+ return 0
76
+ }
77
+ }
package/fan/Native.fan ADDED
@@ -0,0 +1,270 @@
1
+ //
2
+ // Raw access to the Polycall binding ABI v1 (polycall.h, core >= 1.1.0)
3
+ // through Fantom's Java FFI and the Java 22+ Foreign Function & Memory API
4
+ // (java.lang.foreign). No JNI, no JNA, no Java source: one downcall handle
5
+ // per C function, resolved from the real libpolycall at run time.
6
+ //
7
+ // Fantom's Java FFI compiles calls to *static* methods of Java interfaces
8
+ // (Arena.ofConfined, Linker.nativeLinker, SymbolLookup.libraryLookup,
9
+ // FunctionDescriptor.of) against a non-existent `Iface$` class, so those few
10
+ // entry points are reached through MethodHandles.lookup().findStatic and
11
+ // static interface fields (ValueLayout.JAVA_INT, MemorySegment.NULL) through
12
+ // reflection. Everything else is ordinary FFI calls.
13
+ //
14
+
15
+ using [java] java.lang.foreign
16
+ using [java] java.lang.foreign::Linker$Option as LinkerOption
17
+ using [java] java.lang.foreign::ValueLayout$OfLong as OfLong
18
+ using [java] java.lang.foreign::ValueLayout$OfInt as OfInt
19
+ using [java] java.lang.invoke
20
+ using [java] java.lang::Class as JClass
21
+ using [java] java.lang::Integer as JInt
22
+ using [java] java.io::File as JFile
23
+ using [java] java.nio::ByteBuffer
24
+ using [java] fanx.interop::Interop
25
+ using concurrent
26
+
27
+ **
28
+ ** The loaded core: one downcall handle per C function of polycall.h.
29
+ ** Loaded once per VM, on first use. Immutable after construction and
30
+ ** therefore safe to share between threads (MethodHandles are thread-safe;
31
+ ** every call allocates its own confined Arena).
32
+ **
33
+ internal class Native
34
+ {
35
+ ** The text a missing core produces; the tests look for it.
36
+ static const Str missingCore :=
37
+ "fantom-polycall: the Polycall core library could not be loaded.\n" +
38
+ "Set the environment variable POLYCALL_LIBRARY to the core's shared library: the full path of " +
39
+ "polycall.dll (Windows) / libpolycall.so.1 (Linux), or the directory that contains it. " +
40
+ "Alternatively put that directory on PATH (Windows) or LD_LIBRARY_PATH (Linux).\n" +
41
+ "Build the core from https://github.com/obinexus/polycall (>= 1.1.0, binding ABI v1)."
42
+
43
+ private static const AtomicRef cached := AtomicRef(null)
44
+
45
+ ** The process-wide instance; throws PolycallLoadErr when the core cannot be found.
46
+ static Native get()
47
+ {
48
+ u := cached.val as Unsafe
49
+ if (u != null) return u.val
50
+ cached.compareAndSet(null, Unsafe(make))
51
+ return ((Unsafe)cached.val).val
52
+ }
53
+
54
+ private static const Str ffi := "java.lang.foreign."
55
+
56
+ private new make()
57
+ {
58
+ ofConfined = findStatic("Arena", "ofConfined", "Arena", Str[,])
59
+ Arena global := findStatic("Arena", "global", "Arena", Str[,]).invokeWithArguments(Obj?[,])
60
+ Linker linker := findStatic("Linker", "nativeLinker", "Linker", Str[,]).invokeWithArguments(Obj?[,])
61
+ lib := load(global)
62
+ fdOf := findStatic("FunctionDescriptor", "of", "FunctionDescriptor", ["MemoryLayout", "[MemoryLayout"])
63
+
64
+ intLayout = staticField("ValueLayout", "JAVA_INT")
65
+ Obj i := intLayout
66
+ Obj a := staticField("ValueLayout", "ADDRESS")
67
+ longLayout = staticField("ValueLayout", "JAVA_LONG")
68
+ Obj z := longLayout
69
+ nullPtr = staticField("MemorySegment", "NULL")
70
+
71
+ |Str, Obj[]->MethodHandle| h := |Str name, Obj[] sig->MethodHandle|
72
+ {
73
+ found := lib.find(name)
74
+ if (!found.isPresent)
75
+ throw PolycallLoadErr("fantom-polycall: the loaded library does not export $name; " +
76
+ "it is not a Polycall core with binding ABI v1 (polycall >= 1.1.0).\n$missingCore")
77
+ FunctionDescriptor fd := fdOf.invokeWithArguments(sig)
78
+ return linker.downcallHandle((MemorySegment)found.get, fd, LinkerOption[,])
79
+ }
80
+
81
+ // library
82
+ abiVersion = h("polycall_ffi_abi_version", [i])
83
+ version = h("polycall_ffi_version", [i, a, i])
84
+ strerror = h("polycall_strerror", [a, i])
85
+ lastError = h("polycall_last_error", [i, a, z])
86
+ // configuration
87
+ runConfig = h("polycall_ffi_run_config", [i, a, i])
88
+ describe = h("polycall_ffi_describe", [i, a, a, i])
89
+ // RPC
90
+ call = h("polycall_call", [i, a, a, a, a, i, a, z, a])
91
+ // peer node
92
+ peerOpen = h("polycall_peer_open", [i, a, a, a, a])
93
+ peerClose = h("polycall_peer_close", [i, i])
94
+ peerEndpoint = h("polycall_peer_endpoint", [i, i, a, z])
95
+ peerNodeId = h("polycall_peer_node_id", [i, i, a, z])
96
+ peerRegister = h("polycall_peer_register", [i, i, a, a])
97
+ peerUnregister = h("polycall_peer_unregister", [i, i, a])
98
+ peerList = h("polycall_peer_list", [i, i, a, z, a])
99
+ peerPing = h("polycall_peer_ping", [i, i, a, i])
100
+ peerSend = h("polycall_peer_send", [i, i, a, a, z, a, i])
101
+ peerRecv = h("polycall_peer_recv", [i, i, i, a, z, a, z, a, z, a])
102
+ peerCancel = h("polycall_peer_cancel", [i, i])
103
+ peerHealth = h("polycall_peer_health", [i, i, a, z, a])
104
+ }
105
+
106
+ //////////////////////////////////////////////////////////////////////////
107
+ // Loading
108
+ //////////////////////////////////////////////////////////////////////////
109
+
110
+ ** POLYCALL_LIBRARY (a file, or a directory holding the platform's file
111
+ ** name), else the system loader (PATH / LD_LIBRARY_PATH / ld.so cache).
112
+ private static SymbolLookup load(Arena global)
113
+ {
114
+ byPath := findStatic("SymbolLookup", "libraryLookup", "SymbolLookup", ["java.nio.file.Path", "Arena"])
115
+ byName := findStatic("SymbolLookup", "libraryLookup", "SymbolLookup", ["java.lang.String", "Arena"])
116
+
117
+ os := Env.cur.os
118
+ names := ["libpolycall.so.1", "libpolycall.so"]
119
+ if (os == "win32") names = ["polycall.dll"]
120
+ if (os == "macosx") names = ["libpolycall.1.dylib", "libpolycall.dylib"]
121
+
122
+ tried := Str[,]
123
+ setting := (Env.cur.vars["POLYCALL_LIBRARY"] ?: "").trim
124
+ if (!setting.isEmpty)
125
+ {
126
+ base := JFile(setting)
127
+ files := base.isDirectory ? names.map |n->JFile| { JFile(base, n) } : [base]
128
+ for (k := 0; k < files.size; ++k)
129
+ {
130
+ JFile f := files[k]
131
+ try
132
+ return byPath.invokeWithArguments(Obj?[f.toPath, global])
133
+ catch (Err e)
134
+ tried.add("POLYCALL_LIBRARY -> ${f.getPath}: ${e.msg}")
135
+ }
136
+ }
137
+ else
138
+ {
139
+ for (k := 0; k < names.size; ++k)
140
+ {
141
+ try
142
+ return byName.invokeWithArguments(Obj?[names[k], global])
143
+ catch (Err e)
144
+ tried.add("system loader -> ${names[k]}: ${e.msg}")
145
+ }
146
+ }
147
+ throw PolycallLoadErr(missingCore + "\nTried:\n " + tried.join("\n "))
148
+ }
149
+
150
+ private static JClass cls(Str name)
151
+ {
152
+ if (name.startsWith("[")) return JClass.forName("[L" + qualify(name[1..-1]) + ";")
153
+ return JClass.forName(qualify(name))
154
+ }
155
+
156
+ private static Str qualify(Str name) { name.contains(".") ? name : ffi + name }
157
+
158
+ private static MethodHandle findStatic(Str owner, Str name, Str ret, Str[] params)
159
+ {
160
+ JClass[] types := params.map |p->JClass| { cls(p) }
161
+ return MethodHandles.lookup.findStatic(cls(owner), name, MethodType.methodType(cls(ret), types))
162
+ }
163
+
164
+ private static Obj staticField(Str owner, Str name) { cls(owner).getField(name).get(null) }
165
+
166
+ //////////////////////////////////////////////////////////////////////////
167
+ // Call helpers
168
+ //////////////////////////////////////////////////////////////////////////
169
+
170
+ ** Run `f` with a fresh confined arena that is closed afterwards.
171
+ Obj? scoped(|Arena->Obj?| f)
172
+ {
173
+ Arena arena := ofConfined.invokeWithArguments(Obj?[,])
174
+ try return f(arena)
175
+ finally arena.close
176
+ }
177
+
178
+ ** A C int / uint32_t argument (uint32 values above Int32 wrap, as in C).
179
+ static Obj cint(Int v) { JInt.valueOf(v) }
180
+
181
+ ** Invoke a handle whose C return type is int.
182
+ static Int invokeInt(MethodHandle mh, Obj?[] args) { ((JInt)mh.invokeWithArguments(args)).intValue }
183
+
184
+ ** A NUL-terminated UTF-8 copy of `s`, or NULL.
185
+ MemorySegment cstr(Arena arena, Str? s) { s == null ? nullPtr : arena.allocateFrom(s) }
186
+
187
+ ** A zeroed caller-owned buffer of `size` bytes (at least 1).
188
+ MemorySegment buffer(Arena arena, Int size) { arena.allocate(size.max(1)) }
189
+
190
+ ** A size_t out-parameter.
191
+ MemorySegment sizeOut(Arena arena) { arena.allocate(8) }
192
+
193
+ ** The size_t stored at `seg`.
194
+ Int readSize(MemorySegment seg) { seg.get((OfLong)longLayout, 0) }
195
+
196
+ ** The int32_t stored at `seg`.
197
+ Int readInt32(MemorySegment seg) { seg.get((OfInt)intLayout, 0) }
198
+
199
+ ** The NUL-terminated UTF-8 text at the start of `seg`.
200
+ Str text(MemorySegment seg) { seg.getString(0) }
201
+
202
+ ** The first `len` bytes of `seg` as an immutable Buf.
203
+ Buf bytes(MemorySegment seg, Int len)
204
+ {
205
+ out := Buf(len.max(1))
206
+ if (len > 0) out.writeBuf(Interop.toFan(seg.asSlice(0, len).asByteBuffer), len)
207
+ return out.flip.toImmutable
208
+ }
209
+
210
+ ** A native copy of `data` (positions 0..size of the Buf).
211
+ MemorySegment copyIn(Arena arena, Buf data)
212
+ {
213
+ size := data.size
214
+ seg := buffer(arena, size)
215
+ if (size > 0)
216
+ {
217
+ ByteBuffer src := Interop.toJava(data.dup.seek(0))
218
+ seg.asByteBuffer.put(src)
219
+ }
220
+ return seg
221
+ }
222
+
223
+ ** The static text of `polycall_strerror(status)`.
224
+ Str strerrorText(Int status)
225
+ {
226
+ MemorySegment p := strerror.invokeWithArguments(Obj?[cint(status)])
227
+ return p.reinterpret(4096).getString(0)
228
+ }
229
+
230
+ ** This thread's last-error detail ("" when none).
231
+ Str lastErrorText()
232
+ {
233
+ scoped |arena->Obj?|
234
+ {
235
+ cap := 1024
236
+ buf := buffer(arena, cap)
237
+ n := invokeInt(lastError, Obj?[buf, cap])
238
+ return n <= 0 ? "" : text(buf)
239
+ }
240
+ }
241
+
242
+ //////////////////////////////////////////////////////////////////////////
243
+ // Handles and layouts
244
+ //////////////////////////////////////////////////////////////////////////
245
+
246
+ private MethodHandle ofConfined
247
+ private Obj longLayout
248
+ private Obj intLayout
249
+ private MemorySegment nullPtr
250
+
251
+ MethodHandle abiVersion
252
+ MethodHandle version
253
+ MethodHandle strerror
254
+ MethodHandle lastError
255
+ MethodHandle runConfig
256
+ MethodHandle describe
257
+ MethodHandle call
258
+ MethodHandle peerOpen
259
+ MethodHandle peerClose
260
+ MethodHandle peerEndpoint
261
+ MethodHandle peerNodeId
262
+ MethodHandle peerRegister
263
+ MethodHandle peerUnregister
264
+ MethodHandle peerList
265
+ MethodHandle peerPing
266
+ MethodHandle peerSend
267
+ MethodHandle peerRecv
268
+ MethodHandle peerCancel
269
+ MethodHandle peerHealth
270
+ }