kobako 0.30.0 → 0.31.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 (266) hide show
  1. checksums.yaml +4 -4
  2. data/.release-please-manifest.json +1 -1
  3. data/CHANGELOG.md +335 -0
  4. data/Cargo.lock +469 -11
  5. data/README.md +43 -3
  6. data/ROADMAP.md +1 -1
  7. data/crates/kobako-runtime/CHANGELOG.md +219 -0
  8. data/crates/kobako-runtime/Cargo.toml +51 -3
  9. data/crates/kobako-runtime/README.md +7 -4
  10. data/crates/kobako-runtime/src/cred.rs +124 -0
  11. data/crates/kobako-runtime/src/dispatch.rs +4 -5
  12. data/crates/kobako-runtime/src/endpoint/buffer.rs +153 -44
  13. data/crates/kobako-runtime/src/endpoint/dispatch.rs +80 -41
  14. data/crates/kobako-runtime/src/endpoint/invoke.rs +23 -36
  15. data/crates/kobako-runtime/src/endpoint.rs +137 -36
  16. data/crates/kobako-runtime/src/errno.rs +391 -0
  17. data/crates/kobako-runtime/src/error.rs +31 -10
  18. data/crates/kobako-runtime/src/filesystem/anon_inodes.rs +52 -0
  19. data/crates/kobako-runtime/src/filesystem/bind/lookup.rs +52 -14
  20. data/crates/kobako-runtime/src/filesystem/bind/walk.rs +19 -20
  21. data/crates/kobako-runtime/src/filesystem/bind.rs +437 -245
  22. data/crates/kobako-runtime/src/filesystem/overlay/file.rs +6 -6
  23. data/crates/kobako-runtime/src/filesystem/overlay/path.rs +43 -65
  24. data/crates/kobako-runtime/src/filesystem/overlay/stack/copy_up.rs +9 -16
  25. data/crates/kobako-runtime/src/filesystem/overlay/stack/dir.rs +47 -72
  26. data/crates/kobako-runtime/src/filesystem/overlay/stack/namei.rs +12 -12
  27. data/crates/kobako-runtime/src/filesystem/overlay/stack/readdir.rs +4 -7
  28. data/crates/kobako-runtime/src/filesystem/overlay/stack.rs +121 -37
  29. data/crates/kobako-runtime/src/filesystem/overlay.rs +302 -343
  30. data/crates/kobako-runtime/src/filesystem/pipe.rs +12 -9
  31. data/crates/kobako-runtime/src/filesystem/rdir.rs +15 -32
  32. data/crates/kobako-runtime/src/filesystem/tmpfs/seed.rs +32 -0
  33. data/crates/kobako-runtime/src/filesystem/tmpfs/tmpfile.rs +3 -3
  34. data/crates/kobako-runtime/src/filesystem/tmpfs/whiteout.rs +57 -35
  35. data/crates/kobako-runtime/src/filesystem/tmpfs/xattr.rs +2 -2
  36. data/crates/kobako-runtime/src/filesystem/tmpfs.rs +172 -160
  37. data/crates/kobako-runtime/src/filesystem/wrap.rs +36 -52
  38. data/crates/kobako-runtime/src/filesystem.rs +6 -3
  39. data/crates/kobako-runtime/src/fork.rs +96 -0
  40. data/crates/kobako-runtime/src/grant.rs +3 -0
  41. data/crates/kobako-runtime/src/hashtable.rs +4 -2
  42. data/crates/kobako-runtime/src/lib.rs +18 -7
  43. data/crates/kobako-runtime/src/limits.rs +195 -0
  44. data/crates/kobako-runtime/src/locking.rs +10 -0
  45. data/crates/kobako-runtime/src/memcg.rs +383 -0
  46. data/crates/kobako-runtime/src/mount.rs +67 -9
  47. data/crates/kobako-runtime/src/net/backends.rs +43 -0
  48. data/crates/kobako-runtime/src/net/connections.rs +179 -0
  49. data/crates/kobako-runtime/src/net/credential.rs +125 -0
  50. data/crates/kobako-runtime/src/net/egress.rs +160 -0
  51. data/crates/kobako-runtime/src/net/family.rs +181 -0
  52. data/crates/kobako-runtime/src/net/http.rs +2733 -0
  53. data/crates/kobako-runtime/src/net/lookup.rs +285 -0
  54. data/crates/kobako-runtime/src/net/mock.rs +251 -0
  55. data/crates/kobako-runtime/src/net/namespace.rs +1366 -0
  56. data/crates/kobako-runtime/src/net/reactor.rs +531 -0
  57. data/crates/kobako-runtime/src/net/resolv/darwin.rs +275 -0
  58. data/crates/kobako-runtime/src/net/resolv/stub/tests.rs +469 -0
  59. data/crates/kobako-runtime/src/net/resolv/stub.rs +536 -0
  60. data/crates/kobako-runtime/src/net/resolv/windows.rs +248 -0
  61. data/crates/kobako-runtime/src/net/resolv.rs +227 -0
  62. data/crates/kobako-runtime/src/net/socket.rs +870 -0
  63. data/crates/kobako-runtime/src/net/tcp.rs +1588 -0
  64. data/crates/kobako-runtime/src/net/tls.rs +58 -0
  65. data/crates/kobako-runtime/src/net/transport.rs +279 -0
  66. data/crates/kobako-runtime/src/net/udp.rs +1003 -0
  67. data/crates/kobako-runtime/src/net.rs +42 -0
  68. data/crates/kobako-runtime/src/network/builder.rs +177 -0
  69. data/crates/kobako-runtime/src/network/ruleset.rs +777 -0
  70. data/crates/kobako-runtime/src/network.rs +551 -0
  71. data/crates/kobako-runtime/src/policy.rs +16 -0
  72. data/crates/kobako-runtime/src/profile.rs +29 -144
  73. data/crates/kobako-runtime/src/runtime.rs +3 -5
  74. data/crates/kobako-runtime/src/sched.rs +130 -29
  75. data/crates/kobako-runtime/src/security/entry_policy.rs +22 -0
  76. data/crates/kobako-runtime/src/{vfs/cred.rs → security/hooks.rs} +52 -144
  77. data/crates/kobako-runtime/src/security/mount_policy.rs +158 -0
  78. data/crates/kobako-runtime/src/security.rs +101 -196
  79. data/crates/kobako-runtime/src/snapshot.rs +121 -2
  80. data/crates/kobako-runtime/src/vfs/attr.rs +5 -5
  81. data/crates/kobako-runtime/src/vfs/dentry.rs +143 -89
  82. data/crates/kobako-runtime/src/vfs/file.rs +199 -203
  83. data/crates/kobako-runtime/src/vfs/inode.rs +41 -45
  84. data/crates/kobako-runtime/src/vfs/kern_path.rs +38 -42
  85. data/crates/kobako-runtime/src/vfs/mount.rs +10 -9
  86. data/crates/kobako-runtime/src/vfs/namei.rs +829 -700
  87. data/crates/kobako-runtime/src/vfs/namespace.rs +162 -0
  88. data/crates/kobako-runtime/src/vfs/open_files.rs +69 -0
  89. data/crates/kobako-runtime/src/vfs/openat2.rs +3 -3
  90. data/crates/kobako-runtime/src/vfs/path.rs +6 -6
  91. data/crates/kobako-runtime/src/vfs/readdir.rs +6 -6
  92. data/crates/kobako-runtime/src/vfs/stat.rs +159 -23
  93. data/crates/kobako-runtime/src/vfs/super_block.rs +18 -14
  94. data/crates/kobako-runtime/src/vfs/utimes.rs +37 -27
  95. data/crates/kobako-runtime/src/vfs.rs +9 -6
  96. data/crates/kobako-runtime/src/wait.rs +356 -0
  97. data/crates/kobako-transport/CHANGELOG.md +31 -0
  98. data/crates/kobako-transport/Cargo.toml +1 -1
  99. data/crates/kobako-transport/README.md +3 -4
  100. data/crates/kobako-transport/src/abi.rs +78 -72
  101. data/crates/kobako-transport/src/envelope/bytes.rs +17 -6
  102. data/crates/kobako-transport/src/envelope/call.rs +32 -4
  103. data/crates/kobako-transport/src/envelope/error_record.rs +21 -0
  104. data/crates/kobako-transport/src/envelope/name.rs +99 -0
  105. data/crates/kobako-transport/src/envelope/outcome.rs +9 -9
  106. data/crates/kobako-transport/src/envelope/preamble.rs +24 -21
  107. data/crates/kobako-transport/src/envelope/reply.rs +27 -27
  108. data/crates/kobako-transport/src/envelope/unsupported.rs +10 -10
  109. data/crates/kobako-transport/src/envelope.rs +13 -8
  110. data/crates/kobako-wasmtime/CHANGELOG.md +161 -0
  111. data/crates/kobako-wasmtime/Cargo.toml +26 -7
  112. data/crates/kobako-wasmtime/README.md +3 -2
  113. data/crates/kobako-wasmtime/build/preview2.rs +1339 -0
  114. data/crates/kobako-wasmtime/build.rs +16 -0
  115. data/crates/kobako-wasmtime/src/abi.rs +17 -37
  116. data/crates/kobako-wasmtime/src/ambient.rs +33 -18
  117. data/crates/kobako-wasmtime/src/cache.rs +23 -15
  118. data/crates/kobako-wasmtime/src/config.rs +52 -68
  119. data/crates/kobako-wasmtime/src/driver.rs +48 -63
  120. data/crates/kobako-wasmtime/src/exports.rs +143 -17
  121. data/crates/kobako-wasmtime/src/guest.rs +12 -6
  122. data/crates/kobako-wasmtime/src/guest_binary.rs +14 -0
  123. data/crates/kobako-wasmtime/src/imports.rs +42 -18
  124. data/crates/kobako-wasmtime/src/instance_pre.rs +4 -4
  125. data/crates/kobako-wasmtime/src/invocation.rs +74 -12
  126. data/crates/kobako-wasmtime/src/lib.rs +5 -3
  127. data/crates/kobako-wasmtime/src/limiter.rs +70 -5
  128. data/crates/kobako-wasmtime/src/preview1/descriptors.rs +309 -0
  129. data/crates/kobako-wasmtime/src/preview1/differential/mount.rs +5 -15
  130. data/crates/kobako-wasmtime/src/preview1/differential.rs +27 -31
  131. data/crates/kobako-wasmtime/src/preview1/errno.rs +55 -66
  132. data/crates/kobako-wasmtime/src/preview1/fd.rs +327 -296
  133. data/crates/kobako-wasmtime/src/preview1/memory.rs +21 -12
  134. data/crates/kobako-wasmtime/src/preview1/mount_view/wrap.rs +34 -53
  135. data/crates/kobako-wasmtime/src/preview1/mount_view.rs +231 -217
  136. data/crates/kobako-wasmtime/src/preview1/path.rs +56 -121
  137. data/crates/kobako-wasmtime/src/preview1/poll.rs +244 -120
  138. data/crates/kobako-wasmtime/src/preview1/sock.rs +10 -8
  139. data/crates/kobako-wasmtime/src/preview1/testsuite.rs +5 -15
  140. data/crates/kobako-wasmtime/src/preview1.rs +46 -42
  141. data/crates/kobako-wasmtime/src/preview2/abi.rs +227 -0
  142. data/crates/kobako-wasmtime/src/preview2/error.rs +118 -0
  143. data/crates/kobako-wasmtime/src/preview2/filesystem.rs +122 -0
  144. data/crates/kobako-wasmtime/src/preview2/host.rs +3959 -0
  145. data/crates/kobako-wasmtime/src/preview2/http.rs +1503 -0
  146. data/crates/kobako-wasmtime/src/preview2/io.rs +315 -0
  147. data/crates/kobako-wasmtime/src/preview2/sockets.rs +379 -0
  148. data/crates/kobako-wasmtime/src/preview2/table.rs +305 -0
  149. data/crates/kobako-wasmtime/src/preview2.rs +57 -0
  150. data/crates/kobako-wasmtime/src/trap.rs +24 -9
  151. data/crates/kobako-wasmtime/src/wasi.rs +210 -81
  152. data/crates/kobako-wasmtime/wit/deps/cli.wit +233 -0
  153. data/crates/kobako-wasmtime/wit/deps/clocks.wit +162 -0
  154. data/crates/kobako-wasmtime/wit/deps/filesystem.wit +589 -0
  155. data/crates/kobako-wasmtime/wit/deps/http.wit +733 -0
  156. data/crates/kobako-wasmtime/wit/deps/io.wit +299 -0
  157. data/crates/kobako-wasmtime/wit/deps/random.wit +92 -0
  158. data/crates/kobako-wasmtime/wit/deps/sockets.wit +949 -0
  159. data/data/kobako.wasm +0 -0
  160. data/ext/kobako/Cargo.toml +1 -1
  161. data/ext/kobako/src/{runtime/errors.rs → errors.rs} +34 -26
  162. data/ext/kobako/src/{runtime/escape.rs → escape.rs} +42 -11
  163. data/ext/kobako/src/{runtime/filesystem → filesystem}/grants.rs +30 -26
  164. data/ext/kobako/src/{runtime/filesystem → filesystem}/ruby.rs +149 -168
  165. data/ext/kobako/src/{runtime/filesystem.rs → filesystem.rs} +24 -15
  166. data/ext/kobako/src/gvl.rs +306 -0
  167. data/ext/kobako/src/lib.rs +64 -3
  168. data/ext/kobako/src/network/mock.rs +187 -0
  169. data/ext/kobako/src/network.rs +591 -0
  170. data/ext/kobako/src/runtime/bridge.rs +30 -29
  171. data/ext/kobako/src/runtime/snapshot.rs +4 -4
  172. data/ext/kobako/src/runtime.rs +221 -143
  173. data/ext/kobako/src/wire.rs +42 -0
  174. data/lib/kobako/catalog/extensions.rb +14 -2
  175. data/lib/kobako/catalog/flags.rb +3 -5
  176. data/lib/kobako/catalog/grants.rb +5 -4
  177. data/lib/kobako/catalog/handles.rb +5 -27
  178. data/lib/kobako/catalog/mount.rb +11 -3
  179. data/lib/kobako/catalog/network.rb +35 -0
  180. data/lib/kobako/catalog/replacements.rb +28 -0
  181. data/lib/kobako/catalog/services.rb +5 -19
  182. data/lib/kobako/catalog/snippets.rb +3 -18
  183. data/lib/kobako/catalog.rb +3 -0
  184. data/lib/kobako/codec/{utils.rb → boundary.rb} +4 -2
  185. data/lib/kobako/codec/decoder.rb +4 -4
  186. data/lib/kobako/codec/ext_types.rb +3 -3
  187. data/lib/kobako/codec/handle_walk.rb +3 -43
  188. data/lib/kobako/codec/value_budget.rb +132 -40
  189. data/lib/kobako/codec.rb +1 -1
  190. data/lib/kobako/context.rb +24 -11
  191. data/lib/kobako/errors.rb +15 -12
  192. data/lib/kobako/extension.rb +3 -2
  193. data/lib/kobako/filesystem.rb +9 -2
  194. data/lib/kobako/handle.rb +2 -2
  195. data/lib/kobako/names.rb +28 -0
  196. data/lib/kobako/network.rb +210 -0
  197. data/lib/kobako/outcome.rb +7 -7
  198. data/lib/kobako/pool.rb +45 -23
  199. data/lib/kobako/runtime.rb +3 -2
  200. data/lib/kobako/sandbox.rb +92 -35
  201. data/lib/kobako/sandbox_options.rb +41 -106
  202. data/lib/kobako/transport/argument_wrap.rb +64 -0
  203. data/lib/kobako/transport/block_failure.rb +1 -1
  204. data/lib/kobako/transport/dispatcher.rb +6 -6
  205. data/lib/kobako/transport/exposure.rb +26 -15
  206. data/lib/kobako/transport/reflection.rb +21 -4
  207. data/lib/kobako/transport/run.rb +8 -23
  208. data/lib/kobako/transport/yielder.rb +2 -9
  209. data/lib/kobako/transport.rb +1 -0
  210. data/lib/kobako/version.rb +1 -1
  211. data/lib/kobako.rb +6 -2
  212. data/release-please-config.json +15 -0
  213. data/sig/core/thread.rbs +6 -0
  214. data/sig/kobako/catalog/extensions.rbs +2 -0
  215. data/sig/kobako/catalog/grants.rbs +7 -4
  216. data/sig/kobako/catalog/handles.rbs +0 -2
  217. data/sig/kobako/catalog/mount.rbs +3 -1
  218. data/sig/kobako/catalog/network.rbs +20 -0
  219. data/sig/kobako/catalog/replacements.rbs +14 -0
  220. data/sig/kobako/catalog/services.rbs +0 -4
  221. data/sig/kobako/catalog/snippets.rbs +0 -2
  222. data/sig/kobako/codec/{utils.rbs → boundary.rbs} +2 -2
  223. data/sig/kobako/codec/handle_walk.rbs +0 -6
  224. data/sig/kobako/codec/value_budget.rbs +47 -4
  225. data/sig/kobako/context.rbs +3 -1
  226. data/sig/kobako/errors.rbs +4 -4
  227. data/sig/kobako/filesystem.rbs +21 -3
  228. data/sig/kobako/network.rbs +115 -0
  229. data/sig/kobako/outcome.rbs +1 -1
  230. data/sig/kobako/pool.rbs +7 -3
  231. data/sig/kobako/runtime.rbs +32 -3
  232. data/sig/kobako/sandbox.rbs +19 -2
  233. data/sig/kobako/sandbox_options.rbs +29 -38
  234. data/sig/kobako/transport/argument_wrap.rbs +15 -0
  235. data/sig/kobako/transport/error.rbs +1 -1
  236. data/sig/kobako/transport/exposure.rbs +2 -4
  237. data/sig/kobako/transport/reflection.rbs +10 -0
  238. data/sig/kobako/transport/run.rbs +0 -2
  239. data/sig/kobako/transport/yielder.rbs +0 -3
  240. data/sig/kobako/transport.rbs +1 -1
  241. data/sig/kobako.rbs +13 -0
  242. metadata +84 -35
  243. data/crates/kobako-runtime/src/endpoint/capture.rs +0 -115
  244. data/crates/kobako-runtime/src/endpoint/memory_cap.rs +0 -238
  245. data/crates/kobako-runtime/src/filesystem/path.rs +0 -21
  246. data/crates/kobako-runtime/src/vfs/errno.rs +0 -153
  247. data/crates/kobako-runtime/tests/linux_baseline/calls.rs +0 -171
  248. data/crates/kobako-runtime/tests/linux_baseline/concurrent.rs +0 -276
  249. data/crates/kobako-runtime/tests/linux_baseline/kobako.rs +0 -323
  250. data/crates/kobako-runtime/tests/linux_baseline/linux-baseline-expected.txt +0 -16
  251. data/crates/kobako-runtime/tests/linux_baseline/linux.rs +0 -449
  252. data/crates/kobako-runtime/tests/linux_baseline/main.rs +0 -611
  253. data/crates/kobako-runtime/tests/linux_baseline/permissions.rs +0 -236
  254. data/crates/kobako-wasmtime/src/descriptors.rs +0 -200
  255. data/crates/kobako-wasmtime/tests/integration/compile_posture.rs +0 -43
  256. data/crates/kobako-wasmtime/tests/integration/guest_file.rs +0 -1085
  257. data/crates/kobako-wasmtime/tests/integration/main.rs +0 -29
  258. data/crates/kobako-wasmtime/tests/integration/preamble_flags.rs +0 -70
  259. data/crates/kobako-wasmtime/tests/integration/snippet_compile.rs +0 -95
  260. data/crates/kobako-wasmtime/tests/integration/support/mod.rs +0 -30
  261. data/crates/kobako-wasmtime/tests/integration/unanswered_call.rs +0 -86
  262. data/crates/kobako-wasmtime/tests/integration/unsupported_call.rs +0 -51
  263. data/ext/kobako/src/runtime/gvl.rs +0 -147
  264. data/lib/kobako/constant_name.rb +0 -8
  265. data/sig/kobako/constant_name.rbs +0 -3
  266. /data/ext/kobako/src/{runtime/pinned_value.rs → pinned_value.rs} +0 -0
@@ -0,0 +1,1339 @@
1
+ //! The generator behind `build.rs`: each WIT function a Guest Binary imports
2
+ //! becomes one core `Linker` function, lifting its arguments from the core
3
+ //! values and linear memory, calling the `Host` trait, and lowering the
4
+ //! answer back, as the Canonical ABI's guest-import side has the host do.
5
+ //! `wit-bindgen-core` walks the ABI; this file only says how each step is
6
+ //! spelled in Rust.
7
+
8
+ use std::fmt::Write as _;
9
+ use std::path::Path;
10
+
11
+ use wit_bindgen_core::abi::{self, Bindgen, Instruction, LiftLower, WasmType};
12
+ use wit_bindgen_core::wit_parser::{
13
+ Alignment, ArchitectureSize, Function, FunctionKind, Handle, InterfaceId, Resolve, SizeAlign,
14
+ Type, TypeDefKind, TypeId, TypeOwner,
15
+ };
16
+
17
+ /// The packages vendored under `wit/deps`, each depending only on those
18
+ /// before it.
19
+ const PACKAGES: [&str; 7] = [
20
+ "io.wit",
21
+ "clocks.wit",
22
+ "random.wit",
23
+ "filesystem.wit",
24
+ "sockets.wit",
25
+ "cli.wit",
26
+ "http.wit",
27
+ ];
28
+
29
+ /// The unstable WIT features kobako answers: a stream's failure reaches the
30
+ /// guest as the error code `network-error-code` downcasts it to, as the guest
31
+ /// may not read `to-debug-string` mechanically.
32
+ const FEATURES: &[&str] = &["network-error-code"];
33
+
34
+ /// The functions kobako answers, each interface's by its WIT name, resource
35
+ /// drops included: those a Guest Binary imports, and those a scenario holds
36
+ /// an answer to. No other links, so a call no answer was written for fails to
37
+ /// link rather than to run.
38
+ const IMPORTS: &[(&str, &[&str])] = &[
39
+ (
40
+ "wasi:io/error@0.2.12",
41
+ &["[method]error.to-debug-string", "[resource-drop]error"],
42
+ ),
43
+ (
44
+ "wasi:io/poll@0.2.12",
45
+ &["[method]pollable.block", "[resource-drop]pollable", "poll"],
46
+ ),
47
+ (
48
+ "wasi:io/streams@0.2.12",
49
+ &[
50
+ "[method]input-stream.read",
51
+ "[method]input-stream.subscribe",
52
+ "[method]output-stream.blocking-write-and-flush",
53
+ "[method]output-stream.check-write",
54
+ "[method]output-stream.write",
55
+ "[method]output-stream.flush",
56
+ "[method]output-stream.subscribe",
57
+ "[resource-drop]input-stream",
58
+ "[resource-drop]output-stream",
59
+ ],
60
+ ),
61
+ (
62
+ "wasi:clocks/monotonic-clock@0.2.12",
63
+ &["subscribe-duration"],
64
+ ),
65
+ (
66
+ "wasi:sockets/network@0.2.12",
67
+ &["[resource-drop]network", "network-error-code"],
68
+ ),
69
+ (
70
+ "wasi:sockets/instance-network@0.2.12",
71
+ &["instance-network"],
72
+ ),
73
+ (
74
+ "wasi:sockets/tcp-create-socket@0.2.12",
75
+ &["create-tcp-socket"],
76
+ ),
77
+ (
78
+ "wasi:sockets/tcp@0.2.12",
79
+ &[
80
+ "[method]tcp-socket.start-bind",
81
+ "[method]tcp-socket.finish-bind",
82
+ "[method]tcp-socket.start-connect",
83
+ "[method]tcp-socket.finish-connect",
84
+ "[method]tcp-socket.shutdown",
85
+ "[method]tcp-socket.subscribe",
86
+ "[method]tcp-socket.local-address",
87
+ "[method]tcp-socket.remote-address",
88
+ "[method]tcp-socket.keep-alive-enabled",
89
+ "[method]tcp-socket.set-keep-alive-enabled",
90
+ "[method]tcp-socket.keep-alive-idle-time",
91
+ "[method]tcp-socket.set-keep-alive-idle-time",
92
+ "[method]tcp-socket.keep-alive-interval",
93
+ "[method]tcp-socket.set-keep-alive-interval",
94
+ "[method]tcp-socket.keep-alive-count",
95
+ "[method]tcp-socket.set-keep-alive-count",
96
+ "[method]tcp-socket.receive-buffer-size",
97
+ "[method]tcp-socket.set-receive-buffer-size",
98
+ "[method]tcp-socket.send-buffer-size",
99
+ "[method]tcp-socket.set-send-buffer-size",
100
+ "[method]tcp-socket.hop-limit",
101
+ "[method]tcp-socket.set-hop-limit",
102
+ "[resource-drop]tcp-socket",
103
+ ],
104
+ ),
105
+ (
106
+ "wasi:sockets/ip-name-lookup@0.2.12",
107
+ &[
108
+ "resolve-addresses",
109
+ "[method]resolve-address-stream.resolve-next-address",
110
+ "[method]resolve-address-stream.subscribe",
111
+ "[resource-drop]resolve-address-stream",
112
+ ],
113
+ ),
114
+ (
115
+ "wasi:sockets/udp-create-socket@0.2.12",
116
+ &["create-udp-socket"],
117
+ ),
118
+ (
119
+ "wasi:sockets/udp@0.2.12",
120
+ &[
121
+ "[method]udp-socket.start-bind",
122
+ "[method]udp-socket.finish-bind",
123
+ "[method]udp-socket.stream",
124
+ "[method]udp-socket.subscribe",
125
+ "[method]udp-socket.local-address",
126
+ "[method]udp-socket.unicast-hop-limit",
127
+ "[method]udp-socket.set-unicast-hop-limit",
128
+ "[method]udp-socket.receive-buffer-size",
129
+ "[method]udp-socket.set-receive-buffer-size",
130
+ "[method]udp-socket.send-buffer-size",
131
+ "[method]udp-socket.set-send-buffer-size",
132
+ "[method]incoming-datagram-stream.receive",
133
+ "[method]incoming-datagram-stream.subscribe",
134
+ "[method]outgoing-datagram-stream.check-send",
135
+ "[method]outgoing-datagram-stream.send",
136
+ "[method]outgoing-datagram-stream.subscribe",
137
+ "[resource-drop]udp-socket",
138
+ "[resource-drop]incoming-datagram-stream",
139
+ "[resource-drop]outgoing-datagram-stream",
140
+ ],
141
+ ),
142
+ (
143
+ "wasi:http/types@0.2.12",
144
+ &[
145
+ "[constructor]fields",
146
+ "[method]fields.append",
147
+ "[method]fields.entries",
148
+ "[constructor]outgoing-request",
149
+ "[method]outgoing-request.body",
150
+ "[method]outgoing-request.set-method",
151
+ "[method]outgoing-request.set-path-with-query",
152
+ "[method]outgoing-request.set-scheme",
153
+ "[method]outgoing-request.set-authority",
154
+ "[method]outgoing-body.write",
155
+ "[static]outgoing-body.finish",
156
+ "[method]future-incoming-response.subscribe",
157
+ "[method]future-incoming-response.get",
158
+ "[method]incoming-response.status",
159
+ "[method]incoming-response.headers",
160
+ "[method]incoming-response.consume",
161
+ "[method]incoming-body.stream",
162
+ "[static]incoming-body.finish",
163
+ "[resource-drop]fields",
164
+ "[resource-drop]outgoing-request",
165
+ "[resource-drop]outgoing-body",
166
+ "[resource-drop]future-incoming-response",
167
+ "[resource-drop]incoming-response",
168
+ "[resource-drop]incoming-body",
169
+ "[resource-drop]future-trailers",
170
+ "[constructor]request-options",
171
+ "[method]request-options.connect-timeout",
172
+ "[method]request-options.set-connect-timeout",
173
+ "[method]request-options.first-byte-timeout",
174
+ "[method]request-options.set-first-byte-timeout",
175
+ "[method]request-options.between-bytes-timeout",
176
+ "[method]request-options.set-between-bytes-timeout",
177
+ "[resource-drop]request-options",
178
+ ],
179
+ ),
180
+ ("wasi:http/outgoing-handler@0.2.12", &["handle"]),
181
+ ];
182
+
183
+ /// The host type each WIT resource's handle stands for, as `bindgen!` takes
184
+ /// `with:`, keyed by interface and resource name. A resource of an interface
185
+ /// `IMPORTS` does not name gets its handle alone, since preview1 holds it
186
+ /// before any guest links its functions.
187
+ const WITH: &[(&str, &str, &str)] = &[
188
+ ("wasi:io/error@0.2.12", "error", "io::Error"),
189
+ ("wasi:io/poll@0.2.12", "pollable", "io::Pollable"),
190
+ ("wasi:io/streams@0.2.12", "input-stream", "io::InputStream"),
191
+ (
192
+ "wasi:io/streams@0.2.12",
193
+ "output-stream",
194
+ "io::OutputStream",
195
+ ),
196
+ (
197
+ "wasi:filesystem/types@0.2.12",
198
+ "descriptor",
199
+ "filesystem::File",
200
+ ),
201
+ ("wasi:sockets/network@0.2.12", "network", "sockets::Network"),
202
+ (
203
+ "wasi:sockets/tcp@0.2.12",
204
+ "tcp-socket",
205
+ "sockets::TcpSocket",
206
+ ),
207
+ (
208
+ "wasi:sockets/ip-name-lookup@0.2.12",
209
+ "resolve-address-stream",
210
+ "sockets::ResolveAddressStream",
211
+ ),
212
+ (
213
+ "wasi:sockets/udp@0.2.12",
214
+ "udp-socket",
215
+ "sockets::UdpSocket",
216
+ ),
217
+ (
218
+ "wasi:sockets/udp@0.2.12",
219
+ "incoming-datagram-stream",
220
+ "sockets::IncomingDatagramStream",
221
+ ),
222
+ (
223
+ "wasi:sockets/udp@0.2.12",
224
+ "outgoing-datagram-stream",
225
+ "sockets::OutgoingDatagramStream",
226
+ ),
227
+ ("wasi:http/types@0.2.12", "fields", "http::resource::Fields"),
228
+ (
229
+ "wasi:http/types@0.2.12",
230
+ "outgoing-request",
231
+ "http::resource::OutgoingRequest",
232
+ ),
233
+ (
234
+ "wasi:http/types@0.2.12",
235
+ "outgoing-body",
236
+ "http::resource::OutgoingBody",
237
+ ),
238
+ (
239
+ "wasi:http/types@0.2.12",
240
+ "future-incoming-response",
241
+ "http::resource::FutureIncomingResponse",
242
+ ),
243
+ (
244
+ "wasi:http/types@0.2.12",
245
+ "incoming-response",
246
+ "http::resource::IncomingResponse",
247
+ ),
248
+ (
249
+ "wasi:http/types@0.2.12",
250
+ "incoming-body",
251
+ "http::resource::IncomingBody",
252
+ ),
253
+ (
254
+ "wasi:http/types@0.2.12",
255
+ "future-trailers",
256
+ "http::resource::FutureTrailers",
257
+ ),
258
+ (
259
+ "wasi:http/types@0.2.12",
260
+ "request-options",
261
+ "http::resource::RequestOptions",
262
+ ),
263
+ ];
264
+
265
+ /// The host type each WIT error stands for, as `bindgen!` takes
266
+ /// `trappable_error_type:`, keyed by interface and type name: a function
267
+ /// answering a lone `result<_, e>` of one returns it, so its host answers the
268
+ /// error or traps through one `?`.
269
+ const TRAPPABLE: &[(&str, &str, &str)] = &[
270
+ ("wasi:io/streams@0.2.12", "stream-error", "StreamError"),
271
+ ("wasi:sockets/network@0.2.12", "error-code", "SocketError"),
272
+ ("wasi:http/types@0.2.12", "error-code", "HttpError"),
273
+ ("wasi:http/types@0.2.12", "header-error", "HeaderError"),
274
+ ];
275
+
276
+ /// Where the generated file is included, so every type has one path.
277
+ const ROOT: &str = "crate::preview2::bindings";
278
+
279
+ /// Where `WITH`'s host types and the `Handle` trait live.
280
+ const HOSTS: &str = "crate::preview2";
281
+
282
+ pub fn generate(wit: &Path) -> anyhow::Result<String> {
283
+ let mut resolve = Resolve::default();
284
+ resolve
285
+ .features
286
+ .extend(FEATURES.iter().map(|f| f.to_string()));
287
+ for package in PACKAGES {
288
+ resolve.push_file(wit.join(package))?;
289
+ }
290
+ let mut sizes = SizeAlign::default();
291
+ sizes.fill(&resolve)?;
292
+
293
+ let imports = IMPORTS
294
+ .iter()
295
+ .map(|(name, functions)| {
296
+ let id = resolve
297
+ .interfaces
298
+ .iter()
299
+ .find(|(id, _)| resolve.id_of(*id).as_deref() == Some(*name))
300
+ .map(|(id, _)| id)
301
+ .ok_or_else(|| anyhow::anyhow!("{name} is not in the vendored WIT"))?;
302
+ let found = functions_of(&resolve, id, functions).count()
303
+ + resources_of(&resolve, id, functions).count();
304
+ if found != functions.len() {
305
+ return Err(anyhow::anyhow!("{name} lacks a function IMPORTS names"));
306
+ }
307
+ match resources_of(&resolve, id, functions)
308
+ .find(|(r, _)| host_by_resource(name, r).is_none())
309
+ {
310
+ Some((r, _)) => Err(anyhow::anyhow!("WITH names no host type for {name} {r}")),
311
+ None => Ok((id, *functions)),
312
+ }
313
+ })
314
+ .collect::<anyhow::Result<Vec<_>>>()?;
315
+
316
+ let mut out = String::new();
317
+ out.push_str("// Generated by build.rs from wit/deps; do not edit.\n\n");
318
+ for (id, _) in &imports {
319
+ write_types(&resolve, *id, &mut out);
320
+ }
321
+ for (interface, resources) in handles_unimported() {
322
+ let id = resolve
323
+ .interfaces
324
+ .iter()
325
+ .find(|(id, _)| resolve.id_of(*id).as_deref() == Some(interface))
326
+ .map(|(id, _)| id)
327
+ .ok_or_else(|| anyhow::anyhow!("{interface} is not in the vendored WIT"))?;
328
+ let _ = writeln!(
329
+ out,
330
+ "#[allow(dead_code)]\npub mod {} {{",
331
+ module_of(&resolve, id)
332
+ );
333
+ for (resource, host) in resources {
334
+ if !resolve.interfaces[id].types.contains_key(resource) {
335
+ return Err(anyhow::anyhow!("{interface} has no resource {resource}"));
336
+ }
337
+ write_handle(&to_camel(resource), host, &mut out);
338
+ }
339
+ out.push_str("}\n\n");
340
+ }
341
+ write_host_trait(&resolve, &imports, &mut out);
342
+ write_linker(&resolve, &sizes, &imports, &mut out);
343
+ Ok(out)
344
+ }
345
+
346
+ /// The host type `WITH` names for `interface`'s `resource`.
347
+ fn host_by_resource(interface: &str, resource: &str) -> Option<&'static str> {
348
+ WITH.iter()
349
+ .find(|(i, r, _)| *i == interface && *r == resource)
350
+ .map(|(_, _, host)| *host)
351
+ }
352
+
353
+ /// Each interface `WITH` names that `IMPORTS` does not, with its resources
354
+ /// and their host types.
355
+ fn handles_unimported() -> Vec<(&'static str, Vec<(&'static str, &'static str)>)> {
356
+ let mut found: Vec<(&str, Vec<(&str, &str)>)> = Vec::new();
357
+ for (interface, resource, host) in WITH {
358
+ if IMPORTS.iter().any(|(name, _)| name == interface) {
359
+ continue;
360
+ }
361
+ match found.iter_mut().find(|(name, _)| name == interface) {
362
+ Some((_, resources)) => resources.push((resource, host)),
363
+ None => found.push((interface, vec![(resource, host)])),
364
+ }
365
+ }
366
+ found
367
+ }
368
+
369
+ /// A resource's handle, the index the resource table holds it under, bound
370
+ /// to the host type `host` names.
371
+ fn write_handle(name: &str, host: &str, out: &mut String) {
372
+ let _ = writeln!(
373
+ out,
374
+ "/// A handle the guest holds, its index in the resource table.\n\
375
+ #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]\npub struct {name}(pub u32);\n\
376
+ impl {HOSTS}::table::Handle for {name} {{\n\
377
+ type Host = {HOSTS}::{host};\n\
378
+ fn new(index: u32) -> Self {{ Self(index) }}\n\
379
+ fn index(self) -> u32 {{ self.0 }}\n}}"
380
+ );
381
+ }
382
+
383
+ /// The module one interface's types live in.
384
+ fn module_of(resolve: &Resolve, id: InterfaceId) -> String {
385
+ to_snake(&resolve.id_of(id).expect("a named interface"))
386
+ }
387
+
388
+ fn to_snake(name: &str) -> String {
389
+ let mut out = String::new();
390
+ for c in name.chars() {
391
+ match c {
392
+ 'a'..='z' | '0'..='9' => out.push(c),
393
+ 'A'..='Z' => out.push(c.to_ascii_lowercase()),
394
+ _ if out.ends_with('_') || out.is_empty() => {}
395
+ _ => out.push('_'),
396
+ }
397
+ }
398
+ let out = out.trim_end_matches('_').to_string();
399
+ match out.as_str() {
400
+ // A method's receiver, which `self` already names in the trait.
401
+ "self" => "this".into(),
402
+ "type" | "in" | "loop" | "move" | "ref" | "use" | "match" | "mod" => format!("r#{out}"),
403
+ _ => out,
404
+ }
405
+ }
406
+
407
+ fn to_camel(name: &str) -> String {
408
+ name.split(['-', '_', '.'])
409
+ .filter(|part| !part.is_empty())
410
+ .map(|part| {
411
+ let mut chars = part.chars();
412
+ let first = chars.next().expect("a part").to_ascii_uppercase();
413
+ std::iter::once(first).chain(chars).collect::<String>()
414
+ })
415
+ .collect()
416
+ }
417
+
418
+ /// The Rust path of a named WIT type.
419
+ fn type_path_of(resolve: &Resolve, id: TypeId) -> String {
420
+ let def = &resolve.types[id];
421
+ let name = to_camel(def.name.as_deref().expect("only named types have a path"));
422
+ match def.owner {
423
+ TypeOwner::Interface(owner) => format!("{ROOT}::{}::{name}", module_of(resolve, owner)),
424
+ _ => unreachable!("every imported type belongs to an interface"),
425
+ }
426
+ }
427
+
428
+ /// How a WIT type is spelled in Rust.
429
+ fn to_rust_type(resolve: &Resolve, ty: &Type) -> String {
430
+ match ty {
431
+ Type::Bool => "bool".into(),
432
+ Type::U8 => "u8".into(),
433
+ Type::U16 => "u16".into(),
434
+ Type::U32 => "u32".into(),
435
+ Type::U64 => "u64".into(),
436
+ Type::S8 => "i8".into(),
437
+ Type::S16 => "i16".into(),
438
+ Type::S32 => "i32".into(),
439
+ Type::S64 => "i64".into(),
440
+ Type::String => "String".into(),
441
+ Type::Id(id) => match resolve.types[*id].name {
442
+ Some(_) => type_path_of(resolve, *id),
443
+ None => to_structural_type(resolve, &resolve.types[*id].kind),
444
+ },
445
+ other => unreachable!("no import kobako answers takes {other:?}"),
446
+ }
447
+ }
448
+
449
+ /// How a parameter of `ty` reaches the host: a handle the guest owns comes
450
+ /// as the resource itself, taken out of the table as it is lifted, as
451
+ /// wasmtime moves an `own` resource into the call; anything else as
452
+ /// `to_rust_type` spells it.
453
+ fn to_param_type(resolve: &Resolve, ty: &Type) -> String {
454
+ let Type::Id(id) = ty else {
455
+ return to_rust_type(resolve, ty);
456
+ };
457
+ match &resolve.types[definition_of(resolve, *id)].kind {
458
+ TypeDefKind::Handle(Handle::Own(r)) => format!(
459
+ "<{} as {HOSTS}::table::Handle>::Host",
460
+ type_path_of(resolve, definition_of(resolve, *r))
461
+ ),
462
+ TypeDefKind::Option(inner) => format!("Option<{}>", to_param_type(resolve, inner)),
463
+ _ => to_rust_type(resolve, ty),
464
+ }
465
+ }
466
+
467
+ /// The type `id` names, through every `use` alias of it.
468
+ fn definition_of(resolve: &Resolve, mut id: TypeId) -> TypeId {
469
+ while let TypeDefKind::Type(Type::Id(aliased)) = resolve.types[id].kind {
470
+ id = aliased;
471
+ }
472
+ id
473
+ }
474
+
475
+ /// How a type made of other types is spelled, named or not.
476
+ fn to_structural_type(resolve: &Resolve, kind: &TypeDefKind) -> String {
477
+ match kind {
478
+ TypeDefKind::Handle(Handle::Own(r) | Handle::Borrow(r)) => {
479
+ type_path_of(resolve, definition_of(resolve, *r))
480
+ }
481
+ TypeDefKind::List(t) => format!("Vec<{}>", to_rust_type(resolve, t)),
482
+ TypeDefKind::Option(t) => format!("Option<{}>", to_rust_type(resolve, t)),
483
+ TypeDefKind::Result(r) => format!(
484
+ "Result<{}, {}>",
485
+ r.ok.as_ref()
486
+ .map_or("()".into(), |t| to_rust_type(resolve, t)),
487
+ r.err
488
+ .as_ref()
489
+ .map_or("()".into(), |t| to_rust_type(resolve, t)),
490
+ ),
491
+ TypeDefKind::Tuple(t) => format!(
492
+ "({})",
493
+ t.types
494
+ .iter()
495
+ .map(|t| format!("{},", to_rust_type(resolve, t)))
496
+ .collect::<String>()
497
+ ),
498
+ TypeDefKind::Type(t) => to_rust_type(resolve, t),
499
+ other => unreachable!("no 0.2 import takes {other:?}"),
500
+ }
501
+ }
502
+
503
+ /// Each named type an interface declares.
504
+ fn write_types(resolve: &Resolve, id: InterfaceId, out: &mut String) {
505
+ let interface = &resolve.interfaces[id];
506
+ let _ = writeln!(
507
+ out,
508
+ "#[allow(dead_code, clippy::all)]\npub mod {} {{",
509
+ module_of(resolve, id)
510
+ );
511
+ let wit_name = resolve.id_of(id).expect("a named interface");
512
+ for (wit, ty) in &interface.types {
513
+ let name = to_camel(wit);
514
+ match &resolve.types[*ty].kind {
515
+ TypeDefKind::Record(record) => {
516
+ let _ = writeln!(
517
+ out,
518
+ "#[derive(Clone, Debug, PartialEq)]\npub struct {name} {{"
519
+ );
520
+ for field in &record.fields {
521
+ let _ = writeln!(
522
+ out,
523
+ "pub {}: {},",
524
+ to_snake(&field.name),
525
+ to_rust_type(resolve, &field.ty)
526
+ );
527
+ }
528
+ out.push_str("}\n");
529
+ }
530
+ TypeDefKind::Variant(variant) => {
531
+ let _ = writeln!(
532
+ out,
533
+ "#[derive(Clone, Debug, PartialEq)]\npub enum {name} {{"
534
+ );
535
+ for case in &variant.cases {
536
+ match &case.ty {
537
+ Some(ty) => {
538
+ let _ = writeln!(
539
+ out,
540
+ "{}({}),",
541
+ to_camel(&case.name),
542
+ to_rust_type(resolve, ty)
543
+ );
544
+ }
545
+ None => {
546
+ let _ = writeln!(out, "{},", to_camel(&case.name));
547
+ }
548
+ }
549
+ }
550
+ out.push_str("}\n");
551
+ }
552
+ TypeDefKind::Enum(enum_) => {
553
+ let _ = writeln!(
554
+ out,
555
+ "#[derive(Clone, Copy, Debug, PartialEq, Eq)]\npub enum {name} {{"
556
+ );
557
+ for case in &enum_.cases {
558
+ let _ = writeln!(out, "{},", to_camel(&case.name));
559
+ }
560
+ out.push_str("}\n");
561
+ }
562
+ TypeDefKind::Resource => match host_by_resource(&wit_name, wit) {
563
+ Some(host) => write_handle(&name, host, out),
564
+ None => {
565
+ let _ = writeln!(
566
+ out,
567
+ "/// A handle the guest holds, its index in the resource table.\n\
568
+ #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]\npub struct {name}(pub u32);"
569
+ );
570
+ }
571
+ },
572
+ other => {
573
+ let _ = writeln!(
574
+ out,
575
+ "pub type {name} = {};",
576
+ to_structural_type(resolve, other)
577
+ );
578
+ }
579
+ }
580
+ }
581
+ out.push_str("}\n\n");
582
+ }
583
+
584
+ /// The functions of `id` among `names`.
585
+ fn functions_of<'a>(
586
+ resolve: &'a Resolve,
587
+ id: InterfaceId,
588
+ names: &'a [&str],
589
+ ) -> impl Iterator<Item = &'a Function> {
590
+ resolve.interfaces[id]
591
+ .functions
592
+ .values()
593
+ .filter(move |func| names.contains(&func.name.as_str()))
594
+ }
595
+
596
+ /// The resources of `id` whose drop is among `names`.
597
+ fn resources_of<'a>(
598
+ resolve: &'a Resolve,
599
+ id: InterfaceId,
600
+ names: &'a [&str],
601
+ ) -> impl Iterator<Item = (&'a str, TypeId)> {
602
+ resolve.interfaces[id]
603
+ .types
604
+ .iter()
605
+ .filter(|(_, ty)| matches!(resolve.types[**ty].kind, TypeDefKind::Resource))
606
+ .filter(move |(name, _)| names.contains(&format!("[resource-drop]{name}").as_str()))
607
+ .map(|(name, ty)| (name.as_str(), *ty))
608
+ }
609
+
610
+ /// The `Host` method answering `func`.
611
+ fn to_method_name(resolve: &Resolve, id: InterfaceId, func: &Function) -> String {
612
+ let interface = to_snake(
613
+ resolve.interfaces[id]
614
+ .name
615
+ .as_deref()
616
+ .expect("a named interface"),
617
+ );
618
+ let item = match &func.kind {
619
+ FunctionKind::Constructor(_) => "new".to_string(),
620
+ _ => func.item_name().to_string(),
621
+ };
622
+ let owner = match &func.kind {
623
+ FunctionKind::Method(r) | FunctionKind::Static(r) | FunctionKind::Constructor(r) => {
624
+ format!(
625
+ "{}_",
626
+ to_snake(resolve.types[*r].name.as_deref().expect("a named resource"))
627
+ )
628
+ }
629
+ _ => String::new(),
630
+ };
631
+ format!("{interface}_{owner}{}", to_snake(&item))
632
+ }
633
+
634
+ /// A WIT error `TRAPPABLE` gives a host type.
635
+ struct Trappable {
636
+ /// The error's own definition, past every `use` alias.
637
+ error: TypeId,
638
+ /// The host type a method answering it returns.
639
+ host: String,
640
+ }
641
+
642
+ impl Trappable {
643
+ /// The trappable error `func` answers, as `bindgen!` special-cases a
644
+ /// function whose one result is `result<_, e>` with `e` in its table.
645
+ fn of(resolve: &Resolve, func: &Function) -> Option<Self> {
646
+ let Some(Type::Id(result)) = func.result else {
647
+ return None;
648
+ };
649
+ let TypeDefKind::Result(result) = &resolve.types[result].kind else {
650
+ return None;
651
+ };
652
+ let Some(Type::Id(error)) = result.err else {
653
+ return None;
654
+ };
655
+ let error = definition_of(resolve, error);
656
+ let def = &resolve.types[error];
657
+ let TypeOwner::Interface(owner) = def.owner else {
658
+ return None;
659
+ };
660
+ let interface = resolve.id_of(owner)?;
661
+ let name = def.name.as_deref()?;
662
+ TRAPPABLE
663
+ .iter()
664
+ .find(|(i, t, _)| *i == interface && *t == name)
665
+ .map(|(_, _, host)| Self {
666
+ error,
667
+ host: format!("{HOSTS}::error::{host}"),
668
+ })
669
+ }
670
+
671
+ /// The method turning the host type back into the WIT error, or into a
672
+ /// trap, on the trait of the interface that declares it, as `bindgen!`
673
+ /// names it `convert_<error>`.
674
+ fn convert_method_of(&self, resolve: &Resolve) -> String {
675
+ let def = &resolve.types[self.error];
676
+ let TypeOwner::Interface(owner) = def.owner else {
677
+ unreachable!("a trappable error belongs to an interface");
678
+ };
679
+ format!(
680
+ "{}_convert_{}",
681
+ to_snake(resolve.interfaces[owner].name.as_deref().expect("named")),
682
+ to_snake(def.name.as_deref().expect("a named error"))
683
+ )
684
+ }
685
+ }
686
+
687
+ /// The trait one WIT package's imports are answered through, as `IoHost` for
688
+ /// `wasi:io`.
689
+ fn package_trait_of(resolve: &Resolve, id: InterfaceId) -> String {
690
+ let package = resolve.interfaces[id]
691
+ .package
692
+ .expect("a vendored interface has a package");
693
+ format!("{}Host", to_camel(&resolve.packages[package].name.name))
694
+ }
695
+
696
+ /// The traits the Wasm Driver implements, one per WIT package and one method
697
+ /// per import, and `Host`, which every one of them makes. No method has a
698
+ /// default, so an import without an answer does not compile.
699
+ fn write_host_trait(resolve: &Resolve, imports: &[(InterfaceId, &[&str])], out: &mut String) {
700
+ let mut traits = Vec::<String>::new();
701
+ for (id, _) in imports {
702
+ let name = package_trait_of(resolve, *id);
703
+ if !traits.contains(&name) {
704
+ traits.push(name);
705
+ }
706
+ }
707
+ for name in &traits {
708
+ let package = imports
709
+ .iter()
710
+ .filter(|(id, _)| package_trait_of(resolve, *id) == *name)
711
+ .copied()
712
+ .collect::<Vec<_>>();
713
+ let _ = writeln!(
714
+ out,
715
+ "#[allow(unused_variables, clippy::too_many_arguments)]\npub trait {name} {{"
716
+ );
717
+ write_package_methods(resolve, &package, out);
718
+ write_convert_methods(resolve, imports, &package, out);
719
+ out.push_str("}\n\n");
720
+ }
721
+ let _ = writeln!(
722
+ out,
723
+ "pub trait Host: {} {{\n\
724
+ /// The trap a call ends the run with once it answered, if its host gave the\n\
725
+ /// invocation up meanwhile, as each preview1 call does.\n\
726
+ fn abandonment(&self) -> Option<wasmtime::Error>;\n\
727
+ /// `handle`, once the guest holds it as its kind; any other traps as it\n\
728
+ /// is lifted, before the host is asked, as wasmtime lifts a resource.\n\
729
+ fn lift_handle<H: {HOSTS}::table::Handle>(&mut self, handle: H) -> wasmtime::Result<H>;\n\
730
+ /// The resource `handle` names, taken out of the table as the guest gives\n\
731
+ /// it up, as wasmtime moves an `own` resource into the call; one the guest\n\
732
+ /// does not hold as its kind, or one whose children live, traps.\n\
733
+ fn take_handle<H: {HOSTS}::table::Handle>(&mut self, handle: H) -> wasmtime::Result<H::Host>;\n}}\n",
734
+ traits.join(" + ")
735
+ );
736
+ }
737
+
738
+ fn write_package_methods(resolve: &Resolve, imports: &[(InterfaceId, &[&str])], out: &mut String) {
739
+ for (id, names) in imports {
740
+ for func in functions_of(resolve, *id, names) {
741
+ let params = func
742
+ .params
743
+ .iter()
744
+ .map(|p| format!(", {}: {}", to_snake(&p.name), to_param_type(resolve, &p.ty)))
745
+ .collect::<String>();
746
+ let result = match (Trappable::of(resolve, func), func.result) {
747
+ (Some(trappable), Some(Type::Id(result))) => {
748
+ let TypeDefKind::Result(result) = &resolve.types[result].kind else {
749
+ unreachable!("a trappable function answers a result");
750
+ };
751
+ let ok = result
752
+ .ok
753
+ .as_ref()
754
+ .map_or("()".into(), |t| to_rust_type(resolve, t));
755
+ format!("Result<{ok}, {}>", trappable.host)
756
+ }
757
+ (_, result) => format!(
758
+ "wasmtime::Result<{}>",
759
+ result
760
+ .as_ref()
761
+ .map_or("()".into(), |t| to_rust_type(resolve, t))
762
+ ),
763
+ };
764
+ let _ = writeln!(
765
+ out,
766
+ "fn {}(&mut self{params}) -> {result};",
767
+ to_method_name(resolve, *id, func),
768
+ );
769
+ }
770
+ for (name, ty) in resources_of(resolve, *id, names) {
771
+ let interface = to_snake(resolve.interfaces[*id].name.as_deref().expect("named"));
772
+ let _ = writeln!(
773
+ out,
774
+ "fn {interface}_{}_drop(&mut self, handle: {}) -> wasmtime::Result<()>;",
775
+ to_snake(name),
776
+ type_path_of(resolve, ty),
777
+ );
778
+ }
779
+ }
780
+ }
781
+
782
+ /// One `convert_<error>` method for each trappable error some import answers
783
+ /// and an interface of `package` declares.
784
+ fn write_convert_methods(
785
+ resolve: &Resolve,
786
+ imports: &[(InterfaceId, &[&str])],
787
+ package: &[(InterfaceId, &[&str])],
788
+ out: &mut String,
789
+ ) {
790
+ let mut written = Vec::<TypeId>::new();
791
+ let answered = imports
792
+ .iter()
793
+ .flat_map(|(id, names)| functions_of(resolve, *id, names))
794
+ .filter_map(|func| Trappable::of(resolve, func));
795
+ for trappable in answered {
796
+ let declared = package
797
+ .iter()
798
+ .any(|(id, _)| resolve.types[trappable.error].owner == TypeOwner::Interface(*id));
799
+ if declared && !written.contains(&trappable.error) {
800
+ written.push(trappable.error);
801
+ let _ = writeln!(
802
+ out,
803
+ "fn {}(&mut self, err: {}) -> wasmtime::Result<{}>;",
804
+ trappable.convert_method_of(resolve),
805
+ trappable.host,
806
+ type_path_of(resolve, trappable.error),
807
+ );
808
+ }
809
+ }
810
+ }
811
+
812
+ fn to_core_type(ty: &WasmType) -> &'static str {
813
+ match ty {
814
+ WasmType::I32 | WasmType::Pointer | WasmType::Length => "i32",
815
+ WasmType::I64 | WasmType::PointerOrI64 => "i64",
816
+ other => unreachable!("no import kobako answers carries {other:?}"),
817
+ }
818
+ }
819
+
820
+ /// `add_to_linker`, linking every import under its interface's module.
821
+ fn write_linker(
822
+ resolve: &Resolve,
823
+ sizes: &SizeAlign,
824
+ imports: &[(InterfaceId, &[&str])],
825
+ out: &mut String,
826
+ ) {
827
+ out.push_str(
828
+ "#[allow(unused_mut, unused_variables, clippy::all)]\n\
829
+ pub fn add_to_linker<T: Host + 'static>(linker: &mut wasmtime::Linker<T>) -> wasmtime::Result<()> {\n",
830
+ );
831
+ for (id, names) in imports {
832
+ let module = resolve.id_of(*id).expect("a named interface");
833
+ for func in functions_of(resolve, *id, names) {
834
+ let sig = resolve.wasm_signature(abi::AbiVariant::GuestImport, func);
835
+ let params = sig
836
+ .params
837
+ .iter()
838
+ .enumerate()
839
+ .map(|(i, ty)| format!(", arg{i}: {}", to_core_type(ty)))
840
+ .collect::<String>();
841
+ let result = match sig.results.as_slice() {
842
+ [] => "()".to_string(),
843
+ [one] => to_core_type(one).to_string(),
844
+ _ => unreachable!("a core import answers at most one value"),
845
+ };
846
+ let mut body = FunctionBody::new(resolve, sizes, *id, func);
847
+ // The answer lands in the return area the guest's last argument
848
+ // names, checked once the call returns, as the Canonical ABI does.
849
+ if let (Some(answer), true) = (&func.result, sig.retptr) {
850
+ body.return_area = Some(format!(
851
+ "crate::preview2::abi::ensure_return_area(&mut caller, arg{}, {}, {})?;\n",
852
+ sig.params.len() - 1,
853
+ sizes.size(answer).size_wasm32(),
854
+ sizes.align(answer).align_wasm32()
855
+ ));
856
+ }
857
+ abi::call(
858
+ resolve,
859
+ abi::AbiVariant::GuestImport,
860
+ LiftLower::LiftArgsLowerResults,
861
+ func,
862
+ &mut body,
863
+ false,
864
+ );
865
+ let _ = writeln!(
866
+ out,
867
+ "linker.func_wrap({module:?}, {:?}, |mut caller: wasmtime::Caller<'_, T>{params}| \
868
+ -> wasmtime::Result<{result}> {{\n\
869
+ let mut fuel = crate::preview2::abi::Fuel::new(&mut caller);\n{}}})?;",
870
+ func.name, body.src
871
+ );
872
+ }
873
+ for (name, ty) in resources_of(resolve, *id, names) {
874
+ let interface = to_snake(resolve.interfaces[*id].name.as_deref().expect("named"));
875
+ let _ = writeln!(
876
+ out,
877
+ "linker.func_wrap({module:?}, \"[resource-drop]{name}\", \
878
+ |mut caller: wasmtime::Caller<'_, T>, handle: i32| -> wasmtime::Result<()> {{ \
879
+ caller.data_mut().{interface}_{}_drop({}(handle as u32))?; \
880
+ caller.data().abandonment().map_or(Ok(()), Err) }})?;",
881
+ to_snake(name),
882
+ type_path_of(resolve, ty)
883
+ );
884
+ }
885
+ }
886
+ out.push_str("Ok(())\n}\n");
887
+ }
888
+
889
+ /// One import's body, as the Canonical ABI walks it.
890
+ struct FunctionBody<'a> {
891
+ resolve: &'a Resolve,
892
+ sizes: &'a SizeAlign,
893
+ method: String,
894
+ /// The `convert_<error>` method a trappable answer passes through.
895
+ convert: Option<String>,
896
+ /// The check of the return area an answer lands in, made once the call
897
+ /// returns.
898
+ return_area: Option<String>,
899
+ src: String,
900
+ blocks: Vec<String>,
901
+ stack: Vec<String>,
902
+ tmp: usize,
903
+ }
904
+
905
+ impl<'a> FunctionBody<'a> {
906
+ fn new(resolve: &'a Resolve, sizes: &'a SizeAlign, id: InterfaceId, func: &Function) -> Self {
907
+ Self {
908
+ resolve,
909
+ sizes,
910
+ method: to_method_name(resolve, id, func),
911
+ convert: Trappable::of(resolve, func).map(|t| t.convert_method_of(resolve)),
912
+ return_area: None,
913
+ src: String::new(),
914
+ blocks: Vec::new(),
915
+ stack: Vec::new(),
916
+ tmp: 0,
917
+ }
918
+ }
919
+
920
+ fn tmp(&mut self) -> String {
921
+ self.tmp += 1;
922
+ format!("t{}", self.tmp)
923
+ }
924
+
925
+ /// Bind `expr` to a fresh name, so each operand is read once.
926
+ fn bind(&mut self, expr: String) -> String {
927
+ let name = self.tmp();
928
+ let _ = writeln!(self.src, "let {name} = {expr};");
929
+ name
930
+ }
931
+
932
+ fn take_blocks(&mut self, count: usize) -> Vec<String> {
933
+ self.blocks.drain(self.blocks.len() - count..).collect()
934
+ }
935
+
936
+ fn rust_type_of(&self, id: TypeId) -> String {
937
+ to_rust_type(self.resolve, &Type::Id(id))
938
+ }
939
+
940
+ fn size_of(&self, element: &Type) -> usize {
941
+ self.sizes.size(element).size_wasm32()
942
+ }
943
+
944
+ fn align_of(&self, element: &Type) -> usize {
945
+ self.sizes.align(element).align_wasm32()
946
+ }
947
+ }
948
+
949
+ fn to_offset(offset: &ArchitectureSize) -> usize {
950
+ offset.size_wasm32()
951
+ }
952
+
953
+ impl Bindgen for FunctionBody<'_> {
954
+ type Operand = String;
955
+
956
+ fn emit(
957
+ &mut self,
958
+ resolve: &Resolve,
959
+ inst: &Instruction<'_>,
960
+ operands: &mut Vec<String>,
961
+ results: &mut Vec<String>,
962
+ ) {
963
+ let abi = "crate::preview2::abi";
964
+ match inst {
965
+ Instruction::GetArg { nth } => results.push(format!("arg{nth}")),
966
+ Instruction::I32Const { val } => results.push(format!("{val}i32")),
967
+ Instruction::I32Load { offset: o }
968
+ | Instruction::PointerLoad { offset: o }
969
+ | Instruction::LengthLoad { offset: o } => {
970
+ let e = format!(
971
+ "{abi}::load::<i32>(&mut caller, {}, {})?",
972
+ operands[0],
973
+ to_offset(o)
974
+ );
975
+ results.push(self.bind(e));
976
+ }
977
+ Instruction::I32Load8U { offset: o } => {
978
+ let e = format!(
979
+ "({abi}::load::<u8>(&mut caller, {}, {})? as i32)",
980
+ operands[0],
981
+ to_offset(o)
982
+ );
983
+ results.push(self.bind(e));
984
+ }
985
+ Instruction::I32Load16U { offset: o } => {
986
+ let e = format!(
987
+ "({abi}::load::<u16>(&mut caller, {}, {})? as i32)",
988
+ operands[0],
989
+ to_offset(o)
990
+ );
991
+ results.push(self.bind(e));
992
+ }
993
+ Instruction::I32Store { offset: o }
994
+ | Instruction::PointerStore { offset: o }
995
+ | Instruction::LengthStore { offset: o } => {
996
+ let _ = writeln!(
997
+ self.src,
998
+ "{abi}::store::<i32>(&mut caller, {}, {}, {})?;",
999
+ operands[1],
1000
+ to_offset(o),
1001
+ operands[0]
1002
+ );
1003
+ }
1004
+ Instruction::I32Store8 { offset: o } => {
1005
+ let _ = writeln!(
1006
+ self.src,
1007
+ "{abi}::store::<u8>(&mut caller, {}, {}, {} as u8)?;",
1008
+ operands[1],
1009
+ to_offset(o),
1010
+ operands[0]
1011
+ );
1012
+ }
1013
+ Instruction::I32Store16 { offset: o } => {
1014
+ let _ = writeln!(
1015
+ self.src,
1016
+ "{abi}::store::<u16>(&mut caller, {}, {}, {} as u16)?;",
1017
+ operands[1],
1018
+ to_offset(o),
1019
+ operands[0]
1020
+ );
1021
+ }
1022
+ Instruction::I64Store { offset: o } => {
1023
+ let _ = writeln!(
1024
+ self.src,
1025
+ "{abi}::store::<i64>(&mut caller, {}, {}, {})?;",
1026
+ operands[1],
1027
+ to_offset(o),
1028
+ operands[0]
1029
+ );
1030
+ }
1031
+ Instruction::I64FromU64 => results.push(format!("({} as i64)", operands[0])),
1032
+ Instruction::I32FromU32 | Instruction::I32FromU16 | Instruction::I32FromU8 => {
1033
+ results.push(format!("({} as i32)", operands[0]))
1034
+ }
1035
+ Instruction::U8FromI32 => results.push(format!("({} as u8)", operands[0])),
1036
+ Instruction::U16FromI32 => results.push(format!("({} as u16)", operands[0])),
1037
+ Instruction::U32FromI32 => results.push(format!("({} as u32)", operands[0])),
1038
+ Instruction::U64FromI64 => results.push(format!("({} as u64)", operands[0])),
1039
+ Instruction::I32FromBool => results.push(format!("({} as i32)", operands[0])),
1040
+ Instruction::BoolFromI32 => results.push(format!("({} != 0)", operands[0])),
1041
+ Instruction::ListCanonLift { element, .. } => {
1042
+ let e = format!(
1043
+ "{abi}::load_list::<{}>(&mut caller, &mut fuel, {}, {})?",
1044
+ to_rust_type(resolve, element),
1045
+ operands[0],
1046
+ operands[1]
1047
+ );
1048
+ results.push(self.bind(e));
1049
+ }
1050
+ Instruction::StringLift => {
1051
+ let e = format!(
1052
+ "{abi}::load_string(&mut caller, &mut fuel, {}, {})?",
1053
+ operands[0], operands[1]
1054
+ );
1055
+ results.push(self.bind(e));
1056
+ }
1057
+ Instruction::ListCanonLower { element, .. } => {
1058
+ let (ptr, len) = (self.tmp(), self.tmp());
1059
+ let _ = writeln!(
1060
+ self.src,
1061
+ "let ({ptr}, {len}) = {abi}::store_list::<{}>(&mut caller, &{}, {})?;",
1062
+ to_rust_type(resolve, element),
1063
+ operands[0],
1064
+ self.align_of(element)
1065
+ );
1066
+ results.push(ptr);
1067
+ results.push(len);
1068
+ }
1069
+ Instruction::StringLower { .. } => {
1070
+ let (ptr, len) = (self.tmp(), self.tmp());
1071
+ let _ = writeln!(
1072
+ self.src,
1073
+ "let ({ptr}, {len}) = {abi}::store_list::<u8>(&mut caller, {}.as_bytes(), 1)?;",
1074
+ operands[0]
1075
+ );
1076
+ results.push(ptr);
1077
+ results.push(len);
1078
+ }
1079
+ Instruction::ListLift { element, .. } => {
1080
+ let block = self.take_blocks(1).remove(0);
1081
+ let (size, align) = (self.size_of(element), self.align_of(element));
1082
+ let (list, len) = (self.tmp(), self.tmp());
1083
+ let _ = writeln!(
1084
+ self.src,
1085
+ "let {len} = {abi}::checked_list_len(&mut caller, {ptr}, {given}, {size}, {align})?;\n\
1086
+ fuel.spend({len}, {size})?;\n\
1087
+ let mut {list} = Vec::with_capacity({len});\n\
1088
+ for i in 0..{len} {{ let base = {ptr}.wrapping_add((i * {size}) as i32); {list}.push({block}); }}",
1089
+ ptr = operands[0],
1090
+ given = operands[1],
1091
+ );
1092
+ results.push(list);
1093
+ }
1094
+ Instruction::ListLower { element, .. } => {
1095
+ let block = self.take_blocks(1).remove(0);
1096
+ let (size, align) = (self.size_of(element), self.align_of(element));
1097
+ let (ptr, len) = (self.tmp(), self.tmp());
1098
+ let _ = writeln!(
1099
+ self.src,
1100
+ "let {len} = {list}.len() as i32;\n\
1101
+ let {ptr} = {abi}::realloc(&mut caller, ({len} as usize * {size}) as i32, {align})?;\n\
1102
+ for (i, e) in {list}.into_iter().enumerate() {{ let base = {ptr}.wrapping_add((i * {size}) as i32); {block}; }}",
1103
+ list = operands[0],
1104
+ );
1105
+ results.push(ptr);
1106
+ results.push(len);
1107
+ }
1108
+ Instruction::IterElem { .. } => results.push("e".into()),
1109
+ Instruction::IterBasePointer => results.push("base".into()),
1110
+ Instruction::RecordLift { record, ty, .. } => {
1111
+ let fields = record
1112
+ .fields
1113
+ .iter()
1114
+ .zip(operands.iter())
1115
+ .map(|(f, op)| format!("{}: {op}", to_snake(&f.name)))
1116
+ .collect::<Vec<_>>()
1117
+ .join(", ");
1118
+ let e = format!("{} {{ {fields} }}", self.rust_type_of(*ty));
1119
+ results.push(self.bind(e));
1120
+ }
1121
+ Instruction::RecordLower { record, ty, .. } => {
1122
+ let names = record.fields.iter().map(|_| self.tmp()).collect::<Vec<_>>();
1123
+ let pattern = record
1124
+ .fields
1125
+ .iter()
1126
+ .zip(&names)
1127
+ .map(|(f, n)| format!("{}: {n}", to_snake(&f.name)))
1128
+ .collect::<Vec<_>>()
1129
+ .join(", ");
1130
+ let _ = writeln!(
1131
+ self.src,
1132
+ "let {} {{ {pattern} }} = {};",
1133
+ self.rust_type_of(*ty),
1134
+ operands[0]
1135
+ );
1136
+ results.extend(names);
1137
+ }
1138
+ Instruction::TupleLift { .. } => {
1139
+ let e = format!("({},)", operands.join(", "));
1140
+ results.push(self.bind(e));
1141
+ }
1142
+ Instruction::TupleLower { tuple, .. } => {
1143
+ let names = tuple.types.iter().map(|_| self.tmp()).collect::<Vec<_>>();
1144
+ let _ = writeln!(self.src, "let ({},) = {};", names.join(", "), operands[0]);
1145
+ results.extend(names);
1146
+ }
1147
+ Instruction::HandleLift { handle, .. } => {
1148
+ let (lift, r) = match handle {
1149
+ Handle::Own(r) => ("take_handle", r),
1150
+ Handle::Borrow(r) => ("lift_handle", r),
1151
+ };
1152
+ let path = type_path_of(resolve, definition_of(resolve, *r));
1153
+ let lifted = self.bind(format!(
1154
+ "caller.data_mut().{lift}({path}({} as u32))?",
1155
+ operands[0]
1156
+ ));
1157
+ results.push(lifted)
1158
+ }
1159
+ Instruction::HandleLower { .. } => results.push(format!("({}.0 as i32)", operands[0])),
1160
+ Instruction::EnumLift { enum_, ty, .. } => {
1161
+ let name = self.rust_type_of(*ty);
1162
+ let arms = enum_
1163
+ .cases
1164
+ .iter()
1165
+ .enumerate()
1166
+ .map(|(i, c)| format!("{i} => {name}::{},", to_camel(&c.name)))
1167
+ .collect::<String>();
1168
+ let e = format!(
1169
+ "match {} {{ {arms} _ => return Err({abi}::invalid(\"enum discriminant\")) }}",
1170
+ operands[0]
1171
+ );
1172
+ results.push(self.bind(e));
1173
+ }
1174
+ Instruction::EnumLower { enum_, ty, .. } => {
1175
+ let name = self.rust_type_of(*ty);
1176
+ let arms = enum_
1177
+ .cases
1178
+ .iter()
1179
+ .enumerate()
1180
+ .map(|(i, c)| format!("{name}::{} => {i}i32,", to_camel(&c.name)))
1181
+ .collect::<String>();
1182
+ results.push(format!("(match {} {{ {arms} }})", operands[0]));
1183
+ }
1184
+ Instruction::VariantPayloadName => results.push("e".into()),
1185
+ Instruction::VariantLift { variant, ty, .. } => {
1186
+ let blocks = self.take_blocks(variant.cases.len());
1187
+ let name = self.rust_type_of(*ty);
1188
+ let arms = variant
1189
+ .cases
1190
+ .iter()
1191
+ .zip(blocks)
1192
+ .enumerate()
1193
+ .map(|(i, (c, b))| match c.ty {
1194
+ Some(_) => format!("{i} => {name}::{}({b}),", to_camel(&c.name)),
1195
+ None => format!("{i} => {{ {b}; {name}::{} }},", to_camel(&c.name)),
1196
+ })
1197
+ .collect::<String>();
1198
+ let e = format!(
1199
+ "match {} {{ {arms} _ => return Err({abi}::invalid(\"variant discriminant\")) }}",
1200
+ operands[0]
1201
+ );
1202
+ results.push(self.bind(e));
1203
+ }
1204
+ Instruction::VariantLower {
1205
+ variant,
1206
+ ty,
1207
+ results: types,
1208
+ ..
1209
+ } => {
1210
+ let blocks = self.take_blocks(variant.cases.len());
1211
+ let name = self.rust_type_of(*ty);
1212
+ let arms = variant
1213
+ .cases
1214
+ .iter()
1215
+ .zip(blocks)
1216
+ .map(|(c, b)| match c.ty {
1217
+ Some(_) => format!("{name}::{}(e) => {b},", to_camel(&c.name)),
1218
+ None => format!("{name}::{} => {b},", to_camel(&c.name)),
1219
+ })
1220
+ .collect::<String>();
1221
+ self.lower_match(&operands[0], &arms, types.len(), results);
1222
+ }
1223
+ Instruction::OptionLift { .. } => {
1224
+ let blocks = self.take_blocks(2);
1225
+ let e = format!(
1226
+ "match {} {{ 0 => {{ {}; None }}, 1 => Some({}), _ => return Err({abi}::invalid(\"option discriminant\")) }}",
1227
+ operands[0], blocks[0], blocks[1]
1228
+ );
1229
+ results.push(self.bind(e));
1230
+ }
1231
+ Instruction::OptionLower { results: types, .. } => {
1232
+ let blocks = self.take_blocks(2);
1233
+ let arms = format!("None => {}, Some(e) => {},", blocks[0], blocks[1]);
1234
+ self.lower_match(&operands[0], &arms, types.len(), results);
1235
+ }
1236
+ Instruction::ResultLower { results: types, .. } => {
1237
+ let blocks = self.take_blocks(2);
1238
+ let arms = format!("Ok(e) => {}, Err(e) => {},", blocks[0], blocks[1]);
1239
+ self.lower_match(&operands[0], &arms, types.len(), results);
1240
+ }
1241
+ Instruction::CallInterface { func, .. } => {
1242
+ let args = operands.join(", ");
1243
+ let call = match &self.convert {
1244
+ Some(convert) => format!(
1245
+ "match caller.data_mut().{}({args}) {{ Ok(answer) => Ok(answer), \
1246
+ Err(err) => Err(caller.data_mut().{convert}(err)?) }}",
1247
+ self.method
1248
+ ),
1249
+ None => format!("caller.data_mut().{}({args})?", self.method),
1250
+ };
1251
+ let answered = match func.result {
1252
+ Some(_) => Some(self.bind(call)),
1253
+ None => {
1254
+ let _ = writeln!(self.src, "{call};");
1255
+ None
1256
+ }
1257
+ };
1258
+ self.src.push_str(
1259
+ "if let Some(trap) = caller.data().abandonment() { return Err(trap); }\n",
1260
+ );
1261
+ if let Some(check) = self.return_area.take() {
1262
+ self.src.push_str(&check);
1263
+ }
1264
+ results.extend(answered);
1265
+ }
1266
+ Instruction::Return { amt, .. } => match amt {
1267
+ 0 => self.src.push_str("Ok(())\n"),
1268
+ _ => {
1269
+ let _ = writeln!(self.src, "Ok({})", operands[0]);
1270
+ }
1271
+ },
1272
+ other => unreachable!("no import kobako answers lowers through {other:?}"),
1273
+ }
1274
+ }
1275
+
1276
+ fn return_pointer(&mut self, _size: ArchitectureSize, _align: Alignment) -> String {
1277
+ unreachable!("the guest hands an import its return area")
1278
+ }
1279
+
1280
+ fn push_block(&mut self) {
1281
+ let outer = std::mem::take(&mut self.src);
1282
+ self.stack.push(outer);
1283
+ }
1284
+
1285
+ fn finish_block(&mut self, operands: &mut Vec<String>) {
1286
+ let outer = self.stack.pop().expect("a block was pushed");
1287
+ let inner = std::mem::replace(&mut self.src, outer);
1288
+ let value = match operands.len() {
1289
+ 0 => "()".to_string(),
1290
+ 1 => operands[0].clone(),
1291
+ _ => format!("({})", operands.join(", ")),
1292
+ };
1293
+ self.blocks.push(format!("{{\n{inner}{value}\n}}"));
1294
+ }
1295
+
1296
+ fn sizes(&self) -> &SizeAlign {
1297
+ self.sizes
1298
+ }
1299
+
1300
+ fn is_list_canonical(&self, _resolve: &Resolve, element: &Type) -> bool {
1301
+ matches!(
1302
+ element,
1303
+ Type::U8
1304
+ | Type::S8
1305
+ | Type::U16
1306
+ | Type::S16
1307
+ | Type::U32
1308
+ | Type::S32
1309
+ | Type::U64
1310
+ | Type::S64
1311
+ )
1312
+ }
1313
+ }
1314
+
1315
+ impl FunctionBody<'_> {
1316
+ /// Lower a value through `arms`, each arm a block answering `count` core
1317
+ /// values.
1318
+ fn lower_match(&mut self, op: &str, arms: &str, count: usize, results: &mut Vec<String>) {
1319
+ match count {
1320
+ 0 => {
1321
+ let _ = writeln!(self.src, "match {op} {{ {arms} }};");
1322
+ }
1323
+ 1 => {
1324
+ let name = self.tmp();
1325
+ let _ = writeln!(self.src, "let {name} = match {op} {{ {arms} }};");
1326
+ results.push(name);
1327
+ }
1328
+ n => {
1329
+ let names = (0..n).map(|_| self.tmp()).collect::<Vec<_>>();
1330
+ let _ = writeln!(
1331
+ self.src,
1332
+ "let ({}) = match {op} {{ {arms} }};",
1333
+ names.join(", ")
1334
+ );
1335
+ results.extend(names);
1336
+ }
1337
+ }
1338
+ }
1339
+ }