Skip to main content

vihaco/
lib.rs

1// SPDX-FileCopyrightText: 2026 The vihaco Authors
2// SPDX-License-Identifier: MIT
3
4extern crate self as vihaco;
5
6use vihaco_bytecode as binary;
7// Extracted crates re-exported at their original module paths so the public
8// API is unchanged (see design/crate-split.md §7).
9pub use vihaco_abi::{effect, frame, instruction_syntax, metadata, program, word};
10pub use vihaco_module::{color, module, show, show_instruction};
11
12/// Program loading interfaces and the standard program image.
13pub mod loader {
14    pub use vihaco_module::loader::*;
15    pub use vihaco_stdlib::ProgramImage;
16}
17
18pub use vihaco_syntax as syntax;
19// The runtime layer and standard-library observers now live in their focused
20// crates; re-export them at the original paths (see design/crate-split.md §7).
21pub use vihaco_runtime as runtime;
22pub use vihaco_stdlib::observer;
23
24pub mod instruction;
25pub mod machine;
26pub mod macros;
27
28#[doc(hidden)]
29pub mod traits;
30pub mod value {
31    pub use vihaco_abi::{Type, Value};
32}
33
34pub use binary::{
35    BytecodeFile, BytecodeGlobalContext, BytecodeHeader, BytecodeSectionView, ConstantId,
36    ContextHandle, FLAGS, GlobalContext, MAGIC, NoContext, SectionNameResolver, SectionPath,
37    SstFile, SstGlobalContext, SstHeader, SstSectionView, VERSION, WriteBytecodeHeader,
38    decode_instruction_stream,
39};
40
41pub use chumsky;
42pub use effect::Effects;
43
44#[doc(hidden)]
45pub use eyre;
46pub use instruction_syntax::{
47    CanonicalInstructionSyntax, CanonicalInstructionVariantSyntax, InstructionSugarSyntax,
48    InstructionSugarVariantSyntax, OperandKind, SugarOperandKind,
49};
50
51pub use loader::ProgramImage;
52
53#[cfg(not(feature = "program-image-execution"))]
54pub use loader::{LoadBytecodeSection, LoadOwnBytecodeSection, LoadOwnSstSection, LoadSstSection};
55
56pub use macros::{Instruction, Message, component, composite, dispatch, observe};
57pub use program::{Type, Value};
58pub use runtime::{
59    Component, Composite, CompositeMetadata, EffectSink, GeneratedComponent, HasInstructionSet,
60    MemberOf, Message as MessageMarker, NoMessage, Observe, expect_exactly_one_effect,
61};
62
63pub use traits::{FromBytes, FromText, GetProgramInfo, Reset};
64pub use vihaco_abi::{Lower, Runtime, Syntax};
65pub use vihaco_parser::Parse;
66pub use vihaco_parser::SurfaceInstruction;
67#[doc(hidden)]
68pub use vihaco_parser::trivia;
69pub use vihaco_parser_derive::Parse;
70
71#[cfg(feature = "typed-declarations")]
72#[doc(hidden)]
73pub use runtime::__private;
74
75#[cfg(feature = "typed-declarations")]
76pub use runtime::{BuildMessage, Dispatch, Execute, Field, ReusableMessageRecipe, Step};
77
78/// Name a composite field or nested route. See [`runtime::field`].
79#[cfg(feature = "typed-declarations")]
80pub use runtime::field;
81
82/// Declare instruction leaves with phase-aware parsers under `typed-declarations`.
83/// See [`runtime::dialect`] for the `#[vihaco(crate = path)]` framework-root override.
84///
85/// ```
86/// # #[cfg(feature = "typed-declarations")]
87/// # {
88/// use vihaco::{dialect, Parse, chumsky::Parser};
89/// #[dialect]
90/// # #[vihaco(crate = ::vihaco)]
91/// pub mod arithmetic {
92///     #[instruction]
93///     pub struct Add(pub i64);
94/// }
95/// assert_eq!(arithmetic::Add::parser().parse("add 2")
96///     .into_result().unwrap().0, 2);
97/// # }
98/// ```
99#[cfg(feature = "typed-declarations")]
100pub use runtime::dialect;
101
102#[cfg(feature = "program-image-execution")]
103pub use runtime::{
104    Apply, HasOperandStack, InputCount, PopFromStack, PopStack, PushStack, PushToStack, StackBatch,
105    StackBatchIntoIter, StackInputCount, StackValue,
106};
107
108#[cfg(feature = "program-image-execution")]
109pub use vihaco_runtime::HasProgram;
110
111#[cfg(feature = "program-image-execution")]
112pub use vihaco_stdlib::{
113    ExecutionState, Image, Loadable,
114    execution_state::{execute, resume},
115};
116
117#[cfg(test)]
118mod public_api_tests {
119    use crate::{
120        BytecodeGlobalContext, BytecodeHeader, ConstantId, EffectSink, Effects, GeneratedComponent,
121        GlobalContext, Reset, SectionNameResolver, SstGlobalContext, SstHeader,
122        WriteBytecodeHeader,
123        instruction::{FromBytes, OpCode, WriteBytes},
124        module::FunctionInfo,
125        observer::stdio::StdoutEffect,
126    };
127
128    #[cfg(not(feature = "program-image-execution"))]
129    use crate::{LoadBytecodeSection, LoadOwnBytecodeSection};
130
131    struct PublicReset;
132
133    impl Reset for PublicReset {
134        fn reset(&mut self) {}
135    }
136
137    struct PublicContext;
138
139    impl SectionNameResolver for PublicContext {
140        fn section_name(&self, _index: u32) -> Option<&str> {
141            None
142        }
143    }
144
145    impl BytecodeGlobalContext for PublicContext {
146        fn from_bytes(_bytes: &[u8]) -> eyre::Result<Self> {
147            Ok(Self)
148        }
149    }
150
151    impl SstGlobalContext for PublicContext {
152        fn from_text(_text: &str) -> eyre::Result<Self> {
153            Ok(Self)
154        }
155    }
156
157    #[cfg(not(feature = "program-image-execution"))]
158    impl LoadOwnBytecodeSection<PublicContext> for PublicReset {
159        type Output = ();
160
161        fn load_own_bytecode_section<'bc>(
162            &mut self,
163            _section: crate::BytecodeSectionView<'bc, PublicContext>,
164        ) -> eyre::Result<()> {
165            Ok(())
166        }
167    }
168
169    #[cfg(not(feature = "program-image-execution"))]
170    impl LoadBytecodeSection<PublicContext> for PublicReset {
171        type Output = ();
172
173        fn load_bytecode_section<'bc>(
174            &mut self,
175            section: crate::BytecodeSectionView<'bc, PublicContext>,
176        ) -> eyre::Result<()> {
177            self.load_own_bytecode_section(section)
178        }
179    }
180
181    struct PublicSstHeader;
182
183    impl crate::traits::FromText for PublicSstHeader {
184        fn from_text(_text: &str) -> eyre::Result<Self> {
185            Ok(Self)
186        }
187    }
188
189    impl SstHeader for PublicSstHeader {}
190
191    #[test]
192    fn crate_root_exports_new_traits() {
193        fn require_effect_sink<S: EffectSink<()>>() {}
194        fn require_reset<T: Reset>() {}
195        fn require_instruction<T: FromBytes + OpCode + WriteBytes>() {}
196        fn require_bytecode_header<T: BytecodeHeader>() {}
197        fn require_sst_header<T: SstHeader>() {}
198        fn require_write_bytecode_header<T: WriteBytecodeHeader>() {}
199        fn require_section_name_resolver<T: SectionNameResolver>() {}
200        fn require_bytecode_global_context<T: BytecodeGlobalContext>() {}
201        fn require_sst_global_context<T: SstGlobalContext>() {}
202        fn require_global_context<T: GlobalContext>() {}
203        #[cfg(not(feature = "program-image-execution"))]
204        fn require_load_own_bytecode_section<T: LoadOwnBytecodeSection<PublicContext>>() {}
205        #[cfg(not(feature = "program-image-execution"))]
206        fn require_load_bytecode_section<T: LoadBytecodeSection<PublicContext>>() {}
207        fn require_stdout_effect(_effect: StdoutEffect) {}
208        fn require_metadata(_metadata: crate::CompositeMetadata) {}
209
210        require_effect_sink::<Vec<()>>();
211        require_reset::<PublicReset>();
212        require_instruction::<u32>();
213        require_bytecode_header::<u32>();
214        require_sst_header::<PublicSstHeader>();
215        require_write_bytecode_header::<u32>();
216        require_section_name_resolver::<PublicContext>();
217        require_bytecode_global_context::<PublicContext>();
218        require_sst_global_context::<PublicContext>();
219        require_sst_global_context::<crate::NoContext>();
220        require_global_context::<PublicContext>();
221        #[cfg(not(feature = "program-image-execution"))]
222        require_load_own_bytecode_section::<PublicReset>();
223        #[cfg(not(feature = "program-image-execution"))]
224        require_load_bytecode_section::<PublicReset>();
225        let _constant = ConstantId(0);
226        let _function: Option<FunctionInfo<crate::Type>> = None;
227        require_stdout_effect(StdoutEffect(String::new()));
228        require_metadata(crate::CompositeMetadata {
229            devices: &[],
230            source_symbol_aliases: &[],
231        });
232    }
233
234    #[derive(Clone, Copy)]
235    struct DemoComponent;
236
237    impl GeneratedComponent for DemoComponent {
238        type Instruction = ();
239        type Message = ();
240        type Effect = u8;
241
242        fn execute_generated(
243            &mut self,
244            _inst: &Self::Instruction,
245            _msg: Self::Message,
246        ) -> eyre::Result<Effects<Self::Effect>> {
247            Ok(Effects::one(7))
248        }
249    }
250
251    #[test]
252    fn generated_component_executes_without_exec_context() {
253        let mut component = DemoComponent;
254        let effects = GeneratedComponent::execute_generated(&mut component, &(), ()).unwrap();
255
256        assert_eq!(effects, Effects::one(7));
257        assert_eq!(crate::expect_exactly_one_effect(effects).unwrap(), 7);
258    }
259}