1pub use oxdock_parser::{
10 Field, LIST_TAG, MAP_TAG, OxDockType, TypeDescriptor, TypeTag, Value, ValuePayload,
11 check_value, check_value_at, clone_boxed, clone_copy, clone_shared, drop_boxed, drop_noop,
12 drop_shared, eq_boxed, eq_inline, eq_shared, fmt_boxed, fmt_inline, fmt_shared, load_inline,
13 startup_descriptors, store_inline, type_anchor, unshare_boxed, unshare_inline, unshare_shared,
14};
15
16use std::collections::{HashMap, HashSet};
17
18use anyhow::{Result, bail};
19use oxdock_parser::{
20 ANY_TAG, MAX_GENERIC_DEPTH, Spelled, SpelledField, Step, StepKind, canonicalize_spelling,
21 intern_composed, lookup_composed, parse_spelling,
22};
23use oxdock_process::ProcessManager;
24
25use super::state::ExecState;
26
27pub fn check_options(
36 map: &std::collections::BTreeMap<String, Value>,
37 options: &[crate::ParamOption],
38 func: &str,
39) -> Result<()> {
40 for key in map.keys() {
41 if !options.iter().any(|known| known.name == key) {
42 let known: Vec<&str> = options.iter().map(|known| known.name).collect();
43 bail!(
44 "{func}() unknown option '{key}' (expected: {})",
45 known.join(", ")
46 );
47 }
48 }
49 Ok(())
50}
51
52pub(super) fn startup_type_map() -> HashMap<String, &'static TypeDescriptor> {
54 startup_descriptors()
55 .into_iter()
56 .map(|(name, descriptor)| (name.to_string(), descriptor))
57 .collect()
58}
59
60impl<P: ProcessManager> ExecState<P> {
61 pub fn register_type(&mut self, descriptor: &'static TypeDescriptor) {
68 if let Some(live) = self.types.get(descriptor.name) {
69 if !std::ptr::eq(*live, descriptor) {
70 panic!(
71 "type name `{}` already registered for a different descriptor",
72 descriptor.name
73 );
74 }
75 return;
76 }
77 self.types.insert(descriptor.name.to_string(), descriptor);
78 }
79
80 pub fn is_known_type(&self, name: &str) -> bool {
82 self.types.contains_key(name)
83 }
84
85 pub fn register_record_schema(&mut self, name: &'static str, fields: &'static [Field]) {
91 if let Some(live) = self.record_schemas.get(name) {
92 if live.len() != fields.len()
93 || live
94 .iter()
95 .zip(fields.iter())
96 .any(|(a, b)| a.name != b.name)
97 {
98 panic!("record schema `{name}` already registered with different fields");
99 }
100 return;
101 }
102 self.record_schemas.insert(name.to_string(), fields);
103 }
104
105 pub fn schema_names(&self) -> Vec<String> {
107 let mut names: Vec<String> = self.record_schemas.keys().cloned().collect();
108 names.sort();
109 names
110 }
111
112 pub fn alias_names(&self) -> Vec<String> {
115 let mut names: Vec<String> = self.type_aliases.keys().cloned().collect();
116 names.sort();
117 names
118 }
119
120 pub fn alias_target(&self, name: &str) -> Option<String> {
123 self.type_aliases.get(name).cloned()
124 }
125
126 pub fn resolve_tag(&self, name: &str) -> Result<TypeTag> {
136 let canonical = canonicalize_spelling(name);
137 if canonical.contains('<') {
138 return self.resolve_spelling_text(&canonical, &mut Vec::new(), 0);
139 }
140 self.resolve_named(&canonical, &mut Vec::new(), 0)
141 }
142
143 fn resolve_named(
148 &self,
149 name: &str,
150 resolving: &mut Vec<String>,
151 depth: usize,
152 ) -> Result<TypeTag> {
153 if depth > MAX_GENERIC_DEPTH {
154 bail!("type spelling exceeds maximum generic depth of {MAX_GENERIC_DEPTH}: '{name}'");
155 }
156 if name == "MAP" {
157 bail!(
158 "bare MAP is not a declaration type: write a shape (MAP<name: TYPE, ...>) or MAP<ANY> for maps with unknown keys"
159 );
160 }
161 if name == "LIST" {
162 bail!(
163 "bare LIST is not a declaration type: write a shape (LIST<TYPE>) or LIST<ANY> for lists with unknown elements"
164 );
165 }
166 if let Some(tag) = TypeTag::builtin(name) {
167 return Ok(tag);
168 }
169 if let Some(descriptor) = self.types.get(name) {
170 return Ok(TypeTag::Custom(descriptor));
171 }
172 if let Some(fields) = self.record_schemas.get(name) {
173 let tag = TypeTag::Record(fields);
174 self.check_tag_known("declaration", &tag)?;
175 return Ok(tag);
176 }
177 if let Some(target) = self.type_aliases.get(name) {
178 if resolving.contains(&name.to_string()) {
179 resolving.push(name.to_string());
180 bail!("type alias cycle: {}", resolving.join(" -> "));
181 }
182 resolving.push(name.to_string());
183 let target = target.clone();
184 let result = self.resolve_spelling_text(&target, resolving, depth + 1);
185 resolving.pop();
186 return result;
187 }
188 bail!(
189 "unknown type '{name}'; known types: {} and schemas: {} and aliases: {}",
190 self.type_names().join(", "),
191 self.schema_names().join(", "),
192 self.alias_names().join(", "),
193 )
194 }
195
196 fn resolve_spelling_text(
199 &self,
200 canonical: &str,
201 resolving: &mut Vec<String>,
202 depth: usize,
203 ) -> Result<TypeTag> {
204 if let Some(hit) = lookup_composed(canonical) {
205 return Ok(*hit);
206 }
207 let spelled = parse_spelling(canonical)
208 .map_err(|err| anyhow::anyhow!("invalid type spelling: {err}"))?;
209 let tag = self.build_composed(&spelled, resolving, depth)?;
210 Ok(*intern_composed(canonical.to_string(), tag))
211 }
212
213 fn build_composed(
219 &self,
220 spelled: &Spelled,
221 resolving: &mut Vec<String>,
222 depth: usize,
223 ) -> Result<TypeTag> {
224 if depth > MAX_GENERIC_DEPTH {
225 bail!(
226 "type spelling exceeds maximum generic depth of {MAX_GENERIC_DEPTH}: '{spelled:?}'"
227 );
228 }
229 match spelled {
230 Spelled::Named(name) => self.resolve_named(name, resolving, depth),
231 Spelled::Generic { name, args } => self.build_generic(name, args, resolving, depth),
232 }
233 }
234
235 #[allow(clippy::disallowed_methods)]
243 fn build_generic(
244 &self,
245 name: &str,
246 args: &[SpelledField],
247 resolving: &mut Vec<String>,
248 depth: usize,
249 ) -> Result<TypeTag> {
250 if name != "LIST" && name != "MAP" {
251 self.resolve_named(name, resolving, depth)?;
252 bail!("'{name}' takes no type arguments");
253 }
254 if name == "LIST" {
255 let [
256 SpelledField {
257 name: None,
258 ty: element,
259 ..
260 },
261 ] = args
262 else {
263 bail!("LIST takes exactly one bare type argument");
264 };
265 let element = self.build_composed(element, resolving, depth + 1)?;
266 return Ok(TypeTag::ListOf(Box::leak(Box::new(element))));
267 }
268 if name == "MAP"
269 && let [
270 SpelledField {
271 name: None,
272 ty: Spelled::Named(any),
273 ..
274 },
275 ] = args
276 && any.as_str() == "ANY"
277 {
278 return Ok(TypeTag::MapOf(&ANY_TAG));
282 }
283 let mut fields = Vec::with_capacity(args.len());
284 for arg in args {
285 let Some(field_name) = arg.name.as_ref() else {
286 bail!("MAP fields require 'name: TYPE'; '{name}' takes no bare arguments");
287 };
288 let ty = self.build_composed(&arg.ty, resolving, depth + 1)?;
289 let leaked: &'static str = Box::leak(field_name.clone().into_boxed_str());
290 fields.push(Field {
291 name: leaked,
292 ty,
293 docs: "",
294 optional: arg.optional,
295 });
296 }
297 Ok(TypeTag::Record(Box::leak(fields.into_boxed_slice())))
298 }
299}
300pub fn collect_type_aliases<P: ProcessManager>(
308 steps: &[Step],
309 exec: &ExecState<P>,
310) -> Result<HashMap<String, String>> {
311 let mut func_names = HashSet::new();
312 for step in steps {
313 if let StepKind::FuncDef { name, .. } = &step.kind {
314 func_names.insert(name.clone());
315 }
316 }
317 let mut aliases = HashMap::new();
318 for step in steps {
319 let StepKind::TypeAlias { name, target } = &step.kind else {
320 continue;
321 };
322 if aliases.contains_key(name) {
323 bail!("type alias '{name}' is already defined");
324 }
325 if TypeTag::builtin(name).is_some() {
326 bail!("type alias '{name}' collides with a builtin type");
327 }
328 if exec.types.contains_key(name) {
329 bail!("type alias '{name}' collides with registered host type '{name}'");
330 }
331 if exec.record_schemas.contains_key(name) {
332 bail!("type alias '{name}' collides with registered record schema '{name}'");
333 }
334 if func_names.contains(name) {
335 bail!("type alias '{name}' collides with function '{name}'");
336 }
337 aliases.insert(name.clone(), canonicalize_spelling(target));
338 }
339 Ok(aliases)
340}
341
342impl<P: ProcessManager> ExecState<P> {
343 fn check_tag_known(&self, what: &str, tag: &TypeTag) -> Result<()> {
348 match tag {
349 TypeTag::Custom(descriptor) => {
350 if !self.types.contains_key(descriptor.name) {
351 bail!(
352 "{what} declares unregistered type '{}'; known types: {}",
353 descriptor.name,
354 self.type_names().join(", ")
355 );
356 }
357 }
358 TypeTag::ListOf(element) => self.check_tag_known(what, element)?,
359 TypeTag::MapOf(values) => self.check_tag_known(what, values)?,
360 TypeTag::Record(fields) => {
361 for field in *fields {
362 self.check_tag_known(what, &field.ty)?;
363 }
364 }
365 _ => {}
366 }
367 Ok(())
368 }
369
370 pub fn validate_function_type_tags(&self) -> Result<()> {
380 for meta in self.functions.all_metas() {
381 if let Some(params) = meta.params.as_deref() {
382 for (position, param) in params.iter().enumerate() {
383 if let Some(expected) = param.param_type.as_ref() {
384 let what = format!("param '{}' of '{}'", param.name, meta.name);
385 Self::check_tag_known(self, &what, expected)?;
386 }
387 if param.param_type.is_none() && param.allowed.is_some() {
388 anyhow::bail!(
389 "param '{}' of '{}' declares values without a type",
390 param.name,
391 meta.name,
392 );
393 }
394 if param.optional {
395 let trails = params[position..].iter().all(|later| later.optional);
399 if !trails {
400 anyhow::bail!(
401 "param '{}' of '{}' is optional before a required param",
402 param.name,
403 meta.name,
404 );
405 }
406 if !matches!(param.param_type, Some(TypeTag::Map)) {
407 anyhow::bail!(
408 "param '{}' of '{}' is optional without a MAP type",
409 param.name,
410 meta.name,
411 );
412 }
413 }
414 }
415 }
416 if let Some(returns) = meta.returns.as_ref() {
417 let what = format!("return of '{}'", meta.name);
418 Self::check_tag_known(self, &what, returns)?;
419 }
420 }
421 Ok(())
422 }
423
424 pub fn describe_type(&self, name: &str) -> Option<&'static TypeDescriptor> {
426 self.types.get(name).copied()
427 }
428
429 pub fn type_names(&self) -> Vec<String> {
432 let mut names: Vec<String> = startup_descriptors()
433 .into_iter()
434 .map(|(name, _)| name.to_string())
435 .collect();
436 for name in self.types.keys() {
437 if !names.contains(&name.to_string()) {
438 names.push(name.clone());
439 }
440 }
441 for name in self.alias_names() {
442 if !names.contains(&name) {
443 names.push(name);
444 }
445 }
446 names
447 }
448}