forked from nulang-org/nulang
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmir_wasm.rs
More file actions
3840 lines (3642 loc) · 171 KB
/
Copy pathmir_wasm.rs
File metadata and controls
3840 lines (3642 loc) · 171 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
//! WASM backend: compiles MIR directly to WebAssembly bytecode.
//!
//! Lowers `mir::Module` → `.wasm` binary via `wasm-encoder`. Values are
//! represented as `i64` using the i64-tagged encoding from `value_layout`.
//!
//! # Effect handling
//!
//! Built-in effects (`IO.print`, `IO.read`, etc.) compile to host imports.
//! User-defined effect handlers (`EnterHandle`/`PopHandler`/`Resume`) are
//! stubbed — they need the CPS transform or WasmFX for full support.
use crate::mir::{self, BlockId, FuncRef, LocalId, RValue, Stmt, Terminator};
use crate::types::NuResult;
use crate::value_layout;
use std::collections::HashMap;
use wasm_encoder::*;
// ── Import / type index constants (used by import/type builders) ───
// Note: import indices count all imports, but function indices only
// count function imports. The memory import (index 0) is NOT a function,
// so function indices start at 0 while import indices start at 1.
const IMPORT_ALLOC_IDX: u32 = 0; // function index of nulang_alloc
/// Function index of `env.nulang_dispatch` — generic effect dispatch
/// (i32, i32, i32, i32) -> i64 (result-length return).
const IMPORT_NULANG_DISPATCH: u32 = 1;
/// Linear-memory base of the host's effect-result ring buffer. Must match
/// `ActorCtx::ring_buffer_base` in nulang-cloud's wasmtime-actor-pool
/// (0x1000). The host writes the dispatch result here and returns its
/// length; the guest reads it back from this fixed address.
pub(crate) const RING_BUFFER_BASE: u32 = 0x1000;
/// Function index of `env.io_print` — used in `Call` instructions.
const IMPORT_IO_PRINT: u32 = 3;
/// Function index of `env.io_read` — used in `Call` instructions.
const IMPORT_IO_READ: u32 = 4;
/// Function index of `env.str_concat` — string concatenation (i64, i64) -> i64.
const IMPORT_STR_CONCAT: u32 = 5;
/// Function index of `env.str_eq` — string content equality (i64, i64) -> i64.
const IMPORT_STR_EQ: u32 = 6;
/// Function index of `env.pow` — integer exponentiation (i64, i64) -> i64.
const IMPORT_POW: u32 = 7;
/// Function index of `env.arith_add` — float/int add (i64, i64) -> i64.
const IMPORT_ARITH_ADD: u32 = 8;
const IMPORT_ARITH_SUB: u32 = 9;
const IMPORT_ARITH_MUL: u32 = 10;
const IMPORT_ARITH_DIV: u32 = 11;
const IMPORT_ARITH_MOD: u32 = 12;
/// Function index of `env.arith_cmp` — float/int comparison (i64, i64, i64) -> i64.
const IMPORT_ARITH_CMP: u32 = 13;
/// Function index of `env.arith_neg` — unary negation (i64) -> i64.
const IMPORT_ARITH_NEG: u32 = 14;
/// Function index of `env.arith_fneg` — VM FNeg semantics (i64) -> i64.
/// Kept after the existing imports so older indices remain stable.
const IMPORT_ARITH_FNEG: u32 = 21;
/// Function index of `env.arr_load` — bounds-checked array load (i64, i64) -> i64.
const IMPORT_ARR_LOAD: u32 = 15;
/// Function index of `env.ffi_call_0` — foreign call (lib, sym, sig) -> i64.
const IMPORT_FFI_CALL_0: u32 = 16;
const IMPORT_FFI_CALL_1: u32 = 17;
const IMPORT_FFI_CALL_2: u32 = 18;
const IMPORT_FFI_CALL_3: u32 = 19;
const IMPORT_FFI_CALL_4: u32 = 20;
/// Number of function imports. Module-defined functions start at this index.
const FUNC_IMPORT_COUNT: u32 = 22;
/// Module-global indices for the guest-side actor emulation (spawn/send/
/// ask/state/receive all run inside one WASM instance — the pool delivers
/// one `nulang_init` invocation per message and the module's own mailbox
/// handles intra-program messaging).
const GLOBAL_CURRENT_ACTOR: u32 = 0; // byte offset of the actor record whose
// behavior is executing (0 = none)
const GLOBAL_MAILBOX_HEAD: u32 = 1; // head of the singly-linked message queue
const GLOBAL_MAILBOX_TAIL: u32 = 2; // tail of the queue
/// Scratch locals for the actor emulation (the function declares 256 i64
/// locals; 251 is `state_local`, 252-255 are the dispatch/binop scratch —
/// all transient within one statement, as here).
const SCRATCH_NODE: u32 = 248; // message node / actor record pointer
const SCRATCH_A: u32 = 249; // saved current-actor / prev pointer / target
const SCRATCH_B: u32 = 250; // ask target pointer
/// Actor record layout (a `nulang_alloc`'d block of i64 slots):
/// slot 0 = the spawned actor's first behavior index; slots 1.. = state
/// fields per `state_field_map`. The record's byte offset doubles as the
/// actor handle carried in a `TAG_ACTOR` value's payload.
const ACTOR_RECORD_SLOT_SIZE: i64 = 8;
/// Message node layout (a `nulang_alloc`'d block of i64 slots):
/// [next_ptr, target_record_ptr, behavior_idx, nargs, arg0..argN-1].
const MSG_SLOT_NEXT: u32 = 0;
const MSG_SLOT_TARGET: u32 = 1;
const MSG_SLOT_BEHAVIOR: u32 = 2;
const MSG_SLOT_NARGS: u32 = 3;
const MSG_SLOT_ARGS: u32 = 4;
const TY_VOID_TO_I64: u32 = 0;
/// (i64, i64) -> i64 — used by `env.str_concat`.
const TY_I64I64_TO_I64: u32 = 2;
/// (i64) -> i64 — used by `env.arith_neg`.
const TY_I64_TO_I64: u32 = 1;
/// (i64, i64, i64) -> i64 — used by `env.arith_cmp`.
const TY_I64I64I64_TO_I64: u32 = 3;
const TY_I32I32_TO_I64: u32 = 4;
const TY_FIXED_COUNT: u32 = 5;
// ── WasmBackend ──────────────────────────────────────────────────────
pub struct WasmBackend {
types: TypeSection,
imports: ImportSection,
functions: FunctionSection,
globals: GlobalSection,
exports: ExportSection,
codes: CodeSection,
data: DataSection,
/// Accumulated data-segment bytes for interned strings.
string_data: Vec<u8>,
/// String content → (offset in data segment, length).
interned: HashMap<String, (u32, u32)>,
func_index_map: HashMap<usize, u32>,
next_func_idx: u32,
func_types: HashMap<Vec<ValType>, u32>,
next_type_idx: u32,
/// Module-wide record field name → slot index map. Built by pre-scanning
/// the MIR; used so `Record` literals and `LoadFieldNamed` agree on slot
/// positions.
field_map: HashMap<String, u8>,
/// Foreign function declarations, indexed by `RValue::FFICall.idx`.
foreign_functions: Vec<mir::ForeignFunction>,
/// True when the module contains actor machinery (spawn/send/ask/
/// receive/state) — gates the globals section + the entry-function
/// mailbox drain.
uses_actor_ops: bool,
/// Module-wide actor-state field name → slot index map (StateGet/
/// StateSet inside behavior bodies). Slots are 1-based within an actor
/// record (slot 0 = the spawned behavior index).
state_field_map: HashMap<String, u8>,
/// Declared state defaults per spawned actor: behavior_idx (the actor's
/// first behavior, from `RValue::Spawn`) → [(field name, default)].
actor_state_defaults: HashMap<usize, Vec<(String, crate::bytecode::Constant)>>,
/// Param counts of `Module::behaviors`, by behavior index — the mailbox
/// drain needs each behavior's arity to build its call.
behavior_param_counts: Vec<usize>,
/// Number of plain (non-behavior) module functions — behaviors are
/// compiled after them, so a behavior's wasm index =
/// FUNC_IMPORT_COUNT + module_function_count + behavior_idx.
module_function_count: usize,
}
/// Resolve a MIR local to its defining constant, if it is assigned exactly
/// once from `RValue::Const`. Used to pre-compute effect-dispatch JSON at
/// compile time — the WASM backend requires constant effect args (dynamic
/// args are a loud compile error, not a silent nil).
fn resolve_const(func: &mir::Function, local: mir::LocalId) -> Option<crate::bytecode::Constant> {
use crate::mir::Stmt;
let mut found = None;
for block in &func.blocks {
for stmt in &block.stmts {
if let Stmt::Assign { dst, op } = stmt {
if *dst == local {
// Multiple assignments (a `var` mutated along the way)
// mean the value is not a compile-time constant.
if found.is_some() {
return None;
}
if let RValue::Const(c) = op {
found = Some(c.clone());
} else {
return None;
}
}
}
}
}
found
}
/// JSON-encode one constant for an effect-dispatch payload.
fn json_arg(c: &crate::bytecode::Constant) -> Option<String> {
use crate::bytecode::Constant;
match c {
Constant::Int(n) => Some(n.to_string()),
Constant::Float(f) => {
let mut s = f.to_string();
// JSON requires a float-looking literal; Rust prints 42.0 as
// "42", which is a valid JSON int but the WRONG type.
if !s.contains('.') && !s.contains('e') && !s.contains('E') {
s.push_str(".0");
}
Some(s)
}
Constant::Bool(true) => Some("true".into()),
Constant::Bool(false) => Some("false".into()),
Constant::String(s) => Some(json_quote(s)),
Constant::Nil | Constant::Unit => Some("null".into()),
_ => None, // TypeDescriptor, FunctionRef, BehaviorRef
}
}
/// JSON-quote a string (escape `"`, `\`, and control characters).
fn json_quote(s: &str) -> String {
let mut out = String::with_capacity(s.len() + 2);
out.push('"');
for c in s.chars() {
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
c => out.push(c),
}
}
out.push('"');
out
}
/// How the guest parses a `nulang_dispatch` result out of the ring buffer.
#[derive(Debug, Clone, Copy, PartialEq)]
enum DispatchResultShape {
/// The result IS the JSON value (int/string/bool/null) — the generic
/// handler contract (handlers return JSON Nulang values directly).
JsonValue,
/// The result is a JSON object; extract the named field's value. Used
/// by pool builtins whose handlers return envelope objects (e.g. the
/// inference handler's `{"content": "...", ...}` response).
JsonField(&'static str),
/// The result is discarded entirely (e.g. fire-and-forget writes).
/// Returns nil without parsing the ring buffer.
Discard,
}
/// A nulang language effect mapped to a pool EffectId + envelope.
struct PoolEffectContract {
/// The exact EffectId the pool's `HandlerRegistry` serves.
tag: &'static str,
/// The JSON payload the pool handler expects (built from constant args).
payload: String,
/// How to parse the handler's JSON response.
shape: DispatchResultShape,
}
/// JSON-quote a constant string arg (`None` when the arg is not a string
/// constant — dynamic args are rejected earlier in the pre-scan).
fn const_str_arg(consts: &[crate::bytecode::Constant], idx: usize) -> Option<String> {
match consts.get(idx) {
Some(crate::bytecode::Constant::String(s)) => Some(json_quote(s)),
_ => None,
}
}
/// A constant int arg as a JSON number literal.
fn const_int_arg(consts: &[crate::bytecode::Constant], idx: usize) -> Option<String> {
match consts.get(idx) {
Some(crate::bytecode::Constant::Int(n)) => Some(n.to_string()),
_ => None,
}
}
/// nulang builtin effects with a KNOWN nulang-cloud pool contract. These
/// bypass the generic dotted-tag + positional-array contract so nulang
/// programs can call the platform's built-in handlers by their language
/// names (`perform Inference.ask("...")` → `nulang:inference/inference`
/// with the chat envelope). Effects not listed here keep the generic
/// contract (programs target handler-registered dotted tags directly).
///
/// The storage/queue/http builtins target the pool's STRING-contract tags
/// (`nulang:storage/string` etc.) — the language-facing adapter handlers
/// registered alongside the byte-contract WIT handlers in nulang-cloud's
/// dev-server emulator. The nulang value type for these domains is the
/// string, so the adapter speaks strings where the WIT world speaks bytes.
fn pool_effect_contract(
effect: &str,
op: &str,
consts: &[crate::bytecode::Constant],
) -> Option<PoolEffectContract> {
use crate::bytecode::Constant;
match (effect, op) {
("Inference", "ask") => {
// `perform Inference.ask(prompt)` → nulang:inference/inference
// with the chat envelope; the handler replies with
// `{"content": "...", ...}` — extract `content`.
let prompt = match consts.first() {
Some(Constant::String(s)) => s.clone(),
_ => return None,
};
Some(PoolEffectContract {
tag: "nulang:inference/inference",
payload: format!(
"{{\"operation\":\"chat\",\"messages\":[{{\"role\":\"user\",\"content\":{}}}]}}",
json_quote(&prompt)
),
shape: DispatchResultShape::JsonField("content"),
})
}
("Storage", "write") => {
// Storage.write(key, value) → string-contract storage handler.
let key = const_str_arg(consts, 0)?;
let value = const_str_arg(consts, 1)?;
Some(PoolEffectContract {
tag: "nulang:storage/string",
payload: format!(r#"{{"operation":"Write","key":{key},"value":{value}}}"#),
shape: DispatchResultShape::Discard,
})
}
("Storage", "read") => {
// Storage.read(key) → String; the handler replies with
// `{"found": bool, "value": "..."}` — extract `value` (empty
// string when the key is absent).
let key = const_str_arg(consts, 0)?;
Some(PoolEffectContract {
tag: "nulang:storage/string",
payload: format!(r#"{{"operation":"Read","key":{key}}}"#),
shape: DispatchResultShape::JsonField("value"),
})
}
("Storage", "delete") => {
let key = const_str_arg(consts, 0)?;
Some(PoolEffectContract {
tag: "nulang:storage/string",
payload: format!(r#"{{"operation":"Delete","key":{key}}}"#),
shape: DispatchResultShape::Discard,
})
}
("Queue", "push") => {
// Queue.push(queue, message) → string-contract queue handler.
// (`send` is a reserved word in the nulang parser, so the
// language surface uses `push`; the handler envelope op is
// still `Send`.)
let name = const_str_arg(consts, 0)?;
let message = const_str_arg(consts, 1)?;
Some(PoolEffectContract {
tag: "nulang:queue/string",
payload: format!(
r#"{{"operation":"Send","queue_name":{name},"message":{message}}}"#
),
shape: DispatchResultShape::Discard,
})
}
("Queue", "pop") => {
// Queue.pop(queue) → String; the handler replies with
// `{"message": "..."}` (empty string when the queue is empty).
let name = const_str_arg(consts, 0)?;
Some(PoolEffectContract {
tag: "nulang:queue/string",
payload: format!(r#"{{"operation":"Receive","queue_name":{name}}}"#),
shape: DispatchResultShape::JsonField("message"),
})
}
("Http", "get") => {
// Http.get(url) → String body; the handler replies with
// `{"status": u16, "body": "..."}` — extract `body`.
let url = const_str_arg(consts, 0)?;
Some(PoolEffectContract {
tag: "nulang:http/string",
payload: format!(r#"{{"url":{url},"method":"GET","headers":{{}},"body":""}}"#),
shape: DispatchResultShape::JsonField("body"),
})
}
("Timer", "sleep") => {
// Timer.sleep(ms) → nulang:timer/timer (the pool's timer
// handler); the result is discarded (nulang's sleep yields
// unit).
let ms = const_int_arg(consts, 0)?;
Some(PoolEffectContract {
tag: "nulang:timer/timer",
payload: format!(r#"{{"ms":{ms}}}"#),
shape: DispatchResultShape::Discard,
})
}
_ => None,
}
}
impl WasmBackend {
pub fn new() -> Self {
let mut types = TypeSection::new();
types.ty().function([], [ValType::I64]); // 0
types.ty().function([ValType::I64], [ValType::I64]); // 1
types
.ty()
.function([ValType::I64, ValType::I64], [ValType::I64]); // 2
types
.ty()
.function([ValType::I64, ValType::I64, ValType::I64], [ValType::I64]); // 3
types
.ty()
.function([ValType::I32, ValType::I32], [ValType::I64]); // 4
let mut imports = ImportSection::new();
imports.import(
"env",
"memory",
MemoryType {
minimum: 1,
maximum: None,
memory64: false,
shared: false,
page_size_log2: None,
},
);
imports.import("env", "nulang_alloc", EntityType::Function(TY_VOID_TO_I64)); // placeholder type — rebuilt in rebuild_imports()
imports.import(
"env",
"nulang_dispatch",
EntityType::Function(TY_VOID_TO_I64),
); // placeholder type — rebuilt in rebuild_imports()
imports.import("env", "log", EntityType::Function(TY_I32I32_TO_I64));
imports.import("env", "io_print", EntityType::Function(TY_I32I32_TO_I64));
imports.import("env", "io_read", EntityType::Function(TY_VOID_TO_I64));
// Placeholder import type indices are fixed up in `rebuild_imports()`
// after the type section is finalized, so the constructor uses
// provisional types here.
WasmBackend {
types,
imports,
functions: FunctionSection::new(),
globals: GlobalSection::new(),
exports: ExportSection::new(),
codes: CodeSection::new(),
data: DataSection::new(),
string_data: Vec::new(),
interned: HashMap::new(),
func_index_map: HashMap::new(),
next_func_idx: FUNC_IMPORT_COUNT,
func_types: HashMap::new(),
next_type_idx: TY_FIXED_COUNT,
field_map: HashMap::new(),
foreign_functions: Vec::new(),
uses_actor_ops: false,
state_field_map: HashMap::new(),
actor_state_defaults: HashMap::new(),
behavior_param_counts: Vec::new(),
module_function_count: 0,
}
}
/// Intern a string into the data segment. Returns (offset, len) in
/// the data section. The WASM module's memory must be initialized
/// with this data at the given offset.
fn intern_string(&mut self, s: &str) -> (u32, u32) {
if let Some(&entry) = self.interned.get(s) {
return entry;
}
let offset = self.string_data.len() as u32;
let len = s.len() as u32;
self.string_data.extend_from_slice(s.as_bytes());
// Null-terminate so the host `str_concat` helper can recover each
// string's length with a `strlen` scan. The value's offset and the
// explicit `len` reported to `io_print` are unchanged by the byte.
self.string_data.push(0);
self.interned.insert(s.to_string(), (offset, len));
(offset, len)
}
// ── Compile ───────────────────────────────────────────────────
pub fn compile(&mut self, mir: &mir::Module, _module_name: &str) -> NuResult<Vec<u8>> {
self.foreign_functions = mir.foreign_functions.clone();
// Pre-scan: build the module-wide record field name → slot index map
// (mirrors the AOT backend) so Record literals and LoadFieldNamed agree.
let mut field_map: std::collections::HashMap<String, u8> = std::collections::HashMap::new();
let mut next_field_id: u8 = 0;
for func in mir.functions.iter().chain(mir.behaviors.iter()) {
for block in &func.blocks {
for stmt in &block.stmts {
collect_wasm_fields(stmt, &mut field_map, &mut next_field_id);
}
}
}
self.field_map = field_map;
// Pre-scan: actor machinery. Collect state fields, actor state
// defaults, behavior arities, and mark the module as using actor
// ops (gates the globals section + entry mailbox drain).
self.state_field_map.clear();
self.actor_state_defaults.clear();
self.behavior_param_counts = mir.behaviors.iter().map(|b| b.params.len()).collect();
self.module_function_count = mir.functions.len();
let mut next_state_slot: u8 = 1;
fn collect_state(
map: &mut std::collections::HashMap<String, u8>,
next_slot: &mut u8,
name: &str,
) {
map.entry(name.to_string()).or_insert_with(|| {
let s = *next_slot;
*next_slot = next_slot.saturating_add(1);
s
});
}
for meta in &mir.actor_metadata {
let first = meta.behavior_indices.first().copied();
let defaults: Vec<(String, crate::bytecode::Constant)> = meta
.state_defaults
.iter()
.map(|(n, c)| (n.clone(), c.clone()))
.collect();
if let Some(first) = first {
self.actor_state_defaults.insert(first, defaults);
}
for (name, _) in &meta.state_defaults {
collect_state(&mut self.state_field_map, &mut next_state_slot, name);
}
}
// Closure pre-scan: the WASM backend does not currently support
// closures (first-class functions). Return a compilation error so
// callers (like the differential fuzzer) know it's unsupported.
for func in mir.functions.iter().chain(mir.behaviors.iter()) {
for block in &func.blocks {
for stmt in &block.stmts {
if let Stmt::Assign { op, .. } = stmt {
if let RValue::Call {
func: FuncRef::Local(_),
..
} = op
{
return Err(crate::types::NuError::VMError {
msg: "WASM backend does not support closures (FuncRef::Local)"
.into(),
span: crate::types::Span::default(),
});
}
// Reject RValues the standalone WASM runtime has no
// machinery for — they previously silently compiled
// to nil. Fail loudly at compile time instead.
// (Send/Spawn/Ask/Receive*/State are supported via
// the guest-side actor emulation below.)
let unsupported = match op {
RValue::Migrate { .. }
| RValue::SignalWait { .. }
| RValue::Closure { .. } => true,
// Remote spawn (`spawn@node`) has no counterpart
// in a single-instance WASM module.
RValue::Spawn {
target_node: Some(_),
..
} => true,
// The borrow (`&`) and dereference operators touch
// reference capabilities which are compile-time
// only (no runtime representation in the WASM VM).
RValue::Unary(crate::ast::UnOp::Ref(_), _)
| RValue::Unary(crate::ast::UnOp::Deref, _) => true,
// IO.print/println/read and Array.length keep
// dedicated imports; every OTHER effect dispatches
// through nulang_dispatch (handled below — not
// unsupported).
RValue::Perform { .. } => false,
// Actor machinery is supported (guest-side).
RValue::Spawn { .. }
| RValue::Send { .. }
| RValue::Ask { .. }
| RValue::Receive
| RValue::ReceiveMatch { .. }
| RValue::ReceiveWait { .. }
| RValue::ReceiveCommit
| RValue::StateGet { .. } => false,
_ => false,
};
if unsupported {
return Err(crate::types::NuError::VMError {
msg: "WASM backend does not support this actor/effect operation"
.into(),
span: crate::types::Span::default(),
});
}
// Collect state fields (StateSet too — covered by the
// fallthrough below).
if let RValue::StateGet { field } = op {
collect_state(&mut self.state_field_map, &mut next_state_slot, field);
self.uses_actor_ops = true;
}
match op {
RValue::Send { .. }
| RValue::Spawn { .. }
| RValue::Ask { .. }
| RValue::Receive
| RValue::ReceiveMatch { .. }
| RValue::ReceiveWait { .. }
| RValue::ReceiveCommit => {
self.uses_actor_ops = true;
}
_ => {}
}
// Effect dispatch pre-scan: `perform Effect.op(args)`
// and async variants (`perform Inference.ask(prompt)`
// lowers to PerformAsync) intern the nulang_dispatch
// tag + compile-time JSON payload here (intern_string
// needs `&mut self`, compile_rvalue has only `&self`);
// dynamic args are a loud compile error.
match op {
RValue::Perform {
effect, op, args, ..
} => {
self.intern_effect_dispatch(effect, op, args, func)?;
}
RValue::PerformAsync {
effect_op, args, ..
} => {
let (effect, op) = effect_op
.split_once('.')
.unwrap_or((effect_op.as_str(), ""));
self.intern_effect_dispatch(effect, op, args, func)?;
}
_ => {}
}
self.intern_const_strings(op);
}
if let Stmt::StateSet { field, .. } = stmt {
collect_state(&mut self.state_field_map, &mut next_state_slot, field);
self.uses_actor_ops = true;
}
}
}
}
// Pre-intern FFI library/symbol strings so compile_rvalue (which has
// only `&self`) can look them up by content.
for ff in &mir.foreign_functions {
self.intern_string(&ff.library);
self.intern_string(&ff.symbol);
}
// Register function types.
for func in &mir.functions {
self.register_function_type(func);
}
for func in &mir.behaviors {
self.register_function_type(func);
}
// Rebuild imports with correct type indices now that types are
// finalized.
self.rebuild_imports();
// Compile functions.
for (idx, func) in mir.functions.iter().enumerate() {
self.compile_function(func, idx);
}
for (idx, func) in mir.behaviors.iter().enumerate() {
self.compile_function(func, mir.functions.len() + idx);
}
if !mir.functions.is_empty() {
// Export the actual entry function as `nulang_init`. Lifted closure
// functions are appended after `__main`, so `len()-1` can point at
// a closure carrying parameters, which the host rejects when it
// looks for a `() -> i64` export.
if let Some(main_in_module) = mir
.functions
.iter()
.position(|f| f.name == "__main" || f.name == "main")
{
let main_idx = FUNC_IMPORT_COUNT + main_in_module as u32;
self.exports
.export("nulang_init", ExportKind::Func, main_idx);
} else {
// Library module (no entry expression): export a synthetic
// `() -> i64` function returning nil, matching the interpreter
// (a program with only function definitions evaluates to nil).
// Falling back to the last module function could be a
// parameterized one, which the host can't call as `() -> i64`.
self.emit_nil_entry();
}
}
// Emit the actor-emulation globals (current actor + mailbox queue)
// only when the module actually uses actor machinery.
if self.uses_actor_ops {
let mut g = GlobalSection::new();
for _ in 0..3 {
g.global(
GlobalType {
val_type: ValType::I64,
mutable: true,
shared: false,
},
&ConstExpr::i64_const(0),
);
}
self.globals = g;
}
// Emit data segment.
if !self.string_data.is_empty() {
self.data
.active(0, &ConstExpr::i32_const(0), self.string_data.clone());
}
// Build module.
let mut module = Module::new();
module.section(&self.types);
module.section(&self.imports);
module.section(&self.functions);
if self.uses_actor_ops {
module.section(&self.globals);
}
module.section(&self.exports);
module.section(&self.codes);
module.section(&self.data);
Ok(module.finish())
}
fn intern_const_strings(&mut self, rvalue: &RValue) {
if let RValue::Const(crate::bytecode::Constant::String(s)) = rvalue {
self.intern_string(s);
}
}
/// Pre-scan interning for a dispatchable effect (`Perform` or the async
/// variant): validates constant args, computes the tag + JSON payload
/// (pool-builtin envelope or generic positional array), and interns both
/// so compile_rvalue can look them up by content.
fn intern_effect_dispatch(
&mut self,
effect: &str,
op: &str,
args: &[LocalId],
func: &mir::Function,
) -> NuResult<()> {
let dispatchable = !matches!(
(effect, op),
("IO", "print") | ("IO", "println") | ("IO", "read") | ("Array", "length")
);
if !dispatchable {
return Ok(());
}
let consts = args
.iter()
.map(|l| resolve_const(func, *l))
.collect::<Option<Vec<_>>>();
let Some(consts) = consts else {
return Err(crate::types::NuError::VMError {
msg: format!(
"WASM backend: effect {effect}.{op} requires constant \
args (dynamic effect args are not yet supported in \
the WASM backend)"
),
span: crate::types::Span::default(),
});
};
let encoded = consts.iter().map(json_arg).collect::<Option<Vec<_>>>();
let Some(encoded) = encoded else {
return Err(crate::types::NuError::VMError {
msg: format!(
"WASM backend: effect {effect}.{op} has an arg that \
is not JSON-encodable (int/float/bool/string/nil only)"
),
span: crate::types::Span::default(),
});
};
let (tag, payload) = pool_effect_contract(effect, op, &consts)
.map(|c| (c.tag.to_string(), c.payload))
.unwrap_or_else(|| (format!("{effect}.{op}"), format!("[{}]", encoded.join(","))));
self.intern_string(&tag);
self.intern_string(&payload);
Ok(())
}
fn rebuild_imports(&mut self) {
use wasm_encoder::ValType;
// Alloc: (i32) -> i32
let ty_alloc = self.ensure_type(vec![ValType::I32], vec![ValType::I32]);
// Dispatch: (i32, i32, i32, i32) -> i64 (bytes of effect result
// written to the ring buffer; 0 = no result/no handler). Mirrors
// io_read's length-return contract so the compiler lowering can
// read the result back from linear memory.
let ty_dispatch = self.ensure_type(vec![ValType::I32; 4], vec![ValType::I64]);
let mut imports = ImportSection::new();
imports.import(
"env",
"memory",
MemoryType {
minimum: 1,
maximum: None,
memory64: false,
shared: false,
page_size_log2: None,
},
);
imports.import("env", "nulang_alloc", EntityType::Function(ty_alloc));
imports.import("env", "nulang_dispatch", EntityType::Function(ty_dispatch));
imports.import("env", "log", EntityType::Function(TY_I32I32_TO_I64));
imports.import("env", "io_print", EntityType::Function(TY_I32I32_TO_I64));
imports.import("env", "io_read", EntityType::Function(TY_VOID_TO_I64));
imports.import("env", "str_concat", EntityType::Function(TY_I64I64_TO_I64));
imports.import("env", "str_eq", EntityType::Function(TY_I64I64_TO_I64));
imports.import("env", "pow", EntityType::Function(TY_I64I64_TO_I64));
imports.import("env", "arith_add", EntityType::Function(TY_I64I64_TO_I64));
imports.import("env", "arith_sub", EntityType::Function(TY_I64I64_TO_I64));
imports.import("env", "arith_mul", EntityType::Function(TY_I64I64_TO_I64));
imports.import("env", "arith_div", EntityType::Function(TY_I64I64_TO_I64));
imports.import("env", "arith_mod", EntityType::Function(TY_I64I64_TO_I64));
imports.import(
"env",
"arith_cmp",
EntityType::Function(TY_I64I64I64_TO_I64),
);
imports.import("env", "arith_neg", EntityType::Function(TY_I64_TO_I64));
imports.import("env", "arr_load", EntityType::Function(TY_I64I64_TO_I64));
// ffi_call_N(lib, sym, sig, arg0..argN-1) -> i64.
let ffi0 = self.ensure_type(vec![ValType::I64; 3], vec![ValType::I64]);
let ffi1 = self.ensure_type(vec![ValType::I64; 4], vec![ValType::I64]);
let ffi2 = self.ensure_type(vec![ValType::I64; 5], vec![ValType::I64]);
let ffi3 = self.ensure_type(vec![ValType::I64; 6], vec![ValType::I64]);
let ffi4 = self.ensure_type(vec![ValType::I64; 7], vec![ValType::I64]);
imports.import("env", "ffi_call_0", EntityType::Function(ffi0));
imports.import("env", "ffi_call_1", EntityType::Function(ffi1));
imports.import("env", "ffi_call_2", EntityType::Function(ffi2));
imports.import("env", "ffi_call_3", EntityType::Function(ffi3));
imports.import("env", "ffi_call_4", EntityType::Function(ffi4));
// Keep this new import at the end so existing function indices stay stable.
imports.import("env", "arith_fneg", EntityType::Function(TY_I64_TO_I64));
self.imports = imports;
}
fn ensure_type(&mut self, params: Vec<ValType>, results: Vec<ValType>) -> u32 {
// Always add a new type — simple, correct, minimal overhead.
let idx = self.next_type_idx;
self.next_type_idx += 1;
if results.is_empty() {
self.types.ty().function(params, []);
} else {
self.types.ty().function(params, results);
}
idx
}
// ── Function type registration ─────────────────────────────────
fn register_function_type(&mut self, func: &mir::Function) {
let count = func.params.len() + func.captures.len();
let param_types: Vec<ValType> = vec![ValType::I64; count];
if self.func_types.contains_key(¶m_types) {
return;
}
let type_idx = self.next_type_idx;
self.next_type_idx += 1;
self.func_types.insert(param_types.clone(), type_idx);
if param_types.is_empty() {
self.types.ty().function([], [ValType::I64]);
} else {
self.types.ty().function(param_types, [ValType::I64]);
}
}
fn func_type_idx(&self, func: &mir::Function) -> u32 {
let count = func.params.len() + func.captures.len();
let param_types: Vec<ValType> = vec![ValType::I64; count];
self.func_types.get(¶m_types).copied().unwrap_or(0)
}
// ── Function compilation ───────────────────────────────────────
/// Emit a synthetic `() -> i64` function returning nil and export it as
/// `nulang_init` — the entry for a module with no `__main`/`main`.
fn emit_nil_entry(&mut self) {
let wasm_idx = self.next_func_idx;
self.next_func_idx += 1;
self.functions.function(TY_VOID_TO_I64);
let mut body = Function::new(vec![]);
body.instruction(&Instruction::I64Const(value_layout::TAG_NIL as i64));
body.instruction(&Instruction::End); // function end
self.codes.function(&body);
self.exports
.export("nulang_init", ExportKind::Func, wasm_idx);
}
fn compile_function(&mut self, func: &mir::Function, mir_idx: usize) {
let wasm_idx = self.next_func_idx;
self.next_func_idx += 1;
self.func_index_map.insert(mir_idx, wasm_idx);
self.functions.function(self.func_type_idx(func));
let _local_count = func.locals.len() + func.params.len() + func.captures.len();
let wasm_locals: Vec<_> = vec![(256u32, ValType::I64)];
let mut body = Function::new(wasm_locals);
let block_order: Vec<BlockId> = (0..func.blocks.len() as u32).map(BlockId).collect();
let mut labels: HashMap<BlockId, u32> = HashMap::new();
for (li, &bid) in block_order.iter().enumerate() {
labels.insert(bid, li as u32);
}
let vec_loops = crate::mir_wasm_simd::find_vectorizable_loops(func);
let vec_body_to_loop: HashMap<BlockId, &crate::mir_wasm_simd::VecLoop> =
vec_loops.iter().map(|l| (l.body, l)).collect();
let state_local = 251u32;
body.instruction(&Instruction::I64Const(0));
body.instruction(&Instruction::LocalSet(state_local));
body.instruction(&Instruction::Loop(BlockType::Empty));
for _ in &block_order {
body.instruction(&Instruction::Block(BlockType::Empty));
}
body.instruction(&Instruction::LocalGet(state_local));
body.instruction(&Instruction::I32WrapI64);
let targets: Vec<u32> = (0..block_order.len() as u32).collect();
body.instruction(&Instruction::BrTable(
std::borrow::Cow::Owned(targets.clone()),
targets.last().copied().unwrap_or(0),
));
for (li, &bid) in block_order.iter().enumerate() {
let li = li as u32;
body.instruction(&Instruction::End); // end block
let block = &func.blocks[bid.0 as usize];
if let Some(vloop) = vec_body_to_loop.get(&bid) {
self.compile_simd_body(&mut body, vloop, func);
} else {
for stmt in &block.stmts {
self.compile_stmt(&mut body, stmt, func);
}
}
match &block.terminator {
Terminator::Return(Some(l)) => {
// The entry function drains the mailbox on return so
// fire-and-forget sends have their effects before the
// program result is observed (any return point ends the
// program — mirroring scheduler-driven mailbox processing
// to quiescence).
if self.uses_actor_ops && self.is_entry_function(func) {
self.emit_mailbox_drain(&mut body);
}
body.instruction(&Instruction::LocalGet(self.mir_local(l, func)));
body.instruction(&Instruction::Return);
}
Terminator::Return(None) => {
if self.uses_actor_ops && self.is_entry_function(func) {
self.emit_mailbox_drain(&mut body);
}
body.instruction(&Instruction::I64Const(crate::value_layout::TAG_UNIT as i64));
body.instruction(&Instruction::Return);
}
Terminator::Jump(t) => {
let tl = labels.get(t).copied().unwrap_or(0);
if tl > li {
body.instruction(&Instruction::Br(tl - li - 1));
} else {
body.instruction(&Instruction::I64Const(tl as i64));
body.instruction(&Instruction::LocalSet(state_local));
body.instruction(&Instruction::Br(
(block_order.len() - 1 - li as usize) as u32,
));
}
}
Terminator::Branch { cond, then_, else_ } => {
body.instruction(&Instruction::LocalGet(self.mir_local(cond, func)));
body.instruction(&Instruction::I64Const(
crate::value_layout::tag_bool(false) as i64
));
body.instruction(&Instruction::I64Ne);
body.instruction(&Instruction::If(BlockType::Empty));
let tl = labels.get(then_).copied().unwrap_or(0);
if tl > li {
body.instruction(&Instruction::Br(tl - li));
} else {
body.instruction(&Instruction::I64Const(tl as i64));
body.instruction(&Instruction::LocalSet(state_local));
body.instruction(&Instruction::Br(
(block_order.len() - li as usize) as u32,
));
}
body.instruction(&Instruction::Else);
let el = labels.get(else_).copied().unwrap_or(0);
if el > li {
body.instruction(&Instruction::Br(el - li));
} else {
body.instruction(&Instruction::I64Const(el as i64));
body.instruction(&Instruction::LocalSet(state_local));
body.instruction(&Instruction::Br(
(block_order.len() - li as usize) as u32,
));
}
body.instruction(&Instruction::End); // end If
}
Terminator::Resume(_) | Terminator::Unterminated => {
body.instruction(&Instruction::I64Const(crate::value_layout::TAG_NIL as i64));
body.instruction(&Instruction::Return);
}
}
}
body.instruction(&Instruction::End); // end Loop