-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodule.rs
More file actions
2923 lines (2770 loc) · 111 KB
/
module.rs
File metadata and controls
2923 lines (2770 loc) · 111 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Top-level wasm module assembly.
//!
//! Walks post-pipeline IR, assembles a wasm-gc module:
//!
//! 1. **Type section**, two layers in order:
//! - User-type slots (records, variant constructors) — assigned by
//! `TypeRegistry::build` so emit sites already know their indices.
//! - Function types — one per Aver fn, plus type-0 reserved for
//! `_start: () -> ()`.
//! 2. **Function section** — one entry per Aver fn referencing the
//! function-type idx assigned in step 1.
//! 3. **Export section** — `_start` (always at fn idx 0) plus every
//! user fn by name.
//! 4. **Code section** — `_start` calls `main` and drops any return
//! value; user fns get their bodies from `body::emit_fn_body`.
//!
//! Validation runs `wasmparser` with GC + tail-call features before
//! returning bytes.
use std::collections::HashMap;
use wasm_encoder::{
CodeSection, DataCountSection, DataSection, EntityType, ExportKind, ExportSection, Function,
FunctionSection, ImportSection, Instruction, Module, TypeSection, ValType,
};
use super::WasmGcError;
use super::body::eq_helpers::{EqHelperRegistry, EqKind};
use super::body::{FnEntry, FnMap, emit_fn_body};
use super::builtins::{BuiltinName, BuiltinRegistry};
use super::effects::{EffectName, EffectRegistry};
use super::maps::MapHelperRegistry;
use super::types::{TypeRegistry, param_types, record_struct_type, return_results};
use super::wat_helper;
use crate::types::Type as AverType;
use crate::ast::{Expr, FnDef, Stmt, TopLevel, TypeDef};
pub(super) fn emit_module(
items: &[TopLevel],
handler_name: Option<&str>,
) -> Result<Vec<u8>, WasmGcError> {
let registry = TypeRegistry::build_with_handler(items, handler_name.is_some());
let fn_defs: Vec<&FnDef> = items
.iter()
.filter_map(|it| match it {
TopLevel::FnDef(fd) => Some(fd),
_ => None,
})
.collect();
// Discover used pure-builtins. Walk every fn body looking for
// `FnCall` whose callee is `Attr(_, "method")` and the dotted
// form is a known builtin. Discovery happens before slot
// allocation so the registry can reserve indices in declaration
// order.
let mut builtin_registry = BuiltinRegistry::new();
let mut effect_registry = EffectRegistry::new();
let mut eq_helpers_registry = EqHelperRegistry::new();
for fd in &fn_defs {
discover_builtins_in_fn(
fd,
&mut builtin_registry,
&mut effect_registry,
&mut eq_helpers_registry,
®istry,
);
}
// Eq helpers over records / sums with String fields need
// `__wasmgc_string_eq` — force-register so the slot is allocated
// before bodies emit.
if eq_helpers_registry.needs_string_eq(®istry) {
builtin_registry.register(BuiltinName::StringEq);
}
// `--handler X` shape — the synthesised `aver_http_handle`
// wrapper reads `Request.*` and dispatches `Response.text` /
// `Response.setHeader`, so register them up front. The user
// handler may also touch `Http.*` / `Env.*`, which discovery
// already picks up through `discover_builtins_in_fn`.
if handler_name.is_some() {
for eff in [
EffectName::RequestMethod,
EffectName::RequestUrl,
EffectName::RequestQuery,
EffectName::RequestBody,
EffectName::RequestHeadersLoad,
EffectName::ResponseText,
EffectName::ResponseSetHeader,
] {
effect_registry.register(eff);
}
}
// List<String>/List<Char> show up as soon as the program reaches
// for `String.split` or any List<String> literal. Their per-T
// `contains` helper compares heads via `__wasmgc_string_eq`, so
// force-register that builtin if any such list type is in the
// registry — keeps slot allocation deterministic regardless of
// whether `match` discovery already picked it up.
if registry.list_order.iter().any(|c| c == "List<String>") {
builtin_registry.register(BuiltinName::StringEq);
}
// Same trigger for `List<Record>` when the record has any
// String field — `List.contains` over such a list does inline
// field-by-field eq and reaches `__wasmgc_string_eq`.
for canonical in ®istry.list_order {
if let Some(elem) = super::types::TypeRegistry::list_element_type(canonical)
&& let Some(fields) = registry.record_fields.get(elem.trim())
&& fields.iter().any(|(_, t)| t.trim() == "String")
{
builtin_registry.register(BuiltinName::StringEq);
break;
}
}
if fn_defs.is_empty() {
return Err(WasmGcError::Validation(
"module has no fn definitions".into(),
));
}
// `_start` calls `__entry__` if present (synthesised by the
// playground / `--expr` path to wrap a user fn call with literal
// args), otherwise `main`. Both are optional — modules that act
// as a Worker handler (e.g. `tools/edge/handler.av`) export
// `handler` instead and never run `_start`; when neither is
// present, `_start` is emitted as a no-op so the module shape
// stays valid.
let main_idx: Option<usize> = fn_defs
.iter()
.position(|fd| fd.name == "__entry__")
.or_else(|| fn_defs.iter().position(|fd| fd.name == "main"));
let mut module = Module::new();
// ── Type section ───────────────────────────────────────────────
let mut types = TypeSection::new();
// 1) User types in `TypeRegistry` order. Indices match what the
// registry recorded so emit sites can reference them directly.
emit_user_types(&mut types, items, ®istry)?;
// 2) Effect import types. Imports take fn idx 0..K so their
// type slots come right after user types.
let mut next_type_idx = registry.user_type_count;
effect_registry.assign_slots(&mut next_type_idx);
for name in effect_registry.iter() {
let p = name.params(®istry)?;
let r = name.results(®istry)?;
types.ty().function(p, r);
}
// 3) `_start` type — () -> ().
types.ty().function([], []);
let start_type_idx = next_type_idx;
next_type_idx += 1;
// 4) One fn type per user fn. `fn_type_indices[i]` is the wasm
// type idx for the i-th user fn (in declaration order).
let mut fn_type_indices: Vec<u32> = Vec::with_capacity(fn_defs.len());
for fd in &fn_defs {
let params = param_types(&fd.params, Some(®istry))?;
let results = return_results(&fd.return_type, Some(®istry))?;
types.ty().function(params, results);
fn_type_indices.push(next_type_idx);
next_type_idx += 1;
}
// 5) One fn type per registered builtin.
let import_count = effect_registry.import_count();
let mut next_builtin_fn_idx = import_count + 1 + (fn_defs.len() as u32);
builtin_registry.assign_slots(&mut next_builtin_fn_idx, &mut next_type_idx);
for name in builtin_registry.iter() {
let p = name.params(®istry)?;
let r = name.results(®istry)?;
types.ty().function(p, r);
}
// 6) Map helper fn types (per-K hash + eq, per-(K,V) empty/set/get/len).
let mut map_helpers = MapHelperRegistry::default();
map_helpers.assign_slots(
®istry.map_order,
®istry,
&mut next_builtin_fn_idx,
&mut next_type_idx,
)?;
map_helpers.emit_helper_types(&mut types, ®istry)?;
// 7) List / Vector.fromList / String.split-join helpers — per-T
// instantiation list ops, plus singleton split/join when the
// surface code uses them.
let needs_split_join = items_use_string_split_join(items);
let mut list_helpers = super::lists::ListHelperRegistry::default();
list_helpers.assign_slots(
®istry.list_order,
®istry.vector_order,
®istry.tuple_order,
needs_split_join,
®istry,
&mut next_builtin_fn_idx,
&mut next_type_idx,
)?;
list_helpers.emit_helper_types(&mut types, ®istry)?;
// Per-(record/sum) `__eq_<TypeName>` helpers — slot allocation +
// type emit. Bodies emitted after list helpers (they may call
// `__wasmgc_string_eq` registered above).
eq_helpers_registry.assign_slots(&mut next_builtin_fn_idx, &mut next_type_idx);
eq_helpers_registry.emit_helper_types(&mut types);
// 8a) `aver_http_handle` wrapper — `--handler X` synthesises a
// no-arg fn that reads request fields via the `Request.*`
// effects, builds an `HttpRequest`, calls the user's
// `handler`, then walks the response Map and dispatches per
// header before finalising via `Response.text`. Slot the type
// and fn idx now; the body lands at the end of the code
// section (after every helper) so the wrapper's fn idx is
// the highest in the module.
let handler_wrapper: Option<HandlerWrapper> = if let Some(name) = handler_name {
let user_idx = fn_defs
.iter()
.position(|fd| fd.name == name)
.ok_or_else(|| {
WasmGcError::Validation(format!(
"--handler `{name}` doesn't match any fn in this module"
))
})?;
// wrapper is `() -> ()`; status/body land via Response.text.
types.ty().function([], []);
let wrapper_type = next_type_idx;
next_type_idx += 1;
// list_cons : (head: ref string, tail: ref list_String) -> ref list_String
let s_idx = registry
.string_array_type_idx
.ok_or(WasmGcError::Validation(
"handler wrapper requires String slot".into(),
))?;
let list_idx = registry
.list_type_idx("List<String>")
.ok_or(WasmGcError::Validation(
"handler wrapper requires List<String> slot".into(),
))?;
let s_ref = ValType::Ref(wasm_encoder::RefType {
nullable: true,
heap_type: wasm_encoder::HeapType::Concrete(s_idx),
});
let l_ref = ValType::Ref(wasm_encoder::RefType {
nullable: true,
heap_type: wasm_encoder::HeapType::Concrete(list_idx),
});
types.ty().function([s_ref, l_ref], [l_ref]);
let list_cons_type = next_type_idx;
next_type_idx += 1;
let wrapper_fn = next_builtin_fn_idx;
next_builtin_fn_idx += 1;
let list_cons_fn = next_builtin_fn_idx;
next_builtin_fn_idx += 1;
Some(HandlerWrapper {
user_handler_idx: user_idx,
wrapper_type,
wrapper_fn,
list_cons_type,
list_cons_fn,
})
} else {
None
};
// 8) Host-bridge helpers + LM transport buffer — see
// `BridgeIndices` for the why. Emit only when the registry
// actually allocated a String slot.
let bridge: Option<BridgeIndices> = if registry.string_array_type_idx.is_some() {
let idx = emit_bridge_types(&mut types, ®istry, &mut next_type_idx)?;
let mut next_fn = || {
let v = next_builtin_fn_idx;
next_builtin_fn_idx += 1;
v
};
Some(BridgeIndices {
from_lm_type: idx.from_lm_type,
to_lm_type: idx.to_lm_type,
pages_type: idx.pages_type,
grow_type: idx.grow_type,
from_lm_fn: next_fn(),
to_lm_fn: next_fn(),
pages_fn: next_fn(),
grow_fn: next_fn(),
})
} else {
None
};
// 9) Wasm-owned value factories. JS host can't construct wasm-gc
// structs/variants directly, so any effect import that returns
// a structured ref needs per-type constructor helpers exported
// from the binary. Same per-instantiation pattern as
// `__rt_string_from_lm` / per-Map probes — host calls the
// factory, factory does `struct.new`, returns the ref. Emitted
// only when the corresponding effect is registered (DCE'd
// otherwise by `wasm-opt -Oz`).
let factory_exports = allocate_factory_exports(
&mut types,
&mut next_type_idx,
&mut next_builtin_fn_idx,
®istry,
&effect_registry,
)?;
module.section(&types);
// ── Import section ─────────────────────────────────────────────
if effect_registry.import_count() > 0 {
let mut imports = ImportSection::new();
for name in effect_registry.iter() {
let (module_, field) = name.import_pair();
let type_idx = effect_registry
.lookup_wasm_type_idx(name)
.expect("just-assigned effect type idx");
imports.import(module_, field, EntityType::Function(type_idx));
}
module.section(&imports);
}
// ── Function section ───────────────────────────────────────────
let mut funcs = FunctionSection::new();
funcs.function(start_type_idx); // _start at wasm fn idx K
for type_idx in &fn_type_indices {
funcs.function(*type_idx);
}
for name in builtin_registry.iter() {
let type_idx = builtin_registry
.lookup_wasm_type_idx(name)
.expect("just-assigned builtin type idx");
funcs.function(type_idx);
}
map_helpers.emit_function_section(&mut funcs);
list_helpers.emit_function_section(&mut funcs);
// Eq helpers — one fn entry per registered `__eq_<TypeName>` slot.
for (name, _kind) in eq_helpers_registry.iter() {
let t_idx = eq_helpers_registry
.lookup_type_idx(name)
.expect("registered eq helper has type idx after assign_slots");
funcs.function(t_idx);
}
if let Some(hw) = &handler_wrapper {
funcs.function(hw.wrapper_type);
funcs.function(hw.list_cons_type);
}
if let Some(b) = &bridge {
funcs.function(b.from_lm_type);
funcs.function(b.to_lm_type);
funcs.function(b.pages_type);
funcs.function(b.grow_type);
}
factory_exports.emit_function_entries(&mut funcs);
// `__init_globals`: wasm-level start fn that lazy-fills the
// caller_fn globals via `array.new_data`. Has to be a separate
// fn (not part of `_start`) because the host invokes `main`
// directly when both are exported, bypassing `_start` —
// wasm-level start fns are auto-run at instantiation regardless
// of which export the host calls. Allocated last so its idx is
// import_count + funcs.len() once the entry is appended.
let init_globals_fn_idx: Option<u32> = if !registry.caller_fn_global_order.is_empty() {
let idx = import_count + funcs.len();
funcs.function(start_type_idx);
Some(idx)
} else {
None
};
module.section(&funcs);
// ── Memory section (bridge LM only) ────────────────────────────
// 1 page initial, 2048 max (128 MiB ceiling — matches Cloudflare
// Workers' per-request memory limit). The bridge helpers grow
// on demand: `__rt_string_to_lm` checks if it can fit the
// outgoing array and calls `memory.grow` if not. JS host can
// also grow upfront via `__rt_memory_grow` before writing into
// LM with `TextEncoder.encodeInto`. Memory is not a guest heap
// (engine GC owns that); it exists solely as a transport buffer
// between JS host and the `(array i8)` carrier.
if bridge.is_some() {
let mut memories = wasm_encoder::MemorySection::new();
memories.memory(wasm_encoder::MemoryType {
minimum: 1,
maximum: Some(2048),
memory64: false,
shared: false,
page_size_log2: None,
});
module.section(&memories);
}
// ── Global section ─────────────────────────────────────────────
// One mutable `(ref null $string)` global per fn def, declared as
// `ref.null` and lazy-initialised at the top of `_start` via
// `array.new_data $string $segment 0 N`. The wasm-gc spec doesn't
// permit `array.new_data` in const-expr position, so the init has
// to land in a code body — `_start` runs once per instantiation
// and dominates every effect call site, which is what we need.
// Body emit pushes the caller-fn ref through
// `global.get $caller_fn_<idx>` at every effect call site — the
// alloc happens once at startup, the hot path costs one global
// load.
if !registry.caller_fn_global_order.is_empty() {
let string_idx = registry
.string_array_type_idx
.expect("caller_fn globals require the $string slot — TypeRegistry forces it on");
let mut globals = wasm_encoder::GlobalSection::new();
for _ in ®istry.caller_fn_global_order {
let init = wasm_encoder::ConstExpr::extended([Instruction::RefNull(
wasm_encoder::HeapType::Concrete(string_idx),
)]);
globals.global(
wasm_encoder::GlobalType {
val_type: wasm_encoder::ValType::Ref(wasm_encoder::RefType {
nullable: true,
heap_type: wasm_encoder::HeapType::Concrete(string_idx),
}),
mutable: true,
shared: false,
},
&init,
);
}
module.section(&globals);
}
// Build the fn-name → wasm-fn-idx map. With K imports:
// imports at idx 0..K
// _start at K
// user fn i at K+1+i
// builtin at K+1+N+m (assigned by builtin_registry already)
let start_wasm_idx = import_count;
let mut by_name: HashMap<String, FnEntry> = HashMap::new();
for (i, fd) in fn_defs.iter().enumerate() {
by_name.insert(
fd.name.clone(),
FnEntry {
wasm_idx: import_count + 1 + (i as u32),
return_type: fd.return_type.clone(),
},
);
}
let mut builtin_idx_lookup: HashMap<String, u32> = HashMap::new();
for name in builtin_registry.iter() {
let idx = builtin_registry
.lookup_wasm_fn_idx(name)
.expect("registered builtin has wasm fn idx");
builtin_idx_lookup.insert(name.canonical().to_string(), idx);
}
let mut effect_idx_lookup: HashMap<String, u32> = HashMap::new();
for name in effect_registry.iter() {
let idx = effect_registry
.lookup_wasm_fn_idx(name)
.expect("registered effect has wasm fn idx");
effect_idx_lookup.insert(name.canonical().to_string(), idx);
}
let mut map_helpers_lookup: HashMap<String, super::maps::MapKVHelpers> = HashMap::new();
for canonical in ®istry.map_order {
if let Some(h) = map_helpers.kv_helpers(canonical) {
map_helpers_lookup.insert(canonical.clone(), h);
}
}
let mut list_ops_lookup: HashMap<String, super::lists::ListOps> = HashMap::new();
for canonical in ®istry.list_order {
if let Some(o) = list_helpers.list_ops_for(canonical) {
list_ops_lookup.insert(canonical.clone(), o);
}
}
let mut vfl_ops_lookup: HashMap<String, super::lists::VectorFromListOps> = HashMap::new();
for canonical in ®istry.list_order {
if let Some(o) = list_helpers.vfl_ops_for(canonical) {
vfl_ops_lookup.insert(canonical.clone(), o);
}
}
let mut zip_ops_lookup: HashMap<String, u32> = HashMap::new();
for tup_canonical in ®istry.tuple_order {
if let Some(idx) = list_helpers.zip_op_for(tup_canonical) {
zip_ops_lookup.insert(tup_canonical.clone(), idx);
}
}
let string_split_ops = list_helpers.string_split_ops();
let mut eq_helpers_lookup: HashMap<String, u32> = HashMap::new();
for (name, _kind) in eq_helpers_registry.iter() {
if let Some(fn_idx) = eq_helpers_registry.lookup_fn_idx(name) {
eq_helpers_lookup.insert(name.to_string(), fn_idx);
}
}
let fn_map = FnMap {
by_name,
builtins: builtin_idx_lookup,
effects: effect_idx_lookup.clone(),
map_helpers: map_helpers_lookup,
list_ops: list_ops_lookup,
vfl_ops: vfl_ops_lookup,
zip_ops: zip_ops_lookup,
string_split_ops,
eq_helpers: eq_helpers_lookup,
};
// ── Export section ─────────────────────────────────────────────
let mut exports = ExportSection::new();
exports.export("_start", ExportKind::Func, start_wasm_idx);
for (i, fd) in fn_defs.iter().enumerate() {
let wasm_idx = import_count + 1 + (i as u32);
exports.export(&fd.name, ExportKind::Func, wasm_idx);
}
if let Some(b) = &bridge {
exports.export("__rt_string_from_lm", ExportKind::Func, b.from_lm_fn);
exports.export("__rt_string_to_lm", ExportKind::Func, b.to_lm_fn);
exports.export("__rt_memory_pages", ExportKind::Func, b.pages_fn);
exports.export("__rt_memory_grow", ExportKind::Func, b.grow_fn);
exports.export("memory", ExportKind::Memory, 0);
}
factory_exports.emit_exports(&mut exports);
if let Some(hw) = &handler_wrapper {
exports.export("aver_http_handle", ExportKind::Func, hw.wrapper_fn);
exports.export("__rt_list_string_cons", ExportKind::Func, hw.list_cons_fn);
// Map<String,List<String>> bridge: the JS host needs to build
// a request-headers map to satisfy `request_headers_load`.
// Re-export the per-instance Map helper slots under stable
// bridge names.
if let Some(map_h) = map_helpers.kv_helpers("Map<String,List<String>>") {
exports.export(
"__rt_map_string_list_string_empty",
ExportKind::Func,
map_h.empty,
);
exports.export(
"__rt_map_string_list_string_set",
ExportKind::Func,
map_h.set,
);
}
}
module.section(&exports);
// ── Start section ──────────────────────────────────────────────
// Wasm-level start fn — auto-runs once at instantiation, ahead of
// any host-invoked export. Used for caller_fn global init.
if let Some(idx) = init_globals_fn_idx {
module.section(&wasm_encoder::StartSection {
function_index: idx,
});
}
// ── Data count section (must precede code when using passive
// segments via array.new_data / data.drop).
if !registry.string_literals.is_empty() {
let count = DataCountSection {
count: registry.string_literals.len() as u32,
};
module.section(&count);
}
// ── Code section ───────────────────────────────────────────────
let mut codes = CodeSection::new();
// _start: call main if present, drop its return value. Caller_fn
// globals are NOT init here — the wasm-level `(start
// __init_globals)` section handles that on instantiation, before
// any export gets called.
let mut start = Function::new([]);
if let Some(idx) = main_idx {
let main_idx_wasm = import_count + 1 + (idx as u32);
let main_returns_value = !fn_defs[idx].return_type.trim().eq("Unit");
start.instruction(&Instruction::Call(main_idx_wasm));
if main_returns_value {
start.instruction(&Instruction::Drop);
}
}
start.instruction(&Instruction::End);
codes.function(&start);
for (i, fd) in fn_defs.iter().enumerate() {
let self_wasm_idx = import_count + 1 + (i as u32);
// Dry run: discover extra locals by emitting into a throwaway
// fn. Cheaper than threading a separate pre-pass.
let mut probe = Function::new([]);
let extra_locals_dry = emit_fn_body(
&mut probe,
fd,
&fn_map,
self_wasm_idx,
®istry,
&effect_idx_lookup,
)?;
let local_groups: Vec<(u32, ValType)> = extra_locals_dry.iter().map(|v| (1, *v)).collect();
let mut func = Function::new(local_groups);
let _ = emit_fn_body(
&mut func,
fd,
&fn_map,
self_wasm_idx,
®istry,
&effect_idx_lookup,
)?;
codes.function(&func);
}
// Builtin helper bodies — emitted after user fns so their own
// wasm fn indices come last. Bodies are stubs today (Unreachable);
// real impls land in `builtins/` per phase 3c roadmap.
builtin_registry.emit_helper_bodies(&mut codes, ®istry)?;
// Map helper bodies (hash, eq, empty, set, get, len per
// instantiation) — emitted last so their wasm fn indices line up
// with what `MapHelperRegistry::assign_slots` recorded.
// Snapshot list / vector eq+hash fn idxes so map record-key
// helpers can dispatch `List<T>` / `Vector<T>` field types
// without cross-module lookups.
let mut compound_eq_hash_lookup: HashMap<String, (u32, u32)> = HashMap::new();
for canonical in ®istry.list_order {
if let Some(o) = list_helpers.list_ops_for(canonical)
&& let (Some(eq_fn), Some(hash_fn)) = (o.eq, o.hash)
{
compound_eq_hash_lookup.insert(canonical.clone(), (eq_fn, hash_fn));
}
}
for canonical in ®istry.list_order {
// vfl_ops keyed by list canonical, but the `Vector<T>`
// canonical is the right pseudo-K name for record-field
// dispatch — translate.
if let Some(elem) = TypeRegistry::list_element_type(canonical)
&& let Some(o) = list_helpers.vfl_ops_for(canonical)
&& let (Some(eq_fn), Some(hash_fn)) = (o.eq, o.hash)
{
compound_eq_hash_lookup.insert(format!("Vector<{}>", elem.trim()), (eq_fn, hash_fn));
}
}
map_helpers.emit_helper_bodies(&mut codes, ®istry, &compound_eq_hash_lookup)?;
// List / Vector.fromList / String.split-join helper bodies.
let string_eq_fn_idx = builtin_registry.lookup_wasm_fn_idx(BuiltinName::StringEq);
list_helpers.emit_helper_bodies(&mut codes, ®istry, string_eq_fn_idx)?;
// Per-(record/sum) `__eq_<TypeName>` helper bodies — emit after
// list helpers so any String fields can call `__wasmgc_string_eq`
// by the index recorded above.
eq_helpers_registry.emit_helper_bodies(&mut codes, ®istry, string_eq_fn_idx)?;
if let Some(hw) = &handler_wrapper {
let user_handler_wasm_idx = import_count + 1 + (hw.user_handler_idx as u32);
codes.function(&emit_handler_wrapper(
®istry,
&fn_map,
user_handler_wasm_idx,
)?);
codes.function(&emit_list_string_cons(®istry)?);
let _ = hw.list_cons_type; // type idx already consumed by emit_function_section
}
if bridge.is_some() {
emit_bridge_bodies(&mut codes, ®istry)?;
}
factory_exports.emit_bodies(&mut codes, ®istry)?;
// `__init_globals` body — one `array.new_data → global.set` per
// registered caller_fn name. Walks `caller_fn_global_order` so
// global idx i in the section matches the `i`-th name in the
// walker output. Runs at instantiation via the StartSection
// emitted below.
if init_globals_fn_idx.is_some() {
let string_idx = registry
.string_array_type_idx
.expect("caller_fn globals require the $string slot");
let mut init = Function::new([]);
for (idx, fn_name) in registry.caller_fn_global_order.iter().enumerate() {
let bytes = fn_name.as_bytes();
let segment_idx = registry
.string_literal_segment(bytes)
.expect("fn-name passive segment registered alongside the global");
init.instruction(&Instruction::I32Const(0));
init.instruction(&Instruction::I32Const(bytes.len() as i32));
init.instruction(&Instruction::ArrayNewData {
array_type_index: string_idx,
array_data_index: segment_idx,
});
init.instruction(&Instruction::GlobalSet(idx as u32));
}
init.instruction(&Instruction::End);
codes.function(&init);
}
module.section(&codes);
// ── Data section ───────────────────────────────────────────────
// Passive segments holding String literal byte sequences. Emitted
// last; `array.new_data $string $segment_idx` reads from these.
if !registry.string_literals.is_empty() {
let mut data = DataSection::new();
for bytes in ®istry.string_literals {
data.passive(bytes.iter().copied());
}
module.section(&data);
}
let bytes = module.finish();
if let Err(e) = validate(&bytes) {
// Dump invalid bytes for `wasm-tools print` inspection.
let _ = std::fs::write("/tmp/aver_wasm_gc_invalid.wasm", &bytes);
return Err(e);
}
Ok(bytes)
}
fn emit_user_types(
types: &mut TypeSection,
items: &[TopLevel],
registry: &TypeRegistry,
) -> Result<(), WasmGcError> {
// ALL user types — records, variants, string array, vectors,
// results, lists, options, maps, builtin records — go into a
// single explicit rec group. Inside a rec group wasm-gc allows
// forward references between members, which lifts the strict
// bottom-up ordering constraint that otherwise made
// `Vector<List<Int>>` / `List<Map<K, V>>` / any cross-collection
// nesting impossible to express. Type indices follow registry
// insertion order exactly the way they did before the rec group;
// the difference is that members can refer to peers at higher
// indices without crossing a group boundary.
use wasm_encoder::{ArrayType, CompositeInnerType, CompositeType, StructType, SubType};
// Each entry pairs a registry-recorded type idx with the subtype
// shape. Sorting by idx at the end guarantees the rec-group emit
// position matches what `vector_type_idx` / `list_type_idx` /
// `option_type_idx` / `map_slots` / `record_type_idx` recorded —
// critical because eager registrations (`Option<Vector<T>>`,
// `List<K>` for Map keys, etc.) interleave categories so the
// per-collection iteration order no longer matches insertion
// order.
let mut entries: Vec<(u32, SubType)> = Vec::new();
let mk_struct = |fields: Vec<wasm_encoder::FieldType>| SubType {
is_final: true,
supertype_idx: None,
composite_type: CompositeType {
inner: CompositeInnerType::Struct(StructType {
fields: fields.into_boxed_slice(),
}),
shared: false,
},
};
let mk_array = |elem: wasm_encoder::FieldType| SubType {
is_final: true,
supertype_idx: None,
composite_type: CompositeType {
inner: CompositeInnerType::Array(ArrayType(elem)),
shared: false,
},
};
// Records / variants — registered first in `TypeRegistry::build`,
// idx assigned in source order. Look up the recorded idx for each.
for item in items {
match item {
TopLevel::TypeDef(TypeDef::Product { name, fields, .. }) => {
let st = record_struct_type(fields, registry)?;
let idx = registry
.record_type_idx(name)
.ok_or(WasmGcError::Validation(format!(
"record `{name}` not registered"
)))?;
entries.push((idx, mk_struct(st.fields.to_vec())));
}
TopLevel::TypeDef(TypeDef::Sum {
name: parent,
variants,
..
}) => {
for v in variants {
let mut fields = Vec::new();
for ty in &v.fields {
let val_ty = super::types::aver_to_wasm(ty, Some(registry))?.ok_or(
WasmGcError::Validation(format!(
"variant `{}` field of type {ty} has no wasm representation",
v.name
)),
)?;
fields.push(wasm_encoder::FieldType {
element_type: wasm_encoder::StorageType::Val(val_ty),
mutable: false,
});
}
// Look up by (parent, variant) so two sumtypes
// sharing a bare variant name (e.g. payment_ops's
// `Query.ProviderSummary` and `QueryOutput.
// ProviderSummary`) each emit their own struct
// type idx with their own field shape — instead of
// both nadpisując the same entry under the `bare`
// key.
let info =
registry
.variant_in(parent, &v.name)
.ok_or(WasmGcError::Validation(format!(
"variant `{parent}.{}` not registered",
v.name
)))?;
entries.push((info.type_idx, mk_struct(fields)));
}
}
_ => {}
}
}
// String slot.
if let Some(idx) = registry.string_array_type_idx {
entries.push((
idx,
mk_array(wasm_encoder::FieldType {
element_type: wasm_encoder::StorageType::I8,
mutable: true,
}),
));
}
// Vector<T> instantiations.
for canonical in ®istry.vector_order {
let element =
TypeRegistry::vector_element_type(canonical).ok_or(WasmGcError::Validation(
format!("registered vector `{canonical}` has no parsable element type"),
))?;
let elem_val =
super::types::aver_to_wasm(element, Some(registry))?.ok_or(WasmGcError::Validation(
format!("Vector element type `{element}` has no wasm representation"),
))?;
let idx = registry
.vector_type_idx(canonical)
.ok_or(WasmGcError::Validation(format!(
"vector `{canonical}` not registered"
)))?;
entries.push((
idx,
mk_array(wasm_encoder::FieldType {
element_type: wasm_encoder::StorageType::Val(elem_val),
mutable: true,
}),
));
}
// `Result<T, E>` — `(struct (mut i32 tag) (mut T ok) (mut E err))`.
// Unit on either side has no wasm value; we use a dummy `i32` slot
// so the struct shape stays uniform. The slot is never read for
// Unit-typed sides — pattern matching only inspects the tag and
// unwraps the *other* side.
for canonical in ®istry.result_order {
let (t_aver, e_aver) =
TypeRegistry::result_te(canonical).ok_or(WasmGcError::Validation(format!(
"registered result `{canonical}` has no parsable T, E"
)))?;
let t_val = super::types::aver_to_wasm(t_aver, Some(registry))?.unwrap_or(ValType::I32);
let e_val = super::types::aver_to_wasm(e_aver, Some(registry))?.unwrap_or(ValType::I32);
let idx = registry
.result_type_idx(canonical)
.ok_or(WasmGcError::Validation(format!(
"result `{canonical}` not registered"
)))?;
entries.push((
idx,
mk_struct(vec![
wasm_encoder::FieldType {
element_type: wasm_encoder::StorageType::Val(ValType::I32),
mutable: true,
},
wasm_encoder::FieldType {
element_type: wasm_encoder::StorageType::Val(t_val),
mutable: true,
},
wasm_encoder::FieldType {
element_type: wasm_encoder::StorageType::Val(e_val),
mutable: true,
},
]),
));
}
// `List<T>` — recursive Cons cell.
for canonical in ®istry.list_order {
let element = TypeRegistry::list_element_type(canonical).ok_or(WasmGcError::Validation(
format!("registered list `{canonical}` has no parsable element type"),
))?;
let elem_val =
super::types::aver_to_wasm(element, Some(registry))?.ok_or(WasmGcError::Validation(
format!("List element type `{element}` has no wasm representation"),
))?;
let own_idx = registry
.list_type_idx(canonical)
.expect("just-registered list slot");
let tail_ref = wasm_encoder::ValType::Ref(wasm_encoder::RefType {
nullable: true,
heap_type: wasm_encoder::HeapType::Concrete(own_idx),
});
entries.push((
own_idx,
mk_struct(vec![
wasm_encoder::FieldType {
element_type: wasm_encoder::StorageType::Val(elem_val),
mutable: false,
},
wasm_encoder::FieldType {
element_type: wasm_encoder::StorageType::Val(tail_ref),
mutable: false,
},
]),
));
}
// Option<T> — `(struct (mut i32 tag) (mut T value))`.
for canonical in ®istry.option_order {
let element =
TypeRegistry::option_element_type(canonical).ok_or(WasmGcError::Validation(
format!("registered option `{canonical}` has no parsable element type"),
))?;
let elem_val =
super::types::aver_to_wasm(element, Some(registry))?.ok_or(WasmGcError::Validation(
format!("Option element type `{element}` has no wasm representation"),
))?;
let idx = registry
.option_type_idx(canonical)
.ok_or(WasmGcError::Validation(format!(
"option `{canonical}` not registered"
)))?;
entries.push((
idx,
mk_struct(vec![
wasm_encoder::FieldType {
element_type: wasm_encoder::StorageType::Val(ValType::I32),
mutable: true,
},
wasm_encoder::FieldType {
element_type: wasm_encoder::StorageType::Val(elem_val),
mutable: true,
},
]),
));
}
// `Map<K, V>` — three wasm types per registered instantiation
// (keys array, values array, map struct).
for canonical in ®istry.map_order {
let (k_aver, v_aver) = super::types::parse_map_kv(canonical).ok_or(
WasmGcError::Validation(format!("registered map `{canonical}` has no parsable K, V")),
)?;
let v_val =
super::types::aver_to_wasm(v_aver, Some(registry))?.ok_or(WasmGcError::Validation(
format!("Map value type `{v_aver}` has no wasm representation"),
))?;
// Keys array element: for primitive K, a `(ref null
// $primitive_key_box_K)` so the empty-slot marker stays
// uniform; for ref K (String / record), the K's own ref.
let key_storage_val = if let Some(box_idx) = registry.primitive_key_box_idx(k_aver) {
ValType::Ref(wasm_encoder::RefType {
nullable: true,
heap_type: wasm_encoder::HeapType::Concrete(box_idx),
})
} else {
super::types::aver_to_wasm(k_aver, Some(registry))?.ok_or(WasmGcError::Validation(
format!("Map key type `{k_aver}` has no wasm representation"),
))?
};
let slots = registry
.map_slots(canonical)
.expect("just-registered map slots");
entries.push((
slots.keys_array,
mk_array(wasm_encoder::FieldType {
element_type: wasm_encoder::StorageType::Val(key_storage_val),
mutable: true,
}),
));
entries.push((
slots.values_array,
mk_array(wasm_encoder::FieldType {
element_type: wasm_encoder::StorageType::Val(v_val),
mutable: true,
}),
));
let keys_ref = wasm_encoder::ValType::Ref(wasm_encoder::RefType {
nullable: true,
heap_type: wasm_encoder::HeapType::Concrete(slots.keys_array),
});
let values_ref = wasm_encoder::ValType::Ref(wasm_encoder::RefType {
nullable: true,
heap_type: wasm_encoder::HeapType::Concrete(slots.values_array),
});
entries.push((
slots.map,
mk_struct(vec![
wasm_encoder::FieldType {
element_type: wasm_encoder::StorageType::Val(ValType::I32),
mutable: true,
},
wasm_encoder::FieldType {
element_type: wasm_encoder::StorageType::Val(ValType::I32),
mutable: true,
},
wasm_encoder::FieldType {
element_type: wasm_encoder::StorageType::Val(keys_ref),
mutable: true,
},