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(
38 map: &std::collections::BTreeMap<String, Value>,
39 options: &[crate::ParamOption],
40 func: &str,
41) -> Result<()> {
42 for key in map.keys() {
43 if !options.iter().any(|known| known.name == key) {
44 let known: Vec<&str> = options.iter().map(|known| known.name).collect();
45 bail!(
46 "{func}() unknown option '{key}' (expected: {})",
47 known.join(", ")
48 );
49 }
50 }
51 for (key, value) in map.iter() {
52 let option = options
53 .iter()
54 .find(|known| known.name == *key)
55 .expect("unknown keys rejected above");
56 crate::check_value_at(&option.value, value, &format!("{func}() option '{key}'"))?;
57 }
58 Ok(())
59}
60
61pub(super) fn startup_type_map() -> HashMap<String, &'static TypeDescriptor> {
63 startup_descriptors()
64 .into_iter()
65 .map(|(name, descriptor)| (name.to_string(), descriptor))
66 .collect()
67}
68
69impl<P: ProcessManager> ExecState<P> {
70 pub fn register_type(&mut self, descriptor: &'static TypeDescriptor) {
77 if let Some(live) = self.types.get(descriptor.name) {
78 if !std::ptr::eq(*live, descriptor) {
79 panic!(
80 "type name `{}` already registered for a different descriptor",
81 descriptor.name
82 );
83 }
84 return;
85 }
86 self.types.insert(descriptor.name.to_string(), descriptor);
87 }
88
89 pub fn is_known_type(&self, name: &str) -> bool {
91 self.types.contains_key(name)
92 }
93
94 pub fn register_record_schema(&mut self, name: &'static str, fields: std::sync::Arc<[Field]>) {
100 if let Some(live) = self.record_schemas.get(name) {
101 if live.len() != fields.len()
102 || live
103 .iter()
104 .zip(fields.iter())
105 .any(|(a, b)| a.name != b.name)
106 {
107 panic!("record schema `{name}` already registered with different fields");
108 }
109 return;
110 }
111 self.record_schemas.insert(name.to_string(), fields);
112 }
113
114 pub fn schema_names(&self) -> Vec<String> {
116 let mut names: Vec<String> = self.record_schemas.keys().cloned().collect();
117 names.sort();
118 names
119 }
120
121 pub fn alias_names(&self) -> Vec<String> {
124 let mut names: Vec<String> = self.type_aliases.keys().cloned().collect();
125 names.sort();
126 names
127 }
128
129 pub fn alias_target(&self, name: &str) -> Option<String> {
132 self.type_aliases.get(name).cloned()
133 }
134
135 pub fn resolve_tag(&self, name: &str) -> Result<TypeTag> {
146 let canonical = canonicalize_spelling(name);
147 if canonical.contains('<') || canonical.contains('|') {
148 return self.resolve_spelling_text(&canonical, &mut Vec::new(), 0);
149 }
150 self.resolve_named(&canonical, &mut Vec::new(), 0)
151 }
152
153 fn resolve_named(
158 &self,
159 name: &str,
160 resolving: &mut Vec<String>,
161 depth: usize,
162 ) -> Result<TypeTag> {
163 if depth > MAX_GENERIC_DEPTH {
164 bail!("type spelling exceeds maximum generic depth of {MAX_GENERIC_DEPTH}: '{name}'");
165 }
166 if name == "MAP" {
167 bail!(
168 "bare MAP is not a declaration type: write a shape (MAP<name: TYPE, ...>) or MAP<ANY> for maps with unknown keys"
169 );
170 }
171 if name == "LIST" {
172 bail!(
173 "bare LIST is not a declaration type: write a shape (LIST<TYPE>) or LIST<ANY> for lists with unknown elements"
174 );
175 }
176 if let Some(tag) = TypeTag::builtin(name) {
177 return Ok(tag);
178 }
179 if let Some(descriptor) = self.types.get(name) {
180 return Ok(TypeTag::Custom(descriptor));
181 }
182 if let Some(fields) = self.record_schemas.get(name) {
183 let tag = TypeTag::Record(fields.clone());
184 self.check_tag_known("declaration", &tag)?;
185 return Ok(tag);
186 }
187 if let Some(target) = self.type_aliases.get(name) {
188 if resolving.contains(&name.to_string()) {
189 resolving.push(name.to_string());
190 bail!("type alias cycle: {}", resolving.join(" -> "));
191 }
192 resolving.push(name.to_string());
193 let target = target.clone();
194 let result = self.resolve_spelling_text(&target, resolving, depth + 1);
195 resolving.pop();
196 return result;
197 }
198 bail!(
199 "unknown type '{name}'; known types: {} and schemas: {} and aliases: {}",
200 self.type_names().join(", "),
201 self.schema_names().join(", "),
202 self.alias_names().join(", "),
203 )
204 }
205
206 fn resolve_spelling_text(
209 &self,
210 canonical: &str,
211 resolving: &mut Vec<String>,
212 depth: usize,
213 ) -> Result<TypeTag> {
214 if let Some(hit) = lookup_composed(canonical) {
215 return Ok(hit);
216 }
217 let spelled = parse_spelling(canonical)
218 .map_err(|err| anyhow::anyhow!("invalid type spelling: {err}"))?;
219 let tag = self.build_composed(&spelled, resolving, depth)?;
220 Ok(intern_composed(canonical.to_string(), tag))
221 }
222
223 fn build_composed(
231 &self,
232 spelled: &Spelled,
233 resolving: &mut Vec<String>,
234 depth: usize,
235 ) -> Result<TypeTag> {
236 if depth > MAX_GENERIC_DEPTH {
237 bail!(
238 "type spelling exceeds maximum generic depth of {MAX_GENERIC_DEPTH}: '{spelled:?}'"
239 );
240 }
241 match spelled {
242 Spelled::Named(name) => self.resolve_named(name, resolving, depth),
243 Spelled::Generic { name, args } => self.build_generic(name, args, resolving, depth),
244 Spelled::Union(members) => {
245 let mut resolved = Vec::with_capacity(members.len());
246 for member in members {
247 resolved.push(self.build_composed(member, resolving, depth)?);
248 }
249 finish_union(resolved)
250 }
251 }
252 }
253
254 #[allow(clippy::disallowed_methods)]
262 fn build_generic(
263 &self,
264 name: &str,
265 args: &[SpelledField],
266 resolving: &mut Vec<String>,
267 depth: usize,
268 ) -> Result<TypeTag> {
269 if name != "LIST" && name != "MAP" {
270 self.resolve_named(name, resolving, depth)?;
271 bail!("'{name}' takes no type arguments");
272 }
273 if name == "LIST" {
274 let [
275 SpelledField {
276 name: None,
277 ty: element,
278 ..
279 },
280 ] = args
281 else {
282 bail!("LIST takes exactly one bare type argument");
283 };
284 let element = self.build_composed(element, resolving, depth + 1)?;
285 return Ok(TypeTag::ListOf(std::sync::Arc::new(element)));
286 }
287 if name == "MAP"
288 && let [
289 SpelledField {
290 name: None,
291 ty: Spelled::Named(any),
292 ..
293 },
294 ] = args
295 && any.as_str() == "ANY"
296 {
297 return Ok(TypeTag::MapOf(std::sync::Arc::new(ANY_TAG)));
301 }
302 let mut fields = Vec::with_capacity(args.len());
303 for arg in args {
304 let Some(field_name) = arg.name.as_ref() else {
305 bail!("MAP fields require 'name: TYPE'; '{name}' takes no bare arguments");
306 };
307 let ty = self.build_composed(&arg.ty, resolving, depth + 1)?;
308 fields.push(Field {
309 name: field_name.clone(),
310 ty,
311 docs: "",
312 optional: arg.optional,
313 });
314 }
315 Ok(TypeTag::Record(std::sync::Arc::from(fields)))
316 }
317}
318
319fn finish_union(members: Vec<TypeTag>) -> Result<TypeTag> {
326 let mut flat: Vec<TypeTag> = Vec::with_capacity(members.len());
327 for member in members {
328 if let TypeTag::Union(_, nested) = member {
331 flat.extend(nested.iter().cloned());
332 } else {
333 flat.push(member);
334 }
335 }
336 if flat.is_empty() {
337 bail!("empty union: no member shapes to admit");
338 }
339 if flat.iter().any(|member| matches!(member, TypeTag::Any)) {
341 return Ok(TypeTag::Any);
342 }
343 let mut unique: Vec<TypeTag> = Vec::with_capacity(flat.len());
346 for member in flat {
347 if !unique
348 .iter()
349 .any(|seen| super::static_check::tags_equal(seen, &member))
350 {
351 unique.push(member);
352 }
353 }
354 if unique.len() == 1 {
355 return Ok(unique.pop().expect("single survivor checked above"));
356 }
357 Ok(TypeTag::union(unique))
358}
359
360pub fn collect_type_aliases<P: ProcessManager>(
368 steps: &[Step],
369 exec: &ExecState<P>,
370) -> Result<HashMap<String, String>> {
371 let mut func_names = HashSet::new();
372 for step in steps {
373 if let StepKind::FuncDef { name, .. } = &step.kind {
374 func_names.insert(name.clone());
375 }
376 }
377 let mut aliases = HashMap::new();
378 for step in steps {
379 let StepKind::TypeAlias { name, target } = &step.kind else {
380 continue;
381 };
382 if aliases.contains_key(name) {
383 bail!("type alias '{name}' is already defined");
384 }
385 if TypeTag::builtin(name).is_some() {
386 bail!("type alias '{name}' collides with a builtin type");
387 }
388 if exec.types.contains_key(name) {
389 bail!("type alias '{name}' collides with registered host type '{name}'");
390 }
391 if exec.record_schemas.contains_key(name) {
392 bail!("type alias '{name}' collides with registered record schema '{name}'");
393 }
394 if func_names.contains(name) {
395 bail!("type alias '{name}' collides with function '{name}'");
396 }
397 aliases.insert(name.clone(), canonicalize_spelling(target));
398 }
399 Ok(aliases)
400}
401
402impl<P: ProcessManager> ExecState<P> {
403 fn check_tag_known(&self, what: &str, tag: &TypeTag) -> Result<()> {
408 match tag {
409 TypeTag::Custom(descriptor) => {
410 if !self.types.contains_key(descriptor.name) {
411 bail!(
412 "{what} declares unregistered type '{}'; known types: {}",
413 descriptor.name,
414 self.type_names().join(", ")
415 );
416 }
417 }
418 TypeTag::ListOf(element) => self.check_tag_known(what, element)?,
419 TypeTag::MapOf(values) => self.check_tag_known(what, values)?,
420 TypeTag::Record(fields) => {
421 for field in fields.iter() {
422 self.check_tag_known(what, &field.ty)?;
423 }
424 }
425 TypeTag::Union(_, members) => {
428 for member in members.iter() {
429 self.check_tag_known(what, member)?;
430 }
431 }
432 TypeTag::String
436 | TypeTag::Int
437 | TypeTag::Float
438 | TypeTag::Bool
439 | TypeTag::List
440 | TypeTag::Map
441 | TypeTag::Pipe
442 | TypeTag::Handle
443 | TypeTag::Duration
444 | TypeTag::Path
445 | TypeTag::Semaphore
446 | TypeTag::Permit
447 | TypeTag::Any => {}
448 }
449 Ok(())
450 }
451
452 pub fn validate_function_type_tags(&self) -> Result<()> {
462 for meta in self.functions.all_metas() {
463 if let Some(params) = meta.params.as_deref() {
464 for (position, param) in params.iter().enumerate() {
465 if let Some(expected) = param.param_type.as_ref() {
466 let what = format!("param '{}' of '{}'", param.name, meta.name);
467 Self::check_tag_known(self, &what, expected)?;
468 }
469 if param.param_type.is_none() && param.allowed.is_some() {
470 anyhow::bail!(
471 "param '{}' of '{}' declares values without a type",
472 param.name,
473 meta.name,
474 );
475 }
476 if param.optional {
477 let trails = params[position..].iter().all(|later| later.optional);
481 if !trails {
482 anyhow::bail!(
483 "param '{}' of '{}' is optional before a required param",
484 param.name,
485 meta.name,
486 );
487 }
488 if !matches!(param.param_type, Some(TypeTag::Map)) {
489 anyhow::bail!(
490 "param '{}' of '{}' is optional without a MAP type",
491 param.name,
492 meta.name,
493 );
494 }
495 }
496 }
497 }
498 if let Some(returns) = meta.returns.as_ref() {
499 let what = format!("return of '{}'", meta.name);
500 Self::check_tag_known(self, &what, returns)?;
501 }
502 }
503 Ok(())
504 }
505
506 pub fn describe_type(&self, name: &str) -> Option<&'static TypeDescriptor> {
508 self.types.get(name).copied()
509 }
510
511 pub fn type_names(&self) -> Vec<String> {
514 let mut names: Vec<String> = startup_descriptors()
515 .into_iter()
516 .map(|(name, _)| name.to_string())
517 .collect();
518 for name in self.types.keys() {
519 if !names.contains(&name.to_string()) {
520 names.push(name.clone());
521 }
522 }
523 for name in self.alias_names() {
524 if !names.contains(&name) {
525 names.push(name);
526 }
527 }
528 names
529 }
530}