aluvm/vm.rs
1// Reference rust implementation of AluVM (arithmetic logic unit virtual machine).
2// To find more on AluVM please check <https://aluvm.org>
3//
4// SPDX-License-Identifier: Apache-2.0
5//
6// Designed in 2021-2025 by Dr Maxim Orlovsky <orlovsky@ubideco.org>
7// Written in 2021-2025 by Dr Maxim Orlovsky <orlovsky@ubideco.org>
8//
9// Copyright (C) 2021-2024 LNP/BP Standards Association, Switzerland.
10// Copyright (C) 2024-2025 Laboratories for Ubiquitous Deterministic Computing (UBIDECO),
11// Institute for Distributed and Cognitive Systems (InDCS), Switzerland.
12// Copyright (C) 2021-2025 Dr Maxim Orlovsky.
13// All rights under the above copyrights are reserved.
14//
15// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
16// in compliance with the License. You may obtain a copy of the License at
17//
18// http://www.apache.org/licenses/LICENSE-2.0
19//
20// Unless required by applicable law or agreed to in writing, software distributed under the License
21// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
22// or implied. See the License for the specific language governing permissions and limitations under
23// the License.
24
25//! Alu virtual machine
26
27use core::marker::PhantomData;
28
29use crate::core::{Core, CoreConfig, CoreExt, Status};
30use crate::isa::{Instr, Instruction};
31use crate::library::{Jump, Lib, LibId, LibSite};
32
33/// Alu virtual machine providing single-core execution environment
34#[derive(Clone, Debug, Default)]
35pub struct Vm<Isa = Instr<LibId>>
36where Isa: Instruction<LibId>
37{
38 /// A set of registers
39 pub core: Core<LibId, Isa::Core>,
40
41 phantom: PhantomData<Isa>,
42}
43
44/// Runtime for program execution.
45impl<Isa> Vm<Isa>
46where Isa: Instruction<LibId>
47{
48 /// Constructs new virtual machine instance with default core configuration.
49 pub fn new() -> Self { Self { core: Core::new(), phantom: Default::default() } }
50
51 /// Constructs new virtual machine instance with default core configuration.
52 pub fn with(config: CoreConfig, cx_config: <Isa::Core as CoreExt>::Config) -> Self {
53 Self {
54 core: Core::with(config, cx_config),
55 phantom: Default::default(),
56 }
57 }
58
59 /// Resets all registers of the VM except those which were set up with the config object.
60 pub fn reset(&mut self) { self.core.reset(); }
61
62 /// Executes the program starting from the provided entry point.
63 ///
64 /// # Returns
65 ///
66 /// Value of the `CK` register at the end of the program execution.
67 pub fn exec<L: AsRef<Lib>>(
68 &mut self,
69 entry_point: LibSite,
70 context: &Isa::Context<'_>,
71 lib_resolver: impl Fn(LibId) -> Option<L>,
72 ) -> Status {
73 let mut site = entry_point;
74 let mut skip = false;
75 loop {
76 if let Some(lib) = lib_resolver(site.lib_id) {
77 let jump = lib
78 .as_ref()
79 .exec::<Isa>(site.offset, skip, &mut self.core, context);
80 match jump {
81 Jump::Halt => {
82 #[cfg(feature = "log")]
83 {
84 let core = &self.core;
85 let z = "\x1B[0m";
86 let y = "\x1B[0;33m";
87 let c = if core.ck().is_ok() { "\x1B[0;32m" } else { "\x1B[0;31m" };
88 eprintln!();
89 eprintln!(
90 ">; execution stopped: {y}CK{z} {c}{}{z}, {y}CO{z} {c}{}{z}",
91 core.ck(),
92 core.co()
93 );
94 }
95 break;
96 }
97 Jump::Instr(new_site) => {
98 skip = false;
99 site = new_site.into();
100 }
101 Jump::Next(new_site) => {
102 skip = true;
103 site = new_site.into();
104 }
105 }
106 } else {
107 let fail = self.core.fail_ck();
108 // We stop execution if the failure flag is set
109 if fail {
110 break;
111 } else if let Some(pos) = site.offset.checked_add(1) {
112 // Otherwise we just proceed
113 site.offset = pos;
114 } else {
115 // or we still stop if we reached the end of the code
116 break;
117 }
118 };
119 }
120 self.core.ck()
121 }
122}