Skip to main content

vihaco_syntax/
lower.rs

1// SPDX-FileCopyrightText: 2026 The vihaco Authors
2// SPDX-License-Identifier: MIT
3
4//! Instruction-set-independent lowering of a parsed `.text` stream.
5
6use crate::{ParsedModule, Symbol};
7use eyre::WrapErr;
8use vihaco_abi::{Lower, Value};
9use vihaco_module::loader::InternedStrings;
10use vihaco_module::module::{LocalModule, ProgramMetadata};
11
12/// Describe an address relative to the nearest preceding symbol, e.g. `@main+3`.
13fn locate(symbols: &[Symbol], address: usize) -> String {
14    symbols
15        .iter()
16        .filter(|symbol| symbol.address as usize <= address)
17        .max_by_key(|symbol| symbol.address)
18        .map(|symbol| match address - symbol.address as usize {
19            0 => format!("@{}", symbol.name),
20            offset => format!("@{}+{offset}", symbol.name),
21        })
22        .unwrap_or_else(|| format!("address {address}"))
23}
24
25/// Lower a code stream in address order.
26///
27/// Each syntax instruction lowers to one runtime instruction. The context must
28/// already know the whole symbol table, so forward references resolve. Errors
29/// name the instruction by address and nearest preceding symbol; no partial
30/// code vector is returned. Context mutations before an error are not rolled
31/// back.
32pub fn lower_code<I, C>(
33    code: Vec<I>,
34    symbols: &[Symbol],
35    context: &mut C,
36) -> eyre::Result<Vec<I::Runtime>>
37where
38    I: Lower<C>,
39{
40    code.into_iter()
41        .enumerate()
42        .map(|(address, instruction)| {
43            instruction.lower(context).wrap_err_with(|| {
44                format!(
45                    "lowering instruction {address} ({})",
46                    locate(symbols, address)
47                )
48            })
49        })
50        .collect()
51}
52
53/// Validate supplied metadata and lower a code stream without consuming it.
54///
55/// Available with `program-image-execution`. The caller prepares the metadata
56/// and context independently, for example by processing individual header
57/// declarations. The context may borrow prepared configuration or the metadata
58/// itself; neither is moved or cloned by this function.
59///
60/// Function declarations, the symbol table, and table bounds are validated
61/// before lowering starts. Lowering may intern string literals in the
62/// context; store the context's completed string table in the metadata
63/// (`metadata.strings = context.into_strings()` for
64/// `MetadataLoweringContext`) and assemble the returned code with
65/// [`ProgramMetadata::into_module`], which also checks standard value
66/// references.
67///
68/// # Errors
69/// Returns declaration, symbol, table, or instruction-lowering errors. No
70/// partial code is returned; earlier context mutations are not rolled back.
71#[cfg(feature = "program-image-execution")]
72pub fn lower_code_with_metadata<I, Ty, V, Info, C>(
73    code: Vec<I>,
74    symbols: &[Symbol],
75    metadata: &ProgramMetadata<V, Ty, Info>,
76    context: &mut C,
77) -> eyre::Result<Vec<I::Runtime>>
78where
79    Ty: Clone,
80    I: Lower<C>,
81{
82    metadata.validate(symbols, code.len())?;
83    lower_code(code, symbols, context)
84}
85
86impl<I, H> ParsedModule<I, H> {
87    /// Validate declarations, symbols, and tables, lower instructions with the
88    /// supplied context, and assemble a module without inventing or reordering
89    /// metadata. The module's string table is the context's: the metadata's
90    /// strings followed by those interned during lowering.
91    ///
92    /// The consumer extracts the metadata from its chosen header schema and
93    /// prepares section-wide context capabilities (for example
94    /// `MetadataLoweringContext::new(&metadata, &parsed.symbols)`) before
95    /// calling this method. The header itself is not interpreted here.
96    ///
97    /// # Errors
98    /// Returns declaration, symbol, table, or lowering errors. Context
99    /// mutations before an error are retained; no partial module is returned.
100    pub fn lower_with_metadata<C, Ty: Clone, Info>(
101        self,
102        metadata: ProgramMetadata<Value, Ty, Info>,
103        context: &mut C,
104    ) -> eyre::Result<LocalModule<I::Runtime, Value, Ty, Info>>
105    where
106        I: Lower<C>,
107        C: InternedStrings,
108    {
109        metadata.validate(&self.symbols, self.code.len())?;
110        let code = lower_code(self.code, &self.symbols, context)?;
111        let mut metadata = metadata;
112        metadata.strings = context.take_strings();
113        metadata.into_module(code, self.symbols)
114    }
115}
116
117#[cfg(test)]
118mod tests;