1use std::collections::{BTreeMap, HashMap};
19
20use crate::module::{FunctionDecl, FunctionInfo, LocalModule, NoInfo, SourceSymbolInfo, Symbol};
21use vihaco_abi::{Type, Value};
22
23#[derive(Debug, Clone, PartialEq)]
26pub struct ProgramMetadata<V = Value, Ty = Type, Info = NoInfo> {
27 pub strings: Vec<String>,
28 pub functions: Vec<FunctionDecl<Ty>>,
29 pub constants: Vec<V>,
30 pub main_function: Option<u32>,
31 pub source_symbols: Vec<SourceSymbolInfo>,
32 pub extra: Info,
33}
34
35fn check_index(index: u32, len: usize, what: &str) -> eyre::Result<()> {
36 eyre::ensure!(
37 (index as usize) < len,
38 "{what}: index {index} is outside table of length {len}"
39 );
40 Ok(())
41}
42
43pub fn index_symbols(
48 symbols: &[Symbol],
49 instruction_count: usize,
50) -> eyre::Result<HashMap<&str, u32>> {
51 let mut table = HashMap::with_capacity(symbols.len());
52 for symbol in symbols {
53 eyre::ensure!(
54 symbol.address as usize <= instruction_count,
55 "symbol `@{}` at {} is outside the instruction stream of length {instruction_count}",
56 symbol.name,
57 symbol.address
58 );
59 eyre::ensure!(
60 table.insert(symbol.name.as_str(), symbol.address).is_none(),
61 "duplicate symbol `@{}`",
62 symbol.name
63 );
64 }
65 Ok(table)
66}
67
68impl<V, Ty, Info> ProgramMetadata<V, Ty, Info> {
69 pub fn map_extra<NewInfo>(
71 self,
72 map: impl FnOnce(Info) -> NewInfo,
73 ) -> ProgramMetadata<V, Ty, NewInfo> {
74 ProgramMetadata {
75 functions: self.functions,
76 constants: self.constants,
77 strings: self.strings,
78 main_function: self.main_function,
79 source_symbols: self.source_symbols,
80 extra: map(self.extra),
81 }
82 }
83
84 pub fn function_name(&self, index: usize) -> eyre::Result<&str> {
86 let function = self
87 .functions
88 .get(index)
89 .ok_or_else(|| eyre::eyre!("metadata.functions[{index}] does not exist"))?;
90 self.strings
91 .get(function.name as usize)
92 .map(String::as_str)
93 .ok_or_else(|| {
94 eyre::eyre!(
95 "metadata.functions[{index}].name: index {} is outside table of length {}",
96 function.name,
97 self.strings.len()
98 )
99 })
100 }
101
102 pub fn validate(&self, symbols: &[Symbol], instruction_count: usize) -> eyre::Result<()>
105 where
106 Ty: Clone,
107 {
108 self.resolve_functions(symbols, instruction_count)
109 .map(|_| ())
110 }
111
112 pub fn resolve_functions(
118 &self,
119 symbols: &[Symbol],
120 instruction_count: usize,
121 ) -> eyre::Result<Vec<FunctionInfo<Ty>>>
122 where
123 Ty: Clone,
124 {
125 eyre::ensure!(
126 u32::try_from(instruction_count).is_ok(),
127 "instruction stream exceeds u32 address space"
128 );
129 let table = index_symbols(symbols, instruction_count)?;
130 if let Some(main) = self.main_function {
131 check_index(main, self.functions.len(), "metadata.main_function")?;
132 }
133
134 let mut starts = Vec::with_capacity(self.functions.len());
135 let mut names = BTreeMap::new();
136 for (index, function) in self.functions.iter().enumerate() {
137 let path = format!("metadata.functions[{index}]");
138 let name = self.function_name(index)?;
139 check_index(function.file, self.strings.len(), &format!("{path}.file"))?;
140 if let Some(previous) = names.insert(name, index) {
141 eyre::bail!(
142 "function `@{name}` is declared by both metadata.functions[{previous}] and {path}"
143 );
144 }
145 eyre::ensure!(
146 function.local_count as usize >= function.signature.params.len(),
147 "{path}.local_count: fewer slots than parameters"
148 );
149 for parameter in &function.signature.params {
150 check_index(
151 parameter.name,
152 self.strings.len(),
153 &format!("{path}.signature.params.name"),
154 )?;
155 }
156 let start = *table.get(name).ok_or_else(|| {
157 eyre::eyre!("function `@{name}` ({path}) has no `@{name}:` symbol definition")
158 })?;
159 starts.push(start);
160 }
161
162 let mut boundaries = starts.clone();
163 boundaries.sort_unstable();
164 boundaries.dedup();
165 let end_of = |start: u32| {
166 boundaries
167 .iter()
168 .copied()
169 .find(|&boundary| boundary > start)
170 .unwrap_or(instruction_count as u32)
171 };
172
173 let mut seen = std::collections::BTreeSet::new();
174 for symbol in &self.source_symbols {
175 eyre::ensure!(
176 seen.insert(symbol.index),
177 "metadata.source_symbols: duplicate index {}",
178 symbol.index
179 );
180 }
181
182 Ok(self
183 .functions
184 .iter()
185 .zip(starts)
186 .map(|(function, start)| FunctionInfo {
187 name: function.name,
188 signature: function.signature.clone(),
189 local_count: function.local_count,
190 start_address: start,
191 end_address: end_of(start),
192 file: function.file,
193 })
194 .collect())
195 }
196}
197
198impl<Ty: Clone, Info> ProgramMetadata<Value, Ty, Info> {
199 pub fn into_module<I>(
203 self,
204 code: Vec<I>,
205 symbols: Vec<Symbol>,
206 ) -> eyre::Result<LocalModule<I, Value, Ty, Info>> {
207 let functions = self.resolve_functions(&symbols, code.len())?;
208 for (index, constant) in self.constants.iter().enumerate() {
209 match constant {
210 Value::String(id) => check_index(
211 *id,
212 self.strings.len(),
213 &format!("metadata.constants[{index}] string"),
214 )?,
215 Value::FunctionRef(id) => check_index(
216 *id,
217 self.functions.len(),
218 &format!("metadata.constants[{index}] function"),
219 )?,
220 _ => {}
221 }
222 }
223 Ok(LocalModule {
224 code,
225 functions,
226 symbols,
227 constants: self.constants,
228 strings: self.strings,
229 main_function: self.main_function,
230 source_symbols: self.source_symbols,
231 extra: self.extra,
232 })
233 }
234}