Skip to main content

vihaco_stdlib/program/
lower.rs

1// SPDX-FileCopyrightText: 2026 The vihaco Authors
2// SPDX-License-Identifier: MIT
3
4//! Instruction-owned program lowering, separate from the dialect definitions.
5
6use super::{
7    operand::{StringOperand, Target},
8    program,
9};
10
11use vihaco_abi::{Lower, Syntax};
12use vihaco_module::loader::MetadataLoweringContext;
13
14/// Resolve `@name` branch targets through the section's symbol table.
15///
16/// The loader prepares the whole table before lowering so forward references
17/// work. Addresses count executable instructions; `@name:` definitions occupy
18/// no slot.
19pub trait LabelLookup {
20    fn label_address(&self, name: &str) -> eyre::Result<u32>;
21}
22
23/// Resolve function names in the section currently being lowered.
24///
25/// Calls need an executable address; reference constants need a function-table
26/// index. These are separate values even when a program happens to make them equal.
27pub trait FunctionLookup {
28    fn function_address(&self, name: &str) -> eyre::Result<u32>;
29    fn function_index(&self, name: &str) -> eyre::Result<u32>;
30}
31
32/// Intern decoded string contents in the current section's string table.
33///
34/// Equal contents must return the same index, including contents already in the
35/// table. Implementations report an error if the table cannot represent an index.
36pub trait StringIntern {
37    fn intern_string(&mut self, value: &str) -> eyre::Result<u32>;
38}
39
40impl LabelLookup for MetadataLoweringContext {
41    fn label_address(&self, name: &str) -> eyre::Result<u32> {
42        MetadataLoweringContext::label_address(self, name)
43    }
44}
45
46impl FunctionLookup for MetadataLoweringContext {
47    fn function_address(&self, name: &str) -> eyre::Result<u32> {
48        MetadataLoweringContext::function_address(self, name)
49    }
50
51    fn function_index(&self, name: &str) -> eyre::Result<u32> {
52        MetadataLoweringContext::function_index(self, name)
53    }
54}
55
56impl StringIntern for MetadataLoweringContext {
57    fn intern_string(&mut self, value: &str) -> eyre::Result<u32> {
58        self.string_index(value)
59    }
60}
61
62fn label_target<C: LabelLookup + ?Sized>(target: Target, context: &C) -> eyre::Result<u32> {
63    match target {
64        Target::Resolved(address) => Ok(address),
65        Target::Symbol(name) => context.label_address(name.as_str()),
66    }
67}
68
69impl<C: LabelLookup + ?Sized> Lower<C> for program::Branch<Syntax> {
70    type Runtime = program::Branch;
71    fn lower(self, context: &mut C) -> eyre::Result<Self::Runtime> {
72        Ok(program::Branch(label_target(self.0, context)?))
73    }
74}
75
76impl<C: LabelLookup + ?Sized> Lower<C> for program::ConditionalBranch<Syntax> {
77    type Runtime = program::ConditionalBranch;
78    fn lower(self, context: &mut C) -> eyre::Result<Self::Runtime> {
79        Ok(program::ConditionalBranch(
80            label_target(self.0, context)?,
81            label_target(self.1, context)?,
82        ))
83    }
84}
85
86impl<C: FunctionLookup + ?Sized> Lower<C> for program::Call<Syntax> {
87    type Runtime = program::Call;
88    fn lower(self, context: &mut C) -> eyre::Result<Self::Runtime> {
89        let address = match self.1 {
90            Target::Resolved(address) => address,
91            Target::Symbol(name) => context.function_address(name.as_str())?,
92        };
93        Ok(program::Call(self.0, address))
94    }
95}
96
97impl<C: FunctionLookup + ?Sized> Lower<C> for program::ConstFunctionRef<Syntax> {
98    type Runtime = program::ConstFunctionRef;
99    fn lower(self, context: &mut C) -> eyre::Result<Self::Runtime> {
100        let index = match self.0 {
101            Target::Resolved(index) => index,
102            Target::Symbol(name) => context.function_index(name.as_str())?,
103        };
104        Ok(program::ConstFunctionRef(
105            vihaco_abi::word::encode_function_ref(index),
106        ))
107    }
108}
109
110impl<C: StringIntern + ?Sized> Lower<C> for program::ConstString<Syntax> {
111    type Runtime = program::ConstString;
112    fn lower(self, context: &mut C) -> eyre::Result<Self::Runtime> {
113        let index = match self.0 {
114            StringOperand::Resolved(index) => index,
115            StringOperand::Literal(value) => context.intern_string(value.as_str())?,
116        };
117        Ok(program::ConstString(vihaco_abi::word::encode_string_id(
118            index,
119        )))
120    }
121}
122
123// Literal encoding is instruction-owned lowering and needs no loader capabilities.
124macro_rules! lower_literal {
125    ($($instruction:ident => $convert:expr),* $(,)?) => {$(
126        impl<C: ?Sized> vihaco_abi::Lower<C> for program::$instruction<vihaco_abi::Syntax> {
127            type Runtime = program::$instruction;
128            fn lower(self, _: &mut C) -> eyre::Result<Self::Runtime> {
129                Ok(program::$instruction(($convert)(self.0)))
130            }
131        }
132    )*};
133}
134
135lower_literal! {
136    ConstI32 => vihaco_abi::word::Word::from,
137    ConstI64 => vihaco_abi::word::Word::from,
138    ConstF32 => vihaco_abi::word::Word::from,
139    ConstF64 => vihaco_abi::word::Word::from,
140    ConstU32 => vihaco_abi::word::encode_u32,
141    ConstBool => vihaco_abi::word::encode_bool,
142    ConstHeapRef => vihaco_abi::word::encode_heap_ref,
143}
144
145// String interning belongs to module construction, before immutable loading.
146impl<I, V, Ty, Info> StringIntern for vihaco_module::module::LocalModule<I, V, Ty, Info> {
147    fn intern_string(&mut self, value: &str) -> eyre::Result<u32> {
148        if let Some(index) = self.strings.iter().position(|existing| existing == value) {
149            return Ok(u32::try_from(index)?);
150        }
151        let index = u32::try_from(self.strings.len())?;
152        self.strings.push(value.to_owned());
153        Ok(index)
154    }
155}