-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathupdate.rs
More file actions
2346 lines (2268 loc) · 93.1 KB
/
Copy pathupdate.rs
File metadata and controls
2346 lines (2268 loc) · 93.1 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
//! Per-tick process, snapshot, lifecycle-action, and timer runtime emission.
use std::collections::HashMap;
use wasm_encoder::{BlockType, Function, HeapType, Instruction, RefType, ValType};
use crate::{
abi::AbiImportId,
ast::{ActionKind, Program, StateField, ValueId},
semantic::SemanticModel,
stdlib::{
CoreTypeId, RuntimeRepresentation, StdlibFieldId, StdlibStateProvider,
StdlibStateProviderId, StdlibTypeId,
},
wasm_ir,
};
use super::{
GcLayout, STATE_TYPE, Type,
data_plan::StringPool,
emit_result_error, emit_typed_struct_get,
global_plan::{ATTACH_PREPARED, ATTACH_READY, ATTACH_REJECTED, RuntimeGlobals},
imports::Abi,
managed_state_reads::ManagedStateReadCache,
memarg,
memory_plan::RuntimeScratch,
pointer_prefixes::{
PointerPrefixPlan, PrefixEmissionContext, PrefixEmissionState, PrefixLocals,
},
semantic_type, state_storage_index, struct_field_type, value_type,
};
/// Per-tick runtime view of the completed backend plans.
pub(super) struct UpdateContext<'a> {
pub standard_library: &'a crate::stdlib::StandardLibrary,
pub abi: &'a Abi,
pub gc: &'a GcLayout,
pub failure_payloads: &'a super::failure_payload::FailurePayloadDemand,
pub runtime_helpers: &'a super::RuntimeHelperPlan,
pub runtime_globals: RuntimeGlobals,
pub provider_values: &'a HashMap<StdlibStateProviderId, u32>,
pub semantics: &'a crate::semantic::SemanticModel,
pub managed: &'a crate::managed::ManagedBindingPlan,
pub managed_state_reads: &'a ManagedStateReadCache,
pub pointer_prefixes: &'a PointerPrefixPlan,
pub scratch: RuntimeScratch,
pub explicit_shape_selection: bool,
pub globals: &'a HashMap<ValueId, u32>,
pub global_types: &'a HashMap<ValueId, Type>,
pub attachment_globals: &'a [ValueId],
pub attempt_globals: &'a [ValueId],
pub scoped_globals: &'a crate::ScopedGlobalAnalysis,
pub process_names: &'a [&'a str],
pub provider_attach: Option<ProviderAttach>,
pub provider_alternatives: &'a [ProviderAlternative<'a>],
pub provider_preparation: Option<ProviderPreparation>,
}
pub(super) struct ProviderAlternative<'a> {
pub provider: StdlibStateProviderId,
pub declaration: &'a StdlibStateProvider,
pub source_processes: &'a [String],
pub attachment: Option<ProviderAttach>,
}
#[derive(Clone, Copy)]
pub(super) struct ProviderAttach {
pub init: u32,
pub poll: u32,
pub frame_global: u32,
pub frame_type: u32,
pub completion_field: u32,
/// Synchronous provider-owned mapping validation. When it returns false,
/// the logical attachment ends and ordinary discovery starts again while
/// retaining the still-open host process.
pub validation: Option<u32>,
}
#[derive(Clone, Copy)]
struct ProviderValidation {
function: u32,
provider_global: u32,
}
#[derive(Clone, Copy)]
pub(super) struct ProviderPreparation {
pub init: u32,
pub poll: u32,
pub frame_global: u32,
pub frame_type: u32,
pub completion_field: u32,
pub value_global: u32,
pub value_type: Type,
pub ready_global: u32,
}
pub(super) struct StatePollFunctions<'a> {
pub reads: &'a [u32],
pub transforms: &'a [Option<u32>],
}
#[derive(Clone, Copy)]
pub(super) enum PredicateState {
Unavailable,
Local(u32),
Global(u32),
}
#[derive(Clone, Copy)]
struct StateFieldPoll {
field: ValueId,
read_function: u32,
transform_function: Option<u32>,
poll_result_local: u32,
}
struct SnapshotPollContext<'a> {
program: &'a Program,
candidate_state: u32,
poll_result_locals: HashMap<ValueId, u32>,
pointer_prefix_locals: &'a PrefixLocals,
pointer_emission: PrefixEmissionContext<'a>,
lowering: &'a UpdateContext<'a>,
}
#[derive(Clone, Copy)]
struct ProcessSelectionLocals {
result: u32,
capacity: u32,
count: u32,
index: u32,
required_pages: u32,
pid: u32,
}
fn emit_process_attachment(
function: &mut Function,
strings: &StringPool,
actions: &HashMap<ActionKind, u32>,
selection_locals: Option<ProcessSelectionLocals>,
newly_attached: u32,
lowering: &UpdateContext<'_>,
) {
let Some(selector) = actions.get(&ActionKind::SelectProcess).copied() else {
emit_default_process_attachment(function, strings, newly_attached, lowering);
return;
};
emit_selected_process_attachment(
function,
strings,
selector,
selection_locals.expect("selectProcess has selection locals"),
newly_attached,
lowering,
);
}
fn emit_default_process_attachment(
function: &mut Function,
strings: &StringPool,
newly_attached: u32,
lowering: &UpdateContext<'_>,
) {
let globals = lowering.runtime_globals;
function
.instruction(&Instruction::GlobalGet(globals.process))
.instruction(&Instruction::I64Eqz)
.instruction(&Instruction::If(BlockType::Empty));
for (process_index, process) in lowering.process_names.iter().enumerate() {
let (process_ptr, process_len) = strings.get(process);
function
.instruction(&Instruction::GlobalGet(globals.process))
.instruction(&Instruction::I64Eqz)
.instruction(&Instruction::If(BlockType::Empty))
.instruction(&Instruction::I32Const(process_ptr as i32))
.instruction(&Instruction::I32Const(process_len as i32))
.instruction(&Instruction::Call(
lowering.abi.function(AbiImportId::ProcessAttach),
))
.instruction(&Instruction::GlobalSet(globals.process))
.instruction(&Instruction::GlobalGet(globals.process))
.instruction(&Instruction::I64Eqz)
.instruction(&Instruction::If(BlockType::Empty))
.instruction(&Instruction::Else)
.instruction(&Instruction::I32Const(process_index as i32))
.instruction(&Instruction::GlobalSet(globals.process_name))
.instruction(&Instruction::I32Const(1))
.instruction(&Instruction::LocalSet(newly_attached))
.instruction(&Instruction::End)
.instruction(&Instruction::End);
}
function.instruction(&Instruction::End);
}
fn emit_selected_process_attachment(
function: &mut Function,
strings: &StringPool,
selector: u32,
locals: ProcessSelectionLocals,
newly_attached: u32,
lowering: &UpdateContext<'_>,
) {
let globals = lowering.runtime_globals;
let abi = lowering.abi;
let length_pointer = lowering.scratch.settings_length.start();
let list_pointer = lowering.scratch.host_strings_start;
// The zero-capacity sizing call still receives a non-null aligned
// one-past pointer, matching Rust's empty-slice validity requirements.
let empty_list_pointer = list_pointer;
// Reserve enough headroom for the page-rounding calculation below.
let maximum_count = (u32::MAX - list_pointer as u32) / 8;
let result = lowering
.semantics
.action_result(ActionKind::SelectProcess)
.expect("checked selectProcess has a result type");
let crate::types::TypeKind::Result { layout, .. } = lowering.semantics.types().kind(result)
else {
unreachable!("selectProcess has a fallible boolean ABI result")
};
let result_struct = lowering.gc.index(Type::Result(*layout));
function
.instruction(&Instruction::GlobalGet(globals.process))
.instruction(&Instruction::I64Eqz)
.instruction(&Instruction::If(BlockType::Empty));
for (process_index, process) in lowering.process_names.iter().enumerate() {
let (process_ptr, process_len) = strings.get(process);
function
.instruction(&Instruction::GlobalGet(globals.process))
.instruction(&Instruction::I64Eqz)
.instruction(&Instruction::If(BlockType::Empty))
// First query only obtains the complete candidate count.
.instruction(&Instruction::I32Const(length_pointer))
.instruction(&Instruction::I32Const(0))
.instruction(&Instruction::I32Store(memarg()))
.instruction(&Instruction::I32Const(process_ptr as i32))
.instruction(&Instruction::I32Const(process_len as i32))
.instruction(&Instruction::I32Const(empty_list_pointer))
.instruction(&Instruction::I32Const(length_pointer))
.instruction(&Instruction::Call(
abi.function(AbiImportId::ProcessListByName),
))
.instruction(&Instruction::If(BlockType::Empty))
.instruction(&Instruction::I32Const(length_pointer))
.instruction(&Instruction::I32Load(memarg()))
.instruction(&Instruction::LocalTee(locals.capacity))
.instruction(&Instruction::I32Const(maximum_count as i32))
.instruction(&Instruction::I32LeU)
.instruction(&Instruction::If(BlockType::Empty))
// Grow the unbounded host staging area to hold every returned PID.
.instruction(&Instruction::LocalGet(locals.capacity))
.instruction(&Instruction::I32Const(3))
.instruction(&Instruction::I32Shl)
.instruction(&Instruction::I32Const(list_pointer))
.instruction(&Instruction::I32Add)
.instruction(&Instruction::I32Const(1))
.instruction(&Instruction::I32Sub)
.instruction(&Instruction::I32Const(16))
.instruction(&Instruction::I32ShrU)
.instruction(&Instruction::I32Const(1))
.instruction(&Instruction::I32Add)
.instruction(&Instruction::LocalTee(locals.required_pages))
.instruction(&Instruction::MemorySize(0))
.instruction(&Instruction::I32GtU)
.instruction(&Instruction::If(BlockType::Empty))
.instruction(&Instruction::LocalGet(locals.required_pages))
.instruction(&Instruction::MemorySize(0))
.instruction(&Instruction::I32Sub)
.instruction(&Instruction::MemoryGrow(0))
.instruction(&Instruction::I32Const(-1))
.instruction(&Instruction::I32Eq)
.instruction(&Instruction::If(BlockType::Empty))
.instruction(&Instruction::Return)
.instruction(&Instruction::End)
.instruction(&Instruction::End)
// Re-query into the correctly sized buffer. If the process set
// grew between calls, ignore the partial list until the next tick.
.instruction(&Instruction::I32Const(length_pointer))
.instruction(&Instruction::LocalGet(locals.capacity))
.instruction(&Instruction::I32Store(memarg()))
.instruction(&Instruction::I32Const(process_ptr as i32))
.instruction(&Instruction::I32Const(process_len as i32))
.instruction(&Instruction::I32Const(list_pointer))
.instruction(&Instruction::I32Const(length_pointer))
.instruction(&Instruction::Call(
abi.function(AbiImportId::ProcessListByName),
))
.instruction(&Instruction::If(BlockType::Empty))
.instruction(&Instruction::I32Const(length_pointer))
.instruction(&Instruction::I32Load(memarg()))
.instruction(&Instruction::LocalTee(locals.count))
.instruction(&Instruction::LocalGet(locals.capacity))
.instruction(&Instruction::I32LeU)
.instruction(&Instruction::If(BlockType::Empty))
.instruction(&Instruction::I32Const(0))
.instruction(&Instruction::LocalSet(locals.index))
.instruction(&Instruction::Block(BlockType::Empty))
.instruction(&Instruction::Loop(BlockType::Empty))
.instruction(&Instruction::GlobalGet(globals.process))
.instruction(&Instruction::I64Eqz)
.instruction(&Instruction::I32Eqz)
.instruction(&Instruction::BrIf(1))
.instruction(&Instruction::LocalGet(locals.index))
.instruction(&Instruction::LocalGet(locals.count))
.instruction(&Instruction::I32GeU)
.instruction(&Instruction::BrIf(1))
.instruction(&Instruction::I32Const(list_pointer))
.instruction(&Instruction::LocalGet(locals.index))
.instruction(&Instruction::I32Const(3))
.instruction(&Instruction::I32Shl)
.instruction(&Instruction::I32Add)
.instruction(&Instruction::I64Load(memarg()))
.instruction(&Instruction::LocalSet(locals.pid))
.instruction(&Instruction::LocalGet(locals.pid))
.instruction(&Instruction::Call(
abi.function(AbiImportId::ProcessAttachByPid),
))
.instruction(&Instruction::GlobalSet(globals.process))
.instruction(&Instruction::GlobalGet(globals.process))
.instruction(&Instruction::I64Eqz)
.instruction(&Instruction::If(BlockType::Empty))
.instruction(&Instruction::Else)
.instruction(&Instruction::I32Const(process_index as i32))
.instruction(&Instruction::GlobalSet(globals.process_name))
.instruction(&Instruction::Call(selector))
.instruction(&Instruction::LocalSet(locals.result))
// Both an uncaught error and `false` reject only this candidate.
.instruction(&Instruction::LocalGet(locals.result))
.instruction(&Instruction::StructGet {
struct_type_index: result_struct,
field_index: 1,
})
.instruction(&Instruction::If(BlockType::Empty));
emit_reject_process_candidate(function, lowering);
function
.instruction(&Instruction::Else)
.instruction(&Instruction::LocalGet(locals.result))
.instruction(&Instruction::RefAsNonNull);
emit_typed_struct_get(function, result_struct, 0, Type::Bool);
function
.instruction(&Instruction::If(BlockType::Empty))
.instruction(&Instruction::I32Const(1))
.instruction(&Instruction::LocalSet(newly_attached))
.instruction(&Instruction::Else);
emit_reject_process_candidate(function, lowering);
function
.instruction(&Instruction::End)
.instruction(&Instruction::End)
.instruction(&Instruction::End)
.instruction(&Instruction::LocalGet(locals.index))
.instruction(&Instruction::I32Const(1))
.instruction(&Instruction::I32Add)
.instruction(&Instruction::LocalSet(locals.index))
.instruction(&Instruction::Br(0))
.instruction(&Instruction::End)
.instruction(&Instruction::End)
.instruction(&Instruction::End)
.instruction(&Instruction::End)
.instruction(&Instruction::End)
.instruction(&Instruction::End)
.instruction(&Instruction::End);
}
function.instruction(&Instruction::End);
}
fn emit_reject_process_candidate(function: &mut Function, lowering: &UpdateContext<'_>) {
let globals = lowering.runtime_globals;
function
.instruction(&Instruction::GlobalGet(globals.process))
.instruction(&Instruction::Call(
lowering.abi.function(AbiImportId::ProcessDetach),
))
.instruction(&Instruction::I64Const(0))
.instruction(&Instruction::GlobalSet(globals.process))
.instruction(&Instruction::I32Const(-1))
.instruction(&Instruction::GlobalSet(globals.process_name));
}
fn emit_attached_tick_rate(
function: &mut Function,
program: &Program,
lowering: &UpdateContext<'_>,
) {
function
.instruction(&Instruction::F64Const(program.attached_tick_rate().into()))
.instruction(&Instruction::Call(
lowering.abi.function(AbiImportId::RuntimeSetTickRate),
));
}
/// Ends one source-visible state-provider attachment. Emulator providers can
/// lose their guest-memory mapping while the host process remains open, so
/// process-handle teardown is deliberately separate from attachment-owned
/// state, continuations, lifecycle events, and polling policy.
fn emit_attachment_teardown(
function: &mut Function,
program: &Program,
actions: &HashMap<ActionKind, u32>,
cancellation_region: Option<wasm_ir::CancellationRegion>,
attachment_transition: u32,
detach_process: bool,
lowering: &UpdateContext<'_>,
) {
let globals = lowering.runtime_globals;
let state = program.state.as_ref().expect("update requires state");
if detach_process {
function
.instruction(&Instruction::GlobalGet(globals.process))
.instruction(&Instruction::Call(
lowering.abi.function(AbiImportId::ProcessDetach),
))
.instruction(&Instruction::I64Const(0))
.instruction(&Instruction::GlobalSet(globals.process))
.instruction(&Instruction::I32Const(-1))
.instruction(&Instruction::GlobalSet(globals.process_name));
if let Some(pointer_size) = globals.process_pointer_size {
function
.instruction(&Instruction::I32Const(0))
.instruction(&Instruction::GlobalSet(pointer_size));
}
}
function
.instruction(&Instruction::I32Const(0))
.instruction(&Instruction::GlobalSet(globals.state_ready))
.instruction(&Instruction::I32Const(0))
.instruction(&Instruction::GlobalSet(globals.attach_ready));
if let Some(provider_global) = globals.provider_value {
let provider_type = lowering
.semantics
.state_provider()
.map(|provider| {
lowering
.standard_library
.state_provider(provider)
.process_type
})
.expect("provider storage requires a resolved provider");
emit_provider_default(function, provider_type, lowering);
function.instruction(&Instruction::GlobalSet(provider_global));
}
for alternative in lowering.provider_alternatives {
let Some(provider_global) = lowering.provider_values.get(&alternative.provider).copied()
else {
continue;
};
emit_provider_default(function, alternative.declaration.process_type, lowering);
function.instruction(&Instruction::GlobalSet(provider_global));
}
if let (Some(frame_global), Some(ProviderAttach { frame_type, .. })) =
(globals.provider_attachment_frame, lowering.provider_attach)
{
function
.instruction(&Instruction::RefNull(HeapType::Concrete(frame_type)))
.instruction(&Instruction::GlobalSet(frame_global));
}
for attachment in lowering
.provider_alternatives
.iter()
.filter_map(|alternative| alternative.attachment)
{
function
.instruction(&Instruction::RefNull(HeapType::Concrete(
attachment.frame_type,
)))
.instruction(&Instruction::GlobalSet(attachment.frame_global));
}
if let Some(preparation) = lowering.provider_preparation {
function
.instruction(&Instruction::RefNull(HeapType::Concrete(
preparation.frame_type,
)))
.instruction(&Instruction::GlobalSet(preparation.frame_global));
emit_storage_default(function, lowering.gc.val_type(preparation.value_type));
function
.instruction(&Instruction::GlobalSet(preparation.value_global))
.instruction(&Instruction::I32Const(0))
.instruction(&Instruction::GlobalSet(preparation.ready_global));
}
if let (Some(selected), Some(provider_value)) =
(globals.selected_provider, state.provider_value)
{
let provider_type = lowering.global_types[&provider_value];
emit_storage_default(function, lowering.gc.val_type(provider_type));
function.instruction(&Instruction::GlobalSet(selected));
}
for value in lowering.attachment_globals {
let ty = lowering.global_types[value];
if !ty.has_runtime_value() {
continue;
}
emit_storage_default(function, lowering.gc.val_type(ty));
function.instruction(&Instruction::GlobalSet(lowering.globals[value]));
}
if let Some(region) = cancellation_region {
emit_cancel_region(function, region, lowering.gc, globals);
}
function
.instruction(&Instruction::F64Const(program.detached_tick_rate().into()))
.instruction(&Instruction::Call(
lowering.abi.function(AbiImportId::RuntimeSetTickRate),
));
if let Some(detach) = actions.get(&ActionKind::OnDetach) {
function
.instruction(&Instruction::LocalGet(attachment_transition))
.instruction(&Instruction::If(BlockType::Empty))
.instruction(&Instruction::Call(*detach))
.instruction(&Instruction::End);
}
}
pub(super) fn compile_update(
program: &Program,
strings: &StringPool,
state_functions: StatePollFunctions<'_>,
actions: &HashMap<ActionKind, u32>,
refresh_settings: Option<u32>,
cancellation_region: Option<wasm_ir::CancellationRegion>,
lowering: &UpdateContext<'_>,
) -> Function {
let abi = lowering.abi;
let globals = lowering.runtime_globals;
let semantics = lowering.semantics;
let has_game_time = actions.contains_key(&ActionKind::GameTime);
let has_timer_lifecycle = globals.observed_timer_state.is_some();
let has_timer_decisions = actions.keys().any(|action| {
matches!(
action,
ActionKind::Start
| ActionKind::Split
| ActionKind::Reset
| ActionKind::IsLoading
| ActionKind::GameTime
)
});
let timer_state = 0;
let nullable_bool = 1;
let attachment_transition = 2;
let duration_local = 3;
let candidate_state = if has_game_time { 4 } else { 3 };
let first_poll_result = candidate_state + 1;
let mut locals = vec![(3, ValType::I32)];
if has_game_time {
locals.push((
1,
ValType::Ref(RefType {
nullable: true,
heap_type: HeapType::Concrete(lowering.gc.standard_index(StdlibTypeId::Duration)),
}),
));
}
locals.push((
1,
ValType::Ref(RefType {
nullable: true,
heap_type: HeapType::Concrete(STATE_TYPE),
}),
));
let state = program.state.as_ref().unwrap();
let all_fields = state.all_fields().collect::<Vec<_>>();
let read_indices = all_fields
.iter()
.enumerate()
.map(|(index, field)| (field.id, index))
.collect::<HashMap<_, _>>();
let poll_result_locals = read_indices
.iter()
.map(|(field, index)| (*field, first_poll_result + *index as u32))
.collect();
for field in &all_fields {
let poll_result = semantic_type(
semantics
.state_poll_result(field.id)
.expect("checked state fields have poll-result types"),
semantics,
);
locals.push((1, lowering.gc.val_type(poll_result)));
}
let first_selection_local = first_poll_result + all_fields.len() as u32;
let selection_locals = actions.contains_key(&ActionKind::SelectProcess).then(|| {
let result = semantics
.action_result(ActionKind::SelectProcess)
.expect("checked selectProcess has a result type");
locals.push((
1,
lowering
.gc
.val_type(semantic_type(result, lowering.semantics)),
));
locals.push((4, ValType::I32));
locals.push((1, ValType::I64));
ProcessSelectionLocals {
result: first_selection_local,
capacity: first_selection_local + 1,
count: first_selection_local + 2,
index: first_selection_local + 3,
required_pages: first_selection_local + 4,
pid: first_selection_local + 5,
}
});
let first_prefix_local = first_selection_local + u32::from(selection_locals.is_some()) * 6;
let (prefix_local_declarations, pointer_prefix_locals) = lowering
.pointer_prefixes
.allocate_locals(first_prefix_local);
locals.extend(prefix_local_declarations);
let mut function = Function::new(locals);
let snapshot_poll = SnapshotPollContext {
program,
candidate_state,
poll_result_locals,
pointer_prefix_locals: &pointer_prefix_locals,
pointer_emission: PrefixEmissionContext {
plan: lowering.pointer_prefixes,
strings,
abi: lowering.abi,
process_global: lowering.runtime_globals.process,
process_pointer_size: lowering.runtime_globals.process_pointer_size,
abi_read: lowering.scratch.abi_read,
},
lowering,
};
function
.instruction(&Instruction::GlobalGet(globals.future_poll_epoch))
.instruction(&Instruction::I64Const(1))
.instruction(&Instruction::I64Add)
.instruction(&Instruction::GlobalSet(globals.future_poll_epoch));
if let Some(refresh_settings) = refresh_settings {
function.instruction(&Instruction::Call(refresh_settings));
}
if let Some(observed_timer_state) = globals.observed_timer_state {
emit_timer_lifecycle_events(
&mut function,
timer_state,
observed_timer_state,
actions,
lowering,
);
}
emit_process_attachment(
&mut function,
strings,
actions,
selection_locals,
attachment_transition,
lowering,
);
function
.instruction(&Instruction::GlobalGet(globals.process))
.instruction(&Instruction::I64Eqz)
.instruction(&Instruction::If(BlockType::Empty))
.instruction(&Instruction::Return)
.instruction(&Instruction::End);
if lowering.provider_alternatives.is_empty() && lowering.provider_attach.is_none() {
function
.instruction(&Instruction::LocalGet(attachment_transition))
.instruction(&Instruction::If(BlockType::Empty))
.instruction(&Instruction::F64Const(program.attached_tick_rate().into()))
.instruction(&Instruction::Call(
abi.function(AbiImportId::RuntimeSetTickRate),
))
.instruction(&Instruction::End);
}
function
.instruction(&Instruction::GlobalGet(globals.process))
.instruction(&Instruction::Call(abi.function(AbiImportId::ProcessIsOpen)))
.instruction(&Instruction::I32Eqz)
.instruction(&Instruction::If(BlockType::Empty))
// Only a process whose complete attachment initialization succeeded
// owns an onDetach event. Pending or rejected initialization is merely
// cancelled and cleared when that process closes.
.instruction(&Instruction::GlobalGet(globals.attach_ready))
.instruction(&Instruction::I32Const(ATTACH_READY))
.instruction(&Instruction::I32Eq)
.instruction(&Instruction::LocalSet(attachment_transition));
emit_attachment_teardown(
&mut function,
program,
actions,
cancellation_region,
attachment_transition,
true,
lowering,
);
function
.instruction(&Instruction::Return)
.instruction(&Instruction::End);
emit_native_pointer_size_detection(&mut function, strings, lowering);
if !lowering.provider_alternatives.is_empty() {
let selected = globals
.selected_provider
.expect("multi-provider state has selected-provider storage");
let enumeration = state
.provider_enum
.as_ref()
.expect("multi-provider state generates StateProvider");
for (variant_index, alternative) in lowering.provider_alternatives.iter().enumerate() {
function
.instruction(&Instruction::GlobalGet(selected))
.instruction(&Instruction::RefIsNull)
.instruction(&Instruction::If(BlockType::Empty));
let accepted = match alternative.declaration.processes {
crate::stdlib::StateProviderProcesses::Declared(names) => names.to_vec(),
crate::stdlib::StateProviderProcesses::SourceState => alternative
.source_processes
.iter()
.map(String::as_str)
.collect(),
};
let mut emitted_process = false;
for (index, name) in lowering.process_names.iter().enumerate() {
if !accepted.iter().any(|accepted| accepted == name) {
continue;
}
function
.instruction(&Instruction::GlobalGet(globals.process_name))
.instruction(&Instruction::I32Const(index as i32))
.instruction(&Instruction::I32Eq);
if emitted_process {
function.instruction(&Instruction::I32Or);
}
emitted_process = true;
}
debug_assert!(emitted_process, "every provider contributes a process name");
function.instruction(&Instruction::If(BlockType::Empty));
if let Some(attachment) = alternative.attachment {
function
.instruction(&Instruction::GlobalGet(attachment.frame_global))
.instruction(&Instruction::RefIsNull)
.instruction(&Instruction::If(BlockType::Empty));
// Callable providers discover their guest mapping cooperatively.
// Use the active cadence before the first poll: range discovery
// and signature scans intentionally perform bounded work per
// update and would otherwise take prohibitively long at the
// detached cadence. Mapping validation still owns the logical
// attachment boundary and restores the detached rate first.
emit_attached_tick_rate(&mut function, program, lowering);
function
.instruction(&Instruction::Call(attachment.init))
.instruction(&Instruction::GlobalSet(attachment.frame_global))
.instruction(&Instruction::End)
.instruction(&Instruction::GlobalGet(attachment.frame_global))
.instruction(&Instruction::RefAsNonNull)
.instruction(&Instruction::Call(attachment.poll))
.instruction(&Instruction::If(BlockType::Empty))
.instruction(&Instruction::GlobalGet(attachment.frame_global))
.instruction(&Instruction::StructGet {
struct_type_index: attachment.frame_type,
field_index: attachment.completion_field,
})
.instruction(&Instruction::GlobalSet(
lowering.provider_values[&alternative.provider],
))
.instruction(&Instruction::RefNull(HeapType::Concrete(
attachment.frame_type,
)))
.instruction(&Instruction::GlobalSet(attachment.frame_global));
emit_provider_selection(
&mut function,
variant_index,
enumeration,
selected,
lowering,
);
function.instruction(&Instruction::End);
} else {
debug_assert_eq!(
alternative.declaration.attachment,
crate::stdlib::StateProviderAttachment::Identity
);
emit_attached_tick_rate(&mut function, program, lowering);
emit_provider_selection(
&mut function,
variant_index,
enumeration,
selected,
lowering,
);
}
function
.instruction(&Instruction::End)
.instruction(&Instruction::End);
}
function
.instruction(&Instruction::GlobalGet(selected))
.instruction(&Instruction::RefIsNull)
.instruction(&Instruction::If(BlockType::Empty))
.instruction(&Instruction::Return)
.instruction(&Instruction::End);
// The selected alternative owns the logical attachment. Losing its
// private mapping ends that attachment even if the shared host process
// remains open; ordinary provider selection runs again next update.
for (variant_index, alternative) in lowering.provider_alternatives.iter().enumerate() {
let Some(attachment) = alternative.attachment else {
continue;
};
let Some(validation) = attachment.validation else {
continue;
};
function
.instruction(&Instruction::GlobalGet(selected))
.instruction(&Instruction::StructGet {
struct_type_index: lowering.gc.index(Type::Enum(enumeration.id)),
field_index: 0,
})
.instruction(&Instruction::I32Const(variant_index as i32))
.instruction(&Instruction::I32Eq)
.instruction(&Instruction::If(BlockType::Empty));
emit_provider_validation(
&mut function,
program,
actions,
cancellation_region,
ProviderValidation {
function: validation,
provider_global: lowering.provider_values[&alternative.provider],
},
attachment_transition,
lowering,
);
function.instruction(&Instruction::End);
}
}
if let (Some(provider_global), Some(provider_attach)) =
(globals.provider_value, lowering.provider_attach)
{
let provider_type = semantics
.state_provider()
.map(|provider| {
lowering
.standard_library
.state_provider(provider)
.process_type
})
.expect("provider storage requires a resolved provider");
emit_provider_unavailable(&mut function, provider_global, provider_type, lowering);
function.instruction(&Instruction::If(BlockType::Empty));
let ProviderAttach {
init,
poll,
frame_global,
frame_type,
completion_field,
..
} = provider_attach;
function
.instruction(&Instruction::GlobalGet(frame_global))
.instruction(&Instruction::RefIsNull)
.instruction(&Instruction::If(BlockType::Empty));
// Provider acquisition is cooperative and may scan only one bounded
// window or mapped range per host update. Raise the cadence before the
// future starts, both initially and after mapping invalidation.
emit_attached_tick_rate(&mut function, program, lowering);
function
.instruction(&Instruction::Call(init))
.instruction(&Instruction::GlobalSet(frame_global))
.instruction(&Instruction::End)
.instruction(&Instruction::GlobalGet(frame_global))
.instruction(&Instruction::RefAsNonNull)
.instruction(&Instruction::Call(poll))
.instruction(&Instruction::I32Eqz)
.instruction(&Instruction::If(BlockType::Empty))
.instruction(&Instruction::Return)
.instruction(&Instruction::End)
.instruction(&Instruction::GlobalGet(frame_global))
.instruction(&Instruction::StructGet {
struct_type_index: frame_type,
field_index: completion_field,
})
.instruction(&Instruction::GlobalSet(provider_global))
.instruction(&Instruction::RefNull(HeapType::Concrete(frame_type)))
.instruction(&Instruction::GlobalSet(frame_global));
function.instruction(&Instruction::End);
emit_provider_unavailable(&mut function, provider_global, provider_type, lowering);
function
.instruction(&Instruction::If(BlockType::Empty))
.instruction(&Instruction::Return)
.instruction(&Instruction::End);
if let Some(validation) = provider_attach.validation {
emit_provider_validation(
&mut function,
program,
actions,
cancellation_region,
ProviderValidation {
function: validation,
provider_global,
},
attachment_transition,
lowering,
);
}
}
if let Some(preparation) = lowering.provider_preparation {
function
.instruction(&Instruction::GlobalGet(preparation.ready_global))
.instruction(&Instruction::I32Eqz)
.instruction(&Instruction::If(BlockType::Empty))
.instruction(&Instruction::GlobalGet(preparation.frame_global))
.instruction(&Instruction::RefIsNull)
.instruction(&Instruction::If(BlockType::Empty))
.instruction(&Instruction::Call(preparation.init))
.instruction(&Instruction::GlobalSet(preparation.frame_global))
.instruction(&Instruction::End)
.instruction(&Instruction::GlobalGet(preparation.frame_global))
.instruction(&Instruction::RefAsNonNull)
.instruction(&Instruction::Call(preparation.poll))
.instruction(&Instruction::I32Eqz)
.instruction(&Instruction::If(BlockType::Empty))
.instruction(&Instruction::Return)
.instruction(&Instruction::End)
.instruction(&Instruction::GlobalGet(preparation.frame_global))
.instruction(&Instruction::StructGet {
struct_type_index: preparation.frame_type,
field_index: preparation.completion_field,
})
.instruction(&Instruction::GlobalSet(preparation.value_global))
.instruction(&Instruction::RefNull(HeapType::Concrete(
preparation.frame_type,
)))
.instruction(&Instruction::GlobalSet(preparation.frame_global))
.instruction(&Instruction::I32Const(1))
.instruction(&Instruction::GlobalSet(preparation.ready_global))
.instruction(&Instruction::End);
}
let automatic_shape = if lowering.explicit_shape_selection {
None
} else {
lowering.managed.automatic_shape.as_ref().filter(|plan| {
plan.evidence_fields.is_empty()
|| semantics.state_provider() == Some(crate::stdlib::StdlibStateProviderId::Unity)
})
};
if let Some(plan) = automatic_shape {
function
.instruction(&Instruction::GlobalGet(globals.attach_ready))
.instruction(&Instruction::I32Eqz)
.instruction(&Instruction::If(BlockType::Empty));
emit_automatic_shape_selection(&mut function, program, plan, lowering);
function
.instruction(&Instruction::GlobalGet(globals.attach_ready))
.instruction(&Instruction::I32Eqz)
.instruction(&Instruction::If(BlockType::Empty));
emit_automatic_shape_failure_report(&mut function, strings, program, plan, lowering);
function
.instruction(&Instruction::I32Const(ATTACH_REJECTED))
.instruction(&Instruction::GlobalSet(globals.attach_ready))
.instruction(&Instruction::Return)
.instruction(&Instruction::End)
.instruction(&Instruction::I32Const(
if actions.contains_key(&ActionKind::OnAttach) {
ATTACH_PREPARED
} else {
ATTACH_READY
},
))
.instruction(&Instruction::GlobalSet(globals.attach_ready))
.instruction(&Instruction::End);
if let Some(on_attach) = actions.get(&ActionKind::OnAttach) {
function
.instruction(&Instruction::GlobalGet(globals.attach_ready))
.instruction(&Instruction::I32Const(ATTACH_PREPARED))
.instruction(&Instruction::I32Eq)
.instruction(&Instruction::If(BlockType::Empty))
.instruction(&Instruction::GlobalGet(globals.process))
.instruction(&Instruction::Call(*on_attach))
.instruction(&Instruction::I32Eqz)
.instruction(&Instruction::If(BlockType::Empty))
.instruction(&Instruction::Return)
.instruction(&Instruction::End);
emit_return_if_attachment_rejected(&mut function, globals);
if globals.while_attached_result.is_some() {
emit_reset_async_action_frame(&mut function, lowering.gc, globals);
}
function
.instruction(&Instruction::I32Const(ATTACH_READY))
.instruction(&Instruction::GlobalSet(globals.attach_ready))
.instruction(&Instruction::End);
}
} else if let Some(on_attach) = actions.get(&ActionKind::OnAttach) {
function
.instruction(&Instruction::GlobalGet(globals.attach_ready))
.instruction(&Instruction::I32Eqz)
.instruction(&Instruction::If(BlockType::Empty))
.instruction(&Instruction::GlobalGet(globals.process))
.instruction(&Instruction::Call(*on_attach))
.instruction(&Instruction::I32Eqz)
.instruction(&Instruction::If(BlockType::Empty))
.instruction(&Instruction::Return)
.instruction(&Instruction::End);
emit_return_if_attachment_rejected(&mut function, globals);
emit_managed_field_presence_validation(&mut function, program, lowering);