rhai 1.27.0

Embedded scripting for Rust
Documentation
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
#[cfg(feature = "no_std")]
use std::prelude::v1::*;

#[cfg(not(feature = "no_ast"))]
use crate::ast::{ASTNode, Expr, Stmt};
use crate::engine::KEYWORD_EVAL;
#[cfg(not(feature = "no_module"))]
use crate::module_resolvers::StaticModuleResolver;
use crate::{
    expose_under_internals, types::Token, Dynamic, FnAccess, ImmutableString, Shared, SharedModule,
};

use crate::grain::bytecode::CustomSyntaxSite;
use crate::grain::bytecode::{
    site_to_position, sites, AssignOp, Chain, Chunk, Code, Pools, Positions, Strings, Switch,
    TableError,
};
use crate::grain::format::{Caps, Sidecar};

/// _(internals)_ One compiled script function.
/// Exported under the `internals` feature only.
//
// Called by [`Op::Call`](crate::bytecode::Op::Call) directly, without going
// through Rhai's dispatch: the name is already an index into the same pool the
// call site used, so matching one is two integer comparisons rather than a
// hash and a module walk.
#[derive(Debug, Clone)]
pub struct Function {
    /// Index into the name pool.
    pub name: u32,
    /// Parameter names, in order, as name-pool indices.
    ///
    /// They become the callee's first locals, which is what makes them
    /// slot 0 upwards.
    pub params: Vec<u32>,
    /// Function access mode.
    pub access: FnAccess,
    /// The receiver type this function was declared for, as a name-pool index.
    ///
    /// `None` for an ordinary function, which is nearly all of them.
    pub this_type: Option<u32>,
    /// The function's [`Chunk`].
    pub chunk: Chunk,
}

impl Function {
    /// Disassemble the function into a human-readable string.
    #[cfg(feature = "internals")]
    pub fn disassemble(&self, program: &Program) -> String {
        format!(
            "{}{}{}({})",
            self.this_type.map_or("", |t| program.name(t).unwrap()),
            if self.this_type.is_some() { "!" } else { "" },
            program.name(self.name).unwrap(),
            self.params
                .iter()
                .map(|&p| program.name(p).unwrap())
                .collect::<Vec<_>>()
                .join(", "),
        )
    }
}

/// A shared [`Program`].
pub type SharedProgram = Shared<Program<'static>>;

/// A script [`AST`] compiled into bytecodes, ready to run against a [`Vm`]
/// through an [`Engine`].
///
/// Owns everything execution needs that is not the [`Engine`] itself, so the
/// original [`AST`] can be dropped after compiling. On a resource-constrained
/// embedded target, that is the whole point: the [`AST`] is the part whose cost
/// scales with the script's size.
///
/// # Residual Fragments
///
/// _Residuals_ is the exception, and the reason a [`Program`] is not always
/// serializable.
///
/// Fragments that Rhai's [`AST`] interpreter still has to evaluate are held as
/// [`AST`] nodes, which is precisely what Rhai Grain is here to remove.
///
/// The bytecodes format refuses to write out a [`Program`] that has any,
/// so nothing reaching a device can depend on them.
///
/// [`AST`]: crate::AST
/// [`Engine`]: crate::Engine
/// [`Vm`]: crate::grain::Vm
pub struct Program<'a> {
    /// The capabilities required by this program's instructions.
    caps: Caps,

    /// Every [Chunk]'s instructions, concatenated: main first, then each
    /// function. One buffer means one position table and one instruction
    /// address, so a device that fails reports a single number.
    code: Code<'a>,

    main: Chunk,

    /// Script functions compiled to chunks. Empty when none were compiled,
    /// which is when Rhai's own versions are carried in `lib` instead.
    functions: Vec<Function>,

    /// The deepest [Chunk]'s operand-stack need, cached.
    max_stack: u16,

    /// Whether any function was declared for a receiver type.
    ///
    /// Derived, not stored: [`Program::method`] is a linear scan on every method
    /// call, and typed-first selection would double it for the overwhelming
    /// majority of programs that have nothing typed to find.
    has_typed_methods: bool,

    /// Where each instruction came from, or [`Positions::Stripped`].
    ///
    /// Separable on purpose: a device is shipped the code and the host keeps
    /// the table, so an error arrives as an instruction address and is resolved
    /// where the source is. See [`crate::bytecode::Positions`].
    positions: Positions,

    /// Names the diagnostics that were compiled with this program.
    ///
    /// Survives [`Program::strip_positions`] and travels in the artifact, so a
    /// program that no longer holds its positions can still say which sidecar
    /// is the one that fits. See [`Program::debug_id`].
    debug_id: u128,

    #[cfg(not(feature = "no_ast"))]
    residuals: Vec<Expr>,

    /// Values `Op::Const` indexes. Deduplicated, so a constant repeated across
    /// the script is stored once.
    consts: Vec<Dynamic>,

    /// Every name the program mentions, as one borrowed blob.
    ///
    /// Nothing needs a `String` of its own. Call names, operators, getters and
    /// property keys go to Rhai as `&str`; a `Scope` entry name goes in as an
    /// `Identifier`, which is a `SmartString` and keeps a short name inline
    /// rather than on the heap. So the whole table is two allocations — the
    /// blob and the spans — and neither grows with how many names there are.
    names: Strings<'a>,

    /// Operator tokens the built-in lookup keys on. A `Token` does not fit an
    /// operand, and one script uses a handful of distinct operators however
    /// many times it mentions them.
    tokens: Vec<Token>,

    /// What each `x op= y` site needs, for the same reason.
    assign_ops: Vec<AssignOp>,

    /// The steps of each `a.b[i].c`. Out of the instruction stream because a
    /// chain is one instruction however many steps it has.
    chains: Vec<Chain>,

    /// One dispatch table per `switch`, for the same reason.
    switches: Vec<Switch>,

    /// One record per `Op::CustomSyntax` site: the custom syntax to invoke
    /// and its (possibly only partially lowered) inputs.
    custom_syntax: Vec<CustomSyntaxSite>,

    /// Script functions the compiler did not lower, as Rhai's own library, so
    /// a fragment can still call one the ordinary way.
    ///
    /// `None` when the script declared none, which is every program that came
    /// from an artifact. An empty `Module` is 264 bytes and a reference count,
    /// which is a fifth of what loading a small program retains — worth not
    /// allocating for something nothing will look in.
    lib: Option<SharedModule>,

    /// Reinstated on the runtime state at each run, mirroring
    /// `Engine::eval_ast_with_scope_raw`, so `import` resolves as it would have.
    #[cfg(not(feature = "no_module"))]
    resolver: Option<Shared<StaticModuleResolver>>,

    /// Names the script in error messages and `NativeCallContext::call_source`.
    source: Option<ImmutableString>,
}

/// A summary rather than a dump: the library alone would render every script
/// function's whole AST, which is never what someone printing a `Program`
/// wants to read.
impl core::fmt::Debug for Program<'_> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let mut f = f.debug_struct("Program");

        f.field("source", &self.source)
            .field("bytes", &self.code.len())
            .field("max_stack", &self.main.max_stack())
            .field("consts", &self.consts.len())
            .field("names", &self.names.len());

        #[cfg(not(feature = "no_ast"))]
        f.field("residuals", &self.residuals.len());

        f.field("custom_syntax_sites", &self.custom_syntax.len());

        f.field("compiled_fns", &self.functions.len())
            .field(
                "walked_fns",
                &self.lib.as_ref().map_or(0, |lib| lib.count().1),
            )
            .field("positions", &!self.positions.is_stripped())
            .finish()
    }
}

/// What a script author would call the construct at this node, for the
/// constructs the compiler does not lower yet.
///
/// Only the ones worth naming: an author can act on "switch at line 42", not
/// on "Expr::Dot". Anything else falls through to the generic message.
#[cfg(not(feature = "no_ast"))]
fn unsupported_kind(node: &ASTNode) -> Option<&'static str> {
    Some(match node {
        ASTNode::Stmt(stmt) => match stmt {
            #[cfg(not(feature = "no_module"))]
            Stmt::Import(..) => "import",
            #[cfg(not(feature = "no_module"))]
            Stmt::Export(..) => "export",
            Stmt::FnCall(call, ..) if call.name == KEYWORD_EVAL => "eval",
            _ => return None,
        },
        ASTNode::Expr(expr) => match expr {
            Expr::FnCall(call, ..) if call.name == KEYWORD_EVAL => "eval",
            // Only "unsupported" when it may change the scope's shape --
            // otherwise it lowers to `Op::CustomSyntax`, per input.
            #[cfg(not(feature = "no_custom_syntax"))]
            Expr::Custom(custom, ..) if custom.scope_may_be_changed => "custom syntax",
            _ => return None,
        },
    })
}

#[cfg(not(feature = "no_ast"))]
fn node_position(node: &ASTNode) -> rhai::Position {
    match node {
        ASTNode::Stmt(stmt) => stmt.position(),
        ASTNode::Expr(expr) => expr.start_position(),
    }
}

/// Everything a program holds besides its code, gathered so the constructor
/// does not take ten positional arguments.
pub(crate) struct Parts<'a> {
    pub positions: Positions,
    /// Names the diagnostics, or `None` to derive one from `positions` and
    /// `chains`.
    ///
    /// A loaded program passes the artifact's, because a stripped one no longer
    /// has the diagnostics to derive it from.
    pub debug_id: Option<u128>,
    #[cfg(not(feature = "no_ast"))]
    pub residuals: Vec<Expr>,
    pub consts: Vec<Dynamic>,
    pub names: Strings<'a>,
    pub tokens: Vec<Token>,
    pub assign_ops: Vec<AssignOp>,
    pub chains: Vec<Chain>,
    pub switches: Vec<Switch>,
    pub custom_syntax: Vec<CustomSyntaxSite>,
    pub lib: Option<SharedModule>,
    #[cfg(not(feature = "no_module"))]
    pub resolver: Option<Shared<StaticModuleResolver>>,
    pub source: Option<ImmutableString>,
}

impl<'a> Program<'a> {
    /// Create a new [`Program`].
    pub(crate) fn new(
        caps: Caps,
        code: Code<'a>,
        main: Chunk,
        functions: Vec<Function>,
        parts: Parts<'a>,
    ) -> Self {
        let has_typed_methods = functions.iter().any(|f| f.this_type.is_some());

        // Derived from the diagnostics it was built with, unless a loader
        // supplied the artifact's.
        let debug_id = parts.debug_id.unwrap_or_else(|| {
            crate::grain::format::debug_id(
                &parts.positions.to_table(),
                &sites::encode(&parts.chains),
            )
        });

        let mut program = Self {
            caps,
            code,
            main,
            functions,
            max_stack: 0,
            has_typed_methods,
            positions: parts.positions,
            debug_id,
            #[cfg(not(feature = "no_ast"))]
            residuals: parts.residuals,
            consts: parts.consts,
            names: parts.names,
            tokens: parts.tokens,
            assign_ops: parts.assign_ops,
            chains: parts.chains,
            switches: parts.switches,
            custom_syntax: parts.custom_syntax,
            lib: parts.lib,
            #[cfg(not(feature = "no_module"))]
            resolver: parts.resolver,
            source: parts.source,
        };
        program.recompute_max_stack();
        program
    }

    /// Copy the borrowed instructions, so this [`Program`] is self-contained and
    /// outlives the artifact it was read from.
    #[must_use]
    pub fn into_owned(self) -> Program<'static> {
        Program {
            code: Code::Owned(self.code.into_owned()),
            caps: self.caps,
            main: self.main,
            functions: self.functions,
            max_stack: self.max_stack,
            has_typed_methods: self.has_typed_methods,
            positions: self.positions,
            debug_id: self.debug_id,
            #[cfg(not(feature = "no_ast"))]
            residuals: self.residuals,
            consts: self.consts,
            names: self.names.into_owned(),
            tokens: self.tokens,
            assign_ops: self.assign_ops,
            chains: self.chains,
            switches: self.switches,
            custom_syntax: self.custom_syntax,
            lib: self.lib,
            #[cfg(not(feature = "no_module"))]
            resolver: self.resolver,
            source: self.source,
        }
    }

    /// Convert the [`Program`] into a shared, read-only version.
    #[inline(always)]
    #[must_use]
    pub fn into_shared(self) -> SharedProgram {
        Shared::new(self.into_owned())
    }

    /// Check that the [`Program`] is internally consistent, returning the stack
    /// high water measured.
    ///
    /// Cheap enough to run after each compile and on each load. This is the gate
    /// an artifact loaded from a wire has to pass before the VM will touch it.
    pub fn verify(&self) -> Result<Vec<u16>, crate::grain::bytecode::VerifyError> {
        crate::grain::bytecode::verify(
            self.caps,
            self.consts(),
            &self.code,
            self.functions(),
            &self.chunks(),
            &self.pools(),
        )
    }

    /// Every chunk, main first, in the order they sit in the code.
    fn chunks(&self) -> Vec<Chunk> {
        std::iter::once(self.main)
            .chain(self.functions.iter().map(|f| f.chunk))
            .chain({
                #[cfg(not(feature = "no_custom_syntax"))]
                {
                    self.custom_syntax
                        .iter()
                        .flat_map(|custom| custom.inputs.iter().map(|&(chunk, _)| chunk))
                }
                #[cfg(feature = "no_custom_syntax")]
                {
                    std::iter::empty()
                }
            })
            .collect()
    }

    pub(crate) fn pools(&self) -> Pools<'_> {
        Pools {
            consts: self.consts.len(),
            names: &self.names,
            tokens: self.tokens.len(),
            assign_ops: self.assign_ops.len(),
            #[cfg(not(feature = "no_ast"))]
            residuals: self.residuals.len(),
            chains: &self.chains,
            switches: &self.switches,
            custom_syntax: &self.custom_syntax,
        }
    }

    /// Replace the compiler's upper-bound stack estimate with the verified high
    /// water, so the VM reserves what the chunk uses rather than one slot per
    /// instruction.
    ///
    /// A chunk that does not verify keeps its estimate: the VM is still safe
    /// with a value that is too large, and [`Program::verify`] is where the
    /// real failure should surface.
    #[cfg(not(feature = "no_ast"))]
    pub(crate) fn tighten_stack(&mut self) {
        let Ok(high_water) = self.verify() else {
            return;
        };
        let mut measured = high_water.into_iter();
        if let Some(main) = measured.next() {
            self.main.set_max_stack(main);
        }
        for (function, high_water) in self.functions.iter_mut().zip(measured) {
            function.chunk.set_max_stack(high_water);
        }
        self.recompute_max_stack();
    }

    /// _(internals)_ Every [Chunk]'s instructions, concatenated.
    /// Exported under the `internals` feature only.
    #[expose_under_internals]
    #[inline(always)]
    #[must_use]
    fn code(&self) -> &[u8] {
        &self.code
    }

    /// The capabilities required by every [Chunk]'s instructions.
    #[inline(always)]
    #[must_use]
    pub fn caps(&self) -> Caps {
        self.caps
    }

    /// _(internals)_ The compiled script functions.
    /// Exported under the `internals` feature only.
    #[expose_under_internals]
    #[inline(always)]
    #[must_use]
    fn functions(&self) -> &[Function] {
        &self.functions
    }

    /// Number of compiled script functions in this[`Program`].
    #[inline(always)]
    #[must_use]
    pub fn num_functions(&self) -> usize {
        self.functions.len()
    }

    /// _(internals)_ The compiled function a call site resolves to, if there is one.
    /// Exported under the `internals` feature only.
    ///
    /// Name and arity only, matching how Rhai keys script functions. The name
    /// is an index into the pool the call site also indexes, so equal names
    /// have equal indices and this is two integer comparisons.
    ///
    /// Typed methods are invisible here. Rhai only ever tries a typed hash on a
    /// *method* call, so `fn int.foo()` cannot be reached as `foo()`.
    #[expose_under_internals]
    #[inline(always)]
    fn function(&self, name: u32, argc: usize) -> Option<&Function> {
        self.functions
            .iter()
            .find(|f| f.name == name && f.params.len() == argc && f.this_type.is_none())
    }

    /// The compiled function a *method* call resolves to.
    ///
    /// `argc` excludes the receiver: `x.foo(1)` looks for the script function
    /// `foo` of arity **one** and binds `this` to `x`, which is what the parser
    /// hashes. That is the whole difference from [`Program::function`], whose
    /// `argc` counts the receiver because the rewrite it serves is function-call
    /// style.
    ///
    /// `typed` is the receiver's mapped type name. A function declared for it
    /// wins, and an untyped one of the same name and arity is the fallback —
    /// Rhai's order, minus the hashing.
    pub(crate) fn method(&self, name: u32, argc: usize, typed: &str) -> Option<&Function> {
        let matching = |f: &&Function| f.name == name && f.params.len() == argc;

        // Nearly every program has no typed method at all, and this is a linear
        // scan on every method call — so the extra pass is bought only where
        // there is something for it to find.
        if self.has_typed_methods {
            let found = self
                .functions
                .iter()
                .find(|f| matching(f) && f.this_type.and_then(|t| self.name(t)) == Some(typed));
            if found.is_some() {
                return found;
            }
        }

        self.functions
            .iter()
            .find(|f| matching(f) && f.this_type.is_none())
    }

    /// Name index of the compiled function with a particular name and arity.
    ///
    /// A linear scan, which at these sizes beats a map and
    /// keeps the common indexed lookup untouched.
    pub(crate) fn function_name_index(&self, name: &str, argc: usize) -> Option<u32> {
        self.functions
            .iter()
            .find(|f| {
                f.params.len() == argc && f.this_type.is_none() && self.name(f.name) == Some(name)
            })
            .map(|f| f.name as u32)
    }

    /// The compiled function with a particular name and arity.
    ///
    /// A linear scan, which at these sizes beats a map and
    /// keeps the common indexed lookup untouched.
    pub(crate) fn function_named(&self, name: &str, argc: usize) -> Option<&Function> {
        self.functions.iter().find(|f| {
            f.params.len() == argc && f.this_type.is_none() && self.name(f.name) == Some(name)
        })
    }

    /// Whether this program can hand a function pointer to something that
    /// might call it back.
    ///
    /// A compiled function lives in this program's own table and nowhere Rhai
    /// can see, so a native that calls a pointer — `map`, `filter` — cannot
    /// reach one. Making it reachable means registering a wrapper, and Rhai
    /// requires a registered function to be `'static`, so the wrapper has to
    /// own the program: [`Program::into_owned`] first, at the cost of the
    /// borrowed-from-the-artifact loading that is the point of the format.
    ///
    /// This is how a host decides whether to pay that, without having to read
    /// the script. False is the common answer and costs nothing.
    #[inline(always)]
    #[must_use]
    pub fn makes_fn_pointers(&self) -> bool {
        self.caps().contains(Caps::FN_PTR)
    }

    /// How much operand stack the deepest chunk needs.
    ///
    /// One reservation serves every frame, because a call pushes its operands
    /// above the caller's rather than starting a stack of its own.
    ///
    /// Cached rather than recomputed, since entering a frame reads it and
    /// entering a frame is what a call does.
    #[inline(always)]
    #[must_use]
    pub fn max_stack(&self) -> u16 {
        self.max_stack
    }

    fn recompute_max_stack(&mut self) {
        self.max_stack = self
            .functions
            .iter()
            .map(|f| f.chunk.max_stack())
            .chain(core::iter::once(self.main.max_stack()))
            .max()
            .unwrap_or(0);
    }

    pub(crate) fn constant(&self, index: u32) -> Option<&Dynamic> {
        self.consts.get(index as usize)
    }

    /// A name, borrowed from the artifact. Never allocates.
    pub(crate) fn name(&self, index: u32) -> Option<&str> {
        self.names.get(index)
    }

    pub(crate) fn token(&self, index: u32) -> Option<&Token> {
        self.tokens.get(index as usize)
    }

    pub(crate) fn assign_op(&self, index: u32) -> Option<&AssignOp> {
        self.assign_ops.get(index as usize)
    }

    pub(crate) fn chain(&self, index: u32) -> Option<&Chain> {
        self.chains.get(index as usize)
    }

    pub(crate) fn chains(&self) -> &[Chain] {
        &self.chains
    }

    pub(crate) fn switch(&self, index: u32) -> Option<&Switch> {
        self.switches.get(index as usize)
    }

    /// The dispatch tables [`Op::Switch`](crate::grain::bytecode::Op::Switch) indexes.
    ///
    /// Public because a disassembly that leaves them out is misleading: a
    /// switch's arms are reached only from its table, so without it they read
    /// as unreachable code.
    #[must_use]
    pub(crate) fn switches(&self) -> &[Switch] {
        &self.switches
    }

    #[cfg(any(feature = "internals", not(feature = "no_custom_syntax")))]
    #[must_use]
    pub(crate) fn custom_syntax_site(&self, index: u32) -> Option<&CustomSyntaxSite> {
        self.custom_syntax.get(index as usize)
    }

    #[must_use]
    pub(crate) fn custom_syntax(&self) -> &[CustomSyntaxSite] {
        &self.custom_syntax
    }

    /// _(internals)_ Where instruction `pc` came from, or [`Position::NONE`][rhai::Position::NONE]
    /// if the table was stripped or has nothing for it.
    /// Exported under the `internals` feature only.
    #[expose_under_internals]
    #[inline(always)]
    #[must_use]
    fn position(&self, pc: usize) -> rhai::Position {
        self.positions.get(pc)
    }

    /// _(internals)_ The whole position table, keyed on instruction address.
    /// Exported under the `internals` feature only.
    #[expose_under_internals]
    #[inline(always)]
    #[must_use]
    fn positions(&self) -> &Positions {
        &self.positions
    }

    /// Names the diagnostics this [`Program`] was compiled with.
    #[inline(always)]
    #[must_use]
    pub fn debug_id(&self) -> u128 {
        self.debug_id
    }

    /// Drop this [`Program`]'s diagnostics, returning them.
    ///
    /// See [`Program::attach_positions`] for the inverse.
    #[inline]
    pub fn strip_positions(&mut self) -> Sidecar {
        let sidecar = self.sidecar();

        self.positions = Positions::Stripped;
        for chain in &mut self.chains {
            for pos in chain.positions_mut() {
                *pos = rhai::Position::NONE;
            }
        }

        sidecar
    }

    /// Put a [`Sidecar`] back, so this [`Program`] reports positions again.
    ///
    /// # Errors
    ///
    /// Refuses a malformed [`Sidecar`], or one from another [`Program`].
    /// Attaching the wrong one would misreport every error rather than reporting none.
    pub fn attach_positions(&mut self, sidecar: &Sidecar) -> Result<(), TableError> {
        if sidecar.debug_id != self.debug_id {
            return Err(TableError::WrongProgram {
                expected: sidecar.debug_id,
                found: self.debug_id,
            });
        }

        // Both decoded before either is applied, so a sidecar sound in one half
        // and not the other leaves the program as it was.
        let positions = Positions::from_table(&sidecar.positions, &self.code)?;
        let sites = sites::decode(&sidecar.chains).map_err(TableError::ChainStream)?;

        let slots = self.chains.iter().map(Chain::position_slots).sum::<u32>() as usize;
        if sites.len() != slots {
            return Err(TableError::ChainCount {
                sites: sites.len(),
                slots,
            });
        }

        let mut sites = sites.into_iter();
        for chain in &mut self.chains {
            for pos in chain.positions_mut() {
                *pos = sites
                    .next()
                    .flatten()
                    .map_or(rhai::Position::NONE, site_to_position);
            }
        }

        self.positions = positions;
        Ok(())
    }

    pub(crate) fn consts(&self) -> &[Dynamic] {
        &self.consts
    }

    pub(crate) fn names(&self) -> &Strings<'a> {
        &self.names
    }

    pub(crate) fn tokens(&self) -> &[Token] {
        &self.tokens
    }

    pub(crate) fn assign_ops(&self) -> &[AssignOp] {
        &self.assign_ops
    }

    /// _(internals)_ The top-level chunk, where execution starts.
    /// Exported under the `internals` feature only.
    #[crate::expose_under_internals]
    #[inline(always)]
    #[must_use]
    fn main(&self) -> &Chunk {
        &self.main
    }

    /// How many fragments Rhai's [`AST`][crate::AST] walker still evaluates.
    ///
    /// Non-zero is the reason a [`Program`] cannot yet be serialized.
    ///
    /// See also [`Program::residual_nodes`].
    #[cfg(not(feature = "no_ast"))]
    #[inline(always)]
    #[must_use]
    pub fn residual_count(&self) -> usize {
        self.residuals.len()
    }

    /// How many [`AST`][crate::AST] nodes are still inside fragments.
    #[cfg(not(feature = "no_ast"))]
    #[inline(always)]
    #[must_use]
    pub fn residual_nodes(&self) -> usize {
        let mut nodes = 0;
        let path = &mut Vec::new();
        for residual in &self.residuals {
            residual.walk(path, &mut |_| {
                nodes += 1;
                true
            });
        }
        nodes
    }

    #[cfg(not(feature = "no_ast"))]
    pub(crate) fn residual(&self, index: u32) -> Option<&Expr> {
        self.residuals.get(index as usize)
    }

    /// The construct that stopped this program being written, and where.
    ///
    /// A count of fragments is not something anyone can act on. This names the
    /// first thing the compiler could not lower, so a validator can reject an
    /// upload with the line to go and look at — which is what makes falling
    /// back to shipping source a decision rather than a mystery.
    #[cfg(not(feature = "no_ast"))]
    #[must_use]
    pub fn first_unsupported(&self) -> Option<(&'static str, rhai::Position)> {
        let path = &mut Vec::new();
        let mut found: Option<(&'static str, rhai::Position)> = None;

        for residual in &self.residuals {
            residual.walk(path, &mut |path| {
                if found.is_some() {
                    return false;
                }
                if let Some(name) = path.last().and_then(unsupported_kind) {
                    found = Some((name, node_position(path.last().expect("just matched"))));
                    return false;
                }
                true
            });
            if found.is_some() {
                break;
            }
        }

        // A fragment made of nothing this recognizes is still a fragment, so
        // say so rather than reporting nothing wrong.
        found.or_else(|| {
            self.residuals
                .first()
                .map(|expr| ("an unlowered expression", expr.start_position()))
        })
    }

    pub(crate) fn lib(&self) -> Option<&SharedModule> {
        self.lib.as_ref()
    }

    #[cfg(not(feature = "no_module"))]
    pub(crate) fn resolver(&self) -> Option<&Shared<StaticModuleResolver>> {
        self.resolver.as_ref()
    }

    /// Script source name, if known.
    #[must_use]
    pub fn source(&self) -> Option<&ImmutableString> {
        self.source.as_ref()
    }

    /// Set the script source name.
    pub fn set_source(&mut self, source: impl Into<ImmutableString>) -> &mut Self {
        self.source = Some(source.into());
        self
    }
}

/// Export non-private functions into a [`Module`].
#[cfg(not(feature = "no_function"))]
#[cfg(not(feature = "no_module"))]
pub fn export_functions_to_module(
    program: &SharedProgram,
    module: &mut crate::Module,
    env: &Shared<crate::func::EncapsulatedEnviron>,
) {
    program
        .functions()
        .iter()
        .filter(|&f| match f.access {
            crate::func::FnAccess::Public => true,
            crate::func::FnAccess::Private => false,
        })
        .for_each(|f| {
            let fn_name: ImmutableString =
                program.name(f.name).expect("valid function name").into();
            let params: crate::FnArgsVec<ImmutableString> = f
                .params
                .iter()
                .map(|&idx| program.name(idx).expect("valid param name").into())
                .collect();

            let fn_def = crate::func::ScriptFuncDef {
                name: fn_name,
                access: f.access,
                #[cfg(not(feature = "no_object"))]
                this_type: f
                    .this_type
                    .and_then(|index| program.name(index))
                    .map(Into::into),
                params,
                body: crate::func::ScriptFuncPayload::GrainVM {
                    program: program.clone(),
                    params: f.params.iter().copied().collect(),
                    chunk: f.chunk,
                    span: crate::types::Span::new(
                        program.position(f.chunk.entry() as usize),
                        program.position(f.chunk.end() as usize),
                    ),
                },
                #[cfg(feature = "metadata")]
                comments: <_>::default(),
            };

            let hash = module.set_script_fn(fn_def);

            if let Some(crate::func::RhaiFunc::Script { env: ref mut e, .. }) =
                module.get_script_fn_by_hash_mut(hash)
            {
                // Encapsulated environment
                *e = Some(env.clone());
            }
        });
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::grain::bytecode::code::assemble;
    use crate::grain::bytecode::{Op, Positions, Strings};

    /// Names: 0 `f`, 1 `i64`, 2 `string`.
    fn program_of(functions: &[(u32, Option<u32>, usize)]) -> Program<'static> {
        // Every chunk is the same two instructions; only the table matters here.
        let (code, _) = assemble(&[Op::Unit, Op::Return]).expect("must assemble");
        let whole = Chunk::new(0, code.len() as u32, 8);

        let functions = functions
            .iter()
            .map(|&(name, this_type, argc)| Function {
                name,
                params: vec![0; argc],
                access: crate::FnAccess::Public,
                this_type,
                chunk: whole,
            })
            .collect();

        Program::new(
            Caps::FUNCTION,
            code.into(),
            whole,
            functions,
            Parts {
                positions: Positions::default(),
                debug_id: None,
                #[cfg(not(feature = "no_ast"))]
                residuals: Vec::new(),
                consts: Vec::new(),
                names: Strings::new(["f", "i64", "string"]),
                tokens: Vec::new(),
                assign_ops: Vec::new(),
                chains: Vec::new(),
                switches: Vec::new(),
                custom_syntax: Vec::new(),
                lib: None,
                #[cfg(not(feature = "no_module"))]
                resolver: None,
                source: None,
            },
        )
    }

    /// Rhai tries the receiver's type first and falls back to the untyped
    /// function of the same name and arity.
    #[test]
    fn a_typed_method_wins_over_an_untyped_one_of_the_same_arity() {
        let program = program_of(&[(0, Some(1), 0), (0, None, 0)]);

        assert_eq!(program.method(0, 0, "i64").unwrap().this_type, Some(1));
        // No function declared for a string, so the untyped one answers.
        assert_eq!(program.method(0, 0, "string").unwrap().this_type, None);
    }

    /// A typed method is only ever reached through a method call: Rhai computes
    /// the typed hash nowhere else, so `foo()` cannot find `fn <int>.foo()`.
    #[test]
    fn a_typed_method_is_unreachable_in_call_style() {
        let program = program_of(&[(0, Some(1), 0)]);

        assert!(program.function(0, 0).is_none());
        assert!(program.function_named("f", 0).is_none());
        assert!(program.method(0, 0, "i64").is_some());
    }

    #[test]
    fn arity_is_matched_before_the_receiver_type() {
        let program = program_of(&[(0, Some(1), 1), (0, None, 0)]);

        // The typed one takes an argument, so a no-argument call is the untyped.
        assert_eq!(program.method(0, 0, "i64").unwrap().this_type, None);
        assert_eq!(program.method(0, 1, "i64").unwrap().this_type, Some(1));
    }

    #[test]
    #[cfg(not(feature = "no_function"))]
    fn a_receiver_type_survives_the_round_trip() {
        let program = program_of(&[(0, Some(1), 0), (0, None, 0)]);

        let bytes = program.write().expect("must be writable");
        let reloaded = Program::read(&bytes).expect("must load");

        let typed: Vec<_> = reloaded.functions().iter().map(|f| f.this_type).collect();
        assert_eq!(typed, vec![Some(1), None]);
        assert_eq!(reloaded.method(0, 0, "i64").unwrap().this_type, Some(1));
    }
}