yomi_core/program.rs
1//! A compiled program (bytecode).
2
3use std::sync::Arc;
4
5use crate::pool::{Idx, Pool};
6use crate::value::{Ty, TypeDecl, Value};
7
8/// The reference to the program that a `Vm` holds. Either a `Program` borrowed from the host, or an extended program
9/// built (and owned) by the REPL (section 7.8 of `spec/host/07-repl.md`).
10#[derive(Debug, Clone)]
11pub(crate) enum ProgRef<'a> {
12 /// Borrows the `Program` given by the host.
13 Borrowed(&'a Program),
14 /// An extended program built by the REPL (shared between copies).
15 Shared(Arc<Program>),
16}
17
18impl std::ops::Deref for ProgRef<'_> {
19 type Target = Program;
20
21 fn deref(&self) -> &Program {
22 match self {
23 ProgRef::Borrowed(p) => p,
24 ProgRef::Shared(p) => p,
25 }
26 }
27}
28
29/// A register number (an index into the frame's array, where temporaries follow the local variables).
30pub(crate) type Reg = u16;
31
32/// A register-based instruction. Values are passed through registers (`Reg`). Variable-length data is held as indices
33/// into the tables of [`RegCode`]. The place for return values and resume values is the `dst` of the instruction that
34/// is returned to (`Call`, `CallFn`, `Stop`, `ChoiceStop`).
35#[derive(Debug, Clone, PartialEq)]
36pub(crate) enum RegOp {
37 Int {
38 dst: Reg,
39 n: i64,
40 },
41 Const {
42 dst: Reg,
43 k: Idx<Value>,
44 },
45 /// Copies to a temporary (the size is not counted).
46 Move {
47 dst: Reg,
48 src: Reg,
49 },
50 /// Copies into a local variable (the size is counted).
51 Set {
52 dst: Reg,
53 src: Reg,
54 },
55 /// Moves the value of a temporary into a local variable (the size is counted; the temporary becomes `()`).
56 SetMove {
57 dst: Reg,
58 src: Reg,
59 },
60 LoadGlobal {
61 dst: Reg,
62 g: u32,
63 },
64 StoreGlobal {
65 g: u32,
66 src: Reg,
67 },
68 LoadHost {
69 dst: Reg,
70 h: u32,
71 },
72 StoreHost {
73 h: u32,
74 src: Reg,
75 },
76 /// Reads the value reached from a variable through `struct` fields (without copying the whole value of the variable).
77 LoadField {
78 dst: Reg,
79 place: PlaceRef,
80 path: Idx<Box<[u32]>>,
81 },
82 GetField {
83 dst: Reg,
84 src: Reg,
85 field: u32,
86 },
87 IdField {
88 dst: Reg,
89 src: Reg,
90 name: bool,
91 },
92 AddI {
93 dst: Reg,
94 a: Reg,
95 b: Reg,
96 },
97 SubI {
98 dst: Reg,
99 a: Reg,
100 b: Reg,
101 },
102 MulI {
103 dst: Reg,
104 a: Reg,
105 b: Reg,
106 },
107 DivI {
108 dst: Reg,
109 a: Reg,
110 b: Reg,
111 },
112 RemI {
113 dst: Reg,
114 a: Reg,
115 b: Reg,
116 },
117 AddIK {
118 dst: Reg,
119 a: Reg,
120 k: i64,
121 },
122 SubIK {
123 dst: Reg,
124 a: Reg,
125 k: i64,
126 },
127 MulIK {
128 dst: Reg,
129 a: Reg,
130 k: i64,
131 },
132 DivIK {
133 dst: Reg,
134 a: Reg,
135 k: i64,
136 },
137 RemIK {
138 dst: Reg,
139 a: Reg,
140 k: i64,
141 },
142 LtI {
143 dst: Reg,
144 a: Reg,
145 b: Reg,
146 },
147 LeI {
148 dst: Reg,
149 a: Reg,
150 b: Reg,
151 },
152 LtIK {
153 dst: Reg,
154 a: Reg,
155 k: i64,
156 },
157 LeIK {
158 dst: Reg,
159 a: Reg,
160 k: i64,
161 },
162 GtIK {
163 dst: Reg,
164 a: Reg,
165 k: i64,
166 },
167 GeIK {
168 dst: Reg,
169 a: Reg,
170 k: i64,
171 },
172 EqIK {
173 dst: Reg,
174 a: Reg,
175 k: i64,
176 },
177 NeIK {
178 dst: Reg,
179 a: Reg,
180 k: i64,
181 },
182 /// `float` arithmetic (no `%`).
183 ArithF {
184 op: ArithOp,
185 dst: Reg,
186 a: Reg,
187 b: Reg,
188 },
189 /// `float` ordering comparison (`a < b`, `a <= b`; `>` and `>=` swap the operands).
190 LtF {
191 dst: Reg,
192 a: Reg,
193 b: Reg,
194 },
195 LeF {
196 dst: Reg,
197 a: Reg,
198 b: Reg,
199 },
200 /// Equality of values (any type).
201 Eq {
202 dst: Reg,
203 a: Reg,
204 b: Reg,
205 },
206 Ne {
207 dst: Reg,
208 a: Reg,
209 b: Reg,
210 },
211 /// Negation (`int` and `float`).
212 Neg {
213 dst: Reg,
214 a: Reg,
215 },
216 Not {
217 dst: Reg,
218 a: Reg,
219 },
220 ToInt {
221 dst: Reg,
222 a: Reg,
223 },
224 ToFloat {
225 dst: Reg,
226 a: Reg,
227 },
228 ToStr {
229 dst: Reg,
230 a: Reg,
231 },
232 /// Concatenates the strings in the `n` registers starting at `start`.
233 Concat {
234 dst: Reg,
235 start: Reg,
236 n: u16,
237 },
238 Range {
239 dst: Reg,
240 a: Reg,
241 b: Reg,
242 },
243 Random {
244 dst: Reg,
245 a: Reg,
246 b: Reg,
247 },
248 RandomFloat {
249 dst: Reg,
250 },
251 Jump {
252 to: u32,
253 },
254 JumpIfFalse {
255 cond: Reg,
256 to: u32,
257 },
258 JumpIfTrue {
259 cond: Reg,
260 to: u32,
261 },
262 /// Integer comparison and conditional jump (jumps to `to` if `a < b` is false). The form used for the conditions of `if`
263 /// and `while` that does not put the comparison result in a temporary.
264 JumpUnlessLtI {
265 a: Reg,
266 b: Reg,
267 to: u32,
268 },
269 JumpUnlessLeI {
270 a: Reg,
271 b: Reg,
272 to: u32,
273 },
274 JumpUnlessLtIK {
275 a: Reg,
276 k: i64,
277 to: u32,
278 },
279 JumpUnlessLeIK {
280 a: Reg,
281 k: i64,
282 to: u32,
283 },
284 JumpUnlessGtIK {
285 a: Reg,
286 k: i64,
287 to: u32,
288 },
289 JumpUnlessGeIK {
290 a: Reg,
291 k: i64,
292 to: u32,
293 },
294 JumpUnlessEqIK {
295 a: Reg,
296 k: i64,
297 to: u32,
298 },
299 JumpUnlessNeIK {
300 a: Reg,
301 k: i64,
302 to: u32,
303 },
304 MakeList {
305 dst: Reg,
306 start: Reg,
307 n: u16,
308 },
309 MakeSome {
310 dst: Reg,
311 a: Reg,
312 },
313 MakeStruct {
314 dst: Reg,
315 start: Reg,
316 ty: u32,
317 order: Idx<Vec<u32>>,
318 },
319 MakeEnum {
320 dst: Reg,
321 start: Reg,
322 n: u16,
323 ty: u32,
324 variant: u32,
325 },
326 /// Makes a `map` from the `2 * n` registers starting at `start` (key then value).
327 MakeMap {
328 dst: Reg,
329 start: Reg,
330 n: u16,
331 },
332 Index {
333 dst: Reg,
334 base: Reg,
335 index: Reg,
336 },
337 MapGet {
338 dst: Reg,
339 map: Reg,
340 key: Reg,
341 },
342 MapHas {
343 dst: Reg,
344 map: Reg,
345 key: Reg,
346 },
347 MapKeys {
348 dst: Reg,
349 map: Reg,
350 },
351 MapValues {
352 dst: Reg,
353 map: Reg,
354 },
355 Len {
356 dst: Reg,
357 a: Reg,
358 },
359 IsEmpty {
360 dst: Reg,
361 a: Reg,
362 },
363 ListContains {
364 dst: Reg,
365 list: Reg,
366 item: Reg,
367 },
368 /// A stable ascending copy of `list`, ordered by `keys` (the same register as `list` for a plain sort).
369 ListSortBy {
370 dst: Reg,
371 list: Reg,
372 keys: Reg,
373 },
374 ListReverse {
375 dst: Reg,
376 list: Reg,
377 },
378 /// The total of `list`. `float` is whether the elements are `float` (the total of an empty list is `0.0` or `0`).
379 ListSum {
380 dst: Reg,
381 list: Reg,
382 float: bool,
383 },
384 /// The first element of `list` with the least (or greatest, if `max`) key in `keys`, as an `Option`.
385 ListExtreme {
386 dst: Reg,
387 list: Reg,
388 keys: Reg,
389 max: bool,
390 },
391 /// Moves to `next` if `src` is not equal to the constant.
392 MatchLit {
393 src: Reg,
394 k: Idx<Value>,
395 next: u32,
396 },
397 MatchSome {
398 src: Reg,
399 next: u32,
400 },
401 MatchNone {
402 src: Reg,
403 next: u32,
404 },
405 MatchVariant {
406 src: Reg,
407 name: Idx<String>,
408 next: u32,
409 },
410 /// Discards a temporary (discards the subject of a `match` on entering an arm).
411 Clear {
412 r: Reg,
413 },
414 /// The `i`-th content of `src` (a `Some` or an `enum`).
415 Payload {
416 dst: Reg,
417 src: Reg,
418 i: u32,
419 },
420 /// The next element of a `for` (`list`, `idx` and `var` are local variables). Moves to `end` when finished.
421 ForNext {
422 list: Reg,
423 idx: Reg,
424 var: Reg,
425 end: u32,
426 },
427 /// Same as `ForNext`, and also puts the index in `key` (`for i, x in xs`).
428 ForNextAt {
429 list: Reg,
430 idx: Reg,
431 var: Reg,
432 key: Reg,
433 end: u32,
434 },
435 /// Compacts the holes left by removals in the copy of the `map` that a `for` iterates.
436 MapCompact {
437 map: Reg,
438 },
439 /// Puts the pair at position `idx` of the `map` into `key` and `var`, and advances `idx`. Moves to `end` if there is none.
440 ForMapNext {
441 map: Reg,
442 idx: Reg,
443 key: Reg,
444 var: Reg,
445 end: u32,
446 },
447 /// `for i in range(a, b)`: if `idx` is less than `limit`, puts it in `var` and advances; otherwise moves to `end`.
448 ForRange {
449 idx: Reg,
450 limit: Reg,
451 var: Reg,
452 end: u32,
453 },
454 /// Updates a place in place. Starting at `start`, the indices and keys (in the order of the path's `Index` and `Key`)
455 /// come first, followed by the update values.
456 Mutate {
457 place: PlaceRef,
458 plan: Idx<(Vec<PathStep>, Action)>,
459 start: Reg,
460 },
461 ArgsBegin,
462 TextBegin,
463 /// Records the string in `src` as the value of a `${expr}` of the current body.
464 Capture {
465 src: Reg,
466 },
467 /// An effect command. If it has a return value, puts it in `dst`.
468 CallEffect {
469 dst: Reg,
470 start: Reg,
471 n: u16,
472 native: u32,
473 },
474 CallQuery {
475 dst: Reg,
476 start: Reg,
477 n: u16,
478 native: u32,
479 },
480 Seen {
481 dst: Reg,
482 a: Reg,
483 },
484 Visited {
485 dst: Reg,
486 a: Reg,
487 },
488 OnceAvailable {
489 dst: Reg,
490 key: Idx<String>,
491 },
492 MarkSeen {
493 key: Idx<String>,
494 },
495 MarkOnce {
496 key: Idx<String>,
497 },
498 ChoiceBegin,
499 ChoiceItem {
500 text: Reg,
501 id: Reg,
502 orig: u32,
503 },
504 JumpLabel {
505 label: u32,
506 },
507 /// Calls a label. The `n` registers from `start` are the arguments. The return value goes into `dst`.
508 Call {
509 dst: Reg,
510 start: Reg,
511 n: u16,
512 label: u32,
513 site: u32,
514 },
515 CallFn {
516 dst: Reg,
517 start: Reg,
518 n: u16,
519 f: u32,
520 },
521 /// Calls a function value (`callee`). The `n` registers from `start` are the arguments. The return value goes into `dst`.
522 CallValue {
523 dst: Reg,
524 callee: Reg,
525 start: Reg,
526 n: u16,
527 },
528 /// Makes a function value. The `n` registers from `start` are the captured values.
529 MakeFn {
530 dst: Reg,
531 start: Reg,
532 n: u16,
533 f: u32,
534 },
535 ReturnFn {
536 src: Option<Reg>,
537 },
538 Return {
539 src: Option<Reg>,
540 },
541 /// Stops at a stop command. The `n` registers from `start` are the arguments. The resume value goes into `dst` (only for
542 /// stop points that receive it).
543 Stop {
544 dst: Reg,
545 start: Reg,
546 n: u16,
547 cmd: u32,
548 stop: u32,
549 },
550 /// Stops at a choice. On resume, the number of the chosen option (in the order written) goes into `dst`.
551 ChoiceStop {
552 dst: Reg,
553 cmd: u32,
554 stop: u32,
555 },
556 /// Moves to the position numbered by `src`.
557 JumpTable {
558 src: Reg,
559 table: Idx<Vec<u32>>,
560 },
561 /// The end of REPL input. For expression input, keeps its value (`src`).
562 ReplDone {
563 src: Option<Reg>,
564 },
565 End,
566}
567
568/// The register-based code of one label or `fn`.
569#[derive(Debug, Clone, PartialEq, Default)]
570pub(crate) struct RegCode {
571 pub ops: Vec<RegOp>,
572 /// The number of registers (local variables and temporaries).
573 pub regs: u32,
574 /// The number of local variables (registers after these are temporaries).
575 pub vars: u32,
576 pub consts: Pool<Value>,
577 pub paths: Pool<Box<[u32]>>,
578 pub orders: Pool<Vec<u32>>,
579 pub names: Pool<String>,
580 pub plans: Pool<(Vec<PathStep>, Action)>,
581 pub tables: Pool<Vec<u32>>,
582}
583
584/// The variable of the place to update.
585#[derive(Debug, Clone, Copy, PartialEq, Eq)]
586pub(crate) enum PlaceRef {
587 Local(u32),
588 Global(u32),
589 Host(u32),
590}
591
592/// One step of the path to a place.
593#[derive(Debug, Clone, Copy, PartialEq, Eq)]
594pub(crate) enum PathStep {
595 /// The `i`-th field of a `struct`.
596 Field(u32),
597 /// An index into a `list` (the value is taken from the stack).
598 Index,
599 /// A key of a `map` (the value is taken from the stack). A `Set` at the last step appends the key if it is missing.
600 Key,
601}
602
603/// The kind of update to a place.
604#[derive(Debug, Clone, Copy, PartialEq, Eq)]
605pub(crate) enum Action {
606 /// Assignment.
607 Set,
608 /// `place op= value` (`op` is `ArithOp::Add` and so on).
609 Arith(ArithOp),
610 /// Appends to the end of a `list`.
611 Push,
612 /// Inserts at an index of a `list` (`0 <= i <= len`). The operands are the value (top) and the index (below it).
613 Insert,
614 /// Removes the element at an index of a `list` (for a `map`, removes the pair with the key; does nothing if missing).
615 Remove,
616 /// Empties a `list` or `map`.
617 Clear,
618 /// Shuffles the elements of a `list` with the core's random generator (Fisher–Yates).
619 Shuffle,
620}
621
622/// The operation of a compound assignment.
623#[derive(Debug, Clone, Copy, PartialEq, Eq)]
624pub(crate) enum ArithOp {
625 Add,
626 Sub,
627 Mul,
628 Div,
629 Rem,
630}
631
632/// The kind of stop point: a sugar (plain line, quote line, choice) or a command written with `@`. Text tables
633/// (`spec/host/05-texts.md`) replace only the bodies of sugar.
634#[non_exhaustive]
635#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
636pub enum StopKind {
637 /// A stop command called with `@` (its arguments are not replaced).
638 #[default]
639 Command,
640 /// A plain line (argument 0 is the body).
641 Plain,
642 /// A quote line (argument 1 is the body).
643 Quote,
644 /// A choice (argument 0 is the `list` of option texts, argument 1 the `list` of stable IDs).
645 Choice,
646}
647
648impl StopKind {
649 /// The stable English name.
650 pub fn code(self) -> &'static str {
651 match self {
652 StopKind::Command => "command",
653 StopKind::Plain => "plain",
654 StopKind::Quote => "quote",
655 StopKind::Choice => "choice",
656 }
657 }
658}
659
660/// A part of the original text of a body (`${expr}` is only a number; the expression itself is not kept).
661#[derive(Debug, Clone, PartialEq, Eq)]
662pub(crate) enum TextPart {
663 /// Characters (after unescaping).
664 Lit(String),
665 /// One `${expr}`.
666 Interp,
667}
668
669/// Information about a stop point.
670#[derive(Debug, Clone, PartialEq)]
671pub(crate) struct StopInfo {
672 /// The kind of sugar (`@` commands are `Command`).
673 pub kind: StopKind,
674 /// The original text of the body of a plain or quote line (empty otherwise). For a command with `text_arg`, the original
675 /// text of that argument.
676 pub text: Vec<TextPart>,
677 /// A stop point of a command whose arguments can be translated by a text table (when an argument that is a `text_param`
678 /// in the registry is written as a string literal). The argument number, and its number in the record of `${expr}` values
679 /// (`StopRecord::values`).
680 pub text_arg: Option<TextArg>,
681 /// The start of the instructions that compute the arguments.
682 pub args_pc: u32,
683 /// The position of the stopping instruction.
684 pub pc: u32,
685 /// The stable ID.
686 pub id: Option<String>,
687 /// The content hash (command name + original text of the arguments).
688 pub hash: u64,
689 /// Line.
690 pub line: u32,
691 /// For a choice stop point, information about its options.
692 pub choice: Option<ChoiceInfo>,
693 /// Whether the stop point receives the return value in a variable (`let name = @command(...)`, `name = @command(...)`).
694 /// If true, the resume value (`resume`) is pushed onto the stack, and the instruction after the stop stores it in the
695 /// variable.
696 pub binds: bool,
697}
698
699/// An argument of a command that can be translated by a text table (section 5.2a of `spec/host/05-texts.md`).
700#[derive(Debug, Clone, Copy, PartialEq, Eq)]
701pub(crate) struct TextArg {
702 /// The argument number.
703 pub arg: u32,
704 /// The number in the record of `${expr}` values (only string literal arguments are counted).
705 pub values: u32,
706}
707
708/// One identity declaration (the display name can be translated by a text table; section 5.2a of
709/// `spec/host/05-texts.md`).
710#[derive(Debug, Clone, PartialEq, Eq)]
711pub(crate) struct IdentityInfo {
712 /// The declaring module (an index into `Program::modules`).
713 pub module: u32,
714 /// The declared name (`案内人`).
715 pub name: String,
716 /// The display name (original text).
717 pub display: String,
718 /// The display name as parts of the original text of a body (has no `${expr}`).
719 pub parts: Vec<TextPart>,
720}
721
722/// Information about the options of a choice stop point (in the order written).
723#[derive(Debug, Clone, PartialEq)]
724pub(crate) struct ChoiceInfo {
725 pub options: Vec<ChoiceOptInfo>,
726}
727
728/// Information about one option.
729#[derive(Debug, Clone, PartialEq)]
730pub(crate) struct ChoiceOptInfo {
731 /// The stable ID.
732 pub id: Option<String>,
733 /// The original text of the option.
734 pub text: Vec<TextPart>,
735 /// The line of the option.
736 pub line: u32,
737}
738
739/// A local variable.
740#[derive(Debug, Clone, PartialEq)]
741pub(crate) struct LocalInfo {
742 pub name: String,
743 pub ty: Ty,
744}
745
746/// Information about where a `call` was placed (used on load to find the position of the caller).
747#[derive(Debug, Clone, PartialEq)]
748pub(crate) struct CallSite {
749 /// The position of the `Call` instruction. Execution returns to the one after it.
750 pub pc: u32,
751 /// The content hash (`call` + how the called label is written + original text of the arguments).
752 pub hash: u64,
753 /// The called label (a sequential number across the whole program).
754 pub target: u32,
755 /// Line.
756 pub line: u32,
757}
758
759/// The code of a label.
760#[derive(Debug, Clone, PartialEq)]
761pub(crate) struct LabelCode {
762 /// The module it belongs to (an index into `Program::modules`).
763 pub module: u32,
764 pub name: String,
765 pub reg: Box<RegCode>,
766 /// The line number of each instruction.
767 pub lines: Vec<u32>,
768 /// Local variables. The first `params` are the parameters.
769 pub locals: Vec<LocalInfo>,
770 /// The number of parameters.
771 pub params: u32,
772 /// The return type.
773 pub ret: Option<Ty>,
774 pub stops: Vec<StopInfo>,
775 pub calls: Vec<CallSite>,
776}
777
778impl LabelCode {
779 /// Whether the label can only be called with `call` (it has parameters or a return type).
780 pub fn callable(&self) -> bool {
781 self.params > 0 || self.ret.is_some()
782 }
783}
784
785/// The code of a `fn`. Unlike a label, it has neither stop points nor `call` positions (it does not go into saves).
786#[derive(Debug, Clone, PartialEq)]
787pub(crate) struct FnCode {
788 /// The module it belongs to (an index into `Program::modules`).
789 pub module: u32,
790 pub name: String,
791 pub reg: Box<RegCode>,
792 pub lines: Vec<u32>,
793 /// Local variables. The first `params` are the parameters, followed by `captures` captured values.
794 pub locals: Vec<LocalInfo>,
795 /// The number of parameters.
796 pub params: u32,
797 /// The number of captured values (only for lambdas; copied from the function value).
798 pub captures: u32,
799 /// The return type.
800 pub ret: Option<Ty>,
801}
802
803/// A module variable.
804#[derive(Debug, Clone, PartialEq)]
805pub(crate) struct GlobalInfo {
806 /// The module it belongs to (an index into `Program::modules`).
807 pub module: u32,
808 /// Whether it is a `persistent var` (false means `save var`). It goes into persistent data, not into saves.
809 pub persistent: bool,
810 pub name: String,
811 pub ty: Ty,
812 pub init: Value,
813}
814
815/// The compiled `migrate` blocks and the frozen schemas they use (`spec/language/07-migrate.md`).
816#[derive(Debug, Clone, PartialEq, Default)]
817pub(crate) struct MigrateCode {
818 /// In version order.
819 pub blocks: Vec<MigrateBlock>,
820 /// The frozen schemas, by version.
821 pub schemas: std::collections::BTreeMap<u32, FrozenSchema>,
822}
823
824/// One `migrate N { … }` block.
825#[derive(Debug, Clone, PartialEq)]
826pub(crate) struct MigrateBlock {
827 pub version: u32,
828 pub ops: Vec<MigrateOp>,
829}
830
831/// One statement of a `migrate` block. Variable names are `module.variable`.
832#[derive(Debug, Clone, PartialEq)]
833pub(crate) enum MigrateOp {
834 Rename {
835 old: String,
836 new: String,
837 persistent: bool,
838 },
839 Convert {
840 old: String,
841 new: String,
842 persistent: bool,
843 /// The types as written, without version prefixes.
844 old_ty: String,
845 new_ty: String,
846 /// The hidden label that evaluates the expression (parameter 0 is the old value; the result is left on the stack).
847 label: usize,
848 /// Whether the new side is a frozen schema (otherwise the current scripts).
849 new_frozen: bool,
850 },
851 Drop {
852 old: String,
853 persistent: bool,
854 },
855}
856
857/// A frozen schema as the program keeps it: the shapes of the declarations (as in `TypeDecl::signature`), for expanding the
858/// types of variables, and the names of the types that have a versioned copy (`v2::game.Item`) for running `convert`.
859#[derive(Debug, Clone, PartialEq, Default)]
860pub(crate) struct FrozenSchema {
861 pub decls: Vec<(String, String)>,
862 pub versioned: Vec<String>,
863}
864
865/// A compiled program (one or more modules).
866#[derive(Debug, Clone, PartialEq)]
867pub struct Program {
868 /// The names of the modules (in the order given).
869 pub(crate) modules: Vec<String>,
870 /// The variables of all modules (in module order, then declaration order).
871 pub(crate) globals: Vec<GlobalInfo>,
872 /// The labels of all modules (in module order, then declaration order).
873 pub(crate) labels: Vec<LabelCode>,
874 /// The `fn`s of all modules (in module order, then declaration order).
875 pub(crate) fns: Vec<FnCode>,
876 /// The names of the stop commands used.
877 pub(crate) commands: Vec<String>,
878 /// The names of the effect and query commands used.
879 pub(crate) natives: Vec<String>,
880 /// The names of the host-declared variables used.
881 pub(crate) host_vars: Vec<String>,
882 /// The `struct`s and `enum`s declared by users (in module order, then declaration order).
883 pub(crate) types: Vec<TypeDecl>,
884 /// The lines that can have stable IDs (in script order; used by `assign-ids`).
885 pub(crate) id_sites: Vec<IdSite>,
886 /// Identity declarations (in module order, then declaration order).
887 pub(crate) identities: Vec<IdentityInfo>,
888 /// The compiled sources (in the same order, from the start of `modules`). Kept so that the REPL can build an extended
889 /// program with added declarations. In the REPL's extended program, the `<repl>` module is not included (shorter than
890 /// `modules`).
891 pub(crate) sources: Vec<String>,
892 pub(crate) schema_version: u32,
893 pub(crate) min_save_version: u32,
894 pub(crate) migrate: MigrateCode,
895}
896
897/// One line that can have a stable ID (a plain line, quote line, option text or stop command line).
898#[derive(Debug, Clone, PartialEq, Eq)]
899pub(crate) struct IdSite {
900 /// The module it belongs to (an index into `Program::modules`).
901 pub module: u32,
902 /// The name of the label it belongs to.
903 pub label: String,
904 /// The kind (option texts are `Choice`).
905 pub kind: StopKind,
906 /// The stable ID written.
907 pub id: Option<String>,
908 /// When there is no ID, the position to append `#id` (line and column; columns are 1-based in characters).
909 pub line: u32,
910 pub col: u32,
911}
912
913impl Program {
914 /// The schema version of the scripts (the largest `N` of the `migrate N` blocks; 1 when there are none).
915 pub fn schema_version(&self) -> u32 {
916 self.schema_version
917 }
918
919 /// The oldest save schema version that can still be loaded (`min_save_version`; 1 when not written).
920 pub fn min_save_version(&self) -> u32 {
921 self.min_save_version
922 }
923
924 /// Declarations of `struct`s and `enum`s declared by users (in module order, then declaration order).
925 pub fn types(&self) -> &[TypeDecl] {
926 &self.types
927 }
928
929 /// Keys and original text parts of the bodies to be replaced. In script order: display names of identities
930 /// (`identity:module.name`, in declaration order), followed by, in the order of modules, labels, stop points and options
931 /// as written, plain lines, quote lines and option texts with stable IDs, and stop command lines whose translatable
932 /// arguments (such as input prompts) are written as string literals.
933 pub(crate) fn text_entries(&self) -> Vec<(String, &[TextPart])> {
934 let mut out = Vec::new();
935 for d in &self.identities {
936 out.push((
937 identity_key(&self.modules[d.module as usize], &d.name),
938 d.parts.as_slice(),
939 ));
940 }
941 for l in &self.labels {
942 let path = format!("{}.{}", self.modules[l.module as usize], l.name);
943 for st in &l.stops {
944 if let Some(choice) = &st.choice {
945 for o in &choice.options {
946 if let Some(id) = &o.id {
947 out.push((format!("{path}#{id}"), o.text.as_slice()));
948 }
949 }
950 } else if (st.kind != StopKind::Command || st.text_arg.is_some())
951 && let Some(id) = &st.id
952 {
953 out.push((format!("{path}#{id}"), st.text.as_slice()));
954 }
955 }
956 }
957 out
958 }
959
960 /// Finds the stop point of a command with translatable arguments from one history entry (`module.label` of the label and
961 /// the stable ID of the stop point).
962 pub(crate) fn command_text_arg(&self, label: &str, id: &str) -> Option<TextArg> {
963 let (module, name) = label.split_once('.')?;
964 let l = self
965 .labels
966 .iter()
967 .find(|l| l.name == name && self.modules[l.module as usize] == module)?;
968 l.stops
969 .iter()
970 .find(|st| st.kind == StopKind::Command && st.id.as_deref() == Some(id))
971 .and_then(|st| st.text_arg)
972 }
973
974 /// The text table key for the `Identity` of a quote line (the declared name and the original display name). `module` is
975 /// the name of the module containing the quote line. When multiple modules have declarations with the same name and
976 /// display name, the one in `module` comes first.
977 pub(crate) fn identity_key_of(&self, module: &str, id: &str, display: &str) -> Option<String> {
978 let mut found = self
979 .identities
980 .iter()
981 .filter(|d| d.name == id && d.display == display)
982 .map(|d| self.modules[d.module as usize].as_str());
983 let first = found.next()?;
984 let m = if first == module || found.any(|m| m == module) {
985 module
986 } else {
987 first
988 };
989 Some(identity_key(m, id))
990 }
991
992 /// The name of the first module (for a program with one module, that module).
993 pub fn module(&self) -> &str {
994 self.modules.first().map_or("", String::as_str)
995 }
996
997 /// The list of module names (in the order passed to compilation).
998 pub fn module_names(&self) -> impl Iterator<Item = &str> {
999 self.modules.iter().map(String::as_str)
1000 }
1001
1002 /// The list of label names of the first module (in declaration order).
1003 pub fn label_names(&self) -> impl Iterator<Item = &str> {
1004 self.labels
1005 .iter()
1006 .filter(|l| l.module == 0)
1007 .map(|l| l.name.as_str())
1008 }
1009
1010 /// The list of label names of the given module (in declaration order). Empty if the module does not exist.
1011 pub fn labels_of(&self, module: &str) -> Vec<&str> {
1012 let Some(idx) = self.modules.iter().position(|m| m == module) else {
1013 return Vec::new();
1014 };
1015 self.labels
1016 .iter()
1017 .filter(|l| l.module as usize == idx)
1018 .map(|l| l.name.as_str())
1019 .collect()
1020 }
1021}
1022
1023/// The text table key for the display name of an identity (`identity:module.name`; line keys contain `#`, so they do not
1024/// collide).
1025pub(crate) fn identity_key(module: &str, name: &str) -> String {
1026 format!("identity:{module}.{name}")
1027}
1028
1029/// FNV-1a (64 bits). Gives the same value on every platform.
1030pub(crate) fn fnv1a(parts: &[&[u8]]) -> u64 {
1031 let mut h: u64 = 0xcbf2_9ce4_8422_2325;
1032 for p in parts {
1033 for b in *p {
1034 h ^= u64::from(*b);
1035 h = h.wrapping_mul(0x0000_0100_0000_01b3);
1036 }
1037 h ^= 0xff;
1038 h = h.wrapping_mul(0x0000_0100_0000_01b3);
1039 }
1040 h
1041}